Compare commits

..

67 Commits

Author SHA1 Message Date
Ivan Shymko
e1d6c76830
chore: remove dependabot.yml (#400) 2026-04-07 10:58:03 +02:00
Ivan Shymko
87cd79774f
ci: enable groups for dependabot (#394)
Bring back the previous behavior of only having security updates.
2026-04-07 10:27:23 +02:00
Ivan Shymko
c8b40684c8
ci: enable groups for dependabot (#388)
Currently it creates some noise with individual upgrades PRs.

Reference:
https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference
2026-04-07 10:08:18 +02:00
dependabot[bot]
6bacf4f605
chore(deps): bump vite from 7.3.0 to 7.3.2 (#386)
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite)
from 7.3.0 to 7.3.2.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/vitejs/vite/releases">vite's
releases</a>.</em></p>
<blockquote>
<h2>v7.3.2</h2>
<p>Please refer to <a
href="https://github.com/vitejs/vite/blob/v7.3.2/packages/vite/CHANGELOG.md">CHANGELOG.md</a>
for details.</p>
<h2>v7.3.1</h2>
<p>Please refer to <a
href="https://github.com/vitejs/vite/blob/v7.3.1/packages/vite/CHANGELOG.md">CHANGELOG.md</a>
for details.</p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/vitejs/vite/blob/v7.3.2/packages/vite/CHANGELOG.md">vite's
changelog</a>.</em></p>
<blockquote>
<h2><!-- raw HTML omitted --><a
href="https://github.com/vitejs/vite/compare/v7.3.1...v7.3.2">7.3.2</a>
(2026-04-06)<!-- raw HTML omitted --></h2>
<h3>Bug Fixes</h3>
<ul>
<li>avoid path traversal with optimize deps sourcemap handler (<a
href="https://redirect.github.com/vitejs/vite/issues/22161">#22161</a>)
(<a
href="09d8c903bd">09d8c90</a>)</li>
<li>backport <a
href="https://redirect.github.com/vitejs/vite/issues/22159">#22159</a>,
apply server.fs check to env transport (<a
href="https://redirect.github.com/vitejs/vite/issues/22162">#22162</a>)
(<a
href="19db0f29c3">19db0f2</a>)</li>
<li>check <code>server.fs</code> after stripping query as well (<a
href="https://redirect.github.com/vitejs/vite/issues/22160">#22160</a>)
(<a
href="f8103cc946">f8103cc</a>)</li>
</ul>
<h2><!-- raw HTML omitted --><a
href="https://github.com/vitejs/vite/compare/v7.3.0...v7.3.1">7.3.1</a>
(2026-01-07)<!-- raw HTML omitted --></h2>
<h3>Features</h3>
<ul>
<li>add <code>ignoreOutdatedRequests</code> option to
<code>optimizeDeps</code> (<a
href="https://redirect.github.com/vitejs/vite/issues/21364">#21364</a>)
(<a
href="9d39d373a7">9d39d37</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="cc383e07b6"><code>cc383e0</code></a>
release: v7.3.2</li>
<li><a
href="09d8c903bd"><code>09d8c90</code></a>
fix: avoid path traversal with optimize deps sourcemap handler (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22161">#22161</a>)</li>
<li><a
href="f8103cc946"><code>f8103cc</code></a>
fix: check <code>server.fs</code> after stripping query as well (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22160">#22160</a>)</li>
<li><a
href="19db0f29c3"><code>19db0f2</code></a>
fix: backport <a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22159">#22159</a>,
apply server.fs check to env transport (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/22162">#22162</a>)</li>
<li><a
href="95e8923f35"><code>95e8923</code></a>
release: v7.3.1</li>
<li><a
href="9d39d373a7"><code>9d39d37</code></a>
feat: add <code>ignoreOutdatedRequests</code> option to
<code>optimizeDeps</code> (<a
href="https://github.com/vitejs/vite/tree/HEAD/packages/vite/issues/21364">#21364</a>)</li>
<li>See full diff in <a
href="https://github.com/vitejs/vite/commits/v7.3.2/packages/vite">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=vite&package-manager=npm_and_yarn&previous-version=7.3.0&new-version=7.3.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-07 09:35:14 +02:00
dependabot[bot]
e2dc048b2a
chore(deps-dev): bump flatted from 3.3.3 to 3.4.2 (#366)
Bumps [flatted](https://github.com/WebReflection/flatted) from 3.3.3 to
3.4.2.
<details>
<summary>Commits</summary>
<ul>
<li><a
href="3bf09091c3"><code>3bf0909</code></a>
3.4.2</li>
<li><a
href="885ddcc33c"><code>885ddcc</code></a>
fix CWE-1321</li>
<li><a
href="0bdba705d1"><code>0bdba70</code></a>
added flatted-view to the benchmark</li>
<li><a
href="2a02dce7c6"><code>2a02dce</code></a>
3.4.1</li>
<li><a
href="fba4e8f2e1"><code>fba4e8f</code></a>
Merge pull request <a
href="https://redirect.github.com/WebReflection/flatted/issues/89">#89</a>
from WebReflection/python-fix</li>
<li><a
href="5fe86485e6"><code>5fe8648</code></a>
added &quot;when in Rome&quot; also a test for PHP</li>
<li><a
href="53517adbef"><code>53517ad</code></a>
some minor improvement</li>
<li><a
href="b3e2a0c387"><code>b3e2a0c</code></a>
Fixing recursion issue in Python too</li>
<li><a
href="c4b46dbcbf"><code>c4b46db</code></a>
Add SECURITY.md for security policy and reporting</li>
<li><a
href="f86d071e0f"><code>f86d071</code></a>
Create dependabot.yml for version updates</li>
<li>Additional commits viewable in <a
href="https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=flatted&package-manager=npm_and_yarn&previous-version=3.3.3&new-version=3.4.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-20 11:37:39 +01:00
dependabot[bot]
1f219b0c85
chore(deps-dev): bump fast-xml-parser from 5.5.6 to 5.5.7 in /src/samples (#365)
Bumps
[fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser)
from 5.5.6 to 5.5.7.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md">fast-xml-parser's
changelog</a>.</em></p>
<blockquote>
<p><!-- raw HTML omitted -->Note: If you find missing information about
particular minor version, that version must have been changed without
any functional change in this library.<!-- raw HTML omitted --></p>
<p>Note: Due to some last quick changes on v4, detail of v4.5.3 &amp;
v4.5.4 are not updated here. v4.5.4x is the last tag of v4 in github
repository. I'm extremely sorry for the confusion</p>
<p><strong>5.5.7 / 2026-03-19</strong></p>
<ul>
<li>fix: entity expansion limits</li>
<li>update strnum package to 2.2.0</li>
</ul>
<p><strong>5.5.6 / 2026-03-16</strong></p>
<ul>
<li>update builder dependency</li>
<li>fix incorrect regex to replace . in entity name</li>
<li>fix check for entitiy expansion for lastEntities and html entities
too</li>
</ul>
<p><strong>5.5.5 / 2026-03-13</strong></p>
<ul>
<li>sanitize dangerous tag or attribute name</li>
<li>error on critical property name</li>
<li>support onDangerousProperty option</li>
</ul>
<p><strong>5.5.4 / 2026-03-13</strong></p>
<ul>
<li>declare Matcher &amp; Expression as unknown so user is not forced to
install path-expression-matcher</li>
</ul>
<p><strong>5.5.3 / 2026-03-11</strong></p>
<ul>
<li>upgrade builder</li>
</ul>
<p><strong>5.5.2 / 2026-03-11</strong></p>
<ul>
<li>update dependency to fix typings</li>
</ul>
<p><strong>5.5.1 / 2026-03-10</strong></p>
<ul>
<li>fix dependency</li>
</ul>
<p><strong>5.5.0 / 2026-03-10</strong></p>
<ul>
<li>support path-expression-matcher</li>
<li>fix: stopNode should not be parsed</li>
<li>performance improvement for stopNode checking</li>
</ul>
<p><strong>5.4.2 / 2026-03-03</strong></p>
<ul>
<li>support maxEntityCount option</li>
</ul>
<p><strong>5.4.1  / 2026-02-25</strong></p>
<ul>
<li>fix (<a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/issues/785">#785</a>)
unpairedTag node should not have tag content</li>
</ul>
<p><strong>5.4.0  / 2026-02-25</strong></p>
<ul>
<li>migrate to fast-xml-builder</li>
</ul>
<p><strong>5.3.9 / 2026-02-25</strong></p>
<ul>
<li>support strictReservedNames</li>
</ul>
<p><strong>5.3.8 / 2026-02-25</strong></p>
<ul>
<li>support maxNestedTags</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="a21c44123c"><code>a21c441</code></a>
update package detail</li>
<li><a
href="239b64aa1f"><code>239b64a</code></a>
check for min value for entity exapantion options</li>
<li><a
href="61cb666d13"><code>61cb666</code></a>
restrict more properties to be unsafe</li>
<li><a
href="41abd66adc"><code>41abd66</code></a>
performance improvement of reading DOCTYPE</li>
<li><a
href="3dfcd20c8c"><code>3dfcd20</code></a>
refactor: performance improvement</li>
<li>See full diff in <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.5.6...v5.5.7">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=fast-xml-parser&package-manager=npm_and_yarn&previous-version=5.5.6&new-version=5.5.7)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-20 10:09:01 +01:00
bartek-gralewicz
2220644539
ci: Update coverage workflow (#362)
# Description

Modification to code coverage calculation workflow so that the
comparison is made against target branch and not `main`.
This is valuable when PR targets some epic branch. Comparing the
coverage with `main` branch is not accurate if the epic branch already
drifted from `main`.

# IMPORTANT NOTE

An attempt to test this change was done on a draft PR: #363 but the
coverage comment workflow is executed from the `main` branch and not
from the branch checkout. This means that in order to properly test this
functionality in action, it needs to reach `main` state.

In case any issues occur, I will provide an update to this logic or
revert back to the original state.
2026-03-19 11:11:14 +01:00
dependabot[bot]
0f433ed802
chore(deps-dev): bump fast-xml-parser from 5.4.1 to 5.5.6 in /src/samples (#357)
Bumps
[fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser)
from 5.4.1 to 5.5.6.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/releases">fast-xml-parser's
releases</a>.</em></p>
<blockquote>
<h2>fix entity expansion and incorrect replacement and performance</h2>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.5.5...v5.5.6">https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.5.5...v5.5.6</a></p>
<h2>support onDangerousProperty</h2>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.5.3...v5.5.5">https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.5.3...v5.5.5</a></p>
<h2>update dependecies to fix typings</h2>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.5.1...v5.5.2">https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.5.1...v5.5.2</a></p>
<h2>integrate path-expression-matcher</h2>
<ul>
<li>support path-expression-matcher</li>
<li>fix: stopNode should not be parsed</li>
<li>performance improvement for stopNode checking</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md">fast-xml-parser's
changelog</a>.</em></p>
<blockquote>
<p><!-- raw HTML omitted -->Note: If you find missing information about
particular minor version, that version must have been changed without
any functional change in this library.<!-- raw HTML omitted --></p>
<p>Note: Due to some last quick changes on v4, detail of v4.5.3 &amp;
v4.5.4 are not updated here. v4.5.4x is the last tag of v4 in github
repository. I'm extremely sorry for the confusion</p>
<p><strong>5.5.6 / 2026-03-16</strong></p>
<ul>
<li>update builder dependency</li>
<li>fix incorrect regex to replace . in entity name</li>
<li>fix check for entitiy expansion for lastEntities and html entities
too</li>
</ul>
<p><strong>5.5.5 / 2026-03-13</strong></p>
<ul>
<li>sanitize dangerous tag or attribute name</li>
<li>error on critical property name</li>
<li>support onDangerousProperty option</li>
</ul>
<p><strong>5.5.4 / 2026-03-13</strong></p>
<ul>
<li>declare Matcher &amp; Expression as unknown so user is not forced to
install path-expression-matcher</li>
</ul>
<p><strong>5.5.3 / 2026-03-11</strong></p>
<ul>
<li>upgrade builder</li>
</ul>
<p><strong>5.5.2 / 2026-03-11</strong></p>
<ul>
<li>update dependency to fix typings</li>
</ul>
<p><strong>5.5.1 / 2026-03-10</strong></p>
<ul>
<li>fix dependency</li>
</ul>
<p><strong>5.5.0 / 2026-03-10</strong></p>
<ul>
<li>support path-expression-matcher</li>
<li>fix: stopNode should not be parsed</li>
<li>performance improvement for stopNode checking</li>
</ul>
<p><strong>5.4.2 / 2026-03-03</strong></p>
<ul>
<li>support maxEntityCount option</li>
</ul>
<p><strong>5.4.1  / 2026-02-25</strong></p>
<ul>
<li>fix (<a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/issues/785">#785</a>)
unpairedTag node should not have tag content</li>
</ul>
<p><strong>5.4.0  / 2026-02-25</strong></p>
<ul>
<li>migrate to fast-xml-builder</li>
</ul>
<p><strong>5.3.9 / 2026-02-25</strong></p>
<ul>
<li>support strictReservedNames</li>
</ul>
<p><strong>5.3.8 / 2026-02-25</strong></p>
<ul>
<li>support maxNestedTags</li>
<li>handle non-array input for XML builder when preserveOrder is true
(By <a href="https://github.com/Angelopvtac">Angelo Coetzee</a>)</li>
<li>save use of js properies</li>
</ul>
<p><strong>5.3.7 / 2026-02-20</strong></p>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="870043e75e"><code>870043e</code></a>
update release info</li>
<li><a
href="6df401ef2b"><code>6df401e</code></a>
update builder dependency</li>
<li><a
href="bd26122c83"><code>bd26122</code></a>
check for entitiy expansion for lastEntities and html entities too</li>
<li><a
href="7e70dd8f75"><code>7e70dd8</code></a>
fix incorrect regex to replace . in entity name</li>
<li><a
href="e54155f530"><code>e54155f</code></a>
update package info</li>
<li><a
href="3308fd7a45"><code>3308fd7</code></a>
handle critical properties</li>
<li><a
href="0500f6b4d6"><code>0500f6b</code></a>
refactor</li>
<li><a
href="ea07bb2e84"><code>ea07bb2</code></a>
declare Matcher &amp; Expression as unknown</li>
<li><a
href="0a4dc92f97"><code>0a4dc92</code></a>
upgrade builder</li>
<li><a
href="e0a14f7d15"><code>e0a14f7</code></a>
update dependency to fix typings</li>
<li>Additional commits viewable in <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.4.1...v5.5.6">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=fast-xml-parser&package-manager=npm_and_yarn&previous-version=5.4.1&new-version=5.5.6)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-18 11:13:05 +01:00
Agent2Agent (A2A) Bot
82d36c7fdb
chore(main): release 0.3.13 (#354)
🤖 I have created a release *beep* *boop*
---


##
[0.3.13](https://github.com/a2aproject/a2a-js/compare/v0.3.12...v0.3.13)
(2026-03-16)


### Bug Fixes

* properly parse ProtoJSON body for POST pushNotificationConfigs
([#352](https://github.com/a2aproject/a2a-js/issues/352))
([57696a8](57696a8001)),
closes [#336](https://github.com/a2aproject/a2a-js/issues/336)

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2026-03-16 12:03:41 +01:00
Ivan Shymko
57696a8001
fix: properly parse ProtoJSON body for POST pushNotificationConfigs (#352)
Apparently the code removed in #346 wasn't "dead", this method wasn't
properly migrated in #292.

Tests are updated to cover this.

Fixes #336
2026-03-16 11:30:55 +01:00
dependabot[bot]
1323897b5e
chore(deps-dev): bump simple-git from 3.30.0 to 3.33.0 (#349)
Bumps
[simple-git](https://github.com/steveukx/git-js/tree/HEAD/simple-git)
from 3.30.0 to 3.33.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/steveukx/git-js/releases">simple-git's
releases</a>.</em></p>
<blockquote>
<h2>simple-git@3.33.0</h2>
<h3>Minor Changes</h3>
<ul>
<li>a263635: Use <code>pathspec</code> wrappers for remote and local
paths when running either <code>git.clone</code> or
<code>git.mirror</code> to
avoid leaving them less open for unexpected outcomes when passing
unsanitised data into these tasks.</li>
</ul>
<h3>Patch Changes</h3>
<ul>
<li>
<p>e253a0d: Enhanced <code>git -c</code> checks in <code>unsafe</code>
plugin.</p>
<p>Thanks to <a
href="https://github.com/JohannesLks"><code>@​JohannesLks</code></a> for
identifying the issue</p>
</li>
</ul>
<h2>simple-git@3.32.3</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p>f704208: Enhanced <code>protocol.allow</code> checks in
<code>allowUnsafeExtProtocol</code> handling.</p>
<p>Thanks to <a
href="https://github.com/CodeAnt-AI-Security"><code>@​CodeAnt-AI-Security</code></a>
for identifying the issue</p>
</li>
</ul>
<h2>simple-git@3.32.2</h2>
<h3>Patch Changes</h3>
<ul>
<li>8d02097: Enhanced clone unsafe switch detection.</li>
</ul>
<h2>simple-git@3.32.1</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p>23b070f: Fix regex for detecting unsafe clone options</p>
<p>Thanks to <a
href="https://github.com/stevenwdv"><code>@​stevenwdv</code></a> for
reporting this issue.</p>
</li>
</ul>
<h2>simple-git@3.32.0</h2>
<h3>Minor Changes</h3>
<ul>
<li>
<p>1effd8e: Enhances the <code>unsafe</code> plugin to block additional
cases where the <code>-u</code> switch may be disguised
along with other single character options.</p>
<p>Thanks to <a
href="https://github.com/JuHwiSang"><code>@​JuHwiSang</code></a> for
identifying this as vulnerability.</p>
</li>
</ul>
<h3>Patch Changes</h3>
<ul>
<li>d5fd4fe: Use task runner for logging use of deprecated (already
no-op) functions.</li>
</ul>
<h2>simple-git@3.31.1</h2>
<h3>Patch Changes</h3>
<ul>
<li>a44184f: Resolve NPM publish steps</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/steveukx/git-js/blob/main/simple-git/CHANGELOG.md">simple-git's
changelog</a>.</em></p>
<blockquote>
<h2>3.33.0</h2>
<h3>Minor Changes</h3>
<ul>
<li>a263635: Use <code>pathspec</code> wrappers for remote and local
paths when running either <code>git.clone</code> or
<code>git.mirror</code> to
avoid leaving them less open for unexpected outcomes when passing
unsanitised data into these tasks.</li>
</ul>
<h3>Patch Changes</h3>
<ul>
<li>
<p>e253a0d: Enhanced <code>git -c</code> checks in <code>unsafe</code>
plugin.</p>
<p>Thanks to <a
href="https://github.com/JohannesLks"><code>@​JohannesLks</code></a> for
identifying the issue</p>
</li>
</ul>
<h2>3.32.3</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p>f704208: Enhanced <code>protocol.allow</code> checks in
<code>allowUnsafeExtProtocol</code> handling.</p>
<p>Thanks to <a
href="https://github.com/CodeAnt-AI-Security"><code>@​CodeAnt-AI-Security</code></a>
for identifying the issue</p>
</li>
</ul>
<h2>3.32.2</h2>
<h3>Patch Changes</h3>
<ul>
<li>8d02097: Enhanced clone unsafe switch detection.</li>
</ul>
<h2>3.32.1</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p>23b070f: Fix regex for detecting unsafe clone options</p>
<p>Thanks to <a
href="https://github.com/stevenwdv"><code>@​stevenwdv</code></a> for
reporting this issue.</p>
</li>
</ul>
<h2>3.32.0</h2>
<h3>Minor Changes</h3>
<ul>
<li>
<p>1effd8e: Enhances the <code>unsafe</code> plugin to block additional
cases where the <code>-u</code> switch may be disguised
along with other single character options.</p>
<p>Thanks to <a
href="https://github.com/JuHwiSang"><code>@​JuHwiSang</code></a> for
identifying this as vulnerability.</p>
</li>
</ul>
<h3>Patch Changes</h3>
<ul>
<li>d5fd4fe: Use task runner for logging use of deprecated (already
no-op) functions.</li>
</ul>
<h2>3.31.1</h2>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="8bbbabc827"><code>8bbbabc</code></a>
Version Packages</li>
<li><a
href="a263635ca4"><code>a263635</code></a>
Clone API use pathspec (<a
href="https://github.com/steveukx/git-js/tree/HEAD/simple-git/issues/1132">#1132</a>)</li>
<li><a
href="e253a0d1bf"><code>e253a0d</code></a>
Fix/block unsafe 2603 (<a
href="https://github.com/steveukx/git-js/tree/HEAD/simple-git/issues/1135">#1135</a>)</li>
<li><a
href="a1170e506e"><code>a1170e5</code></a>
Version Packages</li>
<li><a
href="f7042088aa"><code>f704208</code></a>
In extension to CVE-2022-25912, switch to case-insensitive check for
`protoco...</li>
<li><a
href="4bb20811eb"><code>4bb2081</code></a>
Version Packages</li>
<li><a
href="7ae7537737"><code>7ae7537</code></a>
Match tokens to word boundary</li>
<li><a
href="c47ad103b0"><code>c47ad10</code></a>
Lint</li>
<li><a
href="8d02097b72"><code>8d02097</code></a>
Enhanced clone switch detection</li>
<li><a
href="f6909a5280"><code>f6909a5</code></a>
Remove test timeout override</li>
<li>Additional commits viewable in <a
href="https://github.com/steveukx/git-js/commits/simple-git@3.33.0/simple-git">compare
view</a></li>
</ul>
</details>
<details>
<summary>Maintainer changes</summary>
<p>This version was pushed to npm by [GitHub Actions](<a
href="https://www.npmjs.com/~GitHub">https://www.npmjs.com/~GitHub</a>
Actions), a new releaser for simple-git since your current version.</p>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=simple-git&package-manager=npm_and_yarn&previous-version=3.30.0&new-version=3.33.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-11 12:47:00 +01:00
Agent2Agent (A2A) Bot
321d331b67
chore(main): release 0.3.12 (#348)
🤖 I have created a release *beep* *boop*
---


##
[0.3.12](https://github.com/a2aproject/a2a-js/compare/v0.3.11...v0.3.12)
(2026-03-10)


### Bug Fixes

* Fixing missing push configuration after normalization for rest
transport ([#346](https://github.com/a2aproject/a2a-js/issues/346))
([54ac8c4](54ac8c41ca))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2026-03-10 16:29:26 +01:00
bartek-gralewicz
54ac8c41ca
fix: Fixing missing push configuration after normalization for rest transport (#346)
# Description

This PR solves a bug that was mentioned here: #336.

The issue occurred due to missing mapping of `pushNotificationConfig` in
the mapping method. Since mapping is no longer needed, all logic related
to field mapping was removed in this PR.

Changes:

- Extension to an existing unit test to check for
`pushNotificationConfig` presence. This test failed as expected before
removing the normalization, hence, catching the bug for the future.
- Remove rest types and related unions.
- Removed snake_case cases from unit testes.
- Removed normalization functions but remained field checks to align
with currently existing unit tests.

Fixes #336

---------

Co-authored-by: Bartek Gralewicz <bgralewicz@google.com>
2026-03-10 16:22:09 +01:00
Ivan Shymko
c03e80780d
test: fix naming in card-resolver.spec.ts (#347)
It had nothing to do with 0.3 and 1.0.

Re #344
2026-03-10 15:44:01 +01:00
Agent2Agent (A2A) Bot
d45c212ea6
chore(main): release 0.3.11 (#320)
🤖 I have created a release *beep* *boop*
---


##
[0.3.11](https://github.com/a2aproject/a2a-js/compare/v0.3.10...v0.3.11)
(2026-03-10)


### Bug Fixes

* support proto-based AgentCard in AgentCardResolver
([#344](https://github.com/a2aproject/a2a-js/issues/344))
([e71221c](e71221cbc8))
* throw on JSON-RPC response id mismatch
([#318](https://github.com/a2aproject/a2a-js/issues/318))
([5ea1c94](5ea1c94aca))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2026-03-10 10:04:36 +01:00
Ivan Shymko
e71221cbc8
fix: support proto-based AgentCard in AgentCardResolver (#344)
## Description

Fixes an issue where the SDK fails to resolve Agent Cards served in
Protobuf JSON format.

In the v0.3.0 specification, there was a structural drift between the
JSON Schema data model and the Protobuf data model:
- **JSON Schema:** Uses a `"type"` discriminator (e.g., `{"type":
"openIdConnect"}`).
[Source](8d57eba286/specification/json/a2a.json (L1757-L1782))
- **Protobuf:** Uses the `oneof` field name as the discriminator (e.g.,
`{"oauth2SecurityScheme": {...}}`).
[Source](8d57eba286/specification/grpc/a2a.proto (L502-L510))
2026-03-10 09:50:20 +01:00
Ivan Shymko
98293b899a
docs: allow specifying transport preferences in samples CLI (#345)
Now one can do `--transport=` to specify `JSONRPC`, `HTTP+JSON` or
`GRPC` (constants as in the A2A spec).
2026-03-09 17:37:39 +01:00
dependabot[bot]
0338ed38ed
chore(deps): bump minimatch from 9.0.5 to 9.0.8 in /src/samples (#339)
Bumps [minimatch](https://github.com/isaacs/minimatch) from 9.0.5 to
9.0.8.
<details>
<summary>Commits</summary>
<ul>
<li><a
href="446cfa3e2a"><code>446cfa3</code></a>
9.0.8</li>
<li><a
href="8fa151ab95"><code>8fa151a</code></a>
docs: add warning about ReDoS</li>
<li><a
href="71b78a2a4c"><code>71b78a2</code></a>
fix partial matching of globstar patterns</li>
<li><a
href="2de496f6d9"><code>2de496f</code></a>
9.0.7</li>
<li><a
href="0d4616de91"><code>0d4616d</code></a>
limit nested extglob recursion, flatten extglobs</li>
<li><a
href="7117ef381e"><code>7117ef3</code></a>
9.0.6</li>
<li><a
href="2418458b7f"><code>2418458</code></a>
update deps, do not checkin dist</li>
<li><a
href="1d1f531009"><code>1d1f531</code></a>
update deps</li>
<li><a
href="03b1778ab3"><code>03b1778</code></a>
update CI matrix and actions</li>
<li><a
href="f1aaffe08f"><code>f1aaffe</code></a>
update test expectations for coalesced consecutive stars</li>
<li>Additional commits viewable in <a
href="https://github.com/isaacs/minimatch/compare/v9.0.5...v9.0.8">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=minimatch&package-manager=npm_and_yarn&previous-version=9.0.5&new-version=9.0.8)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ivan Shymko <ishymko@google.com>
2026-03-02 17:29:57 +01:00
dependabot[bot]
867b472047
chore(deps): bump rollup from 4.53.5 to 4.59.0 (#340)
Bumps [rollup](https://github.com/rollup/rollup) from 4.53.5 to 4.59.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/rollup/rollup/releases">rollup's
releases</a>.</em></p>
<blockquote>
<h2>v4.59.0</h2>
<h2>4.59.0</h2>
<p><em>2026-02-22</em></p>
<h3>Features</h3>
<ul>
<li>Throw when the generated bundle contains paths that would leave the
output directory (<a
href="https://redirect.github.com/rollup/rollup/issues/6276">#6276</a>)</li>
</ul>
<h3>Pull Requests</h3>
<ul>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6275">#6275</a>:
Validate bundle stays within output dir (<a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
</ul>
<h2>v4.58.0</h2>
<h2>4.58.0</h2>
<p><em>2026-02-20</em></p>
<h3>Features</h3>
<ul>
<li>Also support <code>__NO_SIDE_EFFECTS__</code> annotation before
variable declarations declaring function expressions (<a
href="https://redirect.github.com/rollup/rollup/issues/6272">#6272</a>)</li>
</ul>
<h3>Pull Requests</h3>
<ul>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6256">#6256</a>:
docs: document PreRenderedChunk properties including isDynamicEntry and
isImplicitEntry (<a
href="https://github.com/njg7194"><code>@​njg7194</code></a>, <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6259">#6259</a>:
docs: Correct typo and improve sentence structure in docs for
<code>output.experimentalMinChunkSize</code> (<a
href="https://github.com/millerick"><code>@​millerick</code></a>, <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6260">#6260</a>:
fix(deps): update rust crate swc_compiler_base to v47 (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot], <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6261">#6261</a>:
fix(deps): lock file maintenance minor/patch updates (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot], <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6262">#6262</a>:
Avoid unnecessary cloning of the code string (<a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6263">#6263</a>:
fix(deps): update minor/patch updates (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot], <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6265">#6265</a>:
chore(deps): lock file maintenance (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot])</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6267">#6267</a>:
fix(deps): update minor/patch updates (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot])</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6268">#6268</a>:
chore(deps): update dependency eslint-plugin-unicorn to v63 (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot], <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6269">#6269</a>:
chore(deps): update dependency lru-cache to v11 (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot])</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6270">#6270</a>:
chore(deps): lock file maintenance (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot])</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6272">#6272</a>:
forward NO_SIDE_EFFECTS annotations to function expressions in variable
declarations (<a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
</ul>
<h2>v4.57.1</h2>
<h2>4.57.1</h2>
<p><em>2026-01-30</em></p>
<h3>Bug Fixes</h3>
<ul>
<li>Fix heap corruption issue in Windows (<a
href="https://redirect.github.com/rollup/rollup/issues/6251">#6251</a>)</li>
<li>Ensure exports of a dynamic import are fully included when called
from a try...catch (<a
href="https://redirect.github.com/rollup/rollup/issues/6254">#6254</a>)</li>
</ul>
<h3>Pull Requests</h3>
<ul>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6251">#6251</a>:
fix: Isolate and cache <code>process.report.getReport()</code> calls in
a child process for robust environment detection (<a
href="https://github.com/alan-agius4"><code>@​alan-agius4</code></a>, <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/rollup/rollup/blob/master/CHANGELOG.md">rollup's
changelog</a>.</em></p>
<blockquote>
<h2>4.59.0</h2>
<p><em>2026-02-22</em></p>
<h3>Features</h3>
<ul>
<li>Throw when the generated bundle contains paths that would leave the
output directory (<a
href="https://redirect.github.com/rollup/rollup/issues/6276">#6276</a>)</li>
</ul>
<h3>Pull Requests</h3>
<ul>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6275">#6275</a>:
Validate bundle stays within output dir (<a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
</ul>
<h2>4.58.0</h2>
<p><em>2026-02-20</em></p>
<h3>Features</h3>
<ul>
<li>Also support <code>__NO_SIDE_EFFECTS__</code> annotation before
variable declarations declaring function expressions (<a
href="https://redirect.github.com/rollup/rollup/issues/6272">#6272</a>)</li>
</ul>
<h3>Pull Requests</h3>
<ul>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6256">#6256</a>:
docs: document PreRenderedChunk properties including isDynamicEntry and
isImplicitEntry (<a
href="https://github.com/njg7194"><code>@​njg7194</code></a>, <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6259">#6259</a>:
docs: Correct typo and improve sentence structure in docs for
<code>output.experimentalMinChunkSize</code> (<a
href="https://github.com/millerick"><code>@​millerick</code></a>, <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6260">#6260</a>:
fix(deps): update rust crate swc_compiler_base to v47 (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot], <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6261">#6261</a>:
fix(deps): lock file maintenance minor/patch updates (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot], <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6262">#6262</a>:
Avoid unnecessary cloning of the code string (<a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6263">#6263</a>:
fix(deps): update minor/patch updates (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot], <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6265">#6265</a>:
chore(deps): lock file maintenance (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot])</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6267">#6267</a>:
fix(deps): update minor/patch updates (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot])</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6268">#6268</a>:
chore(deps): update dependency eslint-plugin-unicorn to v63 (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot], <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6269">#6269</a>:
chore(deps): update dependency lru-cache to v11 (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot])</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6270">#6270</a>:
chore(deps): lock file maintenance (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot])</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6272">#6272</a>:
forward NO_SIDE_EFFECTS annotations to function expressions in variable
declarations (<a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
</ul>
<h2>4.57.1</h2>
<p><em>2026-01-30</em></p>
<h3>Bug Fixes</h3>
<ul>
<li>Fix heap corruption issue in Windows (<a
href="https://redirect.github.com/rollup/rollup/issues/6251">#6251</a>)</li>
<li>Ensure exports of a dynamic import are fully included when called
from a try...catch (<a
href="https://redirect.github.com/rollup/rollup/issues/6254">#6254</a>)</li>
</ul>
<h3>Pull Requests</h3>
<ul>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6251">#6251</a>:
fix: Isolate and cache <code>process.report.getReport()</code> calls in
a child process for robust environment detection (<a
href="https://github.com/alan-agius4"><code>@​alan-agius4</code></a>, <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6252">#6252</a>:
chore(deps): update dependency lru-cache to v11 (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot])</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6253">#6253</a>:
chore(deps): lock file maintenance minor/patch updates (<a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot], <a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
<li><a
href="https://redirect.github.com/rollup/rollup/pull/6254">#6254</a>:
Fully include dynamic imports in a try-catch (<a
href="https://github.com/lukastaegert"><code>@​lukastaegert</code></a>)</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="ae846957f1"><code>ae84695</code></a>
4.59.0</li>
<li><a
href="b39616e917"><code>b39616e</code></a>
Update audit-resolve</li>
<li><a
href="c60770d7aa"><code>c60770d</code></a>
Validate bundle stays within output dir (<a
href="https://redirect.github.com/rollup/rollup/issues/6275">#6275</a>)</li>
<li><a
href="33f39c1f20"><code>33f39c1</code></a>
4.58.0</li>
<li><a
href="b61c40803b"><code>b61c408</code></a>
forward NO_SIDE_EFFECTS annotations to function expressions in variable
decla...</li>
<li><a
href="7f00689ec9"><code>7f00689</code></a>
Extend agent instructions</li>
<li><a
href="e7b2b85af0"><code>e7b2b85</code></a>
chore(deps): lock file maintenance (<a
href="https://redirect.github.com/rollup/rollup/issues/6270">#6270</a>)</li>
<li><a
href="2aa5da9baf"><code>2aa5da9</code></a>
fix(deps): update minor/patch updates (<a
href="https://redirect.github.com/rollup/rollup/issues/6267">#6267</a>)</li>
<li><a
href="4319837c54"><code>4319837</code></a>
chore(deps): update dependency lru-cache to v11 (<a
href="https://redirect.github.com/rollup/rollup/issues/6269">#6269</a>)</li>
<li><a
href="c3b6b4bdc4"><code>c3b6b4b</code></a>
chore(deps): update dependency eslint-plugin-unicorn to v63 (<a
href="https://redirect.github.com/rollup/rollup/issues/6268">#6268</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/rollup/rollup/compare/v4.53.5...v4.59.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=rollup&package-manager=npm_and_yarn&previous-version=4.53.5&new-version=4.59.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ivan Shymko <ishymko@google.com>
2026-03-02 12:31:01 +01:00
dependabot[bot]
7f9907496c
chore(deps-dev): bump fast-xml-parser from 5.3.6 to 5.4.1 in /src/samples (#341)
Bumps
[fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser)
from 5.3.6 to 5.4.1.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/releases">fast-xml-parser's
releases</a>.</em></p>
<blockquote>
<h2>Separate Builder</h2>
<p>XML Builder was the part of <a
href="https://github.com/NaturalIntelligence/fast-xml-builder">fast-xml-parser</a>
for years. But considering that any bug in builder may false-alarm the
users who are only using parser and vice-versa, we have decided to split
it into a separate package.</p>
<h2>Migration</h2>
<p>To migrate to fast-xml-builder;</p>
<p>From</p>
<pre lang="js"><code>import { XMLBuilder } from
&quot;fast-xml-parser&quot;;
</code></pre>
<p>To</p>
<pre lang="js"><code>import XMLBuilder from
&quot;fast-xml-builder&quot;;
</code></pre>
<p>XMLBuilder will be removed from current package in any next major
version of this library. So better to migrate.</p>
<h2>support strictReservedNames</h2>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.9...v5.3.9">https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.9...v5.3.9</a></p>
<h2>handle non-array input for XML builder &amp;&amp; support
maxNestedTags</h2>
<ul>
<li>support maxNestedTags</li>
<li>handle non-array input for XML builder when preserveOrder is true
(By <a href="https://github.com/Angelopvtac">Angelo Coetzee</a>)</li>
<li>save use of js properies
<strong>Full Changelog</strong>: <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.7...v5.3.8">https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.7...v5.3.8</a></li>
</ul>
<h2>CJS typing fix</h2>
<h2>What's Changed</h2>
<ul>
<li>Unexport <code>X2jOptions</code> at declaration site by <a
href="https://github.com/Drarig29"><code>@​Drarig29</code></a> in <a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/pull/787">NaturalIntelligence/fast-xml-parser#787</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/Drarig29"><code>@​Drarig29</code></a>
made their first contribution in <a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/pull/787">NaturalIntelligence/fast-xml-parser#787</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.6...v5.3.7">https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.6...v5.3.7</a></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md">fast-xml-parser's
changelog</a>.</em></p>
<blockquote>
<p><!-- raw HTML omitted -->Note: If you find missing information about
particular minor version, that version must have been changed without
any functional change in this library.<!-- raw HTML omitted --></p>
<p>Note: Due to some last quick changes on v4, detail of v4.5.3 &amp;
v4.5.4 are not updated here. v4.5.4x is the last tag of v4 in github
repository. I'm extremely sorry for the confusion</p>
<p><strong>5.4.1  / 2026-02-25</strong></p>
<ul>
<li>fix (<a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/issues/785">#785</a>)
unpairedTag node should not have tag content</li>
</ul>
<p><strong>5.4.0  / 2026-02-25</strong></p>
<ul>
<li>migrate to fast-xml-builder</li>
</ul>
<p><strong>5.3.9 / 2026-02-25</strong></p>
<ul>
<li>support strictReservedNames</li>
</ul>
<p><strong>5.3.8 / 2026-02-25</strong></p>
<ul>
<li>support maxNestedTags</li>
<li>handle non-array input for XML builder when preserveOrder is true
(By <a href="https://github.com/Angelopvtac">Angelo Coetzee</a>)</li>
<li>save use of js properies</li>
</ul>
<p><strong>5.3.7 / 2026-02-20</strong></p>
<ul>
<li>fix typings for CJS (By <a
href="https://github.com/Drarig29">Corentin Girard</a>)</li>
</ul>
<p><strong>5.3.6 / 2026-02-14</strong></p>
<ul>
<li>Improve security and performance of entity processing
<ul>
<li>new options <code>maxEntitySize</code>,
<code>maxExpansionDepth</code>, <code>maxTotalExpansions</code>,
<code>maxExpandedLength</code>,
<code>allowedTags</code>,<code>tagFilter</code></li>
<li>fast return when no edtity is present</li>
<li>improvement replacement logic to reduce number of calls</li>
</ul>
</li>
</ul>
<p><strong>5.3.5 / 2026-02-08</strong></p>
<ul>
<li>fix: Escape regex char in entity name</li>
<li>update strnum to 2.1.2</li>
<li>add missing exports in CJS typings</li>
</ul>
<p><strong>5.3.4 / 2026-01-30</strong></p>
<ul>
<li>fix: handle HTML numeric and hex entities when out of range</li>
</ul>
<p><strong>5.3.3 / 2025-12-12</strong></p>
<ul>
<li>fix <a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/issues/775">#775</a>:
transformTagName with allowBooleanAttributes adds an unnecessary
attribute</li>
</ul>
<p><strong>5.3.2 / 2025-11-14</strong></p>
<ul>
<li>fix for import statement for v6</li>
</ul>
<p><strong>5.3.1 / 2025-11-03</strong></p>
<ul>
<li>Performance improvement for stopNodes (By <a
href="https://github.com/macieklamberski">Maciek Lamberski</a>)</li>
</ul>
<p><strong>5.3.0 / 2025-10-03</strong></p>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="4e7ca80e78"><code>4e7ca80</code></a>
update release info</li>
<li><a
href="36023b4963"><code>36023b4</code></a>
fix (<a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/issues/785">#785</a>)
unpairedTag node should not have tag content</li>
<li><a
href="b3660266f5"><code>b366026</code></a>
separate builder</li>
<li><a
href="6f333a8569"><code>6f333a8</code></a>
update release info</li>
<li><a
href="c3ffbab9e5"><code>c3ffbab</code></a>
support strictReservedNames</li>
<li><a
href="c692040f6b"><code>c692040</code></a>
update release info</li>
<li><a
href="107e34c046"><code>107e34c</code></a>
avoid <code>{}</code> to create an empty object</li>
<li><a
href="60835a4c72"><code>60835a4</code></a>
support maxNestedTags</li>
<li><a
href="f55657c2b1"><code>f55657c</code></a>
avoid direct call to hasOwnProperty</li>
<li><a
href="c13a961910"><code>c13a961</code></a>
handle non-array input for XML builder when preserveOrder is true</li>
<li>Additional commits viewable in <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.6...v5.4.1">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=fast-xml-parser&package-manager=npm_and_yarn&previous-version=5.3.6&new-version=5.4.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-02 10:15:16 +01:00
dependabot[bot]
b3ad0cbc63
chore(deps): bump minimatch (#342)
Bumps and [minimatch](https://github.com/isaacs/minimatch). These
dependencies needed to be updated together.
Updates `minimatch` from 9.0.5 to 9.0.9
<details>
<summary>Commits</summary>
<ul>
<li><a
href="8a10e473e2"><code>8a10e47</code></a>
9.0.9</li>
<li><a
href="c6f180636c"><code>c6f1806</code></a>
brace-expansion@2</li>
<li><a
href="446cfa3e2a"><code>446cfa3</code></a>
9.0.8</li>
<li><a
href="8fa151ab95"><code>8fa151a</code></a>
docs: add warning about ReDoS</li>
<li><a
href="71b78a2a4c"><code>71b78a2</code></a>
fix partial matching of globstar patterns</li>
<li><a
href="2de496f6d9"><code>2de496f</code></a>
9.0.7</li>
<li><a
href="0d4616de91"><code>0d4616d</code></a>
limit nested extglob recursion, flatten extglobs</li>
<li><a
href="7117ef381e"><code>7117ef3</code></a>
9.0.6</li>
<li><a
href="2418458b7f"><code>2418458</code></a>
update deps, do not checkin dist</li>
<li><a
href="1d1f531009"><code>1d1f531</code></a>
update deps</li>
<li>Additional commits viewable in <a
href="https://github.com/isaacs/minimatch/compare/v9.0.5...v9.0.9">compare
view</a></li>
</ul>
</details>
<br />

Updates `minimatch` from 5.1.6 to 5.1.9
<details>
<summary>Commits</summary>
<ul>
<li><a
href="8a10e473e2"><code>8a10e47</code></a>
9.0.9</li>
<li><a
href="c6f180636c"><code>c6f1806</code></a>
brace-expansion@2</li>
<li><a
href="446cfa3e2a"><code>446cfa3</code></a>
9.0.8</li>
<li><a
href="8fa151ab95"><code>8fa151a</code></a>
docs: add warning about ReDoS</li>
<li><a
href="71b78a2a4c"><code>71b78a2</code></a>
fix partial matching of globstar patterns</li>
<li><a
href="2de496f6d9"><code>2de496f</code></a>
9.0.7</li>
<li><a
href="0d4616de91"><code>0d4616d</code></a>
limit nested extglob recursion, flatten extglobs</li>
<li><a
href="7117ef381e"><code>7117ef3</code></a>
9.0.6</li>
<li><a
href="2418458b7f"><code>2418458</code></a>
update deps, do not checkin dist</li>
<li><a
href="1d1f531009"><code>1d1f531</code></a>
update deps</li>
<li>Additional commits viewable in <a
href="https://github.com/isaacs/minimatch/compare/v9.0.5...v9.0.9">compare
view</a></li>
</ul>
</details>
<br />

Updates `minimatch` from 3.1.2 to 3.1.5
<details>
<summary>Commits</summary>
<ul>
<li><a
href="8a10e473e2"><code>8a10e47</code></a>
9.0.9</li>
<li><a
href="c6f180636c"><code>c6f1806</code></a>
brace-expansion@2</li>
<li><a
href="446cfa3e2a"><code>446cfa3</code></a>
9.0.8</li>
<li><a
href="8fa151ab95"><code>8fa151a</code></a>
docs: add warning about ReDoS</li>
<li><a
href="71b78a2a4c"><code>71b78a2</code></a>
fix partial matching of globstar patterns</li>
<li><a
href="2de496f6d9"><code>2de496f</code></a>
9.0.7</li>
<li><a
href="0d4616de91"><code>0d4616d</code></a>
limit nested extglob recursion, flatten extglobs</li>
<li><a
href="7117ef381e"><code>7117ef3</code></a>
9.0.6</li>
<li><a
href="2418458b7f"><code>2418458</code></a>
update deps, do not checkin dist</li>
<li><a
href="1d1f531009"><code>1d1f531</code></a>
update deps</li>
<li>Additional commits viewable in <a
href="https://github.com/isaacs/minimatch/compare/v9.0.5...v9.0.9">compare
view</a></li>
</ul>
</details>
<br />


Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-02 10:11:16 +01:00
dependabot[bot]
d4c261a4aa
chore(deps): bump qs from 6.14.1 to 6.15.0 (#335)
Bumps [qs](https://github.com/ljharb/qs) from 6.14.1 to 6.15.0.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ljharb/qs/blob/main/CHANGELOG.md">qs's
changelog</a>.</em></p>
<blockquote>
<h2><strong>6.15.0</strong></h2>
<ul>
<li>[New] <code>parse</code>: add <code>strictMerge</code> option to
wrap object/primitive conflicts in an array (<a
href="https://redirect.github.com/ljharb/qs/issues/425">#425</a>, <a
href="https://redirect.github.com/ljharb/qs/issues/122">#122</a>)</li>
<li>[Fix] <code>duplicates</code> option should not apply to bracket
notation keys (<a
href="https://redirect.github.com/ljharb/qs/issues/514">#514</a>)</li>
</ul>
<h2><strong>6.14.2</strong></h2>
<ul>
<li>[Fix] <code>parse</code>: mark overflow objects for indexed notation
exceeding <code>arrayLimit</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/546">#546</a>)</li>
<li>[Fix] <code>arrayLimit</code> means max count, not max index, in
<code>combine</code>/<code>merge</code>/<code>parseArrayValue</code></li>
<li>[Fix] <code>parse</code>: throw on <code>arrayLimit</code> exceeded
with indexed notation when <code>throwOnLimitExceeded</code> is true (<a
href="https://redirect.github.com/ljharb/qs/issues/529">#529</a>)</li>
<li>[Fix] <code>parse</code>: enforce <code>arrayLimit</code> on
<code>comma</code>-parsed values</li>
<li>[Fix] <code>parse</code>: fix error message to reflect arrayLimit as
max index; remove extraneous comments (<a
href="https://redirect.github.com/ljharb/qs/issues/545">#545</a>)</li>
<li>[Robustness] avoid <code>.push</code>, use <code>void</code></li>
<li>[readme] document that <code>addQueryPrefix</code> does not add
<code>?</code> to empty output (<a
href="https://redirect.github.com/ljharb/qs/issues/418">#418</a>)</li>
<li>[readme] clarify <code>parseArrays</code> and
<code>arrayLimit</code> documentation (<a
href="https://redirect.github.com/ljharb/qs/issues/543">#543</a>)</li>
<li>[readme] replace runkit CI badge with shields.io check-runs
badge</li>
<li>[meta] fix changelog typo (<code>arrayLength</code> →
<code>arrayLimit</code>)</li>
<li>[actions] fix rebase workflow permissions</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="d9b4c66303"><code>d9b4c66</code></a>
v6.15.0</li>
<li><a
href="cb41a545a3"><code>cb41a54</code></a>
[New] <code>parse</code>: add <code>strictMerge</code> option to wrap
object/primitive conflicts in...</li>
<li><a
href="88e15636da"><code>88e1563</code></a>
[Fix] <code>duplicates</code> option should not apply to bracket
notation keys</li>
<li><a
href="9d441d2704"><code>9d441d2</code></a>
Merge backport release tags v6.0.6–v6.13.3 into main</li>
<li><a
href="85cc8cac6b"><code>85cc8ca</code></a>
v6.12.5</li>
<li><a
href="ffc12aa710"><code>ffc12aa</code></a>
v6.11.4</li>
<li><a
href="0506b11e45"><code>0506b11</code></a>
[actions] update reusable workflows</li>
<li><a
href="6a37fafc75"><code>6a37faf</code></a>
[actions] update reusable workflows</li>
<li><a
href="8e8df5a3b1"><code>8e8df5a</code></a>
[Fix] fix regressions from robustness refactor</li>
<li><a
href="d60bab35a4"><code>d60bab3</code></a>
v6.10.7</li>
<li>Additional commits viewable in <a
href="https://github.com/ljharb/qs/compare/v6.14.1...v6.15.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=qs&package-manager=npm_and_yarn&previous-version=6.14.1&new-version=6.15.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-20 08:38:19 +01:00
dependabot[bot]
3f625b4932
chore(deps): bump fast-xml-parser and @google-cloud/storage in /src/samples (#334)
Bumps
[fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser)
and
[@google-cloud/storage](https://github.com/googleapis/nodejs-storage).
These dependencies needed to be updated together.
Updates `fast-xml-parser` from 4.5.3 to 5.3.6
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/releases">fast-xml-parser's
releases</a>.</em></p>
<blockquote>
<h2>Entity security and performance</h2>
<ul>
<li>Improve security and performance of entity processing
<ul>
<li>new options <code>maxEntitySize</code>,
<code>maxExpansionDepth</code>, <code>maxTotalExpansions</code>,
<code>maxExpandedLength</code>,
<code>allowedTags</code>,<code>tagFilter</code></li>
<li>fast return when no edtity is present</li>
<li>improvement replacement logic to reduce number of calls</li>
<li></li>
</ul>
</li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.5...v5.3.6">https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.5...v5.3.6</a></p>
<h2>v5.3.5</h2>
<h2>What's Changed</h2>
<ul>
<li>Add missing exports to fxp commonjs types by <a
href="https://github.com/jeremymeng"><code>@​jeremymeng</code></a> in <a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/pull/782">NaturalIntelligence/fast-xml-parser#782</a></li>
<li>fix: Escape regex char in entity name</li>
<li>update strnum to 2.1.2</li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a
href="https://github.com/jeremymeng"><code>@​jeremymeng</code></a> made
their first contribution in <a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/pull/782">NaturalIntelligence/fast-xml-parser#782</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.4...v5.3.5">https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.4...v5.3.5</a></p>
<h2>fix: handle HTML numeric and hex entities when out of range</h2>
<p>No release notes provided.</p>
<h2>bug fix and performance improvements</h2>
<ul>
<li>fix <a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/issues/775">#775</a>:
transformTagName with allowBooleanAttributes adds an unnecessary
attribute</li>
<li>Performance improvement for stopNodes (By <a
href="https://github.com/macieklamberski">Maciek Lamberski</a>)</li>
</ul>
<h2>Replace <code>Buffer</code> with <code>Uint8Array</code></h2>
<ul>
<li>Launched Separate CLI module</li>
<li>Replace <code>Buffer</code> with <code>Uint8Array</code></li>
</ul>
<h2>Support EMPTY and ANY with ELEMENT in DOCTYPE</h2>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.2.4...v5.2.4">https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.2.4...v5.2.4</a></p>
<h2>upgrade to ESM module and fixing value parsing issues</h2>
<ul>
<li>Support ESM modules</li>
<li>fix value parsing issues</li>
<li>a feature to access tag location is added (metadata)</li>
<li>fix to read DOCTYPE correctly</li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md">https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md</a></p>
<h2>Summary update on all the previous releases from v4.2.4</h2>
<ul>
<li>Multiple minor fixes provided in the validator and parser</li>
<li>v6 is added for experimental use.</li>
<li>ignoreAttributes support function, and array of string or regex</li>
<li>Add support for parsing HTML numeric entities</li>
<li>v5 of the application is ESM module now. However, JS is also
supported</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md">fast-xml-parser's
changelog</a>.</em></p>
<blockquote>
<p><!-- raw HTML omitted -->Note: If you find missing information about
particular minor version, that version must have been changed without
any functional change in this library.<!-- raw HTML omitted --></p>
<p><strong>5.3.6 / 2026-02-14</strong></p>
<ul>
<li>Improve security and performance of entity processing
<ul>
<li>new options <code>maxEntitySize</code>,
<code>maxExpansionDepth</code>, <code>maxTotalExpansions</code>,
<code>maxExpandedLength</code>,
<code>allowedTags</code>,<code>tagFilter</code></li>
<li>fast return when no edtity is present</li>
<li>improvement replacement logic to reduce number of calls</li>
</ul>
</li>
</ul>
<p><strong>5.3.5 / 2026-02-08</strong></p>
<ul>
<li>fix: Escape regex char in entity name</li>
<li>update strnum to 2.1.2</li>
<li>add missing exports in CJS typings</li>
</ul>
<p><strong>5.3.4 / 2026-01-30</strong></p>
<ul>
<li>fix: handle HTML numeric and hex entities when out of range</li>
</ul>
<p><strong>5.3.3 / 2025-12-12</strong></p>
<ul>
<li>fix <a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/issues/775">#775</a>:
transformTagName with allowBooleanAttributes adds an unnecessary
attribute</li>
</ul>
<p><strong>5.3.2 / 2025-11-14</strong></p>
<ul>
<li>fix for import statement for v6</li>
</ul>
<p><strong>5.3.1 / 2025-11-03</strong></p>
<ul>
<li>Performance improvement for stopNodes (By <a
href="https://github.com/macieklamberski">Maciek Lamberski</a>)</li>
</ul>
<p><strong>5.3.0 / 2025-10-03</strong></p>
<ul>
<li>Use <code>Uint8Array</code> in place of <code>Buffer</code> in
Parser</li>
</ul>
<p><strong>5.2.5 / 2025-06-08</strong></p>
<ul>
<li>Inform user to use <a
href="https://github.com/NaturalIntelligence/fxp-cli">fxp-cli</a>
instead of in-built CLI feature</li>
<li>Export typings  for direct use</li>
</ul>
<p><strong>5.2.4 / 2025-06-06</strong></p>
<ul>
<li>fix (<a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/issues/747">#747</a>):
fix EMPTY and ANY with ELEMENT in DOCTYPE</li>
</ul>
<p><strong>5.2.3 / 2025-05-11</strong></p>
<ul>
<li>fix (<a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/issues/747">#747</a>):
support EMPTY and ANY with ELEMENT in DOCTYPE</li>
</ul>
<p><strong>5.2.2 / 2025-05-05</strong></p>
<ul>
<li>fix (<a
href="https://redirect.github.com/NaturalIntelligence/fast-xml-parser/issues/746">#746</a>):
update strnum to fix parsing issues related to enotations</li>
</ul>
<p><strong>5.2.1 / 2025-04-22</strong></p>
<ul>
<li>fix: read DOCTYPE entity value correctly</li>
<li>read DOCTYPE NOTATION, ELEMENT exp but not using read values</li>
</ul>
<p><strong>5.2.0 / 2025-04-03</strong></p>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/NaturalIntelligence/fast-xml-parser/commits/v5.3.6">compare
view</a></li>
</ul>
</details>
<br />

Updates `@google-cloud/storage` from 7.17.3 to 7.19.0
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/googleapis/nodejs-storage/releases"><code>@​google-cloud/storage</code>'s
releases</a>.</em></p>
<blockquote>
<h2>v7.19.0</h2>
<h2><a
href="https://github.com/googleapis/nodejs-storage/compare/v7.18.0...v7.19.0">7.19.0</a>
(2026-02-05)</h2>
<h3>Features</h3>
<ul>
<li>Enable full object checksum validation on JSON path (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2687">#2687</a>)
(<a
href="08a896240e">08a8962</a>)</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li><strong>deps:</strong> Update dependency fast-xml-parser to v5
[security] (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2713">#2713</a>)
(<a
href="420935a033">420935a</a>)</li>
</ul>
<h2>v7.18.0</h2>
<h2><a
href="https://github.com/googleapis/nodejs-storage/compare/v7.17.3...v7.18.0">7.18.0</a>
(2025-11-28)</h2>
<h3>Features</h3>
<ul>
<li><strong>listBuckets:</strong> Add support for returning partial
success (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2678">#2678</a>)
(<a
href="c7004daae0">c7004da</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/googleapis/nodejs-storage/blob/main/CHANGELOG.md"><code>@​google-cloud/storage</code>'s
changelog</a>.</em></p>
<blockquote>
<h2><a
href="https://github.com/googleapis/nodejs-storage/compare/v7.18.0...v7.19.0">7.19.0</a>
(2026-02-05)</h2>
<h3>Features</h3>
<ul>
<li>Enable full object checksum validation on JSON path (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2687">#2687</a>)
(<a
href="08a896240e">08a8962</a>)</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li><strong>deps:</strong> Update dependency fast-xml-parser to v5
[security] (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2713">#2713</a>)
(<a
href="420935a033">420935a</a>)</li>
</ul>
<h2><a
href="https://github.com/googleapis/nodejs-storage/compare/v7.17.3...v7.18.0">7.18.0</a>
(2025-11-28)</h2>
<h3>Features</h3>
<ul>
<li><strong>listBuckets:</strong> Add support for returning partial
success (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2678">#2678</a>)
(<a
href="c7004daae0">c7004da</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="95a2af4cc8"><code>95a2af4</code></a>
chore(main): release 7.19.0 (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2694">#2694</a>)</li>
<li><a
href="420935a033"><code>420935a</code></a>
fix(deps): update dependency fast-xml-parser to v5 [security] (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2713">#2713</a>)</li>
<li><a
href="4e3c328ccf"><code>4e3c328</code></a>
test: skip system tests requiring public access (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2717">#2717</a>)</li>
<li><a
href="30522654c5"><code>3052265</code></a>
chore: fix lint failures (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2685">#2685</a>)</li>
<li><a
href="08a896240e"><code>08a8962</code></a>
feat: Enable full object checksum validation on JSON path (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2687">#2687</a>)</li>
<li><a
href="3dcda1b715"><code>3dcda1b</code></a>
chore: lint failures (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2681">#2681</a>)</li>
<li><a
href="3e5210f133"><code>3e5210f</code></a>
chore(main): release 7.18.0 (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2684">#2684</a>)</li>
<li><a
href="c7004daae0"><code>c7004da</code></a>
feat(listBuckets): Add support for returning partial success (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2678">#2678</a>)</li>
<li><a
href="633a13a161"><code>633a13a</code></a>
chore(python): remove configure_previous_major_version_branches (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2675">#2675</a>)</li>
<li><a
href="bae7040760"><code>bae7040</code></a>
samples: Add Soft Delete policy and object management samples (<a
href="https://redirect.github.com/googleapis/nodejs-storage/issues/2676">#2676</a>)</li>
<li>See full diff in <a
href="https://github.com/googleapis/nodejs-storage/compare/v7.17.3...v7.19.0">compare
view</a></li>
</ul>
</details>
<br />


Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-18 08:05:38 +01:00
dependabot[bot]
d9ae691980
chore(deps-dev): bump qs from 6.14.1 to 6.14.2 in /src/samples (#333)
Bumps [qs](https://github.com/ljharb/qs) from 6.14.1 to 6.14.2.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ljharb/qs/blob/main/CHANGELOG.md">qs's
changelog</a>.</em></p>
<blockquote>
<h2><strong>6.14.2</strong></h2>
<ul>
<li>[Fix] <code>parse</code>: mark overflow objects for indexed notation
exceeding <code>arrayLimit</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/546">#546</a>)</li>
<li>[Fix] <code>arrayLimit</code> means max count, not max index, in
<code>combine</code>/<code>merge</code>/<code>parseArrayValue</code></li>
<li>[Fix] <code>parse</code>: throw on <code>arrayLimit</code> exceeded
with indexed notation when <code>throwOnLimitExceeded</code> is true (<a
href="https://redirect.github.com/ljharb/qs/issues/529">#529</a>)</li>
<li>[Fix] <code>parse</code>: enforce <code>arrayLimit</code> on
<code>comma</code>-parsed values</li>
<li>[Fix] <code>parse</code>: fix error message to reflect arrayLimit as
max index; remove extraneous comments (<a
href="https://redirect.github.com/ljharb/qs/issues/545">#545</a>)</li>
<li>[Robustness] avoid <code>.push</code>, use <code>void</code></li>
<li>[readme] document that <code>addQueryPrefix</code> does not add
<code>?</code> to empty output (<a
href="https://redirect.github.com/ljharb/qs/issues/418">#418</a>)</li>
<li>[readme] clarify <code>parseArrays</code> and
<code>arrayLimit</code> documentation (<a
href="https://redirect.github.com/ljharb/qs/issues/543">#543</a>)</li>
<li>[readme] replace runkit CI badge with shields.io check-runs
badge</li>
<li>[meta] fix changelog typo (<code>arrayLength</code> →
<code>arrayLimit</code>)</li>
<li>[actions] fix rebase workflow permissions</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="bdcf0c7f82"><code>bdcf0c7</code></a>
v6.14.2</li>
<li><a
href="294db90c81"><code>294db90</code></a>
[readme] document that <code>addQueryPrefix</code> does not add
<code>?</code> to empty output</li>
<li><a
href="5c308e5516"><code>5c308e5</code></a>
[readme] clarify <code>parseArrays</code> and <code>arrayLimit</code>
documentation</li>
<li><a
href="6addf8cf73"><code>6addf8c</code></a>
[Fix] <code>parse</code>: mark overflow objects for indexed notation
exceeding <code>arrayLimit</code></li>
<li><a
href="cfc108f662"><code>cfc108f</code></a>
[Fix] <code>arrayLimit</code> means max count, not max index, in
<code>combine</code>/<code>merge</code>/`pars...</li>
<li><a
href="febb64442a"><code>febb644</code></a>
[Fix] <code>parse</code>: throw on <code>arrayLimit</code> exceeded with
indexed notation when `thr...</li>
<li><a
href="f6a7abff1f"><code>f6a7abf</code></a>
[Fix] <code>parse</code>: enforce <code>arrayLimit</code> on
<code>comma</code>-parsed values</li>
<li><a
href="fbc5206c25"><code>fbc5206</code></a>
[Fix] <code>parse</code>: fix error message to reflect arrayLimit as max
index; remove e...</li>
<li><a
href="1b9a8b4e78"><code>1b9a8b4</code></a>
[actions] fix rebase workflow permissions</li>
<li><a
href="2a35775614"><code>2a35775</code></a>
[meta] fix changelog typo (<code>arrayLength</code> →
<code>arrayLimit</code>)</li>
<li>Additional commits viewable in <a
href="https://github.com/ljharb/qs/compare/v6.14.1...v6.14.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=qs&package-manager=npm_and_yarn&previous-version=6.14.1&new-version=6.14.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-13 09:53:09 +01:00
Ivan Shymko
1140122adf
ci: fix lint.yml syntax (#332)
Was broken in #329 accidentially.

<img width="1738" height="1916" alt="image"
src="https://github.com/user-attachments/assets/a1db333d-37a3-4a9c-b1e4-9f98754477b9"
/>


i.e. https://github.com/a2aproject/a2a-js/actions/runs/21979649269
2026-02-13 09:50:04 +01:00
Ivan Shymko
95543f88e9
refactor: strict mode fixes (#331)
Mainly to test Betterer workflow.

```
🎉 Betterer (5,538ms): 1 test done!
✅ TypeScript Strict Mode: "TypeScript Strict Mode" got better! (3 fixed issues, 58 remaining) 😍
・ 1 fixed issue in "src/client/factory.ts".
・ 1 fixed issue in "src/server/events/execution_event_queue.ts".
・ 1 fixed, 1 existing issues in "src/server/express/rest_handler.ts".
```

Re #182
2026-02-13 09:15:47 +01:00
Ivan Shymko
40b840d754
build: integrate betterer to progress with strict mode (#329)
1. Integrate
[betterer](https://phenomnomnominal.github.io/betterer/docs/introduction)
and enable strict mode test to stop introducing more errors.
2. Refactor `npm` scripts to integrate this workflow better: `npm run
lint` will do all safe automatic fixes (from both linters and betterer),
while `npm run lint:ci` will strictly fail if formatting changes or
betterer update is required.

Doing this before 1.0 work (#321) as many code changes are going to be
required either way.

Re #182

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-02-12 11:58:46 +01:00
Corvid Agent
5ea1c94aca
fix: throw on JSON-RPC response id mismatch (#318)
## Summary

Replaces `console.error`/`console.warn` calls with thrown errors when a
JSON-RPC response id does not match the request id. Per the JSON-RPC 2.0
specification, this is a protocol invariant violation — continuing
execution with a mismatched response can lead to silent data corruption.

### Changes

- **`_sendRpcRequest`**: `console.error` → `throw new Error` on id
mismatch
- **`_processSseEventData`**: `console.warn` → `throw new Error` on id
mismatch
- **`_processSseEventData` catch block**: Added the new error message to
the pass-through condition so it is not swallowed and re-wrapped as a
parse error

### Context

From the code review on PR #169: *"Go SDK doesn't perform any
validation, but I'd probably be throwing in case of a mismatch"* —
@yarolegovich

Fixes #176

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 08:36:45 +01:00
Agent2Agent (A2A) Bot
e056416335
chore(main): release 0.3.10 (#312)
🤖 I have created a release *beep* *boop*
---


##
[0.3.10](https://github.com/a2aproject/a2a-js/compare/v0.3.9...v0.3.10)
(2026-01-27)


### Bug Fixes

* do not use ReadableStream async iterator in SSE stream parsing
([#311](https://github.com/a2aproject/a2a-js/issues/311))
([5359fa8](5359fa802f))
* preserve typed error as cause in SSE errors
([#315](https://github.com/a2aproject/a2a-js/issues/315))
([d39544e](d39544ea4b))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2026-02-03 09:59:14 +01:00
Johannes Brüderl
d39544ea4b
fix: preserve typed error as cause in SSE errors (#315)
## What

Wrap the typed error from `mapToError()` as the `cause` when throwing
SSE stream errors.

## Why

When an SSE stream contains a JSON-RPC error, we throw an Error with a
formatted message string. The structured error data (code, message,
data) is serialized into that string and lost. Consumers who need the
structured data have to parse it back out with regex.

## Implementation details

Use the standard JS error `cause` option to preserve the typed error:

```typescript
throw new Error(
  `SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`,
  { cause: JsonRpcTransport.mapToError(a2aStreamResponse as JSONRPCErrorResponse) }
);
```

Backward compatible - the message string is unchanged. Consumers can
access structured data via:

```typescript
const cause = error.cause as JSONRPCTransportError;
const { code, message, data } = cause.errorResponse.error;
```
2026-01-27 19:48:23 +01:00
Ivan Shymko
b8158fdb7d
ci: do not run TCK and unit tests on samples folder updates (#314)
Follow-up for #282.
2026-01-26 17:17:25 +01:00
Ivan Shymko
33be02c72f
docs: use artifacts for agent result in movie-agent sample (#313)
Same as #297 but for `movie-agent`. Artifacts should be used for this:
https://github.com/a2aproject/A2A/issues/822#issuecomment-3084892313.
2026-01-26 17:13:42 +01:00
Luca Bertelli
5359fa802f
fix: do not use ReadableStream async iterator in SSE stream parsing (#311)
# Description

The async iterator in `ReadableStream` is not available in browsers like
Safari:
[MDN](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#browser_compatibility).
This PR changes it to a lower-level API which has better support across
different environments.

Fixes #308.
2026-01-23 14:41:02 +01:00
dependabot[bot]
f31e0c5960
chore(deps-dev): bump lodash from 4.17.21 to 4.17.23 (#310) 2026-01-22 07:17:33 +00:00
dependabot[bot]
fa8a7f5581
chore(deps): bump wrangler and @cloudflare/vitest-pool-workers (#309)
Bumps
[wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler)
to 4.59.3 and updates ancestor dependency
[@cloudflare/vitest-pool-workers](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-pool-workers).
These dependencies need to be updated together.

Updates `wrangler` from 4.54.0 to 4.59.3
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/cloudflare/workers-sdk/releases">wrangler's
releases</a>.</em></p>
<blockquote>
<h2>wrangler@4.59.3</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/9396">#9396</a>
<a
href="75386b1f14"><code>75386b1</code></a>
Thanks <a href="https://github.com/gnekich"><code>@​gnekich</code></a>!
- Fix <code>wrangler login</code> with custom
<code>callback-host</code>/<code>callback-port</code></p>
<p>The Cloudflare OAuth API always requires the
<code>redirect_uri</code> to be <code>localhost:8976</code>. However,
sometimes the Wrangler OAuth server needed to listen on a different
host/port, for example when running from inside a container. We were
previously incorrectly setting the <code>redirect_uri</code> to the
configured callback host/port, but it needs to be up to the user to map
<code>localhost:8976</code> to the Wrangler OAuth server in the
container.</p>
<p><strong>Example:</strong></p>
<p>You might run Wrangler inside a docker container like this:
<code>docker run -p 8989:8976 &lt;image&gt;</code>, which forwards port
8976 on your host to 8989 inside the container.</p>
<p>Then inside the container, run <code>wrangler login
--callback-host=0.0.0.0 --callback-port=8989</code></p>
<p>The OAuth link still has a <code>redirect_uri</code> set
to<code>localhost:8976</code>. For example
<code>https://dash.cloudflare.com/oauth2/auth?...&amp;redirect_uri=http%3A%2F%2Flocalhost%3A8976%2Foauth%2Fcallback&amp;...</code></p>
<p>However the redirect to<code> localhost:8976</code> is then forwarded
to the Wrangler OAuth server inside your container, allowing the login
to complete.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11925">#11925</a>
<a
href="8e4a0e5e8d"><code>8e4a0e5</code></a>
Thanks <a
href="https://github.com/apps/dependabot"><code>@​dependabot</code></a>!
- chore: update dependencies of &quot;miniflare&quot;,
&quot;wrangler&quot;</p>
<p>The following dependency versions have been updated:</p>
<table>
<thead>
<tr>
<th>Dependency</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody>
<tr>
<td>workerd</td>
<td>1.20260114.0</td>
<td>1.20260115.0</td>
</tr>
</tbody>
</table>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11942">#11942</a>
<a
href="133bf95783"><code>133bf95</code></a>
Thanks <a
href="https://github.com/penalosa"><code>@​penalosa</code></a>! - chore:
update dependencies of &quot;miniflare&quot;, &quot;wrangler&quot;</p>
<p>The following dependency versions have been updated:</p>
<table>
<thead>
<tr>
<th>Dependency</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody>
<tr>
<td>workerd</td>
<td>1.20260115.0</td>
<td>1.20260116.0</td>
</tr>
</tbody>
</table>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11922">#11922</a>
<a
href="93d8d78ce0"><code>93d8d78</code></a>
Thanks <a
href="https://github.com/dario-piotrowicz"><code>@​dario-piotrowicz</code></a>!
- Improve telemetry errors being sent to Sentry by <code>wrangler
init</code> when it delegates to C3 by ensuring that they contain the
output of the C3 execution.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11940">#11940</a>
<a
href="69ff962048"><code>69ff962</code></a>
Thanks <a
href="https://github.com/penalosa"><code>@​penalosa</code></a>! - Show
helpful messages for file not found errors (<code>ENOENT</code>)</p>
<p>When users encounter file not found errors, Wrangler now displays a
helpful message with the missing file path and common causes, instead of
reporting to Sentry.</p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11904">#11904</a>
<a
href="22727c29ee"><code>22727c2</code></a>
Thanks <a
href="https://github.com/danielrs"><code>@​danielrs</code></a>! - Fix
false positive infinite loop detection for exact path redirects</p>
<p>Fixed an issue where the redirect validation incorrectly flagged
exact path redirects like <code>/ /index.html 200</code> as infinite
loops. This was particularly problematic when <code>html_handling</code>
is set to &quot;none&quot;, where such redirects are valid.</p>
<p>The fix makes the validation more specific to only block wildcard
patterns (like <code>/* /index.html</code>) that would actually cause
infinite loops, while allowing exact path matches that are valid in
certain configurations.</p>
<p>Fixes: <a
href="https://redirect.github.com/cloudflare/workers-sdk/issues/11824">cloudflare/workers-sdk#11824</a></p>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11946">#11946</a>
<a
href="fa39a73040"><code>fa39a73</code></a>
Thanks <a
href="https://github.com/MattieTK"><code>@​MattieTK</code></a>! - Fix
<code>configFileName</code> returning wrong filename for
<code>.jsonc</code> config files</p>
<p>Previously, users with a <code>wrangler.jsonc</code> config file
would see error messages and hints referring to
<code>wrangler.json</code> instead of <code>wrangler.jsonc</code>. This
was because the <code>configFormat</code> function collapsed both
<code>.json</code> and <code>.jsonc</code> files into a single
<code>&quot;jsonc&quot;</code> value, losing the distinction between
them.</p>
</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="0c7e1f4bd4"><code>0c7e1f4</code></a>
Version Packages (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler/issues/11937">#11937</a>)</li>
<li><a
href="75386b1f14"><code>75386b1</code></a>
Always pass a valid <code>redirect_uri</code> callback parameter
(<code>localhost:8976</code>) to C...</li>
<li><a
href="d58fbd1189"><code>d58fbd1</code></a>
Wrangler: Make <code>name</code> the positional argument for
<code>wrangler delete</code> instead o...</li>
<li><a
href="133bf95783"><code>133bf95</code></a>
Add <code>MessageBuilder</code> support for Email Sending API in local
mode (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler/issues/11942">#11942</a>)</li>
<li><a
href="4ac7c82609"><code>4ac7c82</code></a>
[wrangler] Include version components in command event metrics (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler/issues/11968">#11968</a>)</li>
<li><a
href="69ff962048"><code>69ff962</code></a>
Reduce more Sentry noise (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler/issues/11940">#11940</a>)</li>
<li><a
href="029531acd2"><code>029531a</code></a>
Wrangler: cache chosen account in memory to avoid repeated prompts (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler/issues/11962">#11962</a>)</li>
<li><a
href="bc70bfa486"><code>bc70bfa</code></a>
Re-enable Media binding e2e tests (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler/issues/11954">#11954</a>)</li>
<li><a
href="93d8d78ce0"><code>93d8d78</code></a>
Ensure that <code>wrangler init</code> includes C3 error details when
reporting to Sentr...</li>
<li><a
href="fa39a73040"><code>fa39a73</code></a>
fix(wrangler): return correct config filename for .jsonc files (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler/issues/11946">#11946</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/cloudflare/workers-sdk/commits/wrangler@4.59.3/packages/wrangler">compare
view</a></li>
</ul>
</details>
<br />

Updates `@cloudflare/vitest-pool-workers` from 0.10.15 to 0.12.5
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/cloudflare/workers-sdk/releases"><code>@​cloudflare/vitest-pool-workers</code>'s
releases</a>.</em></p>
<blockquote>
<h2><code>@​cloudflare/vitest-pool-workers</code><a
href="https://github.com/0"><code>@​0</code></a>.12.5</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11967">#11967</a>
<a
href="202c59e4f4"><code>202c59e</code></a>
Thanks <a
href="https://github.com/emily-shen"><code>@​emily-shen</code></a>! -
chore: update undici</p>
<p>The following dependency versions have been updated:</p>
<table>
<thead>
<tr>
<th>Dependency</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody>
<tr>
<td>undici</td>
<td>7.14.0</td>
<td>7.18.2</td>
</tr>
</tbody>
</table>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11943">#11943</a>
<a
href="25e2c608d5"><code>25e2c60</code></a>
Thanks <a href="https://github.com/vicb"><code>@​vicb</code></a>! - Bump
capnp-es to ^0.0.14</p>
</li>
<li>
<p>Updated dependencies [<a
href="75386b1f14"><code>75386b1</code></a>,
<a
href="8e4a0e5e8d"><code>8e4a0e5</code></a>,
<a
href="133bf95783"><code>133bf95</code></a>,
<a
href="93d8d78ce0"><code>93d8d78</code></a>,
<a
href="69ff962048"><code>69ff962</code></a>,
<a
href="22727c29ee"><code>22727c2</code></a>,
<a
href="fa39a73040"><code>fa39a73</code></a>,
<a
href="4ac7c82609"><code>4ac7c82</code></a>,
<a
href="69ff962048"><code>69ff962</code></a>,
<a
href="029531acd2"><code>029531a</code></a>,
<a
href="d58fbd1189"><code>d58fbd1</code></a>,
<a
href="202c59e4f4"><code>202c59e</code></a>,
<a
href="133bf95783"><code>133bf95</code></a>,
<a
href="25e2c608d5"><code>25e2c60</code></a>,
<a
href="69ff962048"><code>69ff962</code></a>]:</p>
<ul>
<li>wrangler@4.59.3</li>
<li>miniflare@4.20260116.0</li>
</ul>
</li>
</ul>
<h2><code>@​cloudflare/vitest-pool-workers</code><a
href="https://github.com/0"><code>@​0</code></a>.12.4</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11898">#11898</a>
<a
href="c17e971af0"><code>c17e971</code></a>
Thanks <a
href="https://github.com/petebacondarwin"><code>@​petebacondarwin</code></a>!
- Bundle more third-party dependencies to reduce supply chain risk</p>
<p>Previously, several small utility packages were listed as runtime
dependencies and
installed separately. These are now bundled directly into the published
packages,
reducing the number of external dependencies users need to trust.</p>
<p>Bundled dependencies:</p>
<ul>
<li><strong>miniflare</strong>: <code>acorn</code>,
<code>acorn-walk</code>, <code>exit-hook</code>,
<code>glob-to-regexp</code>, <code>stoppable</code></li>
<li><strong>kv-asset-handler</strong>: <code>mime</code></li>
<li><strong>vite-plugin-cloudflare</strong>:
<code>@remix-run/node-fetch-server</code>, <code>defu</code>,
<code>get-port</code>, <code>picocolors</code>,
<code>tinyglobby</code></li>
<li><strong>vitest-pool-workers</strong>: <code>birpc</code>,
<code>devalue</code>, <code>get-port</code>, <code>semver</code></li>
</ul>
</li>
<li>
<p>Updated dependencies [<a
href="e78186dae9"><code>e78186d</code></a>,
<a
href="fe4faa3066"><code>fe4faa3</code></a>,
<a
href="4714ca12c1"><code>4714ca1</code></a>,
<a
href="c17e971af0"><code>c17e971</code></a>,
<a
href="695b043b4d"><code>695b043</code></a>]:</p>
<ul>
<li>miniflare@4.20260114.0</li>
<li>wrangler@4.59.2</li>
</ul>
</li>
</ul>
<h2><code>@​cloudflare/vitest-pool-workers</code><a
href="https://github.com/0"><code>@​0</code></a>.12.3</h2>
<h3>Patch Changes</h3>
<ul>
<li>Updated dependencies [<a
href="99b1f328a9"><code>99b1f32</code></a>]:
<ul>
<li>wrangler@4.59.1</li>
</ul>
</li>
</ul>
<h2><code>@​cloudflare/vitest-pool-workers</code><a
href="https://github.com/0"><code>@​0</code></a>.12.2</h2>
<h3>Patch Changes</h3>
<ul>
<li>Updated dependencies [<a
href="b0e54b26f2"><code>b0e54b2</code></a>,
<a
href="ed60c4f01c"><code>ed60c4f</code></a>,
<a
href="faa5753fa6"><code>faa5753</code></a>,
<a
href="e574ef3e73"><code>e574ef3</code></a>,
<a
href="b6148ed733"><code>b6148ed</code></a>,
<a
href="ab3859c597"><code>ab3859c</code></a>,
<a
href="0eb973deb5"><code>0eb973d</code></a>,
<a
href="ad65efa73a"><code>ad65efa</code></a>,
<a
href="fc96e5fe11"><code>fc96e5f</code></a>,
<a
href="43d5363c7b"><code>43d5363</code></a>,
<a
href="0f8d69d310"><code>0f8d69d</code></a>]:
<ul>
<li>wrangler@4.59.0</li>
<li>miniflare@4.20260111.0</li>
</ul>
</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/cloudflare/workers-sdk/blob/main/packages/vitest-pool-workers/CHANGELOG.md"><code>@​cloudflare/vitest-pool-workers</code>'s
changelog</a>.</em></p>
<blockquote>
<h2>0.12.5</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11967">#11967</a>
<a
href="202c59e4f4"><code>202c59e</code></a>
Thanks <a
href="https://github.com/emily-shen"><code>@​emily-shen</code></a>! -
chore: update undici</p>
<p>The following dependency versions have been updated:</p>
<table>
<thead>
<tr>
<th>Dependency</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody>
<tr>
<td>undici</td>
<td>7.14.0</td>
<td>7.18.2</td>
</tr>
</tbody>
</table>
</li>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11943">#11943</a>
<a
href="25e2c608d5"><code>25e2c60</code></a>
Thanks <a href="https://github.com/vicb"><code>@​vicb</code></a>! - Bump
capnp-es to ^0.0.14</p>
</li>
<li>
<p>Updated dependencies [<a
href="75386b1f14"><code>75386b1</code></a>,
<a
href="8e4a0e5e8d"><code>8e4a0e5</code></a>,
<a
href="133bf95783"><code>133bf95</code></a>,
<a
href="93d8d78ce0"><code>93d8d78</code></a>,
<a
href="69ff962048"><code>69ff962</code></a>,
<a
href="22727c29ee"><code>22727c2</code></a>,
<a
href="fa39a73040"><code>fa39a73</code></a>,
<a
href="4ac7c82609"><code>4ac7c82</code></a>,
<a
href="69ff962048"><code>69ff962</code></a>,
<a
href="029531acd2"><code>029531a</code></a>,
<a
href="d58fbd1189"><code>d58fbd1</code></a>,
<a
href="202c59e4f4"><code>202c59e</code></a>,
<a
href="133bf95783"><code>133bf95</code></a>,
<a
href="25e2c608d5"><code>25e2c60</code></a>,
<a
href="69ff962048"><code>69ff962</code></a>]:</p>
<ul>
<li>wrangler@4.59.3</li>
<li>miniflare@4.20260116.0</li>
</ul>
</li>
</ul>
<h2>0.12.4</h2>
<h3>Patch Changes</h3>
<ul>
<li>
<p><a
href="https://redirect.github.com/cloudflare/workers-sdk/pull/11898">#11898</a>
<a
href="c17e971af0"><code>c17e971</code></a>
Thanks <a
href="https://github.com/petebacondarwin"><code>@​petebacondarwin</code></a>!
- Bundle more third-party dependencies to reduce supply chain risk</p>
<p>Previously, several small utility packages were listed as runtime
dependencies and
installed separately. These are now bundled directly into the published
packages,
reducing the number of external dependencies users need to trust.</p>
<p>Bundled dependencies:</p>
<ul>
<li><strong>miniflare</strong>: <code>acorn</code>,
<code>acorn-walk</code>, <code>exit-hook</code>,
<code>glob-to-regexp</code>, <code>stoppable</code></li>
<li><strong>kv-asset-handler</strong>: <code>mime</code></li>
<li><strong>vite-plugin-cloudflare</strong>:
<code>@remix-run/node-fetch-server</code>, <code>defu</code>,
<code>get-port</code>, <code>picocolors</code>,
<code>tinyglobby</code></li>
<li><strong>vitest-pool-workers</strong>: <code>birpc</code>,
<code>devalue</code>, <code>get-port</code>, <code>semver</code></li>
</ul>
</li>
<li>
<p>Updated dependencies [<a
href="e78186dae9"><code>e78186d</code></a>,
<a
href="fe4faa3066"><code>fe4faa3</code></a>,
<a
href="4714ca12c1"><code>4714ca1</code></a>,
<a
href="c17e971af0"><code>c17e971</code></a>,
<a
href="695b043b4d"><code>695b043</code></a>]:</p>
<ul>
<li>miniflare@4.20260114.0</li>
<li>wrangler@4.59.2</li>
</ul>
</li>
</ul>
<h2>0.12.3</h2>
<h3>Patch Changes</h3>
<ul>
<li>Updated dependencies [<a
href="99b1f328a9"><code>99b1f32</code></a>]:
<ul>
<li>wrangler@4.59.1</li>
</ul>
</li>
</ul>
<h2>0.12.2</h2>
<h3>Patch Changes</h3>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="0c7e1f4bd4"><code>0c7e1f4</code></a>
Version Packages (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-pool-workers/issues/11937">#11937</a>)</li>
<li><a
href="9f59043888"><code>9f59043</code></a>
fix(vitest-pool-workers): suppress deprecation warnings in test
subprocesses ...</li>
<li><a
href="25e2c608d5"><code>25e2c60</code></a>
Bump capnp-es to ^0.0.14 (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-pool-workers/issues/11943">#11943</a>)</li>
<li><a
href="bca7114b51"><code>bca7114</code></a>
Version Packages (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-pool-workers/issues/11903">#11903</a>)</li>
<li><a
href="c17e971af0"><code>c17e971</code></a>
chore: add CI validation for external package dependencies (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-pool-workers/issues/11898">#11898</a>)</li>
<li><a
href="37a8607161"><code>37a8607</code></a>
Version Packages (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-pool-workers/issues/11890">#11890</a>)</li>
<li><a
href="e98c95aa22"><code>e98c95a</code></a>
Version Packages (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-pool-workers/issues/11836">#11836</a>)</li>
<li><a
href="455361bfbe"><code>455361b</code></a>
Version Packages (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-pool-workers/issues/11819">#11819</a>)</li>
<li><a
href="f97860992d"><code>f978609</code></a>
Version Packages (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-pool-workers/issues/11700">#11700</a>)</li>
<li><a
href="6a05b1cdf8"><code>6a05b1c</code></a>
chore(deps): update zod from ^3.22.3 to ^3.25.76 (<a
href="https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-pool-workers/issues/11493">#11493</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/cloudflare/workers-sdk/commits/@cloudflare/vitest-pool-workers@0.12.5/packages/vitest-pool-workers">compare
view</a></li>
</ul>
</details>
<br />


Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-22 08:10:41 +01:00
Agent2Agent (A2A) Bot
3d9a052fe8
chore(main): release 0.3.9 (#298)
🤖 I have created a release *beep* *boop*
---


## [0.3.9](https://github.com/a2aproject/a2a-js/compare/v0.3.8...v0.3.9)
(2026-01-21)


### Features

* implement gRPC client
([#299](https://github.com/a2aproject/a2a-js/issues/299))
([dbdb96e](dbdb96eeb1))
* implement gRPC server
([#279](https://github.com/a2aproject/a2a-js/issues/279))
([bd4caa2](bd4caa22a0))


### Bug Fixes

* use proto default values in generated a2a_types.ts
([#303](https://github.com/a2aproject/a2a-js/issues/303))
([0215d42](0215d42326))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2026-01-21 17:36:58 +01:00
Guglielmo Colombo
987fbed0a5
docs: Document supported GRPC transport (#306)
# Description

Integration of gRpc spec in the documentation
2026-01-21 17:13:03 +01:00
Ivan Shymko
40acbd4d2c
ci: properly setup npm install cache (#305)
# Description

Add `cache` to `actions/setup-node@v4` where it was previously missing.
2026-01-20 14:52:46 +01:00
Ivan Shymko
53bfcefc85
docs: support gRPC in samples/cli (#307)
# Description

Add gRPC factory and add some debug output around transports.

Tested against [a2a-go
helloworld](https://github.com/a2aproject/a2a-go/tree/main/examples/helloworld/server/grpc)
example (`go run main.go`):

```
$ npm run a2a:cli -- http://127.0.0.1:9001

> a2a:cli
> tsx cli.ts http://127.0.0.1:9001

A2A Terminal Client
Agent Base URL: http://127.0.0.1:9001
Attempting to fetch agent card from agent at: http://127.0.0.1:9001
✓ Agent Card Found:
  Name:        Hello World Agent
  Description: Just a hello world agent
  Version:     N/A
  Streaming:   Supported
  Supported Transports: GRPC

✓ Connected via GrpcTransport
No active task or context initially. Use '/new' to start a fresh session or send a message.
Enter messages, or use '/new' to start a new session. '/exit' to quit.
Hello World Agent > You: hello
Sending message...

Hello World Agent [11:57:31 AM]: ✉️ Message Stream Event:
  Part 1: 📝 Text: Hello, world!
--- End of response stream for this input ---
Hello World Agent > You:
```
2026-01-20 14:07:18 +01:00
Ivan Shymko
a0f144df36
test: test sendMessageStream fallback to sendMessage in e2e.spec.ts (#304) 2026-01-20 10:23:34 +01:00
Guglielmo Colombo
0215d42326
fix: use proto default values in generated a2a_types.ts (#303)
# Description

This PR standardizes the handling of optional fields in the generated
a2a_types and converters. It aligns the codebase with Protobuf standards
by replacing undefined checks with empty string checks for missing
string values.

**Key Changes**
- Generated Types (a2a_types.ts):
  - Removed the optionality from generated string fields.
- Updated fromJSON and toJSON methods to validate against empty strings
("") instead of undefined for missing values.

- Converters:
- ToProto: Updated to convert undefined domain fields into empty
strings, ensuring compliance with the new non-optional proto types.
- FromProto: Updated to convert empty strings from the proto layer back
into undefined, preserving the existing undefined semantics for the
internal domain model.

**Motivation**
These changes ensure consistency with the Protobuf specification, where
missing strings must default to the empty string rather than undefined.
2026-01-20 09:52:15 +01:00
Guglielmo Colombo
dbdb96eeb1
feat: implement gRPC client (#299)
# Description

This PR extends the implementation of grpc to Client.
A new index.js is created to export the grpc specific functions,
preventing the need for every client to install the `grpc/js` package

Release-As: 0.3.9

Fixes #275  🦕

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Ivan Shymko <vana.shimko@gmail.com>
2026-01-19 16:15:51 +01:00
Ivan Shymko
66a59d0532
test: remove delays in push notification integration tests (#302)
# Description

`send` is not awaited in the `DefaultRequestHandler`, so returning a
final promise has no impact on it. Collect all promises to wait for
sending push notifications instead of relying on a static delay.

Fixes #148
2026-01-16 13:48:08 +01:00
Ivan Shymko
f1626afa2a
build: remove gts dev dependency (#301)
# Description

1. Set `clean: true` in `tsup.config.ts` which enables `Clean output
directory before each build`.
2. Remove `gts` dev dependency as it has a lot of transitive
dependencies and was only used in `clean` script which just removes the
output directory.
2026-01-16 11:32:52 +01:00
dependabot[bot]
0de54d607a
chore(deps-dev): bump devalue from 5.6.1 to 5.6.2 (#300)
Bumps [devalue](https://github.com/sveltejs/devalue) from 5.6.1 to
5.6.2.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/sveltejs/devalue/releases">devalue's
releases</a>.</em></p>
<blockquote>
<h2>v5.6.2</h2>
<h3>Patch Changes</h3>
<ul>
<li>1175584: fix: validate input for <code>ArrayBuffer</code>
parsing</li>
<li>e46afa6: fix: validate input for typed arrays</li>
<li>1175584: fix: more helpful errors for inputs causing stack
overflows</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md">devalue's
changelog</a>.</em></p>
<blockquote>
<h2>5.6.2</h2>
<h3>Patch Changes</h3>
<ul>
<li>1175584: fix: validate input for <code>ArrayBuffer</code>
parsing</li>
<li>e46afa6: fix: validate input for typed arrays</li>
<li>1175584: fix: more helpful errors for inputs causing stack
overflows</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="fcf4e88275"><code>fcf4e88</code></a>
fix tests</li>
<li><a
href="1d8a5ea586"><code>1d8a5ea</code></a>
Version Packages (<a
href="https://redirect.github.com/sveltejs/devalue/issues/131">#131</a>)</li>
<li><a
href="11755849fa"><code>1175584</code></a>
Merge commit from fork</li>
<li><a
href="e46afa64dd"><code>e46afa6</code></a>
Merge commit from fork</li>
<li>See full diff in <a
href="https://github.com/sveltejs/devalue/compare/v5.6.1...v5.6.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=devalue&package-manager=npm_and_yarn&previous-version=5.6.1&new-version=5.6.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-15 22:13:42 +01:00
Guglielmo Colombo
bd4caa22a0
feat: implement GRPC server (#279)
# Description

This Pull Request implements server-side support for the gRPC transport
protocol.

**Schema and Generation**
The implementation is based on [A2A Proto Specification
v3.0.0](https://raw.githubusercontent.com/a2aproject/A2A/v0.3.0/specification/grpc/a2a.proto).

**Tooling**
ts-proto was adopted for generating TypeScript service definitions (with
buf), which will reuse the message types previously generated (this
requires a manual modification of the generated file).

**Limitations**
Due to the current dependency on Proto v3.0.0, the gRPC implementation
is missing some APIs already available for other transports, for example
the `getExtendedAuthenticatedAgentCard` method.
These missing endpoints will be implemented with future official
releases of proto specification.

**Entry Points**
A new dedicated entry point has been introduced to export the gRPC
server logic and @grpc/grpc-js and its related transport libraries have
been added as peer dependencies.

Fixes #275  🦕

Release-As: 0.3.9

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Ivan Shymko <ishymko@google.com>
Co-authored-by: Ivan Shymko <vana.shimko@gmail.com>
2026-01-15 13:56:11 +01:00
Agent2Agent (A2A) Bot
7f8bb6bb1d
chore(main): release 0.3.8 (#283)
🤖 I have created a release *beep* *boop*
---


## [0.3.8](https://github.com/a2aproject/a2a-js/compare/v0.3.7...v0.3.8)
(2026-01-15)


### ⚠ BREAKING CHANGES

* use ProtoJSON for REST transport
([#292](https://github.com/a2aproject/a2a-js/issues/292))

### Features

* use case-insensitive transport protocol name comparison in
ClientFactory
([5246067](5246067f5f))


### Bug Fixes

* add typesVersions to support legacy module resolution
([#288](https://github.com/a2aproject/a2a-js/issues/288))
([6499e29](6499e290f6))
* use ProtoJSON for REST transport
([#292](https://github.com/a2aproject/a2a-js/issues/292))
([d2efc4c](d2efc4cf34))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2026-01-15 10:32:57 +01:00
Aryan Raj
6499e290f6
fix: add typesVersions to support legacy module resolution (#288)
# Description

Thank you for opening a Pull Request!
Before submitting your PR, there are a few things you can do to make
sure it goes smoothly:

- [x] Follow the [`CONTRIBUTING`
Guide](https://github.com/google-a2a/a2a-js/blob/main/CONTRIBUTING.md).
- [x] Make your Pull Request title in the
<https://www.conventionalcommits.org/> specification.
- Important Prefixes for
[release-please](https://github.com/googleapis/release-please):
- `fix:` which represents bug fixes, and correlates to a
[SemVer](https://semver.org/) patch.
- `feat:` represents a new feature, and correlates to a SemVer minor.
- `feat!:`, or `fix!:`, `refactor!:`, etc., which represent a breaking
change (indicated by the `!`) and will result in a SemVer major.
- [x] Ensure the tests and linter pass
- [x] Appropriate docs were updated (if necessary)

Fixes #287  🦕
2026-01-15 08:47:49 +01:00
Ivan Shymko
45c0342f1d
docs: use artifact to deliver execution result in sample-agent (#297)
# Description

According to the
https://github.com/a2aproject/A2A/issues/822#issuecomment-3084892313 do
not use `TaskStatusUpdateEvent`'s to deliver agent execution results,
use `TaskArtifactUpdateEvent`'s instead:

<img width="1343" height="448" alt="Screenshot 2026-01-14 at 15 42 59"
src="https://github.com/user-attachments/assets/fc259512-3016-4a1d-84cc-d8e89b35669f"
/>
2026-01-14 16:29:29 +01:00
Ivan Shymko
78cbd44b24
ci: run TCK capabilities tests for REST (#296)
# Description

Bring back TCK capabilities tests for REST and use
[0.3.0.beta3](https://github.com/a2aproject/a2a-tck/releases/tag/0.3.0.beta3)
tag, both work now after #292.
2026-01-14 09:48:43 +01:00
Guglielmo Colombo
d2efc4cf34
fix!: use ProtoJSON for REST transport (#292)
# Description

This PR resolves an incompatibility in the payload shape between the
REST Transport handlers and other A2A SDKs.

In this version, the transmitted payload now aligns with the field names
and structure defined in the proto file. A new `a2a.ts` file has been
introduced to represent the proto types, including their corresponding
`fromJson` and `toJson` conversion functions.

**Technically this is a breaking change, however current implementation
isn't compatible with other official SDKs, so fixing in-place.** Current
situation with JSON format for HTTP+JSON is complicated as there is no
explicit specification in 0.3, see
[here](https://github.com/a2aproject/a2a-js/issues/291#issuecomment-3719125908)
for more details.

Fixes #291  🦕

Release-As: 0.3.8

---------

Co-authored-by: Ivan Shymko <ishymko@google.com>
2026-01-13 17:08:15 +00:00
Ivan Shymko
20c16fcc01
docs: add AGENTS.md and .gemini/settings.json (#295)
# Description

Make the repo a bit more LLM-friendly.

1. Generate `AGENTS.md` via Gemini CLI `/init` (reviewed and edited
manually afterwards).
2. Allowlist safe lint and test commands via `.gemini/settings.json`.

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-01-13 11:04:36 +01:00
Ivan Shymko
eb604acc79
docs: support A2A agent on Agent Engine in samples/cli (#293)
# Description

Add `--agent-engine` parameter to the test CLI to add ADC authentication
used for Agent Engine deployed instances. It is required for both agent
card fetching (which requires auth as there is no public well-known
endpoint exposed) and other client calls.

Adding this for proper E2E manual testing of the mentioned issue and the
fix.

With current REST implementation it's not going to work with Agent
Engine instances (as per #291), this PR was tested on a WIP fix #292
against a "hello world" agent from
[here](b814aabd12/vertexai/preview/reasoning_engines/templates/a2a.py (L114))
deployed on Agent Engine:

```
npm run a2a:cli -- https://us-central1-aiplatform.googleapis.com/v1beta1/projects/XXX/locations/us-central1/reasoningEngines/XXX/ --agent-engine

> a2a:cli
> tsx cli.ts https://us-central1-aiplatform.googleapis.com/v1beta1/projects/XXX/locations/us-central1/reasoningEngines/XXX/ --agent-engine

A2A Terminal Client
Agent Base URL: https://us-central1-aiplatform.googleapis.com/v1beta1/projects/XXX/locations/us-central1/reasoningEngines/XXX/
Attempting to fetch agent card from agent at: https://us-central1-aiplatform.googleapis.com/v1beta1/projects/XXX/locations/us-central1/reasoningEngines/XXX/
✓ Agent Card Found:
  Name:        Hello World Agent
  Description: Just a hello world agent
  Version:     1.0.0
  Streaming:   Not Supported (or not specified)
No active task or context initially. Use '/new' to start a fresh session or send a message.
Enter messages, or use '/new' to start a new session. '/exit' to quit.
Hello World Agent > You: test
Sending message...

Hello World Agent [11:24:36 AM]: ✉️ Message Stream Event:
  Part 1: 📝 Text: Hello World
--- End of response stream for this input ---
Hello World Agent > You: 
```


Re #291, #292
2026-01-12 14:02:42 +01:00
dependabot[bot]
aaea98e1eb
chore(deps): bump qs, body-parser and express in /src/samples (#285)
Bumps [qs](https://github.com/ljharb/qs),
[body-parser](https://github.com/expressjs/body-parser) and
[express](https://github.com/expressjs/express). These dependencies
needed to be updated together.
Updates `qs` from 6.14.0 to 6.14.1
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ljharb/qs/blob/main/CHANGELOG.md">qs's
changelog</a>.</em></p>
<blockquote>
<h2><strong>6.14.1</strong></h2>
<ul>
<li>[Fix] ensure arrayLength applies to <code>[]</code> notation as
well</li>
<li>[Fix] <code>parse</code>: when a custom decoder returns
<code>null</code> for a key, ignore that key</li>
<li>[Refactor] <code>parse</code>: extract key segment splitting
helper</li>
<li>[meta] add threat model</li>
<li>[actions] add workflow permissions</li>
<li>[Tests] <code>stringify</code>: increase coverage</li>
<li>[Dev Deps] update <code>eslint</code>,
<code>@ljharb/eslint-config</code>, <code>npmignore</code>,
<code>es-value-fixtures</code>, <code>for-each</code>,
<code>object-inspect</code></li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="3fa11a5f64"><code>3fa11a5</code></a>
v6.14.1</li>
<li><a
href="a62670423c"><code>a626704</code></a>
[Dev Deps] update <code>npmignore</code></li>
<li><a
href="3086902ecf"><code>3086902</code></a>
[Fix] ensure arrayLength applies to <code>[]</code> notation as
well</li>
<li><a
href="fc7930e86c"><code>fc7930e</code></a>
[Dev Deps] update <code>eslint</code>,
<code>@ljharb/eslint-config</code></li>
<li><a
href="0b06aac566"><code>0b06aac</code></a>
[Dev Deps] update <code>@ljharb/eslint-config</code></li>
<li><a
href="64951f6200"><code>64951f6</code></a>
[Refactor] <code>parse</code>: extract key segment splitting helper</li>
<li><a
href="e1bd2599cd"><code>e1bd259</code></a>
[Dev Deps] update <code>@ljharb/eslint-config</code></li>
<li><a
href="f4b3d39709"><code>f4b3d39</code></a>
[eslint] add eslint 9 optional peer dep</li>
<li><a
href="6e94d9596c"><code>6e94d95</code></a>
[Dev Deps] update <code>eslint</code>,
<code>@ljharb/eslint-config</code>, <code>npmignore</code></li>
<li><a
href="973dc3c51c"><code>973dc3c</code></a>
[actions] add workflow permissions</li>
<li>Additional commits viewable in <a
href="https://github.com/ljharb/qs/compare/v6.14.0...v6.14.1">compare
view</a></li>
</ul>
</details>
<br />

Updates `body-parser` from 1.20.3 to 1.20.4
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/expressjs/body-parser/releases">body-parser's
releases</a>.</em></p>
<blockquote>
<h2>1.20.4</h2>
<h2>What's Changed</h2>
<ul>
<li>Remove redundant depth check by <a
href="https://github.com/blakeembrey"><code>@​blakeembrey</code></a> in
<a
href="https://redirect.github.com/expressjs/body-parser/pull/538">expressjs/body-parser#538</a></li>
<li>ci: add support for Node.js v23 by <a
href="https://github.com/Phillip9587"><code>@​Phillip9587</code></a> in
<a
href="https://redirect.github.com/expressjs/body-parser/pull/553">expressjs/body-parser#553</a></li>
<li>ci: restore CI for 1.x branch by <a
href="https://github.com/bjohansebas"><code>@​bjohansebas</code></a> in
<a
href="https://redirect.github.com/expressjs/body-parser/pull/665">expressjs/body-parser#665</a></li>
<li>deps: qs@^6.14.0 by <a
href="https://github.com/bjohansebas"><code>@​bjohansebas</code></a> in
<a
href="https://redirect.github.com/expressjs/body-parser/pull/664">expressjs/body-parser#664</a></li>
<li>deps: use tilde notation and update certain dependencies by <a
href="https://github.com/Phillip9587"><code>@​Phillip9587</code></a> in
<a
href="https://redirect.github.com/expressjs/body-parser/pull/668">expressjs/body-parser#668</a></li>
<li>chore: remove SECURITY.md by <a
href="https://github.com/Phillip9587"><code>@​Phillip9587</code></a> in
<a
href="https://redirect.github.com/expressjs/body-parser/pull/669">expressjs/body-parser#669</a></li>
<li>ci: add CodeQL (SAST) by <a
href="https://github.com/Phillip9587"><code>@​Phillip9587</code></a> in
<a
href="https://redirect.github.com/expressjs/body-parser/pull/670">expressjs/body-parser#670</a></li>
<li>Release: 1.20.4 by <a
href="https://github.com/UlisesGascon"><code>@​UlisesGascon</code></a>
in <a
href="https://redirect.github.com/expressjs/body-parser/pull/672">expressjs/body-parser#672</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/expressjs/body-parser/compare/1.20.3...1.20.4">https://github.com/expressjs/body-parser/compare/1.20.3...1.20.4</a></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/expressjs/body-parser/blob/master/HISTORY.md">body-parser's
changelog</a>.</em></p>
<blockquote>
<h1>1.20.4 / 2025-12-01</h1>
<ul>
<li>deps: qs@~6.14.0</li>
<li>deps: use tilde notation for dependencies</li>
<li>deps: http-errors@~2.0.1</li>
<li>deps: raw-body@~2.5.3</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="7db202cac8"><code>7db202c</code></a>
1.20.4 (<a
href="https://redirect.github.com/expressjs/body-parser/issues/672">#672</a>)</li>
<li><a
href="d8f8adb898"><code>d8f8adb</code></a>
ci: add CodeQL (SAST) (<a
href="https://redirect.github.com/expressjs/body-parser/issues/670">#670</a>)</li>
<li><a
href="6d133c19b3"><code>6d133c1</code></a>
chore: remove SECURITY.md (<a
href="https://redirect.github.com/expressjs/body-parser/issues/669">#669</a>)</li>
<li><a
href="fcd1535504"><code>fcd1535</code></a>
deps: use tilde notation and update certain dependencies (<a
href="https://redirect.github.com/expressjs/body-parser/issues/668">#668</a>)</li>
<li><a
href="ec5fa290d2"><code>ec5fa29</code></a>
deps: qs@~6.14.0 (<a
href="https://redirect.github.com/expressjs/body-parser/issues/664">#664</a>)</li>
<li><a
href="ffb95c12c7"><code>ffb95c1</code></a>
ci: restore CI for 1.x branch (<a
href="https://redirect.github.com/expressjs/body-parser/issues/665">#665</a>)</li>
<li><a
href="48a5f074a4"><code>48a5f07</code></a>
ci: add support for Node.js v23 (<a
href="https://redirect.github.com/expressjs/body-parser/issues/553">#553</a>)</li>
<li><a
href="f20f6adc71"><code>f20f6ad</code></a>
Remove redundant depth check (<a
href="https://redirect.github.com/expressjs/body-parser/issues/538">#538</a>)</li>
<li>See full diff in <a
href="https://github.com/expressjs/body-parser/compare/1.20.3...1.20.4">compare
view</a></li>
</ul>
</details>
<br />

Updates `express` from 4.21.2 to 4.22.1
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/expressjs/express/releases">express's
releases</a>.</em></p>
<blockquote>
<h2>v4.22.1</h2>
<h2>What's Changed</h2>
<blockquote>
<p>[!IMPORTANT]<br />
The prior release (4.22.0) included an erroneous breaking change related
to the extended query parser. There is no actual security vulnerability
associated with this behavior (CVE-2024-51999 has been rejected). The
change has been fully reverted in this release.</p>
</blockquote>
<ul>
<li>Release: 4.22.1 by <a
href="https://github.com/UlisesGascon"><code>@​UlisesGascon</code></a>
in <a
href="https://redirect.github.com/expressjs/express/pull/6934">expressjs/express#6934</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/expressjs/express/compare/4.22.0...v4.22.1">https://github.com/expressjs/express/compare/4.22.0...v4.22.1</a></p>
<h2>4.22.0</h2>
<h2>Important: Security</h2>
<ul>
<li>Security fix for <a
href="https://www.cve.org/CVERecord?id=CVE-2024-51999">CVE-2024-51999</a>
(<a
href="https://github.com/expressjs/express/security/advisories/GHSA-pj86-cfqh-vqx6">GHSA-pj86-cfqh-vqx6</a>)</li>
</ul>
<h2>What's Changed</h2>
<ul>
<li>Refactor: improve readability by <a
href="https://github.com/sazk07"><code>@​sazk07</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6190">expressjs/express#6190</a></li>
<li>ci: add support for Node.js@23.0 by <a
href="https://github.com/UlisesGascon"><code>@​UlisesGascon</code></a>
in <a
href="https://redirect.github.com/expressjs/express/pull/6080">expressjs/express#6080</a></li>
<li>Method functions with no path should error by <a
href="https://github.com/wesleytodd"><code>@​wesleytodd</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/5957">expressjs/express#5957</a></li>
<li>ci: updated github actions ci workflow by <a
href="https://github.com/Phillip9587"><code>@​Phillip9587</code></a> in
<a
href="https://redirect.github.com/expressjs/express/pull/6323">expressjs/express#6323</a></li>
<li>ci: reorder <code>npm i</code> steps to fix ci for older node
versions by <a
href="https://github.com/Phillip9587"><code>@​Phillip9587</code></a> in
<a
href="https://redirect.github.com/expressjs/express/pull/6336">expressjs/express#6336</a></li>
<li>Backport: ci: add node.js 24 to test matrix by <a
href="https://github.com/Phillip9587"><code>@​Phillip9587</code></a> in
<a
href="https://redirect.github.com/expressjs/express/pull/6506">expressjs/express#6506</a></li>
<li>chore(4.x): wider range for query test skip by <a
href="https://github.com/jonchurch"><code>@​jonchurch</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6513">expressjs/express#6513</a></li>
<li>use tilde notation for certain dependencies by <a
href="https://github.com/UlisesGascon"><code>@​UlisesGascon</code></a>
in <a
href="https://redirect.github.com/expressjs/express/pull/6905">expressjs/express#6905</a></li>
<li>deps: qs@6.14.0 by <a
href="https://github.com/UlisesGascon"><code>@​UlisesGascon</code></a>
in <a
href="https://redirect.github.com/expressjs/express/pull/6909">expressjs/express#6909</a></li>
<li>deps: use tilde notation for <code>qs</code> by <a
href="https://github.com/Phillip9587"><code>@​Phillip9587</code></a> in
<a
href="https://redirect.github.com/expressjs/express/pull/6919">expressjs/express#6919</a></li>
<li>Release: 4.22.0 by <a
href="https://github.com/UlisesGascon"><code>@​UlisesGascon</code></a>
in <a
href="https://redirect.github.com/expressjs/express/pull/6921">expressjs/express#6921</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/expressjs/express/compare/4.21.2...4.22.0">https://github.com/expressjs/express/compare/4.21.2...4.22.0</a></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/expressjs/express/blob/v4.22.1/History.md">express's
changelog</a>.</em></p>
<blockquote>
<h1>4.22.1 / 2025-12-01</h1>
<ul>
<li>Revert security fix for <a
href="https://www.cve.org/CVERecord?id=CVE-2024-51999">CVE-2024-51999</a>
(<a
href="https://github.com/expressjs/express/security/advisories/GHSA-pj86-cfqh-vqx6">GHSA-pj86-cfqh-vqx6</a>)</li>
</ul>
<h1>4.22.0 / 2025-12-01</h1>
<ul>
<li>Security fix for <a
href="https://www.cve.org/CVERecord?id=CVE-2024-51999">CVE-2024-51999</a>
(<a
href="https://github.com/expressjs/express/security/advisories/GHSA-pj86-cfqh-vqx6">GHSA-pj86-cfqh-vqx6</a>)</li>
<li>deps: use tilde notation for dependencies</li>
<li>deps: qs@6.14.0</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="12fae14531"><code>12fae14</code></a>
4.22.1</li>
<li><a
href="5ddf311af3"><code>5ddf311</code></a>
Revert &quot;sec: security patch for CVE-2024-51999&quot;</li>
<li><a
href="49744abd11"><code>49744ab</code></a>
4.22.0 (<a
href="https://redirect.github.com/expressjs/express/issues/6921">#6921</a>)</li>
<li><a
href="6e97452f60"><code>6e97452</code></a>
sec: security patch for CVE-2024-51999</li>
<li><a
href="6a23d34d65"><code>6a23d34</code></a>
deps: use tilde notation for <code>qs</code> (<a
href="https://redirect.github.com/expressjs/express/issues/6919">#6919</a>)</li>
<li><a
href="8c12cdf93b"><code>8c12cdf</code></a>
deps: qs@6.14.0 (<a
href="https://redirect.github.com/expressjs/express/issues/6909">#6909</a>)</li>
<li><a
href="7fea74fcf0"><code>7fea74f</code></a>
deps: use tilde notation for certain dependencies (<a
href="https://redirect.github.com/expressjs/express/issues/6905">#6905</a>)</li>
<li><a
href="dac7a0475a"><code>dac7a04</code></a>
chore: wider range for query test skip (<a
href="https://redirect.github.com/expressjs/express/issues/6513">#6513</a>)</li>
<li><a
href="997919b488"><code>997919b</code></a>
ci: add node.js 24 to test matrix (<a
href="https://redirect.github.com/expressjs/express/issues/6506">#6506</a>)</li>
<li><a
href="36fb59c6c7"><code>36fb59c</code></a>
fix(ci): reorder <code>npm i</code> steps to fix ci for older node
versions (<a
href="https://redirect.github.com/expressjs/express/issues/6336">#6336</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/expressjs/express/compare/4.21.2...v4.22.1">compare
view</a></li>
</ul>
</details>
<br />


Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Co-authored-by: Ivan Shymko <ishymko@google.com>
2026-01-07 11:12:15 +01:00
dependabot[bot]
ebcf162167
chore(deps): bump qs from 6.14.0 to 6.14.1 (#286)
Bumps [qs](https://github.com/ljharb/qs) from 6.14.0 to 6.14.1.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ljharb/qs/blob/main/CHANGELOG.md">qs's
changelog</a>.</em></p>
<blockquote>
<h2><strong>6.14.1</strong></h2>
<ul>
<li>[Fix] ensure arrayLength applies to <code>[]</code> notation as
well</li>
<li>[Fix] <code>parse</code>: when a custom decoder returns
<code>null</code> for a key, ignore that key</li>
<li>[Refactor] <code>parse</code>: extract key segment splitting
helper</li>
<li>[meta] add threat model</li>
<li>[actions] add workflow permissions</li>
<li>[Tests] <code>stringify</code>: increase coverage</li>
<li>[Dev Deps] update <code>eslint</code>,
<code>@ljharb/eslint-config</code>, <code>npmignore</code>,
<code>es-value-fixtures</code>, <code>for-each</code>,
<code>object-inspect</code></li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="3fa11a5f64"><code>3fa11a5</code></a>
v6.14.1</li>
<li><a
href="a62670423c"><code>a626704</code></a>
[Dev Deps] update <code>npmignore</code></li>
<li><a
href="3086902ecf"><code>3086902</code></a>
[Fix] ensure arrayLength applies to <code>[]</code> notation as
well</li>
<li><a
href="fc7930e86c"><code>fc7930e</code></a>
[Dev Deps] update <code>eslint</code>,
<code>@ljharb/eslint-config</code></li>
<li><a
href="0b06aac566"><code>0b06aac</code></a>
[Dev Deps] update <code>@ljharb/eslint-config</code></li>
<li><a
href="64951f6200"><code>64951f6</code></a>
[Refactor] <code>parse</code>: extract key segment splitting helper</li>
<li><a
href="e1bd2599cd"><code>e1bd259</code></a>
[Dev Deps] update <code>@ljharb/eslint-config</code></li>
<li><a
href="f4b3d39709"><code>f4b3d39</code></a>
[eslint] add eslint 9 optional peer dep</li>
<li><a
href="6e94d9596c"><code>6e94d95</code></a>
[Dev Deps] update <code>eslint</code>,
<code>@ljharb/eslint-config</code>, <code>npmignore</code></li>
<li><a
href="973dc3c51c"><code>973dc3c</code></a>
[actions] add workflow permissions</li>
<li>Additional commits viewable in <a
href="https://github.com/ljharb/qs/compare/v6.14.0...v6.14.1">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=qs&package-manager=npm_and_yarn&previous-version=6.14.0&new-version=6.14.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/a2aproject/a2a-js/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-07 09:54:56 +01:00
tchapacan
8676abf964
test: add tests for RestTransportHandler (#280)
# Description

Thank you for opening a Pull Request!
Before submitting your PR, there are a few things you can do to make
sure it goes smoothly:

- [x] Follow the [`CONTRIBUTING`
Guide](https://github.com/google-a2a/a2a-js/blob/main/CONTRIBUTING.md).
- [x] Make your Pull Request title in the
<https://www.conventionalcommits.org/> specification.
- Important Prefixes for
[release-please](https://github.com/googleapis/release-please):
- `fix:` which represents bug fixes, and correlates to a
[SemVer](https://semver.org/) patch.
- `feat:` represents a new feature, and correlates to a SemVer minor.
- `feat!:`, or `fix!:`, `refactor!:`, etc., which represent a breaking
change (indicated by the `!`) and will result in a SemVer major.
- [x] Ensure the tests and linter pass
- [ ] Appropriate docs were updated (if necessary)

Fixes #278 🦕

Co-authored-by: Ivan Shymko <ishymko@google.com>
2025-12-23 09:19:41 +01:00
tchapacan
5246067f5f
feat: use case-insensitive transport protocol name comparison in ClientFactory (#281)
# Description

Thank you for opening a Pull Request!
Before submitting your PR, there are a few things you can do to make
sure it goes smoothly:

- [x] Follow the [`CONTRIBUTING`
Guide](https://github.com/google-a2a/a2a-js/blob/main/CONTRIBUTING.md).
- [x] Make your Pull Request title in the
<https://www.conventionalcommits.org/> specification.
- Important Prefixes for
[release-please](https://github.com/googleapis/release-please):
- `fix:` which represents bug fixes, and correlates to a
[SemVer](https://semver.org/) patch.
- `feat:` represents a new feature, and correlates to a SemVer minor.
- `feat!:`, or `fix!:`, `refactor!:`, etc., which represent a breaking
change (indicated by the `!`) and will result in a SemVer major.
- [x] Ensure the tests and linter pass
- [ ] Appropriate docs were updated (if necessary)

Fixes #264 🦕

Release-As: 0.3.8

---------

Co-authored-by: Ivan Shimko <vana.shimko@gmail.com>
2025-12-23 08:22:02 +01:00
Ivan Shymko
d0e0485f38
ci: optimize workflows with path filters for PRs (#282)
# Description

Do not run some workflows on PRs. Everything is still running on the
main branch in case PR run missed something.
2025-12-22 13:13:31 +01:00
Ivan Shymko
c9eb9bac7e
ci: per-file coverage experiment (#276)
# Description

1. Post per-file coverage deltas.
2. Use only statements coverage for simplicity.

# Examples

Tested in fork https://github.com/ishymko/a2a-js/pull/3.

<img width="300" alt="image"
src="https://github.com/user-attachments/assets/54cc3f7b-23a5-4d35-954d-2157171baf18"
/>
<img width="300" alt="image"
src="https://github.com/user-attachments/assets/3c97d78f-f918-47d9-b01d-0c6094b1e7cd"
/>
<img width="300" alt="image"
src="https://github.com/user-attachments/assets/aa3b1af3-d769-4dcd-9514-1cbdffd08e2a"
/>

Re #192
2025-12-19 10:46:12 +01:00
Ivan Shymko
80d559afb6
docs: document supported transports for 0.3.7 (#273)
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-12-17 15:09:06 +00:00
Agent2Agent (A2A) Bot
5046f3a546
chore(main): release 0.3.7 (#260)
🤖 I have created a release *beep* *boop*
---


## [0.3.7](https://github.com/a2aproject/a2a-js/compare/v0.3.6...v0.3.7)
(2025-12-17)


### Features

* add rest client
([#258](https://github.com/a2aproject/a2a-js/issues/258))
([96be3a1](96be3a1d6c))
* remove EventEmitter dependency to support Edge Runtime
([#219](https://github.com/a2aproject/a2a-js/issues/219))
([6c76fef](6c76fef264)),
closes [#218](https://github.com/a2aproject/a2a-js/issues/218)


### Bug Fixes

* export transport agnostic errors from client
([#272](https://github.com/a2aproject/a2a-js/issues/272))
([23cd42e](23cd42e83d))
* pass ServerCallContext to getAuthenticatedExtendedAgentCard for REST
([#274](https://github.com/a2aproject/a2a-js/issues/274))
([89b141b](89b141b5ba)),
closes [#137](https://github.com/a2aproject/a2a-js/issues/137)

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2025-12-17 16:01:41 +01:00
Ivan Shymko
89b141b5ba
fix: pass ServerCallContext to getAuthenticatedExtendedAgentCard for REST (#274)
# Description

Follow-up for #142: authenticated agent card logic relies on context to
determine authentication status.

`src/server/transports/rest/rest_transport_handler.ts` is not exported,
so adding a required parameter is fine.

Re #137
2025-12-17 14:53:43 +00:00
Ivan Shymko
23cd42e83d
fix: export transport agnostic errors from client (#272)
# Description

Due to a name conflict with legacy JSON-RPC types reexported from
`src/index.ts` below errors are going to be exported via
`src/client/index.ts` to allow usage from external transport
implementations.

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-12-17 15:34:30 +01:00
Ivan Shymko
98b8908788
test: run tests on Edge environment (#271)
# Description

Implemented according to
https://github.com/a2aproject/a2a-js/issues/237#issuecomment-3654100699.

1. Downgrade to vitest 3 to enable
[`@cloudflare/vitest-pool-workers`](https://developers.cloudflare.com/workers/testing/vitest-integration/).
2. Disable tests which have Express dependencies.
3. Remove listener errors tests from event bus: even on Node.js
EventEmitter erroring out inside listener results in uncaught exception
which stops the process by default, with this behavior running (or not
running) other listeners makes no difference. The workaround in test is
Node.js specific.
4. Explicitly define inclusions and exclusions for coverage, as this
behavior changed after downgrade.
5. Update static esbuild test to run on server entry point as well.

Fixes #237, re #218
2025-12-17 14:27:18 +01:00
Ivan Shymko
2829681182
test: remove sinon dependency and use vitest for mocking (#261)
# Description

Follow-up for #254.

Also related to
https://github.com/a2aproject/a2a-js/issues/237#issuecomment-3654100699:
an attempt to run current tests on `@cloudflare/vitest-pool-workers`
fails with `Disallowed operation called within global scope` coming from
`sinon`. A quick try to replace one file with pure vitest worked, even
if there're going to be other blockers for running proper Edge runtime
tests this change removes extra dependency.

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-12-17 11:14:24 +00:00
tchapacan
96be3a1d6c
feat: add rest client (#258)
# Description

Following continuation of this PR
https://github.com/a2aproject/a2a-js/pull/142, this one is related to
the implementation of the REST mode support for the client part of
**a2a-js** sdk. Following the same pattern as other sdk (agnostic
transport).

----

Thank you for opening a Pull Request!
Before submitting your PR, there are a few things you can do to make
sure it goes smoothly:

- [x] Follow the [`CONTRIBUTING`
Guide](https://github.com/google-a2a/a2a-js/blob/main/CONTRIBUTING.md).
- [x] Make your Pull Request title in the
<https://www.conventionalcommits.org/> specification.
- Important Prefixes for
[release-please](https://github.com/googleapis/release-please):
- `fix:` which represents bug fixes, and correlates to a
[SemVer](https://semver.org/) patch.
- `feat:` represents a new feature, and correlates to a SemVer minor.
- `feat!:`, or `fix!:`, `refactor!:`, etc., which represent a breaking
change (indicated by the `!`) and will result in a SemVer major.
- [x] Ensure the tests and linter pass
- [ ] Appropriate docs were updated (if necessary)

Fixes #137, fixes #175 🦕

Release-As: 0.3.7

Co-authored-by: Ivan Shymko <ishymko@google.com>
2025-12-17 11:38:44 +01:00
Ivan Shymko
cda0f5669c
ci: fix coverage comment workflow (#270)
# Description

Original approach from #262 isn't going to work for PRs from forks, as
such actions can't have write access to the upstream repo by default and
granting this access is not secure.

Following the approach with a dedicated
[`workflow_run`](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#workflow_run)
triggered workflow which is executed in a secure context.

Reference:
https://securitylab.github.com/resources/github-actions-preventing-pwn-requests/.

Tested in a fork: https://github.com/ishymko/a2a-js/pull/2.

Re #192
2025-12-17 11:26:29 +01:00
89 changed files with 26003 additions and 5237 deletions

85
.betterer.results Normal file
View File

@ -0,0 +1,85 @@
// BETTERER RESULTS V2.
//
// If this file contains merge conflicts, use `betterer merge` to automatically resolve them:
// https://phenomnomnominal.github.io/betterer/docs/results-file/#merge
//
exports[`TypeScript Strict Mode`] = {
value: `{
"src/client/client.ts:1182451551": [
[444, 45, 6, "tsc: Argument of type \'TParams | undefined\' is not assignable to parameter of type \'TParams\'.\\n \'TParams | undefined\' is assignable to the constraint of type \'TParams\', but \'TParams\' could be instantiated with a different subtype of constraint \'JsonRpcParams\'.\\n Type \'undefined\' is not assignable to type \'TParams\'.\\n \'undefined\' is assignable to the constraint of type \'TParams\', but \'TParams\' could be instantiated with a different subtype of constraint \'JsonRpcParams\'.", "1898504825"],
[474, 4, 6, "tsc: Type \'undefined\' is not assignable to type \'JSONRPCErrorResponse\'.", "2123913871"]
],
"src/client/multitransport-client.ts:1457951880": [
[82, 24, 44, "tsc: Type \'Promise<AgentCard>\' is not assignable to type \'Promise<never>\'.\\n Type \'AgentCard\' is not assignable to type \'never\'.", "1356744557"],
[101, 6, 47, "tsc: Argument of type \'(params: MessageSendParams, options?: RequestOptions | undefined) => Promise<SendMessageResult>\' is not assignable to parameter of type \'(params: MessageSendParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<SendMessageResult>\' is not assignable to type \'Promise<never>\'.\\n Type \'SendMessageResult\' is not assignable to type \'never\'.\\n Type \'Message\' is not assignable to type \'never\'.", "2571452626"],
[178, 6, 65, "tsc: Argument of type \'(params: TaskPushNotificationConfig, options?: RequestOptions | undefined) => Promise<TaskPushNotificationConfig>\' is not assignable to parameter of type \'(params: TaskPushNotificationConfig, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<TaskPushNotificationConfig>\' is not assignable to type \'Promise<never>\'.\\n Type \'TaskPushNotificationConfig\' is not assignable to type \'never\'.", "2789685747"],
[197, 6, 65, "tsc: Argument of type \'(params: GetTaskPushNotificationConfigParams, options?: RequestOptions | undefined) => Promise<TaskPushNotificationConfig>\' is not assignable to parameter of type \'(params: TaskIdParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<TaskPushNotificationConfig>\' is not assignable to type \'Promise<never>\'.\\n Type \'TaskPushNotificationConfig\' is not assignable to type \'never\'.", "1581152103"],
[216, 6, 66, "tsc: Argument of type \'(params: ListTaskPushNotificationConfigParams, options?: RequestOptions | undefined) => Promise<TaskPushNotificationConfig[]>\' is not assignable to parameter of type \'(params: ListTaskPushNotificationConfigParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<TaskPushNotificationConfig[]>\' is not assignable to type \'Promise<never>\'.\\n Type \'TaskPushNotificationConfig[]\' is not assignable to type \'never\'.", "4161961235"],
[230, 6, 68, "tsc: Argument of type \'(params: DeleteTaskPushNotificationConfigParams, options?: RequestOptions | undefined) => Promise<void>\' is not assignable to parameter of type \'(params: DeleteTaskPushNotificationConfigParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<void>\' is not assignable to type \'Promise<never>\'.\\n Type \'void\' is not assignable to type \'never\'.", "1244975368"],
[241, 6, 43, "tsc: Argument of type \'(params: TaskQueryParams, options?: RequestOptions | undefined) => Promise<Task>\' is not assignable to parameter of type \'(params: TaskQueryParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<Task>\' is not assignable to type \'Promise<never>\'.\\n Type \'Task\' is not assignable to type \'never\'.", "2875666270"],
[253, 6, 46, "tsc: Argument of type \'(params: TaskIdParams, options?: RequestOptions | undefined) => Promise<Task>\' is not assignable to parameter of type \'(params: TaskIdParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<Task>\' is not assignable to type \'Promise<never>\'.\\n Type \'Task\' is not assignable to type \'never\'.", "588661070"]
],
"src/client/transports/json_rpc_transport.ts:956778244": [
[54, 6, 9, "tsc: Type \'undefined\' does not satisfy the constraint \'{ [key: string]: any; }\'.", "2620553983"],
[169, 38, 16, "tsc: Type \'TExtensionParams\' does not satisfy the constraint \'{ [key: string]: any; }\'.", "3740514676"]
],
"src/server/events/execution_event_bus.ts:341476271": [
[248, 15, 4, "tsc: Expected 2 arguments, but got 1.", "2087764327"],
[271, 15, 4, "tsc: Expected 2 arguments, but got 1.", "2087764327"]
],
"src/server/express/rest_handler.ts:2436698925": [
[204, 50, 17, "tsc: Argument of type \'unknown\' is not assignable to parameter of type \'Message | Task | TaskArtifactUpdateEvent | TaskStatusUpdateEvent\'.", "3749434707"]
],
"src/server/request_handler/default_request_handler.ts:1208203039": [
[433, 22, 23, "tsc: Type \'Message1 | Message2 | undefined\' is not assignable to type \'Message1\'.\\n Type \'undefined\' is not assignable to type \'Message1\'.", "1479072653"],
[433, 47, 19, "tsc: Type \'Message2 | undefined\' is not assignable to type \'Message1\'.\\n Type \'undefined\' is not assignable to type \'Message1\'.", "2682097303"],
[619, 6, 6, "tsc: Type \'string | undefined\' is not assignable to type \'string\'.\\n Type \'undefined\' is not assignable to type \'string\'.", "1741934565"]
],
"src/server/transports/jsonrpc/jsonrpc_transport_handler.ts:3071717608": [
[55, 12, 10, "tsc: Variable \'rpcRequest\' is used before being assigned.", "3927050741"]
],
"src/types/converters/from_proto.ts:3167572508": [
[84, 6, 22, "tsc: Type \'PushNotificationConfig | undefined\' is not assignable to type \'PushNotificationConfig1\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationConfig1\'.", "2368778428"],
[138, 63, 30, "tsc: Argument of type \'PushNotificationConfig | undefined\' is not assignable to parameter of type \'PushNotificationConfig\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationConfig\'.", "4185699816"],
[153, 67, 21, "tsc: Argument of type \'AuthenticationInfo | undefined\' is not assignable to parameter of type \'AuthenticationInfo\'.\\n Type \'undefined\' is not assignable to type \'AuthenticationInfo\'.", "243589825"],
[203, 8, 4, "tsc: Type \'undefined | { [key: string]: any; }\' is not assignable to type \'{ [k: string]: unknown; }\'.\\n Type \'undefined\' is not assignable to type \'{ [k: string]: unknown; }\'.", "2087377941"],
[211, 6, 7, "tsc: Type \'Message | undefined\' is not assignable to type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "1236122734"],
[211, 33, 15, "tsc: Argument of type \'Message | undefined\' is not assignable to parameter of type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "1725852363"],
[212, 56, 21, "tsc: Argument of type \'SendMessageConfiguration | undefined\' is not assignable to parameter of type \'SendMessageConfiguration\'.\\n Type \'undefined\' is not assignable to type \'SendMessageConfiguration\'.", "2141283338"],
[221, 6, 6, "tsc: Type \'Message | undefined\' is not assignable to type \'Message | Task\'.\\n Type \'undefined\' is not assignable to type \'Message | Task\'.", "2123913871"],
[230, 35, 11, "tsc: Argument of type \'TaskStatus | undefined\' is not assignable to parameter of type \'TaskStatus\'.\\n Type \'undefined\' is not assignable to type \'TaskStatus\'.", "3290243250"],
[233, 6, 7, "tsc: Type \'(Message | undefined)[]\' is not assignable to type \'Message1[]\'.\\n Type \'Message | undefined\' is not assignable to type \'Message1\'.\\n Type \'undefined\' is not assignable to type \'Message1\'.", "502375463"],
[240, 33, 13, "tsc: Argument of type \'Message | undefined\' is not assignable to parameter of type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "586067534"],
[286, 6, 22, "tsc: Type \'PushNotificationConfig | undefined\' is not assignable to type \'PushNotificationConfig1\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationConfig1\'.", "2368778428"],
[286, 63, 30, "tsc: Argument of type \'PushNotificationConfig | undefined\' is not assignable to parameter of type \'PushNotificationConfig\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationConfig\'.", "1238494243"],
[389, 38, 34, "tsc: Argument of type \'OAuthFlows | undefined\' is not assignable to parameter of type \'OAuthFlows\'.\\n Type \'undefined\' is not assignable to type \'OAuthFlows\'.", "2386187236"],
[468, 35, 12, "tsc: Argument of type \'TaskStatus | undefined\' is not assignable to parameter of type \'TaskStatus\'.\\n Type \'undefined\' is not assignable to type \'TaskStatus\'.", "3657456819"],
[479, 35, 14, "tsc: Argument of type \'Artifact | undefined\' is not assignable to parameter of type \'Artifact\'.\\n Type \'undefined\' is not assignable to type \'Artifact\'.", "3619116505"],
[491, 8, 6, "tsc: Type \'Message | undefined\' is not assignable to type \'Message | Task | TaskArtifactUpdateEvent | TaskStatusUpdateEvent\'.\\n Type \'undefined\' is not assignable to type \'Message | Task | TaskArtifactUpdateEvent | TaskStatusUpdateEvent\'.", "2123913871"]
],
"src/types/converters/to_proto.ts:3424105456": [
[52, 38, 18, "tsc: Argument of type \'AgentProvider | undefined\' is not assignable to parameter of type \'AgentProvider\'.\\n Type \'undefined\' is not assignable to type \'AgentProvider\'.", "1428962279"],
[68, 6, 33, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "212802179"],
[223, 6, 6, "tsc: Type \'undefined\' is not assignable to type \'AgentProvider\'.", "2123913871"],
[233, 6, 9, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "4113723737"],
[234, 6, 17, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "4249068261"],
[263, 58, 31, "tsc: Argument of type \'string | undefined\' is not assignable to parameter of type \'string\'.\\n Type \'undefined\' is not assignable to type \'string\'.", "113348213"],
[303, 6, 8, "tsc: Type \'string | undefined\' is not assignable to type \'string\'.\\n Type \'undefined\' is not assignable to type \'string\'.", "2373810498"],
[309, 6, 6, "tsc: Type \'undefined\' is not assignable to type \'PushNotificationConfig\'.", "2123913871"],
[316, 65, 21, "tsc: Argument of type \'PushNotificationAuthenticationInfo | undefined\' is not assignable to parameter of type \'PushNotificationAuthenticationInfo\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationAuthenticationInfo\'.", "243589825"],
[339, 10, 5, "tsc: Type \'Message | undefined\' is not assignable to type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "189936718"],
[384, 6, 6, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "1326815083"],
[385, 6, 9, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "11251860"],
[389, 64, 19, "tsc: Function lacks ending return statement and return type does not include \'undefined\'.", "2245381585"],
[394, 10, 5, "tsc: Type \'Message | undefined\' is not assignable to type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "189936718"],
[440, 6, 7, "tsc: Type \'(Message | undefined)[]\' is not assignable to type \'Message[]\'.\\n Type \'Message | undefined\' is not assignable to type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "502375463"],
[448, 30, 14, "tsc: Argument of type \'Message2 | undefined\' is not assignable to parameter of type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "3366941076"],
[501, 10, 8, "tsc: Type \'string | undefined\' is not assignable to type \'string\'.\\n Type \'undefined\' is not assignable to type \'string\'.", "3750463409"],
[506, 10, 8, "tsc: Type \'string | undefined\' is not assignable to type \'string\'.\\n Type \'undefined\' is not assignable to type \'string\'.", "3750463409"],
[527, 43, 20, "tsc: Argument of type \'MessageSendConfiguration | undefined\' is not assignable to parameter of type \'MessageSendConfiguration\'.\\n Type \'undefined\' is not assignable to type \'MessageSendConfiguration\'.", "2639404487"],
[534, 6, 6, "tsc: Type \'undefined\' is not assignable to type \'SendMessageConfiguration\'.", "2123913871"],
[538, 6, 8, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "3894148428"],
[540, 55, 36, "tsc: Argument of type \'PushNotificationConfig | undefined\' is not assignable to parameter of type \'PushNotificationConfig\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationConfig\'.", "1308984194"]
]
}`
};

8
.betterer.ts Normal file
View File

@ -0,0 +1,8 @@
import { typescript } from '@betterer/typescript';
export default {
'TypeScript Strict Mode': () =>
typescript('./tsconfig.json', {
strict: true,
}).include('./src/**/*.ts', './tck/**/*.ts'),
};

15
.gemini/settings.json Normal file
View File

@ -0,0 +1,15 @@
{
"tools": {
"allowed": [
"run_shell_command(npm run build)",
"run_shell_command(npm test)",
"run_shell_command(npm run test)",
"run_shell_command(npm run test:edge)",
"run_shell_command(npm run test-build)",
"run_shell_command(npm run coverage)",
"run_shell_command(npm run lint)",
"run_shell_command(npm run lint:ci)",
"run_shell_command(npm run format:readme)"
]
}
}

View File

@ -1,4 +1,4 @@
# Ensures no accidential Node.js API usage in browser-compatible entrypoints.
# Ensures no accidential Node.js API usage in browser and Edge compatible entrypoints.
name: Run Build Tests
@ -7,6 +7,11 @@ on:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
paths-ignore:
- '**.md'
- 'LICENSE'
- '.github/CODEOWNERS'
- 'test/**'
jobs:
test:
@ -22,4 +27,4 @@ jobs:
cache: 'npm'
- run: npm ci
- run: npm run build
- run: npm run test-build:browser
- run: npm run test-build

164
.github/workflows/coverage-comment.yml vendored Normal file
View File

@ -0,0 +1,164 @@
name: Post Coverage Comment
on:
workflow_run:
workflows: ["Run Unit Tests"]
types:
- completed
permissions:
pull-requests: write
actions: read
jobs:
comment:
runs-on: ubuntu-latest
if: >
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion == 'success'
steps:
- name: Download Coverage Artifacts
uses: actions/download-artifact@v4
with:
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ secrets.GITHUB_TOKEN }}
name: coverage-data
- name: Upload Coverage Report
id: upload-report
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: coverage/
retention-days: 14
- name: Post Comment
uses: actions/github-script@v6
env:
ARTIFACT_URL: ${{ steps.upload-report.outputs.artifact-url }}
with:
script: |
const fs = require('fs');
const { owner, repo } = context.repo;
const headSha = context.payload.workflow_run.head_commit.id;
const loadSummary = (path) => {
try {
return JSON.parse(fs.readFileSync(path, 'utf8'));
} catch (e) {
console.log(`Could not read ${path}: ${e}`);
return null;
}
};
const baseSummary = loadSummary('./coverage-base-summary.json');
const prSummary = loadSummary('./coverage-pr-summary.json');
if (!baseSummary || !prSummary) {
console.log("Missing coverage data, skipping comment.");
return;
}
let markdown = `### 🧪 Code Coverage\n\n`;
markdown += `[⬇️ **Download Full Report**](${process.env.ARTIFACT_URL})\n\n`;
const metric = 'statements';
const getPct = (summaryItem, m) => summaryItem && summaryItem[m] ? summaryItem[m].pct : 0;
const formatDiff = (oldPct, newPct) => {
const diff = (newPct - oldPct).toFixed(2);
let icon = '';
if (diff > 0) icon = '🟢';
else if (diff < 0) icon = '🔴';
else icon = '⚪️';
const diffStr = diff > 0 ? `+${diff}%` : `${diff}%`;
return `${icon} ${diffStr}`;
};
const fileUrl = (path) => `https://github.com/${owner}/${repo}/blob/${headSha}/${path}`;
const allFiles = new Set([...Object.keys(baseSummary), ...Object.keys(prSummary)]);
allFiles.delete('total');
const workspacePath = process.env.GITHUB_WORKSPACE ? process.env.GITHUB_WORKSPACE + '/' : '';
let changedRows = [];
let newRows = [];
for (const file of allFiles) {
const baseFile = baseSummary[file];
const prFile = prSummary[file];
if (!prFile) continue;
const oldPct = getPct(baseFile, metric);
const newPct = getPct(prFile, metric);
const relativeFilePath = file.replace(workspacePath, '');
const linkedPath = `[${relativeFilePath}](${fileUrl(relativeFilePath)})`;
if (!baseFile && prFile) {
newRows.push(`| ${linkedPath} (**new**) | — | ${newPct}% | — |\n`);
} else if (oldPct !== newPct) {
changedRows.push(`| ${linkedPath} | ${oldPct}% | ${newPct}% | ${formatDiff(oldPct, newPct)} |\n`);
}
}
if (changedRows.length === 0 && newRows.length === 0) {
markdown += `\n_No coverage changes._\n`;
} else {
markdown += `| | Base | PR | Delta |\n`;
markdown += `| :--- | :---: | :---: | :---: |\n`;
if (changedRows.length > 0) {
markdown += changedRows.sort().join('');
}
if (newRows.length > 0) {
markdown += newRows.sort().join('');
}
const oldTotalPct = getPct(baseSummary.total, metric);
const newTotalPct = getPct(prSummary.total, metric);
if (oldTotalPct !== newTotalPct) {
markdown += `| **Total** | ${oldTotalPct}% | ${newTotalPct}% | ${formatDiff(oldTotalPct, newTotalPct)} |\n`;
}
}
markdown += `\n\n_Generated by [coverage-comment.yml](https://github.com/a2aproject/a2a-js/actions/workflows/coverage-comment.yml)_`;
const prNumber = fs.readFileSync('./PR_NUMBER', 'utf8').trim();
if (!prNumber) {
console.log("No PR number found.");
return;
}
const comments = await github.rest.issues.listComments({
owner,
repo,
issue_number: prNumber,
});
const existingComment = comments.data.find(c =>
c.body.includes('Generated by [coverage-comment.yml]') &&
c.user.type === 'Bot'
);
if (existingComment) {
await github.rest.issues.updateComment({
owner,
repo,
comment_id: existingComment.id,
body: markdown
});
} else {
await github.rest.issues.createComment({
owner,
repo,
issue_number: prNumber,
body: markdown
});
}

View File

@ -5,6 +5,10 @@ on:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
paths-ignore:
- '**.md'
- 'LICENSE'
- '.github/CODEOWNERS'
jobs:
eslint:
@ -18,5 +22,8 @@ jobs:
node-version: 18
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
cache-dependency-path: |
package-lock.json
src/samples/package-lock.json
- run: npm ci && (cd src/samples && npm ci)
- run: npm run lint
- run: npm run lint:ci

View File

@ -19,6 +19,7 @@ jobs:
with:
node-version: 18
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
- run: npm ci
- run: npm run build

View File

@ -5,13 +5,17 @@ on:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
paths-ignore:
- '**.md'
- 'LICENSE'
- '.github/CODEOWNERS'
- 'test/**'
- 'src/samples/**'
env:
# TODO once we have the TCK for 0.4.0 we will need to look at the branch to decide which TCK version to run.
# Tag of the TCK
# Temporary set to this commit sha because of this issue https://github.com/a2aproject/a2a-js/pull/142#issuecomment-3558892334
TCK_VERSION: 601bf0d6f63baafb079c2ab23f53d73ce03e5461
TCK_VERSION: 0.3.0.beta3
# Tells uv to not need a venv, and instead use system
UV_SYSTEM_PYTHON: 1
# Base URL for the SUT agent
@ -40,6 +44,7 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
- run: |
npm ci
npm run build
@ -100,14 +105,13 @@ jobs:
id: run-tck-mandatory
timeout-minutes: 5
run: |
./run_tck.py --sut-url ${{ env.SUT_JSONRPC_URL }} --category mandatory --transports jsonrpc,rest
./run_tck.py --sut-url ${{ env.SUT_JSONRPC_URL }} --category mandatory --transports jsonrpc,rest,grpc
working-directory: tck/a2a-tck
# TODO: Add back the transports jsonrpc,rest once the TCK supports REST, linked to https://github.com/a2aproject/a2a-tck/issues/99
- name: Run TCK (capabilities)
id: run-tck-capabilities
timeout-minutes: 5
run: |
./run_tck.py --sut-url ${{ env.SUT_JSONRPC_URL }} --category capabilities
./run_tck.py --sut-url ${{ env.SUT_JSONRPC_URL }} --category capabilities --transports jsonrpc,rest,grpc
working-directory: tck/a2a-tck
- name: Stop SUT
if: always()

View File

@ -5,9 +5,14 @@ name: Run Unit Tests
on:
push:
branches: [ "main" ]
branches: [ "main", "epic/**" ]
pull_request:
branches: [ "main" ]
branches: [ "main", "epic/**" ]
paths-ignore:
- '**.md'
- 'LICENSE'
- '.github/CODEOWNERS'
- 'src/samples/**'
jobs:
test:
@ -49,23 +54,25 @@ jobs:
coverage:
runs-on: ubuntu-latest
steps:
- uses: actions/setup-node@v3
with:
node-version: 24
- name: Checkout Main
- name: Checkout Base Branch
uses: actions/checkout@v4
with:
ref: main
ref: ${{ github.event.pull_request.base.ref || 'main' }}
clean: true
- name: Install & Test (Main)
- uses: actions/setup-node@v4
with:
node-version: 24
cache: 'npm'
- name: Install & Test (Base Branch)
timeout-minutes: 10
run: |
npm ci
npm run coverage
mv coverage/coverage-summary.json ${{ runner.temp }}/coverage-main-summary.json
mv coverage/coverage-summary.json ${{ runner.temp }}/coverage-base-summary.json
- name: Upload Artifact (main)
- name: Upload Artifact (base)
uses: actions/upload-artifact@v4
if: github.event_name != 'pull_request'
with:
@ -85,83 +92,21 @@ jobs:
run: |
npm ci
npm run coverage
mv coverage/coverage-summary.json coverage-pr-summary.json
mv ${{ runner.temp }}/coverage-base-summary.json coverage-base-summary.json
- name: Upload Artifact (PR)
id: upload-artifact-pr
- name: Save PR number
run: |
echo ${{ github.event.number }} > ./PR_NUMBER
- name: Upload Coverage Artifacts
uses: actions/upload-artifact@v4
if: github.event_name == 'pull_request'
with:
name: coverage-report
path: coverage
retention-days: 14
- name: Post Comment
uses: actions/github-script@v6
if: github.event_name == 'pull_request'
env:
ARTIFACT_URL: ${{ steps.upload-artifact-pr.outputs.artifact-url }}
with:
script: |
const fs = require('fs');
const loadSummary = (path) => {
return JSON.parse(fs.readFileSync(path, 'utf8'));
};
let markdown = `### 🧪 Code Coverage\n\n`;
markdown += `[⬇️ **Download HTML Report**](${process.env.ARTIFACT_URL})\n\n`;
markdown += `| Metric | Main | PR | Delta |\n`;
markdown += `| :--- | :---: | :---: | :---: |\n`;
const metrics = ['lines', 'statements', 'functions', 'branches'];
const getPct = (summary, metric) => summary.total[metric].pct;
const mainSummary = loadSummary('${{ runner.temp }}/coverage-main-summary.json');
const prSummary = loadSummary('./coverage/coverage-summary.json');
metrics.forEach(metric => {
const oldPct = getPct(mainSummary, metric);
const newPct = getPct(prSummary, metric);
const diff = (newPct - oldPct).toFixed(2);
let icon = '';
if (diff > 0) icon = '🟢';
else if (diff < 0) icon = '🔴';
else icon = '⚪️';
const diffStr = diff > 0 ? `+${diff}%` : `${diff}%`;
markdown += `| **${metric}** | ${oldPct}% | ${newPct}% | ${icon} ${diffStr} |\n`;
});
markdown += `\n_Generated by [unit-tests.yml](https://github.com/a2aproject/a2a-js/actions/workflows/unit-tests.yml)_`;
const { owner, repo } = context.repo;
const issue_number = context.issue.number;
const comments = await github.rest.issues.listComments({
owner,
repo,
issue_number,
});
const existingComment = comments.data.find(c =>
c.body.includes('Generated by [unit-tests.yml]') &&
c.user.type === 'Bot'
);
if (existingComment) {
await github.rest.issues.updateComment({
owner,
repo,
comment_id: existingComment.id,
body: markdown
});
} else {
await github.rest.issues.createComment({
owner,
repo,
issue_number,
body: markdown
});
}
name: coverage-data
path: |
coverage-base-summary.json
coverage-pr-summary.json
coverage/
PR_NUMBER
retention-days: 1

74
AGENTS.md Normal file
View File

@ -0,0 +1,74 @@
# @a2a-js/sdk
## Project Overview
`@a2a-js/sdk` is the official TypeScript/JavaScript SDK for the **Agent2Agent (A2A) Protocol**. It enables developers to build both:
1. **A2A Clients**: Applications that can discover, connect to, and interact with A2A agents.
2. **A2A Servers**: Agents that expose their capabilities via the A2A protocol (JSON-RPC or HTTP+JSON/REST).
The SDK implements the **A2A Protocol Specification v0.3.0**.
## Tech Stack
* **Language**: TypeScript (Node.js >= 18)
* **Build System**: `tsup` (Outputs ESM and CJS)
* **Testing Framework**: `vitest`
* **Linting/Formatting**: `eslint`, `prettier`
* **Peer Dependencies**: `express` (for server-side Express integration)
## Architecture & Key Components
The project is structured into modular entry points to allow tree-shaking and separation of concerns.
### 1. Common (`src/index.ts`)
* **Types**: Core protocol types (`Message`, `Task`, `AgentCard`).
* **Constants**: Protocol constants like `AGENT_CARD_PATH`.
* **Errors**: Common error classes (`A2AError`).
### 2. Client (`src/client/index.ts`)
* **`ClientFactory`**: The main entry point for creating clients. Can create clients from a base URL or an `AgentCard`.
* **`A2AClient`**: The interface for sending messages and streams.
* **Transports**:
* `JsonRpcTransport`: Uses JSON-RPC over HTTP.
* `RestTransport`: Uses standard HTTP+JSON REST patterns.
* **Interceptors**: `CallInterceptor` for modifying requests/responses (e.g., adding auth headers).
* **Auth**: `AuthenticationHandler` and `createAuthenticatingFetchWithRetry` for handling token refresh logic.
### 3. Server (`src/server/index.ts`)
* **`AgentExecutor`**: The core interface you implement to define your agent's logic (`execute`, `cancelTask`).
* **`DefaultRequestHandler`**: Orchestrates request processing, task management, and event dispatching.
* **`ExecutionEventBus`**: Used within `AgentExecutor` to publish `Message`, `Task`, and `Artifact` updates.
* **`InMemoryTaskStore`**: Default in-memory storage for task state.
* **Push Notifications**: `PushNotificationSender` and `InMemoryPushNotificationStore` for async updates.
### 4. Server Express Integration (`src/server/express/index.ts`)
* **Handlers**: `agentCardHandler`, `jsonRpcHandler`, `restHandler` to easily mount A2A endpoints in an Express app.
* **`UserBuilder`**: Middleware for extracting user identity from requests.
## Building and Running
### Key Commands
| Command | Description |
| :--- | :--- |
| `npm run build` | Builds the SDK using `tsup` into `dist/`. |
| `npm test` | Runs unit tests using `vitest`. |
| `npm run lint` | Runs all linting checks and applies automatic fixes (ESLint + Prettier + betterer). |
| `npm run lint:ci` | Runs all linting checks without applying fixes. Fails if any issues are found. |
| `npm run format:readme` | Formats the README file. |
## Samples
The `src/samples` directory contains practical examples:
* **`agents/`**:
* `movie-agent/`: A sample agent that queries movie data from TMDB.
* `sample-agent/`: A basic reference agent implementation.
* **`authentication/`**: Examples of how to implement authentication middleware and user building.
* **`extensions/`**: Examples of using protocol extensions.
* **`cli.ts`**: A CLI tool example for interacting with agents.
## Development Conventions
* **Testing**: All new features should have accompanying unit tests in `test/` or alongside source files.
* **Exports**: The project uses specific export paths in `package.json` (`.`, `./client`, `./server`, `./server/express`). Ensure new components are exported from the correct entry point.

View File

@ -1,5 +1,79 @@
# Changelog
## [0.3.13](https://github.com/a2aproject/a2a-js/compare/v0.3.12...v0.3.13) (2026-03-16)
### Bug Fixes
* properly parse ProtoJSON body for POST pushNotificationConfigs ([#352](https://github.com/a2aproject/a2a-js/issues/352)) ([57696a8](https://github.com/a2aproject/a2a-js/commit/57696a8001416ae2c5c592406c1f46b3e9209eca)), closes [#336](https://github.com/a2aproject/a2a-js/issues/336)
## [0.3.12](https://github.com/a2aproject/a2a-js/compare/v0.3.11...v0.3.12) (2026-03-10)
### Bug Fixes
* Fixing missing push configuration after normalization for rest transport ([#346](https://github.com/a2aproject/a2a-js/issues/346)) ([54ac8c4](https://github.com/a2aproject/a2a-js/commit/54ac8c41cacc54fb0d80526b79c87ba3aede14af))
## [0.3.11](https://github.com/a2aproject/a2a-js/compare/v0.3.10...v0.3.11) (2026-03-10)
### Bug Fixes
* support proto-based AgentCard in AgentCardResolver ([#344](https://github.com/a2aproject/a2a-js/issues/344)) ([e71221c](https://github.com/a2aproject/a2a-js/commit/e71221cbc87b54acd96fbb4e7a46439a33ccbed6))
* throw on JSON-RPC response id mismatch ([#318](https://github.com/a2aproject/a2a-js/issues/318)) ([5ea1c94](https://github.com/a2aproject/a2a-js/commit/5ea1c94acaf2cae5aa1bc10ea5816f5400a62423))
## [0.3.10](https://github.com/a2aproject/a2a-js/compare/v0.3.9...v0.3.10) (2026-01-27)
### Bug Fixes
* do not use ReadableStream async iterator in SSE stream parsing ([#311](https://github.com/a2aproject/a2a-js/issues/311)) ([5359fa8](https://github.com/a2aproject/a2a-js/commit/5359fa802fc3a3dcf35438f3cee18f7ab9bc3ca3))
* preserve typed error as cause in SSE errors ([#315](https://github.com/a2aproject/a2a-js/issues/315)) ([d39544e](https://github.com/a2aproject/a2a-js/commit/d39544ea4ba0db004fcca15b9fac870a97725e5c))
## [0.3.9](https://github.com/a2aproject/a2a-js/compare/v0.3.8...v0.3.9) (2026-01-21)
### Features
* implement gRPC client ([#299](https://github.com/a2aproject/a2a-js/issues/299)) ([dbdb96e](https://github.com/a2aproject/a2a-js/commit/dbdb96eeb14a710ad612f36f371d848fc7cce186))
* implement gRPC server ([#279](https://github.com/a2aproject/a2a-js/issues/279)) ([bd4caa2](https://github.com/a2aproject/a2a-js/commit/bd4caa22a09480ba8cebec755528b67b80a95323))
### Bug Fixes
* use proto default values in generated a2a_types.ts ([#303](https://github.com/a2aproject/a2a-js/issues/303)) ([0215d42](https://github.com/a2aproject/a2a-js/commit/0215d4232654c356c5d48e93cb94da46093576dd))
## [0.3.8](https://github.com/a2aproject/a2a-js/compare/v0.3.7...v0.3.8) (2026-01-15)
### ⚠ BREAKING CHANGES
* use ProtoJSON for REST transport ([#292](https://github.com/a2aproject/a2a-js/issues/292))
### Features
* use case-insensitive transport protocol name comparison in ClientFactory ([5246067](https://github.com/a2aproject/a2a-js/commit/5246067f5fc1ca3aa7b1aef7176aab5b0f164acb))
### Bug Fixes
* add typesVersions to support legacy module resolution ([#288](https://github.com/a2aproject/a2a-js/issues/288)) ([6499e29](https://github.com/a2aproject/a2a-js/commit/6499e290f6e5a932eb7a6946c3b708cdea367165))
* use ProtoJSON for REST transport ([#292](https://github.com/a2aproject/a2a-js/issues/292)) ([d2efc4c](https://github.com/a2aproject/a2a-js/commit/d2efc4cf343860d25b05f064f507ef4da7bba06b))
## [0.3.7](https://github.com/a2aproject/a2a-js/compare/v0.3.6...v0.3.7) (2025-12-17)
### Features
* add rest client ([#258](https://github.com/a2aproject/a2a-js/issues/258)) ([96be3a1](https://github.com/a2aproject/a2a-js/commit/96be3a1d6caa3f55673e0c0e77859fe064beab2d))
* remove EventEmitter dependency to support Edge Runtime ([#219](https://github.com/a2aproject/a2a-js/issues/219)) ([6c76fef](https://github.com/a2aproject/a2a-js/commit/6c76fef26473d8b15d729040b6c474de2794c7fe)), closes [#218](https://github.com/a2aproject/a2a-js/issues/218)
### Bug Fixes
* export transport agnostic errors from client ([#272](https://github.com/a2aproject/a2a-js/issues/272)) ([23cd42e](https://github.com/a2aproject/a2a-js/commit/23cd42e83d6510b54b013df2efd762017f47d2a1))
* pass ServerCallContext to getAuthenticatedExtendedAgentCard for REST ([#274](https://github.com/a2aproject/a2a-js/issues/274)) ([89b141b](https://github.com/a2aproject/a2a-js/commit/89b141b5ba915c53c04b2ffb1632e673b3adaace)), closes [#137](https://github.com/a2aproject/a2a-js/issues/137)
## [0.3.6](https://github.com/a2aproject/a2a-js/compare/v0.3.5...v0.3.6) (2025-12-10)

View File

@ -29,10 +29,28 @@ If you plan to use the Express integration (imports from `@a2a-js/sdk/server/exp
npm install express
```
### For gRPC Usage
If you plan to use the GRPC transport (imports from `@a2a-js/sdk/server/grpc` or `@a2a-js/sdk/client/grpc`), you must install the required peer dependencies:
```bash
npm install @grpc/grpc-js @bufbuild/protobuf
```
You can also find some samples [here](https://github.com/a2aproject/a2a-js/tree/main/src/samples).
---
## Compatibility
This SDK implements the A2A Protocol Specification [`v0.3.0`](https://a2a-protocol.org/v0.3.0/specification).
| Transport | Client | Server |
| :--- | :---: | :---: |
| **JSON-RPC** | ✅ | ✅ |
| **HTTP+JSON/REST** | ✅ | ✅ |
| **GRPC** (Node.js only) | ✅ | ✅ |
## Quickstart
This example shows how to create a simple "Hello World" agent server and a client to interact with it.
@ -44,6 +62,7 @@ The core of an A2A server is the `AgentExecutor`, which contains your agent's lo
```typescript
// server.ts
import express from 'express';
import { Server, ServerCredentials } from '@grpc/grpc-js';
import { v4 as uuidv4 } from 'uuid';
import { AgentCard, Message, AGENT_CARD_PATH } from '@a2a-js/sdk';
import {
@ -54,6 +73,7 @@ import {
InMemoryTaskStore,
} from '@a2a-js/sdk/server';
import { agentCardHandler, jsonRpcHandler, restHandler, UserBuilder } from '@a2a-js/sdk/server/express';
import { grpcService, A2AService } from '@a2a-js/sdk/server/grpc';
// 1. Define your agent's identity card.
const helloAgentCard: AgentCard = {
@ -71,6 +91,7 @@ const helloAgentCard: AgentCard = {
additionalInterfaces: [
{ url: 'http://localhost:4000/a2a/jsonrpc', transport: 'JSONRPC' }, // Default JSON-RPC transport
{ url: 'http://localhost:4000/a2a/rest', transport: 'HTTP+JSON' }, // HTTP+JSON/REST transport
{ url: 'localhost:4001', transport: 'GRPC' }, // GRPC transport
],
};
@ -113,6 +134,15 @@ app.use('/a2a/rest', restHandler({ requestHandler, userBuilder: UserBuilder.noAu
app.listen(4000, () => {
console.log(`🚀 Server started on http://localhost:4000`);
});
const server = new Server();
server.addService(A2AService, grpcService({
requestHandler,
userBuilder: UserBuilder.noAuthentication,
}));
server.bindAsync(`localhost:4001`, ServerCredentials.createInsecure(), () => {
console.log(`🚀 Server started on localhost:4001`);
});
```
### Client: Sending a Message
@ -153,6 +183,46 @@ async function run() {
await run();
```
### gRPC Client: Sending a Message
The [`ClientFactory`](src/client/factory.ts) has to be created explicitly passing the [`GrpcTransportFactory`](src/client/transports/grpc/grpc_transport.ts).
```typescript
// client.ts
import { ClientFactory, ClientFactoryOptions } from '@a2a-js/sdk/client';
import { GrpcTransportFactory } from '@a2a-js/sdk/client/grpc';
import { Message, MessageSendParams, SendMessageSuccessResponse } from '@a2a-js/sdk';
import { v4 as uuidv4 } from 'uuid';
async function run() {
const factory = new ClientFactory({
transports: [new GrpcTransportFactory()]
});
// createFromUrl accepts baseUrl and optional path,
// (the default path is /.well-known/agent-card.json)
const client = await factory.createFromUrl('http://localhost:4000');
const sendParams: MessageSendParams = {
message: {
messageId: uuidv4(),
role: 'user',
parts: [{ kind: 'text', text: 'Hi there!' }],
kind: 'message',
},
};
try {
const response = await client.sendMessage(sendParams);
const result = response as Message;
console.log('Agent response:', result.parts[0].text); // "Hello, world!"
} catch(e) {
console.error('Error:', e);
}
}
await run();
```
---
## A2A `Task` Support

View File

@ -11,7 +11,7 @@ export default defineConfig(
tseslint.configs.recommended,
eslintPluginPrettier, // Automatically disables eslint formatting rules and enables `prettier`
{
ignores: ['dist/', 'node_modules/', 'src/types.ts'],
ignores: ['dist/', 'node_modules/', 'src/types.ts', 'build/'],
},
{
rules: {

7413
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "@a2a-js/sdk",
"version": "0.3.6",
"version": "0.3.13",
"description": "Server & Client SDK for Agent2Agent protocol",
"license": "Apache-2.0",
"repository": {
@ -13,6 +13,25 @@
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"typesVersions": {
"*": {
"server": [
"./dist/server/index.d.ts"
],
"server/express": [
"./dist/server/express/index.d.ts"
],
"server/grpc": [
"./dist/server/grpc/index.d.ts"
],
"client": [
"./dist/client/index.d.ts"
],
"client/grpc": [
"./dist/client/transports/grpc/index.d.ts"
]
}
},
"exports": {
".": {
"types": "./dist/index.d.ts",
@ -29,10 +48,20 @@
"import": "./dist/server/express/index.js",
"require": "./dist/server/express/index.cjs"
},
"./server/grpc": {
"types": "./dist/server/grpc/index.d.ts",
"import": "./dist/server/grpc/index.js",
"require": "./dist/server/grpc/index.cjs"
},
"./client": {
"types": "./dist/client/index.d.ts",
"import": "./dist/client/index.js",
"require": "./dist/client/index.cjs"
},
"./client/grpc": {
"types": "./dist/client/transports/grpc/index.d.ts",
"import": "./dist/client/transports/grpc/index.js",
"require": "./dist/client/transports/grpc/index.cjs"
}
},
"files": [
@ -41,50 +70,59 @@
"README.md"
],
"devDependencies": {
"@edge-runtime/vm": "5.0.0",
"@betterer/cli": "^6.0.0-alpha.1",
"@betterer/typescript": "^6.0.0-alpha.1",
"@bufbuild/buf": "^1.61.0",
"@bufbuild/protobuf": "^2.10.2",
"@cloudflare/vitest-pool-workers": "^0.12.5",
"@eslint/js": "^9.39.1",
"@grpc/grpc-js": "^1.11.0",
"@types/express": "^5.0.3",
"@types/node": "^22.13.14",
"@types/sinon": "^17.0.4",
"@types/supertest": "^6.0.3",
"@vitest/coverage-v8": "^4.0.15",
"@vitest/coverage-v8": "^3.2.4",
"esbuild": "^0.27.0",
"eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.4",
"express": "^5.1.0",
"gts": "^6.0.2",
"json-schema-to-typescript": "^15.0.4",
"prettier": "^3.6.2",
"sinon": "^20.0.0",
"supertest": "^7.1.4",
"tsup": "^8.5.0",
"tsx": "^4.19.3",
"typescript": "^5.9.3",
"typescript-eslint": "^8.46.4",
"vitest": "^4.0.15"
"vitest": "^3.2.4"
},
"scripts": {
"clean": "gts clean",
"build": "tsup",
"test": "vitest run",
"test:edge": "vitest run --config vitest.edge.config.ts",
"lint": "tsc --noEmit && npx eslint .",
"lint": "tsc --noEmit && npx eslint . --fix && betterer precommit",
"lint:ci": "tsc --noEmit && npx eslint . && betterer ci",
"format:readme": "prettier --write ./README.md",
"lint:fix": "npx eslint . --fix",
"coverage": "vitest run --coverage",
"generate": "curl https://raw.githubusercontent.com/google-a2a/A2A/refs/heads/main/specification/json/a2a.json > spec.json && node scripts/generateTypes.js && rm spec.json",
"test-build:browser": "esbuild ./dist/client/index.js ./dist/index.js --bundle --platform=browser --outdir=dist/tmp-checks --outbase=./dist"
"test-build": "esbuild ./dist/client/index.js ./dist/server/index.js ./dist/index.js --bundle --platform=neutral --outdir=dist/tmp-checks --outbase=./dist"
},
"dependencies": {
"uuid": "^11.1.0"
},
"peerDependencies": {
"@bufbuild/protobuf": "^2.10.2",
"@grpc/grpc-js": "^1.11.0",
"express": "^4.21.2 || ^5.1.0"
},
"peerDependenciesMeta": {
"express": {
"optional": true
},
"@grpc/grpc-js": {
"optional": true
},
"@bufbuild/protobuf": {
"optional": true
}
}
}

View File

@ -1,5 +1,7 @@
import { AGENT_CARD_PATH } from '../constants.js';
import { AgentCard } from '../types.js';
import { AgentCard as PBAgentCard } from '../types/pb/a2a_types.js';
import { FromProto } from '../types/converters/from_proto.js';
export interface AgentCardResolverOptions {
path?: string;
@ -29,7 +31,8 @@ export class DefaultAgentCardResolver implements AgentCardResolver {
if (!response.ok) {
throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status}`);
}
return await response.json();
const rawCard = await response.json();
return this.normalizeAgentCard(rawCard);
}
private fetchImpl(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
@ -38,6 +41,66 @@ export class DefaultAgentCardResolver implements AgentCardResolver {
}
return fetch(...args);
}
/*
* In the v0.3.0 specification, there was a structural drift between the JSON Schema data model
* and the Protobuf-based data model for AgentCards.
* The JSON Schema format uses a `"type"` discriminator (e.g., `{"type": "openIdConnect"}`),
* while the Protobuf JSON representation uses the `oneof` field name as the discriminator
* (e.g., `{"openIdConnectSecurityScheme": {...}}`).
*
* The A2A SDK internal logic expects the JSON Schema-based format. This fallback detection
* allows us to parse cards served by endpoints returning the Protobuf JSON structure by
* identifying the lack of the "type" field in security schemes or the presence of the
* "schemes" wrapper in security entries, and normalizing it before use.
*/
private normalizeAgentCard(card: unknown): AgentCard {
if (this.isProtoAgentCard(card)) {
const parsedProto = PBAgentCard.fromJSON(card);
return FromProto.agentCard(parsedProto);
}
return card as AgentCard;
}
private isProtoAgentCard(card: unknown): boolean {
if (!card || typeof card !== 'object') return false;
const c = card as Record<string, unknown>;
if (this.hasProtoSecurity(c.security)) return true;
if (this.hasProtoSecuritySchemes(c.securitySchemes)) return true;
if (Array.isArray(c.skills)) {
return c.skills.some(
(skill) =>
skill &&
typeof skill === 'object' &&
this.hasProtoSecurity((skill as Record<string, unknown>).security)
);
}
return false;
}
private hasProtoSecurity(securityArray: unknown): boolean {
if (Array.isArray(securityArray) && securityArray.length > 0) {
const first = securityArray[0];
return first && typeof first === 'object' && 'schemes' in first;
}
return false;
}
private hasProtoSecuritySchemes(securitySchemes: unknown): boolean {
if (securitySchemes && typeof securitySchemes === 'object') {
const schemes = Object.values(securitySchemes);
if (schemes.length > 0) {
const first = schemes[0];
// Proto JSON maps use the oneof field name directly rather than a "type" property
return first && typeof first === 'object' && !('type' in first);
}
}
return false;
}
}
export const AgentCardResolver = {

View File

@ -3,6 +3,7 @@ import { AgentCard } from '../types.js';
import { AgentCardResolver } from './card-resolver.js';
import { Client, ClientConfig } from './multitransport-client.js';
import { JsonRpcTransportFactory } from './transports/json_rpc_transport.js';
import { RestTransportFactory } from './transports/rest_transport.js';
import { TransportFactory } from './transports/transport.js';
export interface ClientFactoryOptions {
@ -34,7 +35,7 @@ export const ClientFactoryOptions = {
* SDK default options for {@link ClientFactory}.
*/
default: {
transports: [new JsonRpcTransportFactory()],
transports: [new JsonRpcTransportFactory(), new RestTransportFactory()],
} as Readonly<ClientFactoryOptions>,
/**
@ -74,7 +75,7 @@ export const ClientFactoryOptions = {
};
export class ClientFactory {
private readonly transportsByName: Map<string, TransportFactory>;
private readonly transportsByName: CaseInsensitiveMap<TransportFactory>;
private readonly agentCardResolver: AgentCardResolver;
constructor(public readonly options: ClientFactoryOptions = ClientFactoryOptions.default) {
@ -83,8 +84,7 @@ export class ClientFactory {
}
this.transportsByName = transportsByName(options.transports);
for (const transport of options.preferredTransports ?? []) {
const factory = this.options.transports.find((t) => t.protocolName === transport);
if (!factory) {
if (!this.transportsByName.has(transport)) {
throw new Error(
`Unknown preferred transport: ${transport}, available transports: ${[...this.transportsByName.keys()].join()}`
);
@ -99,7 +99,7 @@ export class ClientFactory {
async createFromAgentCard(agentCard: AgentCard): Promise<Client> {
const agentCardPreferred = agentCard.preferredTransport ?? JsonRpcTransportFactory.name;
const additionalInterfaces = agentCard.additionalInterfaces ?? [];
const urlsPerAgentTransports = new Map<string, string>([
const urlsPerAgentTransports = new CaseInsensitiveMap<string>([
[agentCardPreferred, agentCard.url],
...additionalInterfaces.map<[string, string]>((i) => [i.transport, i.url]),
]);
@ -109,18 +109,15 @@ export class ClientFactory {
...additionalInterfaces.map((i) => i.transport),
];
for (const transport of transportsByPreference) {
if (!urlsPerAgentTransports.has(transport)) {
continue;
}
const url = urlsPerAgentTransports.get(transport);
const factory = this.transportsByName.get(transport);
if (!factory) {
continue;
if (factory && url) {
return new Client(
await factory.create(url, agentCard),
agentCard,
this.options.clientConfig
);
}
return new Client(
await factory.create(urlsPerAgentTransports.get(transport), agentCard),
agentCard,
this.options.clientConfig
);
}
throw new Error(
'No compatible transport found, available transports: ' +
@ -164,8 +161,8 @@ function mergeTransports(
function transportsByName(
transports: ReadonlyArray<TransportFactory> | undefined
): Map<string, TransportFactory> {
const result = new Map<string, TransportFactory>();
): CaseInsensitiveMap<TransportFactory> {
const result = new CaseInsensitiveMap<TransportFactory>();
if (!transports) {
return result;
}
@ -188,3 +185,29 @@ function mergeArrays<T>(
return [...(a1 ?? []), ...(a2 ?? [])];
}
/**
* A Map that normalizes string keys to uppercase for case-insensitive lookups.
* This prevents errors from inconsistent casing in protocol names.
*/
class CaseInsensitiveMap<T> extends Map<string, T> {
private normalizeKey(key: string): string {
return key.toUpperCase();
}
override set(key: string, value: T): this {
return super.set(this.normalizeKey(key), value);
}
override get(key: string): T | undefined {
return super.get(this.normalizeKey(key));
}
override has(key: string): boolean {
return super.has(this.normalizeKey(key));
}
override delete(key: string): boolean {
return super.delete(this.normalizeKey(key));
}
}

View File

@ -18,6 +18,11 @@ export {
JsonRpcTransportFactory,
type JsonRpcTransportOptions,
} from './transports/json_rpc_transport.js';
export {
RestTransport,
RestTransportFactory,
type RestTransportOptions,
} from './transports/rest_transport.js';
export type {
CallInterceptor,
BeforeArgs,
@ -31,3 +36,12 @@ export {
withA2AExtensions,
} from './service-parameters.js';
export { ClientCallContext, type ContextUpdate, ClientCallContextKey } from './context.js';
export {
AuthenticatedExtendedCardNotConfiguredError,
ContentTypeNotSupportedError,
InvalidAgentResponseError,
PushNotificationNotSupportedError,
TaskNotCancelableError,
TaskNotFoundError,
UnsupportedOperationError,
} from '../errors.js';

View File

@ -0,0 +1,349 @@
import * as grpc from '@grpc/grpc-js';
import { TransportProtocolName } from '../../../core.js';
import { A2AServiceClient } from '../../../grpc/pb/a2a_services.js';
import {
MessageSendParams,
TaskPushNotificationConfig,
TaskIdParams,
ListTaskPushNotificationConfigParams,
DeleteTaskPushNotificationConfigParams,
TaskQueryParams,
Task,
AgentCard,
GetTaskPushNotificationConfigParams,
} from '../../../types.js';
import { A2AStreamEventData, SendMessageResult } from '../../client.js';
import { RequestOptions } from '../../multitransport-client.js';
import { Transport, TransportFactory } from '../transport.js';
import { ToProto } from '../../../types/converters/to_proto.js';
import { FromProto } from '../../../types/converters/from_proto.js';
import {
AuthenticatedExtendedCardNotConfiguredError,
PushNotificationNotSupportedError,
TaskNotFoundError,
TaskNotCancelableError,
UnsupportedOperationError,
} from '../../../errors.js';
type GrpcUnaryCall<TReq, TRes> = (
request: TReq,
metadata: grpc.Metadata,
options: Partial<grpc.CallOptions>,
callback: (error: grpc.ServiceError | null, response: TRes) => void
) => grpc.ClientUnaryCall;
type GrpcStreamCall<TReq, TRes> = (
request: TReq,
metadata?: grpc.Metadata,
options?: Partial<grpc.CallOptions>
) => grpc.ClientReadableStream<TRes>;
export interface GrpcTransportOptions {
endpoint: string;
grpcChannelCredentials?: grpc.ChannelCredentials;
grpcCallOptions?: Partial<grpc.CallOptions>;
}
export class GrpcTransport implements Transport {
private readonly grpcCallOptions?: Partial<grpc.CallOptions>;
private readonly grpcClient: A2AServiceClient;
constructor(options: GrpcTransportOptions) {
this.grpcCallOptions = options.grpcCallOptions;
this.grpcClient = new A2AServiceClient(
options.endpoint,
options.grpcChannelCredentials ?? grpc.credentials.createInsecure()
);
}
async getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard> {
const rpcResponse = await this._sendGrpcRequest(
'getAgentCard',
undefined,
options,
this.grpcClient.getAgentCard.bind(this.grpcClient),
ToProto.getAgentCardRequest,
FromProto.agentCard
);
return rpcResponse;
}
async sendMessage(
params: MessageSendParams,
options?: RequestOptions
): Promise<SendMessageResult> {
const rpcResponse = await this._sendGrpcRequest(
'sendMessage',
params,
options,
this.grpcClient.sendMessage.bind(this.grpcClient),
ToProto.messageSendParams,
FromProto.sendMessageResult
);
return rpcResponse;
}
async *sendMessageStream(
params: MessageSendParams,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined> {
yield* this._sendGrpcStreamingRequest(
'sendStreamingMessage',
params,
options,
this.grpcClient.sendStreamingMessage.bind(this.grpcClient),
ToProto.messageSendParams
);
}
async setTaskPushNotificationConfig(
params: TaskPushNotificationConfig,
options?: RequestOptions
): Promise<TaskPushNotificationConfig> {
const rpcResponse = await this._sendGrpcRequest(
'createTaskPushNotificationConfig',
params,
options,
this.grpcClient.createTaskPushNotificationConfig.bind(this.grpcClient),
ToProto.taskPushNotificationConfigCreate,
FromProto.taskPushNotificationConfig
);
return rpcResponse;
}
async getTaskPushNotificationConfig(
params: GetTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<TaskPushNotificationConfig> {
const rpcResponse = await this._sendGrpcRequest(
'getTaskPushNotificationConfig',
params,
options,
this.grpcClient.getTaskPushNotificationConfig.bind(this.grpcClient),
ToProto.getTaskPushNotificationConfigParams,
FromProto.taskPushNotificationConfig
);
return rpcResponse;
}
async listTaskPushNotificationConfig(
params: ListTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<TaskPushNotificationConfig[]> {
const rpcResponse = await this._sendGrpcRequest(
'listTaskPushNotificationConfig',
params,
options,
this.grpcClient.listTaskPushNotificationConfig.bind(this.grpcClient),
ToProto.listTaskPushNotificationConfigParams,
FromProto.listTaskPushNotificationConfig
);
return rpcResponse;
}
async deleteTaskPushNotificationConfig(
params: DeleteTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<void> {
await this._sendGrpcRequest(
'deleteTaskPushNotificationConfig',
params,
options,
this.grpcClient.deleteTaskPushNotificationConfig.bind(this.grpcClient),
ToProto.deleteTaskPushNotificationConfigParams,
() => {}
);
}
async getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task> {
const rpcResponse = await this._sendGrpcRequest(
'getTask',
params,
options,
this.grpcClient.getTask.bind(this.grpcClient),
ToProto.taskQueryParams,
FromProto.task
);
return rpcResponse;
}
async cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task> {
const rpcResponse = await this._sendGrpcRequest(
'cancelTask',
params,
options,
this.grpcClient.cancelTask.bind(this.grpcClient),
ToProto.cancelTaskRequest,
FromProto.task
);
return rpcResponse;
}
async *resubscribeTask(
params: TaskIdParams,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined> {
yield* this._sendGrpcStreamingRequest(
'taskSubscription',
params,
options,
this.grpcClient.taskSubscription.bind(this.grpcClient),
ToProto.taskIdParams
);
}
private async _sendGrpcRequest<TReq, TRes, TParams, TResponse>(
method: keyof A2AServiceClient,
params: TParams,
options: RequestOptions | undefined,
call: GrpcUnaryCall<TReq, TRes>,
parser: (req: TParams) => TReq,
converter: (res: TRes) => TResponse
): Promise<TResponse> {
return new Promise((resolve, reject) => {
let onAbort: (() => void) | undefined;
const clientCall = call(
parser(params),
this._buildMetadata(options),
this.grpcCallOptions ?? {},
(error, response) => {
if (options?.signal && onAbort) {
options.signal.removeEventListener('abort', onAbort);
}
if (error) {
return reject(GrpcTransport.mapToError(error, method));
}
resolve(converter(response));
}
);
if (options?.signal) {
if (options.signal.aborted) {
clientCall.cancel();
} else {
onAbort = () => clientCall.cancel();
options.signal.addEventListener('abort', onAbort);
}
}
});
}
private async *_sendGrpcStreamingRequest<TReq, TRes, TParams>(
method: 'sendStreamingMessage' | 'taskSubscription',
params: TParams,
options: RequestOptions | undefined,
call: GrpcStreamCall<TReq, TRes>,
parser: (req: TParams) => TReq
): AsyncGenerator<A2AStreamEventData, void, undefined> {
const streamResponse = call(
parser(params),
this._buildMetadata(options),
this.grpcCallOptions ?? {}
);
let onAbort: (() => void) | undefined;
if (options?.signal) {
if (options.signal.aborted) {
streamResponse.cancel();
} else {
onAbort = () => streamResponse.cancel();
options.signal.addEventListener('abort', onAbort);
}
}
try {
for await (const response of streamResponse) {
yield FromProto.messageStreamResult(response);
}
} catch (error) {
if (this.isServiceError(error)) {
throw GrpcTransport.mapToError(error, method);
} else {
throw new Error(`GRPC error for ${String(method)}!`, {
cause: error,
});
}
} finally {
if (options?.signal && onAbort) {
options.signal.removeEventListener('abort', onAbort);
}
streamResponse.cancel();
}
}
private isServiceError(error: unknown): error is grpc.ServiceError {
return typeof error === 'object' && error !== null && 'code' in error;
}
private _buildMetadata(options: RequestOptions | undefined): grpc.Metadata {
const metadata = new grpc.Metadata();
if (options?.serviceParameters) {
for (const [key, value] of Object.entries(options.serviceParameters)) {
metadata.set(key, value);
}
}
return metadata;
}
// TODO: the logic of mapToError will be removed in v1.0.0 with the enriched error model (https://a2a-protocol.org/latest/specification/#106-error-handling)
private static mapToError(error: grpc.ServiceError, method: keyof A2AServiceClient): Error {
switch (error.code) {
case grpc.status.NOT_FOUND:
return new TaskNotFoundError(error.details);
case grpc.status.FAILED_PRECONDITION:
if (method === 'cancelTask') {
return new TaskNotCancelableError(error.details);
}
if (method === 'getAgentCard') {
return new AuthenticatedExtendedCardNotConfiguredError(error.details);
}
break;
case grpc.status.UNIMPLEMENTED:
if (
[
'getTaskPushNotificationConfig',
'createTaskPushNotificationConfig',
'deleteTaskPushNotificationConfig',
'listTaskPushNotificationConfig',
].includes(method)
) {
return new PushNotificationNotSupportedError(error.details);
}
if (['getAgentCard', 'taskSubscription'].includes(method)) {
return new UnsupportedOperationError(error.details);
}
break;
//TODO: add case for grpc.status.INVALID_ARGUMENT and grpc.status.INTERNAL (the respective a2a errors are not implemented yet)
default:
break;
}
return new Error(`GRPC error for ${String(method)}! ${error.code} ${error.details}`, {
cause: error,
});
}
}
export class GrpcTransportFactoryOptions {
grpcChannelCredentials?: grpc.ChannelCredentials;
grpcCallOptions?: Partial<grpc.CallOptions>;
}
export class GrpcTransportFactory implements TransportFactory {
public static readonly name: TransportProtocolName = 'GRPC';
constructor(private readonly options?: GrpcTransportFactoryOptions) {}
get protocolName(): string {
return GrpcTransportFactory.name;
}
async create(url: string, _agentCard: AgentCard): Promise<Transport> {
return new GrpcTransport({
endpoint: url,
grpcChannelCredentials: this.options?.grpcChannelCredentials,
grpcCallOptions: this.options?.grpcCallOptions,
});
}
}

View File

@ -0,0 +1,5 @@
export {
GrpcTransport,
GrpcTransportFactory,
type GrpcTransportOptions,
} from './grpc_transport.js';

View File

@ -32,6 +32,7 @@ import {
} from '../../types.js';
import { A2AStreamEventData, SendMessageResult } from '../client.js';
import { RequestOptions } from '../multitransport-client.js';
import { parseSseStream } from '../../sse_utils.js';
import { Transport, TransportFactory } from './transport.js';
export interface JsonRpcTransportOptions {
@ -231,8 +232,8 @@ export class JsonRpcTransport implements Transport {
const rpcResponse: JSONRPCResponse = await httpResponse.json();
if (rpcResponse.id !== requestId) {
console.error(
`CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}.`
throw new Error(
`JSON-RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}.`
);
}
@ -303,62 +304,8 @@ export class JsonRpcTransport implements Transport {
);
}
yield* this._parseA2ASseStream<A2AStreamEventData>(response, clientRequestId);
}
private async *_parseA2ASseStream<TStreamItem>(
response: Response,
originalRequestId: number | string | null
): AsyncGenerator<TStreamItem, void, undefined> {
if (!response.body) {
throw new Error('SSE response body is undefined. Cannot read stream.');
}
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
let eventDataBuffer = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
if (eventDataBuffer.trim()) {
const result = this._processSseEventData<TStreamItem>(
eventDataBuffer,
originalRequestId
);
yield result;
}
break;
}
buffer += value;
let lineEndIndex;
while ((lineEndIndex = buffer.indexOf('\n')) >= 0) {
const line = buffer.substring(0, lineEndIndex).trim();
buffer = buffer.substring(lineEndIndex + 1);
if (line === '') {
if (eventDataBuffer) {
const result = this._processSseEventData<TStreamItem>(
eventDataBuffer,
originalRequestId
);
yield result;
eventDataBuffer = '';
}
} else if (line.startsWith('data:')) {
eventDataBuffer += line.substring(5).trimStart() + '\n';
}
}
}
} catch (error) {
console.error(
'Error reading or parsing SSE stream:',
(error instanceof Error && error.message) || 'Error unknown'
);
throw error;
} finally {
reader.releaseLock();
for await (const event of parseSseStream(response)) {
yield this._processSseEventData<A2AStreamEventData>(event.data, clientRequestId);
}
}
@ -369,45 +316,36 @@ export class JsonRpcTransport implements Transport {
if (!jsonData.trim()) {
throw new Error('Attempted to process empty SSE event data.');
}
let a2aStreamResponse: JSONRPCResponse;
try {
const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\n$/, ''));
const a2aStreamResponse: JSONRPCResponse = sseJsonRpcResponse as JSONRPCResponse;
if (a2aStreamResponse.id !== originalRequestId) {
console.warn(
`SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`
);
}
if ('error' in a2aStreamResponse) {
const err = a2aStreamResponse.error;
throw new Error(
`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`
);
}
if (!('result' in a2aStreamResponse) || typeof a2aStreamResponse.result === 'undefined') {
throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
}
return a2aStreamResponse.result as TStreamItem;
a2aStreamResponse = JSON.parse(jsonData) as JSONRPCResponse;
} catch (e) {
if (
e instanceof Error &&
(e.message.startsWith('SSE event contained an error') ||
e.message.startsWith("SSE event JSON-RPC response is missing 'result' field"))
) {
throw e;
}
console.error(
'Failed to parse SSE event data string or unexpected JSON-RPC structure:',
jsonData,
e
);
throw new Error(
`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${(e instanceof Error && e.message) || 'Unknown error'}`
`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${(e instanceof Error && e.message) || 'Unknown error'}`,
{ cause: e }
);
}
if (a2aStreamResponse.id !== originalRequestId) {
throw new Error(
`JSON-RPC response ID mismatch in SSE event. Expected ${originalRequestId}, got ${a2aStreamResponse.id}.`
);
}
if ('error' in a2aStreamResponse) {
const err = a2aStreamResponse.error;
throw new Error(
`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`,
{ cause: JsonRpcTransport.mapToError(a2aStreamResponse) }
);
}
if (!('result' in a2aStreamResponse) || typeof a2aStreamResponse.result === 'undefined') {
throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
}
return a2aStreamResponse.result as TStreamItem;
}
private static mapToError(response: JSONRPCErrorResponse): Error {

View File

@ -0,0 +1,383 @@
import { TransportProtocolName } from '../../core.js';
import {
A2A_ERROR_CODE,
AuthenticatedExtendedCardNotConfiguredError,
ContentTypeNotSupportedError,
InvalidAgentResponseError,
PushNotificationNotSupportedError,
TaskNotFoundError,
TaskNotCancelableError,
UnsupportedOperationError,
} from '../../errors.js';
import {
AgentCard,
DeleteTaskPushNotificationConfigParams,
GetTaskPushNotificationConfigParams,
ListTaskPushNotificationConfigParams,
MessageSendParams,
TaskPushNotificationConfig,
TaskIdParams,
TaskQueryParams,
Task,
} from '../../types.js';
import { A2AStreamEventData, SendMessageResult } from '../client.js';
import { RequestOptions } from '../multitransport-client.js';
import { parseSseStream } from '../../sse_utils.js';
import { Transport, TransportFactory } from './transport.js';
import { ToProto } from '../../types/converters/to_proto.js';
import { FromProto } from '../../types/converters/from_proto.js';
import * as a2a from '../../types/pb/a2a_types.js';
export interface RestTransportOptions {
endpoint: string;
fetchImpl?: typeof fetch;
}
interface RestErrorResponse {
code: number;
message: string;
data?: Record<string, unknown>;
}
export class RestTransport implements Transport {
private readonly customFetchImpl?: typeof fetch;
private readonly endpoint: string;
constructor(options: RestTransportOptions) {
this.endpoint = options.endpoint.replace(/\/+$/, '');
this.customFetchImpl = options.fetchImpl;
}
async getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard> {
const response = await this._sendRequest<undefined, a2a.AgentCard>(
'GET',
'/v1/card',
undefined,
options,
undefined,
a2a.AgentCard
);
return FromProto.agentCard(response);
}
async sendMessage(
params: MessageSendParams,
options?: RequestOptions
): Promise<SendMessageResult> {
const requestBody = ToProto.messageSendParams(params);
const response = await this._sendRequest<a2a.SendMessageRequest, a2a.SendMessageResponse>(
'POST',
'/v1/message:send',
requestBody,
options,
a2a.SendMessageRequest,
a2a.SendMessageResponse
);
return FromProto.sendMessageResult(response);
}
async *sendMessageStream(
params: MessageSendParams,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined> {
const protoParams = ToProto.messageSendParams(params);
const requestBody = a2a.SendMessageRequest.toJSON(protoParams);
yield* this._sendStreamingRequest('/v1/message:stream', requestBody, options);
}
async setTaskPushNotificationConfig(
params: TaskPushNotificationConfig,
options?: RequestOptions
): Promise<TaskPushNotificationConfig> {
const requestBody = ToProto.taskPushNotificationConfig(params);
const response = await this._sendRequest<
a2a.TaskPushNotificationConfig,
a2a.TaskPushNotificationConfig
>(
'POST',
`/v1/tasks/${encodeURIComponent(params.taskId)}/pushNotificationConfigs`,
requestBody,
options,
a2a.TaskPushNotificationConfig,
a2a.TaskPushNotificationConfig
);
return FromProto.taskPushNotificationConfig(response);
}
async getTaskPushNotificationConfig(
params: GetTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<TaskPushNotificationConfig> {
const { pushNotificationConfigId } = params;
if (!pushNotificationConfigId) {
throw new Error(
'pushNotificationConfigId is required for getTaskPushNotificationConfig with REST transport.'
);
}
const response = await this._sendRequest<undefined, a2a.TaskPushNotificationConfig>(
'GET',
`/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs/${encodeURIComponent(pushNotificationConfigId)}`,
undefined,
options,
undefined,
a2a.TaskPushNotificationConfig
);
return FromProto.taskPushNotificationConfig(response);
}
async listTaskPushNotificationConfig(
params: ListTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<TaskPushNotificationConfig[]> {
const response = await this._sendRequest<undefined, a2a.ListTaskPushNotificationConfigResponse>(
'GET',
`/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs`,
undefined,
options,
undefined,
a2a.ListTaskPushNotificationConfigResponse
);
return FromProto.listTaskPushNotificationConfig(response);
}
async deleteTaskPushNotificationConfig(
params: DeleteTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<void> {
await this._sendRequest<undefined, void>(
'DELETE',
`/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs/${encodeURIComponent(params.pushNotificationConfigId)}`,
undefined,
options,
undefined,
undefined
);
}
async getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task> {
const queryParams = new URLSearchParams();
if (params.historyLength !== undefined) {
queryParams.set('historyLength', String(params.historyLength));
}
const queryString = queryParams.toString();
const path = `/v1/tasks/${encodeURIComponent(params.id)}${queryString ? `?${queryString}` : ''}`;
const response = await this._sendRequest<undefined, a2a.Task>(
'GET',
path,
undefined,
options,
undefined,
a2a.Task
);
return FromProto.task(response);
}
async cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task> {
const response = await this._sendRequest<undefined, a2a.Task>(
'POST',
`/v1/tasks/${encodeURIComponent(params.id)}:cancel`,
undefined,
options,
undefined,
a2a.Task
);
return FromProto.task(response);
}
async *resubscribeTask(
params: TaskIdParams,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined> {
yield* this._sendStreamingRequest(
`/v1/tasks/${encodeURIComponent(params.id)}:subscribe`,
undefined,
options
);
}
private _fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
if (this.customFetchImpl) {
return this.customFetchImpl(...args);
}
if (typeof fetch === 'function') {
return fetch(...args);
}
throw new Error(
'A `fetch` implementation was not provided and is not available in the global scope. ' +
'Please provide a `fetchImpl` in the RestTransportOptions.'
);
}
private _buildHeaders(
options: RequestOptions | undefined,
acceptHeader: string = 'application/json'
): HeadersInit {
return {
...options?.serviceParameters,
'Content-Type': 'application/json',
Accept: acceptHeader,
};
}
private async _sendRequest<TRequest, TResponse>(
method: 'GET' | 'POST' | 'DELETE',
path: string,
body: TRequest,
options: RequestOptions | undefined,
requestType: a2a.MessageFns<TRequest> | undefined,
responseType: a2a.MessageFns<TResponse> | undefined
): Promise<TResponse> {
const url = `${this.endpoint}${path}`;
const requestInit: RequestInit = {
method,
headers: this._buildHeaders(options),
signal: options?.signal,
};
if (body !== undefined && method !== 'GET') {
if (!requestType) {
throw new Error(
`Bug: Request body provided for ${method} ${path} but no toJson serializer provided.`
);
}
requestInit.body = JSON.stringify(requestType.toJSON(body));
}
const response = await this._fetch(url, requestInit);
if (!response.ok) {
await this._handleErrorResponse(response, path);
}
if (response.status === 204 || !responseType) {
return undefined as TResponse;
}
const result = await response.json();
return responseType.fromJSON(result);
}
private async _handleErrorResponse(response: Response, path: string): Promise<never> {
let errorBodyText = '(empty or non-JSON response)';
let errorBody: RestErrorResponse | undefined;
try {
errorBodyText = await response.text();
if (errorBodyText) {
errorBody = JSON.parse(errorBodyText);
}
} catch (e) {
throw new Error(
`HTTP error for ${path}! Status: ${response.status} ${response.statusText}. Response: ${errorBodyText}`,
{ cause: e }
);
}
if (errorBody && typeof errorBody.code === 'number') {
throw RestTransport.mapToError(errorBody);
}
throw new Error(
`HTTP error for ${path}! Status: ${response.status} ${response.statusText}. Response: ${errorBodyText}`
);
}
private async *_sendStreamingRequest(
path: string,
body: unknown | undefined,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined> {
const url = `${this.endpoint}${path}`;
const requestInit: RequestInit = {
method: 'POST',
headers: this._buildHeaders(options, 'text/event-stream'),
signal: options?.signal,
};
if (body !== undefined) {
requestInit.body = JSON.stringify(body);
}
const response = await this._fetch(url, requestInit);
if (!response.ok) {
await this._handleErrorResponse(response, path);
}
const contentType = response.headers.get('Content-Type');
if (!contentType?.startsWith('text/event-stream')) {
throw new Error(
`Invalid response Content-Type for SSE stream. Expected 'text/event-stream', got '${contentType}'.`
);
}
for await (const event of parseSseStream(response)) {
if (event.type === 'error') {
const errorData = JSON.parse(event.data);
throw RestTransport.mapToError(errorData);
}
yield this._processSseEventData(event.data);
}
}
private _processSseEventData(jsonData: string): A2AStreamEventData {
if (!jsonData.trim()) {
throw new Error('Attempted to process empty SSE event data.');
}
try {
const response = JSON.parse(jsonData);
const protoResponse = a2a.StreamResponse.fromJSON(response);
return FromProto.messageStreamResult(protoResponse);
} catch (e) {
console.error('Failed to parse SSE event data:', jsonData, e);
throw new Error(
`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${(e instanceof Error && e.message) || 'Unknown error'}`
);
}
}
private static mapToError(error: RestErrorResponse): Error {
switch (error.code) {
case A2A_ERROR_CODE.TASK_NOT_FOUND:
return new TaskNotFoundError(error.message);
case A2A_ERROR_CODE.TASK_NOT_CANCELABLE:
return new TaskNotCancelableError(error.message);
case A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED:
return new PushNotificationNotSupportedError(error.message);
case A2A_ERROR_CODE.UNSUPPORTED_OPERATION:
return new UnsupportedOperationError(error.message);
case A2A_ERROR_CODE.CONTENT_TYPE_NOT_SUPPORTED:
return new ContentTypeNotSupportedError(error.message);
case A2A_ERROR_CODE.INVALID_AGENT_RESPONSE:
return new InvalidAgentResponseError(error.message);
case A2A_ERROR_CODE.AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED:
return new AuthenticatedExtendedCardNotConfiguredError(error.message);
default:
return new Error(
`REST error: ${error.message} (Code: ${error.code})${error.data ? ` Data: ${JSON.stringify(error.data)}` : ''}`
);
}
}
}
export interface RestTransportFactoryOptions {
fetchImpl?: typeof fetch;
}
export class RestTransportFactory implements TransportFactory {
public static readonly name: TransportProtocolName = 'HTTP+JSON';
constructor(private readonly options?: RestTransportFactoryOptions) {}
get protocolName(): string {
return RestTransportFactory.name;
}
async create(url: string, _agentCard: AgentCard): Promise<Transport> {
return new RestTransport({
endpoint: url,
fetchImpl: this.options?.fetchImpl,
});
}
}

View File

@ -1,4 +1,23 @@
// Transport-agnostic errors according to https://a2a-protocol.org/latest/specification/#82-a2a-specific-errors;
// Legacy JSON-RPC error codes.
export const A2A_ERROR_CODE = {
PARSE_ERROR: -32700,
INVALID_REQUEST: -32600,
METHOD_NOT_FOUND: -32601,
INVALID_PARAMS: -32602,
INTERNAL_ERROR: -32603,
TASK_NOT_FOUND: -32001,
TASK_NOT_CANCELABLE: -32002,
PUSH_NOTIFICATION_NOT_SUPPORTED: -32003,
UNSUPPORTED_OPERATION: -32004,
CONTENT_TYPE_NOT_SUPPORTED: -32005,
INVALID_AGENT_RESPONSE: -32006,
AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED: -32007,
} as const;
// Transport-agnostic errors according to https://a2a-protocol.org/v0.3.0/specification/#82-a2a-specific-errors.
// Due to a name conflict with legacy JSON-RPC types reexported from src/index.ts
// below errors are going to be exported via src/client/index.ts to allow usage
// from external transport implementations.
export class TaskNotFoundError extends Error {
constructor(message?: string) {

51
src/grpc/README.md Normal file
View File

@ -0,0 +1,51 @@
# gRPC Service Generation
This directory contains the configuration for generating the gRPC service definitions for the A2A SDK. The generation process uses [Buf](https://buf.build/) and `ts-proto`.
## Prerequisites
Ensure you have the project dependencies installed:
```bash
npm install
```
This project uses `@bufbuild/buf` which is listed in the `devDependencies`.
Add the `a2a_services.proto` files to the `pb` directory.
## Generating Code
To generate the gRPC service definitions, run the following command from this directory (`src/grpc`):
```bash
npx buf generate
```
This will generate the TypeScript files in the `./pb` directory (as configured in `buf.gen.yaml`).
## Post-Processing
**Important:** After running the generation, a post-processing step is **necessary**.
The `buf` generation process produces a file (e.g., `src/grpc/pb/a2a_services.ts`) that contains both the service definitions and the message types. However, to maintain consistency across the SDK and ensure that we are using the canonical types, we must update the generated file to import the actual types from the central types definition file.
**Steps:**
1. Open the generated file (e.g., `src/grpc/pb/a2a_services.ts`).
2. Locate the imports/type definitions section.
3. Replace the local message type definitions or imports with an import from the shared types file:
`src/types/pb/a2a_types.ts`
For example, change:
```typescript
export interface Task { ... }
```
to:
```typescript
import * as pb from "../../types/pb/a2a_types.js";
export type Task = pb.Task;
// ... maps other types similarly
```
This ensures that the gRPC services operate on the same `Task` (and other) interfaces as the rest of the application, avoiding type mismatch errors.

18
src/grpc/buf.gen.yaml Normal file
View File

@ -0,0 +1,18 @@
# buf generate
# Configuration for the buf generate command
# Uses remote plugins, no separate install required.
version: v2
inputs:
- directory: ./pb
plugins:
- remote: buf.build/community/stephenh-ts-proto:v2.6.1
opt:
- oneof=unions-value
- importSuffix=.js
- outputServices=grpc-js
- env=node
- esModuleInterop=true
- outputJsonMethods=false
- outputPartialMethods=false
- useDate=string
out: ./pb

6
src/grpc/buf.lock Normal file
View File

@ -0,0 +1,6 @@
# Generated by buf. DO NOT EDIT.
version: v2
deps:
- name: buf.build/googleapis/googleapis
commit: 004180b77378443887d3b55cabc00384
digest: b5:e8f475fe3330f31f5fd86ac689093bcd274e19611a09db91f41d637cb9197881ce89882b94d13a58738e53c91c6e4bae7dc1feba85f590164c975a89e25115dc

6
src/grpc/buf.yaml Normal file
View File

@ -0,0 +1,6 @@
version: v2
modules:
- path: ./pb
deps:
# Common Protobuf types.
- buf.build/googleapis/googleapis

3627
src/grpc/pb/a2a_services.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
// versions:
// protoc-gen-ts_proto v2.6.1
// protoc unknown
// source: google/api/annotations.proto
/* eslint-disable */
export const protobufPackage = "google.api";

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,83 @@
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
// versions:
// protoc-gen-ts_proto v2.6.1
// protoc unknown
// source: google/api/field_behavior.proto
/* eslint-disable */
export const protobufPackage = "google.api";
/**
* An indicator of the behavior of a given field (for example, that a field
* is required in requests, or given as output but ignored as input).
* This **does not** change the behavior in protocol buffers itself; it only
* denotes the behavior and may affect how API tooling handles the field.
*
* Note: This enum **may** receive new values in the future.
*/
export enum FieldBehavior {
/** FIELD_BEHAVIOR_UNSPECIFIED - Conventional default for enums. Do not use this. */
FIELD_BEHAVIOR_UNSPECIFIED = 0,
/**
* OPTIONAL - Specifically denotes a field as optional.
* While all fields in protocol buffers are optional, this may be specified
* for emphasis if appropriate.
*/
OPTIONAL = 1,
/**
* REQUIRED - Denotes a field as required.
* This indicates that the field **must** be provided as part of the request,
* and failure to do so will cause an error (usually `INVALID_ARGUMENT`).
*/
REQUIRED = 2,
/**
* OUTPUT_ONLY - Denotes a field as output only.
* This indicates that the field is provided in responses, but including the
* field in a request does nothing (the server *must* ignore it and
* *must not* throw an error as a result of the field's presence).
*/
OUTPUT_ONLY = 3,
/**
* INPUT_ONLY - Denotes a field as input only.
* This indicates that the field is provided in requests, and the
* corresponding field is not included in output.
*/
INPUT_ONLY = 4,
/**
* IMMUTABLE - Denotes a field as immutable.
* This indicates that the field may be set once in a request to create a
* resource, but may not be changed thereafter.
*/
IMMUTABLE = 5,
/**
* UNORDERED_LIST - Denotes that a (repeated) field is an unordered list.
* This indicates that the service may provide the elements of the list
* in any arbitrary order, rather than the order the user originally
* provided. Additionally, the list's order may or may not be stable.
*/
UNORDERED_LIST = 6,
/**
* NON_EMPTY_DEFAULT - Denotes that this field returns a non-empty default value if not set.
* This indicates that if the user provides the empty value in a request,
* a non-empty value will be returned. The user will not be aware of what
* non-empty value to expect.
*/
NON_EMPTY_DEFAULT = 7,
/**
* IDENTIFIER - Denotes that the field in a resource (a message annotated with
* google.api.resource) is used in the resource name to uniquely identify the
* resource. For AIP-compliant APIs, this should only be applied to the
* `name` field on the resource.
*
* This behavior should not be applied to references to other resources within
* the message.
*
* The identifier field of resources often have different field behavior
* depending on the request it is embedded in (e.g. for Create methods name
* is optional and unused, while for Update methods it is required). Instead
* of method-specific annotations, only `IDENTIFIER` is required.
*/
IDENTIFIER = 8,
UNRECOGNIZED = -1,
}

View File

@ -0,0 +1,612 @@
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
// versions:
// protoc-gen-ts_proto v2.6.1
// protoc unknown
// source: google/api/http.proto
/* eslint-disable */
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
export const protobufPackage = "google.api";
/**
* Defines the HTTP configuration for an API service. It contains a list of
* [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
* to one or more HTTP REST API methods.
*/
export interface Http {
/**
* A list of HTTP configuration rules that apply to individual API methods.
*
* **NOTE:** All service configuration rules follow "last one wins" order.
*/
rules: HttpRule[];
/**
* When set to true, URL path parameters will be fully URI-decoded except in
* cases of single segment matches in reserved expansion, where "%2F" will be
* left encoded.
*
* The default behavior is to not decode RFC 6570 reserved characters in multi
* segment matches.
*/
fullyDecodeReservedExpansion: boolean;
}
/**
* gRPC Transcoding
*
* gRPC Transcoding is a feature for mapping between a gRPC method and one or
* more HTTP REST endpoints. It allows developers to build a single API service
* that supports both gRPC APIs and REST APIs. Many systems, including [Google
* APIs](https://github.com/googleapis/googleapis),
* [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC
* Gateway](https://github.com/grpc-ecosystem/grpc-gateway),
* and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature
* and use it for large scale production services.
*
* `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies
* how different portions of the gRPC request message are mapped to the URL
* path, URL query parameters, and HTTP request body. It also controls how the
* gRPC response message is mapped to the HTTP response body. `HttpRule` is
* typically specified as an `google.api.http` annotation on the gRPC method.
*
* Each mapping specifies a URL path template and an HTTP method. The path
* template may refer to one or more fields in the gRPC request message, as long
* as each field is a non-repeated field with a primitive (non-message) type.
* The path template controls how fields of the request message are mapped to
* the URL path.
*
* Example:
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http) = {
* get: "/v1/{name=messages/*}"
* };
* }
* }
* message GetMessageRequest {
* string name = 1; // Mapped to URL path.
* }
* message Message {
* string text = 1; // The resource content.
* }
*
* This enables an HTTP REST to gRPC mapping as below:
*
* - HTTP: `GET /v1/messages/123456`
* - gRPC: `GetMessage(name: "messages/123456")`
*
* Any fields in the request message which are not bound by the path template
* automatically become HTTP query parameters if there is no HTTP request body.
* For example:
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http) = {
* get:"/v1/messages/{message_id}"
* };
* }
* }
* message GetMessageRequest {
* message SubMessage {
* string subfield = 1;
* }
* string message_id = 1; // Mapped to URL path.
* int64 revision = 2; // Mapped to URL query parameter `revision`.
* SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`.
* }
*
* This enables a HTTP JSON to RPC mapping as below:
*
* - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo`
* - gRPC: `GetMessage(message_id: "123456" revision: 2 sub:
* SubMessage(subfield: "foo"))`
*
* Note that fields which are mapped to URL query parameters must have a
* primitive type or a repeated primitive type or a non-repeated message type.
* In the case of a repeated type, the parameter can be repeated in the URL
* as `...?param=A&param=B`. In the case of a message type, each field of the
* message is mapped to a separate parameter, such as
* `...?foo.a=A&foo.b=B&foo.c=C`.
*
* For HTTP methods that allow a request body, the `body` field
* specifies the mapping. Consider a REST update method on the
* message resource collection:
*
* service Messaging {
* rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
* option (google.api.http) = {
* patch: "/v1/messages/{message_id}"
* body: "message"
* };
* }
* }
* message UpdateMessageRequest {
* string message_id = 1; // mapped to the URL
* Message message = 2; // mapped to the body
* }
*
* The following HTTP JSON to RPC mapping is enabled, where the
* representation of the JSON in the request body is determined by
* protos JSON encoding:
*
* - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }`
* - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })`
*
* The special name `*` can be used in the body mapping to define that
* every field not bound by the path template should be mapped to the
* request body. This enables the following alternative definition of
* the update method:
*
* service Messaging {
* rpc UpdateMessage(Message) returns (Message) {
* option (google.api.http) = {
* patch: "/v1/messages/{message_id}"
* body: "*"
* };
* }
* }
* message Message {
* string message_id = 1;
* string text = 2;
* }
*
* The following HTTP JSON to RPC mapping is enabled:
*
* - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }`
* - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")`
*
* Note that when using `*` in the body mapping, it is not possible to
* have HTTP parameters, as all fields not bound by the path end in
* the body. This makes this option more rarely used in practice when
* defining REST APIs. The common usage of `*` is in custom methods
* which don't use the URL at all for transferring data.
*
* It is possible to define multiple HTTP methods for one RPC by using
* the `additional_bindings` option. Example:
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http) = {
* get: "/v1/messages/{message_id}"
* additional_bindings {
* get: "/v1/users/{user_id}/messages/{message_id}"
* }
* };
* }
* }
* message GetMessageRequest {
* string message_id = 1;
* string user_id = 2;
* }
*
* This enables the following two alternative HTTP JSON to RPC mappings:
*
* - HTTP: `GET /v1/messages/123456`
* - gRPC: `GetMessage(message_id: "123456")`
*
* - HTTP: `GET /v1/users/me/messages/123456`
* - gRPC: `GetMessage(user_id: "me" message_id: "123456")`
*
* Rules for HTTP mapping
*
* 1. Leaf request fields (recursive expansion nested messages in the request
* message) are classified into three categories:
* - Fields referred by the path template. They are passed via the URL path.
* - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They
* are passed via the HTTP
* request body.
* - All other fields are passed via the URL query parameters, and the
* parameter name is the field path in the request message. A repeated
* field can be represented as multiple query parameters under the same
* name.
* 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL
* query parameter, all fields
* are passed via URL path and HTTP request body.
* 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP
* request body, all
* fields are passed via URL path and URL query parameters.
*
* Path template syntax
*
* Template = "/" Segments [ Verb ] ;
* Segments = Segment { "/" Segment } ;
* Segment = "*" | "**" | LITERAL | Variable ;
* Variable = "{" FieldPath [ "=" Segments ] "}" ;
* FieldPath = IDENT { "." IDENT } ;
* Verb = ":" LITERAL ;
*
* The syntax `*` matches a single URL path segment. The syntax `**` matches
* zero or more URL path segments, which must be the last part of the URL path
* except the `Verb`.
*
* The syntax `Variable` matches part of the URL path as specified by its
* template. A variable template must not contain other variables. If a variable
* matches a single path segment, its template may be omitted, e.g. `{var}`
* is equivalent to `{var=*}`.
*
* The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL`
* contains any reserved character, such characters should be percent-encoded
* before the matching.
*
* If a variable contains exactly one path segment, such as `"{var}"` or
* `"{var=*}"`, when such a variable is expanded into a URL path on the client
* side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The
* server side does the reverse decoding. Such variables show up in the
* [Discovery
* Document](https://developers.google.com/discovery/v1/reference/apis) as
* `{var}`.
*
* If a variable contains multiple path segments, such as `"{var=foo/*}"`
* or `"{var=**}"`, when such a variable is expanded into a URL path on the
* client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded.
* The server side does the reverse decoding, except "%2F" and "%2f" are left
* unchanged. Such variables show up in the
* [Discovery
* Document](https://developers.google.com/discovery/v1/reference/apis) as
* `{+var}`.
*
* Using gRPC API Service Configuration
*
* gRPC API Service Configuration (service config) is a configuration language
* for configuring a gRPC service to become a user-facing product. The
* service config is simply the YAML representation of the `google.api.Service`
* proto message.
*
* As an alternative to annotating your proto file, you can configure gRPC
* transcoding in your service config YAML files. You do this by specifying a
* `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same
* effect as the proto annotation. This can be particularly useful if you
* have a proto that is reused in multiple services. Note that any transcoding
* specified in the service config will override any matching transcoding
* configuration in the proto.
*
* The following example selects a gRPC method and applies an `HttpRule` to it:
*
* http:
* rules:
* - selector: example.v1.Messaging.GetMessage
* get: /v1/messages/{message_id}/{sub.subfield}
*
* Special notes
*
* When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the
* proto to JSON conversion must follow the [proto3
* specification](https://developers.google.com/protocol-buffers/docs/proto3#json).
*
* While the single segment variable follows the semantics of
* [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String
* Expansion, the multi segment variable **does not** follow RFC 6570 Section
* 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion
* does not expand special characters like `?` and `#`, which would lead
* to invalid URLs. As the result, gRPC Transcoding uses a custom encoding
* for multi segment variables.
*
* The path variables **must not** refer to any repeated or mapped field,
* because client libraries are not capable of handling such variable expansion.
*
* The path variables **must not** capture the leading "/" character. The reason
* is that the most common use case "{var}" does not capture the leading "/"
* character. For consistency, all path variables must share the same behavior.
*
* Repeated message fields must not be mapped to URL query parameters, because
* no client library can support such complicated mapping.
*
* If an API needs to use a JSON array for request or response body, it can map
* the request or response body to a repeated field. However, some gRPC
* Transcoding implementations may not support this feature.
*/
export interface HttpRule {
/**
* Selects a method to which this rule applies.
*
* Refer to [selector][google.api.DocumentationRule.selector] for syntax
* details.
*/
selector: string;
/**
* Determines the URL pattern is matched by this rules. This pattern can be
* used with any of the {get|put|post|delete|patch} methods. A custom method
* can be defined using the 'custom' field.
*/
pattern?:
| //
/**
* Maps to HTTP GET. Used for listing and getting information about
* resources.
*/
{ $case: "get"; value: string }
| //
/** Maps to HTTP PUT. Used for replacing a resource. */
{ $case: "put"; value: string }
| //
/** Maps to HTTP POST. Used for creating a resource or performing an action. */
{ $case: "post"; value: string }
| //
/** Maps to HTTP DELETE. Used for deleting a resource. */
{ $case: "delete"; value: string }
| //
/** Maps to HTTP PATCH. Used for updating a resource. */
{ $case: "patch"; value: string }
| //
/**
* The custom pattern is used for specifying an HTTP method that is not
* included in the `pattern` field, such as HEAD, or "*" to leave the
* HTTP method unspecified for this rule. The wild-card rule is useful
* for services that provide content to Web (HTML) clients.
*/
{ $case: "custom"; value: CustomHttpPattern }
| undefined;
/**
* The name of the request field whose value is mapped to the HTTP request
* body, or `*` for mapping all request fields not captured by the path
* pattern to the HTTP body, or omitted for not having any HTTP request body.
*
* NOTE: the referred field must be present at the top-level of the request
* message type.
*/
body: string;
/**
* Optional. The name of the response field whose value is mapped to the HTTP
* response body. When omitted, the entire response message will be used
* as the HTTP response body.
*
* NOTE: The referred field must be present at the top-level of the response
* message type.
*/
responseBody: string;
/**
* Additional HTTP bindings for the selector. Nested bindings must
* not contain an `additional_bindings` field themselves (that is,
* the nesting may only be one level deep).
*/
additionalBindings: HttpRule[];
}
/** A custom pattern is used for defining custom HTTP verb. */
export interface CustomHttpPattern {
/** The name of this custom HTTP verb. */
kind: string;
/** The path matched by this custom verb. */
path: string;
}
function createBaseHttp(): Http {
return { rules: [], fullyDecodeReservedExpansion: false };
}
export const Http: MessageFns<Http> = {
encode(message: Http, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
for (const v of message.rules) {
HttpRule.encode(v!, writer.uint32(10).fork()).join();
}
if (message.fullyDecodeReservedExpansion !== false) {
writer.uint32(16).bool(message.fullyDecodeReservedExpansion);
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): Http {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseHttp();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (tag !== 10) {
break;
}
message.rules.push(HttpRule.decode(reader, reader.uint32()));
continue;
}
case 2: {
if (tag !== 16) {
break;
}
message.fullyDecodeReservedExpansion = reader.bool();
continue;
}
}
if ((tag & 7) === 4 || tag === 0) {
break;
}
reader.skip(tag & 7);
}
return message;
},
};
function createBaseHttpRule(): HttpRule {
return { selector: "", pattern: undefined, body: "", responseBody: "", additionalBindings: [] };
}
export const HttpRule: MessageFns<HttpRule> = {
encode(message: HttpRule, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
if (message.selector !== "") {
writer.uint32(10).string(message.selector);
}
switch (message.pattern?.$case) {
case "get":
writer.uint32(18).string(message.pattern.value);
break;
case "put":
writer.uint32(26).string(message.pattern.value);
break;
case "post":
writer.uint32(34).string(message.pattern.value);
break;
case "delete":
writer.uint32(42).string(message.pattern.value);
break;
case "patch":
writer.uint32(50).string(message.pattern.value);
break;
case "custom":
CustomHttpPattern.encode(message.pattern.value, writer.uint32(66).fork()).join();
break;
}
if (message.body !== "") {
writer.uint32(58).string(message.body);
}
if (message.responseBody !== "") {
writer.uint32(98).string(message.responseBody);
}
for (const v of message.additionalBindings) {
HttpRule.encode(v!, writer.uint32(90).fork()).join();
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): HttpRule {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseHttpRule();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (tag !== 10) {
break;
}
message.selector = reader.string();
continue;
}
case 2: {
if (tag !== 18) {
break;
}
message.pattern = { $case: "get", value: reader.string() };
continue;
}
case 3: {
if (tag !== 26) {
break;
}
message.pattern = { $case: "put", value: reader.string() };
continue;
}
case 4: {
if (tag !== 34) {
break;
}
message.pattern = { $case: "post", value: reader.string() };
continue;
}
case 5: {
if (tag !== 42) {
break;
}
message.pattern = { $case: "delete", value: reader.string() };
continue;
}
case 6: {
if (tag !== 50) {
break;
}
message.pattern = { $case: "patch", value: reader.string() };
continue;
}
case 8: {
if (tag !== 66) {
break;
}
message.pattern = { $case: "custom", value: CustomHttpPattern.decode(reader, reader.uint32()) };
continue;
}
case 7: {
if (tag !== 58) {
break;
}
message.body = reader.string();
continue;
}
case 12: {
if (tag !== 98) {
break;
}
message.responseBody = reader.string();
continue;
}
case 11: {
if (tag !== 90) {
break;
}
message.additionalBindings.push(HttpRule.decode(reader, reader.uint32()));
continue;
}
}
if ((tag & 7) === 4 || tag === 0) {
break;
}
reader.skip(tag & 7);
}
return message;
},
};
function createBaseCustomHttpPattern(): CustomHttpPattern {
return { kind: "", path: "" };
}
export const CustomHttpPattern: MessageFns<CustomHttpPattern> = {
encode(message: CustomHttpPattern, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
if (message.kind !== "") {
writer.uint32(10).string(message.kind);
}
if (message.path !== "") {
writer.uint32(18).string(message.path);
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): CustomHttpPattern {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseCustomHttpPattern();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (tag !== 10) {
break;
}
message.kind = reader.string();
continue;
}
case 2: {
if (tag !== 18) {
break;
}
message.path = reader.string();
continue;
}
}
if ((tag & 7) === 4 || tag === 0) {
break;
}
reader.skip(tag & 7);
}
return message;
},
};
export interface MessageFns<T> {
encode(message: T, writer?: BinaryWriter): BinaryWriter;
decode(input: BinaryReader | Uint8Array, length?: number): T;
}

View File

@ -0,0 +1,64 @@
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
// versions:
// protoc-gen-ts_proto v2.6.1
// protoc unknown
// source: google/api/launch_stage.proto
/* eslint-disable */
export const protobufPackage = "google.api";
/**
* The launch stage as defined by [Google Cloud Platform
* Launch Stages](https://cloud.google.com/terms/launch-stages).
*/
export enum LaunchStage {
/** LAUNCH_STAGE_UNSPECIFIED - Do not use this default value. */
LAUNCH_STAGE_UNSPECIFIED = 0,
/** UNIMPLEMENTED - The feature is not yet implemented. Users can not use it. */
UNIMPLEMENTED = 6,
/** PRELAUNCH - Prelaunch features are hidden from users and are only visible internally. */
PRELAUNCH = 7,
/**
* EARLY_ACCESS - Early Access features are limited to a closed group of testers. To use
* these features, you must sign up in advance and sign a Trusted Tester
* agreement (which includes confidentiality provisions). These features may
* be unstable, changed in backward-incompatible ways, and are not
* guaranteed to be released.
*/
EARLY_ACCESS = 1,
/**
* ALPHA - Alpha is a limited availability test for releases before they are cleared
* for widespread use. By Alpha, all significant design issues are resolved
* and we are in the process of verifying functionality. Alpha customers
* need to apply for access, agree to applicable terms, and have their
* projects allowlisted. Alpha releases don't have to be feature complete,
* no SLAs are provided, and there are no technical support obligations, but
* they will be far enough along that customers can actually use them in
* test environments or for limited-use tests -- just like they would in
* normal production cases.
*/
ALPHA = 2,
/**
* BETA - Beta is the point at which we are ready to open a release for any
* customer to use. There are no SLA or technical support obligations in a
* Beta release. Products will be complete from a feature perspective, but
* may have some open outstanding issues. Beta releases are suitable for
* limited production use cases.
*/
BETA = 3,
/**
* GA - GA features are open to all developers and are considered stable and
* fully qualified for production use.
*/
GA = 4,
/**
* DEPRECATED - Deprecated features are scheduled to be shut down and removed. For more
* information, see the "Deprecation Policy" section of our [Terms of
* Service](https://cloud.google.com/terms/)
* and the [Google Cloud Platform Subject to the Deprecation
* Policy](https://cloud.google.com/terms/deprecation) documentation.
*/
DEPRECATED = 5,
UNRECOGNIZED = -1,
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,152 @@
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
// versions:
// protoc-gen-ts_proto v2.6.1
// protoc unknown
// source: google/protobuf/duration.proto
/* eslint-disable */
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
export const protobufPackage = "google.protobuf";
/**
* A Duration represents a signed, fixed-length span of time represented
* as a count of seconds and fractions of seconds at nanosecond
* resolution. It is independent of any calendar and concepts like "day"
* or "month". It is related to Timestamp in that the difference between
* two Timestamp values is a Duration and it can be added or subtracted
* from a Timestamp. Range is approximately +-10,000 years.
*
* # Examples
*
* Example 1: Compute Duration from two Timestamps in pseudo code.
*
* Timestamp start = ...;
* Timestamp end = ...;
* Duration duration = ...;
*
* duration.seconds = end.seconds - start.seconds;
* duration.nanos = end.nanos - start.nanos;
*
* if (duration.seconds < 0 && duration.nanos > 0) {
* duration.seconds += 1;
* duration.nanos -= 1000000000;
* } else if (duration.seconds > 0 && duration.nanos < 0) {
* duration.seconds -= 1;
* duration.nanos += 1000000000;
* }
*
* Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
*
* Timestamp start = ...;
* Duration duration = ...;
* Timestamp end = ...;
*
* end.seconds = start.seconds + duration.seconds;
* end.nanos = start.nanos + duration.nanos;
*
* if (end.nanos < 0) {
* end.seconds -= 1;
* end.nanos += 1000000000;
* } else if (end.nanos >= 1000000000) {
* end.seconds += 1;
* end.nanos -= 1000000000;
* }
*
* Example 3: Compute Duration from datetime.timedelta in Python.
*
* td = datetime.timedelta(days=3, minutes=10)
* duration = Duration()
* duration.FromTimedelta(td)
*
* # JSON Mapping
*
* In JSON format, the Duration type is encoded as a string rather than an
* object, where the string ends in the suffix "s" (indicating seconds) and
* is preceded by the number of seconds, with nanoseconds expressed as
* fractional seconds. For example, 3 seconds with 0 nanoseconds should be
* encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
* be expressed in JSON format as "3.000000001s", and 3 seconds and 1
* microsecond should be expressed in JSON format as "3.000001s".
*/
export interface Duration {
/**
* Signed seconds of the span of time. Must be from -315,576,000,000
* to +315,576,000,000 inclusive. Note: these bounds are computed from:
* 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
*/
seconds: number;
/**
* Signed fractions of a second at nanosecond resolution of the span
* of time. Durations less than one second are represented with a 0
* `seconds` field and a positive or negative `nanos` field. For durations
* of one second or more, a non-zero value for the `nanos` field must be
* of the same sign as the `seconds` field. Must be from -999,999,999
* to +999,999,999 inclusive.
*/
nanos: number;
}
function createBaseDuration(): Duration {
return { seconds: 0, nanos: 0 };
}
export const Duration: MessageFns<Duration> = {
encode(message: Duration, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
if (message.seconds !== 0) {
writer.uint32(8).int64(message.seconds);
}
if (message.nanos !== 0) {
writer.uint32(16).int32(message.nanos);
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): Duration {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseDuration();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (tag !== 8) {
break;
}
message.seconds = longToNumber(reader.int64());
continue;
}
case 2: {
if (tag !== 16) {
break;
}
message.nanos = reader.int32();
continue;
}
}
if ((tag & 7) === 4 || tag === 0) {
break;
}
reader.skip(tag & 7);
}
return message;
},
};
function longToNumber(int64: { toString(): string }): number {
const num = globalThis.Number(int64.toString());
if (num > globalThis.Number.MAX_SAFE_INTEGER) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
if (num < globalThis.Number.MIN_SAFE_INTEGER) {
throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
}
return num;
}
export interface MessageFns<T> {
encode(message: T, writer?: BinaryWriter): BinaryWriter;
decode(input: BinaryReader | Uint8Array, length?: number): T;
}

View File

@ -0,0 +1,53 @@
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
// versions:
// protoc-gen-ts_proto v2.6.1
// protoc unknown
// source: google/protobuf/empty.proto
/* eslint-disable */
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
export const protobufPackage = "google.protobuf";
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance:
*
* service Foo {
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
* }
*/
export interface Empty {
}
function createBaseEmpty(): Empty {
return {};
}
export const Empty: MessageFns<Empty> = {
encode(_: Empty, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): Empty {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseEmpty();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
}
if ((tag & 7) === 4 || tag === 0) {
break;
}
reader.skip(tag & 7);
}
return message;
},
};
export interface MessageFns<T> {
encode(message: T, writer?: BinaryWriter): BinaryWriter;
decode(input: BinaryReader | Uint8Array, length?: number): T;
}

View File

@ -0,0 +1,384 @@
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
// versions:
// protoc-gen-ts_proto v2.6.1
// protoc unknown
// source: google/protobuf/struct.proto
/* eslint-disable */
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
export const protobufPackage = "google.protobuf";
/**
* `NullValue` is a singleton enumeration to represent the null value for the
* `Value` type union.
*
* The JSON representation for `NullValue` is JSON `null`.
*/
export enum NullValue {
/** NULL_VALUE - Null value. */
NULL_VALUE = 0,
UNRECOGNIZED = -1,
}
/**
* `Struct` represents a structured data value, consisting of fields
* which map to dynamically typed values. In some languages, `Struct`
* might be supported by a native representation. For example, in
* scripting languages like JS a struct is represented as an
* object. The details of that representation are described together
* with the proto support for the language.
*
* The JSON representation for `Struct` is JSON object.
*/
export interface Struct {
/** Unordered map of dynamically typed values. */
fields: { [key: string]: any | undefined };
}
export interface Struct_FieldsEntry {
key: string;
value: any | undefined;
}
/**
* `Value` represents a dynamically typed value which can be either
* null, a number, a string, a boolean, a recursive struct value, or a
* list of values. A producer of value is expected to set one of these
* variants. Absence of any variant indicates an error.
*
* The JSON representation for `Value` is JSON value.
*/
export interface Value {
/** The kind of value. */
kind?:
| //
/** Represents a null value. */
{ $case: "nullValue"; value: NullValue }
| //
/** Represents a double value. */
{ $case: "numberValue"; value: number }
| //
/** Represents a string value. */
{ $case: "stringValue"; value: string }
| //
/** Represents a boolean value. */
{ $case: "boolValue"; value: boolean }
| //
/** Represents a structured value. */
{ $case: "structValue"; value: { [key: string]: any } | undefined }
| //
/** Represents a repeated `Value`. */
{ $case: "listValue"; value: Array<any> | undefined }
| undefined;
}
/**
* `ListValue` is a wrapper around a repeated field of values.
*
* The JSON representation for `ListValue` is JSON array.
*/
export interface ListValue {
/** Repeated field of dynamically typed values. */
values: any[];
}
function createBaseStruct(): Struct {
return { fields: {} };
}
export const Struct: MessageFns<Struct> & StructWrapperFns = {
encode(message: Struct, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
Object.entries(message.fields).forEach(([key, value]) => {
if (value !== undefined) {
Struct_FieldsEntry.encode({ key: key as any, value }, writer.uint32(10).fork()).join();
}
});
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): Struct {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseStruct();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (tag !== 10) {
break;
}
const entry1 = Struct_FieldsEntry.decode(reader, reader.uint32());
if (entry1.value !== undefined) {
message.fields[entry1.key] = entry1.value;
}
continue;
}
}
if ((tag & 7) === 4 || tag === 0) {
break;
}
reader.skip(tag & 7);
}
return message;
},
wrap(object: { [key: string]: any } | undefined): Struct {
const struct = createBaseStruct();
if (object !== undefined) {
for (const key of Object.keys(object)) {
struct.fields[key] = object[key];
}
}
return struct;
},
unwrap(message: Struct): { [key: string]: any } {
const object: { [key: string]: any } = {};
if (message.fields) {
for (const key of Object.keys(message.fields)) {
object[key] = message.fields[key];
}
}
return object;
},
};
function createBaseStruct_FieldsEntry(): Struct_FieldsEntry {
return { key: "", value: undefined };
}
export const Struct_FieldsEntry: MessageFns<Struct_FieldsEntry> = {
encode(message: Struct_FieldsEntry, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
Value.encode(Value.wrap(message.value), writer.uint32(18).fork()).join();
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): Struct_FieldsEntry {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseStruct_FieldsEntry();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (tag !== 10) {
break;
}
message.key = reader.string();
continue;
}
case 2: {
if (tag !== 18) {
break;
}
message.value = Value.unwrap(Value.decode(reader, reader.uint32()));
continue;
}
}
if ((tag & 7) === 4 || tag === 0) {
break;
}
reader.skip(tag & 7);
}
return message;
},
};
function createBaseValue(): Value {
return { kind: undefined };
}
export const Value: MessageFns<Value> & AnyValueWrapperFns = {
encode(message: Value, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
switch (message.kind?.$case) {
case "nullValue":
writer.uint32(8).int32(message.kind.value);
break;
case "numberValue":
writer.uint32(17).double(message.kind.value);
break;
case "stringValue":
writer.uint32(26).string(message.kind.value);
break;
case "boolValue":
writer.uint32(32).bool(message.kind.value);
break;
case "structValue":
Struct.encode(Struct.wrap(message.kind.value), writer.uint32(42).fork()).join();
break;
case "listValue":
ListValue.encode(ListValue.wrap(message.kind.value), writer.uint32(50).fork()).join();
break;
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): Value {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseValue();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (tag !== 8) {
break;
}
message.kind = { $case: "nullValue", value: reader.int32() as any };
continue;
}
case 2: {
if (tag !== 17) {
break;
}
message.kind = { $case: "numberValue", value: reader.double() };
continue;
}
case 3: {
if (tag !== 26) {
break;
}
message.kind = { $case: "stringValue", value: reader.string() };
continue;
}
case 4: {
if (tag !== 32) {
break;
}
message.kind = { $case: "boolValue", value: reader.bool() };
continue;
}
case 5: {
if (tag !== 42) {
break;
}
message.kind = { $case: "structValue", value: Struct.unwrap(Struct.decode(reader, reader.uint32())) };
continue;
}
case 6: {
if (tag !== 50) {
break;
}
message.kind = { $case: "listValue", value: ListValue.unwrap(ListValue.decode(reader, reader.uint32())) };
continue;
}
}
if ((tag & 7) === 4 || tag === 0) {
break;
}
reader.skip(tag & 7);
}
return message;
},
wrap(value: any): Value {
const result = createBaseValue();
if (value === null) {
result.kind = { $case: "nullValue", value };
} else if (typeof value === "boolean") {
result.kind = { $case: "boolValue", value };
} else if (typeof value === "number") {
result.kind = { $case: "numberValue", value };
} else if (typeof value === "string") {
result.kind = { $case: "stringValue", value };
} else if (globalThis.Array.isArray(value)) {
result.kind = { $case: "listValue", value };
} else if (typeof value === "object") {
result.kind = { $case: "structValue", value };
} else if (typeof value !== "undefined") {
throw new globalThis.Error("Unsupported any value type: " + typeof value);
}
return result;
},
unwrap(message: Value): string | number | boolean | Object | null | Array<any> | undefined {
return message.kind?.value;
},
};
function createBaseListValue(): ListValue {
return { values: [] };
}
export const ListValue: MessageFns<ListValue> & ListValueWrapperFns = {
encode(message: ListValue, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
for (const v of message.values) {
Value.encode(Value.wrap(v!), writer.uint32(10).fork()).join();
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): ListValue {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseListValue();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (tag !== 10) {
break;
}
message.values.push(Value.unwrap(Value.decode(reader, reader.uint32())));
continue;
}
}
if ((tag & 7) === 4 || tag === 0) {
break;
}
reader.skip(tag & 7);
}
return message;
},
wrap(array: Array<any> | undefined): ListValue {
const result = createBaseListValue();
result.values = array ?? [];
return result;
},
unwrap(message: ListValue): Array<any> {
if (message?.hasOwnProperty("values") && globalThis.Array.isArray(message.values)) {
return message.values;
} else {
return message as any;
}
},
};
export interface MessageFns<T> {
encode(message: T, writer?: BinaryWriter): BinaryWriter;
decode(input: BinaryReader | Uint8Array, length?: number): T;
}
export interface StructWrapperFns {
wrap(object: { [key: string]: any } | undefined): Struct;
unwrap(message: Struct): { [key: string]: any };
}
export interface AnyValueWrapperFns {
wrap(value: any): Value;
unwrap(message: any): string | number | boolean | Object | null | Array<any> | undefined;
}
export interface ListValueWrapperFns {
wrap(array: Array<any> | undefined): ListValue;
unwrap(message: ListValue): Array<any>;
}

View File

@ -0,0 +1,181 @@
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
// versions:
// protoc-gen-ts_proto v2.6.1
// protoc unknown
// source: google/protobuf/timestamp.proto
/* eslint-disable */
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
export const protobufPackage = "google.protobuf";
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
* Example 5: Compute Timestamp from Java `Instant.now()`.
*
* Instant now = Instant.now();
*
* Timestamp timestamp =
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
* .setNanos(now.getNano()).build();
*
* Example 6: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A proto3 JSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a proto3 JSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
* http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
* ) to obtain a formatter capable of generating timestamps in this format.
*/
export interface Timestamp {
/**
* Represents seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
*/
seconds: number;
/**
* Non-negative fractions of a second at nanosecond resolution. Negative
* second values with fractions must still have non-negative nanos values
* that count forward in time. Must be from 0 to 999,999,999
* inclusive.
*/
nanos: number;
}
function createBaseTimestamp(): Timestamp {
return { seconds: 0, nanos: 0 };
}
export const Timestamp: MessageFns<Timestamp> = {
encode(message: Timestamp, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
if (message.seconds !== 0) {
writer.uint32(8).int64(message.seconds);
}
if (message.nanos !== 0) {
writer.uint32(16).int32(message.nanos);
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): Timestamp {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseTimestamp();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (tag !== 8) {
break;
}
message.seconds = longToNumber(reader.int64());
continue;
}
case 2: {
if (tag !== 16) {
break;
}
message.nanos = reader.int32();
continue;
}
}
if ((tag & 7) === 4 || tag === 0) {
break;
}
reader.skip(tag & 7);
}
return message;
},
};
function longToNumber(int64: { toString(): string }): number {
const num = globalThis.Number(int64.toString());
if (num > globalThis.Number.MAX_SAFE_INTEGER) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
if (num < globalThis.Number.MIN_SAFE_INTEGER) {
throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
}
return num;
}
export interface MessageFns<T> {
encode(message: T, writer?: BinaryWriter): BinaryWriter;
decode(input: BinaryReader | Uint8Array, length?: number): T;
}

View File

@ -9,6 +9,9 @@ import {
TextPart,
Message,
AGENT_CARD_PATH,
TaskArtifactUpdateEvent,
Artifact,
Part,
} from '../../../index.js';
import {
InMemoryTaskStore,
@ -192,25 +195,44 @@ class MovieAgentExecutor implements AgentExecutor {
finalA2AState = 'completed'; // Default if LLM deviates
}
// 5. Publish final task status update
// 5. Publish artifact with the result
const parts: Part[] = [{ kind: 'text', text: agentReplyText || 'Completed.' }];
const artifactId = uuidv4();
const resultArtifact: Artifact = {
artifactId: artifactId,
name: 'Result',
description: 'The result of the movie agent.',
parts: parts,
};
const artifactUpdate: TaskArtifactUpdateEvent = {
kind: 'artifact-update',
taskId: taskId,
contextId: contextId,
artifact: resultArtifact,
lastChunk: true,
};
eventBus.publish(artifactUpdate);
// 6. Update local history context (internal only)
const agentMessage: Message = {
kind: 'message',
role: 'agent',
messageId: uuidv4(),
parts: [{ kind: 'text', text: agentReplyText || 'Completed.' }], // Ensure some text
parts: parts,
taskId: taskId,
contextId: contextId,
};
historyForGenkit.push(agentMessage);
contexts.set(contextId, historyForGenkit);
// 7. Publish final task status update
const finalUpdate: TaskStatusUpdateEvent = {
kind: 'status-update',
taskId: taskId,
contextId: contextId,
status: {
state: finalA2AState,
message: agentMessage,
timestamp: new Date().toISOString(),
},
final: true,

View File

@ -1,6 +1,12 @@
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
import { Task, TaskStatusUpdateEvent, Message } from '../../../index.js';
import {
Task,
TaskStatusUpdateEvent,
Message,
TaskArtifactUpdateEvent,
Artifact,
} from '../../../index.js';
import { AgentExecutor, RequestContext, ExecutionEventBus } from '../../../server/index.js';
/**
@ -58,31 +64,39 @@ export class SampleAgentExecutor implements AgentExecutor {
};
eventBus.publish(workingStatusUpdate);
// 3. Publish final task status update
// 3. Publish artifact with the result
const agentReplyText = this.parseInputMessage(userMessage);
console.info(`[SampleAgentExecutor] Prompt response: ${agentReplyText}`);
const agentMessage: Message = {
kind: 'message',
role: 'agent',
messageId: uuidv4(),
const artifactId = uuidv4();
const resultArtifact: Artifact = {
artifactId: artifactId,
name: 'Result',
description: 'The final result from the agent.',
parts: [{ kind: 'text', text: agentReplyText }],
taskId: taskId,
contextId: contextId,
};
const artifactUpdate: TaskArtifactUpdateEvent = {
kind: 'artifact-update',
taskId: taskId,
contextId: contextId,
artifact: resultArtifact,
lastChunk: true,
};
await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate processing delay
eventBus.publish(artifactUpdate);
// 4. Publish final task status update (completed, no message)
const finalUpdate: TaskStatusUpdateEvent = {
kind: 'status-update',
taskId: taskId,
contextId: contextId,
status: {
state: 'completed',
message: agentMessage,
timestamp: new Date().toISOString(),
},
final: true,
};
await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate processing delay
eventBus.publish(finalUpdate);
console.log(`[SampleAgentExecutor] Task ${taskId} finished with state: completed`);

View File

@ -2,6 +2,7 @@
import readline from 'node:readline';
import crypto from 'node:crypto';
import { GoogleAuth } from 'google-auth-library';
import {
// Specific Params/Payload types used by the CLI
@ -16,9 +17,19 @@ import {
// Type for the agent card
AgentCard,
Part, // Added for explicit Part typing
AGENT_CARD_PATH,
} from '../index.js';
import { ClientFactory } from '../client/index.js';
import {
AuthenticationHandler,
ClientFactory,
ClientFactoryOptions,
createAuthenticatingFetchWithRetry,
DefaultAgentCardResolver,
JsonRpcTransportFactory,
RestTransportFactory,
} from '../client/index.js';
import { GrpcTransportFactory } from '../client/transports/grpc/grpc_transport.js';
// --- ANSI Colors ---
const colors = {
@ -44,12 +55,58 @@ function generateId(): string {
return crypto.randomUUID();
}
// Application Default Credentials required for A2A agent running on Agent Engine.
export class ADCHandler implements AuthenticationHandler {
private auth = new GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
async headers(): Promise<Record<string, string>> {
const client = await this.auth.getClient();
const token = await client.getAccessToken();
if (token?.token) {
return { Authorization: `Bearer ${token.token}` };
}
throw new Error('Failed to retrieve ADC access token.');
}
async shouldRetryWithHeaders(
_req: RequestInit,
res: Response
): Promise<Record<string, string> | undefined> {
if (res.status !== 401 && res.status !== 403) return undefined;
return this.headers();
}
}
// --- State ---
let currentTaskId: string | undefined = undefined; // Initialize as undefined
let currentContextId: string | undefined = undefined; // Initialize as undefined
const serverUrl = process.argv[2] || 'http://localhost:41241'; // Agent's base URL
const factory = new ClientFactory();
const client = await factory.createFromUrl(serverUrl);
const preferredTransport = process.argv
.find((arg) => arg.startsWith('--transport='))
?.split('=')[1];
const serverUrlArg = process.argv.slice(2).find((arg) => !arg.startsWith('--'));
const serverUrl = serverUrlArg || 'http://localhost:41241'; // Agent's base URL
let fetchImpl: typeof fetch = fetch;
let agentCardPath = AGENT_CARD_PATH;
if (process.argv.includes('--agent-engine')) {
fetchImpl = createAuthenticatingFetchWithRetry(fetch, new ADCHandler());
agentCardPath = 'a2a/v1/card'; // Agent Engine doesn't use well-known public agent card endpoint.
}
const factory = new ClientFactory(
ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
cardResolver: new DefaultAgentCardResolver({ fetchImpl }),
transports: [
new JsonRpcTransportFactory({ fetchImpl }),
new RestTransportFactory({ fetchImpl }),
new GrpcTransportFactory(),
],
preferredTransports: preferredTransport ? [preferredTransport] : undefined,
})
);
const client = await factory.createFromUrl(serverUrl, agentCardPath);
let agentName = 'Agent'; // Default, try to get from agent card later
// --- Readline Setup ---
@ -184,6 +241,23 @@ async function fetchAndDisplayAgentCard() {
} else {
console.log(` Streaming: ${colorize('yellow', 'Not Supported (or not specified)')}`);
}
const supportedTransports = new Set<string>();
supportedTransports.add(card.preferredTransport || 'JSONRPC');
if (card.additionalInterfaces) {
for (const iface of card.additionalInterfaces) {
supportedTransports.add(iface.transport);
}
}
console.log(` Supported Transports: ${Array.from(supportedTransports).join(', ')}`);
// TODO (https://github.com/a2aproject/a2a-js/issues/179): Add a way to get the protocol name from the transport.
console.log(
colorize(
'green',
`\n✓ Connected via ${Object.getPrototypeOf(client.transport).constructor.name}`
)
);
// Update prompt prefix to use the fetched name
// The prompt is set dynamically before each rl.prompt() call in the main loop
// to reflect the current agentName if it changes (though unlikely after initial fetch).

File diff suppressed because it is too large Load Diff

View File

@ -20,6 +20,9 @@
"tsx": "^4.19.3"
},
"dependencies": {
"@bufbuild/protobuf": "^2.10.2",
"@grpc/grpc-js": "^1.14.3",
"google-auth-library": "^10.5.0",
"uuid": "^11.1.0"
}
}

View File

@ -10,7 +10,6 @@ export class ExecutionEventQueue {
private eventQueue: AgentExecutionEvent[] = [];
private resolvePromise?: (value: void | PromiseLike<void>) => void;
private stopped: boolean = false;
private boundHandleEvent: (event: AgentExecutionEvent) => void;
constructor(eventBus: ExecutionEventBus) {
this.eventBus = eventBus;

View File

@ -11,7 +11,6 @@ import { A2ARequestHandler } from '../request_handler/a2a_request_handler.js';
import { JsonRpcTransportHandler } from '../transports/jsonrpc/jsonrpc_transport_handler.js';
import { ServerCallContext } from '../context.js';
import { HTTP_EXTENSION_HEADER } from '../../constants.js';
import { UnauthenticatedUser } from '../authentication/user.js';
import { UserBuilder } from './common.js';
import { SSE_HEADERS, formatSSEEvent, formatSSEErrorEvent } from '../../sse_utils.js';
import { Extensions } from '../../extensions.js';
@ -44,7 +43,7 @@ export function jsonRpcHandler(options: JsonRpcHandlerOptions): RequestHandler {
const user = await options.userBuilder(req);
const context = new ServerCallContext(
Extensions.parseServiceParameter(req.header(HTTP_EXTENSION_HEADER)),
user ?? new UnauthenticatedUser()
user
);
const rpcResponseOrStream = await jsonRpcTransportHandler.handle(req.body, context);

View File

@ -19,6 +19,11 @@ import { HTTP_EXTENSION_HEADER } from '../../constants.js';
import { UserBuilder } from './common.js';
import { Extensions } from '../../extensions.js';
import { FromProto } from '../../types/converters/from_proto.js';
import * as a2a from '../../types/pb/a2a_types.js';
import { ToProto } from '../../types/converters/to_proto.js';
import { Message, Task, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '../../types.js';
/**
* Options for configuring the HTTP+JSON/REST handler.
*/
@ -130,19 +135,24 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
* @param statusCode - HTTP status code
* @param context - ServerCallContext for setting extension headers
* @param body - Response body (omitted for 204 responses)
* @param responseType - Optional protobuf message type for serialization
*/
const sendResponse = (
const sendResponse = <T>(
res: Response,
statusCode: number,
context: ServerCallContext,
body?: unknown
body?: T,
responseType?: a2a.MessageFns<T>
): void => {
setExtensionsHeader(res, context);
res.status(statusCode);
if (statusCode === HTTP_STATUS.NO_CONTENT) {
res.end();
} else {
res.json(body);
if (!responseType || body === undefined) {
throw new Error('Bug: toJson serializer and body must be provided for non-204 responses.');
}
res.json(responseType.toJSON(body));
}
};
@ -158,7 +168,11 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
*/
const sendStreamResponse = async (
res: Response,
stream: AsyncGenerator<unknown, void, undefined>,
stream: AsyncGenerator<
Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent,
void,
undefined
>,
context: ServerCallContext
): Promise<void> => {
// Get first event before flushing headers to catch early errors
@ -188,11 +202,14 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
try {
// Write first event
if (!firstResult.done) {
res.write(formatSSEEvent(firstResult.value));
const proto = ToProto.messageStreamResult(firstResult.value);
const result = a2a.StreamResponse.toJSON(proto);
res.write(formatSSEEvent(result));
}
// Continue with remaining events
for await (const event of { [Symbol.asyncIterator]: () => iterator }) {
res.write(formatSSEEvent(event));
const proto = ToProto.messageStreamResult(event);
const result = a2a.StreamResponse.toJSON(proto);
res.write(formatSSEEvent(result));
}
} catch (streamError: unknown) {
console.error('SSE streaming error:', streamError);
@ -268,8 +285,9 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
'/v1/card',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const result = await restTransportHandler.getAuthenticatedExtendedAgentCard();
sendResponse(res, HTTP_STATUS.OK, context, result);
const result = await restTransportHandler.getAuthenticatedExtendedAgentCard(context);
const protoResult = ToProto.agentCard(result);
sendResponse<a2a.AgentCard>(res, HTTP_STATUS.OK, context, protoResult, a2a.AgentCard);
})
);
@ -288,8 +306,17 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
'/v1/message\\:send',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const result = await restTransportHandler.sendMessage(req.body, context);
sendResponse(res, HTTP_STATUS.CREATED, context, result);
const protoReq = a2a.SendMessageRequest.fromJSON(req.body);
const params = FromProto.messageSendParams(protoReq);
const result = await restTransportHandler.sendMessage(params, context);
const protoResult = ToProto.messageSendResult(result);
sendResponse<a2a.SendMessageResponse>(
res,
HTTP_STATUS.CREATED,
context,
protoResult,
a2a.SendMessageResponse
);
})
);
@ -309,7 +336,9 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
'/v1/message\\:stream',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const stream = await restTransportHandler.sendMessageStream(req.body, context);
const protoReq = a2a.SendMessageRequest.fromJSON(req.body);
const params = FromProto.messageSendParams(protoReq);
const stream = await restTransportHandler.sendMessageStream(params, context);
await sendStreamResponse(res, stream, context);
})
);
@ -332,9 +361,11 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
const result = await restTransportHandler.getTask(
req.params.taskId,
context,
req.query.historyLength
//TODO: clarify for version 1.0.0 the format of the historyLength query parameter, and if history should always be added to the returned object
req.query.historyLength ?? req.query.history_length
);
sendResponse(res, HTTP_STATUS.OK, context, result);
const protoResult = ToProto.task(result);
sendResponse<a2a.Task>(res, HTTP_STATUS.OK, context, protoResult, a2a.Task);
})
);
@ -354,7 +385,8 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const result = await restTransportHandler.cancelTask(req.params.taskId, context);
sendResponse(res, HTTP_STATUS.ACCEPTED, context, result);
const protoResult = ToProto.task(result);
sendResponse<a2a.Task>(res, HTTP_STATUS.ACCEPTED, context, protoResult, a2a.Task);
})
);
@ -393,13 +425,17 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
'/v1/tasks/:taskId/pushNotificationConfigs',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const config = {
...req.body,
taskId: req.params.taskId,
task_id: req.params.taskId,
};
const result = await restTransportHandler.setTaskPushNotificationConfig(config, context);
sendResponse(res, HTTP_STATUS.CREATED, context, result);
const protoReq = a2a.CreateTaskPushNotificationConfigRequest.fromJSON(req.body);
const params = FromProto.createTaskPushNotificationConfig(protoReq);
const result = await restTransportHandler.setTaskPushNotificationConfig(params, context);
const protoResult = ToProto.taskPushNotificationConfig(result);
sendResponse<a2a.TaskPushNotificationConfig>(
res,
HTTP_STATUS.CREATED,
context,
protoResult,
a2a.TaskPushNotificationConfig
);
})
);
@ -420,7 +456,14 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
req.params.taskId,
context
);
sendResponse(res, HTTP_STATUS.OK, context, result);
const protoResult = ToProto.listTaskPushNotificationConfig(result);
sendResponse<a2a.ListTaskPushNotificationConfigResponse>(
res,
HTTP_STATUS.OK,
context,
protoResult,
a2a.ListTaskPushNotificationConfigResponse
);
})
);
@ -443,7 +486,14 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
req.params.configId,
context
);
sendResponse(res, HTTP_STATUS.OK, context, result);
const protoResult = ToProto.taskPushNotificationConfig(result);
sendResponse<a2a.TaskPushNotificationConfig>(
res,
HTTP_STATUS.OK,
context,
protoResult,
a2a.TaskPushNotificationConfig
);
})
);

10
src/server/grpc/common.ts Normal file
View File

@ -0,0 +1,10 @@
import type * as grpc from '@grpc/grpc-js';
import { UnauthenticatedUser, User } from '../authentication/user.js';
export type UserBuilder = (
call: grpc.ServerUnaryCall<unknown, unknown> | grpc.ServerWritableStream<unknown, unknown>
) => Promise<User>;
export const UserBuilder = {
noAuthentication: () => Promise.resolve(new UnauthenticatedUser()),
};

View File

@ -0,0 +1,285 @@
import * as grpc from '@grpc/grpc-js';
import {
A2AServiceServer,
AgentCard,
CancelTaskRequest,
CreateTaskPushNotificationConfigRequest,
DeleteTaskPushNotificationConfigRequest,
GetAgentCardRequest,
GetTaskPushNotificationConfigRequest,
GetTaskRequest,
ListTaskPushNotificationConfigRequest,
ListTaskPushNotificationConfigResponse,
SendMessageRequest,
SendMessageResponse,
StreamResponse,
Task,
TaskPushNotificationConfig,
TaskSubscriptionRequest,
} from '../../grpc/pb/a2a_services.js';
import { Empty } from '../../grpc/pb/google/protobuf/empty.js';
import { A2ARequestHandler } from '../request_handler/a2a_request_handler.js';
import { FromProto } from '../../types/converters/from_proto.js';
import { ToProto } from '../../types/converters/to_proto.js';
import { ServerCallContext } from '../context.js';
import { Extensions } from '../../extensions.js';
import { UserBuilder } from './common.js';
import { HTTP_EXTENSION_HEADER } from '../../constants.js';
import { A2AError } from '../error.js';
/**
* Options for configuring the gRPC handler.
*/
export interface GrpcServiceOptions {
requestHandler: A2ARequestHandler;
userBuilder: UserBuilder;
}
/**
* Creates a gRPC transport handler.
* This handler implements the A2A gRPC service definition and acts as an
* adapter between the gRPC transport layer and the core A2A request handler.
*
* @param requestHandler - The core A2A request handler for business logic.
* @returns An object that implements the A2AServiceServer interface.
*
* @example
* ```ts
* const server = new grpc.Server();
* const requestHandler = new DefaultRequestHandler(...);
* server.addService(A2AService, grpcService({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
* ```
*/
export function grpcService(options: GrpcServiceOptions): A2AServiceServer {
const requestHandler = options.requestHandler;
/**
* Helper to wrap Unary calls with common logic (context, metadata, error handling)
*/
const wrapUnary = async <TReq, TRes, TParams, TResult>(
call: grpc.ServerUnaryCall<TReq, TRes>,
callback: grpc.sendUnaryData<TRes>,
parser: (req: TReq) => TParams,
handler: (params: TParams, ctx: ServerCallContext) => Promise<TResult>,
converter: (res: TResult) => TRes
) => {
try {
const context = await buildContext(call, options.userBuilder);
const params = parser(call.request);
const result = await handler(params, context);
call.sendMetadata(buildMetadata(context));
callback(null, converter(result));
} catch (error) {
callback(mapToError(error), null);
}
};
/**
* Helper to wrap Streaming calls with common logic (context, metadata, error handling)
*/
const wrapStreaming = async <TReq, TRes, TParams, TResult>(
call: grpc.ServerWritableStream<TReq, TRes>,
parser: (req: TReq) => TParams,
handler: (params: TParams, ctx: ServerCallContext) => AsyncGenerator<TResult>,
converter: (res: TResult) => TRes
) => {
try {
const context = await buildContext(call, options.userBuilder);
const params = parser(call.request);
const stream = await handler(params, context);
const metadata = buildMetadata(context);
call.sendMetadata(metadata);
for await (const responsePart of stream) {
const response = converter(responsePart);
call.write(response);
}
} catch (error) {
call.emit('error', mapToError(error));
} finally {
call.end();
}
};
return {
sendMessage(
call: grpc.ServerUnaryCall<SendMessageRequest, SendMessageResponse>,
callback: grpc.sendUnaryData<SendMessageResponse>
): Promise<void> {
return wrapUnary(
call,
callback,
FromProto.messageSendParams,
requestHandler.sendMessage.bind(requestHandler),
ToProto.messageSendResult
);
},
sendStreamingMessage(
call: grpc.ServerWritableStream<SendMessageRequest, StreamResponse>
): Promise<void> {
return wrapStreaming(
call,
FromProto.messageSendParams,
requestHandler.sendMessageStream.bind(requestHandler),
ToProto.messageStreamResult
);
},
taskSubscription(
call: grpc.ServerWritableStream<TaskSubscriptionRequest, StreamResponse>
): Promise<void> {
return wrapStreaming(
call,
FromProto.taskIdParams,
requestHandler.resubscribe.bind(requestHandler),
ToProto.messageStreamResult
);
},
deleteTaskPushNotificationConfig(
call: grpc.ServerUnaryCall<DeleteTaskPushNotificationConfigRequest, Empty>,
callback: grpc.sendUnaryData<Empty>
): Promise<void> {
return wrapUnary(
call,
callback,
FromProto.deleteTaskPushNotificationConfigParams,
requestHandler.deleteTaskPushNotificationConfig.bind(requestHandler),
() => ({})
);
},
listTaskPushNotificationConfig(
call: grpc.ServerUnaryCall<
ListTaskPushNotificationConfigRequest,
ListTaskPushNotificationConfigResponse
>,
callback: grpc.sendUnaryData<ListTaskPushNotificationConfigResponse>
): Promise<void> {
return wrapUnary(
call,
callback,
FromProto.listTaskPushNotificationConfigParams,
requestHandler.listTaskPushNotificationConfigs.bind(requestHandler),
ToProto.listTaskPushNotificationConfig
);
},
createTaskPushNotificationConfig(
call: grpc.ServerUnaryCall<
CreateTaskPushNotificationConfigRequest,
TaskPushNotificationConfig
>,
callback: grpc.sendUnaryData<TaskPushNotificationConfig>
): Promise<void> {
return wrapUnary(
call,
callback,
FromProto.createTaskPushNotificationConfig,
requestHandler.setTaskPushNotificationConfig.bind(requestHandler),
ToProto.taskPushNotificationConfig
);
},
getTaskPushNotificationConfig(
call: grpc.ServerUnaryCall<GetTaskPushNotificationConfigRequest, TaskPushNotificationConfig>,
callback: grpc.sendUnaryData<TaskPushNotificationConfig>
): Promise<void> {
return wrapUnary(
call,
callback,
FromProto.getTaskPushNotificationConfigParams,
requestHandler.getTaskPushNotificationConfig.bind(requestHandler),
ToProto.taskPushNotificationConfig
);
},
getTask(
call: grpc.ServerUnaryCall<GetTaskRequest, Task>,
callback: grpc.sendUnaryData<Task>
): Promise<void> {
return wrapUnary(
call,
callback,
FromProto.taskQueryParams,
requestHandler.getTask.bind(requestHandler),
ToProto.task
);
},
cancelTask(
call: grpc.ServerUnaryCall<CancelTaskRequest, Task>,
callback: grpc.sendUnaryData<Task>
): Promise<void> {
return wrapUnary(
call,
callback,
FromProto.taskIdParams,
requestHandler.cancelTask.bind(requestHandler),
ToProto.task
);
},
getAgentCard(
call: grpc.ServerUnaryCall<GetAgentCardRequest, AgentCard>,
callback: grpc.sendUnaryData<AgentCard>
): Promise<void> {
return wrapUnary(
call,
callback,
() => ({}),
(_params, context) => requestHandler.getAuthenticatedExtendedAgentCard(context),
ToProto.agentCard
);
},
};
}
// --- Internal Helpers ---
/**
* Maps A2AError or standard Error to gRPC Status codes
*/
const mapping: Record<number, grpc.status> = {
[-32001]: grpc.status.NOT_FOUND,
[-32002]: grpc.status.FAILED_PRECONDITION,
[-32003]: grpc.status.UNIMPLEMENTED,
[-32004]: grpc.status.UNIMPLEMENTED,
[-32005]: grpc.status.INVALID_ARGUMENT,
[-32006]: grpc.status.INTERNAL,
[-32007]: grpc.status.FAILED_PRECONDITION,
[-32600]: grpc.status.INVALID_ARGUMENT,
[-32602]: grpc.status.INVALID_ARGUMENT,
[-32603]: grpc.status.INTERNAL,
};
const mapToError = (error: unknown): Partial<grpc.ServiceError> => {
const a2aError =
error instanceof A2AError
? error
: A2AError.internalError(error instanceof Error ? error.message : 'Internal server error');
return {
code: mapping[a2aError.code] ?? grpc.status.UNKNOWN,
details: a2aError.message,
};
};
const buildContext = async (
call: grpc.ServerUnaryCall<unknown, unknown> | grpc.ServerWritableStream<unknown, unknown>,
userBuilder: UserBuilder
): Promise<ServerCallContext> => {
const user = await userBuilder(call);
const extensionHeaders = call.metadata.get(HTTP_EXTENSION_HEADER);
const extensionString = extensionHeaders.map((v) => v.toString()).join(',');
return new ServerCallContext(Extensions.parseServiceParameter(extensionString), user);
};
const buildMetadata = (context: ServerCallContext): grpc.Metadata => {
const metadata = new grpc.Metadata();
if (context.activatedExtensions?.length) {
metadata.set(HTTP_EXTENSION_HEADER, context.activatedExtensions.join(','));
}
return metadata;
};

9
src/server/grpc/index.ts Normal file
View File

@ -0,0 +1,9 @@
/**
* gRPC integration for the A2A Server library.
* This module provides gRPC specific functionality.
*/
export { grpcService } from './grpc_service.js';
export type { GrpcServiceOptions } from './grpc_service.js';
export { A2AServiceService as A2AService } from '../../grpc/pb/a2a_services.js';
export { UserBuilder } from './common.js';

View File

@ -56,7 +56,7 @@ export class DefaultPushNotificationSender implements PushNotificationSender {
});
this.notificationChain.set(task.id, newPromise);
newPromise.finally(() => {
return newPromise.finally(() => {
// Clean up the chain if it's the last notification
if (this.notificationChain.get(task.id) === newPromise) {
this.notificationChain.delete(task.id);

View File

@ -17,21 +17,9 @@ import {
TaskPushNotificationConfig,
TaskQueryParams,
TaskIdParams,
Part,
AgentCard,
FileWithBytes,
FileWithUri,
} from '../../../types.js';
import {
RestMessage,
RestMessageSendParams,
RestTaskPushNotificationConfig,
PartInput,
MessageInput,
MessageSendParamsInput,
TaskPushNotificationConfigInput,
FileInput,
} from './rest_types.js';
import { A2A_ERROR_CODE } from '../../../errors.js';
// ============================================================================
// HTTP Status Codes and Error Mapping
@ -53,21 +41,6 @@ export const HTTP_STATUS = {
NOT_IMPLEMENTED: 501,
} as const;
/**
* A2A error codes mapped to JSON-RPC and protocol-specific errors.
*/
const A2A_ERROR_CODE = {
PARSE_ERROR: -32700,
INVALID_REQUEST: -32600,
METHOD_NOT_FOUND: -32601,
INVALID_PARAMS: -32602,
TASK_NOT_FOUND: -32001,
TASK_NOT_CANCELABLE: -32002,
PUSH_NOTIFICATION_NOT_SUPPORTED: -32003,
UNSUPPORTED_OPERATION: -32004,
UNAUTHORIZED: -32005,
} as const;
/**
* Maps A2A error codes to appropriate HTTP status codes.
*
@ -92,8 +65,6 @@ export function mapErrorToStatus(errorCode: number): number {
case A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED:
case A2A_ERROR_CODE.UNSUPPORTED_OPERATION:
return HTTP_STATUS.BAD_REQUEST;
case A2A_ERROR_CODE.UNAUTHORIZED:
return HTTP_STATUS.UNAUTHORIZED;
default:
return HTTP_STATUS.INTERNAL_SERVER_ERROR;
}
@ -162,29 +133,39 @@ export class RestTransportHandler {
/**
* Gets the authenticated extended agent card.
*/
async getAuthenticatedExtendedAgentCard(): Promise<AgentCard> {
return this.requestHandler.getAuthenticatedExtendedAgentCard();
async getAuthenticatedExtendedAgentCard(context: ServerCallContext): Promise<AgentCard> {
return this.requestHandler.getAuthenticatedExtendedAgentCard(context);
}
/**
* Validate MessageSendParams.
*/
private validateMessageSendParams(params: MessageSendParams): void {
if (!params.message) {
throw A2AError.invalidParams('message is required');
}
if (!params.message.messageId) {
throw A2AError.invalidParams('message.messageId is required');
}
}
/**
* Sends a message to the agent.
* Accepts both snake_case and camelCase input, returns camelCase.
*/
async sendMessage(
params: MessageSendParamsInput,
params: MessageSendParams,
context: ServerCallContext
): Promise<Message | Task> {
const normalized = this.normalizeMessageParams(params);
return this.requestHandler.sendMessage(normalized, context);
this.validateMessageSendParams(params);
return this.requestHandler.sendMessage(params, context);
}
/**
* Sends a message with streaming response.
* Accepts both snake_case and camelCase input, returns camelCase stream.
* @throws {A2AError} UnsupportedOperation if streaming not supported
*/
async sendMessageStream(
params: MessageSendParamsInput,
params: MessageSendParams,
context: ServerCallContext
): Promise<
AsyncGenerator<
@ -194,8 +175,8 @@ export class RestTransportHandler {
>
> {
await this.requireCapability('streaming');
const normalized = this.normalizeMessageParams(params);
return this.requestHandler.sendMessageStream(normalized, context);
this.validateMessageSendParams(params);
return this.requestHandler.sendMessageStream(params, context);
}
/**
@ -240,16 +221,20 @@ export class RestTransportHandler {
/**
* Sets a push notification configuration.
* Accepts both snake_case and camelCase input, returns camelCase.
* @throws {A2AError} PushNotificationNotSupported if push notifications not supported
*/
async setTaskPushNotificationConfig(
config: TaskPushNotificationConfigInput,
config: TaskPushNotificationConfig,
context: ServerCallContext
): Promise<TaskPushNotificationConfig> {
await this.requireCapability('pushNotifications');
const normalized = this.normalizeTaskPushNotificationConfig(config);
return this.requestHandler.setTaskPushNotificationConfig(normalized, context);
if (!config.taskId) {
throw A2AError.invalidParams('taskId is required');
}
if (!config.pushNotificationConfig) {
throw A2AError.invalidParams('pushNotificationConfig is required');
}
return this.requestHandler.setTaskPushNotificationConfig(config, context);
}
/**
@ -290,31 +275,6 @@ export class RestTransportHandler {
);
}
// ==========================================================================
// Private Transformation Methods
// ==========================================================================
// All type conversion between REST (snake_case) and internal (camelCase) formats
/**
* Validates and normalizes message parameters.
* Accepts both snake_case and camelCase input.
* @throws {A2AError} InvalidParams if message is missing or conversion fails
*/
private normalizeMessageParams(input: MessageSendParamsInput): MessageSendParams {
if (!input.message) {
throw A2AError.invalidParams('message is required');
}
try {
return this.normalizeMessageSendParams(input);
} catch (error) {
if (error instanceof A2AError) throw error;
throw A2AError.invalidParams(
error instanceof Error ? error.message : 'Invalid message parameters'
);
}
}
/**
* Static map of capability to error for missing capabilities.
*/
@ -353,102 +313,4 @@ export class RestTransportHandler {
}
return parsed;
}
/**
* Normalizes Part input - accepts both snake_case and camelCase for file mimeType.
*/
private normalizePart(part: PartInput): Part {
if (part.kind === 'text') return { kind: 'text', text: part.text };
if (part.kind === 'file') {
const file = this.normalizeFile(part.file);
return { kind: 'file', file, metadata: part.metadata };
}
return { kind: 'data', data: part.data, metadata: part.metadata };
}
/**
* Normalizes File input - accepts both snake_case (mime_type) and camelCase (mimeType).
*/
private normalizeFile(f: FileInput): FileWithBytes | FileWithUri {
// Access both formats via intersection cast
const file = f as FileInput & { mimeType?: string; mime_type?: string };
const mimeType = file.mimeType ?? file.mime_type;
if ('bytes' in file) {
return { bytes: file.bytes, mimeType, name: file.name };
}
return { uri: file.uri, mimeType, name: file.name };
}
/**
* Normalizes Message input - accepts both snake_case and camelCase.
*/
private normalizeMessage(input: MessageInput): Message {
// Cast to access both formats
const m = input as Message & RestMessage;
const messageId = m.messageId ?? m.message_id;
if (!messageId) {
throw A2AError.invalidParams('message.messageId is required');
}
if (!m.parts || !Array.isArray(m.parts)) {
throw A2AError.invalidParams('message.parts must be an array');
}
return {
contextId: m.contextId ?? m.context_id,
extensions: m.extensions,
kind: 'message',
messageId,
metadata: m.metadata,
parts: m.parts.map((p) => this.normalizePart(p)),
referenceTaskIds: m.referenceTaskIds ?? m.reference_task_ids,
role: m.role,
taskId: m.taskId ?? m.task_id,
};
}
/**
* Normalizes MessageSendParams - accepts both snake_case and camelCase.
*/
private normalizeMessageSendParams(input: MessageSendParamsInput): MessageSendParams {
// Cast to access both formats
const p = input as MessageSendParams & RestMessageSendParams;
const config = p.configuration as
| (MessageSendParams['configuration'] & RestMessageSendParams['configuration'])
| undefined;
return {
configuration: config
? {
acceptedOutputModes: config.acceptedOutputModes ?? config.accepted_output_modes,
blocking: config.blocking,
historyLength: config.historyLength ?? config.history_length,
}
: undefined,
message: this.normalizeMessage(p.message),
metadata: p.metadata,
};
}
/**
* Normalizes TaskPushNotificationConfig - accepts both snake_case and camelCase.
*/
private normalizeTaskPushNotificationConfig(
input: TaskPushNotificationConfigInput
): TaskPushNotificationConfig {
// Cast to access both formats
const c = input as TaskPushNotificationConfig & RestTaskPushNotificationConfig;
const taskId = c.taskId ?? c.task_id;
if (!taskId) {
throw A2AError.invalidParams('taskId is required');
}
const pnConfig = c.pushNotificationConfig ?? c.push_notification_config;
if (!pnConfig) {
throw A2AError.invalidParams('pushNotificationConfig is required');
}
return {
pushNotificationConfig: pnConfig,
taskId,
};
}
}

View File

@ -1,120 +0,0 @@
/**
* REST API Types (snake_case format)
*
* These types mirror the internal types but use snake_case naming
* to support TCK and clients that send snake_case payloads.
*/
import {
Part,
Message,
MessageSendParams,
TaskPushNotificationConfig,
FileWithBytes,
FileWithUri,
} from '../../../types.js';
// ============================================================================
// REST Types (snake_case format)
// ============================================================================
/**
* REST file with bytes (snake_case mime_type).
*/
export interface RestFileWithBytes {
bytes: string;
mime_type?: string;
name?: string;
}
/**
* REST file with URI (snake_case mime_type).
*/
export interface RestFileWithUri {
uri: string;
mime_type?: string;
name?: string;
}
/**
* REST file union.
*/
export type RestFile = RestFileWithBytes | RestFileWithUri;
/**
* File input - accepts both camelCase and snake_case.
*/
export type FileInput = FileWithBytes | FileWithUri | RestFileWithBytes | RestFileWithUri;
/**
* REST Part with snake_case file fields.
*/
export type RestPart =
| { kind: 'text'; text: string; metadata?: Record<string, unknown> }
| { kind: 'file'; file: RestFile; metadata?: Record<string, unknown> }
| { kind: 'data'; data: Record<string, unknown>; metadata?: Record<string, unknown> };
/**
* REST Message with snake_case fields.
*/
export interface RestMessage {
kind: 'message';
role: 'agent' | 'user';
parts: RestPart[];
message_id: string;
context_id?: string;
task_id?: string;
reference_task_ids?: string[];
extensions?: string[];
metadata?: Record<string, unknown>;
}
/**
* REST PushNotificationConfig (same as internal, no snake_case fields).
*/
export interface RestPushNotificationConfig {
id: string;
url: string;
authentication?: {
schemes: string[];
credentials?: string;
};
}
/**
* REST MessageSendConfiguration with snake_case fields.
*/
export interface RestMessageSendConfiguration {
blocking?: boolean;
accepted_output_modes?: string[];
history_length?: number;
push_notification_config?: RestPushNotificationConfig;
}
/**
* REST MessageSendParams with snake_case configuration.
*/
export interface RestMessageSendParams {
message: RestMessage;
configuration?: RestMessageSendConfiguration;
metadata?: Record<string, unknown>;
}
/**
* REST TaskPushNotificationConfig with snake_case fields.
*/
export interface RestTaskPushNotificationConfig {
task_id: string;
push_notification_config: RestPushNotificationConfig;
}
// ============================================================================
// Input Types - Accept both camelCase and snake_case
// ============================================================================
export type PartInput = Part | RestPart;
export type MessageInput = Message | RestMessage;
export type MessageSendParamsInput = MessageSendParams | RestMessageSendParams;
export type TaskPushNotificationConfigInput =
| TaskPushNotificationConfig
| RestTaskPushNotificationConfig;

View File

@ -1,6 +1,6 @@
/**
* Shared Server-Sent Events (SSE) utilities for both JSON-RPC and REST transports.
* This module provides common SSE formatting functions and headers.
* This module provides common SSE formatting and parsing functions.
*/
// ============================================================================
@ -19,7 +19,19 @@ export const SSE_HEADERS = {
} as const;
// ============================================================================
// SSE Event Formatting
// SSE Event Types
// ============================================================================
/**
* Represents a parsed SSE event with type and data.
*/
export interface SseEvent {
type: string;
data: string;
}
// ============================================================================
// SSE Event Formatting (Server-side)
// ============================================================================
/**
@ -59,3 +71,96 @@ export function formatSSEEvent(event: unknown): string {
export function formatSSEErrorEvent(error: unknown): string {
return `event: error\ndata: ${JSON.stringify(error)}\n\n`;
}
// ============================================================================
// SSE Event Parsing (Client-side)
// ============================================================================
/**
* Parses a Server-Sent Events (SSE) stream from a Response object.
* Yields parsed SSE events as they arrive.
*
* This parser expects well-formed SSE events with single-line JSON data,
* matching the format produced by formatSSEEvent and formatSSEErrorEvent.
*
* @param response - The fetch Response containing an SSE stream
* @yields SseEvent objects with type and data fields
*
* @example
* ```ts
* for await (const event of parseSseStream(response)) {
* if (event.type === 'error') {
* handleError(JSON.parse(event.data));
* } else {
* handleData(JSON.parse(event.data));
* }
* }
* ```
*/
export async function* parseSseStream(
response: Response
): AsyncGenerator<SseEvent, void, undefined> {
if (!response.body) {
throw new Error('SSE response body is undefined. Cannot read stream.');
}
let buffer = '';
let eventType = 'message';
let eventData = '';
const stream = response.body.pipeThrough(new TextDecoderStream());
for await (const value of readFrom(stream)) {
buffer += value;
let lineEndIndex: number;
while ((lineEndIndex = buffer.indexOf('\n')) >= 0) {
const line = buffer.substring(0, lineEndIndex).trim();
buffer = buffer.substring(lineEndIndex + 1);
if (line === '') {
// Empty line signals end of event
if (eventData) {
yield { type: eventType, data: eventData };
eventData = '';
eventType = 'message';
}
} else if (line.startsWith('event:')) {
eventType = line.substring('event:'.length).trim();
} else if (line.startsWith('data:')) {
// Expect well-formed JSON on a single data line
eventData = line.substring('data:'.length).trim();
}
}
}
// Yield any pending event at stream end
if (eventData) {
yield { type: eventType, data: eventData };
}
}
/**
* Reads string chunks from a ReadableStream using the reader API.
*
* We use the manual reader approach the native async iterator directly on the stream
* because ReadableStream async iteration is not supported in all environments.
* @see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#browser_compatibility
*
* @param stream - The ReadableStream to read from
* @yields String chunks from the stream
*/
async function* readFrom(stream: ReadableStream<string>): AsyncGenerator<string, void, void> {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
yield value;
}
} finally {
reader.releaseLock();
}
}

24
src/types/README.md Normal file
View File

@ -0,0 +1,24 @@
# Types Generation
This directory contains the configuration for generating types definitions for the A2A SDK from the proto file. The generation process uses [Buf](https://buf.build/) and `ts-proto`.
## Prerequisites
Ensure you have the project dependencies installed:
```bash
npm install
```
This project uses `@bufbuild/buf` which is listed in the `devDependencies`.
Add the `a2a_types.proto` files to the `pb` directory.
## Generating Code
To generate the gRPC types definitions, run the following command from this directory (`src/types`):
```bash
npx buf generate
```
This will generate the TypeScript files in the `./pb` directory (as configured in `buf.gen.yaml`).

21
src/types/buf.gen.yaml Normal file
View File

@ -0,0 +1,21 @@
# buf generate
# Configuration for the buf generate command
# Uses remote plugins, no separate install required.
version: v2
inputs:
- directory: ./pb
plugins:
- remote: buf.build/community/stephenh-ts-proto:v2.11.0
out: ./pb
opt:
- oneof=unions-value
- importSuffix=.js
- outputServices=false
- env=node
- esModuleInterop=true
- outputJsonMethods=true
- outputPartialMethods=false
- outputEncodeMethods=false
- snakeToCamel=keys
- emitImportedFiles=false
- useDate=string

6
src/types/buf.lock Normal file
View File

@ -0,0 +1,6 @@
# Generated by buf. DO NOT EDIT.
version: v2
deps:
- name: buf.build/googleapis/googleapis
commit: 004180b77378443887d3b55cabc00384
digest: b5:e8f475fe3330f31f5fd86ac689093bcd274e19611a09db91f41d637cb9197881ce89882b94d13a58738e53c91c6e4bae7dc1feba85f590164c975a89e25115dc

6
src/types/buf.yaml Normal file
View File

@ -0,0 +1,6 @@
version: v2
modules:
- path: ./pb
deps:
# Common Protobuf types.
- buf.build/googleapis/googleapis

View File

@ -0,0 +1,503 @@
import { A2AError } from '../../server/error.js';
import {
CancelTaskRequest,
GetTaskPushNotificationConfigRequest,
ListTaskPushNotificationConfigRequest,
GetTaskRequest,
CreateTaskPushNotificationConfigRequest,
DeleteTaskPushNotificationConfigRequest,
Message,
Role,
SendMessageConfiguration,
PushNotificationConfig,
AuthenticationInfo,
SendMessageRequest,
Part,
SendMessageResponse,
Task,
TaskStatus,
TaskState,
Artifact,
TaskPushNotificationConfig,
ListTaskPushNotificationConfigResponse,
AgentCard,
Security,
SecurityScheme,
AgentSkill,
AgentCardSignature,
TaskStatusUpdateEvent,
TaskArtifactUpdateEvent,
OAuthFlows,
StreamResponse,
AgentInterface,
AgentProvider,
AgentCapabilities,
AgentExtension,
} from '../pb/a2a_types.js';
import * as types from '../../types.js';
import { extractTaskId, extractTaskAndPushNotificationConfigId } from './id_decoding.js';
/**
* Converts proto types to internal types.
*/
export class FromProto {
static taskQueryParams(request: GetTaskRequest): types.TaskQueryParams {
return {
id: extractTaskId(request.name),
historyLength: request.historyLength,
};
}
static taskIdParams(request: CancelTaskRequest): types.TaskIdParams {
return {
id: extractTaskId(request.name),
};
}
static getTaskPushNotificationConfigParams(
request: GetTaskPushNotificationConfigRequest
): types.GetTaskPushNotificationConfigParams {
const { taskId, configId } = extractTaskAndPushNotificationConfigId(request.name);
return {
id: taskId,
pushNotificationConfigId: configId,
};
}
static listTaskPushNotificationConfigParams(
request: ListTaskPushNotificationConfigRequest
): types.ListTaskPushNotificationConfigParams {
return {
id: extractTaskId(request.parent),
};
}
static createTaskPushNotificationConfig(
request: CreateTaskPushNotificationConfigRequest
): types.TaskPushNotificationConfig {
if (!request.config?.pushNotificationConfig) {
throw A2AError.invalidParams(
'Request must include a `config` object with a `pushNotificationConfig`'
);
}
return {
taskId: extractTaskId(request.parent),
pushNotificationConfig: FromProto.pushNotificationConfig(
request.config.pushNotificationConfig
),
};
}
static deleteTaskPushNotificationConfigParams(
request: DeleteTaskPushNotificationConfigRequest
): types.DeleteTaskPushNotificationConfigParams {
const { taskId, configId } = extractTaskAndPushNotificationConfigId(request.name);
return {
id: taskId,
pushNotificationConfigId: configId,
};
}
static message(message: Message): types.Message | undefined {
if (!message) {
return undefined;
}
return {
kind: 'message',
messageId: message.messageId,
parts: message.content.map((p) => FromProto.part(p)),
contextId: message.contextId || undefined,
taskId: message.taskId || undefined,
role: FromProto.role(message.role),
metadata: message.metadata,
extensions: message.extensions,
};
}
static role(role: Role): 'agent' | 'user' {
switch (role) {
case Role.ROLE_AGENT:
return 'agent';
case Role.ROLE_USER:
return 'user';
default:
throw A2AError.invalidParams(`Invalid role: ${role}`);
}
}
static messageSendConfiguration(
configuration: SendMessageConfiguration
): types.MessageSendConfiguration | undefined {
if (!configuration) {
return undefined;
}
return {
blocking: configuration.blocking,
acceptedOutputModes: configuration.acceptedOutputModes,
pushNotificationConfig: FromProto.pushNotificationConfig(configuration.pushNotification),
};
}
static pushNotificationConfig(
config: PushNotificationConfig
): types.PushNotificationConfig | undefined {
if (!config) {
return undefined;
}
return {
id: config.id,
url: config.url,
token: config.token || undefined,
authentication: FromProto.pushNotificationAuthenticationInfo(config.authentication),
};
}
static pushNotificationAuthenticationInfo(
authInfo: AuthenticationInfo
): types.PushNotificationAuthenticationInfo | undefined {
if (!authInfo) {
return undefined;
}
return {
schemes: authInfo.schemes,
credentials: authInfo.credentials,
};
}
static part(part: Part): types.Part {
if (part.part?.$case === 'text') {
return {
kind: 'text',
text: part.part.value,
};
}
if (part.part?.$case === 'file') {
const filePart = part.part.value;
if (filePart.file?.$case === 'fileWithUri') {
return {
kind: 'file',
file: {
uri: filePart.file.value,
mimeType: filePart.mimeType,
},
};
} else if (filePart.file?.$case === 'fileWithBytes') {
return {
kind: 'file',
file: {
bytes: filePart.file.value.toString('base64'),
mimeType: filePart.mimeType,
},
};
}
throw A2AError.invalidParams('Invalid file part type');
}
if (part.part?.$case === 'data') {
return {
kind: 'data',
data: part.part.value.data,
};
}
throw A2AError.invalidParams('Invalid part type');
}
static messageSendParams(request: SendMessageRequest): types.MessageSendParams {
return {
message: FromProto.message(request.request),
configuration: FromProto.messageSendConfiguration(request.configuration),
metadata: request.metadata,
};
}
static sendMessageResult(response: SendMessageResponse): types.Task | types.Message {
if (response.payload?.$case === 'task') {
return FromProto.task(response.payload.value);
} else if (response.payload?.$case === 'msg') {
return FromProto.message(response.payload.value);
}
throw A2AError.invalidParams('Invalid SendMessageResponse: missing result');
}
static task(task: Task): types.Task {
return {
kind: 'task',
id: task.id,
status: FromProto.taskStatus(task.status),
contextId: task.contextId,
artifacts: task.artifacts?.map((a) => FromProto.artifact(a)),
history: task.history?.map((h) => FromProto.message(h)),
metadata: task.metadata,
};
}
static taskStatus(status: TaskStatus): types.TaskStatus {
return {
message: FromProto.message(status.update),
state: FromProto.taskState(status.state),
timestamp: status.timestamp,
};
}
static taskState(state: TaskState): types.TaskState {
switch (state) {
case TaskState.TASK_STATE_SUBMITTED:
return 'submitted';
case TaskState.TASK_STATE_WORKING:
return 'working';
case TaskState.TASK_STATE_INPUT_REQUIRED:
return 'input-required';
case TaskState.TASK_STATE_COMPLETED:
return 'completed';
case TaskState.TASK_STATE_CANCELLED:
return 'canceled';
case TaskState.TASK_STATE_FAILED:
return 'failed';
case TaskState.TASK_STATE_REJECTED:
return 'rejected';
case TaskState.TASK_STATE_AUTH_REQUIRED:
return 'auth-required';
case TaskState.TASK_STATE_UNSPECIFIED:
return 'unknown';
default:
throw A2AError.invalidParams(`Invalid task state: ${state}`);
}
}
static artifact(artifact: Artifact): types.Artifact {
return {
artifactId: artifact.artifactId,
name: artifact.name || undefined,
description: artifact.description || undefined,
parts: artifact.parts.map((p) => FromProto.part(p)),
metadata: artifact.metadata,
};
}
static taskPushNotificationConfig(
request: TaskPushNotificationConfig
): types.TaskPushNotificationConfig {
return {
taskId: extractTaskId(request.name),
pushNotificationConfig: FromProto.pushNotificationConfig(request.pushNotificationConfig),
};
}
static listTaskPushNotificationConfig(
request: ListTaskPushNotificationConfigResponse
): types.TaskPushNotificationConfig[] {
return request.configs.map((c) => FromProto.taskPushNotificationConfig(c));
}
static agentCard(agentCard: AgentCard): types.AgentCard {
return {
additionalInterfaces: agentCard.additionalInterfaces?.map((i) => FromProto.agentInterface(i)),
capabilities: agentCard.capabilities
? FromProto.agentCapabilities(agentCard.capabilities)
: {},
defaultInputModes: agentCard.defaultInputModes,
defaultOutputModes: agentCard.defaultOutputModes,
description: agentCard.description,
documentationUrl: agentCard.documentationUrl || undefined,
name: agentCard.name,
preferredTransport: agentCard.preferredTransport,
provider: agentCard.provider ? FromProto.agentProvider(agentCard.provider) : undefined,
protocolVersion: agentCard.protocolVersion,
security: agentCard.security?.map((s) => FromProto.security(s)),
securitySchemes: agentCard.securitySchemes
? Object.fromEntries(
Object.entries(agentCard.securitySchemes).map(([key, value]) => [
key,
FromProto.securityScheme(value),
])
)
: {},
skills: agentCard.skills.map((s) => FromProto.skills(s)),
signatures: agentCard.signatures?.map((s) => FromProto.agentCardSignature(s)),
supportsAuthenticatedExtendedCard: agentCard.supportsAuthenticatedExtendedCard,
url: agentCard.url,
version: agentCard.version,
};
}
static agentCapabilities(capabilities: AgentCapabilities): types.AgentCapabilities1 {
return {
extensions: capabilities.extensions?.map((e) => FromProto.agentExtension(e)),
pushNotifications: capabilities.pushNotifications,
streaming: capabilities.streaming,
};
}
static agentExtension(extension: AgentExtension): types.AgentExtension {
return {
uri: extension.uri,
description: extension.description || undefined,
required: extension.required,
params: extension.params,
};
}
static agentInterface(intf: AgentInterface): types.AgentInterface {
return {
transport: intf.transport,
url: intf.url,
};
}
static agentProvider(provider: AgentProvider): types.AgentProvider {
return {
organization: provider.organization,
url: provider.url,
};
}
static security(security: Security): { [k: string]: string[] } {
return Object.fromEntries(
Object.entries(security.schemes)?.map(([key, value]) => [key, value.list])
);
}
static securityScheme(securitySchemes: SecurityScheme): types.SecurityScheme {
switch (securitySchemes.scheme?.$case) {
case 'apiKeySecurityScheme':
return {
type: 'apiKey',
name: securitySchemes.scheme.value.name,
in: securitySchemes.scheme.value.location as 'query' | 'header' | 'cookie',
description: securitySchemes.scheme.value.description || undefined,
};
case 'httpAuthSecurityScheme':
return {
type: 'http',
scheme: securitySchemes.scheme.value.scheme,
bearerFormat: securitySchemes.scheme.value.bearerFormat || undefined,
description: securitySchemes.scheme.value.description || undefined,
};
case 'mtlsSecurityScheme':
return {
type: 'mutualTLS',
description: securitySchemes.scheme.value.description || undefined,
};
case 'oauth2SecurityScheme':
return {
type: 'oauth2',
description: securitySchemes.scheme.value.description || undefined,
flows: FromProto.oauthFlows(securitySchemes.scheme.value.flows),
oauth2MetadataUrl: securitySchemes.scheme.value.oauth2MetadataUrl || undefined,
};
case 'openIdConnectSecurityScheme':
return {
type: 'openIdConnect',
description: securitySchemes.scheme.value.description || undefined,
openIdConnectUrl: securitySchemes.scheme.value.openIdConnectUrl,
};
default:
throw A2AError.internalError(`Unsupported security scheme type`);
}
}
static oauthFlows(flows: OAuthFlows): types.OAuthFlows {
switch (flows.flow?.$case) {
case 'implicit':
return {
implicit: {
authorizationUrl: flows.flow.value.authorizationUrl,
scopes: flows.flow.value.scopes,
refreshUrl: flows.flow.value.refreshUrl || undefined,
},
};
case 'password':
return {
password: {
refreshUrl: flows.flow.value.refreshUrl || undefined,
scopes: flows.flow.value.scopes,
tokenUrl: flows.flow.value.tokenUrl,
},
};
case 'authorizationCode':
return {
authorizationCode: {
refreshUrl: flows.flow.value.refreshUrl || undefined,
authorizationUrl: flows.flow.value.authorizationUrl,
scopes: flows.flow.value.scopes,
tokenUrl: flows.flow.value.tokenUrl,
},
};
case 'clientCredentials':
return {
clientCredentials: {
refreshUrl: flows.flow.value.refreshUrl || undefined,
scopes: flows.flow.value.scopes,
tokenUrl: flows.flow.value.tokenUrl,
},
};
default:
throw A2AError.internalError(`Unsupported OAuth flows`);
}
}
static skills(skill: AgentSkill): types.AgentSkill {
return {
id: skill.id,
name: skill.name,
description: skill.description,
tags: skill.tags,
examples: skill.examples,
inputModes: skill.inputModes,
outputModes: skill.outputModes,
security: skill.security?.map((s) => FromProto.security(s)),
};
}
static agentCardSignature(signatures: AgentCardSignature): types.AgentCardSignature {
return {
protected: signatures.protected,
signature: signatures.signature,
header: signatures.header,
};
}
static taskStatusUpdateEvent(event: TaskStatusUpdateEvent): types.TaskStatusUpdateEvent {
return {
kind: 'status-update',
taskId: event.taskId,
status: FromProto.taskStatus(event.status),
contextId: event.contextId,
metadata: event.metadata,
final: event.final,
};
}
static taskArtifactUpdateEvent(event: TaskArtifactUpdateEvent): types.TaskArtifactUpdateEvent {
return {
kind: 'artifact-update',
taskId: event.taskId,
artifact: FromProto.artifact(event.artifact),
contextId: event.contextId,
metadata: event.metadata,
lastChunk: event.lastChunk,
};
}
static messageStreamResult(
event: StreamResponse
): types.Message | types.Task | types.TaskStatusUpdateEvent | types.TaskArtifactUpdateEvent {
switch (event.payload?.$case) {
case 'msg':
return FromProto.message(event.payload.value);
case 'task':
return FromProto.task(event.payload.value);
case 'statusUpdate':
return FromProto.taskStatusUpdateEvent(event.payload.value);
case 'artifactUpdate':
return FromProto.taskArtifactUpdateEvent(event.payload.value);
default:
throw A2AError.internalError('Invalid event type in StreamResponse');
}
}
}

View File

@ -0,0 +1,30 @@
import { A2AError } from '../../server/error.js';
const CONFIG_REGEX = /^tasks\/([^/]+)\/pushNotificationConfigs\/([^/]+)$/;
const TASK_ONLY_REGEX = /^tasks\/([^/]+)(?:\/|$)/;
export const extractTaskId = (name: string): string => {
const match = name.match(TASK_ONLY_REGEX);
if (!match) {
throw A2AError.invalidParams(`Invalid or missing task ID in: "${name}"`);
}
return match[1];
};
export const generateTaskName = (taskId: string): string => {
return `tasks/${taskId}`;
};
export const extractTaskAndPushNotificationConfigId = (
name: string
): { taskId: string; configId: string } => {
const match = name.match(CONFIG_REGEX);
if (!match) {
throw A2AError.invalidParams(`Invalid or missing config ID in: "${name}"`);
}
return { taskId: match[1], configId: match[2] };
};
export const generatePushNotificationConfigName = (taskId: string, configId: string): string => {
return `tasks/${taskId}/pushNotificationConfigs/${configId}`;
};

View File

@ -0,0 +1,568 @@
import { A2AError } from '../../server/error.js';
import * as types from '../../types.js';
import {
AgentCard,
AgentCardSignature,
AgentCapabilities,
AgentExtension,
AgentInterface,
AgentProvider,
Artifact,
AuthenticationInfo,
FilePart as ProtoFilePart,
Message,
OAuthFlows,
Part,
PushNotificationConfig,
Role,
Security,
SecurityScheme,
SendMessageResponse,
StreamResponse,
Task,
TaskArtifactUpdateEvent,
TaskPushNotificationConfig,
TaskState,
TaskStatus,
TaskStatusUpdateEvent,
ListTaskPushNotificationConfigResponse,
AgentSkill,
SendMessageRequest,
SendMessageConfiguration,
GetTaskPushNotificationConfigRequest,
ListTaskPushNotificationConfigRequest,
DeleteTaskPushNotificationConfigRequest,
GetTaskRequest,
CancelTaskRequest,
TaskSubscriptionRequest,
CreateTaskPushNotificationConfigRequest,
GetAgentCardRequest,
} from '../pb/a2a_types.js';
import { generatePushNotificationConfigName, generateTaskName } from './id_decoding.js';
export class ToProto {
static agentCard(agentCard: types.AgentCard): AgentCard {
return {
protocolVersion: agentCard.protocolVersion,
name: agentCard.name,
description: agentCard.description,
url: agentCard.url,
preferredTransport: agentCard.preferredTransport ?? '',
additionalInterfaces:
agentCard.additionalInterfaces?.map((i) => ToProto.agentInterface(i)) ?? [],
provider: ToProto.agentProvider(agentCard.provider),
version: agentCard.version,
documentationUrl: agentCard.documentationUrl ?? '',
capabilities: ToProto.agentCapabilities(agentCard.capabilities),
securitySchemes: agentCard.securitySchemes
? Object.fromEntries(
Object.entries(agentCard.securitySchemes).map(([key, value]) => [
key,
ToProto.securityScheme(value),
])
)
: {},
security: agentCard.security?.map((s) => ToProto.security(s)) ?? [],
defaultInputModes: agentCard.defaultInputModes,
defaultOutputModes: agentCard.defaultOutputModes,
skills: agentCard.skills.map((s) => ToProto.agentSkill(s)),
supportsAuthenticatedExtendedCard: agentCard.supportsAuthenticatedExtendedCard,
signatures: agentCard.signatures?.map((s) => ToProto.agentCardSignature(s)) ?? [],
};
}
static agentCardSignature(signatures: types.AgentCardSignature): AgentCardSignature {
return {
protected: signatures.protected,
signature: signatures.signature,
header: signatures.header,
};
}
static agentSkill(skill: types.AgentSkill): AgentSkill {
return {
id: skill.id,
name: skill.name,
description: skill.description,
tags: skill.tags ?? [],
examples: skill.examples ?? [],
inputModes: skill.inputModes ?? [],
outputModes: skill.outputModes ?? [],
security: skill.security ? skill.security.map((s) => ToProto.security(s)) : [],
};
}
static security(security: { [k: string]: string[] }): Security {
return {
schemes: Object.fromEntries(
Object.entries(security).map(([key, value]) => {
return [key, { list: value }];
})
),
};
}
static securityScheme(scheme: types.SecurityScheme): SecurityScheme {
switch (scheme.type) {
case 'apiKey':
return {
scheme: {
$case: 'apiKeySecurityScheme',
value: {
name: scheme.name,
location: scheme.in,
description: scheme.description ?? '',
},
},
};
case 'http':
return {
scheme: {
$case: 'httpAuthSecurityScheme',
value: {
description: scheme.description ?? '',
scheme: scheme.scheme,
bearerFormat: scheme.bearerFormat ?? '',
},
},
};
case 'mutualTLS':
return {
scheme: {
$case: 'mtlsSecurityScheme',
value: {
description: scheme.description ?? '',
},
},
};
case 'oauth2':
return {
scheme: {
$case: 'oauth2SecurityScheme',
value: {
description: scheme.description ?? '',
flows: ToProto.oauthFlows(scheme.flows),
oauth2MetadataUrl: scheme.oauth2MetadataUrl ?? '',
},
},
};
case 'openIdConnect':
return {
scheme: {
$case: 'openIdConnectSecurityScheme',
value: {
description: scheme.description ?? '',
openIdConnectUrl: scheme.openIdConnectUrl,
},
},
};
default:
throw A2AError.internalError(`Unsupported security scheme type`);
}
}
static oauthFlows(flows: types.OAuthFlows): OAuthFlows {
if (flows.implicit) {
return {
flow: {
$case: 'implicit',
value: {
authorizationUrl: flows.implicit.authorizationUrl,
scopes: flows.implicit.scopes,
refreshUrl: flows.implicit.refreshUrl ?? '',
},
},
};
} else if (flows.password) {
return {
flow: {
$case: 'password',
value: {
tokenUrl: flows.password.tokenUrl,
scopes: flows.password.scopes,
refreshUrl: flows.password.refreshUrl ?? '',
},
},
};
} else if (flows.clientCredentials) {
return {
flow: {
$case: 'clientCredentials',
value: {
tokenUrl: flows.clientCredentials.tokenUrl,
scopes: flows.clientCredentials.scopes,
refreshUrl: flows.clientCredentials.refreshUrl ?? '',
},
},
};
} else if (flows.authorizationCode) {
return {
flow: {
$case: 'authorizationCode',
value: {
authorizationUrl: flows.authorizationCode.authorizationUrl,
tokenUrl: flows.authorizationCode.tokenUrl,
scopes: flows.authorizationCode.scopes,
refreshUrl: flows.authorizationCode.refreshUrl ?? '',
},
},
};
} else {
throw A2AError.internalError(`Unsupported OAuth flows`);
}
}
static agentInterface(agentInterface: types.AgentInterface): AgentInterface {
return {
transport: agentInterface.transport,
url: agentInterface.url,
};
}
static agentProvider(agentProvider: types.AgentProvider): AgentProvider {
if (!agentProvider) {
return undefined;
}
return {
url: agentProvider.url,
organization: agentProvider.organization,
};
}
static agentCapabilities(capabilities: types.AgentCapabilities): AgentCapabilities {
return {
streaming: capabilities.streaming,
pushNotifications: capabilities.pushNotifications,
extensions: capabilities.extensions
? capabilities.extensions.map((e) => ToProto.agentExtension(e))
: [],
};
}
static agentExtension(extension: types.AgentExtension): AgentExtension {
return {
uri: extension.uri,
description: extension.description ?? '',
required: extension.required ?? false,
params: extension.params,
};
}
static listTaskPushNotificationConfig(
config: types.TaskPushNotificationConfig[]
): ListTaskPushNotificationConfigResponse {
return {
configs: config.map((c) => ToProto.taskPushNotificationConfig(c)),
nextPageToken: '',
};
}
static getTaskPushNotificationConfigParams(
config: types.GetTaskPushNotificationConfigParams
): GetTaskPushNotificationConfigRequest {
return {
name: generatePushNotificationConfigName(config.id, config.pushNotificationConfigId),
};
}
static listTaskPushNotificationConfigParams(
config: types.ListTaskPushNotificationConfigParams
): ListTaskPushNotificationConfigRequest {
return {
parent: generateTaskName(config.id),
pageToken: '',
pageSize: 0,
};
}
static deleteTaskPushNotificationConfigParams(
config: types.DeleteTaskPushNotificationConfigParams
): DeleteTaskPushNotificationConfigRequest {
return {
name: generatePushNotificationConfigName(config.id, config.pushNotificationConfigId),
};
}
static taskPushNotificationConfig(
config: types.TaskPushNotificationConfig
): TaskPushNotificationConfig {
return {
name: generatePushNotificationConfigName(
config.taskId,
config.pushNotificationConfig.id ?? ''
),
pushNotificationConfig: ToProto.pushNotificationConfig(config.pushNotificationConfig),
};
}
static taskPushNotificationConfigCreate(
config: types.TaskPushNotificationConfig
): CreateTaskPushNotificationConfigRequest {
return {
parent: generateTaskName(config.taskId),
config: ToProto.taskPushNotificationConfig(config),
configId: config.pushNotificationConfig.id,
};
}
static pushNotificationConfig(config: types.PushNotificationConfig): PushNotificationConfig {
if (!config) {
return undefined;
}
return {
id: config.id ?? '',
url: config.url,
token: config.token ?? '',
authentication: ToProto.pushNotificationAuthenticationInfo(config.authentication),
};
}
static pushNotificationAuthenticationInfo(
authInfo: types.PushNotificationAuthenticationInfo
): AuthenticationInfo | undefined {
if (!authInfo) {
return undefined;
}
return {
schemes: authInfo.schemes,
credentials: authInfo.credentials ?? '',
};
}
static messageStreamResult(
event: types.Message | types.Task | types.TaskStatusUpdateEvent | types.TaskArtifactUpdateEvent
): StreamResponse {
if (event.kind === 'message') {
return {
payload: {
$case: 'msg',
value: ToProto.message(event),
},
};
} else if (event.kind === 'task') {
return {
payload: {
$case: 'task',
value: ToProto.task(event),
},
};
} else if (event.kind === 'status-update') {
return {
payload: {
$case: 'statusUpdate',
value: ToProto.taskStatusUpdateEvent(event),
},
};
} else if (event.kind === 'artifact-update') {
return {
payload: {
$case: 'artifactUpdate',
value: ToProto.taskArtifactUpdateEvent(event),
},
};
} else {
throw A2AError.internalError('Invalid event type');
}
}
static taskStatusUpdateEvent(event: types.TaskStatusUpdateEvent): TaskStatusUpdateEvent {
return {
taskId: event.taskId,
status: ToProto.taskStatus(event.status),
contextId: event.contextId,
metadata: event.metadata,
final: event.final,
};
}
static taskArtifactUpdateEvent(event: types.TaskArtifactUpdateEvent): TaskArtifactUpdateEvent {
return {
taskId: event.taskId,
artifact: ToProto.artifact(event.artifact),
contextId: event.contextId,
metadata: event.metadata,
append: event.append,
lastChunk: event.lastChunk,
};
}
static messageSendResult(params: types.Message | types.Task): SendMessageResponse {
if (params.kind === 'message') {
return {
payload: {
$case: 'msg',
value: ToProto.message(params),
},
};
} else if (params.kind === 'task') {
return {
payload: {
$case: 'task',
value: ToProto.task(params),
},
};
}
}
static message(message: types.Message): Message | undefined {
if (!message) {
return undefined;
}
return {
messageId: message.messageId,
content: message.parts.map((p) => ToProto.part(p)),
contextId: message.contextId ?? '',
taskId: message.taskId ?? '',
role: ToProto.role(message.role),
metadata: message.metadata,
extensions: message.extensions ?? [],
};
}
static role(role: string): Role {
switch (role) {
case 'agent':
return Role.ROLE_AGENT;
case 'user':
return Role.ROLE_USER;
default:
throw A2AError.internalError(`Invalid role`);
}
}
static task(task: types.Task): Task {
return {
id: task.id,
contextId: task.contextId,
status: ToProto.taskStatus(task.status),
artifacts: task.artifacts?.map((a) => ToProto.artifact(a)) ?? [],
history: task.history?.map((m) => ToProto.message(m)) ?? [],
metadata: task.metadata,
};
}
static taskStatus(status: types.TaskStatus): TaskStatus {
return {
state: ToProto.taskState(status.state),
update: ToProto.message(status.message),
timestamp: status.timestamp,
};
}
static artifact(artifact: types.Artifact): Artifact {
return {
artifactId: artifact.artifactId,
name: artifact.name ?? '',
description: artifact.description ?? '',
parts: artifact.parts.map((p) => ToProto.part(p)),
metadata: artifact.metadata,
extensions: artifact.extensions ? artifact.extensions : [],
};
}
static taskState(state: types.TaskState): TaskState {
switch (state) {
case 'submitted':
return TaskState.TASK_STATE_SUBMITTED;
case 'working':
return TaskState.TASK_STATE_WORKING;
case 'input-required':
return TaskState.TASK_STATE_INPUT_REQUIRED;
case 'rejected':
return TaskState.TASK_STATE_REJECTED;
case 'auth-required':
return TaskState.TASK_STATE_AUTH_REQUIRED;
case 'completed':
return TaskState.TASK_STATE_COMPLETED;
case 'failed':
return TaskState.TASK_STATE_FAILED;
case 'canceled':
return TaskState.TASK_STATE_CANCELLED;
case 'unknown':
return TaskState.TASK_STATE_UNSPECIFIED;
default:
return TaskState.UNRECOGNIZED;
}
}
static part(part: types.Part): Part {
if (part.kind === 'text') {
return {
part: { $case: 'text', value: part.text },
};
}
if (part.kind === 'file') {
let filePart: ProtoFilePart;
if ('uri' in part.file) {
filePart = {
file: { $case: 'fileWithUri', value: part.file.uri },
mimeType: part.file.mimeType,
};
} else if ('bytes' in part.file) {
filePart = {
file: { $case: 'fileWithBytes', value: Buffer.from(part.file.bytes, 'base64') },
mimeType: part.file.mimeType,
};
} else {
throw A2AError.internalError('Invalid file part');
}
return {
part: { $case: 'file', value: filePart },
};
}
if (part.kind === 'data') {
return {
part: { $case: 'data', value: { data: part.data } },
};
}
throw A2AError.internalError('Invalid part type');
}
static messageSendParams(params: types.MessageSendParams): SendMessageRequest {
return {
request: ToProto.message(params.message),
configuration: ToProto.configuration(params.configuration),
metadata: params.metadata,
};
}
static configuration(configuration: types.MessageSendConfiguration): SendMessageConfiguration {
if (!configuration) {
return undefined;
}
return {
blocking: configuration.blocking,
acceptedOutputModes: configuration.acceptedOutputModes ?? [],
pushNotification: ToProto.pushNotificationConfig(configuration.pushNotificationConfig),
historyLength: configuration.historyLength ?? 0,
};
}
static taskQueryParams(params: types.TaskQueryParams): GetTaskRequest {
return {
name: generateTaskName(params.id),
historyLength: params.historyLength ?? 0,
};
}
static cancelTaskRequest(params: types.TaskIdParams): CancelTaskRequest {
return {
name: generateTaskName(params.id),
};
}
static taskIdParams(params: types.TaskIdParams): TaskSubscriptionRequest {
return {
name: generateTaskName(params.id),
};
}
static getAgentCardRequest(): GetAgentCardRequest {
return {};
}
}

2480
src/types/pb/a2a_types.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
import express from 'express';
import { Server, ServerCredentials } from '@grpc/grpc-js';
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
import { AgentCard, Task, TaskStatusUpdateEvent, Message } from '../../src/index.js';
@ -16,6 +17,7 @@ import {
restHandler,
UserBuilder,
} from '../../src/server/express/index.js';
import { grpcService, A2AService } from '../../src/server/grpc/index.js';
/**
* SUTAgentExecutor implements the agent's core logic.
@ -183,6 +185,7 @@ const SUTAgentCard: AgentCard = {
additionalInterfaces: [
{ url: 'http://localhost:41241/a2a/jsonrpc', transport: 'JSONRPC' },
{ url: 'http://localhost:41241/a2a/rest', transport: 'HTTP+JSON' },
{ url: 'http://localhost:41242', transport: 'GRPC' },
],
};
@ -218,15 +221,27 @@ async function main() {
);
// 5. Start the server
const PORT = process.env.PORT || 41241;
expressApp.listen(PORT, (err) => {
const HTTP_PORT = process.env.HTTP_PORT || 41241;
expressApp.listen(HTTP_PORT, (err) => {
if (err) {
throw err;
}
console.log(`[SUTAgent] Server using new framework started on http://localhost:${PORT}`);
console.log(`[SUTAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`);
console.log(`[SUTAgent] HTTP server started on http://localhost:${HTTP_PORT}`);
console.log(`[SUTAgent] Agent Card: http://localhost:${HTTP_PORT}/.well-known/agent-card.json`);
console.log('[SUTAgent] Press Ctrl+C to stop the server');
});
// 6. Start the gRPC server on a different port
const GRPC_PORT = process.env.GRPC_PORT || 41242;
const grpcHandlerInstance = grpcService({
requestHandler,
userBuilder: UserBuilder.noAuthentication,
});
const server = new Server();
server.addService(A2AService, grpcHandlerInstance);
server.bindAsync(`localhost:${GRPC_PORT}`, ServerCredentials.createInsecure(), () => {
console.log(`[SUTAgent] gRPC server running at localhost:${GRPC_PORT}`);
});
}
main().catch(console.error);

View File

@ -1,10 +1,10 @@
import { describe, it, beforeEach, expect } from 'vitest';
import { describe, it, beforeEach, expect, vi, Mock } from 'vitest';
import { DefaultAgentCardResolver } from '../../src/client/card-resolver.js';
import sinon from 'sinon';
import { AgentCard } from '../../src/types.js';
import { AgentCard as PBAgentCard } from '../../src/types/pb/a2a_types.js';
describe('DefaultAgentCardResolver', () => {
let mockFetch: sinon.SinonStub;
let mockFetch: Mock;
const testAgentCard: AgentCard = {
protocolVersion: '0.3.0',
@ -23,12 +23,12 @@ describe('DefaultAgentCardResolver', () => {
};
beforeEach(() => {
mockFetch = sinon.stub();
mockFetch = vi.fn();
});
it('should fetch the agent card', async () => {
const resolver = new DefaultAgentCardResolver({ fetchImpl: mockFetch });
mockFetch.resolves(
mockFetch.mockResolvedValue(
new Response(JSON.stringify(testAgentCard), {
status: 200,
})
@ -37,11 +37,11 @@ describe('DefaultAgentCardResolver', () => {
const actual = await resolver.resolve('https://example.com');
expect(actual).to.deep.equal(testAgentCard);
expect(
mockFetch.calledOnceWith(
sinon.match.has('href', 'https://example.com/.well-known/agent-card.json')
)
).to.be.true;
expect(mockFetch).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
href: 'https://example.com/.well-known/agent-card.json',
})
);
});
const pathTests = [
@ -68,7 +68,7 @@ describe('DefaultAgentCardResolver', () => {
fetchImpl: mockFetch,
path: test.path,
});
mockFetch.resolves(
mockFetch.mockResolvedValue(
new Response(JSON.stringify(testAgentCard), {
status: 200,
})
@ -77,14 +77,16 @@ describe('DefaultAgentCardResolver', () => {
const actual = await resolver.resolve(test.baseUrl);
expect(actual).to.deep.equal(testAgentCard);
expect(mockFetch.calledOnceWithExactly(sinon.match.has('href', test.expected))).to.be.true;
expect(mockFetch).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ href: test.expected })
);
});
it(`should use custom path "${test.path}" from parameter`, async () => {
const resolver = new DefaultAgentCardResolver({
fetchImpl: mockFetch,
});
mockFetch.resolves(
mockFetch.mockResolvedValue(
new Response(JSON.stringify(testAgentCard), {
status: 200,
})
@ -93,7 +95,9 @@ describe('DefaultAgentCardResolver', () => {
const actual = await resolver.resolve(test.baseUrl, test.path);
expect(actual).to.deep.equal(testAgentCard);
expect(mockFetch.calledOnceWith(sinon.match.has('href', test.expected))).to.be.true;
expect(mockFetch).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ href: test.expected })
);
});
});
@ -115,12 +119,12 @@ describe('DefaultAgentCardResolver', () => {
const actual = await resolver.resolve('https://example.com');
expect(actual).to.deep.equal(testAgentCard);
expect(mockFetch.notCalled).to.be.true;
expect(mockFetch).not.toHaveBeenCalled();
});
it('should throw on non-OK response', async () => {
const resolver = new DefaultAgentCardResolver({ fetchImpl: mockFetch });
mockFetch.resolves(
mockFetch.mockResolvedValue(
new Response(JSON.stringify(testAgentCard), {
status: 404,
})
@ -133,4 +137,134 @@ describe('DefaultAgentCardResolver', () => {
expect(e.message).to.include('Failed to fetch Agent Card from https://example.com');
}
});
const expectedAgentCard: AgentCard = {
protocolVersion: '0.3.0',
name: 'Unified Agent',
description: '',
documentationUrl: undefined,
version: '1.0.0',
capabilities: {},
additionalInterfaces: [],
provider: undefined,
defaultInputModes: [],
defaultOutputModes: [],
supportsAuthenticatedExtendedCard: false,
signatures: [],
url: 'https://unified-agent.example.com/a2a/v1',
preferredTransport: 'GRPC',
securitySchemes: {
google: {
type: 'openIdConnect',
openIdConnectUrl: 'https://accounts.google.com/.well-known/openid-configuration',
},
},
security: [{ google: ['openid', 'profile', 'email'] }],
skills: [],
};
const JsonSchemaAgentCard: AgentCard = {
// A JSON Schema shape is essentially identical to the internal format
...expectedAgentCard,
};
const ProtoAgentCard: PBAgentCard = {
protocolVersion: '0.3.0',
name: 'Unified Agent',
description: '',
documentationUrl: '',
version: '1.0.0',
capabilities: undefined,
additionalInterfaces: [],
provider: undefined,
defaultInputModes: [],
defaultOutputModes: [],
supportsAuthenticatedExtendedCard: false,
signatures: [],
url: 'https://unified-agent.example.com/a2a/v1',
preferredTransport: 'GRPC',
securitySchemes: {
google: {
scheme: {
$case: 'openIdConnectSecurityScheme',
value: {
description: '',
openIdConnectUrl: 'https://accounts.google.com/.well-known/openid-configuration',
},
},
},
},
security: [
{
schemes: {
google: { list: ['openid', 'profile', 'email'] },
},
},
],
skills: [],
};
const expectedAgentCardWithSkill: AgentCard = {
...expectedAgentCard,
security: [],
securitySchemes: {},
skills: [
{
id: 'test-skill',
name: 'Test Skill',
description: 'A skill for testing',
tags: [],
examples: [],
inputModes: [],
outputModes: [],
security: [{ google: ['openid'] }],
},
],
};
const ProtoAgentCardWithSkill: PBAgentCard = {
...ProtoAgentCard,
security: [],
securitySchemes: {},
skills: [
{
id: 'test-skill',
name: 'Test Skill',
description: 'A skill for testing',
tags: [],
examples: [],
inputModes: [],
outputModes: [],
security: [
{
schemes: {
google: { list: ['openid'] },
},
},
],
},
],
};
it.each([
['JSON schema', JsonSchemaAgentCard, expectedAgentCard],
['protobuf', PBAgentCard.toJSON(ProtoAgentCard), expectedAgentCard],
[
'protobuf (skills only)',
PBAgentCard.toJSON(ProtoAgentCardWithSkill),
expectedAgentCardWithSkill,
],
])('should parse and normalize %s agent card correctly', async (_, payload, expectedResult) => {
const resolver = new DefaultAgentCardResolver({ fetchImpl: mockFetch });
mockFetch.mockResolvedValue(new Response(JSON.stringify(payload), { status: 200 }));
const actual = await resolver.resolve('https://example.com');
// Both should normalize to the exact same internal AgentCard format
// Strip undefined properties before comparison using JSON
const expected = JSON.parse(JSON.stringify(expectedResult));
const actualClean = JSON.parse(JSON.stringify(actual));
expect(actualClean).to.deep.equal(expected);
});
});

View File

@ -1,5 +1,4 @@
import { describe, it, beforeEach, afterEach, expect } from 'vitest';
import sinon from 'sinon';
import { describe, it, beforeEach, afterEach, expect, vi, Mock } from 'vitest';
import { A2AClient } from '../../src/client/client.js';
import {
MessageSendParams,
@ -45,7 +44,7 @@ function isErrorResponse(response: any): response is JSONRPCErrorResponse {
describe('A2AClient Basic Tests', () => {
let client: A2AClient;
let mockFetch: sinon.SinonStub;
let mockFetch: Mock & { capturedAuthHeaders: string[] };
let originalConsoleError: typeof console.error;
const agentCardUrl = `https://test-agent.example.com/${AGENT_CARD_PATH}`;
const agentBaseUrl = 'https://test-agent.example.com';
@ -65,7 +64,7 @@ describe('A2AClient Basic Tests', () => {
afterEach(() => {
// Restore console.error
console.error = originalConsoleError;
sinon.restore();
vi.restoreAllMocks();
});
describe('Client Initialization', () => {
@ -79,9 +78,9 @@ describe('A2AClient Basic Tests', () => {
});
it('should initialize client with custom fetch implementation', async () => {
const customFetch = sinon
.stub()
.resolves(new Response(JSON.stringify(createMockAgentCard()), { status: 200 }));
const customFetch = vi
.fn()
.mockResolvedValue(new Response(JSON.stringify(createMockAgentCard()), { status: 200 }));
const clientWithCustomFetch = await A2AClient.fromCardUrl(agentCardUrl, {
fetchImpl: customFetch,
});
@ -120,32 +119,29 @@ describe('A2AClient Basic Tests', () => {
// Wait for agent card to be fetched
await client.getAgentCard();
expect(mockFetch.callCount).to.be.greaterThan(0);
const agentCardCall = mockFetch
.getCalls()
.find((call) => call.args[0].includes(AGENT_CARD_PATH));
expect(mockFetch.mock.calls.length).to.be.greaterThan(0);
const agentCardCall = mockFetch.mock.calls.find((args) =>
(args[0] as string).includes(AGENT_CARD_PATH)
);
expect(agentCardCall).to.exist;
});
});
describe('Backward Compatibility', () => {
it('should construct with a URL and log a warning', async () => {
const consoleWarnSpy = sinon.spy(console, 'warn');
const consoleWarnSpy = vi.spyOn(console, 'warn');
const backwardCompatibleClient = new A2AClient(agentBaseUrl, {
fetchImpl: mockFetch,
});
expect(consoleWarnSpy.calledOnce).to.be.true;
expect(
consoleWarnSpy.calledWith(
'Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead.'
)
).to.be.true;
expect(consoleWarnSpy).toHaveBeenCalledExactlyOnceWith(
'Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead.'
);
const agentCard = await backwardCompatibleClient.getAgentCard();
expect(agentCard).to.have.property('name', 'Test Agent');
consoleWarnSpy.restore();
consoleWarnSpy.mockRestore();
});
});
@ -168,15 +164,15 @@ describe('A2AClient Basic Tests', () => {
// Second call - should not fetch agent card again
await client.getAgentCard();
const agentCardCalls = mockFetch
.getCalls()
.filter((call) => call.args[0].includes(AGENT_CARD_PATH));
const agentCardCalls = mockFetch.mock.calls.filter((args) =>
(args[0] as string).includes(AGENT_CARD_PATH)
);
expect(agentCardCalls).to.have.length(1);
});
it('should handle agent card fetch errors', async () => {
const errorFetch = sinon.stub().callsFake(async (url: string) => {
const errorFetch = vi.fn().mockImplementation(async (url: string) => {
if (url.includes(AGENT_CARD_PATH)) {
return new Response('Not found', { status: 404 });
}
@ -215,19 +211,19 @@ describe('A2AClient Basic Tests', () => {
const result = await client.sendMessage(messageParams);
// Verify fetch was called
expect(mockFetch.callCount).to.be.greaterThan(0);
expect(mockFetch.mock.calls.length).to.be.greaterThan(0);
// Verify RPC call was made
const rpcCall = mockFetch.getCalls().find((call) => call.args[0].includes('/api'));
const rpcCall = mockFetch.mock.calls.find((args) => (args[0] as string).includes('/api'));
expect(rpcCall).to.exist;
expect(rpcCall.args[1]).to.deep.include({
expect(rpcCall[1]).to.deep.include({
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
expect(rpcCall.args[1].body).to.include('"method":"message/send"');
expect(rpcCall[1].body).to.include('"method":"message/send"');
// Verify the result
expect(isSuccessResponse(result)).to.be.true;
@ -238,7 +234,7 @@ describe('A2AClient Basic Tests', () => {
});
it('should handle message sending errors', async () => {
const errorFetch = sinon.stub().callsFake(async (url: string, options?: RequestInit) => {
const errorFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
if (url.includes(AGENT_CARD_PATH)) {
const mockAgentCard = createMockAgentCard({
description: 'A test agent for error testing',
@ -293,7 +289,7 @@ describe('A2AClient Basic Tests', () => {
describe('Error Handling', () => {
it('should handle network errors gracefully', async () => {
const networkErrorFetch = sinon.stub().rejects(new Error('Network error'));
const networkErrorFetch = vi.fn().mockRejectedValue(new Error('Network error'));
try {
await A2AClient.fromCardUrl(agentCardUrl, {
@ -307,7 +303,7 @@ describe('A2AClient Basic Tests', () => {
});
it('should handle malformed JSON responses', async () => {
const malformedFetch = sinon.stub().callsFake(async (url: string) => {
const malformedFetch = vi.fn().mockImplementation(async (url: string) => {
if (url.includes(AGENT_CARD_PATH)) {
return new Response('Invalid JSON', {
status: 200,
@ -328,7 +324,7 @@ describe('A2AClient Basic Tests', () => {
});
it('should handle missing agent card URL', async () => {
const missingUrlFetch = sinon.stub().callsFake(async (url: string) => {
const missingUrlFetch = vi.fn().mockImplementation(async (url: string) => {
if (url.includes(AGENT_CARD_PATH)) {
const invalidAgentCard = {
name: 'Test Agent',
@ -386,7 +382,7 @@ describe('A2AClient Basic Tests', () => {
// Getting the card should return the provided card without a fetch call
const agentCard = await clientFromCard.getAgentCard();
expect(agentCard).to.deep.equal(mockAgentCard);
expect(mockFetchForStatic.called).to.be.false;
expect(mockFetchForStatic.mock.calls.length).to.equal(0);
// Test sending a message to ensure serviceEndpointUrl is set
const messageParams: MessageSendParams = {
@ -406,9 +402,9 @@ describe('A2AClient Basic Tests', () => {
const result = await clientFromCard.sendMessage(messageParams);
// Verify fetch was called for the RPC request
expect(mockFetchForStatic.calledOnce).to.be.true;
const rpcCall = mockFetchForStatic.getCall(0);
expect(rpcCall.args[0]).to.equal('https://static-agent.example.com/api');
expect(mockFetchForStatic.mock.calls.length).to.equal(1);
const rpcCall = mockFetchForStatic.mock.calls[0];
expect(rpcCall[0]).to.equal('https://static-agent.example.com/api');
expect(isSuccessResponse(result)).to.be.true;
});
@ -442,7 +438,7 @@ describe('A2AClient Basic Tests', () => {
});
describe('Extension Methods', () => {
let mockFetch: sinon.SinonStub;
let mockFetch: Mock & { capturedAuthHeaders: string[] };
let originalConsoleError: typeof console.error;
const agentCardUrl = `https://test-agent.example.com/${AGENT_CARD_PATH}`;
@ -461,7 +457,7 @@ describe('Extension Methods', () => {
afterEach(() => {
// Restore console.error
console.error = originalConsoleError;
sinon.restore();
vi.restoreAllMocks();
});
describe('callExtensionMethod', () => {
@ -492,7 +488,7 @@ describe('Extension Methods', () => {
};
// Setup custom fetch mock for this specific test
const customFetch = sinon.stub().callsFake(async (url: string, options?: RequestInit) => {
const customFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
if (url.includes(AGENT_CARD_PATH)) {
return createAgentCardResponse(createMockAgentCard());
}
@ -552,7 +548,7 @@ describe('Extension Methods', () => {
};
// Setup custom fetch mock for this specific test
const errorFetch = sinon.stub().callsFake(async (url: string, options?: RequestInit) => {
const errorFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
if (url.includes(AGENT_CARD_PATH)) {
return createAgentCardResponse(createMockAgentCard());
}
@ -613,7 +609,7 @@ describe('Push Notification Config Operations', () => {
afterEach(() => {
// Restore console.error
console.error = originalConsoleError;
sinon.restore();
vi.restoreAllMocks();
});
describe('listTaskPushNotificationConfig', () => {
@ -638,7 +634,7 @@ describe('Push Notification Config Operations', () => {
];
// Setup custom mock fetch for this specific test
const customFetch = sinon.stub().callsFake(async (url: string, options?: RequestInit) => {
const customFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
if (url.includes(AGENT_CARD_PATH)) {
const mockAgentCard = createMockAgentCard({
capabilities: { pushNotifications: true },
@ -714,7 +710,7 @@ describe('Push Notification Config Operations', () => {
};
// Setup custom mock fetch for this specific test
const customFetch = sinon.stub().callsFake(async (url: string, options?: RequestInit) => {
const customFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
if (url.includes(AGENT_CARD_PATH)) {
const mockAgentCard = createMockAgentCard({
capabilities: { pushNotifications: true },

View File

@ -1,5 +1,4 @@
import { describe, it, beforeEach, afterEach, expect } from 'vitest';
import sinon from 'sinon';
import { describe, it, beforeEach, afterEach, expect, vi, type Mock } from 'vitest';
import { A2AClient } from '../../src/client/client.js';
import {
AuthenticationHandler,
@ -78,7 +77,7 @@ function isSuccessResponse(response: SendMessageResponse): response is SendMessa
describe('A2AClient Authentication Tests', () => {
let client: A2AClient;
let authHandler: MockAuthHandler;
let mockFetch: sinon.SinonStub;
let mockFetch: Mock & { capturedAuthHeaders: string[] };
let originalConsoleError: typeof console.error;
const agentCardUrl = `https://test-agent.example.com/${AGENT_CARD_PATH}`;
@ -109,7 +108,7 @@ describe('A2AClient Authentication Tests', () => {
afterEach(() => {
// Restore console.error
console.error = originalConsoleError;
sinon.restore();
vi.restoreAllMocks();
});
describe('Authentication Flow', () => {
@ -123,40 +122,40 @@ describe('A2AClient Authentication Tests', () => {
const result = await client.sendMessage(messageParams);
// Verify fetch was called multiple times
expect(mockFetch.callCount).to.equal(3);
expect(mockFetch.mock.calls.length).to.equal(3);
// First call: agent card fetch
expect(mockFetch.firstCall.args[0]).to.equal(agentCardUrl);
expect(mockFetch.firstCall.args[1]).to.deep.include({
expect(mockFetch.mock.calls[0][0]).to.equal(agentCardUrl);
expect(mockFetch.mock.calls[0][1]).to.deep.include({
headers: { Accept: 'application/json' },
});
// Second call: RPC request without auth header
expect(mockFetch.secondCall.args[0]).to.equal('https://test-agent.example.com/api');
expect(mockFetch.secondCall.args[1]).to.deep.include({
expect(mockFetch.mock.calls[1][0]).to.equal('https://test-agent.example.com/api');
expect(mockFetch.mock.calls[1][1]).to.deep.include({
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
expect(mockFetch.secondCall.args[1].body).to.include('"method":"message/send"');
expect(mockFetch.mock.calls[1][1].body).to.include('"method":"message/send"');
// Third call: RPC request with auth header
expect(mockFetch.thirdCall.args[0]).to.equal('https://test-agent.example.com/api');
expect(mockFetch.thirdCall.args[1]).to.deep.include({
expect(mockFetch.mock.calls[2][0]).to.equal('https://test-agent.example.com/api');
expect(mockFetch.mock.calls[2][1]).to.deep.include({
method: 'POST',
});
// Check headers separately to avoid issues with Authorization header
expect(mockFetch.thirdCall.args[1].headers).to.have.property(
expect(mockFetch.mock.calls[2][1].headers).to.have.property(
'Content-Type',
'application/json'
);
expect(mockFetch.thirdCall.args[1].headers).to.have.property('Accept', 'application/json');
expect(mockFetch.thirdCall.args[1].headers).to.have.property('Authorization');
expect(mockFetch.mock.calls[2][1].headers).to.have.property('Accept', 'application/json');
expect(mockFetch.mock.calls[2][1].headers).to.have.property('Authorization');
expect(mockFetch.thirdCall.args[1].headers['Authorization']).to.match(/^Bearer .+$/);
expect(mockFetch.thirdCall.args[1].body).to.include('"method":"message/send"');
expect(mockFetch.mock.calls[2][1].headers['Authorization']).to.match(/^Bearer .+$/);
expect(mockFetch.mock.calls[2][1].body).to.include('"method":"message/send"');
// Verify the result
expect(isSuccessResponse(result)).to.be.true;
@ -175,26 +174,26 @@ describe('A2AClient Authentication Tests', () => {
await client.sendMessage(messageParams);
// Capture the token from the first request
const firstRequestAuthCall = mockFetch
.getCalls()
.find((call) => call.args[0].includes('/api') && call.args[1]?.headers?.['Authorization']);
const firstRequestToken = firstRequestAuthCall?.args[1]?.headers?.['Authorization'];
const firstRequestAuthCall = mockFetch.mock.calls.find(
(args) => (args[0] as string).includes('/api') && args[1].headers?.['Authorization']
);
const firstRequestToken = firstRequestAuthCall?.[1]?.headers?.['Authorization'];
// Second request - should use existing token
const result2 = await client.sendMessage(messageParams);
// Total calls should be 4: 3 for first request + 1 for second request (both agent card and auth token cached)
expect(mockFetch.callCount).to.equal(4);
expect(mockFetch.mock.calls.length).to.equal(4);
// Second request should start from call #4 (after the first 3 calls)
const secondRequestCalls = mockFetch.getCalls().slice(3);
const secondRequestCalls = mockFetch.mock.calls.slice(3);
// Only one call for second request: RPC request with auth header (agent card and token cached)
expect(secondRequestCalls[0].args[0]).to.equal('https://test-agent.example.com/api');
expect(secondRequestCalls[0].args[1].headers).to.have.property('Authorization');
expect(secondRequestCalls[0][0]).to.equal('https://test-agent.example.com/api');
expect(secondRequestCalls[0][1].headers).to.have.property('Authorization');
// Should use the exact same token from the first request
expect(secondRequestCalls[0].args[1].headers['Authorization']).to.equal(firstRequestToken);
expect(secondRequestCalls[0][1].headers['Authorization']).to.equal(firstRequestToken);
expect(isSuccessResponse(result2)).to.be.true;
});
@ -203,9 +202,9 @@ describe('A2AClient Authentication Tests', () => {
describe('Authentication Handler Integration', () => {
it('should call auth handler methods correctly', async () => {
const authHandlerSpy = {
headers: sinon.spy(authHandler, 'headers'),
shouldRetryWithHeaders: sinon.spy(authHandler, 'shouldRetryWithHeaders'),
onSuccess: sinon.spy(authHandler, 'onSuccessfulRetry'),
headers: vi.spyOn(authHandler, 'headers'),
shouldRetryWithHeaders: vi.spyOn(authHandler, 'shouldRetryWithHeaders'),
onSuccess: vi.spyOn(authHandler, 'onSuccessfulRetry'),
};
const messageParams = createMessageParams({
@ -216,16 +215,16 @@ describe('A2AClient Authentication Tests', () => {
await client.sendMessage(messageParams);
// Verify auth handler methods were called
expect(authHandlerSpy.headers.called).to.be.true;
expect(authHandlerSpy.shouldRetryWithHeaders.called).to.be.true;
expect(authHandlerSpy.onSuccess.called).to.be.true;
expect(authHandlerSpy.headers).toHaveBeenCalled();
expect(authHandlerSpy.shouldRetryWithHeaders).toHaveBeenCalled();
expect(authHandlerSpy.onSuccess).toHaveBeenCalled();
});
it('should handle auth handler returning undefined for retry', async () => {
// Create a mock that doesn't retry
const noRetryHandler = new MockAuthHandler();
noRetryHandler.shouldRetryWithHeaders.bind(noRetryHandler);
noRetryHandler.shouldRetryWithHeaders = sinon.stub().resolves(undefined);
// noRetryHandler.shouldRetryWithHeaders.bind(noRetryHandler);
noRetryHandler.shouldRetryWithHeaders = vi.fn().mockResolvedValue(undefined);
const clientNoRetry = await A2AClient.fromCardUrl(agentCardUrl, {
fetchImpl: mockFetch,
@ -347,13 +346,13 @@ describe('A2AClient Authentication Tests', () => {
expect((result as any).error).to.have.property('message', 'Authentication required');
// Verify that fetch was called only once (no retry attempted)
expect(fetchWithApiError.callCount).to.equal(2); // One for agent card, one for API call
expect(fetchWithApiError.mock.calls.length).to.equal(2); // One for agent card, one for API call
});
});
});
describe('AuthHandlingFetch Tests', () => {
let mockFetch: sinon.SinonStub;
let mockFetch: Mock & { capturedAuthHeaders: string[] };
let authHandler: MockAuthHandler;
let authHandlingFetch: ReturnType<typeof createAuthenticatingFetchWithRetry>;
@ -372,7 +371,7 @@ describe('AuthHandlingFetch Tests', () => {
});
afterEach(() => {
sinon.restore();
vi.restoreAllMocks();
});
describe('Constructor and Function Call', () => {
@ -410,8 +409,8 @@ describe('AuthHandlingFetch Tests', () => {
});
// Verify that the fetch was called with merged headers including auth headers
const fetchCall = mockFetch.getCall(0);
const headers = fetchCall.args[1]?.headers as Record<string, string>;
const fetchCallArgs = mockFetch.mock.calls[0];
const headers = fetchCallArgs[1]?.headers as Record<string, string>;
// Should include both user headers and auth headers
expect(headers).to.include({
@ -431,15 +430,15 @@ describe('AuthHandlingFetch Tests', () => {
await emptyAuthFetch('https://test.example.com/api');
const fetchCall = mockFetch.getCall(0);
expect(fetchCall.args[1]).to.exist;
const fetchCallArgs = mockFetch.mock.calls[0];
expect(fetchCallArgs[1]).to.exist;
});
});
describe('Success Callback', () => {
it('should call onSuccessfulRetry when retry succeeds', async () => {
const successAuthHandler = new MockAuthHandler();
const onSuccessSpy = sinon.spy(successAuthHandler, 'onSuccessfulRetry');
const onSuccessSpy = vi.spyOn(successAuthHandler, 'onSuccessfulRetry');
// Create a modified version of the existing mockFetch that returns 401 first, then 200
const successMockFetch = createMockFetch({
@ -457,15 +456,15 @@ describe('AuthHandlingFetch Tests', () => {
await successAuthFetch('https://test.example.com/api');
expect(onSuccessSpy.called).to.be.true;
expect(onSuccessSpy.firstCall.args[0]).to.deep.include({
expect(onSuccessSpy).toHaveBeenCalled();
expect(onSuccessSpy.mock.calls[0][0]).to.deep.include({
Authorization: 'Bearer challenge123.challenge123',
});
});
it('should not call onSuccessfulRetry when retry fails', async () => {
const failAuthHandler = new MockAuthHandler();
const onSuccessSpy = sinon.spy(failAuthHandler, 'onSuccessfulRetry');
const onSuccessSpy = vi.spyOn(failAuthHandler, 'onSuccessfulRetry');
createAuthenticatingFetchWithRetry(mockFetch, failAuthHandler);
@ -478,14 +477,14 @@ describe('AuthHandlingFetch Tests', () => {
const response = await failAuthFetch('https://test.example.com/api');
expect(onSuccessSpy.called).to.be.false;
expect(onSuccessSpy).not.toHaveBeenCalled();
expect(response.status).to.equal(401);
});
});
describe('Error Handling', () => {
it('should propagate fetch errors', async () => {
const errorFetch = sinon.stub().rejects(new Error('Network error'));
const errorFetch = vi.fn().mockRejectedValue(new Error('Network error'));
const errorAuthFetch = createAuthenticatingFetchWithRetry(errorFetch, authHandler);
try {
@ -499,8 +498,8 @@ describe('AuthHandlingFetch Tests', () => {
it('should handle auth handler errors gracefully', async () => {
const errorAuthHandler = new MockAuthHandler();
const shouldRetrySpy = sinon.stub(errorAuthHandler, 'shouldRetryWithHeaders');
shouldRetrySpy.rejects(new Error('Auth handler error'));
const shouldRetrySpy = vi.spyOn(errorAuthHandler, 'shouldRetryWithHeaders');
shouldRetrySpy.mockRejectedValue(new Error('Auth handler error'));
const errorAuthFetch = createAuthenticatingFetchWithRetry(mockFetch, errorAuthHandler);

View File

@ -1,42 +1,41 @@
import { describe, it, beforeEach, expect } from 'vitest';
import sinon from 'sinon';
import { describe, it, beforeEach, expect, vi, Mock } from 'vitest';
import { ClientFactory, ClientFactoryOptions } from '../../src/client/factory.js';
import { TransportFactory, Transport } from '../../src/client/transports/transport.js';
import { Transport } from '../../src/client/transports/transport.js';
import { JsonRpcTransportFactory } from '../../src/client/transports/json_rpc_transport.js';
import { AgentCard } from '../../src/types.js';
import { Client } from '../../src/client/multitransport-client.js';
import { CallInterceptor } from '../../src/client/interceptors.js';
describe('ClientFactory', () => {
let mockTransportFactory1: sinon.SinonStubbedInstance<TransportFactory>;
let mockTransportFactory2: sinon.SinonStubbedInstance<TransportFactory>;
let mockTransport: sinon.SinonStubbedInstance<Transport>;
let mockTransportFactory1: { protocolName: string; create: Mock };
let mockTransportFactory2: { protocolName: string; create: Mock };
let mockTransport: Record<keyof Transport, Mock>;
beforeEach(() => {
mockTransport = {
getExtendedAgentCard: sinon.stub(),
sendMessage: sinon.stub(),
sendMessageStream: sinon.stub(),
setTaskPushNotificationConfig: sinon.stub(),
getTaskPushNotificationConfig: sinon.stub(),
listTaskPushNotificationConfig: sinon.stub(),
deleteTaskPushNotificationConfig: sinon.stub(),
getTask: sinon.stub(),
cancelTask: sinon.stub(),
resubscribeTask: sinon.stub(),
getExtendedAgentCard: vi.fn(),
sendMessage: vi.fn(),
sendMessageStream: vi.fn(),
setTaskPushNotificationConfig: vi.fn(),
getTaskPushNotificationConfig: vi.fn(),
listTaskPushNotificationConfig: vi.fn(),
deleteTaskPushNotificationConfig: vi.fn(),
getTask: vi.fn(),
cancelTask: vi.fn(),
resubscribeTask: vi.fn(),
};
mockTransportFactory1 = {
protocolName: 'Transport1',
create: sinon.stub(),
create: vi.fn(),
};
mockTransportFactory1.create.resolves(mockTransport);
mockTransportFactory1.create.mockResolvedValue(mockTransport);
mockTransportFactory2 = {
protocolName: 'Transport2',
create: sinon.stub(),
create: vi.fn(),
};
mockTransportFactory2.create.resolves(mockTransport);
mockTransportFactory2.create.mockResolvedValue(mockTransport);
});
describe('constructor', () => {
@ -51,7 +50,7 @@ describe('ClientFactory', () => {
preferredTransports: ['UnknownTransport'],
};
expect(() => new ClientFactory(options)).to.throw(
'Unknown preferred transport: UnknownTransport, available transports: Transport1'
'Unknown preferred transport: UnknownTransport, available transports: TRANSPORT1'
);
});
@ -72,6 +71,30 @@ describe('ClientFactory', () => {
expect(factory.options).to.equal(options);
});
it('should accept preferred transport with different case', () => {
const options: ClientFactoryOptions = {
transports: [mockTransportFactory1],
preferredTransports: ['transport1'], // lowercase, but Transport1 is registered
};
// Should not throw
const factory = new ClientFactory(options);
expect(factory.options).to.equal(options);
});
it('should detect duplicate transports with different case as duplicates', () => {
const transport1Lower = {
protocolName: 'transport1', // lowercase
create: vi.fn(),
};
const options: ClientFactoryOptions = {
transports: [mockTransportFactory1, transport1Lower], // Transport1 and transport1
};
expect(() => new ClientFactory(options)).to.throw('Duplicate protocol name: transport1');
});
});
describe('createClient', () => {
@ -98,8 +121,10 @@ describe('ClientFactory', () => {
const client = await factory.createFromAgentCard(agentCard);
expect(client).to.be.instanceOf(Client);
expect(mockTransportFactory1.create.calledOnceWith('http://transport1.com', agentCard)).to.be
.true;
expect(mockTransportFactory1.create).toHaveBeenCalledExactlyOnceWith(
'http://transport1.com',
agentCard
);
});
it('should use factory preferred transport if available', async () => {
@ -111,7 +136,7 @@ describe('ClientFactory', () => {
await factory.createFromAgentCard(agentCard);
expect(mockTransportFactory2.create.calledOnce).to.be.true;
expect(mockTransportFactory2.create).toHaveBeenCalledTimes(1);
});
it('should throw error if no compatible transport found', async () => {
@ -134,20 +159,20 @@ describe('ClientFactory', () => {
await factory.createFromAgentCard(agentCard);
expect(mockTransportFactory1.create.calledOnce).to.be.true;
expect(mockTransportFactory1.create).toHaveBeenCalledTimes(1);
});
it('should default to JSONRPC transport if agentCard.preferredTransport is undefined', async () => {
agentCard.preferredTransport = undefined;
const jsonRpcFactory = {
protocolName: JsonRpcTransportFactory.name,
create: sinon.stub().resolves(mockTransport),
create: vi.fn().mockResolvedValue(mockTransport),
};
const factory = new ClientFactory({ transports: [jsonRpcFactory] });
await factory.createFromAgentCard(agentCard);
expect(jsonRpcFactory.create.calledOnce).to.be.true;
expect(jsonRpcFactory.create).toHaveBeenCalledTimes(1);
});
it('should pass clientConfig to the created Client', async () => {
@ -162,9 +187,49 @@ describe('ClientFactory', () => {
expect(client.config).to.equal(clientConfig);
});
it('should match transport with case-insensitive protocol name', async () => {
// Transport factory uses "Transport1" but agent card uses "transport1" (lowercase)
agentCard.preferredTransport = 'transport1';
const factory = new ClientFactory({ transports: [mockTransportFactory1] });
const client = await factory.createFromAgentCard(agentCard);
expect(client).to.be.instanceOf(Client);
expect(mockTransportFactory1.create).toHaveBeenCalledExactlyOnceWith(
'http://transport1.com',
agentCard
);
});
it('should match HTTP+JSON transport regardless of case', async () => {
const httpJsonFactory = {
protocolName: 'HTTP+JSON',
create: vi.fn().mockResolvedValue(mockTransport),
};
agentCard.preferredTransport = 'http+json'; // lowercase
const factory = new ClientFactory({ transports: [httpJsonFactory] });
await factory.createFromAgentCard(agentCard);
expect(httpJsonFactory.create).toHaveBeenCalledTimes(1);
});
it('should match JSONRPC transport regardless of case', async () => {
const jsonRpcFactory = {
protocolName: 'JSONRPC',
create: vi.fn().mockResolvedValue(mockTransport),
};
agentCard.preferredTransport = 'JsonRpc'; // mixed case
const factory = new ClientFactory({ transports: [jsonRpcFactory] });
await factory.createFromAgentCard(agentCard);
expect(jsonRpcFactory.create).toHaveBeenCalledTimes(1);
});
it('should use card resolver with default path', async () => {
const cardResolver = {
resolve: sinon.stub().resolves(agentCard),
resolve: vi.fn().mockResolvedValue(agentCard),
};
const factory = new ClientFactory({
transports: [mockTransportFactory1],
@ -173,13 +238,16 @@ describe('ClientFactory', () => {
await factory.createFromUrl('http://transport1.com');
expect(mockTransportFactory1.create.calledOnce);
expect(cardResolver.resolve.calledOnceWith('http://transport1.com')).to.be.true;
expect(mockTransportFactory1.create).toHaveBeenCalledTimes(1);
expect(cardResolver.resolve).toHaveBeenCalledExactlyOnceWith(
'http://transport1.com',
undefined
);
});
it('should use card resolver with custom path', async () => {
const cardResolver = {
resolve: sinon.stub().resolves(agentCard),
resolve: vi.fn().mockResolvedValue(agentCard),
};
const factory = new ClientFactory({
transports: [mockTransportFactory1],
@ -188,9 +256,11 @@ describe('ClientFactory', () => {
await factory.createFromUrl('http://transport1.com', 'a2a/my-agent-card.json');
expect(mockTransportFactory1.create.calledOnce);
expect(cardResolver.resolve.calledOnceWith('http://transport1.com', 'a2a/my-agent-card.json'))
.to.be.true;
expect(mockTransportFactory1.create).toHaveBeenCalledTimes(1);
expect(cardResolver.resolve).toHaveBeenCalledExactlyOnceWith(
'http://transport1.com',
'a2a/my-agent-card.json'
);
});
});
@ -200,13 +270,13 @@ describe('ClientFactory', () => {
transports: [mockTransportFactory1],
clientConfig: { polling: true },
preferredTransports: ['Transport1'],
cardResolver: { resolve: sinon.stub() } as any,
cardResolver: { resolve: vi.fn() } as any,
};
const overrides: Partial<ClientFactoryOptions> = {
transports: [mockTransportFactory2],
clientConfig: { polling: false, acceptedOutputModes: undefined, interceptors: undefined },
preferredTransports: ['Transport2'],
cardResolver: { resolve: sinon.stub() } as any,
cardResolver: { resolve: vi.fn() } as any,
};
const result = ClientFactoryOptions.createFrom(original, overrides);
expect(result.transports).to.deep.equal([mockTransportFactory1, mockTransportFactory2]);
@ -247,15 +317,15 @@ describe('ClientFactory', () => {
it('should merge transports arrays by protocol name', () => {
const transport1Factory = {
protocolName: 'Transport1',
create: sinon.stub(),
create: vi.fn(),
};
const transport1FactoryOverride = {
protocolName: 'Transport1',
create: sinon.stub(),
create: vi.fn(),
};
const transport2Factory = {
protocolName: 'Transport2',
create: sinon.stub(),
create: vi.fn(),
};
const original: ClientFactoryOptions = { transports: [transport1Factory] };
const overrides: Partial<ClientFactoryOptions> = {

View File

@ -1,5 +1,4 @@
import { describe, it, beforeEach, expect } from 'vitest';
import sinon from 'sinon';
import { describe, it, beforeEach, expect, vi, Mock } from 'vitest';
import { Client, ClientConfig, RequestOptions } from '../../src/client/multitransport-client.js';
import { Transport } from '../../src/client/transports/transport.js';
import {
@ -19,22 +18,22 @@ import { A2AStreamEventData } from '../../src/client/client.js';
import { ClientCallResult } from '../../src/client/interceptors.js';
describe('Client', () => {
let transport: sinon.SinonStubbedInstance<Transport>;
let transport: Record<keyof Transport, Mock>;
let client: Client;
let agentCard: AgentCard;
beforeEach(() => {
transport = {
getExtendedAgentCard: sinon.stub(),
sendMessage: sinon.stub(),
sendMessageStream: sinon.stub(),
setTaskPushNotificationConfig: sinon.stub(),
getTaskPushNotificationConfig: sinon.stub(),
listTaskPushNotificationConfig: sinon.stub(),
deleteTaskPushNotificationConfig: sinon.stub(),
getTask: sinon.stub(),
cancelTask: sinon.stub(),
resubscribeTask: sinon.stub(),
getExtendedAgentCard: vi.fn(),
sendMessage: vi.fn(),
sendMessageStream: vi.fn(),
setTaskPushNotificationConfig: vi.fn(),
getTaskPushNotificationConfig: vi.fn(),
listTaskPushNotificationConfig: vi.fn(),
deleteTaskPushNotificationConfig: vi.fn(),
getTask: vi.fn(),
cancelTask: vi.fn(),
resubscribeTask: vi.fn(),
};
agentCard = {
protocolVersion: '0.3.0',
@ -62,7 +61,7 @@ describe('Client', () => {
client = new Client(transport, agentCardWithExtendedSupport);
let caughtOptions;
transport.getExtendedAgentCard.callsFake(async (options) => {
transport.getExtendedAgentCard.mockImplementation(async (options) => {
caughtOptions = options;
return extendedAgentCard;
});
@ -72,7 +71,7 @@ describe('Client', () => {
};
const result = await client.getAgentCard(expectedOptions);
expect(transport.getExtendedAgentCard.calledOnce).to.be.true;
expect(transport.getExtendedAgentCard).toHaveBeenCalledTimes(1);
expect(result).to.equal(extendedAgentCard);
expect(caughtOptions).to.equal(expectedOptions);
});
@ -80,7 +79,7 @@ describe('Client', () => {
it('should not call transport.getAuthenticatedExtendedAgentCard if not supported', async () => {
const result = await client.getAgentCard();
expect(transport.getExtendedAgentCard.called).to.be.false;
expect(transport.getExtendedAgentCard).not.toHaveBeenCalled();
expect(result).to.equal(agentCard);
});
@ -100,7 +99,7 @@ describe('Client', () => {
role: 'agent',
parts: [{ kind: 'text', text: 'response' }],
};
transport.sendMessage.resolves(response);
transport.sendMessage.mockResolvedValue(response);
const result = await client.sendMessage(params);
@ -108,8 +107,8 @@ describe('Client', () => {
...params,
configuration: { ...params.configuration, blocking: true },
};
expect(transport.sendMessage.calledOn(transport)).to.be.true;
expect(transport.sendMessage.calledOnceWith(expectedParams)).to.be.true;
expect(transport.sendMessage.mock.contexts[0]).toBe(transport);
expect(transport.sendMessage).toHaveBeenCalledExactlyOnceWith(expectedParams, undefined);
expect(result).to.deep.equal(response);
});
@ -136,7 +135,7 @@ describe('Client', () => {
async function* stream() {
yield* events;
}
transport.sendMessageStream.returns(stream());
transport.sendMessageStream.mockReturnValue(stream());
const result = client.sendMessageStream(params);
@ -148,8 +147,8 @@ describe('Client', () => {
...params,
configuration: { ...params.configuration, blocking: true },
};
expect(transport.sendMessageStream.calledOn(transport)).to.be.true;
expect(transport.sendMessageStream.calledOnceWith(expectedParams)).to.be.true;
expect(transport.sendMessageStream).toHaveBeenCalledTimes(1);
expect(transport.sendMessageStream).toHaveBeenCalledWith(expectedParams, undefined);
expect(got).to.deep.equal(events);
});
@ -158,12 +157,15 @@ describe('Client', () => {
taskId: '123',
pushNotificationConfig: { url: 'http://example.com' },
};
transport.setTaskPushNotificationConfig.resolves(params);
transport.setTaskPushNotificationConfig.mockResolvedValue(params);
const result = await client.setTaskPushNotificationConfig(params);
expect(transport.setTaskPushNotificationConfig.calledOn(transport)).to.be.true;
expect(transport.setTaskPushNotificationConfig.calledOnceWith(params)).to.be.true;
expect(transport.setTaskPushNotificationConfig.mock.contexts[0]).toBe(transport);
expect(transport.setTaskPushNotificationConfig).toHaveBeenCalledExactlyOnceWith(
params,
undefined
);
expect(result).to.equal(params);
});
@ -176,12 +178,15 @@ describe('Client', () => {
taskId: '123',
pushNotificationConfig: { url: 'http://example.com' },
};
transport.getTaskPushNotificationConfig.resolves(config);
transport.getTaskPushNotificationConfig.mockResolvedValue(config);
const result = await client.getTaskPushNotificationConfig(params);
expect(transport.getTaskPushNotificationConfig.calledOn(transport)).to.be.true;
expect(transport.getTaskPushNotificationConfig.calledOnceWith(params)).to.be.true;
expect(transport.getTaskPushNotificationConfig.mock.contexts[0]).toBe(transport);
expect(transport.getTaskPushNotificationConfig).toHaveBeenCalledExactlyOnceWith(
params,
undefined
);
expect(result).to.equal(config);
});
@ -190,11 +195,14 @@ describe('Client', () => {
const configs: TaskPushNotificationConfig[] = [
{ taskId: '123', pushNotificationConfig: { url: 'http://example.com' } },
];
transport.listTaskPushNotificationConfig.resolves(configs);
transport.listTaskPushNotificationConfig.mockResolvedValue(configs);
const result = await client.listTaskPushNotificationConfig(params);
expect(transport.listTaskPushNotificationConfig.calledOnceWith(params)).to.be.true;
expect(transport.listTaskPushNotificationConfig).toHaveBeenCalledExactlyOnceWith(
params,
undefined
);
expect(result).to.equal(configs);
});
@ -203,22 +211,25 @@ describe('Client', () => {
id: '123',
pushNotificationConfigId: 'abc',
};
transport.deleteTaskPushNotificationConfig.resolves();
transport.deleteTaskPushNotificationConfig.mockResolvedValue(undefined);
await client.deleteTaskPushNotificationConfig(params);
expect(transport.deleteTaskPushNotificationConfig.calledOn(transport)).to.be.true;
expect(transport.deleteTaskPushNotificationConfig.calledOnceWith(params)).to.be.true;
expect(transport.deleteTaskPushNotificationConfig.mock.contexts[0]).toBe(transport);
expect(transport.deleteTaskPushNotificationConfig).toHaveBeenCalledExactlyOnceWith(
params,
undefined
);
});
it('should call transport.getTask', async () => {
const params: TaskQueryParams = { id: '123' };
const task: Task = { id: '123', kind: 'task', contextId: 'ctx1', status: { state: 'working' } };
transport.getTask.resolves(task);
transport.getTask.mockResolvedValue(task);
const result = await client.getTask(params);
expect(transport.getTask.calledOnceWith(params)).to.be.true;
expect(transport.getTask).toHaveBeenCalledExactlyOnceWith(params, undefined);
expect(result).to.equal(task);
});
@ -230,12 +241,12 @@ describe('Client', () => {
contextId: 'ctx1',
status: { state: 'canceled' },
};
transport.cancelTask.resolves(task);
transport.cancelTask.mockResolvedValue(task);
const result = await client.cancelTask(params);
expect(transport.cancelTask.calledOn(transport)).to.be.true;
expect(transport.cancelTask.calledOnceWith(params)).to.be.true;
expect(transport.cancelTask.mock.contexts[0]).toBe(transport);
expect(transport.cancelTask).toHaveBeenCalledExactlyOnceWith(params, undefined);
expect(result).to.equal(task);
});
@ -260,7 +271,7 @@ describe('Client', () => {
async function* stream() {
yield* events;
}
transport.resubscribeTask.returns(stream());
transport.resubscribeTask.mockReturnValue(stream());
const result = client.resubscribeTask(params);
@ -268,8 +279,8 @@ describe('Client', () => {
for await (const event of result) {
got.push(event);
}
expect(transport.resubscribeTask.calledOn(transport)).to.be.true;
expect(transport.resubscribeTask.calledOnceWith(params)).to.be.true;
expect(transport.resubscribeTask.mock.contexts[0]).toBe(transport);
expect(transport.resubscribeTask).toHaveBeenCalledExactlyOnceWith(params, undefined);
expect(got).to.deep.equal(events);
});
@ -287,7 +298,7 @@ describe('Client', () => {
...params,
configuration: { blocking: false },
};
expect(transport.sendMessage.calledOnceWith(expectedParams)).to.be.true;
expect(transport.sendMessage).toHaveBeenCalledExactlyOnceWith(expectedParams, undefined);
});
it('should set blocking=false when explicitly provided in request', async () => {
@ -303,7 +314,7 @@ describe('Client', () => {
...params,
configuration: { blocking: false },
};
expect(transport.sendMessage.calledOnceWith(expectedParams)).to.be.true;
expect(transport.sendMessage).toHaveBeenCalledExactlyOnceWith(expectedParams, undefined);
});
it('should apply acceptedOutputModes', async () => {
@ -319,7 +330,7 @@ describe('Client', () => {
...params,
configuration: { blocking: true, acceptedOutputModes: ['application/json'] },
};
expect(transport.sendMessage.calledOnceWith(expectedParams)).to.be.true;
expect(transport.sendMessage).toHaveBeenCalledExactlyOnceWith(expectedParams, undefined);
});
it('should use acceptedOutputModes from request when provided', async () => {
@ -336,7 +347,7 @@ describe('Client', () => {
...params,
configuration: { blocking: true, acceptedOutputModes: ['text/plain'] },
};
expect(transport.sendMessage.calledOnceWith(expectedParams)).to.be.true;
expect(transport.sendMessage).toHaveBeenCalledExactlyOnceWith(expectedParams, undefined);
});
it('should apply pushNotificationConfig', async () => {
@ -353,7 +364,7 @@ describe('Client', () => {
...params,
configuration: { blocking: true, pushNotificationConfig: pushConfig },
};
expect(transport.sendMessage.calledOnceWith(expectedParams)).to.be.true;
expect(transport.sendMessage).toHaveBeenCalledExactlyOnceWith(expectedParams, undefined);
});
it('should use pushNotificationConfig from request when provided', async () => {
@ -374,7 +385,7 @@ describe('Client', () => {
...params,
configuration: { blocking: true, pushNotificationConfig: pushConfig },
};
expect(transport.sendMessage.calledOnceWith(expectedParams)).to.be.true;
expect(transport.sendMessage).toHaveBeenCalledExactlyOnceWith(expectedParams, undefined);
});
});
@ -391,7 +402,7 @@ describe('Client', () => {
role: 'agent',
parts: [],
};
transport.sendMessage.resolves(response);
transport.sendMessage.mockResolvedValue(response);
const result = client.sendMessageStream(params);
const yielded = await result.next();
@ -400,7 +411,7 @@ describe('Client', () => {
...params,
configuration: { blocking: true },
};
expect(transport.sendMessage.calledOnceWith(expectedParams)).to.be.true;
expect(transport.sendMessage).toHaveBeenCalledExactlyOnceWith(expectedParams, undefined);
expect(yielded.value).to.deep.equal(response);
});
});
@ -427,11 +438,14 @@ describe('Client', () => {
contextId: 'ctx1',
status: { state: 'working' },
};
transport.getTask.resolves(task);
transport.getTask.mockResolvedValue(task);
const result = await client.getTask(params);
expect(transport.getTask.calledOnceWith({ id: '123', metadata: { foo: 'bar' } })).to.be.true;
expect(transport.getTask).toHaveBeenCalledExactlyOnceWith(
{ id: '123', metadata: { foo: 'bar' } },
undefined
);
expect(result).to.equal(task);
});
@ -456,11 +470,11 @@ describe('Client', () => {
contextId: 'ctx1',
status: { state: 'working' },
};
transport.getTask.resolves(task);
transport.getTask.mockResolvedValue(task);
const result = await client.getTask(params);
expect(transport.getTask.calledOnceWith(params)).to.be.true;
expect(transport.getTask).toHaveBeenCalledExactlyOnceWith(params, undefined);
expect(result).to.deep.equal({ ...task, metadata: { foo: 'bar' } });
});
@ -483,12 +497,13 @@ describe('Client', () => {
contextId: 'ctx1',
status: { state: 'working' },
};
transport.getTask.resolves(task);
transport.getTask.mockResolvedValue(task);
const result = await client.getTask(params);
expect(transport.getTask.calledOnceWith(params, { context: { [Symbol.for('foo')]: 'bar' } }))
.to.be.true;
expect(transport.getTask).toHaveBeenCalledExactlyOnceWith(params, {
context: { [Symbol.for('foo')]: 'bar' },
});
expect(result).to.equal(task);
});
@ -512,7 +527,7 @@ describe('Client', () => {
contextId: 'ctx1',
status: { state: 'working' },
};
transport.getTask.resolves(task);
transport.getTask.mockResolvedValue(task);
await client.getTask(params);
expect(caughtAgentCard).to.equal(agentCard);
@ -548,11 +563,11 @@ describe('Client', () => {
};
client = new Client(transport, agentCard, config);
const params: TaskQueryParams = { id: '123' };
transport.getTask.resolves(task);
transport.getTask.mockResolvedValue(task);
const result = await client.getTask(params);
expect(transport.getTask.notCalled).to.be.true;
expect(transport.getTask).not.toHaveBeenCalled();
expect(result).to.equal(task);
});
@ -583,11 +598,11 @@ describe('Client', () => {
};
client = new Client(transport, agentCard, config);
const params: TaskQueryParams = { id: '123' };
transport.getTask.resolves(task);
transport.getTask.mockResolvedValue(task);
const result = await client.getTask(params);
expect(transport.getTask.calledOnceWith(params)).to.be.true;
expect(transport.getTask).toHaveBeenCalledExactlyOnceWith(params, undefined);
expect(result).to.equal(task);
});
@ -632,11 +647,11 @@ describe('Client', () => {
};
client = new Client(transport, agentCard, config);
const params: TaskQueryParams = { id: '123' };
transport.getTask.resolves(task);
transport.getTask.mockResolvedValue(task);
const result = await client.getTask(params);
expect(transport.getTask.notCalled).to.be.true;
expect(transport.getTask).not.toHaveBeenCalled();
expect(firstAfterCalled).to.be.true;
expect(secondAfterCalled).to.be.true;
expect(thirdAfterCalled).to.be.false;
@ -666,7 +681,7 @@ describe('Client', () => {
async function* stream() {
yield* events;
}
transport.sendMessageStream.returns(stream());
transport.sendMessageStream.mockReturnValue(stream());
const config: ClientConfig = {
interceptors: [
{
@ -694,7 +709,10 @@ describe('Client', () => {
...params,
configuration: { ...params.configuration, blocking: true },
};
expect(transport.sendMessageStream.calledOnceWith(expectedParams)).to.be.true;
expect(transport.sendMessageStream).toHaveBeenCalledExactlyOnceWith(
expectedParams,
undefined
);
expect(got).to.deep.equal(events.map((event) => ({ ...event, metadata: { foo: 'bar' } })));
});
@ -708,7 +726,7 @@ describe('Client', () => {
role: 'agent',
parts: [],
};
transport.sendMessage.resolves(message);
transport.sendMessage.mockResolvedValue(message);
const config: ClientConfig = {
interceptors: [
{
@ -735,8 +753,7 @@ describe('Client', () => {
const iteratorsTests = [
{
name: 'sendMessageStream',
transportStubGetter: (t: sinon.SinonStubbedInstance<Transport>): sinon.SinonStub =>
t.sendMessageStream,
transportStubGetter: (t: Record<keyof Transport, Mock>): Mock => t.sendMessageStream,
caller: (c: Client): AsyncGenerator<A2AStreamEventData> =>
c.sendMessageStream({
message: { kind: 'message', messageId: '1', role: 'user', parts: [] },
@ -744,8 +761,7 @@ describe('Client', () => {
},
{
name: 'resubscribeTask',
transportStubGetter: (t: sinon.SinonStubbedInstance<Transport>): sinon.SinonStub =>
t.resubscribeTask,
transportStubGetter: (t: Record<keyof Transport, Mock>): Mock => t.resubscribeTask,
caller: (c: Client): AsyncGenerator<A2AStreamEventData> => c.resubscribeTask({ id: '123' }),
},
];
@ -773,7 +789,7 @@ describe('Client', () => {
yield* events;
}
const transportStub = test.transportStubGetter(transport);
transportStub.returns(stream());
transportStub.mockReturnValue(stream());
let firstAfterCalled = false;
let secondAfterCalled = false;
let thirdAfterCalled = false;
@ -814,7 +830,7 @@ describe('Client', () => {
for await (const event of result) {
got.push(event);
}
expect(transportStub.notCalled).to.be.true;
expect(transportStub).not.toHaveBeenCalled();
expect(got).to.deep.equal([events[0]]);
expect(firstAfterCalled).to.be.true;
expect(secondAfterCalled).to.be.true;
@ -842,7 +858,7 @@ describe('Client', () => {
yield* events;
}
const transportStub = test.transportStubGetter(transport);
transportStub.returns(stream());
transportStub.mockReturnValue(stream());
const config: ClientConfig = {
interceptors: [
{
@ -866,7 +882,7 @@ describe('Client', () => {
for await (const event of result) {
got.push(event);
}
expect(transportStub.calledOnce).to.be.true;
expect(transportStub).toHaveBeenCalledTimes(1);
expect(got).to.deep.equal([events[0]]);
});
});

View File

@ -0,0 +1,387 @@
import { describe, it, beforeEach, afterEach, expect, vi, type Mock } from 'vitest';
import { credentials, Metadata, ServiceError, status } from '@grpc/grpc-js';
import {
GrpcTransport,
GrpcTransportFactory,
} from '../../../src/client/transports/grpc/grpc_transport.js';
import { A2AServiceClient } from '../../../src/grpc/pb/a2a_services.js';
import { ToProto } from '../../../src/types/converters/to_proto.js';
import { FromProto } from '../../../src/types/converters/from_proto.js';
import {
TaskNotFoundError,
TaskNotCancelableError,
PushNotificationNotSupportedError,
} from '../../../src/errors.js';
import {
createMessageParams,
createMockAgentCard,
createMockMessage,
createMockTask,
} from '../util.js';
// --- Mocks ---
// Mock the gRPC client class
vi.mock('../../../src/grpc/pb/a2a_services.js', () => {
const A2AServiceClient = vi.fn();
A2AServiceClient.prototype.getAgentCard = vi.fn();
A2AServiceClient.prototype.sendMessage = vi.fn();
A2AServiceClient.prototype.sendStreamingMessage = vi.fn();
A2AServiceClient.prototype.createTaskPushNotificationConfig = vi.fn();
A2AServiceClient.prototype.getTaskPushNotificationConfig = vi.fn();
A2AServiceClient.prototype.listTaskPushNotificationConfig = vi.fn();
A2AServiceClient.prototype.deleteTaskPushNotificationConfig = vi.fn();
A2AServiceClient.prototype.getTask = vi.fn();
A2AServiceClient.prototype.cancelTask = vi.fn();
A2AServiceClient.prototype.taskSubscription = vi.fn();
return { A2AServiceClient };
});
// Mock ToProto and FromProto to act as pass-throughs or return simple objects for testing flow
vi.mock('../../../src/types/converters/to_proto.js', () => ({
ToProto: {
agentCard: vi.fn((x) => x),
messageSendParams: vi.fn((x) => x),
taskPushNotificationConfig: vi.fn((x) => x),
getTaskPushNotificationConfigParams: vi.fn((x) => x),
listTaskPushNotificationConfigParams: vi.fn((x) => x),
deleteTaskPushNotificationConfigParams: vi.fn((x) => x),
getTaskRequest: vi.fn((x) => x),
cancelTaskRequest: vi.fn((x) => x),
taskIdParams: vi.fn((x) => x),
taskPushNotificationConfigCreate: vi.fn((x) => x),
taskQueryParams: vi.fn((x) => x),
getAgentCardRequest: vi.fn((x) => x),
},
}));
vi.mock('../../../src/types/converters/from_proto.js', () => ({
FromProto: {
agentCard: vi.fn((x) => x),
sendMessageResult: vi.fn((x) => x),
message: vi.fn((x) => x),
setTaskPushNotificationConfigParams: vi.fn((x) => x),
getTaskPushNoticationConfig: vi.fn((x) => x),
listTaskPushNotificationConfig: vi.fn((x) => x),
task: vi.fn((x) => x),
taskStatusUpdate: vi.fn((x) => x),
taskArtifactUpdate: vi.fn((x) => x),
taskPushNotificationConfig: vi.fn((x) => x),
messageStreamResult: vi.fn((x) => x),
},
}));
describe('GrpcTransport', () => {
let transport: GrpcTransport;
let mockGrpcClient: A2AServiceClient;
const endpoint = 'localhost:50051';
// Helper to simulate a successful gRPC unary callback
const mockUnarySuccess = (method: Mock, response: any) => {
method.mockImplementation((_req: any, _meta: any, _opts: any, callback: any) => {
callback(null, response);
return {};
});
};
// Helper to simulate a gRPC error
const mockUnaryError = (method: Mock, code: number, message: string) => {
method.mockImplementation((_req: any, _meta: any, _opts: any, callback: any) => {
const error: Partial<ServiceError> = {
code: code,
details: message,
};
callback(error, null);
return {};
});
};
beforeEach(() => {
mockGrpcClient = new A2AServiceClient(endpoint, credentials.createInsecure());
transport = new GrpcTransport({ endpoint });
});
afterEach(() => {
vi.clearAllMocks();
});
describe('getExtendedAgentCard', () => {
it('should get agent card successfully', async () => {
const mockCard = createMockAgentCard();
mockUnarySuccess(mockGrpcClient.getAgentCard as Mock, mockCard);
const result = await transport.getExtendedAgentCard();
expect(result).toEqual(mockCard);
expect(mockGrpcClient.getAgentCard).toHaveBeenCalled();
expect(FromProto.agentCard).toHaveBeenCalledWith(mockCard);
});
});
describe('sendMessage', () => {
it('should send message successfully', async () => {
const params = createMessageParams();
const mockResult = createMockMessage();
mockUnarySuccess(mockGrpcClient.sendMessage as Mock, mockResult);
const result = await transport.sendMessage(params);
expect(result).toEqual(mockResult);
expect(ToProto.messageSendParams).toHaveBeenCalledWith(params);
expect(mockGrpcClient.sendMessage).toHaveBeenCalled();
});
it('should pass service parameters as metadata', async () => {
const params = createMessageParams();
const options = { serviceParameters: { 'x-test-header': 'test-value' } };
mockUnarySuccess(mockGrpcClient.sendMessage as Mock, {});
await transport.sendMessage(params, options);
const calledMetadata = (mockGrpcClient.sendMessage as Mock).mock.calls[0][1] as Metadata;
expect(calledMetadata.get('x-test-header')).toEqual(['test-value']);
});
it('should throw TaskNotFoundError when mapped from A2A error code', async () => {
const params = createMessageParams();
mockUnaryError(mockGrpcClient.sendMessage as Mock, status.NOT_FOUND, 'Task Missing');
await expect(transport.sendMessage(params)).rejects.toThrow(TaskNotFoundError);
});
it('should throw generic Error for unmapped gRPC errors', async () => {
const params = createMessageParams();
mockUnaryError(mockGrpcClient.sendMessage as Mock, status.UNKNOWN, 'Internal Error');
await expect(transport.sendMessage(params)).rejects.toThrow('GRPC error for sendMessage');
});
it('should cancel request when signal is aborted', async () => {
const params = createMessageParams();
const cancelMock = vi.fn();
(mockGrpcClient.sendMessage as Mock).mockImplementation((_req, _meta, _opts, callback) => {
return {
cancel: () => {
cancelMock();
callback({ code: status.CANCELLED, details: 'Cancelled' }, null);
},
};
});
const controller = new AbortController();
const promise = transport.sendMessage(params, { signal: controller.signal });
controller.abort();
expect(cancelMock).toHaveBeenCalled();
await expect(promise).rejects.toThrow();
});
});
describe('sendMessageStream', () => {
it('should yield messages from stream', async () => {
const params = createMessageParams();
const mockMsg = createMockMessage();
const mockMsgResponse = { payload: { $case: 'msg', value: mockMsg } };
const mockStream = {
[Symbol.asyncIterator]: async function* () {
yield mockMsgResponse;
},
cancel: vi.fn(),
};
(mockGrpcClient.sendStreamingMessage as Mock).mockReturnValue(mockStream);
const iterator = transport.sendMessageStream(params);
const result = await iterator.next();
expect(result.value).toEqual(mockMsgResponse);
expect(FromProto.messageStreamResult).toHaveBeenCalledWith(mockMsgResponse);
expect(mockGrpcClient.sendStreamingMessage).toHaveBeenCalled();
});
it('should handle stream errors', async () => {
const params = createMessageParams();
const mockStream = {
[Symbol.asyncIterator]: async function* () {
throw { code: 13, message: 'Stream failed' };
yield {};
},
cancel: vi.fn(),
};
(mockGrpcClient.sendStreamingMessage as Mock).mockReturnValue(mockStream);
const iterator = transport.sendMessageStream(params);
await expect(iterator.next()).rejects.toThrow('GRPC error for sendStreamingMessage!');
});
it('should cancel stream when signal is aborted', async () => {
const params = createMessageParams();
const cancelMock = vi.fn();
const mockStream = {
[Symbol.asyncIterator]: async function* () {
await new Promise((resolve) => setTimeout(resolve, 50));
yield { payload: { $case: 'msg', value: createMockMessage() } };
},
cancel: cancelMock,
};
(mockGrpcClient.sendStreamingMessage as Mock).mockReturnValue(mockStream);
const controller = new AbortController();
const iterator = transport.sendMessageStream(params, { signal: controller.signal });
iterator.next();
controller.abort();
expect(cancelMock).toHaveBeenCalled();
});
});
describe('getTask', () => {
it('should get task successfully', async () => {
const taskId = 'task-123';
const mockTask = createMockTask(taskId);
mockUnarySuccess(mockGrpcClient.getTask as Mock, mockTask);
const result = await transport.getTask({ id: taskId });
expect(result).toEqual(mockTask);
expect(ToProto.taskQueryParams).toHaveBeenCalled();
expect(mockGrpcClient.getTask).toHaveBeenCalled();
});
it('should throw TaskNotFoundError', async () => {
mockUnaryError(mockGrpcClient.getTask as Mock, status.NOT_FOUND, 'Not Found');
await expect(transport.getTask({ id: 'bad-id' })).rejects.toThrow(TaskNotFoundError);
});
});
describe('cancelTask', () => {
it('should cancel task successfully', async () => {
const taskId = 'task-123';
const mockTask = createMockTask(taskId, 'canceled');
mockUnarySuccess(mockGrpcClient.cancelTask as Mock, mockTask);
const result = await transport.cancelTask({ id: taskId });
expect(result).toEqual(mockTask);
expect(mockGrpcClient.cancelTask).toHaveBeenCalled();
});
it('should throw TaskNotCancelableError', async () => {
mockUnaryError(
mockGrpcClient.cancelTask as Mock,
status.FAILED_PRECONDITION,
'Cannot cancel'
);
await expect(transport.cancelTask({ id: 'task-123' })).rejects.toThrow(
TaskNotCancelableError
);
});
});
describe('Push Notification Config', () => {
const taskId = 'task-123';
const configId = 'config-456';
const mockConfig = {
taskId,
pushNotificationConfig: { id: configId, url: 'http://test' },
};
describe('setTaskPushNotificationConfig', () => {
it('should set config successfully', async () => {
mockUnarySuccess(mockGrpcClient.createTaskPushNotificationConfig as Mock, mockConfig);
const result = await transport.setTaskPushNotificationConfig(mockConfig);
expect(result).toEqual(mockConfig);
expect(mockGrpcClient.createTaskPushNotificationConfig).toHaveBeenCalled();
});
it('should throw PushNotificationNotSupportedError', async () => {
mockUnaryError(
mockGrpcClient.createTaskPushNotificationConfig as Mock,
status.UNIMPLEMENTED,
'Not supported'
);
await expect(transport.setTaskPushNotificationConfig(mockConfig)).rejects.toThrow(
PushNotificationNotSupportedError
);
});
});
describe('getTaskPushNotificationConfig', () => {
it('should get config successfully', async () => {
mockUnarySuccess(mockGrpcClient.getTaskPushNotificationConfig as Mock, mockConfig);
const result = await transport.getTaskPushNotificationConfig({
id: taskId,
pushNotificationConfigId: configId,
});
expect(result).toEqual(mockConfig);
});
});
describe('listTaskPushNotificationConfig', () => {
it('should list configs successfully', async () => {
const mockList = [mockConfig];
mockUnarySuccess(mockGrpcClient.listTaskPushNotificationConfig as Mock, mockList);
const result = await transport.listTaskPushNotificationConfig({ id: taskId });
expect(result).toEqual(mockList);
});
});
describe('deleteTaskPushNotificationConfig', () => {
it('should delete config successfully', async () => {
mockUnarySuccess(mockGrpcClient.deleteTaskPushNotificationConfig as Mock, {});
await transport.deleteTaskPushNotificationConfig({
id: taskId,
pushNotificationConfigId: configId,
});
expect(mockGrpcClient.deleteTaskPushNotificationConfig).toHaveBeenCalled();
});
});
});
describe('resubscribeTask', () => {
it('should yield task updates from stream', async () => {
const params = { id: 'task-123' };
const mockUpdate = createMockTask('task-123');
const mockResponse = { payload: { $case: 'task', value: mockUpdate } };
const mockStream = {
[Symbol.asyncIterator]: async function* () {
yield mockResponse;
},
cancel: vi.fn(),
};
(mockGrpcClient.taskSubscription as Mock).mockReturnValue(mockStream);
const iterator = transport.resubscribeTask(params);
const result = await iterator.next();
expect(result.value).toEqual(mockResponse);
expect(FromProto.messageStreamResult).toHaveBeenCalledWith(mockResponse);
});
});
});
describe('GrpcTransportFactory', () => {
it('should have correct protocol name', () => {
const factory = new GrpcTransportFactory();
expect(factory.protocolName).toBe('GRPC');
});
it('should create transport with correct endpoint', async () => {
const factory = new GrpcTransportFactory();
const agentCard = createMockAgentCard({ url: 'localhost:50051' });
const transport = await factory.create(agentCard.url, agentCard);
expect(transport).toBeInstanceOf(GrpcTransport);
});
});

View File

@ -1,6 +1,5 @@
import { JsonRpcTransport } from '../../../src/client/transports/json_rpc_transport.js';
import sinon from 'sinon';
import { describe, it, beforeEach, expect } from 'vitest';
import { describe, it, beforeEach, expect, vi, type Mock } from 'vitest';
import { MessageSendParams, TextPart } from '../../../src/types.js';
import { RequestOptions } from '../../../src/client/multitransport-client.js';
import { HTTP_EXTENSION_HEADER } from '../../../src/constants.js';
@ -8,11 +7,11 @@ import { ServiceParameters, withA2AExtensions } from '../../../src/client/servic
describe('JsonRpcTransport', () => {
let transport: JsonRpcTransport;
let mockFetch: sinon.SinonStubbedFunction<typeof fetch>;
let mockFetch: Mock<typeof fetch>;
const endpoint = 'https://test.endpoint/api';
beforeEach(() => {
mockFetch = sinon.stub();
mockFetch = vi.fn();
transport = new JsonRpcTransport({
endpoint,
fetchImpl: mockFetch,
@ -41,13 +40,13 @@ describe('JsonRpcTransport', () => {
serviceParameters,
};
mockFetch.resolves(
mockFetch.mockResolvedValue(
new Response(JSON.stringify({ jsonrpc: '2.0', result: {}, id: 1 }), {
status: 200,
})
);
await transport.sendMessage(messageParams, options);
const fetchArgs = mockFetch.firstCall.args[1];
const fetchArgs = mockFetch.mock.calls[0][1];
const headers = fetchArgs.headers;
expect((headers as any)[HTTP_EXTENSION_HEADER]).to.deep.equal(expectedExtensions);
});

View File

@ -0,0 +1,386 @@
import {
RestTransport,
RestTransportFactory,
} from '../../../src/client/transports/rest_transport.js';
import { describe, it, beforeEach, afterEach, expect, vi, type Mock } from 'vitest';
import { TaskPushNotificationConfig } from '../../../src/types.js';
import { RequestOptions } from '../../../src/client/multitransport-client.js';
import { HTTP_EXTENSION_HEADER } from '../../../src/constants.js';
import { ServiceParameters, withA2AExtensions } from '../../../src/client/service-parameters.js';
import {
TaskNotFoundError,
TaskNotCancelableError,
PushNotificationNotSupportedError,
} from '../../../src/errors.js';
import {
createMessageParams,
createMockAgentCard,
createMockMessage,
createMockTask,
createRestResponse,
createRestErrorResponse,
createMockProtoMessage,
createMockProtoTask,
} from '../util.js';
import {
AgentCard,
ListTaskPushNotificationConfigResponse,
TaskPushNotificationConfig as TaskPushNotificationConfigProto,
TaskState,
} from '../../../src/types/pb/a2a_types.js';
import { FromProto } from '../../../src/types/converters/from_proto.js';
import { ToProto } from '../../../src/types/converters/to_proto.js';
describe('RestTransport', () => {
let transport: RestTransport;
let mockFetch: Mock<typeof fetch>;
const endpoint = 'https://test.endpoint/api';
beforeEach(() => {
mockFetch = vi.fn();
transport = new RestTransport({
endpoint,
fetchImpl: mockFetch,
});
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('constructor', () => {
it('should trim trailing slashes from endpoint', async () => {
const trailingSlashTransport = new RestTransport({
endpoint: 'https://example.com/a2a/rest/',
fetchImpl: mockFetch,
});
const mockResponse = createMockProtoMessage();
mockFetch.mockResolvedValue(createRestResponse(mockResponse));
await trailingSlashTransport.sendMessage(createMessageParams());
const [url] = mockFetch.mock.calls[0];
expect(url).to.equal('https://example.com/a2a/rest/v1/message:send');
});
it('should trim multiple trailing slashes from endpoint', async () => {
const trailingSlashTransport = new RestTransport({
endpoint: 'https://example.com/a2a/rest///',
fetchImpl: mockFetch,
});
const mockResponse = createMockProtoMessage();
mockFetch.mockResolvedValue(createRestResponse(mockResponse));
await trailingSlashTransport.sendMessage(createMessageParams());
const [url] = mockFetch.mock.calls[0];
expect(url).to.equal('https://example.com/a2a/rest/v1/message:send');
});
});
describe('sendMessage', () => {
it('should send message successfully', async () => {
const messageParams = createMessageParams();
const mockResponse = createMockProtoMessage();
mockFetch.mockResolvedValue(createRestResponse(mockResponse));
const result = await transport.sendMessage(messageParams);
expect(result).to.deep.equal(createMockMessage());
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url).to.equal(`${endpoint}/v1/message:send`);
expect(options?.method).to.equal('POST');
expect((options?.headers as Record<string, string>)['Content-Type']).to.equal(
'application/json'
);
});
it('should correctly add the extension headers', async () => {
const messageParams = createMessageParams();
const expectedExtensions = 'extension1,extension2';
const serviceParameters = ServiceParameters.create(withA2AExtensions(expectedExtensions));
const options: RequestOptions = { serviceParameters };
mockFetch.mockResolvedValue(createRestResponse(createMockProtoMessage()));
await transport.sendMessage(messageParams, options);
const fetchArgs = mockFetch.mock.calls[0][1];
const headers = fetchArgs?.headers as Record<string, string>;
expect(headers[HTTP_EXTENSION_HEADER]).to.equal(expectedExtensions);
});
it('should throw TaskNotFoundError on -32001', async () => {
const messageParams = createMessageParams();
mockFetch.mockResolvedValue(createRestErrorResponse(-32001, 'Task not found', 404));
await expect(transport.sendMessage(messageParams)).rejects.toThrow(TaskNotFoundError);
});
});
describe('getTask', () => {
it('should get task successfully', async () => {
const taskId = 'task-123';
const mockTask = createMockProtoTask(taskId);
mockFetch.mockResolvedValue(createRestResponse(mockTask));
const result = await transport.getTask({ id: taskId });
expect(result).to.deep.equal(createMockTask(taskId));
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}`);
expect(options?.method).to.equal('GET');
});
it('should pass historyLength as query parameter', async () => {
const taskId = 'task-123';
const historyLength = 10;
const mockTask = createMockProtoTask(taskId);
mockFetch.mockResolvedValue(createRestResponse(mockTask));
const result = await transport.getTask({ id: taskId, historyLength });
expect(result).to.deep.equal(createMockTask(taskId));
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}?historyLength=${historyLength}`);
expect(options?.method).to.equal('GET');
});
it('should throw TaskNotFoundError when task does not exist', async () => {
mockFetch.mockResolvedValue(createRestErrorResponse(-32001, 'Task not found', 404));
await expect(transport.getTask({ id: 'nonexistent' })).rejects.toThrow(TaskNotFoundError);
});
});
describe('cancelTask', () => {
it('should cancel task successfully', async () => {
const taskId = 'task-123';
const mockTask = createMockProtoTask(taskId, TaskState.TASK_STATE_CANCELLED);
mockFetch.mockResolvedValue(createRestResponse(mockTask));
const result = await transport.cancelTask({ id: taskId });
expect(result).to.deep.equal(createMockTask(taskId, 'canceled'));
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}:cancel`);
expect(options?.method).to.equal('POST');
});
it('should throw TaskNotCancelableError on -32002', async () => {
mockFetch.mockResolvedValue(createRestErrorResponse(-32002, 'Task cannot be canceled', 409));
await expect(transport.cancelTask({ id: 'task-123' })).rejects.toThrow(
TaskNotCancelableError
);
});
});
describe('getExtendedAgentCard', () => {
it('should get extended agent card successfully', async () => {
const mockCard: AgentCard = {
name: 'Test Agent',
description: 'A test agent for testing',
supportsAuthenticatedExtendedCard: true,
capabilities: {
streaming: true,
pushNotifications: true,
extensions: [],
},
skills: [],
defaultInputModes: ['text'],
defaultOutputModes: ['text'],
url: endpoint,
version: '1.0.0',
protocolVersion: '0.3.0',
preferredTransport: 'HTTP+JSON',
additionalInterfaces: [],
provider: {
url: '',
organization: '',
},
security: [],
securitySchemes: {},
documentationUrl: '',
signatures: [],
};
mockFetch.mockResolvedValue(createRestResponse(AgentCard.toJSON(mockCard)));
const result = await transport.getExtendedAgentCard();
expect(result).to.deep.equal(FromProto.agentCard(mockCard));
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url).to.equal(`${endpoint}/v1/card`);
expect(options?.method).to.equal('GET');
});
});
describe('Push Notification Config', () => {
const taskId = 'task-123';
const configId = 'config-456';
const mockConfig: TaskPushNotificationConfig = {
taskId,
pushNotificationConfig: {
id: configId,
url: 'https://notify.example.com/webhook',
authentication: undefined,
token: 'secret-token',
},
};
const mockProtoConfig = ToProto.taskPushNotificationConfig(mockConfig);
describe('setTaskPushNotificationConfig', () => {
it('should set push notification config successfully', async () => {
mockFetch.mockResolvedValue(
createRestResponse(TaskPushNotificationConfigProto.toJSON(mockProtoConfig))
);
const result = await transport.setTaskPushNotificationConfig(mockConfig);
expect(result).to.deep.equal(mockConfig);
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}/pushNotificationConfigs`);
expect(options?.method).to.equal('POST');
});
it('should throw PushNotificationNotSupportedError on -32003', async () => {
mockFetch.mockResolvedValue(
createRestErrorResponse(-32003, 'Push notifications not supported', 400)
);
await expect(transport.setTaskPushNotificationConfig(mockConfig)).rejects.toThrow(
PushNotificationNotSupportedError
);
});
});
describe('getTaskPushNotificationConfig', () => {
it('should get push notification config successfully', async () => {
mockFetch.mockResolvedValue(
createRestResponse(TaskPushNotificationConfigProto.toJSON(mockProtoConfig))
);
const result = await transport.getTaskPushNotificationConfig({
id: taskId,
pushNotificationConfigId: configId,
});
expect(result).to.deep.equal(mockConfig);
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}/pushNotificationConfigs/${configId}`);
expect(options?.method).to.equal('GET');
});
it('should throw error when pushNotificationConfigId is missing', async () => {
await expect(
transport.getTaskPushNotificationConfig({
id: taskId,
pushNotificationConfigId: undefined as unknown as string,
})
).rejects.toThrow('pushNotificationConfigId is required');
});
});
describe('listTaskPushNotificationConfig', () => {
it('should list push notification configs successfully', async () => {
const mockConfigs: TaskPushNotificationConfig[] = [
mockConfig,
{
...mockConfig,
pushNotificationConfig: {
id: 'config-789',
url: 'https://test.com',
authentication: undefined,
token: 'secret-token',
},
},
];
mockFetch.mockResolvedValue(
createRestResponse(
ListTaskPushNotificationConfigResponse.toJSON(
ToProto.listTaskPushNotificationConfig(mockConfigs)
)
)
);
const result = await transport.listTaskPushNotificationConfig({ id: taskId });
expect(result).to.deep.equal(mockConfigs);
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}/pushNotificationConfigs`);
expect(options?.method).to.equal('GET');
});
});
describe('deleteTaskPushNotificationConfig', () => {
it('should delete push notification config successfully', async () => {
mockFetch.mockResolvedValue(new Response(null, { status: 204 }));
await transport.deleteTaskPushNotificationConfig({
id: taskId,
pushNotificationConfigId: configId,
});
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}/pushNotificationConfigs/${configId}`);
expect(options?.method).to.equal('DELETE');
});
});
});
describe('Error Handling', () => {
it('should handle HTTP errors with non-JSON response', async () => {
mockFetch.mockResolvedValue(
new Response('Internal Server Error', {
status: 500,
headers: { 'Content-Type': 'text/plain' },
})
);
await expect(transport.getTask({ id: 'task-123' })).rejects.toThrow('HTTP error');
});
it('should handle network errors', async () => {
mockFetch.mockRejectedValue(new Error('Network error'));
await expect(transport.getTask({ id: 'task-123' })).rejects.toThrow('Network error');
});
});
});
describe('RestTransportFactory', () => {
it('should have correct protocol name', () => {
const factory = new RestTransportFactory();
expect(factory.protocolName).to.equal('HTTP+JSON');
});
it('should create transport with correct endpoint', async () => {
const factory = new RestTransportFactory();
const agentCard = createMockAgentCard({ url: 'https://example.com/api' });
const transport = await factory.create(agentCard.url, agentCard);
expect(transport).to.be.instanceOf(RestTransport);
});
});

View File

@ -2,8 +2,10 @@
* Utility functions for A2A client tests
*/
import sinon from 'sinon';
import { vi, Mock } from 'vitest';
import { AGENT_CARD_PATH } from '../../src/constants.js';
import { Role, SendMessageResponse, Task, TaskState } from '../../src/types/pb/a2a_types.js';
import { SendMessageResult } from '../../src/client/client.js';
/**
* Extracts the request ID from a RequestInit options object.
@ -179,6 +181,42 @@ export function createMessageParams(
};
}
export function createMockProtoMessage(
options: {
messageId?: string;
text?: string;
role?: Role.ROLE_USER | Role.ROLE_AGENT;
} = {}
): any {
const messageId = options.messageId ?? 'msg-123';
const text = options.text ?? 'Hello, agent!';
const role = options.role ?? Role.ROLE_USER;
const obj: SendMessageResponse = {
payload: {
$case: 'msg',
value: {
messageId: messageId,
contextId: 'context-123',
taskId: 'task-123',
role: role,
content: [
{
part: {
$case: 'text',
value: text,
},
},
],
metadata: {},
extensions: [],
},
},
};
return SendMessageResponse.toJSON(obj);
}
/**
* Factory function to create common mock message objects for testing.
* Creates a Message object with text content that can be used
@ -194,9 +232,9 @@ export function createMockMessage(
options: {
messageId?: string;
text?: string;
role?: 'user' | 'assistant';
role?: 'user' | 'agent';
} = {}
): any {
): SendMessageResult {
const messageId = options.messageId ?? 'msg-123';
const text = options.text ?? 'Hello, agent!';
const role = options.role ?? 'user';
@ -204,6 +242,8 @@ export function createMockMessage(
return {
kind: 'message',
messageId: messageId,
contextId: 'context-123',
taskId: 'task-123',
role: role,
parts: [
{
@ -211,6 +251,8 @@ export function createMockMessage(
text: text,
},
],
metadata: {},
extensions: [],
};
}
@ -244,11 +286,11 @@ export interface MockFetchConfig {
* This is the single function that replaces all previous mock fetch utilities.
*
* @param config - Configuration options for the mock fetch behavior
* @returns A sinon stub that can be used as a mock fetch implementation, with capturedAuthHeaders attached as a property
* @returns A vitest mock that can be used as a mock fetch implementation, with capturedAuthHeaders attached as a property
*/
export function createMockFetch(
config: MockFetchConfig = {}
): sinon.SinonStub & { capturedAuthHeaders: string[] } {
): Mock & { capturedAuthHeaders: string[] } {
const {
requiresAuth = false, // Default to no auth required for basic testing
agentDescription = 'A test agent for basic client testing',
@ -268,7 +310,7 @@ export function createMockFetch(
let callCount = 0;
const capturedAuthHeaders: string[] = [];
const mockFetch = sinon.stub().callsFake(async (url: string, options?: RequestInit) => {
const mockFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
// Handle agent card requests
if (url.includes(AGENT_CARD_PATH)) {
const mockAgentCard = createMockAgentCard({
@ -356,5 +398,96 @@ export function createMockFetch(
// Attach the capturedAuthHeaders as a property to the mock fetch function
(mockFetch as any).capturedAuthHeaders = capturedAuthHeaders;
return mockFetch as sinon.SinonStub & { capturedAuthHeaders: string[] };
return mockFetch as Mock & { capturedAuthHeaders: string[] };
}
/**
* Creates a REST response (plain JSON, not JSON-RPC wrapped).
* Used for testing REST transport which doesn't use JSON-RPC envelope.
*
* @param data - The data to include in the response
* @param status - HTTP status code (defaults to 200)
* @param headers - Additional headers to include
* @returns A Response object with JSON content
*/
export function createRestResponse(
data: unknown,
status: number = 200,
headers: Record<string, string> = {}
): Response {
const defaultHeaders = { 'Content-Type': 'application/json' };
const responseHeaders = { ...defaultHeaders, ...headers };
return new Response(JSON.stringify(data), { status, headers: responseHeaders });
}
/**
* Creates a REST error response with A2A error format.
*
* @param code - A2A error code (e.g., -32001 for TaskNotFound)
* @param message - Error message
* @param status - HTTP status code (defaults to 400)
* @param data - Optional additional error data
* @returns A Response object with error JSON content
*/
export function createRestErrorResponse(
code: number,
message: string,
status: number = 400,
data?: Record<string, unknown>
): Response {
const errorBody = { code, message, ...(data && { data }) };
return new Response(JSON.stringify(errorBody), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
/**
* Creates a mock task response for testing.
*
* @param id - Task ID (defaults to 'task-123')
* @param status - Task status state (defaults to 'completed')
* @returns A mock Task object
*/
export function createMockTask(id: string = 'task-123', status: string = 'completed'): any {
return {
id,
contextId: 'context-123',
status: {
state: status,
timestamp: new Date('2023-01-01T00:00:00.000Z').toISOString(),
message: undefined,
},
kind: 'task',
artifacts: [],
history: [],
metadata: {},
};
}
/**
* Creates a mock task response for testing.
*
* @param id - Task ID (defaults to 'task-123')
* @param status - Task status state (defaults to 'completed')
* @returns A mock Task object
*/
export function createMockProtoTask(
id: string = 'task-123',
status: TaskState = TaskState.TASK_STATE_COMPLETED
): any {
const obj: Task = {
id: id,
contextId: 'context-123',
status: {
state: status,
timestamp: '2023-01-01T00:00:00.000Z',
update: undefined,
},
artifacts: [],
history: [],
metadata: {},
};
return Task.toJSON(obj);
}

View File

@ -1,4 +1,5 @@
import express, { Express } from 'express';
import * as grpc from '@grpc/grpc-js';
import { describe, it, beforeEach, afterEach, expect } from 'vitest';
import {
AgentExecutionEvent,
@ -9,14 +10,16 @@ import {
RequestContext,
} from '../src/server/index.js';
import { AgentCard, Message } from '../src/types.js';
import sinon from 'sinon';
import { agentCardHandler } from '../src/server/express/agent_card_handler.js';
import { jsonRpcHandler } from '../src/server/express/json_rpc_handler.js';
import { ClientFactory } from '../src/client/factory.js';
import { restHandler } from '../src/server/express/rest_handler.js';
import { ClientFactory, ClientFactoryOptions } from '../src/client/factory.js';
import { Server } from 'http';
import { AddressInfo } from 'net';
import { A2AStreamEventData } from '../src/client/client.js';
import { UserBuilder } from '../src/server/express/common.js';
import { A2AService, grpcService } from '../src/server/grpc/index.js';
import { GrpcTransportFactory } from '../src/client/transports/grpc/grpc_transport.js';
class TestAgentExecutor implements AgentExecutor {
constructor(public events: AgentExecutionEvent[] = []) {}
@ -30,124 +33,201 @@ class TestAgentExecutor implements AgentExecutor {
cancelTask: (taskId: string, eventBus: ExecutionEventBus) => Promise<void>;
}
interface TransportConfig {
name: string;
preferredTransport: string;
serverPath?: string;
}
const transportConfigs: TransportConfig[] = [
{
name: 'JSON-RPC',
preferredTransport: 'JSONRPC',
serverPath: '/a2a/rpc',
},
{
name: 'REST',
preferredTransport: 'HTTP+JSON',
serverPath: '/a2a/rest',
},
{
name: 'GRPC',
preferredTransport: 'GRPC',
},
];
describe('Client E2E tests', () => {
let app: Express;
let server: Server;
let agentExecutor: TestAgentExecutor;
let clientFactory: ClientFactory;
let agentCard: AgentCard;
const clientFactory = new ClientFactory(
ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
transports: [new GrpcTransportFactory()],
})
);
beforeEach(() => {
agentExecutor = new TestAgentExecutor();
agentCard = {
protocolVersion: '0.3.0',
name: 'Test Agent',
description: 'An agent for testing purposes',
preferredTransport: 'JSONRPC',
url: 'localhost',
version: '1.0.0',
capabilities: {
streaming: true,
pushNotifications: true,
},
defaultInputModes: ['text/plain'],
defaultOutputModes: ['text/plain'],
skills: [],
};
const requestHandler = new DefaultRequestHandler(
agentCard,
new InMemoryTaskStore(),
agentExecutor
);
transportConfigs.forEach((transportConfig) => {
describe(`[${transportConfig.name}]`, () => {
let app: Express;
let server: Server;
let grpcServer: grpc.Server;
let agentExecutor: TestAgentExecutor;
let agentCard: AgentCard;
app = express();
beforeEach(async () => {
agentExecutor = new TestAgentExecutor();
agentCard = {
protocolVersion: '0.3.0',
name: 'Test Agent',
description: 'An agent for testing purposes',
preferredTransport: transportConfig.preferredTransport,
url: 'localhost',
version: '1.0.0',
capabilities: {
streaming: true,
pushNotifications: true,
},
defaultInputModes: ['text/plain'],
defaultOutputModes: ['text/plain'],
skills: [],
};
const requestHandler = new DefaultRequestHandler(
agentCard,
new InMemoryTaskStore(),
agentExecutor
);
app.use(
'/.well-known/agent-card.json',
agentCardHandler({ agentCardProvider: requestHandler })
);
app = express();
app.use(
'/a2a/rpc',
jsonRpcHandler({ requestHandler: requestHandler, userBuilder: UserBuilder.noAuthentication })
);
app.use(
'/.well-known/agent-card.json',
agentCardHandler({ agentCardProvider: requestHandler })
);
server = app.listen();
app.use(
'/a2a/rpc',
jsonRpcHandler({
requestHandler: requestHandler,
userBuilder: UserBuilder.noAuthentication,
})
);
const address = server.address() as AddressInfo;
agentCard.url = `http://localhost:${address.port}/a2a/rpc`;
app.use(
'/a2a/rest',
restHandler({ requestHandler: requestHandler, userBuilder: UserBuilder.noAuthentication })
);
clientFactory = new ClientFactory();
});
server = app.listen();
const address = server.address() as AddressInfo;
agentCard.url = `http://localhost:${address.port}${transportConfig.serverPath}`;
afterEach(async () => {
sinon.restore();
// await new Promise<void>((resolve, reject) => {
// server.close((err) => {
// if (err) reject(err);
// else resolve();
// });
// });
});
describe('sendMessage', () => {
it('should send a message to the agent', async () => {
const expected = createTestMessage('1', 'test');
agentExecutor.events = [expected];
const client = await clientFactory.createFromAgentCard(agentCard);
const actual = await client.sendMessage({
message: createTestMessage('1', 'test'),
grpcServer = new grpc.Server();
grpcServer.addService(
A2AService,
grpcService({
requestHandler: requestHandler,
userBuilder: UserBuilder.noAuthentication,
})
);
await new Promise<void>((resolve, reject) => {
grpcServer.bindAsync(
`localhost:0`,
grpc.ServerCredentials.createInsecure(),
(error, port) => {
if (error) {
reject(error);
return;
}
if (transportConfig.name === 'GRPC') {
agentCard.url = `localhost:${port}`;
}
resolve();
}
);
});
});
expect(actual).to.deep.equal(expected);
});
});
afterEach(() => {
server.close();
grpcServer.forceShutdown();
});
describe('sendMessageStream', () => {
it('should send a message to the agent and read event stream', async () => {
const taskId = '1';
const contextId = '2';
const expected: AgentExecutionEvent[] = [
{
id: taskId,
contextId,
status: { state: 'submitted' },
kind: 'task',
},
{
taskId,
contextId,
kind: 'status-update',
status: { state: 'working' },
final: false,
},
{
taskId,
contextId,
kind: 'status-update',
status: { state: 'completed' },
final: true,
},
];
agentExecutor.events = expected;
const client = await clientFactory.createFromAgentCard(agentCard);
describe('sendMessage', () => {
it('should send a message to the agent', async () => {
const expected = createTestMessage('1', 'test');
agentExecutor.events = [expected];
const client = await clientFactory.createFromAgentCard(agentCard);
const actual: A2AStreamEventData[] = [];
for await (const message of client.sendMessageStream({
message: createTestMessage('1', 'test'),
})) {
actual.push(message);
}
const actual = await client.sendMessage({
message: createTestMessage('1', 'test'),
});
expect(removeUndefinedFields(actual)).to.deep.equal(expected);
});
});
expect(actual).to.deep.equal(expected);
describe('sendMessageStream', () => {
it('should send a message to the agent and read event stream', async () => {
const taskId = '1';
const contextId = '2';
const expected: AgentExecutionEvent[] = [
{
id: taskId,
contextId,
status: { state: 'submitted' },
kind: 'task',
artifacts: [],
history: [],
},
{
taskId,
contextId,
kind: 'status-update',
status: { state: 'working' },
final: false,
},
{
taskId,
contextId,
kind: 'status-update',
status: { state: 'completed' },
final: true,
},
];
agentExecutor.events = expected;
const client = await clientFactory.createFromAgentCard(agentCard);
const actual: A2AStreamEventData[] = [];
for await (const message of client.sendMessageStream({
message: createTestMessage('1', 'test'),
})) {
actual.push(message);
}
expect(removeUndefinedFields(actual)).to.deep.equal(expected);
});
it('should fallback to non-streaming sendMessage if agent does not support streaming', async () => {
agentCard.capabilities.streaming = false;
const requestMessage = createTestMessage('1', 'request-message');
const responseMessage = createTestMessage('2', 'response-message');
agentExecutor.events = [responseMessage];
const client = await clientFactory.createFromAgentCard(agentCard);
const actual: A2AStreamEventData[] = [];
for await (const message of client.sendMessageStream({ message: requestMessage })) {
actual.push(message);
}
expect(actual).to.have.lengthOf(1);
expect(removeUndefinedFields(actual[0])).to.deep.equal(responseMessage);
});
});
});
});
});
const removeUndefinedFields = (obj: any) => JSON.parse(JSON.stringify(obj));
function createTestMessage(id: string, text: string): Message {
return {
messageId: id,
extensions: [],
role: 'user',
parts: [{ kind: 'text', text }],
kind: 'message',

View File

@ -1,5 +1,4 @@
import { describe, it, beforeEach, afterEach, assert, expect } from 'vitest';
import sinon, { SinonStub, SinonFakeTimers } from 'sinon';
import { describe, it, beforeEach, afterEach, assert, expect, vi, type Mock } from 'vitest';
import { AgentExecutor } from '../../src/server/agent_execution/agent_executor.js';
import {
@ -50,7 +49,6 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
let mockTaskStore: TaskStore;
let mockAgentExecutor: AgentExecutor;
let executionEventBusManager: ExecutionEventBusManager;
let clock: SinonFakeTimers;
const testAgentCard: AgentCard = {
name: 'Test Agent',
@ -107,12 +105,10 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
);
});
// After each test, restore any sinon fakes or stubs
// After each test, restore any mocks
afterEach(() => {
sinon.restore();
if (clock) {
clock.restore();
}
vi.restoreAllMocks();
vi.useRealTimers();
});
// Helper function to create a basic user message
@ -135,7 +131,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
kind: 'message',
};
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
bus.publish(agentResponse);
bus.finished();
});
@ -143,10 +139,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
const result = await handler.sendMessage(params, serverCallContext);
assert.deepEqual(result, agentResponse, "The result should be the agent's message");
assert.isTrue(
(mockAgentExecutor as MockAgentExecutor).execute.calledOnce,
'AgentExecutor.execute should be called once'
);
expect((mockAgentExecutor as MockAgentExecutor).execute).toHaveBeenCalledTimes(1);
});
it('sendMessage: (blocking) should return a task in a completed state with an artifact', async () => {
@ -163,7 +156,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
parts: [{ kind: 'text', text: 'This is the content of the artifact.' }],
};
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
bus.publish({
id: taskId,
contextId,
@ -215,7 +208,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
it('sendMessage: should handle agent execution failure for blocking calls', async () => {
const errorMessage = 'Agent failed!';
(mockAgentExecutor as MockAgentExecutor).execute.rejects(new Error(errorMessage));
(mockAgentExecutor as MockAgentExecutor).execute.mockRejectedValue(new Error(errorMessage));
// Test blocking case
const blockingParams: MessageSendParams = {
@ -234,8 +227,8 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
});
it('sendMessage: (non-blocking) should return first task event immediately and process full task in background', async () => {
clock = sinon.useFakeTimers();
const saveSpy = sinon.spy(mockTaskStore, 'save');
vi.useFakeTimers();
const saveSpy = vi.spyOn(mockTaskStore, 'save');
const params: MessageSendParams = {
message: createTestMessage('msg-nonblock', 'Do a long task'),
@ -245,7 +238,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
const taskId = 'task-nonblock-123';
const contextId = 'ctx-nonblock-abc';
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
// First event is the task creation, which should be returned immediately
bus.publish({
id: taskId,
@ -255,7 +248,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
});
// Simulate work before publishing more events
await clock.tickAsync(500);
await vi.advanceTimersByTimeAsync(500);
bus.publish({
taskId,
@ -281,11 +274,11 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
);
// The background processing should not have completed yet
assert.isTrue(saveSpy.calledOnce, 'Save should be called for the initial task creation');
assert.equal(saveSpy.firstCall.args[0].status.state, 'submitted');
expect(saveSpy).toHaveBeenCalledTimes(1);
assert.equal(saveSpy.mock.calls[0][0].status.state, 'submitted');
// Allow the background processing to complete
await clock.runAllAsync();
await vi.runAllTimersAsync();
// Now, check the final state in the store to ensure background processing finished
const finalTask = await mockTaskStore.load(taskId, serverCallContext);
@ -295,12 +288,12 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
'completed',
"Task should be 'completed' in the store after background processing"
);
assert.isTrue(saveSpy.calledTwice, 'Save should be called twice (submitted and completed)');
assert.equal(saveSpy.secondCall.args[0].status.state, 'completed');
expect(saveSpy).toHaveBeenCalledTimes(2);
assert.equal(saveSpy.mock.calls[1][0].status.state, 'completed');
});
it('sendMessage: (non-blocking) should handle failure in event loop after successfull task event', async () => {
clock = sinon.useFakeTimers();
vi.useFakeTimers();
const mockTaskStore = new MockTaskStore();
const handler = new DefaultRequestHandler(
@ -320,7 +313,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
const taskId = 'task-nonblock-123';
const contextId = 'ctx-nonblock-abc';
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
// First event is the task creation, which should be returned immediately
bus.publish({
id: taskId,
@ -330,7 +323,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
});
// Simulate work before publishing more events
await clock.tickAsync(500);
await vi.advanceTimersByTimeAsync(500);
bus.publish({
taskId,
@ -344,7 +337,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
let finalTaskSaved: Task | undefined;
const errorMessage = 'Error thrown on saving completed task notification';
(mockTaskStore as MockTaskStore).save.callsFake(async (task) => {
(mockTaskStore as MockTaskStore).save.mockImplementation(async (task) => {
if (task.status.state == 'completed') {
throw new Error(errorMessage);
}
@ -368,7 +361,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
);
// Allow the background processing to complete
await clock.runAllAsync();
await vi.runAllTimersAsync();
assert.equal(finalTaskSaved!.status.state, 'failed');
assert.equal(finalTaskSaved!.id, taskId);
@ -382,7 +375,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
it('sendMessage: should handle agent execution failure for non-blocking calls', async () => {
const errorMessage = 'Agent failed!';
(mockAgentExecutor as MockAgentExecutor).execute.rejects(new Error(errorMessage));
(mockAgentExecutor as MockAgentExecutor).execute.mockRejectedValue(new Error(errorMessage));
// Test non-blocking case
const nonBlockingParams: MessageSendParams = {
@ -413,7 +406,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
let taskId: string;
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
taskId = ctx.taskId;
// Publish task creation
@ -488,7 +481,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
message: secondMessage,
};
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
// Publish a status update with working state
bus.publish({
taskId,
@ -603,7 +596,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
it('sendMessage: should return second task with full history if message is sent to an existing, non-terminal task, in non-blocking mode', async () => {
const contextId = 'ctx-history-abc';
clock = sinon.useFakeTimers();
vi.useFakeTimers();
// First message
const firstMessage = createTestMessage('msg-1', 'Message 1');
@ -614,7 +607,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
let taskId: string;
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
taskId = ctx.taskId;
// Publish task creation
@ -690,7 +683,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
configuration: { blocking: false },
};
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
// Publish a status update with working state
bus.publish({
taskId,
@ -700,7 +693,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
final: false,
});
await clock.tickAsync(10);
await vi.advanceTimersByTimeAsync(10);
// Publish a status update with working state and message
bus.publish({
@ -756,7 +749,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
assert.equal(secondTask.id, taskId, 'Should be the same task');
assert.equal(secondTask.status.state, 'working'); // It will receive the Task in the status of the first published event
await clock.runAllAsync(); // give time to the second task to publish all the updates
await vi.runAllTimersAsync(); // give time to the second task to publish all the updates
const finalTask = await mockTaskStore.load(taskId, serverCallContext);
@ -813,7 +806,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
const taskId = 'task-stream-1';
const contextId = 'ctx-stream-1';
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
bus.publish({
id: taskId,
contextId,
@ -915,7 +908,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
const taskId = 'task-input';
const contextId = 'ctx-input';
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
bus.publish({
id: taskId,
contextId,
@ -945,8 +938,8 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
});
it('resubscribe: should allow multiple clients to receive events for the same task', async () => {
const saveSpy = sinon.spy(mockTaskStore, 'save');
clock = sinon.useFakeTimers();
const saveSpy = vi.spyOn(mockTaskStore, 'save');
vi.useFakeTimers();
const params: MessageSendParams = {
message: createTestMessage('msg-5', 'Long running task'),
};
@ -954,7 +947,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
let taskId;
let contextId;
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
taskId = ctx.taskId;
contextId = ctx.contextId;
@ -971,7 +964,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
status: { state: 'working' },
final: false,
});
await clock.tickAsync(100);
await vi.advanceTimersByTimeAsync(100);
bus.publish({
taskId,
contextId,
@ -1007,7 +1000,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
const p1 = collect(stream1_iterator, results1);
const p2 = collect(stream2_generator, results2);
await clock.runAllAsync();
await vi.runAllTimersAsync();
await Promise.all([p1, p2]);
assert.equal((results1[0] as TaskStatusUpdateEvent).status.state, 'submitted');
@ -1018,8 +1011,8 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
assert.equal((results2[0] as Task).status.state, 'working');
assert.equal((results2[1] as TaskStatusUpdateEvent).status.state, 'completed');
assert.isTrue(saveSpy.calledThrice, 'TaskStore.save should be called 3 times');
const lastSaveCall = saveSpy.lastCall.args[0];
expect(saveSpy).toHaveBeenCalledTimes(3);
const lastSaveCall = saveSpy.mock.calls[saveSpy.mock.calls.length - 1][0];
assert.equal(lastSaveCall.id, taskId);
assert.equal(lastSaveCall.status.state, 'completed');
});
@ -1325,7 +1318,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
};
let taskId: string;
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
taskId = ctx.taskId;
fakeTaskExecute(ctx, bus);
});
@ -1341,11 +1334,13 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
};
// Verify push notifications were sent with complete task objects
assert.isTrue((mockPushNotificationSender as MockPushNotificationSender).send.calledThrice);
expect((mockPushNotificationSender as MockPushNotificationSender).send).toHaveBeenCalledTimes(
3
);
// Verify first call (submitted state)
const firstCallTask = (mockPushNotificationSender as MockPushNotificationSender).send.firstCall
.args[0] as Task;
const firstCallTask = (mockPushNotificationSender as MockPushNotificationSender).send.mock
.calls[0][0] as Task;
const expectedFirstTask: Task = {
...expectedTask,
status: { state: 'submitted' },
@ -1353,8 +1348,8 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
assert.deepEqual(firstCallTask, expectedFirstTask);
// // Verify second call (working state)
const secondCallTask = (mockPushNotificationSender as MockPushNotificationSender).send
.secondCall.args[0] as Task;
const secondCallTask = (mockPushNotificationSender as MockPushNotificationSender).send.mock
.calls[1][0] as Task;
const expectedSecondTask: Task = {
...expectedTask,
status: { state: 'working' },
@ -1362,8 +1357,8 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
assert.deepEqual(secondCallTask, expectedSecondTask);
// // Verify third call (completed state)
const thirdCallTask = (mockPushNotificationSender as MockPushNotificationSender).send.thirdCall
.args[0] as Task;
const thirdCallTask = (mockPushNotificationSender as MockPushNotificationSender).send.mock
.calls[2][0] as Task;
const expectedThirdTask: Task = {
...expectedTask,
status: { state: 'completed' },
@ -1400,7 +1395,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
};
let taskId: string;
(mockAgentExecutor as MockAgentExecutor).execute.callsFake(async (ctx, bus) => {
(mockAgentExecutor as MockAgentExecutor).execute.mockImplementation(async (ctx, bus) => {
taskId = ctx.taskId;
fakeTaskExecute(ctx, bus);
});
@ -1419,7 +1414,9 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
assert.isTrue((events[2] as TaskStatusUpdateEvent).final);
// Verify push notifications were sent with complete task objects
assert.isTrue((mockPushNotificationSender as MockPushNotificationSender).send.calledThrice);
expect((mockPushNotificationSender as MockPushNotificationSender).send).toHaveBeenCalledTimes(
3
);
const expectedTask: Task = {
id: taskId,
@ -1429,8 +1426,8 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
history: [params.message as Message],
};
// Verify first call (submitted state)
const firstCallTask = (mockPushNotificationSender as MockPushNotificationSender).send.firstCall
.args[0] as Task;
const firstCallTask = (mockPushNotificationSender as MockPushNotificationSender).send.mock
.calls[0][0] as Task;
const expectedFirstTask: Task = {
...expectedTask,
status: { state: 'submitted' },
@ -1438,8 +1435,8 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
assert.deepEqual(firstCallTask, expectedFirstTask);
// Verify second call (working state)
const secondCallTask = (mockPushNotificationSender as MockPushNotificationSender).send
.secondCall.args[0] as Task;
const secondCallTask = (mockPushNotificationSender as MockPushNotificationSender).send.mock
.calls[1][0] as Task;
const expectedSecondTask: Task = {
...expectedTask,
status: { state: 'working' },
@ -1447,8 +1444,8 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
assert.deepEqual(secondCallTask, expectedSecondTask);
// Verify third call (completed state)
const thirdCallTask = (mockPushNotificationSender as MockPushNotificationSender).send.thirdCall
.args[0] as Task;
const thirdCallTask = (mockPushNotificationSender as MockPushNotificationSender).send.mock
.calls[2][0] as Task;
const expectedThirdTask: Task = {
...expectedTask,
status: { state: 'completed' },
@ -1548,9 +1545,9 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
});
it('cancelTask: should cancel a running task and notify listeners', async () => {
clock = sinon.useFakeTimers();
vi.useFakeTimers();
// Use the more advanced mock for this specific test
const cancellableExecutor = new CancellableMockAgentExecutor(clock);
const cancellableExecutor = new CancellableMockAgentExecutor();
handler = new DefaultRequestHandler(
testAgentCard,
mockTaskStore,
@ -1571,7 +1568,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
})();
// Allow the task to be created and enter the 'working' state
await clock.tickAsync(150);
await vi.advanceTimersByTimeAsync(150);
const createdTask = streamEvents.find((e) => e.kind === 'task') as Task;
assert.isDefined(createdTask, 'Task creation event should have been received');
@ -1581,9 +1578,12 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
const cancelResponse = await handler.cancelTask({ id: taskId }, serverCallContext);
// Let the executor's loop run to completion to detect the cancellation
await clock.runAllAsync();
await vi.runAllTimersAsync();
assert.isTrue(cancellableExecutor.cancelTaskSpy.calledOnceWith(taskId, sinon.match.any));
expect(cancellableExecutor.cancelTaskSpy).toHaveBeenCalledExactlyOnceWith(
taskId,
expect.anything()
);
const finalTask = await handler.getTask({ id: taskId }, serverCallContext);
assert.equal(finalTask.status.state, 'canceled');
@ -1592,9 +1592,9 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
});
it('cancelTask: should fail when it fails to cancel a task', async () => {
clock = sinon.useFakeTimers();
vi.useFakeTimers();
// Use the more advanced mock for this specific test
const failingCancellableExecutor = new FailingCancellableMockAgentExecutor(clock);
const failingCancellableExecutor = new FailingCancellableMockAgentExecutor();
handler = new DefaultRequestHandler(
testAgentCard,
@ -1616,7 +1616,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
})();
// Allow the task to be created and enter the 'working' state
await clock.tickAsync(150);
await vi.advanceTimersByTimeAsync(150);
const createdTask = streamEvents.find((e) => e.kind === 'task') as Task;
assert.isDefined(createdTask, 'Task creation event should have been received');
@ -1633,8 +1633,9 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
assert.isUndefined(cancelResponse);
assert.equal(thrownError.code, -32002);
expect(thrownError.message).to.contain('Task not cancelable');
assert.isTrue(
failingCancellableExecutor.cancelTaskSpy.calledOnceWith(taskId, sinon.match.any)
expect(failingCancellableExecutor.cancelTaskSpy).toHaveBeenCalledWith(
taskId,
expect.anything()
);
}
});
@ -1656,7 +1657,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
assert.equal(error.code, -32002);
expect(error.message).to.contain('Task not cancelable');
}
assert.isFalse((mockAgentExecutor as MockAgentExecutor).cancelTask.called);
expect((mockAgentExecutor as MockAgentExecutor).cancelTask).not.toHaveBeenCalled();
});
it('should use contextId from incomingMessage if present (contextId assignment logic)', async () => {
@ -1670,7 +1671,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
},
};
let capturedContextId: string | undefined;
(mockAgentExecutor.execute as SinonStub).callsFake(async (ctx, bus) => {
(mockAgentExecutor.execute as unknown as Mock).mockImplementation(async (ctx, bus) => {
capturedContextId = ctx.contextId;
bus.publish({
id: ctx.taskId,
@ -1706,7 +1707,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
},
};
let capturedContextId: string | undefined;
(mockAgentExecutor.execute as SinonStub).callsFake(async (ctx, bus) => {
(mockAgentExecutor.execute as unknown as Mock).mockImplementation(async (ctx, bus) => {
capturedContextId = ctx.contextId;
bus.publish({
id: ctx.taskId,
@ -1730,7 +1731,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
},
};
let capturedContextId: string | undefined;
(mockAgentExecutor.execute as SinonStub).callsFake(async (ctx, bus) => {
(mockAgentExecutor.execute as unknown as Mock).mockImplementation(async (ctx, bus) => {
capturedContextId = ctx.contextId;
bus.publish({
id: ctx.taskId,
@ -1772,7 +1773,7 @@ describe('DefaultRequestHandler as A2ARequestHandler', () => {
};
let capturedRequestContext: RequestContext | undefined;
(mockAgentExecutor.execute as SinonStub).callsFake(
(mockAgentExecutor.execute as unknown as Mock).mockImplementation(
async (ctx: RequestContext, bus: ExecutionEventBus) => {
capturedRequestContext = ctx;
bus.publish({

View File

@ -377,64 +377,4 @@ describe('DefaultExecutionEventBus', () => {
expect(thisCapture.value).to.equal(eventBus);
});
});
describe('listener errors', () => {
async function captureUncaughtException(run: () => void): Promise<void> {
// Node's EventTarget reports listener errors as an uncaught exception on nextTick.
// We attach a temporary handler to prevent vitest from failing the run.
let handlerCalled = false;
const handler = () => {
handlerCalled = true;
};
// Use the real Node global when available (no casts); `typeof` is safe even if `process` is missing.
const nodeProcess = typeof process !== 'undefined' ? process : undefined;
if (nodeProcess) {
nodeProcess.once('uncaughtException', handler);
}
run();
// Give Node a tick to surface the uncaught exception (if any), then clean up.
await new Promise((resolve) => setTimeout(resolve, 0));
if (!handlerCalled && nodeProcess) {
nodeProcess.removeListener('uncaughtException', handler);
}
}
it('should continue calling other event listeners when one throws', async () => {
let secondCalled = false;
await captureUncaughtException(() => {
eventBus.on('event', () => {
throw new Error('listener error');
});
eventBus.on('event', () => {
secondCalled = true;
});
eventBus.publish(createMessage('test'));
});
expect(secondCalled).to.equal(true);
});
it('should continue calling other finished listeners when one throws', async () => {
let secondCalled = false;
await captureUncaughtException(() => {
eventBus.on('finished', () => {
throw new Error('listener error');
});
eventBus.on('finished', () => {
secondCalled = true;
});
eventBus.finished();
});
expect(secondCalled).to.equal(true);
});
});
});

View File

@ -1,22 +1,31 @@
import { describe, it, beforeEach, afterEach, assert, expect } from 'vitest';
import sinon, { SinonStub } from 'sinon';
import {
describe,
it,
beforeEach,
afterEach,
assert,
expect,
vi,
Mock,
MockInstance,
} from 'vitest';
import express, { Express, NextFunction, Request, Response } from 'express';
import request from 'supertest';
import { A2AExpressApp } from '../../src/server/express/a2a_express_app.js';
import { A2ARequestHandler } from '../../src/server/request_handler/a2a_request_handler.js';
import { JsonRpcTransportHandler } from '../../src/server/transports/jsonrpc/jsonrpc_transport_handler.js';
import { AgentCard, JSONRPCSuccessResponse, JSONRPCErrorResponse } from '../../src/index.js';
import { AGENT_CARD_PATH, HTTP_EXTENSION_HEADER } from '../../src/constants.js';
import { A2AError } from '../../src/server/error.js';
import { ServerCallContext } from '../../src/server/context.js';
import { User, UnauthenticatedUser } from '../../src/server/authentication/user.js';
import { A2AExpressApp } from '../../../src/server/express/a2a_express_app.js';
import { A2ARequestHandler } from '../../../src/server/request_handler/a2a_request_handler.js';
import { JsonRpcTransportHandler } from '../../../src/server/transports/jsonrpc/jsonrpc_transport_handler.js';
import { AgentCard, JSONRPCSuccessResponse, JSONRPCErrorResponse } from '../../../src/index.js';
import { AGENT_CARD_PATH, HTTP_EXTENSION_HEADER } from '../../../src/constants.js';
import { A2AError } from '../../../src/server/error.js';
import { ServerCallContext } from '../../../src/server/context.js';
import { User, UnauthenticatedUser } from '../../../src/server/authentication/user.js';
describe('A2AExpressApp', () => {
let mockRequestHandler: A2ARequestHandler;
let app: A2AExpressApp;
let expressApp: Express;
let handleStub: SinonStub;
let handleStub: MockInstance;
// Helper function to create JSON-RPC request bodies
const createRpcRequest = (id: string | null, method = 'message/send', params: object = {}) => ({
@ -44,27 +53,27 @@ describe('A2AExpressApp', () => {
beforeEach(() => {
mockRequestHandler = {
getAgentCard: sinon.stub().resolves(testAgentCard),
getAuthenticatedExtendedAgentCard: sinon.stub(),
sendMessage: sinon.stub(),
sendMessageStream: sinon.stub(),
getTask: sinon.stub(),
cancelTask: sinon.stub(),
setTaskPushNotificationConfig: sinon.stub(),
getTaskPushNotificationConfig: sinon.stub(),
listTaskPushNotificationConfigs: sinon.stub(),
deleteTaskPushNotificationConfig: sinon.stub(),
resubscribe: sinon.stub(),
getAgentCard: vi.fn().mockResolvedValue(testAgentCard),
getAuthenticatedExtendedAgentCard: vi.fn(),
sendMessage: vi.fn(),
sendMessageStream: vi.fn(),
getTask: vi.fn(),
cancelTask: vi.fn(),
setTaskPushNotificationConfig: vi.fn(),
getTaskPushNotificationConfig: vi.fn(),
listTaskPushNotificationConfigs: vi.fn(),
deleteTaskPushNotificationConfig: vi.fn(),
resubscribe: vi.fn(),
};
app = new A2AExpressApp(mockRequestHandler);
expressApp = express();
handleStub = sinon.stub(JsonRpcTransportHandler.prototype, 'handle');
handleStub = vi.spyOn(JsonRpcTransportHandler.prototype, 'handle');
});
afterEach(() => {
sinon.restore();
vi.restoreAllMocks();
});
describe('constructor', () => {
@ -91,7 +100,7 @@ describe('A2AExpressApp', () => {
const response = await request(expressApp).get(`/${AGENT_CARD_PATH}`).expect(200);
assert.deepEqual(response.body, testAgentCard);
assert.isTrue((mockRequestHandler.getAgentCard as SinonStub).calledOnce);
expect(mockRequestHandler.getAgentCard as Mock).toHaveBeenCalledTimes(1);
});
it('should return agent card on custom path when agentCardPath is provided', async () => {
@ -106,7 +115,7 @@ describe('A2AExpressApp', () => {
it('should handle errors when getting agent card', async () => {
const errorMessage = 'Failed to get agent card';
(mockRequestHandler.getAgentCard as SinonStub).rejects(new Error(errorMessage));
(mockRequestHandler.getAgentCard as Mock).mockRejectedValue(new Error(errorMessage));
const response = await request(expressApp).get(`/${AGENT_CARD_PATH}`).expect(500);
@ -128,14 +137,14 @@ describe('A2AExpressApp', () => {
result: { message: 'success' },
};
handleStub.resolves(mockResponse);
handleStub.mockResolvedValue(mockResponse);
const requestBody = createRpcRequest('test-id');
const response = await request(expressApp).post('/').send(requestBody).expect(200);
assert.deepEqual(response.body, mockResponse);
assert.isTrue(handleStub.calledOnceWith(requestBody));
expect(handleStub).toHaveBeenCalledExactlyOnceWith(requestBody, expect.anything());
});
it('should handle streaming JSON-RPC response', async () => {
@ -146,7 +155,7 @@ describe('A2AExpressApp', () => {
},
};
handleStub.resolves(mockStreamResponse);
handleStub.mockResolvedValue(mockStreamResponse);
const requestBody = createRpcRequest('stream-test', 'message/stream');
@ -169,7 +178,7 @@ describe('A2AExpressApp', () => {
},
};
handleStub.resolves(mockErrorStream);
handleStub.mockResolvedValue(mockErrorStream);
const requestBody = createRpcRequest('stream-error-test', 'message/stream');
@ -188,7 +197,7 @@ describe('A2AExpressApp', () => {
},
};
handleStub.resolves(mockImmediateErrorStream);
handleStub.mockResolvedValue(mockImmediateErrorStream);
const requestBody = createRpcRequest('immediate-stream-error-test', 'message/stream');
@ -206,7 +215,7 @@ describe('A2AExpressApp', () => {
it('should handle general processing error', async () => {
const error = new A2AError(-32603, 'Processing error');
handleStub.rejects(error);
handleStub.mockRejectedValue(error);
const requestBody = createRpcRequest('error-test');
@ -226,7 +235,7 @@ describe('A2AExpressApp', () => {
it('should handle non-A2AError with fallback error handling', async () => {
const genericError = new Error('Generic error');
handleStub.rejects(genericError);
handleStub.mockRejectedValue(genericError);
const requestBody = createRpcRequest('generic-error-test');
@ -239,7 +248,7 @@ describe('A2AExpressApp', () => {
it('should handle request without id', async () => {
const error = new A2AError(-32600, 'No ID error');
handleStub.rejects(error);
handleStub.mockRejectedValue(error);
const requestBody = createRpcRequest(null);
@ -254,7 +263,7 @@ describe('A2AExpressApp', () => {
id: 'test-id',
result: { message: 'success' },
};
handleStub.resolves(mockResponse);
handleStub.mockResolvedValue(mockResponse);
const requestBody = createRpcRequest('test-id');
const uriExtensionsValues = 'test-extension-uri, another-extension';
@ -266,8 +275,8 @@ describe('A2AExpressApp', () => {
.send(requestBody)
.expect(200);
assert.isTrue(handleStub.calledOnce);
const serverCallContext = handleStub.getCall(0).args[1];
expect(handleStub).toHaveBeenCalledTimes(1);
const serverCallContext = handleStub.mock.calls[0][1];
expect(serverCallContext).to.be.an.instanceOf(ServerCallContext);
expect(serverCallContext.requestedExtensions).to.deep.equal([
'test-extension-uri',
@ -285,13 +294,15 @@ describe('A2AExpressApp', () => {
const requestBody = createRpcRequest('test-id');
const uriExtensionsValues = 'activated-extension, non-activated-extension';
handleStub.callsFake(async (requestBody: any, serverCallContext: ServerCallContext) => {
const firstRequestedExtension = serverCallContext.requestedExtensions
?.values()
.next().value;
serverCallContext.addActivatedExtension(firstRequestedExtension);
return mockResponse;
});
handleStub.mockImplementation(
async (requestBody: any, serverCallContext: ServerCallContext) => {
const firstRequestedExtension = serverCallContext.requestedExtensions
?.values()
.next().value;
serverCallContext.addActivatedExtension(firstRequestedExtension);
return mockResponse;
}
);
const response = await request(expressApp)
.post('/')
.set(HTTP_EXTENSION_HEADER, uriExtensionsValues)
@ -305,7 +316,7 @@ describe('A2AExpressApp', () => {
describe('middleware integration', () => {
it('should apply custom middlewares to routes', async () => {
const middlewareCalled = sinon.spy();
const middlewareCalled = vi.fn();
const testMiddleware = (_req: Request, _res: Response, next: NextFunction) => {
middlewareCalled();
next();
@ -316,7 +327,7 @@ describe('A2AExpressApp', () => {
await request(middlewareApp).get(`/${AGENT_CARD_PATH}`).expect(200);
assert.isTrue(middlewareCalled.calledOnce);
expect(middlewareCalled).toHaveBeenCalledTimes(1);
});
it('should handle middleware errors', async () => {
@ -340,13 +351,13 @@ describe('A2AExpressApp', () => {
id: 'test-id',
result: { message: 'success' },
};
handleStub.resolves(mockResponse);
handleStub.mockResolvedValue(mockResponse);
const requestBody = createRpcRequest('test-id');
await request(middlewareApp).post('/').send(requestBody).expect(200);
assert.isTrue(handleStub.calledOnce);
const serverCallContext = handleStub.getCall(0).args[1];
expect(handleStub).toHaveBeenCalledTimes(1);
const serverCallContext = handleStub.mock.calls[0][1];
expect(serverCallContext).to.be.an.instanceOf(ServerCallContext);
expect(serverCallContext.user).to.be.an.instanceOf(UnauthenticatedUser);
expect(serverCallContext.user.isAuthenticated).to.be.false;
@ -381,13 +392,13 @@ describe('A2AExpressApp', () => {
id: 'test-id',
result: { message: 'success' },
};
handleStub.resolves(mockResponse);
handleStub.mockResolvedValue(mockResponse);
const requestBody = createRpcRequest('test-id');
await request(middlewareApp).post('/').send(requestBody).expect(200);
assert.isTrue(handleStub.calledOnce);
const serverCallContext = handleStub.getCall(0).args[1];
expect(handleStub).toHaveBeenCalledTimes(1);
const serverCallContext = handleStub.mock.calls[0][1];
expect(serverCallContext).to.be.an.instanceOf(ServerCallContext);
expect(serverCallContext.user.isAuthenticated).to.be.true;
expect(serverCallContext.user.userName).to.equal('authenticated-user');
@ -430,13 +441,13 @@ describe('A2AExpressApp', () => {
id: 'test-id',
result: { message: 'success' },
};
handleStub.resolves(mockResponse);
handleStub.mockResolvedValue(mockResponse);
const requestBody = createRpcRequest('test-id');
await request(middlewareApp).post('/').send(requestBody).expect(200);
assert.isTrue(handleStub.calledOnce);
const serverCallContext = handleStub.getCall(0).args[1];
expect(handleStub).toHaveBeenCalledTimes(1);
const serverCallContext = handleStub.mock.calls[0][1];
expect(serverCallContext).to.be.an.instanceOf(ServerCallContext);
expect(serverCallContext.user.isAuthenticated).to.be.true;
expect(serverCallContext.user.userName).to.equal('test_email');
@ -467,13 +478,13 @@ describe('A2AExpressApp', () => {
id: 'test-id',
result: { message: 'success' },
};
handleStub.resolves(mockResponse);
handleStub.mockResolvedValue(mockResponse);
const requestBody = createRpcRequest('test-id');
await request(middlewareApp).post('/').send(requestBody).expect(200);
assert.isTrue(handleStub.calledOnce);
const serverCallContext = handleStub.getCall(0).args[1];
expect(handleStub).toHaveBeenCalledTimes(1);
const serverCallContext = handleStub.mock.calls[0][1];
expect(serverCallContext).to.be.an.instanceOf(ServerCallContext);
expect(serverCallContext.user.isAuthenticated).to.be.false;
expect(serverCallContext.user.userName).to.equal('');
@ -506,7 +517,7 @@ describe('A2AExpressApp', () => {
await request(jsonApp).post('/').send(requestBody).expect(200);
assert.isTrue(handleStub.calledOnceWith(requestBody));
expect(handleStub).toHaveBeenCalledExactlyOnceWith(requestBody, expect.anything());
});
it('should handle malformed json request', async () => {

View File

@ -1,12 +1,19 @@
import { describe, it, beforeEach, afterEach, assert } from 'vitest';
import sinon, { SinonStub } from 'sinon';
import { describe, it, beforeEach, afterEach, assert, expect, vi, Mock } from 'vitest';
import express, { Express } from 'express';
import request from 'supertest';
import { restHandler, UserBuilder } from '../../src/server/express/index.js';
import { A2ARequestHandler } from '../../src/server/request_handler/a2a_request_handler.js';
import { AgentCard, Task, Message } from '../../src/types.js';
import { A2AError } from '../../src/server/error.js';
import { restHandler, UserBuilder } from '../../../src/server/express/index.js';
import { A2ARequestHandler } from '../../../src/server/request_handler/a2a_request_handler.js';
import { AgentCard, Task, Message } from '../../../src/types.js';
import { A2AError } from '../../../src/server/error.js';
import { ToProto } from '../../../src/types/converters/to_proto.js';
import {
ListTaskPushNotificationConfigResponse,
Message as ProtoMessage,
SendMessageResponse,
TaskPushNotificationConfig,
} from '../../../src/types/pb/a2a_types.js';
import { FromProto } from '../../../src/types/converters/from_proto.js';
/**
* Test suite for restHandler - HTTP+JSON/REST transport implementation
@ -48,14 +55,6 @@ describe('restHandler', () => {
kind: 'message' as const,
};
// snake_case format (REST/TCK style input)
const snakeCaseMessage = {
message_id: 'msg-1',
role: 'user' as const,
parts: [{ kind: 'text' as const, text: 'Hello' }],
kind: 'message' as const,
};
const testTask: Task = {
id: 'task-1',
kind: 'task' as const,
@ -66,17 +65,17 @@ describe('restHandler', () => {
beforeEach(() => {
mockRequestHandler = {
getAgentCard: sinon.stub().resolves(testAgentCard),
getAuthenticatedExtendedAgentCard: sinon.stub().resolves(testAgentCard),
sendMessage: sinon.stub(),
sendMessageStream: sinon.stub(),
getTask: sinon.stub(),
cancelTask: sinon.stub(),
setTaskPushNotificationConfig: sinon.stub(),
getTaskPushNotificationConfig: sinon.stub(),
listTaskPushNotificationConfigs: sinon.stub(),
deleteTaskPushNotificationConfig: sinon.stub(),
resubscribe: sinon.stub(),
getAgentCard: vi.fn().mockResolvedValue(testAgentCard),
getAuthenticatedExtendedAgentCard: vi.fn().mockResolvedValue(testAgentCard),
sendMessage: vi.fn(),
sendMessageStream: vi.fn(),
getTask: vi.fn(),
cancelTask: vi.fn(),
setTaskPushNotificationConfig: vi.fn(),
getTaskPushNotificationConfig: vi.fn(),
listTaskPushNotificationConfigs: vi.fn(),
deleteTaskPushNotificationConfig: vi.fn(),
resubscribe: vi.fn(),
};
app = express();
@ -89,7 +88,7 @@ describe('restHandler', () => {
});
afterEach(() => {
sinon.restore();
vi.restoreAllMocks();
});
describe('GET /v1/card', () => {
@ -97,12 +96,12 @@ describe('restHandler', () => {
const response = await request(app).get('/v1/card').expect(200);
// REST API returns data (format checked by handler)
assert.isTrue((mockRequestHandler.getAuthenticatedExtendedAgentCard as SinonStub).calledOnce);
expect(mockRequestHandler.getAuthenticatedExtendedAgentCard as Mock).toHaveBeenCalledTimes(1);
assert.deepEqual(response.body.name, testAgentCard.name);
});
it('should return 500 if getAuthenticatedExtendedAgentCard fails', async () => {
(mockRequestHandler.getAuthenticatedExtendedAgentCard as SinonStub).rejects(
(mockRequestHandler.getAuthenticatedExtendedAgentCard as Mock).mockRejectedValue(
A2AError.internalError('Card fetch failed')
);
@ -115,44 +114,39 @@ describe('restHandler', () => {
describe('POST /v1/message:send', () => {
it('should accept camelCase message and return 201 with Task', async () => {
(mockRequestHandler.sendMessage as SinonStub).resolves(testTask);
const message = ProtoMessage.toJSON(ToProto.message(testMessage));
(mockRequestHandler.sendMessage as Mock).mockResolvedValue(testTask);
const response = await request(app)
.post('/v1/message:send')
.send({ message: testMessage })
.expect(201);
const response = await request(app).post('/v1/message:send').send({ message }).expect(201);
assert.deepEqual(response.body.id, testTask.id);
assert.deepEqual(response.body.kind, 'task');
});
expect(mockRequestHandler.sendMessage).toHaveBeenCalledWith(
{
message: {
messageId: 'msg-1',
role: 'user',
parts: [{ kind: 'text', text: 'Hello' }],
kind: 'message',
contextId: undefined,
extensions: [],
metadata: undefined,
taskId: undefined,
},
configuration: undefined,
metadata: undefined,
},
expect.anything()
);
it('should accept snake_case message and return 201 with Task', async () => {
(mockRequestHandler.sendMessage as SinonStub).resolves(testTask);
const response = await request(app)
.post('/v1/message:send')
.send({ message: snakeCaseMessage })
.expect(201);
assert.deepEqual(response.body.id, testTask.id);
assert.deepEqual(response.body.kind, 'task');
});
it('should return camelCase response regardless of input format', async () => {
(mockRequestHandler.sendMessage as SinonStub).resolves(testTask);
const response = await request(app)
.post('/v1/message:send')
.send({ message: snakeCaseMessage })
.expect(201);
// Response must be camelCase only
assert.property(response.body, 'contextId');
assert.notProperty(response.body, 'context_id');
const converted_result = FromProto.sendMessageResult(
SendMessageResponse.fromJSON(response.body)
);
assert.deepEqual((converted_result as Task).id, testTask.id);
// Kind is not present in Proto JSON
assert.isUndefined(response.body.kind);
});
it('should return 400 when message is invalid', async () => {
(mockRequestHandler.sendMessage as SinonStub).rejects(
(mockRequestHandler.sendMessage as Mock).mockRejectedValue(
A2AError.invalidParams('Message is required')
);
@ -162,38 +156,40 @@ describe('restHandler', () => {
describe('POST /v1/message:stream', () => {
it('should accept camelCase message and stream via SSE', async () => {
const message = ProtoMessage.toJSON(ToProto.message(testMessage));
async function* mockStream() {
yield testMessage;
yield testTask;
}
(mockRequestHandler.sendMessageStream as SinonStub).resolves(mockStream());
(mockRequestHandler.sendMessageStream as Mock).mockResolvedValue(mockStream());
const response = await request(app)
.post('/v1/message:stream')
.send({ message: testMessage })
.expect(200);
const response = await request(app).post('/v1/message:stream').send({ message }).expect(200);
assert.equal(response.headers['content-type'], 'text/event-stream');
});
it('should accept snake_case message and stream via SSE', async () => {
async function* mockStream() {
yield testMessage;
}
(mockRequestHandler.sendMessageStream as SinonStub).resolves(mockStream());
const response = await request(app)
.post('/v1/message:stream')
.send({ message: snakeCaseMessage })
.expect(200);
assert.equal(response.headers['content-type'], 'text/event-stream');
expect(mockRequestHandler.sendMessageStream).toHaveBeenCalledWith(
{
message: {
messageId: 'msg-1',
role: 'user',
parts: [{ kind: 'text', text: 'Hello' }],
kind: 'message',
contextId: undefined,
extensions: [],
metadata: undefined,
taskId: undefined,
},
configuration: undefined,
metadata: undefined,
},
expect.anything()
);
});
it('should return 400 if streaming is not supported', async () => {
const noStreamRequestHandler = {
...mockRequestHandler,
getAgentCard: sinon.stub().resolves({
getAgentCard: vi.fn().mockResolvedValue({
...testAgentCard,
capabilities: { streaming: false, pushNotifications: false },
}),
@ -215,25 +211,32 @@ describe('restHandler', () => {
describe('GET /v1/tasks/:taskId', () => {
it('should return task with 200 OK', async () => {
(mockRequestHandler.getTask as SinonStub).resolves(testTask);
(mockRequestHandler.getTask as Mock).mockResolvedValue(testTask);
const response = await request(app).get('/v1/tasks/task-1').expect(200);
assert.deepEqual(response.body.id, testTask.id);
assert.deepEqual(response.body.kind, 'task');
assert.isTrue((mockRequestHandler.getTask as SinonStub).calledWith({ id: 'task-1' }));
// Kind is not present in Proto JSON
assert.isUndefined(response.body.kind);
// Status state is enum string
assert.deepEqual(response.body.status.state, 'TASK_STATE_COMPLETED');
expect(mockRequestHandler.getTask as Mock).toHaveBeenCalledWith(
{ id: 'task-1' },
expect.anything()
);
});
it('should support historyLength query parameter', async () => {
(mockRequestHandler.getTask as SinonStub).resolves(testTask);
(mockRequestHandler.getTask as Mock).mockResolvedValue(testTask);
await request(app).get('/v1/tasks/task-1?historyLength=10').expect(200);
assert.isTrue(
(mockRequestHandler.getTask as SinonStub).calledWith({
expect(mockRequestHandler.getTask as Mock).toHaveBeenCalledWith(
{
id: 'task-1',
historyLength: 10,
})
},
expect.anything()
);
});
@ -242,7 +245,7 @@ describe('restHandler', () => {
});
it('should return 404 if task is not found', async () => {
(mockRequestHandler.getTask as SinonStub).rejects(A2AError.taskNotFound('task-1'));
(mockRequestHandler.getTask as Mock).mockRejectedValue(A2AError.taskNotFound('task-1'));
const response = await request(app).get('/v1/tasks/task-1').expect(404);
@ -254,17 +257,21 @@ describe('restHandler', () => {
describe('POST /v1/tasks/:taskId:cancel', () => {
it('should cancel task and return 202 Accepted', async () => {
const cancelledTask = { ...testTask, status: { state: 'canceled' as const } };
(mockRequestHandler.cancelTask as SinonStub).resolves(cancelledTask);
(mockRequestHandler.cancelTask as Mock).mockResolvedValue(cancelledTask);
const response = await request(app).post('/v1/tasks/task-1:cancel').expect(202);
assert.deepEqual(response.body.id, cancelledTask.id);
assert.deepEqual(response.body.status.state, 'canceled');
assert.isTrue((mockRequestHandler.cancelTask as SinonStub).calledWith({ id: 'task-1' }));
assert.deepEqual(response.body.status.state, 'TASK_STATE_CANCELLED');
expect(mockRequestHandler.cancelTask).toHaveBeenCalledWith(
{ id: 'task-1' },
expect.anything()
);
});
it('should return 404 if task is not found', async () => {
(mockRequestHandler.cancelTask as SinonStub).rejects(A2AError.taskNotFound('task-1'));
(mockRequestHandler.cancelTask as Mock).mockRejectedValue(A2AError.taskNotFound('task-1'));
const response = await request(app).post('/v1/tasks/task-1:cancel').expect(404);
@ -273,7 +280,9 @@ describe('restHandler', () => {
});
it('should return 409 if task is not cancelable', async () => {
(mockRequestHandler.cancelTask as SinonStub).rejects(A2AError.taskNotCancelable('task-1'));
(mockRequestHandler.cancelTask as Mock).mockRejectedValue(
A2AError.taskNotCancelable('task-1')
);
const response = await request(app).post('/v1/tasks/task-1:cancel').expect(409);
@ -288,19 +297,23 @@ describe('restHandler', () => {
yield testTask;
}
(mockRequestHandler.resubscribe as SinonStub).resolves(mockStream());
(mockRequestHandler.resubscribe as Mock).mockResolvedValue(mockStream());
const response = await request(app).post('/v1/tasks/task-1:subscribe').expect(200);
assert.equal(response.headers['content-type'], 'text/event-stream');
assert.isTrue((mockRequestHandler.resubscribe as SinonStub).calledWith({ id: 'task-1' }));
expect(mockRequestHandler.resubscribe).toHaveBeenCalledWith(
{ id: 'task-1' },
expect.anything()
);
});
it('should return 400 if streaming is not supported', async () => {
// Create new app with handler that has capabilities without streaming
const noStreamRequestHandler = {
...mockRequestHandler,
getAgentCard: sinon.stub().resolves({
getAgentCard: vi.fn().mockResolvedValue({
...testAgentCard,
capabilities: { streaming: false, pushNotifications: false },
}),
@ -330,59 +343,66 @@ describe('restHandler', () => {
};
describe('POST /v1/tasks/:taskId/pushNotificationConfigs', () => {
it('should accept camelCase pushNotificationConfig and return 201', async () => {
(mockRequestHandler.setTaskPushNotificationConfig as SinonStub).resolves(mockConfig);
it.each([
{
name: 'camelCase',
payload: {
parent: 'tasks/task-1',
configId: 'push-954f670f-598d-49bf-9981-642d523f7746',
config: {
name: 'tasks/task-1/pushNotificationConfigs/push-954f670f-598d-49bf-9981-642d523f7746',
pushNotificationConfig: {
id: 'push-954f670f-598d-49bf-9981-642d523f7746',
url: 'http://127.0.0.1:9999/webhook',
},
},
},
},
{
name: 'snake_case',
payload: {
parent: 'tasks/task-1',
config_id: 'push-954f670f-598d-49bf-9981-642d523f7746',
config: {
name: 'tasks/task-1/pushNotificationConfigs/push-954f670f-598d-49bf-9981-642d523f7746',
push_notification_config: {
id: 'push-954f670f-598d-49bf-9981-642d523f7746',
url: 'http://127.0.0.1:9999/webhook',
},
},
},
},
])('should accept $name config and return 201', async ({ payload }) => {
(mockRequestHandler.setTaskPushNotificationConfig as Mock).mockResolvedValue(mockConfig);
const response = await request(app)
.post('/v1/tasks/task-1/pushNotificationConfigs')
.send({
.send(payload)
.expect(201);
const protoResponse = FromProto.taskPushNotificationConfig(
TaskPushNotificationConfig.fromJSON(response.body)
);
assert.deepEqual(protoResponse.taskId, mockConfig.taskId);
expect(mockRequestHandler.setTaskPushNotificationConfig).toHaveBeenCalledWith(
{
taskId: 'task-1',
pushNotificationConfig: {
id: 'config-1',
url: 'https://example.com/webhook',
id: 'push-954f670f-598d-49bf-9981-642d523f7746',
url: 'http://127.0.0.1:9999/webhook',
token: undefined,
authentication: undefined,
},
})
.expect(201);
assert.deepEqual(response.body.taskId, mockConfig.taskId);
});
it('should accept snake_case push_notification_config and return 201', async () => {
(mockRequestHandler.setTaskPushNotificationConfig as SinonStub).resolves(mockConfig);
const response = await request(app)
.post('/v1/tasks/task-1/pushNotificationConfigs')
.send({
push_notification_config: {
id: 'config-1',
url: 'https://example.com/webhook',
},
})
.expect(201);
assert.deepEqual(response.body.taskId, mockConfig.taskId);
});
it('should return camelCase response regardless of input format', async () => {
(mockRequestHandler.setTaskPushNotificationConfig as SinonStub).resolves(mockConfig);
const response = await request(app)
.post('/v1/tasks/task-1/pushNotificationConfigs')
.send({
push_notification_config: { id: 'config-1', url: 'https://example.com/webhook' },
})
.expect(201);
// Response must be camelCase only
assert.property(response.body, 'taskId');
assert.property(response.body, 'pushNotificationConfig');
assert.notProperty(response.body, 'task_id');
assert.notProperty(response.body, 'push_notification_config');
},
expect.anything()
);
});
it('should return 400 if push notifications not supported', async () => {
const noPNRequestHandler = {
...mockRequestHandler,
getAgentCard: sinon.stub().resolves({
getAgentCard: vi.fn().mockResolvedValue({
...testAgentCard,
capabilities: { streaming: false, pushNotifications: false },
}),
@ -405,37 +425,47 @@ describe('restHandler', () => {
describe('GET /v1/tasks/:taskId/pushNotificationConfigs', () => {
it('should list push notification configs and return 200', async () => {
const configs = [mockConfig];
(mockRequestHandler.listTaskPushNotificationConfigs as SinonStub).resolves(configs);
(mockRequestHandler.listTaskPushNotificationConfigs as Mock).mockResolvedValue(configs);
const response = await request(app)
.get('/v1/tasks/task-1/pushNotificationConfigs')
.expect(200);
assert.isArray(response.body);
assert.lengthOf(response.body, configs.length);
const convertedResult = FromProto.listTaskPushNotificationConfig(
ListTaskPushNotificationConfigResponse.fromJSON(response.body)
);
assert.isArray(convertedResult);
assert.lengthOf(convertedResult, configs.length);
expect(mockRequestHandler.listTaskPushNotificationConfigs).toHaveBeenCalledWith(
{ id: 'task-1' },
expect.anything()
);
});
});
describe('GET /v1/tasks/:taskId/pushNotificationConfigs/:configId', () => {
it('should get specific push notification config and return 200', async () => {
(mockRequestHandler.getTaskPushNotificationConfig as SinonStub).resolves(mockConfig);
(mockRequestHandler.getTaskPushNotificationConfig as Mock).mockResolvedValue(mockConfig);
const response = await request(app)
.get('/v1/tasks/task-1/pushNotificationConfigs/config-1')
.expect(200);
// REST API returns camelCase
assert.deepEqual(response.body.taskId, mockConfig.taskId);
assert.isTrue(
(mockRequestHandler.getTaskPushNotificationConfig as SinonStub).calledWith({
id: 'task-1',
pushNotificationConfigId: 'config-1',
})
const convertedResult = FromProto.taskPushNotificationConfig(
TaskPushNotificationConfig.fromJSON(response.body)
);
assert.deepEqual(convertedResult.taskId, mockConfig.taskId);
expect(mockRequestHandler.getTaskPushNotificationConfig).toHaveBeenCalledWith(
{ id: 'task-1', pushNotificationConfigId: 'config-1' },
expect.anything()
);
});
it('should return 404 if config not found', async () => {
(mockRequestHandler.getTaskPushNotificationConfig as SinonStub).rejects(
(mockRequestHandler.getTaskPushNotificationConfig as Mock).mockRejectedValue(
A2AError.taskNotFound('task-1')
);
@ -450,20 +480,18 @@ describe('restHandler', () => {
describe('DELETE /v1/tasks/:taskId/pushNotificationConfigs/:configId', () => {
it('should delete push notification config and return 204', async () => {
(mockRequestHandler.deleteTaskPushNotificationConfig as SinonStub).resolves();
(mockRequestHandler.deleteTaskPushNotificationConfig as Mock).mockResolvedValue(undefined);
await request(app).delete('/v1/tasks/task-1/pushNotificationConfigs/config-1').expect(204);
assert.isTrue(
(mockRequestHandler.deleteTaskPushNotificationConfig as SinonStub).calledWith({
id: 'task-1',
pushNotificationConfigId: 'config-1',
})
expect(mockRequestHandler.deleteTaskPushNotificationConfig).toHaveBeenCalledWith(
{ id: 'task-1', pushNotificationConfigId: 'config-1' },
expect.anything()
);
});
it('should return 404 if config not found', async () => {
(mockRequestHandler.deleteTaskPushNotificationConfig as SinonStub).rejects(
(mockRequestHandler.deleteTaskPushNotificationConfig as Mock).mockRejectedValue(
A2AError.taskNotFound('task-1')
);
@ -481,54 +509,96 @@ describe('restHandler', () => {
* File Parts Format Tests
*/
describe('File parts format acceptance', () => {
it('should accept camelCase mimeType in file parts', async () => {
(mockRequestHandler.sendMessage as SinonStub).resolves(testTask);
await request(app)
.post('/v1/message:send')
.send({
it.each([
{
name: 'camelCase',
payload: {
message: {
messageId: 'msg-file',
role: 'user',
messageId: 'msg-parts',
role: 'ROLE_USER',
kind: 'message',
content: [
{
file: {
fileWithUri: 'https://example.com/file.pdf',
mimeType: 'application/pdf',
},
},
{
text: 'Hello world',
},
{
data: {
data: { foo: 'bar' },
},
},
],
},
},
},
{
name: 'snake_case',
payload: {
message: {
message_id: 'msg-parts',
role: 'ROLE_USER',
kind: 'message',
content: [
{
file: {
file_with_uri: 'https://example.com/file.pdf',
mime_type: 'application/pdf',
},
},
{
text: 'Hello world',
},
{
data: {
data: { foo: 'bar' },
},
},
],
},
},
},
])('should accept $name message parts', async ({ payload }) => {
(mockRequestHandler.sendMessage as Mock).mockResolvedValue(testTask);
await request(app).post('/v1/message:send').send(payload).expect(201);
expect(mockRequestHandler.sendMessage).toHaveBeenCalledWith(
{
message: {
kind: 'message',
messageId: 'msg-parts',
role: 'user', // ROLE_USER is converted to 'user'
parts: [
{
kind: 'file',
file: {
uri: 'https://example.com/file.pdf',
mimeType: 'application/pdf',
name: 'document.pdf',
},
},
],
},
})
.expect(201);
});
it('should accept snake_case mime_type in file parts', async () => {
(mockRequestHandler.sendMessage as SinonStub).resolves(testTask);
await request(app)
.post('/v1/message:send')
.send({
message: {
message_id: 'msg-file',
role: 'user',
kind: 'message',
parts: [
{
kind: 'file',
file: {
uri: 'https://example.com/file.pdf',
mime_type: 'application/pdf',
name: 'document.pdf',
},
kind: 'text',
text: 'Hello world',
},
{
kind: 'data',
data: { foo: 'bar' },
},
],
contextId: undefined,
extensions: [],
metadata: undefined,
taskId: undefined,
},
})
.expect(201);
configuration: undefined,
metadata: undefined,
},
expect.anything()
);
});
});
@ -536,34 +606,46 @@ describe('restHandler', () => {
* Configuration Format Tests
*/
describe('Configuration format acceptance', () => {
it('should accept camelCase configuration fields', async () => {
(mockRequestHandler.sendMessage as SinonStub).resolves(testTask);
it.each([
{
name: 'camelCase',
payload: {
message: { messageId: 'msg-1', role: 'ROLE_USER', kind: 'message' },
configuration: { acceptedOutputModes: ['text/plain'], historyLength: 5 },
},
},
{
name: 'snake_case',
payload: {
message: { message_id: 'msg-1', role: 'ROLE_USER', kind: 'message' },
configuration: { accepted_output_modes: ['text/plain'], history_length: 5 },
},
},
])('should accept $name configuration fields', async ({ payload }) => {
(mockRequestHandler.sendMessage as Mock).mockResolvedValue(testTask);
await request(app).post('/v1/message:send').send(payload).expect(201);
await request(app)
.post('/v1/message:send')
.send({
message: testMessage,
expect(mockRequestHandler.sendMessage).toHaveBeenCalledWith(
{
message: {
kind: 'message',
messageId: 'msg-1',
role: 'user', // ROLE_USER is converted to 'user'
parts: [], // empty content converts to empty parts
contextId: undefined,
extensions: [],
metadata: undefined,
taskId: undefined,
},
configuration: {
acceptedOutputModes: ['text/plain'],
historyLength: 5,
blocking: false,
pushNotificationConfig: undefined,
},
})
.expect(201);
});
it('should accept snake_case configuration fields', async () => {
(mockRequestHandler.sendMessage as SinonStub).resolves(testTask);
await request(app)
.post('/v1/message:send')
.send({
message: snakeCaseMessage,
configuration: {
accepted_output_modes: ['text/plain'],
history_length: 5,
},
})
.expect(201);
metadata: undefined,
},
expect.anything()
);
});
});
@ -579,11 +661,14 @@ describe('restHandler', () => {
});
it('should handle internal server errors gracefully', async () => {
(mockRequestHandler.sendMessage as SinonStub).rejects(new Error('Unexpected internal error'));
(mockRequestHandler.sendMessage as Mock).mockRejectedValue(
new Error('Unexpected internal error')
);
const messageProto = ProtoMessage.toJSON(ToProto.message(testMessage));
const response = await request(app)
.post('/v1/message:send')
.send({ message: snakeCaseMessage })
.send({ message: messageProto })
.expect(500);
assert.property(response.body, 'code');

View File

@ -0,0 +1,259 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { FromProto } from '../../../src/types/converters/from_proto.js';
import * as proto from '../../../src/types/pb/a2a_types.js';
import * as idDecoding from '../../../src/types/converters/id_decoding.js';
import { A2AError } from '../../../src/server/index.js';
vi.mock('../../../src/types/converters/id_decoding.js', () => ({
extractTaskId: vi.fn(),
extractTaskAndPushNotificationConfigId: vi.fn(),
}));
describe('FromProto', () => {
beforeEach(() => {
vi.mocked(idDecoding.extractTaskId).mockReturnValue('task-123');
vi.mocked(idDecoding.extractTaskAndPushNotificationConfigId).mockReturnValue({
taskId: 'task-123',
configId: 'pnc-456',
});
});
it('should convert GetTaskRequest to taskQueryParams', () => {
const request: proto.GetTaskRequest = {
name: 'tasks/task-123',
historyLength: 10,
};
const result = FromProto.taskQueryParams(request);
expect(idDecoding.extractTaskId).toHaveBeenCalledWith('tasks/task-123');
expect(result).toEqual({
id: 'task-123',
historyLength: 10,
});
});
it('should convert CancelTaskRequest to taskIdParams', () => {
const request: proto.CancelTaskRequest = {
name: 'tasks/task-123',
};
const result = FromProto.taskIdParams(request);
expect(idDecoding.extractTaskId).toHaveBeenCalledWith('tasks/task-123');
expect(result).toEqual({
id: 'task-123',
});
});
it('should convert GetTaskPushNotificationConfigRequest to params', () => {
const request: proto.GetTaskPushNotificationConfigRequest = {
name: 'tasks/task-123/pushNotificationConfigs/pnc-456',
};
const result = FromProto.getTaskPushNotificationConfigParams(request);
expect(idDecoding.extractTaskAndPushNotificationConfigId).toHaveBeenCalledWith(request.name);
expect(result).toEqual({
id: 'task-123',
pushNotificationConfigId: 'pnc-456',
});
});
it('should convert ListTaskPushNotificationConfigRequest to params', () => {
const request: proto.ListTaskPushNotificationConfigRequest = {
parent: 'tasks/task-123',
pageToken: '',
pageSize: 0,
};
const result = FromProto.listTaskPushNotificationConfigParams(request);
expect(idDecoding.extractTaskId).toHaveBeenCalledWith(request.parent);
expect(result).toEqual({
id: 'task-123',
});
});
it('should convert CreateTaskPushNotificationConfigRequest to params', () => {
const request: proto.TaskPushNotificationConfig = {
name: 'tasks/task-123/pushNotificationConfigs/pnc-456',
pushNotificationConfig: {
id: 'pnc-456',
url: 'http://example.com',
token: 'token-abc',
authentication: undefined,
},
};
const result = FromProto.taskPushNotificationConfig(request);
expect(idDecoding.extractTaskId).toHaveBeenCalledWith(request.name);
expect(result).toEqual({
taskId: 'task-123',
pushNotificationConfig: {
id: 'pnc-456',
url: 'http://example.com',
token: 'token-abc',
authentication: undefined,
},
});
});
it('should convert DeleteTaskPushNotificationConfigRequest to params', () => {
const request: proto.DeleteTaskPushNotificationConfigRequest = {
name: 'tasks/task-123/pushNotificationConfigs/pnc-456',
};
const result = FromProto.deleteTaskPushNotificationConfigParams(request);
expect(idDecoding.extractTaskAndPushNotificationConfigId).toHaveBeenCalledWith(request.name);
expect(result).toEqual({
id: 'task-123',
pushNotificationConfigId: 'pnc-456',
});
});
it('should convert proto Message to internal Message', () => {
const protoMessage: proto.Message = {
messageId: 'msg-1',
content: [],
contextId: 'ctx-1',
taskId: 'task-1',
role: proto.Role.ROLE_AGENT,
metadata: { key: 'value' },
extensions: ['ext1'],
};
const result = FromProto.message(protoMessage);
expect(result).toEqual({
kind: 'message',
messageId: 'msg-1',
parts: [],
contextId: 'ctx-1',
taskId: 'task-1',
role: 'agent',
metadata: { key: 'value' },
extensions: ['ext1'],
});
});
it('should convert proto SendMessageConfiguration to internal type', () => {
const protoConfig: proto.SendMessageConfiguration = {
blocking: true,
acceptedOutputModes: ['text/plain'],
pushNotification: {
id: 'pnc-1',
url: 'http://notify.me',
token: 'token',
authentication: undefined,
},
historyLength: 0,
};
const result = FromProto.messageSendConfiguration(protoConfig);
expect(result).toEqual({
blocking: true,
acceptedOutputModes: ['text/plain'],
pushNotificationConfig: {
id: 'pnc-1',
url: 'http://notify.me',
token: 'token',
authentication: undefined,
},
});
});
it('should convert proto AuthenticationInfo to internal type', () => {
const authInfo: proto.AuthenticationInfo = {
schemes: ['bearer'],
credentials: 'bearer-token',
};
const result = FromProto.pushNotificationAuthenticationInfo(authInfo);
expect(result).toEqual({
schemes: ['bearer'],
credentials: 'bearer-token',
});
});
describe('parts', () => {
it('should convert a text part', () => {
const part: proto.Part = { part: { $case: 'text', value: 'hello' } };
const result = FromProto.part(part);
expect(result).toEqual({ kind: 'text', text: 'hello' });
});
it('should convert a file part with URI', () => {
const part: proto.Part = {
part: {
$case: 'file',
value: {
file: { $case: 'fileWithUri', value: 'file://path/to/file' },
mimeType: 'text/plain',
},
},
};
const result = FromProto.part(part);
expect(result).toEqual({
kind: 'file',
file: { mimeType: 'text/plain', uri: 'file://path/to/file' },
});
});
it('should convert a file part with bytes', () => {
const bytes = Buffer.from('file content');
const part: proto.Part = {
part: {
$case: 'file',
value: { file: { $case: 'fileWithBytes', value: bytes }, mimeType: 'text/plain' },
},
};
const result = FromProto.part(part);
expect(result).toEqual({
kind: 'file',
file: { bytes: bytes.toString('base64'), mimeType: 'text/plain' },
});
});
it('should throw for invalid file part', () => {
const part: proto.Part = {
part: {
$case: 'file',
value: {
file: { $case: 'wrong format', value: 'invalid bytes' } as any,
mimeType: 'text/plain',
}, // Invalid state
},
};
expect(() => FromProto.part(part)).toThrow(new A2AError(-32602, 'Invalid file part type'));
});
it('should convert a data part', () => {
const data = { foo: 'bar' };
const part: proto.Part = { part: { $case: 'data', value: { data } } };
const result = FromProto.part(part);
expect(result).toEqual({ kind: 'data', data });
});
it('should throw for an unknown part type', () => {
const part: proto.Part = { part: { $case: 'invalid', value: undefined } as any }; // Invalid state
expect(() => FromProto.part(part)).toThrow(new A2AError(-32602, 'Invalid part type'));
});
});
it('should convert SendMessageRequest to messageSendParams', () => {
const request: proto.SendMessageRequest = {
request: {
messageId: 'msg-1',
content: [],
contextId: 'ctx-1',
taskId: 'task-1',
role: proto.Role.ROLE_USER,
metadata: {},
extensions: [],
},
configuration: {
blocking: false,
acceptedOutputModes: [],
pushNotification: undefined,
historyLength: 0,
},
metadata: { client: 'test' },
};
const result = FromProto.messageSendParams(request);
expect(result).toEqual({
message: expect.any(Object),
configuration: expect.any(Object),
metadata: { client: 'test' },
});
expect(result.message.role).toBe('user');
});
});

View File

@ -0,0 +1,218 @@
import { describe, it, beforeEach, afterEach, assert, expect, vi, Mock } from 'vitest';
import * as grpc from '@grpc/grpc-js';
import * as proto from '../../../src/grpc/pb/a2a_services.js';
import { A2AError, A2ARequestHandler } from '../../../src/server/index.js';
import { grpcService } from '../../../src/server/grpc/grpc_service.js';
import { AgentCard, HTTP_EXTENSION_HEADER, MessageSendParams, Task } from '../../../src/index.js';
import { ToProto } from '../../../src/types/converters/to_proto.js';
import { FromProto } from '../../../src/types/converters/from_proto.js';
vi.mock('../../../src/types/converters/from_proto.js');
vi.mock('../../../src/types/converters/to_proto.js');
describe('grpcHandler', () => {
let mockRequestHandler: A2ARequestHandler;
let handler: ReturnType<typeof grpcService>;
const testAgentCard: AgentCard = {
protocolVersion: '0.3.0',
name: 'Test Agent',
description: 'An agent for testing purposes',
url: 'http://localhost:8080',
preferredTransport: 'gRPC',
version: '1.0.0',
capabilities: { streaming: true, pushNotifications: true },
defaultInputModes: ['text/plain'],
defaultOutputModes: ['text/plain'],
skills: [],
};
const testTask: Task = {
id: 'task-1',
kind: 'task' as const,
status: { state: 'completed' as const },
contextId: 'ctx-1',
history: [],
};
// Helper to create a mock gRPC Unary Call
const createMockUnaryCall = (
request: any,
metadataValues: Record<string, string> = {}
): grpc.ServerUnaryCall<any, any> => {
const metadata = new grpc.Metadata();
Object.entries(metadataValues).forEach(([k, v]) => metadata.set(k, v));
return {
request,
metadata,
sendMetadata: vi.fn(),
} as unknown as grpc.ServerUnaryCall<any, any>;
};
// Helper to create a mock gRPC Writable Stream
const createMockWritableStream = (request: any) => {
return {
request,
metadata: new grpc.Metadata(),
sendMetadata: vi.fn(),
write: vi.fn(),
end: vi.fn(),
emit: vi.fn(),
} as unknown as grpc.ServerWritableStream<any, any>;
};
beforeEach(() => {
mockRequestHandler = {
getAgentCard: vi.fn().mockResolvedValue(testAgentCard),
getAuthenticatedExtendedAgentCard: vi.fn().mockResolvedValue(testAgentCard),
sendMessage: vi.fn().mockResolvedValue(testTask),
sendMessageStream: vi.fn(),
getTask: vi.fn(),
cancelTask: vi.fn(),
setTaskPushNotificationConfig: vi.fn(),
getTaskPushNotificationConfig: vi.fn(),
listTaskPushNotificationConfigs: vi.fn(),
deleteTaskPushNotificationConfig: vi.fn(),
resubscribe: vi.fn(),
};
handler = grpcService({
requestHandler: mockRequestHandler,
userBuilder: async () => ({ id: 'test-user' }) as any,
});
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('getAgentCard', () => {
it('should return agent card via gRPC callback', async () => {
const call = createMockUnaryCall({});
const callback = vi.fn();
const mockProtoAgentCard = { name: 'Proto Test Agent' } as proto.AgentCard;
(ToProto.agentCard as Mock).mockReturnValue(mockProtoAgentCard);
await handler.getAgentCard(call, callback);
expect(mockRequestHandler.getAuthenticatedExtendedAgentCard).toHaveBeenCalled();
expect(ToProto.agentCard).toHaveBeenCalledWith(testAgentCard);
const [err, response] = callback.mock.calls[0];
assert.isNull(err);
assert.deepEqual(response, mockProtoAgentCard);
expect(call.sendMetadata).toHaveBeenCalled();
});
it('should return gRPC error code on failure', async () => {
(mockRequestHandler.getAuthenticatedExtendedAgentCard as Mock).mockRejectedValue(
new A2AError(-32001, 'Not Found')
);
const call = createMockUnaryCall({});
const callback = vi.fn();
await handler.getAgentCard(call, callback);
const [err] = callback.mock.calls[0];
assert.equal(err.code, grpc.status.NOT_FOUND);
assert.equal(err.details, 'Not Found');
});
});
describe('sendMessage', () => {
it('should successfully send a message and return a task', async () => {
const call = createMockUnaryCall({ message: { role: 'user', parts: [] } });
const callback = vi.fn();
const messageSendParams = { message: { role: 'user' } } as MessageSendParams;
(FromProto.messageSendParams as Mock).mockReturnValue(messageSendParams);
const sendMessageResponse = {
payload: { $case: 'task', value: { id: 'task-1' } } as proto.SendMessageResponse,
};
(ToProto.messageSendResult as Mock).mockReturnValue(sendMessageResponse);
await handler.sendMessage(call, callback);
const [err, response] = callback.mock.calls[0];
assert.isNull(err);
assert.equal(response.payload.$case, 'task');
assert.equal(response.payload.value.id, testTask.id);
});
});
describe('sendStreamingMessage', () => {
it('should stream multiple parts and end correctly', async () => {
async function* mockStream() {
yield { kind: 'message', messageId: 'm1' };
yield { kind: 'task', id: 't1' };
}
(mockRequestHandler.sendMessageStream as Mock).mockResolvedValue(mockStream());
const call = createMockWritableStream({ message: { role: 'user', parts: [] } });
await handler.sendStreamingMessage(call);
expect(call.write).toHaveBeenCalledTimes(2);
expect(call.end).toHaveBeenCalled();
expect(call.sendMetadata).toHaveBeenCalled();
});
it('should emit error on stream failure', async () => {
(mockRequestHandler.sendMessageStream as Mock).mockRejectedValue(new Error('Stream crash'));
const call = createMockWritableStream({});
await handler.sendStreamingMessage(call);
expect(call.emit).toHaveBeenCalledWith(
'error',
expect.objectContaining({
code: grpc.status.INTERNAL,
})
);
expect(call.end).toHaveBeenCalled();
});
});
describe('Extensions (Metadata) Handling', () => {
it('should extract extensions from metadata and pass to context', async () => {
// Mocking the header 'x-a2a-extension'
const call = createMockUnaryCall(
{ id: 'task-1' },
{
[HTTP_EXTENSION_HEADER.toLowerCase()]: 'extension-v1',
}
);
const callback = vi.fn();
(FromProto.taskQueryParams as Mock).mockReturnValue({ id: 'task-1' });
(ToProto.task as Mock).mockReturnValue({ id: 'task-1', contextId: 'ctx-1' });
await handler.getTask(call, callback);
const contextArg = (mockRequestHandler.getTask as Mock).mock.calls[0][1];
expect(contextArg).toBeDefined();
expect(contextArg.requestedExtensions).toEqual(['extension-v1']);
});
it('should return activated extensions in context through metadata', async () => {
// Mocking the header 'x-a2a-extension'
const call = createMockUnaryCall(
{ id: 'task-1' },
{
[HTTP_EXTENSION_HEADER.toLowerCase()]: 'extension-v1',
}
);
const callback = vi.fn();
(mockRequestHandler.getTask as Mock).mockImplementation(async (_params, context) => {
context.addActivatedExtension('extension-v1');
return testTask;
});
(FromProto.taskQueryParams as Mock).mockReturnValue({ id: 'task-1' });
(ToProto.task as Mock).mockReturnValue({ id: 'task-1', contextId: 'ctx-1' });
await handler.getTask(call, callback);
const [metadata] = (call.sendMetadata as Mock).mock.calls[0];
expect(metadata).toBeDefined();
expect(metadata.get(HTTP_EXTENSION_HEADER.toLowerCase())).toEqual(['extension-v1']);
});
});
});

View File

@ -0,0 +1,390 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ToProto } from '../../../src/types/converters/to_proto.js';
import * as types from '../../../src/types.js';
import * as proto from '../../../src/types/pb/a2a_types.js';
import * as idDecoding from '../../../src/types/converters/id_decoding.js';
import { A2AError } from '../../../src/server/index.js';
vi.mock('../../../src/types/converters/id_decoding.js', () => ({
generatePushNotificationConfigName: vi.fn(),
}));
describe('ToProto', () => {
beforeEach(() => {
vi.mocked(idDecoding.generatePushNotificationConfigName).mockReturnValue(
'tasks/task-123/pushNotificationConfigs/pnc-456'
);
});
it('should convert internal Task to proto Task', () => {
const internalTask: types.Task = {
id: 'task-123',
kind: 'task',
contextId: 'ctx-1',
status: {
state: 'completed',
timestamp: '2023-01-01T00:00:00.000Z',
},
artifacts: [],
history: [],
metadata: { key: 'value' },
};
const result = ToProto.task(internalTask);
expect(result).toEqual({
id: 'task-123',
contextId: 'ctx-1',
status: {
state: proto.TaskState.TASK_STATE_COMPLETED,
timestamp: '2023-01-01T00:00:00.000Z',
update: undefined,
},
artifacts: [],
history: [],
metadata: { key: 'value' },
});
});
it('should convert internal Message to proto Message', () => {
const internalMessage: types.Message = {
kind: 'message',
messageId: 'msg-1',
parts: [{ kind: 'text', text: 'hello' }],
contextId: 'ctx-1',
taskId: 'task-1',
role: 'user',
metadata: { key: 'value' },
extensions: ['ext1'],
};
const result = ToProto.message(internalMessage);
expect(result).toEqual({
messageId: 'msg-1',
content: [{ part: { $case: 'text', value: 'hello' } }],
contextId: 'ctx-1',
taskId: 'task-1',
role: proto.Role.ROLE_USER,
metadata: { key: 'value' },
extensions: ['ext1'],
});
});
describe('taskState', () => {
it.each([
['submitted', proto.TaskState.TASK_STATE_SUBMITTED],
['working', proto.TaskState.TASK_STATE_WORKING],
['input-required', proto.TaskState.TASK_STATE_INPUT_REQUIRED],
['rejected', proto.TaskState.TASK_STATE_REJECTED],
['auth-required', proto.TaskState.TASK_STATE_AUTH_REQUIRED],
['completed', proto.TaskState.TASK_STATE_COMPLETED],
['failed', proto.TaskState.TASK_STATE_FAILED],
['canceled', proto.TaskState.TASK_STATE_CANCELLED],
['unknown', proto.TaskState.TASK_STATE_UNSPECIFIED],
['invalid-state' as types.TaskState, proto.TaskState.UNRECOGNIZED],
])('should convert internal state "%s" to proto state %s', (internalState, expectedState) => {
const result = ToProto.taskState(internalState as types.TaskState);
expect(result).toBe(expectedState);
});
});
describe('parts', () => {
it('should convert a text part', () => {
const part: types.Part = { kind: 'text', text: 'hello' };
const result = ToProto.part(part);
expect(result).toEqual({
part: { $case: 'text', value: 'hello' },
});
});
it('should convert a file part with URI', () => {
const part: types.Part = {
kind: 'file',
file: { uri: 'file://path', mimeType: 'text/plain' },
};
const result = ToProto.part(part);
expect(result).toEqual({
part: {
$case: 'file',
value: {
file: { $case: 'fileWithUri', value: 'file://path' },
mimeType: 'text/plain',
},
},
});
});
it('should convert a file part with bytes', () => {
const base64Bytes = Buffer.from('file content').toString('base64');
const part: types.Part = {
kind: 'file',
file: { bytes: base64Bytes, mimeType: 'application/octet-stream' },
};
const result = ToProto.part(part);
expect(result).toEqual({
part: {
$case: 'file',
value: {
file: { $case: 'fileWithBytes', value: Buffer.from('file content') },
mimeType: 'application/octet-stream',
},
},
});
});
it('should throw for an invalid file part', () => {
const part: types.Part = {
kind: 'file',
file: {} as any,
};
expect(() => ToProto.part(part)).toThrow(new A2AError(-32603, 'Invalid file part'));
});
it('should convert a data part', () => {
const data = { foo: 'bar' };
const part: types.Part = { kind: 'data', data };
const result = ToProto.part(part);
expect(result).toEqual({
part: { $case: 'data', value: { data } },
});
});
it('should throw for an unknown part type', () => {
const part: types.Part = { kind: 'unknown' } as any;
expect(() => ToProto.part(part)).toThrow(new A2AError(-32603, 'Invalid part type'));
});
});
it('should convert internal Artifact to proto Artifact', () => {
const internalArtifact: types.Artifact = {
artifactId: 'art-1',
name: 'My Artifact',
description: 'A test artifact',
parts: [{ kind: 'text', text: 'artifact content' }],
metadata: { key: 'value' },
extensions: ['ext1'],
};
const result = ToProto.artifact(internalArtifact);
expect(result).toEqual({
artifactId: 'art-1',
name: 'My Artifact',
description: 'A test artifact',
parts: [{ part: { $case: 'text', value: 'artifact content' } }],
metadata: { key: 'value' },
extensions: ['ext1'],
});
});
describe('messageSendResult', () => {
it('should convert a message result', () => {
const message: types.Message = {
kind: 'message',
messageId: 'msg-1',
parts: [],
role: 'agent',
};
const result = ToProto.messageSendResult(message);
expect(result.payload?.$case).toBe('msg');
expect((result.payload as any).value.messageId).toBe('msg-1');
});
it('should convert a task result', () => {
const task: types.Task = {
kind: 'task',
id: 'task-123',
contextId: 'ctx-1',
status: { state: 'submitted' },
history: [],
artifacts: [],
};
const result = ToProto.messageSendResult(task);
expect(result.payload?.$case).toBe('task');
expect((result.payload as any).value.id).toBe('task-123');
});
it('should return undefined for invalid kind', () => {
const invalid = { kind: 'invalid' } as any;
const result = ToProto.messageSendResult(invalid);
expect(result).toBeUndefined();
});
});
describe('messageStreamResult', () => {
it('should convert a message event', () => {
const event: types.Message = {
kind: 'message',
messageId: 'msg-1',
parts: [],
role: 'agent',
};
const result = ToProto.messageStreamResult(event);
expect(result.payload?.$case).toBe('msg');
});
it('should convert a task event', () => {
const event: types.Task = {
kind: 'task',
id: 'task-123',
contextId: 'ctx-1',
status: { state: 'submitted' },
history: [],
artifacts: [],
};
const result = ToProto.messageStreamResult(event);
expect(result.payload?.$case).toBe('task');
});
it('should convert a status-update event', () => {
const event: types.TaskStatusUpdateEvent = {
kind: 'status-update',
taskId: 'task-123',
status: { state: 'working' },
contextId: 'ctx-1',
metadata: {},
final: false,
};
const result = ToProto.messageStreamResult(event);
expect(result.payload?.$case).toBe('statusUpdate');
});
it('should convert an artifact-update event', () => {
const event: types.TaskArtifactUpdateEvent = {
kind: 'artifact-update',
taskId: 'task-123',
artifact: { artifactId: 'art-1', parts: [] },
contextId: 'ctx-1',
metadata: {},
};
const result = ToProto.messageStreamResult(event);
expect(result.payload?.$case).toBe('artifactUpdate');
});
it('should throw for an invalid event type', () => {
const event = { kind: 'invalid' } as any;
expect(() => ToProto.messageStreamResult(event)).toThrow(
new A2AError(-32603, 'Invalid event type')
);
});
});
it('should convert PushNotificationAuthenticationInfo', () => {
const authInfo: types.PushNotificationAuthenticationInfo = {
schemes: ['bearer'],
credentials: 'my-token',
};
const result = ToProto.pushNotificationAuthenticationInfo(authInfo);
expect(result).toEqual({
schemes: ['bearer'],
credentials: 'my-token',
});
});
it('should convert PushNotificationConfig', () => {
const config: types.PushNotificationConfig = {
id: 'pnc-456',
url: 'https://example.com/notify',
token: 'push-token',
authentication: {
schemes: ['bearer'],
credentials: 'my-token',
},
};
const result = ToProto.pushNotificationConfig(config);
expect(result).toEqual({
id: 'pnc-456',
url: 'https://example.com/notify',
token: 'push-token',
authentication: {
schemes: ['bearer'],
credentials: 'my-token',
},
});
});
it('should convert TaskPushNotificationConfig', () => {
const config: types.TaskPushNotificationConfig = {
taskId: 'task-123',
pushNotificationConfig: {
id: 'pnc-456',
url: 'https://example.com/notify',
},
};
const result = ToProto.taskPushNotificationConfig(config);
expect(idDecoding.generatePushNotificationConfigName).toHaveBeenCalledWith(
'task-123',
'pnc-456'
);
expect(result).toEqual({
name: 'tasks/task-123/pushNotificationConfigs/pnc-456',
pushNotificationConfig: {
id: 'pnc-456',
url: 'https://example.com/notify',
token: '',
authentication: undefined,
},
});
});
it('should convert a list of TaskPushNotificationConfigs', () => {
const configs: types.TaskPushNotificationConfig[] = [
{
taskId: 'task-123',
pushNotificationConfig: { id: 'pnc-456', url: 'https://example.com/notify' },
},
];
const result = ToProto.listTaskPushNotificationConfig(configs);
expect(result.configs.length).toBe(1);
expect(result.nextPageToken).toBe('');
expect(result.configs[0].name).toBe('tasks/task-123/pushNotificationConfigs/pnc-456');
});
describe('securityScheme', () => {
it('should convert apiKey scheme', () => {
const scheme: types.SecurityScheme = {
type: 'apiKey',
name: 'X-API-KEY',
in: 'header',
description: 'API Key auth',
};
const result = ToProto.securityScheme(scheme);
expect(result.scheme?.$case).toBe('apiKeySecurityScheme');
});
it('should convert http scheme', () => {
const scheme: types.SecurityScheme = {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
};
const result = ToProto.securityScheme(scheme);
expect(result.scheme?.$case).toBe('httpAuthSecurityScheme');
});
it('should throw on unsupported security scheme', () => {
const scheme: types.SecurityScheme = { type: 'unsupported' } as any;
expect(() => ToProto.securityScheme(scheme)).toThrow(
A2AError.internalError('Unsupported security scheme type')
);
});
});
describe('oauthFlows', () => {
it('should convert implicit flow', () => {
const flows: types.OAuthFlows = {
implicit: { authorizationUrl: 'url', scopes: { s1: '' } },
};
const result = ToProto.oauthFlows(flows);
expect(result.flow?.$case).toBe('implicit');
});
it('should throw on unsupported flow', () => {
const flows: types.OAuthFlows = {};
expect(() => ToProto.oauthFlows(flows)).toThrow(
A2AError.internalError('Unsupported OAuth flows')
);
});
});
});

View File

@ -1,5 +1,4 @@
import { describe, it, beforeEach, afterEach, expect } from 'vitest';
import sinon from 'sinon';
import { describe, it, beforeEach, afterEach, expect, vi, type Mock } from 'vitest';
import { JsonRpcTransportHandler } from '../../src/server/transports/jsonrpc/jsonrpc_transport_handler.js';
import { A2ARequestHandler } from '../../src/server/request_handler/a2a_request_handler.js';
@ -11,23 +10,23 @@ describe('JsonRpcTransportHandler', () => {
beforeEach(() => {
mockRequestHandler = {
getAgentCard: sinon.stub(),
getAuthenticatedExtendedAgentCard: sinon.stub(),
sendMessage: sinon.stub(),
sendMessageStream: sinon.stub(),
getTask: sinon.stub(),
cancelTask: sinon.stub(),
setTaskPushNotificationConfig: sinon.stub(),
getTaskPushNotificationConfig: sinon.stub(),
listTaskPushNotificationConfigs: sinon.stub(),
deleteTaskPushNotificationConfig: sinon.stub(),
resubscribe: sinon.stub(),
getAgentCard: vi.fn(),
getAuthenticatedExtendedAgentCard: vi.fn(),
sendMessage: vi.fn(),
sendMessageStream: vi.fn(),
getTask: vi.fn(),
cancelTask: vi.fn(),
setTaskPushNotificationConfig: vi.fn(),
getTaskPushNotificationConfig: vi.fn(),
listTaskPushNotificationConfigs: vi.fn(),
deleteTaskPushNotificationConfig: vi.fn(),
resubscribe: vi.fn(),
};
transportHandler = new JsonRpcTransportHandler(mockRequestHandler);
});
afterEach(() => {
sinon.restore();
vi.restoreAllMocks();
});
describe('Check JSON-RPC request format', () => {
@ -120,7 +119,7 @@ describe('JsonRpcTransportHandler', () => {
id: null,
params: {},
};
(mockRequestHandler.getAuthenticatedExtendedAgentCard as sinon.SinonStub).resolves({
(mockRequestHandler.getAuthenticatedExtendedAgentCard as Mock).mockResolvedValue({
card: 'data',
});
const response = await transportHandler.handle(request);

View File

@ -1,4 +1,4 @@
import sinon, { SinonStub, SinonFakeTimers } from 'sinon';
import { vi, type Mock, type MockInstance } from 'vitest';
import { AgentExecutor } from '../../../src/server/agent_execution/agent_executor.js';
import { RequestContext, ExecutionEventBus } from '../../../src/server/index.js';
@ -7,9 +7,11 @@ import { RequestContext, ExecutionEventBus } from '../../../src/server/index.js'
*/
export class MockAgentExecutor implements AgentExecutor {
// Stubs to control and inspect calls to execute and cancelTask
public execute: SinonStub<[RequestContext, ExecutionEventBus], Promise<void>> = sinon.stub();
public execute: Mock<
(requestContext: RequestContext, eventBus: ExecutionEventBus) => Promise<void>
> = vi.fn();
public cancelTask: SinonStub<[string, ExecutionEventBus], Promise<void>> = sinon.stub();
public cancelTask: Mock<(taskId: string, eventBus: ExecutionEventBus) => Promise<void>> = vi.fn();
}
/**
@ -53,16 +55,13 @@ export const fakeTaskExecute = async (ctx: RequestContext, bus: ExecutionEventBu
*/
export class CancellableMockAgentExecutor implements AgentExecutor {
private cancelledTasks = new Set<string>();
private clock: SinonFakeTimers;
public cancelTaskSpy: MockInstance;
constructor(clock: SinonFakeTimers) {
this.clock = clock;
constructor() {
this.cancelTaskSpy = vi.spyOn(this as CancellableMockAgentExecutor, 'cancelTask');
}
public execute = async (
requestContext: RequestContext,
eventBus: ExecutionEventBus
): Promise<void> => {
public async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
const taskId = requestContext.taskId;
const contextId = requestContext.contextId;
@ -94,7 +93,7 @@ export class CancellableMockAgentExecutor implements AgentExecutor {
return;
}
// Use fake timers to simulate work
await this.clock.tickAsync(100);
await vi.advanceTimersByTimeAsync(100);
}
eventBus.publish({
@ -105,15 +104,12 @@ export class CancellableMockAgentExecutor implements AgentExecutor {
final: true,
});
eventBus.finished();
};
}
public cancelTask = async (taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {
public async cancelTask(taskId: string, _eventBus: ExecutionEventBus): Promise<void> {
this.cancelledTasks.add(taskId);
// The execute loop is responsible for publishing the final state
};
// Stub for spying on cancelTask calls
public cancelTaskSpy = sinon.spy(this, 'cancelTask');
}
}
/**
@ -121,16 +117,13 @@ export class CancellableMockAgentExecutor implements AgentExecutor {
*/
export class FailingCancellableMockAgentExecutor implements AgentExecutor {
private cancelledTasks = new Set<string>();
private clock: SinonFakeTimers;
public cancelTaskSpy: MockInstance;
constructor(clock: SinonFakeTimers) {
this.clock = clock;
constructor() {
this.cancelTaskSpy = vi.spyOn(this as FailingCancellableMockAgentExecutor, 'cancelTask');
}
public execute = async (
requestContext: RequestContext,
eventBus: ExecutionEventBus
): Promise<void> => {
public async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
const taskId = requestContext.taskId;
const contextId = requestContext.contextId;
@ -162,7 +155,7 @@ export class FailingCancellableMockAgentExecutor implements AgentExecutor {
return;
}
// Use fake timers to simulate work
await this.clock.tickAsync(100);
await vi.advanceTimersByTimeAsync(100);
}
eventBus.publish({
@ -173,12 +166,9 @@ export class FailingCancellableMockAgentExecutor implements AgentExecutor {
final: true,
});
eventBus.finished();
};
}
public cancelTask = async (_taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {
public async cancelTask(_taskId: string, _eventBus: ExecutionEventBus): Promise<void> {
// No operation: simulates the failure of task cancellation
};
// Stub for spying on cancelTask calls
public cancelTaskSpy = sinon.spy(this, 'cancelTask');
}
}

View File

@ -1,7 +1,7 @@
import sinon, { SinonStub } from 'sinon';
import { vi, type Mock } from 'vitest';
import { Task } from '../../../src/index.js';
import { PushNotificationSender } from '../../../src/server/push_notification/push_notification_sender.js';
export class MockPushNotificationSender implements PushNotificationSender {
public send: SinonStub<[Task], Promise<void>> = sinon.stub();
public send: Mock<(task: Task) => Promise<void>> = vi.fn();
}

View File

@ -1,8 +1,9 @@
import sinon, { SinonStub } from 'sinon';
import { vi, type Mock } from 'vitest';
import { Task } from '../../../src/index.js';
import { TaskStore } from '../../../src/server/store.js';
import { ServerCallContext } from '../../../src/server/context.js';
export class MockTaskStore implements TaskStore {
public save: SinonStub<[Task], Promise<void>> = sinon.stub();
public load: SinonStub<[string], Promise<Task | undefined>> = sinon.stub();
public save: Mock<(task: Task, ctx?: ServerCallContext) => Promise<void>> = vi.fn();
public load: Mock<(id: string, ctx?: ServerCallContext) => Promise<Task | undefined>> = vi.fn();
}

View File

@ -1,5 +1,4 @@
import { describe, it, beforeEach, afterEach, assert } from 'vitest';
import sinon from 'sinon';
import { describe, it, beforeEach, afterEach, assert, vi, type MockInstance } from 'vitest';
import express, { Request, Response } from 'express';
import { Server } from 'http';
import { AddressInfo } from 'net';
@ -18,6 +17,8 @@ import {
} from '../../src/index.js';
import { fakeTaskExecute, MockAgentExecutor } from './mocks/agent-executor.mock.js';
type PushNotificationSenderSpy = MockInstance<(task: Task) => Promise<void>>;
describe('Push Notification Integration Tests', () => {
let testServer: Server;
let testServerUrl: string;
@ -33,6 +34,7 @@ describe('Push Notification Integration Tests', () => {
let mockAgentExecutor: MockAgentExecutor;
let pushNotificationStore: InMemoryPushNotificationStore;
let pushNotificationSender: DefaultPushNotificationSender;
let pushNotificationSenderSpy: PushNotificationSenderSpy;
const testAgentCard: AgentCard = {
name: 'Test Agent',
@ -117,6 +119,7 @@ describe('Push Notification Integration Tests', () => {
const executionEventBusManager = new DefaultExecutionEventBusManager();
pushNotificationStore = new InMemoryPushNotificationStore();
pushNotificationSender = new DefaultPushNotificationSender(pushNotificationStore);
pushNotificationSenderSpy = vi.spyOn(pushNotificationSender, 'send');
handler = new DefaultRequestHandler(
testAgentCard,
@ -130,15 +133,10 @@ describe('Push Notification Integration Tests', () => {
afterEach(async () => {
// Clean up test server
// if (testServer) {
// await new Promise<void>((resolve, reject) => {
// testServer.close((err) => {
// if (err) reject(err);
// else resolve();
// });
// });
// }
sinon.restore();
if (testServer) {
await testServer.close();
}
vi.restoreAllMocks();
});
const createTestMessage = (text: string, taskId?: string): Message => ({
@ -149,6 +147,10 @@ describe('Push Notification Integration Tests', () => {
...(taskId && { taskId }),
});
const waitForPushNotifications = async (spy: PushNotificationSenderSpy) => {
await Promise.all(spy.mock.results.map((r) => r.value));
};
describe('End-to-End Push Notification Flow', () => {
it('should send push notifications for task status updates', async () => {
const pushConfig: PushNotificationConfig = {
@ -170,7 +172,7 @@ describe('Push Notification Integration Tests', () => {
let taskId: string;
// Mock the agent executor to publish all three states for this test only
mockAgentExecutor.execute.callsFake(async (ctx, bus) => {
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
taskId = ctx.taskId;
fakeTaskExecute(ctx, bus);
});
@ -179,7 +181,7 @@ describe('Push Notification Integration Tests', () => {
await handler.sendMessage(params);
// Wait for async push notifications to be sent
await new Promise((resolve) => setTimeout(resolve, 200));
await waitForPushNotifications(pushNotificationSenderSpy);
// Load the task from the store
const expectedTaskResult: Task = {
@ -269,7 +271,7 @@ describe('Push Notification Integration Tests', () => {
});
// Mock the agent executor to publish only completed state
mockAgentExecutor.execute.callsFake(async (ctx, bus) => {
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
const taskId = ctx.taskId;
const contextId = ctx.contextId;
@ -297,7 +299,7 @@ describe('Push Notification Integration Tests', () => {
await handler.sendMessage(params);
// Wait for async push notifications to be sent
await new Promise((resolve) => setTimeout(resolve, 300));
await waitForPushNotifications(pushNotificationSenderSpy);
// Should now have notifications from both endpoints
const notificationsByEndpoint = receivedNotifications.reduce(
@ -343,7 +345,7 @@ describe('Push Notification Integration Tests', () => {
let taskId: string;
// Mock the agent executor to publish task states
mockAgentExecutor.execute.callsFake(async (ctx, bus) => {
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
taskId = ctx.taskId;
fakeTaskExecute(ctx, bus);
});
@ -353,7 +355,7 @@ describe('Push Notification Integration Tests', () => {
const task = result as Task;
// Wait for async push notifications to be sent
await new Promise((resolve) => setTimeout(resolve, 200));
await waitForPushNotifications(pushNotificationSenderSpy);
// Load the task from the store
const expectedTaskResult: Task = {
@ -393,7 +395,7 @@ describe('Push Notification Integration Tests', () => {
};
// Mock the agent executor to publish completion
mockAgentExecutor.execute.callsFake(async (ctx, bus) => {
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
const taskId = ctx.taskId;
const contextId = ctx.contextId;
@ -418,7 +420,7 @@ describe('Push Notification Integration Tests', () => {
await handler.sendMessage(params);
// Wait for async push notifications to be sent
await new Promise((resolve) => setTimeout(resolve, 200));
await waitForPushNotifications(pushNotificationSenderSpy);
// Verify default header name is used
assert.lengthOf(
@ -449,6 +451,7 @@ describe('Push Notification Integration Tests', () => {
tokenHeaderName: 'X-Custom-Auth-Token',
}
);
const customSenderSpy = vi.spyOn(customPushNotificationSender, 'send');
const customHandler = new DefaultRequestHandler(
testAgentCard,
@ -473,7 +476,7 @@ describe('Push Notification Integration Tests', () => {
};
// Mock the agent executor to publish completion
mockAgentExecutor.execute.callsFake(async (ctx, bus) => {
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
const taskId = ctx.taskId;
const contextId = ctx.contextId;
@ -498,7 +501,7 @@ describe('Push Notification Integration Tests', () => {
await customHandler.sendMessage(params);
// Wait for async push notifications to be sent
await new Promise((resolve) => setTimeout(resolve, 200));
await waitForPushNotifications(customSenderSpy);
// Verify custom header name is used
assert.lengthOf(
@ -540,7 +543,7 @@ describe('Push Notification Integration Tests', () => {
};
// Mock the agent executor to publish completion
mockAgentExecutor.execute.callsFake(async (ctx, bus) => {
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
const taskId = ctx.taskId;
const contextId = ctx.contextId;
@ -565,7 +568,7 @@ describe('Push Notification Integration Tests', () => {
await handler.sendMessage(params);
// Wait for async push notifications to be sent
await new Promise((resolve) => setTimeout(resolve, 200));
await waitForPushNotifications(pushNotificationSenderSpy);
// Verify no token header is sent
assert.lengthOf(
@ -595,6 +598,7 @@ describe('Push Notification Integration Tests', () => {
tokenHeaderName: 'X-Custom-Token',
}
);
const customSenderSpy = vi.spyOn(customPushNotificationSender, 'send');
const customHandler = new DefaultRequestHandler(
testAgentCard,
@ -645,7 +649,7 @@ describe('Push Notification Integration Tests', () => {
});
// Mock the agent executor to publish completion
mockAgentExecutor.execute.callsFake(async (ctx, bus) => {
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
const taskId = ctx.taskId;
const contextId = ctx.contextId;
@ -663,7 +667,7 @@ describe('Push Notification Integration Tests', () => {
await customHandler.sendMessage(params);
// Wait for async push notifications to be sent
await new Promise((resolve) => setTimeout(resolve, 300));
await waitForPushNotifications(customSenderSpy);
// Verify both endpoints received notifications with correct headers
const config1Notifications = receivedNotifications.filter((n) => n.url === '/notify');

View File

@ -0,0 +1,453 @@
import { describe, it, beforeEach, afterEach, expect, vi, type Mock } from 'vitest';
import {
RestTransportHandler,
mapErrorToStatus,
toHTTPError,
HTTP_STATUS,
} from '../../src/server/transports/rest/rest_transport_handler.js';
import { A2ARequestHandler } from '../../src/server/request_handler/a2a_request_handler.js';
import { A2AError } from '../../src/server/error.js';
import { A2A_ERROR_CODE } from '../../src/errors.js';
import { AgentCard, Task, Message } from '../../src/types.js';
import { ServerCallContext } from '../../src/server/context.js';
describe('RestTransportHandler', () => {
let mockRequestHandler: A2ARequestHandler;
let transportHandler: RestTransportHandler;
let mockContext: ServerCallContext;
const testAgentCard: AgentCard = {
protocolVersion: '0.3.0',
name: 'Test Agent',
description: 'An agent for testing purposes',
url: 'http://localhost:8080',
preferredTransport: 'HTTP+JSON',
version: '1.0.0',
capabilities: {
streaming: true,
pushNotifications: true,
},
defaultInputModes: ['text/plain'],
defaultOutputModes: ['text/plain'],
skills: [],
};
const testMessage: Message = {
messageId: 'msg-1',
role: 'user' as const,
parts: [{ kind: 'text' as const, text: 'Hello' }],
kind: 'message' as const,
};
const testTask: Task = {
id: 'task-1',
kind: 'task' as const,
status: { state: 'completed' as const },
contextId: 'ctx-1',
history: [],
};
beforeEach(() => {
mockRequestHandler = {
getAgentCard: vi.fn().mockResolvedValue(testAgentCard),
getAuthenticatedExtendedAgentCard: vi.fn().mockResolvedValue(testAgentCard),
sendMessage: vi.fn().mockResolvedValue(testTask),
sendMessageStream: vi.fn(),
getTask: vi.fn().mockResolvedValue(testTask),
cancelTask: vi.fn().mockResolvedValue(testTask),
setTaskPushNotificationConfig: vi.fn(),
getTaskPushNotificationConfig: vi.fn(),
listTaskPushNotificationConfigs: vi.fn(),
deleteTaskPushNotificationConfig: vi.fn(),
resubscribe: vi.fn(),
};
transportHandler = new RestTransportHandler(mockRequestHandler);
mockContext = new ServerCallContext();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('mapErrorToStatus', () => {
it.each([
[A2A_ERROR_CODE.PARSE_ERROR, HTTP_STATUS.BAD_REQUEST],
[A2A_ERROR_CODE.INVALID_REQUEST, HTTP_STATUS.BAD_REQUEST],
[A2A_ERROR_CODE.INVALID_PARAMS, HTTP_STATUS.BAD_REQUEST],
[A2A_ERROR_CODE.METHOD_NOT_FOUND, HTTP_STATUS.NOT_FOUND],
[A2A_ERROR_CODE.TASK_NOT_FOUND, HTTP_STATUS.NOT_FOUND],
[A2A_ERROR_CODE.TASK_NOT_CANCELABLE, HTTP_STATUS.CONFLICT],
[A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED, HTTP_STATUS.BAD_REQUEST],
[A2A_ERROR_CODE.UNSUPPORTED_OPERATION, HTTP_STATUS.BAD_REQUEST],
[-99999, HTTP_STATUS.INTERNAL_SERVER_ERROR],
])('should map error code %s to HTTP status %s', (errorCode, httpStatus) => {
expect(mapErrorToStatus(errorCode)).to.equal(httpStatus);
});
});
describe('toHTTPError', () => {
it('should convert A2AError to HTTP error format', () => {
const error = A2AError.invalidParams('Invalid input');
const httpError = toHTTPError(error);
expect(httpError.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
expect(httpError.message).to.equal('Invalid input');
expect(httpError.data).to.be.undefined;
});
it('should include data if present in A2AError', () => {
const error = A2AError.invalidParams('Invalid input');
error.data = { field: 'email' };
const httpError = toHTTPError(error);
expect(httpError.data).to.deep.equal({ field: 'email' });
});
});
describe('getAgentCard', () => {
it('should return agent card from request handler', async () => {
const card = await transportHandler.getAgentCard();
expect(card).to.deep.equal(testAgentCard);
expect(mockRequestHandler.getAgentCard as Mock).toHaveBeenCalledTimes(1);
});
});
describe('getAuthenticatedExtendedAgentCard', () => {
it('should return extended agent card from request handler', async () => {
const card = await transportHandler.getAuthenticatedExtendedAgentCard(mockContext);
expect(card).to.deep.equal(testAgentCard);
expect(mockRequestHandler.getAuthenticatedExtendedAgentCard as Mock).toHaveBeenCalledTimes(1);
});
});
describe('sendMessage', () => {
it.each([
{
name: 'camelCase',
input: {
message: {
messageId: 'msg-1',
role: 'user' as const,
parts: [{ kind: 'text' as const, text: 'Hello' }],
kind: 'message' as const,
},
},
expectedMessageId: 'msg-1',
},
])(
'should normalize $name message and call request handler',
async ({ input, expectedMessageId }) => {
const result = await transportHandler.sendMessage(input as any, mockContext);
expect(result).to.deep.equal(testTask);
expect(mockRequestHandler.sendMessage as Mock).toHaveBeenCalledWith(
expect.objectContaining({
message: expect.objectContaining({ messageId: expectedMessageId }),
}),
mockContext
);
}
);
it('should throw InvalidParams if message is missing', async () => {
await expect(transportHandler.sendMessage({} as any, mockContext)).rejects.toThrow(
'message is required'
);
});
it('should throw InvalidParams if message.messageId is missing', async () => {
const invalidMessage = {
message: {
role: 'user' as const,
parts: [{ kind: 'text' as const, text: 'Hello' }],
kind: 'message' as const,
},
};
await expect(
transportHandler.sendMessage(invalidMessage as any, mockContext)
).rejects.toThrow('message.messageId is required');
});
it('should normalize configuration with snake_case fields', async () => {
const inputWithConfig = {
message: testMessage,
configuration: {
blocking: true,
acceptedOutputModes: ['text/plain'],
historyLength: 5,
pushNotificationConfig: {
id: 'push-1',
url: 'https://example.com',
},
},
};
await transportHandler.sendMessage(inputWithConfig as any, mockContext);
expect(mockRequestHandler.sendMessage as Mock).toHaveBeenCalledWith(
expect.objectContaining({
configuration: expect.objectContaining({
blocking: true,
acceptedOutputModes: ['text/plain'],
historyLength: 5,
pushNotificationConfig: {
id: 'push-1',
url: 'https://example.com',
},
}),
}),
mockContext
);
});
});
describe('sendMessageStream', () => {
it('should throw UnsupportedOperation if streaming not supported', async () => {
(mockRequestHandler.getAgentCard as Mock).mockResolvedValue({
...testAgentCard,
capabilities: { streaming: false },
});
await expect(
transportHandler.sendMessageStream({ message: testMessage }, mockContext)
).rejects.toThrow('Agent does not support streaming');
});
it('should call request handler sendMessageStream if streaming supported', async () => {
async function* mockStream() {
yield testMessage;
}
(mockRequestHandler.sendMessageStream as Mock).mockResolvedValue(mockStream());
const stream = await transportHandler.sendMessageStream(
{ message: testMessage },
mockContext
);
expect(stream).toBeDefined();
expect(mockRequestHandler.sendMessageStream as Mock).toHaveBeenCalled();
});
});
describe('getTask', () => {
it('should get task by ID', async () => {
const result = await transportHandler.getTask('task-1', mockContext);
expect(result).to.deep.equal(testTask);
expect(mockRequestHandler.getTask as Mock).toHaveBeenCalledWith(
{ id: 'task-1' },
mockContext
);
});
it('should include historyLength if provided', async () => {
await transportHandler.getTask('task-1', mockContext, '10');
expect(mockRequestHandler.getTask as Mock).toHaveBeenCalledWith(
{ id: 'task-1', historyLength: 10 },
mockContext
);
});
it('should throw InvalidParams if historyLength is invalid', async () => {
await expect(transportHandler.getTask('task-1', mockContext, 'invalid')).rejects.toThrow(
'historyLength must be a valid integer'
);
});
it('should throw InvalidParams if historyLength is negative', async () => {
await expect(transportHandler.getTask('task-1', mockContext, '-5')).rejects.toThrow(
'historyLength must be non-negative'
);
});
});
describe('cancelTask', () => {
it('should cancel task by ID', async () => {
const cancelledTask = { ...testTask, status: { state: 'canceled' as const } };
(mockRequestHandler.cancelTask as Mock).mockResolvedValue(cancelledTask);
const result = await transportHandler.cancelTask('task-1', mockContext);
expect(result.status.state).to.equal('canceled');
expect(mockRequestHandler.cancelTask as Mock).toHaveBeenCalledWith(
{ id: 'task-1' },
mockContext
);
});
});
describe('resubscribe', () => {
it('should throw UnsupportedOperation if streaming not supported', async () => {
(mockRequestHandler.getAgentCard as Mock).mockResolvedValue({
...testAgentCard,
capabilities: { streaming: false },
});
await expect(transportHandler.resubscribe('task-1', mockContext)).rejects.toThrow(
'Agent does not support streaming'
);
});
it('should call request handler resubscribe if streaming supported', async () => {
async function* mockStream() {
yield testTask;
}
(mockRequestHandler.resubscribe as Mock).mockResolvedValue(mockStream());
const stream = await transportHandler.resubscribe('task-1', mockContext);
expect(stream).toBeDefined();
expect(mockRequestHandler.resubscribe as Mock).toHaveBeenCalledWith(
{ id: 'task-1' },
mockContext
);
});
});
describe('Push Notification Config', () => {
const mockConfig = {
taskId: 'task-1',
pushNotificationConfig: {
id: 'config-1',
url: 'https://example.com/webhook',
},
};
describe('setTaskPushNotificationConfig', () => {
it('should throw PushNotificationNotSupported if not supported', async () => {
(mockRequestHandler.getAgentCard as Mock).mockResolvedValue({
...testAgentCard,
capabilities: { pushNotifications: false },
});
await expect(
transportHandler.setTaskPushNotificationConfig(mockConfig, mockContext)
).rejects.toThrow('Push Notification is not supported');
});
it('should normalize and set config if supported', async () => {
(mockRequestHandler.setTaskPushNotificationConfig as Mock).mockResolvedValue(mockConfig);
const result = await transportHandler.setTaskPushNotificationConfig(
mockConfig,
mockContext
);
expect(result).to.deep.equal(mockConfig);
});
it('should throw InvalidParams if taskId is missing', async () => {
const invalidConfig = {
pushNotificationConfig: { id: 'config-1', url: 'https://example.com/webhook' },
};
await expect(
transportHandler.setTaskPushNotificationConfig(invalidConfig as any, mockContext)
).rejects.toThrow('taskId is required');
});
it('should throw InvalidParams if pushNotificationConfig is missing', async () => {
const invalidConfig = {
taskId: 'task-1',
};
await expect(
transportHandler.setTaskPushNotificationConfig(invalidConfig as any, mockContext)
).rejects.toThrow('pushNotificationConfig is required');
});
});
describe('listTaskPushNotificationConfigs', () => {
it('should list configs for task', async () => {
const configs = [mockConfig];
(mockRequestHandler.listTaskPushNotificationConfigs as Mock).mockResolvedValue(configs);
const result = await transportHandler.listTaskPushNotificationConfigs(
'task-1',
mockContext
);
expect(result).to.deep.equal(configs);
expect(mockRequestHandler.listTaskPushNotificationConfigs as Mock).toHaveBeenCalledWith(
{ id: 'task-1' },
mockContext
);
});
});
describe('getTaskPushNotificationConfig', () => {
it('should get specific config', async () => {
(mockRequestHandler.getTaskPushNotificationConfig as Mock).mockResolvedValue(mockConfig);
const result = await transportHandler.getTaskPushNotificationConfig(
'task-1',
'config-1',
mockContext
);
expect(result).to.deep.equal(mockConfig);
expect(mockRequestHandler.getTaskPushNotificationConfig as Mock).toHaveBeenCalledWith(
{ id: 'task-1', pushNotificationConfigId: 'config-1' },
mockContext
);
});
});
describe('deleteTaskPushNotificationConfig', () => {
it('should delete specific config', async () => {
(mockRequestHandler.deleteTaskPushNotificationConfig as Mock).mockResolvedValue(undefined);
await transportHandler.deleteTaskPushNotificationConfig('task-1', 'config-1', mockContext);
expect(mockRequestHandler.deleteTaskPushNotificationConfig as Mock).toHaveBeenCalledWith(
{ id: 'task-1', pushNotificationConfigId: 'config-1' },
mockContext
);
});
});
});
describe('File parts normalization', () => {
it.each([
{
name: 'camelCase',
message: {
messageId: 'msg-file',
role: 'user' as const,
parts: [
{
kind: 'file' as const,
file: {
uri: 'https://example.com/file.pdf',
mimeType: 'application/pdf',
name: 'document.pdf',
},
},
],
kind: 'message' as const,
},
},
])('should normalize $name file parts to camelCase', async ({ message }) => {
await transportHandler.sendMessage({ message } as any, mockContext);
expect(mockRequestHandler.sendMessage as Mock).toHaveBeenCalledWith(
expect.objectContaining({
message: expect.objectContaining({
parts: [
expect.objectContaining({
kind: 'file',
file: expect.objectContaining({ mimeType: 'application/pdf' }),
}),
],
}),
}),
mockContext
);
});
});
});

214
test/sse_utils.spec.ts Normal file
View File

@ -0,0 +1,214 @@
import { describe, it, expect } from 'vitest';
import { formatSSEEvent, formatSSEErrorEvent, parseSseStream, SseEvent } from '../src/sse_utils.js';
const MOCK_CHUNK_SIZE = 2;
/**
* Creates a ReadableStream from chunks of Uint8Array data.
*/
function createStream(chunks: Uint8Array[]): ReadableStream<Uint8Array> {
let chunkIndex = 0;
return new ReadableStream({
pull(controller) {
if (chunkIndex < chunks.length) {
controller.enqueue(chunks[chunkIndex]);
chunkIndex++;
} else {
controller.close();
}
},
});
}
/**
* Encodes a string into chunks of Uint8Array data.
*/
function encodeChunks(data: string): Uint8Array[] {
const encoder = new TextEncoder();
const chunks: Uint8Array[] = [];
for (let i = 0; i < data.length; i += MOCK_CHUNK_SIZE) {
chunks.push(encoder.encode(data.slice(i, i + MOCK_CHUNK_SIZE)));
}
return chunks;
}
/**
* Creates a mock Response object from SSE-formatted strings.
* Used to test that the parser can understand what the formatter produces.
*/
function createMockResponse(sseData: string): Response {
const chunks = encodeChunks(sseData);
return new Response(createStream(chunks), {
headers: { 'Content-Type': 'text/event-stream' },
});
}
/**
* Creates a mock Response where the decoded stream has no native async iterator.
* Simulates environments where ReadableStream async iteration is not supported.
* @see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#browser_compatibility
*/
function createMockResponseWithoutAsyncIterator(sseData: string): Response {
const chunks = encodeChunks(sseData);
const stream = createStream(chunks);
const originalPipeThrough = stream.pipeThrough.bind(stream);
stream.pipeThrough = function <T>(transform: ReadableWritablePair<T, Uint8Array>) {
const result = originalPipeThrough(transform);
delete result[Symbol.asyncIterator];
return result;
} as typeof stream.pipeThrough;
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream' },
});
}
describe('SSE Utils', () => {
describe('formatSSEEvent', () => {
it('should format a data event', () => {
const event = { kind: 'message', text: 'Hello' };
const formatted = formatSSEEvent(event);
expect(formatted).toBe('data: {"kind":"message","text":"Hello"}\n\n');
});
it('should format complex objects', () => {
const event = { nested: { value: 123 }, array: [1, 2, 3] };
const formatted = formatSSEEvent(event);
expect(formatted).toBe('data: {"nested":{"value":123},"array":[1,2,3]}\n\n');
});
});
describe('formatSSEErrorEvent', () => {
it('should format an error event with event type', () => {
const error = { code: -32603, message: 'Internal error' };
const formatted = formatSSEErrorEvent(error);
expect(formatted).toBe('event: error\ndata: {"code":-32603,"message":"Internal error"}\n\n');
});
});
describe.each([
['with native async iterator', createMockResponse],
['without native async iterator', createMockResponseWithoutAsyncIterator],
])('parseSseStream (%s)', (_, createResponse) => {
it('should parse a single data event', async () => {
const sseData = 'data: {"kind":"message"}\n\n';
const response = createResponse(sseData);
const events: SseEvent[] = [];
for await (const event of parseSseStream(response)) {
events.push(event);
}
expect(events).toHaveLength(1);
expect(events[0].type).toBe('message');
expect(events[0].data).toBe('{"kind":"message"}');
});
it('should parse an error event', async () => {
const sseData = 'event: error\ndata: {"code":-32001}\n\n';
const response = createResponse(sseData);
const events: SseEvent[] = [];
for await (const event of parseSseStream(response)) {
events.push(event);
}
expect(events).toHaveLength(1);
expect(events[0].type).toBe('error');
expect(events[0].data).toBe('{"code":-32001}');
});
it('should parse multiple events', async () => {
const sseData = 'data: {"id":1}\n\ndata: {"id":2}\n\n';
const response = createResponse(sseData);
const events: SseEvent[] = [];
for await (const event of parseSseStream(response)) {
events.push(event);
}
expect(events).toHaveLength(2);
expect(JSON.parse(events[0].data)).toEqual({ id: 1 });
expect(JSON.parse(events[1].data)).toEqual({ id: 2 });
});
});
describe('Symmetry: parser understands formatter output', () => {
it('should parse what formatSSEEvent produces', async () => {
const originalData = { kind: 'task', id: '123', status: 'completed' };
const formatted = formatSSEEvent(originalData);
const response = createMockResponse(formatted);
const events: SseEvent[] = [];
for await (const event of parseSseStream(response)) {
events.push(event);
}
expect(events).toHaveLength(1);
expect(events[0].type).toBe('message');
expect(JSON.parse(events[0].data)).toEqual(originalData);
});
it('should parse what formatSSEErrorEvent produces', async () => {
const originalError = { code: -32001, message: 'Task not found', data: { taskId: 'abc' } };
const formatted = formatSSEErrorEvent(originalError);
const response = createMockResponse(formatted);
const events: SseEvent[] = [];
for await (const event of parseSseStream(response)) {
events.push(event);
}
expect(events).toHaveLength(1);
expect(events[0].type).toBe('error');
expect(JSON.parse(events[0].data)).toEqual(originalError);
});
it('should parse multiple formatted events in sequence', async () => {
const events_to_format = [
{ kind: 'status-update', status: 'working' },
{ kind: 'artifact', data: 'hello' },
{ kind: 'status-update', status: 'completed' },
];
const formatted = events_to_format.map(formatSSEEvent).join('');
const response = createMockResponse(formatted);
const parsedEvents: SseEvent[] = [];
for await (const event of parseSseStream(response)) {
parsedEvents.push(event);
}
expect(parsedEvents).toHaveLength(3);
for (let i = 0; i < events_to_format.length; i++) {
expect(JSON.parse(parsedEvents[i].data)).toEqual(events_to_format[i]);
}
});
it('should parse mixed data and error events', async () => {
const dataEvent = { kind: 'message', text: 'hello' };
const errorEvent = { code: -32603, message: 'Internal error' };
const formatted = formatSSEEvent(dataEvent) + formatSSEErrorEvent(errorEvent);
const response = createMockResponse(formatted);
const parsedEvents: SseEvent[] = [];
for await (const event of parseSseStream(response)) {
parsedEvents.push(event);
}
expect(parsedEvents).toHaveLength(2);
expect(parsedEvents[0].type).toBe('message');
expect(JSON.parse(parsedEvents[0].data)).toEqual(dataEvent);
expect(parsedEvents[1].type).toBe('error');
expect(JSON.parse(parsedEvents[1].data)).toEqual(errorEvent);
});
});
});

View File

@ -5,8 +5,11 @@ export default defineConfig({
'src/index.ts',
'src/server/index.ts',
'src/server/express/index.ts',
'src/server/grpc/index.ts',
'src/client/index.ts',
'src/client/transports/grpc/index.ts',
],
format: ['esm', 'cjs'],
dts: true,
clean: true,
});

View File

@ -8,6 +8,8 @@ export default defineConfig({
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html', 'json-summary'],
include: ['src/**/*'],
exclude: ['src/samples/**/*', 'src/types/pb/**/*', 'src/grpc/pb/**/*'],
},
},
});

View File

@ -1,14 +1,28 @@
import { mergeConfig } from 'vitest/config';
import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config';
import defaultConfig from './vitest.config';
export default mergeConfig(defaultConfig, {
test: {
environment: 'edge-runtime',
exclude: [
// Express tests require Node.js-specific APIs (http, Express framework)
'test/server/a2a_express_app.spec.ts',
// Node modules should always be excluded
'**/node_modules/**',
],
},
});
export default defineWorkersConfig(
mergeConfig(defaultConfig, {
test: {
exclude: [
// Express tests require Node.js-specific APIs (http, Express framework)
'test/server/express/**',
// gRpc test require Node.js-specific gRPC module
'test/server/grpc/*.spec.ts',
'test/client/transports/grpc_transport.spec.ts',
'test/e2e.spec.ts',
'test/server/push_notification_integration.spec.ts',
// Node modules should always be excluded
'**/node_modules/**',
],
poolOptions: {
workers: {
miniflare: {
compatibilityDate: '2024-04-01',
},
},
},
},
})
);