Compare commits
1 Commits
main
...
update-rel
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d3082f56e |
@ -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"]
|
||||
]
|
||||
}`
|
||||
};
|
||||
@ -1,8 +0,0 @@
|
||||
import { typescript } from '@betterer/typescript';
|
||||
|
||||
export default {
|
||||
'TypeScript Strict Mode': () =>
|
||||
typescript('./tsconfig.json', {
|
||||
strict: true,
|
||||
}).include('./src/**/*.ts', './tck/**/*.ts'),
|
||||
};
|
||||
@ -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)"
|
||||
]
|
||||
}
|
||||
}
|
||||
2
.github/CODEOWNERS
vendored
2
.github/CODEOWNERS
vendored
@ -4,4 +4,4 @@
|
||||
# For syntax help see:
|
||||
# https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax
|
||||
|
||||
* @a2aproject/google-a2a-js
|
||||
* @google-a2a/googlers
|
||||
|
||||
2
.github/conventional-commit-lint.yaml
vendored
Normal file
2
.github/conventional-commit-lint.yaml
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
enabled: true
|
||||
always_check_pr_title: true
|
||||
30
.github/workflows/build-tests.yml
vendored
30
.github/workflows/build-tests.yml
vendored
@ -1,30 +0,0 @@
|
||||
# Ensures no accidential Node.js API usage in browser and Edge compatible entrypoints.
|
||||
|
||||
name: Run Build Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
- '.github/CODEOWNERS'
|
||||
- 'test/**'
|
||||
|
||||
jobs:
|
||||
test:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- run: npm run test-build
|
||||
26
.github/workflows/conventional-commits.yml
vendored
26
.github/workflows/conventional-commits.yml
vendored
@ -1,26 +0,0 @@
|
||||
name: "Conventional Commits"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types:
|
||||
- opened
|
||||
- edited
|
||||
- synchronize
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
main:
|
||||
permissions:
|
||||
pull-requests: read
|
||||
statuses: write
|
||||
name: Validate PR Title
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: semantic-pull-request
|
||||
uses: amannn/action-semantic-pull-request@v5.5.3
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
validateSingleCommit: false
|
||||
164
.github/workflows/coverage-comment.yml
vendored
164
.github/workflows/coverage-comment.yml
vendored
@ -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
|
||||
});
|
||||
}
|
||||
29
.github/workflows/lint.yml
vendored
29
.github/workflows/lint.yml
vendored
@ -1,29 +0,0 @@
|
||||
name: Run Linter & Formatter
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
- '.github/CODEOWNERS'
|
||||
|
||||
jobs:
|
||||
eslint:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: |
|
||||
package-lock.json
|
||||
src/samples/package-lock.json
|
||||
- run: npm ci && (cd src/samples && npm ci)
|
||||
- run: npm run lint:ci
|
||||
4
.github/workflows/npm-publish.yml
vendored
4
.github/workflows/npm-publish.yml
vendored
@ -10,16 +10,12 @@ on:
|
||||
jobs:
|
||||
publish-npm:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
|
||||
|
||||
1
.github/workflows/release-please.yml
vendored
1
.github/workflows/release-please.yml
vendored
@ -15,5 +15,4 @@ jobs:
|
||||
steps:
|
||||
- uses: googleapis/release-please-action@v4
|
||||
with:
|
||||
token: ${{ secrets.A2A_BOT_PAT }}
|
||||
release-type: node
|
||||
|
||||
121
.github/workflows/run-tck.yaml
vendored
121
.github/workflows/run-tck.yaml
vendored
@ -1,121 +0,0 @@
|
||||
name: Run TCK
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
- '.github/CODEOWNERS'
|
||||
- 'test/**'
|
||||
- 'src/samples/**'
|
||||
|
||||
|
||||
env:
|
||||
# Tag of the TCK
|
||||
TCK_VERSION: 0.3.0.beta3
|
||||
# Tells uv to not need a venv, and instead use system
|
||||
UV_SYSTEM_PYTHON: 1
|
||||
# Base URL for the SUT agent
|
||||
SUT_BASE_URL: http://localhost:41241
|
||||
# Base URL for the SUT agent JSON-RPC transport
|
||||
SUT_JSONRPC_URL: http://localhost:41241/a2a/jsonrpc
|
||||
# Slow system on CI
|
||||
TCK_STREAMING_TIMEOUT: 5.0
|
||||
|
||||
# Only run the latest job
|
||||
concurrency:
|
||||
group: '${{ github.workflow }} @ ${{ github.head_ref || github.ref }}'
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
tck-test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20, 22, 24]
|
||||
steps:
|
||||
- name: Checkout a2a-js
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: |
|
||||
npm ci
|
||||
npm run build
|
||||
- name: Checkout a2a-tck
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: a2aproject/a2a-tck
|
||||
path: tck/a2a-tck
|
||||
ref: ${{ env.TCK_VERSION }}
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version-file: "tck/a2a-tck/pyproject.toml"
|
||||
- name: Install uv and Python dependencies
|
||||
run: |
|
||||
pip install uv
|
||||
uv pip install -e .
|
||||
working-directory: tck/a2a-tck
|
||||
- name: Start SUT
|
||||
run: |
|
||||
cd tck
|
||||
npm run tck:sut-agent &
|
||||
- name: Wait for SUT to start
|
||||
run: |
|
||||
URL="${{ env.SUT_BASE_URL }}/.well-known/agent-card.json"
|
||||
EXPECTED_STATUS=200
|
||||
TIMEOUT=120
|
||||
RETRY_INTERVAL=2
|
||||
START_TIME=$(date +%s)
|
||||
|
||||
while true; do
|
||||
# Calculate elapsed time
|
||||
CURRENT_TIME=$(date +%s)
|
||||
ELAPSED_TIME=$((CURRENT_TIME - START_TIME))
|
||||
|
||||
# Check for timeout
|
||||
if [ "$ELAPSED_TIME" -ge "$TIMEOUT" ]; then
|
||||
echo "❌ Timeout: Server did not respond with status $EXPECTED_STATUS within $TIMEOUT seconds."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get HTTP status code. || true is to reporting a failure to connect as an error
|
||||
HTTP_STATUS=$(curl --output /dev/null --silent --write-out "%{http_code}" "$URL") || true
|
||||
echo "STATUS: ${HTTP_STATUS}"
|
||||
|
||||
# Check if we got the correct status code
|
||||
if [ "$HTTP_STATUS" -eq "$EXPECTED_STATUS" ]; then
|
||||
echo "✅ Server is up! Received status $HTTP_STATUS after $ELAPSED_TIME seconds."
|
||||
break;
|
||||
fi
|
||||
|
||||
# Wait before retrying
|
||||
echo "⏳ Server not ready (status: $HTTP_STATUS). Retrying in $RETRY_INTERVAL seconds..."
|
||||
sleep "$RETRY_INTERVAL"
|
||||
done
|
||||
|
||||
- name: Run TCK (mandatory)
|
||||
id: run-tck-mandatory
|
||||
timeout-minutes: 5
|
||||
run: |
|
||||
./run_tck.py --sut-url ${{ env.SUT_JSONRPC_URL }} --category mandatory --transports jsonrpc,rest,grpc
|
||||
working-directory: tck/a2a-tck
|
||||
- name: Run TCK (capabilities)
|
||||
id: run-tck-capabilities
|
||||
timeout-minutes: 5
|
||||
run: |
|
||||
./run_tck.py --sut-url ${{ env.SUT_JSONRPC_URL }} --category capabilities --transports jsonrpc,rest,grpc
|
||||
working-directory: tck/a2a-tck
|
||||
- name: Stop SUT
|
||||
if: always()
|
||||
run: |
|
||||
# Find and kill the SUT process
|
||||
pkill -f "npm run tck:sut-agent" || true
|
||||
sleep 2
|
||||
97
.github/workflows/unit-tests.yml
vendored
97
.github/workflows/unit-tests.yml
vendored
@ -5,108 +5,21 @@ 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:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20, 22, 24]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
node-version: 18
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
|
||||
# Edge runtime tests use @edge-runtime/vm to emulate Cloudflare Workers,
|
||||
# Vercel Edge Functions, and similar environments. This ensures the SDK
|
||||
# works correctly in non-Node.js server environments.
|
||||
test-edge:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm run test:edge
|
||||
|
||||
# The vitest 4.0.x test coverage integration doesn't support Node 18,
|
||||
# Node 18 has reached EOL already, however for compatibility we're still going to run tests
|
||||
# for Node 18 until the next major release (see https://github.com/a2aproject/a2a-js/pull/256).
|
||||
# Run coverage only once on a modern node to generate a report to avoid downgrading vitest.
|
||||
coverage:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Base Branch
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.base.ref || 'main' }}
|
||||
clean: true
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install & Test (Base Branch)
|
||||
timeout-minutes: 10
|
||||
run: |
|
||||
npm ci
|
||||
npm run coverage
|
||||
mv coverage/coverage-summary.json ${{ runner.temp }}/coverage-base-summary.json
|
||||
|
||||
- name: Upload Artifact (base)
|
||||
uses: actions/upload-artifact@v4
|
||||
if: github.event_name != 'pull_request'
|
||||
with:
|
||||
name: coverage-report
|
||||
path: coverage
|
||||
retention-days: 14
|
||||
|
||||
- name: Checkout PR Branch
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
clean: true
|
||||
|
||||
- name: Install & Test (PR)
|
||||
if: github.event_name == 'pull_request'
|
||||
timeout-minutes: 10
|
||||
run: |
|
||||
npm ci
|
||||
npm run coverage
|
||||
mv coverage/coverage-summary.json coverage-pr-summary.json
|
||||
mv ${{ runner.temp }}/coverage-base-summary.json coverage-base-summary.json
|
||||
|
||||
- name: Save PR number
|
||||
run: |
|
||||
echo ${{ github.event.number }} > ./PR_NUMBER
|
||||
|
||||
- name: Upload Coverage Artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
if: github.event_name == 'pull_request'
|
||||
with:
|
||||
name: coverage-data
|
||||
path: |
|
||||
coverage-base-summary.json
|
||||
coverage-pr-summary.json
|
||||
coverage/
|
||||
PR_NUMBER
|
||||
retention-days: 1
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -179,4 +179,3 @@ testem.log
|
||||
# System files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.nyc_output/
|
||||
|
||||
@ -1,7 +0,0 @@
|
||||
{
|
||||
"trailingComma": "es5",
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2
|
||||
}
|
||||
74
AGENTS.md
74
AGENTS.md
@ -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.
|
||||
183
CHANGELOG.md
183
CHANGELOG.md
@ -1,188 +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)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add support for extendedAgentCard on client side ([#234](https://github.com/a2aproject/a2a-js/issues/234)) ([3073376](https://github.com/a2aproject/a2a-js/commit/3073376f7c311f0c13c51c129d7065249735517a))
|
||||
* Add support for extension headers on client side ([#227](https://github.com/a2aproject/a2a-js/issues/227)) ([8c57002](https://github.com/a2aproject/a2a-js/commit/8c57002add3b25387da899df7a610098b0f4e01b))
|
||||
* implement client interceptors ([#223](https://github.com/a2aproject/a2a-js/issues/223)) ([5694c22](https://github.com/a2aproject/a2a-js/commit/5694c22e3bccba87137c5b4ad1b3011f9e30dcd0))
|
||||
* Implement extended card support on server side ([#197](https://github.com/a2aproject/a2a-js/issues/197)) ([45014ac](https://github.com/a2aproject/a2a-js/commit/45014ac4a192ad3c6120849577530d1d63eb27b8))
|
||||
* implement server http+json ([#142](https://github.com/a2aproject/a2a-js/issues/142)) ([f20e662](https://github.com/a2aproject/a2a-js/commit/f20e66247d3c962144d77e98e7720d6041537533))
|
||||
* introduce AgentCardResolver ([#225](https://github.com/a2aproject/a2a-js/issues/225)) ([ddaf7de](https://github.com/a2aproject/a2a-js/commit/ddaf7ded169ccc285051eeb63088dc697e6ae93e))
|
||||
* introduce transport agnostic client ([#198](https://github.com/a2aproject/a2a-js/issues/198)) ([94a9848](https://github.com/a2aproject/a2a-js/commit/94a98483998a62669140de9bfbdde483787fa065))
|
||||
* server side support for extensions ([5ef7396](https://github.com/a2aproject/a2a-js/commit/5ef73960758b78ed2a52356a10cb35cadeb440bd))
|
||||
* support authentication on server side ([#195](https://github.com/a2aproject/a2a-js/issues/195)) ([9872d93](https://github.com/a2aproject/a2a-js/commit/9872d93622e12efb7369d7e658cec7ab4fd8590c))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* handle errors occurred in non-blocking sendMessage ([#187](https://github.com/a2aproject/a2a-js/issues/187)) ([e55c0f4](https://github.com/a2aproject/a2a-js/commit/e55c0f4791b556cc42e256073cf9018d1ec18cca))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* set version to 0.3.6 ([#191](https://github.com/a2aproject/a2a-js/issues/191)) ([3f8cea0](https://github.com/a2aproject/a2a-js/commit/3f8cea066efa59ae38ac405801884b9b5037841b))
|
||||
|
||||
## [0.3.5](https://github.com/a2aproject/a2a-js/compare/v0.3.4...v0.3.5) (2025-11-05)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* cancel/task now returns the expected 'cancelled' task status ([#158](https://github.com/a2aproject/a2a-js/issues/158)) ([3eec0bd](https://github.com/a2aproject/a2a-js/commit/3eec0bd98ab02f8d76c4b01dc8ea8351bc8f1a07))
|
||||
* correct the default value in the agentCardPath comment ([#130](https://github.com/a2aproject/a2a-js/issues/130)) ([3279c7b](https://github.com/a2aproject/a2a-js/commit/3279c7bf4de088950c81aaeccb1cfaca5ee26284))
|
||||
* enable follow up task issue on non blocking request ([#160](https://github.com/a2aproject/a2a-js/issues/160)) ([352dc05](https://github.com/a2aproject/a2a-js/commit/352dc0585122db341da93b5fbd2f8cf7acf7fcca))
|
||||
* ensure push notifications order ([#141](https://github.com/a2aproject/a2a-js/issues/141)) ([22360e6](https://github.com/a2aproject/a2a-js/commit/22360e6ba735b10c611b5881ea8f98c898622117))
|
||||
* ensure user messages are added to existing tasks ([#138](https://github.com/a2aproject/a2a-js/issues/138)) ([00fb916](https://github.com/a2aproject/a2a-js/commit/00fb916ca4b877b11b3153d67593027e508c3d64))
|
||||
* validate JSON-RPC params ([#155](https://github.com/a2aproject/a2a-js/issues/155)) ([5b39f4d](https://github.com/a2aproject/a2a-js/commit/5b39f4dd96b619e1683c0f2226279d20572f2a27))
|
||||
* validate JSON-RPC request id according to the spec ([#152](https://github.com/a2aproject/a2a-js/issues/152)) ([9558c36](https://github.com/a2aproject/a2a-js/commit/9558c3613a0e5c8c48743412b0c47f9480345666))
|
||||
|
||||
## [0.3.4](https://github.com/a2aproject/a2a-js/compare/v0.3.3...v0.3.4) (2025-09-04)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add list and delete task push notification config rpc method and custom rpc methods for extensions ([#119](https://github.com/a2aproject/a2a-js/issues/119)) ([26c4e7d](https://github.com/a2aproject/a2a-js/commit/26c4e7df48e0cd1088a9340ddc34bfbed320664c))
|
||||
* Added push notifications support ([#108](https://github.com/a2aproject/a2a-js/issues/108)) ([45a211a](https://github.com/a2aproject/a2a-js/commit/45a211a738ea7770ec5ee8b10a1238060ba7a471))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* release 0.3.4 ([#128](https://github.com/a2aproject/a2a-js/issues/128)) ([41791d9](https://github.com/a2aproject/a2a-js/commit/41791d99a4c7776ac3ee183d3e834df31a2020ac))
|
||||
|
||||
## [0.3.3](https://github.com/a2aproject/a2a-js/compare/v0.3.2...v0.3.3) (2025-08-27)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* Update A2AClient constructor to initialize with full agentCardUrl ([#121](https://github.com/a2aproject/a2a-js/issues/121))
|
||||
|
||||
### Features
|
||||
|
||||
* Update A2AClient constructor to initialize with full agentCardUrl ([#121](https://github.com/a2aproject/a2a-js/issues/121)) ([755044c](https://github.com/a2aproject/a2a-js/commit/755044c6c610991b5c86747da72b24e1fff9ade3))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Improve fetch implementation handling ([#117](https://github.com/a2aproject/a2a-js/issues/117)) ([09adbd3](https://github.com/a2aproject/a2a-js/commit/09adbd31d1ef7a73e4c8c87045af84bb1280226f))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* release 0.3.3 ([#124](https://github.com/a2aproject/a2a-js/issues/124)) ([ea59193](https://github.com/a2aproject/a2a-js/commit/ea591932901742af76afb5aeee4cf8d27cc9a6c2))
|
||||
|
||||
## [0.3.2](https://github.com/a2aproject/a2a-js/compare/v0.3.1...v0.3.2) (2025-08-17)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Added generic client hooks for HTTP based authentication, and improved agent.json resolution ([#33](https://github.com/a2aproject/a2a-js/issues/33)) ([a9826ac](https://github.com/a2aproject/a2a-js/commit/a9826acde3bb1f741153407e6179fd21f2e7a4bb))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* fix Incorrect Well-Known Path for Agent Card ([#102](https://github.com/a2aproject/a2a-js/issues/102)) ([3a0f1d0](https://github.com/a2aproject/a2a-js/commit/3a0f1d07843b725c9beaf1078bc43418ff2871ed))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* release 0.3.2 ([#111](https://github.com/a2aproject/a2a-js/issues/111)) ([03f35e0](https://github.com/a2aproject/a2a-js/commit/03f35e0ed29d2b24df7eddb2a7fe21d0690f503e))
|
||||
|
||||
## [0.3.1](https://github.com/a2aproject/a2a-js/compare/v0.3.0...v0.3.1) (2025-08-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add missing express entrypoint to tsup config ([#96](https://github.com/a2aproject/a2a-js/issues/96)) ([8e990e4](https://github.com/a2aproject/a2a-js/commit/8e990e497927e3554699f8ebb005829b170d9bc3))
|
||||
|
||||
## [0.3.0](https://github.com/a2aproject/a2a-js/compare/v0.2.5...v0.3.0) (2025-08-05)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* upgrade to a2a 0.3.0 spec version ([#87](https://github.com/a2aproject/a2a-js/issues/87))
|
||||
* make Express dependency optional
|
||||
|
||||
### Features
|
||||
|
||||
* make Express dependency optional ([60899c5](https://github.com/a2aproject/a2a-js/commit/60899c51e2910570402d1207f6b50952bed8862f))
|
||||
* upgrade to a2a 0.3.0 spec version ([#87](https://github.com/a2aproject/a2a-js/issues/87)) ([ae53da1](https://github.com/a2aproject/a2a-js/commit/ae53da1e36ff58912e01fefa854c5b3174edf7d8))
|
||||
|
||||
## [0.2.5](https://github.com/a2aproject/a2a-js/compare/v0.2.4...v0.2.5) (2025-07-30)
|
||||
|
||||
|
||||
|
||||
@ -2,6 +2,27 @@
|
||||
|
||||
We'd love to accept your patches and contributions to this project.
|
||||
|
||||
## Before you begin
|
||||
|
||||
### Sign our Contributor License Agreement
|
||||
|
||||
Contributions to this project must be accompanied by a
|
||||
[Contributor License Agreement](https://cla.developers.google.com/about) (CLA).
|
||||
You (or your employer) retain the copyright to your contribution; this simply
|
||||
gives us permission to use and redistribute your contributions as part of the
|
||||
project.
|
||||
|
||||
If you or your current employer have already signed the Google CLA (even if it
|
||||
was for a different project), you probably don't need to do it again.
|
||||
|
||||
Visit <https://cla.developers.google.com/> to see your current agreements or to
|
||||
sign a new one.
|
||||
|
||||
### Review our community guidelines
|
||||
|
||||
This project follows
|
||||
[Google's Open Source Community Guidelines](https://opensource.google/conduct/).
|
||||
|
||||
## Contribution process
|
||||
|
||||
### Code reviews
|
||||
@ -26,3 +47,11 @@ Here are some additional things to keep in mind during the process:
|
||||
|
||||
- **Test your changes.** Before you submit a pull request, make sure that your changes work as expected.
|
||||
- **Be patient.** It may take some time for your pull request to be reviewed and merged.
|
||||
|
||||
---
|
||||
|
||||
## For Google Employees
|
||||
|
||||
Complete the following steps to register your GitHub account and be added as a contributor to this repository.
|
||||
|
||||
1. Register your GitHub account at [go/GitHub](http://go/github)
|
||||
|
||||
@ -1,43 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
import eslint from '@eslint/js';
|
||||
import { defineConfig } from 'eslint/config';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import eslintPluginPrettier from 'eslint-plugin-prettier/recommended';
|
||||
import globals from 'globals';
|
||||
|
||||
export default defineConfig(
|
||||
eslint.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
eslintPluginPrettier, // Automatically disables eslint formatting rules and enables `prettier`
|
||||
{
|
||||
ignores: ['dist/', 'node_modules/', 'src/types.ts', 'build/'],
|
||||
},
|
||||
{
|
||||
rules: {
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{
|
||||
// Ignore error for unused args and caught errors if with '_' prefix
|
||||
argsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['test/**/*.ts', 'src/samples/**/*.ts'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off', // Allow the usage of `any` in the test files and in samples
|
||||
'@typescript-eslint/no-unused-expressions': 'off', // Allow unused expressions in test files, for compatibility with 'chai'
|
||||
},
|
||||
},
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
// Define global variables for Node.js environment
|
||||
...globals.node,
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
10844
package-lock.json
generated
10844
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
97
package.json
97
package.json
@ -1,37 +1,14 @@
|
||||
{
|
||||
"name": "@a2a-js/sdk",
|
||||
"version": "0.3.13",
|
||||
"version": "0.2.5",
|
||||
"description": "Server & Client SDK for Agent2Agent protocol",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/a2aproject/a2a-js.git"
|
||||
},
|
||||
"repository": "google-a2a/a2a-js.git",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"type": "module",
|
||||
"typesVersions": {
|
||||
"*": {
|
||||
"server": [
|
||||
"./dist/server/index.d.ts"
|
||||
],
|
||||
"server/express": [
|
||||
"./dist/server/express/index.d.ts"
|
||||
],
|
||||
"server/grpc": [
|
||||
"./dist/server/grpc/index.d.ts"
|
||||
],
|
||||
"client": [
|
||||
"./dist/client/index.d.ts"
|
||||
],
|
||||
"client/grpc": [
|
||||
"./dist/client/transports/grpc/index.d.ts"
|
||||
]
|
||||
}
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
@ -48,20 +25,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 +37,47 @@
|
||||
"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",
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@grpc/grpc-js": "^1.11.0",
|
||||
"@types/express": "^5.0.3",
|
||||
"@genkit-ai/googleai": "^1.8.0",
|
||||
"@genkit-ai/vertexai": "^1.8.0",
|
||||
"@types/chai": "^5.2.2",
|
||||
"@types/express": "^4.17.23",
|
||||
"@types/mocha": "^10.0.10",
|
||||
"@types/node": "^22.13.14",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"esbuild": "^0.27.0",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-prettier": "^5.5.4",
|
||||
"express": "^5.1.0",
|
||||
"@types/sinon": "^17.0.4",
|
||||
"c8": "^10.1.3",
|
||||
"chai": "^5.2.0",
|
||||
"express": "^4.21.2",
|
||||
"genkit": "^1.8.0",
|
||||
"gts": "^6.0.2",
|
||||
"json-schema-to-typescript": "^15.0.4",
|
||||
"prettier": "^3.6.2",
|
||||
"supertest": "^7.1.4",
|
||||
"mocha": "^11.6.0",
|
||||
"sinon": "^20.0.0",
|
||||
"tsup": "^8.5.0",
|
||||
"tsx": "^4.19.3",
|
||||
"typescript": "^5.9.3",
|
||||
"typescript-eslint": "^8.46.4",
|
||||
"vitest": "^3.2.4"
|
||||
"typescript": "^5.8.2"
|
||||
},
|
||||
"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",
|
||||
"format:readme": "prettier --write ./README.md",
|
||||
"coverage": "vitest run --coverage",
|
||||
"pretest": "npm run build",
|
||||
"test": "mocha test/**/*.spec.ts",
|
||||
"coverage": "c8 npm run test",
|
||||
"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"
|
||||
"sample:cli": "tsx src/samples/cli.ts",
|
||||
"sample:movie-agent": "tsx src/samples/agents/movie-agent/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"uuid": "^11.1.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@bufbuild/protobuf": "^2.10.2",
|
||||
"@grpc/grpc-js": "^1.11.0",
|
||||
"express": "^4.21.2 || ^5.1.0"
|
||||
"express": "^4.21.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"express": {
|
||||
"optional": true
|
||||
},
|
||||
"@grpc/grpc-js": {
|
||||
"optional": true
|
||||
},
|
||||
"@bufbuild/protobuf": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"mocha": {
|
||||
"require": "tsx"
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { compile } from 'json-schema-to-typescript';
|
||||
import { compile, compileFromFile } from 'json-schema-to-typescript'
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
@ -6,8 +6,9 @@ const typeSchemaContents = fs.readFileSync(path.join(process.cwd(), 'spec.json')
|
||||
const typeSchema = JSON.parse(typeSchemaContents.toString());
|
||||
|
||||
compile(typeSchema, 'MySchema', {
|
||||
additionalProperties: false,
|
||||
enableConstEnums: false,
|
||||
unreachableDefinitions: true,
|
||||
unknownAny: true,
|
||||
}).then((ts) => fs.writeFileSync('src/types.ts', ts));
|
||||
additionalProperties: false,
|
||||
enableConstEnums: false,
|
||||
unreachableDefinitions: true,
|
||||
unknownAny: true,
|
||||
})
|
||||
.then(ts => fs.writeFileSync('src/types.ts', ts))
|
||||
|
||||
@ -1,15 +1,4 @@
|
||||
import {
|
||||
SendMessageResponse,
|
||||
SendStreamingMessageResponse,
|
||||
GetTaskResponse,
|
||||
CancelTaskResponse,
|
||||
SetTaskPushNotificationConfigResponse,
|
||||
GetTaskPushNotificationConfigResponse,
|
||||
JSONRPCErrorResponse,
|
||||
ListTaskPushNotificationConfigSuccessResponse,
|
||||
DeleteTaskPushNotificationConfigSuccessResponse,
|
||||
GetAuthenticatedExtendedCardSuccessResponse,
|
||||
} from './types.js';
|
||||
import { SendMessageResponse, SendStreamingMessageResponse, GetTaskResponse, CancelTaskResponse, SetTaskPushNotificationConfigResponse, GetTaskPushNotificationConfigResponse, JSONRPCErrorResponse, ListTaskPushNotificationConfigSuccessResponse, DeleteTaskPushNotificationConfigSuccessResponse, GetAuthenticatedExtendedCardSuccessResponse } from "./types.js";
|
||||
|
||||
/**
|
||||
* Represents any valid JSON-RPC response defined in the A2A protocol.
|
||||
@ -25,3 +14,4 @@ export type A2AResponse =
|
||||
| DeleteTaskPushNotificationConfigSuccessResponse
|
||||
| GetAuthenticatedExtendedCardSuccessResponse
|
||||
| JSONRPCErrorResponse; // Catch-all for other error responses
|
||||
|
||||
@ -1,116 +0,0 @@
|
||||
export interface HttpHeaders {
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic interface for handling authentication for HTTP requests.
|
||||
*
|
||||
* - For each HTTP request, this handler is called to provide additional headers to the request through
|
||||
* the headers() function.
|
||||
* - After the server returns a response, the shouldRetryWithHeaders() function is called. Usually this
|
||||
* function responds to a 401 or 403 response or JSON-RPC codes, but can respond to any other signal -
|
||||
* that is an implementation detail of the AuthenticationHandler.
|
||||
* - If the shouldRetryWithHeaders() function returns new headers, then the request should retried with the provided
|
||||
* revised headers. These provisional headers may, or may not, be optimistically stored for subsequent requests -
|
||||
* that is an implementation detail of the AuthenticationHandler.
|
||||
* - If the request is successful and the onSuccessfulRetry() is defined, then the onSuccessfulRetry() function is
|
||||
* called with the headers that were used to successfully complete the request. This callback provides an
|
||||
* opportunity to save the headers for subsequent requests if they were not already saved.
|
||||
*
|
||||
*/
|
||||
export interface AuthenticationHandler {
|
||||
/**
|
||||
* Provides additional HTTP request headers.
|
||||
* @returns HTTP headers which may include Authorization if available.
|
||||
*/
|
||||
headers: () => Promise<HttpHeaders>;
|
||||
|
||||
/**
|
||||
* For every HTTP response (even 200s) the shouldRetryWithHeaders() method is called.
|
||||
* This method is supposed to check if the request needs to be retried and if, yes,
|
||||
* return a set of headers. An A2A server might indicate auth failures in its response
|
||||
* by JSON-rpc codes, HTTP codes like 401, 403 or headers like WWW-Authenticate.
|
||||
*
|
||||
* @param req The RequestInit object used to invoke fetch()
|
||||
* @param res The fetch Response object
|
||||
* @returns If the HTTP request should be retried then returns the HTTP headers to use,
|
||||
* or returns undefined if no retry should be made.
|
||||
*/
|
||||
shouldRetryWithHeaders: (req: RequestInit, res: Response) => Promise<HttpHeaders | undefined>;
|
||||
|
||||
/**
|
||||
* If the last HTTP request using the headers from shouldRetryWithHeaders() was successful, and
|
||||
* this function is implemented, then it will be called with the headers provided from
|
||||
* shouldRetryWithHeaders().
|
||||
*
|
||||
* This callback allows transient headers to be saved for subsequent requests only when they
|
||||
* are validated by the server.
|
||||
*/
|
||||
onSuccessfulRetry?: (headers: HttpHeaders) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Higher-order function that wraps fetch with authentication handling logic.
|
||||
* Returns a new fetch function that automatically handles authentication retries for 401/403 responses.
|
||||
*
|
||||
* @param fetchImpl The underlying fetch implementation to wrap
|
||||
* @param authHandler Authentication handler for managing auth headers and retries
|
||||
* @returns A new fetch function with authentication handling capabilities
|
||||
*
|
||||
* Usage examples:
|
||||
* - const authFetch = createAuthHandlingFetch(fetch, authHandler);
|
||||
* - const response = await authFetch(url, options);
|
||||
* - const response = await authFetch(url); // Direct function call
|
||||
*/
|
||||
export function createAuthenticatingFetchWithRetry(
|
||||
fetchImpl: typeof fetch,
|
||||
authHandler: AuthenticationHandler
|
||||
): typeof fetch {
|
||||
/**
|
||||
* Executes a fetch request with authentication handling.
|
||||
* If the auth handler provides new headers for the shouldRetryWithHeaders() function,
|
||||
* then the request is retried.
|
||||
* @param url The URL to fetch
|
||||
* @param init The fetch request options
|
||||
* @returns A Promise that resolves to the Response
|
||||
*/
|
||||
async function authFetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
// Merge auth headers with provided headers
|
||||
const authHeaders = (await authHandler.headers()) || {};
|
||||
const mergedInit: RequestInit = {
|
||||
...(init || {}),
|
||||
headers: {
|
||||
...authHeaders,
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
};
|
||||
|
||||
let response = await fetchImpl(url, mergedInit);
|
||||
|
||||
// Check if the auth handler wants to retry the request with new headers
|
||||
const updatedHeaders = await authHandler.shouldRetryWithHeaders(mergedInit, response);
|
||||
if (updatedHeaders) {
|
||||
// Retry request with revised headers
|
||||
const retryInit: RequestInit = {
|
||||
...(init || {}),
|
||||
headers: {
|
||||
...updatedHeaders,
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
};
|
||||
response = await fetchImpl(url, retryInit);
|
||||
|
||||
if (response.ok && authHandler.onSuccessfulRetry) {
|
||||
await authHandler.onSuccessfulRetry(updatedHeaders); // Remember headers that worked
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// Copy fetch properties to maintain compatibility
|
||||
Object.setPrototypeOf(authFetch, Object.getPrototypeOf(fetchImpl));
|
||||
Object.defineProperties(authFetch, Object.getOwnPropertyDescriptors(fetchImpl));
|
||||
|
||||
return authFetch;
|
||||
}
|
||||
@ -1,108 +0,0 @@
|
||||
import { AGENT_CARD_PATH } from '../constants.js';
|
||||
import { AgentCard } from '../types.js';
|
||||
import { AgentCard as PBAgentCard } from '../types/pb/a2a_types.js';
|
||||
import { FromProto } from '../types/converters/from_proto.js';
|
||||
|
||||
export interface AgentCardResolverOptions {
|
||||
path?: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
export interface AgentCardResolver {
|
||||
/**
|
||||
* Fetches the agent card based on provided base URL and path,
|
||||
*/
|
||||
resolve(baseUrl: string, path?: string): Promise<AgentCard>;
|
||||
}
|
||||
|
||||
export class DefaultAgentCardResolver implements AgentCardResolver {
|
||||
constructor(public readonly options?: AgentCardResolverOptions) {}
|
||||
|
||||
/**
|
||||
* Fetches the agent card based on provided base URL and path.
|
||||
* Path is selected in the following order:
|
||||
* 1) path parameter
|
||||
* 2) path from options
|
||||
* 3) .well-known/agent-card.json
|
||||
*/
|
||||
async resolve(baseUrl: string, path?: string): Promise<AgentCard> {
|
||||
const agentCardUrl = new URL(path ?? this.options?.path ?? AGENT_CARD_PATH, baseUrl);
|
||||
const response = await this.fetchImpl(agentCardUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status}`);
|
||||
}
|
||||
const rawCard = await response.json();
|
||||
return this.normalizeAgentCard(rawCard);
|
||||
}
|
||||
|
||||
private fetchImpl(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
|
||||
if (this.options?.fetchImpl) {
|
||||
return this.options.fetchImpl(...args);
|
||||
}
|
||||
return fetch(...args);
|
||||
}
|
||||
|
||||
/*
|
||||
* In the v0.3.0 specification, there was a structural drift between the JSON Schema data model
|
||||
* and the Protobuf-based data model for AgentCards.
|
||||
* The JSON Schema format uses a `"type"` discriminator (e.g., `{"type": "openIdConnect"}`),
|
||||
* while the Protobuf JSON representation uses the `oneof` field name as the discriminator
|
||||
* (e.g., `{"openIdConnectSecurityScheme": {...}}`).
|
||||
*
|
||||
* The A2A SDK internal logic expects the JSON Schema-based format. This fallback detection
|
||||
* allows us to parse cards served by endpoints returning the Protobuf JSON structure by
|
||||
* identifying the lack of the "type" field in security schemes or the presence of the
|
||||
* "schemes" wrapper in security entries, and normalizing it before use.
|
||||
*/
|
||||
private normalizeAgentCard(card: unknown): AgentCard {
|
||||
if (this.isProtoAgentCard(card)) {
|
||||
const parsedProto = PBAgentCard.fromJSON(card);
|
||||
return FromProto.agentCard(parsedProto);
|
||||
}
|
||||
return card as AgentCard;
|
||||
}
|
||||
|
||||
private isProtoAgentCard(card: unknown): boolean {
|
||||
if (!card || typeof card !== 'object') return false;
|
||||
const c = card as Record<string, unknown>;
|
||||
|
||||
if (this.hasProtoSecurity(c.security)) return true;
|
||||
|
||||
if (this.hasProtoSecuritySchemes(c.securitySchemes)) return true;
|
||||
|
||||
if (Array.isArray(c.skills)) {
|
||||
return c.skills.some(
|
||||
(skill) =>
|
||||
skill &&
|
||||
typeof skill === 'object' &&
|
||||
this.hasProtoSecurity((skill as Record<string, unknown>).security)
|
||||
);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private hasProtoSecurity(securityArray: unknown): boolean {
|
||||
if (Array.isArray(securityArray) && securityArray.length > 0) {
|
||||
const first = securityArray[0];
|
||||
return first && typeof first === 'object' && 'schemes' in first;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private hasProtoSecuritySchemes(securitySchemes: unknown): boolean {
|
||||
if (securitySchemes && typeof securitySchemes === 'object') {
|
||||
const schemes = Object.values(securitySchemes);
|
||||
if (schemes.length > 0) {
|
||||
const first = schemes[0];
|
||||
// Proto JSON maps use the oneof field name directly rather than a "type" property
|
||||
return first && typeof first === 'object' && !('type' in first);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const AgentCardResolver = {
|
||||
default: new DefaultAgentCardResolver(),
|
||||
};
|
||||
@ -1,376 +1,88 @@
|
||||
import {
|
||||
AgentCard,
|
||||
AgentCapabilities,
|
||||
JSONRPCRequest,
|
||||
JSONRPCResponse,
|
||||
MessageSendParams,
|
||||
SendMessageResponse,
|
||||
TaskQueryParams,
|
||||
GetTaskResponse,
|
||||
TaskIdParams,
|
||||
CancelTaskResponse,
|
||||
TaskPushNotificationConfig, // Renamed from PushNotificationConfigParams for direct schema alignment
|
||||
SetTaskPushNotificationConfigResponse,
|
||||
GetTaskPushNotificationConfigResponse,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigResponse,
|
||||
DeleteTaskPushNotificationConfigResponse,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
JSONRPCSuccessResponse,
|
||||
JSONRPCError,
|
||||
JSONRPCErrorResponse,
|
||||
Message,
|
||||
Task,
|
||||
TaskArtifactUpdateEvent,
|
||||
TaskStatusUpdateEvent,
|
||||
A2ARequest,
|
||||
JSONRPCErrorResponse,
|
||||
TaskArtifactUpdateEvent,
|
||||
MessageSendParams,
|
||||
SendMessageResponse,
|
||||
SendStreamingMessageResponse,
|
||||
SendStreamingMessageSuccessResponse,
|
||||
TaskQueryParams,
|
||||
GetTaskResponse,
|
||||
GetTaskSuccessResponse,
|
||||
TaskIdParams,
|
||||
CancelTaskResponse,
|
||||
CancelTaskSuccessResponse,
|
||||
TaskPushNotificationConfig, // Renamed from PushNotificationConfigParams for direct schema alignment
|
||||
SetTaskPushNotificationConfigRequest,
|
||||
SetTaskPushNotificationConfigResponse,
|
||||
SetTaskPushNotificationConfigSuccessResponse,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
GetTaskPushNotificationConfigResponse,
|
||||
GetTaskPushNotificationConfigSuccessResponse,
|
||||
TaskResubscriptionRequest,
|
||||
A2AError,
|
||||
SendMessageSuccessResponse
|
||||
} from '../types.js'; // Assuming schema.ts is in the same directory or appropriately pathed
|
||||
import { AGENT_CARD_PATH } from '../constants.js';
|
||||
import { JsonRpcTransport } from './transports/json_rpc_transport.js';
|
||||
import { RequestOptions } from './multitransport-client.js';
|
||||
|
||||
export type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
|
||||
// Helper type for the data yielded by streaming methods
|
||||
type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
|
||||
|
||||
export type SendMessageResult = Message | Task;
|
||||
|
||||
export interface A2AClientOptions {
|
||||
agentCardPath?: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
/**
|
||||
* A2AClient is a TypeScript HTTP client for interacting with A2A-compliant agents.
|
||||
* Only JSON-RPC transport is supported.
|
||||
* @deprecated Use {@link ClientFactory}
|
||||
*/
|
||||
export class A2AClient {
|
||||
private static emptyOptions?: RequestOptions = undefined;
|
||||
|
||||
private readonly agentCardPromise: Promise<AgentCard>;
|
||||
private readonly customFetchImpl?: typeof fetch;
|
||||
private serviceEndpointUrl?: string; // To be populated from AgentCard after fetchin
|
||||
|
||||
// A2AClient is built around JSON-RPC types, so it will only support JSON-RPC transport, new client with transport agnostic interface is going to be created for multi-transport.
|
||||
// New transport abstraction isn't going to expose individual transport specific fields, so to keep returning JSON-RPC IDs here for compatibility,
|
||||
// keep counter here and pass it to JsonRpcTransport via an optional idOverride parameter (which is not visible via transport-agnostic A2ATransport interface).
|
||||
private transport?: JsonRpcTransport;
|
||||
private agentBaseUrl: string;
|
||||
private agentCardPath: string;
|
||||
private agentCardPromise: Promise<AgentCard>;
|
||||
private static readonly DEFAULT_AGENT_CARD_PATH = ".well-known/agent.json";
|
||||
private requestIdCounter: number = 1;
|
||||
private serviceEndpointUrl?: string; // To be populated from AgentCard after fetching
|
||||
|
||||
/**
|
||||
* Constructs an A2AClient instance from an AgentCard.
|
||||
* @param agentCard The AgentCard object.
|
||||
* @param options Optional. The options for the A2AClient including the fetch/auth implementation.
|
||||
* Constructs an A2AClient instance.
|
||||
* It initiates fetching the agent card from the provided agent baseUrl.
|
||||
* The Agent Card is fetched from a path relative to the agentBaseUrl, which defaults to '.well-known/agent.json'.
|
||||
* The `url` field from the Agent Card will be used as the RPC service endpoint.
|
||||
* @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com)
|
||||
* @param agentCardPath path to the agent card, defaults to .well-known/agent.json
|
||||
*/
|
||||
constructor(agentCard: AgentCard | string, options?: A2AClientOptions) {
|
||||
this.customFetchImpl = options?.fetchImpl;
|
||||
if (typeof agentCard === 'string') {
|
||||
console.warn(
|
||||
'Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead.'
|
||||
);
|
||||
this.agentCardPromise = this._fetchAndCacheAgentCard(agentCard, options?.agentCardPath);
|
||||
} else {
|
||||
if (!agentCard.url) {
|
||||
throw new Error(
|
||||
"Provided Agent Card does not contain a valid 'url' for the service endpoint."
|
||||
);
|
||||
}
|
||||
this.serviceEndpointUrl = agentCard.url;
|
||||
this.agentCardPromise = Promise.resolve(agentCard);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamically resolves the fetch implementation to use for requests.
|
||||
* Prefers a custom implementation if provided, otherwise falls back to the global fetch.
|
||||
* @returns The fetch implementation.
|
||||
* @param args Arguments to pass to the fetch implementation.
|
||||
* @throws If no fetch implementation is available.
|
||||
*/
|
||||
private _fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
|
||||
if (this.customFetchImpl) {
|
||||
return this.customFetchImpl(...args);
|
||||
}
|
||||
if (typeof fetch === 'function') {
|
||||
return fetch(...args);
|
||||
}
|
||||
throw new Error(
|
||||
'A `fetch` implementation was not provided and is not available in the global scope. ' +
|
||||
'Please provide a `fetchImpl` in the A2AClientOptions. ' +
|
||||
'For earlier Node.js versions (pre-v18), you can use a library like `node-fetch`.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an A2AClient instance by fetching the AgentCard from a URL then constructing the A2AClient.
|
||||
* @param agentCardUrl The URL of the agent card.
|
||||
* @param options Optional. The options for the A2AClient including the fetch/auth implementation.
|
||||
* @returns A Promise that resolves to a new A2AClient instance.
|
||||
*/
|
||||
public static async fromCardUrl(
|
||||
agentCardUrl: string,
|
||||
options?: A2AClientOptions
|
||||
): Promise<A2AClient> {
|
||||
const fetchImpl = options?.fetchImpl;
|
||||
const requestInit = {
|
||||
headers: { Accept: 'application/json' },
|
||||
};
|
||||
|
||||
let response: Response;
|
||||
if (fetchImpl) {
|
||||
response = await fetchImpl(agentCardUrl, requestInit);
|
||||
} else if (typeof fetch === 'function') {
|
||||
// Use the global fetch implementation if no custom one is provided.
|
||||
response = await fetch(agentCardUrl, requestInit);
|
||||
} else {
|
||||
throw new Error(
|
||||
'A `fetch` implementation was not provided and is not available in the global scope. ' +
|
||||
'Please provide a `fetchImpl` in the A2AClientOptions. ' +
|
||||
'For earlier Node.js versions (pre-v18), you can use a library like `node-fetch`.'
|
||||
);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
|
||||
let agentCard: AgentCard;
|
||||
try {
|
||||
agentCard = await response.json();
|
||||
} catch (error) {
|
||||
console.error('Failed to parse Agent Card JSON:', error);
|
||||
throw new Error(
|
||||
`Failed to parse Agent Card JSON from ${agentCardUrl}. Original error: ${(error as Error).message}`
|
||||
);
|
||||
}
|
||||
|
||||
return new A2AClient(agentCard, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to the agent.
|
||||
* The behavior (blocking/non-blocking) and push notification configuration
|
||||
* are specified within the `params.configuration` object.
|
||||
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
|
||||
* @param params The parameters for sending the message, including the message content and configuration.
|
||||
* @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
|
||||
*/
|
||||
public async sendMessage(params: MessageSendParams): Promise<SendMessageResponse> {
|
||||
return await this.invokeJsonRpc<MessageSendParams, SendMessageResponse>(
|
||||
(t, p, id) => t.sendMessage(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
|
||||
* Push notification configuration can be specified in `params.configuration`.
|
||||
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
|
||||
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
|
||||
* @param params The parameters for sending the message.
|
||||
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
|
||||
* The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
|
||||
*/
|
||||
public async *sendMessageStream(
|
||||
params: MessageSendParams
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const agentCard = await this.agentCardPromise; // Ensure agent card is fetched
|
||||
if (!agentCard.capabilities?.streaming) {
|
||||
throw new Error(
|
||||
'Agent does not support streaming (AgentCard.capabilities.streaming is not true).'
|
||||
);
|
||||
}
|
||||
|
||||
const transport = await this._getOrCreateTransport();
|
||||
yield* transport.sendMessageStream(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets or updates the push notification configuration for a given task.
|
||||
* Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
|
||||
* @param params Parameters containing the taskId and the TaskPushNotificationConfig.
|
||||
* @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig
|
||||
): Promise<SetTaskPushNotificationConfigResponse> {
|
||||
const agentCard = await this.agentCardPromise;
|
||||
if (!agentCard.capabilities?.pushNotifications) {
|
||||
throw new Error(
|
||||
'Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true).'
|
||||
);
|
||||
}
|
||||
return await this.invokeJsonRpc<
|
||||
TaskPushNotificationConfig,
|
||||
SetTaskPushNotificationConfigResponse
|
||||
>((t, p, id) => t.setTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the push notification configuration for a given task.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async getTaskPushNotificationConfig(
|
||||
params: TaskIdParams
|
||||
): Promise<GetTaskPushNotificationConfigResponse> {
|
||||
return await this.invokeJsonRpc<TaskIdParams, GetTaskPushNotificationConfigResponse>(
|
||||
(t, p, id) => t.getTaskPushNotificationConfig(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the push notification configurations for a given task.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to ListTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams
|
||||
): Promise<ListTaskPushNotificationConfigResponse> {
|
||||
return await this.invokeJsonRpc<
|
||||
ListTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigResponse
|
||||
>((t, p, id) => t.listTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the push notification configuration for a given task.
|
||||
* @param params Parameters containing the taskId and push notification configuration ID.
|
||||
* @returns A Promise resolving to DeleteTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams
|
||||
): Promise<DeleteTaskPushNotificationConfigResponse> {
|
||||
return await this.invokeJsonRpc<
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigResponse
|
||||
>((t, p, id) => t.deleteTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a task by its ID.
|
||||
* @param params Parameters containing the taskId and optional historyLength.
|
||||
* @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
|
||||
*/
|
||||
public async getTask(params: TaskQueryParams): Promise<GetTaskResponse> {
|
||||
return await this.invokeJsonRpc<TaskQueryParams, GetTaskResponse>(
|
||||
(t, p, id) => t.getTask(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels a task by its ID.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
|
||||
*/
|
||||
public async cancelTask(params: TaskIdParams): Promise<CancelTaskResponse> {
|
||||
return await this.invokeJsonRpc<TaskIdParams, CancelTaskResponse>(
|
||||
(t, p, id) => t.cancelTask(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @template TExtensionParams The type of parameters for the custom extension method.
|
||||
* @template TExtensionResponse The type of response expected from the custom extension method.
|
||||
* This should extend JSONRPCResponse. This ensures the extension response is still a valid A2A response.
|
||||
* @param method Custom JSON-RPC method defined in the AgentCard's extensions.
|
||||
* @param params Extension paramters defined in the AgentCard's extensions.
|
||||
* @returns A Promise that resolves to the RPC response.
|
||||
*/
|
||||
public async callExtensionMethod<TExtensionParams, TExtensionResponse extends JSONRPCResponse>(
|
||||
method: string,
|
||||
params: TExtensionParams
|
||||
) {
|
||||
const transport = await this._getOrCreateTransport();
|
||||
try {
|
||||
return await transport.callExtensionMethod<TExtensionParams, TExtensionResponse>(
|
||||
method,
|
||||
params,
|
||||
this.requestIdCounter++
|
||||
);
|
||||
} catch (e) {
|
||||
// For compatibility, return JSON-RPC errors as errors instead of throwing transport-agnostic errors
|
||||
// produced by JsonRpcTransport.
|
||||
const errorResponse = extractJSONRPCError(e);
|
||||
if (errorResponse) {
|
||||
return errorResponse as TExtensionResponse;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resubscribes to a task's event stream using Server-Sent Events (SSE).
|
||||
* This is used if a previous SSE connection for an active task was broken.
|
||||
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
|
||||
*/
|
||||
public async *resubscribeTask(
|
||||
params: TaskIdParams
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const agentCard = await this.agentCardPromise;
|
||||
if (!agentCard.capabilities?.streaming) {
|
||||
throw new Error('Agent does not support streaming (required for tasks/resubscribe).');
|
||||
}
|
||||
|
||||
const transport = await this._getOrCreateTransport();
|
||||
yield* transport.resubscribeTask(params);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Functions used to support old A2AClient Constructor to be deprecated soon
|
||||
// TODOs:
|
||||
// * remove `agentCardPromise`, and just use agentCard initialized
|
||||
// * _getServiceEndpoint can be made synchronous or deleted and accessed via
|
||||
// agentCard.url
|
||||
// * getAgentCard changed to this.agentCard
|
||||
// * delete resolveAgentCardUrl(), _fetchAndCacheAgentCard(),
|
||||
// agentCardPath from A2AClientOptions
|
||||
// * delete _getOrCreateTransport
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private async _getOrCreateTransport(): Promise<JsonRpcTransport> {
|
||||
if (this.transport) {
|
||||
return this.transport;
|
||||
}
|
||||
|
||||
const endpoint = await this._getServiceEndpoint();
|
||||
this.transport = new JsonRpcTransport({ fetchImpl: this.customFetchImpl, endpoint: endpoint });
|
||||
return this.transport;
|
||||
constructor(agentBaseUrl: string, agentCardPath: string = A2AClient.DEFAULT_AGENT_CARD_PATH) {
|
||||
this.agentBaseUrl = agentBaseUrl.replace(/\/$/, ""); // Remove trailing slash if any
|
||||
this.agentCardPath = agentCardPath.replace(/^\//, ""); // Remove leading slash if any
|
||||
this.agentCardPromise = this._fetchAndCacheAgentCard();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
|
||||
* This method is called by the constructor.
|
||||
* @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com)
|
||||
* @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
|
||||
* @returns A Promise that resolves to the AgentCard.
|
||||
*/
|
||||
private async _fetchAndCacheAgentCard(
|
||||
agentBaseUrl: string,
|
||||
agentCardPath?: string
|
||||
): Promise<AgentCard> {
|
||||
private async _fetchAndCacheAgentCard(): Promise<AgentCard> {
|
||||
const agentCardUrl = `${this.agentBaseUrl}/${this.agentCardPath}`
|
||||
try {
|
||||
const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
|
||||
const response = await this._fetch(agentCardUrl, {
|
||||
headers: { Accept: 'application/json' },
|
||||
const response = await fetch(agentCardUrl, {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
const agentCard: AgentCard = await response.json();
|
||||
if (!agentCard.url) {
|
||||
throw new Error(
|
||||
"Fetched Agent Card does not contain a valid 'url' for the service endpoint."
|
||||
);
|
||||
throw new Error("Fetched Agent Card does not contain a valid 'url' for the service endpoint.");
|
||||
}
|
||||
this.serviceEndpointUrl = agentCard.url; // Cache the service endpoint URL from the agent card
|
||||
return agentCard;
|
||||
} catch (error) {
|
||||
console.error('Error fetching or parsing Agent Card:', error);
|
||||
console.error("Error fetching or parsing Agent Card:");
|
||||
// Allow the promise to reject so users of agentCardPromise can handle it.
|
||||
throw error;
|
||||
}
|
||||
@ -381,40 +93,25 @@ export class A2AClient {
|
||||
* If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
|
||||
* Otherwise, it returns the card fetched and cached during client construction.
|
||||
* @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
|
||||
* @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
|
||||
* @param agentCardPath path to the agent card, defaults to .well-known/agent.json
|
||||
* If provided, this will fetch a new card, not use the cached one from the constructor's URL.
|
||||
* @returns A Promise that resolves to the AgentCard.
|
||||
*/
|
||||
public async getAgentCard(agentBaseUrl?: string, agentCardPath?: string): Promise<AgentCard> {
|
||||
public async getAgentCard(agentBaseUrl?: string, agentCardPath: string = A2AClient.DEFAULT_AGENT_CARD_PATH): Promise<AgentCard> {
|
||||
if (agentBaseUrl) {
|
||||
const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
|
||||
|
||||
const response = await this._fetch(agentCardUrl, {
|
||||
headers: { Accept: 'application/json' },
|
||||
const agentCardUrl = `${agentBaseUrl.replace(/\/$/, "")}/${agentCardPath.replace(/^\//, "")}`
|
||||
const response = await fetch(agentCardUrl, {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
return (await response.json()) as AgentCard;
|
||||
return await response.json() as AgentCard;
|
||||
}
|
||||
// If no specific URL is given, return the promise for the initially configured agent's card.
|
||||
return this.agentCardPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the agent card URL based on the agent URL.
|
||||
* @param agentBaseUrl The agent URL.
|
||||
* @param agentCardPath Optional relative path to the agent card, defaults to .well-known/agent-card.json
|
||||
*/
|
||||
private resolveAgentCardUrl(
|
||||
agentBaseUrl: string,
|
||||
agentCardPath: string = AGENT_CARD_PATH
|
||||
): string {
|
||||
return `${agentBaseUrl.replace(/\/$/, '')}/${agentCardPath.replace(/^\//, '')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the RPC service endpoint URL. Ensures the agent card has been fetched first.
|
||||
* @returns A Promise that resolves to the service endpoint URL string.
|
||||
@ -428,60 +125,365 @@ export class A2AClient {
|
||||
await this.agentCardPromise;
|
||||
if (!this.serviceEndpointUrl) {
|
||||
// This case should ideally be covered by the error handling in _fetchAndCacheAgentCard
|
||||
throw new Error(
|
||||
'Agent Card URL for RPC endpoint is not available. Fetching might have failed.'
|
||||
);
|
||||
throw new Error("Agent Card URL for RPC endpoint is not available. Fetching might have failed.");
|
||||
}
|
||||
return this.serviceEndpointUrl;
|
||||
}
|
||||
|
||||
private async invokeJsonRpc<TParams extends JsonRpcParams, TResponse extends JSONRPCResponse>(
|
||||
caller: JsonRpcCaller<TParams, TResponse>,
|
||||
params?: TParams
|
||||
/**
|
||||
* Helper method to make a generic JSON-RPC POST request.
|
||||
* @param method The RPC method name.
|
||||
* @param params The parameters for the RPC method.
|
||||
* @returns A Promise that resolves to the RPC response.
|
||||
*/
|
||||
private async _postRpcRequest<TParams, TResponse extends JSONRPCResponse>(
|
||||
method: string,
|
||||
params: TParams
|
||||
): Promise<TResponse> {
|
||||
const transport = await this._getOrCreateTransport();
|
||||
const endpoint = await this._getServiceEndpoint();
|
||||
const requestId = this.requestIdCounter++;
|
||||
try {
|
||||
const result = await caller(transport, params, requestId);
|
||||
return {
|
||||
id: requestId,
|
||||
jsonrpc: '2.0',
|
||||
result: result ?? null, // JSON-RPC requires result property on success, it will be null for "void" methods.
|
||||
} as TResponse;
|
||||
} catch (e) {
|
||||
// For compatibility, return JSON-RPC errors as response objects instead of throwing transport-agnostic errors
|
||||
// produced by JsonRpcTransport.
|
||||
const errorResponse = extractJSONRPCError(e);
|
||||
if (errorResponse) {
|
||||
return errorResponse as TResponse;
|
||||
const rpcRequest: JSONRPCRequest = {
|
||||
jsonrpc: "2.0",
|
||||
method,
|
||||
params: params as { [key: string]: any; }, // Cast because TParams structure varies per method
|
||||
id: requestId,
|
||||
};
|
||||
|
||||
const httpResponse = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json", // Expect JSON response for non-streaming requests
|
||||
},
|
||||
body: JSON.stringify(rpcRequest),
|
||||
});
|
||||
|
||||
if (!httpResponse.ok) {
|
||||
let errorBodyText = '(empty or non-JSON response)';
|
||||
try {
|
||||
errorBodyText = await httpResponse.text();
|
||||
const errorJson = JSON.parse(errorBodyText);
|
||||
// If the body is a valid JSON-RPC error response, let it be handled by the standard parsing below.
|
||||
// However, if it's not even a JSON-RPC structure but still an error, throw based on HTTP status.
|
||||
if (!errorJson.jsonrpc && errorJson.error) { // Check if it's a JSON-RPC error structure
|
||||
throw new Error(`RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data || {})}`);
|
||||
} else if (!errorJson.jsonrpc) {
|
||||
throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
|
||||
}
|
||||
} catch (e: any) {
|
||||
// If parsing the error body fails or it's not a JSON-RPC error, throw a generic HTTP error.
|
||||
// If it was already an error thrown from within the try block, rethrow it.
|
||||
if (e.message.startsWith('RPC error for') || e.message.startsWith('HTTP error for')) throw e;
|
||||
throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
const rpcResponse = await httpResponse.json();
|
||||
|
||||
if (rpcResponse.id !== requestId) {
|
||||
// This is a significant issue for request-response matching.
|
||||
console.error(`CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`);
|
||||
// Depending on strictness, one might throw an error here.
|
||||
// throw new Error(`RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}`);
|
||||
}
|
||||
|
||||
return rpcResponse as TResponse;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sends a message to the agent.
|
||||
* The behavior (blocking/non-blocking) and push notification configuration
|
||||
* are specified within the `params.configuration` object.
|
||||
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
|
||||
* @param params The parameters for sending the message, including the message content and configuration.
|
||||
* @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
|
||||
*/
|
||||
public async sendMessage(params: MessageSendParams): Promise<SendMessageResponse> {
|
||||
return this._postRpcRequest<MessageSendParams, SendMessageResponse>("message/send", params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
|
||||
* Push notification configuration can be specified in `params.configuration`.
|
||||
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
|
||||
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
|
||||
* @param params The parameters for sending the message.
|
||||
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
|
||||
* The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
|
||||
*/
|
||||
public async *sendMessageStream(params: MessageSendParams): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const agentCard = await this.agentCardPromise; // Ensure agent card is fetched
|
||||
if (!agentCard.capabilities?.streaming) {
|
||||
throw new Error("Agent does not support streaming (AgentCard.capabilities.streaming is not true).");
|
||||
}
|
||||
|
||||
const endpoint = await this._getServiceEndpoint();
|
||||
const clientRequestId = this.requestIdCounter++; // Use a unique ID for this stream request
|
||||
const rpcRequest: JSONRPCRequest = { // This is the initial JSON-RPC request to establish the stream
|
||||
jsonrpc: "2.0",
|
||||
method: "message/stream",
|
||||
params: params as { [key: string]: any; },
|
||||
id: clientRequestId,
|
||||
};
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "text/event-stream", // Crucial for SSE
|
||||
},
|
||||
body: JSON.stringify(rpcRequest),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// Attempt to read error body for more details
|
||||
let errorBody = "";
|
||||
try {
|
||||
errorBody = await response.text();
|
||||
const errorJson = JSON.parse(errorBody);
|
||||
if (errorJson.error) {
|
||||
throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (e.message.startsWith('HTTP error establishing stream')) throw e;
|
||||
// Fallback if body is not JSON or parsing fails
|
||||
throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`);
|
||||
}
|
||||
throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
|
||||
// Server should explicitly set this content type for SSE.
|
||||
throw new Error("Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.");
|
||||
}
|
||||
|
||||
// Yield events from the parsed SSE stream.
|
||||
// Each event's 'data' field is a JSON-RPC response.
|
||||
yield* this._parseA2ASseStream<A2AStreamEventData>(response, clientRequestId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets or updates the push notification configuration for a given task.
|
||||
* Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
|
||||
* @param params Parameters containing the taskId and the TaskPushNotificationConfig.
|
||||
* @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async setTaskPushNotificationConfig(params: TaskPushNotificationConfig): Promise<SetTaskPushNotificationConfigResponse> {
|
||||
const agentCard = await this.agentCardPromise;
|
||||
if (!agentCard.capabilities?.pushNotifications) {
|
||||
throw new Error("Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true).");
|
||||
}
|
||||
// The 'params' directly matches the structure expected by the RPC method.
|
||||
return this._postRpcRequest<TaskPushNotificationConfig, SetTaskPushNotificationConfigResponse>(
|
||||
"tasks/pushNotificationConfig/set",
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the push notification configuration for a given task.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async getTaskPushNotificationConfig(params: TaskIdParams): Promise<GetTaskPushNotificationConfigResponse> {
|
||||
// The 'params' (TaskIdParams) directly matches the structure expected by the RPC method.
|
||||
return this._postRpcRequest<TaskIdParams, GetTaskPushNotificationConfigResponse>(
|
||||
"tasks/pushNotificationConfig/get",
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves a task by its ID.
|
||||
* @param params Parameters containing the taskId and optional historyLength.
|
||||
* @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
|
||||
*/
|
||||
public async getTask(params: TaskQueryParams): Promise<GetTaskResponse> {
|
||||
return this._postRpcRequest<TaskQueryParams, GetTaskResponse>("tasks/get", params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels a task by its ID.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
|
||||
*/
|
||||
public async cancelTask(params: TaskIdParams): Promise<CancelTaskResponse> {
|
||||
return this._postRpcRequest<TaskIdParams, CancelTaskResponse>("tasks/cancel", params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resubscribes to a task's event stream using Server-Sent Events (SSE).
|
||||
* This is used if a previous SSE connection for an active task was broken.
|
||||
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
|
||||
*/
|
||||
public async *resubscribeTask(params: TaskIdParams): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const agentCard = await this.agentCardPromise;
|
||||
if (!agentCard.capabilities?.streaming) {
|
||||
throw new Error("Agent does not support streaming (required for tasks/resubscribe).");
|
||||
}
|
||||
|
||||
const endpoint = await this._getServiceEndpoint();
|
||||
const clientRequestId = this.requestIdCounter++; // Unique ID for this resubscribe request
|
||||
const rpcRequest: JSONRPCRequest = { // Initial JSON-RPC request to establish the stream
|
||||
jsonrpc: "2.0",
|
||||
method: "tasks/resubscribe",
|
||||
params: params as { [key: string]: any; },
|
||||
id: clientRequestId,
|
||||
};
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "text/event-stream",
|
||||
},
|
||||
body: JSON.stringify(rpcRequest),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorBody = "";
|
||||
try {
|
||||
errorBody = await response.text();
|
||||
const errorJson = JSON.parse(errorBody);
|
||||
if (errorJson.error) {
|
||||
throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (e.message.startsWith('HTTP error establishing stream')) throw e;
|
||||
throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`);
|
||||
}
|
||||
throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
|
||||
throw new Error("Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.");
|
||||
}
|
||||
|
||||
// The events structure for resubscribe is assumed to be the same as message/stream.
|
||||
// Each event's 'data' field is a JSON-RPC response.
|
||||
yield* this._parseA2ASseStream<A2AStreamEventData>(response, clientRequestId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an HTTP response body as an A2A Server-Sent Event stream.
|
||||
* Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,
|
||||
* specifically a SendStreamingMessageResponse (or similar structure for resubscribe).
|
||||
* @param response The HTTP Response object whose body is the SSE stream.
|
||||
* @param originalRequestId The ID of the client's JSON-RPC request that initiated this stream.
|
||||
* Used to validate the `id` in the streamed JSON-RPC responses.
|
||||
* @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.
|
||||
*/
|
||||
private async *_parseA2ASseStream<TStreamItem>(
|
||||
response: Response,
|
||||
originalRequestId: number | string | null
|
||||
): AsyncGenerator<TStreamItem, void, undefined> {
|
||||
if (!response.body) {
|
||||
throw new Error("SSE response body is undefined. Cannot read stream.");
|
||||
}
|
||||
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
||||
let buffer = ""; // Holds incomplete lines from the stream
|
||||
let eventDataBuffer = ""; // Holds accumulated 'data:' lines for the current event
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
// Process any final buffered event data if the stream ends abruptly after a 'data:' line
|
||||
if (eventDataBuffer.trim()) {
|
||||
const result = this._processSseEventData<TStreamItem>(eventDataBuffer, originalRequestId);
|
||||
yield result;
|
||||
}
|
||||
break; // Stream finished
|
||||
}
|
||||
|
||||
buffer += value; // Append new chunk to buffer
|
||||
let lineEndIndex;
|
||||
// Process all complete lines in the buffer
|
||||
while ((lineEndIndex = buffer.indexOf('\n')) >= 0) {
|
||||
const line = buffer.substring(0, lineEndIndex).trim(); // Get and trim the line
|
||||
buffer = buffer.substring(lineEndIndex + 1); // Remove processed line from buffer
|
||||
|
||||
if (line === "") { // Empty line: signifies the end of an event
|
||||
if (eventDataBuffer) { // If we have accumulated data for an event
|
||||
const result = this._processSseEventData<TStreamItem>(eventDataBuffer, originalRequestId);
|
||||
yield result;
|
||||
eventDataBuffer = ""; // Reset buffer for the next event
|
||||
}
|
||||
} else if (line.startsWith("data:")) {
|
||||
eventDataBuffer += line.substring(5).trimStart() + "\n"; // Append data (multi-line data is possible)
|
||||
} else if (line.startsWith(":")) {
|
||||
// This is a comment line in SSE, ignore it.
|
||||
} else if (line.includes(":")) {
|
||||
// Other SSE fields like 'event:', 'id:', 'retry:'.
|
||||
// The A2A spec primarily focuses on the 'data' field for JSON-RPC payloads.
|
||||
// For now, we don't specifically handle these other SSE fields unless required by spec.
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
// Log and re-throw errors encountered during stream processing
|
||||
console.error("Error reading or parsing SSE stream:", error.message);
|
||||
throw error;
|
||||
} finally {
|
||||
reader.releaseLock(); // Ensure the reader lock is released
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function extractJSONRPCError(error: unknown): JSONRPCErrorResponse {
|
||||
if (
|
||||
error instanceof Object &&
|
||||
'errorResponse' in error &&
|
||||
error.errorResponse instanceof Object &&
|
||||
'jsonrpc' in error.errorResponse &&
|
||||
error.errorResponse.jsonrpc === '2.0' &&
|
||||
'error' in error.errorResponse &&
|
||||
error.errorResponse.error !== null
|
||||
) {
|
||||
return error.errorResponse as JSONRPCErrorResponse;
|
||||
} else {
|
||||
return undefined;
|
||||
/**
|
||||
* Processes a single SSE event's data string, expecting it to be a JSON-RPC response.
|
||||
* @param jsonData The string content from one or more 'data:' lines of an SSE event.
|
||||
* @param originalRequestId The ID of the client's request that initiated the stream.
|
||||
* @returns The `result` field of the parsed JSON-RPC success response.
|
||||
* @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.
|
||||
*/
|
||||
private _processSseEventData<TStreamItem>(
|
||||
jsonData: string,
|
||||
originalRequestId: number | string | null
|
||||
): TStreamItem {
|
||||
if (!jsonData.trim()) {
|
||||
throw new Error("Attempted to process empty SSE event data.");
|
||||
}
|
||||
try {
|
||||
// SSE data can be multi-line, ensure it's treated as a single JSON string.
|
||||
const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\n$/, '')); // Remove trailing newline if any
|
||||
|
||||
// Type assertion to SendStreamingMessageResponse, as this is the expected structure for A2A streams.
|
||||
const a2aStreamResponse: SendStreamingMessageResponse = sseJsonRpcResponse as SendStreamingMessageResponse;
|
||||
|
||||
if (a2aStreamResponse.id !== originalRequestId) {
|
||||
// According to JSON-RPC spec, notifications (which SSE events can be seen as) might not have an ID,
|
||||
// or if they do, it should match. A2A spec implies streamed events are tied to the initial request.
|
||||
console.warn(`SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`);
|
||||
// Depending on strictness, this could be an error. For now, it's a warning.
|
||||
}
|
||||
|
||||
if (this.isErrorResponse(a2aStreamResponse)) {
|
||||
const err = a2aStreamResponse.error as (JSONRPCError | A2AError);
|
||||
throw new Error(`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`);
|
||||
}
|
||||
|
||||
// Check if 'result' exists, as it's mandatory for successful JSON-RPC responses
|
||||
if (!('result' in a2aStreamResponse) || typeof (a2aStreamResponse as SendStreamingMessageSuccessResponse).result === 'undefined') {
|
||||
throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
|
||||
}
|
||||
|
||||
const successResponse = a2aStreamResponse as SendStreamingMessageSuccessResponse;
|
||||
return successResponse.result as TStreamItem;
|
||||
} catch (e: any) {
|
||||
// Catch errors from JSON.parse or if it's an error response that was thrown by this function
|
||||
if (e.message.startsWith("SSE event contained an error") || e.message.startsWith("SSE event JSON-RPC response is missing 'result' field")) {
|
||||
throw e; // Re-throw errors already processed/identified by this function
|
||||
}
|
||||
// For other parsing errors or unexpected structures:
|
||||
console.error("Failed to parse SSE event data string or unexpected JSON-RPC structure:", jsonData, e);
|
||||
throw new Error(`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
isErrorResponse(response: JSONRPCResponse): response is JSONRPCErrorResponse {
|
||||
return "error" in response;
|
||||
}
|
||||
}
|
||||
|
||||
// Utility unexported types to properly factor out common "compatibility" logic via invokeJsonRpc.
|
||||
type ParamsOf<T> = T extends { params: unknown } ? T['params'] : undefined;
|
||||
type ResultOf<T> = T extends { result: unknown } ? T['result'] : void;
|
||||
type JsonRpcParams = ParamsOf<A2ARequest>;
|
||||
type JsonRpcCaller<TParams extends JsonRpcParams, TResponse extends JSONRPCResponse> = (
|
||||
transport: JsonRpcTransport,
|
||||
params: TParams,
|
||||
idOverride: number
|
||||
) => Promise<ResultOf<TResponse>>;
|
||||
|
||||
@ -1,62 +0,0 @@
|
||||
/**
|
||||
* Opaque context object to carry per-call context data.
|
||||
* Use {@link ClientCallContextKey} to create typed keys for storing and retrieving values.
|
||||
*/
|
||||
export type ClientCallContext = Record<symbol, unknown>;
|
||||
|
||||
/**
|
||||
* Function that applies an update to a {@link ClientCallContext}.
|
||||
*/
|
||||
export type ContextUpdate = (context: ClientCallContext) => void;
|
||||
|
||||
export const ClientCallContext = {
|
||||
/**
|
||||
* Create a new {@link ClientCallContext} with optional updates applied.
|
||||
*/
|
||||
create: (...updates: ContextUpdate[]): ClientCallContext => {
|
||||
return ClientCallContext.createFrom(undefined, ...updates);
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new {@link ClientCallContext} based on an existing one with updates applied.
|
||||
*/
|
||||
createFrom: (
|
||||
context: ClientCallContext | undefined,
|
||||
...updates: ContextUpdate[]
|
||||
): ClientCallContext => {
|
||||
const result = context ? { ...context } : {};
|
||||
for (const update of updates) {
|
||||
update(result);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Each instance represents a unique key for storing
|
||||
* and retrieving typed values in a {@link ClientCallContext}.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const key = new ClientCallContextKey<string>('My key');
|
||||
* const context = ClientCallContext.create(key.set('example-value'));
|
||||
* const value = key.get(context); // 'example-value'
|
||||
* ```
|
||||
*/
|
||||
export class ClientCallContextKey<T> {
|
||||
public readonly symbol: symbol;
|
||||
|
||||
constructor(description: string) {
|
||||
this.symbol = Symbol(description);
|
||||
}
|
||||
|
||||
set(value: T): ContextUpdate {
|
||||
return (context) => {
|
||||
context[this.symbol] = value;
|
||||
};
|
||||
}
|
||||
|
||||
get(context: ClientCallContext): T | undefined {
|
||||
return context[this.symbol] as T | undefined;
|
||||
}
|
||||
}
|
||||
@ -1,213 +0,0 @@
|
||||
import { TransportProtocolName } from '../core.js';
|
||||
import { AgentCard } from '../types.js';
|
||||
import { AgentCardResolver } from './card-resolver.js';
|
||||
import { Client, ClientConfig } from './multitransport-client.js';
|
||||
import { JsonRpcTransportFactory } from './transports/json_rpc_transport.js';
|
||||
import { RestTransportFactory } from './transports/rest_transport.js';
|
||||
import { TransportFactory } from './transports/transport.js';
|
||||
|
||||
export interface ClientFactoryOptions {
|
||||
/**
|
||||
* Transport factories to use.
|
||||
* Effectively defines transports supported by this client factory.
|
||||
*/
|
||||
transports: TransportFactory[];
|
||||
|
||||
/**
|
||||
* Client config to be used for clients created by this factory.
|
||||
*/
|
||||
clientConfig?: ClientConfig;
|
||||
|
||||
/**
|
||||
* Transport preferences to override ones defined by the agent card.
|
||||
* If no matches are found among preferred transports, agent card values are used next.
|
||||
*/
|
||||
preferredTransports?: TransportProtocolName[];
|
||||
|
||||
/**
|
||||
* Used for createFromAgentCardUrl to download agent card.
|
||||
*/
|
||||
cardResolver?: AgentCardResolver;
|
||||
}
|
||||
|
||||
export const ClientFactoryOptions = {
|
||||
/**
|
||||
* SDK default options for {@link ClientFactory}.
|
||||
*/
|
||||
default: {
|
||||
transports: [new JsonRpcTransportFactory(), new RestTransportFactory()],
|
||||
} as Readonly<ClientFactoryOptions>,
|
||||
|
||||
/**
|
||||
* Creates new options by merging an original and an override object.
|
||||
* Transports are merged based on `TransportFactory.protocolName`,
|
||||
* interceptors are concatenated, other fields are overriden.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const options = ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
|
||||
* transports: [new MyCustomTransportFactory()], // adds a custom transport
|
||||
* clientConfig: { interceptors: [new MyInterceptor()] }, // adds a custom interceptor
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
createFrom(
|
||||
original: ClientFactoryOptions,
|
||||
overrides: Partial<ClientFactoryOptions>
|
||||
): ClientFactoryOptions {
|
||||
return {
|
||||
...original,
|
||||
...overrides,
|
||||
transports: mergeTransports(original.transports, overrides.transports),
|
||||
clientConfig: {
|
||||
...(original.clientConfig ?? {}),
|
||||
...(overrides.clientConfig ?? {}),
|
||||
interceptors: mergeArrays(
|
||||
original.clientConfig?.interceptors,
|
||||
overrides.clientConfig?.interceptors
|
||||
),
|
||||
acceptedOutputModes:
|
||||
overrides.clientConfig?.acceptedOutputModes ?? original.clientConfig?.acceptedOutputModes,
|
||||
},
|
||||
preferredTransports: overrides.preferredTransports ?? original.preferredTransports,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export class ClientFactory {
|
||||
private readonly transportsByName: CaseInsensitiveMap<TransportFactory>;
|
||||
private readonly agentCardResolver: AgentCardResolver;
|
||||
|
||||
constructor(public readonly options: ClientFactoryOptions = ClientFactoryOptions.default) {
|
||||
if (!options.transports || options.transports.length === 0) {
|
||||
throw new Error('No transports provided');
|
||||
}
|
||||
this.transportsByName = transportsByName(options.transports);
|
||||
for (const transport of options.preferredTransports ?? []) {
|
||||
if (!this.transportsByName.has(transport)) {
|
||||
throw new Error(
|
||||
`Unknown preferred transport: ${transport}, available transports: ${[...this.transportsByName.keys()].join()}`
|
||||
);
|
||||
}
|
||||
}
|
||||
this.agentCardResolver = options.cardResolver ?? AgentCardResolver.default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new client from the provided agent card.
|
||||
*/
|
||||
async createFromAgentCard(agentCard: AgentCard): Promise<Client> {
|
||||
const agentCardPreferred = agentCard.preferredTransport ?? JsonRpcTransportFactory.name;
|
||||
const additionalInterfaces = agentCard.additionalInterfaces ?? [];
|
||||
const urlsPerAgentTransports = new CaseInsensitiveMap<string>([
|
||||
[agentCardPreferred, agentCard.url],
|
||||
...additionalInterfaces.map<[string, string]>((i) => [i.transport, i.url]),
|
||||
]);
|
||||
const transportsByPreference = [
|
||||
...(this.options.preferredTransports ?? []),
|
||||
agentCardPreferred,
|
||||
...additionalInterfaces.map((i) => i.transport),
|
||||
];
|
||||
for (const transport of transportsByPreference) {
|
||||
const url = urlsPerAgentTransports.get(transport);
|
||||
const factory = this.transportsByName.get(transport);
|
||||
if (factory && url) {
|
||||
return new Client(
|
||||
await factory.create(url, agentCard),
|
||||
agentCard,
|
||||
this.options.clientConfig
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
'No compatible transport found, available transports: ' +
|
||||
[...this.transportsByName.keys()].join()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads agent card using AgentCardResolver from options
|
||||
* and creates a new client from the downloaded card.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const factory = new ClientFactory(); // use default options and default {@link AgentCardResolver}.
|
||||
* const client1 = await factory.createFromUrl('https://example.com'); // /.well-known/agent-card.json is used by default
|
||||
* const client2 = await factory.createFromUrl('https://example.com', '/my-agent-card.json'); // specify custom path
|
||||
* const client3 = await factory.createFromUrl('https://example.com/my-agent-card.json', ''); // specify full URL and set path to empty
|
||||
* ```
|
||||
*/
|
||||
async createFromUrl(baseUrl: string, path?: string): Promise<Client> {
|
||||
const agentCard = await this.agentCardResolver.resolve(baseUrl, path);
|
||||
return this.createFromAgentCard(agentCard);
|
||||
}
|
||||
}
|
||||
|
||||
function mergeTransports(
|
||||
original: TransportFactory[],
|
||||
overrides: TransportFactory[] | undefined
|
||||
): TransportFactory[] {
|
||||
if (!overrides) {
|
||||
return original;
|
||||
}
|
||||
|
||||
const result = transportsByName(original);
|
||||
const overridesByName = transportsByName(overrides);
|
||||
for (const [name, factory] of overridesByName) {
|
||||
result.set(name, factory);
|
||||
}
|
||||
return Array.from(result.values());
|
||||
}
|
||||
|
||||
function transportsByName(
|
||||
transports: ReadonlyArray<TransportFactory> | undefined
|
||||
): CaseInsensitiveMap<TransportFactory> {
|
||||
const result = new CaseInsensitiveMap<TransportFactory>();
|
||||
if (!transports) {
|
||||
return result;
|
||||
}
|
||||
for (const t of transports) {
|
||||
if (result.has(t.protocolName)) {
|
||||
throw new Error(`Duplicate protocol name: ${t.protocolName}`);
|
||||
}
|
||||
result.set(t.protocolName, t);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function mergeArrays<T>(
|
||||
a1: ReadonlyArray<T> | undefined,
|
||||
a2: ReadonlyArray<T> | undefined
|
||||
): T[] | undefined {
|
||||
if (!a1 && !a2) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return [...(a1 ?? []), ...(a2 ?? [])];
|
||||
}
|
||||
|
||||
/**
|
||||
* A Map that normalizes string keys to uppercase for case-insensitive lookups.
|
||||
* This prevents errors from inconsistent casing in protocol names.
|
||||
*/
|
||||
class CaseInsensitiveMap<T> extends Map<string, T> {
|
||||
private normalizeKey(key: string): string {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
|
||||
override set(key: string, value: T): this {
|
||||
return super.set(this.normalizeKey(key), value);
|
||||
}
|
||||
|
||||
override get(key: string): T | undefined {
|
||||
return super.get(this.normalizeKey(key));
|
||||
}
|
||||
|
||||
override has(key: string): boolean {
|
||||
return super.has(this.normalizeKey(key));
|
||||
}
|
||||
|
||||
override delete(key: string): boolean {
|
||||
return super.delete(this.normalizeKey(key));
|
||||
}
|
||||
}
|
||||
@ -2,46 +2,4 @@
|
||||
* Client entry point for the A2A Server V2 library.
|
||||
*/
|
||||
|
||||
export { A2AClient } from './client.js';
|
||||
export type { A2AClientOptions } from './client.js';
|
||||
export * from './auth-handler.js';
|
||||
export {
|
||||
AgentCardResolver,
|
||||
type AgentCardResolverOptions,
|
||||
DefaultAgentCardResolver,
|
||||
} from './card-resolver.js';
|
||||
export { Client, type ClientConfig, type RequestOptions } from './multitransport-client.js';
|
||||
export type { Transport, TransportFactory } from './transports/transport.js';
|
||||
export { ClientFactory, ClientFactoryOptions } from './factory.js';
|
||||
export {
|
||||
JsonRpcTransport,
|
||||
JsonRpcTransportFactory,
|
||||
type JsonRpcTransportOptions,
|
||||
} from './transports/json_rpc_transport.js';
|
||||
export {
|
||||
RestTransport,
|
||||
RestTransportFactory,
|
||||
type RestTransportOptions,
|
||||
} from './transports/rest_transport.js';
|
||||
export type {
|
||||
CallInterceptor,
|
||||
BeforeArgs,
|
||||
AfterArgs,
|
||||
ClientCallInput,
|
||||
ClientCallResult,
|
||||
} from './interceptors.js';
|
||||
export {
|
||||
ServiceParameters,
|
||||
type ServiceParametersUpdate,
|
||||
withA2AExtensions,
|
||||
} from './service-parameters.js';
|
||||
export { ClientCallContext, type ContextUpdate, ClientCallContextKey } from './context.js';
|
||||
export {
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
ContentTypeNotSupportedError,
|
||||
InvalidAgentResponseError,
|
||||
PushNotificationNotSupportedError,
|
||||
TaskNotCancelableError,
|
||||
TaskNotFoundError,
|
||||
UnsupportedOperationError,
|
||||
} from '../errors.js';
|
||||
export { A2AClient } from "./client.js";
|
||||
|
||||
@ -1,134 +0,0 @@
|
||||
import { AgentCard } from '../types.js';
|
||||
import { A2AStreamEventData } from './client.js';
|
||||
import { Client } from './multitransport-client.js';
|
||||
import { RequestOptions } from './multitransport-client.js';
|
||||
|
||||
export interface CallInterceptor {
|
||||
/**
|
||||
* Invoked before transport method.
|
||||
*/
|
||||
before(args: BeforeArgs): Promise<void>;
|
||||
|
||||
/**
|
||||
* Invoked after transport method.
|
||||
*/
|
||||
after(args: AfterArgs): Promise<void>;
|
||||
}
|
||||
|
||||
export interface BeforeArgs<K extends keyof Client = keyof Client> {
|
||||
/**
|
||||
* Identifies the client method invoked and its payload.
|
||||
* Payload inside the input object can be modified.
|
||||
*/
|
||||
readonly input: ClientCallInput<K>;
|
||||
|
||||
/**
|
||||
* Identifies the agent card cached on the client
|
||||
*/
|
||||
readonly agentCard: AgentCard;
|
||||
|
||||
/**
|
||||
* If set by the interceptor, stops execution, invokes "after"
|
||||
* for executed interceptors and returns the result. Transport is not called.
|
||||
*/
|
||||
earlyReturn?: ClientCallResult<K>;
|
||||
|
||||
/**
|
||||
* Options passed to the client.
|
||||
*/
|
||||
options?: RequestOptions;
|
||||
}
|
||||
|
||||
export interface AfterArgs<K extends keyof Client = keyof Client> {
|
||||
/**
|
||||
* Identifies the client method invoked and its result.
|
||||
* Payload inside the result object can be modified.
|
||||
*/
|
||||
readonly result: ClientCallResult<K>;
|
||||
|
||||
/**
|
||||
* Identifies the agent card cached on the client
|
||||
*/
|
||||
readonly agentCard: AgentCard;
|
||||
|
||||
/**
|
||||
* If set by the interceptor, stops execution and returns result value,
|
||||
* remaining interceptors are not executed.
|
||||
*/
|
||||
earlyReturn?: boolean;
|
||||
|
||||
/**
|
||||
* Options passed to the client.
|
||||
*/
|
||||
options?: RequestOptions;
|
||||
}
|
||||
|
||||
export type ClientCallInput<K extends keyof Client = keyof Client> = MethodInput<Client, K>;
|
||||
export type ClientCallResult<K extends keyof Client = keyof Client> = MethodResult<
|
||||
Client,
|
||||
K,
|
||||
ResultsOverrides
|
||||
>;
|
||||
|
||||
// Types below are helper types and are not exported to allow simplifying it without affecting
|
||||
// public API if necessary. They are exported via type aliases ClientXxx which can be replaced with explicit union if necessary.
|
||||
|
||||
/**
|
||||
* For
|
||||
*
|
||||
* interface Foo {
|
||||
* f1(arg: string): Promise<Result1>;
|
||||
* f2(arg: number): Promise<Result2>;
|
||||
* }
|
||||
*
|
||||
* MethodInputs<Foo> resolves to
|
||||
*
|
||||
* {
|
||||
* readonly method: "f1";
|
||||
* value: string;
|
||||
* } | {
|
||||
* readonly method: "f2";
|
||||
* value: number;
|
||||
* }
|
||||
*/
|
||||
type MethodInput<T, TMembers extends keyof T = keyof T> = {
|
||||
[M in TMembers]: T[M] extends (options: RequestOptions | undefined) => unknown
|
||||
? { readonly method: M; value?: never }
|
||||
: T[M] extends (payload: infer P) => unknown
|
||||
? { readonly method: M; value: P }
|
||||
: never;
|
||||
}[TMembers];
|
||||
|
||||
/**
|
||||
* For
|
||||
*
|
||||
* interface Foo {
|
||||
* f1(): Promise<Result1>;
|
||||
* f2(): Promise<Result2>;
|
||||
* }
|
||||
*
|
||||
* MethodsResults<Foo> resolves to
|
||||
*
|
||||
* {
|
||||
* readonly method: "f1";
|
||||
* value: Result1;
|
||||
* } | {
|
||||
* readonly method: "f2";
|
||||
* value: Result2;
|
||||
* }
|
||||
*/
|
||||
type MethodResult<T, TMembers extends keyof T = keyof T, TOverrides = object> = {
|
||||
[M in TMembers]: M extends keyof TOverrides // If there is an override, use it directly.
|
||||
? { readonly method: M; value: TOverrides[M] }
|
||||
: // Infer result, unwrap it from Promise and pack with method name.
|
||||
T[M] extends (payload: unknown) => infer R
|
||||
? { readonly method: M; value: Awaited<R> }
|
||||
: never;
|
||||
}[TMembers];
|
||||
|
||||
interface ResultsOverrides {
|
||||
// sendMessageStream and resubscribeTask return async iterators and are intercepted on each item,
|
||||
// which requires custom handling.
|
||||
sendMessageStream: A2AStreamEventData;
|
||||
resubscribeTask: A2AStreamEventData;
|
||||
}
|
||||
@ -1,393 +0,0 @@
|
||||
import { PushNotificationNotSupportedError } from '../errors.js';
|
||||
import {
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
Task,
|
||||
TaskIdParams,
|
||||
TaskQueryParams,
|
||||
PushNotificationConfig,
|
||||
AgentCard,
|
||||
} from '../types.js';
|
||||
import { A2AStreamEventData, SendMessageResult } from './client.js';
|
||||
import { ClientCallContext } from './context.js';
|
||||
import {
|
||||
CallInterceptor,
|
||||
BeforeArgs,
|
||||
AfterArgs,
|
||||
ClientCallResult,
|
||||
ClientCallInput,
|
||||
} from './interceptors.js';
|
||||
import { ServiceParameters } from './service-parameters.js';
|
||||
import { Transport } from './transports/transport.js';
|
||||
|
||||
export interface ClientConfig {
|
||||
/**
|
||||
* Whether client prefers to poll for task updates instead of blocking until a terminal state is reached.
|
||||
* If set to true, non-streaming send message result might be a Message or a Task in any (including non-terminal) state.
|
||||
* Callers are responsible for running the polling loop. This configuration does not apply to streaming requests.
|
||||
*/
|
||||
polling?: boolean;
|
||||
|
||||
/**
|
||||
* Specifies the default list of accepted media types to apply for all "send message" calls.
|
||||
*/
|
||||
acceptedOutputModes?: string[];
|
||||
|
||||
/**
|
||||
* Specifies the default push notification configuration to apply for every Task.
|
||||
*/
|
||||
pushNotificationConfig?: PushNotificationConfig;
|
||||
|
||||
/**
|
||||
* Interceptors invoked for each request.
|
||||
*/
|
||||
interceptors?: CallInterceptor[];
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
/**
|
||||
* Signal to abort request execution.
|
||||
*/
|
||||
signal?: AbortSignal;
|
||||
|
||||
/**
|
||||
* A key-value map for passing horizontally applicable context or parameters.
|
||||
* All parameters are passed to the server via underlying transports (e.g. In JsonRPC via Headers).
|
||||
*/
|
||||
serviceParameters?: ServiceParameters;
|
||||
|
||||
/**
|
||||
* Arbitrary data available to interceptors and transport implementation.
|
||||
*/
|
||||
context?: ClientCallContext;
|
||||
}
|
||||
|
||||
export class Client {
|
||||
constructor(
|
||||
public readonly transport: Transport,
|
||||
private agentCard: AgentCard,
|
||||
public readonly config?: ClientConfig
|
||||
) {}
|
||||
|
||||
/**
|
||||
* If the current agent card supports the extended feature, it will try to fetch the extended agent card from the server,
|
||||
* Otherwise it will return the current agent card value.
|
||||
*/
|
||||
async getAgentCard(options?: RequestOptions): Promise<AgentCard> {
|
||||
if (this.agentCard.supportsAuthenticatedExtendedCard) {
|
||||
this.agentCard = await this.executeWithInterceptors(
|
||||
{ method: 'getAgentCard' },
|
||||
options,
|
||||
(_, options) => this.transport.getExtendedAgentCard(options)
|
||||
);
|
||||
}
|
||||
return this.agentCard;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to an agent to initiate a new interaction or to continue an existing one.
|
||||
* Uses blocking mode by default.
|
||||
*/
|
||||
sendMessage(params: MessageSendParams, options?: RequestOptions): Promise<SendMessageResult> {
|
||||
params = this.applyClientConfig({
|
||||
params,
|
||||
blocking: !(this.config?.polling ?? false),
|
||||
});
|
||||
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'sendMessage', value: params },
|
||||
options,
|
||||
this.transport.sendMessage.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to an agent to initiate/continue a task AND subscribes the client to real-time updates for that task.
|
||||
* Performs fallback to non-streaming if not supported by the agent.
|
||||
*/
|
||||
async *sendMessageStream(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const method = 'sendMessageStream';
|
||||
|
||||
params = this.applyClientConfig({ params, blocking: true });
|
||||
const beforeArgs: BeforeArgs<'sendMessageStream'> = {
|
||||
input: { method, value: params },
|
||||
agentCard: this.agentCard,
|
||||
options,
|
||||
};
|
||||
const beforeResult = await this.interceptBefore(beforeArgs);
|
||||
|
||||
if (beforeResult) {
|
||||
const earlyReturn = beforeResult.earlyReturn.value;
|
||||
const afterArgs: AfterArgs<'sendMessageStream'> = {
|
||||
result: { method, value: earlyReturn },
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs, beforeResult.executed);
|
||||
yield afterArgs.result.value;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.agentCard.capabilities.streaming) {
|
||||
const result = await this.transport.sendMessage(beforeArgs.input.value, beforeArgs.options);
|
||||
const afterArgs: AfterArgs<'sendMessageStream'> = {
|
||||
result: { method, value: result },
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs);
|
||||
yield afterArgs.result.value;
|
||||
return;
|
||||
}
|
||||
for await (const event of this.transport.sendMessageStream(
|
||||
beforeArgs.input.value,
|
||||
beforeArgs.options
|
||||
)) {
|
||||
const afterArgs: AfterArgs<'sendMessageStream'> = {
|
||||
result: { method, value: event },
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs);
|
||||
yield afterArgs.result.value;
|
||||
if (afterArgs.earlyReturn) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets or updates the push notification configuration for a specified task.
|
||||
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
||||
*/
|
||||
setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
}
|
||||
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'setTaskPushNotificationConfig', value: params },
|
||||
options,
|
||||
this.transport.setTaskPushNotificationConfig.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the current push notification configuration for a specified task.
|
||||
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
||||
*/
|
||||
getTaskPushNotificationConfig(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
}
|
||||
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'getTaskPushNotificationConfig', value: params },
|
||||
options,
|
||||
this.transport.getTaskPushNotificationConfig.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the associated push notification configurations for a specified task.
|
||||
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
||||
*/
|
||||
listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
}
|
||||
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'listTaskPushNotificationConfig', value: params },
|
||||
options,
|
||||
this.transport.listTaskPushNotificationConfig.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an associated push notification configuration for a task.
|
||||
*/
|
||||
deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<void> {
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'deleteTaskPushNotificationConfig', value: params },
|
||||
options,
|
||||
this.transport.deleteTaskPushNotificationConfig.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the current state (including status, artifacts, and optionally history) of a previously initiated task.
|
||||
*/
|
||||
getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task> {
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'getTask', value: params },
|
||||
options,
|
||||
this.transport.getTask.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the cancellation of an ongoing task. The server will attempt to cancel the task,
|
||||
* but success is not guaranteed (e.g., the task might have already completed or failed, or cancellation might not be supported at its current stage).
|
||||
*/
|
||||
cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task> {
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'cancelTask', value: params },
|
||||
options,
|
||||
this.transport.cancelTask.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows a client to reconnect to an updates stream for an ongoing task after a previous connection was interrupted.
|
||||
*/
|
||||
async *resubscribeTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const method = 'resubscribeTask';
|
||||
|
||||
const beforeArgs: BeforeArgs<'resubscribeTask'> = {
|
||||
input: { method, value: params },
|
||||
agentCard: this.agentCard,
|
||||
options,
|
||||
};
|
||||
const beforeResult = await this.interceptBefore(beforeArgs);
|
||||
|
||||
if (beforeResult) {
|
||||
const earlyReturn = beforeResult.earlyReturn.value;
|
||||
const afterArgs: AfterArgs<'resubscribeTask'> = {
|
||||
result: { method, value: earlyReturn },
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs, beforeResult.executed);
|
||||
yield afterArgs.result.value;
|
||||
return;
|
||||
}
|
||||
|
||||
for await (const event of this.transport.resubscribeTask(
|
||||
beforeArgs.input.value,
|
||||
beforeArgs.options
|
||||
)) {
|
||||
const afterArgs: AfterArgs<'resubscribeTask'> = {
|
||||
result: { method, value: event },
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs);
|
||||
yield afterArgs.result.value;
|
||||
if (afterArgs.earlyReturn) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private applyClientConfig({
|
||||
params,
|
||||
blocking,
|
||||
}: {
|
||||
params: MessageSendParams;
|
||||
blocking: boolean;
|
||||
}): MessageSendParams {
|
||||
const result = { ...params, configuration: params.configuration ?? {} };
|
||||
|
||||
if (!result.configuration.acceptedOutputModes && this.config?.acceptedOutputModes) {
|
||||
result.configuration.acceptedOutputModes = this.config.acceptedOutputModes;
|
||||
}
|
||||
if (!result.configuration.pushNotificationConfig && this.config?.pushNotificationConfig) {
|
||||
result.configuration.pushNotificationConfig = this.config.pushNotificationConfig;
|
||||
}
|
||||
result.configuration.blocking ??= blocking;
|
||||
return result;
|
||||
}
|
||||
|
||||
private async executeWithInterceptors<K extends keyof Client>(
|
||||
input: ClientCallInput<K>,
|
||||
options: RequestOptions | undefined,
|
||||
transportCall: (
|
||||
params: ClientCallInput<K>['value'],
|
||||
options?: RequestOptions
|
||||
) => Promise<ClientCallResult<K>['value']>
|
||||
): Promise<ClientCallResult<K>['value']> {
|
||||
const beforeArgs: BeforeArgs<K> = {
|
||||
input: input,
|
||||
agentCard: this.agentCard,
|
||||
options,
|
||||
};
|
||||
const beforeResult = await this.interceptBefore(beforeArgs);
|
||||
|
||||
if (beforeResult) {
|
||||
const afterArgs: AfterArgs<K> = {
|
||||
result: {
|
||||
method: input.method,
|
||||
value: beforeResult.earlyReturn.value,
|
||||
} as ClientCallResult<K>,
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs, beforeResult.executed);
|
||||
return afterArgs.result.value;
|
||||
}
|
||||
|
||||
const result = await transportCall(beforeArgs.input.value, beforeArgs.options);
|
||||
|
||||
const afterArgs: AfterArgs<K> = {
|
||||
result: { method: input.method, value: result } as ClientCallResult<K>,
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs);
|
||||
|
||||
return afterArgs.result.value;
|
||||
}
|
||||
|
||||
private async interceptBefore<K extends keyof Client>(
|
||||
args: BeforeArgs<K>
|
||||
): Promise<{ earlyReturn: ClientCallResult<K>; executed: CallInterceptor[] } | undefined> {
|
||||
if (!this.config?.interceptors || this.config.interceptors.length === 0) {
|
||||
return;
|
||||
}
|
||||
const executed: CallInterceptor[] = [];
|
||||
for (const interceptor of this.config.interceptors) {
|
||||
await interceptor.before(args);
|
||||
executed.push(interceptor);
|
||||
if (args.earlyReturn) {
|
||||
return {
|
||||
earlyReturn: args.earlyReturn,
|
||||
executed,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async interceptAfter<K extends keyof Client>(
|
||||
args: AfterArgs<K>,
|
||||
interceptors?: CallInterceptor[]
|
||||
): Promise<void> {
|
||||
const reversedInterceptors = [...(interceptors ?? this.config?.interceptors ?? [])].reverse();
|
||||
for (const interceptor of reversedInterceptors) {
|
||||
await interceptor.after(args);
|
||||
if (args.earlyReturn) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,29 +0,0 @@
|
||||
import { HTTP_EXTENSION_HEADER } from '../constants.js';
|
||||
import { Extensions } from '../extensions.js';
|
||||
|
||||
export type ServiceParameters = Record<string, string>;
|
||||
|
||||
export type ServiceParametersUpdate = (parameters: ServiceParameters) => void;
|
||||
|
||||
export const ServiceParameters = {
|
||||
create(...updates: ServiceParametersUpdate[]): ServiceParameters {
|
||||
return ServiceParameters.createFrom(undefined, ...updates);
|
||||
},
|
||||
|
||||
createFrom: (
|
||||
serviceParameters: ServiceParameters | undefined,
|
||||
...updates: ServiceParametersUpdate[]
|
||||
): ServiceParameters => {
|
||||
const result = serviceParameters ? { ...serviceParameters } : {};
|
||||
for (const update of updates) {
|
||||
update(result);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
|
||||
export function withA2AExtensions(...extensions: Extensions): ServiceParametersUpdate {
|
||||
return (parameters: ServiceParameters) => {
|
||||
parameters[HTTP_EXTENSION_HEADER] = Extensions.toServiceParameter(extensions);
|
||||
};
|
||||
}
|
||||
@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1,5 +0,0 @@
|
||||
export {
|
||||
GrpcTransport,
|
||||
GrpcTransportFactory,
|
||||
type GrpcTransportOptions,
|
||||
} from './grpc_transport.js';
|
||||
@ -1,445 +0,0 @@
|
||||
import { TransportProtocolName } from '../../core.js';
|
||||
import {
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
ContentTypeNotSupportedError,
|
||||
InvalidAgentResponseError,
|
||||
PushNotificationNotSupportedError,
|
||||
TaskNotCancelableError,
|
||||
TaskNotFoundError,
|
||||
UnsupportedOperationError,
|
||||
} from '../../errors.js';
|
||||
import {
|
||||
JSONRPCRequest,
|
||||
JSONRPCResponse,
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
TaskIdParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigResponse,
|
||||
TaskQueryParams,
|
||||
Task,
|
||||
JSONRPCErrorResponse,
|
||||
SendMessageSuccessResponse,
|
||||
SetTaskPushNotificationConfigSuccessResponse,
|
||||
GetTaskPushNotificationConfigSuccessResponse,
|
||||
ListTaskPushNotificationConfigSuccessResponse,
|
||||
GetTaskSuccessResponse,
|
||||
CancelTaskSuccessResponse,
|
||||
AgentCard,
|
||||
GetTaskPushNotificationConfigParams,
|
||||
GetAuthenticatedExtendedCardSuccessResponse,
|
||||
} from '../../types.js';
|
||||
import { A2AStreamEventData, SendMessageResult } from '../client.js';
|
||||
import { RequestOptions } from '../multitransport-client.js';
|
||||
import { parseSseStream } from '../../sse_utils.js';
|
||||
import { Transport, TransportFactory } from './transport.js';
|
||||
|
||||
export interface JsonRpcTransportOptions {
|
||||
endpoint: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
export class JsonRpcTransport implements Transport {
|
||||
private readonly customFetchImpl?: typeof fetch;
|
||||
private readonly endpoint: string;
|
||||
private requestIdCounter: number = 1;
|
||||
|
||||
constructor(options: JsonRpcTransportOptions) {
|
||||
this.endpoint = options.endpoint;
|
||||
this.customFetchImpl = options.fetchImpl;
|
||||
}
|
||||
|
||||
async getExtendedAgentCard(options?: RequestOptions, idOverride?: number): Promise<AgentCard> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
undefined,
|
||||
GetAuthenticatedExtendedCardSuccessResponse
|
||||
>('agent/getAuthenticatedExtendedCard', undefined, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<SendMessageResult> {
|
||||
const rpcResponse = await this._sendRpcRequest<MessageSendParams, SendMessageSuccessResponse>(
|
||||
'message/send',
|
||||
params,
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async *sendMessageStream(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendStreamingRequest('message/stream', params, options);
|
||||
}
|
||||
|
||||
async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
TaskPushNotificationConfig,
|
||||
SetTaskPushNotificationConfigSuccessResponse
|
||||
>('tasks/pushNotificationConfig/set', params, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
GetTaskPushNotificationConfigParams,
|
||||
GetTaskPushNotificationConfigSuccessResponse
|
||||
>('tasks/pushNotificationConfig/get', params, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
ListTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigSuccessResponse
|
||||
>('tasks/pushNotificationConfig/list', params, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<void> {
|
||||
await this._sendRpcRequest<
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigResponse
|
||||
>('tasks/pushNotificationConfig/delete', params, idOverride, options);
|
||||
}
|
||||
|
||||
async getTask(
|
||||
params: TaskQueryParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<Task> {
|
||||
const rpcResponse = await this._sendRpcRequest<TaskQueryParams, GetTaskSuccessResponse>(
|
||||
'tasks/get',
|
||||
params,
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async cancelTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<Task> {
|
||||
const rpcResponse = await this._sendRpcRequest<TaskIdParams, CancelTaskSuccessResponse>(
|
||||
'tasks/cancel',
|
||||
params,
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async *resubscribeTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendStreamingRequest('tasks/resubscribe', params, options);
|
||||
}
|
||||
|
||||
async callExtensionMethod<TExtensionParams, TExtensionResponse extends JSONRPCResponse>(
|
||||
method: string,
|
||||
params: TExtensionParams,
|
||||
idOverride: number,
|
||||
options?: RequestOptions
|
||||
) {
|
||||
return await this._sendRpcRequest<TExtensionParams, TExtensionResponse>(
|
||||
method,
|
||||
params,
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
private _fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
|
||||
if (this.customFetchImpl) {
|
||||
return this.customFetchImpl(...args);
|
||||
}
|
||||
if (typeof fetch === 'function') {
|
||||
return fetch(...args);
|
||||
}
|
||||
throw new Error(
|
||||
'A `fetch` implementation was not provided and is not available in the global scope. ' +
|
||||
'Please provide a `fetchImpl` in the A2ATransportOptions. '
|
||||
);
|
||||
}
|
||||
|
||||
private async _sendRpcRequest<
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
TParams extends { [key: string]: any },
|
||||
TResponse extends JSONRPCResponse,
|
||||
>(
|
||||
method: string,
|
||||
params: TParams,
|
||||
idOverride: number | undefined,
|
||||
options: RequestOptions | undefined
|
||||
): Promise<TResponse> {
|
||||
const requestId = idOverride ?? this.requestIdCounter++;
|
||||
|
||||
const rpcRequest: JSONRPCRequest = {
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params: params,
|
||||
id: requestId,
|
||||
};
|
||||
|
||||
const httpResponse = await this._fetchRpc(rpcRequest, 'application/json', options);
|
||||
|
||||
if (!httpResponse.ok) {
|
||||
let errorBodyText = '(empty or non-JSON response)';
|
||||
let errorJson: JSONRPCErrorResponse;
|
||||
try {
|
||||
errorBodyText = await httpResponse.text();
|
||||
errorJson = JSON.parse(errorBodyText);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,
|
||||
{ cause: e }
|
||||
);
|
||||
}
|
||||
if (errorJson.jsonrpc && errorJson.error) {
|
||||
throw JsonRpcTransport.mapToError(errorJson);
|
||||
} else {
|
||||
throw new Error(
|
||||
`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const rpcResponse: JSONRPCResponse = await httpResponse.json();
|
||||
if (rpcResponse.id !== requestId) {
|
||||
throw new Error(
|
||||
`JSON-RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}.`
|
||||
);
|
||||
}
|
||||
|
||||
if ('error' in rpcResponse) {
|
||||
throw JsonRpcTransport.mapToError(rpcResponse);
|
||||
}
|
||||
|
||||
return rpcResponse as TResponse;
|
||||
}
|
||||
|
||||
private async _fetchRpc(
|
||||
rpcRequest: JSONRPCRequest,
|
||||
acceptHeader: string = 'application/json',
|
||||
options?: RequestOptions
|
||||
): Promise<Response> {
|
||||
const requestInit: RequestInit = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...options?.serviceParameters,
|
||||
'Content-Type': 'application/json',
|
||||
Accept: acceptHeader,
|
||||
},
|
||||
body: JSON.stringify(rpcRequest),
|
||||
signal: options?.signal,
|
||||
};
|
||||
return this._fetch(this.endpoint, requestInit);
|
||||
}
|
||||
|
||||
private async *_sendStreamingRequest(
|
||||
method: string,
|
||||
params: unknown,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const clientRequestId = this.requestIdCounter++;
|
||||
const rpcRequest: JSONRPCRequest = {
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params: params as { [key: string]: unknown },
|
||||
id: clientRequestId,
|
||||
};
|
||||
|
||||
const response = await this._fetchRpc(rpcRequest, 'text/event-stream', options);
|
||||
|
||||
if (!response.ok) {
|
||||
let errorBody = '';
|
||||
let errorJson: JSONRPCErrorResponse;
|
||||
try {
|
||||
errorBody = await response.text();
|
||||
errorJson = JSON.parse(errorBody);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,
|
||||
{ cause: e }
|
||||
);
|
||||
}
|
||||
if (errorJson.error) {
|
||||
throw new Error(
|
||||
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`
|
||||
);
|
||||
}
|
||||
throw new Error(
|
||||
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {
|
||||
throw new Error(
|
||||
`Invalid response Content-Type for SSE stream for ${method}. Expected 'text/event-stream'.`
|
||||
);
|
||||
}
|
||||
|
||||
for await (const event of parseSseStream(response)) {
|
||||
yield this._processSseEventData<A2AStreamEventData>(event.data, clientRequestId);
|
||||
}
|
||||
}
|
||||
|
||||
private _processSseEventData<TStreamItem>(
|
||||
jsonData: string,
|
||||
originalRequestId: number | string | null
|
||||
): TStreamItem {
|
||||
if (!jsonData.trim()) {
|
||||
throw new Error('Attempted to process empty SSE event data.');
|
||||
}
|
||||
|
||||
let a2aStreamResponse: JSONRPCResponse;
|
||||
try {
|
||||
a2aStreamResponse = JSON.parse(jsonData) as JSONRPCResponse;
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${(e instanceof Error && e.message) || 'Unknown error'}`,
|
||||
{ cause: e }
|
||||
);
|
||||
}
|
||||
|
||||
if (a2aStreamResponse.id !== originalRequestId) {
|
||||
throw new Error(
|
||||
`JSON-RPC response ID mismatch in SSE event. Expected ${originalRequestId}, got ${a2aStreamResponse.id}.`
|
||||
);
|
||||
}
|
||||
|
||||
if ('error' in a2aStreamResponse) {
|
||||
const err = a2aStreamResponse.error;
|
||||
throw new Error(
|
||||
`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`,
|
||||
{ cause: JsonRpcTransport.mapToError(a2aStreamResponse) }
|
||||
);
|
||||
}
|
||||
|
||||
if (!('result' in a2aStreamResponse) || typeof a2aStreamResponse.result === 'undefined') {
|
||||
throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
|
||||
}
|
||||
|
||||
return a2aStreamResponse.result as TStreamItem;
|
||||
}
|
||||
|
||||
private static mapToError(response: JSONRPCErrorResponse): Error {
|
||||
switch (response.error.code) {
|
||||
case -32001:
|
||||
return new TaskNotFoundJSONRPCError(response);
|
||||
case -32002:
|
||||
return new TaskNotCancelableJSONRPCError(response);
|
||||
case -32003:
|
||||
return new PushNotificationNotSupportedJSONRPCError(response);
|
||||
case -32004:
|
||||
return new UnsupportedOperationJSONRPCError(response);
|
||||
case -32005:
|
||||
return new ContentTypeNotSupportedJSONRPCError(response);
|
||||
case -32006:
|
||||
return new InvalidAgentResponseJSONRPCError(response);
|
||||
case -32007:
|
||||
return new AuthenticatedExtendedCardNotConfiguredJSONRPCError(response);
|
||||
default:
|
||||
return new JSONRPCTransportError(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class JsonRpcTransportFactoryOptions {
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
export class JsonRpcTransportFactory implements TransportFactory {
|
||||
public static readonly name: TransportProtocolName = 'JSONRPC';
|
||||
|
||||
constructor(private readonly options?: JsonRpcTransportFactoryOptions) {}
|
||||
|
||||
get protocolName(): string {
|
||||
return JsonRpcTransportFactory.name;
|
||||
}
|
||||
|
||||
async create(url: string, _agentCard: AgentCard): Promise<Transport> {
|
||||
return new JsonRpcTransport({
|
||||
endpoint: url,
|
||||
fetchImpl: this.options?.fetchImpl,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class JSONRPCTransportError extends Error {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super(
|
||||
`JSON-RPC error: ${errorResponse.error.message} (Code: ${errorResponse.error.code}) Data: ${JSON.stringify(errorResponse.error.data || {})}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Redeclare domain errors with the original JSON-RPC response as a field to be compatible
|
||||
// with the legacy A2AClient built around JSON-RPC interface.
|
||||
|
||||
export class TaskNotFoundJSONRPCError extends TaskNotFoundError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class TaskNotCancelableJSONRPCError extends TaskNotCancelableError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class PushNotificationNotSupportedJSONRPCError extends PushNotificationNotSupportedError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class UnsupportedOperationJSONRPCError extends UnsupportedOperationError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class ContentTypeNotSupportedJSONRPCError extends ContentTypeNotSupportedError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class InvalidAgentResponseJSONRPCError extends InvalidAgentResponseError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class AuthenticatedExtendedCardNotConfiguredJSONRPCError extends AuthenticatedExtendedCardNotConfiguredError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1,59 +0,0 @@
|
||||
import {
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
TaskIdParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
TaskQueryParams,
|
||||
Task,
|
||||
AgentCard,
|
||||
GetTaskPushNotificationConfigParams,
|
||||
} from '../../types.js';
|
||||
import { A2AStreamEventData, SendMessageResult } from '../client.js';
|
||||
import { RequestOptions } from '../multitransport-client.js';
|
||||
|
||||
export interface Transport {
|
||||
getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard>;
|
||||
|
||||
sendMessage(params: MessageSendParams, options?: RequestOptions): Promise<SendMessageResult>;
|
||||
|
||||
sendMessageStream(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined>;
|
||||
|
||||
setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
|
||||
getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
|
||||
listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig[]>;
|
||||
|
||||
deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<void>;
|
||||
|
||||
getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task>;
|
||||
|
||||
cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task>;
|
||||
|
||||
resubscribeTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined>;
|
||||
}
|
||||
|
||||
export interface TransportFactory {
|
||||
get protocolName(): string;
|
||||
|
||||
create(url: string, agentCard: AgentCard): Promise<Transport>;
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
/**
|
||||
* Shared constants for the A2A library
|
||||
*/
|
||||
|
||||
/**
|
||||
* The well-known path for the agent card
|
||||
*/
|
||||
export const AGENT_CARD_PATH = '.well-known/agent-card.json';
|
||||
|
||||
/**
|
||||
* The name of the extension header used in http
|
||||
*/
|
||||
export const HTTP_EXTENSION_HEADER = 'X-A2A-Extensions';
|
||||
@ -1 +0,0 @@
|
||||
export type TransportProtocolName = 'JSONRPC' | 'HTTP+JSON' | 'GRPC' | (string & {});
|
||||
@ -1,69 +0,0 @@
|
||||
// Legacy JSON-RPC error codes.
|
||||
export const A2A_ERROR_CODE = {
|
||||
PARSE_ERROR: -32700,
|
||||
INVALID_REQUEST: -32600,
|
||||
METHOD_NOT_FOUND: -32601,
|
||||
INVALID_PARAMS: -32602,
|
||||
INTERNAL_ERROR: -32603,
|
||||
TASK_NOT_FOUND: -32001,
|
||||
TASK_NOT_CANCELABLE: -32002,
|
||||
PUSH_NOTIFICATION_NOT_SUPPORTED: -32003,
|
||||
UNSUPPORTED_OPERATION: -32004,
|
||||
CONTENT_TYPE_NOT_SUPPORTED: -32005,
|
||||
INVALID_AGENT_RESPONSE: -32006,
|
||||
AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED: -32007,
|
||||
} as const;
|
||||
|
||||
// Transport-agnostic errors according to https://a2a-protocol.org/v0.3.0/specification/#82-a2a-specific-errors.
|
||||
// Due to a name conflict with legacy JSON-RPC types reexported from src/index.ts
|
||||
// below errors are going to be exported via src/client/index.ts to allow usage
|
||||
// from external transport implementations.
|
||||
|
||||
export class TaskNotFoundError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Task not found');
|
||||
this.name = 'TaskNotFoundError';
|
||||
}
|
||||
}
|
||||
|
||||
export class TaskNotCancelableError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Task cannot be canceled');
|
||||
this.name = 'TaskNotCancelableError';
|
||||
}
|
||||
}
|
||||
|
||||
export class PushNotificationNotSupportedError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Push Notification is not supported');
|
||||
this.name = 'PushNotificationNotSupportedError';
|
||||
}
|
||||
}
|
||||
|
||||
export class UnsupportedOperationError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'This operation is not supported');
|
||||
this.name = 'UnsupportedOperationError';
|
||||
}
|
||||
}
|
||||
|
||||
export class ContentTypeNotSupportedError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Incompatible content types');
|
||||
this.name = 'ContentTypeNotSupportedError';
|
||||
}
|
||||
}
|
||||
|
||||
export class InvalidAgentResponseError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Invalid agent response type');
|
||||
this.name = 'InvalidAgentResponseError';
|
||||
}
|
||||
}
|
||||
|
||||
export class AuthenticatedExtendedCardNotConfiguredError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Authenticated Extended Card not configured');
|
||||
this.name = 'AuthenticatedExtendedCardNotConfiguredError';
|
||||
}
|
||||
}
|
||||
@ -1,48 +0,0 @@
|
||||
/**
|
||||
* A2A Protocol Extension URI.
|
||||
*/
|
||||
export type ExtensionURI = string;
|
||||
|
||||
/**
|
||||
* A collection of {@link ExtensionURI}.
|
||||
*/
|
||||
export type Extensions = ExtensionURI[];
|
||||
|
||||
export const Extensions = {
|
||||
/**
|
||||
* Creates new {@link Extensions} from `current` and `additional`.
|
||||
* If `current` already contains `additional` it is returned unmodified.
|
||||
*/
|
||||
createFrom: (current: Extensions | undefined, additional: ExtensionURI): Extensions => {
|
||||
if (current?.includes(additional)) {
|
||||
return current;
|
||||
}
|
||||
return [...(current ?? []), additional];
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates {@link Extensions} from comma separated extensions identifiers as per
|
||||
* https://a2a-protocol.org/latest/specification/#326-service-parameters.
|
||||
* Parses the output of `toServiceParameter`.
|
||||
*/
|
||||
parseServiceParameter: (value: string | undefined): Extensions => {
|
||||
if (!value) {
|
||||
return [];
|
||||
}
|
||||
const unique = new Set(
|
||||
value
|
||||
.split(',')
|
||||
.map((ext) => ext.trim())
|
||||
.filter((ext) => ext.length > 0)
|
||||
);
|
||||
return Array.from(unique);
|
||||
},
|
||||
|
||||
/**
|
||||
* Converts {@link Extensions} to comma separated extensions identifiers as per
|
||||
* https://a2a-protocol.org/latest/specification/#326-service-parameters.
|
||||
*/
|
||||
toServiceParameter: (value: Extensions): string => {
|
||||
return value.join(',');
|
||||
},
|
||||
};
|
||||
@ -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.
|
||||
@ -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
|
||||
@ -1,6 +0,0 @@
|
||||
# Generated by buf. DO NOT EDIT.
|
||||
version: v2
|
||||
deps:
|
||||
- name: buf.build/googleapis/googleapis
|
||||
commit: 004180b77378443887d3b55cabc00384
|
||||
digest: b5:e8f475fe3330f31f5fd86ac689093bcd274e19611a09db91f41d637cb9197881ce89882b94d13a58738e53c91c6e4bae7dc1feba85f590164c975a89e25115dc
|
||||
@ -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
@ -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
@ -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,
|
||||
}
|
||||
@ -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¶m=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;
|
||||
}
|
||||
@ -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
@ -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;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
@ -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>;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
10
src/index.ts
10
src/index.ts
@ -1,11 +1,7 @@
|
||||
/**
|
||||
* Main entry point for the A2A Server V2 library.
|
||||
* Exports the common types.
|
||||
*
|
||||
* Use the client/index.ts file to import the client-only codebase.
|
||||
* Use the server/index.ts file to import the server-only codebase.
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export type { A2AResponse } from './a2a_response.js';
|
||||
export { AGENT_CARD_PATH, HTTP_EXTENSION_HEADER } from './constants.js';
|
||||
export { Extensions, type ExtensionURI } from './extensions.js';
|
||||
export * from "./types.js";
|
||||
export type { A2AResponse } from "./a2a_response.js";
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
import { googleAI } from '@genkit-ai/googleai';
|
||||
import { genkit } from 'genkit';
|
||||
import { dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { googleAI } from "@genkit-ai/googleai";
|
||||
import { genkit } from "genkit";
|
||||
import { dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
export const ai = genkit({
|
||||
plugins: [googleAI()],
|
||||
model: googleAI.model('gemini-2.0-flash'),
|
||||
model: googleAI.model("gemini-2.0-flash"),
|
||||
promptDir: dirname(fileURLToPath(import.meta.url)),
|
||||
});
|
||||
|
||||
export { z } from 'genkit';
|
||||
export { z } from "genkit";
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import express from 'express';
|
||||
import express from "express";
|
||||
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
|
||||
|
||||
import {
|
||||
@ -7,27 +7,23 @@ import {
|
||||
TaskState,
|
||||
TaskStatusUpdateEvent,
|
||||
TextPart,
|
||||
Message,
|
||||
AGENT_CARD_PATH,
|
||||
TaskArtifactUpdateEvent,
|
||||
Artifact,
|
||||
Part,
|
||||
} from '../../../index.js';
|
||||
Message
|
||||
} from "../../../index.js";
|
||||
import {
|
||||
InMemoryTaskStore,
|
||||
TaskStore,
|
||||
AgentExecutor,
|
||||
RequestContext,
|
||||
ExecutionEventBus,
|
||||
DefaultRequestHandler,
|
||||
} from '../../../server/index.js';
|
||||
import { agentCardHandler, jsonRpcHandler, UserBuilder } from '../../../server/express/index.js';
|
||||
import { MessageData } from 'genkit';
|
||||
import { ai } from './genkit.js';
|
||||
import { searchMovies, searchPeople } from './tools.js';
|
||||
DefaultRequestHandler
|
||||
} from "../../../server/index.js";
|
||||
import { A2AExpressApp } from "../../../server/express/index.js";
|
||||
import { MessageData } from "genkit";
|
||||
import { ai } from "./genkit.js";
|
||||
import { searchMovies, searchPeople } from "./tools.js";
|
||||
|
||||
if (!process.env.GEMINI_API_KEY || !process.env.TMDB_API_KEY) {
|
||||
console.error('GEMINI_API_KEY and TMDB_API_KEY environment variables are required');
|
||||
console.error("GEMINI_API_KEY and TMDB_API_KEY environment variables are required")
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@ -43,12 +39,18 @@ const movieAgentPrompt = ai.prompt('movie_agent');
|
||||
class MovieAgentExecutor implements AgentExecutor {
|
||||
private cancelledTasks = new Set<string>();
|
||||
|
||||
public cancelTask = async (taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {
|
||||
this.cancelledTasks.add(taskId);
|
||||
// The execute loop is responsible for publishing the final state
|
||||
};
|
||||
public cancelTask = async (
|
||||
taskId: string,
|
||||
eventBus: ExecutionEventBus,
|
||||
): Promise<void> => {
|
||||
this.cancelledTasks.add(taskId);
|
||||
// The execute loop is responsible for publishing the final state
|
||||
};
|
||||
|
||||
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
async execute(
|
||||
requestContext: RequestContext,
|
||||
eventBus: ExecutionEventBus
|
||||
): Promise<void> {
|
||||
const userMessage = requestContext.userMessage;
|
||||
const existingTask = requestContext.task;
|
||||
|
||||
@ -99,10 +101,10 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
|
||||
// 3. Prepare messages for Genkit prompt
|
||||
const historyForGenkit = contexts.get(contextId) || [];
|
||||
if (!historyForGenkit.find((m) => m.messageId === userMessage.messageId)) {
|
||||
if (!historyForGenkit.find(m => m.messageId === userMessage.messageId)) {
|
||||
historyForGenkit.push(userMessage);
|
||||
}
|
||||
contexts.set(contextId, historyForGenkit);
|
||||
contexts.set(contextId, historyForGenkit)
|
||||
|
||||
const messages: MessageData[] = historyForGenkit
|
||||
.map((m) => ({
|
||||
@ -141,9 +143,7 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
return;
|
||||
}
|
||||
|
||||
const goal =
|
||||
(existingTask?.metadata?.goal as string | undefined) ||
|
||||
(userMessage.metadata?.goal as string | undefined);
|
||||
const goal = existingTask?.metadata?.goal as string | undefined || userMessage.metadata?.goal as string | undefined;
|
||||
|
||||
try {
|
||||
// 4. Run the Genkit prompt
|
||||
@ -177,12 +177,9 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
console.info(`[MovieAgentExecutor] Prompt response: ${responseText}`);
|
||||
const lines = responseText.trim().split('\n');
|
||||
const finalStateLine = lines.at(-1)?.trim().toUpperCase();
|
||||
const agentReplyText = lines
|
||||
.slice(0, lines.length - 1)
|
||||
.join('\n')
|
||||
.trim();
|
||||
const agentReplyText = lines.slice(0, lines.length - 1).join('\n').trim();
|
||||
|
||||
let finalA2AState: TaskState = 'unknown';
|
||||
let finalA2AState: TaskState = "unknown";
|
||||
|
||||
if (finalStateLine === 'COMPLETED') {
|
||||
finalA2AState = 'completed';
|
||||
@ -195,53 +192,40 @@ 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);
|
||||
contexts.set(contextId, historyForGenkit)
|
||||
|
||||
// 7. Publish final task status update
|
||||
const finalUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: finalA2AState,
|
||||
message: agentMessage,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(finalUpdate);
|
||||
|
||||
console.log(`[MovieAgentExecutor] Task ${taskId} finished with state: ${finalA2AState}`);
|
||||
console.log(
|
||||
`[MovieAgentExecutor] Task ${taskId} finished with state: ${finalA2AState}`
|
||||
);
|
||||
|
||||
} catch (error: any) {
|
||||
console.error(`[MovieAgentExecutor] Error processing task ${taskId}:`, error);
|
||||
console.error(
|
||||
`[MovieAgentExecutor] Error processing task ${taskId}:`,
|
||||
error
|
||||
);
|
||||
const errorUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
@ -270,13 +254,13 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
const movieAgentCard: AgentCard = {
|
||||
name: 'Movie Agent',
|
||||
description: 'An agent that can answer questions about movies and actors using TMDB.',
|
||||
url: 'http://localhost:41241/',
|
||||
// Adjust the base URL and port as needed. /a2a is the default base in A2AExpressApp
|
||||
url: 'http://localhost:41241/', // Example: if baseUrl in A2AExpressApp
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples', // Added provider URL
|
||||
url: 'https://example.com/a2a-samples' // Added provider URL
|
||||
},
|
||||
version: '0.0.2', // Incremented version
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
streaming: true, // The new framework supports streaming
|
||||
pushNotifications: false, // Assuming not implemented for this agent yet
|
||||
@ -302,7 +286,7 @@ const movieAgentCard: AgentCard = {
|
||||
'Which came out first, Jurassic Park or Terminator 2?',
|
||||
],
|
||||
inputModes: ['text'], // Explicitly defining for skill
|
||||
outputModes: ['text', 'task-status'], // Explicitly defining for skill
|
||||
outputModes: ['text', 'task-status'] // Explicitly defining for skill
|
||||
},
|
||||
],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
@ -316,24 +300,24 @@ async function main() {
|
||||
const agentExecutor: AgentExecutor = new MovieAgentExecutor();
|
||||
|
||||
// 3. Create DefaultRequestHandler
|
||||
const requestHandler = new DefaultRequestHandler(movieAgentCard, taskStore, agentExecutor);
|
||||
const requestHandler = new DefaultRequestHandler(
|
||||
movieAgentCard,
|
||||
taskStore,
|
||||
agentExecutor
|
||||
);
|
||||
|
||||
// 4. Create and setup Express.js app
|
||||
const app = express();
|
||||
|
||||
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
|
||||
app.use(jsonRpcHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
|
||||
// 4. Create and setup A2AExpressApp
|
||||
const appBuilder = new A2AExpressApp(requestHandler);
|
||||
const expressApp = appBuilder.setupRoutes(express());
|
||||
|
||||
// 5. Start the server
|
||||
const PORT = process.env.PORT || 41241;
|
||||
app.listen(PORT, (err) => {
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
expressApp.listen(PORT, () => {
|
||||
console.log(`[MovieAgent] Server using new framework started on http://localhost:${PORT}`);
|
||||
console.log(`[MovieAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`);
|
||||
console.log(`[MovieAgent] Agent Card: http://localhost:${PORT}/.well-known/agent.json`);
|
||||
console.log('[MovieAgent] Press Ctrl+C to stop the server');
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
|
||||
|
||||
@ -8,22 +8,24 @@ export async function callTmdbApi(endpoint: string, query: string) {
|
||||
// Validate API key
|
||||
const apiKey = process.env.TMDB_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error('TMDB_API_KEY environment variable is not set');
|
||||
throw new Error("TMDB_API_KEY environment variable is not set");
|
||||
}
|
||||
|
||||
try {
|
||||
// Make request to TMDB API
|
||||
const url = new URL(`https://api.themoviedb.org/3/search/${endpoint}`);
|
||||
url.searchParams.append('api_key', apiKey);
|
||||
url.searchParams.append('query', query);
|
||||
url.searchParams.append('include_adult', 'false');
|
||||
url.searchParams.append('language', 'en-US');
|
||||
url.searchParams.append('page', '1');
|
||||
url.searchParams.append("api_key", apiKey);
|
||||
url.searchParams.append("query", query);
|
||||
url.searchParams.append("include_adult", "false");
|
||||
url.searchParams.append("language", "en-US");
|
||||
url.searchParams.append("page", "1");
|
||||
|
||||
const response = await fetch(url.toString());
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`TMDB API error: ${response.status} ${response.statusText}`);
|
||||
throw new Error(
|
||||
`TMDB API error: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
|
||||
@ -1,18 +1,18 @@
|
||||
import { ai, z } from './genkit.js';
|
||||
import { callTmdbApi } from './tmdb.js';
|
||||
import { ai, z } from "./genkit.js";
|
||||
import { callTmdbApi } from "./tmdb.js";
|
||||
|
||||
export const searchMovies = ai.defineTool(
|
||||
{
|
||||
name: 'searchMovies',
|
||||
description: 'search TMDB for movies by title',
|
||||
name: "searchMovies",
|
||||
description: "search TMDB for movies by title",
|
||||
inputSchema: z.object({
|
||||
query: z.string(),
|
||||
}),
|
||||
},
|
||||
async ({ query }) => {
|
||||
console.log('[tmdb:searchMovies]', JSON.stringify(query));
|
||||
console.log("[tmdb:searchMovies]", JSON.stringify(query));
|
||||
try {
|
||||
const data = await callTmdbApi('movie', query);
|
||||
const data = await callTmdbApi("movie", query);
|
||||
|
||||
// Only modify image paths to be full URLs
|
||||
const results = data.results.map((movie: any) => {
|
||||
@ -30,7 +30,7 @@ export const searchMovies = ai.defineTool(
|
||||
results,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error searching movies:', error);
|
||||
console.error("Error searching movies:", error);
|
||||
// Re-throwing allows Genkit/the caller to handle it appropriately
|
||||
throw error;
|
||||
}
|
||||
@ -39,16 +39,16 @@ export const searchMovies = ai.defineTool(
|
||||
|
||||
export const searchPeople = ai.defineTool(
|
||||
{
|
||||
name: 'searchPeople',
|
||||
description: 'search TMDB for people by name',
|
||||
name: "searchPeople",
|
||||
description: "search TMDB for people by name",
|
||||
inputSchema: z.object({
|
||||
query: z.string(),
|
||||
}),
|
||||
},
|
||||
async ({ query }) => {
|
||||
console.log('[tmdb:searchPeople]', JSON.stringify(query));
|
||||
console.log("[tmdb:searchPeople]", JSON.stringify(query));
|
||||
try {
|
||||
const data = await callTmdbApi('person', query);
|
||||
const data = await callTmdbApi("person", query);
|
||||
|
||||
// Only modify image paths to be full URLs
|
||||
const results = data.results.map((person: any) => {
|
||||
@ -77,7 +77,7 @@ export const searchPeople = ai.defineTool(
|
||||
results,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error searching people:', error);
|
||||
console.error("Error searching people:", error);
|
||||
// Re-throwing allows Genkit/the caller to handle it appropriately
|
||||
throw error;
|
||||
}
|
||||
|
||||
@ -1,9 +0,0 @@
|
||||
# Sample Agent
|
||||
|
||||
This agent is a sample to emulate the task flow in a streaming scenario. To run:
|
||||
|
||||
```bash
|
||||
npm run agents:sample-agent
|
||||
```
|
||||
|
||||
The agent will start on `http://localhost:41241`.
|
||||
@ -1,126 +0,0 @@
|
||||
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
|
||||
|
||||
import {
|
||||
Task,
|
||||
TaskStatusUpdateEvent,
|
||||
Message,
|
||||
TaskArtifactUpdateEvent,
|
||||
Artifact,
|
||||
} from '../../../index.js';
|
||||
import { AgentExecutor, RequestContext, ExecutionEventBus } from '../../../server/index.js';
|
||||
|
||||
/**
|
||||
* SampleAgentExecutor implements the agent's core logic.
|
||||
*/
|
||||
export class SampleAgentExecutor implements AgentExecutor {
|
||||
public cancelTask = async (_taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {};
|
||||
|
||||
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
const userMessage = requestContext.userMessage;
|
||||
const existingTask = requestContext.task;
|
||||
|
||||
// Determine IDs for the task and context
|
||||
const taskId = requestContext.taskId;
|
||||
const contextId = requestContext.contextId;
|
||||
|
||||
console.log(
|
||||
`[SampleAgentExecutor] Processing message ${userMessage.messageId} for task ${taskId} (context: ${contextId})`
|
||||
);
|
||||
|
||||
// 1. Publish initial Task event if it's a new task
|
||||
if (!existingTask) {
|
||||
const initialTask: Task = {
|
||||
kind: 'task',
|
||||
id: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'submitted',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
history: [userMessage], // Start history with the current user message
|
||||
metadata: userMessage.metadata, // Carry over metadata from message if any
|
||||
};
|
||||
eventBus.publish(initialTask);
|
||||
}
|
||||
|
||||
// 2. Publish "working" status update
|
||||
const workingStatusUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'working',
|
||||
message: {
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [{ kind: 'text', text: 'Processing your question' }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
final: false,
|
||||
};
|
||||
eventBus.publish(workingStatusUpdate);
|
||||
|
||||
// 3. Publish artifact with the result
|
||||
const agentReplyText = this.parseInputMessage(userMessage);
|
||||
console.info(`[SampleAgentExecutor] Prompt response: ${agentReplyText}`);
|
||||
|
||||
const artifactId = uuidv4();
|
||||
const resultArtifact: Artifact = {
|
||||
artifactId: artifactId,
|
||||
name: 'Result',
|
||||
description: 'The final result from the agent.',
|
||||
parts: [{ kind: 'text', text: agentReplyText }],
|
||||
};
|
||||
|
||||
const artifactUpdate: TaskArtifactUpdateEvent = {
|
||||
kind: 'artifact-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
artifact: resultArtifact,
|
||||
lastChunk: true,
|
||||
};
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate processing delay
|
||||
eventBus.publish(artifactUpdate);
|
||||
|
||||
// 4. Publish final task status update (completed, no message)
|
||||
const finalUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'completed',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(finalUpdate);
|
||||
|
||||
console.log(`[SampleAgentExecutor] Task ${taskId} finished with state: completed`);
|
||||
}
|
||||
|
||||
parseInputMessage(message: Message): string {
|
||||
/** Process the user query and return a response. */
|
||||
const textPart = message.parts.find((part) => part.kind === 'text');
|
||||
const query = textPart ? textPart.text.trim() : '';
|
||||
|
||||
if (!query) {
|
||||
return 'Hello! Please provide a message for me to respond to.';
|
||||
}
|
||||
|
||||
// Simple responses based on input
|
||||
const queryLower = query.toLowerCase();
|
||||
if (queryLower.includes('hello') || queryLower.includes('hi')) {
|
||||
return 'Hello World! Nice to meet you!';
|
||||
} else if (queryLower.includes('how are you')) {
|
||||
return "I'm doing great! Thanks for asking. How can I help you today?";
|
||||
} else if (queryLower.includes('goodbye') || queryLower.includes('bye')) {
|
||||
return 'Goodbye! Have a wonderful day!';
|
||||
} else {
|
||||
return `Hello World! You said: '${query}'. Thanks for your message!`;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,74 +0,0 @@
|
||||
import express from 'express';
|
||||
import { AgentCard, AGENT_CARD_PATH } from '../../../index.js';
|
||||
import {
|
||||
InMemoryTaskStore,
|
||||
TaskStore,
|
||||
AgentExecutor,
|
||||
DefaultRequestHandler,
|
||||
} from '../../../server/index.js';
|
||||
import { agentCardHandler, jsonRpcHandler, UserBuilder } from '../../../server/express/index.js';
|
||||
import { SampleAgentExecutor } from './agent_executor.js';
|
||||
|
||||
// --- Server Setup ---
|
||||
|
||||
const sampleAgentCard: AgentCard = {
|
||||
name: 'Sample Agent',
|
||||
description:
|
||||
'A sample agent to test the stream functionality and simulate the flow of tasks statuses.',
|
||||
url: 'http://localhost:41241/',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples', // Added provider URL
|
||||
},
|
||||
version: '1.0.0', // Incremented version
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
streaming: true, // The new framework supports streaming
|
||||
pushNotifications: false, // Assuming not implemented for this agent yet
|
||||
stateTransitionHistory: true, // Agent uses history
|
||||
},
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text', 'task-status'], // task-status is a common output mode
|
||||
skills: [
|
||||
{
|
||||
id: 'sample_agent',
|
||||
name: 'Sample Agent',
|
||||
description: 'Simulate the general flow of a streaming agent.',
|
||||
tags: ['sample'],
|
||||
examples: ['hi', 'hello world', 'how are you', 'goodbye'],
|
||||
inputModes: ['text'], // Explicitly defining for skill
|
||||
outputModes: ['text', 'task-status'], // Explicitly defining for skill
|
||||
},
|
||||
],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// 1. Create TaskStore
|
||||
const taskStore: TaskStore = new InMemoryTaskStore();
|
||||
|
||||
// 2. Create AgentExecutor
|
||||
const agentExecutor: AgentExecutor = new SampleAgentExecutor();
|
||||
|
||||
// 3. Create DefaultRequestHandler
|
||||
const requestHandler = new DefaultRequestHandler(sampleAgentCard, taskStore, agentExecutor);
|
||||
|
||||
// 4. Create and setup Express app
|
||||
const app = express();
|
||||
|
||||
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
|
||||
app.use(jsonRpcHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
|
||||
|
||||
// 5. Start the server
|
||||
const PORT = process.env.PORT || 41241;
|
||||
app.listen(PORT, (err) => {
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
console.log(`[SampleAgent] Server using new framework started on http://localhost:${PORT}`);
|
||||
console.log(`[SampleAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`);
|
||||
console.log('[SampleAgent] Press Ctrl+C to stop the server');
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@ -1,80 +0,0 @@
|
||||
# Authentication Sample
|
||||
|
||||
This sample demonstrates how to implement **Bearer Token authentication**. It shows how to intercept requests, validate tokens, extract the user generated by the authentication and pass it to the context.
|
||||
|
||||
|
||||
## Key Components
|
||||
|
||||
- `index.ts`: generates an `AgentCard` that requires for the Bearer authentication for incoming requests and starts the server with the authentication middleware and user builder.
|
||||
- `authentication_middleware.ts`: creates the middleware responsible for authentication. It uses Passport to support Bearer token authorization and populates the `user` parameter in the Request object with the plain extracted object.
|
||||
- `user_builder.ts`: defines the callback for the user extraction. It expects the user object (populated by the middleware) to contain specific values (`email`, `userName`, `role`) which are used to build the `CustomUser` object.
|
||||
- `agent_executor.ts`: creates a simple agent executor that checks the authentication status of the user object present in the context, which is expected to be an instance of `CustomUser` in case of successful authentication, and sends back the content.
|
||||
|
||||
|
||||
To test the agent:
|
||||
|
||||
```bash
|
||||
npm run agents:authentication-agent
|
||||
```
|
||||
|
||||
The agent will start on `http://localhost:41241`.
|
||||
|
||||
Use this [tool](https://www.jwt.io/) to generate your Json Web Token with the JWT Encoder. The secret key for the signature is `a2a-secret-for-authentication-sample`.
|
||||
For a successful authentication the payload data MUST contain these values: "email", "userName", "role".
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:41241/
|
||||
-H "Authorization: Bearer <jwt-token>"
|
||||
-H "Content-Type: application/json"
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "message/send",
|
||||
"params": {
|
||||
"message": {
|
||||
"role": "user",
|
||||
"parts": [
|
||||
{
|
||||
"kind": "text",
|
||||
"text": "Hello, who am i?"
|
||||
}
|
||||
],
|
||||
"messageId": "9229e770-767c-417b-a0b0-f0741243c589"
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
Expected response, with successful authentication:
|
||||
```json
|
||||
{
|
||||
"jsonrpc":"2.0",
|
||||
"id":1,
|
||||
"result": {
|
||||
"kind":"message",
|
||||
"role":"agent",
|
||||
"parts":[ {
|
||||
"kind":"text",
|
||||
"text":"The request is coming from the authenticated user <your-userName>, with email <your-email> and role <your-role>."
|
||||
} ]
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Expected response, with failed authentication:
|
||||
```json
|
||||
{
|
||||
"jsonrpc":"2.0",
|
||||
"id":1,
|
||||
"result": {
|
||||
"kind":"message",
|
||||
"role":"agent",
|
||||
"parts":[ {
|
||||
"kind":"text",
|
||||
"text":"The request is not coming from an authenticated user."
|
||||
} ]
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
@ -1,28 +0,0 @@
|
||||
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
|
||||
import { AgentExecutor, ExecutionEventBus, RequestContext } from '../../server/index.js';
|
||||
import { CustomUser } from './user_builder.js';
|
||||
import { Message } from '../../types.js';
|
||||
|
||||
export class AuthenticationAgentExecutor implements AgentExecutor {
|
||||
public cancelTask = async (_taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {};
|
||||
|
||||
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
let finalText;
|
||||
if (
|
||||
requestContext.context?.user?.isAuthenticated &&
|
||||
requestContext.context.user instanceof CustomUser
|
||||
) {
|
||||
const customUser = requestContext.context.user;
|
||||
finalText = `The request is coming from the authenticated user ${customUser.userName}, with email ${customUser.email} and role ${customUser.role}.`;
|
||||
} else {
|
||||
finalText = `The request is not coming from an authenticated user.`;
|
||||
}
|
||||
const finalMessage: Message = {
|
||||
kind: 'message',
|
||||
messageId: uuidv4(),
|
||||
role: 'agent',
|
||||
parts: [{ kind: 'text', text: finalText }],
|
||||
};
|
||||
eventBus.publish(finalMessage);
|
||||
}
|
||||
}
|
||||
@ -1,31 +0,0 @@
|
||||
import { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
import passport from 'passport';
|
||||
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
|
||||
|
||||
passport.use(
|
||||
new JwtStrategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: 'a2a-secret-for-authentication-sample',
|
||||
},
|
||||
(jwt_payload, done) => {
|
||||
return done(null, jwt_payload);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const authenticationHandler: RequestHandler = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
passport.authenticate('jwt', { session: false }, (err: any, user: any) => {
|
||||
if (err) {
|
||||
return next(err);
|
||||
}
|
||||
if (user) {
|
||||
req.user = user;
|
||||
}
|
||||
next();
|
||||
})(req, res, next);
|
||||
};
|
||||
@ -1,88 +0,0 @@
|
||||
import express from 'express';
|
||||
import { AgentCard } from '../../index.js';
|
||||
import {
|
||||
InMemoryTaskStore,
|
||||
TaskStore,
|
||||
AgentExecutor,
|
||||
DefaultRequestHandler,
|
||||
} from '../../server/index.js';
|
||||
import { jsonRpcHandler } from '../../server/express/index.js';
|
||||
import { AuthenticationAgentExecutor } from './agent_executor.js';
|
||||
import { userBuilder } from './user_builder.js';
|
||||
import { authenticationHandler } from './authentication_middleware.js';
|
||||
|
||||
// --- Server Setup ---
|
||||
|
||||
const authenticationAgentCard: AgentCard = {
|
||||
name: 'Sample Authentication Agent',
|
||||
description: 'A sample agent to test the authentication functionality',
|
||||
url: 'http://localhost:41241/',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples',
|
||||
},
|
||||
version: '1.0.0',
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
stateTransitionHistory: true, // Agent uses history
|
||||
},
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text', 'task-status'],
|
||||
skills: [
|
||||
{
|
||||
id: 'sample_agent',
|
||||
name: 'Sample Agent',
|
||||
description: 'Simulate the general flow of an agent with authentication feature.',
|
||||
tags: ['sample'],
|
||||
examples: ['hello, who am i?'],
|
||||
inputModes: ['text'],
|
||||
outputModes: ['text', 'task-status'],
|
||||
},
|
||||
],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
security: [{ Bearer: [] }],
|
||||
securitySchemes: { Bearer: { type: 'http', scheme: 'bearer' } },
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// 1. Create TaskStore
|
||||
const taskStore: TaskStore = new InMemoryTaskStore();
|
||||
|
||||
// 2. Create AgentExecutor
|
||||
const agentExecutor: AgentExecutor = new AuthenticationAgentExecutor();
|
||||
|
||||
// 3. Create DefaultRequestHandler
|
||||
const requestHandler = new DefaultRequestHandler(
|
||||
authenticationAgentCard,
|
||||
taskStore,
|
||||
agentExecutor
|
||||
);
|
||||
|
||||
// 4. Create and setup express app, with authentication middleware and user builder
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(authenticationHandler);
|
||||
app.use(
|
||||
jsonRpcHandler({
|
||||
requestHandler,
|
||||
userBuilder,
|
||||
})
|
||||
);
|
||||
|
||||
// 5. Start the server
|
||||
const PORT = process.env.PORT || 41241;
|
||||
app.listen(PORT, (err: unknown) => {
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
console.log(
|
||||
`[AuthenticationAgent] Server using new framework started on http://localhost:${PORT}`
|
||||
);
|
||||
console.log(
|
||||
`[AuthenticationAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`
|
||||
);
|
||||
console.log('[AuthenticationAgent] Press Ctrl+C to stop the server');
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@ -1,22 +0,0 @@
|
||||
import { Request } from 'express';
|
||||
import { UnauthenticatedUser, User } from '../../server/index.js';
|
||||
import { UserBuilder } from '../../server/express/index.js';
|
||||
|
||||
export class CustomUser implements User {
|
||||
public isAuthenticated: boolean = true;
|
||||
constructor(
|
||||
public userName: string,
|
||||
public email: string,
|
||||
public role: string
|
||||
) {}
|
||||
}
|
||||
|
||||
export const userBuilder: UserBuilder = async (req: Request): Promise<User> => {
|
||||
if ('user' in req && typeof req.user === 'object') {
|
||||
const user = req.user;
|
||||
if ('userName' in user && 'email' in user && 'role' in user) {
|
||||
return new CustomUser(user.userName as string, user.email as string, user.role as string);
|
||||
}
|
||||
}
|
||||
return new UnauthenticatedUser();
|
||||
};
|
||||
@ -1,8 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import readline from 'node:readline';
|
||||
import crypto from 'node:crypto';
|
||||
import { GoogleAuth } from 'google-auth-library';
|
||||
import readline from "node:readline";
|
||||
import crypto from "node:crypto";
|
||||
|
||||
import {
|
||||
// Specific Params/Payload types used by the CLI
|
||||
@ -12,37 +11,28 @@ import {
|
||||
Message,
|
||||
Task, // Added for direct Task events
|
||||
// Other types needed for message/part handling
|
||||
TaskState,
|
||||
FilePart,
|
||||
DataPart,
|
||||
// Type for the agent card
|
||||
AgentCard,
|
||||
Part, // Added for explicit Part typing
|
||||
AGENT_CARD_PATH,
|
||||
} from '../index.js';
|
||||
Part // Added for explicit Part typing
|
||||
} 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 { A2AClient } from "../client/index.js";
|
||||
|
||||
// --- ANSI Colors ---
|
||||
const colors = {
|
||||
reset: '\x1b[0m',
|
||||
bright: '\x1b[1m',
|
||||
dim: '\x1b[2m',
|
||||
red: '\x1b[31m',
|
||||
green: '\x1b[32m',
|
||||
yellow: '\x1b[33m',
|
||||
blue: '\x1b[34m',
|
||||
magenta: '\x1b[35m',
|
||||
cyan: '\x1b[36m',
|
||||
gray: '\x1b[90m',
|
||||
reset: "\x1b[0m",
|
||||
bright: "\x1b[1m",
|
||||
dim: "\x1b[2m",
|
||||
red: "\x1b[31m",
|
||||
green: "\x1b[32m",
|
||||
yellow: "\x1b[33m",
|
||||
blue: "\x1b[34m",
|
||||
magenta: "\x1b[35m",
|
||||
cyan: "\x1b[36m",
|
||||
gray: "\x1b[90m",
|
||||
};
|
||||
|
||||
// --- Helper Functions ---
|
||||
@ -50,114 +40,68 @@ function colorize(color: keyof typeof colors, text: string): string {
|
||||
return `${colors[color]}${text}${colors.reset}`;
|
||||
}
|
||||
|
||||
function generateId(): string {
|
||||
// Renamed for more general use
|
||||
function generateId(): string { // Renamed for more general use
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
|
||||
// Application Default Credentials required for A2A agent running on Agent Engine.
|
||||
export class ADCHandler implements AuthenticationHandler {
|
||||
private auth = new GoogleAuth({
|
||||
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
|
||||
});
|
||||
|
||||
async headers(): Promise<Record<string, string>> {
|
||||
const client = await this.auth.getClient();
|
||||
const token = await client.getAccessToken();
|
||||
if (token?.token) {
|
||||
return { Authorization: `Bearer ${token.token}` };
|
||||
}
|
||||
throw new Error('Failed to retrieve ADC access token.');
|
||||
}
|
||||
|
||||
async shouldRetryWithHeaders(
|
||||
_req: RequestInit,
|
||||
res: Response
|
||||
): Promise<Record<string, string> | undefined> {
|
||||
if (res.status !== 401 && res.status !== 403) return undefined;
|
||||
return this.headers();
|
||||
}
|
||||
}
|
||||
|
||||
// --- State ---
|
||||
let currentTaskId: string | undefined = undefined; // Initialize as undefined
|
||||
let currentContextId: string | undefined = undefined; // Initialize as undefined
|
||||
|
||||
const preferredTransport = process.argv
|
||||
.find((arg) => arg.startsWith('--transport='))
|
||||
?.split('=')[1];
|
||||
const serverUrlArg = process.argv.slice(2).find((arg) => !arg.startsWith('--'));
|
||||
const serverUrl = serverUrlArg || 'http://localhost:41241'; // Agent's base URL
|
||||
|
||||
let fetchImpl: typeof fetch = fetch;
|
||||
let agentCardPath = AGENT_CARD_PATH;
|
||||
if (process.argv.includes('--agent-engine')) {
|
||||
fetchImpl = createAuthenticatingFetchWithRetry(fetch, new ADCHandler());
|
||||
agentCardPath = 'a2a/v1/card'; // Agent Engine doesn't use well-known public agent card endpoint.
|
||||
}
|
||||
const factory = new ClientFactory(
|
||||
ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
|
||||
cardResolver: new DefaultAgentCardResolver({ fetchImpl }),
|
||||
transports: [
|
||||
new JsonRpcTransportFactory({ fetchImpl }),
|
||||
new RestTransportFactory({ fetchImpl }),
|
||||
new GrpcTransportFactory(),
|
||||
],
|
||||
preferredTransports: preferredTransport ? [preferredTransport] : undefined,
|
||||
})
|
||||
);
|
||||
const client = await factory.createFromUrl(serverUrl, agentCardPath);
|
||||
let agentName = 'Agent'; // Default, try to get from agent card later
|
||||
const serverUrl = process.argv[2] || "http://localhost:41241"; // Agent's base URL
|
||||
const client = new A2AClient(serverUrl);
|
||||
let agentName = "Agent"; // Default, try to get from agent card later
|
||||
|
||||
// --- Readline Setup ---
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
prompt: colorize('cyan', 'You: '),
|
||||
prompt: colorize("cyan", "You: "),
|
||||
});
|
||||
|
||||
// --- Response Handling ---
|
||||
// Function now accepts the unwrapped event payload directly
|
||||
function printAgentEvent(event: TaskStatusUpdateEvent | TaskArtifactUpdateEvent) {
|
||||
function printAgentEvent(
|
||||
event: TaskStatusUpdateEvent | TaskArtifactUpdateEvent
|
||||
) {
|
||||
const timestamp = new Date().toLocaleTimeString();
|
||||
const prefix = colorize('magenta', `\n${agentName} [${timestamp}]:`);
|
||||
const prefix = colorize("magenta", `\n${agentName} [${timestamp}]:`);
|
||||
|
||||
// Check if it's a TaskStatusUpdateEvent
|
||||
if (event.kind === 'status-update') {
|
||||
if (event.kind === "status-update") {
|
||||
const update = event as TaskStatusUpdateEvent; // Cast for type safety
|
||||
const state = update.status.state;
|
||||
let stateEmoji = '❓';
|
||||
let stateColor: keyof typeof colors = 'yellow';
|
||||
let stateEmoji = "❓";
|
||||
let stateColor: keyof typeof colors = "yellow";
|
||||
|
||||
switch (state) {
|
||||
case 'working':
|
||||
stateEmoji = '⏳';
|
||||
stateColor = 'blue';
|
||||
case "working":
|
||||
stateEmoji = "⏳";
|
||||
stateColor = "blue";
|
||||
break;
|
||||
case 'input-required':
|
||||
stateEmoji = '🤔';
|
||||
stateColor = 'yellow';
|
||||
case "input-required":
|
||||
stateEmoji = "🤔";
|
||||
stateColor = "yellow";
|
||||
break;
|
||||
case 'completed':
|
||||
stateEmoji = '✅';
|
||||
stateColor = 'green';
|
||||
case "completed":
|
||||
stateEmoji = "✅";
|
||||
stateColor = "green";
|
||||
break;
|
||||
case 'canceled':
|
||||
stateEmoji = '⏹️';
|
||||
stateColor = 'gray';
|
||||
case "canceled":
|
||||
stateEmoji = "⏹️";
|
||||
stateColor = "gray";
|
||||
break;
|
||||
case 'failed':
|
||||
stateEmoji = '❌';
|
||||
stateColor = 'red';
|
||||
case "failed":
|
||||
stateEmoji = "❌";
|
||||
stateColor = "red";
|
||||
break;
|
||||
default:
|
||||
stateEmoji = 'ℹ️'; // For other states like submitted, rejected etc.
|
||||
stateColor = 'dim';
|
||||
stateEmoji = "ℹ️"; // For other states like submitted, rejected etc.
|
||||
stateColor = "dim";
|
||||
break;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`${prefix} ${stateEmoji} Status: ${colorize(stateColor, state)} (Task: ${update.taskId}, Context: ${update.contextId}) ${update.final ? colorize('bright', '[FINAL]') : ''}`
|
||||
`${prefix} ${stateEmoji} Status: ${colorize(stateColor, state)} (Task: ${update.taskId}, Context: ${update.contextId}) ${update.final ? colorize("bright", "[FINAL]") : ""}`
|
||||
);
|
||||
|
||||
if (update.status.message) {
|
||||
@ -165,18 +109,17 @@ function printAgentEvent(event: TaskStatusUpdateEvent | TaskArtifactUpdateEvent)
|
||||
}
|
||||
}
|
||||
// Check if it's a TaskArtifactUpdateEvent
|
||||
else if (event.kind === 'artifact-update') {
|
||||
else if (event.kind === "artifact-update") {
|
||||
const update = event as TaskArtifactUpdateEvent; // Cast for type safety
|
||||
console.log(
|
||||
`${prefix} 📄 Artifact Received: ${
|
||||
update.artifact.name || '(unnamed)'
|
||||
`${prefix} 📄 Artifact Received: ${update.artifact.name || "(unnamed)"
|
||||
} (ID: ${update.artifact.artifactId}, Task: ${update.taskId}, Context: ${update.contextId})`
|
||||
);
|
||||
// Create a temporary message-like structure to reuse printMessageContent
|
||||
printMessageContent({
|
||||
messageId: generateId(), // Dummy messageId
|
||||
kind: 'message', // Dummy kind
|
||||
role: 'agent', // Assuming artifact parts are from agent
|
||||
kind: "message", // Dummy kind
|
||||
role: "agent", // Assuming artifact parts are from agent
|
||||
parts: update.artifact.parts,
|
||||
taskId: update.taskId,
|
||||
contextId: update.contextId,
|
||||
@ -185,38 +128,32 @@ function printAgentEvent(event: TaskStatusUpdateEvent | TaskArtifactUpdateEvent)
|
||||
// This case should ideally not be reached if called correctly
|
||||
console.log(
|
||||
prefix,
|
||||
colorize('yellow', 'Received unknown event type in printAgentEvent:'),
|
||||
colorize("yellow", "Received unknown event type in printAgentEvent:"),
|
||||
event
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function printMessageContent(message: Message) {
|
||||
message.parts.forEach((part: Part, index: number) => {
|
||||
// Added explicit Part type
|
||||
const partPrefix = colorize('red', ` Part ${index + 1}:`);
|
||||
if (part.kind === 'text') {
|
||||
// Check kind property
|
||||
console.log(`${partPrefix} ${colorize('green', '📝 Text:')}`, part.text);
|
||||
} else if (part.kind === 'file') {
|
||||
// Check kind property
|
||||
message.parts.forEach((part: Part, index: number) => { // Added explicit Part type
|
||||
const partPrefix = colorize("red", ` Part ${index + 1}:`);
|
||||
if (part.kind === "text") { // Check kind property
|
||||
console.log(`${partPrefix} ${colorize("green", "📝 Text:")}`, part.text);
|
||||
} else if (part.kind === "file") { // Check kind property
|
||||
const filePart = part as FilePart;
|
||||
console.log(
|
||||
`${partPrefix} ${colorize('blue', '📄 File:')} Name: ${
|
||||
filePart.file.name || 'N/A'
|
||||
}, Type: ${filePart.file.mimeType || 'N/A'}, Source: ${
|
||||
'bytes' in filePart.file ? 'Inline (bytes)' : filePart.file.uri
|
||||
`${partPrefix} ${colorize("blue", "📄 File:")} Name: ${filePart.file.name || "N/A"
|
||||
}, Type: ${filePart.file.mimeType || "N/A"}, Source: ${("bytes" in filePart.file) ? "Inline (bytes)" : filePart.file.uri
|
||||
}`
|
||||
);
|
||||
} else if (part.kind === 'data') {
|
||||
// Check kind property
|
||||
} else if (part.kind === "data") { // Check kind property
|
||||
const dataPart = part as DataPart;
|
||||
console.log(
|
||||
`${partPrefix} ${colorize('yellow', '📊 Data:')}`,
|
||||
`${partPrefix} ${colorize("yellow", "📊 Data:")}`,
|
||||
JSON.stringify(dataPart.data, null, 2)
|
||||
);
|
||||
} else {
|
||||
console.log(`${partPrefix} ${colorize('yellow', 'Unsupported part kind:')}`, part);
|
||||
console.log(`${partPrefix} ${colorize("yellow", "Unsupported part kind:")}`, part);
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -225,86 +162,70 @@ function printMessageContent(message: Message) {
|
||||
async function fetchAndDisplayAgentCard() {
|
||||
// Use the client's getAgentCard method.
|
||||
// The client was initialized with serverUrl, which is the agent's base URL.
|
||||
console.log(colorize('dim', `Attempting to fetch agent card from agent at: ${serverUrl}`));
|
||||
console.log(
|
||||
colorize("dim", `Attempting to fetch agent card from agent at: ${serverUrl}`)
|
||||
);
|
||||
try {
|
||||
// client.getAgentCard() uses the agentBaseUrl provided during client construction
|
||||
const card: AgentCard = await client.getAgentCard();
|
||||
agentName = card.name || 'Agent'; // Update global agent name
|
||||
console.log(colorize('green', `✓ Agent Card Found:`));
|
||||
console.log(` Name: ${colorize('bright', agentName)}`);
|
||||
agentName = card.name || "Agent"; // Update global agent name
|
||||
console.log(colorize("green", `✓ Agent Card Found:`));
|
||||
console.log(` Name: ${colorize("bright", agentName)}`);
|
||||
if (card.description) {
|
||||
console.log(` Description: ${card.description}`);
|
||||
}
|
||||
console.log(` Version: ${card.version || 'N/A'}`);
|
||||
console.log(` Version: ${card.version || "N/A"}`);
|
||||
if (card.capabilities?.streaming) {
|
||||
console.log(` Streaming: ${colorize('green', 'Supported')}`);
|
||||
console.log(` Streaming: ${colorize("green", "Supported")}`);
|
||||
} else {
|
||||
console.log(` Streaming: ${colorize('yellow', 'Not Supported (or not specified)')}`);
|
||||
console.log(` Streaming: ${colorize("yellow", "Not Supported (or not specified)")}`);
|
||||
}
|
||||
|
||||
const supportedTransports = new Set<string>();
|
||||
supportedTransports.add(card.preferredTransport || 'JSONRPC');
|
||||
if (card.additionalInterfaces) {
|
||||
for (const iface of card.additionalInterfaces) {
|
||||
supportedTransports.add(iface.transport);
|
||||
}
|
||||
}
|
||||
console.log(` Supported Transports: ${Array.from(supportedTransports).join(', ')}`);
|
||||
|
||||
// TODO (https://github.com/a2aproject/a2a-js/issues/179): Add a way to get the protocol name from the transport.
|
||||
console.log(
|
||||
colorize(
|
||||
'green',
|
||||
`\n✓ Connected via ${Object.getPrototypeOf(client.transport).constructor.name}`
|
||||
)
|
||||
);
|
||||
// Update prompt prefix to use the fetched name
|
||||
// The prompt is set dynamically before each rl.prompt() call in the main loop
|
||||
// to reflect the current agentName if it changes (though unlikely after initial fetch).
|
||||
} catch (error: any) {
|
||||
console.log(colorize('yellow', `⚠️ Error fetching or parsing agent card`));
|
||||
console.log(
|
||||
colorize("yellow", `⚠️ Error fetching or parsing agent card`)
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Main Loop ---
|
||||
async function main() {
|
||||
console.log(colorize('bright', `A2A Terminal Client`));
|
||||
console.log(colorize('dim', `Agent Base URL: ${serverUrl}`));
|
||||
console.log(colorize("bright", `A2A Terminal Client`));
|
||||
console.log(colorize("dim", `Agent Base URL: ${serverUrl}`));
|
||||
|
||||
await fetchAndDisplayAgentCard(); // Fetch the card before starting the loop
|
||||
|
||||
console.log(colorize("dim", `No active task or context initially. Use '/new' to start a fresh session or send a message.`));
|
||||
console.log(
|
||||
colorize(
|
||||
'dim',
|
||||
`No active task or context initially. Use '/new' to start a fresh session or send a message.`
|
||||
)
|
||||
);
|
||||
console.log(
|
||||
colorize('green', `Enter messages, or use '/new' to start a new session. '/exit' to quit.`)
|
||||
colorize("green", `Enter messages, or use '/new' to start a new session. '/exit' to quit.`)
|
||||
);
|
||||
|
||||
rl.setPrompt(colorize('cyan', `${agentName} > You: `)); // Set initial prompt
|
||||
rl.setPrompt(colorize("cyan", `${agentName} > You: `)); // Set initial prompt
|
||||
rl.prompt();
|
||||
|
||||
rl.on('line', async (line) => {
|
||||
rl.on("line", async (line) => {
|
||||
const input = line.trim();
|
||||
rl.setPrompt(colorize('cyan', `${agentName} > You: `)); // Ensure prompt reflects current agentName
|
||||
rl.setPrompt(colorize("cyan", `${agentName} > You: `)); // Ensure prompt reflects current agentName
|
||||
|
||||
if (!input) {
|
||||
rl.prompt();
|
||||
return;
|
||||
}
|
||||
|
||||
if (input.toLowerCase() === '/new') {
|
||||
if (input.toLowerCase() === "/new") {
|
||||
currentTaskId = undefined;
|
||||
currentContextId = undefined; // Reset contextId on /new
|
||||
console.log(colorize('bright', `✨ Starting new session. Task and Context IDs are cleared.`));
|
||||
console.log(
|
||||
colorize("bright", `✨ Starting new session. Task and Context IDs are cleared.`)
|
||||
);
|
||||
rl.prompt();
|
||||
return;
|
||||
}
|
||||
|
||||
if (input.toLowerCase() === '/exit') {
|
||||
if (input.toLowerCase() === "/exit") {
|
||||
rl.close();
|
||||
return;
|
||||
}
|
||||
@ -314,11 +235,11 @@ async function main() {
|
||||
|
||||
const messagePayload: Message = {
|
||||
messageId: messageId,
|
||||
kind: 'message', // Required by Message interface
|
||||
role: 'user',
|
||||
kind: "message", // Required by Message interface
|
||||
role: "user",
|
||||
parts: [
|
||||
{
|
||||
kind: 'text', // Required by TextPart interface
|
||||
kind: "text", // Required by TextPart interface
|
||||
text: input,
|
||||
},
|
||||
],
|
||||
@ -333,6 +254,7 @@ async function main() {
|
||||
messagePayload.contextId = currentContextId;
|
||||
}
|
||||
|
||||
|
||||
const params: MessageSendParams = {
|
||||
message: messagePayload,
|
||||
// Optional: configuration for streaming, blocking, etc.
|
||||
@ -343,109 +265,93 @@ async function main() {
|
||||
};
|
||||
|
||||
try {
|
||||
console.log(colorize('red', 'Sending message...'));
|
||||
console.log(colorize("red", "Sending message..."));
|
||||
// Use sendMessageStream
|
||||
const stream = client.sendMessageStream(params);
|
||||
|
||||
// Iterate over the events from the stream
|
||||
for await (const event of stream) {
|
||||
const timestamp = new Date().toLocaleTimeString(); // Get fresh timestamp for each event
|
||||
const prefix = colorize('magenta', `\n${agentName} [${timestamp}]:`);
|
||||
const prefix = colorize("magenta", `\n${agentName} [${timestamp}]:`);
|
||||
|
||||
if (event.kind === 'status-update' || event.kind === 'artifact-update') {
|
||||
if (event.kind === "status-update" || event.kind === "artifact-update") {
|
||||
const typedEvent = event as TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
|
||||
printAgentEvent(typedEvent);
|
||||
|
||||
// If the event is a TaskStatusUpdateEvent and it's final, reset currentTaskId
|
||||
if (
|
||||
typedEvent.kind === 'status-update' &&
|
||||
(typedEvent as TaskStatusUpdateEvent).final &&
|
||||
(typedEvent as TaskStatusUpdateEvent).status.state !== 'input-required'
|
||||
) {
|
||||
console.log(
|
||||
colorize('yellow', ` Task ${typedEvent.taskId} is final. Clearing current task ID.`)
|
||||
);
|
||||
if (typedEvent.kind === "status-update" && (typedEvent as TaskStatusUpdateEvent).final && (typedEvent as TaskStatusUpdateEvent).status.state !== "input-required") {
|
||||
console.log(colorize("yellow", ` Task ${typedEvent.taskId} is final. Clearing current task ID.`));
|
||||
currentTaskId = undefined;
|
||||
// Optionally, you might want to clear currentContextId as well if a task ending implies context ending.
|
||||
// currentContextId = undefined;
|
||||
// currentContextId = undefined;
|
||||
// console.log(colorize("dim", ` Context ID also cleared as task is final.`));
|
||||
}
|
||||
} else if (event.kind === 'message') {
|
||||
|
||||
} else if (event.kind === "message") {
|
||||
const msg = event as Message;
|
||||
console.log(`${prefix} ${colorize('green', '✉️ Message Stream Event:')}`);
|
||||
console.log(`${prefix} ${colorize("green", "✉️ Message Stream Event:")}`);
|
||||
printMessageContent(msg);
|
||||
if (msg.taskId && msg.taskId !== currentTaskId) {
|
||||
console.log(
|
||||
colorize('dim', ` Task ID context updated to ${msg.taskId} based on message event.`)
|
||||
);
|
||||
console.log(colorize("dim", ` Task ID context updated to ${msg.taskId} based on message event.`));
|
||||
currentTaskId = msg.taskId;
|
||||
}
|
||||
if (msg.contextId && msg.contextId !== currentContextId) {
|
||||
console.log(
|
||||
colorize('dim', ` Context ID updated to ${msg.contextId} based on message event.`)
|
||||
);
|
||||
console.log(colorize("dim", ` Context ID updated to ${msg.contextId} based on message event.`));
|
||||
currentContextId = msg.contextId;
|
||||
}
|
||||
} else if (event.kind === 'task') {
|
||||
} else if (event.kind === "task") {
|
||||
const task = event as Task;
|
||||
console.log(
|
||||
`${prefix} ${colorize('blue', 'ℹ️ Task Stream Event:')} ID: ${task.id}, Context: ${task.contextId}, Status: ${task.status.state}`
|
||||
);
|
||||
console.log(`${prefix} ${colorize("blue", "ℹ️ Task Stream Event:")} ID: ${task.id}, Context: ${task.contextId}, Status: ${task.status.state}`);
|
||||
if (task.id !== currentTaskId) {
|
||||
console.log(
|
||||
colorize('dim', ` Task ID updated from ${currentTaskId || 'N/A'} to ${task.id}`)
|
||||
);
|
||||
console.log(colorize("dim", ` Task ID updated from ${currentTaskId || 'N/A'} to ${task.id}`));
|
||||
currentTaskId = task.id;
|
||||
}
|
||||
if (task.contextId && task.contextId !== currentContextId) {
|
||||
console.log(
|
||||
colorize(
|
||||
'dim',
|
||||
` Context ID updated from ${currentContextId || 'N/A'} to ${task.contextId}`
|
||||
)
|
||||
);
|
||||
console.log(colorize("dim", ` Context ID updated from ${currentContextId || 'N/A'} to ${task.contextId}`));
|
||||
currentContextId = task.contextId;
|
||||
}
|
||||
if (task.status.message) {
|
||||
console.log(colorize('gray', ' Task includes message:'));
|
||||
console.log(colorize("gray", " Task includes message:"));
|
||||
printMessageContent(task.status.message);
|
||||
}
|
||||
if (task.artifacts && task.artifacts.length > 0) {
|
||||
console.log(colorize('gray', ` Task includes ${task.artifacts.length} artifact(s).`));
|
||||
console.log(colorize("gray", ` Task includes ${task.artifacts.length} artifact(s).`));
|
||||
}
|
||||
} else {
|
||||
console.log(
|
||||
prefix,
|
||||
colorize('yellow', 'Received unknown event structure from stream:'),
|
||||
event
|
||||
);
|
||||
console.log(prefix, colorize("yellow", "Received unknown event structure from stream:"), event);
|
||||
}
|
||||
}
|
||||
console.log(colorize('dim', `--- End of response stream for this input ---`));
|
||||
console.log(colorize("dim", `--- End of response stream for this input ---`));
|
||||
} catch (error: any) {
|
||||
const timestamp = new Date().toLocaleTimeString();
|
||||
const prefix = colorize('red', `\n${agentName} [${timestamp}] ERROR:`);
|
||||
console.error(prefix, `Error communicating with agent:`, error.message || error);
|
||||
const prefix = colorize("red", `\n${agentName} [${timestamp}] ERROR:`);
|
||||
console.error(
|
||||
prefix,
|
||||
`Error communicating with agent:`,
|
||||
error.message || error
|
||||
);
|
||||
if (error.code) {
|
||||
console.error(colorize('gray', ` Code: ${error.code}`));
|
||||
console.error(colorize("gray", ` Code: ${error.code}`));
|
||||
}
|
||||
if (error.data) {
|
||||
console.error(colorize('gray', ` Data: ${JSON.stringify(error.data)}`));
|
||||
console.error(
|
||||
colorize("gray", ` Data: ${JSON.stringify(error.data)}`)
|
||||
);
|
||||
}
|
||||
if (!(error.code || error.data) && error.stack) {
|
||||
console.error(colorize('gray', error.stack.split('\n').slice(1, 3).join('\n')));
|
||||
console.error(colorize("gray", error.stack.split('\n').slice(1, 3).join('\n')));
|
||||
}
|
||||
} finally {
|
||||
rl.prompt();
|
||||
}
|
||||
}).on('close', () => {
|
||||
console.log(colorize('yellow', '\nExiting A2A Terminal Client. Goodbye!'));
|
||||
}).on("close", () => {
|
||||
console.log(colorize("yellow", "\nExiting A2A Terminal Client. Goodbye!"));
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
|
||||
// --- Start ---
|
||||
main().catch((err) => {
|
||||
console.error(colorize('red', 'Unhandled error in main:'), err);
|
||||
main().catch(err => {
|
||||
console.error(colorize("red", "Unhandled error in main:"), err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@ -1,75 +0,0 @@
|
||||
# Extension
|
||||
|
||||
This configuration is using a sample agent to test the extension feature integration. It uses the sample agent executor defined in `agents/sample-agent`, with a modified agent card which includes the support for extensions.
|
||||
The `extensions.ts` adds a timestamp in the metadata of the `TaskStatusUpdateEvent` Message.
|
||||
|
||||
To run the agent:
|
||||
|
||||
```bash
|
||||
npm run agents:extension-agent
|
||||
```
|
||||
|
||||
The agent will start on `http://localhost:41241`.
|
||||
|
||||
To test the extension:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:41241/
|
||||
-H "X-A2A-Extensions: https://github.com/a2aproject/a2a-js/src/samples/extensions/v1"
|
||||
-H "Content-Type: application/json"
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "message/send",
|
||||
"params": {
|
||||
"message": {
|
||||
"role": "user",
|
||||
"parts": [
|
||||
{
|
||||
"kind": "text",
|
||||
"text": "Hello how are you?"
|
||||
}
|
||||
],
|
||||
"messageId": "9229e770-767c-417b-a0b0-f0741243c589"
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
Expected simplified response:
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"result": {
|
||||
"kind": "task",
|
||||
"status": {
|
||||
"state": "completed",
|
||||
"message": {
|
||||
...
|
||||
"metadata": {
|
||||
"timestamp": "2025-11-14T15:51:36.725Z" // Timestamp added to metadata on the 'completed' TaskStatusUpdateEvent
|
||||
}
|
||||
},
|
||||
},
|
||||
"history": [
|
||||
{
|
||||
...
|
||||
},
|
||||
{
|
||||
...
|
||||
"metadata": {
|
||||
"timestamp": "2025-11-14T15:51:35.722Z" // Timestamp added to metadata on the 'running' TaskStatusUpdateEvent
|
||||
}
|
||||
},
|
||||
{
|
||||
...
|
||||
"metadata": {
|
||||
"timestamp": "2025-11-14T15:51:36.725Z" // Timestamp added to metadata on the 'completed' TaskStatusUpdateEvent
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
@ -1,96 +0,0 @@
|
||||
import {
|
||||
AgentExecutor,
|
||||
RequestContext,
|
||||
ExecutionEventBus,
|
||||
AgentExecutionEvent,
|
||||
} from '../../server/index.js';
|
||||
import { TaskStatusUpdateEvent } from '../../types.js';
|
||||
|
||||
const URI = 'https://github.com/a2aproject/a2a-js/src/samples/extensions/v1';
|
||||
|
||||
class TimeStampExtension {
|
||||
activate(context: RequestContext): boolean {
|
||||
const serverContext = context.context;
|
||||
if (serverContext?.requestedExtensions?.includes(URI)) {
|
||||
serverContext.addActivatedExtension(URI);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
timestampEvent(event: AgentExecutionEvent): void {
|
||||
if (event.kind === 'status-update') {
|
||||
const statusUpdateEvent = event as TaskStatusUpdateEvent;
|
||||
if (statusUpdateEvent.status.message) {
|
||||
if (!statusUpdateEvent.status.message.metadata) {
|
||||
statusUpdateEvent.status.message.metadata = {};
|
||||
}
|
||||
statusUpdateEvent.status.message.metadata['timestamp'] = new Date().toISOString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class TimestampingAgentExecutor implements AgentExecutor {
|
||||
private readonly _delegate: AgentExecutor;
|
||||
private readonly _ext: TimeStampExtension;
|
||||
|
||||
constructor(delegate: AgentExecutor, ext: TimeStampExtension = new TimeStampExtension()) {
|
||||
this._delegate = delegate;
|
||||
this._ext = ext;
|
||||
}
|
||||
|
||||
async execute(context: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
return await this._delegate.execute(context, this._maybeWrapQueue(context, eventBus));
|
||||
}
|
||||
|
||||
_maybeWrapQueue(context: RequestContext, eventBus: ExecutionEventBus): ExecutionEventBus {
|
||||
if (this._ext.activate(context)) {
|
||||
return new TimestampingEventQueue(eventBus, this._ext);
|
||||
}
|
||||
return eventBus;
|
||||
}
|
||||
|
||||
async cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise<void> {
|
||||
return await this._delegate.cancelTask(taskId, eventBus);
|
||||
}
|
||||
}
|
||||
|
||||
class TimestampingEventQueue implements ExecutionEventBus {
|
||||
private readonly _delegate: ExecutionEventBus;
|
||||
private readonly _ext: TimeStampExtension;
|
||||
|
||||
constructor(delegate: ExecutionEventBus, ext: TimeStampExtension) {
|
||||
this._delegate = delegate;
|
||||
this._ext = ext;
|
||||
}
|
||||
|
||||
publish(event: AgentExecutionEvent): void {
|
||||
this._ext.timestampEvent(event);
|
||||
this._delegate.publish(event);
|
||||
}
|
||||
|
||||
finished(): void {
|
||||
this._delegate.finished();
|
||||
}
|
||||
|
||||
on(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this {
|
||||
this._delegate.on(eventName, listener);
|
||||
return this;
|
||||
}
|
||||
|
||||
off(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this {
|
||||
this._delegate.off(eventName, listener);
|
||||
return this;
|
||||
}
|
||||
|
||||
once(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this {
|
||||
this._delegate.once(eventName, listener);
|
||||
return this;
|
||||
}
|
||||
|
||||
removeAllListeners(eventName?: 'event' | 'finished'): this {
|
||||
this._delegate.removeAllListeners(eventName);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@ -1,88 +0,0 @@
|
||||
import express from 'express';
|
||||
|
||||
import { AGENT_CARD_PATH, AgentCard } from '../../index.js';
|
||||
import {
|
||||
InMemoryTaskStore,
|
||||
TaskStore,
|
||||
AgentExecutor,
|
||||
DefaultRequestHandler,
|
||||
} from '../../server/index.js';
|
||||
import { jsonRpcHandler, agentCardHandler, UserBuilder } from '../../server/express/index.js';
|
||||
import { TimestampingAgentExecutor } from './extensions.js';
|
||||
import { SampleAgentExecutor } from '../agents/sample-agent/agent_executor.js';
|
||||
|
||||
// --- Server Setup ---
|
||||
|
||||
const extensionAgentCard: AgentCard = {
|
||||
name: 'Sample Agent with timestamp extensions',
|
||||
description:
|
||||
'A sample agent to test the stream functionality and simulate the flow of tasks statuses, with extensions integration.',
|
||||
url: 'http://localhost:41241/',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples', // Added provider URL
|
||||
},
|
||||
version: '1.0.0', // Incremented version
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
extensions: [{ uri: 'https://github.com/a2aproject/a2a-js/src/samples/extensions/v1' }],
|
||||
streaming: true, // The new framework supports streaming
|
||||
pushNotifications: false, // Assuming not implemented for this agent yet
|
||||
stateTransitionHistory: true, // Agent uses history
|
||||
},
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text', 'task-status'], // task-status is a common output mode
|
||||
skills: [
|
||||
{
|
||||
id: 'sample_agent',
|
||||
name: 'Sample Agent with extensions',
|
||||
description: 'Simulate the general flow of a streaming agent with extensions integration.',
|
||||
tags: ['sample'],
|
||||
examples: ['hi', 'hello world', 'how are you', 'goodbye'],
|
||||
inputModes: ['text'], // Explicitly defining for skill
|
||||
outputModes: ['text', 'task-status'], // Explicitly defining for skill
|
||||
},
|
||||
],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// 1. Create TaskStore
|
||||
const taskStore: TaskStore = new InMemoryTaskStore();
|
||||
|
||||
// 2. Create AgentExecutor
|
||||
const agentExecutor: AgentExecutor = new SampleAgentExecutor();
|
||||
|
||||
// 3. Use the TimestampingAgentExecutor to wrap the AgentExecutor
|
||||
const timestampAgentExecutor: AgentExecutor = new TimestampingAgentExecutor(agentExecutor);
|
||||
|
||||
// 4. Create DefaultRequestHandler
|
||||
const requestHandler = new DefaultRequestHandler(
|
||||
extensionAgentCard,
|
||||
taskStore,
|
||||
timestampAgentExecutor
|
||||
);
|
||||
|
||||
// 5. Create and setup Express.js app
|
||||
const app = express();
|
||||
|
||||
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
|
||||
app.use(jsonRpcHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
|
||||
|
||||
// 6. Start the server
|
||||
const PORT = process.env.PORT || 41241;
|
||||
app.listen(PORT, (err) => {
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
console.log(
|
||||
`[ExtensionsSampleAgent] Server using new framework started on http://localhost:${PORT}`
|
||||
);
|
||||
console.log(
|
||||
`[ExtensionsSampleAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`
|
||||
);
|
||||
console.log('[ExtensionsSampleAgent] Press Ctrl+C to stop the server');
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
7928
src/samples/package-lock.json
generated
7928
src/samples/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -1,28 +0,0 @@
|
||||
{
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"a2a:cli": "tsx cli.ts",
|
||||
"agents:movie-agent": "tsx agents/movie-agent/index.ts",
|
||||
"agents:sample-agent": "tsx agents/sample-agent/index.ts",
|
||||
"agents:extension-agent": "tsx extensions/index.ts",
|
||||
"agents:authentication-agent": "tsx authentication/index.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@genkit-ai/googleai": "^1.8.0",
|
||||
"@types/express": "^5.0.5",
|
||||
"@types/passport": "^1.0.17",
|
||||
"@types/passport-jwt": "^4.0.1",
|
||||
"express": "^5.1.0",
|
||||
"genkit": "^1.8.0",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"tsx": "^4.19.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@bufbuild/protobuf": "^2.10.2",
|
||||
"@grpc/grpc-js": "^1.14.3",
|
||||
"google-auth-library": "^10.5.0",
|
||||
"uuid": "^11.1.0"
|
||||
}
|
||||
}
|
||||
@ -1,20 +1,26 @@
|
||||
import { ExecutionEventBus } from '../events/execution_event_bus.js';
|
||||
import { RequestContext } from './request_context.js';
|
||||
import { ExecutionEventBus } from "../events/execution_event_bus.js";
|
||||
import { RequestContext } from "./request_context.js";
|
||||
|
||||
export interface AgentExecutor {
|
||||
/**
|
||||
* Executes the agent logic based on the request context and publishes events.
|
||||
* @param requestContext The context of the current request.
|
||||
* @param eventBus The bus to publish execution events to.
|
||||
*/
|
||||
execute: (requestContext: RequestContext, eventBus: ExecutionEventBus) => Promise<void>;
|
||||
/**
|
||||
* Executes the agent logic based on the request context and publishes events.
|
||||
* @param requestContext The context of the current request.
|
||||
* @param eventBus The bus to publish execution events to.
|
||||
*/
|
||||
execute: (
|
||||
requestContext: RequestContext,
|
||||
eventBus: ExecutionEventBus
|
||||
) => Promise<void>;
|
||||
|
||||
/**
|
||||
* Method to explicitly cancel a running task.
|
||||
* The implementation should handle the logic of stopping the execution
|
||||
* and publishing the final 'canceled' status event on the provided event bus.
|
||||
* @param taskId The ID of the task to cancel.
|
||||
* @param eventBus The event bus associated with the task's execution.
|
||||
*/
|
||||
cancelTask: (taskId: string, eventBus: ExecutionEventBus) => Promise<void>;
|
||||
/**
|
||||
* Method to explicitly cancel a running task.
|
||||
* The implementation should handle the logic of stopping the execution
|
||||
* and publishing the final 'canceled' status event on the provided event bus.
|
||||
* @param taskId The ID of the task to cancel.
|
||||
* @param eventBus The event bus associated with the task's execution.
|
||||
*/
|
||||
cancelTask: (
|
||||
taskId: string,
|
||||
eventBus: ExecutionEventBus
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
@ -1,27 +1,26 @@
|
||||
import { Message, Task } from '../../types.js';
|
||||
import { ServerCallContext } from '../context.js';
|
||||
import {
|
||||
Message,
|
||||
Task,
|
||||
} from "../../types.js";
|
||||
|
||||
export class RequestContext {
|
||||
public readonly userMessage: Message;
|
||||
public readonly taskId: string;
|
||||
public readonly contextId: string;
|
||||
public readonly task?: Task;
|
||||
public readonly referenceTasks?: Task[];
|
||||
public readonly context?: ServerCallContext;
|
||||
public readonly userMessage: Message;
|
||||
public readonly task?: Task;
|
||||
public readonly referenceTasks?: Task[];
|
||||
public readonly taskId: string;
|
||||
public readonly contextId: string;
|
||||
|
||||
constructor(
|
||||
userMessage: Message,
|
||||
taskId: string,
|
||||
contextId: string,
|
||||
task?: Task,
|
||||
referenceTasks?: Task[],
|
||||
context?: ServerCallContext
|
||||
) {
|
||||
this.userMessage = userMessage;
|
||||
this.taskId = taskId;
|
||||
this.contextId = contextId;
|
||||
this.task = task;
|
||||
this.referenceTasks = referenceTasks;
|
||||
this.context = context;
|
||||
}
|
||||
}
|
||||
constructor(
|
||||
userMessage: Message,
|
||||
taskId: string,
|
||||
contextId: string,
|
||||
task?: Task,
|
||||
referenceTasks?: Task[],
|
||||
) {
|
||||
this.userMessage = userMessage;
|
||||
this.taskId = taskId;
|
||||
this.contextId = contextId;
|
||||
this.task = task;
|
||||
this.referenceTasks = referenceTasks;
|
||||
}
|
||||
}
|
||||
@ -1,27 +0,0 @@
|
||||
/**
|
||||
* Represents a user accessing A2A server.
|
||||
*/
|
||||
export interface User {
|
||||
/**
|
||||
* Indicates whether the user is authenticated.
|
||||
*/
|
||||
get isAuthenticated(): boolean;
|
||||
|
||||
/**
|
||||
* A unique name (identifier) for the user.
|
||||
*/
|
||||
get userName(): string;
|
||||
}
|
||||
|
||||
/**
|
||||
* An implementation of {@link User} representing an unauthenticated user.
|
||||
*/
|
||||
export class UnauthenticatedUser implements User {
|
||||
get isAuthenticated(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
get userName(): string {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@ -1,29 +0,0 @@
|
||||
import { Extensions } from '../extensions.js';
|
||||
import { User } from './authentication/user.js';
|
||||
|
||||
export class ServerCallContext {
|
||||
private readonly _requestedExtensions?: Extensions;
|
||||
private readonly _user?: User;
|
||||
private _activatedExtensions?: Extensions;
|
||||
|
||||
constructor(requestedExtensions?: Extensions, user?: User) {
|
||||
this._requestedExtensions = requestedExtensions;
|
||||
this._user = user;
|
||||
}
|
||||
|
||||
get user(): User | undefined {
|
||||
return this._user;
|
||||
}
|
||||
|
||||
get activatedExtensions(): Extensions | undefined {
|
||||
return this._activatedExtensions;
|
||||
}
|
||||
|
||||
get requestedExtensions(): Extensions | undefined {
|
||||
return this._requestedExtensions;
|
||||
}
|
||||
|
||||
public addActivatedExtension(uri: string) {
|
||||
this._activatedExtensions = Extensions.createFrom(this._activatedExtensions, uri);
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
import * as schema from '../types.js';
|
||||
import * as schema from "../types.js";
|
||||
|
||||
/**
|
||||
* Custom error class for A2A server operations, incorporating JSON-RPC error codes.
|
||||
@ -8,9 +8,14 @@ export class A2AError extends Error {
|
||||
public data?: Record<string, unknown>;
|
||||
public taskId?: string; // Optional task ID context
|
||||
|
||||
constructor(code: number, message: string, data?: Record<string, unknown>, taskId?: string) {
|
||||
constructor(
|
||||
code: number,
|
||||
message: string,
|
||||
data?: Record<string, unknown>,
|
||||
taskId?: string
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'A2AError';
|
||||
this.name = "A2AError";
|
||||
this.code = code;
|
||||
this.data = data;
|
||||
this.taskId = taskId; // Store associated task ID if provided
|
||||
@ -25,10 +30,10 @@ export class A2AError extends Error {
|
||||
message: this.message,
|
||||
};
|
||||
|
||||
if (this.data !== undefined) {
|
||||
if(this.data !== undefined) {
|
||||
errorObject.data = this.data;
|
||||
}
|
||||
|
||||
|
||||
return errorObject;
|
||||
}
|
||||
|
||||
@ -43,7 +48,10 @@ export class A2AError extends Error {
|
||||
}
|
||||
|
||||
static methodNotFound(method: string): A2AError {
|
||||
return new A2AError(-32601, `Method not found: ${method}`);
|
||||
return new A2AError(
|
||||
-32601,
|
||||
`Method not found: ${method}`
|
||||
);
|
||||
}
|
||||
|
||||
static invalidParams(message: string, data?: Record<string, unknown>): A2AError {
|
||||
@ -55,22 +63,41 @@ export class A2AError extends Error {
|
||||
}
|
||||
|
||||
static taskNotFound(taskId: string): A2AError {
|
||||
return new A2AError(-32001, `Task not found: ${taskId}`, undefined, taskId);
|
||||
return new A2AError(
|
||||
-32001,
|
||||
`Task not found: ${taskId}`,
|
||||
undefined,
|
||||
taskId
|
||||
);
|
||||
}
|
||||
|
||||
static taskNotCancelable(taskId: string): A2AError {
|
||||
return new A2AError(-32002, `Task not cancelable: ${taskId}`, undefined, taskId);
|
||||
return new A2AError(
|
||||
-32002,
|
||||
`Task not cancelable: ${taskId}`,
|
||||
undefined,
|
||||
taskId
|
||||
);
|
||||
}
|
||||
|
||||
static pushNotificationNotSupported(): A2AError {
|
||||
return new A2AError(-32003, 'Push Notification is not supported');
|
||||
return new A2AError(
|
||||
-32003,
|
||||
"Push Notification is not supported"
|
||||
);
|
||||
}
|
||||
|
||||
static unsupportedOperation(operation: string): A2AError {
|
||||
return new A2AError(-32004, `Unsupported operation: ${operation}`);
|
||||
return new A2AError(
|
||||
-32004,
|
||||
`Unsupported operation: ${operation}`
|
||||
);
|
||||
}
|
||||
|
||||
static authenticatedExtendedCardNotConfigured(): A2AError {
|
||||
return new A2AError(-32007, `Extended card not configured.`);
|
||||
return new A2AError(
|
||||
-32007,
|
||||
`Extended card not configured.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,278 +1,37 @@
|
||||
import { Message, Task, TaskStatusUpdateEvent, TaskArtifactUpdateEvent } from '../../types.js';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
export type AgentExecutionEvent = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
|
||||
import {
|
||||
Message,
|
||||
Task,
|
||||
TaskStatusUpdateEvent,
|
||||
TaskArtifactUpdateEvent,
|
||||
} from "../../types.js";
|
||||
|
||||
/**
|
||||
* Event names supported by ExecutionEventBus.
|
||||
*/
|
||||
export type ExecutionEventName = 'event' | 'finished';
|
||||
export type AgentExecutionEvent =
|
||||
| Message
|
||||
| Task
|
||||
| TaskStatusUpdateEvent
|
||||
| TaskArtifactUpdateEvent;
|
||||
|
||||
export interface ExecutionEventBus {
|
||||
publish(event: AgentExecutionEvent): void;
|
||||
on(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this;
|
||||
off(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this;
|
||||
once(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this;
|
||||
removeAllListeners(eventName?: ExecutionEventName): this;
|
||||
finished(): void;
|
||||
publish(event: AgentExecutionEvent): void;
|
||||
on(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this;
|
||||
off(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this;
|
||||
once(eventName: 'event' | 'finished', listener: (event: AgentExecutionEvent) => void): this;
|
||||
removeAllListeners(eventName?: 'event' | 'finished'): this;
|
||||
finished(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* CustomEvent polyfill for Node.js 15-18 (CustomEvent was added globally in Node.js 19).
|
||||
* In browsers and modern edge runtimes, CustomEvent is already available globally.
|
||||
* Per the spec, detail defaults to null when not provided.
|
||||
*/
|
||||
const CustomEventImpl: typeof CustomEvent =
|
||||
typeof CustomEvent !== 'undefined'
|
||||
? CustomEvent
|
||||
: (class CustomEventPolyfill<T> extends Event {
|
||||
readonly detail: T;
|
||||
constructor(type: string, eventInitDict?: CustomEventInit<T>) {
|
||||
super(type, eventInitDict);
|
||||
this.detail = (eventInitDict?.detail ?? null) as T;
|
||||
}
|
||||
} as typeof CustomEvent);
|
||||
export class DefaultExecutionEventBus extends EventEmitter implements ExecutionEventBus {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Listener type matching the ExecutionEventBus interface.
|
||||
*/
|
||||
type Listener = (event: AgentExecutionEvent) => void;
|
||||
publish(event: AgentExecutionEvent): void {
|
||||
this.emit('event', event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Type for wrapped listener functions registered with EventTarget.
|
||||
*/
|
||||
type WrappedListener = (e: Event) => void;
|
||||
|
||||
/**
|
||||
* Type guard to narrow Event to CustomEvent with AgentExecutionEvent payload.
|
||||
* This guard should always pass for 'event' type events since we control
|
||||
* the dispatch via publish(). If it fails, there's a bug in the implementation.
|
||||
*/
|
||||
function isAgentExecutionCustomEvent(e: Event): e is CustomEvent<AgentExecutionEvent> {
|
||||
return e instanceof CustomEventImpl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Web-compatible ExecutionEventBus using EventTarget.
|
||||
* Works across all modern runtimes: Node.js 15+, browsers, Cloudflare Workers, Deno, Bun.
|
||||
*
|
||||
* This implementation provides the subset of EventEmitter methods defined in the
|
||||
* ExecutionEventBus interface. Users extending DefaultExecutionEventBus should note
|
||||
* that other EventEmitter methods (e.g., listenerCount, rawListeners) are not available.
|
||||
*/
|
||||
export class DefaultExecutionEventBus extends EventTarget implements ExecutionEventBus {
|
||||
// Separate storage for each event type - both use the interface's Listener type
|
||||
// but are invoked differently (with event payload vs. no arguments)
|
||||
private readonly eventListeners: Map<Listener, WrappedListener[]> = new Map();
|
||||
private readonly finishedListeners: Map<Listener, WrappedListener[]> = new Map();
|
||||
|
||||
publish(event: AgentExecutionEvent): void {
|
||||
this.dispatchEvent(new CustomEventImpl('event', { detail: event }));
|
||||
}
|
||||
|
||||
finished(): void {
|
||||
this.dispatchEvent(new Event('finished'));
|
||||
}
|
||||
|
||||
/**
|
||||
* EventEmitter-compatible 'on' method.
|
||||
* Wraps the listener to extract event detail from CustomEvent.
|
||||
* Supports multiple registrations of the same listener (like EventEmitter).
|
||||
* @param eventName The event name to listen for.
|
||||
* @param listener The callback function to invoke when the event is emitted.
|
||||
* @returns This instance for method chaining.
|
||||
*/
|
||||
on(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this {
|
||||
if (eventName === 'event') {
|
||||
this.addEventListenerInternal(listener);
|
||||
} else {
|
||||
this.addFinishedListenerInternal(listener);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* EventEmitter-compatible 'off' method.
|
||||
* Uses the stored wrapped listener for proper removal.
|
||||
* Removes at most one instance of a listener per call (like EventEmitter).
|
||||
* @param eventName The event name to stop listening for.
|
||||
* @param listener The callback function to remove.
|
||||
* @returns This instance for method chaining.
|
||||
*/
|
||||
off(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this {
|
||||
if (eventName === 'event') {
|
||||
this.removeEventListenerInternal(listener);
|
||||
} else {
|
||||
this.removeFinishedListenerInternal(listener);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* EventEmitter-compatible 'once' method.
|
||||
* Listener is automatically removed after first invocation.
|
||||
* Supports multiple registrations of the same listener (like EventEmitter).
|
||||
* @param eventName The event name to listen for once.
|
||||
* @param listener The callback function to invoke when the event is emitted.
|
||||
* @returns This instance for method chaining.
|
||||
*/
|
||||
once(eventName: ExecutionEventName, listener: (event: AgentExecutionEvent) => void): this {
|
||||
if (eventName === 'event') {
|
||||
this.addEventListenerOnceInternal(listener);
|
||||
} else {
|
||||
this.addFinishedListenerOnceInternal(listener);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* EventEmitter-compatible 'removeAllListeners' method.
|
||||
* Removes all listeners for a specific event or all events.
|
||||
* @param eventName Optional event name to remove listeners for. If omitted, removes all.
|
||||
* @returns This instance for method chaining.
|
||||
*/
|
||||
removeAllListeners(eventName?: ExecutionEventName): this {
|
||||
if (eventName === undefined || eventName === 'event') {
|
||||
for (const wrappedListeners of this.eventListeners.values()) {
|
||||
for (const wrapped of wrappedListeners) {
|
||||
this.removeEventListener('event', wrapped);
|
||||
}
|
||||
}
|
||||
this.eventListeners.clear();
|
||||
}
|
||||
|
||||
if (eventName === undefined || eventName === 'finished') {
|
||||
for (const wrappedListeners of this.finishedListeners.values()) {
|
||||
for (const wrapped of wrappedListeners) {
|
||||
this.removeEventListener('finished', wrapped);
|
||||
}
|
||||
}
|
||||
this.finishedListeners.clear();
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// ========================
|
||||
// Helper methods for listener tracking
|
||||
// ========================
|
||||
|
||||
/**
|
||||
* Adds a wrapped listener to the tracking map.
|
||||
*/
|
||||
private trackListener(
|
||||
listenerMap: Map<Listener, WrappedListener[]>,
|
||||
listener: Listener,
|
||||
wrapped: WrappedListener
|
||||
): void {
|
||||
const existing = listenerMap.get(listener);
|
||||
if (existing) {
|
||||
existing.push(wrapped);
|
||||
} else {
|
||||
listenerMap.set(listener, [wrapped]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a wrapped listener from the tracking map (for once cleanup).
|
||||
*/
|
||||
private untrackWrappedListener(
|
||||
listenerMap: Map<Listener, WrappedListener[]>,
|
||||
listener: Listener,
|
||||
wrapped: WrappedListener
|
||||
): void {
|
||||
const wrappedList = listenerMap.get(listener);
|
||||
if (wrappedList && wrappedList.length > 0) {
|
||||
const index = wrappedList.indexOf(wrapped);
|
||||
if (index !== -1) {
|
||||
wrappedList.splice(index, 1);
|
||||
if (wrappedList.length === 0) {
|
||||
listenerMap.delete(listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========================
|
||||
// Internal methods for 'event' listeners
|
||||
// ========================
|
||||
|
||||
private addEventListenerInternal(listener: Listener): void {
|
||||
const wrapped: WrappedListener = (e: Event) => {
|
||||
if (!isAgentExecutionCustomEvent(e)) {
|
||||
throw new Error('Internal error: expected CustomEvent for "event" type');
|
||||
}
|
||||
listener.call(this, e.detail);
|
||||
};
|
||||
|
||||
this.trackListener(this.eventListeners, listener, wrapped);
|
||||
this.addEventListener('event', wrapped);
|
||||
}
|
||||
|
||||
private removeEventListenerInternal(listener: Listener): void {
|
||||
const wrappedList = this.eventListeners.get(listener);
|
||||
if (wrappedList && wrappedList.length > 0) {
|
||||
const wrapped = wrappedList.pop()!;
|
||||
if (wrappedList.length === 0) {
|
||||
this.eventListeners.delete(listener);
|
||||
}
|
||||
this.removeEventListener('event', wrapped);
|
||||
}
|
||||
}
|
||||
|
||||
private addEventListenerOnceInternal(listener: Listener): void {
|
||||
const wrapped: WrappedListener = (e: Event) => {
|
||||
// Validate first before any state changes
|
||||
if (!isAgentExecutionCustomEvent(e)) {
|
||||
throw new Error('Internal error: expected CustomEvent for "event" type');
|
||||
}
|
||||
|
||||
// Clean up tracking
|
||||
this.untrackWrappedListener(this.eventListeners, listener, wrapped);
|
||||
|
||||
listener.call(this, e.detail);
|
||||
};
|
||||
|
||||
this.trackListener(this.eventListeners, listener, wrapped);
|
||||
this.addEventListener('event', wrapped, { once: true });
|
||||
}
|
||||
|
||||
// ========================
|
||||
// Internal methods for 'finished' listeners
|
||||
// ========================
|
||||
// The interface declares listeners as (event: AgentExecutionEvent) => void,
|
||||
// but for 'finished' events they are invoked with no arguments (EventEmitter behavior).
|
||||
// We use Function.prototype.call to invoke with `this` as the event bus (matching
|
||||
// EventEmitter semantics) and no arguments, which is type-safe.
|
||||
|
||||
private addFinishedListenerInternal(listener: Listener): void {
|
||||
const wrapped: WrappedListener = () => {
|
||||
listener.call(this);
|
||||
};
|
||||
|
||||
this.trackListener(this.finishedListeners, listener, wrapped);
|
||||
this.addEventListener('finished', wrapped);
|
||||
}
|
||||
|
||||
private removeFinishedListenerInternal(listener: Listener): void {
|
||||
const wrappedList = this.finishedListeners.get(listener);
|
||||
if (wrappedList && wrappedList.length > 0) {
|
||||
const wrapped = wrappedList.pop()!;
|
||||
if (wrappedList.length === 0) {
|
||||
this.finishedListeners.delete(listener);
|
||||
}
|
||||
this.removeEventListener('finished', wrapped);
|
||||
}
|
||||
}
|
||||
|
||||
private addFinishedListenerOnceInternal(listener: Listener): void {
|
||||
const wrapped: WrappedListener = () => {
|
||||
// Clean up tracking
|
||||
this.untrackWrappedListener(this.finishedListeners, listener, wrapped);
|
||||
|
||||
listener.call(this);
|
||||
};
|
||||
|
||||
this.trackListener(this.finishedListeners, listener, wrapped);
|
||||
this.addEventListener('finished', wrapped, { once: true });
|
||||
}
|
||||
finished(): void {
|
||||
this.emit('finished');
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,45 +1,45 @@
|
||||
import { DefaultExecutionEventBus, ExecutionEventBus } from './execution_event_bus.js';
|
||||
import { DefaultExecutionEventBus, ExecutionEventBus } from "./execution_event_bus.js";
|
||||
|
||||
export interface ExecutionEventBusManager {
|
||||
createOrGetByTaskId(taskId: string): ExecutionEventBus;
|
||||
getByTaskId(taskId: string): ExecutionEventBus | undefined;
|
||||
cleanupByTaskId(taskId: string): void;
|
||||
createOrGetByTaskId(taskId: string): ExecutionEventBus;
|
||||
getByTaskId(taskId: string): ExecutionEventBus | undefined;
|
||||
cleanupByTaskId(taskId: string): void;
|
||||
}
|
||||
|
||||
export class DefaultExecutionEventBusManager implements ExecutionEventBusManager {
|
||||
private taskIdToBus: Map<string, ExecutionEventBus> = new Map();
|
||||
private taskIdToBus: Map<string, ExecutionEventBus> = new Map();
|
||||
|
||||
/**
|
||||
* Creates or retrieves an existing ExecutionEventBus based on the taskId.
|
||||
* @param taskId The ID of the task.
|
||||
* @returns An instance of ExecutionEventBus.
|
||||
*/
|
||||
public createOrGetByTaskId(taskId: string): ExecutionEventBus {
|
||||
if (!this.taskIdToBus.has(taskId)) {
|
||||
this.taskIdToBus.set(taskId, new DefaultExecutionEventBus());
|
||||
/**
|
||||
* Creates or retrieves an existing ExecutionEventBus based on the taskId.
|
||||
* @param taskId The ID of the task.
|
||||
* @returns An instance of IExecutionEventBus.
|
||||
*/
|
||||
public createOrGetByTaskId(taskId: string): ExecutionEventBus {
|
||||
if (!this.taskIdToBus.has(taskId)) {
|
||||
this.taskIdToBus.set(taskId, new DefaultExecutionEventBus());
|
||||
}
|
||||
return this.taskIdToBus.get(taskId)!;
|
||||
}
|
||||
return this.taskIdToBus.get(taskId)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves an existing ExecutionEventBus based on the taskId.
|
||||
* @param taskId The ID of the task.
|
||||
* @returns An instance of ExecutionEventBus or undefined if not found.
|
||||
*/
|
||||
public getByTaskId(taskId: string): ExecutionEventBus | undefined {
|
||||
return this.taskIdToBus.get(taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the event bus for a given taskId.
|
||||
* This should be called when an execution flow is complete to free resources.
|
||||
* @param taskId The ID of the task.
|
||||
*/
|
||||
public cleanupByTaskId(taskId: string): void {
|
||||
const bus = this.taskIdToBus.get(taskId);
|
||||
if (bus) {
|
||||
bus.removeAllListeners();
|
||||
/**
|
||||
* Retrieves an existing ExecutionEventBus based on the taskId.
|
||||
* @param taskId The ID of the task.
|
||||
* @returns An instance of IExecutionEventBus or undefined if not found.
|
||||
*/
|
||||
public getByTaskId(taskId: string): ExecutionEventBus | undefined {
|
||||
return this.taskIdToBus.get(taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the event bus for a given taskId.
|
||||
* This should be called when an execution flow is complete to free resources.
|
||||
* @param taskId The ID of the task.
|
||||
*/
|
||||
public cleanupByTaskId(taskId: string): void {
|
||||
const bus = this.taskIdToBus.get(taskId);
|
||||
if (bus) {
|
||||
bus.removeAllListeners();
|
||||
}
|
||||
this.taskIdToBus.delete(taskId);
|
||||
}
|
||||
this.taskIdToBus.delete(taskId);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,70 +1,73 @@
|
||||
import { TaskStatusUpdateEvent } from '../../types.js';
|
||||
import { ExecutionEventBus, AgentExecutionEvent } from './execution_event_bus.js';
|
||||
import {
|
||||
TaskStatusUpdateEvent,
|
||||
} from "../../types.js";
|
||||
import { ExecutionEventBus, AgentExecutionEvent } from "./execution_event_bus.js";
|
||||
|
||||
/**
|
||||
* An async queue that subscribes to an ExecutionEventBus for events
|
||||
* and provides an async generator to consume them.
|
||||
*/
|
||||
export class ExecutionEventQueue {
|
||||
private eventBus: ExecutionEventBus;
|
||||
private eventQueue: AgentExecutionEvent[] = [];
|
||||
private resolvePromise?: (value: void | PromiseLike<void>) => void;
|
||||
private stopped: boolean = false;
|
||||
private eventBus: ExecutionEventBus;
|
||||
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;
|
||||
this.eventBus.on('event', this.handleEvent);
|
||||
this.eventBus.on('finished', this.handleFinished);
|
||||
}
|
||||
|
||||
private handleEvent = (event: AgentExecutionEvent) => {
|
||||
if (this.stopped) return;
|
||||
this.eventQueue.push(event);
|
||||
if (this.resolvePromise) {
|
||||
this.resolvePromise();
|
||||
this.resolvePromise = undefined;
|
||||
constructor(eventBus: ExecutionEventBus) {
|
||||
this.eventBus = eventBus;
|
||||
this.eventBus.on('event', this.handleEvent);
|
||||
this.eventBus.on('finished', this.handleFinished);
|
||||
}
|
||||
};
|
||||
|
||||
private handleFinished = () => {
|
||||
this.stop();
|
||||
};
|
||||
|
||||
/**
|
||||
* Provides an async generator that yields events from the event bus.
|
||||
* Stops when a Message event is received or a TaskStatusUpdateEvent with final=true is received.
|
||||
*/
|
||||
public async *events(): AsyncGenerator<AgentExecutionEvent, void, undefined> {
|
||||
while (!this.stopped || this.eventQueue.length > 0) {
|
||||
if (this.eventQueue.length > 0) {
|
||||
const event = this.eventQueue.shift()!;
|
||||
yield event;
|
||||
if (
|
||||
event.kind === 'message' ||
|
||||
(event.kind === 'status-update' && (event as TaskStatusUpdateEvent).final)
|
||||
) {
|
||||
this.handleFinished();
|
||||
break;
|
||||
private handleEvent = (event: AgentExecutionEvent) => {
|
||||
if (this.stopped) return;
|
||||
this.eventQueue.push(event);
|
||||
if (this.resolvePromise) {
|
||||
this.resolvePromise();
|
||||
this.resolvePromise = undefined;
|
||||
}
|
||||
} else if (!this.stopped) {
|
||||
await new Promise<void>((resolve) => {
|
||||
this.resolvePromise = resolve;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the event queue from processing further events.
|
||||
*/
|
||||
public stop(): void {
|
||||
this.stopped = true;
|
||||
if (this.resolvePromise) {
|
||||
this.resolvePromise(); // Unblock any pending await
|
||||
this.resolvePromise = undefined;
|
||||
}
|
||||
|
||||
this.eventBus.off('event', this.handleEvent);
|
||||
this.eventBus.off('finished', this.handleFinished);
|
||||
}
|
||||
private handleFinished = () => {
|
||||
this.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides an async generator that yields events from the event bus.
|
||||
* Stops when a Message event is received or a TaskStatusUpdateEvent with final=true is received.
|
||||
*/
|
||||
public async *events(): AsyncGenerator<AgentExecutionEvent, void, undefined> {
|
||||
while (!this.stopped || this.eventQueue.length > 0) {
|
||||
if (this.eventQueue.length > 0) {
|
||||
const event = this.eventQueue.shift()!;
|
||||
yield event;
|
||||
if (event.kind === 'message' || (
|
||||
event.kind === 'status-update' &&
|
||||
(event as TaskStatusUpdateEvent).final
|
||||
)) {
|
||||
this.handleFinished();
|
||||
break;
|
||||
}
|
||||
} else if(!this.stopped) {
|
||||
await new Promise<void>((resolve) => {
|
||||
this.resolvePromise = resolve;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the event queue from processing further events.
|
||||
*/
|
||||
public stop(): void {
|
||||
this.stopped = true;
|
||||
if (this.resolvePromise) {
|
||||
this.resolvePromise(); // Unblock any pending await
|
||||
this.resolvePromise = undefined;
|
||||
}
|
||||
|
||||
this.eventBus.off('event', this.handleEvent);
|
||||
this.eventBus.off('finished', this.handleFinished);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,61 +1,109 @@
|
||||
import express, { Express, RequestHandler, ErrorRequestHandler } from 'express';
|
||||
import express, { Request, Response, Express, RequestHandler, ErrorRequestHandler } from 'express';
|
||||
|
||||
import { A2ARequestHandler } from '../request_handler/a2a_request_handler.js';
|
||||
import { AGENT_CARD_PATH } from '../../constants.js';
|
||||
import { jsonErrorHandler, jsonRpcHandler } from './json_rpc_handler.js';
|
||||
import { agentCardHandler } from './agent_card_handler.js';
|
||||
import { UserBuilder } from './common.js';
|
||||
import { A2AError } from "../error.js";
|
||||
import { JSONRPCErrorResponse, JSONRPCSuccessResponse, JSONRPCResponse } from "../../index.js";
|
||||
import { A2ARequestHandler } from "../request_handler/a2a_request_handler.js";
|
||||
import { JsonRpcTransportHandler } from "../transports/jsonrpc_transport_handler.js";
|
||||
|
||||
/**
|
||||
* @deprecated Use specific middlewares ({@link jsonRpcHandler}, {@link agentCardHandler}) directly.
|
||||
*/
|
||||
export class A2AExpressApp {
|
||||
private requestHandler: A2ARequestHandler;
|
||||
private userBuilder: UserBuilder;
|
||||
private requestHandler: A2ARequestHandler; // Kept for getAgentCard
|
||||
private jsonRpcTransportHandler: JsonRpcTransportHandler;
|
||||
|
||||
constructor(
|
||||
requestHandler: A2ARequestHandler,
|
||||
userBuilder: UserBuilder = UserBuilder.noAuthentication
|
||||
) {
|
||||
this.requestHandler = requestHandler;
|
||||
this.userBuilder = userBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds A2A routes to an existing Express app.
|
||||
* @param app Optional existing Express app.
|
||||
* @param baseUrl The base URL for A2A endpoints (e.g., "/a2a/api").
|
||||
* @param middlewares Optional array of Express middlewares to apply to the A2A routes.
|
||||
* @param agentCardPath Optional custom path for the agent card endpoint (defaults to .well-known/agent-card.json).
|
||||
* @returns The Express app with A2A routes.
|
||||
*/
|
||||
public setupRoutes(
|
||||
app: Express,
|
||||
baseUrl: string = '',
|
||||
middlewares?: Array<RequestHandler | ErrorRequestHandler>,
|
||||
agentCardPath: string = AGENT_CARD_PATH
|
||||
): Express {
|
||||
const router = express.Router();
|
||||
|
||||
// Doing it here to maintain previous behaviour of invoking provided middlewares
|
||||
// after JSON body is parsed, jsonRpcHandler registers JSON parsing on the local router.
|
||||
// body-parser used by express.json() ignores subsequent calls and is safe to be added twice:
|
||||
// https://github.com/expressjs/body-parser/blob/168afff3470302aa28050a8ae6681fa1fdaf71a2/lib/read.js#L41.
|
||||
router.use(express.json(), jsonErrorHandler);
|
||||
|
||||
if (middlewares && middlewares.length > 0) {
|
||||
router.use(middlewares);
|
||||
constructor(requestHandler: A2ARequestHandler) {
|
||||
this.requestHandler = requestHandler; // DefaultRequestHandler instance
|
||||
this.jsonRpcTransportHandler = new JsonRpcTransportHandler(requestHandler);
|
||||
}
|
||||
|
||||
router.use(
|
||||
jsonRpcHandler({
|
||||
requestHandler: this.requestHandler,
|
||||
userBuilder: this.userBuilder,
|
||||
})
|
||||
);
|
||||
router.use(`/${agentCardPath}`, agentCardHandler({ agentCardProvider: this.requestHandler }));
|
||||
/**
|
||||
* Adds A2A routes to an existing Express app.
|
||||
* @param app Optional existing Express app.
|
||||
* @param baseUrl The base URL for A2A endpoints (e.g., "/a2a/api").
|
||||
* @param middlewares Optional array of Express middlewares to apply to the A2A routes.
|
||||
* @returns The Express app with A2A routes.
|
||||
*/
|
||||
public setupRoutes(
|
||||
app: Express,
|
||||
baseUrl: string = "",
|
||||
middlewares?: Array<RequestHandler | ErrorRequestHandler>
|
||||
): Express {
|
||||
const router = express.Router();
|
||||
router.use(express.json(), ...(middlewares ?? []));
|
||||
|
||||
app.use(baseUrl, router);
|
||||
return app;
|
||||
}
|
||||
router.get("/.well-known/agent.json", async (req: Request, res: Response) => {
|
||||
try {
|
||||
// getAgentCard is on A2ARequestHandler, which DefaultRequestHandler implements
|
||||
const agentCard = await this.requestHandler.getAgentCard();
|
||||
res.json(agentCard);
|
||||
} catch (error: any) {
|
||||
console.error("Error fetching agent card:", error);
|
||||
res.status(500).json({ error: "Failed to retrieve agent card" });
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/", async (req: Request, res: Response) => {
|
||||
try {
|
||||
const rpcResponseOrStream = await this.jsonRpcTransportHandler.handle(req.body);
|
||||
|
||||
// Check if it's an AsyncGenerator (stream)
|
||||
if (typeof (rpcResponseOrStream as any)?.[Symbol.asyncIterator] === 'function') {
|
||||
const stream = rpcResponseOrStream as AsyncGenerator<JSONRPCSuccessResponse, void, undefined>;
|
||||
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.flushHeaders();
|
||||
|
||||
try {
|
||||
for await (const event of stream) {
|
||||
// Each event from the stream is already a JSONRPCResult
|
||||
res.write(`id: ${new Date().getTime()}\n`);
|
||||
res.write(`data: ${JSON.stringify(event)}\n\n`);
|
||||
}
|
||||
} catch (streamError: any) {
|
||||
console.error(`Error during SSE streaming (request ${req.body?.id}):`, streamError);
|
||||
// If the stream itself throws an error, send a final JSONRPCErrorResponse
|
||||
const a2aError = streamError instanceof A2AError ? streamError : A2AError.internalError(streamError.message || 'Streaming error.');
|
||||
const errorResponse: JSONRPCErrorResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: req.body?.id || null, // Use original request ID if available
|
||||
error: a2aError.toJSONRPCError(),
|
||||
};
|
||||
if (!res.headersSent) { // Should not happen if flushHeaders worked
|
||||
res.status(500).json(errorResponse); // Should be JSON, not SSE here
|
||||
} else {
|
||||
// Try to send as last SSE event if possible, though client might have disconnected
|
||||
res.write(`id: ${new Date().getTime()}\n`);
|
||||
res.write(`event: error\n`); // Custom event type for client-side handling
|
||||
res.write(`data: ${JSON.stringify(errorResponse)}\n\n`);
|
||||
}
|
||||
} finally {
|
||||
if (!res.writableEnded) {
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
} else { // Single JSON-RPC response
|
||||
const rpcResponse = rpcResponseOrStream as JSONRPCResponse;
|
||||
res.status(200).json(rpcResponse);
|
||||
}
|
||||
} catch (error: any) { // Catch errors from jsonRpcTransportHandler.handle itself (e.g., initial parse error)
|
||||
console.error("Unhandled error in A2AExpressApp POST handler:", error);
|
||||
const a2aError = error instanceof A2AError ? error : A2AError.internalError('General processing error.');
|
||||
const errorResponse: JSONRPCErrorResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: req.body?.id || null,
|
||||
error: a2aError.toJSONRPCError(),
|
||||
};
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json(errorResponse);
|
||||
} else if (!res.writableEnded) {
|
||||
// If headers sent (likely during a stream attempt that failed early), try to end gracefully
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
app.use(baseUrl, router);
|
||||
// The separate /stream endpoint is no longer needed.
|
||||
return app;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,40 +0,0 @@
|
||||
import express, { Request, RequestHandler, Response } from 'express';
|
||||
import { AgentCard } from '../../types.js';
|
||||
|
||||
export interface AgentCardHandlerOptions {
|
||||
agentCardProvider: AgentCardProvider;
|
||||
}
|
||||
|
||||
export type AgentCardProvider = { getAgentCard(): Promise<AgentCard> } | (() => Promise<AgentCard>);
|
||||
|
||||
/**
|
||||
* Creates Express.js middleware to handle agent card requests.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // With an existing A2ARequestHandler instance:
|
||||
* app.use('/.well-known/agent-card.json', agentCardHandler({ agentCardProvider: a2aRequestHandler }));
|
||||
* // or with a factory lambda:
|
||||
* app.use('/.well-known/agent-card.json', agentCardHandler({ agentCardProvider: async () => agentCard }));
|
||||
* ```
|
||||
*/
|
||||
export function agentCardHandler(options: AgentCardHandlerOptions): RequestHandler {
|
||||
const router = express.Router();
|
||||
|
||||
const provider =
|
||||
typeof options.agentCardProvider === 'function'
|
||||
? options.agentCardProvider
|
||||
: options.agentCardProvider.getAgentCard.bind(options.agentCardProvider);
|
||||
|
||||
router.get('/', async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const agentCard = await provider();
|
||||
res.json(agentCard);
|
||||
} catch (error) {
|
||||
console.error('Error fetching agent card:', error);
|
||||
res.status(500).json({ error: 'Failed to retrieve agent card' });
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@ -1,8 +0,0 @@
|
||||
import { Request } from 'express';
|
||||
import { UnauthenticatedUser, User } from '../authentication/user.js';
|
||||
|
||||
export type UserBuilder = (req: Request) => Promise<User>;
|
||||
|
||||
export const UserBuilder = {
|
||||
noAuthentication: () => Promise.resolve(new UnauthenticatedUser()),
|
||||
};
|
||||
@ -3,11 +3,4 @@
|
||||
* This module provides Express.js specific functionality.
|
||||
*/
|
||||
|
||||
export { A2AExpressApp } from './a2a_express_app.js';
|
||||
export { UserBuilder } from './common.js';
|
||||
export { jsonRpcHandler } from './json_rpc_handler.js';
|
||||
export type { JsonRpcHandlerOptions } from './json_rpc_handler.js';
|
||||
export { agentCardHandler } from './agent_card_handler.js';
|
||||
export type { AgentCardHandlerOptions, AgentCardProvider } from './agent_card_handler.js';
|
||||
export { restHandler } from './rest_handler.js';
|
||||
export type { RestHandlerOptions } from './rest_handler.js';
|
||||
export { A2AExpressApp } from "./a2a_express_app.js";
|
||||
|
||||
@ -1,147 +0,0 @@
|
||||
import express, {
|
||||
Request,
|
||||
Response,
|
||||
ErrorRequestHandler,
|
||||
NextFunction,
|
||||
RequestHandler,
|
||||
} from 'express';
|
||||
import { JSONRPCErrorResponse, JSONRPCSuccessResponse, JSONRPCResponse } from '../../types.js';
|
||||
import { A2AError } from '../error.js';
|
||||
import { A2ARequestHandler } from '../request_handler/a2a_request_handler.js';
|
||||
import { JsonRpcTransportHandler } from '../transports/jsonrpc/jsonrpc_transport_handler.js';
|
||||
import { ServerCallContext } from '../context.js';
|
||||
import { HTTP_EXTENSION_HEADER } from '../../constants.js';
|
||||
import { UserBuilder } from './common.js';
|
||||
import { SSE_HEADERS, formatSSEEvent, formatSSEErrorEvent } from '../../sse_utils.js';
|
||||
import { Extensions } from '../../extensions.js';
|
||||
|
||||
export interface JsonRpcHandlerOptions {
|
||||
requestHandler: A2ARequestHandler;
|
||||
userBuilder: UserBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates Express.js middleware to handle A2A JSON-RPC requests.
|
||||
* @example
|
||||
*
|
||||
* ```ts
|
||||
* // Handle at root
|
||||
* app.use(jsonRpcHandler({ requestHandler: a2aRequestHandler, userBuilder: UserBuilder.noAuthentication }));
|
||||
* // or
|
||||
* app.use('/a2a/json-rpc', jsonRpcHandler({ requestHandler: a2aRequestHandler, userBuilder: UserBuilder.noAuthentication }));
|
||||
* ```
|
||||
*/
|
||||
export function jsonRpcHandler(options: JsonRpcHandlerOptions): RequestHandler {
|
||||
const jsonRpcTransportHandler = new JsonRpcTransportHandler(options.requestHandler);
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(express.json(), jsonErrorHandler);
|
||||
|
||||
router.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const user = await options.userBuilder(req);
|
||||
const context = new ServerCallContext(
|
||||
Extensions.parseServiceParameter(req.header(HTTP_EXTENSION_HEADER)),
|
||||
user
|
||||
);
|
||||
const rpcResponseOrStream = await jsonRpcTransportHandler.handle(req.body, context);
|
||||
|
||||
if (context.activatedExtensions) {
|
||||
res.setHeader(HTTP_EXTENSION_HEADER, Array.from(context.activatedExtensions));
|
||||
}
|
||||
// Check if it's an AsyncGenerator (stream)
|
||||
if (typeof (rpcResponseOrStream as AsyncGenerator)?.[Symbol.asyncIterator] === 'function') {
|
||||
const stream = rpcResponseOrStream as AsyncGenerator<
|
||||
JSONRPCSuccessResponse,
|
||||
void,
|
||||
undefined
|
||||
>;
|
||||
|
||||
// Set SSE headers using shared utility
|
||||
Object.entries(SSE_HEADERS).forEach(([key, value]) => {
|
||||
res.setHeader(key, value);
|
||||
});
|
||||
|
||||
res.flushHeaders();
|
||||
|
||||
try {
|
||||
for await (const event of stream) {
|
||||
// Each event from the stream is already a JSONRPCResult
|
||||
// Use shared formatSSEEvent utility
|
||||
res.write(formatSSEEvent(event));
|
||||
}
|
||||
} catch (streamError) {
|
||||
console.error(`Error during SSE streaming (request ${req.body?.id}):`, streamError);
|
||||
// If the stream itself throws an error, send a final JSONRPCErrorResponse
|
||||
let a2aError: A2AError;
|
||||
if (streamError instanceof A2AError) {
|
||||
a2aError = streamError;
|
||||
} else {
|
||||
a2aError = A2AError.internalError(
|
||||
(streamError instanceof Error && streamError.message) || 'Streaming error.'
|
||||
);
|
||||
}
|
||||
const errorResponse: JSONRPCErrorResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: req.body?.id || null, // Use original request ID if available
|
||||
error: a2aError.toJSONRPCError(),
|
||||
};
|
||||
if (!res.headersSent) {
|
||||
// Should not happen if flushHeaders worked
|
||||
res.status(500).json(errorResponse); // Should be JSON, not SSE here
|
||||
} else {
|
||||
// Try to send as last SSE event if possible, though client might have disconnected
|
||||
// Use shared formatSSEErrorEvent utility
|
||||
res.write(formatSSEErrorEvent(errorResponse));
|
||||
}
|
||||
} finally {
|
||||
if (!res.writableEnded) {
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single JSON-RPC response
|
||||
const rpcResponse = rpcResponseOrStream as JSONRPCResponse;
|
||||
res.status(200).json(rpcResponse);
|
||||
}
|
||||
} catch (error) {
|
||||
// Catch errors from jsonRpcTransportHandler.handle itself (e.g., initial parse error)
|
||||
console.error('Unhandled error in JSON-RPC POST handler:', error);
|
||||
const a2aError =
|
||||
error instanceof A2AError ? error : A2AError.internalError('General processing error.');
|
||||
const errorResponse: JSONRPCErrorResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: req.body?.id || null,
|
||||
error: a2aError.toJSONRPCError(),
|
||||
};
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json(errorResponse);
|
||||
} else if (!res.writableEnded) {
|
||||
// If headers sent (likely during a stream attempt that failed early), try to end gracefully
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
export const jsonErrorHandler: ErrorRequestHandler = (
|
||||
err: unknown,
|
||||
_req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
// Handle JSON parse errors from express.json() (https://github.com/expressjs/body-parser/issues/122)
|
||||
if (err instanceof SyntaxError && 'body' in err) {
|
||||
const a2aError = A2AError.parseError('Invalid JSON payload.');
|
||||
const errorResponse: JSONRPCErrorResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: null,
|
||||
error: a2aError.toJSONRPCError(),
|
||||
};
|
||||
return res.status(400).json(errorResponse);
|
||||
}
|
||||
next(err);
|
||||
};
|
||||
@ -1,524 +0,0 @@
|
||||
import express, {
|
||||
Request,
|
||||
Response,
|
||||
RequestHandler,
|
||||
ErrorRequestHandler,
|
||||
NextFunction,
|
||||
} from 'express';
|
||||
import { A2ARequestHandler } from '../request_handler/a2a_request_handler.js';
|
||||
import { A2AError } from '../error.js';
|
||||
import { SSE_HEADERS, formatSSEEvent, formatSSEErrorEvent } from '../../sse_utils.js';
|
||||
import {
|
||||
RestTransportHandler,
|
||||
HTTP_STATUS,
|
||||
mapErrorToStatus,
|
||||
toHTTPError,
|
||||
} from '../transports/rest/rest_transport_handler.js';
|
||||
import { ServerCallContext } from '../context.js';
|
||||
import { HTTP_EXTENSION_HEADER } from '../../constants.js';
|
||||
import { UserBuilder } from './common.js';
|
||||
import { Extensions } from '../../extensions.js';
|
||||
|
||||
import { FromProto } from '../../types/converters/from_proto.js';
|
||||
import * as a2a from '../../types/pb/a2a_types.js';
|
||||
import { ToProto } from '../../types/converters/to_proto.js';
|
||||
import { Message, Task, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '../../types.js';
|
||||
|
||||
/**
|
||||
* Options for configuring the HTTP+JSON/REST handler.
|
||||
*/
|
||||
export interface RestHandlerOptions {
|
||||
requestHandler: A2ARequestHandler;
|
||||
userBuilder: UserBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Express error handler middleware for REST API JSON parse errors.
|
||||
* Catches SyntaxError from express.json() and converts to A2A parse error format.
|
||||
*
|
||||
* @param err - Error thrown by express.json() middleware
|
||||
* @param _req - Express request (unused)
|
||||
* @param res - Express response
|
||||
* @param next - Next middleware function
|
||||
*/
|
||||
const restErrorHandler: ErrorRequestHandler = (
|
||||
err: Error,
|
||||
_req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
if (err instanceof SyntaxError && 'body' in err) {
|
||||
const a2aError = A2AError.parseError('Invalid JSON payload.');
|
||||
return res.status(400).json(toHTTPError(a2aError));
|
||||
}
|
||||
next(err);
|
||||
};
|
||||
|
||||
// Route patterns removed - using explicit route definitions instead
|
||||
|
||||
/**
|
||||
* Type alias for async Express route handlers used in this module.
|
||||
*/
|
||||
type AsyncRouteHandler = (req: Request, res: Response) => Promise<void>;
|
||||
|
||||
// ============================================================================
|
||||
// HTTP+JSON/REST Handler - Main Export
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Creates Express.js middleware to handle A2A HTTP+JSON/REST requests.
|
||||
*
|
||||
* This handler implements the A2A REST API specification with snake_case
|
||||
* field names, providing endpoints for:
|
||||
* - Agent card retrieval (GET /v1/card)
|
||||
* - Message sending with optional streaming (POST /v1/message:send|stream)
|
||||
* - Task management (GET/POST /v1/tasks/:taskId:cancel|subscribe)
|
||||
* - Push notification configuration
|
||||
*
|
||||
* The handler acts as an adapter layer, converting between REST format
|
||||
* (snake_case) at the API boundary and internal TypeScript format (camelCase)
|
||||
* for business logic.
|
||||
*
|
||||
* @param options - Configuration options including the request handler
|
||||
* @returns Express router configured with all A2A REST endpoints
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const app = express();
|
||||
* const requestHandler = new DefaultRequestHandler(...);
|
||||
* app.use('/api/rest', restHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
|
||||
* ```
|
||||
*/
|
||||
export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
const router = express.Router();
|
||||
const restTransportHandler = new RestTransportHandler(options.requestHandler);
|
||||
|
||||
router.use(express.json(), restErrorHandler);
|
||||
|
||||
// ============================================================================
|
||||
// Helper Functions
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Builds a ServerCallContext from the Express request.
|
||||
* Extracts protocol extensions from headers and builds user from request.
|
||||
*
|
||||
* @param req - Express request object
|
||||
* @returns ServerCallContext with requested extensions and authenticated user
|
||||
*/
|
||||
const buildContext = async (req: Request): Promise<ServerCallContext> => {
|
||||
const user = await options.userBuilder(req);
|
||||
return new ServerCallContext(
|
||||
Extensions.parseServiceParameter(req.header(HTTP_EXTENSION_HEADER)),
|
||||
user
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets activated extensions header in the response if any extensions were activated.
|
||||
*
|
||||
* @param res - Express response object
|
||||
* @param context - ServerCallContext containing activated extensions
|
||||
*/
|
||||
const setExtensionsHeader = (res: Response, context: ServerCallContext): void => {
|
||||
if (context.activatedExtensions) {
|
||||
res.setHeader(HTTP_EXTENSION_HEADER, Array.from(context.activatedExtensions));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Sends a JSON response with the specified status code.
|
||||
* Handles 204 No Content responses specially (no body).
|
||||
* Sets activated extensions header if present in context.
|
||||
*
|
||||
* @param res - Express response object
|
||||
* @param statusCode - HTTP status code
|
||||
* @param context - ServerCallContext for setting extension headers
|
||||
* @param body - Response body (omitted for 204 responses)
|
||||
* @param responseType - Optional protobuf message type for serialization
|
||||
*/
|
||||
const sendResponse = <T>(
|
||||
res: Response,
|
||||
statusCode: number,
|
||||
context: ServerCallContext,
|
||||
body?: T,
|
||||
responseType?: a2a.MessageFns<T>
|
||||
): void => {
|
||||
setExtensionsHeader(res, context);
|
||||
res.status(statusCode);
|
||||
if (statusCode === HTTP_STATUS.NO_CONTENT) {
|
||||
res.end();
|
||||
} else {
|
||||
if (!responseType || body === undefined) {
|
||||
throw new Error('Bug: toJson serializer and body must be provided for non-204 responses.');
|
||||
}
|
||||
res.json(responseType.toJSON(body));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Sends a Server-Sent Events (SSE) stream response.
|
||||
* Sets appropriate SSE headers, streams events, and handles errors gracefully.
|
||||
* Events are already converted to REST format by the transport handler.
|
||||
* Sets activated extensions header if present in context.
|
||||
*
|
||||
* @param res - Express response object
|
||||
* @param stream - Async generator yielding REST-formatted events
|
||||
* @param context - ServerCallContext for setting extension headers
|
||||
*/
|
||||
const sendStreamResponse = async (
|
||||
res: Response,
|
||||
stream: AsyncGenerator<
|
||||
Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent,
|
||||
void,
|
||||
undefined
|
||||
>,
|
||||
context: ServerCallContext
|
||||
): Promise<void> => {
|
||||
// Get first event before flushing headers to catch early errors
|
||||
// This allows returning proper HTTP error codes instead of 200 + SSE error
|
||||
const iterator = stream[Symbol.asyncIterator]();
|
||||
let firstResult: IteratorResult<unknown>;
|
||||
try {
|
||||
firstResult = await iterator.next();
|
||||
} catch (error) {
|
||||
// Early error - return proper HTTP error
|
||||
const a2aError =
|
||||
error instanceof A2AError
|
||||
? error
|
||||
: A2AError.internalError(error instanceof Error ? error.message : 'Streaming error');
|
||||
const statusCode = mapErrorToStatus(a2aError.code);
|
||||
sendResponse(res, statusCode, context, toHTTPError(a2aError));
|
||||
return;
|
||||
}
|
||||
|
||||
// First event succeeded - now set SSE headers and stream
|
||||
Object.entries(SSE_HEADERS).forEach(([key, value]) => {
|
||||
res.setHeader(key, value);
|
||||
});
|
||||
setExtensionsHeader(res, context);
|
||||
res.flushHeaders();
|
||||
|
||||
try {
|
||||
// Write first event
|
||||
if (!firstResult.done) {
|
||||
const proto = ToProto.messageStreamResult(firstResult.value);
|
||||
const result = a2a.StreamResponse.toJSON(proto);
|
||||
res.write(formatSSEEvent(result));
|
||||
}
|
||||
for await (const event of { [Symbol.asyncIterator]: () => iterator }) {
|
||||
const proto = ToProto.messageStreamResult(event);
|
||||
const result = a2a.StreamResponse.toJSON(proto);
|
||||
res.write(formatSSEEvent(result));
|
||||
}
|
||||
} catch (streamError: unknown) {
|
||||
console.error('SSE streaming error:', streamError);
|
||||
const a2aError =
|
||||
streamError instanceof A2AError
|
||||
? streamError
|
||||
: A2AError.internalError(
|
||||
streamError instanceof Error ? streamError.message : 'Streaming error'
|
||||
);
|
||||
if (!res.writableEnded) {
|
||||
res.write(formatSSEErrorEvent(toHTTPError(a2aError)));
|
||||
}
|
||||
} finally {
|
||||
if (!res.writableEnded) {
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles errors in route handlers by converting them to A2A error format
|
||||
* and sending appropriate HTTP response.
|
||||
* Gracefully handles cases where headers have already been sent.
|
||||
*
|
||||
* @param res - Express response object
|
||||
* @param error - Error to handle (can be A2AError or generic Error)
|
||||
*/
|
||||
const handleError = (res: Response, error: unknown): void => {
|
||||
if (res.headersSent) {
|
||||
if (!res.writableEnded) {
|
||||
res.end();
|
||||
}
|
||||
return;
|
||||
}
|
||||
const a2aError =
|
||||
error instanceof A2AError
|
||||
? error
|
||||
: A2AError.internalError(error instanceof Error ? error.message : 'Internal server error');
|
||||
const statusCode = mapErrorToStatus(a2aError.code);
|
||||
res.status(statusCode).json(toHTTPError(a2aError));
|
||||
};
|
||||
|
||||
/**
|
||||
* Wraps an async route handler to centralize error handling.
|
||||
* Catches any errors thrown by the handler and passes them to handleError.
|
||||
*
|
||||
* @param handler - Async route handler function
|
||||
* @returns Wrapped handler with built-in error handling
|
||||
*/
|
||||
const asyncHandler = (handler: AsyncRouteHandler): AsyncRouteHandler => {
|
||||
return async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
await handler(req, res);
|
||||
} catch (error) {
|
||||
handleError(res, error);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Route Handlers
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* GET /v1/card
|
||||
*
|
||||
* Retrieves the authenticated extended agent card.
|
||||
*
|
||||
* @returns 200 OK with agent card
|
||||
* @returns 500 Internal Server Error on failure
|
||||
*/
|
||||
router.get(
|
||||
'/v1/card',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.getAuthenticatedExtendedAgentCard(context);
|
||||
const protoResult = ToProto.agentCard(result);
|
||||
sendResponse<a2a.AgentCard>(res, HTTP_STATUS.OK, context, protoResult, a2a.AgentCard);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /v1/message:send
|
||||
*
|
||||
* Sends a message to the agent synchronously.
|
||||
* Returns either a Message (for immediate responses) or a Task (for async processing).
|
||||
* Note: Colon is escaped in route definition for Express compatibility.
|
||||
*
|
||||
* @param req.body - MessageSendParams (accepts both snake_case and camelCase)
|
||||
* @returns 201 Created with RestMessage or RestTask
|
||||
* @returns 400 Bad Request if message is invalid
|
||||
*/
|
||||
router.post(
|
||||
'/v1/message\\:send',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const protoReq = a2a.SendMessageRequest.fromJSON(req.body);
|
||||
const params = FromProto.messageSendParams(protoReq);
|
||||
const result = await restTransportHandler.sendMessage(params, context);
|
||||
const protoResult = ToProto.messageSendResult(result);
|
||||
sendResponse<a2a.SendMessageResponse>(
|
||||
res,
|
||||
HTTP_STATUS.CREATED,
|
||||
context,
|
||||
protoResult,
|
||||
a2a.SendMessageResponse
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /v1/message:stream
|
||||
*
|
||||
* Sends a message to the agent with streaming response.
|
||||
* Returns a Server-Sent Events (SSE) stream of updates.
|
||||
* Note: Colon is escaped in route definition for Express compatibility.
|
||||
*
|
||||
* @param req.body - MessageSendParams (accepts both snake_case and camelCase)
|
||||
* @returns 200 OK with SSE stream of messages, tasks, and status updates
|
||||
* @returns 400 Bad Request if message is invalid
|
||||
* @returns 501 Not Implemented if streaming not supported
|
||||
*/
|
||||
router.post(
|
||||
'/v1/message\\:stream',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const protoReq = a2a.SendMessageRequest.fromJSON(req.body);
|
||||
const params = FromProto.messageSendParams(protoReq);
|
||||
const stream = await restTransportHandler.sendMessageStream(params, context);
|
||||
await sendStreamResponse(res, stream, context);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /v1/tasks/:taskId
|
||||
*
|
||||
* Retrieves the current status and details of a task.
|
||||
*
|
||||
* @param req.params.taskId - Task identifier
|
||||
* @param req.query.historyLength - Optional number of history messages to include
|
||||
* @returns 200 OK with RestTask
|
||||
* @returns 400 Bad Request if historyLength is invalid
|
||||
* @returns 404 Not Found if task doesn't exist
|
||||
*/
|
||||
router.get(
|
||||
'/v1/tasks/:taskId',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.getTask(
|
||||
req.params.taskId,
|
||||
context,
|
||||
//TODO: clarify for version 1.0.0 the format of the historyLength query parameter, and if history should always be added to the returned object
|
||||
req.query.historyLength ?? req.query.history_length
|
||||
);
|
||||
const protoResult = ToProto.task(result);
|
||||
sendResponse<a2a.Task>(res, HTTP_STATUS.OK, context, protoResult, a2a.Task);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /v1/tasks/:taskId:cancel
|
||||
*
|
||||
* Attempts to cancel an ongoing task.
|
||||
* The task may not be immediately canceled depending on its current state.
|
||||
*
|
||||
* @param req.params.taskId - Task identifier
|
||||
* @returns 202 Accepted with RestTask (task is being canceled)
|
||||
* @returns 404 Not Found if task doesn't exist
|
||||
* @returns 409 Conflict if task cannot be canceled
|
||||
*/
|
||||
router.post(
|
||||
'/v1/tasks/:taskId\\:cancel',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.cancelTask(req.params.taskId, context);
|
||||
const protoResult = ToProto.task(result);
|
||||
sendResponse<a2a.Task>(res, HTTP_STATUS.ACCEPTED, context, protoResult, a2a.Task);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /v1/tasks/:taskId:subscribe
|
||||
*
|
||||
* Resubscribes to an existing task's updates via Server-Sent Events (SSE).
|
||||
* Useful for reconnecting to long-running tasks or receiving missed updates.
|
||||
*
|
||||
* @param req.params.taskId - Task identifier
|
||||
* @returns 200 OK with SSE stream of task status and artifact updates
|
||||
* @returns 404 Not Found if task doesn't exist
|
||||
* @returns 501 Not Implemented if streaming not supported
|
||||
*/
|
||||
router.post(
|
||||
'/v1/tasks/:taskId\\:subscribe',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const stream = await restTransportHandler.resubscribe(req.params.taskId, context);
|
||||
await sendStreamResponse(res, stream, context);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /v1/tasks/:taskId/pushNotificationConfigs
|
||||
*
|
||||
* Creates a push notification configuration for a task.
|
||||
* The agent will send task updates to the configured webhook URL.
|
||||
*
|
||||
* @param req.params.taskId - Task identifier
|
||||
* @param req.body - Push notification configuration (snake_case format)
|
||||
* @returns 201 Created with TaskPushNotificationConfig
|
||||
* @returns 501 Not Implemented if push notifications not supported
|
||||
*/
|
||||
router.post(
|
||||
'/v1/tasks/:taskId/pushNotificationConfigs',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const protoReq = a2a.CreateTaskPushNotificationConfigRequest.fromJSON(req.body);
|
||||
const params = FromProto.createTaskPushNotificationConfig(protoReq);
|
||||
const result = await restTransportHandler.setTaskPushNotificationConfig(params, context);
|
||||
const protoResult = ToProto.taskPushNotificationConfig(result);
|
||||
sendResponse<a2a.TaskPushNotificationConfig>(
|
||||
res,
|
||||
HTTP_STATUS.CREATED,
|
||||
context,
|
||||
protoResult,
|
||||
a2a.TaskPushNotificationConfig
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /v1/tasks/:taskId/pushNotificationConfigs
|
||||
*
|
||||
* Lists all push notification configurations for a task.
|
||||
*
|
||||
* @param req.params.taskId - Task identifier
|
||||
* @returns 200 OK with array of TaskPushNotificationConfig
|
||||
* @returns 404 Not Found if task doesn't exist
|
||||
*/
|
||||
router.get(
|
||||
'/v1/tasks/:taskId/pushNotificationConfigs',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.listTaskPushNotificationConfigs(
|
||||
req.params.taskId,
|
||||
context
|
||||
);
|
||||
const protoResult = ToProto.listTaskPushNotificationConfig(result);
|
||||
sendResponse<a2a.ListTaskPushNotificationConfigResponse>(
|
||||
res,
|
||||
HTTP_STATUS.OK,
|
||||
context,
|
||||
protoResult,
|
||||
a2a.ListTaskPushNotificationConfigResponse
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /v1/tasks/:taskId/pushNotificationConfigs/:configId
|
||||
*
|
||||
* Retrieves a specific push notification configuration.
|
||||
*
|
||||
* @param req.params.taskId - Task identifier
|
||||
* @param req.params.configId - Push notification configuration identifier
|
||||
* @returns 200 OK with TaskPushNotificationConfig
|
||||
* @returns 404 Not Found if task or config doesn't exist
|
||||
*/
|
||||
router.get(
|
||||
'/v1/tasks/:taskId/pushNotificationConfigs/:configId',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.getTaskPushNotificationConfig(
|
||||
req.params.taskId,
|
||||
req.params.configId,
|
||||
context
|
||||
);
|
||||
const protoResult = ToProto.taskPushNotificationConfig(result);
|
||||
sendResponse<a2a.TaskPushNotificationConfig>(
|
||||
res,
|
||||
HTTP_STATUS.OK,
|
||||
context,
|
||||
protoResult,
|
||||
a2a.TaskPushNotificationConfig
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* DELETE /v1/tasks/:taskId/pushNotificationConfigs/:configId
|
||||
*
|
||||
* Deletes a push notification configuration.
|
||||
*
|
||||
* @param req.params.taskId - Task identifier
|
||||
* @param req.params.configId - Push notification configuration identifier
|
||||
* @returns 204 No Content on success
|
||||
* @returns 404 Not Found if task or config doesn't exist
|
||||
*/
|
||||
router.delete(
|
||||
'/v1/tasks/:taskId/pushNotificationConfigs/:configId',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
await restTransportHandler.deleteTaskPushNotificationConfig(
|
||||
req.params.taskId,
|
||||
req.params.configId,
|
||||
context
|
||||
);
|
||||
sendResponse(res, HTTP_STATUS.NO_CONTENT, context);
|
||||
})
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
@ -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()),
|
||||
};
|
||||
@ -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;
|
||||
};
|
||||
@ -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';
|
||||
@ -3,35 +3,20 @@
|
||||
* Exports the server-only codebase.
|
||||
*/
|
||||
|
||||
export type { AgentExecutor } from './agent_execution/agent_executor.js';
|
||||
export { RequestContext } from './agent_execution/request_context.js';
|
||||
export type { AgentExecutor } from "./agent_execution/agent_executor.js";
|
||||
export { RequestContext } from "./agent_execution/request_context.js";
|
||||
|
||||
export type {
|
||||
AgentExecutionEvent,
|
||||
ExecutionEventBus,
|
||||
ExecutionEventName,
|
||||
} from './events/execution_event_bus.js';
|
||||
export { DefaultExecutionEventBus } from './events/execution_event_bus.js';
|
||||
export type { ExecutionEventBusManager } from './events/execution_event_bus_manager.js';
|
||||
export { DefaultExecutionEventBusManager } from './events/execution_event_bus_manager.js';
|
||||
export { ExecutionEventQueue } from './events/execution_event_queue.js';
|
||||
export type { AgentExecutionEvent, ExecutionEventBus } from "./events/execution_event_bus.js";
|
||||
export { DefaultExecutionEventBus } from "./events/execution_event_bus.js";
|
||||
export type { ExecutionEventBusManager } from "./events/execution_event_bus_manager.js";
|
||||
export { DefaultExecutionEventBusManager } from "./events/execution_event_bus_manager.js";
|
||||
export { ExecutionEventQueue } from "./events/execution_event_queue.js";
|
||||
|
||||
export type { A2ARequestHandler } from './request_handler/a2a_request_handler.js';
|
||||
export { DefaultRequestHandler } from './request_handler/default_request_handler.js';
|
||||
export type { ExtendedAgentCardProvider } from './request_handler/default_request_handler.js';
|
||||
export { ResultManager } from './result_manager.js';
|
||||
export type { TaskStore } from './store.js';
|
||||
export { InMemoryTaskStore } from './store.js';
|
||||
export type { A2ARequestHandler } from "./request_handler/a2a_request_handler.js";
|
||||
export { DefaultRequestHandler } from "./request_handler/default_request_handler.js";
|
||||
export { ResultManager } from "./result_manager.js";
|
||||
export type { TaskStore } from "./store.js";
|
||||
export { InMemoryTaskStore } from "./store.js";
|
||||
|
||||
export { JsonRpcTransportHandler } from './transports/jsonrpc/jsonrpc_transport_handler.js';
|
||||
export { ServerCallContext } from './context.js';
|
||||
export { A2AError } from './error.js';
|
||||
|
||||
export type { PushNotificationSender } from './push_notification/push_notification_sender.js';
|
||||
export { DefaultPushNotificationSender } from './push_notification/default_push_notification_sender.js';
|
||||
export type { DefaultPushNotificationSenderOptions } from './push_notification/default_push_notification_sender.js';
|
||||
export type { PushNotificationStore } from './push_notification/push_notification_store.js';
|
||||
export { InMemoryPushNotificationStore } from './push_notification/push_notification_store.js';
|
||||
|
||||
export type { User } from './authentication/user.js';
|
||||
export { UnauthenticatedUser } from './authentication/user.js';
|
||||
export { JsonRpcTransportHandler } from "./transports/jsonrpc_transport_handler.js";
|
||||
export { A2AError } from "./error.js";
|
||||
|
||||
@ -1,101 +0,0 @@
|
||||
import { Task, PushNotificationConfig } from '../../types.js';
|
||||
import { PushNotificationSender } from './push_notification_sender.js';
|
||||
import { PushNotificationStore } from './push_notification_store.js';
|
||||
|
||||
export interface DefaultPushNotificationSenderOptions {
|
||||
/**
|
||||
* Timeout in milliseconds for the abort controller. Defaults to 5000ms.
|
||||
*/
|
||||
timeout?: number;
|
||||
/**
|
||||
* Custom header name for the token. Defaults to 'X-A2A-Notification-Token'.
|
||||
*/
|
||||
tokenHeaderName?: string;
|
||||
}
|
||||
|
||||
export class DefaultPushNotificationSender implements PushNotificationSender {
|
||||
private readonly pushNotificationStore: PushNotificationStore;
|
||||
private notificationChain: Map<string, Promise<unknown>>;
|
||||
private readonly options: Required<DefaultPushNotificationSenderOptions>;
|
||||
|
||||
constructor(
|
||||
pushNotificationStore: PushNotificationStore,
|
||||
options: DefaultPushNotificationSenderOptions = {}
|
||||
) {
|
||||
this.pushNotificationStore = pushNotificationStore;
|
||||
this.notificationChain = new Map();
|
||||
this.options = {
|
||||
timeout: 5000,
|
||||
tokenHeaderName: 'X-A2A-Notification-Token',
|
||||
...options,
|
||||
};
|
||||
}
|
||||
|
||||
async send(task: Task): Promise<void> {
|
||||
const pushConfigs = await this.pushNotificationStore.load(task.id);
|
||||
if (!pushConfigs || pushConfigs.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const lastPromise = this.notificationChain.get(task.id) ?? Promise.resolve();
|
||||
// Chain promises to ensure notifications for the same task are sent sequentially.
|
||||
// Once the promise is resolved, the Garbage Collector will clean it up if there are no other references to it.
|
||||
// This will prevent memory to linearly grow with the number of notifications sent.
|
||||
const newPromise = lastPromise.then(async () => {
|
||||
const dispatches = pushConfigs.map(async (pushConfig) => {
|
||||
try {
|
||||
await this._dispatchNotification(task, pushConfig);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Error sending push notification for task_id=${task.id} to URL: ${pushConfig.url}. Error:`,
|
||||
error
|
||||
);
|
||||
}
|
||||
});
|
||||
await Promise.all(dispatches);
|
||||
});
|
||||
this.notificationChain.set(task.id, newPromise);
|
||||
|
||||
return newPromise.finally(() => {
|
||||
// Clean up the chain if it's the last notification
|
||||
if (this.notificationChain.get(task.id) === newPromise) {
|
||||
this.notificationChain.delete(task.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async _dispatchNotification(
|
||||
task: Task,
|
||||
pushConfig: PushNotificationConfig
|
||||
): Promise<void> {
|
||||
const url = pushConfig.url;
|
||||
const controller = new AbortController();
|
||||
// Abort the request if it takes longer than the configured timeout.
|
||||
const timeoutId = setTimeout(() => controller.abort(), this.options.timeout);
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
if (pushConfig.token) {
|
||||
headers[this.options.tokenHeaderName] = pushConfig.token;
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(task),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
console.info(`Push notification sent for task_id=${task.id} to URL: ${url}`);
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,5 +0,0 @@
|
||||
import { Task } from '../../types.js';
|
||||
|
||||
export interface PushNotificationSender {
|
||||
send(task: Task): Promise<void>;
|
||||
}
|
||||
@ -1,58 +0,0 @@
|
||||
import { PushNotificationConfig } from '../../types.js';
|
||||
|
||||
export interface PushNotificationStore {
|
||||
save(taskId: string, pushNotificationConfig: PushNotificationConfig): Promise<void>;
|
||||
load(taskId: string): Promise<PushNotificationConfig[]>;
|
||||
delete(taskId: string, configId?: string): Promise<void>;
|
||||
}
|
||||
|
||||
export class InMemoryPushNotificationStore implements PushNotificationStore {
|
||||
private store: Map<string, PushNotificationConfig[]> = new Map();
|
||||
|
||||
async save(taskId: string, pushNotificationConfig: PushNotificationConfig): Promise<void> {
|
||||
const configs = this.store.get(taskId) || [];
|
||||
|
||||
// Set ID if it's not already set
|
||||
if (!pushNotificationConfig.id) {
|
||||
pushNotificationConfig.id = taskId;
|
||||
}
|
||||
|
||||
// Remove existing config with the same ID if it exists
|
||||
const existingIndex = configs.findIndex((config) => config.id === pushNotificationConfig.id);
|
||||
if (existingIndex !== -1) {
|
||||
configs.splice(existingIndex, 1);
|
||||
}
|
||||
|
||||
// Add the new/updated config
|
||||
configs.push(pushNotificationConfig);
|
||||
this.store.set(taskId, configs);
|
||||
}
|
||||
|
||||
async load(taskId: string): Promise<PushNotificationConfig[]> {
|
||||
const configs = this.store.get(taskId);
|
||||
return configs || [];
|
||||
}
|
||||
|
||||
async delete(taskId: string, configId?: string): Promise<void> {
|
||||
// If no configId is provided, use taskId as the configId (backward compatibility)
|
||||
if (configId === undefined) {
|
||||
configId = taskId;
|
||||
}
|
||||
|
||||
const configs = this.store.get(taskId);
|
||||
if (!configs) {
|
||||
return;
|
||||
}
|
||||
|
||||
const configIndex = configs.findIndex((config) => config.id === configId);
|
||||
if (configIndex !== -1) {
|
||||
configs.splice(configIndex, 1);
|
||||
}
|
||||
|
||||
if (configs.length === 0) {
|
||||
this.store.delete(taskId);
|
||||
} else {
|
||||
this.store.set(taskId, configs);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,60 +1,64 @@
|
||||
import {
|
||||
Message,
|
||||
AgentCard,
|
||||
MessageSendParams,
|
||||
Task,
|
||||
TaskStatusUpdateEvent,
|
||||
TaskArtifactUpdateEvent,
|
||||
TaskQueryParams,
|
||||
TaskIdParams,
|
||||
TaskPushNotificationConfig,
|
||||
GetTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
} from '../../types.js';
|
||||
import { ServerCallContext } from '../context.js';
|
||||
Message,
|
||||
AgentCard,
|
||||
MessageSendParams,
|
||||
Task,
|
||||
TaskStatusUpdateEvent,
|
||||
TaskArtifactUpdateEvent,
|
||||
TaskQueryParams,
|
||||
TaskIdParams,
|
||||
TaskPushNotificationConfig,
|
||||
GetTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
} from "../../types.js";
|
||||
|
||||
export interface A2ARequestHandler {
|
||||
getAgentCard(): Promise<AgentCard>;
|
||||
getAgentCard(): Promise<AgentCard>;
|
||||
|
||||
getAuthenticatedExtendedAgentCard(context?: ServerCallContext): Promise<AgentCard>;
|
||||
getAuthenticatedExtendedAgentCard(): Promise<AgentCard>;
|
||||
|
||||
sendMessage(params: MessageSendParams, context?: ServerCallContext): Promise<Message | Task>;
|
||||
sendMessage(
|
||||
params: MessageSendParams
|
||||
): Promise<Message | Task>;
|
||||
|
||||
sendMessageStream(
|
||||
params: MessageSendParams,
|
||||
context?: ServerCallContext
|
||||
): AsyncGenerator<
|
||||
Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent,
|
||||
void,
|
||||
undefined
|
||||
>;
|
||||
sendMessageStream(
|
||||
params: MessageSendParams
|
||||
): AsyncGenerator<
|
||||
| Message
|
||||
| Task
|
||||
| TaskStatusUpdateEvent
|
||||
| TaskArtifactUpdateEvent,
|
||||
void,
|
||||
undefined
|
||||
>;
|
||||
|
||||
getTask(params: TaskQueryParams, context?: ServerCallContext): Promise<Task>;
|
||||
cancelTask(params: TaskIdParams, context?: ServerCallContext): Promise<Task>;
|
||||
getTask(params: TaskQueryParams): Promise<Task>;
|
||||
cancelTask(params: TaskIdParams): Promise<Task>;
|
||||
|
||||
setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
context?: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
|
||||
getTaskPushNotificationConfig(
|
||||
params: TaskIdParams | GetTaskPushNotificationConfigParams,
|
||||
context?: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
getTaskPushNotificationConfig(
|
||||
params: TaskIdParams | GetTaskPushNotificationConfigParams
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
|
||||
listTaskPushNotificationConfigs(
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
context?: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig[]>;
|
||||
listTaskPushNotificationConfigs(
|
||||
params: ListTaskPushNotificationConfigParams
|
||||
): Promise<TaskPushNotificationConfig[]>;
|
||||
|
||||
deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
context?: ServerCallContext
|
||||
): Promise<void>;
|
||||
deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams
|
||||
): Promise<void>;
|
||||
|
||||
resubscribe(
|
||||
params: TaskIdParams,
|
||||
context?: ServerCallContext
|
||||
): AsyncGenerator<Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent, void, undefined>;
|
||||
}
|
||||
resubscribe(
|
||||
params: TaskIdParams
|
||||
): AsyncGenerator<
|
||||
| Task
|
||||
| TaskStatusUpdateEvent
|
||||
| TaskArtifactUpdateEvent,
|
||||
void,
|
||||
undefined
|
||||
>;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,181 +1,155 @@
|
||||
import { Message, Task, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '../types.js';
|
||||
import { ServerCallContext } from './context.js';
|
||||
import { AgentExecutionEvent } from './events/execution_event_bus.js';
|
||||
import { TaskStore } from './store.js';
|
||||
import {
|
||||
Message,
|
||||
Task,
|
||||
TaskArtifactUpdateEvent,
|
||||
TaskStatusUpdateEvent
|
||||
} from "../types.js";
|
||||
import { AgentExecutionEvent } from "./events/execution_event_bus.js";
|
||||
import { TaskStore } from "./store.js";
|
||||
|
||||
|
||||
export class ResultManager {
|
||||
private readonly taskStore: TaskStore;
|
||||
private readonly serverCallContext?: ServerCallContext;
|
||||
private taskStore: TaskStore;
|
||||
private currentTask?: Task;
|
||||
private latestUserMessage?: Message; // To add to history if a new task is created
|
||||
private finalMessageResult?: Message; // Stores the message if it's the final result
|
||||
|
||||
private currentTask?: Task;
|
||||
private latestUserMessage?: Message; // To add to history if a new task is created
|
||||
private finalMessageResult?: Message; // Stores the message if it's the final result
|
||||
constructor(taskStore: TaskStore) {
|
||||
this.taskStore = taskStore;
|
||||
}
|
||||
|
||||
constructor(taskStore: TaskStore, serverCallContext?: ServerCallContext) {
|
||||
this.taskStore = taskStore;
|
||||
this.serverCallContext = serverCallContext;
|
||||
}
|
||||
public setContext(latestUserMessage: Message): void {
|
||||
this.latestUserMessage = latestUserMessage;
|
||||
}
|
||||
|
||||
public setContext(latestUserMessage: Message): void {
|
||||
this.latestUserMessage = latestUserMessage;
|
||||
}
|
||||
/**
|
||||
* Processes an agent execution event and updates the task store.
|
||||
* @param event The agent execution event.
|
||||
*/
|
||||
public async processEvent(event: AgentExecutionEvent): Promise<void> {
|
||||
if (event.kind === 'message') {
|
||||
this.finalMessageResult = event as Message;
|
||||
// If a message is received, it's usually the final result,
|
||||
// but we continue processing to ensure task state (if any) is also saved.
|
||||
// The ExecutionEventQueue will stop after a message event.
|
||||
} else if (event.kind === 'task') {
|
||||
const taskEvent = event as Task;
|
||||
this.currentTask = { ...taskEvent }; // Make a copy
|
||||
|
||||
/**
|
||||
* Processes an agent execution event and updates the task store.
|
||||
* @param event The agent execution event.
|
||||
*/
|
||||
public async processEvent(event: AgentExecutionEvent): Promise<void> {
|
||||
if (event.kind === 'message') {
|
||||
this.finalMessageResult = event as Message;
|
||||
// If a message is received, it's usually the final result,
|
||||
// but we continue processing to ensure task state (if any) is also saved.
|
||||
// The ExecutionEventQueue will stop after a message event.
|
||||
} else if (event.kind === 'task') {
|
||||
const taskEvent = event as Task;
|
||||
this.currentTask = { ...taskEvent }; // Make a copy
|
||||
|
||||
// Ensure the latest user message is in history if not already present
|
||||
if (this.latestUserMessage) {
|
||||
if (
|
||||
!this.currentTask.history?.find(
|
||||
(msg) => msg.messageId === this.latestUserMessage!.messageId
|
||||
)
|
||||
) {
|
||||
this.currentTask.history = [this.latestUserMessage, ...(this.currentTask.history || [])];
|
||||
}
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else if (event.kind === 'status-update') {
|
||||
const updateEvent = event as TaskStatusUpdateEvent;
|
||||
if (this.currentTask && this.currentTask.id === updateEvent.taskId) {
|
||||
this.currentTask.status = updateEvent.status;
|
||||
if (updateEvent.status.message) {
|
||||
// Add message to history if not already present
|
||||
if (
|
||||
!this.currentTask.history?.find(
|
||||
(msg) => msg.messageId === updateEvent.status.message!.messageId
|
||||
)
|
||||
) {
|
||||
this.currentTask.history = [
|
||||
...(this.currentTask.history || []),
|
||||
updateEvent.status.message,
|
||||
];
|
||||
}
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else if (!this.currentTask && updateEvent.taskId) {
|
||||
// Potentially an update for a task we haven't seen the 'task' event for yet,
|
||||
// or we are rehydrating. Attempt to load.
|
||||
const loaded = await this.taskStore.load(updateEvent.taskId, this.serverCallContext);
|
||||
if (loaded) {
|
||||
this.currentTask = loaded;
|
||||
this.currentTask.status = updateEvent.status;
|
||||
if (updateEvent.status.message) {
|
||||
if (
|
||||
!this.currentTask.history?.find(
|
||||
(msg) => msg.messageId === updateEvent.status.message!.messageId
|
||||
)
|
||||
) {
|
||||
this.currentTask.history = [
|
||||
...(this.currentTask.history || []),
|
||||
updateEvent.status.message,
|
||||
];
|
||||
// Ensure the latest user message is in history if not already present
|
||||
if (this.latestUserMessage) {
|
||||
if (!this.currentTask.history?.find(msg => msg.messageId === this.latestUserMessage!.messageId)) {
|
||||
this.currentTask.history = [this.latestUserMessage, ...(this.currentTask.history || [])];
|
||||
}
|
||||
}
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else {
|
||||
console.warn(
|
||||
`ResultManager: Received status update for unknown task ${updateEvent.taskId}`
|
||||
);
|
||||
}
|
||||
}
|
||||
// If it's a final status update, the ExecutionEventQueue will stop.
|
||||
// The final result will be the currentTask.
|
||||
} else if (event.kind === 'artifact-update') {
|
||||
const artifactEvent = event as TaskArtifactUpdateEvent;
|
||||
if (this.currentTask && this.currentTask.id === artifactEvent.taskId) {
|
||||
if (!this.currentTask.artifacts) {
|
||||
this.currentTask.artifacts = [];
|
||||
}
|
||||
const existingArtifactIndex = this.currentTask.artifacts.findIndex(
|
||||
(art) => art.artifactId === artifactEvent.artifact.artifactId
|
||||
);
|
||||
if (existingArtifactIndex !== -1) {
|
||||
if (artifactEvent.append) {
|
||||
// Basic append logic, assuming parts are compatible
|
||||
// More sophisticated merging might be needed for specific part types
|
||||
const existingArtifact = this.currentTask.artifacts[existingArtifactIndex];
|
||||
existingArtifact.parts.push(...artifactEvent.artifact.parts);
|
||||
if (artifactEvent.artifact.description)
|
||||
existingArtifact.description = artifactEvent.artifact.description;
|
||||
if (artifactEvent.artifact.name) existingArtifact.name = artifactEvent.artifact.name;
|
||||
if (artifactEvent.artifact.metadata)
|
||||
existingArtifact.metadata = {
|
||||
...existingArtifact.metadata,
|
||||
...artifactEvent.artifact.metadata,
|
||||
};
|
||||
} else {
|
||||
this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
|
||||
}
|
||||
} else {
|
||||
this.currentTask.artifacts.push(artifactEvent.artifact);
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else if (!this.currentTask && artifactEvent.taskId) {
|
||||
// Similar to status update, try to load if task not in memory
|
||||
const loaded = await this.taskStore.load(artifactEvent.taskId, this.serverCallContext);
|
||||
if (loaded) {
|
||||
this.currentTask = loaded;
|
||||
if (!this.currentTask.artifacts) this.currentTask.artifacts = [];
|
||||
// Apply artifact update logic (as above)
|
||||
const existingArtifactIndex = this.currentTask.artifacts.findIndex(
|
||||
(art) => art.artifactId === artifactEvent.artifact.artifactId
|
||||
);
|
||||
if (existingArtifactIndex !== -1) {
|
||||
if (artifactEvent.append) {
|
||||
this.currentTask.artifacts[existingArtifactIndex].parts.push(
|
||||
...artifactEvent.artifact.parts
|
||||
);
|
||||
} else {
|
||||
this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
|
||||
await this.saveCurrentTask();
|
||||
} else if (event.kind === 'status-update') {
|
||||
const updateEvent = event as TaskStatusUpdateEvent;
|
||||
if (this.currentTask && this.currentTask.id === updateEvent.taskId) {
|
||||
this.currentTask.status = updateEvent.status;
|
||||
if (updateEvent.status.message) {
|
||||
// Add message to history if not already present
|
||||
if (!this.currentTask.history?.find(msg => msg.messageId === updateEvent.status.message!.messageId)) {
|
||||
this.currentTask.history = [...(this.currentTask.history || []), updateEvent.status.message];
|
||||
}
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else if (!this.currentTask && updateEvent.taskId) {
|
||||
// Potentially an update for a task we haven't seen the 'task' event for yet,
|
||||
// or we are rehydrating. Attempt to load.
|
||||
const loaded = await this.taskStore.load(updateEvent.taskId);
|
||||
if (loaded) {
|
||||
this.currentTask = loaded;
|
||||
this.currentTask.status = updateEvent.status;
|
||||
if (updateEvent.status.message) {
|
||||
if (!this.currentTask.history?.find(msg => msg.messageId === updateEvent.status.message!.messageId)) {
|
||||
this.currentTask.history = [...(this.currentTask.history || []), updateEvent.status.message];
|
||||
}
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else {
|
||||
console.warn(`ResultManager: Received status update for unknown task ${updateEvent.taskId}`);
|
||||
}
|
||||
}
|
||||
// If it's a final status update, the ExecutionEventQueue will stop.
|
||||
// The final result will be the currentTask.
|
||||
} else if (event.kind === 'artifact-update') {
|
||||
const artifactEvent = event as TaskArtifactUpdateEvent;
|
||||
if (this.currentTask && this.currentTask.id === artifactEvent.taskId) {
|
||||
if (!this.currentTask.artifacts) {
|
||||
this.currentTask.artifacts = [];
|
||||
}
|
||||
const existingArtifactIndex = this.currentTask.artifacts.findIndex(
|
||||
(art) => art.artifactId === artifactEvent.artifact.artifactId
|
||||
);
|
||||
if (existingArtifactIndex !== -1) {
|
||||
if (artifactEvent.append) {
|
||||
// Basic append logic, assuming parts are compatible
|
||||
// More sophisticated merging might be needed for specific part types
|
||||
const existingArtifact = this.currentTask.artifacts[existingArtifactIndex];
|
||||
existingArtifact.parts.push(...artifactEvent.artifact.parts);
|
||||
if (artifactEvent.artifact.description) existingArtifact.description = artifactEvent.artifact.description;
|
||||
if (artifactEvent.artifact.name) existingArtifact.name = artifactEvent.artifact.name;
|
||||
if (artifactEvent.artifact.metadata) existingArtifact.metadata = { ...existingArtifact.metadata, ...artifactEvent.artifact.metadata };
|
||||
|
||||
} else {
|
||||
this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
|
||||
}
|
||||
} else {
|
||||
this.currentTask.artifacts.push(artifactEvent.artifact);
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else if (!this.currentTask && artifactEvent.taskId) {
|
||||
// Similar to status update, try to load if task not in memory
|
||||
const loaded = await this.taskStore.load(artifactEvent.taskId);
|
||||
if (loaded) {
|
||||
this.currentTask = loaded;
|
||||
if (!this.currentTask.artifacts) this.currentTask.artifacts = [];
|
||||
// Apply artifact update logic (as above)
|
||||
const existingArtifactIndex = this.currentTask.artifacts.findIndex(
|
||||
(art) => art.artifactId === artifactEvent.artifact.artifactId
|
||||
);
|
||||
if (existingArtifactIndex !== -1) {
|
||||
if (artifactEvent.append) {
|
||||
this.currentTask.artifacts[existingArtifactIndex].parts.push(...artifactEvent.artifact.parts);
|
||||
} else {
|
||||
this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
|
||||
}
|
||||
} else {
|
||||
this.currentTask.artifacts.push(artifactEvent.artifact);
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else {
|
||||
console.warn(`ResultManager: Received artifact update for unknown task ${artifactEvent.taskId}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.currentTask.artifacts.push(artifactEvent.artifact);
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else {
|
||||
console.warn(
|
||||
`ResultManager: Received artifact update for unknown task ${artifactEvent.taskId}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async saveCurrentTask(): Promise<void> {
|
||||
if (this.currentTask) {
|
||||
await this.taskStore.save(this.currentTask, this.serverCallContext);
|
||||
private async saveCurrentTask(): Promise<void> {
|
||||
if (this.currentTask) {
|
||||
await this.taskStore.save(this.currentTask);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the final result, which could be a Message or a Task.
|
||||
* This should be called after the event stream has been fully processed.
|
||||
* @returns The final Message or the current Task.
|
||||
*/
|
||||
public getFinalResult(): Message | Task | undefined {
|
||||
if (this.finalMessageResult) {
|
||||
return this.finalMessageResult;
|
||||
/**
|
||||
* Gets the final result, which could be a Message or a Task.
|
||||
* This should be called after the event stream has been fully processed.
|
||||
* @returns The final Message or the current Task.
|
||||
*/
|
||||
public getFinalResult(): Message | Task | undefined {
|
||||
if (this.finalMessageResult) {
|
||||
return this.finalMessageResult;
|
||||
}
|
||||
return this.currentTask;
|
||||
}
|
||||
return this.currentTask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the task currently being managed by this ResultManager instance.
|
||||
* This task could be one that was started with or one created during agent execution.
|
||||
* @returns The current Task or undefined if no task is active.
|
||||
*/
|
||||
public getCurrentTask(): Task | undefined {
|
||||
return this.currentTask;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Gets the task currently being managed by this ResultManager instance.
|
||||
* This task could be one that was started with or one created during agent execution.
|
||||
* @returns The current Task or undefined if no task is active.
|
||||
*/
|
||||
public getCurrentTask(): Task | undefined {
|
||||
return this.currentTask;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user