Compare commits

..

1 Commits

Author SHA1 Message Date
Ivan Shymko
97c4f9734d
test: WIP 2025-12-16 13:34:26 +00:00
89 changed files with 5215 additions and 25981 deletions

View File

@ -1,85 +0,0 @@
// 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"]
]
}`
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

7389
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

@ -1,349 +0,0 @@
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

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

View File

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

View File

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

View File

@ -1,23 +1,4 @@
// 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.
// Transport-agnostic errors according to https://a2a-protocol.org/latest/specification/#82-a2a-specific-errors;
export class TaskNotFoundError extends Error {
constructor(message?: string) {

View File

@ -1,51 +0,0 @@
# 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.

View File

@ -1,18 +0,0 @@
# 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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +0,0 @@
// 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

@ -1,83 +0,0 @@
// 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

@ -1,612 +0,0 @@
// 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

@ -1,64 +0,0 @@
// 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

@ -1,152 +0,0 @@
// 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

@ -1,53 +0,0 @@
// 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

@ -1,384 +0,0 @@
// 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

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

View File

@ -9,9 +9,6 @@ import {
TextPart,
Message,
AGENT_CARD_PATH,
TaskArtifactUpdateEvent,
Artifact,
Part,
} from '../../../index.js';
import {
InMemoryTaskStore,
@ -195,44 +192,25 @@ class MovieAgentExecutor implements AgentExecutor {
finalA2AState = 'completed'; // Default if LLM deviates
}
// 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)
// 5. Publish final task status update
const agentMessage: Message = {
kind: 'message',
role: 'agent',
messageId: uuidv4(),
parts: parts,
parts: [{ kind: 'text', text: agentReplyText || 'Completed.' }], // Ensure some text
taskId: taskId,
contextId: contextId,
};
historyForGenkit.push(agentMessage);
contexts.set(contextId, historyForGenkit);
// 7. Publish final task status update
const finalUpdate: TaskStatusUpdateEvent = {
kind: 'status-update',
taskId: taskId,
contextId: contextId,
status: {
state: finalA2AState,
message: agentMessage,
timestamp: new Date().toISOString(),
},
final: true,

View File

@ -1,12 +1,6 @@
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
import {
Task,
TaskStatusUpdateEvent,
Message,
TaskArtifactUpdateEvent,
Artifact,
} from '../../../index.js';
import { Task, TaskStatusUpdateEvent, Message } from '../../../index.js';
import { AgentExecutor, RequestContext, ExecutionEventBus } from '../../../server/index.js';
/**
@ -64,39 +58,31 @@ export class SampleAgentExecutor implements AgentExecutor {
};
eventBus.publish(workingStatusUpdate);
// 3. Publish artifact with the result
// 3. Publish final task status update
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.',
const agentMessage: Message = {
kind: 'message',
role: 'agent',
messageId: uuidv4(),
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',
message: agentMessage,
timestamp: new Date().toISOString(),
},
final: true,
};
await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate processing delay
eventBus.publish(finalUpdate);
console.log(`[SampleAgentExecutor] Task ${taskId} finished with state: completed`);

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

@ -19,11 +19,6 @@ 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.
*/
@ -135,24 +130,19 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
* @param statusCode - HTTP status code
* @param context - ServerCallContext for setting extension headers
* @param body - Response body (omitted for 204 responses)
* @param responseType - Optional protobuf message type for serialization
*/
const sendResponse = <T>(
const sendResponse = (
res: Response,
statusCode: number,
context: ServerCallContext,
body?: T,
responseType?: a2a.MessageFns<T>
body?: unknown
): 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));
res.json(body);
}
};
@ -168,11 +158,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
*/
const sendStreamResponse = async (
res: Response,
stream: AsyncGenerator<
Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent,
void,
undefined
>,
stream: AsyncGenerator<unknown, void, undefined>,
context: ServerCallContext
): Promise<void> => {
// Get first event before flushing headers to catch early errors
@ -202,14 +188,11 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
try {
// Write first event
if (!firstResult.done) {
const proto = ToProto.messageStreamResult(firstResult.value);
const result = a2a.StreamResponse.toJSON(proto);
res.write(formatSSEEvent(result));
res.write(formatSSEEvent(firstResult.value));
}
// Continue with remaining events
for await (const event of { [Symbol.asyncIterator]: () => iterator }) {
const proto = ToProto.messageStreamResult(event);
const result = a2a.StreamResponse.toJSON(proto);
res.write(formatSSEEvent(result));
res.write(formatSSEEvent(event));
}
} catch (streamError: unknown) {
console.error('SSE streaming error:', streamError);
@ -285,9 +268,8 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
'/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);
const result = await restTransportHandler.getAuthenticatedExtendedAgentCard();
sendResponse(res, HTTP_STATUS.OK, context, result);
})
);
@ -306,17 +288,8 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
'/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
);
const result = await restTransportHandler.sendMessage(req.body, context);
sendResponse(res, HTTP_STATUS.CREATED, context, result);
})
);
@ -336,9 +309,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
'/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);
const stream = await restTransportHandler.sendMessageStream(req.body, context);
await sendStreamResponse(res, stream, context);
})
);
@ -361,11 +332,9 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
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
req.query.historyLength
);
const protoResult = ToProto.task(result);
sendResponse<a2a.Task>(res, HTTP_STATUS.OK, context, protoResult, a2a.Task);
sendResponse(res, HTTP_STATUS.OK, context, result);
})
);
@ -385,8 +354,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
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);
sendResponse(res, HTTP_STATUS.ACCEPTED, context, result);
})
);
@ -425,17 +393,13 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
'/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
);
const config = {
...req.body,
taskId: req.params.taskId,
task_id: req.params.taskId,
};
const result = await restTransportHandler.setTaskPushNotificationConfig(config, context);
sendResponse(res, HTTP_STATUS.CREATED, context, result);
})
);
@ -456,14 +420,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
req.params.taskId,
context
);
const protoResult = ToProto.listTaskPushNotificationConfig(result);
sendResponse<a2a.ListTaskPushNotificationConfigResponse>(
res,
HTTP_STATUS.OK,
context,
protoResult,
a2a.ListTaskPushNotificationConfigResponse
);
sendResponse(res, HTTP_STATUS.OK, context, result);
})
);
@ -486,14 +443,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
req.params.configId,
context
);
const protoResult = ToProto.taskPushNotificationConfig(result);
sendResponse<a2a.TaskPushNotificationConfig>(
res,
HTTP_STATUS.OK,
context,
protoResult,
a2a.TaskPushNotificationConfig
);
sendResponse(res, HTTP_STATUS.OK, context, result);
})
);

View File

@ -1,10 +0,0 @@
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

@ -1,285 +0,0 @@
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;
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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