Compare commits

..

169 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
Ivan Shymko
cf9c189149
ci: fix coverage job failing on main (#267)
# Description

The job added in #262 [is failing on
main](https://github.com/a2aproject/a2a-js/actions/runs/20265128688/job/58186385412)
as it tries to post a PR comment although there is no PR 🤦 .

Fixed by:
1. Add conditions for PR related steps.
2. Bring back publishing coverage report as artifact removed mistakenly
in #262.
3. Add a link to this artifact to code coverage comment on PRs.
2025-12-16 12:18:08 +00:00
Ivan Shymko
591a461ad5
ci: set timeout for tests (#266)
# Description

There are some instances of tests hanging for 6h (the default timeout),
while it's being investigated, set lower timeout.

Re #265.
2025-12-16 13:16:53 +01:00
Ivan Shymko
49b06164a0
ci: post code coverage delta comment on PRs (#262)
# Description

Post code coverage delta comment on PRs without third-party actions by
running tests twice and comparing via a script.

# Examples

<img width="374" height="225" alt="Screenshot 2025-12-16 at 11 29 03"
src="https://github.com/user-attachments/assets/bdf8b213-db08-400c-b78e-d24af68f471c"
/>


<img width="366" height="229" alt="Screenshot 2025-12-16 at 11 31 06"
src="https://github.com/user-attachments/assets/d886e3b8-a984-4253-84d5-73a3e321f545"
/>


<img width="370" height="231" alt="Screenshot 2025-12-16 at 11 32 45"
src="https://github.com/user-attachments/assets/7d6a9992-b0b8-4b8f-ae60-f1384f1e1fb2"
/>

Fixes #192.
2025-12-16 11:42:48 +01:00
Ivan Shymko
761afd1ef1
ci: add json-summary coverage reporter (#263)
# Description

This is going to be used to generate a simple coverage delta without
third-party actions. Example output produced by this runner:

```json
{
  "total": {
    "lines": {
      "total": 1356,
      "covered": 1105,
      "skipped": 0,
      "pct": 81.48
    },
    "statements": {
      "total": 1371,
      "covered": 1114,
      "skipped": 0,
      "pct": 81.25
    },
    "functions": {
      "total": 281,
      "covered": 245,
      "skipped": 0,
      "pct": 87.18
    },
    "branches": {
      "total": 863,
      "covered": 604,
      "skipped": 0,
      "pct": 69.98
    },
    "branchesTrue": {
      "total": 0,
      "covered": 0,
      "skipped": 0,
      "pct": 100
    }
  },
. . .
```

Re #192
2025-12-15 17:36:10 +01:00
Drew Foxall
6c76fef264
feat: remove EventEmitter dependency to support Edge Runtime (#219)
## Summary

This PR addresses [issue
#218](https://github.com/a2aproject/a2a-js/issues/218) by replacing the
Node.js-specific `EventEmitter` with the web-standard `EventTarget` API,
enabling the SDK to run natively on edge runtimes (Cloudflare Workers,
Deno, Bun) without requiring Node.js compatibility modes.

## Changes

### Replace EventEmitter with EventTarget

**File:** `src/server/events/execution_event_bus.ts`

- Removes Node.js `events` module dependency
- Uses web-standard `EventTarget` API available in all modern runtimes
- Maintains backward-compatible API (`on`, `off`, `once`,
`removeAllListeners`)
- Adds `ExecutionEventName` type alias for `'event' | 'finished'`
- Includes `CustomEvent` polyfill for Node.js 15-18 (built-in from
Node.js 19+)

## Implementation Details

### EventEmitter Behavior Compatibility

The implementation faithfully replicates EventEmitter semantics:

- **FIFO dispatch order** - Listeners fire in the order they were
registered
- **`this` context** - Listeners are invoked with `this` bound to the
event bus instance
- **Memory semantics** - Listeners are held via strong references until
explicitly removed (identical to EventEmitter)

### Type Safety

- Uses type guards (`isAgentExecutionCustomEvent`) for safe runtime
narrowing - no unsafe casts
- `'finished'` event listeners are invoked with no arguments (using
`Function.prototype.call`) matching EventEmitter behavior
- Internal listener tracking uses `readonly` Maps

## Benefits

- ✅ **Native Cloudflare Workers support** - No `nodejs_compat` flag
needed
- ✅ **Native Deno support** - No `npm:` shims required  
- ✅ **Native Bun support** - Full web API compatibility
- ✅ **Browser compatibility** - True universal JavaScript
- ✅ **Node.js 15+** - EventTarget is built-in

## Breaking Changes

- Requires **Node.js 15+** (EventTarget support)
- Node.js 14 no longer supported (EOL anyway)

## Testing

- All **146 existing tests pass** with these changes
- Added **27 new tests** for `DefaultExecutionEventBus` covering:
  - Basic `on`/`off`/`once` functionality
  - Multiple registrations of same listener
  - `once()` auto-cleanup behavior
  - `removeAllListeners()` for specific events and all events
  - Event firing order (FIFO)
  - Method chaining
  - `this` context binding

## Related Work

I've implemented and tested these changes in my fork:
- Fork: https://github.com/drew-foxall/a2a-js-sdk
- Working Hono implementation:
https://github.com/drew-foxall/a2a-js-sdk-examples

Closes #218

Release-As: 0.3.7
2025-12-15 08:28:25 +01:00
Areo-Joe
2b5f5b385e
docs: fix SendMessageSuccessResponse import in example (#126)
# 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)

Fix the `SendMessageSuccessResponse` import in README.
2025-12-14 08:27:17 +01:00
Ivan Shymko
312071c6d5
ci: run coverage check and upload html report as artifact (#257)
# Description

It doesn't report delta but at lease report can be downloaded now
([example](https://github.com/a2aproject/a2a-js/actions/runs/20171606275?pr=257))

Run only once on a modern Node due to Node 18 issues (see comment).

Re #192
2025-12-12 16:44:42 +01:00
Ivan Shymko
6c5ab27c70
ci: run tests against maintained Node LTS versions (#256)
# Description

Add current LTS versions: 20, 22, 24 keeping 18 as it's declared in
`package.json`. Scheduled dropping 18 version for major release (#179).

Fixes #165
2025-12-12 12:13:14 +01:00
Ivan Shymko
677bb7f3bb
docs: remove Google references from contributing guide (#255) 2025-12-12 09:23:02 +01:00
Ivan Shymko
7f19bc4ee4
test: migrate to vitest (#254)
# Description

Migrate from mocha and chai to vitest to prepare for testing on both
Node and Edge server runtimes (see [vitest
environment](https://vitest.dev/guide/environment)) and also potentially
running non-server tests with headless browsers.

Re #237
2025-12-11 10:36:30 +00:00
Ivan Shymko
aeee54fee2
docs: README.md cosmetics for 0.3.6 (#253)
# Description

Minor follow-up fixes:

1. Do not mention deprecated `A2AExpressApp`.
2. Point to repository internal up-to-date samples.
2025-12-11 11:33:02 +01:00
Ivan Shymko
f5b4ba50a0
ci: fix CODEOWNERS (#252)
# Description

Update CODEOWNERS to automatically assign maintainers for reviews.

[Current
version](a206d13c51/.github/CODEOWNERS)
shows the following error:

```
Unknown owner on line 7: make sure the team @google-a2a/googlers exists, is publicly visible, and has write access to the repository
*   @google-a2a/googlers
```
2025-12-11 09:42:57 +01:00
Agent2Agent (A2A) Bot
a206d13c51
chore(main): release 0.3.6 (#181)
🤖 I have created a release *beep* *boop*
---


## [0.3.6](https://github.com/a2aproject/a2a-js/compare/v0.3.5...v0.3.6)
(2025-12-10)


### Features

* add support for extendedAgentCard on client side
([#234](https://github.com/a2aproject/a2a-js/issues/234))
([3073376](3073376f7c))
* Add support for extension headers on client side
([#227](https://github.com/a2aproject/a2a-js/issues/227))
([8c57002](8c57002add))
* implement client interceptors
([#223](https://github.com/a2aproject/a2a-js/issues/223))
([5694c22](5694c22e3b))
* Implement extended card support on server side
([#197](https://github.com/a2aproject/a2a-js/issues/197))
([45014ac](45014ac4a1))
* implement server http+json
([#142](https://github.com/a2aproject/a2a-js/issues/142))
([f20e662](f20e66247d))
* introduce AgentCardResolver
([#225](https://github.com/a2aproject/a2a-js/issues/225))
([ddaf7de](ddaf7ded16))
* introduce transport agnostic client
([#198](https://github.com/a2aproject/a2a-js/issues/198))
([94a9848](94a9848399))
* server side support for extensions
([5ef7396](5ef7396075))
* support authentication on server side
([#195](https://github.com/a2aproject/a2a-js/issues/195))
([9872d93](9872d93622))


### Bug Fixes

* handle errors occurred in non-blocking sendMessage
([#187](https://github.com/a2aproject/a2a-js/issues/187))
([e55c0f4](e55c0f4791))


### Miscellaneous Chores

* set version to 0.3.6
([#191](https://github.com/a2aproject/a2a-js/issues/191))
([3f8cea0](3f8cea066e))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: Ivan Shymko <ishymko@google.com>
2025-12-10 16:02:35 +00:00
Ivan Shymko
8da480e54f
docs: update docs for 0.3.6 (#246)
# Description

1. Update README.md, sample agents and sample CLI to use new APIs
introduced in #162 (extract middlewares from `A2AExpressApp`) and #198
(transport-agnostic client).
2. Mark `A2AExpressApp` and `A2AClient` as deprecated.
3. Ensure samples and TCK import via index files only to "test" that all
required types are exported.
4.  Consolidate all `@example` tags to use ` ```ts `.
2025-12-10 15:53:59 +00:00
Ivan Shymko
6a3bc0b709
refactor: define and export helper API for Extensions (#251)
# Description

Define types and utility functions for extensions to export for external
usage and share between client and server.

Re #218 #219
2025-12-10 15:50:26 +00:00
Ivan Shymko
67a1217abd
refactor: properly specify export type (#248)
# Description

Fix exports for newly introduced client symbols.
2025-12-10 12:27:43 +01:00
Ivan Shymko
919cbaaa65
refactor: rename HTTP REST to REST (#247)
# Description

Follow-up for unreleased #142.

[The spec](https://a2a-protocol.org/latest/specification/) uses
[`HTTP+JSON/REST`](https://a2a-protocol.org/latest/specification/#11-httpjsonrest-protocol-binding)
wording and other SDKs use just REST in all names (i.e.
[Python](https://github.com/a2aproject/a2a-python/blob/main/src/a2a/server/request_handlers/rest_handler.py)
and
[Golang](https://github.com/a2aproject/a2a-go/blob/release/spec-v1/a2asrv/rest.go)).
2025-12-10 10:35:22 +00:00
Ivan Shymko
22551f9b28
refactor: improve ClientFactory.createFrom array merging logic (#245)
# Description

Update `ClientFactory.createFrom` merging logic to work better with
common use-cases:

1. Merge transports by `TransportFactory.protocolName` to allow the
following:
```ts
const factory = new ClientFactory(ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
  transports: [
    new JsonRpcTransportFactory({ fetchImpl: myCustomFetch })
  ]
}))
```
2. Concatenate interceptors to allow providing SDK default interceptors.
3. Other config-like arrays (`preferredTransports`,
`clientConfig.acceptedOutputModes`) are replaced.

Re: follow-up for unreleased #240
2025-12-10 10:28:05 +00:00
Guglielmo Colombo
cdbaf64240
refactor: reverse execution order of interceptors in the after interceptor (#244)
# Description

This PR reverses the execution order of interceptors in the
interceptAfter method. It ensures symmetry with interceptBefore, meaning
the last interceptor called during the 'before' phase is the first one
called during the 'after' phase.

---------

Co-authored-by: Ivan Shymko <vana.shimko@gmail.com>
2025-12-10 09:08:24 +00:00
dependabot[bot]
9706438a9e
chore(deps-dev): bump jws from 3.2.2 to 3.2.3 in /src/samples (#233)
Bumps [jws](https://github.com/brianloveswords/node-jws) from 3.2.2 to
3.2.3.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/brianloveswords/node-jws/releases">jws's
releases</a>.</em></p>
<blockquote>
<h2>v3.2.3</h2>
<h3>Changed</h3>
<ul>
<li>Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now
require
that a non empty secret is provided (via opts.secret, opts.privateKey or
opts.key)
when using HMAC algorithms.</li>
<li>Upgrading JWA version to 1.4.2, addressing a compatibility issue for
Node &gt;= 25.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/auth0/node-jws/blob/master/CHANGELOG.md">jws's
changelog</a>.</em></p>
<blockquote>
<h2>[3.2.3]</h2>
<h3>Changed</h3>
<ul>
<li>Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now
require
that a non empty secret is provided (via opts.secret, opts.privateKey or
opts.key)
when using HMAC algorithms.</li>
<li>Upgrading JWA version to 1.4.2, adressing a compatibility issue for
Node &gt;= 25.</li>
</ul>
<h2>[3.0.0]</h2>
<h3>Changed</h3>
<ul>
<li><strong>BREAKING</strong>: <code>jwt.verify</code> now requires an
<code>algorithm</code> parameter, and
<code>jws.createVerify</code> requires an <code>algorithm</code> option.
The <code>&quot;alg&quot;</code> field
signature headers is ignored. This mitigates a critical security flaw
in the library which would allow an attacker to generate signatures with
arbitrary contents that would be accepted by <code>jwt.verify</code>.
See
<a
href="https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/">https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/</a>
for details.</li>
</ul>
<h2><a
href="https://github.com/brianloveswords/node-jws/compare/v1.0.1...v2.0.0">2.0.0</a>
- 2015-01-30</h2>
<h3>Changed</h3>
<ul>
<li>
<p><strong>BREAKING</strong>: Default payload encoding changed from
<code>binary</code> to
<code>utf8</code>. <code>utf8</code> is a is a more sensible default
than <code>binary</code> because
many payloads, as far as I can tell, will contain user-facing
strings that could be in any language. (<!-- raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/6b6de48">6b6de48</a><!--
raw HTML omitted -->)</p>
</li>
<li>
<p>Code reorganization, thanks <a
href="https://github.com/fearphage"><code>@​fearphage</code></a>! (<!--
raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/7880050">7880050</a><!--
raw HTML omitted -->)</p>
</li>
</ul>
<h3>Added</h3>
<ul>
<li>Option in all relevant methods for <code>encoding</code>. For those
few users
that might be depending on a <code>binary</code> encoding of the
messages, this
is for them. (<!-- raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/6b6de48">6b6de48</a><!--
raw HTML omitted -->)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="4f6e73f24d"><code>4f6e73f</code></a>
Merge commit from fork</li>
<li><a
href="bd0fea57f3"><code>bd0fea5</code></a>
version 3.2.3</li>
<li><a
href="7c3b4b4110"><code>7c3b4b4</code></a>
Enhance tests for HMAC streaming sign and verify</li>
<li><a
href="a9b8ed999d"><code>a9b8ed9</code></a>
Improve secretOrKey initialization in VerifyStream</li>
<li><a
href="6707fde62c"><code>6707fde</code></a>
Improve secret handling in SignStream</li>
<li>See full diff in <a
href="https://github.com/brianloveswords/node-jws/compare/v3.2.2...v3.2.3">compare
view</a></li>
</ul>
</details>
<details>
<summary>Maintainer changes</summary>
<p>This version was pushed to npm by <a
href="https://www.npmjs.com/~julien.wollscheid">julien.wollscheid</a>, a
new releaser for jws since your current version.</p>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=jws&package-manager=npm_and_yarn&previous-version=3.2.2&new-version=3.2.3)](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>
Co-authored-by: Ivan Shimko <vana.shimko@gmail.com>
2025-12-10 08:00:04 +00:00
tchapacan
f20e66247d
feat: implement server http+json (#142)
# Description

## Add HTTP+REST ServerSide Transport Support

- Server: REST endpoints/routes addition by taking advantage of
pre-existing express from the codebase. Following this
[doc](https://a2a-protocol.org/latest/specification/#356-method-mapping-reference-table)
and internally rerouting to each a2a handler method containing the
buisness logic

Some part of the code has been generated using generative AI to speed up
the development, I have reviewed it carefully, but this should be taken
into account into the review. Keep in mind this is my first time
contributing to the repo and this is an attempt to help a2a-js support
REST (HTTP+JSON) as per describe in the [a2a
documentation](https://a2a-protocol.org/latest/specification/#323-httpjsonrest-transport).
I'll be happy to refacto it during review process, don't hesitate to
challenge it.

---

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)

Re #137 🦕

Release-As: 0.3.6
2025-12-10 08:33:22 +01:00
Ivan Shymko
4ad73c118a
refactor: rename ClientFactory.createFromAgentCardUrl -> createFromUrl (#242)
# Description

`createFromAgentCardUrl` may give a wrong impression that full URL has
to be provided, rename and add examples.

Not yet released, `AgentCardResolver` and the method were added in #225.

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-12-09 17:15:38 +01:00
Ivan Shymko
1ca8c8b225
refactor: define a helper function to customize ClientFactoryOptions (#240)
# Description

Deep cloning each object and array for adding an interceptor into
default client config (for example) is quite involved, define a helper
function so that it can be done as follows:

```ts
const options = ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
  clientConfig: { interceptors: [new MyInterceptor()] },
});
```
2025-12-09 12:27:38 +01:00
Ivan Shymko
bdddac42d1
chore: properly configure license field in package.json (#238)
# Description


Currently license is shown as `none` on npm:
https://www.npmjs.com/package/@a2a-js/sdk.
2025-12-08 16:26:05 +01:00
Guglielmo Colombo
47854792b6
feat: add AgentCard to interceptors parameters (#236)
# Description

This PR add a feature to PR #223 adding the agentCard to the
interceptors' parameters. Some values of the agentCard may be necessary
at the interceptors level (e.g. security schemes).

BEGIN_COMMIT_OVERRIDE
refactor: add AgentCard to interceptors parameters
END_COMMIT_OVERRIDE
2025-12-08 14:05:35 +00:00
Ivan Shymko
7d9a0c7515
refactor: pass ServerCallContext to TaskStore (#235)
# Description

Pass `ServerCallContext` to `TaskStore` to allow DB-backed stores.
Enhance comments for `User`, stating that `userName` is a unique
identifier.

Re #213
2025-12-08 10:24:47 +00:00
Guglielmo Colombo
3073376f7c
feat: add support for extendedAgentCard on client side (#234)
# Description

This PR adds the support on client side for the
getAuthenticatedExtendedCard api.

Fixes #196 🦕

Release-As: 0.3.6

---------

Co-authored-by: Ivan Shymko <vana.shimko@gmail.com>
2025-12-07 17:29:15 +00:00
Guglielmo Colombo
8c57002add
feat: Add support for extension headers on client side (#227)
# Description

This PR implements the support for extensions on client side

Fixes #170 🦕

Release-As: 0.3.6

---------

Co-authored-by: Ivan Shymko <ishymko@google.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-12-05 12:40:00 +00:00
Ivan Shymko
7250d328fa
refactor: define typed API for client call context (#232)
# Description

Provides typed API to read and update context to make predefined and
externally defined keys composable in the same way.

```ts
export type SystemParameters = Record<string, string>;

export const systemParametersKey = new ClientCallContextKey<SystemParameters>('systemParameters');

const myContext = ClientCallContext.create(
  systemParametersKey.set({ 'X-A2A-Extensions': 'http://example.com' })
);

const myParameters = systemParametersKey.get(myContext);
```

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-12-05 11:13:37 +00:00
dependabot[bot]
101b95c617
chore(deps-dev): bump express from 5.1.0 to 5.2.0 (#222)
Bumps [express](https://github.com/expressjs/express) from 5.1.0 to
5.2.0.
<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>v5.2.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>build(deps): bump github/codeql-action from 3.28.11 to 3.28.13 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6429">expressjs/express#6429</a></li>
<li>Refactor: simplify <code>acceptsLanguages</code> implementation
using spread operator by <a
href="https://github.com/Ayoub-Mabrouk"><code>@​Ayoub-Mabrouk</code></a>
in <a
href="https://redirect.github.com/expressjs/express/pull/6137">expressjs/express#6137</a></li>
<li>increased code coverage of utils.js file by <a
href="https://github.com/ashish3011"><code>@​ashish3011</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6386">expressjs/express#6386</a></li>
<li>chore: remove duplicate word by <a
href="https://github.com/dufucun"><code>@​dufucun</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6456">expressjs/express#6456</a></li>
<li>build(deps): bump github/codeql-action from 3.28.13 to 3.28.16 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6498">expressjs/express#6498</a></li>
<li>build(deps): bump actions/setup-node from 4.3.0 to 4.4.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6497">expressjs/express#6497</a></li>
<li>build(deps): bump actions/download-artifact from 4.2.1 to 4.3.0 by
<a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6496">expressjs/express#6496</a></li>
<li>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/6504">expressjs/express#6504</a></li>
<li>ci: update codeql config by <a
href="https://github.com/Phillip9587"><code>@​Phillip9587</code></a> in
<a
href="https://redirect.github.com/expressjs/express/pull/6488">expressjs/express#6488</a></li>
<li>chore: 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/6512">expressjs/express#6512</a></li>
<li>chore: fix typos in test by <a
href="https://github.com/noritaka1166"><code>@​noritaka1166</code></a>
in <a
href="https://redirect.github.com/expressjs/express/pull/6535">expressjs/express#6535</a></li>
<li>ci: disable credential persistence for checkout actions by <a
href="https://github.com/mertssmnoglu"><code>@​mertssmnoglu</code></a>
in <a
href="https://redirect.github.com/expressjs/express/pull/6522">expressjs/express#6522</a></li>
<li>ci: allow manual triggering of workflow by <a
href="https://github.com/shivarm"><code>@​shivarm</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6515">expressjs/express#6515</a></li>
<li>test: add coverage for app.listen() variants by <a
href="https://github.com/kgarg1"><code>@​kgarg1</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6476">expressjs/express#6476</a></li>
<li>docs: move documentation and charters to the discussions and .github
… by <a
href="https://github.com/bjohansebas"><code>@​bjohansebas</code></a> in
<a
href="https://redirect.github.com/expressjs/express/pull/6427">expressjs/express#6427</a></li>
<li>build(deps): bump github/codeql-action from 3.28.16 to 3.28.18 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6549">expressjs/express#6549</a></li>
<li>build(deps): bump ossf/scorecard-action from 2.4.1 to 2.4.2 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6548">expressjs/express#6548</a></li>
<li>chore: enforce explicit <code>Buffer</code> import and add lint rule
by <a href="https://github.com/shivarm"><code>@​shivarm</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6525">expressjs/express#6525</a></li>
<li>chore: use node protocol for querystring by <a
href="https://github.com/shivarm"><code>@​shivarm</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6520">expressjs/express#6520</a></li>
<li>chore: fix typo by <a
href="https://github.com/mountdisk"><code>@​mountdisk</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6609">expressjs/express#6609</a></li>
<li>build(deps): bump github/codeql-action from 3.28.18 to 3.29.2 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6618">expressjs/express#6618</a></li>
<li>add deprecation warnings for redirect arguments undefined by <a
href="https://github.com/bjohansebas"><code>@​bjohansebas</code></a> in
<a
href="https://redirect.github.com/expressjs/express/pull/6405">expressjs/express#6405</a></li>
<li>ci: run CI when the markdown changes by <a
href="https://github.com/bjohansebas"><code>@​bjohansebas</code></a> in
<a
href="https://redirect.github.com/expressjs/express/pull/6632">expressjs/express#6632</a></li>
<li>doc: fix CONTRIBUTING link by <a
href="https://github.com/jonchurch"><code>@​jonchurch</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6653">expressjs/express#6653</a></li>
<li>doc: update contributing guidelines and code of conduct links by <a
href="https://github.com/ShubhamOulkar"><code>@​ShubhamOulkar</code></a>
in <a
href="https://redirect.github.com/expressjs/express/pull/6601">expressjs/express#6601</a></li>
<li>build(deps-dev): bump morgan from 1.10.0 to 1.10.1 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6679">expressjs/express#6679</a></li>
<li>build(deps-dev): bump cookie-session from 2.1.0 to 2.1.1 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6678">expressjs/express#6678</a></li>
<li>lint: add --fix flag to automatic fix linting issue by <a
href="https://github.com/shivarm"><code>@​shivarm</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6644">expressjs/express#6644</a></li>
<li>chore: ignore yarn.lock file and update example by <a
href="https://github.com/shivarm"><code>@​shivarm</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6588">expressjs/express#6588</a></li>
<li>lib: use req.socket over deprecated req.connection by <a
href="https://github.com/bjohansebas"><code>@​bjohansebas</code></a> in
<a
href="https://redirect.github.com/expressjs/express/pull/6705">expressjs/express#6705</a></li>
<li>doc: update express app example by <a
href="https://github.com/shivarm"><code>@​shivarm</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6718">expressjs/express#6718</a></li>
<li>build(deps): bump github/codeql-action from 3.29.2 to 3.29.5 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6675">expressjs/express#6675</a></li>
<li>Remove history.md from being packaged on publish by <a
href="https://github.com/sheplu"><code>@​sheplu</code></a> in <a
href="https://redirect.github.com/expressjs/express/pull/6780">expressjs/express#6780</a></li>
<li>build(deps): bump actions/checkout from 4.2.2 to 5.0.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6797">expressjs/express#6797</a></li>
<li>build(deps): bump github/codeql-action from 3.29.7 to 3.30.5 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6796">expressjs/express#6796</a></li>
<li>build(deps): bump ossf/scorecard-action from 2.4.2 to 2.4.3 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6795">expressjs/express#6795</a></li>
<li>build(deps): bump actions/setup-node from 4.4.0 to 5.0.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6794">expressjs/express#6794</a></li>
<li>build(deps): bump actions/download-artifact from 4.3.0 to 5.0.0 by
<a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6793">expressjs/express#6793</a></li>
<li>ci: add node.js 25 to test matrix by <a
href="https://github.com/Phillip9587"><code>@​Phillip9587</code></a> in
<a
href="https://redirect.github.com/expressjs/express/pull/6843">expressjs/express#6843</a></li>
<li>build(deps): bump actions/download-artifact from 5.0.0 to 6.0.0 by
<a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6871">expressjs/express#6871</a></li>
<li>build(deps): bump actions/setup-node from 5.0.0 to 6.0.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6870">expressjs/express#6870</a></li>
<li>build(deps): bump github/codeql-action from 3.30.5 to 4.31.2 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6869">expressjs/express#6869</a></li>
<li>build(deps): bump actions/upload-artifact from 4.6.2 to 5.0.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/expressjs/express/pull/6868">expressjs/express#6868</a></li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/expressjs/express/blob/master/History.md">express's
changelog</a>.</em></p>
<blockquote>
<h1>5.2.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: <code>body-parser@^2.2.1</code></li>
<li>A deprecation warning was added when using <code>res.redirect</code>
with undefined arguments, Express now emits a warning to help detect
calls that pass undefined as the status or URL and make them easier to
fix.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="4007ad103b"><code>4007ad1</code></a>
Release: 5.2.0 (<a
href="https://redirect.github.com/expressjs/express/issues/6920">#6920</a>)</li>
<li><a
href="2f64f68c37"><code>2f64f68</code></a>
sec: security patch for CVE-2024-51999</li>
<li><a
href="ed0ba3f1dc"><code>ed0ba3f</code></a>
build(deps): bump actions/checkout from 5.0.0 to 6.0.0 (<a
href="https://redirect.github.com/expressjs/express/issues/6928">#6928</a>)</li>
<li><a
href="8eace4603c"><code>8eace46</code></a>
build(deps): bump github/codeql-action from 4.31.2 to 4.31.6 (<a
href="https://redirect.github.com/expressjs/express/issues/6929">#6929</a>)</li>
<li><a
href="30bae81027"><code>30bae81</code></a>
build(deps): bump coverallsapp/github-action from 2.3.6 to 2.3.7 (<a
href="https://redirect.github.com/expressjs/express/issues/6930">#6930</a>)</li>
<li><a
href="758d4355d4"><code>758d435</code></a>
deps: body-parser@^2.2.1 (<a
href="https://redirect.github.com/expressjs/express/issues/6922">#6922</a>)</li>
<li><a
href="77bcd5274a"><code>77bcd52</code></a>
docs: update emeritus triagers (<a
href="https://redirect.github.com/expressjs/express/issues/6890">#6890</a>)</li>
<li><a
href="f33caf1f89"><code>f33caf1</code></a>
Nominate to <a
href="https://github.com/efekrskl"><code>@​efekrskl</code></a> for
triage team (<a
href="https://redirect.github.com/expressjs/express/issues/6888">#6888</a>)</li>
<li><a
href="54af593b73"><code>54af593</code></a>
refactor: use cached slice in app.listen (<a
href="https://redirect.github.com/expressjs/express/issues/6897">#6897</a>)</li>
<li><a
href="2551a7d8af"><code>2551a7d</code></a>
docs: switch badges from badgen.net to shields.io (<a
href="https://redirect.github.com/expressjs/express/issues/6900">#6900</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/expressjs/express/compare/v5.1.0...v5.2.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=express&package-manager=npm_and_yarn&previous-version=5.1.0&new-version=5.2.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 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>
2025-12-05 10:42:02 +00:00
Ivan Shymko
01287978af
refactor: rename const objects properties to camelCase (#231)
# Description

Those types were not released, so renaming to use JS/TS common style of
camelCase.
2025-12-04 17:22:26 +01:00
Ivan Shymko
377e8b9d78
build: run tsc on tck folder (#230)
# Description

Type check TCK SUT code, ESLint already works on this folder as it uses
`eslint .` in `package.json`.
2025-12-04 11:47:39 +00:00
Mats Julius Funke
7a0f648673
docs: Add missing required Agent Card fields to Quickstart in README (#229)
# Description

When trying out a new library I always copy the quickstarts from the
README of the library, when I did it in this case I got an error since
the `capabilities`, `defaultInputModes` and `defaultOutputModes` where
missing since the `AgentCard` type requires them.

```bash
if (agentCard.capabilities.pushNotifications) {
                               ^

TypeError: Cannot read properties of undefined (reading 'pushNotifications')
    at new DefaultRequestHandler (/Users/matsfunke/Desktop/tmp/node_modules/@a2a-js/sdk/dist/server/index.cjs:490:32)
    at express (/Users/matsfunke/Desktop/tmp/server.ts:60:24)
    at Object.<anonymous> (/Users/matsfunke/Desktop/tmp/server.ts:71:2)
    at Module._compile (node:internal/modules/cjs/loader:1706:14)
    at Object.transformer (/Users/matsfunke/Desktop/tmp/node_modules/tsx/dist/register-D46fvsV_.cjs:3:1104)
    at Module.load (node:internal/modules/cjs/loader:1441:32)
    at Function._load (node:internal/modules/cjs/loader:1263:12)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:237:24)
    at cjsLoader (node:internal/modules/esm/translators:309:5)
```

**This is in my option bad UX as users have to fix this before they can
run the server.**

**Also really sorry for just submitting a docs only PR 🙏** 

Before submitting the PR:
- [X] I read and followed [`CONTRIBUTING`
Guide](https://github.com/google-a2a/a2a-js/blob/main/CONTRIBUTING.md).
- [X] I ensured that the PR title follows the
<https://www.conventionalcommits.org/> specification.
- [X] I ensured the tests and linter pass
2025-12-04 08:28:51 +01:00
Guglielmo Colombo
8494544520
fix: change context parameter in RequestOptions from mandatory to optional (#228)
# Description

This PR changes the `context` parameter in `RequestOptions` from
mandatory to optional.

Fix for #223 which is not yet released, so overriding changelog entry
below to avoid extra message for unreleased functionality.

BEGIN_COMMIT_OVERRIDE
refactor: change `context` parameter in `RequestOptions` from mandatory
to optional
END_COMMIT_OVERRIDE
2025-12-03 16:11:50 +01:00
Ivan Shymko
83072f6d6e
fix: properly invoke CallInterceptor.after for async generators (#226)
1. `after` wasn't invoked in case of early return from `before` for
executed interceptors as done in non-generators methods.
2. `after` wasn't invoked for non-streaming fallback from
`sendMessageStream`.

Fix for #223 which is not yet released, so overriding changelog entry
below to avoid extra message for unreleased functionality.

BEGIN_COMMIT_OVERRIDE
refactor: properly invoke CallInterceptor.after for async generators
END_COMMIT_OVERRIDE
2025-12-03 13:57:07 +01:00
Ivan Shymko
ddaf7ded16
feat: introduce AgentCardResolver (#225)
# Description

Define `AgentCardResolver` and wire it up with `ClientFactory` via a new
method `createFromAgentCardUrl`.

Release-As: 0.3.6
2025-12-03 11:37:50 +01:00
Ivan Shymko
5694c22e3b
feat: implement client interceptors (#223)
# Description

Implement client interceptors and export multi-transport client types to
prepare for upcoming release.

Interceptors support "early return" both before and after transport
invocation. For early return before transport invocation client invokes
appropriate "after" methods of executed interceptors.

Release-As: 0.3.6

---------

Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
2025-12-03 11:25:41 +01:00
Ivan Shymko
2db7e3867f
ci: run npm run lint (#224)
# Description

`tsc --noEmit` added in #214 as a part of `npm run lint` wasn't executed
in CI.

Add it and fix errors introduced while it wasn't running.
2025-12-02 13:39:23 +01:00
Guglielmo Colombo
cc9d223e69
docs: create a sample for authentication feature (#211)
# Description

This PR introduces a sample for the authentication feature.

Re #195

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-12-01 16:09:53 +01:00
Guglielmo Colombo
a0cc13575c
refactor: create a dedicated package.json for samples (#216)
# Description

This PR creates a new `package.json` in the `samples` folder, not to
pollute the main `package.json` with libraries specific to the samples.
2025-11-28 15:48:52 +00:00
Ivan Shymko
c2a246828c
refactor: add RequestOptions to multitransport client (#215)
# Description

Propagate `RequestOptions` down to `Transport`.

Re #198, was missing in the original PR - wasn't release yet, so no
impact.
2025-11-28 12:55:34 +00:00
Guglielmo Colombo
31c1a6e822
build: run tsc --noEmit on lint (#214)
# Description

`tsup` does not perform strict type checking before the generation of
the `d.ts` files. Adding the `tsc --noEmit` step checks for types
violation.

---------

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>
2025-11-28 11:36:30 +00:00
dependabot[bot]
0e5c9fd54e
chore(deps-dev): bump node-forge from 1.3.1 to 1.3.2 (#201)
Bumps [node-forge](https://github.com/digitalbazaar/forge) from 1.3.1 to
1.3.2.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/digitalbazaar/forge/blob/main/CHANGELOG.md">node-forge's
changelog</a>.</em></p>
<blockquote>
<h2>1.3.2 - 2025-11-25</h2>
<h3>Security</h3>
<ul>
<li><strong>HIGH</strong>: ASN.1 Validator Desynchronization
<ul>
<li>An Interpretation Conflict (CWE-436) vulnerability in node-forge
versions
1.3.1 and below enables remote, unauthenticated attackers to craft ASN.1
structures to desynchronize schema validations, yielding a semantic
divergence that may bypass downstream cryptographic verifications and
security decisions.</li>
<li>Reported by Hunter Wodzenski.</li>
<li>CVE ID: <a
href="https://www.cve.org/CVERecord?id=CVE-2025-12816">CVE-2025-12816</a></li>
<li>GHSA ID: <a
href="https://github.com/digitalbazaar/forge/security/advisories/GHSA-5gfm-wpxj-wjgq">GHSA-5gfm-wpxj-wjgq</a></li>
</ul>
</li>
<li><strong>HIGH</strong>: ASN.1 Unbounded Recursion
<ul>
<li>An Uncontrolled Recursion (CWE-674) vulnerability in node-forge
versions
1.3.1 and below enables remote, unauthenticated attackers to craft deep
ASN.1 structures that trigger unbounded recursive parsing. This leads to
a
Denial-of-Service (DoS) via stack exhaustion when parsing untrusted DER
inputs.</li>
<li>Reported by Hunter Wodzenski.</li>
<li>CVE ID: <a
href="https://www.cve.org/CVERecord?id=CVE-2025-66031">CVE-2025-66031</a></li>
<li>GHSA ID: <a
href="https://github.com/digitalbazaar/forge/security/advisories/GHSA-554w-wpv2-vw27">GHSA-554w-wpv2-vw27</a></li>
</ul>
</li>
<li><strong>MODERATE</strong>: ASN.1 OID Integer Truncation
<ul>
<li>An Integer Overflow (CWE-190) vulnerability in node-forge versions
1.3.1
and below enables remote, unauthenticated attackers to craft ASN.1
structures containing OIDs with oversized arcs. These arcs may be
decoded
as smaller, trusted OIDs due to 32-bit bitwise truncation, enabling the
bypass of downstream OID-based security decisions.</li>
<li>Reported by Hunter Wodzenski.</li>
<li>CVE ID: <a
href="https://www.cve.org/CVERecord?id=CVE-2025-66030">CVE-2025-66030</a></li>
<li>GHSA ID: <a
href="https://github.com/digitalbazaar/forge/security/advisories/GHSA-65ch-62r8-g69g">GHSA-65ch-62r8-g69g</a></li>
</ul>
</li>
</ul>
<h3>Fixed</h3>
<ul>
<li>[asn1] Fix for vulnerability identified by CVE-2025-12816 PKCS#12
MAC
verification bypass due to missing macData enforcement and improper
asn1.validate routine.</li>
<li>[asn1] Add <code>fromDer()</code> max recursion depth check.
<ul>
<li>Add a <code>asn1.maxDepth</code> global configurable maximum depth
of 256.</li>
<li>Add a <code>asn1.fromDer()</code> per-call <code>maxDepth</code>
option.</li>
<li><strong>NOTE</strong>: The default maximum is assumed to be higher
than needed for valid
data. If this assumption is false then this could be a breaking change.
Please file an issue if there are use cases that need a higher
maximum.</li>
<li><strong>NOTE</strong>: The per-call <code>maxDepth</code> parameter
has not been exposed up through
all of the API stack due to the complexities involved. Please file an
issue
if there are use cases that require this instead of changing the default
maximum.</li>
</ul>
</li>
<li>[asn1] Improve OID handling.
<ul>
<li>Error on parsed OID values larger than <code>2**32 - 1</code>.</li>
<li>Error on DER OID values larger than <code>2**53 - 1 </code>.</li>
</ul>
</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="235ad3e70e"><code>235ad3e</code></a>
Release 1.3.2.</li>
<li><a
href="2598244117"><code>2598244</code></a>
Update changelog.</li>
<li><a
href="0032dd0be8"><code>0032dd0</code></a>
Fix typos.</li>
<li><a
href="d75e08d255"><code>d75e08d</code></a>
Run new security test.</li>
<li><a
href="a5ce91d03d"><code>a5ce91d</code></a>
Update changelog formatting.</li>
<li><a
href="4652de6ddd"><code>4652de6</code></a>
Cleanups.</li>
<li><a
href="eb932d94fb"><code>eb932d9</code></a>
Fix typo.</li>
<li><a
href="db6954ba4b"><code>db6954b</code></a>
Fix style.</li>
<li><a
href="afbf7d8e08"><code>afbf7d8</code></a>
Align error message style.</li>
<li><a
href="6607445859"><code>6607445</code></a>
Revert minor changes.</li>
<li>Additional commits viewable in <a
href="https://github.com/digitalbazaar/forge/compare/v1.3.1...v1.3.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=node-forge&package-manager=npm_and_yarn&previous-version=1.3.1&new-version=1.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 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>
Co-authored-by: Ivan Shymko <ishymko@google.com>
2025-11-27 16:01:25 +00:00
Ivan Shymko
86f6cfaacd
ci: use esbuild to ensure client and root entry points build for browser (#210)
# Description

Add an automated test for the issue solved previously in #46 to ensure
that client and root entry points build for browsers.

Example failure would look like:

```
✘ [ERROR] Could not resolve "events"

    dist/server/index.js:27:29:
      27 │ import { EventEmitter } from "events";
         ╵                              ~~~~~~~~

  The package "events" wasn't found on the file system but is built into node. Are you trying to
  bundle for node? You can use "--platform=node" to do that, which will remove this error.
```

(obtained by running `esbuild ./dist/server/index.js --bundle
--platform=browser --outdir=dist/tmp-checks --outbase=./dist`)

---------

Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
2025-11-27 15:36:26 +00:00
Ivan Shymko
2768ae8281
build: regenerate package-lock.json with matching npm version (#212)
# Description

Currently there is an inconsistency between package.json and
package-lock.json which can be seen in #201. Merging updated file after
`npm install` with matching npm version.
2025-11-27 16:33:50 +01:00
Ivan Shymko
94a9848399
feat: introduce transport agnostic client (#198)
# Description

As a next step after #169, define a transport agnostic client.

# Changes

## Main
- Define `Client` built around core types, not JSON-RPC wrappers.
- Define `ClientFactory` to dynamically select transport among available
based on agent card and factory level preferences.

## Misc
- Rename `A2ATransport` to `Transport` (this type is not yet exported
via `index.ts`).
- Add `AbortSignal` to `Transport` and new client for cancellation.
- Add basic E2E test for `sendMessage` and `sendMessageStream` using
server SDK wired up with real expressjs app and invoked via newly
created client.
- Fix `getTaskPushNotificationConfig` types in transport.

# TODOs
- Client interceptors.
- Extensions support.

Re #137, #142

Release-As: 0.3.6
2025-11-27 16:16:30 +01:00
Ivan Shymko
b1f50ddbfa
ci: run capabilities TCK tests (#204)
# Description

Run `--category capabilities` TCK tests.

Re: #203
2025-11-27 14:31:45 +01:00
Ivan Shymko
5dfeee9664
refactor: make userBuilder non-nullable in A2AExpressApp (#205)
Re #202
2025-11-27 10:19:42 +00:00
Ivan Shymko
8938e73d2c
refactor: require user builder in JsonRpcHandlerOptions (#202)
# Description

Marking as refactor, since updated type wasn't released yet.

Making `userBuilder` a mandatory parameter for `JsonRpcHandlerOptions`
and define a helper `UserBuilder.NoAuthentication` to make it explicit.

Re #195.
2025-11-27 11:13:07 +01:00
Guglielmo Colombo
b72bda503a
fix: Populate the ServerCallContext user param when a new ServerCallContext is created (#200)
# Description

This PR is a fix for the bug caused by the user being deleted when the
request is containing requested extensions, as a new ServerCallContext
was created without copying the `context.user`.

Fixes #199 🦕
PRs #171, #195 

BEGIN_COMMIT_OVERRIDE
refactor: Populate the ServerCallContext user param when a new
ServerCallContext is created
END_COMMIT_OVERRIDE
2025-11-27 08:40:48 +00:00
Guglielmo Colombo
45014ac4a1
feat: Implement extended card support on server side (#197)
# Description

This PR introduces a more robust implementation of the
`getAuthenticatedExtendedAgentCard` API.
The user may inject in the `default_request_handler` an AgentCart object
or a callback (`ExtendedAgentCardProvider`) which receives as input
parameters the `ServerCallContext` and returns an AgentCard object.

- If extendedAgentCardProvider is provided as callback: The logic
delegates entirely to the callback. This allows consumers to implement
custom authorization check if the user has insufficient permissions.
- If extendedAgentCardProvider is provided as AgentCard object:
1. User in context is Authenticated: Returns extendedAgentCard.
2. User in context is Unauthenticated: Returns the basic agentCard.

Fixes #196  🦕

Release-As: 0.3.6

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-11-26 10:42:09 +01:00
Guglielmo Colombo
9872d93622
feat: support authentication on server side (#195)
# Description

This PR integrates a support for authentication on the server side.
A new `User` interface is created to represent the Authenticated and
UnAuthenticated user in the context, with 2 required function:
1. isAuthenticathed()
2. userName()

The callback `authenticathedUserExtractor` provided to the
`A2AExpressApp` is responsible for extracting the user object from the
Request (if set up by the authentication middleware), and returning an
instance of the `User` interface. The returned instance will be added to
the ServerCallContext.
If no authentication middleware or no `authenticathedUserExtractor` is
provided to the Server, the user in the ServerCallContext will be of
type UnAuthenticated.

Fixes #194  🦕

Release-As: 0.3.6
2025-11-25 11:39:29 +01:00
Guglielmo Colombo
9d7208250a
build: enable no-explicit-any in eslint (#190)
# Description

The purpose of this PR is removing all the references to keyword 'any'
present in the repository, as it is considered a bad practice. Future
adoptions will be triggered by the linter automatic checks


Fixes #184  🦕
2025-11-20 12:37:07 +01:00
Ivan Shymko
3f8cea066e
chore: set version to 0.3.6 (#191)
Following
https://github.com/googleapis/release-please?tab=readme-ov-file#how-do-i-change-the-version-number.

Release-As: 0.3.6
2025-11-19 15:40:03 +01:00
Guglielmo Colombo
e55c0f4791
fix: handle errors occurred in non-blocking sendMessage (#187)
# Description

This PR fixes the error of server crash in case of error in the event
loop for non blocking event, if the first reply to the client has been
already sent.
Two different error handling strategies are implemented based on the
origin of the error:

1. If the error originates from the pushNotification service, the loop
is not interrupted, and the error is simply printed on the console error
output
2. If the error is originating from the ExecutionEventQueue or from a
taskStore operation (resultManager interaction), the error is
interrupting the loop.
In the catch clause a TaskStatusUpdateEvent is generated, with
taskStatus equal to "failed", if an already existing Task has been
processed by the ResultManager. The new TaskStatusUpdateEvent is saved
in the taskStore. If a new error occurs within this operation, it is
simply printed on the console error output.

Fixes #186  🦕
2025-11-19 10:46:54 +00:00
Ivan Shymko
dc9f7dc832
refactor: extract JSON-RPC specific logic from client (#169)
# Description

Currently `A2AClient` defined in `client.ts` uses JSON-RPC types in its
interface, i.e. `sendMessage` uses
[`SendMessageResponse`](e7e8f35d5d/src/client/client.ts (L207))
which contains [JSON-RPC fields like `id` and `jsonrpc`
version](e7e8f35d5d/src/types.ts (L2177-L2190)).
It was also the case for Python SDK which required introducing a new
[client.py](https://github.com/a2aproject/a2a-python/blob/main/src/a2a/client/client.py)
keeping the old one as
[legacy.py](https://github.com/a2aproject/a2a-python/blob/main/src/a2a/client/legacy.py)
for backward compatibility (see
[#348](https://github.com/a2aproject/a2a-python/pull/348)).

As a first step of introducing a transport-agnostic client, extract
JSON-RPC specific logic into a transport abstraction and switch existing
`A2AClient` to it in a backward compatible way to take advantage of
existing tests.

**Note:** new types are not exported from `index.ts`, this will be done
once new client is ready.

# Changes

1. Define `A2ATransport` abstraction without using JSON-RPC types.
2. Implement `JsonRpcTransport` from existing `A2AClient`.
3. Use new `JsonRpcTransport` from `A2AClient` - new transports are
**not going** to be added into this client as it uses JSON-RPC types.
This is done in a backward compatible way, existing behavior is
preserved: returning JSON-RPC errors as objects, populating JSON-RPC
specific fields.
4. Define shared transport-agnostic errors for A2A specific errors
defined in [the
spec](https://a2a-protocol.org/latest/specification/#82-a2a-specific-errors).

Re #137, #142
2025-11-19 10:00:27 +01:00
Ivan Shymko
4f07c0dad5
build: explicitly install eslint-config-prettier for local linter runs (#189)
# Description

Fix `Error: Cannot find module 'eslint-config-prettier'` when doing `npm
run lint` locally.
2025-11-18 17:49:15 +01:00
Guglielmo Colombo
542c5fba70
ci: integrate prettier check in github workflow (#185)
# Description

This PR integrates the prettier check in the github workflow to ensure
the code respects the correct formatting standards

Fixes #177  🦕

---------

Co-authored-by: Ivan Shymko <vana.shimko@gmail.com>
2025-11-18 17:06:18 +01:00
Guglielmo Colombo
e7e8f35d5d
ci: introduce workflow for linter (#183)
# Description

This pull request introduces a new ESLint configuration file,
`eslint.config.mjs` to standardize code quality and style across the
project.

Here's a summary of the key changes:

- ESLint Setup with TypeScript and Prettier Integration: The
configuration now leverages @eslint/js and typescript-eslint for linting
of TypeScript code. eslint-config-prettier is included to disable any
ESLint rules that might conflict with Prettier's formatting, which will
be included in a new PR.
- Ignored Files: The dist/ and node_modules/ directories are explicitly
ignored to prevent linting of generated output and third-party
dependencies.

Custom Rule Adjustments:

- @typescript-eslint/no-explicit-any is turned off to allow the use of
the any type where necessary.
- @typescript-eslint/no-unused-vars is configured to ignore unused
arguments and caught errors that are prefixed with an underscore (_).
This is a common pattern to signal intentional unused variables.

Test File Specific Rules: 
- @typescript-eslint/no-unused-expressions is turned off to accommodate
testing libraries like Chai, which often use expression-based
assertions.
- @typescript-eslint/no-unsafe-function-type is turned off to allow more
flexible function type usage within test contexts.

Node.js Global Variables: The configuration now includes globals.node to
correctly recognize Node.js global variables, preventing false positives
for undefined variables in Node.js environments.


The changes in other files in this PR are necessary for the linter
checks to pass. They involve mainly the removal of unused parameters.


Re #177  🦕
2025-11-17 16:30:29 +01:00
Guglielmo Colombo
5ef7396075
feat: server side support for extensions (#171)
# Description

The code submitted in the PR introduces the support for extensions on
the server side.

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 #170 🦕

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-11-17 10:13:21 +01:00
dependabot[bot]
2e424e4446
chore(deps-dev): bump js-yaml from 4.1.0 to 4.1.1 (#180)
Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.1.0 to 4.1.1.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md">js-yaml's
changelog</a>.</em></p>
<blockquote>
<h2>[4.1.1] - 2025-11-12</h2>
<h3>Security</h3>
<ul>
<li>Fix prototype pollution issue in yaml merge (&lt;&lt;)
operator.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="cc482e7759"><code>cc482e7</code></a>
4.1.1 released</li>
<li><a
href="50968b862e"><code>50968b8</code></a>
dist rebuild</li>
<li><a
href="d092d86603"><code>d092d86</code></a>
lint fix</li>
<li><a
href="383665ff42"><code>383665f</code></a>
fix prototype pollution in merge (&lt;&lt;)</li>
<li><a
href="0d3ca7a27b"><code>0d3ca7a</code></a>
README.md: HTTP =&gt; HTTPS (<a
href="https://redirect.github.com/nodeca/js-yaml/issues/678">#678</a>)</li>
<li><a
href="49baadd52a"><code>49baadd</code></a>
doc: 'empty' style option for !!null</li>
<li><a
href="ba3460eb9d"><code>ba3460e</code></a>
Fix demo link (<a
href="https://redirect.github.com/nodeca/js-yaml/issues/618">#618</a>)</li>
<li>See full diff in <a
href="https://github.com/nodeca/js-yaml/compare/4.1.0...4.1.1">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=js-yaml&package-manager=npm_and_yarn&previous-version=4.1.0&new-version=4.1.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>
2025-11-17 09:55:13 +01:00
Ivan Shymko
3d23332c26
refactor: extract request handlers from A2AExpressApp (#162)
# Description

As a preparation step for REST support proposed in #142, extract
Express.js handlers from `A2AExpressApp` to allow assembling your own
app using Express.js API directly for specifying individual paths and
middlewares, rather than wrapping it in `A2AExpressApp`:

```ts
// const a2aRequestHandler = . . .

const app = express();

// Minimal example:
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: a2aRequestHandler }));
app.use(jsonRpcHandler({ requestHandler: a2aRequestHandler }));

// Advanced example:
app.use(myCustomMiddleware());
app.use('/.well-known/custom-agent-card.json', myCustomAgentCardMiddleware, agentCardHandler({ agentCardProvider: a2aRequestHandler }));
app.use('/a2a/jsonrpc', myJsonRpcMiddleware, jsonRpcHandler({ requestHandler: a2aRequestHandler }));
app.use('/a2a/api', restHandler({ requestHandler: a2aRequestHandler }));
```

No logic changes to existing handlers, they are moved as is. Also
`A2AExpressApp` is switched to use new handlers without behavior
changes.

**Note:** new functions **are not** exported via `index.ts` yet, it will
be done together with updating docs and examples once REST support is
done.

Re #137
2025-11-12 18:54:41 -08:00
Ivan Shymko
67869e46b3
refactor: do not string match error message thrown in the same block (#167)
# Description

Minor fix in `client.ts` error handling: avoid checking an error thrown
within the same block via a string match. Include `cause` into rethrown
error.
2025-11-07 14:10:50 +01:00
Ivan Shymko
a2238360f6
test: fix deleteTaskPushNotificationConfig test for client (#166)
# Description

According to the
[spec](https://a2a-protocol.org/latest/specification/#79-taskspushnotificationconfigdelete),
`result` field should contain `null` on success. Currently the test
configures mock to return a non-null response which is validated later.

The PR updates the test to reflect the spec.
2025-11-06 17:36:07 +01:00
Agent2Agent (A2A) Bot
9a633164e8
chore(main): release 0.3.5 (#131)
🤖 I have created a release *beep* *boop*
---


## [0.3.5](https://github.com/a2aproject/a2a-js/compare/v0.3.4...v0.3.5)
(2025-11-05)


### Bug Fixes

* cancel/task now returns the expected 'cancelled' task status
([#158](https://github.com/a2aproject/a2a-js/issues/158))
([3eec0bd](3eec0bd98a))
* correct the default value in the agentCardPath comment
([#130](https://github.com/a2aproject/a2a-js/issues/130))
([3279c7b](3279c7bf4d))
* enable follow up task issue on non blocking request
([#160](https://github.com/a2aproject/a2a-js/issues/160))
([352dc05](352dc05851))
* ensure push notifications order
([#141](https://github.com/a2aproject/a2a-js/issues/141))
([22360e6](22360e6ba7))
* ensure user messages are added to existing tasks
([#138](https://github.com/a2aproject/a2a-js/issues/138))
([00fb916](00fb916ca4))
* validate JSON-RPC params
([#155](https://github.com/a2aproject/a2a-js/issues/155))
([5b39f4d](5b39f4dd96))
* validate JSON-RPC request id according to the spec
([#152](https://github.com/a2aproject/a2a-js/issues/152))
([9558c36](9558c3613a))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2025-11-05 15:38:52 +01:00
Guglielmo Colombo
4b8f783f43
feat: Integrate CI workflow for tck mandatory tests (#164)
# Description

This PR introduces a new CI pipeline that will run automatically on
every push and pull request on the main branch. The created pipeline is
responsible for running the tck mandatory tests against the the newly
created sample agent in the tck forlder.

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 #159 🦕
2025-11-05 15:04:56 +01:00
Guglielmo Colombo
3eec0bd98a
fix: cancel/task now returns the expected 'cancelled' task status (#158)
# Description

The current implementation of the cancel/task did not return the task in
'cancelled' status, because it was not consuming all the events on the
eventBus, but was taking the last published one.
This PR fixes this tck
[test](9893cfdb5f/tests/mandatory/protocol/test_tasks_cancel_method.py (L39))

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 #157 🦕
2025-11-03 08:59:55 +01:00
Guglielmo Colombo
352dc05851
fix: enable follow up task issue on non blocking request (#160)
# Description

This PR ensure that when a follow up task is sent to a task in a non
final state using the NON blocking mode, the `_processEvents` will
return the first available Message/Task status published on the bus, and
will not throw an error.
Follows the implementation of [Python
SDK](aa159f3e10/src/a2a/server/tasks/result_aggregator.py (L129))

This PR will make this
[tck-test](https://github.com/guglielmo-san/a2a-tck/blob/test_javascript/a2a-tck/tests/mandatory/protocol/test_message_send_method.py#L150-L151)
pass.
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 #156  🦕
2025-10-31 17:07:13 +01:00
Guglielmo Colombo
5b39f4dd96
fix: validate JSON-RPC params (#155)
# Description

This PR introduces checks on the params received on the request,
according to the
[specifications](https://a2a-protocol.org/latest/specification/#6111-jsonrpcrequest-object).
This change allows to pass the tck mandatory
[test](9893cfdb5f/tests/mandatory/jsonrpc/test_json_rpc_compliance.py (L56)).

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 #154 🦕

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-10-30 12:30:52 +01:00
Guglielmo Colombo
9558c3613a
fix: validate JSON-RPC request id according to the spec (#152)
# Description

This PR adds checks to guarantee the compliance of the request.Id
parameter of JSON-RPC requests with the specifications. The identifier
"MUST contain a String, Number, or NULL value if included, Numbers
SHOULD NOT contain fractional parts."

This change guarantees the compliance of A2A-js as per [tck
tests](9893cfdb5f/tests/mandatory/jsonrpc/test_json_rpc_compliance.py (L59)).

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 #151  🦕
2025-10-30 10:34:14 +01:00
Ivan Shymko
d02864b82e
build: enable noImplicitAny tsc flag (#153)
# Description

Enforce `noImplicitAny` and fix non-compliant code (one occurrence
introduced in #147).
2025-10-29 12:32:27 +01:00
Guglielmo Colombo
22360e6ba7
fix: ensure push notifications order (#141)
# Description

This PR introduces a promise chain (`this.notificationChain`) to
serialize the batches of notifications. This ensures that only one batch
at a time is processed, in a predictable First-In, First-Out (FIFO)
order. The test was already ensuring it and it caused some flakiness
before, examples:
- https://github.com/a2aproject/a2a-js/actions/runs/18750636883 (see top
right corner for first two failed attempts)
- https://github.com/a2aproject/a2a-js/actions/runs/17686476400

The `push_notification_integration.spec.ts` test file has been modified
to simulate a more deterministic delay (100ms) on the completion of the
first received notification. This guarantee a 100% test failure when the
notification serialization is not implemented.

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 #140  🦕

---------

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>
2025-10-29 09:12:14 +01:00
Guglielmo Colombo
cce1a83747
docs: handle startup errors in sample agents (#150)
# Description

This fix implements an error handling in the server start of the sample
agents. In this way it will be possible to see in output the reason
behind the start up failure of the agent.

Fixes #149 🦕
2025-10-28 17:14:29 +01:00
Guglielmo Colombo
840f167b79
fix: handle json parsing errors in express app (#147)
# Description

This PR is adding an error handling middleware to the express server to
handle the error triggered by the
```
router.use(express.json(), ...(middlewares ?? []));
```
and returns and error according to JSON-RPC specification, instead of
the general SyntaxError.
This change is required to guarantee the compliance of A2A-js as per
[tck tests](https://github.com/a2aproject/a2a-tck).

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 #146 🦕
2025-10-28 16:03:07 +01:00
Ivan Shymko
e59a2241af
docs: add client timeout example to readme (#145)
# Description

Was asked in #78, custom fetch implementation added in #33 allows it
now, updating readme as timeout is a common enough scenario.

Fixes #78 🦕
2025-10-27 16:48:27 -07:00
Guglielmo Colombo
3ff2660758
feat: add a hermetic sample (#144)
# Description

This PR introduces a new sample to test the A2A-js in a hermetic way,
without the need of setting up external API keys.
The sample-agent mock the execution of a streaming agent, publishing
updates the status of the task that can be tracked with the `cli.ts`.

Fixes #133 🦕
2025-10-27 14:53:21 +01:00
Ben Clarke
00fb916ca4
fix: ensure user messages are added to existing tasks (#138)
Ensured user messages are added to existing tasks, inline with the
Python package:
- Added the latest user message to an existing `Task`'s history in the
`RequestContext`
- Added the test "should return second task with full history if message
is sent to an existing, non-terminal task"
- Updated `README.md` to check if a `Task` exists before publishing to
the `eventBus`

# 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 #136 🦕
2025-10-23 15:49:56 +02:00
Ronan Takizawa
21048fb042
chore: add testing for A2AExpressApp (#107)
# Description

Add test coverage for A2AExpressApp class.  

Added 19 test cases covering all A2AExpressApp functionality: 
1. Constructor test: Verifies A2AExpressApp instantiates correctly with
requestHandler and
jsonRpcTransportHandler
2. Setup routes default: Tests setupRoutes works with default parameters
and returns the Express app
3. Setup routes custom baseUrl: Tests setupRoutes accepts and uses a
custom baseUrl parameter
4. Setup routes custom middlewares: Tests setupRoutes accepts and
applies custom middleware array
5. Setup routes custom agentCardPath: Tests setupRoutes accepts custom
agentCardPath parameter
6. Agent card GET default: Tests agent card endpoint returns correct
JSON response at default well-known
 path
7. Agent card GET custom path: Tests agent card endpoint works at custom
path when agentCardPath is
specified
8. Agent card error handling: Tests agent card endpoint returns 500
error when getAgentCard fails
9. JSON-RPC single response: Tests POST endpoint handles single JSON-RPC
response correctly
10. JSON-RPC streaming response: Tests POST endpoint handles streaming
responses with Server-Sent Events
11. JSON-RPC streaming error: Tests streaming error handling sends error
event in SSE format
12. JSON-RPC processing error: Tests A2AError handling returns proper
JSON-RPC error response
13. JSON-RPC generic error: Tests non-A2AError fallback returns generic
error response
14. JSON-RPC no ID error: Tests error response includes null ID when
request has no ID
15. Middleware integration: Tests custom middlewares are applied and
called during requests
16. Middleware error handling: Tests middleware errors are properly
handled and return 500
17. Route baseUrl mounting: Tests routes are correctly mounted at
specified baseUrl
18. Route empty baseUrl: Tests routes work correctly when baseUrl is
empty string
19. Express JSON middleware: Tests express.json() middleware is included
by default and parses request
bodies


Dependencies Added:
• Installed supertest and @types/supertest for HTTP endpoint testing

Fixes #105 🦕
2025-09-09 15:17:03 -07:00
hujiulong
3279c7bf4d
fix: correct the default value in the agentCardPath comment (#130)
# Description
The default value of `agentCardPath` does not have a preceding slash.

c055b769d9/src/constants.ts (L8)
2025-09-06 12:01:45 -07:00
Agent2Agent (A2A) Bot
c055b769d9
chore(main): release 0.3.4 (#127)
🤖 I have created a release *beep* *boop*
---


## [0.3.4](https://github.com/a2aproject/a2a-js/compare/v0.3.3...v0.3.4)
(2025-09-04)


### Features

* add list and delete task push notification config rpc method and
custom rpc methods for extensions
([#119](https://github.com/a2aproject/a2a-js/issues/119))
([26c4e7d](26c4e7df48))
* Added push notifications support
([#108](https://github.com/a2aproject/a2a-js/issues/108))
([45a211a](45a211a738))


### Miscellaneous Chores

* release 0.3.4
([#128](https://github.com/a2aproject/a2a-js/issues/128))
([41791d9](41791d99a4))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2025-09-04 11:25:08 -07:00
swapydapy
41791d99a4
chore: release 0.3.4 (#128)
Release-As: 0.3.4
2025-09-03 21:36:03 -07:00
hasm
26c4e7df48
feat: add list and delete task push notification config rpc method and custom rpc methods for extensions (#119)
- Added missing standard rpc methods defined:
- `tasks/pushNotificationConfig/list`
- `tasks/pushNotificationConfig/delete`
- additionally, exposing generic method to support custom rpc methods 

Fixes #118 🦕
2025-09-03 21:31:27 -07:00
Raunak Sett
45a211a738
feat: Added push notifications support (#108)
Release-As: 0.3.4

# Description

Added push notifications support in the Server sdk.
Defines the configuration for setting up push notifications for task
updates.

Added an `InMemoryPushNotificationStore`, refactored from within the
`DefaultRequestHandler`.
Provided interface for push notification store which can be extended
Added a default implementation in `DefaultRequestHandler`.

Added support when pushNotification config available in
`messageSendParams`

Existing push notification tests still pass
Added new test to ensure push notifications are being called


Fixes #89  🦕
2025-08-31 16:53:33 -07:00
Agent2Agent (A2A) Bot
caeefecdde
chore(main): release 0.3.3 (#122)
🤖 I have created a release *beep* *boop*
---


## [0.3.3](https://github.com/a2aproject/a2a-js/compare/v0.3.2...v0.3.3)
(2025-08-27)


### ⚠ BREAKING CHANGES

* Update A2AClient constructor to initialize with full agentCardUrl
([#121](https://github.com/a2aproject/a2a-js/issues/121))

### Features

* Update A2AClient constructor to initialize with full agentCardUrl
([#121](https://github.com/a2aproject/a2a-js/issues/121))
([755044c](755044c6c6))


### Bug Fixes

* Improve fetch implementation handling
([#117](https://github.com/a2aproject/a2a-js/issues/117))
([09adbd3](09adbd31d1))


### Miscellaneous Chores

* release 0.3.3
([#124](https://github.com/a2aproject/a2a-js/issues/124))
([ea59193](ea59193290))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2025-08-27 13:10:51 -07:00
swapydapy
ea59193290
chore: release 0.3.3 (#124)
Release-As: 0.3.3
2025-08-27 13:05:38 -07:00
swapydapy
de4dbe07bf
chore: cleanup readme (#123)
Release-As: 0.3.3

Break up readme sample code into targeted section.
2025-08-27 12:17:36 -07:00
Ajay Nagotha
09adbd31d1
fix: Improve fetch implementation handling (#117)
Use `fetch` directly from global context instead of saving an unbound reference to it.
2025-08-27 11:37:37 -07:00
Adam Weidman
755044c6c6
feat!: Update A2AClient constructor to initialize with full agentCardUrl (#121)
# Description

- Breaking Change: A2AClient Constructor initialized with full agentCard
rather than `baseUrl` and `agent_card_path`. This previously led to an
error where the baseUrl had to be the baseUrl of the full agent card,
rather than the serviceUrl (which is set by the AgentCard itself).
- Static Method to load A2AClient from agentCardUrl.
- Cleanup trailing spaces at the start of new lines
2025-08-26 12:16:36 -07:00
Adam Weidman
de401038fe
chore: repin express to 5.1 and express types to 5.0.3 (#115)
peerDependency allow both express 4 & 5. Current routes is compatible with both express 4 & express 5.
2025-08-20 09:48:46 -07:00
Agent2Agent (A2A) Bot
1168117482
chore(main): release 0.3.2 (#106)
🤖 I have created a release *beep* *boop*
---


## [0.3.2](https://github.com/a2aproject/a2a-js/compare/v0.3.1...v0.3.2)
(2025-08-17)


### Features

* Added generic client hooks for HTTP based authentication, and improved
agent.json resolution
([#33](https://github.com/a2aproject/a2a-js/issues/33))
([a9826ac](a9826acde3))


### Bug Fixes

* fix Incorrect Well-Known Path for Agent Card
([#102](https://github.com/a2aproject/a2a-js/issues/102))
([3a0f1d0](3a0f1d0784))


### Miscellaneous Chores

* release 0.3.2
([#111](https://github.com/a2aproject/a2a-js/issues/111))
([03f35e0](03f35e0ed2))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2025-08-17 15:27:18 -07:00
swapydapy
03f35e0ed2
chore: release 0.3.2 (#111)
Release-As: 0.3.2
2025-08-17 15:26:14 -07:00
Mike Prince
a9826acde3
feat: Added generic client hooks for HTTP based authentication, and improved agent.json resolution (#33)
This PR allows specifying custom fetch & a particular implementation of auth handler.

This PR also improves the client agent card resolution. Previously the
card was always found at <agentpath>/.well-known/agent.json which is
only correct for agents at the URL path root.

---------

Co-authored-by: swapydapy <agarwal.swapy@gmail.com>
2025-08-17 15:09:26 -07:00
Ronan Takizawa
3a0f1d0784
fix: fix Incorrect Well-Known Path for Agent Card (#102)
# Description

Fix the well-known path for agent card from `/.well-known/agent.json` to
`/.well-known/agent-card.json`

Fixes #99  🦕
2025-08-10 21:54:06 -07:00
Holt Skinner
37d93742de
ci: Add Conventional Commits Action (#103)
Google GitHub App will be deprecated
2025-08-08 12:33:00 +01:00
swapydapy
118abae80f
chore: fix repository url in package.json (#98) 2025-08-06 14:11:50 -07:00
Agent2Agent (A2A) Bot
1a5432d461
chore(main): release 0.3.1 (#97)
🤖 I have created a release *beep* *boop*
---


## [0.3.1](https://github.com/a2aproject/a2a-js/compare/v0.3.0...v0.3.1)
(2025-08-06)


### Bug Fixes

* add missing express entrypoint to tsup config
([#96](https://github.com/a2aproject/a2a-js/issues/96))
([8e990e4](8e990e4979))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2025-08-06 14:01:56 -07:00
ajaynagotha
8e990e4979
fix: add missing express entrypoint to tsup config (#96)
# Description

- Add Missing Express entrypoint to tsup config to fix import issues

Fixes #94  🦕

Co-authored-by: swapydapy <agarwal.swapy@gmail.com>
2025-08-06 13:52:57 -07:00
Jedr Blaszyk
fd30c507da
docs: Add protocolVersion to agent card in readme (#95)
# Description

Include `protocolVersion` in `AgentCard` in docs. This is a required
property according to type definition in `0.3.0` js sdk. Otherwise there are
 linter errors.
2025-08-06 11:31:28 -07:00
swapydapy
19e0d75038
chore: Add permission for npm provenance (#93) 2025-08-05 11:13:24 -07:00
Agent2Agent (A2A) Bot
92a2c9b051
chore(main): release 0.3.0 (#92)
🤖 I have created a release *beep* *boop*
---


## [0.3.0](https://github.com/a2aproject/a2a-js/compare/v0.2.5...v0.3.0)
(2025-08-05)


### ⚠ BREAKING CHANGES

* upgrade to a2a 0.3.0 spec version
([#87](https://github.com/a2aproject/a2a-js/issues/87))
* make Express dependency optional

### Features

* make Express dependency optional
([60899c5](60899c51e2))
* upgrade to a2a 0.3.0 spec version
([#87](https://github.com/a2aproject/a2a-js/issues/87))
([ae53da1](ae53da1e36))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
2025-08-05 10:46:18 -07:00
Holt Skinner
b0ea294999
ci: Add PAT to release-please (#91)
Follow-up to #90
2025-08-05 17:28:11 +01:00
Holt Skinner
654d674872
ci: Update release-please to use GitHub Action (#90) 2025-08-05 09:17:42 -07:00
148 changed files with 47370 additions and 9201 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)"
]
}
}

2
.github/CODEOWNERS vendored
View File

@ -4,4 +4,4 @@
# For syntax help see:
# https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax
* @google-a2a/googlers
* @a2aproject/google-a2a-js

View File

@ -1,2 +0,0 @@
enabled: true
always_check_pr_title: true

30
.github/workflows/build-tests.yml vendored Normal file
View File

@ -0,0 +1,30 @@
# Ensures no accidential Node.js API usage in browser and Edge compatible entrypoints.
name: Run Build Tests
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
paths-ignore:
- '**.md'
- 'LICENSE'
- '.github/CODEOWNERS'
- 'test/**'
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
- run: npm ci
- run: npm run build
- run: npm run test-build

View File

@ -0,0 +1,26 @@
name: "Conventional Commits"
on:
pull_request:
types:
- opened
- edited
- synchronize
permissions:
contents: read
jobs:
main:
permissions:
pull-requests: read
statuses: write
name: Validate PR Title
runs-on: ubuntu-latest
steps:
- name: semantic-pull-request
uses: amannn/action-semantic-pull-request@v5.5.3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
validateSingleCommit: false

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
});
}

29
.github/workflows/lint.yml vendored Normal file
View File

@ -0,0 +1,29 @@
name: Run Linter & Formatter
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
paths-ignore:
- '**.md'
- 'LICENSE'
- '.github/CODEOWNERS'
jobs:
eslint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
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:ci

View File

@ -10,12 +10,16 @@ on:
jobs:
publish-npm:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
- run: npm ci
- run: npm run build

View File

@ -15,4 +15,5 @@ jobs:
steps:
- uses: googleapis/release-please-action@v4
with:
token: ${{ secrets.A2A_BOT_PAT }}
release-type: node

121
.github/workflows/run-tck.yaml vendored Normal file
View File

@ -0,0 +1,121 @@
name: Run TCK
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
paths-ignore:
- '**.md'
- 'LICENSE'
- '.github/CODEOWNERS'
- 'test/**'
- 'src/samples/**'
env:
# Tag of the TCK
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
SUT_BASE_URL: http://localhost:41241
# Base URL for the SUT agent JSON-RPC transport
SUT_JSONRPC_URL: http://localhost:41241/a2a/jsonrpc
# Slow system on CI
TCK_STREAMING_TIMEOUT: 5.0
# Only run the latest job
concurrency:
group: '${{ github.workflow }} @ ${{ github.head_ref || github.ref }}'
cancel-in-progress: true
jobs:
tck-test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18, 20, 22, 24]
steps:
- name: Checkout a2a-js
uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
- run: |
npm ci
npm run build
- name: Checkout a2a-tck
uses: actions/checkout@v4
with:
repository: a2aproject/a2a-tck
path: tck/a2a-tck
ref: ${{ env.TCK_VERSION }}
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version-file: "tck/a2a-tck/pyproject.toml"
- name: Install uv and Python dependencies
run: |
pip install uv
uv pip install -e .
working-directory: tck/a2a-tck
- name: Start SUT
run: |
cd tck
npm run tck:sut-agent &
- name: Wait for SUT to start
run: |
URL="${{ env.SUT_BASE_URL }}/.well-known/agent-card.json"
EXPECTED_STATUS=200
TIMEOUT=120
RETRY_INTERVAL=2
START_TIME=$(date +%s)
while true; do
# Calculate elapsed time
CURRENT_TIME=$(date +%s)
ELAPSED_TIME=$((CURRENT_TIME - START_TIME))
# Check for timeout
if [ "$ELAPSED_TIME" -ge "$TIMEOUT" ]; then
echo "❌ Timeout: Server did not respond with status $EXPECTED_STATUS within $TIMEOUT seconds."
exit 1
fi
# Get HTTP status code. || true is to reporting a failure to connect as an error
HTTP_STATUS=$(curl --output /dev/null --silent --write-out "%{http_code}" "$URL") || true
echo "STATUS: ${HTTP_STATUS}"
# Check if we got the correct status code
if [ "$HTTP_STATUS" -eq "$EXPECTED_STATUS" ]; then
echo "✅ Server is up! Received status $HTTP_STATUS after $ELAPSED_TIME seconds."
break;
fi
# Wait before retrying
echo "⏳ Server not ready (status: $HTTP_STATUS). Retrying in $RETRY_INTERVAL seconds..."
sleep "$RETRY_INTERVAL"
done
- name: Run TCK (mandatory)
id: run-tck-mandatory
timeout-minutes: 5
run: |
./run_tck.py --sut-url ${{ env.SUT_JSONRPC_URL }} --category mandatory --transports jsonrpc,rest,grpc
working-directory: tck/a2a-tck
- name: Run TCK (capabilities)
id: run-tck-capabilities
timeout-minutes: 5
run: |
./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()
run: |
# Find and kill the SUT process
pkill -f "npm run tck:sut-agent" || true
sleep 2

View File

@ -5,21 +5,108 @@ 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:
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
matrix:
node-version: [18, 20, 22, 24]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
node-version: ${{ matrix.node-version }}
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
- run: npm ci
- run: npm test
# Edge runtime tests use @edge-runtime/vm to emulate Cloudflare Workers,
# Vercel Edge Functions, and similar environments. This ensures the SDK
# works correctly in non-Node.js server environments.
test-edge:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
- run: npm ci
- run: npm run test:edge
# The vitest 4.0.x test coverage integration doesn't support Node 18,
# Node 18 has reached EOL already, however for compatibility we're still going to run tests
# for Node 18 until the next major release (see https://github.com/a2aproject/a2a-js/pull/256).
# Run coverage only once on a modern node to generate a report to avoid downgrading vitest.
coverage:
runs-on: ubuntu-latest
steps:
- name: Checkout Base Branch
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.base.ref || 'main' }}
clean: true
- 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-base-summary.json
- name: Upload Artifact (base)
uses: actions/upload-artifact@v4
if: github.event_name != 'pull_request'
with:
name: coverage-report
path: coverage
retention-days: 14
- name: Checkout PR Branch
if: github.event_name == 'pull_request'
uses: actions/checkout@v4
with:
clean: true
- name: Install & Test (PR)
if: github.event_name == 'pull_request'
timeout-minutes: 10
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: 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-data
path: |
coverage-base-summary.json
coverage-pr-summary.json
coverage/
PR_NUMBER
retention-days: 1

1
.gitignore vendored
View File

@ -179,3 +179,4 @@ testem.log
# System files
.DS_Store
Thumbs.db
.nyc_output/

7
.prettierrc.json Normal file
View File

@ -0,0 +1,7 @@
{
"trailingComma": "es5",
"semi": true,
"singleQuote": true,
"printWidth": 100,
"tabWidth": 2
}

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,188 @@
# 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)
### Features
* add support for extendedAgentCard on client side ([#234](https://github.com/a2aproject/a2a-js/issues/234)) ([3073376](https://github.com/a2aproject/a2a-js/commit/3073376f7c311f0c13c51c129d7065249735517a))
* Add support for extension headers on client side ([#227](https://github.com/a2aproject/a2a-js/issues/227)) ([8c57002](https://github.com/a2aproject/a2a-js/commit/8c57002add3b25387da899df7a610098b0f4e01b))
* implement client interceptors ([#223](https://github.com/a2aproject/a2a-js/issues/223)) ([5694c22](https://github.com/a2aproject/a2a-js/commit/5694c22e3bccba87137c5b4ad1b3011f9e30dcd0))
* Implement extended card support on server side ([#197](https://github.com/a2aproject/a2a-js/issues/197)) ([45014ac](https://github.com/a2aproject/a2a-js/commit/45014ac4a192ad3c6120849577530d1d63eb27b8))
* implement server http+json ([#142](https://github.com/a2aproject/a2a-js/issues/142)) ([f20e662](https://github.com/a2aproject/a2a-js/commit/f20e66247d3c962144d77e98e7720d6041537533))
* introduce AgentCardResolver ([#225](https://github.com/a2aproject/a2a-js/issues/225)) ([ddaf7de](https://github.com/a2aproject/a2a-js/commit/ddaf7ded169ccc285051eeb63088dc697e6ae93e))
* introduce transport agnostic client ([#198](https://github.com/a2aproject/a2a-js/issues/198)) ([94a9848](https://github.com/a2aproject/a2a-js/commit/94a98483998a62669140de9bfbdde483787fa065))
* server side support for extensions ([5ef7396](https://github.com/a2aproject/a2a-js/commit/5ef73960758b78ed2a52356a10cb35cadeb440bd))
* support authentication on server side ([#195](https://github.com/a2aproject/a2a-js/issues/195)) ([9872d93](https://github.com/a2aproject/a2a-js/commit/9872d93622e12efb7369d7e658cec7ab4fd8590c))
### Bug Fixes
* handle errors occurred in non-blocking sendMessage ([#187](https://github.com/a2aproject/a2a-js/issues/187)) ([e55c0f4](https://github.com/a2aproject/a2a-js/commit/e55c0f4791b556cc42e256073cf9018d1ec18cca))
### Miscellaneous Chores
* set version to 0.3.6 ([#191](https://github.com/a2aproject/a2a-js/issues/191)) ([3f8cea0](https://github.com/a2aproject/a2a-js/commit/3f8cea066efa59ae38ac405801884b9b5037841b))
## [0.3.5](https://github.com/a2aproject/a2a-js/compare/v0.3.4...v0.3.5) (2025-11-05)
### Bug Fixes
* cancel/task now returns the expected 'cancelled' task status ([#158](https://github.com/a2aproject/a2a-js/issues/158)) ([3eec0bd](https://github.com/a2aproject/a2a-js/commit/3eec0bd98ab02f8d76c4b01dc8ea8351bc8f1a07))
* correct the default value in the agentCardPath comment ([#130](https://github.com/a2aproject/a2a-js/issues/130)) ([3279c7b](https://github.com/a2aproject/a2a-js/commit/3279c7bf4de088950c81aaeccb1cfaca5ee26284))
* enable follow up task issue on non blocking request ([#160](https://github.com/a2aproject/a2a-js/issues/160)) ([352dc05](https://github.com/a2aproject/a2a-js/commit/352dc0585122db341da93b5fbd2f8cf7acf7fcca))
* ensure push notifications order ([#141](https://github.com/a2aproject/a2a-js/issues/141)) ([22360e6](https://github.com/a2aproject/a2a-js/commit/22360e6ba735b10c611b5881ea8f98c898622117))
* ensure user messages are added to existing tasks ([#138](https://github.com/a2aproject/a2a-js/issues/138)) ([00fb916](https://github.com/a2aproject/a2a-js/commit/00fb916ca4b877b11b3153d67593027e508c3d64))
* validate JSON-RPC params ([#155](https://github.com/a2aproject/a2a-js/issues/155)) ([5b39f4d](https://github.com/a2aproject/a2a-js/commit/5b39f4dd96b619e1683c0f2226279d20572f2a27))
* validate JSON-RPC request id according to the spec ([#152](https://github.com/a2aproject/a2a-js/issues/152)) ([9558c36](https://github.com/a2aproject/a2a-js/commit/9558c3613a0e5c8c48743412b0c47f9480345666))
## [0.3.4](https://github.com/a2aproject/a2a-js/compare/v0.3.3...v0.3.4) (2025-09-04)
### Features
* add list and delete task push notification config rpc method and custom rpc methods for extensions ([#119](https://github.com/a2aproject/a2a-js/issues/119)) ([26c4e7d](https://github.com/a2aproject/a2a-js/commit/26c4e7df48e0cd1088a9340ddc34bfbed320664c))
* Added push notifications support ([#108](https://github.com/a2aproject/a2a-js/issues/108)) ([45a211a](https://github.com/a2aproject/a2a-js/commit/45a211a738ea7770ec5ee8b10a1238060ba7a471))
### Miscellaneous Chores
* release 0.3.4 ([#128](https://github.com/a2aproject/a2a-js/issues/128)) ([41791d9](https://github.com/a2aproject/a2a-js/commit/41791d99a4c7776ac3ee183d3e834df31a2020ac))
## [0.3.3](https://github.com/a2aproject/a2a-js/compare/v0.3.2...v0.3.3) (2025-08-27)
### ⚠ BREAKING CHANGES
* Update A2AClient constructor to initialize with full agentCardUrl ([#121](https://github.com/a2aproject/a2a-js/issues/121))
### Features
* Update A2AClient constructor to initialize with full agentCardUrl ([#121](https://github.com/a2aproject/a2a-js/issues/121)) ([755044c](https://github.com/a2aproject/a2a-js/commit/755044c6c610991b5c86747da72b24e1fff9ade3))
### Bug Fixes
* Improve fetch implementation handling ([#117](https://github.com/a2aproject/a2a-js/issues/117)) ([09adbd3](https://github.com/a2aproject/a2a-js/commit/09adbd31d1ef7a73e4c8c87045af84bb1280226f))
### Miscellaneous Chores
* release 0.3.3 ([#124](https://github.com/a2aproject/a2a-js/issues/124)) ([ea59193](https://github.com/a2aproject/a2a-js/commit/ea591932901742af76afb5aeee4cf8d27cc9a6c2))
## [0.3.2](https://github.com/a2aproject/a2a-js/compare/v0.3.1...v0.3.2) (2025-08-17)
### Features
* Added generic client hooks for HTTP based authentication, and improved agent.json resolution ([#33](https://github.com/a2aproject/a2a-js/issues/33)) ([a9826ac](https://github.com/a2aproject/a2a-js/commit/a9826acde3bb1f741153407e6179fd21f2e7a4bb))
### Bug Fixes
* fix Incorrect Well-Known Path for Agent Card ([#102](https://github.com/a2aproject/a2a-js/issues/102)) ([3a0f1d0](https://github.com/a2aproject/a2a-js/commit/3a0f1d07843b725c9beaf1078bc43418ff2871ed))
### Miscellaneous Chores
* release 0.3.2 ([#111](https://github.com/a2aproject/a2a-js/issues/111)) ([03f35e0](https://github.com/a2aproject/a2a-js/commit/03f35e0ed29d2b24df7eddb2a7fe21d0690f503e))
## [0.3.1](https://github.com/a2aproject/a2a-js/compare/v0.3.0...v0.3.1) (2025-08-06)
### Bug Fixes
* add missing express entrypoint to tsup config ([#96](https://github.com/a2aproject/a2a-js/issues/96)) ([8e990e4](https://github.com/a2aproject/a2a-js/commit/8e990e497927e3554699f8ebb005829b170d9bc3))
## [0.3.0](https://github.com/a2aproject/a2a-js/compare/v0.2.5...v0.3.0) (2025-08-05)
### ⚠ BREAKING CHANGES
* upgrade to a2a 0.3.0 spec version ([#87](https://github.com/a2aproject/a2a-js/issues/87))
* make Express dependency optional
### Features
* make Express dependency optional ([60899c5](https://github.com/a2aproject/a2a-js/commit/60899c51e2910570402d1207f6b50952bed8862f))
* upgrade to a2a 0.3.0 spec version ([#87](https://github.com/a2aproject/a2a-js/issues/87)) ([ae53da1](https://github.com/a2aproject/a2a-js/commit/ae53da1e36ff58912e01fefa854c5b3174edf7d8))
## [0.2.5](https://github.com/a2aproject/a2a-js/compare/v0.2.4...v0.2.5) (2025-07-30)

View File

@ -2,27 +2,6 @@
We'd love to accept your patches and contributions to this project.
## Before you begin
### Sign our Contributor License Agreement
Contributions to this project must be accompanied by a
[Contributor License Agreement](https://cla.developers.google.com/about) (CLA).
You (or your employer) retain the copyright to your contribution; this simply
gives us permission to use and redistribute your contributions as part of the
project.
If you or your current employer have already signed the Google CLA (even if it
was for a different project), you probably don't need to do it again.
Visit <https://cla.developers.google.com/> to see your current agreements or to
sign a new one.
### Review our community guidelines
This project follows
[Google's Open Source Community Guidelines](https://opensource.google/conduct/).
## Contribution process
### Code reviews
@ -47,11 +26,3 @@ Here are some additional things to keep in mind during the process:
- **Test your changes.** Before you submit a pull request, make sure that your changes work as expected.
- **Be patient.** It may take some time for your pull request to be reviewed and merged.
---
## For Google Employees
Complete the following steps to register your GitHub account and be added as a contributor to this repository.
1. Register your GitHub account at [go/GitHub](http://go/github)

1041
README.md

File diff suppressed because it is too large Load Diff

43
eslint.config.mjs Normal file
View File

@ -0,0 +1,43 @@
// @ts-check
import eslint from '@eslint/js';
import { defineConfig } from 'eslint/config';
import tseslint from 'typescript-eslint';
import eslintPluginPrettier from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
export default defineConfig(
eslint.configs.recommended,
tseslint.configs.recommended,
eslintPluginPrettier, // Automatically disables eslint formatting rules and enables `prettier`
{
ignores: ['dist/', 'node_modules/', 'src/types.ts', 'build/'],
},
{
rules: {
'@typescript-eslint/no-unused-vars': [
'error',
{
// Ignore error for unused args and caught errors if with '_' prefix
argsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
},
},
{
files: ['test/**/*.ts', 'src/samples/**/*.ts'],
rules: {
'@typescript-eslint/no-explicit-any': 'off', // Allow the usage of `any` in the test files and in samples
'@typescript-eslint/no-unused-expressions': 'off', // Allow unused expressions in test files, for compatibility with 'chai'
},
},
{
languageOptions: {
globals: {
// Define global variables for Node.js environment
...globals.node,
},
},
}
);

10894
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,14 +1,37 @@
{
"name": "@a2a-js/sdk",
"version": "0.2.5",
"version": "0.3.13",
"description": "Server & Client SDK for Agent2Agent protocol",
"repository": "google-a2a/a2a-js.git",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/a2aproject/a2a-js.git"
},
"engines": {
"node": ">=18"
},
"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",
@ -25,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": [
@ -37,47 +70,59 @@
"README.md"
],
"devDependencies": {
"@genkit-ai/googleai": "^1.8.0",
"@genkit-ai/vertexai": "^1.8.0",
"@types/chai": "^5.2.2",
"@types/express": "^4.17.23",
"@types/mocha": "^10.0.10",
"@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",
"c8": "^10.1.3",
"chai": "^5.2.0",
"express": "^4.21.2",
"genkit": "^1.8.0",
"gts": "^6.0.2",
"@types/supertest": "^6.0.3",
"@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",
"json-schema-to-typescript": "^15.0.4",
"mocha": "^11.6.0",
"sinon": "^20.0.0",
"prettier": "^3.6.2",
"supertest": "^7.1.4",
"tsup": "^8.5.0",
"tsx": "^4.19.3",
"typescript": "^5.8.2"
"typescript": "^5.9.3",
"typescript-eslint": "^8.46.4",
"vitest": "^3.2.4"
},
"scripts": {
"clean": "gts clean",
"build": "tsup",
"pretest": "npm run build",
"test": "mocha test/**/*.spec.ts",
"coverage": "c8 npm run test",
"test": "vitest run",
"test:edge": "vitest run --config vitest.edge.config.ts",
"lint": "tsc --noEmit && npx eslint . --fix && betterer precommit",
"lint:ci": "tsc --noEmit && npx eslint . && betterer ci",
"format:readme": "prettier --write ./README.md",
"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",
"sample:cli": "tsx src/samples/cli.ts",
"sample:movie-agent": "tsx src/samples/agents/movie-agent/index.ts"
"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": {
"express": "^4.21.2"
"@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
}
},
"mocha": {
"require": "tsx"
}
}

View File

@ -1,4 +1,4 @@
import { compile, compileFromFile } from 'json-schema-to-typescript'
import { compile } from 'json-schema-to-typescript';
import fs from 'fs';
import path from 'path';
@ -6,9 +6,8 @@ const typeSchemaContents = fs.readFileSync(path.join(process.cwd(), 'spec.json')
const typeSchema = JSON.parse(typeSchemaContents.toString());
compile(typeSchema, 'MySchema', {
additionalProperties: false,
enableConstEnums: false,
unreachableDefinitions: true,
unknownAny: true,
})
.then(ts => fs.writeFileSync('src/types.ts', ts))
additionalProperties: false,
enableConstEnums: false,
unreachableDefinitions: true,
unknownAny: true,
}).then((ts) => fs.writeFileSync('src/types.ts', ts));

View File

@ -1,4 +1,15 @@
import { SendMessageResponse, SendStreamingMessageResponse, GetTaskResponse, CancelTaskResponse, SetTaskPushNotificationConfigResponse, GetTaskPushNotificationConfigResponse, JSONRPCErrorResponse, ListTaskPushNotificationConfigSuccessResponse, DeleteTaskPushNotificationConfigSuccessResponse, GetAuthenticatedExtendedCardSuccessResponse } from "./types.js";
import {
SendMessageResponse,
SendStreamingMessageResponse,
GetTaskResponse,
CancelTaskResponse,
SetTaskPushNotificationConfigResponse,
GetTaskPushNotificationConfigResponse,
JSONRPCErrorResponse,
ListTaskPushNotificationConfigSuccessResponse,
DeleteTaskPushNotificationConfigSuccessResponse,
GetAuthenticatedExtendedCardSuccessResponse,
} from './types.js';
/**
* Represents any valid JSON-RPC response defined in the A2A protocol.
@ -14,4 +25,3 @@ export type A2AResponse =
| DeleteTaskPushNotificationConfigSuccessResponse
| GetAuthenticatedExtendedCardSuccessResponse
| JSONRPCErrorResponse; // Catch-all for other error responses

116
src/client/auth-handler.ts Normal file
View File

@ -0,0 +1,116 @@
export interface HttpHeaders {
[key: string]: string;
}
/**
* Generic interface for handling authentication for HTTP requests.
*
* - For each HTTP request, this handler is called to provide additional headers to the request through
* the headers() function.
* - After the server returns a response, the shouldRetryWithHeaders() function is called. Usually this
* function responds to a 401 or 403 response or JSON-RPC codes, but can respond to any other signal -
* that is an implementation detail of the AuthenticationHandler.
* - If the shouldRetryWithHeaders() function returns new headers, then the request should retried with the provided
* revised headers. These provisional headers may, or may not, be optimistically stored for subsequent requests -
* that is an implementation detail of the AuthenticationHandler.
* - If the request is successful and the onSuccessfulRetry() is defined, then the onSuccessfulRetry() function is
* called with the headers that were used to successfully complete the request. This callback provides an
* opportunity to save the headers for subsequent requests if they were not already saved.
*
*/
export interface AuthenticationHandler {
/**
* Provides additional HTTP request headers.
* @returns HTTP headers which may include Authorization if available.
*/
headers: () => Promise<HttpHeaders>;
/**
* For every HTTP response (even 200s) the shouldRetryWithHeaders() method is called.
* This method is supposed to check if the request needs to be retried and if, yes,
* return a set of headers. An A2A server might indicate auth failures in its response
* by JSON-rpc codes, HTTP codes like 401, 403 or headers like WWW-Authenticate.
*
* @param req The RequestInit object used to invoke fetch()
* @param res The fetch Response object
* @returns If the HTTP request should be retried then returns the HTTP headers to use,
* or returns undefined if no retry should be made.
*/
shouldRetryWithHeaders: (req: RequestInit, res: Response) => Promise<HttpHeaders | undefined>;
/**
* If the last HTTP request using the headers from shouldRetryWithHeaders() was successful, and
* this function is implemented, then it will be called with the headers provided from
* shouldRetryWithHeaders().
*
* This callback allows transient headers to be saved for subsequent requests only when they
* are validated by the server.
*/
onSuccessfulRetry?: (headers: HttpHeaders) => Promise<void>;
}
/**
* Higher-order function that wraps fetch with authentication handling logic.
* Returns a new fetch function that automatically handles authentication retries for 401/403 responses.
*
* @param fetchImpl The underlying fetch implementation to wrap
* @param authHandler Authentication handler for managing auth headers and retries
* @returns A new fetch function with authentication handling capabilities
*
* Usage examples:
* - const authFetch = createAuthHandlingFetch(fetch, authHandler);
* - const response = await authFetch(url, options);
* - const response = await authFetch(url); // Direct function call
*/
export function createAuthenticatingFetchWithRetry(
fetchImpl: typeof fetch,
authHandler: AuthenticationHandler
): typeof fetch {
/**
* Executes a fetch request with authentication handling.
* If the auth handler provides new headers for the shouldRetryWithHeaders() function,
* then the request is retried.
* @param url The URL to fetch
* @param init The fetch request options
* @returns A Promise that resolves to the Response
*/
async function authFetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// Merge auth headers with provided headers
const authHeaders = (await authHandler.headers()) || {};
const mergedInit: RequestInit = {
...(init || {}),
headers: {
...authHeaders,
...(init?.headers || {}),
},
};
let response = await fetchImpl(url, mergedInit);
// Check if the auth handler wants to retry the request with new headers
const updatedHeaders = await authHandler.shouldRetryWithHeaders(mergedInit, response);
if (updatedHeaders) {
// Retry request with revised headers
const retryInit: RequestInit = {
...(init || {}),
headers: {
...updatedHeaders,
...(init?.headers || {}),
},
};
response = await fetchImpl(url, retryInit);
if (response.ok && authHandler.onSuccessfulRetry) {
await authHandler.onSuccessfulRetry(updatedHeaders); // Remember headers that worked
}
}
return response;
}
// Copy fetch properties to maintain compatibility
Object.setPrototypeOf(authFetch, Object.getPrototypeOf(fetchImpl));
Object.defineProperties(authFetch, Object.getOwnPropertyDescriptors(fetchImpl));
return authFetch;
}

108
src/client/card-resolver.ts Normal file
View File

@ -0,0 +1,108 @@
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;
fetchImpl?: typeof fetch;
}
export interface AgentCardResolver {
/**
* Fetches the agent card based on provided base URL and path,
*/
resolve(baseUrl: string, path?: string): Promise<AgentCard>;
}
export class DefaultAgentCardResolver implements AgentCardResolver {
constructor(public readonly options?: AgentCardResolverOptions) {}
/**
* Fetches the agent card based on provided base URL and path.
* Path is selected in the following order:
* 1) path parameter
* 2) path from options
* 3) .well-known/agent-card.json
*/
async resolve(baseUrl: string, path?: string): Promise<AgentCard> {
const agentCardUrl = new URL(path ?? this.options?.path ?? AGENT_CARD_PATH, baseUrl);
const response = await this.fetchImpl(agentCardUrl);
if (!response.ok) {
throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status}`);
}
const rawCard = await response.json();
return this.normalizeAgentCard(rawCard);
}
private fetchImpl(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
if (this.options?.fetchImpl) {
return this.options.fetchImpl(...args);
}
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 = {
default: new DefaultAgentCardResolver(),
};

View File

@ -1,88 +1,376 @@
import {
AgentCard,
AgentCapabilities,
JSONRPCRequest,
JSONRPCResponse,
JSONRPCSuccessResponse,
JSONRPCError,
JSONRPCErrorResponse,
Message,
Task,
TaskStatusUpdateEvent,
TaskArtifactUpdateEvent,
MessageSendParams,
SendMessageResponse,
SendStreamingMessageResponse,
SendStreamingMessageSuccessResponse,
TaskQueryParams,
GetTaskResponse,
GetTaskSuccessResponse,
TaskIdParams,
CancelTaskResponse,
CancelTaskSuccessResponse,
TaskPushNotificationConfig, // Renamed from PushNotificationConfigParams for direct schema alignment
SetTaskPushNotificationConfigRequest,
SetTaskPushNotificationConfigResponse,
SetTaskPushNotificationConfigSuccessResponse,
GetTaskPushNotificationConfigRequest,
GetTaskPushNotificationConfigResponse,
GetTaskPushNotificationConfigSuccessResponse,
TaskResubscriptionRequest,
A2AError,
SendMessageSuccessResponse
ListTaskPushNotificationConfigParams,
ListTaskPushNotificationConfigResponse,
DeleteTaskPushNotificationConfigResponse,
DeleteTaskPushNotificationConfigParams,
Message,
Task,
TaskArtifactUpdateEvent,
TaskStatusUpdateEvent,
A2ARequest,
JSONRPCErrorResponse,
} from '../types.js'; // Assuming schema.ts is in the same directory or appropriately pathed
import { AGENT_CARD_PATH } from '../constants.js';
import { JsonRpcTransport } from './transports/json_rpc_transport.js';
import { RequestOptions } from './multitransport-client.js';
// Helper type for the data yielded by streaming methods
type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
export type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
export type SendMessageResult = Message | Task;
export interface A2AClientOptions {
agentCardPath?: string;
fetchImpl?: typeof fetch;
}
/**
* A2AClient is a TypeScript HTTP client for interacting with A2A-compliant agents.
* Only JSON-RPC transport is supported.
* @deprecated Use {@link ClientFactory}
*/
export class A2AClient {
private agentBaseUrl: string;
private agentCardPath: string;
private agentCardPromise: Promise<AgentCard>;
private static readonly DEFAULT_AGENT_CARD_PATH = ".well-known/agent.json";
private static emptyOptions?: RequestOptions = undefined;
private readonly agentCardPromise: Promise<AgentCard>;
private readonly customFetchImpl?: typeof fetch;
private serviceEndpointUrl?: string; // To be populated from AgentCard after fetchin
// A2AClient is built around JSON-RPC types, so it will only support JSON-RPC transport, new client with transport agnostic interface is going to be created for multi-transport.
// New transport abstraction isn't going to expose individual transport specific fields, so to keep returning JSON-RPC IDs here for compatibility,
// keep counter here and pass it to JsonRpcTransport via an optional idOverride parameter (which is not visible via transport-agnostic A2ATransport interface).
private transport?: JsonRpcTransport;
private requestIdCounter: number = 1;
private serviceEndpointUrl?: string; // To be populated from AgentCard after fetching
/**
* Constructs an A2AClient instance.
* It initiates fetching the agent card from the provided agent baseUrl.
* The Agent Card is fetched from a path relative to the agentBaseUrl, which defaults to '.well-known/agent.json'.
* The `url` field from the Agent Card will be used as the RPC service endpoint.
* @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com)
* @param agentCardPath path to the agent card, defaults to .well-known/agent.json
* Constructs an A2AClient instance from an AgentCard.
* @param agentCard The AgentCard object.
* @param options Optional. The options for the A2AClient including the fetch/auth implementation.
*/
constructor(agentBaseUrl: string, agentCardPath: string = A2AClient.DEFAULT_AGENT_CARD_PATH) {
this.agentBaseUrl = agentBaseUrl.replace(/\/$/, ""); // Remove trailing slash if any
this.agentCardPath = agentCardPath.replace(/^\//, ""); // Remove leading slash if any
this.agentCardPromise = this._fetchAndCacheAgentCard();
constructor(agentCard: AgentCard | string, options?: A2AClientOptions) {
this.customFetchImpl = options?.fetchImpl;
if (typeof agentCard === 'string') {
console.warn(
'Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead.'
);
this.agentCardPromise = this._fetchAndCacheAgentCard(agentCard, options?.agentCardPath);
} else {
if (!agentCard.url) {
throw new Error(
"Provided Agent Card does not contain a valid 'url' for the service endpoint."
);
}
this.serviceEndpointUrl = agentCard.url;
this.agentCardPromise = Promise.resolve(agentCard);
}
}
/**
* Dynamically resolves the fetch implementation to use for requests.
* Prefers a custom implementation if provided, otherwise falls back to the global fetch.
* @returns The fetch implementation.
* @param args Arguments to pass to the fetch implementation.
* @throws If no fetch implementation is available.
*/
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 A2AClientOptions. ' +
'For earlier Node.js versions (pre-v18), you can use a library like `node-fetch`.'
);
}
/**
* Creates an A2AClient instance by fetching the AgentCard from a URL then constructing the A2AClient.
* @param agentCardUrl The URL of the agent card.
* @param options Optional. The options for the A2AClient including the fetch/auth implementation.
* @returns A Promise that resolves to a new A2AClient instance.
*/
public static async fromCardUrl(
agentCardUrl: string,
options?: A2AClientOptions
): Promise<A2AClient> {
const fetchImpl = options?.fetchImpl;
const requestInit = {
headers: { Accept: 'application/json' },
};
let response: Response;
if (fetchImpl) {
response = await fetchImpl(agentCardUrl, requestInit);
} else if (typeof fetch === 'function') {
// Use the global fetch implementation if no custom one is provided.
response = await fetch(agentCardUrl, requestInit);
} else {
throw new Error(
'A `fetch` implementation was not provided and is not available in the global scope. ' +
'Please provide a `fetchImpl` in the A2AClientOptions. ' +
'For earlier Node.js versions (pre-v18), you can use a library like `node-fetch`.'
);
}
if (!response.ok) {
throw new Error(
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
);
}
let agentCard: AgentCard;
try {
agentCard = await response.json();
} catch (error) {
console.error('Failed to parse Agent Card JSON:', error);
throw new Error(
`Failed to parse Agent Card JSON from ${agentCardUrl}. Original error: ${(error as Error).message}`
);
}
return new A2AClient(agentCard, options);
}
/**
* Sends a message to the agent.
* The behavior (blocking/non-blocking) and push notification configuration
* are specified within the `params.configuration` object.
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
* @param params The parameters for sending the message, including the message content and configuration.
* @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
*/
public async sendMessage(params: MessageSendParams): Promise<SendMessageResponse> {
return await this.invokeJsonRpc<MessageSendParams, SendMessageResponse>(
(t, p, id) => t.sendMessage(p, A2AClient.emptyOptions, id),
params
);
}
/**
* Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
* Push notification configuration can be specified in `params.configuration`.
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
* @param params The parameters for sending the message.
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
* The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
*/
public async *sendMessageStream(
params: MessageSendParams
): AsyncGenerator<A2AStreamEventData, void, undefined> {
const agentCard = await this.agentCardPromise; // Ensure agent card is fetched
if (!agentCard.capabilities?.streaming) {
throw new Error(
'Agent does not support streaming (AgentCard.capabilities.streaming is not true).'
);
}
const transport = await this._getOrCreateTransport();
yield* transport.sendMessageStream(params);
}
/**
* Sets or updates the push notification configuration for a given task.
* Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
* @param params Parameters containing the taskId and the TaskPushNotificationConfig.
* @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
*/
public async setTaskPushNotificationConfig(
params: TaskPushNotificationConfig
): Promise<SetTaskPushNotificationConfigResponse> {
const agentCard = await this.agentCardPromise;
if (!agentCard.capabilities?.pushNotifications) {
throw new Error(
'Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true).'
);
}
return await this.invokeJsonRpc<
TaskPushNotificationConfig,
SetTaskPushNotificationConfigResponse
>((t, p, id) => t.setTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
}
/**
* Gets the push notification configuration for a given task.
* @param params Parameters containing the taskId.
* @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
*/
public async getTaskPushNotificationConfig(
params: TaskIdParams
): Promise<GetTaskPushNotificationConfigResponse> {
return await this.invokeJsonRpc<TaskIdParams, GetTaskPushNotificationConfigResponse>(
(t, p, id) => t.getTaskPushNotificationConfig(p, A2AClient.emptyOptions, id),
params
);
}
/**
* Lists the push notification configurations for a given task.
* @param params Parameters containing the taskId.
* @returns A Promise resolving to ListTaskPushNotificationConfigResponse.
*/
public async listTaskPushNotificationConfig(
params: ListTaskPushNotificationConfigParams
): Promise<ListTaskPushNotificationConfigResponse> {
return await this.invokeJsonRpc<
ListTaskPushNotificationConfigParams,
ListTaskPushNotificationConfigResponse
>((t, p, id) => t.listTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
}
/**
* Deletes the push notification configuration for a given task.
* @param params Parameters containing the taskId and push notification configuration ID.
* @returns A Promise resolving to DeleteTaskPushNotificationConfigResponse.
*/
public async deleteTaskPushNotificationConfig(
params: DeleteTaskPushNotificationConfigParams
): Promise<DeleteTaskPushNotificationConfigResponse> {
return await this.invokeJsonRpc<
DeleteTaskPushNotificationConfigParams,
DeleteTaskPushNotificationConfigResponse
>((t, p, id) => t.deleteTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
}
/**
* Retrieves a task by its ID.
* @param params Parameters containing the taskId and optional historyLength.
* @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
*/
public async getTask(params: TaskQueryParams): Promise<GetTaskResponse> {
return await this.invokeJsonRpc<TaskQueryParams, GetTaskResponse>(
(t, p, id) => t.getTask(p, A2AClient.emptyOptions, id),
params
);
}
/**
* Cancels a task by its ID.
* @param params Parameters containing the taskId.
* @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
*/
public async cancelTask(params: TaskIdParams): Promise<CancelTaskResponse> {
return await this.invokeJsonRpc<TaskIdParams, CancelTaskResponse>(
(t, p, id) => t.cancelTask(p, A2AClient.emptyOptions, id),
params
);
}
/**
* @template TExtensionParams The type of parameters for the custom extension method.
* @template TExtensionResponse The type of response expected from the custom extension method.
* This should extend JSONRPCResponse. This ensures the extension response is still a valid A2A response.
* @param method Custom JSON-RPC method defined in the AgentCard's extensions.
* @param params Extension paramters defined in the AgentCard's extensions.
* @returns A Promise that resolves to the RPC response.
*/
public async callExtensionMethod<TExtensionParams, TExtensionResponse extends JSONRPCResponse>(
method: string,
params: TExtensionParams
) {
const transport = await this._getOrCreateTransport();
try {
return await transport.callExtensionMethod<TExtensionParams, TExtensionResponse>(
method,
params,
this.requestIdCounter++
);
} catch (e) {
// For compatibility, return JSON-RPC errors as errors instead of throwing transport-agnostic errors
// produced by JsonRpcTransport.
const errorResponse = extractJSONRPCError(e);
if (errorResponse) {
return errorResponse as TExtensionResponse;
}
throw e;
}
}
/**
* Resubscribes to a task's event stream using Server-Sent Events (SSE).
* This is used if a previous SSE connection for an active task was broken.
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
* @param params Parameters containing the taskId.
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
*/
public async *resubscribeTask(
params: TaskIdParams
): AsyncGenerator<A2AStreamEventData, void, undefined> {
const agentCard = await this.agentCardPromise;
if (!agentCard.capabilities?.streaming) {
throw new Error('Agent does not support streaming (required for tasks/resubscribe).');
}
const transport = await this._getOrCreateTransport();
yield* transport.resubscribeTask(params);
}
////////////////////////////////////////////////////////////////////////////////
// Functions used to support old A2AClient Constructor to be deprecated soon
// TODOs:
// * remove `agentCardPromise`, and just use agentCard initialized
// * _getServiceEndpoint can be made synchronous or deleted and accessed via
// agentCard.url
// * getAgentCard changed to this.agentCard
// * delete resolveAgentCardUrl(), _fetchAndCacheAgentCard(),
// agentCardPath from A2AClientOptions
// * delete _getOrCreateTransport
////////////////////////////////////////////////////////////////////////////////
private async _getOrCreateTransport(): Promise<JsonRpcTransport> {
if (this.transport) {
return this.transport;
}
const endpoint = await this._getServiceEndpoint();
this.transport = new JsonRpcTransport({ fetchImpl: this.customFetchImpl, endpoint: endpoint });
return this.transport;
}
/**
* Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
* This method is called by the constructor.
* @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com)
* @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
* @returns A Promise that resolves to the AgentCard.
*/
private async _fetchAndCacheAgentCard(): Promise<AgentCard> {
const agentCardUrl = `${this.agentBaseUrl}/${this.agentCardPath}`
private async _fetchAndCacheAgentCard(
agentBaseUrl: string,
agentCardPath?: string
): Promise<AgentCard> {
try {
const response = await fetch(agentCardUrl, {
headers: { 'Accept': 'application/json' },
const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
const response = await this._fetch(agentCardUrl, {
headers: { Accept: 'application/json' },
});
if (!response.ok) {
throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
throw new Error(
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
);
}
const agentCard: AgentCard = await response.json();
if (!agentCard.url) {
throw new Error("Fetched Agent Card does not contain a valid 'url' for the service endpoint.");
throw new Error(
"Fetched Agent Card does not contain a valid 'url' for the service endpoint."
);
}
this.serviceEndpointUrl = agentCard.url; // Cache the service endpoint URL from the agent card
return agentCard;
} catch (error) {
console.error("Error fetching or parsing Agent Card:");
console.error('Error fetching or parsing Agent Card:', error);
// Allow the promise to reject so users of agentCardPromise can handle it.
throw error;
}
@ -93,25 +381,40 @@ export class A2AClient {
* If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
* Otherwise, it returns the card fetched and cached during client construction.
* @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
* @param agentCardPath path to the agent card, defaults to .well-known/agent.json
* @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
* If provided, this will fetch a new card, not use the cached one from the constructor's URL.
* @returns A Promise that resolves to the AgentCard.
*/
public async getAgentCard(agentBaseUrl?: string, agentCardPath: string = A2AClient.DEFAULT_AGENT_CARD_PATH): Promise<AgentCard> {
public async getAgentCard(agentBaseUrl?: string, agentCardPath?: string): Promise<AgentCard> {
if (agentBaseUrl) {
const agentCardUrl = `${agentBaseUrl.replace(/\/$/, "")}/${agentCardPath.replace(/^\//, "")}`
const response = await fetch(agentCardUrl, {
headers: { 'Accept': 'application/json' },
const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
const response = await this._fetch(agentCardUrl, {
headers: { Accept: 'application/json' },
});
if (!response.ok) {
throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
throw new Error(
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
);
}
return await response.json() as AgentCard;
return (await response.json()) as AgentCard;
}
// If no specific URL is given, return the promise for the initially configured agent's card.
return this.agentCardPromise;
}
/**
* Determines the agent card URL based on the agent URL.
* @param agentBaseUrl The agent URL.
* @param agentCardPath Optional relative path to the agent card, defaults to .well-known/agent-card.json
*/
private resolveAgentCardUrl(
agentBaseUrl: string,
agentCardPath: string = AGENT_CARD_PATH
): string {
return `${agentBaseUrl.replace(/\/$/, '')}/${agentCardPath.replace(/^\//, '')}`;
}
/**
* Gets the RPC service endpoint URL. Ensures the agent card has been fetched first.
* @returns A Promise that resolves to the service endpoint URL string.
@ -125,365 +428,60 @@ export class A2AClient {
await this.agentCardPromise;
if (!this.serviceEndpointUrl) {
// This case should ideally be covered by the error handling in _fetchAndCacheAgentCard
throw new Error("Agent Card URL for RPC endpoint is not available. Fetching might have failed.");
throw new Error(
'Agent Card URL for RPC endpoint is not available. Fetching might have failed.'
);
}
return this.serviceEndpointUrl;
}
/**
* Helper method to make a generic JSON-RPC POST request.
* @param method The RPC method name.
* @param params The parameters for the RPC method.
* @returns A Promise that resolves to the RPC response.
*/
private async _postRpcRequest<TParams, TResponse extends JSONRPCResponse>(
method: string,
params: TParams
private async invokeJsonRpc<TParams extends JsonRpcParams, TResponse extends JSONRPCResponse>(
caller: JsonRpcCaller<TParams, TResponse>,
params?: TParams
): Promise<TResponse> {
const endpoint = await this._getServiceEndpoint();
const transport = await this._getOrCreateTransport();
const requestId = this.requestIdCounter++;
const rpcRequest: JSONRPCRequest = {
jsonrpc: "2.0",
method,
params: params as { [key: string]: any; }, // Cast because TParams structure varies per method
id: requestId,
};
const httpResponse = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json", // Expect JSON response for non-streaming requests
},
body: JSON.stringify(rpcRequest),
});
if (!httpResponse.ok) {
let errorBodyText = '(empty or non-JSON response)';
try {
errorBodyText = await httpResponse.text();
const errorJson = JSON.parse(errorBodyText);
// If the body is a valid JSON-RPC error response, let it be handled by the standard parsing below.
// However, if it's not even a JSON-RPC structure but still an error, throw based on HTTP status.
if (!errorJson.jsonrpc && errorJson.error) { // Check if it's a JSON-RPC error structure
throw new Error(`RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data || {})}`);
} else if (!errorJson.jsonrpc) {
throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
}
} catch (e: any) {
// If parsing the error body fails or it's not a JSON-RPC error, throw a generic HTTP error.
// If it was already an error thrown from within the try block, rethrow it.
if (e.message.startsWith('RPC error for') || e.message.startsWith('HTTP error for')) throw e;
throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
}
}
const rpcResponse = await httpResponse.json();
if (rpcResponse.id !== requestId) {
// This is a significant issue for request-response matching.
console.error(`CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`);
// Depending on strictness, one might throw an error here.
// throw new Error(`RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}`);
}
return rpcResponse as TResponse;
}
/**
* Sends a message to the agent.
* The behavior (blocking/non-blocking) and push notification configuration
* are specified within the `params.configuration` object.
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
* @param params The parameters for sending the message, including the message content and configuration.
* @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
*/
public async sendMessage(params: MessageSendParams): Promise<SendMessageResponse> {
return this._postRpcRequest<MessageSendParams, SendMessageResponse>("message/send", params);
}
/**
* Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
* Push notification configuration can be specified in `params.configuration`.
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
* @param params The parameters for sending the message.
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
* The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
*/
public async *sendMessageStream(params: MessageSendParams): AsyncGenerator<A2AStreamEventData, void, undefined> {
const agentCard = await this.agentCardPromise; // Ensure agent card is fetched
if (!agentCard.capabilities?.streaming) {
throw new Error("Agent does not support streaming (AgentCard.capabilities.streaming is not true).");
}
const endpoint = await this._getServiceEndpoint();
const clientRequestId = this.requestIdCounter++; // Use a unique ID for this stream request
const rpcRequest: JSONRPCRequest = { // This is the initial JSON-RPC request to establish the stream
jsonrpc: "2.0",
method: "message/stream",
params: params as { [key: string]: any; },
id: clientRequestId,
};
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "text/event-stream", // Crucial for SSE
},
body: JSON.stringify(rpcRequest),
});
if (!response.ok) {
// Attempt to read error body for more details
let errorBody = "";
try {
errorBody = await response.text();
const errorJson = JSON.parse(errorBody);
if (errorJson.error) {
throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
}
} catch (e: any) {
if (e.message.startsWith('HTTP error establishing stream')) throw e;
// Fallback if body is not JSON or parsing fails
throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`);
}
throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`);
}
if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
// Server should explicitly set this content type for SSE.
throw new Error("Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.");
}
// Yield events from the parsed SSE stream.
// Each event's 'data' field is a JSON-RPC response.
yield* this._parseA2ASseStream<A2AStreamEventData>(response, clientRequestId);
}
/**
* Sets or updates the push notification configuration for a given task.
* Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
* @param params Parameters containing the taskId and the TaskPushNotificationConfig.
* @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
*/
public async setTaskPushNotificationConfig(params: TaskPushNotificationConfig): Promise<SetTaskPushNotificationConfigResponse> {
const agentCard = await this.agentCardPromise;
if (!agentCard.capabilities?.pushNotifications) {
throw new Error("Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true).");
}
// The 'params' directly matches the structure expected by the RPC method.
return this._postRpcRequest<TaskPushNotificationConfig, SetTaskPushNotificationConfigResponse>(
"tasks/pushNotificationConfig/set",
params
);
}
/**
* Gets the push notification configuration for a given task.
* @param params Parameters containing the taskId.
* @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
*/
public async getTaskPushNotificationConfig(params: TaskIdParams): Promise<GetTaskPushNotificationConfigResponse> {
// The 'params' (TaskIdParams) directly matches the structure expected by the RPC method.
return this._postRpcRequest<TaskIdParams, GetTaskPushNotificationConfigResponse>(
"tasks/pushNotificationConfig/get",
params
);
}
/**
* Retrieves a task by its ID.
* @param params Parameters containing the taskId and optional historyLength.
* @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
*/
public async getTask(params: TaskQueryParams): Promise<GetTaskResponse> {
return this._postRpcRequest<TaskQueryParams, GetTaskResponse>("tasks/get", params);
}
/**
* Cancels a task by its ID.
* @param params Parameters containing the taskId.
* @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
*/
public async cancelTask(params: TaskIdParams): Promise<CancelTaskResponse> {
return this._postRpcRequest<TaskIdParams, CancelTaskResponse>("tasks/cancel", params);
}
/**
* Resubscribes to a task's event stream using Server-Sent Events (SSE).
* This is used if a previous SSE connection for an active task was broken.
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
* @param params Parameters containing the taskId.
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
*/
public async *resubscribeTask(params: TaskIdParams): AsyncGenerator<A2AStreamEventData, void, undefined> {
const agentCard = await this.agentCardPromise;
if (!agentCard.capabilities?.streaming) {
throw new Error("Agent does not support streaming (required for tasks/resubscribe).");
}
const endpoint = await this._getServiceEndpoint();
const clientRequestId = this.requestIdCounter++; // Unique ID for this resubscribe request
const rpcRequest: JSONRPCRequest = { // Initial JSON-RPC request to establish the stream
jsonrpc: "2.0",
method: "tasks/resubscribe",
params: params as { [key: string]: any; },
id: clientRequestId,
};
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "text/event-stream",
},
body: JSON.stringify(rpcRequest),
});
if (!response.ok) {
let errorBody = "";
try {
errorBody = await response.text();
const errorJson = JSON.parse(errorBody);
if (errorJson.error) {
throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
}
} catch (e: any) {
if (e.message.startsWith('HTTP error establishing stream')) throw e;
throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`);
}
throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`);
}
if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
throw new Error("Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.");
}
// The events structure for resubscribe is assumed to be the same as message/stream.
// Each event's 'data' field is a JSON-RPC response.
yield* this._parseA2ASseStream<A2AStreamEventData>(response, clientRequestId);
}
/**
* Parses an HTTP response body as an A2A Server-Sent Event stream.
* Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,
* specifically a SendStreamingMessageResponse (or similar structure for resubscribe).
* @param response The HTTP Response object whose body is the SSE stream.
* @param originalRequestId The ID of the client's JSON-RPC request that initiated this stream.
* Used to validate the `id` in the streamed JSON-RPC responses.
* @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.
*/
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 = ""; // Holds incomplete lines from the stream
let eventDataBuffer = ""; // Holds accumulated 'data:' lines for the current event
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
// Process any final buffered event data if the stream ends abruptly after a 'data:' line
if (eventDataBuffer.trim()) {
const result = this._processSseEventData<TStreamItem>(eventDataBuffer, originalRequestId);
yield result;
}
break; // Stream finished
}
buffer += value; // Append new chunk to buffer
let lineEndIndex;
// Process all complete lines in the buffer
while ((lineEndIndex = buffer.indexOf('\n')) >= 0) {
const line = buffer.substring(0, lineEndIndex).trim(); // Get and trim the line
buffer = buffer.substring(lineEndIndex + 1); // Remove processed line from buffer
if (line === "") { // Empty line: signifies the end of an event
if (eventDataBuffer) { // If we have accumulated data for an event
const result = this._processSseEventData<TStreamItem>(eventDataBuffer, originalRequestId);
yield result;
eventDataBuffer = ""; // Reset buffer for the next event
}
} else if (line.startsWith("data:")) {
eventDataBuffer += line.substring(5).trimStart() + "\n"; // Append data (multi-line data is possible)
} else if (line.startsWith(":")) {
// This is a comment line in SSE, ignore it.
} else if (line.includes(":")) {
// Other SSE fields like 'event:', 'id:', 'retry:'.
// The A2A spec primarily focuses on the 'data' field for JSON-RPC payloads.
// For now, we don't specifically handle these other SSE fields unless required by spec.
}
}
const result = await caller(transport, params, requestId);
return {
id: requestId,
jsonrpc: '2.0',
result: result ?? null, // JSON-RPC requires result property on success, it will be null for "void" methods.
} as TResponse;
} catch (e) {
// For compatibility, return JSON-RPC errors as response objects instead of throwing transport-agnostic errors
// produced by JsonRpcTransport.
const errorResponse = extractJSONRPCError(e);
if (errorResponse) {
return errorResponse as TResponse;
}
} catch (error: any) {
// Log and re-throw errors encountered during stream processing
console.error("Error reading or parsing SSE stream:", error.message);
throw error;
} finally {
reader.releaseLock(); // Ensure the reader lock is released
throw e;
}
}
/**
* Processes a single SSE event's data string, expecting it to be a JSON-RPC response.
* @param jsonData The string content from one or more 'data:' lines of an SSE event.
* @param originalRequestId The ID of the client's request that initiated the stream.
* @returns The `result` field of the parsed JSON-RPC success response.
* @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.
*/
private _processSseEventData<TStreamItem>(
jsonData: string,
originalRequestId: number | string | null
): TStreamItem {
if (!jsonData.trim()) {
throw new Error("Attempted to process empty SSE event data.");
}
try {
// SSE data can be multi-line, ensure it's treated as a single JSON string.
const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\n$/, '')); // Remove trailing newline if any
// Type assertion to SendStreamingMessageResponse, as this is the expected structure for A2A streams.
const a2aStreamResponse: SendStreamingMessageResponse = sseJsonRpcResponse as SendStreamingMessageResponse;
if (a2aStreamResponse.id !== originalRequestId) {
// According to JSON-RPC spec, notifications (which SSE events can be seen as) might not have an ID,
// or if they do, it should match. A2A spec implies streamed events are tied to the initial request.
console.warn(`SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`);
// Depending on strictness, this could be an error. For now, it's a warning.
}
if (this.isErrorResponse(a2aStreamResponse)) {
const err = a2aStreamResponse.error as (JSONRPCError | A2AError);
throw new Error(`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`);
}
// Check if 'result' exists, as it's mandatory for successful JSON-RPC responses
if (!('result' in a2aStreamResponse) || typeof (a2aStreamResponse as SendStreamingMessageSuccessResponse).result === 'undefined') {
throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
}
const successResponse = a2aStreamResponse as SendStreamingMessageSuccessResponse;
return successResponse.result as TStreamItem;
} catch (e: any) {
// Catch errors from JSON.parse or if it's an error response that was thrown by this function
if (e.message.startsWith("SSE event contained an error") || e.message.startsWith("SSE event JSON-RPC response is missing 'result' field")) {
throw e; // Re-throw errors already processed/identified by this function
}
// For other parsing errors or unexpected structures:
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.message}`);
}
}
isErrorResponse(response: JSONRPCResponse): response is JSONRPCErrorResponse {
return "error" in response;
}
}
function extractJSONRPCError(error: unknown): JSONRPCErrorResponse {
if (
error instanceof Object &&
'errorResponse' in error &&
error.errorResponse instanceof Object &&
'jsonrpc' in error.errorResponse &&
error.errorResponse.jsonrpc === '2.0' &&
'error' in error.errorResponse &&
error.errorResponse.error !== null
) {
return error.errorResponse as JSONRPCErrorResponse;
} else {
return undefined;
}
}
// Utility unexported types to properly factor out common "compatibility" logic via invokeJsonRpc.
type ParamsOf<T> = T extends { params: unknown } ? T['params'] : undefined;
type ResultOf<T> = T extends { result: unknown } ? T['result'] : void;
type JsonRpcParams = ParamsOf<A2ARequest>;
type JsonRpcCaller<TParams extends JsonRpcParams, TResponse extends JSONRPCResponse> = (
transport: JsonRpcTransport,
params: TParams,
idOverride: number
) => Promise<ResultOf<TResponse>>;

62
src/client/context.ts Normal file
View File

@ -0,0 +1,62 @@
/**
* Opaque context object to carry per-call context data.
* Use {@link ClientCallContextKey} to create typed keys for storing and retrieving values.
*/
export type ClientCallContext = Record<symbol, unknown>;
/**
* Function that applies an update to a {@link ClientCallContext}.
*/
export type ContextUpdate = (context: ClientCallContext) => void;
export const ClientCallContext = {
/**
* Create a new {@link ClientCallContext} with optional updates applied.
*/
create: (...updates: ContextUpdate[]): ClientCallContext => {
return ClientCallContext.createFrom(undefined, ...updates);
},
/**
* Create a new {@link ClientCallContext} based on an existing one with updates applied.
*/
createFrom: (
context: ClientCallContext | undefined,
...updates: ContextUpdate[]
): ClientCallContext => {
const result = context ? { ...context } : {};
for (const update of updates) {
update(result);
}
return result;
},
};
/**
* Each instance represents a unique key for storing
* and retrieving typed values in a {@link ClientCallContext}.
*
* @example
* ```ts
* const key = new ClientCallContextKey<string>('My key');
* const context = ClientCallContext.create(key.set('example-value'));
* const value = key.get(context); // 'example-value'
* ```
*/
export class ClientCallContextKey<T> {
public readonly symbol: symbol;
constructor(description: string) {
this.symbol = Symbol(description);
}
set(value: T): ContextUpdate {
return (context) => {
context[this.symbol] = value;
};
}
get(context: ClientCallContext): T | undefined {
return context[this.symbol] as T | undefined;
}
}

213
src/client/factory.ts Normal file
View File

@ -0,0 +1,213 @@
import { TransportProtocolName } from '../core.js';
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 {
/**
* Transport factories to use.
* Effectively defines transports supported by this client factory.
*/
transports: TransportFactory[];
/**
* Client config to be used for clients created by this factory.
*/
clientConfig?: ClientConfig;
/**
* Transport preferences to override ones defined by the agent card.
* If no matches are found among preferred transports, agent card values are used next.
*/
preferredTransports?: TransportProtocolName[];
/**
* Used for createFromAgentCardUrl to download agent card.
*/
cardResolver?: AgentCardResolver;
}
export const ClientFactoryOptions = {
/**
* SDK default options for {@link ClientFactory}.
*/
default: {
transports: [new JsonRpcTransportFactory(), new RestTransportFactory()],
} as Readonly<ClientFactoryOptions>,
/**
* Creates new options by merging an original and an override object.
* Transports are merged based on `TransportFactory.protocolName`,
* interceptors are concatenated, other fields are overriden.
*
* @example
* ```ts
* const options = ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
* transports: [new MyCustomTransportFactory()], // adds a custom transport
* clientConfig: { interceptors: [new MyInterceptor()] }, // adds a custom interceptor
* });
* ```
*/
createFrom(
original: ClientFactoryOptions,
overrides: Partial<ClientFactoryOptions>
): ClientFactoryOptions {
return {
...original,
...overrides,
transports: mergeTransports(original.transports, overrides.transports),
clientConfig: {
...(original.clientConfig ?? {}),
...(overrides.clientConfig ?? {}),
interceptors: mergeArrays(
original.clientConfig?.interceptors,
overrides.clientConfig?.interceptors
),
acceptedOutputModes:
overrides.clientConfig?.acceptedOutputModes ?? original.clientConfig?.acceptedOutputModes,
},
preferredTransports: overrides.preferredTransports ?? original.preferredTransports,
};
},
};
export class ClientFactory {
private readonly transportsByName: CaseInsensitiveMap<TransportFactory>;
private readonly agentCardResolver: AgentCardResolver;
constructor(public readonly options: ClientFactoryOptions = ClientFactoryOptions.default) {
if (!options.transports || options.transports.length === 0) {
throw new Error('No transports provided');
}
this.transportsByName = transportsByName(options.transports);
for (const transport of options.preferredTransports ?? []) {
if (!this.transportsByName.has(transport)) {
throw new Error(
`Unknown preferred transport: ${transport}, available transports: ${[...this.transportsByName.keys()].join()}`
);
}
}
this.agentCardResolver = options.cardResolver ?? AgentCardResolver.default;
}
/**
* Creates a new client from the provided agent card.
*/
async createFromAgentCard(agentCard: AgentCard): Promise<Client> {
const agentCardPreferred = agentCard.preferredTransport ?? JsonRpcTransportFactory.name;
const additionalInterfaces = agentCard.additionalInterfaces ?? [];
const urlsPerAgentTransports = new CaseInsensitiveMap<string>([
[agentCardPreferred, agentCard.url],
...additionalInterfaces.map<[string, string]>((i) => [i.transport, i.url]),
]);
const transportsByPreference = [
...(this.options.preferredTransports ?? []),
agentCardPreferred,
...additionalInterfaces.map((i) => i.transport),
];
for (const transport of transportsByPreference) {
const url = urlsPerAgentTransports.get(transport);
const factory = this.transportsByName.get(transport);
if (factory && url) {
return new Client(
await factory.create(url, agentCard),
agentCard,
this.options.clientConfig
);
}
}
throw new Error(
'No compatible transport found, available transports: ' +
[...this.transportsByName.keys()].join()
);
}
/**
* Downloads agent card using AgentCardResolver from options
* and creates a new client from the downloaded card.
*
* @example
* ```ts
* const factory = new ClientFactory(); // use default options and default {@link AgentCardResolver}.
* const client1 = await factory.createFromUrl('https://example.com'); // /.well-known/agent-card.json is used by default
* const client2 = await factory.createFromUrl('https://example.com', '/my-agent-card.json'); // specify custom path
* const client3 = await factory.createFromUrl('https://example.com/my-agent-card.json', ''); // specify full URL and set path to empty
* ```
*/
async createFromUrl(baseUrl: string, path?: string): Promise<Client> {
const agentCard = await this.agentCardResolver.resolve(baseUrl, path);
return this.createFromAgentCard(agentCard);
}
}
function mergeTransports(
original: TransportFactory[],
overrides: TransportFactory[] | undefined
): TransportFactory[] {
if (!overrides) {
return original;
}
const result = transportsByName(original);
const overridesByName = transportsByName(overrides);
for (const [name, factory] of overridesByName) {
result.set(name, factory);
}
return Array.from(result.values());
}
function transportsByName(
transports: ReadonlyArray<TransportFactory> | undefined
): CaseInsensitiveMap<TransportFactory> {
const result = new CaseInsensitiveMap<TransportFactory>();
if (!transports) {
return result;
}
for (const t of transports) {
if (result.has(t.protocolName)) {
throw new Error(`Duplicate protocol name: ${t.protocolName}`);
}
result.set(t.protocolName, t);
}
return result;
}
function mergeArrays<T>(
a1: ReadonlyArray<T> | undefined,
a2: ReadonlyArray<T> | undefined
): T[] | undefined {
if (!a1 && !a2) {
return undefined;
}
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

@ -2,4 +2,46 @@
* Client entry point for the A2A Server V2 library.
*/
export { A2AClient } from "./client.js";
export { A2AClient } from './client.js';
export type { A2AClientOptions } from './client.js';
export * from './auth-handler.js';
export {
AgentCardResolver,
type AgentCardResolverOptions,
DefaultAgentCardResolver,
} from './card-resolver.js';
export { Client, type ClientConfig, type RequestOptions } from './multitransport-client.js';
export type { Transport, TransportFactory } from './transports/transport.js';
export { ClientFactory, ClientFactoryOptions } from './factory.js';
export {
JsonRpcTransport,
JsonRpcTransportFactory,
type JsonRpcTransportOptions,
} from './transports/json_rpc_transport.js';
export {
RestTransport,
RestTransportFactory,
type RestTransportOptions,
} from './transports/rest_transport.js';
export type {
CallInterceptor,
BeforeArgs,
AfterArgs,
ClientCallInput,
ClientCallResult,
} from './interceptors.js';
export {
ServiceParameters,
type ServiceParametersUpdate,
withA2AExtensions,
} from './service-parameters.js';
export { ClientCallContext, type ContextUpdate, ClientCallContextKey } from './context.js';
export {
AuthenticatedExtendedCardNotConfiguredError,
ContentTypeNotSupportedError,
InvalidAgentResponseError,
PushNotificationNotSupportedError,
TaskNotCancelableError,
TaskNotFoundError,
UnsupportedOperationError,
} from '../errors.js';

134
src/client/interceptors.ts Normal file
View File

@ -0,0 +1,134 @@
import { AgentCard } from '../types.js';
import { A2AStreamEventData } from './client.js';
import { Client } from './multitransport-client.js';
import { RequestOptions } from './multitransport-client.js';
export interface CallInterceptor {
/**
* Invoked before transport method.
*/
before(args: BeforeArgs): Promise<void>;
/**
* Invoked after transport method.
*/
after(args: AfterArgs): Promise<void>;
}
export interface BeforeArgs<K extends keyof Client = keyof Client> {
/**
* Identifies the client method invoked and its payload.
* Payload inside the input object can be modified.
*/
readonly input: ClientCallInput<K>;
/**
* Identifies the agent card cached on the client
*/
readonly agentCard: AgentCard;
/**
* If set by the interceptor, stops execution, invokes "after"
* for executed interceptors and returns the result. Transport is not called.
*/
earlyReturn?: ClientCallResult<K>;
/**
* Options passed to the client.
*/
options?: RequestOptions;
}
export interface AfterArgs<K extends keyof Client = keyof Client> {
/**
* Identifies the client method invoked and its result.
* Payload inside the result object can be modified.
*/
readonly result: ClientCallResult<K>;
/**
* Identifies the agent card cached on the client
*/
readonly agentCard: AgentCard;
/**
* If set by the interceptor, stops execution and returns result value,
* remaining interceptors are not executed.
*/
earlyReturn?: boolean;
/**
* Options passed to the client.
*/
options?: RequestOptions;
}
export type ClientCallInput<K extends keyof Client = keyof Client> = MethodInput<Client, K>;
export type ClientCallResult<K extends keyof Client = keyof Client> = MethodResult<
Client,
K,
ResultsOverrides
>;
// Types below are helper types and are not exported to allow simplifying it without affecting
// public API if necessary. They are exported via type aliases ClientXxx which can be replaced with explicit union if necessary.
/**
* For
*
* interface Foo {
* f1(arg: string): Promise<Result1>;
* f2(arg: number): Promise<Result2>;
* }
*
* MethodInputs<Foo> resolves to
*
* {
* readonly method: "f1";
* value: string;
* } | {
* readonly method: "f2";
* value: number;
* }
*/
type MethodInput<T, TMembers extends keyof T = keyof T> = {
[M in TMembers]: T[M] extends (options: RequestOptions | undefined) => unknown
? { readonly method: M; value?: never }
: T[M] extends (payload: infer P) => unknown
? { readonly method: M; value: P }
: never;
}[TMembers];
/**
* For
*
* interface Foo {
* f1(): Promise<Result1>;
* f2(): Promise<Result2>;
* }
*
* MethodsResults<Foo> resolves to
*
* {
* readonly method: "f1";
* value: Result1;
* } | {
* readonly method: "f2";
* value: Result2;
* }
*/
type MethodResult<T, TMembers extends keyof T = keyof T, TOverrides = object> = {
[M in TMembers]: M extends keyof TOverrides // If there is an override, use it directly.
? { readonly method: M; value: TOverrides[M] }
: // Infer result, unwrap it from Promise and pack with method name.
T[M] extends (payload: unknown) => infer R
? { readonly method: M; value: Awaited<R> }
: never;
}[TMembers];
interface ResultsOverrides {
// sendMessageStream and resubscribeTask return async iterators and are intercepted on each item,
// which requires custom handling.
sendMessageStream: A2AStreamEventData;
resubscribeTask: A2AStreamEventData;
}

View File

@ -0,0 +1,393 @@
import { PushNotificationNotSupportedError } from '../errors.js';
import {
MessageSendParams,
TaskPushNotificationConfig,
DeleteTaskPushNotificationConfigParams,
ListTaskPushNotificationConfigParams,
Task,
TaskIdParams,
TaskQueryParams,
PushNotificationConfig,
AgentCard,
} from '../types.js';
import { A2AStreamEventData, SendMessageResult } from './client.js';
import { ClientCallContext } from './context.js';
import {
CallInterceptor,
BeforeArgs,
AfterArgs,
ClientCallResult,
ClientCallInput,
} from './interceptors.js';
import { ServiceParameters } from './service-parameters.js';
import { Transport } from './transports/transport.js';
export interface ClientConfig {
/**
* Whether client prefers to poll for task updates instead of blocking until a terminal state is reached.
* If set to true, non-streaming send message result might be a Message or a Task in any (including non-terminal) state.
* Callers are responsible for running the polling loop. This configuration does not apply to streaming requests.
*/
polling?: boolean;
/**
* Specifies the default list of accepted media types to apply for all "send message" calls.
*/
acceptedOutputModes?: string[];
/**
* Specifies the default push notification configuration to apply for every Task.
*/
pushNotificationConfig?: PushNotificationConfig;
/**
* Interceptors invoked for each request.
*/
interceptors?: CallInterceptor[];
}
export interface RequestOptions {
/**
* Signal to abort request execution.
*/
signal?: AbortSignal;
/**
* A key-value map for passing horizontally applicable context or parameters.
* All parameters are passed to the server via underlying transports (e.g. In JsonRPC via Headers).
*/
serviceParameters?: ServiceParameters;
/**
* Arbitrary data available to interceptors and transport implementation.
*/
context?: ClientCallContext;
}
export class Client {
constructor(
public readonly transport: Transport,
private agentCard: AgentCard,
public readonly config?: ClientConfig
) {}
/**
* If the current agent card supports the extended feature, it will try to fetch the extended agent card from the server,
* Otherwise it will return the current agent card value.
*/
async getAgentCard(options?: RequestOptions): Promise<AgentCard> {
if (this.agentCard.supportsAuthenticatedExtendedCard) {
this.agentCard = await this.executeWithInterceptors(
{ method: 'getAgentCard' },
options,
(_, options) => this.transport.getExtendedAgentCard(options)
);
}
return this.agentCard;
}
/**
* Sends a message to an agent to initiate a new interaction or to continue an existing one.
* Uses blocking mode by default.
*/
sendMessage(params: MessageSendParams, options?: RequestOptions): Promise<SendMessageResult> {
params = this.applyClientConfig({
params,
blocking: !(this.config?.polling ?? false),
});
return this.executeWithInterceptors(
{ method: 'sendMessage', value: params },
options,
this.transport.sendMessage.bind(this.transport)
);
}
/**
* Sends a message to an agent to initiate/continue a task AND subscribes the client to real-time updates for that task.
* Performs fallback to non-streaming if not supported by the agent.
*/
async *sendMessageStream(
params: MessageSendParams,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined> {
const method = 'sendMessageStream';
params = this.applyClientConfig({ params, blocking: true });
const beforeArgs: BeforeArgs<'sendMessageStream'> = {
input: { method, value: params },
agentCard: this.agentCard,
options,
};
const beforeResult = await this.interceptBefore(beforeArgs);
if (beforeResult) {
const earlyReturn = beforeResult.earlyReturn.value;
const afterArgs: AfterArgs<'sendMessageStream'> = {
result: { method, value: earlyReturn },
agentCard: this.agentCard,
options: beforeArgs.options,
};
await this.interceptAfter(afterArgs, beforeResult.executed);
yield afterArgs.result.value;
return;
}
if (!this.agentCard.capabilities.streaming) {
const result = await this.transport.sendMessage(beforeArgs.input.value, beforeArgs.options);
const afterArgs: AfterArgs<'sendMessageStream'> = {
result: { method, value: result },
agentCard: this.agentCard,
options: beforeArgs.options,
};
await this.interceptAfter(afterArgs);
yield afterArgs.result.value;
return;
}
for await (const event of this.transport.sendMessageStream(
beforeArgs.input.value,
beforeArgs.options
)) {
const afterArgs: AfterArgs<'sendMessageStream'> = {
result: { method, value: event },
agentCard: this.agentCard,
options: beforeArgs.options,
};
await this.interceptAfter(afterArgs);
yield afterArgs.result.value;
if (afterArgs.earlyReturn) {
return;
}
}
}
/**
* Sets or updates the push notification configuration for a specified task.
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
*/
setTaskPushNotificationConfig(
params: TaskPushNotificationConfig,
options?: RequestOptions
): Promise<TaskPushNotificationConfig> {
if (!this.agentCard.capabilities.pushNotifications) {
throw new PushNotificationNotSupportedError();
}
return this.executeWithInterceptors(
{ method: 'setTaskPushNotificationConfig', value: params },
options,
this.transport.setTaskPushNotificationConfig.bind(this.transport)
);
}
/**
* Retrieves the current push notification configuration for a specified task.
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
*/
getTaskPushNotificationConfig(
params: TaskIdParams,
options?: RequestOptions
): Promise<TaskPushNotificationConfig> {
if (!this.agentCard.capabilities.pushNotifications) {
throw new PushNotificationNotSupportedError();
}
return this.executeWithInterceptors(
{ method: 'getTaskPushNotificationConfig', value: params },
options,
this.transport.getTaskPushNotificationConfig.bind(this.transport)
);
}
/**
* Retrieves the associated push notification configurations for a specified task.
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
*/
listTaskPushNotificationConfig(
params: ListTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<TaskPushNotificationConfig[]> {
if (!this.agentCard.capabilities.pushNotifications) {
throw new PushNotificationNotSupportedError();
}
return this.executeWithInterceptors(
{ method: 'listTaskPushNotificationConfig', value: params },
options,
this.transport.listTaskPushNotificationConfig.bind(this.transport)
);
}
/**
* Deletes an associated push notification configuration for a task.
*/
deleteTaskPushNotificationConfig(
params: DeleteTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<void> {
return this.executeWithInterceptors(
{ method: 'deleteTaskPushNotificationConfig', value: params },
options,
this.transport.deleteTaskPushNotificationConfig.bind(this.transport)
);
}
/**
* Retrieves the current state (including status, artifacts, and optionally history) of a previously initiated task.
*/
getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task> {
return this.executeWithInterceptors(
{ method: 'getTask', value: params },
options,
this.transport.getTask.bind(this.transport)
);
}
/**
* Requests the cancellation of an ongoing task. The server will attempt to cancel the task,
* but success is not guaranteed (e.g., the task might have already completed or failed, or cancellation might not be supported at its current stage).
*/
cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task> {
return this.executeWithInterceptors(
{ method: 'cancelTask', value: params },
options,
this.transport.cancelTask.bind(this.transport)
);
}
/**
* Allows a client to reconnect to an updates stream for an ongoing task after a previous connection was interrupted.
*/
async *resubscribeTask(
params: TaskIdParams,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined> {
const method = 'resubscribeTask';
const beforeArgs: BeforeArgs<'resubscribeTask'> = {
input: { method, value: params },
agentCard: this.agentCard,
options,
};
const beforeResult = await this.interceptBefore(beforeArgs);
if (beforeResult) {
const earlyReturn = beforeResult.earlyReturn.value;
const afterArgs: AfterArgs<'resubscribeTask'> = {
result: { method, value: earlyReturn },
agentCard: this.agentCard,
options: beforeArgs.options,
};
await this.interceptAfter(afterArgs, beforeResult.executed);
yield afterArgs.result.value;
return;
}
for await (const event of this.transport.resubscribeTask(
beforeArgs.input.value,
beforeArgs.options
)) {
const afterArgs: AfterArgs<'resubscribeTask'> = {
result: { method, value: event },
agentCard: this.agentCard,
options: beforeArgs.options,
};
await this.interceptAfter(afterArgs);
yield afterArgs.result.value;
if (afterArgs.earlyReturn) {
return;
}
}
}
private applyClientConfig({
params,
blocking,
}: {
params: MessageSendParams;
blocking: boolean;
}): MessageSendParams {
const result = { ...params, configuration: params.configuration ?? {} };
if (!result.configuration.acceptedOutputModes && this.config?.acceptedOutputModes) {
result.configuration.acceptedOutputModes = this.config.acceptedOutputModes;
}
if (!result.configuration.pushNotificationConfig && this.config?.pushNotificationConfig) {
result.configuration.pushNotificationConfig = this.config.pushNotificationConfig;
}
result.configuration.blocking ??= blocking;
return result;
}
private async executeWithInterceptors<K extends keyof Client>(
input: ClientCallInput<K>,
options: RequestOptions | undefined,
transportCall: (
params: ClientCallInput<K>['value'],
options?: RequestOptions
) => Promise<ClientCallResult<K>['value']>
): Promise<ClientCallResult<K>['value']> {
const beforeArgs: BeforeArgs<K> = {
input: input,
agentCard: this.agentCard,
options,
};
const beforeResult = await this.interceptBefore(beforeArgs);
if (beforeResult) {
const afterArgs: AfterArgs<K> = {
result: {
method: input.method,
value: beforeResult.earlyReturn.value,
} as ClientCallResult<K>,
agentCard: this.agentCard,
options: beforeArgs.options,
};
await this.interceptAfter(afterArgs, beforeResult.executed);
return afterArgs.result.value;
}
const result = await transportCall(beforeArgs.input.value, beforeArgs.options);
const afterArgs: AfterArgs<K> = {
result: { method: input.method, value: result } as ClientCallResult<K>,
agentCard: this.agentCard,
options: beforeArgs.options,
};
await this.interceptAfter(afterArgs);
return afterArgs.result.value;
}
private async interceptBefore<K extends keyof Client>(
args: BeforeArgs<K>
): Promise<{ earlyReturn: ClientCallResult<K>; executed: CallInterceptor[] } | undefined> {
if (!this.config?.interceptors || this.config.interceptors.length === 0) {
return;
}
const executed: CallInterceptor[] = [];
for (const interceptor of this.config.interceptors) {
await interceptor.before(args);
executed.push(interceptor);
if (args.earlyReturn) {
return {
earlyReturn: args.earlyReturn,
executed,
};
}
}
}
private async interceptAfter<K extends keyof Client>(
args: AfterArgs<K>,
interceptors?: CallInterceptor[]
): Promise<void> {
const reversedInterceptors = [...(interceptors ?? this.config?.interceptors ?? [])].reverse();
for (const interceptor of reversedInterceptors) {
await interceptor.after(args);
if (args.earlyReturn) {
return;
}
}
}
}

View File

@ -0,0 +1,29 @@
import { HTTP_EXTENSION_HEADER } from '../constants.js';
import { Extensions } from '../extensions.js';
export type ServiceParameters = Record<string, string>;
export type ServiceParametersUpdate = (parameters: ServiceParameters) => void;
export const ServiceParameters = {
create(...updates: ServiceParametersUpdate[]): ServiceParameters {
return ServiceParameters.createFrom(undefined, ...updates);
},
createFrom: (
serviceParameters: ServiceParameters | undefined,
...updates: ServiceParametersUpdate[]
): ServiceParameters => {
const result = serviceParameters ? { ...serviceParameters } : {};
for (const update of updates) {
update(result);
}
return result;
},
};
export function withA2AExtensions(...extensions: Extensions): ServiceParametersUpdate {
return (parameters: ServiceParameters) => {
parameters[HTTP_EXTENSION_HEADER] = Extensions.toServiceParameter(extensions);
};
}

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

@ -0,0 +1,445 @@
import { TransportProtocolName } from '../../core.js';
import {
AuthenticatedExtendedCardNotConfiguredError,
ContentTypeNotSupportedError,
InvalidAgentResponseError,
PushNotificationNotSupportedError,
TaskNotCancelableError,
TaskNotFoundError,
UnsupportedOperationError,
} from '../../errors.js';
import {
JSONRPCRequest,
JSONRPCResponse,
MessageSendParams,
TaskPushNotificationConfig,
TaskIdParams,
ListTaskPushNotificationConfigParams,
DeleteTaskPushNotificationConfigParams,
DeleteTaskPushNotificationConfigResponse,
TaskQueryParams,
Task,
JSONRPCErrorResponse,
SendMessageSuccessResponse,
SetTaskPushNotificationConfigSuccessResponse,
GetTaskPushNotificationConfigSuccessResponse,
ListTaskPushNotificationConfigSuccessResponse,
GetTaskSuccessResponse,
CancelTaskSuccessResponse,
AgentCard,
GetTaskPushNotificationConfigParams,
GetAuthenticatedExtendedCardSuccessResponse,
} 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 {
endpoint: string;
fetchImpl?: typeof fetch;
}
export class JsonRpcTransport implements Transport {
private readonly customFetchImpl?: typeof fetch;
private readonly endpoint: string;
private requestIdCounter: number = 1;
constructor(options: JsonRpcTransportOptions) {
this.endpoint = options.endpoint;
this.customFetchImpl = options.fetchImpl;
}
async getExtendedAgentCard(options?: RequestOptions, idOverride?: number): Promise<AgentCard> {
const rpcResponse = await this._sendRpcRequest<
undefined,
GetAuthenticatedExtendedCardSuccessResponse
>('agent/getAuthenticatedExtendedCard', undefined, idOverride, options);
return rpcResponse.result;
}
async sendMessage(
params: MessageSendParams,
options?: RequestOptions,
idOverride?: number
): Promise<SendMessageResult> {
const rpcResponse = await this._sendRpcRequest<MessageSendParams, SendMessageSuccessResponse>(
'message/send',
params,
idOverride,
options
);
return rpcResponse.result;
}
async *sendMessageStream(
params: MessageSendParams,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined> {
yield* this._sendStreamingRequest('message/stream', params, options);
}
async setTaskPushNotificationConfig(
params: TaskPushNotificationConfig,
options?: RequestOptions,
idOverride?: number
): Promise<TaskPushNotificationConfig> {
const rpcResponse = await this._sendRpcRequest<
TaskPushNotificationConfig,
SetTaskPushNotificationConfigSuccessResponse
>('tasks/pushNotificationConfig/set', params, idOverride, options);
return rpcResponse.result;
}
async getTaskPushNotificationConfig(
params: GetTaskPushNotificationConfigParams,
options?: RequestOptions,
idOverride?: number
): Promise<TaskPushNotificationConfig> {
const rpcResponse = await this._sendRpcRequest<
GetTaskPushNotificationConfigParams,
GetTaskPushNotificationConfigSuccessResponse
>('tasks/pushNotificationConfig/get', params, idOverride, options);
return rpcResponse.result;
}
async listTaskPushNotificationConfig(
params: ListTaskPushNotificationConfigParams,
options?: RequestOptions,
idOverride?: number
): Promise<TaskPushNotificationConfig[]> {
const rpcResponse = await this._sendRpcRequest<
ListTaskPushNotificationConfigParams,
ListTaskPushNotificationConfigSuccessResponse
>('tasks/pushNotificationConfig/list', params, idOverride, options);
return rpcResponse.result;
}
async deleteTaskPushNotificationConfig(
params: DeleteTaskPushNotificationConfigParams,
options?: RequestOptions,
idOverride?: number
): Promise<void> {
await this._sendRpcRequest<
DeleteTaskPushNotificationConfigParams,
DeleteTaskPushNotificationConfigResponse
>('tasks/pushNotificationConfig/delete', params, idOverride, options);
}
async getTask(
params: TaskQueryParams,
options?: RequestOptions,
idOverride?: number
): Promise<Task> {
const rpcResponse = await this._sendRpcRequest<TaskQueryParams, GetTaskSuccessResponse>(
'tasks/get',
params,
idOverride,
options
);
return rpcResponse.result;
}
async cancelTask(
params: TaskIdParams,
options?: RequestOptions,
idOverride?: number
): Promise<Task> {
const rpcResponse = await this._sendRpcRequest<TaskIdParams, CancelTaskSuccessResponse>(
'tasks/cancel',
params,
idOverride,
options
);
return rpcResponse.result;
}
async *resubscribeTask(
params: TaskIdParams,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined> {
yield* this._sendStreamingRequest('tasks/resubscribe', params, options);
}
async callExtensionMethod<TExtensionParams, TExtensionResponse extends JSONRPCResponse>(
method: string,
params: TExtensionParams,
idOverride: number,
options?: RequestOptions
) {
return await this._sendRpcRequest<TExtensionParams, TExtensionResponse>(
method,
params,
idOverride,
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 A2ATransportOptions. '
);
}
private async _sendRpcRequest<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TParams extends { [key: string]: any },
TResponse extends JSONRPCResponse,
>(
method: string,
params: TParams,
idOverride: number | undefined,
options: RequestOptions | undefined
): Promise<TResponse> {
const requestId = idOverride ?? this.requestIdCounter++;
const rpcRequest: JSONRPCRequest = {
jsonrpc: '2.0',
method,
params: params,
id: requestId,
};
const httpResponse = await this._fetchRpc(rpcRequest, 'application/json', options);
if (!httpResponse.ok) {
let errorBodyText = '(empty or non-JSON response)';
let errorJson: JSONRPCErrorResponse;
try {
errorBodyText = await httpResponse.text();
errorJson = JSON.parse(errorBodyText);
} catch (e) {
throw new Error(
`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,
{ cause: e }
);
}
if (errorJson.jsonrpc && errorJson.error) {
throw JsonRpcTransport.mapToError(errorJson);
} else {
throw new Error(
`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`
);
}
}
const rpcResponse: JSONRPCResponse = await httpResponse.json();
if (rpcResponse.id !== requestId) {
throw new Error(
`JSON-RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}.`
);
}
if ('error' in rpcResponse) {
throw JsonRpcTransport.mapToError(rpcResponse);
}
return rpcResponse as TResponse;
}
private async _fetchRpc(
rpcRequest: JSONRPCRequest,
acceptHeader: string = 'application/json',
options?: RequestOptions
): Promise<Response> {
const requestInit: RequestInit = {
method: 'POST',
headers: {
...options?.serviceParameters,
'Content-Type': 'application/json',
Accept: acceptHeader,
},
body: JSON.stringify(rpcRequest),
signal: options?.signal,
};
return this._fetch(this.endpoint, requestInit);
}
private async *_sendStreamingRequest(
method: string,
params: unknown,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined> {
const clientRequestId = this.requestIdCounter++;
const rpcRequest: JSONRPCRequest = {
jsonrpc: '2.0',
method,
params: params as { [key: string]: unknown },
id: clientRequestId,
};
const response = await this._fetchRpc(rpcRequest, 'text/event-stream', options);
if (!response.ok) {
let errorBody = '';
let errorJson: JSONRPCErrorResponse;
try {
errorBody = await response.text();
errorJson = JSON.parse(errorBody);
} catch (e) {
throw new Error(
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,
{ cause: e }
);
}
if (errorJson.error) {
throw new Error(
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`
);
}
throw new Error(
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}`
);
}
if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {
throw new Error(
`Invalid response Content-Type for SSE stream for ${method}. Expected 'text/event-stream'.`
);
}
for await (const event of parseSseStream(response)) {
yield this._processSseEventData<A2AStreamEventData>(event.data, clientRequestId);
}
}
private _processSseEventData<TStreamItem>(
jsonData: string,
originalRequestId: number | string | null
): TStreamItem {
if (!jsonData.trim()) {
throw new Error('Attempted to process empty SSE event data.');
}
let a2aStreamResponse: JSONRPCResponse;
try {
a2aStreamResponse = JSON.parse(jsonData) as JSONRPCResponse;
} catch (e) {
throw new 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 {
switch (response.error.code) {
case -32001:
return new TaskNotFoundJSONRPCError(response);
case -32002:
return new TaskNotCancelableJSONRPCError(response);
case -32003:
return new PushNotificationNotSupportedJSONRPCError(response);
case -32004:
return new UnsupportedOperationJSONRPCError(response);
case -32005:
return new ContentTypeNotSupportedJSONRPCError(response);
case -32006:
return new InvalidAgentResponseJSONRPCError(response);
case -32007:
return new AuthenticatedExtendedCardNotConfiguredJSONRPCError(response);
default:
return new JSONRPCTransportError(response);
}
}
}
export class JsonRpcTransportFactoryOptions {
fetchImpl?: typeof fetch;
}
export class JsonRpcTransportFactory implements TransportFactory {
public static readonly name: TransportProtocolName = 'JSONRPC';
constructor(private readonly options?: JsonRpcTransportFactoryOptions) {}
get protocolName(): string {
return JsonRpcTransportFactory.name;
}
async create(url: string, _agentCard: AgentCard): Promise<Transport> {
return new JsonRpcTransport({
endpoint: url,
fetchImpl: this.options?.fetchImpl,
});
}
}
export class JSONRPCTransportError extends Error {
constructor(public errorResponse: JSONRPCErrorResponse) {
super(
`JSON-RPC error: ${errorResponse.error.message} (Code: ${errorResponse.error.code}) Data: ${JSON.stringify(errorResponse.error.data || {})}`
);
}
}
// Redeclare domain errors with the original JSON-RPC response as a field to be compatible
// with the legacy A2AClient built around JSON-RPC interface.
export class TaskNotFoundJSONRPCError extends TaskNotFoundError {
constructor(public errorResponse: JSONRPCErrorResponse) {
super();
}
}
export class TaskNotCancelableJSONRPCError extends TaskNotCancelableError {
constructor(public errorResponse: JSONRPCErrorResponse) {
super();
}
}
export class PushNotificationNotSupportedJSONRPCError extends PushNotificationNotSupportedError {
constructor(public errorResponse: JSONRPCErrorResponse) {
super();
}
}
export class UnsupportedOperationJSONRPCError extends UnsupportedOperationError {
constructor(public errorResponse: JSONRPCErrorResponse) {
super();
}
}
export class ContentTypeNotSupportedJSONRPCError extends ContentTypeNotSupportedError {
constructor(public errorResponse: JSONRPCErrorResponse) {
super();
}
}
export class InvalidAgentResponseJSONRPCError extends InvalidAgentResponseError {
constructor(public errorResponse: JSONRPCErrorResponse) {
super();
}
}
export class AuthenticatedExtendedCardNotConfiguredJSONRPCError extends AuthenticatedExtendedCardNotConfiguredError {
constructor(public errorResponse: JSONRPCErrorResponse) {
super();
}
}

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

@ -0,0 +1,59 @@
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';
export interface Transport {
getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard>;
sendMessage(params: MessageSendParams, options?: RequestOptions): Promise<SendMessageResult>;
sendMessageStream(
params: MessageSendParams,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined>;
setTaskPushNotificationConfig(
params: TaskPushNotificationConfig,
options?: RequestOptions
): Promise<TaskPushNotificationConfig>;
getTaskPushNotificationConfig(
params: GetTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<TaskPushNotificationConfig>;
listTaskPushNotificationConfig(
params: ListTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<TaskPushNotificationConfig[]>;
deleteTaskPushNotificationConfig(
params: DeleteTaskPushNotificationConfigParams,
options?: RequestOptions
): Promise<void>;
getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task>;
cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task>;
resubscribeTask(
params: TaskIdParams,
options?: RequestOptions
): AsyncGenerator<A2AStreamEventData, void, undefined>;
}
export interface TransportFactory {
get protocolName(): string;
create(url: string, agentCard: AgentCard): Promise<Transport>;
}

13
src/constants.ts Normal file
View File

@ -0,0 +1,13 @@
/**
* Shared constants for the A2A library
*/
/**
* The well-known path for the agent card
*/
export const AGENT_CARD_PATH = '.well-known/agent-card.json';
/**
* The name of the extension header used in http
*/
export const HTTP_EXTENSION_HEADER = 'X-A2A-Extensions';

1
src/core.ts Normal file
View File

@ -0,0 +1 @@
export type TransportProtocolName = 'JSONRPC' | 'HTTP+JSON' | 'GRPC' | (string & {});

69
src/errors.ts Normal file
View File

@ -0,0 +1,69 @@
// 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) {
super(message ?? 'Task not found');
this.name = 'TaskNotFoundError';
}
}
export class TaskNotCancelableError extends Error {
constructor(message?: string) {
super(message ?? 'Task cannot be canceled');
this.name = 'TaskNotCancelableError';
}
}
export class PushNotificationNotSupportedError extends Error {
constructor(message?: string) {
super(message ?? 'Push Notification is not supported');
this.name = 'PushNotificationNotSupportedError';
}
}
export class UnsupportedOperationError extends Error {
constructor(message?: string) {
super(message ?? 'This operation is not supported');
this.name = 'UnsupportedOperationError';
}
}
export class ContentTypeNotSupportedError extends Error {
constructor(message?: string) {
super(message ?? 'Incompatible content types');
this.name = 'ContentTypeNotSupportedError';
}
}
export class InvalidAgentResponseError extends Error {
constructor(message?: string) {
super(message ?? 'Invalid agent response type');
this.name = 'InvalidAgentResponseError';
}
}
export class AuthenticatedExtendedCardNotConfiguredError extends Error {
constructor(message?: string) {
super(message ?? 'Authenticated Extended Card not configured');
this.name = 'AuthenticatedExtendedCardNotConfiguredError';
}
}

48
src/extensions.ts Normal file
View File

@ -0,0 +1,48 @@
/**
* A2A Protocol Extension URI.
*/
export type ExtensionURI = string;
/**
* A collection of {@link ExtensionURI}.
*/
export type Extensions = ExtensionURI[];
export const Extensions = {
/**
* Creates new {@link Extensions} from `current` and `additional`.
* If `current` already contains `additional` it is returned unmodified.
*/
createFrom: (current: Extensions | undefined, additional: ExtensionURI): Extensions => {
if (current?.includes(additional)) {
return current;
}
return [...(current ?? []), additional];
},
/**
* Creates {@link Extensions} from comma separated extensions identifiers as per
* https://a2a-protocol.org/latest/specification/#326-service-parameters.
* Parses the output of `toServiceParameter`.
*/
parseServiceParameter: (value: string | undefined): Extensions => {
if (!value) {
return [];
}
const unique = new Set(
value
.split(',')
.map((ext) => ext.trim())
.filter((ext) => ext.length > 0)
);
return Array.from(unique);
},
/**
* Converts {@link Extensions} to comma separated extensions identifiers as per
* https://a2a-protocol.org/latest/specification/#326-service-parameters.
*/
toServiceParameter: (value: Extensions): string => {
return value.join(',');
},
};

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

@ -1,7 +1,11 @@
/**
* Main entry point for the A2A Server V2 library.
* Exports the common types.
*
* Use the client/index.ts file to import the client-only codebase.
* Use the server/index.ts file to import the server-only codebase.
*/
export * from "./types.js";
export type { A2AResponse } from "./a2a_response.js";
export * from './types.js';
export type { A2AResponse } from './a2a_response.js';
export { AGENT_CARD_PATH, HTTP_EXTENSION_HEADER } from './constants.js';
export { Extensions, type ExtensionURI } from './extensions.js';

View File

@ -1,12 +1,12 @@
import { googleAI } from "@genkit-ai/googleai";
import { genkit } from "genkit";
import { dirname } from "path";
import { fileURLToPath } from "url";
import { googleAI } from '@genkit-ai/googleai';
import { genkit } from 'genkit';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
export const ai = genkit({
plugins: [googleAI()],
model: googleAI.model("gemini-2.0-flash"),
model: googleAI.model('gemini-2.0-flash'),
promptDir: dirname(fileURLToPath(import.meta.url)),
});
export { z } from "genkit";
export { z } from 'genkit';

View File

@ -1,4 +1,4 @@
import express from "express";
import express from 'express';
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
import {
@ -7,23 +7,27 @@ import {
TaskState,
TaskStatusUpdateEvent,
TextPart,
Message
} from "../../../index.js";
Message,
AGENT_CARD_PATH,
TaskArtifactUpdateEvent,
Artifact,
Part,
} from '../../../index.js';
import {
InMemoryTaskStore,
TaskStore,
AgentExecutor,
RequestContext,
ExecutionEventBus,
DefaultRequestHandler
} from "../../../server/index.js";
import { A2AExpressApp } from "../../../server/express/index.js";
import { MessageData } from "genkit";
import { ai } from "./genkit.js";
import { searchMovies, searchPeople } from "./tools.js";
DefaultRequestHandler,
} from '../../../server/index.js';
import { agentCardHandler, jsonRpcHandler, UserBuilder } from '../../../server/express/index.js';
import { MessageData } from 'genkit';
import { ai } from './genkit.js';
import { searchMovies, searchPeople } from './tools.js';
if (!process.env.GEMINI_API_KEY || !process.env.TMDB_API_KEY) {
console.error("GEMINI_API_KEY and TMDB_API_KEY environment variables are required")
console.error('GEMINI_API_KEY and TMDB_API_KEY environment variables are required');
process.exit(1);
}
@ -39,18 +43,12 @@ const movieAgentPrompt = ai.prompt('movie_agent');
class MovieAgentExecutor implements AgentExecutor {
private cancelledTasks = new Set<string>();
public cancelTask = async (
taskId: string,
eventBus: ExecutionEventBus,
): Promise<void> => {
this.cancelledTasks.add(taskId);
// The execute loop is responsible for publishing the final state
};
public cancelTask = async (taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {
this.cancelledTasks.add(taskId);
// The execute loop is responsible for publishing the final state
};
async execute(
requestContext: RequestContext,
eventBus: ExecutionEventBus
): Promise<void> {
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
const userMessage = requestContext.userMessage;
const existingTask = requestContext.task;
@ -101,10 +99,10 @@ class MovieAgentExecutor implements AgentExecutor {
// 3. Prepare messages for Genkit prompt
const historyForGenkit = contexts.get(contextId) || [];
if (!historyForGenkit.find(m => m.messageId === userMessage.messageId)) {
if (!historyForGenkit.find((m) => m.messageId === userMessage.messageId)) {
historyForGenkit.push(userMessage);
}
contexts.set(contextId, historyForGenkit)
contexts.set(contextId, historyForGenkit);
const messages: MessageData[] = historyForGenkit
.map((m) => ({
@ -143,7 +141,9 @@ class MovieAgentExecutor implements AgentExecutor {
return;
}
const goal = existingTask?.metadata?.goal as string | undefined || userMessage.metadata?.goal as string | undefined;
const goal =
(existingTask?.metadata?.goal as string | undefined) ||
(userMessage.metadata?.goal as string | undefined);
try {
// 4. Run the Genkit prompt
@ -177,9 +177,12 @@ class MovieAgentExecutor implements AgentExecutor {
console.info(`[MovieAgentExecutor] Prompt response: ${responseText}`);
const lines = responseText.trim().split('\n');
const finalStateLine = lines.at(-1)?.trim().toUpperCase();
const agentReplyText = lines.slice(0, lines.length - 1).join('\n').trim();
const agentReplyText = lines
.slice(0, lines.length - 1)
.join('\n')
.trim();
let finalA2AState: TaskState = "unknown";
let finalA2AState: TaskState = 'unknown';
if (finalStateLine === 'COMPLETED') {
finalA2AState = 'completed';
@ -192,40 +195,53 @@ 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)
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,
};
eventBus.publish(finalUpdate);
console.log(
`[MovieAgentExecutor] Task ${taskId} finished with state: ${finalA2AState}`
);
console.log(`[MovieAgentExecutor] Task ${taskId} finished with state: ${finalA2AState}`);
} catch (error: any) {
console.error(
`[MovieAgentExecutor] Error processing task ${taskId}:`,
error
);
console.error(`[MovieAgentExecutor] Error processing task ${taskId}:`, error);
const errorUpdate: TaskStatusUpdateEvent = {
kind: 'status-update',
taskId: taskId,
@ -254,13 +270,13 @@ class MovieAgentExecutor implements AgentExecutor {
const movieAgentCard: AgentCard = {
name: 'Movie Agent',
description: 'An agent that can answer questions about movies and actors using TMDB.',
// Adjust the base URL and port as needed. /a2a is the default base in A2AExpressApp
url: 'http://localhost:41241/', // Example: if baseUrl in A2AExpressApp
url: 'http://localhost:41241/',
provider: {
organization: 'A2A Samples',
url: 'https://example.com/a2a-samples' // Added provider URL
url: 'https://example.com/a2a-samples', // Added provider URL
},
version: '0.0.2', // Incremented version
protocolVersion: '0.3.0',
capabilities: {
streaming: true, // The new framework supports streaming
pushNotifications: false, // Assuming not implemented for this agent yet
@ -286,7 +302,7 @@ const movieAgentCard: AgentCard = {
'Which came out first, Jurassic Park or Terminator 2?',
],
inputModes: ['text'], // Explicitly defining for skill
outputModes: ['text', 'task-status'] // Explicitly defining for skill
outputModes: ['text', 'task-status'], // Explicitly defining for skill
},
],
supportsAuthenticatedExtendedCard: false,
@ -300,24 +316,24 @@ async function main() {
const agentExecutor: AgentExecutor = new MovieAgentExecutor();
// 3. Create DefaultRequestHandler
const requestHandler = new DefaultRequestHandler(
movieAgentCard,
taskStore,
agentExecutor
);
const requestHandler = new DefaultRequestHandler(movieAgentCard, taskStore, agentExecutor);
// 4. Create and setup A2AExpressApp
const appBuilder = new A2AExpressApp(requestHandler);
const expressApp = appBuilder.setupRoutes(express());
// 4. Create and setup Express.js app
const app = express();
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
app.use(jsonRpcHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
// 5. Start the server
const PORT = process.env.PORT || 41241;
expressApp.listen(PORT, () => {
app.listen(PORT, (err) => {
if (err) {
throw err;
}
console.log(`[MovieAgent] Server using new framework started on http://localhost:${PORT}`);
console.log(`[MovieAgent] Agent Card: http://localhost:${PORT}/.well-known/agent.json`);
console.log(`[MovieAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`);
console.log('[MovieAgent] Press Ctrl+C to stop the server');
});
}
main().catch(console.error);

View File

@ -8,24 +8,22 @@ export async function callTmdbApi(endpoint: string, query: string) {
// Validate API key
const apiKey = process.env.TMDB_API_KEY;
if (!apiKey) {
throw new Error("TMDB_API_KEY environment variable is not set");
throw new Error('TMDB_API_KEY environment variable is not set');
}
try {
// Make request to TMDB API
const url = new URL(`https://api.themoviedb.org/3/search/${endpoint}`);
url.searchParams.append("api_key", apiKey);
url.searchParams.append("query", query);
url.searchParams.append("include_adult", "false");
url.searchParams.append("language", "en-US");
url.searchParams.append("page", "1");
url.searchParams.append('api_key', apiKey);
url.searchParams.append('query', query);
url.searchParams.append('include_adult', 'false');
url.searchParams.append('language', 'en-US');
url.searchParams.append('page', '1');
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(
`TMDB API error: ${response.status} ${response.statusText}`
);
throw new Error(`TMDB API error: ${response.status} ${response.statusText}`);
}
return await response.json();

View File

@ -1,18 +1,18 @@
import { ai, z } from "./genkit.js";
import { callTmdbApi } from "./tmdb.js";
import { ai, z } from './genkit.js';
import { callTmdbApi } from './tmdb.js';
export const searchMovies = ai.defineTool(
{
name: "searchMovies",
description: "search TMDB for movies by title",
name: 'searchMovies',
description: 'search TMDB for movies by title',
inputSchema: z.object({
query: z.string(),
}),
},
async ({ query }) => {
console.log("[tmdb:searchMovies]", JSON.stringify(query));
console.log('[tmdb:searchMovies]', JSON.stringify(query));
try {
const data = await callTmdbApi("movie", query);
const data = await callTmdbApi('movie', query);
// Only modify image paths to be full URLs
const results = data.results.map((movie: any) => {
@ -30,7 +30,7 @@ export const searchMovies = ai.defineTool(
results,
};
} catch (error) {
console.error("Error searching movies:", error);
console.error('Error searching movies:', error);
// Re-throwing allows Genkit/the caller to handle it appropriately
throw error;
}
@ -39,16 +39,16 @@ export const searchMovies = ai.defineTool(
export const searchPeople = ai.defineTool(
{
name: "searchPeople",
description: "search TMDB for people by name",
name: 'searchPeople',
description: 'search TMDB for people by name',
inputSchema: z.object({
query: z.string(),
}),
},
async ({ query }) => {
console.log("[tmdb:searchPeople]", JSON.stringify(query));
console.log('[tmdb:searchPeople]', JSON.stringify(query));
try {
const data = await callTmdbApi("person", query);
const data = await callTmdbApi('person', query);
// Only modify image paths to be full URLs
const results = data.results.map((person: any) => {
@ -77,7 +77,7 @@ export const searchPeople = ai.defineTool(
results,
};
} catch (error) {
console.error("Error searching people:", error);
console.error('Error searching people:', error);
// Re-throwing allows Genkit/the caller to handle it appropriately
throw error;
}

View File

@ -0,0 +1,9 @@
# Sample Agent
This agent is a sample to emulate the task flow in a streaming scenario. To run:
```bash
npm run agents:sample-agent
```
The agent will start on `http://localhost:41241`.

View File

@ -0,0 +1,126 @@
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
import {
Task,
TaskStatusUpdateEvent,
Message,
TaskArtifactUpdateEvent,
Artifact,
} from '../../../index.js';
import { AgentExecutor, RequestContext, ExecutionEventBus } from '../../../server/index.js';
/**
* SampleAgentExecutor implements the agent's core logic.
*/
export class SampleAgentExecutor implements AgentExecutor {
public cancelTask = async (_taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {};
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
const userMessage = requestContext.userMessage;
const existingTask = requestContext.task;
// Determine IDs for the task and context
const taskId = requestContext.taskId;
const contextId = requestContext.contextId;
console.log(
`[SampleAgentExecutor] Processing message ${userMessage.messageId} for task ${taskId} (context: ${contextId})`
);
// 1. Publish initial Task event if it's a new task
if (!existingTask) {
const initialTask: Task = {
kind: 'task',
id: taskId,
contextId: contextId,
status: {
state: 'submitted',
timestamp: new Date().toISOString(),
},
history: [userMessage], // Start history with the current user message
metadata: userMessage.metadata, // Carry over metadata from message if any
};
eventBus.publish(initialTask);
}
// 2. Publish "working" status update
const workingStatusUpdate: TaskStatusUpdateEvent = {
kind: 'status-update',
taskId: taskId,
contextId: contextId,
status: {
state: 'working',
message: {
kind: 'message',
role: 'agent',
messageId: uuidv4(),
parts: [{ kind: 'text', text: 'Processing your question' }],
taskId: taskId,
contextId: contextId,
},
timestamp: new Date().toISOString(),
},
final: false,
};
eventBus.publish(workingStatusUpdate);
// 3. Publish artifact with the result
const agentReplyText = this.parseInputMessage(userMessage);
console.info(`[SampleAgentExecutor] Prompt response: ${agentReplyText}`);
const artifactId = uuidv4();
const resultArtifact: Artifact = {
artifactId: artifactId,
name: 'Result',
description: 'The final result from the agent.',
parts: [{ kind: 'text', text: agentReplyText }],
};
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',
timestamp: new Date().toISOString(),
},
final: true,
};
eventBus.publish(finalUpdate);
console.log(`[SampleAgentExecutor] Task ${taskId} finished with state: completed`);
}
parseInputMessage(message: Message): string {
/** Process the user query and return a response. */
const textPart = message.parts.find((part) => part.kind === 'text');
const query = textPart ? textPart.text.trim() : '';
if (!query) {
return 'Hello! Please provide a message for me to respond to.';
}
// Simple responses based on input
const queryLower = query.toLowerCase();
if (queryLower.includes('hello') || queryLower.includes('hi')) {
return 'Hello World! Nice to meet you!';
} else if (queryLower.includes('how are you')) {
return "I'm doing great! Thanks for asking. How can I help you today?";
} else if (queryLower.includes('goodbye') || queryLower.includes('bye')) {
return 'Goodbye! Have a wonderful day!';
} else {
return `Hello World! You said: '${query}'. Thanks for your message!`;
}
}
}

View File

@ -0,0 +1,74 @@
import express from 'express';
import { AgentCard, AGENT_CARD_PATH } from '../../../index.js';
import {
InMemoryTaskStore,
TaskStore,
AgentExecutor,
DefaultRequestHandler,
} from '../../../server/index.js';
import { agentCardHandler, jsonRpcHandler, UserBuilder } from '../../../server/express/index.js';
import { SampleAgentExecutor } from './agent_executor.js';
// --- Server Setup ---
const sampleAgentCard: AgentCard = {
name: 'Sample Agent',
description:
'A sample agent to test the stream functionality and simulate the flow of tasks statuses.',
url: 'http://localhost:41241/',
provider: {
organization: 'A2A Samples',
url: 'https://example.com/a2a-samples', // Added provider URL
},
version: '1.0.0', // Incremented version
protocolVersion: '0.3.0',
capabilities: {
streaming: true, // The new framework supports streaming
pushNotifications: false, // Assuming not implemented for this agent yet
stateTransitionHistory: true, // Agent uses history
},
defaultInputModes: ['text'],
defaultOutputModes: ['text', 'task-status'], // task-status is a common output mode
skills: [
{
id: 'sample_agent',
name: 'Sample Agent',
description: 'Simulate the general flow of a streaming agent.',
tags: ['sample'],
examples: ['hi', 'hello world', 'how are you', 'goodbye'],
inputModes: ['text'], // Explicitly defining for skill
outputModes: ['text', 'task-status'], // Explicitly defining for skill
},
],
supportsAuthenticatedExtendedCard: false,
};
async function main() {
// 1. Create TaskStore
const taskStore: TaskStore = new InMemoryTaskStore();
// 2. Create AgentExecutor
const agentExecutor: AgentExecutor = new SampleAgentExecutor();
// 3. Create DefaultRequestHandler
const requestHandler = new DefaultRequestHandler(sampleAgentCard, taskStore, agentExecutor);
// 4. Create and setup Express app
const app = express();
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
app.use(jsonRpcHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
// 5. Start the server
const PORT = process.env.PORT || 41241;
app.listen(PORT, (err) => {
if (err) {
throw err;
}
console.log(`[SampleAgent] Server using new framework started on http://localhost:${PORT}`);
console.log(`[SampleAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`);
console.log('[SampleAgent] Press Ctrl+C to stop the server');
});
}
main().catch(console.error);

View File

@ -0,0 +1,80 @@
# Authentication Sample
This sample demonstrates how to implement **Bearer Token authentication**. It shows how to intercept requests, validate tokens, extract the user generated by the authentication and pass it to the context.
## Key Components
- `index.ts`: generates an `AgentCard` that requires for the Bearer authentication for incoming requests and starts the server with the authentication middleware and user builder.
- `authentication_middleware.ts`: creates the middleware responsible for authentication. It uses Passport to support Bearer token authorization and populates the `user` parameter in the Request object with the plain extracted object.
- `user_builder.ts`: defines the callback for the user extraction. It expects the user object (populated by the middleware) to contain specific values (`email`, `userName`, `role`) which are used to build the `CustomUser` object.
- `agent_executor.ts`: creates a simple agent executor that checks the authentication status of the user object present in the context, which is expected to be an instance of `CustomUser` in case of successful authentication, and sends back the content.
To test the agent:
```bash
npm run agents:authentication-agent
```
The agent will start on `http://localhost:41241`.
Use this [tool](https://www.jwt.io/) to generate your Json Web Token with the JWT Encoder. The secret key for the signature is `a2a-secret-for-authentication-sample`.
For a successful authentication the payload data MUST contain these values: "email", "userName", "role".
```bash
curl -X POST http://localhost:41241/
-H "Authorization: Bearer <jwt-token>"
-H "Content-Type: application/json"
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"role": "user",
"parts": [
{
"kind": "text",
"text": "Hello, who am i?"
}
],
"messageId": "9229e770-767c-417b-a0b0-f0741243c589"
}
}
}'
```
Expected response, with successful authentication:
```json
{
"jsonrpc":"2.0",
"id":1,
"result": {
"kind":"message",
"role":"agent",
"parts":[ {
"kind":"text",
"text":"The request is coming from the authenticated user <your-userName>, with email <your-email> and role <your-role>."
} ]
}
}
```
Expected response, with failed authentication:
```json
{
"jsonrpc":"2.0",
"id":1,
"result": {
"kind":"message",
"role":"agent",
"parts":[ {
"kind":"text",
"text":"The request is not coming from an authenticated user."
} ]
}
}
```

View File

@ -0,0 +1,28 @@
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
import { AgentExecutor, ExecutionEventBus, RequestContext } from '../../server/index.js';
import { CustomUser } from './user_builder.js';
import { Message } from '../../types.js';
export class AuthenticationAgentExecutor implements AgentExecutor {
public cancelTask = async (_taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {};
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
let finalText;
if (
requestContext.context?.user?.isAuthenticated &&
requestContext.context.user instanceof CustomUser
) {
const customUser = requestContext.context.user;
finalText = `The request is coming from the authenticated user ${customUser.userName}, with email ${customUser.email} and role ${customUser.role}.`;
} else {
finalText = `The request is not coming from an authenticated user.`;
}
const finalMessage: Message = {
kind: 'message',
messageId: uuidv4(),
role: 'agent',
parts: [{ kind: 'text', text: finalText }],
};
eventBus.publish(finalMessage);
}
}

View File

@ -0,0 +1,31 @@
import { NextFunction, Request, RequestHandler, Response } from 'express';
import passport from 'passport';
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
passport.use(
new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'a2a-secret-for-authentication-sample',
},
(jwt_payload, done) => {
return done(null, jwt_payload);
}
)
);
export const authenticationHandler: RequestHandler = (
req: Request,
res: Response,
next: NextFunction
) => {
passport.authenticate('jwt', { session: false }, (err: any, user: any) => {
if (err) {
return next(err);
}
if (user) {
req.user = user;
}
next();
})(req, res, next);
};

View File

@ -0,0 +1,88 @@
import express from 'express';
import { AgentCard } from '../../index.js';
import {
InMemoryTaskStore,
TaskStore,
AgentExecutor,
DefaultRequestHandler,
} from '../../server/index.js';
import { jsonRpcHandler } from '../../server/express/index.js';
import { AuthenticationAgentExecutor } from './agent_executor.js';
import { userBuilder } from './user_builder.js';
import { authenticationHandler } from './authentication_middleware.js';
// --- Server Setup ---
const authenticationAgentCard: AgentCard = {
name: 'Sample Authentication Agent',
description: 'A sample agent to test the authentication functionality',
url: 'http://localhost:41241/',
provider: {
organization: 'A2A Samples',
url: 'https://example.com/a2a-samples',
},
version: '1.0.0',
protocolVersion: '0.3.0',
capabilities: {
stateTransitionHistory: true, // Agent uses history
},
defaultInputModes: ['text'],
defaultOutputModes: ['text', 'task-status'],
skills: [
{
id: 'sample_agent',
name: 'Sample Agent',
description: 'Simulate the general flow of an agent with authentication feature.',
tags: ['sample'],
examples: ['hello, who am i?'],
inputModes: ['text'],
outputModes: ['text', 'task-status'],
},
],
supportsAuthenticatedExtendedCard: false,
security: [{ Bearer: [] }],
securitySchemes: { Bearer: { type: 'http', scheme: 'bearer' } },
};
async function main() {
// 1. Create TaskStore
const taskStore: TaskStore = new InMemoryTaskStore();
// 2. Create AgentExecutor
const agentExecutor: AgentExecutor = new AuthenticationAgentExecutor();
// 3. Create DefaultRequestHandler
const requestHandler = new DefaultRequestHandler(
authenticationAgentCard,
taskStore,
agentExecutor
);
// 4. Create and setup express app, with authentication middleware and user builder
const app = express();
app.use(express.json());
app.use(authenticationHandler);
app.use(
jsonRpcHandler({
requestHandler,
userBuilder,
})
);
// 5. Start the server
const PORT = process.env.PORT || 41241;
app.listen(PORT, (err: unknown) => {
if (err) {
throw err;
}
console.log(
`[AuthenticationAgent] Server using new framework started on http://localhost:${PORT}`
);
console.log(
`[AuthenticationAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`
);
console.log('[AuthenticationAgent] Press Ctrl+C to stop the server');
});
}
main().catch(console.error);

View File

@ -0,0 +1,22 @@
import { Request } from 'express';
import { UnauthenticatedUser, User } from '../../server/index.js';
import { UserBuilder } from '../../server/express/index.js';
export class CustomUser implements User {
public isAuthenticated: boolean = true;
constructor(
public userName: string,
public email: string,
public role: string
) {}
}
export const userBuilder: UserBuilder = async (req: Request): Promise<User> => {
if ('user' in req && typeof req.user === 'object') {
const user = req.user;
if ('userName' in user && 'email' in user && 'role' in user) {
return new CustomUser(user.userName as string, user.email as string, user.role as string);
}
}
return new UnauthenticatedUser();
};

View File

@ -1,7 +1,8 @@
#!/usr/bin/env node
import readline from "node:readline";
import crypto from "node:crypto";
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
@ -11,28 +12,37 @@ import {
Message,
Task, // Added for direct Task events
// Other types needed for message/part handling
TaskState,
FilePart,
DataPart,
// Type for the agent card
AgentCard,
Part // Added for explicit Part typing
} from "../index.js";
Part, // Added for explicit Part typing
AGENT_CARD_PATH,
} from '../index.js';
import { A2AClient } 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 = {
reset: "\x1b[0m",
bright: "\x1b[1m",
dim: "\x1b[2m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
magenta: "\x1b[35m",
cyan: "\x1b[36m",
gray: "\x1b[90m",
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
gray: '\x1b[90m',
};
// --- Helper Functions ---
@ -40,68 +50,114 @@ function colorize(color: keyof typeof colors, text: string): string {
return `${colors[color]}${text}${colors.reset}`;
}
function generateId(): string { // Renamed for more general use
function generateId(): string {
// Renamed for more general use
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 client = new A2AClient(serverUrl);
let agentName = "Agent"; // Default, try to get from agent card later
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 ---
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: colorize("cyan", "You: "),
prompt: colorize('cyan', 'You: '),
});
// --- Response Handling ---
// Function now accepts the unwrapped event payload directly
function printAgentEvent(
event: TaskStatusUpdateEvent | TaskArtifactUpdateEvent
) {
function printAgentEvent(event: TaskStatusUpdateEvent | TaskArtifactUpdateEvent) {
const timestamp = new Date().toLocaleTimeString();
const prefix = colorize("magenta", `\n${agentName} [${timestamp}]:`);
const prefix = colorize('magenta', `\n${agentName} [${timestamp}]:`);
// Check if it's a TaskStatusUpdateEvent
if (event.kind === "status-update") {
if (event.kind === 'status-update') {
const update = event as TaskStatusUpdateEvent; // Cast for type safety
const state = update.status.state;
let stateEmoji = "❓";
let stateColor: keyof typeof colors = "yellow";
let stateEmoji = '❓';
let stateColor: keyof typeof colors = 'yellow';
switch (state) {
case "working":
stateEmoji = "⏳";
stateColor = "blue";
case 'working':
stateEmoji = '⏳';
stateColor = 'blue';
break;
case "input-required":
stateEmoji = "🤔";
stateColor = "yellow";
case 'input-required':
stateEmoji = '🤔';
stateColor = 'yellow';
break;
case "completed":
stateEmoji = "✅";
stateColor = "green";
case 'completed':
stateEmoji = '✅';
stateColor = 'green';
break;
case "canceled":
stateEmoji = "⏹️";
stateColor = "gray";
case 'canceled':
stateEmoji = '⏹️';
stateColor = 'gray';
break;
case "failed":
stateEmoji = "❌";
stateColor = "red";
case 'failed':
stateEmoji = '❌';
stateColor = 'red';
break;
default:
stateEmoji = "ℹ️"; // For other states like submitted, rejected etc.
stateColor = "dim";
stateEmoji = 'ℹ️'; // For other states like submitted, rejected etc.
stateColor = 'dim';
break;
}
console.log(
`${prefix} ${stateEmoji} Status: ${colorize(stateColor, state)} (Task: ${update.taskId}, Context: ${update.contextId}) ${update.final ? colorize("bright", "[FINAL]") : ""}`
`${prefix} ${stateEmoji} Status: ${colorize(stateColor, state)} (Task: ${update.taskId}, Context: ${update.contextId}) ${update.final ? colorize('bright', '[FINAL]') : ''}`
);
if (update.status.message) {
@ -109,17 +165,18 @@ function printAgentEvent(
}
}
// Check if it's a TaskArtifactUpdateEvent
else if (event.kind === "artifact-update") {
else if (event.kind === 'artifact-update') {
const update = event as TaskArtifactUpdateEvent; // Cast for type safety
console.log(
`${prefix} 📄 Artifact Received: ${update.artifact.name || "(unnamed)"
`${prefix} 📄 Artifact Received: ${
update.artifact.name || '(unnamed)'
} (ID: ${update.artifact.artifactId}, Task: ${update.taskId}, Context: ${update.contextId})`
);
// Create a temporary message-like structure to reuse printMessageContent
printMessageContent({
messageId: generateId(), // Dummy messageId
kind: "message", // Dummy kind
role: "agent", // Assuming artifact parts are from agent
kind: 'message', // Dummy kind
role: 'agent', // Assuming artifact parts are from agent
parts: update.artifact.parts,
taskId: update.taskId,
contextId: update.contextId,
@ -128,32 +185,38 @@ function printAgentEvent(
// This case should ideally not be reached if called correctly
console.log(
prefix,
colorize("yellow", "Received unknown event type in printAgentEvent:"),
colorize('yellow', 'Received unknown event type in printAgentEvent:'),
event
);
}
}
function printMessageContent(message: Message) {
message.parts.forEach((part: Part, index: number) => { // Added explicit Part type
const partPrefix = colorize("red", ` Part ${index + 1}:`);
if (part.kind === "text") { // Check kind property
console.log(`${partPrefix} ${colorize("green", "📝 Text:")}`, part.text);
} else if (part.kind === "file") { // Check kind property
message.parts.forEach((part: Part, index: number) => {
// Added explicit Part type
const partPrefix = colorize('red', ` Part ${index + 1}:`);
if (part.kind === 'text') {
// Check kind property
console.log(`${partPrefix} ${colorize('green', '📝 Text:')}`, part.text);
} else if (part.kind === 'file') {
// Check kind property
const filePart = part as FilePart;
console.log(
`${partPrefix} ${colorize("blue", "📄 File:")} Name: ${filePart.file.name || "N/A"
}, Type: ${filePart.file.mimeType || "N/A"}, Source: ${("bytes" in filePart.file) ? "Inline (bytes)" : filePart.file.uri
`${partPrefix} ${colorize('blue', '📄 File:')} Name: ${
filePart.file.name || 'N/A'
}, Type: ${filePart.file.mimeType || 'N/A'}, Source: ${
'bytes' in filePart.file ? 'Inline (bytes)' : filePart.file.uri
}`
);
} else if (part.kind === "data") { // Check kind property
} else if (part.kind === 'data') {
// Check kind property
const dataPart = part as DataPart;
console.log(
`${partPrefix} ${colorize("yellow", "📊 Data:")}`,
`${partPrefix} ${colorize('yellow', '📊 Data:')}`,
JSON.stringify(dataPart.data, null, 2)
);
} else {
console.log(`${partPrefix} ${colorize("yellow", "Unsupported part kind:")}`, part);
console.log(`${partPrefix} ${colorize('yellow', 'Unsupported part kind:')}`, part);
}
});
}
@ -162,70 +225,86 @@ function printMessageContent(message: Message) {
async function fetchAndDisplayAgentCard() {
// Use the client's getAgentCard method.
// The client was initialized with serverUrl, which is the agent's base URL.
console.log(
colorize("dim", `Attempting to fetch agent card from agent at: ${serverUrl}`)
);
console.log(colorize('dim', `Attempting to fetch agent card from agent at: ${serverUrl}`));
try {
// client.getAgentCard() uses the agentBaseUrl provided during client construction
const card: AgentCard = await client.getAgentCard();
agentName = card.name || "Agent"; // Update global agent name
console.log(colorize("green", `✓ Agent Card Found:`));
console.log(` Name: ${colorize("bright", agentName)}`);
agentName = card.name || 'Agent'; // Update global agent name
console.log(colorize('green', `✓ Agent Card Found:`));
console.log(` Name: ${colorize('bright', agentName)}`);
if (card.description) {
console.log(` Description: ${card.description}`);
}
console.log(` Version: ${card.version || "N/A"}`);
console.log(` Version: ${card.version || 'N/A'}`);
if (card.capabilities?.streaming) {
console.log(` Streaming: ${colorize("green", "Supported")}`);
console.log(` Streaming: ${colorize('green', 'Supported')}`);
} else {
console.log(` Streaming: ${colorize("yellow", "Not Supported (or not specified)")}`);
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).
} catch (error: any) {
console.log(
colorize("yellow", `⚠️ Error fetching or parsing agent card`)
);
console.log(colorize('yellow', `⚠️ Error fetching or parsing agent card`));
throw error;
}
}
// --- Main Loop ---
async function main() {
console.log(colorize("bright", `A2A Terminal Client`));
console.log(colorize("dim", `Agent Base URL: ${serverUrl}`));
console.log(colorize('bright', `A2A Terminal Client`));
console.log(colorize('dim', `Agent Base URL: ${serverUrl}`));
await fetchAndDisplayAgentCard(); // Fetch the card before starting the loop
console.log(colorize("dim", `No active task or context initially. Use '/new' to start a fresh session or send a message.`));
console.log(
colorize("green", `Enter messages, or use '/new' to start a new session. '/exit' to quit.`)
colorize(
'dim',
`No active task or context initially. Use '/new' to start a fresh session or send a message.`
)
);
console.log(
colorize('green', `Enter messages, or use '/new' to start a new session. '/exit' to quit.`)
);
rl.setPrompt(colorize("cyan", `${agentName} > You: `)); // Set initial prompt
rl.setPrompt(colorize('cyan', `${agentName} > You: `)); // Set initial prompt
rl.prompt();
rl.on("line", async (line) => {
rl.on('line', async (line) => {
const input = line.trim();
rl.setPrompt(colorize("cyan", `${agentName} > You: `)); // Ensure prompt reflects current agentName
rl.setPrompt(colorize('cyan', `${agentName} > You: `)); // Ensure prompt reflects current agentName
if (!input) {
rl.prompt();
return;
}
if (input.toLowerCase() === "/new") {
if (input.toLowerCase() === '/new') {
currentTaskId = undefined;
currentContextId = undefined; // Reset contextId on /new
console.log(
colorize("bright", `✨ Starting new session. Task and Context IDs are cleared.`)
);
console.log(colorize('bright', `✨ Starting new session. Task and Context IDs are cleared.`));
rl.prompt();
return;
}
if (input.toLowerCase() === "/exit") {
if (input.toLowerCase() === '/exit') {
rl.close();
return;
}
@ -235,11 +314,11 @@ async function main() {
const messagePayload: Message = {
messageId: messageId,
kind: "message", // Required by Message interface
role: "user",
kind: 'message', // Required by Message interface
role: 'user',
parts: [
{
kind: "text", // Required by TextPart interface
kind: 'text', // Required by TextPart interface
text: input,
},
],
@ -254,7 +333,6 @@ async function main() {
messagePayload.contextId = currentContextId;
}
const params: MessageSendParams = {
message: messagePayload,
// Optional: configuration for streaming, blocking, etc.
@ -265,93 +343,109 @@ async function main() {
};
try {
console.log(colorize("red", "Sending message..."));
console.log(colorize('red', 'Sending message...'));
// Use sendMessageStream
const stream = client.sendMessageStream(params);
// Iterate over the events from the stream
for await (const event of stream) {
const timestamp = new Date().toLocaleTimeString(); // Get fresh timestamp for each event
const prefix = colorize("magenta", `\n${agentName} [${timestamp}]:`);
const prefix = colorize('magenta', `\n${agentName} [${timestamp}]:`);
if (event.kind === "status-update" || event.kind === "artifact-update") {
if (event.kind === 'status-update' || event.kind === 'artifact-update') {
const typedEvent = event as TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
printAgentEvent(typedEvent);
// If the event is a TaskStatusUpdateEvent and it's final, reset currentTaskId
if (typedEvent.kind === "status-update" && (typedEvent as TaskStatusUpdateEvent).final && (typedEvent as TaskStatusUpdateEvent).status.state !== "input-required") {
console.log(colorize("yellow", ` Task ${typedEvent.taskId} is final. Clearing current task ID.`));
if (
typedEvent.kind === 'status-update' &&
(typedEvent as TaskStatusUpdateEvent).final &&
(typedEvent as TaskStatusUpdateEvent).status.state !== 'input-required'
) {
console.log(
colorize('yellow', ` Task ${typedEvent.taskId} is final. Clearing current task ID.`)
);
currentTaskId = undefined;
// Optionally, you might want to clear currentContextId as well if a task ending implies context ending.
// currentContextId = undefined;
// currentContextId = undefined;
// console.log(colorize("dim", ` Context ID also cleared as task is final.`));
}
} else if (event.kind === "message") {
} else if (event.kind === 'message') {
const msg = event as Message;
console.log(`${prefix} ${colorize("green", "✉️ Message Stream Event:")}`);
console.log(`${prefix} ${colorize('green', '✉️ Message Stream Event:')}`);
printMessageContent(msg);
if (msg.taskId && msg.taskId !== currentTaskId) {
console.log(colorize("dim", ` Task ID context updated to ${msg.taskId} based on message event.`));
console.log(
colorize('dim', ` Task ID context updated to ${msg.taskId} based on message event.`)
);
currentTaskId = msg.taskId;
}
if (msg.contextId && msg.contextId !== currentContextId) {
console.log(colorize("dim", ` Context ID updated to ${msg.contextId} based on message event.`));
console.log(
colorize('dim', ` Context ID updated to ${msg.contextId} based on message event.`)
);
currentContextId = msg.contextId;
}
} else if (event.kind === "task") {
} else if (event.kind === 'task') {
const task = event as Task;
console.log(`${prefix} ${colorize("blue", "ℹ️ Task Stream Event:")} ID: ${task.id}, Context: ${task.contextId}, Status: ${task.status.state}`);
console.log(
`${prefix} ${colorize('blue', 'ℹ️ Task Stream Event:')} ID: ${task.id}, Context: ${task.contextId}, Status: ${task.status.state}`
);
if (task.id !== currentTaskId) {
console.log(colorize("dim", ` Task ID updated from ${currentTaskId || 'N/A'} to ${task.id}`));
console.log(
colorize('dim', ` Task ID updated from ${currentTaskId || 'N/A'} to ${task.id}`)
);
currentTaskId = task.id;
}
if (task.contextId && task.contextId !== currentContextId) {
console.log(colorize("dim", ` Context ID updated from ${currentContextId || 'N/A'} to ${task.contextId}`));
console.log(
colorize(
'dim',
` Context ID updated from ${currentContextId || 'N/A'} to ${task.contextId}`
)
);
currentContextId = task.contextId;
}
if (task.status.message) {
console.log(colorize("gray", " Task includes message:"));
console.log(colorize('gray', ' Task includes message:'));
printMessageContent(task.status.message);
}
if (task.artifacts && task.artifacts.length > 0) {
console.log(colorize("gray", ` Task includes ${task.artifacts.length} artifact(s).`));
console.log(colorize('gray', ` Task includes ${task.artifacts.length} artifact(s).`));
}
} else {
console.log(prefix, colorize("yellow", "Received unknown event structure from stream:"), event);
console.log(
prefix,
colorize('yellow', 'Received unknown event structure from stream:'),
event
);
}
}
console.log(colorize("dim", `--- End of response stream for this input ---`));
console.log(colorize('dim', `--- End of response stream for this input ---`));
} catch (error: any) {
const timestamp = new Date().toLocaleTimeString();
const prefix = colorize("red", `\n${agentName} [${timestamp}] ERROR:`);
console.error(
prefix,
`Error communicating with agent:`,
error.message || error
);
const prefix = colorize('red', `\n${agentName} [${timestamp}] ERROR:`);
console.error(prefix, `Error communicating with agent:`, error.message || error);
if (error.code) {
console.error(colorize("gray", ` Code: ${error.code}`));
console.error(colorize('gray', ` Code: ${error.code}`));
}
if (error.data) {
console.error(
colorize("gray", ` Data: ${JSON.stringify(error.data)}`)
);
console.error(colorize('gray', ` Data: ${JSON.stringify(error.data)}`));
}
if (!(error.code || error.data) && error.stack) {
console.error(colorize("gray", error.stack.split('\n').slice(1, 3).join('\n')));
console.error(colorize('gray', error.stack.split('\n').slice(1, 3).join('\n')));
}
} finally {
rl.prompt();
}
}).on("close", () => {
console.log(colorize("yellow", "\nExiting A2A Terminal Client. Goodbye!"));
}).on('close', () => {
console.log(colorize('yellow', '\nExiting A2A Terminal Client. Goodbye!'));
process.exit(0);
});
}
// --- Start ---
main().catch(err => {
console.error(colorize("red", "Unhandled error in main:"), err);
main().catch((err) => {
console.error(colorize('red', 'Unhandled error in main:'), err);
process.exit(1);
});

View File

@ -0,0 +1,75 @@
# Extension
This configuration is using a sample agent to test the extension feature integration. It uses the sample agent executor defined in `agents/sample-agent`, with a modified agent card which includes the support for extensions.
The `extensions.ts` adds a timestamp in the metadata of the `TaskStatusUpdateEvent` Message.
To run the agent:
```bash
npm run agents:extension-agent
```
The agent will start on `http://localhost:41241`.
To test the extension:
```bash
curl -X POST http://localhost:41241/
-H "X-A2A-Extensions: https://github.com/a2aproject/a2a-js/src/samples/extensions/v1"
-H "Content-Type: application/json"
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"role": "user",
"parts": [
{
"kind": "text",
"text": "Hello how are you?"
}
],
"messageId": "9229e770-767c-417b-a0b0-f0741243c589"
}
}
}'
```
Expected simplified response:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"kind": "task",
"status": {
"state": "completed",
"message": {
...
"metadata": {
"timestamp": "2025-11-14T15:51:36.725Z" // Timestamp added to metadata on the 'completed' TaskStatusUpdateEvent
}
},
},
"history": [
{
...
},
{
...
"metadata": {
"timestamp": "2025-11-14T15:51:35.722Z" // Timestamp added to metadata on the 'running' TaskStatusUpdateEvent
}
},
{
...
"metadata": {
"timestamp": "2025-11-14T15:51:36.725Z" // Timestamp added to metadata on the 'completed' TaskStatusUpdateEvent
}
}
]
}
}
```

View File

@ -0,0 +1,96 @@
import {
AgentExecutor,
RequestContext,
ExecutionEventBus,
AgentExecutionEvent,
} from '../../server/index.js';
import { TaskStatusUpdateEvent } from '../../types.js';
const URI = 'https://github.com/a2aproject/a2a-js/src/samples/extensions/v1';
class TimeStampExtension {
activate(context: RequestContext): boolean {
const serverContext = context.context;
if (serverContext?.requestedExtensions?.includes(URI)) {
serverContext.addActivatedExtension(URI);
return true;
}
return false;
}
timestampEvent(event: AgentExecutionEvent): void {
if (event.kind === 'status-update') {
const statusUpdateEvent = event as TaskStatusUpdateEvent;
if (statusUpdateEvent.status.message) {
if (!statusUpdateEvent.status.message.metadata) {
statusUpdateEvent.status.message.metadata = {};
}
statusUpdateEvent.status.message.metadata['timestamp'] = new Date().toISOString();
}
}
}
}
export class TimestampingAgentExecutor implements AgentExecutor {
private readonly _delegate: AgentExecutor;
private readonly _ext: TimeStampExtension;
constructor(delegate: AgentExecutor, ext: TimeStampExtension = new TimeStampExtension()) {
this._delegate = delegate;
this._ext = ext;
}
async execute(context: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
return await this._delegate.execute(context, this._maybeWrapQueue(context, eventBus));
}
_maybeWrapQueue(context: RequestContext, eventBus: ExecutionEventBus): ExecutionEventBus {
if (this._ext.activate(context)) {
return new TimestampingEventQueue(eventBus, this._ext);
}
return eventBus;
}
async cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise<void> {
return await this._delegate.cancelTask(taskId, eventBus);
}
}
class TimestampingEventQueue implements ExecutionEventBus {
private readonly _delegate: ExecutionEventBus;
private readonly _ext: TimeStampExtension;
constructor(delegate: ExecutionEventBus, ext: TimeStampExtension) {
this._delegate = delegate;
this._ext = ext;
}
publish(event: AgentExecutionEvent): void {
this._ext.timestampEvent(event);
this._delegate.publish(event);
}
finished(): void {
this._delegate.finished();
}
on(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this {
this._delegate.on(eventName, listener);
return this;
}
off(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this {
this._delegate.off(eventName, listener);
return this;
}
once(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this {
this._delegate.once(eventName, listener);
return this;
}
removeAllListeners(eventName?: 'event' | 'finished'): this {
this._delegate.removeAllListeners(eventName);
return this;
}
}

View File

@ -0,0 +1,88 @@
import express from 'express';
import { AGENT_CARD_PATH, AgentCard } from '../../index.js';
import {
InMemoryTaskStore,
TaskStore,
AgentExecutor,
DefaultRequestHandler,
} from '../../server/index.js';
import { jsonRpcHandler, agentCardHandler, UserBuilder } from '../../server/express/index.js';
import { TimestampingAgentExecutor } from './extensions.js';
import { SampleAgentExecutor } from '../agents/sample-agent/agent_executor.js';
// --- Server Setup ---
const extensionAgentCard: AgentCard = {
name: 'Sample Agent with timestamp extensions',
description:
'A sample agent to test the stream functionality and simulate the flow of tasks statuses, with extensions integration.',
url: 'http://localhost:41241/',
provider: {
organization: 'A2A Samples',
url: 'https://example.com/a2a-samples', // Added provider URL
},
version: '1.0.0', // Incremented version
protocolVersion: '0.3.0',
capabilities: {
extensions: [{ uri: 'https://github.com/a2aproject/a2a-js/src/samples/extensions/v1' }],
streaming: true, // The new framework supports streaming
pushNotifications: false, // Assuming not implemented for this agent yet
stateTransitionHistory: true, // Agent uses history
},
defaultInputModes: ['text'],
defaultOutputModes: ['text', 'task-status'], // task-status is a common output mode
skills: [
{
id: 'sample_agent',
name: 'Sample Agent with extensions',
description: 'Simulate the general flow of a streaming agent with extensions integration.',
tags: ['sample'],
examples: ['hi', 'hello world', 'how are you', 'goodbye'],
inputModes: ['text'], // Explicitly defining for skill
outputModes: ['text', 'task-status'], // Explicitly defining for skill
},
],
supportsAuthenticatedExtendedCard: false,
};
async function main() {
// 1. Create TaskStore
const taskStore: TaskStore = new InMemoryTaskStore();
// 2. Create AgentExecutor
const agentExecutor: AgentExecutor = new SampleAgentExecutor();
// 3. Use the TimestampingAgentExecutor to wrap the AgentExecutor
const timestampAgentExecutor: AgentExecutor = new TimestampingAgentExecutor(agentExecutor);
// 4. Create DefaultRequestHandler
const requestHandler = new DefaultRequestHandler(
extensionAgentCard,
taskStore,
timestampAgentExecutor
);
// 5. Create and setup Express.js app
const app = express();
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
app.use(jsonRpcHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
// 6. Start the server
const PORT = process.env.PORT || 41241;
app.listen(PORT, (err) => {
if (err) {
throw err;
}
console.log(
`[ExtensionsSampleAgent] Server using new framework started on http://localhost:${PORT}`
);
console.log(
`[ExtensionsSampleAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`
);
console.log('[ExtensionsSampleAgent] Press Ctrl+C to stop the server');
});
}
main().catch(console.error);

7928
src/samples/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

28
src/samples/package.json Normal file
View File

@ -0,0 +1,28 @@
{
"type": "module",
"private": true,
"scripts": {
"a2a:cli": "tsx cli.ts",
"agents:movie-agent": "tsx agents/movie-agent/index.ts",
"agents:sample-agent": "tsx agents/sample-agent/index.ts",
"agents:extension-agent": "tsx extensions/index.ts",
"agents:authentication-agent": "tsx authentication/index.ts"
},
"devDependencies": {
"@genkit-ai/googleai": "^1.8.0",
"@types/express": "^5.0.5",
"@types/passport": "^1.0.17",
"@types/passport-jwt": "^4.0.1",
"express": "^5.1.0",
"genkit": "^1.8.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"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

@ -1,26 +1,20 @@
import { ExecutionEventBus } from "../events/execution_event_bus.js";
import { RequestContext } from "./request_context.js";
import { ExecutionEventBus } from '../events/execution_event_bus.js';
import { RequestContext } from './request_context.js';
export interface AgentExecutor {
/**
* Executes the agent logic based on the request context and publishes events.
* @param requestContext The context of the current request.
* @param eventBus The bus to publish execution events to.
*/
execute: (
requestContext: RequestContext,
eventBus: ExecutionEventBus
) => Promise<void>;
/**
* Executes the agent logic based on the request context and publishes events.
* @param requestContext The context of the current request.
* @param eventBus The bus to publish execution events to.
*/
execute: (requestContext: RequestContext, eventBus: ExecutionEventBus) => Promise<void>;
/**
* Method to explicitly cancel a running task.
* The implementation should handle the logic of stopping the execution
* and publishing the final 'canceled' status event on the provided event bus.
* @param taskId The ID of the task to cancel.
* @param eventBus The event bus associated with the task's execution.
*/
cancelTask: (
taskId: string,
eventBus: ExecutionEventBus
) => Promise<void>;
/**
* Method to explicitly cancel a running task.
* The implementation should handle the logic of stopping the execution
* and publishing the final 'canceled' status event on the provided event bus.
* @param taskId The ID of the task to cancel.
* @param eventBus The event bus associated with the task's execution.
*/
cancelTask: (taskId: string, eventBus: ExecutionEventBus) => Promise<void>;
}

View File

@ -1,26 +1,27 @@
import {
Message,
Task,
} from "../../types.js";
import { Message, Task } from '../../types.js';
import { ServerCallContext } from '../context.js';
export class RequestContext {
public readonly userMessage: Message;
public readonly task?: Task;
public readonly referenceTasks?: Task[];
public readonly taskId: string;
public readonly contextId: string;
public readonly userMessage: Message;
public readonly taskId: string;
public readonly contextId: string;
public readonly task?: Task;
public readonly referenceTasks?: Task[];
public readonly context?: ServerCallContext;
constructor(
userMessage: Message,
taskId: string,
contextId: string,
task?: Task,
referenceTasks?: Task[],
) {
this.userMessage = userMessage;
this.taskId = taskId;
this.contextId = contextId;
this.task = task;
this.referenceTasks = referenceTasks;
}
}
constructor(
userMessage: Message,
taskId: string,
contextId: string,
task?: Task,
referenceTasks?: Task[],
context?: ServerCallContext
) {
this.userMessage = userMessage;
this.taskId = taskId;
this.contextId = contextId;
this.task = task;
this.referenceTasks = referenceTasks;
this.context = context;
}
}

View File

@ -0,0 +1,27 @@
/**
* Represents a user accessing A2A server.
*/
export interface User {
/**
* Indicates whether the user is authenticated.
*/
get isAuthenticated(): boolean;
/**
* A unique name (identifier) for the user.
*/
get userName(): string;
}
/**
* An implementation of {@link User} representing an unauthenticated user.
*/
export class UnauthenticatedUser implements User {
get isAuthenticated(): boolean {
return false;
}
get userName(): string {
return '';
}
}

29
src/server/context.ts Normal file
View File

@ -0,0 +1,29 @@
import { Extensions } from '../extensions.js';
import { User } from './authentication/user.js';
export class ServerCallContext {
private readonly _requestedExtensions?: Extensions;
private readonly _user?: User;
private _activatedExtensions?: Extensions;
constructor(requestedExtensions?: Extensions, user?: User) {
this._requestedExtensions = requestedExtensions;
this._user = user;
}
get user(): User | undefined {
return this._user;
}
get activatedExtensions(): Extensions | undefined {
return this._activatedExtensions;
}
get requestedExtensions(): Extensions | undefined {
return this._requestedExtensions;
}
public addActivatedExtension(uri: string) {
this._activatedExtensions = Extensions.createFrom(this._activatedExtensions, uri);
}
}

View File

@ -1,4 +1,4 @@
import * as schema from "../types.js";
import * as schema from '../types.js';
/**
* Custom error class for A2A server operations, incorporating JSON-RPC error codes.
@ -8,14 +8,9 @@ export class A2AError extends Error {
public data?: Record<string, unknown>;
public taskId?: string; // Optional task ID context
constructor(
code: number,
message: string,
data?: Record<string, unknown>,
taskId?: string
) {
constructor(code: number, message: string, data?: Record<string, unknown>, taskId?: string) {
super(message);
this.name = "A2AError";
this.name = 'A2AError';
this.code = code;
this.data = data;
this.taskId = taskId; // Store associated task ID if provided
@ -30,10 +25,10 @@ export class A2AError extends Error {
message: this.message,
};
if(this.data !== undefined) {
if (this.data !== undefined) {
errorObject.data = this.data;
}
return errorObject;
}
@ -48,10 +43,7 @@ export class A2AError extends Error {
}
static methodNotFound(method: string): A2AError {
return new A2AError(
-32601,
`Method not found: ${method}`
);
return new A2AError(-32601, `Method not found: ${method}`);
}
static invalidParams(message: string, data?: Record<string, unknown>): A2AError {
@ -63,41 +55,22 @@ export class A2AError extends Error {
}
static taskNotFound(taskId: string): A2AError {
return new A2AError(
-32001,
`Task not found: ${taskId}`,
undefined,
taskId
);
return new A2AError(-32001, `Task not found: ${taskId}`, undefined, taskId);
}
static taskNotCancelable(taskId: string): A2AError {
return new A2AError(
-32002,
`Task not cancelable: ${taskId}`,
undefined,
taskId
);
return new A2AError(-32002, `Task not cancelable: ${taskId}`, undefined, taskId);
}
static pushNotificationNotSupported(): A2AError {
return new A2AError(
-32003,
"Push Notification is not supported"
);
return new A2AError(-32003, 'Push Notification is not supported');
}
static unsupportedOperation(operation: string): A2AError {
return new A2AError(
-32004,
`Unsupported operation: ${operation}`
);
return new A2AError(-32004, `Unsupported operation: ${operation}`);
}
static authenticatedExtendedCardNotConfigured(): A2AError {
return new A2AError(
-32007,
`Extended card not configured.`
);
return new A2AError(-32007, `Extended card not configured.`);
}
}

View File

@ -1,37 +1,278 @@
import { EventEmitter } from 'events';
import { Message, Task, TaskStatusUpdateEvent, TaskArtifactUpdateEvent } from '../../types.js';
import {
Message,
Task,
TaskStatusUpdateEvent,
TaskArtifactUpdateEvent,
} from "../../types.js";
export type AgentExecutionEvent = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
export type AgentExecutionEvent =
| Message
| Task
| TaskStatusUpdateEvent
| TaskArtifactUpdateEvent;
/**
* Event names supported by ExecutionEventBus.
*/
export type ExecutionEventName = 'event' | 'finished';
export interface ExecutionEventBus {
publish(event: AgentExecutionEvent): void;
on(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this;
off(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this;
once(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this;
removeAllListeners(eventName?: 'event' | 'finished'): this;
finished(): void;
publish(event: AgentExecutionEvent): void;
on(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this;
off(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this;
once(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this;
removeAllListeners(eventName?: ExecutionEventName): this;
finished(): void;
}
export class DefaultExecutionEventBus extends EventEmitter implements ExecutionEventBus {
constructor() {
super();
}
/**
* CustomEvent polyfill for Node.js 15-18 (CustomEvent was added globally in Node.js 19).
* In browsers and modern edge runtimes, CustomEvent is already available globally.
* Per the spec, detail defaults to null when not provided.
*/
const CustomEventImpl: typeof CustomEvent =
typeof CustomEvent !== 'undefined'
? CustomEvent
: (class CustomEventPolyfill<T> extends Event {
readonly detail: T;
constructor(type: string, eventInitDict?: CustomEventInit<T>) {
super(type, eventInitDict);
this.detail = (eventInitDict?.detail ?? null) as T;
}
} as typeof CustomEvent);
publish(event: AgentExecutionEvent): void {
this.emit('event', event);
}
/**
* Listener type matching the ExecutionEventBus interface.
*/
type Listener = (event: AgentExecutionEvent) => void;
finished(): void {
this.emit('finished');
}
/**
* Type for wrapped listener functions registered with EventTarget.
*/
type WrappedListener = (e: Event) => void;
/**
* Type guard to narrow Event to CustomEvent with AgentExecutionEvent payload.
* This guard should always pass for 'event' type events since we control
* the dispatch via publish(). If it fails, there's a bug in the implementation.
*/
function isAgentExecutionCustomEvent(e: Event): e is CustomEvent<AgentExecutionEvent> {
return e instanceof CustomEventImpl;
}
/**
* Web-compatible ExecutionEventBus using EventTarget.
* Works across all modern runtimes: Node.js 15+, browsers, Cloudflare Workers, Deno, Bun.
*
* This implementation provides the subset of EventEmitter methods defined in the
* ExecutionEventBus interface. Users extending DefaultExecutionEventBus should note
* that other EventEmitter methods (e.g., listenerCount, rawListeners) are not available.
*/
export class DefaultExecutionEventBus extends EventTarget implements ExecutionEventBus {
// Separate storage for each event type - both use the interface's Listener type
// but are invoked differently (with event payload vs. no arguments)
private readonly eventListeners: Map<Listener, WrappedListener[]> = new Map();
private readonly finishedListeners: Map<Listener, WrappedListener[]> = new Map();
publish(event: AgentExecutionEvent): void {
this.dispatchEvent(new CustomEventImpl('event', { detail: event }));
}
finished(): void {
this.dispatchEvent(new Event('finished'));
}
/**
* EventEmitter-compatible 'on' method.
* Wraps the listener to extract event detail from CustomEvent.
* Supports multiple registrations of the same listener (like EventEmitter).
* @param eventName The event name to listen for.
* @param listener The callback function to invoke when the event is emitted.
* @returns This instance for method chaining.
*/
on(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this {
if (eventName === 'event') {
this.addEventListenerInternal(listener);
} else {
this.addFinishedListenerInternal(listener);
}
return this;
}
/**
* EventEmitter-compatible 'off' method.
* Uses the stored wrapped listener for proper removal.
* Removes at most one instance of a listener per call (like EventEmitter).
* @param eventName The event name to stop listening for.
* @param listener The callback function to remove.
* @returns This instance for method chaining.
*/
off(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this {
if (eventName === 'event') {
this.removeEventListenerInternal(listener);
} else {
this.removeFinishedListenerInternal(listener);
}
return this;
}
/**
* EventEmitter-compatible 'once' method.
* Listener is automatically removed after first invocation.
* Supports multiple registrations of the same listener (like EventEmitter).
* @param eventName The event name to listen for once.
* @param listener The callback function to invoke when the event is emitted.
* @returns This instance for method chaining.
*/
once(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this {
if (eventName === 'event') {
this.addEventListenerOnceInternal(listener);
} else {
this.addFinishedListenerOnceInternal(listener);
}
return this;
}
/**
* EventEmitter-compatible 'removeAllListeners' method.
* Removes all listeners for a specific event or all events.
* @param eventName Optional event name to remove listeners for. If omitted, removes all.
* @returns This instance for method chaining.
*/
removeAllListeners(eventName?: ExecutionEventName): this {
if (eventName === undefined || eventName === 'event') {
for (const wrappedListeners of this.eventListeners.values()) {
for (const wrapped of wrappedListeners) {
this.removeEventListener('event', wrapped);
}
}
this.eventListeners.clear();
}
if (eventName === undefined || eventName === 'finished') {
for (const wrappedListeners of this.finishedListeners.values()) {
for (const wrapped of wrappedListeners) {
this.removeEventListener('finished', wrapped);
}
}
this.finishedListeners.clear();
}
return this;
}
// ========================
// Helper methods for listener tracking
// ========================
/**
* Adds a wrapped listener to the tracking map.
*/
private trackListener(
listenerMap: Map<Listener, WrappedListener[]>,
listener: Listener,
wrapped: WrappedListener
): void {
const existing = listenerMap.get(listener);
if (existing) {
existing.push(wrapped);
} else {
listenerMap.set(listener, [wrapped]);
}
}
/**
* Removes a wrapped listener from the tracking map (for once cleanup).
*/
private untrackWrappedListener(
listenerMap: Map<Listener, WrappedListener[]>,
listener: Listener,
wrapped: WrappedListener
): void {
const wrappedList = listenerMap.get(listener);
if (wrappedList && wrappedList.length > 0) {
const index = wrappedList.indexOf(wrapped);
if (index !== -1) {
wrappedList.splice(index, 1);
if (wrappedList.length === 0) {
listenerMap.delete(listener);
}
}
}
}
// ========================
// Internal methods for 'event' listeners
// ========================
private addEventListenerInternal(listener: Listener): void {
const wrapped: WrappedListener = (e: Event) => {
if (!isAgentExecutionCustomEvent(e)) {
throw new Error('Internal error: expected CustomEvent for "event" type');
}
listener.call(this, e.detail);
};
this.trackListener(this.eventListeners, listener, wrapped);
this.addEventListener('event', wrapped);
}
private removeEventListenerInternal(listener: Listener): void {
const wrappedList = this.eventListeners.get(listener);
if (wrappedList && wrappedList.length > 0) {
const wrapped = wrappedList.pop()!;
if (wrappedList.length === 0) {
this.eventListeners.delete(listener);
}
this.removeEventListener('event', wrapped);
}
}
private addEventListenerOnceInternal(listener: Listener): void {
const wrapped: WrappedListener = (e: Event) => {
// Validate first before any state changes
if (!isAgentExecutionCustomEvent(e)) {
throw new Error('Internal error: expected CustomEvent for "event" type');
}
// Clean up tracking
this.untrackWrappedListener(this.eventListeners, listener, wrapped);
listener.call(this, e.detail);
};
this.trackListener(this.eventListeners, listener, wrapped);
this.addEventListener('event', wrapped, { once: true });
}
// ========================
// Internal methods for 'finished' listeners
// ========================
// The interface declares listeners as (event: AgentExecutionEvent) => void,
// but for 'finished' events they are invoked with no arguments (EventEmitter behavior).
// We use Function.prototype.call to invoke with `this` as the event bus (matching
// EventEmitter semantics) and no arguments, which is type-safe.
private addFinishedListenerInternal(listener: Listener): void {
const wrapped: WrappedListener = () => {
listener.call(this);
};
this.trackListener(this.finishedListeners, listener, wrapped);
this.addEventListener('finished', wrapped);
}
private removeFinishedListenerInternal(listener: Listener): void {
const wrappedList = this.finishedListeners.get(listener);
if (wrappedList && wrappedList.length > 0) {
const wrapped = wrappedList.pop()!;
if (wrappedList.length === 0) {
this.finishedListeners.delete(listener);
}
this.removeEventListener('finished', wrapped);
}
}
private addFinishedListenerOnceInternal(listener: Listener): void {
const wrapped: WrappedListener = () => {
// Clean up tracking
this.untrackWrappedListener(this.finishedListeners, listener, wrapped);
listener.call(this);
};
this.trackListener(this.finishedListeners, listener, wrapped);
this.addEventListener('finished', wrapped, { once: true });
}
}

View File

@ -1,45 +1,45 @@
import { DefaultExecutionEventBus, ExecutionEventBus } from "./execution_event_bus.js";
import { DefaultExecutionEventBus, ExecutionEventBus } from './execution_event_bus.js';
export interface ExecutionEventBusManager {
createOrGetByTaskId(taskId: string): ExecutionEventBus;
getByTaskId(taskId: string): ExecutionEventBus | undefined;
cleanupByTaskId(taskId: string): void;
createOrGetByTaskId(taskId: string): ExecutionEventBus;
getByTaskId(taskId: string): ExecutionEventBus | undefined;
cleanupByTaskId(taskId: string): void;
}
export class DefaultExecutionEventBusManager implements ExecutionEventBusManager {
private taskIdToBus: Map<string, ExecutionEventBus> = new Map();
private taskIdToBus: Map<string, ExecutionEventBus> = new Map();
/**
* Creates or retrieves an existing ExecutionEventBus based on the taskId.
* @param taskId The ID of the task.
* @returns An instance of IExecutionEventBus.
*/
public createOrGetByTaskId(taskId: string): ExecutionEventBus {
if (!this.taskIdToBus.has(taskId)) {
this.taskIdToBus.set(taskId, new DefaultExecutionEventBus());
}
return this.taskIdToBus.get(taskId)!;
/**
* Creates or retrieves an existing ExecutionEventBus based on the taskId.
* @param taskId The ID of the task.
* @returns An instance of ExecutionEventBus.
*/
public createOrGetByTaskId(taskId: string): ExecutionEventBus {
if (!this.taskIdToBus.has(taskId)) {
this.taskIdToBus.set(taskId, new DefaultExecutionEventBus());
}
return this.taskIdToBus.get(taskId)!;
}
/**
* Retrieves an existing ExecutionEventBus based on the taskId.
* @param taskId The ID of the task.
* @returns An instance of IExecutionEventBus or undefined if not found.
*/
public getByTaskId(taskId: string): ExecutionEventBus | undefined {
return this.taskIdToBus.get(taskId);
}
/**
* Retrieves an existing ExecutionEventBus based on the taskId.
* @param taskId The ID of the task.
* @returns An instance of ExecutionEventBus or undefined if not found.
*/
public getByTaskId(taskId: string): ExecutionEventBus | undefined {
return this.taskIdToBus.get(taskId);
}
/**
* Removes the event bus for a given taskId.
* This should be called when an execution flow is complete to free resources.
* @param taskId The ID of the task.
*/
public cleanupByTaskId(taskId: string): void {
const bus = this.taskIdToBus.get(taskId);
if (bus) {
bus.removeAllListeners();
}
this.taskIdToBus.delete(taskId);
/**
* Removes the event bus for a given taskId.
* This should be called when an execution flow is complete to free resources.
* @param taskId The ID of the task.
*/
public cleanupByTaskId(taskId: string): void {
const bus = this.taskIdToBus.get(taskId);
if (bus) {
bus.removeAllListeners();
}
this.taskIdToBus.delete(taskId);
}
}

View File

@ -1,73 +1,70 @@
import {
TaskStatusUpdateEvent,
} from "../../types.js";
import { ExecutionEventBus, AgentExecutionEvent } from "./execution_event_bus.js";
import { TaskStatusUpdateEvent } from '../../types.js';
import { ExecutionEventBus, AgentExecutionEvent } from './execution_event_bus.js';
/**
* An async queue that subscribes to an ExecutionEventBus for events
* and provides an async generator to consume them.
*/
export class ExecutionEventQueue {
private eventBus: ExecutionEventBus;
private eventQueue: AgentExecutionEvent[] = [];
private resolvePromise?: (value: void | PromiseLike<void>) => void;
private stopped: boolean = false;
private boundHandleEvent: (event: AgentExecutionEvent) => void;
private eventBus: ExecutionEventBus;
private eventQueue: AgentExecutionEvent[] = [];
private resolvePromise?: (value: void | PromiseLike<void>) => void;
private stopped: boolean = false;
constructor(eventBus: ExecutionEventBus) {
this.eventBus = eventBus;
this.eventBus.on('event', this.handleEvent);
this.eventBus.on('finished', this.handleFinished);
constructor(eventBus: ExecutionEventBus) {
this.eventBus = eventBus;
this.eventBus.on('event', this.handleEvent);
this.eventBus.on('finished', this.handleFinished);
}
private handleEvent = (event: AgentExecutionEvent) => {
if (this.stopped) return;
this.eventQueue.push(event);
if (this.resolvePromise) {
this.resolvePromise();
this.resolvePromise = undefined;
}
};
private handleEvent = (event: AgentExecutionEvent) => {
if (this.stopped) return;
this.eventQueue.push(event);
if (this.resolvePromise) {
this.resolvePromise();
this.resolvePromise = undefined;
private handleFinished = () => {
this.stop();
};
/**
* Provides an async generator that yields events from the event bus.
* Stops when a Message event is received or a TaskStatusUpdateEvent with final=true is received.
*/
public async *events(): AsyncGenerator<AgentExecutionEvent, void, undefined> {
while (!this.stopped || this.eventQueue.length > 0) {
if (this.eventQueue.length > 0) {
const event = this.eventQueue.shift()!;
yield event;
if (
event.kind === 'message' ||
(event.kind === 'status-update' && (event as TaskStatusUpdateEvent).final)
) {
this.handleFinished();
break;
}
} else if (!this.stopped) {
await new Promise<void>((resolve) => {
this.resolvePromise = resolve;
});
}
}
}
/**
* Stops the event queue from processing further events.
*/
public stop(): void {
this.stopped = true;
if (this.resolvePromise) {
this.resolvePromise(); // Unblock any pending await
this.resolvePromise = undefined;
}
private handleFinished = () => {
this.stop();
}
/**
* Provides an async generator that yields events from the event bus.
* Stops when a Message event is received or a TaskStatusUpdateEvent with final=true is received.
*/
public async *events(): AsyncGenerator<AgentExecutionEvent, void, undefined> {
while (!this.stopped || this.eventQueue.length > 0) {
if (this.eventQueue.length > 0) {
const event = this.eventQueue.shift()!;
yield event;
if (event.kind === 'message' || (
event.kind === 'status-update' &&
(event as TaskStatusUpdateEvent).final
)) {
this.handleFinished();
break;
}
} else if(!this.stopped) {
await new Promise<void>((resolve) => {
this.resolvePromise = resolve;
});
}
}
}
/**
* Stops the event queue from processing further events.
*/
public stop(): void {
this.stopped = true;
if (this.resolvePromise) {
this.resolvePromise(); // Unblock any pending await
this.resolvePromise = undefined;
}
this.eventBus.off('event', this.handleEvent);
this.eventBus.off('finished', this.handleFinished);
}
this.eventBus.off('event', this.handleEvent);
this.eventBus.off('finished', this.handleFinished);
}
}

View File

@ -1,109 +1,61 @@
import express, { Request, Response, Express, RequestHandler, ErrorRequestHandler } from 'express';
import express, { Express, RequestHandler, ErrorRequestHandler } from 'express';
import { A2AError } from "../error.js";
import { JSONRPCErrorResponse, JSONRPCSuccessResponse, JSONRPCResponse } from "../../index.js";
import { A2ARequestHandler } from "../request_handler/a2a_request_handler.js";
import { JsonRpcTransportHandler } from "../transports/jsonrpc_transport_handler.js";
import { A2ARequestHandler } from '../request_handler/a2a_request_handler.js';
import { AGENT_CARD_PATH } from '../../constants.js';
import { jsonErrorHandler, jsonRpcHandler } from './json_rpc_handler.js';
import { agentCardHandler } from './agent_card_handler.js';
import { UserBuilder } from './common.js';
/**
* @deprecated Use specific middlewares ({@link jsonRpcHandler}, {@link agentCardHandler}) directly.
*/
export class A2AExpressApp {
private requestHandler: A2ARequestHandler; // Kept for getAgentCard
private jsonRpcTransportHandler: JsonRpcTransportHandler;
private requestHandler: A2ARequestHandler;
private userBuilder: UserBuilder;
constructor(requestHandler: A2ARequestHandler) {
this.requestHandler = requestHandler; // DefaultRequestHandler instance
this.jsonRpcTransportHandler = new JsonRpcTransportHandler(requestHandler);
constructor(
requestHandler: A2ARequestHandler,
userBuilder: UserBuilder = UserBuilder.noAuthentication
) {
this.requestHandler = requestHandler;
this.userBuilder = userBuilder;
}
/**
* Adds A2A routes to an existing Express app.
* @param app Optional existing Express app.
* @param baseUrl The base URL for A2A endpoints (e.g., "/a2a/api").
* @param middlewares Optional array of Express middlewares to apply to the A2A routes.
* @param agentCardPath Optional custom path for the agent card endpoint (defaults to .well-known/agent-card.json).
* @returns The Express app with A2A routes.
*/
public setupRoutes(
app: Express,
baseUrl: string = '',
middlewares?: Array<RequestHandler | ErrorRequestHandler>,
agentCardPath: string = AGENT_CARD_PATH
): Express {
const router = express.Router();
// Doing it here to maintain previous behaviour of invoking provided middlewares
// after JSON body is parsed, jsonRpcHandler registers JSON parsing on the local router.
// body-parser used by express.json() ignores subsequent calls and is safe to be added twice:
// https://github.com/expressjs/body-parser/blob/168afff3470302aa28050a8ae6681fa1fdaf71a2/lib/read.js#L41.
router.use(express.json(), jsonErrorHandler);
if (middlewares && middlewares.length > 0) {
router.use(middlewares);
}
/**
* Adds A2A routes to an existing Express app.
* @param app Optional existing Express app.
* @param baseUrl The base URL for A2A endpoints (e.g., "/a2a/api").
* @param middlewares Optional array of Express middlewares to apply to the A2A routes.
* @returns The Express app with A2A routes.
*/
public setupRoutes(
app: Express,
baseUrl: string = "",
middlewares?: Array<RequestHandler | ErrorRequestHandler>
): Express {
const router = express.Router();
router.use(express.json(), ...(middlewares ?? []));
router.use(
jsonRpcHandler({
requestHandler: this.requestHandler,
userBuilder: this.userBuilder,
})
);
router.use(`/${agentCardPath}`, agentCardHandler({ agentCardProvider: this.requestHandler }));
router.get("/.well-known/agent.json", async (req: Request, res: Response) => {
try {
// getAgentCard is on A2ARequestHandler, which DefaultRequestHandler implements
const agentCard = await this.requestHandler.getAgentCard();
res.json(agentCard);
} catch (error: any) {
console.error("Error fetching agent card:", error);
res.status(500).json({ error: "Failed to retrieve agent card" });
}
});
router.post("/", async (req: Request, res: Response) => {
try {
const rpcResponseOrStream = await this.jsonRpcTransportHandler.handle(req.body);
// Check if it's an AsyncGenerator (stream)
if (typeof (rpcResponseOrStream as any)?.[Symbol.asyncIterator] === 'function') {
const stream = rpcResponseOrStream as AsyncGenerator<JSONRPCSuccessResponse, void, undefined>;
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
try {
for await (const event of stream) {
// Each event from the stream is already a JSONRPCResult
res.write(`id: ${new Date().getTime()}\n`);
res.write(`data: ${JSON.stringify(event)}\n\n`);
}
} catch (streamError: any) {
console.error(`Error during SSE streaming (request ${req.body?.id}):`, streamError);
// If the stream itself throws an error, send a final JSONRPCErrorResponse
const a2aError = streamError instanceof A2AError ? streamError : A2AError.internalError(streamError.message || 'Streaming error.');
const errorResponse: JSONRPCErrorResponse = {
jsonrpc: '2.0',
id: req.body?.id || null, // Use original request ID if available
error: a2aError.toJSONRPCError(),
};
if (!res.headersSent) { // Should not happen if flushHeaders worked
res.status(500).json(errorResponse); // Should be JSON, not SSE here
} else {
// Try to send as last SSE event if possible, though client might have disconnected
res.write(`id: ${new Date().getTime()}\n`);
res.write(`event: error\n`); // Custom event type for client-side handling
res.write(`data: ${JSON.stringify(errorResponse)}\n\n`);
}
} finally {
if (!res.writableEnded) {
res.end();
}
}
} else { // Single JSON-RPC response
const rpcResponse = rpcResponseOrStream as JSONRPCResponse;
res.status(200).json(rpcResponse);
}
} catch (error: any) { // Catch errors from jsonRpcTransportHandler.handle itself (e.g., initial parse error)
console.error("Unhandled error in A2AExpressApp POST handler:", error);
const a2aError = error instanceof A2AError ? error : A2AError.internalError('General processing error.');
const errorResponse: JSONRPCErrorResponse = {
jsonrpc: '2.0',
id: req.body?.id || null,
error: a2aError.toJSONRPCError(),
};
if (!res.headersSent) {
res.status(500).json(errorResponse);
} else if (!res.writableEnded) {
// If headers sent (likely during a stream attempt that failed early), try to end gracefully
res.end();
}
}
});
app.use(baseUrl, router);
// The separate /stream endpoint is no longer needed.
return app;
}
app.use(baseUrl, router);
return app;
}
}

View File

@ -0,0 +1,40 @@
import express, { Request, RequestHandler, Response } from 'express';
import { AgentCard } from '../../types.js';
export interface AgentCardHandlerOptions {
agentCardProvider: AgentCardProvider;
}
export type AgentCardProvider = { getAgentCard(): Promise<AgentCard> } | (() => Promise<AgentCard>);
/**
* Creates Express.js middleware to handle agent card requests.
*
* @example
* ```ts
* // With an existing A2ARequestHandler instance:
* app.use('/.well-known/agent-card.json', agentCardHandler({ agentCardProvider: a2aRequestHandler }));
* // or with a factory lambda:
* app.use('/.well-known/agent-card.json', agentCardHandler({ agentCardProvider: async () => agentCard }));
* ```
*/
export function agentCardHandler(options: AgentCardHandlerOptions): RequestHandler {
const router = express.Router();
const provider =
typeof options.agentCardProvider === 'function'
? options.agentCardProvider
: options.agentCardProvider.getAgentCard.bind(options.agentCardProvider);
router.get('/', async (_req: Request, res: Response) => {
try {
const agentCard = await provider();
res.json(agentCard);
} catch (error) {
console.error('Error fetching agent card:', error);
res.status(500).json({ error: 'Failed to retrieve agent card' });
}
});
return router;
}

View File

@ -0,0 +1,8 @@
import { Request } from 'express';
import { UnauthenticatedUser, User } from '../authentication/user.js';
export type UserBuilder = (req: Request) => Promise<User>;
export const UserBuilder = {
noAuthentication: () => Promise.resolve(new UnauthenticatedUser()),
};

View File

@ -3,4 +3,11 @@
* This module provides Express.js specific functionality.
*/
export { A2AExpressApp } from "./a2a_express_app.js";
export { A2AExpressApp } from './a2a_express_app.js';
export { UserBuilder } from './common.js';
export { jsonRpcHandler } from './json_rpc_handler.js';
export type { JsonRpcHandlerOptions } from './json_rpc_handler.js';
export { agentCardHandler } from './agent_card_handler.js';
export type { AgentCardHandlerOptions, AgentCardProvider } from './agent_card_handler.js';
export { restHandler } from './rest_handler.js';
export type { RestHandlerOptions } from './rest_handler.js';

View File

@ -0,0 +1,147 @@
import express, {
Request,
Response,
ErrorRequestHandler,
NextFunction,
RequestHandler,
} from 'express';
import { JSONRPCErrorResponse, JSONRPCSuccessResponse, JSONRPCResponse } from '../../types.js';
import { A2AError } from '../error.js';
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 { UserBuilder } from './common.js';
import { SSE_HEADERS, formatSSEEvent, formatSSEErrorEvent } from '../../sse_utils.js';
import { Extensions } from '../../extensions.js';
export interface JsonRpcHandlerOptions {
requestHandler: A2ARequestHandler;
userBuilder: UserBuilder;
}
/**
* Creates Express.js middleware to handle A2A JSON-RPC requests.
* @example
*
* ```ts
* // Handle at root
* app.use(jsonRpcHandler({ requestHandler: a2aRequestHandler, userBuilder: UserBuilder.noAuthentication }));
* // or
* app.use('/a2a/json-rpc', jsonRpcHandler({ requestHandler: a2aRequestHandler, userBuilder: UserBuilder.noAuthentication }));
* ```
*/
export function jsonRpcHandler(options: JsonRpcHandlerOptions): RequestHandler {
const jsonRpcTransportHandler = new JsonRpcTransportHandler(options.requestHandler);
const router = express.Router();
router.use(express.json(), jsonErrorHandler);
router.post('/', async (req: Request, res: Response) => {
try {
const user = await options.userBuilder(req);
const context = new ServerCallContext(
Extensions.parseServiceParameter(req.header(HTTP_EXTENSION_HEADER)),
user
);
const rpcResponseOrStream = await jsonRpcTransportHandler.handle(req.body, context);
if (context.activatedExtensions) {
res.setHeader(HTTP_EXTENSION_HEADER, Array.from(context.activatedExtensions));
}
// Check if it's an AsyncGenerator (stream)
if (typeof (rpcResponseOrStream as AsyncGenerator)?.[Symbol.asyncIterator] === 'function') {
const stream = rpcResponseOrStream as AsyncGenerator<
JSONRPCSuccessResponse,
void,
undefined
>;
// Set SSE headers using shared utility
Object.entries(SSE_HEADERS).forEach(([key, value]) => {
res.setHeader(key, value);
});
res.flushHeaders();
try {
for await (const event of stream) {
// Each event from the stream is already a JSONRPCResult
// Use shared formatSSEEvent utility
res.write(formatSSEEvent(event));
}
} catch (streamError) {
console.error(`Error during SSE streaming (request ${req.body?.id}):`, streamError);
// If the stream itself throws an error, send a final JSONRPCErrorResponse
let a2aError: A2AError;
if (streamError instanceof A2AError) {
a2aError = streamError;
} else {
a2aError = A2AError.internalError(
(streamError instanceof Error && streamError.message) || 'Streaming error.'
);
}
const errorResponse: JSONRPCErrorResponse = {
jsonrpc: '2.0',
id: req.body?.id || null, // Use original request ID if available
error: a2aError.toJSONRPCError(),
};
if (!res.headersSent) {
// Should not happen if flushHeaders worked
res.status(500).json(errorResponse); // Should be JSON, not SSE here
} else {
// Try to send as last SSE event if possible, though client might have disconnected
// Use shared formatSSEErrorEvent utility
res.write(formatSSEErrorEvent(errorResponse));
}
} finally {
if (!res.writableEnded) {
res.end();
}
}
} else {
// Single JSON-RPC response
const rpcResponse = rpcResponseOrStream as JSONRPCResponse;
res.status(200).json(rpcResponse);
}
} catch (error) {
// Catch errors from jsonRpcTransportHandler.handle itself (e.g., initial parse error)
console.error('Unhandled error in JSON-RPC POST handler:', error);
const a2aError =
error instanceof A2AError ? error : A2AError.internalError('General processing error.');
const errorResponse: JSONRPCErrorResponse = {
jsonrpc: '2.0',
id: req.body?.id || null,
error: a2aError.toJSONRPCError(),
};
if (!res.headersSent) {
res.status(500).json(errorResponse);
} else if (!res.writableEnded) {
// If headers sent (likely during a stream attempt that failed early), try to end gracefully
res.end();
}
}
});
return router;
}
export const jsonErrorHandler: ErrorRequestHandler = (
err: unknown,
_req: Request,
res: Response,
next: NextFunction
) => {
// Handle JSON parse errors from express.json() (https://github.com/expressjs/body-parser/issues/122)
if (err instanceof SyntaxError && 'body' in err) {
const a2aError = A2AError.parseError('Invalid JSON payload.');
const errorResponse: JSONRPCErrorResponse = {
jsonrpc: '2.0',
id: null,
error: a2aError.toJSONRPCError(),
};
return res.status(400).json(errorResponse);
}
next(err);
};

View File

@ -0,0 +1,524 @@
import express, {
Request,
Response,
RequestHandler,
ErrorRequestHandler,
NextFunction,
} from 'express';
import { A2ARequestHandler } from '../request_handler/a2a_request_handler.js';
import { A2AError } from '../error.js';
import { SSE_HEADERS, formatSSEEvent, formatSSEErrorEvent } from '../../sse_utils.js';
import {
RestTransportHandler,
HTTP_STATUS,
mapErrorToStatus,
toHTTPError,
} from '../transports/rest/rest_transport_handler.js';
import { ServerCallContext } from '../context.js';
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.
*/
export interface RestHandlerOptions {
requestHandler: A2ARequestHandler;
userBuilder: UserBuilder;
}
/**
* Express error handler middleware for REST API JSON parse errors.
* Catches SyntaxError from express.json() and converts to A2A parse error format.
*
* @param err - Error thrown by express.json() middleware
* @param _req - Express request (unused)
* @param res - Express response
* @param next - Next middleware function
*/
const restErrorHandler: ErrorRequestHandler = (
err: Error,
_req: Request,
res: Response,
next: NextFunction
) => {
if (err instanceof SyntaxError && 'body' in err) {
const a2aError = A2AError.parseError('Invalid JSON payload.');
return res.status(400).json(toHTTPError(a2aError));
}
next(err);
};
// Route patterns removed - using explicit route definitions instead
/**
* Type alias for async Express route handlers used in this module.
*/
type AsyncRouteHandler = (req: Request, res: Response) => Promise<void>;
// ============================================================================
// HTTP+JSON/REST Handler - Main Export
// ============================================================================
/**
* Creates Express.js middleware to handle A2A HTTP+JSON/REST requests.
*
* This handler implements the A2A REST API specification with snake_case
* field names, providing endpoints for:
* - Agent card retrieval (GET /v1/card)
* - Message sending with optional streaming (POST /v1/message:send|stream)
* - Task management (GET/POST /v1/tasks/:taskId:cancel|subscribe)
* - Push notification configuration
*
* The handler acts as an adapter layer, converting between REST format
* (snake_case) at the API boundary and internal TypeScript format (camelCase)
* for business logic.
*
* @param options - Configuration options including the request handler
* @returns Express router configured with all A2A REST endpoints
*
* @example
* ```ts
* const app = express();
* const requestHandler = new DefaultRequestHandler(...);
* app.use('/api/rest', restHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
* ```
*/
export function restHandler(options: RestHandlerOptions): RequestHandler {
const router = express.Router();
const restTransportHandler = new RestTransportHandler(options.requestHandler);
router.use(express.json(), restErrorHandler);
// ============================================================================
// Helper Functions
// ============================================================================
/**
* Builds a ServerCallContext from the Express request.
* Extracts protocol extensions from headers and builds user from request.
*
* @param req - Express request object
* @returns ServerCallContext with requested extensions and authenticated user
*/
const buildContext = async (req: Request): Promise<ServerCallContext> => {
const user = await options.userBuilder(req);
return new ServerCallContext(
Extensions.parseServiceParameter(req.header(HTTP_EXTENSION_HEADER)),
user
);
};
/**
* Sets activated extensions header in the response if any extensions were activated.
*
* @param res - Express response object
* @param context - ServerCallContext containing activated extensions
*/
const setExtensionsHeader = (res: Response, context: ServerCallContext): void => {
if (context.activatedExtensions) {
res.setHeader(HTTP_EXTENSION_HEADER, Array.from(context.activatedExtensions));
}
};
/**
* Sends a JSON response with the specified status code.
* Handles 204 No Content responses specially (no body).
* Sets activated extensions header if present in context.
*
* @param res - Express response object
* @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 = <T>(
res: Response,
statusCode: number,
context: ServerCallContext,
body?: T,
responseType?: a2a.MessageFns<T>
): void => {
setExtensionsHeader(res, context);
res.status(statusCode);
if (statusCode === HTTP_STATUS.NO_CONTENT) {
res.end();
} else {
if (!responseType || body === undefined) {
throw new Error('Bug: toJson serializer and body must be provided for non-204 responses.');
}
res.json(responseType.toJSON(body));
}
};
/**
* Sends a Server-Sent Events (SSE) stream response.
* Sets appropriate SSE headers, streams events, and handles errors gracefully.
* Events are already converted to REST format by the transport handler.
* Sets activated extensions header if present in context.
*
* @param res - Express response object
* @param stream - Async generator yielding REST-formatted events
* @param context - ServerCallContext for setting extension headers
*/
const sendStreamResponse = async (
res: Response,
stream: AsyncGenerator<
Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent,
void,
undefined
>,
context: ServerCallContext
): Promise<void> => {
// Get first event before flushing headers to catch early errors
// This allows returning proper HTTP error codes instead of 200 + SSE error
const iterator = stream[Symbol.asyncIterator]();
let firstResult: IteratorResult<unknown>;
try {
firstResult = await iterator.next();
} catch (error) {
// Early error - return proper HTTP error
const a2aError =
error instanceof A2AError
? error
: A2AError.internalError(error instanceof Error ? error.message : 'Streaming error');
const statusCode = mapErrorToStatus(a2aError.code);
sendResponse(res, statusCode, context, toHTTPError(a2aError));
return;
}
// First event succeeded - now set SSE headers and stream
Object.entries(SSE_HEADERS).forEach(([key, value]) => {
res.setHeader(key, value);
});
setExtensionsHeader(res, context);
res.flushHeaders();
try {
// Write first event
if (!firstResult.done) {
const proto = ToProto.messageStreamResult(firstResult.value);
const result = a2a.StreamResponse.toJSON(proto);
res.write(formatSSEEvent(result));
}
for await (const event of { [Symbol.asyncIterator]: () => iterator }) {
const proto = ToProto.messageStreamResult(event);
const result = a2a.StreamResponse.toJSON(proto);
res.write(formatSSEEvent(result));
}
} catch (streamError: unknown) {
console.error('SSE streaming error:', streamError);
const a2aError =
streamError instanceof A2AError
? streamError
: A2AError.internalError(
streamError instanceof Error ? streamError.message : 'Streaming error'
);
if (!res.writableEnded) {
res.write(formatSSEErrorEvent(toHTTPError(a2aError)));
}
} finally {
if (!res.writableEnded) {
res.end();
}
}
};
/**
* Handles errors in route handlers by converting them to A2A error format
* and sending appropriate HTTP response.
* Gracefully handles cases where headers have already been sent.
*
* @param res - Express response object
* @param error - Error to handle (can be A2AError or generic Error)
*/
const handleError = (res: Response, error: unknown): void => {
if (res.headersSent) {
if (!res.writableEnded) {
res.end();
}
return;
}
const a2aError =
error instanceof A2AError
? error
: A2AError.internalError(error instanceof Error ? error.message : 'Internal server error');
const statusCode = mapErrorToStatus(a2aError.code);
res.status(statusCode).json(toHTTPError(a2aError));
};
/**
* Wraps an async route handler to centralize error handling.
* Catches any errors thrown by the handler and passes them to handleError.
*
* @param handler - Async route handler function
* @returns Wrapped handler with built-in error handling
*/
const asyncHandler = (handler: AsyncRouteHandler): AsyncRouteHandler => {
return async (req: Request, res: Response): Promise<void> => {
try {
await handler(req, res);
} catch (error) {
handleError(res, error);
}
};
};
// ============================================================================
// Route Handlers
// ============================================================================
/**
* GET /v1/card
*
* Retrieves the authenticated extended agent card.
*
* @returns 200 OK with agent card
* @returns 500 Internal Server Error on failure
*/
router.get(
'/v1/card',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const result = await restTransportHandler.getAuthenticatedExtendedAgentCard(context);
const protoResult = ToProto.agentCard(result);
sendResponse<a2a.AgentCard>(res, HTTP_STATUS.OK, context, protoResult, a2a.AgentCard);
})
);
/**
* POST /v1/message:send
*
* Sends a message to the agent synchronously.
* Returns either a Message (for immediate responses) or a Task (for async processing).
* Note: Colon is escaped in route definition for Express compatibility.
*
* @param req.body - MessageSendParams (accepts both snake_case and camelCase)
* @returns 201 Created with RestMessage or RestTask
* @returns 400 Bad Request if message is invalid
*/
router.post(
'/v1/message\\:send',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
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
);
})
);
/**
* POST /v1/message:stream
*
* Sends a message to the agent with streaming response.
* Returns a Server-Sent Events (SSE) stream of updates.
* Note: Colon is escaped in route definition for Express compatibility.
*
* @param req.body - MessageSendParams (accepts both snake_case and camelCase)
* @returns 200 OK with SSE stream of messages, tasks, and status updates
* @returns 400 Bad Request if message is invalid
* @returns 501 Not Implemented if streaming not supported
*/
router.post(
'/v1/message\\:stream',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const protoReq = a2a.SendMessageRequest.fromJSON(req.body);
const params = FromProto.messageSendParams(protoReq);
const stream = await restTransportHandler.sendMessageStream(params, context);
await sendStreamResponse(res, stream, context);
})
);
/**
* GET /v1/tasks/:taskId
*
* Retrieves the current status and details of a task.
*
* @param req.params.taskId - Task identifier
* @param req.query.historyLength - Optional number of history messages to include
* @returns 200 OK with RestTask
* @returns 400 Bad Request if historyLength is invalid
* @returns 404 Not Found if task doesn't exist
*/
router.get(
'/v1/tasks/:taskId',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const result = await restTransportHandler.getTask(
req.params.taskId,
context,
//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
);
const protoResult = ToProto.task(result);
sendResponse<a2a.Task>(res, HTTP_STATUS.OK, context, protoResult, a2a.Task);
})
);
/**
* POST /v1/tasks/:taskId:cancel
*
* Attempts to cancel an ongoing task.
* The task may not be immediately canceled depending on its current state.
*
* @param req.params.taskId - Task identifier
* @returns 202 Accepted with RestTask (task is being canceled)
* @returns 404 Not Found if task doesn't exist
* @returns 409 Conflict if task cannot be canceled
*/
router.post(
'/v1/tasks/:taskId\\:cancel',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const result = await restTransportHandler.cancelTask(req.params.taskId, context);
const protoResult = ToProto.task(result);
sendResponse<a2a.Task>(res, HTTP_STATUS.ACCEPTED, context, protoResult, a2a.Task);
})
);
/**
* POST /v1/tasks/:taskId:subscribe
*
* Resubscribes to an existing task's updates via Server-Sent Events (SSE).
* Useful for reconnecting to long-running tasks or receiving missed updates.
*
* @param req.params.taskId - Task identifier
* @returns 200 OK with SSE stream of task status and artifact updates
* @returns 404 Not Found if task doesn't exist
* @returns 501 Not Implemented if streaming not supported
*/
router.post(
'/v1/tasks/:taskId\\:subscribe',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const stream = await restTransportHandler.resubscribe(req.params.taskId, context);
await sendStreamResponse(res, stream, context);
})
);
/**
* POST /v1/tasks/:taskId/pushNotificationConfigs
*
* Creates a push notification configuration for a task.
* The agent will send task updates to the configured webhook URL.
*
* @param req.params.taskId - Task identifier
* @param req.body - Push notification configuration (snake_case format)
* @returns 201 Created with TaskPushNotificationConfig
* @returns 501 Not Implemented if push notifications not supported
*/
router.post(
'/v1/tasks/:taskId/pushNotificationConfigs',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
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
);
})
);
/**
* GET /v1/tasks/:taskId/pushNotificationConfigs
*
* Lists all push notification configurations for a task.
*
* @param req.params.taskId - Task identifier
* @returns 200 OK with array of TaskPushNotificationConfig
* @returns 404 Not Found if task doesn't exist
*/
router.get(
'/v1/tasks/:taskId/pushNotificationConfigs',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const result = await restTransportHandler.listTaskPushNotificationConfigs(
req.params.taskId,
context
);
const protoResult = ToProto.listTaskPushNotificationConfig(result);
sendResponse<a2a.ListTaskPushNotificationConfigResponse>(
res,
HTTP_STATUS.OK,
context,
protoResult,
a2a.ListTaskPushNotificationConfigResponse
);
})
);
/**
* GET /v1/tasks/:taskId/pushNotificationConfigs/:configId
*
* Retrieves a specific push notification configuration.
*
* @param req.params.taskId - Task identifier
* @param req.params.configId - Push notification configuration identifier
* @returns 200 OK with TaskPushNotificationConfig
* @returns 404 Not Found if task or config doesn't exist
*/
router.get(
'/v1/tasks/:taskId/pushNotificationConfigs/:configId',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
const result = await restTransportHandler.getTaskPushNotificationConfig(
req.params.taskId,
req.params.configId,
context
);
const protoResult = ToProto.taskPushNotificationConfig(result);
sendResponse<a2a.TaskPushNotificationConfig>(
res,
HTTP_STATUS.OK,
context,
protoResult,
a2a.TaskPushNotificationConfig
);
})
);
/**
* DELETE /v1/tasks/:taskId/pushNotificationConfigs/:configId
*
* Deletes a push notification configuration.
*
* @param req.params.taskId - Task identifier
* @param req.params.configId - Push notification configuration identifier
* @returns 204 No Content on success
* @returns 404 Not Found if task or config doesn't exist
*/
router.delete(
'/v1/tasks/:taskId/pushNotificationConfigs/:configId',
asyncHandler(async (req, res) => {
const context = await buildContext(req);
await restTransportHandler.deleteTaskPushNotificationConfig(
req.params.taskId,
req.params.configId,
context
);
sendResponse(res, HTTP_STATUS.NO_CONTENT, context);
})
);
return router;
}

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

@ -3,20 +3,35 @@
* Exports the server-only codebase.
*/
export type { AgentExecutor } from "./agent_execution/agent_executor.js";
export { RequestContext } from "./agent_execution/request_context.js";
export type { AgentExecutor } from './agent_execution/agent_executor.js';
export { RequestContext } from './agent_execution/request_context.js';
export type { AgentExecutionEvent, ExecutionEventBus } from "./events/execution_event_bus.js";
export { DefaultExecutionEventBus } from "./events/execution_event_bus.js";
export type { ExecutionEventBusManager } from "./events/execution_event_bus_manager.js";
export { DefaultExecutionEventBusManager } from "./events/execution_event_bus_manager.js";
export { ExecutionEventQueue } from "./events/execution_event_queue.js";
export type {
AgentExecutionEvent,
ExecutionEventBus,
ExecutionEventName,
} from './events/execution_event_bus.js';
export { DefaultExecutionEventBus } from './events/execution_event_bus.js';
export type { ExecutionEventBusManager } from './events/execution_event_bus_manager.js';
export { DefaultExecutionEventBusManager } from './events/execution_event_bus_manager.js';
export { ExecutionEventQueue } from './events/execution_event_queue.js';
export type { A2ARequestHandler } from "./request_handler/a2a_request_handler.js";
export { DefaultRequestHandler } from "./request_handler/default_request_handler.js";
export { ResultManager } from "./result_manager.js";
export type { TaskStore } from "./store.js";
export { InMemoryTaskStore } from "./store.js";
export type { A2ARequestHandler } from './request_handler/a2a_request_handler.js';
export { DefaultRequestHandler } from './request_handler/default_request_handler.js';
export type { ExtendedAgentCardProvider } from './request_handler/default_request_handler.js';
export { ResultManager } from './result_manager.js';
export type { TaskStore } from './store.js';
export { InMemoryTaskStore } from './store.js';
export { JsonRpcTransportHandler } from "./transports/jsonrpc_transport_handler.js";
export { A2AError } from "./error.js";
export { JsonRpcTransportHandler } from './transports/jsonrpc/jsonrpc_transport_handler.js';
export { ServerCallContext } from './context.js';
export { A2AError } from './error.js';
export type { PushNotificationSender } from './push_notification/push_notification_sender.js';
export { DefaultPushNotificationSender } from './push_notification/default_push_notification_sender.js';
export type { DefaultPushNotificationSenderOptions } from './push_notification/default_push_notification_sender.js';
export type { PushNotificationStore } from './push_notification/push_notification_store.js';
export { InMemoryPushNotificationStore } from './push_notification/push_notification_store.js';
export type { User } from './authentication/user.js';
export { UnauthenticatedUser } from './authentication/user.js';

View File

@ -0,0 +1,101 @@
import { Task, PushNotificationConfig } from '../../types.js';
import { PushNotificationSender } from './push_notification_sender.js';
import { PushNotificationStore } from './push_notification_store.js';
export interface DefaultPushNotificationSenderOptions {
/**
* Timeout in milliseconds for the abort controller. Defaults to 5000ms.
*/
timeout?: number;
/**
* Custom header name for the token. Defaults to 'X-A2A-Notification-Token'.
*/
tokenHeaderName?: string;
}
export class DefaultPushNotificationSender implements PushNotificationSender {
private readonly pushNotificationStore: PushNotificationStore;
private notificationChain: Map<string, Promise<unknown>>;
private readonly options: Required<DefaultPushNotificationSenderOptions>;
constructor(
pushNotificationStore: PushNotificationStore,
options: DefaultPushNotificationSenderOptions = {}
) {
this.pushNotificationStore = pushNotificationStore;
this.notificationChain = new Map();
this.options = {
timeout: 5000,
tokenHeaderName: 'X-A2A-Notification-Token',
...options,
};
}
async send(task: Task): Promise<void> {
const pushConfigs = await this.pushNotificationStore.load(task.id);
if (!pushConfigs || pushConfigs.length === 0) {
return;
}
const lastPromise = this.notificationChain.get(task.id) ?? Promise.resolve();
// Chain promises to ensure notifications for the same task are sent sequentially.
// Once the promise is resolved, the Garbage Collector will clean it up if there are no other references to it.
// This will prevent memory to linearly grow with the number of notifications sent.
const newPromise = lastPromise.then(async () => {
const dispatches = pushConfigs.map(async (pushConfig) => {
try {
await this._dispatchNotification(task, pushConfig);
} catch (error) {
console.error(
`Error sending push notification for task_id=${task.id} to URL: ${pushConfig.url}. Error:`,
error
);
}
});
await Promise.all(dispatches);
});
this.notificationChain.set(task.id, newPromise);
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);
}
});
}
private async _dispatchNotification(
task: Task,
pushConfig: PushNotificationConfig
): Promise<void> {
const url = pushConfig.url;
const controller = new AbortController();
// Abort the request if it takes longer than the configured timeout.
const timeoutId = setTimeout(() => controller.abort(), this.options.timeout);
try {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};
if (pushConfig.token) {
headers[this.options.tokenHeaderName] = pushConfig.token;
}
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(task),
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
console.info(`Push notification sent for task_id=${task.id} to URL: ${url}`);
} finally {
clearTimeout(timeoutId);
}
}
}

View File

@ -0,0 +1,5 @@
import { Task } from '../../types.js';
export interface PushNotificationSender {
send(task: Task): Promise<void>;
}

View File

@ -0,0 +1,58 @@
import { PushNotificationConfig } from '../../types.js';
export interface PushNotificationStore {
save(taskId: string, pushNotificationConfig: PushNotificationConfig): Promise<void>;
load(taskId: string): Promise<PushNotificationConfig[]>;
delete(taskId: string, configId?: string): Promise<void>;
}
export class InMemoryPushNotificationStore implements PushNotificationStore {
private store: Map<string, PushNotificationConfig[]> = new Map();
async save(taskId: string, pushNotificationConfig: PushNotificationConfig): Promise<void> {
const configs = this.store.get(taskId) || [];
// Set ID if it's not already set
if (!pushNotificationConfig.id) {
pushNotificationConfig.id = taskId;
}
// Remove existing config with the same ID if it exists
const existingIndex = configs.findIndex((config) => config.id === pushNotificationConfig.id);
if (existingIndex !== -1) {
configs.splice(existingIndex, 1);
}
// Add the new/updated config
configs.push(pushNotificationConfig);
this.store.set(taskId, configs);
}
async load(taskId: string): Promise<PushNotificationConfig[]> {
const configs = this.store.get(taskId);
return configs || [];
}
async delete(taskId: string, configId?: string): Promise<void> {
// If no configId is provided, use taskId as the configId (backward compatibility)
if (configId === undefined) {
configId = taskId;
}
const configs = this.store.get(taskId);
if (!configs) {
return;
}
const configIndex = configs.findIndex((config) => config.id === configId);
if (configIndex !== -1) {
configs.splice(configIndex, 1);
}
if (configs.length === 0) {
this.store.delete(taskId);
} else {
this.store.set(taskId, configs);
}
}
}

View File

@ -1,64 +1,60 @@
import {
Message,
AgentCard,
MessageSendParams,
Task,
TaskStatusUpdateEvent,
TaskArtifactUpdateEvent,
TaskQueryParams,
TaskIdParams,
TaskPushNotificationConfig,
GetTaskPushNotificationConfigParams,
ListTaskPushNotificationConfigParams,
DeleteTaskPushNotificationConfigParams,
} from "../../types.js";
Message,
AgentCard,
MessageSendParams,
Task,
TaskStatusUpdateEvent,
TaskArtifactUpdateEvent,
TaskQueryParams,
TaskIdParams,
TaskPushNotificationConfig,
GetTaskPushNotificationConfigParams,
ListTaskPushNotificationConfigParams,
DeleteTaskPushNotificationConfigParams,
} from '../../types.js';
import { ServerCallContext } from '../context.js';
export interface A2ARequestHandler {
getAgentCard(): Promise<AgentCard>;
getAgentCard(): Promise<AgentCard>;
getAuthenticatedExtendedAgentCard(): Promise<AgentCard>;
getAuthenticatedExtendedAgentCard(context?: ServerCallContext): Promise<AgentCard>;
sendMessage(
params: MessageSendParams
): Promise<Message | Task>;
sendMessage(params: MessageSendParams, context?: ServerCallContext): Promise<Message | Task>;
sendMessageStream(
params: MessageSendParams
): AsyncGenerator<
| Message
| Task
| TaskStatusUpdateEvent
| TaskArtifactUpdateEvent,
void,
undefined
>;
sendMessageStream(
params: MessageSendParams,
context?: ServerCallContext
): AsyncGenerator<
Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent,
void,
undefined
>;
getTask(params: TaskQueryParams): Promise<Task>;
cancelTask(params: TaskIdParams): Promise<Task>;
getTask(params: TaskQueryParams, context?: ServerCallContext): Promise<Task>;
cancelTask(params: TaskIdParams, context?: ServerCallContext): Promise<Task>;
setTaskPushNotificationConfig(
params: TaskPushNotificationConfig
): Promise<TaskPushNotificationConfig>;
setTaskPushNotificationConfig(
params: TaskPushNotificationConfig,
context?: ServerCallContext
): Promise<TaskPushNotificationConfig>;
getTaskPushNotificationConfig(
params: TaskIdParams | GetTaskPushNotificationConfigParams
): Promise<TaskPushNotificationConfig>;
getTaskPushNotificationConfig(
params: TaskIdParams | GetTaskPushNotificationConfigParams,
context?: ServerCallContext
): Promise<TaskPushNotificationConfig>;
listTaskPushNotificationConfigs(
params: ListTaskPushNotificationConfigParams
): Promise<TaskPushNotificationConfig[]>;
listTaskPushNotificationConfigs(
params: ListTaskPushNotificationConfigParams,
context?: ServerCallContext
): Promise<TaskPushNotificationConfig[]>;
deleteTaskPushNotificationConfig(
params: DeleteTaskPushNotificationConfigParams
): Promise<void>;
deleteTaskPushNotificationConfig(
params: DeleteTaskPushNotificationConfigParams,
context?: ServerCallContext
): Promise<void>;
resubscribe(
params: TaskIdParams
): AsyncGenerator<
| Task
| TaskStatusUpdateEvent
| TaskArtifactUpdateEvent,
void,
undefined
>;
}
resubscribe(
params: TaskIdParams,
context?: ServerCallContext
): AsyncGenerator<Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent, void, undefined>;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,155 +1,181 @@
import {
Message,
Task,
TaskArtifactUpdateEvent,
TaskStatusUpdateEvent
} from "../types.js";
import { AgentExecutionEvent } from "./events/execution_event_bus.js";
import { TaskStore } from "./store.js";
import { Message, Task, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '../types.js';
import { ServerCallContext } from './context.js';
import { AgentExecutionEvent } from './events/execution_event_bus.js';
import { TaskStore } from './store.js';
export class ResultManager {
private taskStore: TaskStore;
private currentTask?: Task;
private latestUserMessage?: Message; // To add to history if a new task is created
private finalMessageResult?: Message; // Stores the message if it's the final result
private readonly taskStore: TaskStore;
private readonly serverCallContext?: ServerCallContext;
constructor(taskStore: TaskStore) {
this.taskStore = taskStore;
}
private currentTask?: Task;
private latestUserMessage?: Message; // To add to history if a new task is created
private finalMessageResult?: Message; // Stores the message if it's the final result
public setContext(latestUserMessage: Message): void {
this.latestUserMessage = latestUserMessage;
}
constructor(taskStore: TaskStore, serverCallContext?: ServerCallContext) {
this.taskStore = taskStore;
this.serverCallContext = serverCallContext;
}
/**
* Processes an agent execution event and updates the task store.
* @param event The agent execution event.
*/
public async processEvent(event: AgentExecutionEvent): Promise<void> {
if (event.kind === 'message') {
this.finalMessageResult = event as Message;
// If a message is received, it's usually the final result,
// but we continue processing to ensure task state (if any) is also saved.
// The ExecutionEventQueue will stop after a message event.
} else if (event.kind === 'task') {
const taskEvent = event as Task;
this.currentTask = { ...taskEvent }; // Make a copy
public setContext(latestUserMessage: Message): void {
this.latestUserMessage = latestUserMessage;
}
// Ensure the latest user message is in history if not already present
if (this.latestUserMessage) {
if (!this.currentTask.history?.find(msg => msg.messageId === this.latestUserMessage!.messageId)) {
this.currentTask.history = [this.latestUserMessage, ...(this.currentTask.history || [])];
}
}
await this.saveCurrentTask();
} else if (event.kind === 'status-update') {
const updateEvent = event as TaskStatusUpdateEvent;
if (this.currentTask && this.currentTask.id === updateEvent.taskId) {
this.currentTask.status = updateEvent.status;
if (updateEvent.status.message) {
// Add message to history if not already present
if (!this.currentTask.history?.find(msg => msg.messageId === updateEvent.status.message!.messageId)) {
this.currentTask.history = [...(this.currentTask.history || []), updateEvent.status.message];
}
}
await this.saveCurrentTask();
} else if (!this.currentTask && updateEvent.taskId) {
// Potentially an update for a task we haven't seen the 'task' event for yet,
// or we are rehydrating. Attempt to load.
const loaded = await this.taskStore.load(updateEvent.taskId);
if (loaded) {
this.currentTask = loaded;
this.currentTask.status = updateEvent.status;
if (updateEvent.status.message) {
if (!this.currentTask.history?.find(msg => msg.messageId === updateEvent.status.message!.messageId)) {
this.currentTask.history = [...(this.currentTask.history || []), updateEvent.status.message];
}
}
await this.saveCurrentTask();
} else {
console.warn(`ResultManager: Received status update for unknown task ${updateEvent.taskId}`);
}
}
// If it's a final status update, the ExecutionEventQueue will stop.
// The final result will be the currentTask.
} else if (event.kind === 'artifact-update') {
const artifactEvent = event as TaskArtifactUpdateEvent;
if (this.currentTask && this.currentTask.id === artifactEvent.taskId) {
if (!this.currentTask.artifacts) {
this.currentTask.artifacts = [];
}
const existingArtifactIndex = this.currentTask.artifacts.findIndex(
(art) => art.artifactId === artifactEvent.artifact.artifactId
);
if (existingArtifactIndex !== -1) {
if (artifactEvent.append) {
// Basic append logic, assuming parts are compatible
// More sophisticated merging might be needed for specific part types
const existingArtifact = this.currentTask.artifacts[existingArtifactIndex];
existingArtifact.parts.push(...artifactEvent.artifact.parts);
if (artifactEvent.artifact.description) existingArtifact.description = artifactEvent.artifact.description;
if (artifactEvent.artifact.name) existingArtifact.name = artifactEvent.artifact.name;
if (artifactEvent.artifact.metadata) existingArtifact.metadata = { ...existingArtifact.metadata, ...artifactEvent.artifact.metadata };
/**
* Processes an agent execution event and updates the task store.
* @param event The agent execution event.
*/
public async processEvent(event: AgentExecutionEvent): Promise<void> {
if (event.kind === 'message') {
this.finalMessageResult = event as Message;
// If a message is received, it's usually the final result,
// but we continue processing to ensure task state (if any) is also saved.
// The ExecutionEventQueue will stop after a message event.
} else if (event.kind === 'task') {
const taskEvent = event as Task;
this.currentTask = { ...taskEvent }; // Make a copy
} else {
this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
}
} else {
this.currentTask.artifacts.push(artifactEvent.artifact);
}
await this.saveCurrentTask();
} else if (!this.currentTask && artifactEvent.taskId) {
// Similar to status update, try to load if task not in memory
const loaded = await this.taskStore.load(artifactEvent.taskId);
if (loaded) {
this.currentTask = loaded;
if (!this.currentTask.artifacts) this.currentTask.artifacts = [];
// Apply artifact update logic (as above)
const existingArtifactIndex = this.currentTask.artifacts.findIndex(
(art) => art.artifactId === artifactEvent.artifact.artifactId
);
if (existingArtifactIndex !== -1) {
if (artifactEvent.append) {
this.currentTask.artifacts[existingArtifactIndex].parts.push(...artifactEvent.artifact.parts);
} else {
this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
}
} else {
this.currentTask.artifacts.push(artifactEvent.artifact);
}
await this.saveCurrentTask();
} else {
console.warn(`ResultManager: Received artifact update for unknown task ${artifactEvent.taskId}`);
}
}
// Ensure the latest user message is in history if not already present
if (this.latestUserMessage) {
if (
!this.currentTask.history?.find(
(msg) => msg.messageId === this.latestUserMessage!.messageId
)
) {
this.currentTask.history = [this.latestUserMessage, ...(this.currentTask.history || [])];
}
}
private async saveCurrentTask(): Promise<void> {
if (this.currentTask) {
await this.taskStore.save(this.currentTask);
}
await this.saveCurrentTask();
} else if (event.kind === 'status-update') {
const updateEvent = event as TaskStatusUpdateEvent;
if (this.currentTask && this.currentTask.id === updateEvent.taskId) {
this.currentTask.status = updateEvent.status;
if (updateEvent.status.message) {
// Add message to history if not already present
if (
!this.currentTask.history?.find(
(msg) => msg.messageId === updateEvent.status.message!.messageId
)
) {
this.currentTask.history = [
...(this.currentTask.history || []),
updateEvent.status.message,
];
}
}
}
/**
* Gets the final result, which could be a Message or a Task.
* This should be called after the event stream has been fully processed.
* @returns The final Message or the current Task.
*/
public getFinalResult(): Message | Task | undefined {
if (this.finalMessageResult) {
return this.finalMessageResult;
await this.saveCurrentTask();
} else if (!this.currentTask && updateEvent.taskId) {
// Potentially an update for a task we haven't seen the 'task' event for yet,
// or we are rehydrating. Attempt to load.
const loaded = await this.taskStore.load(updateEvent.taskId, this.serverCallContext);
if (loaded) {
this.currentTask = loaded;
this.currentTask.status = updateEvent.status;
if (updateEvent.status.message) {
if (
!this.currentTask.history?.find(
(msg) => msg.messageId === updateEvent.status.message!.messageId
)
) {
this.currentTask.history = [
...(this.currentTask.history || []),
updateEvent.status.message,
];
}
}
await this.saveCurrentTask();
} else {
console.warn(
`ResultManager: Received status update for unknown task ${updateEvent.taskId}`
);
}
return this.currentTask;
}
// If it's a final status update, the ExecutionEventQueue will stop.
// The final result will be the currentTask.
} else if (event.kind === 'artifact-update') {
const artifactEvent = event as TaskArtifactUpdateEvent;
if (this.currentTask && this.currentTask.id === artifactEvent.taskId) {
if (!this.currentTask.artifacts) {
this.currentTask.artifacts = [];
}
const existingArtifactIndex = this.currentTask.artifacts.findIndex(
(art) => art.artifactId === artifactEvent.artifact.artifactId
);
if (existingArtifactIndex !== -1) {
if (artifactEvent.append) {
// Basic append logic, assuming parts are compatible
// More sophisticated merging might be needed for specific part types
const existingArtifact = this.currentTask.artifacts[existingArtifactIndex];
existingArtifact.parts.push(...artifactEvent.artifact.parts);
if (artifactEvent.artifact.description)
existingArtifact.description = artifactEvent.artifact.description;
if (artifactEvent.artifact.name) existingArtifact.name = artifactEvent.artifact.name;
if (artifactEvent.artifact.metadata)
existingArtifact.metadata = {
...existingArtifact.metadata,
...artifactEvent.artifact.metadata,
};
} else {
this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
}
} else {
this.currentTask.artifacts.push(artifactEvent.artifact);
}
await this.saveCurrentTask();
} else if (!this.currentTask && artifactEvent.taskId) {
// Similar to status update, try to load if task not in memory
const loaded = await this.taskStore.load(artifactEvent.taskId, this.serverCallContext);
if (loaded) {
this.currentTask = loaded;
if (!this.currentTask.artifacts) this.currentTask.artifacts = [];
// Apply artifact update logic (as above)
const existingArtifactIndex = this.currentTask.artifacts.findIndex(
(art) => art.artifactId === artifactEvent.artifact.artifactId
);
if (existingArtifactIndex !== -1) {
if (artifactEvent.append) {
this.currentTask.artifacts[existingArtifactIndex].parts.push(
...artifactEvent.artifact.parts
);
} else {
this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
}
} else {
this.currentTask.artifacts.push(artifactEvent.artifact);
}
await this.saveCurrentTask();
} else {
console.warn(
`ResultManager: Received artifact update for unknown task ${artifactEvent.taskId}`
);
}
}
}
}
/**
* Gets the task currently being managed by this ResultManager instance.
* This task could be one that was started with or one created during agent execution.
* @returns The current Task or undefined if no task is active.
*/
public getCurrentTask(): Task | undefined {
return this.currentTask;
private async saveCurrentTask(): Promise<void> {
if (this.currentTask) {
await this.taskStore.save(this.currentTask, this.serverCallContext);
}
}
}
/**
* Gets the final result, which could be a Message or a Task.
* This should be called after the event stream has been fully processed.
* @returns The final Message or the current Task.
*/
public getFinalResult(): Message | Task | undefined {
if (this.finalMessageResult) {
return this.finalMessageResult;
}
return this.currentTask;
}
/**
* Gets the task currently being managed by this ResultManager instance.
* This task could be one that was started with or one created during agent execution.
* @returns The current Task or undefined if no task is active.
*/
public getCurrentTask(): Task | undefined {
return this.currentTask;
}
}

Some files were not shown because too many files have changed in this diff Show More