Compare commits
7 Commits
epic/1.0_b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1d6c76830 | ||
|
|
87cd79774f | ||
|
|
c8b40684c8 | ||
|
|
6bacf4f605 | ||
|
|
e2dc048b2a | ||
|
|
1f219b0c85 | ||
|
|
2220644539 |
@ -5,18 +5,81 @@
|
||||
//
|
||||
exports[`TypeScript Strict Mode`] = {
|
||||
value: `{
|
||||
"src/server/events/execution_event_bus.ts:3165663610": [
|
||||
"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:1777885052": [
|
||||
[208, 50, 17, "tsc: Argument of type \'unknown\' is not assignable to parameter of type \'Message | Task | TaskArtifactUpdateEvent | TaskStatusUpdateEvent\'.", "3749434707"]
|
||||
"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/transports/jsonrpc/jsonrpc_transport_handler.ts:1270528550": [
|
||||
[89, 12, 10, "tsc: Variable \'rpcRequest\' is used before being assigned.", "3927050741"]
|
||||
"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/types/converters/to_proto.ts:1276072555": [
|
||||
[57, 52, 19, "tsc: Function lacks ending return statement and return type does not include \'undefined\'.", "2245381585"]
|
||||
"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"]
|
||||
]
|
||||
}`
|
||||
};
|
||||
|
||||
6
.github/workflows/build-tests.yml
vendored
6
.github/workflows/build-tests.yml
vendored
@ -4,9 +4,9 @@ name: Run Build Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main", "epic/**" ]
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main", "epic/**" ]
|
||||
branches: [ "main" ]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
@ -22,7 +22,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 18
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
|
||||
6
.github/workflows/lint.yml
vendored
6
.github/workflows/lint.yml
vendored
@ -2,9 +2,9 @@ name: Run Linter & Formatter
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main", "epic/**" ]
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main", "epic/**" ]
|
||||
branches: [ "main" ]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
@ -19,7 +19,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 18
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: |
|
||||
|
||||
2
.github/workflows/run-tck.yaml
vendored
2
.github/workflows/run-tck.yaml
vendored
@ -35,7 +35,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20, 22, 24]
|
||||
node-version: [18, 20, 22, 24]
|
||||
steps:
|
||||
- name: Checkout a2a-js
|
||||
uses: actions/checkout@v4
|
||||
|
||||
7
.github/workflows/unit-tests.yml
vendored
7
.github/workflows/unit-tests.yml
vendored
@ -20,7 +20,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20, 22, 24]
|
||||
node-version: [18, 20, 22, 24]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
@ -47,7 +47,10 @@ jobs:
|
||||
- run: npm ci
|
||||
- run: npm run test:edge
|
||||
|
||||
# Run coverage once to generate a report.
|
||||
# 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:
|
||||
|
||||
@ -11,7 +11,7 @@ The SDK implements the **A2A Protocol Specification v0.3.0**.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
* **Language**: TypeScript (Node.js >= 20)
|
||||
* **Language**: TypeScript (Node.js >= 18)
|
||||
* **Build System**: `tsup` (Outputs ESM and CJS)
|
||||
* **Testing Framework**: `vitest`
|
||||
* **Linting/Formatting**: `eslint`, `prettier`
|
||||
|
||||
12
package-lock.json
generated
12
package-lock.json
generated
@ -5147,9 +5147,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/flatted": {
|
||||
"version": "3.3.3",
|
||||
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz",
|
||||
"integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==",
|
||||
"version": "3.4.2",
|
||||
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz",
|
||||
"integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
@ -7673,9 +7673,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "7.3.0",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.0.tgz",
|
||||
"integrity": "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg==",
|
||||
"version": "7.3.2",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
|
||||
"integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
@ -8,7 +8,7 @@
|
||||
"url": "git+https://github.com/a2aproject/a2a-js.git"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
"node": ">=18"
|
||||
},
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
27
src/a2a_response.ts
Normal file
27
src/a2a_response.ts
Normal file
@ -0,0 +1,27 @@
|
||||
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.
|
||||
*/
|
||||
export type A2AResponse =
|
||||
| SendMessageResponse
|
||||
| SendStreamingMessageResponse
|
||||
| GetTaskResponse
|
||||
| CancelTaskResponse
|
||||
| SetTaskPushNotificationConfigResponse
|
||||
| GetTaskPushNotificationConfigResponse
|
||||
| ListTaskPushNotificationConfigSuccessResponse
|
||||
| DeleteTaskPushNotificationConfigSuccessResponse
|
||||
| GetAuthenticatedExtendedCardSuccessResponse
|
||||
| JSONRPCErrorResponse; // Catch-all for other error responses
|
||||
@ -1,5 +1,7 @@
|
||||
import { AGENT_CARD_PATH } from '../constants.js';
|
||||
import { AgentCard } from '../index.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;
|
||||
@ -54,8 +56,8 @@ export class DefaultAgentCardResolver implements AgentCardResolver {
|
||||
*/
|
||||
private normalizeAgentCard(card: unknown): AgentCard {
|
||||
if (this.isProtoAgentCard(card)) {
|
||||
const parsedProto = AgentCard.fromJSON(card);
|
||||
return parsedProto;
|
||||
const parsedProto = PBAgentCard.fromJSON(card);
|
||||
return FromProto.agentCard(parsedProto);
|
||||
}
|
||||
return card as AgentCard;
|
||||
}
|
||||
|
||||
487
src/client/client.ts
Normal file
487
src/client/client.ts
Normal file
@ -0,0 +1,487 @@
|
||||
import {
|
||||
AgentCard,
|
||||
JSONRPCResponse,
|
||||
MessageSendParams,
|
||||
SendMessageResponse,
|
||||
TaskQueryParams,
|
||||
GetTaskResponse,
|
||||
TaskIdParams,
|
||||
CancelTaskResponse,
|
||||
TaskPushNotificationConfig, // Renamed from PushNotificationConfigParams for direct schema alignment
|
||||
SetTaskPushNotificationConfigResponse,
|
||||
GetTaskPushNotificationConfigResponse,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigResponse,
|
||||
DeleteTaskPushNotificationConfigResponse,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
Message,
|
||||
Task,
|
||||
TaskArtifactUpdateEvent,
|
||||
TaskStatusUpdateEvent,
|
||||
A2ARequest,
|
||||
JSONRPCErrorResponse,
|
||||
} from '../types.js'; // Assuming schema.ts is in the same directory or appropriately pathed
|
||||
import { AGENT_CARD_PATH } from '../constants.js';
|
||||
import { JsonRpcTransport } from './transports/json_rpc_transport.js';
|
||||
import { RequestOptions } from './multitransport-client.js';
|
||||
|
||||
export type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
|
||||
|
||||
export type SendMessageResult = Message | Task;
|
||||
|
||||
export interface A2AClientOptions {
|
||||
agentCardPath?: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
/**
|
||||
* A2AClient is a TypeScript HTTP client for interacting with A2A-compliant agents.
|
||||
* Only JSON-RPC transport is supported.
|
||||
* @deprecated Use {@link ClientFactory}
|
||||
*/
|
||||
export class A2AClient {
|
||||
private static emptyOptions?: RequestOptions = undefined;
|
||||
|
||||
private readonly agentCardPromise: Promise<AgentCard>;
|
||||
private readonly customFetchImpl?: typeof fetch;
|
||||
private serviceEndpointUrl?: string; // To be populated from AgentCard after fetchin
|
||||
|
||||
// A2AClient is built around JSON-RPC types, so it will only support JSON-RPC transport, new client with transport agnostic interface is going to be created for multi-transport.
|
||||
// New transport abstraction isn't going to expose individual transport specific fields, so to keep returning JSON-RPC IDs here for compatibility,
|
||||
// keep counter here and pass it to JsonRpcTransport via an optional idOverride parameter (which is not visible via transport-agnostic A2ATransport interface).
|
||||
private transport?: JsonRpcTransport;
|
||||
private requestIdCounter: number = 1;
|
||||
|
||||
/**
|
||||
* Constructs an A2AClient instance from an AgentCard.
|
||||
* @param agentCard The AgentCard object.
|
||||
* @param options Optional. The options for the A2AClient including the fetch/auth implementation.
|
||||
*/
|
||||
constructor(agentCard: AgentCard | string, options?: A2AClientOptions) {
|
||||
this.customFetchImpl = options?.fetchImpl;
|
||||
if (typeof agentCard === 'string') {
|
||||
console.warn(
|
||||
'Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead.'
|
||||
);
|
||||
this.agentCardPromise = this._fetchAndCacheAgentCard(agentCard, options?.agentCardPath);
|
||||
} else {
|
||||
if (!agentCard.url) {
|
||||
throw new Error(
|
||||
"Provided Agent Card does not contain a valid 'url' for the service endpoint."
|
||||
);
|
||||
}
|
||||
this.serviceEndpointUrl = agentCard.url;
|
||||
this.agentCardPromise = Promise.resolve(agentCard);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamically resolves the fetch implementation to use for requests.
|
||||
* Prefers a custom implementation if provided, otherwise falls back to the global fetch.
|
||||
* @returns The fetch implementation.
|
||||
* @param args Arguments to pass to the fetch implementation.
|
||||
* @throws If no fetch implementation is available.
|
||||
*/
|
||||
private _fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
|
||||
if (this.customFetchImpl) {
|
||||
return this.customFetchImpl(...args);
|
||||
}
|
||||
if (typeof fetch === 'function') {
|
||||
return fetch(...args);
|
||||
}
|
||||
throw new Error(
|
||||
'A `fetch` implementation was not provided and is not available in the global scope. ' +
|
||||
'Please provide a `fetchImpl` in the A2AClientOptions. ' +
|
||||
'For earlier Node.js versions (pre-v18), you can use a library like `node-fetch`.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an A2AClient instance by fetching the AgentCard from a URL then constructing the A2AClient.
|
||||
* @param agentCardUrl The URL of the agent card.
|
||||
* @param options Optional. The options for the A2AClient including the fetch/auth implementation.
|
||||
* @returns A Promise that resolves to a new A2AClient instance.
|
||||
*/
|
||||
public static async fromCardUrl(
|
||||
agentCardUrl: string,
|
||||
options?: A2AClientOptions
|
||||
): Promise<A2AClient> {
|
||||
const fetchImpl = options?.fetchImpl;
|
||||
const requestInit = {
|
||||
headers: { Accept: 'application/json' },
|
||||
};
|
||||
|
||||
let response: Response;
|
||||
if (fetchImpl) {
|
||||
response = await fetchImpl(agentCardUrl, requestInit);
|
||||
} else if (typeof fetch === 'function') {
|
||||
// Use the global fetch implementation if no custom one is provided.
|
||||
response = await fetch(agentCardUrl, requestInit);
|
||||
} else {
|
||||
throw new Error(
|
||||
'A `fetch` implementation was not provided and is not available in the global scope. ' +
|
||||
'Please provide a `fetchImpl` in the A2AClientOptions. ' +
|
||||
'For earlier Node.js versions (pre-v18), you can use a library like `node-fetch`.'
|
||||
);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
|
||||
let agentCard: AgentCard;
|
||||
try {
|
||||
agentCard = await response.json();
|
||||
} catch (error) {
|
||||
console.error('Failed to parse Agent Card JSON:', error);
|
||||
throw new Error(
|
||||
`Failed to parse Agent Card JSON from ${agentCardUrl}. Original error: ${(error as Error).message}`
|
||||
);
|
||||
}
|
||||
|
||||
return new A2AClient(agentCard, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to the agent.
|
||||
* The behavior (blocking/non-blocking) and push notification configuration
|
||||
* are specified within the `params.configuration` object.
|
||||
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
|
||||
* @param params The parameters for sending the message, including the message content and configuration.
|
||||
* @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
|
||||
*/
|
||||
public async sendMessage(params: MessageSendParams): Promise<SendMessageResponse> {
|
||||
return await this.invokeJsonRpc<MessageSendParams, SendMessageResponse>(
|
||||
(t, p, id) => t.sendMessage(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
|
||||
* Push notification configuration can be specified in `params.configuration`.
|
||||
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
|
||||
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
|
||||
* @param params The parameters for sending the message.
|
||||
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
|
||||
* The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
|
||||
*/
|
||||
public async *sendMessageStream(
|
||||
params: MessageSendParams
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const agentCard = await this.agentCardPromise; // Ensure agent card is fetched
|
||||
if (!agentCard.capabilities?.streaming) {
|
||||
throw new Error(
|
||||
'Agent does not support streaming (AgentCard.capabilities.streaming is not true).'
|
||||
);
|
||||
}
|
||||
|
||||
const transport = await this._getOrCreateTransport();
|
||||
yield* transport.sendMessageStream(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets or updates the push notification configuration for a given task.
|
||||
* Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
|
||||
* @param params Parameters containing the taskId and the TaskPushNotificationConfig.
|
||||
* @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig
|
||||
): Promise<SetTaskPushNotificationConfigResponse> {
|
||||
const agentCard = await this.agentCardPromise;
|
||||
if (!agentCard.capabilities?.pushNotifications) {
|
||||
throw new Error(
|
||||
'Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true).'
|
||||
);
|
||||
}
|
||||
return await this.invokeJsonRpc<
|
||||
TaskPushNotificationConfig,
|
||||
SetTaskPushNotificationConfigResponse
|
||||
>((t, p, id) => t.setTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the push notification configuration for a given task.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async getTaskPushNotificationConfig(
|
||||
params: TaskIdParams
|
||||
): Promise<GetTaskPushNotificationConfigResponse> {
|
||||
return await this.invokeJsonRpc<TaskIdParams, GetTaskPushNotificationConfigResponse>(
|
||||
(t, p, id) => t.getTaskPushNotificationConfig(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the push notification configurations for a given task.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to ListTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams
|
||||
): Promise<ListTaskPushNotificationConfigResponse> {
|
||||
return await this.invokeJsonRpc<
|
||||
ListTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigResponse
|
||||
>((t, p, id) => t.listTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the push notification configuration for a given task.
|
||||
* @param params Parameters containing the taskId and push notification configuration ID.
|
||||
* @returns A Promise resolving to DeleteTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams
|
||||
): Promise<DeleteTaskPushNotificationConfigResponse> {
|
||||
return await this.invokeJsonRpc<
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigResponse
|
||||
>((t, p, id) => t.deleteTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a task by its ID.
|
||||
* @param params Parameters containing the taskId and optional historyLength.
|
||||
* @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
|
||||
*/
|
||||
public async getTask(params: TaskQueryParams): Promise<GetTaskResponse> {
|
||||
return await this.invokeJsonRpc<TaskQueryParams, GetTaskResponse>(
|
||||
(t, p, id) => t.getTask(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels a task by its ID.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
|
||||
*/
|
||||
public async cancelTask(params: TaskIdParams): Promise<CancelTaskResponse> {
|
||||
return await this.invokeJsonRpc<TaskIdParams, CancelTaskResponse>(
|
||||
(t, p, id) => t.cancelTask(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @template TExtensionParams The type of parameters for the custom extension method.
|
||||
* @template TExtensionResponse The type of response expected from the custom extension method.
|
||||
* This should extend JSONRPCResponse. This ensures the extension response is still a valid A2A response.
|
||||
* @param method Custom JSON-RPC method defined in the AgentCard's extensions.
|
||||
* @param params Extension paramters defined in the AgentCard's extensions.
|
||||
* @returns A Promise that resolves to the RPC response.
|
||||
*/
|
||||
public async callExtensionMethod<TExtensionParams, TExtensionResponse extends JSONRPCResponse>(
|
||||
method: string,
|
||||
params: TExtensionParams
|
||||
) {
|
||||
const transport = await this._getOrCreateTransport();
|
||||
try {
|
||||
return await transport.callExtensionMethod<TExtensionParams, TExtensionResponse>(
|
||||
method,
|
||||
params,
|
||||
this.requestIdCounter++
|
||||
);
|
||||
} catch (e) {
|
||||
// For compatibility, return JSON-RPC errors as errors instead of throwing transport-agnostic errors
|
||||
// produced by JsonRpcTransport.
|
||||
const errorResponse = extractJSONRPCError(e);
|
||||
if (errorResponse) {
|
||||
return errorResponse as TExtensionResponse;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resubscribes to a task's event stream using Server-Sent Events (SSE).
|
||||
* This is used if a previous SSE connection for an active task was broken.
|
||||
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
|
||||
*/
|
||||
public async *resubscribeTask(
|
||||
params: TaskIdParams
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const agentCard = await this.agentCardPromise;
|
||||
if (!agentCard.capabilities?.streaming) {
|
||||
throw new Error('Agent does not support streaming (required for tasks/resubscribe).');
|
||||
}
|
||||
|
||||
const transport = await this._getOrCreateTransport();
|
||||
yield* transport.resubscribeTask(params);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Functions used to support old A2AClient Constructor to be deprecated soon
|
||||
// TODOs:
|
||||
// * remove `agentCardPromise`, and just use agentCard initialized
|
||||
// * _getServiceEndpoint can be made synchronous or deleted and accessed via
|
||||
// agentCard.url
|
||||
// * getAgentCard changed to this.agentCard
|
||||
// * delete resolveAgentCardUrl(), _fetchAndCacheAgentCard(),
|
||||
// agentCardPath from A2AClientOptions
|
||||
// * delete _getOrCreateTransport
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private async _getOrCreateTransport(): Promise<JsonRpcTransport> {
|
||||
if (this.transport) {
|
||||
return this.transport;
|
||||
}
|
||||
|
||||
const endpoint = await this._getServiceEndpoint();
|
||||
this.transport = new JsonRpcTransport({ fetchImpl: this.customFetchImpl, endpoint: endpoint });
|
||||
return this.transport;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
|
||||
* This method is called by the constructor.
|
||||
* @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com)
|
||||
* @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
|
||||
* @returns A Promise that resolves to the AgentCard.
|
||||
*/
|
||||
private async _fetchAndCacheAgentCard(
|
||||
agentBaseUrl: string,
|
||||
agentCardPath?: string
|
||||
): Promise<AgentCard> {
|
||||
try {
|
||||
const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
|
||||
const response = await this._fetch(agentCardUrl, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
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."
|
||||
);
|
||||
}
|
||||
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);
|
||||
// Allow the promise to reject so users of agentCardPromise can handle it.
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the Agent Card.
|
||||
* 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
|
||||
* 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> {
|
||||
if (agentBaseUrl) {
|
||||
const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
|
||||
|
||||
const response = await this._fetch(agentCardUrl, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
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.
|
||||
*/
|
||||
private async _getServiceEndpoint(): Promise<string> {
|
||||
if (this.serviceEndpointUrl) {
|
||||
return this.serviceEndpointUrl;
|
||||
}
|
||||
// If serviceEndpointUrl is not set, it means the agent card fetch is pending or failed.
|
||||
// Awaiting agentCardPromise will either resolve it or throw if fetching failed.
|
||||
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.'
|
||||
);
|
||||
}
|
||||
return this.serviceEndpointUrl;
|
||||
}
|
||||
|
||||
private async invokeJsonRpc<TParams extends JsonRpcParams, TResponse extends JSONRPCResponse>(
|
||||
caller: JsonRpcCaller<TParams, TResponse>,
|
||||
params?: TParams
|
||||
): Promise<TResponse> {
|
||||
const transport = await this._getOrCreateTransport();
|
||||
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;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function extractJSONRPCError(error: unknown): JSONRPCErrorResponse {
|
||||
if (
|
||||
error instanceof Object &&
|
||||
'errorResponse' in error &&
|
||||
error.errorResponse instanceof Object &&
|
||||
'jsonrpc' in error.errorResponse &&
|
||||
error.errorResponse.jsonrpc === '2.0' &&
|
||||
'error' in error.errorResponse &&
|
||||
error.errorResponse.error !== null
|
||||
) {
|
||||
return error.errorResponse as JSONRPCErrorResponse;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Utility unexported types to properly factor out common "compatibility" logic via invokeJsonRpc.
|
||||
type ParamsOf<T> = T extends { params: unknown } ? T['params'] : undefined;
|
||||
type ResultOf<T> = T extends { result: unknown } ? T['result'] : void;
|
||||
type JsonRpcParams = ParamsOf<A2ARequest>;
|
||||
type JsonRpcCaller<TParams extends JsonRpcParams, TResponse extends JSONRPCResponse> = (
|
||||
transport: JsonRpcTransport,
|
||||
params: TParams,
|
||||
idOverride: number
|
||||
) => Promise<ResultOf<TResponse>>;
|
||||
@ -1,5 +1,5 @@
|
||||
import { TransportProtocolName } from '../core.js';
|
||||
import { AgentCard } from '../index.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';
|
||||
@ -97,13 +97,16 @@ export class ClientFactory {
|
||||
* Creates a new client from the provided agent card.
|
||||
*/
|
||||
async createFromAgentCard(agentCard: AgentCard): Promise<Client> {
|
||||
const interfaces = agentCard.supportedInterfaces ?? [];
|
||||
const urlsPerAgentTransports = new CaseInsensitiveMap<string>(
|
||||
interfaces.map((i) => [i.protocolBinding, i.url])
|
||||
);
|
||||
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 ?? []),
|
||||
...interfaces.map((i) => i.protocolBinding),
|
||||
agentCardPreferred,
|
||||
...additionalInterfaces.map((i) => i.transport),
|
||||
];
|
||||
for (const transport of transportsByPreference) {
|
||||
const url = urlsPerAgentTransports.get(transport);
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
* 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,
|
||||
@ -42,5 +44,4 @@ export {
|
||||
TaskNotCancelableError,
|
||||
TaskNotFoundError,
|
||||
UnsupportedOperationError,
|
||||
RequestMalformedError,
|
||||
} from '../errors.js';
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { AgentCard, A2AStreamEventData } from '../index.js';
|
||||
import { AgentCard } from '../types.js';
|
||||
import { A2AStreamEventData } from './client.js';
|
||||
import { Client } from './multitransport-client.js';
|
||||
import { RequestOptions } from './multitransport-client.js';
|
||||
|
||||
@ -120,7 +121,7 @@ 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 (...args: never[]) => infer R
|
||||
T[M] extends (payload: unknown) => infer R
|
||||
? { readonly method: M; value: Awaited<R> }
|
||||
: never;
|
||||
}[TMembers];
|
||||
|
||||
@ -1,21 +1,16 @@
|
||||
import { PushNotificationNotSupportedError } from '../errors.js';
|
||||
import {
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
Task,
|
||||
TaskIdParams,
|
||||
TaskQueryParams,
|
||||
PushNotificationConfig,
|
||||
AgentCard,
|
||||
A2AStreamEventData,
|
||||
SendMessageResult,
|
||||
} from '../index.js';
|
||||
import {
|
||||
CancelTaskRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
GetTaskRequest,
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
SendMessageConfiguration,
|
||||
SendMessageRequest,
|
||||
SubscribeToTaskRequest,
|
||||
} from '../types/pb/a2a.js';
|
||||
} from '../types.js';
|
||||
import { A2AStreamEventData, SendMessageResult } from './client.js';
|
||||
import { ClientCallContext } from './context.js';
|
||||
import {
|
||||
CallInterceptor,
|
||||
@ -43,7 +38,7 @@ export interface ClientConfig {
|
||||
/**
|
||||
* Specifies the default push notification configuration to apply for every Task.
|
||||
*/
|
||||
pushNotificationConfig?: TaskPushNotificationConfig;
|
||||
pushNotificationConfig?: PushNotificationConfig;
|
||||
|
||||
/**
|
||||
* Interceptors invoked for each request.
|
||||
@ -81,7 +76,7 @@ export class Client {
|
||||
* Otherwise it will return the current agent card value.
|
||||
*/
|
||||
async getAgentCard(options?: RequestOptions): Promise<AgentCard> {
|
||||
if (this.agentCard.capabilities?.extendedAgentCard) {
|
||||
if (this.agentCard.supportsAuthenticatedExtendedCard) {
|
||||
this.agentCard = await this.executeWithInterceptors(
|
||||
{ method: 'getAgentCard' },
|
||||
options,
|
||||
@ -95,10 +90,10 @@ export class Client {
|
||||
* Sends a message to an agent to initiate a new interaction or to continue an existing one.
|
||||
* Uses blocking mode by default.
|
||||
*/
|
||||
sendMessage(params: SendMessageRequest, options?: RequestOptions): Promise<SendMessageResult> {
|
||||
sendMessage(params: MessageSendParams, options?: RequestOptions): Promise<SendMessageResult> {
|
||||
params = this.applyClientConfig({
|
||||
params,
|
||||
returnImmediately: this.config?.polling ?? false,
|
||||
blocking: !(this.config?.polling ?? false),
|
||||
});
|
||||
|
||||
return this.executeWithInterceptors(
|
||||
@ -113,12 +108,12 @@ export class Client {
|
||||
* Performs fallback to non-streaming if not supported by the agent.
|
||||
*/
|
||||
async *sendMessageStream(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const method = 'sendMessageStream';
|
||||
|
||||
params = this.applyClientConfig({ params, returnImmediately: false });
|
||||
params = this.applyClientConfig({ params, blocking: true });
|
||||
const beforeArgs: BeforeArgs<'sendMessageStream'> = {
|
||||
input: { method, value: params },
|
||||
agentCard: this.agentCard,
|
||||
@ -138,7 +133,7 @@ export class Client {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.agentCard.capabilities?.streaming) {
|
||||
if (!this.agentCard.capabilities.streaming) {
|
||||
const result = await this.transport.sendMessage(beforeArgs.input.value, beforeArgs.options);
|
||||
const afterArgs: AfterArgs<'sendMessageStream'> = {
|
||||
result: { method, value: result },
|
||||
@ -167,21 +162,21 @@ export class Client {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a push notification configuration for a specified task.
|
||||
* Sets or updates the push notification configuration for a specified task.
|
||||
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
||||
*/
|
||||
createTaskPushNotificationConfig(
|
||||
setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
if (!this.agentCard.capabilities?.pushNotifications) {
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
}
|
||||
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'createTaskPushNotificationConfig', value: params },
|
||||
{ method: 'setTaskPushNotificationConfig', value: params },
|
||||
options,
|
||||
this.transport.createTaskPushNotificationConfig.bind(this.transport)
|
||||
this.transport.setTaskPushNotificationConfig.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
@ -190,10 +185,10 @@ export class Client {
|
||||
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
||||
*/
|
||||
getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigRequest,
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
if (!this.agentCard.capabilities?.pushNotifications) {
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
}
|
||||
|
||||
@ -209,10 +204,10 @@ export class Client {
|
||||
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
||||
*/
|
||||
listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigsRequest,
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
if (!this.agentCard.capabilities?.pushNotifications) {
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
}
|
||||
|
||||
@ -227,7 +222,7 @@ export class Client {
|
||||
* Deletes an associated push notification configuration for a task.
|
||||
*/
|
||||
deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigRequest,
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<void> {
|
||||
return this.executeWithInterceptors(
|
||||
@ -240,7 +235,7 @@ export class Client {
|
||||
/**
|
||||
* Retrieves the current state (including status, artifacts, and optionally history) of a previously initiated task.
|
||||
*/
|
||||
getTask(params: GetTaskRequest, options?: RequestOptions): Promise<Task> {
|
||||
getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task> {
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'getTask', value: params },
|
||||
options,
|
||||
@ -252,7 +247,7 @@ export class Client {
|
||||
* 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: CancelTaskRequest, options?: RequestOptions): Promise<Task> {
|
||||
cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task> {
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'cancelTask', value: params },
|
||||
options,
|
||||
@ -264,7 +259,7 @@ export class Client {
|
||||
* Allows a client to reconnect to an updates stream for an ongoing task after a previous connection was interrupted.
|
||||
*/
|
||||
async *resubscribeTask(
|
||||
params: SubscribeToTaskRequest,
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const method = 'resubscribeTask';
|
||||
@ -307,28 +302,20 @@ export class Client {
|
||||
|
||||
private applyClientConfig({
|
||||
params,
|
||||
returnImmediately,
|
||||
blocking,
|
||||
}: {
|
||||
params: SendMessageRequest;
|
||||
returnImmediately: boolean;
|
||||
}): SendMessageRequest {
|
||||
const result = {
|
||||
...params,
|
||||
configuration: params.configuration ?? ({} as SendMessageConfiguration),
|
||||
};
|
||||
params: MessageSendParams;
|
||||
blocking: boolean;
|
||||
}): MessageSendParams {
|
||||
const result = { ...params, configuration: params.configuration ?? {} };
|
||||
|
||||
result.configuration.acceptedOutputModes =
|
||||
result.configuration.acceptedOutputModes ??
|
||||
this.config?.acceptedOutputModes ??
|
||||
([] as string[]);
|
||||
result.configuration.historyLength ??= 0;
|
||||
|
||||
if (!result.configuration.taskPushNotificationConfig && this.config?.pushNotificationConfig) {
|
||||
if (params.message?.taskId !== undefined) {
|
||||
result.configuration.taskPushNotificationConfig = this.config.pushNotificationConfig;
|
||||
}
|
||||
if (!result.configuration.acceptedOutputModes && this.config?.acceptedOutputModes) {
|
||||
result.configuration.acceptedOutputModes = this.config.acceptedOutputModes;
|
||||
}
|
||||
result.configuration.returnImmediately ??= returnImmediately;
|
||||
if (!result.configuration.pushNotificationConfig && this.config?.pushNotificationConfig) {
|
||||
result.configuration.pushNotificationConfig = this.config.pushNotificationConfig;
|
||||
}
|
||||
result.configuration.blocking ??= blocking;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@ -1,24 +1,21 @@
|
||||
import * as grpc from '@grpc/grpc-js';
|
||||
import { TransportProtocolName } from '../../../core.js';
|
||||
import { A2AServiceClient } from '../../../grpc/pb/a2a_services.js';
|
||||
import {
|
||||
A2AServiceClient,
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
GetExtendedAgentCardRequest,
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
SubscribeToTaskRequest,
|
||||
} from '../../../grpc/pb/a2a.js';
|
||||
import { Task, AgentCard } from '../../../types/pb/a2a.js';
|
||||
import {
|
||||
CancelTaskRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
GetTaskRequest,
|
||||
SendMessageRequest,
|
||||
A2AStreamEventData,
|
||||
SendMessageResult,
|
||||
} from '../../../index.js';
|
||||
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 {
|
||||
@ -27,11 +24,8 @@ import {
|
||||
TaskNotFoundError,
|
||||
TaskNotCancelableError,
|
||||
UnsupportedOperationError,
|
||||
RequestMalformedError,
|
||||
} from '../../../errors.js';
|
||||
|
||||
const PROTOCOL_NAME: TransportProtocolName = 'GRPC';
|
||||
|
||||
type GrpcUnaryCall<TReq, TRes> = (
|
||||
request: TReq,
|
||||
metadata: grpc.Metadata,
|
||||
@ -63,27 +57,20 @@ export class GrpcTransport implements Transport {
|
||||
);
|
||||
}
|
||||
|
||||
get protocolName(): string {
|
||||
return PROTOCOL_NAME;
|
||||
}
|
||||
|
||||
async getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard> {
|
||||
const rpcResponse = await this._sendGrpcRequest<
|
||||
GetExtendedAgentCardRequest,
|
||||
AgentCard,
|
||||
AgentCard
|
||||
>(
|
||||
'getExtendedAgentCard',
|
||||
{ tenant: '' },
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'getAgentCard',
|
||||
undefined,
|
||||
options,
|
||||
this.grpcClient.getExtendedAgentCard.bind(this.grpcClient),
|
||||
(req) => req
|
||||
this.grpcClient.getAgentCard.bind(this.grpcClient),
|
||||
ToProto.getAgentCardRequest,
|
||||
FromProto.agentCard
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): Promise<SendMessageResult> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
@ -91,75 +78,72 @@ export class GrpcTransport implements Transport {
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.sendMessage.bind(this.grpcClient),
|
||||
ToProto.messageSendParams,
|
||||
FromProto.sendMessageResult
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async *sendMessageStream(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendGrpcStreamingRequest(
|
||||
'sendStreamingMessage',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.sendStreamingMessage.bind(this.grpcClient)
|
||||
this.grpcClient.sendStreamingMessage.bind(this.grpcClient),
|
||||
ToProto.messageSendParams
|
||||
);
|
||||
}
|
||||
|
||||
async createTaskPushNotificationConfig(
|
||||
async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const rpcResponse = await this._sendGrpcRequest<
|
||||
TaskPushNotificationConfig,
|
||||
TaskPushNotificationConfig,
|
||||
TaskPushNotificationConfig
|
||||
>(
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'createTaskPushNotificationConfig',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.createTaskPushNotificationConfig.bind(this.grpcClient),
|
||||
(req) => req
|
||||
ToProto.taskPushNotificationConfigCreate,
|
||||
FromProto.taskPushNotificationConfig
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigRequest,
|
||||
params: GetTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const rpcResponse = await this._sendGrpcRequest<
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
TaskPushNotificationConfig,
|
||||
TaskPushNotificationConfig
|
||||
>(
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'getTaskPushNotificationConfig',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.getTaskPushNotificationConfig.bind(this.grpcClient),
|
||||
(req) => req
|
||||
ToProto.getTaskPushNotificationConfigParams,
|
||||
FromProto.taskPushNotificationConfig
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigsRequest,
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'listTaskPushNotificationConfigs',
|
||||
'listTaskPushNotificationConfig',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.listTaskPushNotificationConfigs.bind(this.grpcClient),
|
||||
this.grpcClient.listTaskPushNotificationConfig.bind(this.grpcClient),
|
||||
ToProto.listTaskPushNotificationConfigParams,
|
||||
FromProto.listTaskPushNotificationConfig
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigRequest,
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<void> {
|
||||
await this._sendGrpcRequest(
|
||||
@ -167,56 +151,61 @@ export class GrpcTransport implements Transport {
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.deleteTaskPushNotificationConfig.bind(this.grpcClient),
|
||||
ToProto.deleteTaskPushNotificationConfigParams,
|
||||
() => {}
|
||||
);
|
||||
}
|
||||
|
||||
async getTask(params: GetTaskRequest, options?: RequestOptions): Promise<Task> {
|
||||
const rpcResponse = await this._sendGrpcRequest<GetTaskRequest, Task, Task>(
|
||||
async getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'getTask',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.getTask.bind(this.grpcClient),
|
||||
(req) => req
|
||||
ToProto.taskQueryParams,
|
||||
FromProto.task
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async cancelTask(params: CancelTaskRequest, options?: RequestOptions): Promise<Task> {
|
||||
const rpcResponse = await this._sendGrpcRequest<CancelTaskRequest, Task, Task>(
|
||||
async cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'cancelTask',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.cancelTask.bind(this.grpcClient),
|
||||
(req) => req
|
||||
ToProto.cancelTaskRequest,
|
||||
FromProto.task
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async *resubscribeTask(
|
||||
params: SubscribeToTaskRequest,
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendGrpcStreamingRequest(
|
||||
'subscribeToTask',
|
||||
'taskSubscription',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.subscribeToTask.bind(this.grpcClient)
|
||||
this.grpcClient.taskSubscription.bind(this.grpcClient),
|
||||
ToProto.taskIdParams
|
||||
);
|
||||
}
|
||||
|
||||
private async _sendGrpcRequest<TReq, TRes, TResponse>(
|
||||
private async _sendGrpcRequest<TReq, TRes, TParams, TResponse>(
|
||||
method: keyof A2AServiceClient,
|
||||
params: TReq,
|
||||
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(
|
||||
params,
|
||||
parser(params),
|
||||
this._buildMetadata(options),
|
||||
this.grpcCallOptions ?? {},
|
||||
(error, response) => {
|
||||
@ -241,13 +230,18 @@ export class GrpcTransport implements Transport {
|
||||
});
|
||||
}
|
||||
|
||||
private async *_sendGrpcStreamingRequest<TReq, TRes>(
|
||||
method: 'sendStreamingMessage' | 'subscribeToTask',
|
||||
params: TReq,
|
||||
private async *_sendGrpcStreamingRequest<TReq, TRes, TParams>(
|
||||
method: 'sendStreamingMessage' | 'taskSubscription',
|
||||
params: TParams,
|
||||
options: RequestOptions | undefined,
|
||||
call: GrpcStreamCall<TReq, TRes>
|
||||
call: GrpcStreamCall<TReq, TRes>,
|
||||
parser: (req: TParams) => TReq
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const streamResponse = call(params, this._buildMetadata(options), this.grpcCallOptions ?? {});
|
||||
const streamResponse = call(
|
||||
parser(params),
|
||||
this._buildMetadata(options),
|
||||
this.grpcCallOptions ?? {}
|
||||
);
|
||||
|
||||
let onAbort: (() => void) | undefined;
|
||||
if (options?.signal) {
|
||||
@ -302,7 +296,7 @@ export class GrpcTransport implements Transport {
|
||||
if (method === 'cancelTask') {
|
||||
return new TaskNotCancelableError(error.details);
|
||||
}
|
||||
if (method === 'getExtendedAgentCard') {
|
||||
if (method === 'getAgentCard') {
|
||||
return new AuthenticatedExtendedCardNotConfiguredError(error.details);
|
||||
}
|
||||
break;
|
||||
@ -317,13 +311,11 @@ export class GrpcTransport implements Transport {
|
||||
) {
|
||||
return new PushNotificationNotSupportedError(error.details);
|
||||
}
|
||||
if (['getExtendedAgentCard', 'subscribeToTask'].includes(method)) {
|
||||
if (['getAgentCard', 'taskSubscription'].includes(method)) {
|
||||
return new UnsupportedOperationError(error.details);
|
||||
}
|
||||
break;
|
||||
case grpc.status.INVALID_ARGUMENT:
|
||||
case grpc.status.INTERNAL:
|
||||
return new RequestMalformedError(error.details);
|
||||
//TODO: add case for grpc.status.INVALID_ARGUMENT and grpc.status.INTERNAL (the respective a2a errors are not implemented yet)
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@ -339,10 +331,12 @@ export class GrpcTransportFactoryOptions {
|
||||
}
|
||||
|
||||
export class GrpcTransportFactory implements TransportFactory {
|
||||
public static readonly name: TransportProtocolName = 'GRPC';
|
||||
|
||||
constructor(private readonly options?: GrpcTransportFactoryOptions) {}
|
||||
|
||||
get protocolName(): string {
|
||||
return PROTOCOL_NAME;
|
||||
return GrpcTransportFactory.name;
|
||||
}
|
||||
|
||||
async create(url: string, _agentCard: AgentCard): Promise<Transport> {
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import { JSONRPCErrorResponse, TransportProtocolName } from '../../core.js';
|
||||
import { TransportProtocolName } from '../../core.js';
|
||||
import {
|
||||
A2A_ERROR_CODE,
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
ContentTypeNotSupportedError,
|
||||
InvalidAgentResponseError,
|
||||
@ -8,33 +7,33 @@ import {
|
||||
TaskNotCancelableError,
|
||||
TaskNotFoundError,
|
||||
UnsupportedOperationError,
|
||||
RequestMalformedError,
|
||||
} from '../../errors.js';
|
||||
import {
|
||||
Task,
|
||||
AgentCard,
|
||||
JSONRPCRequest,
|
||||
JSONRPCResponse,
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
A2AStreamEventData,
|
||||
SendMessageResult,
|
||||
} from '../../index.js';
|
||||
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';
|
||||
import {
|
||||
CancelTaskRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
MessageFns,
|
||||
SendMessageRequest,
|
||||
SubscribeToTaskRequest,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
GetTaskRequest,
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
SendMessageResponse,
|
||||
ListTaskPushNotificationConfigsResponse,
|
||||
StreamResponse,
|
||||
} from '../../types/pb/a2a.js';
|
||||
|
||||
const PROTOCOL_NAME: TransportProtocolName = 'JSONRPC';
|
||||
|
||||
export interface JsonRpcTransportOptions {
|
||||
endpoint: string;
|
||||
@ -51,138 +50,128 @@ export class JsonRpcTransport implements Transport {
|
||||
this.customFetchImpl = options.fetchImpl;
|
||||
}
|
||||
|
||||
get protocolName(): string {
|
||||
return PROTOCOL_NAME;
|
||||
}
|
||||
|
||||
async getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard> {
|
||||
const rpcResponse = await this._sendRpcRequest<undefined, AgentCard>(
|
||||
'GetExtendedAgentCard',
|
||||
async getExtendedAgentCard(options?: RequestOptions, idOverride?: number): Promise<AgentCard> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
undefined,
|
||||
options,
|
||||
undefined
|
||||
);
|
||||
GetAuthenticatedExtendedCardSuccessResponse
|
||||
>('agent/getAuthenticatedExtendedCard', undefined, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
params: SendMessageRequest,
|
||||
options?: RequestOptions
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<SendMessageResult> {
|
||||
const rpcResponse = await this._sendRpcRequest<SendMessageRequest, SendMessageResponse>(
|
||||
'SendMessage',
|
||||
const rpcResponse = await this._sendRpcRequest<MessageSendParams, SendMessageSuccessResponse>(
|
||||
'message/send',
|
||||
params,
|
||||
options,
|
||||
SendMessageRequest
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
|
||||
if (!rpcResponse.result?.payload?.value) {
|
||||
throw new Error('Invalid response structure from agent.');
|
||||
}
|
||||
|
||||
return rpcResponse.result.payload.value;
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async *sendMessageStream(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendStreamingRequest<SendMessageRequest>(
|
||||
'SendStreamingMessage',
|
||||
params,
|
||||
options,
|
||||
SendMessageRequest
|
||||
);
|
||||
yield* this._sendStreamingRequest('message/stream', params, options);
|
||||
}
|
||||
|
||||
async createTaskPushNotificationConfig(
|
||||
async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
TaskPushNotificationConfig,
|
||||
TaskPushNotificationConfig
|
||||
>('CreateTaskPushNotificationConfig', params, options, TaskPushNotificationConfig);
|
||||
return TaskPushNotificationConfig.fromJSON(rpcResponse.result);
|
||||
SetTaskPushNotificationConfigSuccessResponse
|
||||
>('tasks/pushNotificationConfig/set', params, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigRequest,
|
||||
options?: RequestOptions
|
||||
params: GetTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
TaskPushNotificationConfig
|
||||
>('GetTaskPushNotificationConfig', params, options, GetTaskPushNotificationConfigRequest);
|
||||
return TaskPushNotificationConfig.fromJSON(rpcResponse.result);
|
||||
GetTaskPushNotificationConfigParams,
|
||||
GetTaskPushNotificationConfigSuccessResponse
|
||||
>('tasks/pushNotificationConfig/get', params, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigsRequest,
|
||||
options?: RequestOptions
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
ListTaskPushNotificationConfigsResponse
|
||||
>('ListTaskPushNotificationConfigs', params, options, ListTaskPushNotificationConfigsRequest);
|
||||
const configs = rpcResponse.result.configs || [];
|
||||
return configs.map((c: unknown) => TaskPushNotificationConfig.fromJSON(c));
|
||||
ListTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigSuccessResponse
|
||||
>('tasks/pushNotificationConfig/list', params, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigRequest,
|
||||
options?: RequestOptions
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<void> {
|
||||
await this._sendRpcRequest<DeleteTaskPushNotificationConfigRequest, void>(
|
||||
'DeleteTaskPushNotificationConfig',
|
||||
params,
|
||||
options,
|
||||
DeleteTaskPushNotificationConfigRequest
|
||||
);
|
||||
await this._sendRpcRequest<
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigResponse
|
||||
>('tasks/pushNotificationConfig/delete', params, idOverride, options);
|
||||
}
|
||||
|
||||
async getTask(params: GetTaskRequest, options?: RequestOptions): Promise<Task> {
|
||||
const rpcResponse = await this._sendRpcRequest<GetTaskRequest, Task>(
|
||||
'GetTask',
|
||||
async getTask(
|
||||
params: TaskQueryParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<Task> {
|
||||
const rpcResponse = await this._sendRpcRequest<TaskQueryParams, GetTaskSuccessResponse>(
|
||||
'tasks/get',
|
||||
params,
|
||||
options,
|
||||
GetTaskRequest
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
return Task.fromJSON(rpcResponse.result);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async cancelTask(params: CancelTaskRequest, options?: RequestOptions): Promise<Task> {
|
||||
const rpcResponse = await this._sendRpcRequest<CancelTaskRequest, Task>(
|
||||
'CancelTask',
|
||||
async cancelTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<Task> {
|
||||
const rpcResponse = await this._sendRpcRequest<TaskIdParams, CancelTaskSuccessResponse>(
|
||||
'tasks/cancel',
|
||||
params,
|
||||
options,
|
||||
CancelTaskRequest
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
return Task.fromJSON(rpcResponse.result);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async *resubscribeTask(
|
||||
params: SubscribeToTaskRequest,
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendStreamingRequest<SubscribeToTaskRequest>(
|
||||
'SubscribeToTask',
|
||||
params,
|
||||
options,
|
||||
SubscribeToTaskRequest
|
||||
);
|
||||
yield* this._sendStreamingRequest('tasks/resubscribe', params, options);
|
||||
}
|
||||
|
||||
async callExtensionMethod<TExtensionParams, TExtensionResponse>(
|
||||
async callExtensionMethod<TExtensionParams, TExtensionResponse extends JSONRPCResponse>(
|
||||
method: string,
|
||||
params: TExtensionParams,
|
||||
idOverride: number,
|
||||
options?: RequestOptions
|
||||
) {
|
||||
return await this._sendRpcRequest<TExtensionParams, TExtensionResponse>(
|
||||
method,
|
||||
params,
|
||||
options,
|
||||
undefined
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
@ -199,18 +188,22 @@ export class JsonRpcTransport implements Transport {
|
||||
);
|
||||
}
|
||||
|
||||
private async _sendRpcRequest<TParams, TResponsePayload>(
|
||||
private async _sendRpcRequest<
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
TParams extends { [key: string]: any },
|
||||
TResponse extends JSONRPCResponse,
|
||||
>(
|
||||
method: string,
|
||||
params: TParams,
|
||||
options: RequestOptions | undefined,
|
||||
requestType: MessageFns<TParams> | undefined
|
||||
): Promise<JSONRPCSuccessResponse<TResponsePayload>> {
|
||||
const requestId = this.requestIdCounter++;
|
||||
idOverride: number | undefined,
|
||||
options: RequestOptions | undefined
|
||||
): Promise<TResponse> {
|
||||
const requestId = idOverride ?? this.requestIdCounter++;
|
||||
|
||||
const rpcRequest: JSONRPCRequest = {
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params: requestType?.toJSON(params) ?? params,
|
||||
params: params,
|
||||
id: requestId,
|
||||
};
|
||||
|
||||
@ -237,19 +230,18 @@ export class JsonRpcTransport implements Transport {
|
||||
}
|
||||
}
|
||||
|
||||
const json = await httpResponse.json();
|
||||
if ('error' in json) {
|
||||
throw JsonRpcTransport.mapToError(json as JSONRPCErrorResponse);
|
||||
}
|
||||
|
||||
const rpcResponse = json as JSONRPCSuccessResponse<TResponsePayload>;
|
||||
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}.`
|
||||
);
|
||||
}
|
||||
|
||||
return rpcResponse;
|
||||
if ('error' in rpcResponse) {
|
||||
throw JsonRpcTransport.mapToError(rpcResponse);
|
||||
}
|
||||
|
||||
return rpcResponse as TResponse;
|
||||
}
|
||||
|
||||
private async _fetchRpc(
|
||||
@ -270,17 +262,16 @@ export class JsonRpcTransport implements Transport {
|
||||
return this._fetch(this.endpoint, requestInit);
|
||||
}
|
||||
|
||||
private async *_sendStreamingRequest<TParams>(
|
||||
private async *_sendStreamingRequest(
|
||||
method: string,
|
||||
params: TParams,
|
||||
options: RequestOptions | undefined,
|
||||
requestType: MessageFns<TParams> | undefined
|
||||
params: unknown,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const clientRequestId = this.requestIdCounter++;
|
||||
const rpcRequest: JSONRPCRequest = {
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params: requestType?.toJSON(params) ?? params,
|
||||
params: params as { [key: string]: unknown },
|
||||
id: clientRequestId,
|
||||
};
|
||||
|
||||
@ -326,9 +317,9 @@ export class JsonRpcTransport implements Transport {
|
||||
throw new Error('Attempted to process empty SSE event data.');
|
||||
}
|
||||
|
||||
let a2aStreamResponse: JSONRPCResponse<StreamResponse>;
|
||||
let a2aStreamResponse: JSONRPCResponse;
|
||||
try {
|
||||
a2aStreamResponse = JSON.parse(jsonData) as JSONRPCResponse<StreamResponse>;
|
||||
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'}`,
|
||||
@ -354,37 +345,25 @@ export class JsonRpcTransport implements Transport {
|
||||
throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
|
||||
}
|
||||
|
||||
const result = a2aStreamResponse.result;
|
||||
if (result?.payload?.value) {
|
||||
return result.payload.value as TStreamItem;
|
||||
}
|
||||
|
||||
return result as TStreamItem;
|
||||
return a2aStreamResponse.result as TStreamItem;
|
||||
}
|
||||
|
||||
private static mapToError(response: JSONRPCErrorResponse): Error {
|
||||
const errorMessage = response.error.message;
|
||||
switch (response.error.code) {
|
||||
case A2A_ERROR_CODE.PARSE_ERROR:
|
||||
case A2A_ERROR_CODE.INVALID_REQUEST:
|
||||
case A2A_ERROR_CODE.METHOD_NOT_FOUND:
|
||||
case A2A_ERROR_CODE.INVALID_PARAMS:
|
||||
case A2A_ERROR_CODE.INTERNAL_ERROR:
|
||||
return new RequestMalformedError(errorMessage);
|
||||
case A2A_ERROR_CODE.TASK_NOT_FOUND:
|
||||
return new TaskNotFoundError(errorMessage);
|
||||
case A2A_ERROR_CODE.TASK_NOT_CANCELABLE:
|
||||
return new TaskNotCancelableError(errorMessage);
|
||||
case A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED:
|
||||
return new PushNotificationNotSupportedError(errorMessage);
|
||||
case A2A_ERROR_CODE.UNSUPPORTED_OPERATION:
|
||||
return new UnsupportedOperationError(errorMessage);
|
||||
case A2A_ERROR_CODE.CONTENT_TYPE_NOT_SUPPORTED:
|
||||
return new ContentTypeNotSupportedError(errorMessage);
|
||||
case A2A_ERROR_CODE.INVALID_AGENT_RESPONSE:
|
||||
return new InvalidAgentResponseError(errorMessage);
|
||||
case A2A_ERROR_CODE.AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED:
|
||||
return new AuthenticatedExtendedCardNotConfiguredError(errorMessage);
|
||||
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);
|
||||
}
|
||||
@ -396,10 +375,12 @@ export class JsonRpcTransportFactoryOptions {
|
||||
}
|
||||
|
||||
export class JsonRpcTransportFactory implements TransportFactory {
|
||||
public static readonly name: TransportProtocolName = 'JSONRPC';
|
||||
|
||||
constructor(private readonly options?: JsonRpcTransportFactoryOptions) {}
|
||||
|
||||
get protocolName(): string {
|
||||
return PROTOCOL_NAME;
|
||||
return JsonRpcTransportFactory.name;
|
||||
}
|
||||
|
||||
async create(url: string, _agentCard: AgentCard): Promise<Transport> {
|
||||
@ -410,21 +391,6 @@ export class JsonRpcTransportFactory implements TransportFactory {
|
||||
}
|
||||
}
|
||||
|
||||
interface JSONRPCRequest {
|
||||
jsonrpc: '2.0';
|
||||
method: string;
|
||||
params: unknown;
|
||||
id: string | number | null;
|
||||
}
|
||||
|
||||
interface JSONRPCSuccessResponse<T> {
|
||||
jsonrpc: '2.0';
|
||||
result: T;
|
||||
id: string | number | null;
|
||||
}
|
||||
|
||||
type JSONRPCResponse<T> = JSONRPCSuccessResponse<T> | JSONRPCErrorResponse;
|
||||
|
||||
export class JSONRPCTransportError extends Error {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super(
|
||||
@ -432,3 +398,48 @@ export class JSONRPCTransportError extends Error {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
|
||||
@ -8,32 +8,25 @@ import {
|
||||
TaskNotFoundError,
|
||||
TaskNotCancelableError,
|
||||
UnsupportedOperationError,
|
||||
RequestMalformedError,
|
||||
} from '../../errors.js';
|
||||
|
||||
import { A2AStreamEventData, SendMessageResult } from '../../index.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 {
|
||||
AgentCard,
|
||||
CancelTaskRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
GetTaskRequest,
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
ListTaskPushNotificationConfigsResponse,
|
||||
MessageFns,
|
||||
SendMessageRequest,
|
||||
SendMessageResponse,
|
||||
StreamResponse,
|
||||
Task,
|
||||
TaskPushNotificationConfig,
|
||||
SubscribeToTaskRequest,
|
||||
} from '../../types/pb/a2a.js';
|
||||
|
||||
const PROTOCOL_NAME: TransportProtocolName = 'HTTP+JSON';
|
||||
import * as a2a from '../../types/pb/a2a_types.js';
|
||||
|
||||
export interface RestTransportOptions {
|
||||
endpoint: string;
|
||||
@ -41,9 +34,8 @@ export interface RestTransportOptions {
|
||||
}
|
||||
|
||||
interface RestErrorResponse {
|
||||
name?: string;
|
||||
message?: string;
|
||||
code?: number;
|
||||
code: number;
|
||||
message: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
@ -56,101 +48,105 @@ export class RestTransport implements Transport {
|
||||
this.customFetchImpl = options.fetchImpl;
|
||||
}
|
||||
|
||||
get protocolName(): string {
|
||||
return PROTOCOL_NAME;
|
||||
}
|
||||
|
||||
async getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard> {
|
||||
const response = await this._sendRequest<undefined, AgentCard>(
|
||||
const response = await this._sendRequest<undefined, a2a.AgentCard>(
|
||||
'GET',
|
||||
'/extendedAgentCard',
|
||||
'/v1/card',
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
AgentCard
|
||||
a2a.AgentCard
|
||||
);
|
||||
return response;
|
||||
return FromProto.agentCard(response);
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): Promise<SendMessageResult> {
|
||||
const requestBody = params;
|
||||
const response = await this._sendRequest<SendMessageRequest, SendMessageResponse>(
|
||||
const requestBody = ToProto.messageSendParams(params);
|
||||
const response = await this._sendRequest<a2a.SendMessageRequest, a2a.SendMessageResponse>(
|
||||
'POST',
|
||||
'/message:send',
|
||||
'/v1/message:send',
|
||||
requestBody,
|
||||
options,
|
||||
SendMessageRequest,
|
||||
SendMessageResponse
|
||||
a2a.SendMessageRequest,
|
||||
a2a.SendMessageResponse
|
||||
);
|
||||
return FromProto.sendMessageResult(response);
|
||||
}
|
||||
|
||||
async *sendMessageStream(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const requestBody = SendMessageRequest.toJSON(params);
|
||||
yield* this._sendStreamingRequest('/message:stream', requestBody, options);
|
||||
const protoParams = ToProto.messageSendParams(params);
|
||||
const requestBody = a2a.SendMessageRequest.toJSON(protoParams);
|
||||
yield* this._sendStreamingRequest('/v1/message:stream', requestBody, options);
|
||||
}
|
||||
|
||||
async createTaskPushNotificationConfig(
|
||||
async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const requestBody = ToProto.taskPushNotificationConfig(params);
|
||||
const response = await this._sendRequest<
|
||||
TaskPushNotificationConfig,
|
||||
TaskPushNotificationConfig
|
||||
a2a.TaskPushNotificationConfig,
|
||||
a2a.TaskPushNotificationConfig
|
||||
>(
|
||||
'POST',
|
||||
`/tasks/${encodeURIComponent(params.taskId)}/pushNotificationConfigs`,
|
||||
params,
|
||||
`/v1/tasks/${encodeURIComponent(params.taskId)}/pushNotificationConfigs`,
|
||||
requestBody,
|
||||
options,
|
||||
TaskPushNotificationConfig,
|
||||
TaskPushNotificationConfig
|
||||
a2a.TaskPushNotificationConfig,
|
||||
a2a.TaskPushNotificationConfig
|
||||
);
|
||||
return response;
|
||||
return FromProto.taskPushNotificationConfig(response);
|
||||
}
|
||||
|
||||
async getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigRequest,
|
||||
params: GetTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const response = await this._sendRequest<undefined, 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',
|
||||
`/tasks/${params.taskId}/pushNotificationConfigs/${params.id}`,
|
||||
`/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs/${encodeURIComponent(pushNotificationConfigId)}`,
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
TaskPushNotificationConfig
|
||||
a2a.TaskPushNotificationConfig
|
||||
);
|
||||
return response;
|
||||
return FromProto.taskPushNotificationConfig(response);
|
||||
}
|
||||
|
||||
async listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigsRequest,
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
const response = await this._sendRequest<undefined, ListTaskPushNotificationConfigsResponse>(
|
||||
const response = await this._sendRequest<undefined, a2a.ListTaskPushNotificationConfigResponse>(
|
||||
'GET',
|
||||
`/tasks/${params.taskId}/pushNotificationConfigs`,
|
||||
`/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs`,
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
ListTaskPushNotificationConfigsResponse
|
||||
a2a.ListTaskPushNotificationConfigResponse
|
||||
);
|
||||
return response.configs;
|
||||
return FromProto.listTaskPushNotificationConfig(response);
|
||||
}
|
||||
|
||||
async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigRequest,
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<void> {
|
||||
await this._sendRequest<undefined, void>(
|
||||
'DELETE',
|
||||
`/tasks/${params.taskId}/pushNotificationConfigs/${params.id}`,
|
||||
`/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs/${encodeURIComponent(params.pushNotificationConfigId)}`,
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
@ -158,41 +154,45 @@ export class RestTransport implements Transport {
|
||||
);
|
||||
}
|
||||
|
||||
async getTask(params: GetTaskRequest, options?: RequestOptions): Promise<Task> {
|
||||
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 = `/tasks/${params.id}${queryString ? `?${queryString}` : ''}`;
|
||||
const response = await this._sendRequest<undefined, Task>(
|
||||
const path = `/v1/tasks/${encodeURIComponent(params.id)}${queryString ? `?${queryString}` : ''}`;
|
||||
const response = await this._sendRequest<undefined, a2a.Task>(
|
||||
'GET',
|
||||
path,
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
Task
|
||||
a2a.Task
|
||||
);
|
||||
return response;
|
||||
return FromProto.task(response);
|
||||
}
|
||||
|
||||
async cancelTask(params: CancelTaskRequest, options?: RequestOptions): Promise<Task> {
|
||||
const response = await this._sendRequest<undefined, Task>(
|
||||
async cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task> {
|
||||
const response = await this._sendRequest<undefined, a2a.Task>(
|
||||
'POST',
|
||||
`/tasks/${params.id}:cancel`,
|
||||
`/v1/tasks/${encodeURIComponent(params.id)}:cancel`,
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
Task
|
||||
a2a.Task
|
||||
);
|
||||
return response;
|
||||
return FromProto.task(response);
|
||||
}
|
||||
|
||||
async *resubscribeTask(
|
||||
params: SubscribeToTaskRequest,
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendStreamingRequest(`/tasks/${params.id}:subscribe`, undefined, options);
|
||||
yield* this._sendStreamingRequest(
|
||||
`/v1/tasks/${encodeURIComponent(params.id)}:subscribe`,
|
||||
undefined,
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
private _fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
|
||||
@ -224,8 +224,8 @@ export class RestTransport implements Transport {
|
||||
path: string,
|
||||
body: TRequest,
|
||||
options: RequestOptions | undefined,
|
||||
requestType: MessageFns<TRequest> | undefined,
|
||||
responseType: MessageFns<TResponse> | undefined
|
||||
requestType: a2a.MessageFns<TRequest> | undefined,
|
||||
responseType: a2a.MessageFns<TResponse> | undefined
|
||||
): Promise<TResponse> {
|
||||
const url = `${this.endpoint}${path}`;
|
||||
const requestInit: RequestInit = {
|
||||
@ -273,8 +273,8 @@ export class RestTransport implements Transport {
|
||||
);
|
||||
}
|
||||
|
||||
if (errorBody && (typeof errorBody.name === 'string' || typeof errorBody.code === 'number')) {
|
||||
throw RestTransport.mapToError(errorBody, response.status);
|
||||
if (errorBody && typeof errorBody.code === 'number') {
|
||||
throw RestTransport.mapToError(errorBody);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
@ -327,7 +327,7 @@ export class RestTransport implements Transport {
|
||||
|
||||
try {
|
||||
const response = JSON.parse(jsonData);
|
||||
const protoResponse = StreamResponse.fromJSON(response);
|
||||
const protoResponse = a2a.StreamResponse.fromJSON(response);
|
||||
return FromProto.messageStreamResult(protoResponse);
|
||||
} catch (e) {
|
||||
console.error('Failed to parse SSE event data:', jsonData, e);
|
||||
@ -337,56 +337,27 @@ export class RestTransport implements Transport {
|
||||
}
|
||||
}
|
||||
|
||||
private static mapToError(error: RestErrorResponse, status?: number): Error {
|
||||
const message = error.message || 'Unknown error';
|
||||
|
||||
if (error.name) {
|
||||
switch (error.name) {
|
||||
case 'TaskNotFoundError':
|
||||
return new TaskNotFoundError(message);
|
||||
case 'TaskNotCancelableError':
|
||||
return new TaskNotCancelableError(message);
|
||||
case 'PushNotificationNotSupportedError':
|
||||
return new PushNotificationNotSupportedError(message);
|
||||
case 'UnsupportedOperationError':
|
||||
return new UnsupportedOperationError(message);
|
||||
case 'ContentTypeNotSupportedError':
|
||||
return new ContentTypeNotSupportedError(message);
|
||||
case 'InvalidAgentResponseError':
|
||||
return new InvalidAgentResponseError(message);
|
||||
case 'AuthenticatedExtendedCardNotConfiguredError':
|
||||
return new AuthenticatedExtendedCardNotConfiguredError(message);
|
||||
case 'RequestMalformedError':
|
||||
return new RequestMalformedError(message);
|
||||
}
|
||||
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)}` : ''}`
|
||||
);
|
||||
}
|
||||
|
||||
if (error.code !== undefined) {
|
||||
switch (error.code) {
|
||||
case A2A_ERROR_CODE.TASK_NOT_FOUND:
|
||||
return new TaskNotFoundError(message);
|
||||
case A2A_ERROR_CODE.TASK_NOT_CANCELABLE:
|
||||
return new TaskNotCancelableError(message);
|
||||
case A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED:
|
||||
return new PushNotificationNotSupportedError(message);
|
||||
case A2A_ERROR_CODE.UNSUPPORTED_OPERATION:
|
||||
return new UnsupportedOperationError(message);
|
||||
case A2A_ERROR_CODE.CONTENT_TYPE_NOT_SUPPORTED:
|
||||
return new ContentTypeNotSupportedError(message);
|
||||
case A2A_ERROR_CODE.INVALID_AGENT_RESPONSE:
|
||||
return new InvalidAgentResponseError(message);
|
||||
case A2A_ERROR_CODE.AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED:
|
||||
return new AuthenticatedExtendedCardNotConfiguredError(message);
|
||||
}
|
||||
}
|
||||
|
||||
if (status === 400) return new RequestMalformedError(message);
|
||||
if (status === 404) return new TaskNotFoundError(message);
|
||||
if (status === 409) return new TaskNotCancelableError(message);
|
||||
|
||||
return new Error(
|
||||
`REST error: ${error.name || 'Error'} - ${message}${status ? ` (Status: ${status})` : ''}${error.data ? ` Data: ${JSON.stringify(error.data)}` : ''}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -395,10 +366,12 @@ export interface RestTransportFactoryOptions {
|
||||
}
|
||||
|
||||
export class RestTransportFactory implements TransportFactory {
|
||||
public static readonly name: TransportProtocolName = 'HTTP+JSON';
|
||||
|
||||
constructor(private readonly options?: RestTransportFactoryOptions) {}
|
||||
|
||||
get protocolName(): string {
|
||||
return PROTOCOL_NAME;
|
||||
return RestTransportFactory.name;
|
||||
}
|
||||
|
||||
async create(url: string, _agentCard: AgentCard): Promise<Transport> {
|
||||
|
||||
@ -1,55 +1,53 @@
|
||||
import { TaskPushNotificationConfig, Task, AgentCard } from '../../index.js';
|
||||
import {
|
||||
SendMessageRequest,
|
||||
CancelTaskRequest,
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
GetTaskRequest,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
SubscribeToTaskRequest,
|
||||
A2AStreamEventData,
|
||||
SendMessageResult,
|
||||
} from '../../index.js';
|
||||
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 {
|
||||
get protocolName(): string;
|
||||
|
||||
getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard>;
|
||||
|
||||
sendMessage(params: SendMessageRequest, options?: RequestOptions): Promise<SendMessageResult>;
|
||||
sendMessage(params: MessageSendParams, options?: RequestOptions): Promise<SendMessageResult>;
|
||||
|
||||
sendMessageStream(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined>;
|
||||
|
||||
createTaskPushNotificationConfig(
|
||||
setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
|
||||
getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigRequest,
|
||||
params: GetTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
|
||||
listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigsRequest,
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig[]>;
|
||||
|
||||
deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigRequest,
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<void>;
|
||||
|
||||
getTask(params: GetTaskRequest, options?: RequestOptions): Promise<Task>;
|
||||
getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task>;
|
||||
|
||||
cancelTask(params: CancelTaskRequest, options?: RequestOptions): Promise<Task>;
|
||||
cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task>;
|
||||
|
||||
resubscribeTask(
|
||||
params: SubscribeToTaskRequest,
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined>;
|
||||
}
|
||||
|
||||
@ -11,8 +11,3 @@ 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';
|
||||
|
||||
/**
|
||||
* The default page size for listing tasks
|
||||
*/
|
||||
export const DEFAULT_PAGE_SIZE = 50;
|
||||
|
||||
12
src/core.ts
12
src/core.ts
@ -1,13 +1 @@
|
||||
export type TransportProtocolName = 'JSONRPC' | 'HTTP+JSON' | 'GRPC' | (string & {});
|
||||
|
||||
export interface JSONRPCError {
|
||||
code: number;
|
||||
data?: { [k: string]: unknown };
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface JSONRPCErrorResponse {
|
||||
error: JSONRPCError;
|
||||
id: string | number | null;
|
||||
jsonrpc: '2.0';
|
||||
}
|
||||
|
||||
@ -14,28 +14,10 @@ export const A2A_ERROR_CODE = {
|
||||
AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED: -32007,
|
||||
} as const;
|
||||
|
||||
// --------------------------------------------------
|
||||
// These errors are a2a-js SDK specific and not covered by the protocol's documentation.
|
||||
// They are used when the error does not fit into any of the other error categories.
|
||||
|
||||
export class RequestMalformedError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Request malformed');
|
||||
this.name = 'RequestMalformedError';
|
||||
}
|
||||
}
|
||||
|
||||
export class GenericError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'An unexpected error occurred.');
|
||||
this.name = 'GenericError';
|
||||
}
|
||||
}
|
||||
|
||||
// End of a2a-js SDK specific errors.
|
||||
// --------------------------------------------------
|
||||
|
||||
// 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) {
|
||||
|
||||
@ -10,6 +10,9 @@ Ensure you have the project dependencies installed:
|
||||
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`):
|
||||
@ -24,14 +27,14 @@ This will generate the TypeScript files in the `./pb` directory (as configured i
|
||||
|
||||
**Important:** After running the generation, a post-processing step is **necessary**.
|
||||
|
||||
The `buf` generation process produces a file (e.g., `src/grpc/pb/a2a.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.
|
||||
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.ts`).
|
||||
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.ts`
|
||||
`src/types/pb/a2a_types.ts`
|
||||
|
||||
For example, change:
|
||||
```typescript
|
||||
@ -39,7 +42,7 @@ The `buf` generation process produces a file (e.g., `src/grpc/pb/a2a.ts`) that c
|
||||
```
|
||||
to:
|
||||
```typescript
|
||||
import * as pb from "../../types/pb/a2a.js";
|
||||
import * as pb from "../../types/pb/a2a_types.js";
|
||||
|
||||
export type Task = pb.Task;
|
||||
// ... maps other types similarly
|
||||
|
||||
@ -3,9 +3,7 @@
|
||||
# Uses remote plugins, no separate install required.
|
||||
version: v2
|
||||
inputs:
|
||||
- git_repo: https://github.com/a2aproject/A2A.git
|
||||
ref: v1.0.0
|
||||
subdir: specification
|
||||
- directory: ./pb
|
||||
plugins:
|
||||
- remote: buf.build/community/stephenh-ts-proto:v2.6.1
|
||||
opt:
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -5,11 +5,7 @@
|
||||
* Use the server/index.ts file to import the server-only codebase.
|
||||
*/
|
||||
|
||||
import { Message, Task, TaskStatusUpdateEvent, TaskArtifactUpdateEvent } from './types/pb/a2a.js';
|
||||
|
||||
export * from './types/pb/a2a.js';
|
||||
export * from './types.js';
|
||||
export type { A2AResponse } from './a2a_response.js';
|
||||
export { AGENT_CARD_PATH, HTTP_EXTENSION_HEADER } from './constants.js';
|
||||
export { Extensions, type ExtensionURI } from './extensions.js';
|
||||
|
||||
export type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
|
||||
export type SendMessageResult = Message | Task;
|
||||
|
||||
@ -6,12 +6,12 @@ import {
|
||||
Task,
|
||||
TaskState,
|
||||
TaskStatusUpdateEvent,
|
||||
TextPart,
|
||||
Message,
|
||||
AGENT_CARD_PATH,
|
||||
TaskArtifactUpdateEvent,
|
||||
Artifact,
|
||||
Part,
|
||||
Role,
|
||||
} from '../../../index.js';
|
||||
import {
|
||||
InMemoryTaskStore,
|
||||
@ -63,14 +63,13 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
// 1. Publish initial Task event if it's a new task
|
||||
if (!existingTask) {
|
||||
const initialTask: Task = {
|
||||
kind: 'task',
|
||||
id: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_SUBMITTED,
|
||||
state: 'submitted',
|
||||
timestamp: new Date().toISOString(),
|
||||
message: undefined,
|
||||
},
|
||||
artifacts: [],
|
||||
history: [userMessage], // Start history with the current user message
|
||||
metadata: userMessage.metadata, // Carry over metadata from message if any
|
||||
};
|
||||
@ -79,30 +78,22 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
|
||||
// 2. Publish "working" status update
|
||||
const workingStatusUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_WORKING,
|
||||
state: 'working',
|
||||
message: {
|
||||
role: Role.ROLE_AGENT,
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: 'Processing your question, hang tight!' },
|
||||
metadata: undefined,
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
},
|
||||
],
|
||||
parts: [{ kind: 'text', text: 'Processing your question, hang tight!' }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
metadata: {},
|
||||
final: false,
|
||||
};
|
||||
eventBus.publish(workingStatusUpdate);
|
||||
|
||||
@ -114,17 +105,14 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
contexts.set(contextId, historyForGenkit);
|
||||
|
||||
const messages: MessageData[] = historyForGenkit
|
||||
.map((m) => {
|
||||
const textContent = m.parts
|
||||
.map((p) => (p.content?.$case === 'text' ? p.content.value : ''))
|
||||
.filter((t) => !!t)
|
||||
.join('\n');
|
||||
|
||||
return {
|
||||
role: (m.role === Role.ROLE_AGENT ? 'model' : 'user') as 'user' | 'model',
|
||||
content: textContent ? [{ text: textContent }] : [],
|
||||
};
|
||||
})
|
||||
.map((m) => ({
|
||||
role: (m.role === 'agent' ? 'model' : 'user') as 'user' | 'model',
|
||||
content: m.parts
|
||||
.filter((p): p is TextPart => p.kind === 'text' && !!(p as TextPart).text)
|
||||
.map((p) => ({
|
||||
text: (p as TextPart).text,
|
||||
})),
|
||||
}))
|
||||
.filter((m) => m.content.length > 0);
|
||||
|
||||
if (messages.length === 0) {
|
||||
@ -132,30 +120,22 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
`[MovieAgentExecutor] No valid text messages found in history for task ${taskId}.`
|
||||
);
|
||||
const failureUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_FAILED,
|
||||
state: 'failed',
|
||||
message: {
|
||||
role: Role.ROLE_AGENT,
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: 'No message found to process.' },
|
||||
metadata: undefined,
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
},
|
||||
],
|
||||
parts: [{ kind: 'text', text: 'No message found to process.' }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
metadata: {},
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(failureUpdate);
|
||||
return;
|
||||
@ -180,14 +160,14 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
console.log(`[MovieAgentExecutor] Request cancelled for task: ${taskId}`);
|
||||
|
||||
const cancelledUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_CANCELED,
|
||||
state: 'canceled',
|
||||
timestamp: new Date().toISOString(),
|
||||
message: undefined,
|
||||
},
|
||||
metadata: {},
|
||||
final: true, // Cancellation is a final state
|
||||
};
|
||||
eventBus.publish(cancelledUpdate);
|
||||
return;
|
||||
@ -202,72 +182,60 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
.join('\n')
|
||||
.trim();
|
||||
|
||||
let finalA2AState: TaskState = TaskState.TASK_STATE_UNSPECIFIED;
|
||||
let finalA2AState: TaskState = 'unknown';
|
||||
|
||||
if (finalStateLine === 'COMPLETED') {
|
||||
finalA2AState = TaskState.TASK_STATE_COMPLETED;
|
||||
finalA2AState = 'completed';
|
||||
} else if (finalStateLine === 'AWAITING_USER_INPUT') {
|
||||
finalA2AState = TaskState.TASK_STATE_INPUT_REQUIRED;
|
||||
finalA2AState = 'input-required';
|
||||
} else {
|
||||
console.warn(
|
||||
`[MovieAgentExecutor] Unexpected final state line from prompt: ${finalStateLine}. Defaulting to 'completed'.`
|
||||
);
|
||||
finalA2AState = TaskState.TASK_STATE_COMPLETED; // Default if LLM deviates
|
||||
finalA2AState = 'completed'; // Default if LLM deviates
|
||||
}
|
||||
|
||||
// 5. Publish artifact with the result
|
||||
const parts: Part[] = [
|
||||
{
|
||||
content: { $case: 'text', value: agentReplyText || 'Completed.' },
|
||||
metadata: undefined,
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
},
|
||||
];
|
||||
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,
|
||||
metadata: undefined,
|
||||
extensions: [],
|
||||
};
|
||||
|
||||
const artifactUpdate: TaskArtifactUpdateEvent = {
|
||||
kind: 'artifact-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
artifact: resultArtifact,
|
||||
lastChunk: true,
|
||||
append: false,
|
||||
metadata: {},
|
||||
};
|
||||
eventBus.publish(artifactUpdate);
|
||||
|
||||
// 6. Update local history context (internal only)
|
||||
const agentMessage: Message = {
|
||||
role: Role.ROLE_AGENT,
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: parts,
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
};
|
||||
historyForGenkit.push(agentMessage);
|
||||
contexts.set(contextId, historyForGenkit);
|
||||
|
||||
// 7. Publish final task status update
|
||||
const finalUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: finalA2AState,
|
||||
timestamp: new Date().toISOString(),
|
||||
message: undefined,
|
||||
},
|
||||
metadata: {},
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(finalUpdate);
|
||||
|
||||
@ -275,30 +243,22 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
} catch (error: any) {
|
||||
console.error(`[MovieAgentExecutor] Error processing task ${taskId}:`, error);
|
||||
const errorUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_FAILED,
|
||||
state: 'failed',
|
||||
message: {
|
||||
role: Role.ROLE_AGENT,
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: `Agent error: ${error.message}` },
|
||||
metadata: undefined,
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
},
|
||||
],
|
||||
parts: [{ kind: 'text', text: `Agent error: ${error.message}` }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
extensions: [],
|
||||
metadata: undefined,
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
metadata: undefined,
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(errorUpdate);
|
||||
}
|
||||
@ -310,27 +270,21 @@ class MovieAgentExecutor implements AgentExecutor {
|
||||
const movieAgentCard: AgentCard = {
|
||||
name: 'Movie Agent',
|
||||
description: 'An agent that can answer questions about movies and actors using TMDB.',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:41241/',
|
||||
protocolBinding: 'JSONRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '0.3.0',
|
||||
},
|
||||
],
|
||||
url: 'http://localhost:41241/',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples',
|
||||
url: 'https://example.com/a2a-samples', // Added provider URL
|
||||
},
|
||||
version: '0.0.2',
|
||||
version: '0.0.2', // Incremented version
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: false,
|
||||
extensions: [],
|
||||
extendedAgentCard: false,
|
||||
streaming: true, // The new framework supports streaming
|
||||
pushNotifications: false, // Assuming not implemented for this agent yet
|
||||
stateTransitionHistory: true, // Agent uses history
|
||||
},
|
||||
securitySchemes: {}, // Or define actual security schemes if any
|
||||
securityRequirements: [],
|
||||
// authentication: null, // Property 'authentication' does not exist on type 'AgentCard'.
|
||||
securitySchemes: undefined, // Or define actual security schemes if any
|
||||
security: undefined,
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text', 'task-status'], // task-status is a common output mode
|
||||
skills: [
|
||||
@ -349,11 +303,9 @@ const movieAgentCard: AgentCard = {
|
||||
],
|
||||
inputModes: ['text'], // Explicitly defining for skill
|
||||
outputModes: ['text', 'task-status'], // Explicitly defining for skill
|
||||
securityRequirements: [],
|
||||
},
|
||||
],
|
||||
documentationUrl: '',
|
||||
signatures: [],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
};
|
||||
|
||||
async function main() {
|
||||
|
||||
@ -2,12 +2,10 @@ import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
|
||||
|
||||
import {
|
||||
Task,
|
||||
TaskState,
|
||||
TaskStatusUpdateEvent,
|
||||
Message,
|
||||
TaskArtifactUpdateEvent,
|
||||
Artifact,
|
||||
Role,
|
||||
} from '../../../index.js';
|
||||
import { AgentExecutor, RequestContext, ExecutionEventBus } from '../../../server/index.js';
|
||||
|
||||
@ -32,14 +30,13 @@ export class SampleAgentExecutor implements AgentExecutor {
|
||||
// 1. Publish initial Task event if it's a new task
|
||||
if (!existingTask) {
|
||||
const initialTask: Task = {
|
||||
kind: 'task',
|
||||
id: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_SUBMITTED,
|
||||
state: 'submitted',
|
||||
timestamp: new Date().toISOString(),
|
||||
message: undefined,
|
||||
},
|
||||
artifacts: [],
|
||||
history: [userMessage], // Start history with the current user message
|
||||
metadata: userMessage.metadata, // Carry over metadata from message if any
|
||||
};
|
||||
@ -48,30 +45,22 @@ export class SampleAgentExecutor implements AgentExecutor {
|
||||
|
||||
// 2. Publish "working" status update
|
||||
const workingStatusUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_WORKING,
|
||||
state: 'working',
|
||||
message: {
|
||||
role: Role.ROLE_AGENT,
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: 'Processing your question' },
|
||||
metadata: undefined,
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
},
|
||||
],
|
||||
parts: [{ kind: 'text', text: 'Processing your question' }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
metadata: {},
|
||||
final: false,
|
||||
};
|
||||
eventBus.publish(workingStatusUpdate);
|
||||
|
||||
@ -84,39 +73,29 @@ export class SampleAgentExecutor implements AgentExecutor {
|
||||
artifactId: artifactId,
|
||||
name: 'Result',
|
||||
description: 'The final result from the agent.',
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: agentReplyText },
|
||||
metadata: undefined,
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
},
|
||||
],
|
||||
metadata: undefined,
|
||||
extensions: [],
|
||||
parts: [{ kind: 'text', text: agentReplyText }],
|
||||
};
|
||||
|
||||
const artifactUpdate: TaskArtifactUpdateEvent = {
|
||||
kind: 'artifact-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
artifact: resultArtifact,
|
||||
lastChunk: true,
|
||||
append: false,
|
||||
metadata: undefined,
|
||||
};
|
||||
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: TaskState.TASK_STATE_COMPLETED,
|
||||
state: 'completed',
|
||||
timestamp: new Date().toISOString(),
|
||||
message: undefined,
|
||||
},
|
||||
metadata: undefined,
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(finalUpdate);
|
||||
|
||||
@ -125,8 +104,8 @@ export class SampleAgentExecutor implements AgentExecutor {
|
||||
|
||||
parseInputMessage(message: Message): string {
|
||||
/** Process the user query and return a response. */
|
||||
const textPart = message.parts.find((part) => part.content?.$case === 'text');
|
||||
const query = textPart?.content?.$case === 'text' ? textPart.content.value.trim() : '';
|
||||
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.';
|
||||
|
||||
@ -15,27 +15,18 @@ const sampleAgentCard: AgentCard = {
|
||||
name: 'Sample Agent',
|
||||
description:
|
||||
'A sample agent to test the stream functionality and simulate the flow of tasks statuses.',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:41241/',
|
||||
protocolBinding: 'JSONRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '0.3.0',
|
||||
},
|
||||
],
|
||||
url: 'http://localhost:41241/',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples',
|
||||
url: 'https://example.com/a2a-samples', // Added provider URL
|
||||
},
|
||||
version: '1.0.0',
|
||||
version: '1.0.0', // Incremented version
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: false,
|
||||
extensions: [],
|
||||
extendedAgentCard: false,
|
||||
streaming: true, // The new framework supports streaming
|
||||
pushNotifications: false, // Assuming not implemented for this agent yet
|
||||
stateTransitionHistory: true, // Agent uses history
|
||||
},
|
||||
securitySchemes: {},
|
||||
securityRequirements: [],
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text', 'task-status'], // task-status is a common output mode
|
||||
skills: [
|
||||
@ -47,11 +38,9 @@ const sampleAgentCard: AgentCard = {
|
||||
examples: ['hi', 'hello world', 'how are you', 'goodbye'],
|
||||
inputModes: ['text'], // Explicitly defining for skill
|
||||
outputModes: ['text', 'task-status'], // Explicitly defining for skill
|
||||
securityRequirements: [],
|
||||
},
|
||||
],
|
||||
documentationUrl: '',
|
||||
signatures: [],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
};
|
||||
|
||||
async function main() {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
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, Role } from '../../index.js';
|
||||
import { Message } from '../../types.js';
|
||||
|
||||
export class AuthenticationAgentExecutor implements AgentExecutor {
|
||||
public cancelTask = async (_taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {};
|
||||
@ -18,21 +18,10 @@ export class AuthenticationAgentExecutor implements AgentExecutor {
|
||||
finalText = `The request is not coming from an authenticated user.`;
|
||||
}
|
||||
const finalMessage: Message = {
|
||||
kind: 'message',
|
||||
messageId: uuidv4(),
|
||||
role: Role.ROLE_AGENT,
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: finalText },
|
||||
metadata: undefined,
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
},
|
||||
],
|
||||
taskId: requestContext.taskId,
|
||||
contextId: requestContext.contextId,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
role: 'agent',
|
||||
parts: [{ kind: 'text', text: finalText }],
|
||||
};
|
||||
eventBus.publish(finalMessage);
|
||||
}
|
||||
|
||||
@ -16,24 +16,15 @@ import { authenticationHandler } from './authentication_middleware.js';
|
||||
const authenticationAgentCard: AgentCard = {
|
||||
name: 'Sample Authentication Agent',
|
||||
description: 'A sample agent to test the authentication functionality',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:41241/',
|
||||
protocolBinding: 'JSONRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '0.3.0',
|
||||
},
|
||||
],
|
||||
url: 'http://localhost:41241/',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples',
|
||||
},
|
||||
version: '1.0.0',
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
streaming: false,
|
||||
pushNotifications: false,
|
||||
extensions: [],
|
||||
extendedAgentCard: false,
|
||||
stateTransitionHistory: true, // Agent uses history
|
||||
},
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text', 'task-status'],
|
||||
@ -46,24 +37,11 @@ const authenticationAgentCard: AgentCard = {
|
||||
examples: ['hello, who am i?'],
|
||||
inputModes: ['text'],
|
||||
outputModes: ['text', 'task-status'],
|
||||
securityRequirements: [],
|
||||
},
|
||||
],
|
||||
securityRequirements: [{ schemes: { Bearer: { list: [] } } }],
|
||||
securitySchemes: {
|
||||
Bearer: {
|
||||
scheme: {
|
||||
$case: 'httpAuthSecurityScheme',
|
||||
value: {
|
||||
description: 'Bearer Token',
|
||||
scheme: 'bearer',
|
||||
bearerFormat: 'JWT',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
documentationUrl: 'https://example.com/docs',
|
||||
signatures: [],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
security: [{ Bearer: [] }],
|
||||
securitySchemes: { Bearer: { type: 'http', scheme: 'bearer' } },
|
||||
};
|
||||
|
||||
async function main() {
|
||||
|
||||
@ -5,15 +5,20 @@ import crypto from 'node:crypto';
|
||||
import { GoogleAuth } from 'google-auth-library';
|
||||
|
||||
import {
|
||||
// Specific Params/Payload types used by the CLI
|
||||
MessageSendParams, // Changed from TaskSendParams
|
||||
TaskStatusUpdateEvent,
|
||||
TaskArtifactUpdateEvent,
|
||||
Message,
|
||||
Task, // Added for direct Task events
|
||||
// Other types needed for message/part handling
|
||||
FilePart,
|
||||
DataPart,
|
||||
// Type for the agent card
|
||||
AgentCard,
|
||||
Part, // Added for explicit Part typing
|
||||
AGENT_CARD_PATH,
|
||||
} from '../index.js';
|
||||
import { TaskState, Role, taskStateToJSON, SendMessageRequest } from '../types/pb/a2a.js';
|
||||
|
||||
import {
|
||||
AuthenticationHandler,
|
||||
@ -88,7 +93,7 @@ let fetchImpl: typeof fetch = fetch;
|
||||
let agentCardPath = AGENT_CARD_PATH;
|
||||
if (process.argv.includes('--agent-engine')) {
|
||||
fetchImpl = createAuthenticatingFetchWithRetry(fetch, new ADCHandler());
|
||||
agentCardPath = 'a2a/extendedAgentCard'; // Agent Engine doesn't use well-known public agent card endpoint.
|
||||
agentCardPath = 'a2a/v1/card'; // Agent Engine doesn't use well-known public agent card endpoint.
|
||||
}
|
||||
const factory = new ClientFactory(
|
||||
ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
|
||||
@ -118,65 +123,63 @@ function printAgentEvent(event: TaskStatusUpdateEvent | TaskArtifactUpdateEvent)
|
||||
const prefix = colorize('magenta', `\n${agentName} [${timestamp}]:`);
|
||||
|
||||
// Check if it's a TaskStatusUpdateEvent
|
||||
if ('status' in event && 'taskId' in event) {
|
||||
if (event.kind === 'status-update') {
|
||||
const update = event as TaskStatusUpdateEvent; // Cast for type safety
|
||||
const state = update.status?.state;
|
||||
const state = update.status.state;
|
||||
let stateEmoji = '❓';
|
||||
let stateColor: keyof typeof colors = 'yellow';
|
||||
|
||||
switch (state) {
|
||||
case TaskState.TASK_STATE_WORKING:
|
||||
case 'working':
|
||||
stateEmoji = '⏳';
|
||||
stateColor = 'blue';
|
||||
break;
|
||||
case TaskState.TASK_STATE_INPUT_REQUIRED:
|
||||
case 'input-required':
|
||||
stateEmoji = '🤔';
|
||||
stateColor = 'yellow';
|
||||
break;
|
||||
case TaskState.TASK_STATE_COMPLETED:
|
||||
case 'completed':
|
||||
stateEmoji = '✅';
|
||||
stateColor = 'green';
|
||||
break;
|
||||
case TaskState.TASK_STATE_CANCELED:
|
||||
case 'canceled':
|
||||
stateEmoji = '⏹️';
|
||||
stateColor = 'gray';
|
||||
break;
|
||||
case TaskState.TASK_STATE_FAILED:
|
||||
case 'failed':
|
||||
stateEmoji = '❌';
|
||||
stateColor = 'red';
|
||||
break;
|
||||
default:
|
||||
stateEmoji = 'ℹ️';
|
||||
stateEmoji = 'ℹ️'; // For other states like submitted, rejected etc.
|
||||
stateColor = 'dim';
|
||||
break;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`${prefix} ${stateEmoji} Status: ${colorize(stateColor, taskStateToJSON(state!))} (Task: ${update.taskId}, Context: ${update.contextId})`
|
||||
`${prefix} ${stateEmoji} Status: ${colorize(stateColor, state)} (Task: ${update.taskId}, Context: ${update.contextId}) ${update.final ? colorize('bright', '[FINAL]') : ''}`
|
||||
);
|
||||
|
||||
if (update.status?.message) {
|
||||
if (update.status.message) {
|
||||
printMessageContent(update.status.message);
|
||||
}
|
||||
}
|
||||
// Check if it's a TaskArtifactUpdateEvent
|
||||
else if ('artifact' in event) {
|
||||
else if (event.kind === 'artifact-update') {
|
||||
const update = event as TaskArtifactUpdateEvent; // Cast for type safety
|
||||
console.log(
|
||||
`${prefix} 📄 Artifact Received: ${
|
||||
update.artifact?.name || '(unnamed)'
|
||||
} (ID: ${update.artifact?.artifactId}, Task: ${update.taskId}, Context: ${update.contextId})`
|
||||
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(),
|
||||
role: Role.ROLE_AGENT,
|
||||
parts: update.artifact?.parts || [],
|
||||
messageId: generateId(), // Dummy messageId
|
||||
kind: 'message', // Dummy kind
|
||||
role: 'agent', // Assuming artifact parts are from agent
|
||||
parts: update.artifact.parts,
|
||||
taskId: update.taskId,
|
||||
contextId: update.contextId,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
});
|
||||
} else {
|
||||
// This case should ideally not be reached if called correctly
|
||||
@ -190,39 +193,30 @@ function printAgentEvent(event: TaskStatusUpdateEvent | TaskArtifactUpdateEvent)
|
||||
|
||||
function printMessageContent(message: Message) {
|
||||
message.parts.forEach((part: Part, index: number) => {
|
||||
// Added explicit Part type
|
||||
const partPrefix = colorize('red', ` Part ${index + 1}:`);
|
||||
const p = part.content;
|
||||
|
||||
if (!p) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (p.$case) {
|
||||
case 'text':
|
||||
console.log(`${partPrefix} ${colorize('green', '📝 Text:')}`, p.value);
|
||||
break;
|
||||
case 'url':
|
||||
console.log(
|
||||
`${partPrefix} ${colorize('blue', '📄 URL:')} ${p.value} (Type: ${part.mediaType || 'N/A'})`
|
||||
);
|
||||
break;
|
||||
case 'raw':
|
||||
console.log(
|
||||
`${partPrefix} ${colorize('blue', '📄 Raw Bytes:')} (size: ${p.value.length}, Type: ${part.mediaType || 'N/A'})`
|
||||
);
|
||||
break;
|
||||
case 'data':
|
||||
console.log(
|
||||
`${partPrefix} ${colorize('yellow', '📊 Data:')}`,
|
||||
JSON.stringify(p.value, null, 2)
|
||||
);
|
||||
break;
|
||||
default:
|
||||
console.log(
|
||||
`${partPrefix} ${colorize('yellow', 'Unsupported part case:')}`,
|
||||
(p as any).$case
|
||||
);
|
||||
break;
|
||||
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
|
||||
}`
|
||||
);
|
||||
} else if (part.kind === 'data') {
|
||||
// Check kind property
|
||||
const dataPart = part as DataPart;
|
||||
console.log(
|
||||
`${partPrefix} ${colorize('yellow', '📊 Data:')}`,
|
||||
JSON.stringify(dataPart.data, null, 2)
|
||||
);
|
||||
} else {
|
||||
console.log(`${partPrefix} ${colorize('yellow', 'Unsupported part kind:')}`, part);
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -249,9 +243,10 @@ async function fetchAndDisplayAgentCard() {
|
||||
}
|
||||
|
||||
const supportedTransports = new Set<string>();
|
||||
if (card.supportedInterfaces) {
|
||||
for (const iface of card.supportedInterfaces) {
|
||||
supportedTransports.add(iface.protocolBinding);
|
||||
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(', ')}`);
|
||||
@ -319,23 +314,14 @@ async function main() {
|
||||
|
||||
const messagePayload: Message = {
|
||||
messageId: messageId,
|
||||
role: Role.ROLE_USER,
|
||||
kind: 'message', // Required by Message interface
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
content: {
|
||||
$case: 'text',
|
||||
value: input,
|
||||
},
|
||||
metadata: undefined,
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
kind: 'text', // Required by TextPart interface
|
||||
text: input,
|
||||
},
|
||||
],
|
||||
taskId: '',
|
||||
contextId: '',
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
};
|
||||
|
||||
// Conditionally add taskId to the message payload
|
||||
@ -347,11 +333,8 @@ async function main() {
|
||||
messagePayload.contextId = currentContextId;
|
||||
}
|
||||
|
||||
const params: SendMessageRequest = {
|
||||
tenant: '',
|
||||
const params: MessageSendParams = {
|
||||
message: messagePayload,
|
||||
configuration: undefined,
|
||||
metadata: {},
|
||||
// Optional: configuration for streaming, blocking, etc.
|
||||
// configuration: {
|
||||
// acceptedOutputModes: ['text/plain', 'application/json'], // Example
|
||||
@ -369,96 +352,73 @@ async function main() {
|
||||
const timestamp = new Date().toLocaleTimeString(); // Get fresh timestamp for each event
|
||||
const prefix = colorize('magenta', `\n${agentName} [${timestamp}]:`);
|
||||
|
||||
const payload = (event as any).payload;
|
||||
if (!payload || !payload.$case) {
|
||||
continue;
|
||||
}
|
||||
if (event.kind === 'status-update' || event.kind === 'artifact-update') {
|
||||
const typedEvent = event as TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
|
||||
printAgentEvent(typedEvent);
|
||||
|
||||
switch (payload.$case) {
|
||||
case 'statusUpdate': {
|
||||
const typedEvent = payload.value as TaskStatusUpdateEvent;
|
||||
printAgentEvent(typedEvent);
|
||||
|
||||
if (
|
||||
typedEvent.status?.state === TaskState.TASK_STATE_COMPLETED ||
|
||||
typedEvent.status?.state === TaskState.TASK_STATE_FAILED ||
|
||||
typedEvent.status?.state === TaskState.TASK_STATE_CANCELED ||
|
||||
typedEvent.status?.state === TaskState.TASK_STATE_REJECTED
|
||||
) {
|
||||
console.log(
|
||||
colorize(
|
||||
'yellow',
|
||||
` Task ${typedEvent.taskId} is final. Clearing current task ID.`
|
||||
)
|
||||
);
|
||||
currentTaskId = undefined;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'artifactUpdate': {
|
||||
const typedEvent = payload.value as TaskArtifactUpdateEvent;
|
||||
printAgentEvent(typedEvent);
|
||||
break;
|
||||
}
|
||||
case 'msg': {
|
||||
const msg = payload.value as Message;
|
||||
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.`
|
||||
)
|
||||
);
|
||||
currentTaskId = msg.taskId;
|
||||
}
|
||||
if (msg.contextId && msg.contextId !== currentContextId) {
|
||||
console.log(
|
||||
colorize('dim', ` Context ID updated to ${msg.contextId} based on message event.`)
|
||||
);
|
||||
currentContextId = msg.contextId;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'task': {
|
||||
const task = payload.value as Task;
|
||||
// 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(
|
||||
`${prefix} ${colorize('blue', 'ℹ️ Task Stream Event:')} ID: ${task.id}, Context: ${task.contextId}, Status: ${taskStateToJSON(task.status!.state)}`
|
||||
colorize('yellow', ` Task ${typedEvent.taskId} is final. Clearing current task ID.`)
|
||||
);
|
||||
if (task.id !== currentTaskId) {
|
||||
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}`
|
||||
)
|
||||
);
|
||||
currentContextId = task.contextId;
|
||||
}
|
||||
if (task.status?.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).`)
|
||||
);
|
||||
}
|
||||
break;
|
||||
currentTaskId = undefined;
|
||||
// Optionally, you might want to clear currentContextId as well if a task ending implies context ending.
|
||||
// currentContextId = undefined;
|
||||
// console.log(colorize("dim", ` Context ID also cleared as task is final.`));
|
||||
}
|
||||
default:
|
||||
} else if (event.kind === 'message') {
|
||||
const msg = event as Message;
|
||||
console.log(`${prefix} ${colorize('green', '✉️ Message Stream Event:')}`);
|
||||
printMessageContent(msg);
|
||||
if (msg.taskId && msg.taskId !== currentTaskId) {
|
||||
console.log(
|
||||
prefix,
|
||||
colorize('yellow', 'Received unknown event structure from stream:'),
|
||||
event
|
||||
colorize('dim', ` Task ID context updated to ${msg.taskId} based on message event.`)
|
||||
);
|
||||
break;
|
||||
currentTaskId = msg.taskId;
|
||||
}
|
||||
if (msg.contextId && msg.contextId !== currentContextId) {
|
||||
console.log(
|
||||
colorize('dim', ` Context ID updated to ${msg.contextId} based on message event.`)
|
||||
);
|
||||
currentContextId = msg.contextId;
|
||||
}
|
||||
} 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}`
|
||||
);
|
||||
if (task.id !== currentTaskId) {
|
||||
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}`
|
||||
)
|
||||
);
|
||||
currentContextId = task.contextId;
|
||||
}
|
||||
if (task.status.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).`));
|
||||
}
|
||||
} else {
|
||||
console.log(
|
||||
prefix,
|
||||
colorize('yellow', 'Received unknown event structure from stream:'),
|
||||
event
|
||||
);
|
||||
}
|
||||
}
|
||||
console.log(colorize('dim', `--- End of response stream for this input ---`));
|
||||
|
||||
@ -4,7 +4,7 @@ import {
|
||||
ExecutionEventBus,
|
||||
AgentExecutionEvent,
|
||||
} from '../../server/index.js';
|
||||
import { TaskStatusUpdateEvent } from '../../index.js';
|
||||
import { TaskStatusUpdateEvent } from '../../types.js';
|
||||
|
||||
const URI = 'https://github.com/a2aproject/a2a-js/src/samples/extensions/v1';
|
||||
|
||||
@ -19,9 +19,9 @@ class TimeStampExtension {
|
||||
}
|
||||
|
||||
timestampEvent(event: AgentExecutionEvent): void {
|
||||
if ('status' in event && 'taskId' in event) {
|
||||
if (event.kind === 'status-update') {
|
||||
const statusUpdateEvent = event as TaskStatusUpdateEvent;
|
||||
if (statusUpdateEvent.status?.message) {
|
||||
if (statusUpdateEvent.status.message) {
|
||||
if (!statusUpdateEvent.status.message.metadata) {
|
||||
statusUpdateEvent.status.message.metadata = {};
|
||||
}
|
||||
|
||||
@ -17,31 +17,18 @@ 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.',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:41241/',
|
||||
protocolBinding: 'JSONRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '0.3.0',
|
||||
},
|
||||
],
|
||||
url: 'http://localhost:41241/',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples',
|
||||
url: 'https://example.com/a2a-samples', // Added provider URL
|
||||
},
|
||||
version: '1.0.0',
|
||||
version: '1.0.0', // Incremented version
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
extensions: [
|
||||
{
|
||||
uri: 'https://github.com/a2aproject/a2a-js/src/samples/extensions/v1',
|
||||
description: 'Timestamp extension',
|
||||
required: false,
|
||||
params: {},
|
||||
},
|
||||
],
|
||||
streaming: true,
|
||||
pushNotifications: false,
|
||||
extendedAgentCard: false,
|
||||
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
|
||||
@ -54,13 +41,9 @@ const extensionAgentCard: AgentCard = {
|
||||
examples: ['hi', 'hello world', 'how are you', 'goodbye'],
|
||||
inputModes: ['text'], // Explicitly defining for skill
|
||||
outputModes: ['text', 'task-status'], // Explicitly defining for skill
|
||||
securityRequirements: [],
|
||||
},
|
||||
],
|
||||
documentationUrl: 'https://example.com/docs',
|
||||
securityRequirements: [],
|
||||
securitySchemes: {},
|
||||
signatures: [],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
};
|
||||
|
||||
async function main() {
|
||||
|
||||
14
src/samples/package-lock.json
generated
14
src/samples/package-lock.json
generated
@ -4768,9 +4768,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/fast-xml-parser": {
|
||||
"version": "5.5.6",
|
||||
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.5.6.tgz",
|
||||
"integrity": "sha512-3+fdZyBRVg29n4rXP0joHthhcHdPUHaIC16cuyyd1iLsuaO6Vea36MPrxgAzbZna8lhvZeRL8Bc9GP56/J9xEw==",
|
||||
"version": "5.5.7",
|
||||
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.5.7.tgz",
|
||||
"integrity": "sha512-LteOsISQ2GEiDHZch6L9hB0+MLoYVLToR7xotrzU0opCICBkxOPgHAy1HxAvtxfJNXDJpgAsQN30mkrfpO2Prg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@ -4784,7 +4784,7 @@
|
||||
"dependencies": {
|
||||
"fast-xml-builder": "^1.1.4",
|
||||
"path-expression-matcher": "^1.1.3",
|
||||
"strnum": "^2.1.2"
|
||||
"strnum": "^2.2.0"
|
||||
},
|
||||
"bin": {
|
||||
"fxparser": "src/cli/cli.js"
|
||||
@ -7344,9 +7344,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/strnum": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.2.tgz",
|
||||
"integrity": "sha512-l63NF9y/cLROq/yqKXSLtcMeeyOfnSQlfMSlzFt/K73oIaD8DGaQWd7Z34X9GPiKqP5rbSh84Hl4bOlLcjiSrQ==",
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://registry.npmjs.org/strnum/-/strnum-2.2.1.tgz",
|
||||
"integrity": "sha512-BwRvNd5/QoAtyW1na1y1LsJGQNvRlkde6Q/ipqqEaivoMdV+B1OMOTVdwR+N/cwVUcIt9PYyHmV8HyexCZSupg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Message, Task } from '../../index.js';
|
||||
import { Message, Task } from '../../types.js';
|
||||
import { ServerCallContext } from '../context.js';
|
||||
|
||||
export class RequestContext {
|
||||
|
||||
76
src/server/error.ts
Normal file
76
src/server/error.ts
Normal file
@ -0,0 +1,76 @@
|
||||
import * as schema from '../types.js';
|
||||
|
||||
/**
|
||||
* Custom error class for A2A server operations, incorporating JSON-RPC error codes.
|
||||
*/
|
||||
export class A2AError extends Error {
|
||||
public code: number;
|
||||
public data?: Record<string, unknown>;
|
||||
public taskId?: string; // Optional task ID context
|
||||
|
||||
constructor(code: number, message: string, data?: Record<string, unknown>, taskId?: string) {
|
||||
super(message);
|
||||
this.name = 'A2AError';
|
||||
this.code = code;
|
||||
this.data = data;
|
||||
this.taskId = taskId; // Store associated task ID if provided
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats the error into a standard JSON-RPC error object structure.
|
||||
*/
|
||||
toJSONRPCError(): schema.JSONRPCError {
|
||||
const errorObject: schema.JSONRPCError = {
|
||||
code: this.code,
|
||||
message: this.message,
|
||||
};
|
||||
|
||||
if (this.data !== undefined) {
|
||||
errorObject.data = this.data;
|
||||
}
|
||||
|
||||
return errorObject;
|
||||
}
|
||||
|
||||
// Static factory methods for common errors
|
||||
|
||||
static parseError(message: string, data?: Record<string, unknown>): A2AError {
|
||||
return new A2AError(-32700, message, data);
|
||||
}
|
||||
|
||||
static invalidRequest(message: string, data?: Record<string, unknown>): A2AError {
|
||||
return new A2AError(-32600, message, data);
|
||||
}
|
||||
|
||||
static methodNotFound(method: string): A2AError {
|
||||
return new A2AError(-32601, `Method not found: ${method}`);
|
||||
}
|
||||
|
||||
static invalidParams(message: string, data?: Record<string, unknown>): A2AError {
|
||||
return new A2AError(-32602, message, data);
|
||||
}
|
||||
|
||||
static internalError(message: string, data?: Record<string, unknown>): A2AError {
|
||||
return new A2AError(-32603, message, data);
|
||||
}
|
||||
|
||||
static taskNotFound(taskId: string): A2AError {
|
||||
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);
|
||||
}
|
||||
|
||||
static pushNotificationNotSupported(): A2AError {
|
||||
return new A2AError(-32003, 'Push Notification is not supported');
|
||||
}
|
||||
|
||||
static unsupportedOperation(operation: string): A2AError {
|
||||
return new A2AError(-32004, `Unsupported operation: ${operation}`);
|
||||
}
|
||||
|
||||
static authenticatedExtendedCardNotConfigured(): A2AError {
|
||||
return new A2AError(-32007, `Extended card not configured.`);
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
import { Message, Task, TaskStatusUpdateEvent, TaskArtifactUpdateEvent } from '../../index.js';
|
||||
import { Message, Task, TaskStatusUpdateEvent, TaskArtifactUpdateEvent } from '../../types.js';
|
||||
|
||||
export type AgentExecutionEvent = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
|
||||
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import { TaskStatusUpdateEvent } from '../../index.js';
|
||||
import { TaskStatusUpdateEvent } from '../../types.js';
|
||||
import { ExecutionEventBus, AgentExecutionEvent } from './execution_event_bus.js';
|
||||
import { TERMINAL_STATE_LIST } from '../utils.js';
|
||||
|
||||
/**
|
||||
* An async queue that subscribes to an ExecutionEventBus for events
|
||||
@ -41,10 +40,8 @@ export class ExecutionEventQueue {
|
||||
const event = this.eventQueue.shift()!;
|
||||
yield event;
|
||||
if (
|
||||
'messageId' in event ||
|
||||
('status' in event &&
|
||||
'taskId' in event &&
|
||||
TERMINAL_STATE_LIST.includes((event as TaskStatusUpdateEvent).status!.state))
|
||||
event.kind === 'message' ||
|
||||
(event.kind === 'status-update' && (event as TaskStatusUpdateEvent).final)
|
||||
) {
|
||||
this.handleFinished();
|
||||
break;
|
||||
|
||||
61
src/server/express/a2a_express_app.ts
Normal file
61
src/server/express/a2a_express_app.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import express, { 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';
|
||||
|
||||
/**
|
||||
* @deprecated Use specific middlewares ({@link jsonRpcHandler}, {@link agentCardHandler}) directly.
|
||||
*/
|
||||
export class A2AExpressApp {
|
||||
private requestHandler: A2ARequestHandler;
|
||||
private userBuilder: UserBuilder;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
router.use(
|
||||
jsonRpcHandler({
|
||||
requestHandler: this.requestHandler,
|
||||
userBuilder: this.userBuilder,
|
||||
})
|
||||
);
|
||||
router.use(`/${agentCardPath}`, agentCardHandler({ agentCardProvider: this.requestHandler }));
|
||||
|
||||
app.use(baseUrl, router);
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
import express, { Request, RequestHandler, Response } from 'express';
|
||||
import { AgentCard } from '../../index.js';
|
||||
import { AgentCard } from '../../types.js';
|
||||
|
||||
export interface AgentCardHandlerOptions {
|
||||
agentCardProvider: AgentCardProvider;
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
* 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';
|
||||
|
||||
@ -5,8 +5,8 @@ import express, {
|
||||
NextFunction,
|
||||
RequestHandler,
|
||||
} from 'express';
|
||||
import { JSONRPCErrorResponse } from '../../core.js';
|
||||
import { JSONRPCResponse } from '../transports/jsonrpc/jsonrpc_transport_handler.js';
|
||||
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';
|
||||
@ -14,7 +14,6 @@ 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';
|
||||
import { RequestMalformedError } from '../../errors.js';
|
||||
|
||||
export interface JsonRpcHandlerOptions {
|
||||
requestHandler: A2ARequestHandler;
|
||||
@ -53,7 +52,11 @@ export function jsonRpcHandler(options: JsonRpcHandlerOptions): RequestHandler {
|
||||
}
|
||||
// Check if it's an AsyncGenerator (stream)
|
||||
if (typeof (rpcResponseOrStream as AsyncGenerator)?.[Symbol.asyncIterator] === 'function') {
|
||||
const stream = rpcResponseOrStream as AsyncGenerator<JSONRPCResponse, void, undefined>;
|
||||
const stream = rpcResponseOrStream as AsyncGenerator<
|
||||
JSONRPCSuccessResponse,
|
||||
void,
|
||||
undefined
|
||||
>;
|
||||
|
||||
// Set SSE headers using shared utility
|
||||
Object.entries(SSE_HEADERS).forEach(([key, value]) => {
|
||||
@ -70,10 +73,19 @@ export function jsonRpcHandler(options: JsonRpcHandlerOptions): RequestHandler {
|
||||
}
|
||||
} 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: JsonRpcTransportHandler.mapToJSONRPCError(streamError),
|
||||
error: a2aError.toJSONRPCError(),
|
||||
};
|
||||
if (!res.headersSent) {
|
||||
// Should not happen if flushHeaders worked
|
||||
@ -96,10 +108,12 @@ export function jsonRpcHandler(options: JsonRpcHandlerOptions): RequestHandler {
|
||||
} 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: JsonRpcTransportHandler.mapToJSONRPCError(error),
|
||||
error: a2aError.toJSONRPCError(),
|
||||
};
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json(errorResponse);
|
||||
@ -121,12 +135,11 @@ export const jsonErrorHandler: ErrorRequestHandler = (
|
||||
) => {
|
||||
// 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: JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new RequestMalformedError('Invalid JSON payload.')
|
||||
),
|
||||
error: a2aError.toJSONRPCError(),
|
||||
};
|
||||
return res.status(400).json(errorResponse);
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ import express, {
|
||||
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,
|
||||
@ -18,21 +19,10 @@ import { HTTP_EXTENSION_HEADER } from '../../constants.js';
|
||||
import { UserBuilder } from './common.js';
|
||||
import { Extensions } from '../../extensions.js';
|
||||
|
||||
import {
|
||||
AgentCard,
|
||||
ListTaskPushNotificationConfigsResponse,
|
||||
ListTasksResponse,
|
||||
MessageFns,
|
||||
SendMessageRequest,
|
||||
SendMessageResponse,
|
||||
StreamResponse,
|
||||
Task,
|
||||
TaskPushNotificationConfig,
|
||||
} from '../../types/pb/a2a.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, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '../../index.js';
|
||||
import { RequestMalformedError } from '../../errors.js';
|
||||
import { Message, Task, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '../../types.js';
|
||||
|
||||
/**
|
||||
* Options for configuring the HTTP+JSON/REST handler.
|
||||
@ -58,7 +48,8 @@ const restErrorHandler: ErrorRequestHandler = (
|
||||
next: NextFunction
|
||||
) => {
|
||||
if (err instanceof SyntaxError && 'body' in err) {
|
||||
return res.status(400).json(toHTTPError(new RequestMalformedError('Invalid JSON payload.')));
|
||||
const a2aError = A2AError.parseError('Invalid JSON payload.');
|
||||
return res.status(400).json(toHTTPError(a2aError));
|
||||
}
|
||||
next(err);
|
||||
};
|
||||
@ -79,9 +70,9 @@ type AsyncRouteHandler = (req: Request, res: Response) => Promise<void>;
|
||||
*
|
||||
* This handler implements the A2A REST API specification with snake_case
|
||||
* field names, providing endpoints for:
|
||||
* - Agent card retrieval (GET /extendedAgentCard)
|
||||
* - Message sending with optional streaming (POST /message:send|stream)
|
||||
* - Task management (GET/POST /tasks/:taskId:cancel|subscribe)
|
||||
* - 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
|
||||
@ -151,7 +142,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
statusCode: number,
|
||||
context: ServerCallContext,
|
||||
body?: T,
|
||||
responseType?: MessageFns<T>
|
||||
responseType?: a2a.MessageFns<T>
|
||||
): void => {
|
||||
setExtensionsHeader(res, context);
|
||||
res.status(statusCode);
|
||||
@ -192,7 +183,12 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
firstResult = await iterator.next();
|
||||
} catch (error) {
|
||||
// Early error - return proper HTTP error
|
||||
sendResponse(res, mapErrorToStatus(error), context, toHTTPError(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;
|
||||
}
|
||||
|
||||
@ -207,18 +203,24 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
// Write first event
|
||||
if (!firstResult.done) {
|
||||
const proto = ToProto.messageStreamResult(firstResult.value);
|
||||
const result = StreamResponse.toJSON(proto);
|
||||
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 = StreamResponse.toJSON(proto);
|
||||
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(streamError)));
|
||||
res.write(formatSSEErrorEvent(toHTTPError(a2aError)));
|
||||
}
|
||||
} finally {
|
||||
if (!res.writableEnded) {
|
||||
@ -242,8 +244,12 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
}
|
||||
return;
|
||||
}
|
||||
const statusCode = mapErrorToStatus(error);
|
||||
res.status(statusCode).json(toHTTPError(error));
|
||||
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));
|
||||
};
|
||||
|
||||
/**
|
||||
@ -268,7 +274,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* GET /extendedAgentCard
|
||||
* GET /v1/card
|
||||
*
|
||||
* Retrieves the authenticated extended agent card.
|
||||
*
|
||||
@ -276,16 +282,17 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
* @returns 500 Internal Server Error on failure
|
||||
*/
|
||||
router.get(
|
||||
'/extendedAgentCard',
|
||||
'/v1/card',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.getAuthenticatedExtendedAgentCard(context);
|
||||
sendResponse<AgentCard>(res, HTTP_STATUS.OK, context, result, AgentCard);
|
||||
const protoResult = ToProto.agentCard(result);
|
||||
sendResponse<a2a.AgentCard>(res, HTTP_STATUS.OK, context, protoResult, a2a.AgentCard);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /message:send
|
||||
* POST /v1/message:send
|
||||
*
|
||||
* Sends a message to the agent synchronously.
|
||||
* Returns either a Message (for immediate responses) or a Task (for async processing).
|
||||
@ -296,24 +303,25 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
* @returns 400 Bad Request if message is invalid
|
||||
*/
|
||||
router.post(
|
||||
'/message\\:send',
|
||||
'/v1/message\\:send',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const params = SendMessageRequest.fromJSON(req.body);
|
||||
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<SendMessageResponse>(
|
||||
sendResponse<a2a.SendMessageResponse>(
|
||||
res,
|
||||
HTTP_STATUS.CREATED,
|
||||
context,
|
||||
protoResult,
|
||||
SendMessageResponse
|
||||
a2a.SendMessageResponse
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /message:stream
|
||||
* POST /v1/message:stream
|
||||
*
|
||||
* Sends a message to the agent with streaming response.
|
||||
* Returns a Server-Sent Events (SSE) stream of updates.
|
||||
@ -325,17 +333,18 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
* @returns 501 Not Implemented if streaming not supported
|
||||
*/
|
||||
router.post(
|
||||
'/message\\:stream',
|
||||
'/v1/message\\:stream',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const params = SendMessageRequest.fromJSON(req.body);
|
||||
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 /tasks/:taskId
|
||||
* GET /v1/tasks/:taskId
|
||||
*
|
||||
* Retrieves the current status and details of a task.
|
||||
*
|
||||
@ -346,7 +355,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
* @returns 404 Not Found if task doesn't exist
|
||||
*/
|
||||
router.get(
|
||||
'/tasks/:taskId',
|
||||
'/v1/tasks/:taskId',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.getTask(
|
||||
@ -355,12 +364,13 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
//TODO: clarify for version 1.0.0 the format of the historyLength query parameter, and if history should always be added to the returned object
|
||||
req.query.historyLength ?? req.query.history_length
|
||||
);
|
||||
sendResponse<Task>(res, HTTP_STATUS.OK, context, result, Task);
|
||||
const protoResult = ToProto.task(result);
|
||||
sendResponse<a2a.Task>(res, HTTP_STATUS.OK, context, protoResult, a2a.Task);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /tasks/:taskId:cancel
|
||||
* POST /v1/tasks/:taskId:cancel
|
||||
*
|
||||
* Attempts to cancel an ongoing task.
|
||||
* The task may not be immediately canceled depending on its current state.
|
||||
@ -371,33 +381,17 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
* @returns 409 Conflict if task cannot be canceled
|
||||
*/
|
||||
router.post(
|
||||
'/tasks/:taskId\\:cancel',
|
||||
'/v1/tasks/:taskId\\:cancel',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.cancelTask(req.params.taskId, context);
|
||||
sendResponse<Task>(res, HTTP_STATUS.ACCEPTED, context, result, Task);
|
||||
const protoResult = ToProto.task(result);
|
||||
sendResponse<a2a.Task>(res, HTTP_STATUS.ACCEPTED, context, protoResult, a2a.Task);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /tasks
|
||||
*
|
||||
* Retrieves a list of tasks with optional filtering and pagination capabilities.
|
||||
*
|
||||
* @returns 200 OK with ListTasksResponse
|
||||
* @returns 400 Bad Request if filter or pageSize is invalid
|
||||
*/
|
||||
router.get(
|
||||
'/tasks',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.listTasks(req.query, context);
|
||||
sendResponse<ListTasksResponse>(res, HTTP_STATUS.OK, context, result, ListTasksResponse);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /tasks/:taskId:subscribe
|
||||
* 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.
|
||||
@ -408,7 +402,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
* @returns 501 Not Implemented if streaming not supported
|
||||
*/
|
||||
router.post(
|
||||
'/tasks/:taskId\\:subscribe',
|
||||
'/v1/tasks/:taskId\\:subscribe',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const stream = await restTransportHandler.resubscribe(req.params.taskId, context);
|
||||
@ -417,7 +411,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /tasks/:taskId/pushNotificationConfigs
|
||||
* POST /v1/tasks/:taskId/pushNotificationConfigs
|
||||
*
|
||||
* Creates a push notification configuration for a task.
|
||||
* The agent will send task updates to the configured webhook URL.
|
||||
@ -428,23 +422,25 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
* @returns 501 Not Implemented if push notifications not supported
|
||||
*/
|
||||
router.post(
|
||||
'/tasks/:taskId/pushNotificationConfigs',
|
||||
'/v1/tasks/:taskId/pushNotificationConfigs',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const params = TaskPushNotificationConfig.fromJSON(req.body);
|
||||
const result = await restTransportHandler.createTaskPushNotificationConfig(params, context);
|
||||
sendResponse<TaskPushNotificationConfig>(
|
||||
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,
|
||||
result,
|
||||
TaskPushNotificationConfig
|
||||
protoResult,
|
||||
a2a.TaskPushNotificationConfig
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /tasks/:taskId/pushNotificationConfigs
|
||||
* GET /v1/tasks/:taskId/pushNotificationConfigs
|
||||
*
|
||||
* Lists all push notification configurations for a task.
|
||||
*
|
||||
@ -453,7 +449,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
* @returns 404 Not Found if task doesn't exist
|
||||
*/
|
||||
router.get(
|
||||
'/tasks/:taskId/pushNotificationConfigs',
|
||||
'/v1/tasks/:taskId/pushNotificationConfigs',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.listTaskPushNotificationConfigs(
|
||||
@ -461,18 +457,18 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
context
|
||||
);
|
||||
const protoResult = ToProto.listTaskPushNotificationConfig(result);
|
||||
sendResponse<ListTaskPushNotificationConfigsResponse>(
|
||||
sendResponse<a2a.ListTaskPushNotificationConfigResponse>(
|
||||
res,
|
||||
HTTP_STATUS.OK,
|
||||
context,
|
||||
protoResult,
|
||||
ListTaskPushNotificationConfigsResponse
|
||||
a2a.ListTaskPushNotificationConfigResponse
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /tasks/:taskId/pushNotificationConfigs/:configId
|
||||
* GET /v1/tasks/:taskId/pushNotificationConfigs/:configId
|
||||
*
|
||||
* Retrieves a specific push notification configuration.
|
||||
*
|
||||
@ -482,7 +478,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
* @returns 404 Not Found if task or config doesn't exist
|
||||
*/
|
||||
router.get(
|
||||
'/tasks/:taskId/pushNotificationConfigs/:configId',
|
||||
'/v1/tasks/:taskId/pushNotificationConfigs/:configId',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
const result = await restTransportHandler.getTaskPushNotificationConfig(
|
||||
@ -490,18 +486,19 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
req.params.configId,
|
||||
context
|
||||
);
|
||||
sendResponse<TaskPushNotificationConfig>(
|
||||
const protoResult = ToProto.taskPushNotificationConfig(result);
|
||||
sendResponse<a2a.TaskPushNotificationConfig>(
|
||||
res,
|
||||
HTTP_STATUS.OK,
|
||||
context,
|
||||
result,
|
||||
TaskPushNotificationConfig
|
||||
protoResult,
|
||||
a2a.TaskPushNotificationConfig
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* DELETE /tasks/:taskId/pushNotificationConfigs/:configId
|
||||
* DELETE /v1/tasks/:taskId/pushNotificationConfigs/:configId
|
||||
*
|
||||
* Deletes a push notification configuration.
|
||||
*
|
||||
@ -511,7 +508,7 @@ export function restHandler(options: RestHandlerOptions): RequestHandler {
|
||||
* @returns 404 Not Found if task or config doesn't exist
|
||||
*/
|
||||
router.delete(
|
||||
'/tasks/:taskId/pushNotificationConfigs/:configId',
|
||||
'/v1/tasks/:taskId/pushNotificationConfigs/:configId',
|
||||
asyncHandler(async (req, res) => {
|
||||
const context = await buildContext(req);
|
||||
await restTransportHandler.deleteTaskPushNotificationConfig(
|
||||
|
||||
@ -3,39 +3,29 @@ import {
|
||||
A2AServiceServer,
|
||||
AgentCard,
|
||||
CancelTaskRequest,
|
||||
CreateTaskPushNotificationConfigRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
GetExtendedAgentCardRequest,
|
||||
GetAgentCardRequest,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
GetTaskRequest,
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
ListTaskPushNotificationConfigsResponse,
|
||||
ListTasksRequest,
|
||||
ListTasksResponse,
|
||||
ListTaskPushNotificationConfigRequest,
|
||||
ListTaskPushNotificationConfigResponse,
|
||||
SendMessageRequest,
|
||||
SendMessageResponse,
|
||||
StreamResponse,
|
||||
SubscribeToTaskRequest,
|
||||
Task,
|
||||
TaskPushNotificationConfig,
|
||||
} from '../../grpc/pb/a2a.js';
|
||||
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 {
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
ContentTypeNotSupportedError,
|
||||
InvalidAgentResponseError,
|
||||
RequestMalformedError,
|
||||
GenericError,
|
||||
PushNotificationNotSupportedError,
|
||||
TaskNotCancelableError,
|
||||
TaskNotFoundError,
|
||||
UnsupportedOperationError,
|
||||
} from '../../errors.js';
|
||||
import { A2AError } from '../error.js';
|
||||
|
||||
/**
|
||||
* Options for configuring the gRPC handler.
|
||||
@ -118,7 +108,7 @@ export function grpcService(options: GrpcServiceOptions): A2AServiceServer {
|
||||
return wrapUnary(
|
||||
call,
|
||||
callback,
|
||||
(req) => req,
|
||||
FromProto.messageSendParams,
|
||||
requestHandler.sendMessage.bind(requestHandler),
|
||||
ToProto.messageSendResult
|
||||
);
|
||||
@ -129,18 +119,18 @@ export function grpcService(options: GrpcServiceOptions): A2AServiceServer {
|
||||
): Promise<void> {
|
||||
return wrapStreaming(
|
||||
call,
|
||||
(req) => req,
|
||||
FromProto.messageSendParams,
|
||||
requestHandler.sendMessageStream.bind(requestHandler),
|
||||
ToProto.messageStreamResult
|
||||
);
|
||||
},
|
||||
|
||||
subscribeToTask(
|
||||
call: grpc.ServerWritableStream<SubscribeToTaskRequest, StreamResponse>
|
||||
taskSubscription(
|
||||
call: grpc.ServerWritableStream<TaskSubscriptionRequest, StreamResponse>
|
||||
): Promise<void> {
|
||||
return wrapStreaming(
|
||||
call,
|
||||
(req) => req,
|
||||
FromProto.taskIdParams,
|
||||
requestHandler.resubscribe.bind(requestHandler),
|
||||
ToProto.messageStreamResult
|
||||
);
|
||||
@ -153,38 +143,41 @@ export function grpcService(options: GrpcServiceOptions): A2AServiceServer {
|
||||
return wrapUnary(
|
||||
call,
|
||||
callback,
|
||||
(req) => req,
|
||||
FromProto.deleteTaskPushNotificationConfigParams,
|
||||
requestHandler.deleteTaskPushNotificationConfig.bind(requestHandler),
|
||||
() => ({})
|
||||
);
|
||||
},
|
||||
|
||||
listTaskPushNotificationConfigs(
|
||||
listTaskPushNotificationConfig(
|
||||
call: grpc.ServerUnaryCall<
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
ListTaskPushNotificationConfigsResponse
|
||||
ListTaskPushNotificationConfigRequest,
|
||||
ListTaskPushNotificationConfigResponse
|
||||
>,
|
||||
callback: grpc.sendUnaryData<ListTaskPushNotificationConfigsResponse>
|
||||
callback: grpc.sendUnaryData<ListTaskPushNotificationConfigResponse>
|
||||
): Promise<void> {
|
||||
return wrapUnary(
|
||||
call,
|
||||
callback,
|
||||
(req) => req,
|
||||
FromProto.listTaskPushNotificationConfigParams,
|
||||
requestHandler.listTaskPushNotificationConfigs.bind(requestHandler),
|
||||
ToProto.listTaskPushNotificationConfig
|
||||
);
|
||||
},
|
||||
|
||||
createTaskPushNotificationConfig(
|
||||
call: grpc.ServerUnaryCall<TaskPushNotificationConfig, TaskPushNotificationConfig>,
|
||||
call: grpc.ServerUnaryCall<
|
||||
CreateTaskPushNotificationConfigRequest,
|
||||
TaskPushNotificationConfig
|
||||
>,
|
||||
callback: grpc.sendUnaryData<TaskPushNotificationConfig>
|
||||
): Promise<void> {
|
||||
return wrapUnary(
|
||||
call,
|
||||
callback,
|
||||
(req) => req,
|
||||
requestHandler.createTaskPushNotificationConfig.bind(requestHandler),
|
||||
(res) => res
|
||||
FromProto.createTaskPushNotificationConfig,
|
||||
requestHandler.setTaskPushNotificationConfig.bind(requestHandler),
|
||||
ToProto.taskPushNotificationConfig
|
||||
);
|
||||
},
|
||||
|
||||
@ -195,9 +188,9 @@ export function grpcService(options: GrpcServiceOptions): A2AServiceServer {
|
||||
return wrapUnary(
|
||||
call,
|
||||
callback,
|
||||
(req) => req,
|
||||
FromProto.getTaskPushNotificationConfigParams,
|
||||
requestHandler.getTaskPushNotificationConfig.bind(requestHandler),
|
||||
(res) => res
|
||||
ToProto.taskPushNotificationConfig
|
||||
);
|
||||
},
|
||||
|
||||
@ -208,9 +201,9 @@ export function grpcService(options: GrpcServiceOptions): A2AServiceServer {
|
||||
return wrapUnary(
|
||||
call,
|
||||
callback,
|
||||
(req) => req,
|
||||
FromProto.taskQueryParams,
|
||||
requestHandler.getTask.bind(requestHandler),
|
||||
(res) => res
|
||||
ToProto.task
|
||||
);
|
||||
},
|
||||
|
||||
@ -221,14 +214,14 @@ export function grpcService(options: GrpcServiceOptions): A2AServiceServer {
|
||||
return wrapUnary(
|
||||
call,
|
||||
callback,
|
||||
(req) => req,
|
||||
FromProto.taskIdParams,
|
||||
requestHandler.cancelTask.bind(requestHandler),
|
||||
(res) => res
|
||||
ToProto.task
|
||||
);
|
||||
},
|
||||
|
||||
getExtendedAgentCard(
|
||||
call: grpc.ServerUnaryCall<GetExtendedAgentCardRequest, AgentCard>,
|
||||
getAgentCard(
|
||||
call: grpc.ServerUnaryCall<GetAgentCardRequest, AgentCard>,
|
||||
callback: grpc.sendUnaryData<AgentCard>
|
||||
): Promise<void> {
|
||||
return wrapUnary(
|
||||
@ -236,19 +229,7 @@ export function grpcService(options: GrpcServiceOptions): A2AServiceServer {
|
||||
callback,
|
||||
() => ({}),
|
||||
(_params, context) => requestHandler.getAuthenticatedExtendedAgentCard(context),
|
||||
(res) => res
|
||||
);
|
||||
},
|
||||
listTasks(
|
||||
call: grpc.ServerUnaryCall<ListTasksRequest, ListTasksResponse>,
|
||||
callback: grpc.sendUnaryData<ListTasksResponse>
|
||||
): Promise<void> {
|
||||
return wrapUnary(
|
||||
call,
|
||||
callback,
|
||||
(req) => req,
|
||||
requestHandler.listTasks.bind(requestHandler),
|
||||
(res) => res
|
||||
ToProto.agentCard
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -259,24 +240,28 @@ export function grpcService(options: GrpcServiceOptions): A2AServiceServer {
|
||||
/**
|
||||
* Maps A2AError or standard Error to gRPC Status codes
|
||||
*/
|
||||
const mapToError = (error: unknown): Partial<grpc.ServiceError> => {
|
||||
let code = grpc.status.UNKNOWN;
|
||||
if (error instanceof TaskNotFoundError) code = grpc.status.NOT_FOUND;
|
||||
else if (error instanceof TaskNotCancelableError) code = grpc.status.FAILED_PRECONDITION;
|
||||
else if (error instanceof PushNotificationNotSupportedError) code = grpc.status.UNIMPLEMENTED;
|
||||
else if (error instanceof UnsupportedOperationError) code = grpc.status.UNIMPLEMENTED;
|
||||
else if (error instanceof ContentTypeNotSupportedError) code = grpc.status.INVALID_ARGUMENT;
|
||||
else if (error instanceof InvalidAgentResponseError) code = grpc.status.INTERNAL;
|
||||
else if (error instanceof AuthenticatedExtendedCardNotConfiguredError)
|
||||
code = grpc.status.FAILED_PRECONDITION;
|
||||
else if (error instanceof RequestMalformedError) code = grpc.status.INVALID_ARGUMENT;
|
||||
else if (error instanceof GenericError) code = grpc.status.INTERNAL;
|
||||
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 message = error instanceof Error ? error.message : 'Internal server error';
|
||||
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,
|
||||
details: message,
|
||||
code: mapping[a2aError.code] ?? grpc.status.UNKNOWN,
|
||||
details: a2aError.message,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@ -5,5 +5,5 @@
|
||||
|
||||
export { grpcService } from './grpc_service.js';
|
||||
export type { GrpcServiceOptions } from './grpc_service.js';
|
||||
export { A2AServiceService as A2AService } from '../../grpc/pb/a2a.js';
|
||||
export { A2AServiceService as A2AService } from '../../grpc/pb/a2a_services.js';
|
||||
export { UserBuilder } from './common.js';
|
||||
|
||||
@ -25,16 +25,7 @@ export { InMemoryTaskStore } from './store.js';
|
||||
|
||||
export { JsonRpcTransportHandler } from './transports/jsonrpc/jsonrpc_transport_handler.js';
|
||||
export { ServerCallContext } from './context.js';
|
||||
export {
|
||||
RequestMalformedError,
|
||||
TaskNotFoundError,
|
||||
TaskNotCancelableError,
|
||||
PushNotificationNotSupportedError,
|
||||
UnsupportedOperationError,
|
||||
ContentTypeNotSupportedError,
|
||||
InvalidAgentResponseError,
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
} from '../errors.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';
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Task, TaskPushNotificationConfig } from '../../index.js';
|
||||
import { Task, PushNotificationConfig } from '../../types.js';
|
||||
import { PushNotificationSender } from './push_notification_sender.js';
|
||||
import { PushNotificationStore } from './push_notification_store.js';
|
||||
|
||||
@ -66,7 +66,7 @@ export class DefaultPushNotificationSender implements PushNotificationSender {
|
||||
|
||||
private async _dispatchNotification(
|
||||
task: Task,
|
||||
pushConfig: TaskPushNotificationConfig
|
||||
pushConfig: PushNotificationConfig
|
||||
): Promise<void> {
|
||||
const url = pushConfig.url;
|
||||
const controller = new AbortController();
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Task } from '../../index.js';
|
||||
import { Task } from '../../types.js';
|
||||
|
||||
export interface PushNotificationSender {
|
||||
send(task: Task): Promise<void>;
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
import { TaskPushNotificationConfig } from '../../index.js';
|
||||
import { PushNotificationConfig } from '../../types.js';
|
||||
|
||||
export interface PushNotificationStore {
|
||||
save(taskId: string, pushNotificationConfig: TaskPushNotificationConfig): Promise<void>;
|
||||
load(taskId: string): Promise<TaskPushNotificationConfig[]>;
|
||||
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, TaskPushNotificationConfig[]> = new Map();
|
||||
private store: Map<string, PushNotificationConfig[]> = new Map();
|
||||
|
||||
async save(taskId: string, pushNotificationConfig: TaskPushNotificationConfig): Promise<void> {
|
||||
async save(taskId: string, pushNotificationConfig: PushNotificationConfig): Promise<void> {
|
||||
const configs = this.store.get(taskId) || [];
|
||||
|
||||
// Set ID if it's not already set
|
||||
@ -28,7 +28,7 @@ export class InMemoryPushNotificationStore implements PushNotificationStore {
|
||||
this.store.set(taskId, configs);
|
||||
}
|
||||
|
||||
async load(taskId: string): Promise<TaskPushNotificationConfig[]> {
|
||||
async load(taskId: string): Promise<PushNotificationConfig[]> {
|
||||
const configs = this.store.get(taskId);
|
||||
return configs || [];
|
||||
}
|
||||
|
||||
@ -1,20 +1,17 @@
|
||||
import {
|
||||
Message,
|
||||
AgentCard,
|
||||
MessageSendParams,
|
||||
Task,
|
||||
TaskStatusUpdateEvent,
|
||||
TaskArtifactUpdateEvent,
|
||||
TaskQueryParams,
|
||||
TaskIdParams,
|
||||
TaskPushNotificationConfig,
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
CancelTaskRequest,
|
||||
GetTaskRequest,
|
||||
SubscribeToTaskRequest,
|
||||
SendMessageRequest,
|
||||
ListTasksRequest,
|
||||
ListTasksResponse,
|
||||
} from '../../index.js';
|
||||
GetTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
} from '../../types.js';
|
||||
import { ServerCallContext } from '../context.js';
|
||||
|
||||
export interface A2ARequestHandler {
|
||||
@ -22,10 +19,10 @@ export interface A2ARequestHandler {
|
||||
|
||||
getAuthenticatedExtendedAgentCard(context?: ServerCallContext): Promise<AgentCard>;
|
||||
|
||||
sendMessage(params: SendMessageRequest, context?: ServerCallContext): Promise<Message | Task>;
|
||||
sendMessage(params: MessageSendParams, context?: ServerCallContext): Promise<Message | Task>;
|
||||
|
||||
sendMessageStream(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
context?: ServerCallContext
|
||||
): AsyncGenerator<
|
||||
Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent,
|
||||
@ -33,33 +30,31 @@ export interface A2ARequestHandler {
|
||||
undefined
|
||||
>;
|
||||
|
||||
getTask(params: GetTaskRequest, context?: ServerCallContext): Promise<Task>;
|
||||
cancelTask(params: CancelTaskRequest, context?: ServerCallContext): Promise<Task>;
|
||||
getTask(params: TaskQueryParams, context?: ServerCallContext): Promise<Task>;
|
||||
cancelTask(params: TaskIdParams, context?: ServerCallContext): Promise<Task>;
|
||||
|
||||
createTaskPushNotificationConfig(
|
||||
setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
context?: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
|
||||
getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigRequest,
|
||||
params: TaskIdParams | GetTaskPushNotificationConfigParams,
|
||||
context?: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
|
||||
listTaskPushNotificationConfigs(
|
||||
params: ListTaskPushNotificationConfigsRequest,
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
context?: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig[]>;
|
||||
|
||||
deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigRequest,
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
context?: ServerCallContext
|
||||
): Promise<void>;
|
||||
|
||||
resubscribe(
|
||||
params: SubscribeToTaskRequest,
|
||||
params: TaskIdParams,
|
||||
context?: ServerCallContext
|
||||
): AsyncGenerator<Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent, void, undefined>;
|
||||
|
||||
listTasks(params: ListTasksRequest, context?: ServerCallContext): Promise<ListTasksResponse>;
|
||||
}
|
||||
|
||||
@ -1,36 +1,23 @@
|
||||
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
|
||||
|
||||
import {
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
RequestMalformedError,
|
||||
PushNotificationNotSupportedError,
|
||||
TaskNotCancelableError,
|
||||
TaskNotFoundError,
|
||||
UnsupportedOperationError,
|
||||
GenericError,
|
||||
} from '../../errors.js';
|
||||
|
||||
import {
|
||||
Message,
|
||||
AgentCard,
|
||||
Task,
|
||||
MessageSendParams,
|
||||
TaskState,
|
||||
TaskStatusUpdateEvent,
|
||||
TaskArtifactUpdateEvent,
|
||||
Role,
|
||||
TaskQueryParams,
|
||||
TaskIdParams,
|
||||
TaskPushNotificationConfig,
|
||||
SendMessageRequest,
|
||||
GetTaskRequest,
|
||||
CancelTaskRequest,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
SubscribeToTaskRequest,
|
||||
ListTasksRequest,
|
||||
ListTasksResponse,
|
||||
} from '../../index.js';
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
GetTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
} from '../../types.js';
|
||||
import { AgentExecutor } from '../agent_execution/agent_executor.js';
|
||||
import { RequestContext } from '../agent_execution/request_context.js';
|
||||
import { A2AError } from '../error.js';
|
||||
import {
|
||||
ExecutionEventBusManager,
|
||||
DefaultExecutionEventBusManager,
|
||||
@ -47,8 +34,8 @@ import {
|
||||
import { PushNotificationSender } from '../push_notification/push_notification_sender.js';
|
||||
import { DefaultPushNotificationSender } from '../push_notification/default_push_notification_sender.js';
|
||||
import { ServerCallContext } from '../context.js';
|
||||
import { DEFAULT_PAGE_SIZE } from '../../constants.js';
|
||||
import { TERMINAL_STATE_LIST } from '../utils.js';
|
||||
|
||||
const terminalStates: TaskState[] = ['completed', 'failed', 'canceled', 'rejected'];
|
||||
|
||||
export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
private readonly agentCard: AgentCard;
|
||||
@ -76,7 +63,7 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
|
||||
// If push notifications are supported, use the provided store and sender.
|
||||
// Otherwise, use the default in-memory store and sender.
|
||||
if (agentCard.capabilities?.pushNotifications) {
|
||||
if (agentCard.capabilities.pushNotifications) {
|
||||
this.pushNotificationStore = pushNotificationStore || new InMemoryPushNotificationStore();
|
||||
this.pushNotificationSender =
|
||||
pushNotificationSender || new DefaultPushNotificationSender(this.pushNotificationStore);
|
||||
@ -88,11 +75,11 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
}
|
||||
|
||||
async getAuthenticatedExtendedAgentCard(context?: ServerCallContext): Promise<AgentCard> {
|
||||
if (!this.agentCard.capabilities?.extendedAgentCard) {
|
||||
throw new UnsupportedOperationError('Agent does not support authenticated extended card.');
|
||||
if (!this.agentCard.supportsAuthenticatedExtendedCard) {
|
||||
throw A2AError.unsupportedOperation('Agent does not support authenticated extended card.');
|
||||
}
|
||||
if (!this.extendedAgentCardProvider) {
|
||||
throw new AuthenticatedExtendedCardNotConfiguredError();
|
||||
throw A2AError.authenticatedExtendedCardNotConfigured();
|
||||
}
|
||||
if (typeof this.extendedAgentCardProvider === 'function') {
|
||||
return this.extendedAgentCardProvider(context);
|
||||
@ -114,12 +101,12 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
if (incomingMessage.taskId) {
|
||||
task = await this.taskStore.load(incomingMessage.taskId, context);
|
||||
if (!task) {
|
||||
throw new TaskNotFoundError(`Task not found: ${incomingMessage.taskId}`);
|
||||
throw A2AError.taskNotFound(incomingMessage.taskId);
|
||||
}
|
||||
if (task.status?.state !== undefined && TERMINAL_STATE_LIST.includes(task.status.state)) {
|
||||
if (terminalStates.includes(task.status.state)) {
|
||||
// Throw an error that conforms to the JSON-RPC Invalid Request error specification.
|
||||
throw new RequestMalformedError(
|
||||
`Task ${task.id} is in a terminal state (${task.status!.state}) and cannot be modified.`
|
||||
throw A2AError.invalidRequest(
|
||||
`Task ${task.id} is in a terminal state (${task.status.state}) and cannot be modified.`
|
||||
);
|
||||
}
|
||||
// Add incomingMessage to history and save the task.
|
||||
@ -128,12 +115,10 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
}
|
||||
// Ensure taskId is present
|
||||
const taskId = incomingMessage.taskId || uuidv4();
|
||||
const referenceTaskIds =
|
||||
(incomingMessage as Message & { referenceTaskIds?: string[] }).referenceTaskIds || [];
|
||||
|
||||
if (referenceTaskIds.length > 0) {
|
||||
if (incomingMessage.referenceTaskIds && incomingMessage.referenceTaskIds.length > 0) {
|
||||
referenceTasks = [];
|
||||
for (const refId of referenceTaskIds) {
|
||||
for (const refId of incomingMessage.referenceTaskIds) {
|
||||
const refTask = await this.taskStore.load(refId, context);
|
||||
if (refTask) {
|
||||
referenceTasks.push(refTask);
|
||||
@ -150,7 +135,7 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
if (context?.requestedExtensions) {
|
||||
const agentCard = await this.getAgentCard();
|
||||
const exposedExtensions = new Set(
|
||||
agentCard.capabilities?.extensions?.map((ext) => ext.uri) || []
|
||||
agentCard.capabilities.extensions?.map((ext) => ext.uri) || []
|
||||
);
|
||||
const validExtensions = context.requestedExtensions.filter((extension) =>
|
||||
exposedExtensions.has(extension)
|
||||
@ -189,15 +174,10 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
|
||||
if (options?.firstResultResolver && !firstResultSent) {
|
||||
let firstResult: Message | Task | undefined;
|
||||
if ('messageId' in event) {
|
||||
if (event.kind === 'message') {
|
||||
firstResult = event;
|
||||
} else if ('artifacts' in event) {
|
||||
firstResult = event as Task;
|
||||
} else {
|
||||
const finalResult = resultManager.getFinalResult();
|
||||
if (finalResult && ('messageId' in finalResult || 'id' in finalResult)) {
|
||||
firstResult = finalResult;
|
||||
}
|
||||
firstResult = resultManager.getCurrentTask();
|
||||
}
|
||||
if (firstResult) {
|
||||
options.firstResultResolver(firstResult);
|
||||
@ -207,7 +187,7 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
}
|
||||
if (options?.firstResultRejector && !firstResultSent) {
|
||||
options.firstResultRejector(
|
||||
new RequestMalformedError('Execution finished before a message or task was produced.')
|
||||
A2AError.internalError('Execution finished before a message or task was produced.')
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
@ -225,16 +205,16 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
context?: ServerCallContext
|
||||
): Promise<Message | Task> {
|
||||
const incomingMessage = params.message;
|
||||
if (!incomingMessage?.messageId) {
|
||||
throw new RequestMalformedError('message.messageId is required.');
|
||||
if (!incomingMessage.messageId) {
|
||||
throw A2AError.invalidParams('message.messageId is required.');
|
||||
}
|
||||
|
||||
// Default to blocking behavior if 'returnImmediately' is not explicitly true.
|
||||
const isBlocking = params.configuration?.returnImmediately !== true;
|
||||
// Default to blocking behavior if 'blocking' is not explicitly false.
|
||||
const isBlocking = params.configuration?.blocking !== false;
|
||||
// Instantiate ResultManager before creating RequestContext
|
||||
const resultManager = new ResultManager(this.taskStore, context);
|
||||
resultManager.setContext(incomingMessage); // Set context for ResultManager
|
||||
@ -247,13 +227,10 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
|
||||
// If push notification config is provided, save it to the store.
|
||||
if (
|
||||
params.configuration?.taskPushNotificationConfig &&
|
||||
this.agentCard.capabilities?.pushNotifications
|
||||
params.configuration?.pushNotificationConfig &&
|
||||
this.agentCard.capabilities.pushNotifications
|
||||
) {
|
||||
await this.pushNotificationStore?.save(
|
||||
taskId,
|
||||
params.configuration.taskPushNotificationConfig
|
||||
);
|
||||
await this.pushNotificationStore?.save(taskId, params.configuration.pushNotificationConfig);
|
||||
}
|
||||
|
||||
const eventBus = this.eventBusManager.createOrGetByTaskId(taskId);
|
||||
@ -270,29 +247,19 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
id: requestContext.task?.id || uuidv4(), // Use existing task ID or generate new
|
||||
contextId: finalMessageForAgent.contextId!,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_FAILED,
|
||||
state: 'failed',
|
||||
message: {
|
||||
role: Role.ROLE_AGENT,
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
taskId: requestContext.taskId,
|
||||
parts: [{ kind: 'text', text: `Agent execution error: ${err.message}` }],
|
||||
taskId: requestContext.task?.id,
|
||||
contextId: finalMessageForAgent.contextId!,
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: `Agent execution error: ${err.message}` },
|
||||
mediaType: 'text/plain',
|
||||
filename: '',
|
||||
metadata: {},
|
||||
},
|
||||
],
|
||||
metadata: {},
|
||||
extensions: [],
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
artifacts: [],
|
||||
history: requestContext.task?.history ? [...requestContext.task.history] : [],
|
||||
metadata: {},
|
||||
kind: 'task',
|
||||
};
|
||||
if (finalMessageForAgent) {
|
||||
// Add incoming message to history
|
||||
@ -302,11 +269,12 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
}
|
||||
eventBus.publish(errorTask);
|
||||
eventBus.publish({
|
||||
// And publish a final status update
|
||||
kind: 'status-update',
|
||||
taskId: errorTask.id,
|
||||
contextId: errorTask.contextId,
|
||||
status: errorTask.status,
|
||||
final: true,
|
||||
metadata: {},
|
||||
} as TaskStatusUpdateEvent);
|
||||
eventBus.finished();
|
||||
});
|
||||
@ -316,7 +284,7 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
await this._processEvents(taskId, resultManager, eventQueue, context);
|
||||
const finalResult = resultManager.getFinalResult();
|
||||
if (!finalResult) {
|
||||
throw new GenericError(
|
||||
throw A2AError.internalError(
|
||||
'Agent execution finished without a result, and no task context found.'
|
||||
);
|
||||
}
|
||||
@ -334,7 +302,7 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
}
|
||||
|
||||
async *sendMessageStream(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
context?: ServerCallContext
|
||||
): AsyncGenerator<
|
||||
Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent,
|
||||
@ -342,10 +310,10 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
undefined
|
||||
> {
|
||||
const incomingMessage = params.message;
|
||||
if (!incomingMessage?.messageId) {
|
||||
if (!incomingMessage.messageId) {
|
||||
// For streams, messageId might be set by client, or server can generate if not present.
|
||||
// Let's assume client provides it or throw for now.
|
||||
throw new RequestMalformedError('message.messageId is required for streaming.');
|
||||
throw A2AError.invalidParams('message.messageId is required for streaming.');
|
||||
}
|
||||
|
||||
// Instantiate ResultManager before creating RequestContext
|
||||
@ -361,13 +329,10 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
|
||||
// If push notification config is provided, save it to the store.
|
||||
if (
|
||||
params.configuration?.taskPushNotificationConfig &&
|
||||
this.agentCard.capabilities?.pushNotifications
|
||||
params.configuration?.pushNotificationConfig &&
|
||||
this.agentCard.capabilities.pushNotifications
|
||||
) {
|
||||
await this.pushNotificationStore?.save(
|
||||
taskId,
|
||||
params.configuration.taskPushNotificationConfig
|
||||
);
|
||||
await this.pushNotificationStore?.save(taskId, params.configuration.pushNotificationConfig);
|
||||
}
|
||||
|
||||
// Start agent execution (non-blocking)
|
||||
@ -378,30 +343,22 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
);
|
||||
// Publish a synthetic error event if needed
|
||||
const errorTaskStatus: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: requestContext.task?.id || uuidv4(), // Use existing or a placeholder
|
||||
contextId: finalMessageForAgent.contextId!,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_FAILED,
|
||||
state: 'failed',
|
||||
message: {
|
||||
role: Role.ROLE_AGENT,
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
taskId: requestContext.taskId,
|
||||
parts: [{ kind: 'text', text: `Agent execution error: ${err.message}` }],
|
||||
taskId: requestContext.task?.id,
|
||||
contextId: finalMessageForAgent.contextId!,
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: `Agent execution error: ${err.message}` },
|
||||
mediaType: 'text/plain',
|
||||
filename: '',
|
||||
metadata: {},
|
||||
},
|
||||
],
|
||||
metadata: {},
|
||||
extensions: [],
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
metadata: {},
|
||||
final: true, // This will terminate the stream for the client
|
||||
};
|
||||
eventBus.publish(errorTaskStatus);
|
||||
});
|
||||
@ -418,11 +375,10 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
}
|
||||
}
|
||||
|
||||
async getTask(params: GetTaskRequest, context?: ServerCallContext): Promise<Task> {
|
||||
const taskId = params.id;
|
||||
const task = await this.taskStore.load(taskId, context);
|
||||
async getTask(params: TaskQueryParams, context?: ServerCallContext): Promise<Task> {
|
||||
const task = await this.taskStore.load(params.id, context);
|
||||
if (!task) {
|
||||
throw new TaskNotFoundError(`Task not found: ${params.id}`);
|
||||
throw A2AError.taskNotFound(params.id);
|
||||
}
|
||||
if (params.historyLength !== undefined && params.historyLength >= 0) {
|
||||
if (task.history) {
|
||||
@ -435,43 +391,26 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
return task;
|
||||
}
|
||||
|
||||
async listTasks(
|
||||
params: ListTasksRequest,
|
||||
context?: ServerCallContext
|
||||
): Promise<ListTasksResponse> {
|
||||
const pageSize = params.pageSize ?? DEFAULT_PAGE_SIZE;
|
||||
|
||||
if (pageSize < 1 || pageSize > 100) {
|
||||
throw new RequestMalformedError('pageSize must be between 1 and 100');
|
||||
}
|
||||
|
||||
if (params.statusTimestampAfter && isNaN(Date.parse(params.statusTimestampAfter))) {
|
||||
throw new RequestMalformedError('statusTimestampAfter must be a valid ISO 8601 date string');
|
||||
}
|
||||
|
||||
return this.taskStore.list({ ...params, pageSize }, context);
|
||||
}
|
||||
|
||||
async cancelTask(params: CancelTaskRequest, context?: ServerCallContext): Promise<Task> {
|
||||
const taskId = params.id;
|
||||
const task = await this.taskStore.load(taskId, context);
|
||||
async cancelTask(params: TaskIdParams, context?: ServerCallContext): Promise<Task> {
|
||||
const task = await this.taskStore.load(params.id, context);
|
||||
if (!task) {
|
||||
throw new TaskNotFoundError(`Task not found: ${params.id}`);
|
||||
throw A2AError.taskNotFound(params.id);
|
||||
}
|
||||
|
||||
// Check if task is in a cancelable state
|
||||
if (TERMINAL_STATE_LIST.includes(task.status!.state)) {
|
||||
throw new TaskNotCancelableError(`Task not cancelable: ${params.id}`);
|
||||
const nonCancelableStates = ['completed', 'failed', 'canceled', 'rejected'];
|
||||
if (nonCancelableStates.includes(task.status.state)) {
|
||||
throw A2AError.taskNotCancelable(params.id);
|
||||
}
|
||||
|
||||
const eventBus = this.eventBusManager.getByTaskId(taskId);
|
||||
const eventBus = this.eventBusManager.getByTaskId(params.id);
|
||||
|
||||
if (eventBus) {
|
||||
const eventQueue = new ExecutionEventQueue(eventBus);
|
||||
await this.agentExecutor.cancelTask(taskId, eventBus);
|
||||
await this.agentExecutor.cancelTask(params.id, eventBus);
|
||||
// Consume all the events until the task reaches a terminal state.
|
||||
await this._processEvents(
|
||||
taskId,
|
||||
params.id,
|
||||
new ResultManager(this.taskStore, context),
|
||||
eventQueue,
|
||||
context
|
||||
@ -479,123 +418,132 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
} else {
|
||||
// Here we are marking task as cancelled. We are not waiting for the executor to actually cancel processing.
|
||||
task.status = {
|
||||
state: TaskState.TASK_STATE_CANCELED,
|
||||
state: 'canceled',
|
||||
message: {
|
||||
role: Role.ROLE_AGENT,
|
||||
// Optional: Add a system message indicating cancellation
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [{ kind: 'text', text: 'Task cancellation requested by user.' }],
|
||||
taskId: task.id,
|
||||
contextId: task.contextId,
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: 'Task cancellation requested by user.' },
|
||||
mediaType: 'text/plain',
|
||||
filename: '',
|
||||
metadata: {},
|
||||
},
|
||||
],
|
||||
metadata: {},
|
||||
extensions: [],
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
// Add cancellation message to history
|
||||
if (task.status?.message) {
|
||||
task.history = [...(task.history || []), task.status.message];
|
||||
}
|
||||
task.history = [...(task.history || []), task.status.message];
|
||||
|
||||
await this.taskStore.save(task, context);
|
||||
}
|
||||
|
||||
const latestTask = await this.taskStore.load(taskId, context);
|
||||
const latestTask = await this.taskStore.load(params.id, context);
|
||||
if (!latestTask) {
|
||||
throw new GenericError(`Task ${params.id} not found after cancellation.`);
|
||||
throw A2AError.internalError(`Task ${params.id} not found after cancellation.`);
|
||||
}
|
||||
if (latestTask.status!.state != TaskState.TASK_STATE_CANCELED) {
|
||||
throw new TaskNotCancelableError(`Task not cancelable: ${params.id}`);
|
||||
if (latestTask.status.state != 'canceled') {
|
||||
throw A2AError.taskNotCancelable(params.id);
|
||||
}
|
||||
return latestTask;
|
||||
}
|
||||
|
||||
async createTaskPushNotificationConfig(
|
||||
async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
context?: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
if (!this.agentCard.capabilities?.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw A2AError.pushNotificationNotSupported();
|
||||
}
|
||||
const taskId = params.taskId;
|
||||
const task = await this.taskStore.load(taskId, context);
|
||||
const task = await this.taskStore.load(params.taskId, context);
|
||||
if (!task) {
|
||||
throw new TaskNotFoundError(`Task not found: ${taskId}`);
|
||||
throw A2AError.taskNotFound(params.taskId);
|
||||
}
|
||||
|
||||
await this.pushNotificationStore?.save(taskId, params);
|
||||
const { taskId, pushNotificationConfig } = params;
|
||||
|
||||
// Default the config ID to the task ID if not provided for backward compatibility.
|
||||
if (!pushNotificationConfig.id) {
|
||||
pushNotificationConfig.id = taskId;
|
||||
}
|
||||
|
||||
await this.pushNotificationStore?.save(taskId, pushNotificationConfig);
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
async getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigRequest,
|
||||
params: TaskIdParams | GetTaskPushNotificationConfigParams,
|
||||
context?: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
if (!this.agentCard.capabilities?.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw A2AError.pushNotificationNotSupported();
|
||||
}
|
||||
const taskId = params.taskId;
|
||||
const task = await this.taskStore.load(taskId, context);
|
||||
const task = await this.taskStore.load(params.id, context);
|
||||
if (!task) {
|
||||
throw new TaskNotFoundError(`Task not found: ${taskId}`);
|
||||
throw A2AError.taskNotFound(params.id);
|
||||
}
|
||||
|
||||
const configs = (await this.pushNotificationStore?.load(taskId)) || [];
|
||||
const configs = (await this.pushNotificationStore?.load(params.id)) || [];
|
||||
if (configs.length === 0) {
|
||||
throw new GenericError(`Push notification config not found for task ${taskId}.`);
|
||||
throw A2AError.internalError(`Push notification config not found for task ${params.id}.`);
|
||||
}
|
||||
|
||||
const config = configs.find((c) => c.id === params.id);
|
||||
let configId: string;
|
||||
if ('pushNotificationConfigId' in params && params.pushNotificationConfigId) {
|
||||
configId = params.pushNotificationConfigId;
|
||||
} else {
|
||||
// For backward compatibility, if no config ID is given, assume it's the task ID.
|
||||
configId = params.id;
|
||||
}
|
||||
|
||||
const config = configs.find((c) => c.id === configId);
|
||||
|
||||
if (!config) {
|
||||
throw new GenericError(
|
||||
`Push notification config with id '${params.id}' not found for task ${taskId}.`
|
||||
throw A2AError.internalError(
|
||||
`Push notification config with id '${configId}' not found for task ${params.id}.`
|
||||
);
|
||||
}
|
||||
return config;
|
||||
return { taskId: params.id, pushNotificationConfig: config };
|
||||
}
|
||||
|
||||
async listTaskPushNotificationConfigs(
|
||||
params: ListTaskPushNotificationConfigsRequest,
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
context?: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
if (!this.agentCard.capabilities?.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw A2AError.pushNotificationNotSupported();
|
||||
}
|
||||
const taskId = params.taskId;
|
||||
const task = await this.taskStore.load(taskId, context);
|
||||
const task = await this.taskStore.load(params.id, context);
|
||||
if (!task) {
|
||||
throw new TaskNotFoundError(`Task not found: ${taskId}`);
|
||||
throw A2AError.taskNotFound(params.id);
|
||||
}
|
||||
|
||||
return (await this.pushNotificationStore?.load(taskId)) || [];
|
||||
const configs = (await this.pushNotificationStore?.load(params.id)) || [];
|
||||
|
||||
return configs.map((config) => ({
|
||||
taskId: params.id,
|
||||
pushNotificationConfig: config,
|
||||
}));
|
||||
}
|
||||
|
||||
async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigRequest,
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
context?: ServerCallContext
|
||||
): Promise<void> {
|
||||
if (!this.agentCard.capabilities?.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw A2AError.pushNotificationNotSupported();
|
||||
}
|
||||
const taskId = params.taskId;
|
||||
const task = await this.taskStore.load(taskId, context);
|
||||
const task = await this.taskStore.load(params.id, context);
|
||||
if (!task) {
|
||||
throw new TaskNotFoundError(`Task not found: ${taskId}`);
|
||||
throw A2AError.taskNotFound(params.id);
|
||||
}
|
||||
await this.pushNotificationStore?.delete(taskId, params.id);
|
||||
|
||||
const { id: taskId, pushNotificationConfigId } = params;
|
||||
|
||||
await this.pushNotificationStore?.delete(taskId, pushNotificationConfigId);
|
||||
}
|
||||
|
||||
async *resubscribe(
|
||||
params: SubscribeToTaskRequest,
|
||||
params: TaskIdParams,
|
||||
context?: ServerCallContext
|
||||
): AsyncGenerator<
|
||||
| Task // Initial task state
|
||||
@ -604,28 +552,28 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
void,
|
||||
undefined
|
||||
> {
|
||||
if (!this.agentCard.capabilities?.streaming) {
|
||||
throw new UnsupportedOperationError('Streaming (and thus resubscription) is not supported.');
|
||||
if (!this.agentCard.capabilities.streaming) {
|
||||
throw A2AError.unsupportedOperation('Streaming (and thus resubscription) is not supported.');
|
||||
}
|
||||
|
||||
const taskId = params.id;
|
||||
const task = await this.taskStore.load(taskId, context);
|
||||
const task = await this.taskStore.load(params.id, context);
|
||||
if (!task) {
|
||||
throw new TaskNotFoundError(`Task not found: ${taskId}`);
|
||||
throw A2AError.taskNotFound(params.id);
|
||||
}
|
||||
|
||||
// Yield the current task state first
|
||||
yield task;
|
||||
|
||||
// If task is already in a final state, no more events will come.
|
||||
if (TERMINAL_STATE_LIST.includes(task.status!.state)) {
|
||||
const finalStates = ['completed', 'failed', 'canceled', 'rejected'];
|
||||
if (finalStates.includes(task.status.state)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const eventBus = this.eventBusManager.getByTaskId(taskId);
|
||||
const eventBus = this.eventBusManager.getByTaskId(params.id);
|
||||
if (!eventBus) {
|
||||
// No active execution for this task, so no live events.
|
||||
console.warn(`Resubscribe: No active event bus for task ${taskId}.`);
|
||||
console.warn(`Resubscribe: No active event bus for task ${params.id}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -639,11 +587,11 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
// We only care about updates related to *this* task.
|
||||
// The event bus might be shared if messageId was reused, though
|
||||
// ExecutionEventBusManager tries to give one bus per original message.
|
||||
if ('status' in event && 'taskId' in event && event.taskId === taskId) {
|
||||
if (event.kind === 'status-update' && event.taskId === params.id) {
|
||||
yield event as TaskStatusUpdateEvent;
|
||||
} else if ('artifact' in event && event.taskId === taskId) {
|
||||
} else if (event.kind === 'artifact-update' && event.taskId === params.id) {
|
||||
yield event as TaskArtifactUpdateEvent;
|
||||
} else if ('artifacts' in event && (event as Task).id === taskId) {
|
||||
} else if (event.kind === 'task' && event.id === params.id) {
|
||||
// This implies the task was re-emitted, yield it.
|
||||
yield event as Task;
|
||||
}
|
||||
@ -660,12 +608,12 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
event: AgentExecutionEvent,
|
||||
context: ServerCallContext | undefined
|
||||
): Promise<void> {
|
||||
if (!this.agentCard.capabilities?.pushNotifications) {
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
return;
|
||||
}
|
||||
|
||||
let taskId: string = '';
|
||||
if ('artifacts' in event) {
|
||||
if (event.kind == 'task') {
|
||||
const task = event as Task;
|
||||
taskId = task.id;
|
||||
} else {
|
||||
@ -673,7 +621,7 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
}
|
||||
|
||||
if (!taskId) {
|
||||
console.error(`Task ID not found for event.`);
|
||||
console.error(`Task ID not found for event ${event.kind}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -713,27 +661,19 @@ export class DefaultRequestHandler implements A2ARequestHandler {
|
||||
taskId: currentTask.id,
|
||||
contextId: currentTask.contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_FAILED,
|
||||
state: 'failed',
|
||||
message: {
|
||||
role: Role.ROLE_AGENT,
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [{ kind: 'text', text: `Event processing loop failed: ${errorMessage}` }],
|
||||
taskId: currentTask.id,
|
||||
contextId: currentTask.contextId,
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: `Event processing loop failed: ${errorMessage}` },
|
||||
mediaType: 'text/plain',
|
||||
filename: '',
|
||||
metadata: {},
|
||||
},
|
||||
],
|
||||
metadata: {},
|
||||
extensions: [],
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
final: true,
|
||||
};
|
||||
|
||||
try {
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Message, Task, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '../index.js';
|
||||
import { Message, Task, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '../types.js';
|
||||
import { ServerCallContext } from './context.js';
|
||||
import { AgentExecutionEvent } from './events/execution_event_bus.js';
|
||||
import { TaskStore } from './store.js';
|
||||
@ -25,12 +25,12 @@ export class ResultManager {
|
||||
* @param event The agent execution event.
|
||||
*/
|
||||
public async processEvent(event: AgentExecutionEvent): Promise<void> {
|
||||
if ('messageId' in event) {
|
||||
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 ('id' in event) {
|
||||
} else if (event.kind === 'task') {
|
||||
const taskEvent = event as Task;
|
||||
this.currentTask = { ...taskEvent }; // Make a copy
|
||||
|
||||
@ -38,22 +38,28 @@ export class ResultManager {
|
||||
if (this.latestUserMessage) {
|
||||
if (
|
||||
!this.currentTask.history?.find(
|
||||
(msg) => msg.messageId === this.latestUserMessage?.messageId
|
||||
(msg) => msg.messageId === this.latestUserMessage!.messageId
|
||||
)
|
||||
) {
|
||||
this.currentTask.history = [this.latestUserMessage, ...(this.currentTask.history || [])];
|
||||
}
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else if ('status' in event && 'taskId' in event) {
|
||||
} else if (event.kind === 'status-update') {
|
||||
const updateEvent = event as TaskStatusUpdateEvent;
|
||||
if (this.currentTask && this.currentTask.id === updateEvent.taskId) {
|
||||
this.currentTask.status = updateEvent.status;
|
||||
const update = updateEvent.status?.message;
|
||||
if (update) {
|
||||
if (updateEvent.status.message) {
|
||||
// Add message to history if not already present
|
||||
if (!this.currentTask.history?.find((msg) => msg.messageId === update.messageId)) {
|
||||
this.currentTask.history = [...(this.currentTask.history || []), update];
|
||||
if (
|
||||
!this.currentTask.history?.find(
|
||||
(msg) => msg.messageId === updateEvent.status.message!.messageId
|
||||
)
|
||||
) {
|
||||
this.currentTask.history = [
|
||||
...(this.currentTask.history || []),
|
||||
updateEvent.status.message,
|
||||
];
|
||||
}
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
@ -64,10 +70,16 @@ export class ResultManager {
|
||||
if (loaded) {
|
||||
this.currentTask = loaded;
|
||||
this.currentTask.status = updateEvent.status;
|
||||
const update = updateEvent.status?.message;
|
||||
if (update) {
|
||||
if (!this.currentTask.history?.find((msg) => msg.messageId === update.messageId)) {
|
||||
this.currentTask.history = [...(this.currentTask.history || []), update];
|
||||
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();
|
||||
@ -79,37 +91,37 @@ export class ResultManager {
|
||||
}
|
||||
// If it's a final status update, the ExecutionEventQueue will stop.
|
||||
// The final result will be the currentTask.
|
||||
} else if ('artifact' in event) {
|
||||
} else if (event.kind === 'artifact-update') {
|
||||
const artifactEvent = event as TaskArtifactUpdateEvent;
|
||||
const artifact = artifactEvent.artifact;
|
||||
if (this.currentTask && this.currentTask.id === artifactEvent.taskId && artifact) {
|
||||
if (this.currentTask && this.currentTask.id === artifactEvent.taskId) {
|
||||
if (!this.currentTask.artifacts) {
|
||||
this.currentTask.artifacts = [];
|
||||
}
|
||||
const existingArtifactIndex = this.currentTask.artifacts.findIndex(
|
||||
(art) => art.artifactId === artifact.artifactId
|
||||
(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(...(artifact.parts || []));
|
||||
if (artifact.description) existingArtifact.description = artifact.description;
|
||||
if (artifact.name) existingArtifact.name = artifact.name;
|
||||
if (artifact.metadata)
|
||||
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,
|
||||
...artifact.metadata,
|
||||
...artifactEvent.artifact.metadata,
|
||||
};
|
||||
} else {
|
||||
this.currentTask.artifacts[existingArtifactIndex] = artifact;
|
||||
this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
|
||||
}
|
||||
} else {
|
||||
this.currentTask.artifacts.push(artifact);
|
||||
this.currentTask.artifacts.push(artifactEvent.artifact);
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else if (!this.currentTask && artifactEvent.taskId && artifact) {
|
||||
} 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) {
|
||||
@ -117,18 +129,18 @@ export class ResultManager {
|
||||
if (!this.currentTask.artifacts) this.currentTask.artifacts = [];
|
||||
// Apply artifact update logic (as above)
|
||||
const existingArtifactIndex = this.currentTask.artifacts.findIndex(
|
||||
(art) => art.artifactId === artifact.artifactId
|
||||
(art) => art.artifactId === artifactEvent.artifact.artifactId
|
||||
);
|
||||
if (existingArtifactIndex !== -1) {
|
||||
if (artifactEvent.append) {
|
||||
this.currentTask.artifacts[existingArtifactIndex].parts.push(
|
||||
...(artifact.parts || [])
|
||||
...artifactEvent.artifact.parts
|
||||
);
|
||||
} else {
|
||||
this.currentTask.artifacts[existingArtifactIndex] = artifact;
|
||||
this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
|
||||
}
|
||||
} else {
|
||||
this.currentTask.artifacts.push(artifact);
|
||||
this.currentTask.artifacts.push(artifactEvent.artifact);
|
||||
}
|
||||
await this.saveCurrentTask();
|
||||
} else {
|
||||
|
||||
@ -1,7 +1,5 @@
|
||||
import { Task, ListTasksRequest, ListTasksResponse } from '../index.js';
|
||||
import { Task } from '../types.js';
|
||||
import { ServerCallContext } from './context.js';
|
||||
import { DEFAULT_PAGE_SIZE } from '../constants.js';
|
||||
import { RequestMalformedError } from '../errors.js';
|
||||
|
||||
/**
|
||||
* Simplified interface for task storage providers.
|
||||
@ -24,13 +22,6 @@ export interface TaskStore {
|
||||
* @returns A promise resolving to an object containing the Task, or undefined if not found.
|
||||
*/
|
||||
load(taskId: string, context?: ServerCallContext): Promise<Task | undefined>;
|
||||
|
||||
/**
|
||||
* Lists tasks with filtering and pagination.
|
||||
* @param params Filtering and pagination parameters.
|
||||
* @param context The context of the current call.
|
||||
*/
|
||||
list(params: ListTasksRequest, context?: ServerCallContext): Promise<ListTasksResponse>;
|
||||
}
|
||||
|
||||
// ========================
|
||||
@ -51,104 +42,4 @@ export class InMemoryTaskStore implements TaskStore {
|
||||
// Store copies to prevent internal mutation if caller reuses objects
|
||||
this.store.set(task.id, { ...task });
|
||||
}
|
||||
|
||||
async list(params: ListTasksRequest): Promise<ListTasksResponse> {
|
||||
const {
|
||||
contextId,
|
||||
status,
|
||||
pageSize = DEFAULT_PAGE_SIZE,
|
||||
pageToken,
|
||||
historyLength = 0,
|
||||
statusTimestampAfter,
|
||||
includeArtifacts = false,
|
||||
} = params;
|
||||
|
||||
let tasks = Array.from(this.store.values());
|
||||
|
||||
// Filter by contextId
|
||||
if (contextId) {
|
||||
tasks = tasks.filter((task) => task.contextId === contextId);
|
||||
}
|
||||
|
||||
// Filter by status
|
||||
if (status !== undefined) {
|
||||
tasks = tasks.filter((task) => task.status?.state === status);
|
||||
}
|
||||
|
||||
// Filter by timestamp after
|
||||
if (statusTimestampAfter) {
|
||||
const filterTime = new Date(statusTimestampAfter).getTime();
|
||||
tasks = tasks.filter(
|
||||
(task) => task.status?.timestamp && new Date(task.status.timestamp).getTime() > filterTime
|
||||
);
|
||||
}
|
||||
|
||||
// Sort by timestamp descending
|
||||
tasks.sort((taskA, taskB) => {
|
||||
const timeA = taskA.status?.timestamp || '';
|
||||
const timeB = taskB.status?.timestamp || '';
|
||||
if (timeB !== timeA) {
|
||||
return timeB.localeCompare(timeA);
|
||||
}
|
||||
return taskB.id.localeCompare(taskA.id);
|
||||
});
|
||||
|
||||
const totalSize = tasks.length;
|
||||
|
||||
// Pagination cursor
|
||||
if (pageToken) {
|
||||
try {
|
||||
const decoded = Buffer.from(pageToken, 'base64').toString('utf-8');
|
||||
const [cursorTimestamp, ...idParts] = decoded.split('|');
|
||||
if (idParts.length === 0) {
|
||||
throw new RequestMalformedError('Invalid page token format.');
|
||||
}
|
||||
const cursorId = idParts.join('|');
|
||||
|
||||
const cursorIndex = tasks.findIndex(
|
||||
(task) => (task.status?.timestamp || '') === cursorTimestamp && task.id === cursorId
|
||||
);
|
||||
|
||||
if (cursorIndex !== -1) {
|
||||
tasks = tasks.slice(cursorIndex + 1);
|
||||
} else {
|
||||
// This case can happen if the cursor task was deleted.
|
||||
tasks = [];
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof RequestMalformedError) throw e;
|
||||
throw new RequestMalformedError('Token is not a valid base64-encoded cursor.');
|
||||
}
|
||||
}
|
||||
|
||||
const paginatedTasks = tasks.slice(0, pageSize);
|
||||
|
||||
// Map tasks to response format
|
||||
const resultTasks = paginatedTasks.map((task) => {
|
||||
const taskCopy = JSON.parse(JSON.stringify(task));
|
||||
if (!includeArtifacts) {
|
||||
taskCopy.artifacts = [];
|
||||
}
|
||||
if (historyLength > 0 && taskCopy.history) {
|
||||
taskCopy.history = taskCopy.history.slice(-historyLength);
|
||||
} else {
|
||||
taskCopy.history = [];
|
||||
}
|
||||
return taskCopy;
|
||||
});
|
||||
|
||||
let nextPageToken = '';
|
||||
if (paginatedTasks.length > 0 && tasks.length > paginatedTasks.length) {
|
||||
const lastTask = paginatedTasks[paginatedTasks.length - 1];
|
||||
const lastTime = lastTask.status?.timestamp || '';
|
||||
nextPageToken = Buffer.from(`${lastTime}|${lastTask.id}`).toString('base64');
|
||||
}
|
||||
|
||||
return {
|
||||
tasks: resultTasks,
|
||||
nextPageToken,
|
||||
pageSize,
|
||||
totalSize,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,47 +1,12 @@
|
||||
import {
|
||||
StreamResponse,
|
||||
Message,
|
||||
Task,
|
||||
TaskStatusUpdateEvent,
|
||||
TaskArtifactUpdateEvent,
|
||||
SendMessageRequest,
|
||||
SubscribeToTaskRequest,
|
||||
GetTaskRequest,
|
||||
CancelTaskRequest,
|
||||
TaskPushNotificationConfig,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
ListTasksRequest,
|
||||
} from '../../../index.js';
|
||||
import {
|
||||
A2A_ERROR_CODE,
|
||||
RequestMalformedError,
|
||||
TaskNotFoundError,
|
||||
TaskNotCancelableError,
|
||||
PushNotificationNotSupportedError,
|
||||
UnsupportedOperationError,
|
||||
ContentTypeNotSupportedError,
|
||||
InvalidAgentResponseError,
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
GenericError,
|
||||
} from '../../../errors.js';
|
||||
import { JSONRPCErrorResponse } from '../../../core.js';
|
||||
|
||||
export type A2ARequest = {
|
||||
jsonrpc: '2.0';
|
||||
method: string;
|
||||
params?: unknown;
|
||||
id?: string | number | null;
|
||||
};
|
||||
|
||||
export type JSONRPCResponse = {
|
||||
jsonrpc: string;
|
||||
id: string | number | null;
|
||||
result?: unknown;
|
||||
error?: unknown;
|
||||
};
|
||||
JSONRPCErrorResponse,
|
||||
MessageSendParams,
|
||||
TaskIdParams,
|
||||
A2ARequest,
|
||||
JSONRPCResponse,
|
||||
} from '../../../types.js';
|
||||
import { ServerCallContext } from '../../context.js';
|
||||
import { A2AError } from '../../error.js';
|
||||
import { A2ARequestHandler } from '../../request_handler/a2a_request_handler.js';
|
||||
|
||||
/**
|
||||
@ -73,41 +38,45 @@ export class JsonRpcTransportHandler {
|
||||
} else if (typeof requestBody === 'object' && requestBody !== null) {
|
||||
rpcRequest = requestBody as A2ARequest;
|
||||
} else {
|
||||
throw new RequestMalformedError('Invalid request body type.');
|
||||
throw A2AError.parseError('Invalid request body type.');
|
||||
}
|
||||
|
||||
if (!this.isRequestValid(rpcRequest)) {
|
||||
throw new RequestMalformedError('Invalid JSON-RPC Request.');
|
||||
throw A2AError.invalidRequest('Invalid JSON-RPC Request.');
|
||||
}
|
||||
} catch (error) {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
error instanceof SyntaxError
|
||||
? new RequestMalformedError(error.message || 'Failed to parse JSON request.')
|
||||
: error
|
||||
);
|
||||
const a2aError =
|
||||
error instanceof A2AError
|
||||
? error
|
||||
: A2AError.parseError(
|
||||
(error instanceof SyntaxError && error.message) || 'Failed to parse JSON request.'
|
||||
);
|
||||
return {
|
||||
jsonrpc: '2.0',
|
||||
id: rpcRequest?.id !== undefined ? rpcRequest.id : null,
|
||||
error: mappedError,
|
||||
error: a2aError.toJSONRPCError(),
|
||||
} as JSONRPCErrorResponse;
|
||||
}
|
||||
|
||||
const { method, id: requestId = null } = rpcRequest;
|
||||
try {
|
||||
if (method !== 'GetExtendedAgentCard' && !this.paramsAreValid(rpcRequest.params)) {
|
||||
throw new RequestMalformedError(`Invalid method parameters.`);
|
||||
if (
|
||||
method !== 'agent/getAuthenticatedExtendedCard' &&
|
||||
!this.paramsAreValid(rpcRequest.params)
|
||||
) {
|
||||
throw A2AError.invalidParams(`Invalid method parameters.`);
|
||||
}
|
||||
|
||||
if (method === 'SendStreamingMessage' || method === 'SubscribeToTask') {
|
||||
if (method === 'message/stream' || method === 'tasks/resubscribe') {
|
||||
const params = rpcRequest.params;
|
||||
const agentCard = await this.requestHandler.getAgentCard();
|
||||
if (!agentCard.capabilities?.streaming) {
|
||||
throw new UnsupportedOperationError(`Method ${method} requires streaming capability.`);
|
||||
if (!agentCard.capabilities.streaming) {
|
||||
throw A2AError.unsupportedOperation(`Method ${method} requires streaming capability.`);
|
||||
}
|
||||
const agentEventStream =
|
||||
method === 'SendStreamingMessage'
|
||||
? this.requestHandler.sendMessageStream(SendMessageRequest.fromJSON(params), context)
|
||||
: this.requestHandler.resubscribe(SubscribeToTaskRequest.fromJSON(params), context);
|
||||
method === 'message/stream'
|
||||
? this.requestHandler.sendMessageStream(params as MessageSendParams, context)
|
||||
: this.requestHandler.resubscribe(params as TaskIdParams, context);
|
||||
|
||||
// Wrap the agent event stream into a JSON-RPC result stream
|
||||
return (async function* jsonRpcEventStream(): AsyncGenerator<
|
||||
@ -117,22 +86,10 @@ export class JsonRpcTransportHandler {
|
||||
> {
|
||||
try {
|
||||
for await (const event of agentEventStream) {
|
||||
let payload: StreamResponse['payload'];
|
||||
|
||||
if ('messageId' in event) {
|
||||
payload = { $case: 'message', value: event as Message };
|
||||
} else if ('artifacts' in event) {
|
||||
payload = { $case: 'task', value: event as Task };
|
||||
} else if ('status' in event) {
|
||||
payload = { $case: 'statusUpdate', value: event as TaskStatusUpdateEvent };
|
||||
} else if ('artifact' in event) {
|
||||
payload = { $case: 'artifactUpdate', value: event as TaskArtifactUpdateEvent };
|
||||
}
|
||||
|
||||
yield {
|
||||
jsonrpc: '2.0',
|
||||
id: requestId, // Use the original request ID for all streamed responses
|
||||
result: { payload },
|
||||
result: event,
|
||||
};
|
||||
}
|
||||
} catch (streamError) {
|
||||
@ -146,7 +103,7 @@ export class JsonRpcTransportHandler {
|
||||
);
|
||||
// Ideally, the Express layer should catch this and send a final error to the client if the stream breaks.
|
||||
// Or, the agentEventStream itself should yield a final error event that gets wrapped.
|
||||
// For now, we re-throw so it can be caught by the Express layer streaming support.
|
||||
// For now, we re-throw so it can be caught by A2AExpressApp's stream handling.
|
||||
throw streamError;
|
||||
}
|
||||
})();
|
||||
@ -154,72 +111,42 @@ export class JsonRpcTransportHandler {
|
||||
// Handle non-streaming methods
|
||||
let result: unknown;
|
||||
switch (method) {
|
||||
case 'SendMessage': {
|
||||
const messageOrTask = await this.requestHandler.sendMessage(
|
||||
SendMessageRequest.fromJSON(rpcRequest.params),
|
||||
context
|
||||
);
|
||||
result = {
|
||||
payload: {
|
||||
$case: 'messageId' in messageOrTask ? 'message' : 'task',
|
||||
value: messageOrTask,
|
||||
},
|
||||
};
|
||||
case 'message/send':
|
||||
result = await this.requestHandler.sendMessage(rpcRequest.params, context);
|
||||
break;
|
||||
}
|
||||
case 'GetTask':
|
||||
result = await this.requestHandler.getTask(
|
||||
GetTaskRequest.fromJSON(rpcRequest.params),
|
||||
case 'tasks/get':
|
||||
result = await this.requestHandler.getTask(rpcRequest.params, context);
|
||||
break;
|
||||
case 'tasks/cancel':
|
||||
result = await this.requestHandler.cancelTask(rpcRequest.params, context);
|
||||
break;
|
||||
case 'tasks/pushNotificationConfig/set':
|
||||
result = await this.requestHandler.setTaskPushNotificationConfig(
|
||||
rpcRequest.params,
|
||||
context
|
||||
);
|
||||
break;
|
||||
case 'ListTasks':
|
||||
result = await this.requestHandler.listTasks(
|
||||
ListTasksRequest.fromJSON(rpcRequest.params),
|
||||
context
|
||||
);
|
||||
break;
|
||||
case 'CancelTask':
|
||||
result = await this.requestHandler.cancelTask(
|
||||
CancelTaskRequest.fromJSON(rpcRequest.params),
|
||||
context
|
||||
);
|
||||
break;
|
||||
case 'CreateTaskPushNotificationConfig': {
|
||||
result = await this.requestHandler.createTaskPushNotificationConfig(
|
||||
TaskPushNotificationConfig.fromJSON(rpcRequest.params),
|
||||
context
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'GetTaskPushNotificationConfig':
|
||||
case 'tasks/pushNotificationConfig/get':
|
||||
result = await this.requestHandler.getTaskPushNotificationConfig(
|
||||
GetTaskPushNotificationConfigRequest.fromJSON(rpcRequest.params),
|
||||
rpcRequest.params,
|
||||
context
|
||||
);
|
||||
break;
|
||||
case 'DeleteTaskPushNotificationConfig':
|
||||
await this.requestHandler.deleteTaskPushNotificationConfig(
|
||||
DeleteTaskPushNotificationConfigRequest.fromJSON(rpcRequest.params),
|
||||
context
|
||||
);
|
||||
case 'tasks/pushNotificationConfig/delete':
|
||||
await this.requestHandler.deleteTaskPushNotificationConfig(rpcRequest.params, context);
|
||||
result = null;
|
||||
break;
|
||||
case 'ListTaskPushNotificationConfigs':
|
||||
case 'tasks/pushNotificationConfig/list':
|
||||
result = await this.requestHandler.listTaskPushNotificationConfigs(
|
||||
ListTaskPushNotificationConfigsRequest.fromJSON(rpcRequest.params),
|
||||
rpcRequest.params,
|
||||
context
|
||||
);
|
||||
break;
|
||||
case 'GetExtendedAgentCard':
|
||||
case 'agent/getAuthenticatedExtendedCard':
|
||||
result = await this.requestHandler.getAuthenticatedExtendedAgentCard(context);
|
||||
break;
|
||||
default:
|
||||
return {
|
||||
jsonrpc: '2.0',
|
||||
id: requestId,
|
||||
error: { code: A2A_ERROR_CODE.METHOD_NOT_FOUND, message: 'Invalid method.' },
|
||||
};
|
||||
throw A2AError.methodNotFound(method);
|
||||
}
|
||||
return {
|
||||
jsonrpc: '2.0',
|
||||
@ -228,10 +155,18 @@ export class JsonRpcTransportHandler {
|
||||
} as JSONRPCResponse;
|
||||
}
|
||||
} catch (error) {
|
||||
let a2aError: A2AError;
|
||||
if (error instanceof A2AError) {
|
||||
a2aError = error;
|
||||
} else {
|
||||
a2aError = A2AError.internalError(
|
||||
(error instanceof Error && error.message) || 'An unexpected error occurred.'
|
||||
);
|
||||
}
|
||||
return {
|
||||
jsonrpc: '2.0',
|
||||
id: requestId,
|
||||
error: JsonRpcTransportHandler.mapToJSONRPCError(error),
|
||||
error: a2aError.toJSONRPCError(),
|
||||
} as JSONRPCErrorResponse;
|
||||
}
|
||||
}
|
||||
@ -271,40 +206,4 @@ export class JsonRpcTransportHandler {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static mapToJSONRPCError(error: unknown) {
|
||||
if (error instanceof TaskNotFoundError) {
|
||||
return { code: A2A_ERROR_CODE.TASK_NOT_FOUND, message: error.message };
|
||||
}
|
||||
if (error instanceof TaskNotCancelableError) {
|
||||
return { code: A2A_ERROR_CODE.TASK_NOT_CANCELABLE, message: error.message };
|
||||
}
|
||||
if (error instanceof PushNotificationNotSupportedError) {
|
||||
return { code: A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED, message: error.message };
|
||||
}
|
||||
if (error instanceof UnsupportedOperationError) {
|
||||
return { code: A2A_ERROR_CODE.UNSUPPORTED_OPERATION, message: error.message };
|
||||
}
|
||||
if (error instanceof ContentTypeNotSupportedError) {
|
||||
return { code: A2A_ERROR_CODE.CONTENT_TYPE_NOT_SUPPORTED, message: error.message };
|
||||
}
|
||||
if (error instanceof InvalidAgentResponseError) {
|
||||
return { code: A2A_ERROR_CODE.INVALID_AGENT_RESPONSE, message: error.message };
|
||||
}
|
||||
if (error instanceof AuthenticatedExtendedCardNotConfiguredError) {
|
||||
return {
|
||||
code: A2A_ERROR_CODE.AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
if (error instanceof RequestMalformedError) {
|
||||
return { code: A2A_ERROR_CODE.INVALID_PARAMS, message: error.message };
|
||||
}
|
||||
if (error instanceof GenericError) {
|
||||
return { code: A2A_ERROR_CODE.INTERNAL_ERROR, message: error.message };
|
||||
}
|
||||
|
||||
const message = (error instanceof Error && error.message) || 'An unexpected error occurred.';
|
||||
return { code: A2A_ERROR_CODE.INTERNAL_ERROR, message };
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
* Returns camelCase (internal types).
|
||||
*/
|
||||
|
||||
import { A2AError } from '../../error.js';
|
||||
import { A2ARequestHandler } from '../../request_handler/a2a_request_handler.js';
|
||||
import { ServerCallContext } from '../../context.js';
|
||||
import {
|
||||
@ -12,23 +13,13 @@ import {
|
||||
Task,
|
||||
TaskStatusUpdateEvent,
|
||||
TaskArtifactUpdateEvent,
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
TaskQueryParams,
|
||||
TaskIdParams,
|
||||
AgentCard,
|
||||
SendMessageRequest,
|
||||
GetTaskRequest,
|
||||
CancelTaskRequest,
|
||||
ListTasksRequest,
|
||||
ListTasksResponse,
|
||||
TaskState,
|
||||
} from '../../../index.js';
|
||||
import {
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
PushNotificationNotSupportedError,
|
||||
RequestMalformedError,
|
||||
TaskNotCancelableError,
|
||||
TaskNotFoundError,
|
||||
UnsupportedOperationError,
|
||||
} from '../../../errors.js';
|
||||
} from '../../../types.js';
|
||||
import { A2A_ERROR_CODE } from '../../../errors.js';
|
||||
|
||||
// ============================================================================
|
||||
// HTTP Status Codes and Error Mapping
|
||||
@ -51,19 +42,32 @@ export const HTTP_STATUS = {
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Maps varying errors to appropriate HTTP status codes.
|
||||
* Maps A2A error codes to appropriate HTTP status codes.
|
||||
*
|
||||
* @param error - The actual error instance
|
||||
* @param errorCode - A2A error code (e.g., -32700, -32600, -32602, etc.)
|
||||
* @returns Corresponding HTTP status code
|
||||
*
|
||||
* @example
|
||||
* mapErrorToStatus(-32602) // returns 400 (Bad Request)
|
||||
* mapErrorToStatus(-32001) // returns 404 (Not Found)
|
||||
*/
|
||||
export function mapErrorToStatus(error: unknown): number {
|
||||
if (error instanceof RequestMalformedError) return HTTP_STATUS.BAD_REQUEST;
|
||||
if (error instanceof TaskNotFoundError) return HTTP_STATUS.NOT_FOUND;
|
||||
if (error instanceof TaskNotCancelableError) return HTTP_STATUS.CONFLICT;
|
||||
if (error instanceof PushNotificationNotSupportedError) return HTTP_STATUS.BAD_REQUEST;
|
||||
if (error instanceof UnsupportedOperationError) return HTTP_STATUS.BAD_REQUEST;
|
||||
if (error instanceof AuthenticatedExtendedCardNotConfiguredError) return HTTP_STATUS.BAD_REQUEST;
|
||||
return HTTP_STATUS.INTERNAL_SERVER_ERROR;
|
||||
export function mapErrorToStatus(errorCode: number): number {
|
||||
switch (errorCode) {
|
||||
case A2A_ERROR_CODE.PARSE_ERROR:
|
||||
case A2A_ERROR_CODE.INVALID_REQUEST:
|
||||
case A2A_ERROR_CODE.INVALID_PARAMS:
|
||||
return HTTP_STATUS.BAD_REQUEST;
|
||||
case A2A_ERROR_CODE.METHOD_NOT_FOUND:
|
||||
case A2A_ERROR_CODE.TASK_NOT_FOUND:
|
||||
return HTTP_STATUS.NOT_FOUND;
|
||||
case A2A_ERROR_CODE.TASK_NOT_CANCELABLE:
|
||||
return HTTP_STATUS.CONFLICT;
|
||||
case A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED:
|
||||
case A2A_ERROR_CODE.UNSUPPORTED_OPERATION:
|
||||
return HTTP_STATUS.BAD_REQUEST;
|
||||
default:
|
||||
return HTTP_STATUS.INTERNAL_SERVER_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@ -71,19 +75,29 @@ export function mapErrorToStatus(error: unknown): number {
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Converts any Error to an HTTP+JSON transport format.
|
||||
* Converts an A2AError to HTTP+JSON transport format.
|
||||
* This conversion is private to the HTTP transport layer - errors are currently
|
||||
* tied to JSON-RPC format in A2AError, but for HTTP transport we need a simpler
|
||||
* format without the JSON-RPC wrapper.
|
||||
*
|
||||
* @param error - The error to convert
|
||||
* @returns Error payload
|
||||
* @param error - The A2AError to convert
|
||||
* @returns Error object with code, message, and optional data
|
||||
*/
|
||||
export function toHTTPError(error: unknown): {
|
||||
name: string;
|
||||
export function toHTTPError(error: A2AError): {
|
||||
code: number;
|
||||
message: string;
|
||||
data?: Record<string, unknown>;
|
||||
} {
|
||||
return {
|
||||
name: error instanceof Error ? error.name : 'Error',
|
||||
message: error instanceof Error ? error.message : 'An unexpected error occurred.',
|
||||
const errorObject: { code: number; message: string; data?: Record<string, unknown> } = {
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
};
|
||||
|
||||
if (error.data !== undefined) {
|
||||
errorObject.data = error.data;
|
||||
}
|
||||
|
||||
return errorObject;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@ -124,14 +138,14 @@ export class RestTransportHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the message send parameters.
|
||||
* Validate MessageSendParams.
|
||||
*/
|
||||
private validateSendMessageRequest(params: SendMessageRequest): void {
|
||||
private validateMessageSendParams(params: MessageSendParams): void {
|
||||
if (!params.message) {
|
||||
throw new RequestMalformedError('message is required');
|
||||
throw A2AError.invalidParams('message is required');
|
||||
}
|
||||
if (!params.message.messageId) {
|
||||
throw new RequestMalformedError('message.messageId is required');
|
||||
throw A2AError.invalidParams('message.messageId is required');
|
||||
}
|
||||
}
|
||||
|
||||
@ -139,10 +153,10 @@ export class RestTransportHandler {
|
||||
* Sends a message to the agent.
|
||||
*/
|
||||
async sendMessage(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
context: ServerCallContext
|
||||
): Promise<Message | Task> {
|
||||
this.validateSendMessageRequest(params);
|
||||
this.validateMessageSendParams(params);
|
||||
return this.requestHandler.sendMessage(params, context);
|
||||
}
|
||||
|
||||
@ -151,7 +165,7 @@ export class RestTransportHandler {
|
||||
* @throws {A2AError} UnsupportedOperation if streaming not supported
|
||||
*/
|
||||
async sendMessageStream(
|
||||
params: SendMessageRequest,
|
||||
params: MessageSendParams,
|
||||
context: ServerCallContext
|
||||
): Promise<
|
||||
AsyncGenerator<
|
||||
@ -161,7 +175,7 @@ export class RestTransportHandler {
|
||||
>
|
||||
> {
|
||||
await this.requireCapability('streaming');
|
||||
this.validateSendMessageRequest(params);
|
||||
this.validateMessageSendParams(params);
|
||||
return this.requestHandler.sendMessageStream(params, context);
|
||||
}
|
||||
|
||||
@ -174,7 +188,7 @@ export class RestTransportHandler {
|
||||
context: ServerCallContext,
|
||||
historyLength?: unknown
|
||||
): Promise<Task> {
|
||||
const params: GetTaskRequest = { id: taskId, historyLength: 0, tenant: '' };
|
||||
const params: TaskQueryParams = { id: taskId };
|
||||
if (historyLength !== undefined) {
|
||||
params.historyLength = this.parseHistoryLength(historyLength);
|
||||
}
|
||||
@ -185,32 +199,10 @@ export class RestTransportHandler {
|
||||
* Cancels a task.
|
||||
*/
|
||||
async cancelTask(taskId: string, context: ServerCallContext): Promise<Task> {
|
||||
const params: CancelTaskRequest = { id: taskId, tenant: '', metadata: {} };
|
||||
const params: TaskIdParams = { id: taskId };
|
||||
return this.requestHandler.cancelTask(params, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists tasks with filtering and pagination.
|
||||
*/
|
||||
async listTasks(
|
||||
queryParams: Record<string, unknown>,
|
||||
context: ServerCallContext
|
||||
): Promise<ListTasksResponse> {
|
||||
const params: ListTasksRequest = {
|
||||
tenant: (queryParams.tenant as string) || '',
|
||||
contextId: (queryParams.contextId as string) || '',
|
||||
status: queryParams.status ? Number(queryParams.status) : TaskState.TASK_STATE_UNSPECIFIED,
|
||||
pageSize: queryParams.pageSize ? Number(queryParams.pageSize) : undefined,
|
||||
pageToken: (queryParams.pageToken as string) || '',
|
||||
historyLength: queryParams.historyLength ? Number(queryParams.historyLength) : undefined,
|
||||
statusTimestampAfter: (queryParams.statusTimestampAfter as string) || undefined,
|
||||
includeArtifacts:
|
||||
queryParams.includeArtifacts === 'true' || queryParams.includeArtifacts === true,
|
||||
};
|
||||
|
||||
return this.requestHandler.listTasks(params, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resubscribes to task updates.
|
||||
* Returns camelCase stream of task updates.
|
||||
@ -223,22 +215,26 @@ export class RestTransportHandler {
|
||||
AsyncGenerator<Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent, void, undefined>
|
||||
> {
|
||||
await this.requireCapability('streaming');
|
||||
return this.requestHandler.resubscribe({ id: taskId, tenant: '' }, context);
|
||||
const params: TaskIdParams = { id: taskId };
|
||||
return this.requestHandler.resubscribe(params, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a push notification configuration.
|
||||
* @throws {A2AError} PushNotificationNotSupported if push notifications not supported
|
||||
*/
|
||||
async createTaskPushNotificationConfig(
|
||||
async setTaskPushNotificationConfig(
|
||||
config: TaskPushNotificationConfig,
|
||||
context: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
await this.requireCapability('pushNotifications');
|
||||
if (!config.id) {
|
||||
throw new RequestMalformedError('id is required');
|
||||
if (!config.taskId) {
|
||||
throw A2AError.invalidParams('taskId is required');
|
||||
}
|
||||
return this.requestHandler.createTaskPushNotificationConfig(config, context);
|
||||
if (!config.pushNotificationConfig) {
|
||||
throw A2AError.invalidParams('pushNotificationConfig is required');
|
||||
}
|
||||
return this.requestHandler.setTaskPushNotificationConfig(config, context);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -248,11 +244,7 @@ export class RestTransportHandler {
|
||||
taskId: string,
|
||||
context: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
const configs = await this.requestHandler.listTaskPushNotificationConfigs(
|
||||
{ taskId, pageSize: 0, pageToken: '', tenant: '' },
|
||||
context
|
||||
);
|
||||
return configs;
|
||||
return this.requestHandler.listTaskPushNotificationConfigs({ id: taskId }, context);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -263,11 +255,10 @@ export class RestTransportHandler {
|
||||
configId: string,
|
||||
context: ServerCallContext
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const config = await this.requestHandler.getTaskPushNotificationConfig(
|
||||
{ taskId, id: configId, tenant: '' },
|
||||
return this.requestHandler.getTaskPushNotificationConfig(
|
||||
{ id: taskId, pushNotificationConfigId: configId },
|
||||
context
|
||||
);
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -279,7 +270,7 @@ export class RestTransportHandler {
|
||||
context: ServerCallContext
|
||||
): Promise<void> {
|
||||
await this.requestHandler.deleteTaskPushNotificationConfig(
|
||||
{ taskId, id: configId, tenant: '' },
|
||||
{ id: taskId, pushNotificationConfigId: configId },
|
||||
context
|
||||
);
|
||||
}
|
||||
@ -289,10 +280,10 @@ export class RestTransportHandler {
|
||||
*/
|
||||
private static readonly CAPABILITY_ERRORS: Record<
|
||||
'streaming' | 'pushNotifications',
|
||||
() => Error
|
||||
() => A2AError
|
||||
> = {
|
||||
streaming: () => new UnsupportedOperationError('Agent does not support streaming'),
|
||||
pushNotifications: () => new PushNotificationNotSupportedError(),
|
||||
streaming: () => A2AError.unsupportedOperation('Agent does not support streaming'),
|
||||
pushNotifications: () => A2AError.pushNotificationNotSupported(),
|
||||
};
|
||||
|
||||
/**
|
||||
@ -311,14 +302,14 @@ export class RestTransportHandler {
|
||||
*/
|
||||
private parseHistoryLength(value: unknown): number {
|
||||
if (value === undefined || value === null) {
|
||||
throw new RequestMalformedError('historyLength is required');
|
||||
throw A2AError.invalidParams('historyLength is required');
|
||||
}
|
||||
const parsed = parseInt(String(value), 10);
|
||||
if (isNaN(parsed)) {
|
||||
throw new RequestMalformedError('historyLength must be a valid integer');
|
||||
throw A2AError.invalidParams('historyLength must be a valid integer');
|
||||
}
|
||||
if (parsed < 0) {
|
||||
throw new RequestMalformedError('historyLength must be non-negative');
|
||||
throw A2AError.invalidParams('historyLength must be non-negative');
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
@ -1,12 +1,4 @@
|
||||
import { TaskStatus, TaskState, Artifact } from '../index.js';
|
||||
|
||||
const TERMINAL_STATE_LIST: TaskState[] = [
|
||||
TaskState.TASK_STATE_COMPLETED,
|
||||
TaskState.TASK_STATE_FAILED,
|
||||
TaskState.TASK_STATE_CANCELED,
|
||||
TaskState.TASK_STATE_REJECTED,
|
||||
];
|
||||
export { TERMINAL_STATE_LIST };
|
||||
import { TaskStatus, Artifact } from '../types.js';
|
||||
|
||||
/**
|
||||
* Generates a timestamp in ISO 8601 format.
|
||||
|
||||
2653
src/types.ts
Normal file
2653
src/types.ts
Normal file
File diff suppressed because it is too large
Load Diff
@ -10,6 +10,9 @@ Ensure you have the project dependencies installed:
|
||||
npm install
|
||||
```
|
||||
|
||||
This project uses `@bufbuild/buf` which is listed in the `devDependencies`.
|
||||
Add the `a2a_types.proto` files to the `pb` directory.
|
||||
|
||||
## Generating Code
|
||||
|
||||
To generate the gRPC types definitions, run the following command from this directory (`src/types`):
|
||||
|
||||
@ -3,9 +3,7 @@
|
||||
# Uses remote plugins, no separate install required.
|
||||
version: v2
|
||||
inputs:
|
||||
- git_repo: https://github.com/a2aproject/A2A.git
|
||||
ref: v1.0.0
|
||||
subdir: specification
|
||||
- directory: ./pb
|
||||
plugins:
|
||||
- remote: buf.build/community/stephenh-ts-proto:v2.11.0
|
||||
out: ./pb
|
||||
|
||||
@ -1,42 +1,503 @@
|
||||
import { GenericError } from '../../errors.js';
|
||||
import { A2AError } from '../../server/error.js';
|
||||
import {
|
||||
CancelTaskRequest,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
ListTaskPushNotificationConfigRequest,
|
||||
GetTaskRequest,
|
||||
CreateTaskPushNotificationConfigRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
Message,
|
||||
Role,
|
||||
SendMessageConfiguration,
|
||||
PushNotificationConfig,
|
||||
AuthenticationInfo,
|
||||
SendMessageRequest,
|
||||
Part,
|
||||
SendMessageResponse,
|
||||
Task,
|
||||
TaskStatus,
|
||||
TaskState,
|
||||
Artifact,
|
||||
TaskPushNotificationConfig,
|
||||
ListTaskPushNotificationConfigsResponse,
|
||||
ListTaskPushNotificationConfigResponse,
|
||||
AgentCard,
|
||||
Security,
|
||||
SecurityScheme,
|
||||
AgentSkill,
|
||||
AgentCardSignature,
|
||||
TaskStatusUpdateEvent,
|
||||
TaskArtifactUpdateEvent,
|
||||
OAuthFlows,
|
||||
StreamResponse,
|
||||
} from '../pb/a2a.js';
|
||||
AgentInterface,
|
||||
AgentProvider,
|
||||
AgentCapabilities,
|
||||
AgentExtension,
|
||||
} from '../pb/a2a_types.js';
|
||||
import * as types from '../../types.js';
|
||||
import { extractTaskId, extractTaskAndPushNotificationConfigId } from './id_decoding.js';
|
||||
|
||||
/**
|
||||
* Converts proto types to internal types.
|
||||
* Since we now use proto types as source of truth, this class is mostly an identity mapper
|
||||
* or handles minor structural differences if any legacy support is needed. Planned to be removed completely in the future.
|
||||
*/
|
||||
export class FromProto {
|
||||
static sendMessageResult(response: SendMessageResponse): Task | Message {
|
||||
if (response.payload?.$case === 'task') {
|
||||
return response.payload.value;
|
||||
} else if (response.payload?.$case === 'message') {
|
||||
return response.payload.value;
|
||||
static taskQueryParams(request: GetTaskRequest): types.TaskQueryParams {
|
||||
return {
|
||||
id: extractTaskId(request.name),
|
||||
historyLength: request.historyLength,
|
||||
};
|
||||
}
|
||||
|
||||
static taskIdParams(request: CancelTaskRequest): types.TaskIdParams {
|
||||
return {
|
||||
id: extractTaskId(request.name),
|
||||
};
|
||||
}
|
||||
|
||||
static getTaskPushNotificationConfigParams(
|
||||
request: GetTaskPushNotificationConfigRequest
|
||||
): types.GetTaskPushNotificationConfigParams {
|
||||
const { taskId, configId } = extractTaskAndPushNotificationConfigId(request.name);
|
||||
return {
|
||||
id: taskId,
|
||||
pushNotificationConfigId: configId,
|
||||
};
|
||||
}
|
||||
|
||||
static listTaskPushNotificationConfigParams(
|
||||
request: ListTaskPushNotificationConfigRequest
|
||||
): types.ListTaskPushNotificationConfigParams {
|
||||
return {
|
||||
id: extractTaskId(request.parent),
|
||||
};
|
||||
}
|
||||
|
||||
static createTaskPushNotificationConfig(
|
||||
request: CreateTaskPushNotificationConfigRequest
|
||||
): types.TaskPushNotificationConfig {
|
||||
if (!request.config?.pushNotificationConfig) {
|
||||
throw A2AError.invalidParams(
|
||||
'Request must include a `config` object with a `pushNotificationConfig`'
|
||||
);
|
||||
}
|
||||
throw new GenericError('Invalid SendMessageResponse: missing result');
|
||||
return {
|
||||
taskId: extractTaskId(request.parent),
|
||||
pushNotificationConfig: FromProto.pushNotificationConfig(
|
||||
request.config.pushNotificationConfig
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
static deleteTaskPushNotificationConfigParams(
|
||||
request: DeleteTaskPushNotificationConfigRequest
|
||||
): types.DeleteTaskPushNotificationConfigParams {
|
||||
const { taskId, configId } = extractTaskAndPushNotificationConfigId(request.name);
|
||||
return {
|
||||
id: taskId,
|
||||
pushNotificationConfigId: configId,
|
||||
};
|
||||
}
|
||||
|
||||
static message(message: Message): types.Message | undefined {
|
||||
if (!message) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'message',
|
||||
messageId: message.messageId,
|
||||
parts: message.content.map((p) => FromProto.part(p)),
|
||||
contextId: message.contextId || undefined,
|
||||
taskId: message.taskId || undefined,
|
||||
role: FromProto.role(message.role),
|
||||
metadata: message.metadata,
|
||||
extensions: message.extensions,
|
||||
};
|
||||
}
|
||||
|
||||
static role(role: Role): 'agent' | 'user' {
|
||||
switch (role) {
|
||||
case Role.ROLE_AGENT:
|
||||
return 'agent';
|
||||
case Role.ROLE_USER:
|
||||
return 'user';
|
||||
default:
|
||||
throw A2AError.invalidParams(`Invalid role: ${role}`);
|
||||
}
|
||||
}
|
||||
|
||||
static messageSendConfiguration(
|
||||
configuration: SendMessageConfiguration
|
||||
): types.MessageSendConfiguration | undefined {
|
||||
if (!configuration) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
blocking: configuration.blocking,
|
||||
acceptedOutputModes: configuration.acceptedOutputModes,
|
||||
pushNotificationConfig: FromProto.pushNotificationConfig(configuration.pushNotification),
|
||||
};
|
||||
}
|
||||
|
||||
static pushNotificationConfig(
|
||||
config: PushNotificationConfig
|
||||
): types.PushNotificationConfig | undefined {
|
||||
if (!config) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
id: config.id,
|
||||
url: config.url,
|
||||
token: config.token || undefined,
|
||||
authentication: FromProto.pushNotificationAuthenticationInfo(config.authentication),
|
||||
};
|
||||
}
|
||||
|
||||
static pushNotificationAuthenticationInfo(
|
||||
authInfo: AuthenticationInfo
|
||||
): types.PushNotificationAuthenticationInfo | undefined {
|
||||
if (!authInfo) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
schemes: authInfo.schemes,
|
||||
credentials: authInfo.credentials,
|
||||
};
|
||||
}
|
||||
|
||||
static part(part: Part): types.Part {
|
||||
if (part.part?.$case === 'text') {
|
||||
return {
|
||||
kind: 'text',
|
||||
text: part.part.value,
|
||||
};
|
||||
}
|
||||
|
||||
if (part.part?.$case === 'file') {
|
||||
const filePart = part.part.value;
|
||||
if (filePart.file?.$case === 'fileWithUri') {
|
||||
return {
|
||||
kind: 'file',
|
||||
file: {
|
||||
uri: filePart.file.value,
|
||||
mimeType: filePart.mimeType,
|
||||
},
|
||||
};
|
||||
} else if (filePart.file?.$case === 'fileWithBytes') {
|
||||
return {
|
||||
kind: 'file',
|
||||
file: {
|
||||
bytes: filePart.file.value.toString('base64'),
|
||||
mimeType: filePart.mimeType,
|
||||
},
|
||||
};
|
||||
}
|
||||
throw A2AError.invalidParams('Invalid file part type');
|
||||
}
|
||||
|
||||
if (part.part?.$case === 'data') {
|
||||
return {
|
||||
kind: 'data',
|
||||
data: part.part.value.data,
|
||||
};
|
||||
}
|
||||
throw A2AError.invalidParams('Invalid part type');
|
||||
}
|
||||
|
||||
static messageSendParams(request: SendMessageRequest): types.MessageSendParams {
|
||||
return {
|
||||
message: FromProto.message(request.request),
|
||||
configuration: FromProto.messageSendConfiguration(request.configuration),
|
||||
metadata: request.metadata,
|
||||
};
|
||||
}
|
||||
|
||||
static sendMessageResult(response: SendMessageResponse): types.Task | types.Message {
|
||||
if (response.payload?.$case === 'task') {
|
||||
return FromProto.task(response.payload.value);
|
||||
} else if (response.payload?.$case === 'msg') {
|
||||
return FromProto.message(response.payload.value);
|
||||
}
|
||||
throw A2AError.invalidParams('Invalid SendMessageResponse: missing result');
|
||||
}
|
||||
|
||||
static task(task: Task): types.Task {
|
||||
return {
|
||||
kind: 'task',
|
||||
id: task.id,
|
||||
status: FromProto.taskStatus(task.status),
|
||||
contextId: task.contextId,
|
||||
artifacts: task.artifacts?.map((a) => FromProto.artifact(a)),
|
||||
history: task.history?.map((h) => FromProto.message(h)),
|
||||
metadata: task.metadata,
|
||||
};
|
||||
}
|
||||
|
||||
static taskStatus(status: TaskStatus): types.TaskStatus {
|
||||
return {
|
||||
message: FromProto.message(status.update),
|
||||
state: FromProto.taskState(status.state),
|
||||
timestamp: status.timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
static taskState(state: TaskState): types.TaskState {
|
||||
switch (state) {
|
||||
case TaskState.TASK_STATE_SUBMITTED:
|
||||
return 'submitted';
|
||||
case TaskState.TASK_STATE_WORKING:
|
||||
return 'working';
|
||||
case TaskState.TASK_STATE_INPUT_REQUIRED:
|
||||
return 'input-required';
|
||||
case TaskState.TASK_STATE_COMPLETED:
|
||||
return 'completed';
|
||||
case TaskState.TASK_STATE_CANCELLED:
|
||||
return 'canceled';
|
||||
case TaskState.TASK_STATE_FAILED:
|
||||
return 'failed';
|
||||
case TaskState.TASK_STATE_REJECTED:
|
||||
return 'rejected';
|
||||
case TaskState.TASK_STATE_AUTH_REQUIRED:
|
||||
return 'auth-required';
|
||||
case TaskState.TASK_STATE_UNSPECIFIED:
|
||||
return 'unknown';
|
||||
default:
|
||||
throw A2AError.invalidParams(`Invalid task state: ${state}`);
|
||||
}
|
||||
}
|
||||
|
||||
static artifact(artifact: Artifact): types.Artifact {
|
||||
return {
|
||||
artifactId: artifact.artifactId,
|
||||
name: artifact.name || undefined,
|
||||
description: artifact.description || undefined,
|
||||
parts: artifact.parts.map((p) => FromProto.part(p)),
|
||||
metadata: artifact.metadata,
|
||||
};
|
||||
}
|
||||
|
||||
static taskPushNotificationConfig(
|
||||
request: TaskPushNotificationConfig
|
||||
): types.TaskPushNotificationConfig {
|
||||
return {
|
||||
taskId: extractTaskId(request.name),
|
||||
pushNotificationConfig: FromProto.pushNotificationConfig(request.pushNotificationConfig),
|
||||
};
|
||||
}
|
||||
|
||||
static listTaskPushNotificationConfig(
|
||||
request: ListTaskPushNotificationConfigsResponse
|
||||
): TaskPushNotificationConfig[] {
|
||||
return request.configs;
|
||||
request: ListTaskPushNotificationConfigResponse
|
||||
): types.TaskPushNotificationConfig[] {
|
||||
return request.configs.map((c) => FromProto.taskPushNotificationConfig(c));
|
||||
}
|
||||
|
||||
static agentCard(agentCard: AgentCard): types.AgentCard {
|
||||
return {
|
||||
additionalInterfaces: agentCard.additionalInterfaces?.map((i) => FromProto.agentInterface(i)),
|
||||
capabilities: agentCard.capabilities
|
||||
? FromProto.agentCapabilities(agentCard.capabilities)
|
||||
: {},
|
||||
defaultInputModes: agentCard.defaultInputModes,
|
||||
defaultOutputModes: agentCard.defaultOutputModes,
|
||||
description: agentCard.description,
|
||||
documentationUrl: agentCard.documentationUrl || undefined,
|
||||
name: agentCard.name,
|
||||
preferredTransport: agentCard.preferredTransport,
|
||||
provider: agentCard.provider ? FromProto.agentProvider(agentCard.provider) : undefined,
|
||||
protocolVersion: agentCard.protocolVersion,
|
||||
security: agentCard.security?.map((s) => FromProto.security(s)),
|
||||
securitySchemes: agentCard.securitySchemes
|
||||
? Object.fromEntries(
|
||||
Object.entries(agentCard.securitySchemes).map(([key, value]) => [
|
||||
key,
|
||||
FromProto.securityScheme(value),
|
||||
])
|
||||
)
|
||||
: {},
|
||||
skills: agentCard.skills.map((s) => FromProto.skills(s)),
|
||||
signatures: agentCard.signatures?.map((s) => FromProto.agentCardSignature(s)),
|
||||
supportsAuthenticatedExtendedCard: agentCard.supportsAuthenticatedExtendedCard,
|
||||
url: agentCard.url,
|
||||
version: agentCard.version,
|
||||
};
|
||||
}
|
||||
|
||||
static agentCapabilities(capabilities: AgentCapabilities): types.AgentCapabilities1 {
|
||||
return {
|
||||
extensions: capabilities.extensions?.map((e) => FromProto.agentExtension(e)),
|
||||
pushNotifications: capabilities.pushNotifications,
|
||||
streaming: capabilities.streaming,
|
||||
};
|
||||
}
|
||||
|
||||
static agentExtension(extension: AgentExtension): types.AgentExtension {
|
||||
return {
|
||||
uri: extension.uri,
|
||||
description: extension.description || undefined,
|
||||
required: extension.required,
|
||||
params: extension.params,
|
||||
};
|
||||
}
|
||||
|
||||
static agentInterface(intf: AgentInterface): types.AgentInterface {
|
||||
return {
|
||||
transport: intf.transport,
|
||||
url: intf.url,
|
||||
};
|
||||
}
|
||||
|
||||
static agentProvider(provider: AgentProvider): types.AgentProvider {
|
||||
return {
|
||||
organization: provider.organization,
|
||||
url: provider.url,
|
||||
};
|
||||
}
|
||||
|
||||
static security(security: Security): { [k: string]: string[] } {
|
||||
return Object.fromEntries(
|
||||
Object.entries(security.schemes)?.map(([key, value]) => [key, value.list])
|
||||
);
|
||||
}
|
||||
|
||||
static securityScheme(securitySchemes: SecurityScheme): types.SecurityScheme {
|
||||
switch (securitySchemes.scheme?.$case) {
|
||||
case 'apiKeySecurityScheme':
|
||||
return {
|
||||
type: 'apiKey',
|
||||
name: securitySchemes.scheme.value.name,
|
||||
in: securitySchemes.scheme.value.location as 'query' | 'header' | 'cookie',
|
||||
description: securitySchemes.scheme.value.description || undefined,
|
||||
};
|
||||
case 'httpAuthSecurityScheme':
|
||||
return {
|
||||
type: 'http',
|
||||
scheme: securitySchemes.scheme.value.scheme,
|
||||
bearerFormat: securitySchemes.scheme.value.bearerFormat || undefined,
|
||||
description: securitySchemes.scheme.value.description || undefined,
|
||||
};
|
||||
case 'mtlsSecurityScheme':
|
||||
return {
|
||||
type: 'mutualTLS',
|
||||
description: securitySchemes.scheme.value.description || undefined,
|
||||
};
|
||||
case 'oauth2SecurityScheme':
|
||||
return {
|
||||
type: 'oauth2',
|
||||
description: securitySchemes.scheme.value.description || undefined,
|
||||
flows: FromProto.oauthFlows(securitySchemes.scheme.value.flows),
|
||||
oauth2MetadataUrl: securitySchemes.scheme.value.oauth2MetadataUrl || undefined,
|
||||
};
|
||||
case 'openIdConnectSecurityScheme':
|
||||
return {
|
||||
type: 'openIdConnect',
|
||||
description: securitySchemes.scheme.value.description || undefined,
|
||||
openIdConnectUrl: securitySchemes.scheme.value.openIdConnectUrl,
|
||||
};
|
||||
default:
|
||||
throw A2AError.internalError(`Unsupported security scheme type`);
|
||||
}
|
||||
}
|
||||
|
||||
static oauthFlows(flows: OAuthFlows): types.OAuthFlows {
|
||||
switch (flows.flow?.$case) {
|
||||
case 'implicit':
|
||||
return {
|
||||
implicit: {
|
||||
authorizationUrl: flows.flow.value.authorizationUrl,
|
||||
scopes: flows.flow.value.scopes,
|
||||
refreshUrl: flows.flow.value.refreshUrl || undefined,
|
||||
},
|
||||
};
|
||||
case 'password':
|
||||
return {
|
||||
password: {
|
||||
refreshUrl: flows.flow.value.refreshUrl || undefined,
|
||||
scopes: flows.flow.value.scopes,
|
||||
tokenUrl: flows.flow.value.tokenUrl,
|
||||
},
|
||||
};
|
||||
case 'authorizationCode':
|
||||
return {
|
||||
authorizationCode: {
|
||||
refreshUrl: flows.flow.value.refreshUrl || undefined,
|
||||
authorizationUrl: flows.flow.value.authorizationUrl,
|
||||
scopes: flows.flow.value.scopes,
|
||||
tokenUrl: flows.flow.value.tokenUrl,
|
||||
},
|
||||
};
|
||||
case 'clientCredentials':
|
||||
return {
|
||||
clientCredentials: {
|
||||
refreshUrl: flows.flow.value.refreshUrl || undefined,
|
||||
scopes: flows.flow.value.scopes,
|
||||
tokenUrl: flows.flow.value.tokenUrl,
|
||||
},
|
||||
};
|
||||
default:
|
||||
throw A2AError.internalError(`Unsupported OAuth flows`);
|
||||
}
|
||||
}
|
||||
|
||||
static skills(skill: AgentSkill): types.AgentSkill {
|
||||
return {
|
||||
id: skill.id,
|
||||
name: skill.name,
|
||||
description: skill.description,
|
||||
tags: skill.tags,
|
||||
examples: skill.examples,
|
||||
inputModes: skill.inputModes,
|
||||
outputModes: skill.outputModes,
|
||||
security: skill.security?.map((s) => FromProto.security(s)),
|
||||
};
|
||||
}
|
||||
|
||||
static agentCardSignature(signatures: AgentCardSignature): types.AgentCardSignature {
|
||||
return {
|
||||
protected: signatures.protected,
|
||||
signature: signatures.signature,
|
||||
header: signatures.header,
|
||||
};
|
||||
}
|
||||
|
||||
static taskStatusUpdateEvent(event: TaskStatusUpdateEvent): types.TaskStatusUpdateEvent {
|
||||
return {
|
||||
kind: 'status-update',
|
||||
taskId: event.taskId,
|
||||
status: FromProto.taskStatus(event.status),
|
||||
contextId: event.contextId,
|
||||
metadata: event.metadata,
|
||||
final: event.final,
|
||||
};
|
||||
}
|
||||
|
||||
static taskArtifactUpdateEvent(event: TaskArtifactUpdateEvent): types.TaskArtifactUpdateEvent {
|
||||
return {
|
||||
kind: 'artifact-update',
|
||||
taskId: event.taskId,
|
||||
artifact: FromProto.artifact(event.artifact),
|
||||
contextId: event.contextId,
|
||||
metadata: event.metadata,
|
||||
lastChunk: event.lastChunk,
|
||||
};
|
||||
}
|
||||
|
||||
static messageStreamResult(
|
||||
event: StreamResponse
|
||||
): Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent {
|
||||
if (event.payload) {
|
||||
return event.payload.value;
|
||||
): types.Message | types.Task | types.TaskStatusUpdateEvent | types.TaskArtifactUpdateEvent {
|
||||
switch (event.payload?.$case) {
|
||||
case 'msg':
|
||||
return FromProto.message(event.payload.value);
|
||||
case 'task':
|
||||
return FromProto.task(event.payload.value);
|
||||
case 'statusUpdate':
|
||||
return FromProto.taskStatusUpdateEvent(event.payload.value);
|
||||
case 'artifactUpdate':
|
||||
return FromProto.taskArtifactUpdateEvent(event.payload.value);
|
||||
default:
|
||||
throw A2AError.internalError('Invalid event type in StreamResponse');
|
||||
}
|
||||
throw new GenericError('Invalid event type in StreamResponse');
|
||||
}
|
||||
}
|
||||
|
||||
30
src/types/converters/id_decoding.ts
Normal file
30
src/types/converters/id_decoding.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { A2AError } from '../../server/error.js';
|
||||
|
||||
const CONFIG_REGEX = /^tasks\/([^/]+)\/pushNotificationConfigs\/([^/]+)$/;
|
||||
const TASK_ONLY_REGEX = /^tasks\/([^/]+)(?:\/|$)/;
|
||||
|
||||
export const extractTaskId = (name: string): string => {
|
||||
const match = name.match(TASK_ONLY_REGEX);
|
||||
if (!match) {
|
||||
throw A2AError.invalidParams(`Invalid or missing task ID in: "${name}"`);
|
||||
}
|
||||
return match[1];
|
||||
};
|
||||
|
||||
export const generateTaskName = (taskId: string): string => {
|
||||
return `tasks/${taskId}`;
|
||||
};
|
||||
|
||||
export const extractTaskAndPushNotificationConfigId = (
|
||||
name: string
|
||||
): { taskId: string; configId: string } => {
|
||||
const match = name.match(CONFIG_REGEX);
|
||||
if (!match) {
|
||||
throw A2AError.invalidParams(`Invalid or missing config ID in: "${name}"`);
|
||||
}
|
||||
return { taskId: match[1], configId: match[2] };
|
||||
};
|
||||
|
||||
export const generatePushNotificationConfigName = (taskId: string, configId: string): string => {
|
||||
return `tasks/${taskId}/pushNotificationConfigs/${configId}`;
|
||||
};
|
||||
@ -1,75 +1,568 @@
|
||||
import { GenericError } from '../../errors.js';
|
||||
import { A2AError } from '../../server/error.js';
|
||||
import * as types from '../../types.js';
|
||||
import {
|
||||
AgentCard,
|
||||
AgentCardSignature,
|
||||
AgentCapabilities,
|
||||
AgentExtension,
|
||||
AgentInterface,
|
||||
AgentProvider,
|
||||
Artifact,
|
||||
AuthenticationInfo,
|
||||
FilePart as ProtoFilePart,
|
||||
Message,
|
||||
OAuthFlows,
|
||||
Part,
|
||||
PushNotificationConfig,
|
||||
Role,
|
||||
Security,
|
||||
SecurityScheme,
|
||||
SendMessageResponse,
|
||||
StreamResponse,
|
||||
Task,
|
||||
TaskArtifactUpdateEvent,
|
||||
TaskPushNotificationConfig,
|
||||
TaskState,
|
||||
TaskStatus,
|
||||
TaskStatusUpdateEvent,
|
||||
ListTaskPushNotificationConfigsResponse,
|
||||
} from '../pb/a2a.js';
|
||||
ListTaskPushNotificationConfigResponse,
|
||||
AgentSkill,
|
||||
SendMessageRequest,
|
||||
SendMessageConfiguration,
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
ListTaskPushNotificationConfigRequest,
|
||||
DeleteTaskPushNotificationConfigRequest,
|
||||
GetTaskRequest,
|
||||
CancelTaskRequest,
|
||||
TaskSubscriptionRequest,
|
||||
CreateTaskPushNotificationConfigRequest,
|
||||
GetAgentCardRequest,
|
||||
} from '../pb/a2a_types.js';
|
||||
import { generatePushNotificationConfigName, generateTaskName } from './id_decoding.js';
|
||||
|
||||
export class ToProto {
|
||||
static listTaskPushNotificationConfig(
|
||||
configs: TaskPushNotificationConfig[]
|
||||
): ListTaskPushNotificationConfigsResponse {
|
||||
static agentCard(agentCard: types.AgentCard): AgentCard {
|
||||
return {
|
||||
configs,
|
||||
protocolVersion: agentCard.protocolVersion,
|
||||
name: agentCard.name,
|
||||
description: agentCard.description,
|
||||
url: agentCard.url,
|
||||
preferredTransport: agentCard.preferredTransport ?? '',
|
||||
additionalInterfaces:
|
||||
agentCard.additionalInterfaces?.map((i) => ToProto.agentInterface(i)) ?? [],
|
||||
provider: ToProto.agentProvider(agentCard.provider),
|
||||
version: agentCard.version,
|
||||
documentationUrl: agentCard.documentationUrl ?? '',
|
||||
capabilities: ToProto.agentCapabilities(agentCard.capabilities),
|
||||
securitySchemes: agentCard.securitySchemes
|
||||
? Object.fromEntries(
|
||||
Object.entries(agentCard.securitySchemes).map(([key, value]) => [
|
||||
key,
|
||||
ToProto.securityScheme(value),
|
||||
])
|
||||
)
|
||||
: {},
|
||||
security: agentCard.security?.map((s) => ToProto.security(s)) ?? [],
|
||||
defaultInputModes: agentCard.defaultInputModes,
|
||||
defaultOutputModes: agentCard.defaultOutputModes,
|
||||
skills: agentCard.skills.map((s) => ToProto.agentSkill(s)),
|
||||
supportsAuthenticatedExtendedCard: agentCard.supportsAuthenticatedExtendedCard,
|
||||
signatures: agentCard.signatures?.map((s) => ToProto.agentCardSignature(s)) ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
static agentCardSignature(signatures: types.AgentCardSignature): AgentCardSignature {
|
||||
return {
|
||||
protected: signatures.protected,
|
||||
signature: signatures.signature,
|
||||
header: signatures.header,
|
||||
};
|
||||
}
|
||||
|
||||
static agentSkill(skill: types.AgentSkill): AgentSkill {
|
||||
return {
|
||||
id: skill.id,
|
||||
name: skill.name,
|
||||
description: skill.description,
|
||||
tags: skill.tags ?? [],
|
||||
examples: skill.examples ?? [],
|
||||
inputModes: skill.inputModes ?? [],
|
||||
outputModes: skill.outputModes ?? [],
|
||||
security: skill.security ? skill.security.map((s) => ToProto.security(s)) : [],
|
||||
};
|
||||
}
|
||||
|
||||
static security(security: { [k: string]: string[] }): Security {
|
||||
return {
|
||||
schemes: Object.fromEntries(
|
||||
Object.entries(security).map(([key, value]) => {
|
||||
return [key, { list: value }];
|
||||
})
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
static securityScheme(scheme: types.SecurityScheme): SecurityScheme {
|
||||
switch (scheme.type) {
|
||||
case 'apiKey':
|
||||
return {
|
||||
scheme: {
|
||||
$case: 'apiKeySecurityScheme',
|
||||
value: {
|
||||
name: scheme.name,
|
||||
location: scheme.in,
|
||||
description: scheme.description ?? '',
|
||||
},
|
||||
},
|
||||
};
|
||||
case 'http':
|
||||
return {
|
||||
scheme: {
|
||||
$case: 'httpAuthSecurityScheme',
|
||||
value: {
|
||||
description: scheme.description ?? '',
|
||||
scheme: scheme.scheme,
|
||||
bearerFormat: scheme.bearerFormat ?? '',
|
||||
},
|
||||
},
|
||||
};
|
||||
case 'mutualTLS':
|
||||
return {
|
||||
scheme: {
|
||||
$case: 'mtlsSecurityScheme',
|
||||
value: {
|
||||
description: scheme.description ?? '',
|
||||
},
|
||||
},
|
||||
};
|
||||
case 'oauth2':
|
||||
return {
|
||||
scheme: {
|
||||
$case: 'oauth2SecurityScheme',
|
||||
value: {
|
||||
description: scheme.description ?? '',
|
||||
flows: ToProto.oauthFlows(scheme.flows),
|
||||
oauth2MetadataUrl: scheme.oauth2MetadataUrl ?? '',
|
||||
},
|
||||
},
|
||||
};
|
||||
case 'openIdConnect':
|
||||
return {
|
||||
scheme: {
|
||||
$case: 'openIdConnectSecurityScheme',
|
||||
value: {
|
||||
description: scheme.description ?? '',
|
||||
openIdConnectUrl: scheme.openIdConnectUrl,
|
||||
},
|
||||
},
|
||||
};
|
||||
default:
|
||||
throw A2AError.internalError(`Unsupported security scheme type`);
|
||||
}
|
||||
}
|
||||
|
||||
static oauthFlows(flows: types.OAuthFlows): OAuthFlows {
|
||||
if (flows.implicit) {
|
||||
return {
|
||||
flow: {
|
||||
$case: 'implicit',
|
||||
value: {
|
||||
authorizationUrl: flows.implicit.authorizationUrl,
|
||||
scopes: flows.implicit.scopes,
|
||||
refreshUrl: flows.implicit.refreshUrl ?? '',
|
||||
},
|
||||
},
|
||||
};
|
||||
} else if (flows.password) {
|
||||
return {
|
||||
flow: {
|
||||
$case: 'password',
|
||||
value: {
|
||||
tokenUrl: flows.password.tokenUrl,
|
||||
scopes: flows.password.scopes,
|
||||
refreshUrl: flows.password.refreshUrl ?? '',
|
||||
},
|
||||
},
|
||||
};
|
||||
} else if (flows.clientCredentials) {
|
||||
return {
|
||||
flow: {
|
||||
$case: 'clientCredentials',
|
||||
value: {
|
||||
tokenUrl: flows.clientCredentials.tokenUrl,
|
||||
scopes: flows.clientCredentials.scopes,
|
||||
refreshUrl: flows.clientCredentials.refreshUrl ?? '',
|
||||
},
|
||||
},
|
||||
};
|
||||
} else if (flows.authorizationCode) {
|
||||
return {
|
||||
flow: {
|
||||
$case: 'authorizationCode',
|
||||
value: {
|
||||
authorizationUrl: flows.authorizationCode.authorizationUrl,
|
||||
tokenUrl: flows.authorizationCode.tokenUrl,
|
||||
scopes: flows.authorizationCode.scopes,
|
||||
refreshUrl: flows.authorizationCode.refreshUrl ?? '',
|
||||
},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
throw A2AError.internalError(`Unsupported OAuth flows`);
|
||||
}
|
||||
}
|
||||
|
||||
static agentInterface(agentInterface: types.AgentInterface): AgentInterface {
|
||||
return {
|
||||
transport: agentInterface.transport,
|
||||
url: agentInterface.url,
|
||||
};
|
||||
}
|
||||
|
||||
static agentProvider(agentProvider: types.AgentProvider): AgentProvider {
|
||||
if (!agentProvider) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
url: agentProvider.url,
|
||||
organization: agentProvider.organization,
|
||||
};
|
||||
}
|
||||
|
||||
static agentCapabilities(capabilities: types.AgentCapabilities): AgentCapabilities {
|
||||
return {
|
||||
streaming: capabilities.streaming,
|
||||
pushNotifications: capabilities.pushNotifications,
|
||||
extensions: capabilities.extensions
|
||||
? capabilities.extensions.map((e) => ToProto.agentExtension(e))
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
static agentExtension(extension: types.AgentExtension): AgentExtension {
|
||||
return {
|
||||
uri: extension.uri,
|
||||
description: extension.description ?? '',
|
||||
required: extension.required ?? false,
|
||||
params: extension.params,
|
||||
};
|
||||
}
|
||||
|
||||
static listTaskPushNotificationConfig(
|
||||
config: types.TaskPushNotificationConfig[]
|
||||
): ListTaskPushNotificationConfigResponse {
|
||||
return {
|
||||
configs: config.map((c) => ToProto.taskPushNotificationConfig(c)),
|
||||
nextPageToken: '',
|
||||
};
|
||||
}
|
||||
|
||||
static getTaskPushNotificationConfigParams(
|
||||
config: types.GetTaskPushNotificationConfigParams
|
||||
): GetTaskPushNotificationConfigRequest {
|
||||
return {
|
||||
name: generatePushNotificationConfigName(config.id, config.pushNotificationConfigId),
|
||||
};
|
||||
}
|
||||
|
||||
static listTaskPushNotificationConfigParams(
|
||||
config: types.ListTaskPushNotificationConfigParams
|
||||
): ListTaskPushNotificationConfigRequest {
|
||||
return {
|
||||
parent: generateTaskName(config.id),
|
||||
pageToken: '',
|
||||
pageSize: 0,
|
||||
};
|
||||
}
|
||||
|
||||
static deleteTaskPushNotificationConfigParams(
|
||||
config: types.DeleteTaskPushNotificationConfigParams
|
||||
): DeleteTaskPushNotificationConfigRequest {
|
||||
return {
|
||||
name: generatePushNotificationConfigName(config.id, config.pushNotificationConfigId),
|
||||
};
|
||||
}
|
||||
|
||||
static taskPushNotificationConfig(
|
||||
config: types.TaskPushNotificationConfig
|
||||
): TaskPushNotificationConfig {
|
||||
return {
|
||||
name: generatePushNotificationConfigName(
|
||||
config.taskId,
|
||||
config.pushNotificationConfig.id ?? ''
|
||||
),
|
||||
pushNotificationConfig: ToProto.pushNotificationConfig(config.pushNotificationConfig),
|
||||
};
|
||||
}
|
||||
|
||||
static taskPushNotificationConfigCreate(
|
||||
config: types.TaskPushNotificationConfig
|
||||
): CreateTaskPushNotificationConfigRequest {
|
||||
return {
|
||||
parent: generateTaskName(config.taskId),
|
||||
config: ToProto.taskPushNotificationConfig(config),
|
||||
configId: config.pushNotificationConfig.id,
|
||||
};
|
||||
}
|
||||
|
||||
static pushNotificationConfig(config: types.PushNotificationConfig): PushNotificationConfig {
|
||||
if (!config) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
id: config.id ?? '',
|
||||
url: config.url,
|
||||
token: config.token ?? '',
|
||||
authentication: ToProto.pushNotificationAuthenticationInfo(config.authentication),
|
||||
};
|
||||
}
|
||||
|
||||
static pushNotificationAuthenticationInfo(
|
||||
authInfo: types.PushNotificationAuthenticationInfo
|
||||
): AuthenticationInfo | undefined {
|
||||
if (!authInfo) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
schemes: authInfo.schemes,
|
||||
credentials: authInfo.credentials ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
static messageStreamResult(
|
||||
event: Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent
|
||||
event: types.Message | types.Task | types.TaskStatusUpdateEvent | types.TaskArtifactUpdateEvent
|
||||
): StreamResponse {
|
||||
if ('messageId' in event) {
|
||||
if (event.kind === 'message') {
|
||||
return {
|
||||
payload: {
|
||||
$case: 'message',
|
||||
value: event,
|
||||
$case: 'msg',
|
||||
value: ToProto.message(event),
|
||||
},
|
||||
};
|
||||
} else if ('artifacts' in event) {
|
||||
} else if (event.kind === 'task') {
|
||||
return {
|
||||
payload: {
|
||||
$case: 'task',
|
||||
value: event,
|
||||
value: ToProto.task(event),
|
||||
},
|
||||
};
|
||||
} else if ('status' in event) {
|
||||
} else if (event.kind === 'status-update') {
|
||||
return {
|
||||
payload: {
|
||||
$case: 'statusUpdate',
|
||||
value: event,
|
||||
value: ToProto.taskStatusUpdateEvent(event),
|
||||
},
|
||||
};
|
||||
} else if ('artifact' in event) {
|
||||
} else if (event.kind === 'artifact-update') {
|
||||
return {
|
||||
payload: {
|
||||
$case: 'artifactUpdate',
|
||||
value: event,
|
||||
value: ToProto.taskArtifactUpdateEvent(event),
|
||||
},
|
||||
};
|
||||
} else {
|
||||
throw A2AError.internalError('Invalid event type');
|
||||
}
|
||||
throw new GenericError('Invalid event type');
|
||||
}
|
||||
|
||||
static messageSendResult(params: Message | Task): SendMessageResponse {
|
||||
if ('messageId' in params) {
|
||||
static taskStatusUpdateEvent(event: types.TaskStatusUpdateEvent): TaskStatusUpdateEvent {
|
||||
return {
|
||||
taskId: event.taskId,
|
||||
status: ToProto.taskStatus(event.status),
|
||||
contextId: event.contextId,
|
||||
metadata: event.metadata,
|
||||
final: event.final,
|
||||
};
|
||||
}
|
||||
|
||||
static taskArtifactUpdateEvent(event: types.TaskArtifactUpdateEvent): TaskArtifactUpdateEvent {
|
||||
return {
|
||||
taskId: event.taskId,
|
||||
artifact: ToProto.artifact(event.artifact),
|
||||
contextId: event.contextId,
|
||||
metadata: event.metadata,
|
||||
append: event.append,
|
||||
lastChunk: event.lastChunk,
|
||||
};
|
||||
}
|
||||
|
||||
static messageSendResult(params: types.Message | types.Task): SendMessageResponse {
|
||||
if (params.kind === 'message') {
|
||||
return {
|
||||
payload: {
|
||||
$case: 'message',
|
||||
value: params,
|
||||
$case: 'msg',
|
||||
value: ToProto.message(params),
|
||||
},
|
||||
};
|
||||
} else if ('artifacts' in params) {
|
||||
} else if (params.kind === 'task') {
|
||||
return {
|
||||
payload: {
|
||||
$case: 'task',
|
||||
value: params,
|
||||
value: ToProto.task(params),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
static message(message: types.Message): Message | undefined {
|
||||
if (!message) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
messageId: message.messageId,
|
||||
content: message.parts.map((p) => ToProto.part(p)),
|
||||
contextId: message.contextId ?? '',
|
||||
taskId: message.taskId ?? '',
|
||||
role: ToProto.role(message.role),
|
||||
metadata: message.metadata,
|
||||
extensions: message.extensions ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
static role(role: string): Role {
|
||||
switch (role) {
|
||||
case 'agent':
|
||||
return Role.ROLE_AGENT;
|
||||
case 'user':
|
||||
return Role.ROLE_USER;
|
||||
default:
|
||||
throw A2AError.internalError(`Invalid role`);
|
||||
}
|
||||
}
|
||||
|
||||
static task(task: types.Task): Task {
|
||||
return {
|
||||
id: task.id,
|
||||
contextId: task.contextId,
|
||||
status: ToProto.taskStatus(task.status),
|
||||
artifacts: task.artifacts?.map((a) => ToProto.artifact(a)) ?? [],
|
||||
history: task.history?.map((m) => ToProto.message(m)) ?? [],
|
||||
metadata: task.metadata,
|
||||
};
|
||||
}
|
||||
|
||||
static taskStatus(status: types.TaskStatus): TaskStatus {
|
||||
return {
|
||||
state: ToProto.taskState(status.state),
|
||||
update: ToProto.message(status.message),
|
||||
timestamp: status.timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
static artifact(artifact: types.Artifact): Artifact {
|
||||
return {
|
||||
artifactId: artifact.artifactId,
|
||||
name: artifact.name ?? '',
|
||||
description: artifact.description ?? '',
|
||||
parts: artifact.parts.map((p) => ToProto.part(p)),
|
||||
metadata: artifact.metadata,
|
||||
extensions: artifact.extensions ? artifact.extensions : [],
|
||||
};
|
||||
}
|
||||
|
||||
static taskState(state: types.TaskState): TaskState {
|
||||
switch (state) {
|
||||
case 'submitted':
|
||||
return TaskState.TASK_STATE_SUBMITTED;
|
||||
case 'working':
|
||||
return TaskState.TASK_STATE_WORKING;
|
||||
case 'input-required':
|
||||
return TaskState.TASK_STATE_INPUT_REQUIRED;
|
||||
case 'rejected':
|
||||
return TaskState.TASK_STATE_REJECTED;
|
||||
case 'auth-required':
|
||||
return TaskState.TASK_STATE_AUTH_REQUIRED;
|
||||
case 'completed':
|
||||
return TaskState.TASK_STATE_COMPLETED;
|
||||
case 'failed':
|
||||
return TaskState.TASK_STATE_FAILED;
|
||||
case 'canceled':
|
||||
return TaskState.TASK_STATE_CANCELLED;
|
||||
case 'unknown':
|
||||
return TaskState.TASK_STATE_UNSPECIFIED;
|
||||
default:
|
||||
return TaskState.UNRECOGNIZED;
|
||||
}
|
||||
}
|
||||
|
||||
static part(part: types.Part): Part {
|
||||
if (part.kind === 'text') {
|
||||
return {
|
||||
part: { $case: 'text', value: part.text },
|
||||
};
|
||||
}
|
||||
|
||||
if (part.kind === 'file') {
|
||||
let filePart: ProtoFilePart;
|
||||
if ('uri' in part.file) {
|
||||
filePart = {
|
||||
file: { $case: 'fileWithUri', value: part.file.uri },
|
||||
mimeType: part.file.mimeType,
|
||||
};
|
||||
} else if ('bytes' in part.file) {
|
||||
filePart = {
|
||||
file: { $case: 'fileWithBytes', value: Buffer.from(part.file.bytes, 'base64') },
|
||||
mimeType: part.file.mimeType,
|
||||
};
|
||||
} else {
|
||||
throw A2AError.internalError('Invalid file part');
|
||||
}
|
||||
return {
|
||||
part: { $case: 'file', value: filePart },
|
||||
};
|
||||
}
|
||||
|
||||
if (part.kind === 'data') {
|
||||
return {
|
||||
part: { $case: 'data', value: { data: part.data } },
|
||||
};
|
||||
}
|
||||
throw A2AError.internalError('Invalid part type');
|
||||
}
|
||||
|
||||
static messageSendParams(params: types.MessageSendParams): SendMessageRequest {
|
||||
return {
|
||||
request: ToProto.message(params.message),
|
||||
configuration: ToProto.configuration(params.configuration),
|
||||
metadata: params.metadata,
|
||||
};
|
||||
}
|
||||
|
||||
static configuration(configuration: types.MessageSendConfiguration): SendMessageConfiguration {
|
||||
if (!configuration) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
blocking: configuration.blocking,
|
||||
acceptedOutputModes: configuration.acceptedOutputModes ?? [],
|
||||
pushNotification: ToProto.pushNotificationConfig(configuration.pushNotificationConfig),
|
||||
historyLength: configuration.historyLength ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
static taskQueryParams(params: types.TaskQueryParams): GetTaskRequest {
|
||||
return {
|
||||
name: generateTaskName(params.id),
|
||||
historyLength: params.historyLength ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
static cancelTaskRequest(params: types.TaskIdParams): CancelTaskRequest {
|
||||
return {
|
||||
name: generateTaskName(params.id),
|
||||
};
|
||||
}
|
||||
|
||||
static taskIdParams(params: types.TaskIdParams): TaskSubscriptionRequest {
|
||||
return {
|
||||
name: generateTaskName(params.id),
|
||||
};
|
||||
}
|
||||
|
||||
static getAgentCardRequest(): GetAgentCardRequest {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -2,14 +2,7 @@ import express from 'express';
|
||||
import { Server, ServerCredentials } from '@grpc/grpc-js';
|
||||
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
|
||||
|
||||
import {
|
||||
AgentCard,
|
||||
Task,
|
||||
TaskStatusUpdateEvent,
|
||||
Message,
|
||||
TaskState,
|
||||
Role,
|
||||
} from '../../src/index.js';
|
||||
import { AgentCard, Task, TaskStatusUpdateEvent, Message } from '../../src/index.js';
|
||||
import {
|
||||
InMemoryTaskStore,
|
||||
TaskStore,
|
||||
@ -36,14 +29,14 @@ class SUTAgentExecutor implements AgentExecutor {
|
||||
public cancelTask = async (taskId: string, eventBus: ExecutionEventBus): Promise<void> => {
|
||||
this.runningTask.delete(taskId);
|
||||
const cancelledUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: this.lastContextId ?? uuidv4(),
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_CANCELED,
|
||||
state: 'canceled',
|
||||
timestamp: new Date().toISOString(),
|
||||
message: undefined,
|
||||
},
|
||||
metadata: {},
|
||||
final: true, // Cancellation is a final state
|
||||
};
|
||||
eventBus.publish(cancelledUpdate);
|
||||
};
|
||||
@ -66,14 +59,13 @@ class SUTAgentExecutor implements AgentExecutor {
|
||||
// 1. Publish initial Task event if it's a new task
|
||||
if (!existingTask) {
|
||||
const initialTask: Task = {
|
||||
kind: 'task',
|
||||
id: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_SUBMITTED,
|
||||
state: 'submitted',
|
||||
timestamp: new Date().toISOString(),
|
||||
message: undefined,
|
||||
},
|
||||
artifacts: [],
|
||||
history: [userMessage], // Start history with the current user message
|
||||
metadata: userMessage.metadata, // Carry over metadata from message if any
|
||||
};
|
||||
@ -82,30 +74,22 @@ class SUTAgentExecutor implements AgentExecutor {
|
||||
|
||||
// 2. Publish "working" status update
|
||||
const workingStatusUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_WORKING,
|
||||
state: 'working',
|
||||
message: {
|
||||
role: Role.ROLE_AGENT,
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: 'Processing your question' },
|
||||
metadata: undefined,
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
},
|
||||
],
|
||||
parts: [{ kind: 'text', text: 'Processing your question' }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
metadata: {},
|
||||
final: false,
|
||||
};
|
||||
eventBus.publish(workingStatusUpdate);
|
||||
|
||||
@ -121,40 +105,32 @@ class SUTAgentExecutor implements AgentExecutor {
|
||||
console.info(`[SUTAgentExecutor] Prompt response: ${agentReplyText}`);
|
||||
|
||||
const agentMessage: Message = {
|
||||
role: Role.ROLE_AGENT,
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: agentReplyText },
|
||||
metadata: undefined,
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
},
|
||||
],
|
||||
parts: [{ kind: 'text', text: agentReplyText }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
};
|
||||
|
||||
const finalUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_INPUT_REQUIRED,
|
||||
state: 'input-required',
|
||||
message: agentMessage,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
metadata: {},
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(finalUpdate);
|
||||
}
|
||||
|
||||
parseInputMessage(message: Message): string {
|
||||
/** Process the user query and return a response. */
|
||||
const textPart = message.parts.find((part) => part.content?.$case === 'text');
|
||||
const query = textPart?.content?.$case === 'text' ? textPart.content.value.trim() : '';
|
||||
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.';
|
||||
@ -177,40 +153,18 @@ class SUTAgentExecutor implements AgentExecutor {
|
||||
const SUTAgentCard: AgentCard = {
|
||||
name: 'SUT Agent',
|
||||
description: 'A sample agent to be used as SUT against tck tests.',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:41241/a2a/jsonrpc',
|
||||
protocolBinding: 'JSONRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '0.3.0',
|
||||
},
|
||||
{
|
||||
url: 'http://localhost:41241/a2a/rest',
|
||||
protocolBinding: 'REST',
|
||||
tenant: '',
|
||||
protocolVersion: '0.3.0',
|
||||
},
|
||||
{
|
||||
url: 'http://localhost:41242',
|
||||
protocolBinding: 'GRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '0.3.0',
|
||||
},
|
||||
],
|
||||
// Main URL points to JSON-RPC endpoint (preferred transport)
|
||||
url: 'http://localhost:41241/a2a/jsonrpc',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples',
|
||||
url: 'https://example.com/a2a-samples', // Added provider URL
|
||||
},
|
||||
documentationUrl: 'https://example.com/docs',
|
||||
securitySchemes: {},
|
||||
signatures: [],
|
||||
securityRequirements: [],
|
||||
version: '1.0.0',
|
||||
version: '1.0.0', // Incremented version
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: false,
|
||||
extensions: [],
|
||||
extendedAgentCard: false,
|
||||
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
|
||||
@ -223,9 +177,16 @@ const SUTAgentCard: AgentCard = {
|
||||
examples: ['hi', 'hello world', 'how are you', 'goodbye'],
|
||||
inputModes: ['text'], // Explicitly defining for skill
|
||||
outputModes: ['text', 'task-status'], // Explicitly defining for skill
|
||||
securityRequirements: [],
|
||||
},
|
||||
],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
preferredTransport: 'JSONRPC',
|
||||
// All supported transports (including preferred)
|
||||
additionalInterfaces: [
|
||||
{ url: 'http://localhost:41241/a2a/jsonrpc', transport: 'JSONRPC' },
|
||||
{ url: 'http://localhost:41241/a2a/rest', transport: 'HTTP+JSON' },
|
||||
{ url: 'http://localhost:41242', transport: 'GRPC' },
|
||||
],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
|
||||
@ -1,35 +1,25 @@
|
||||
import { describe, it, beforeEach, expect, vi, Mock } from 'vitest';
|
||||
import { DefaultAgentCardResolver } from '../../src/client/card-resolver.js';
|
||||
import { AgentCard } from '../../src/index.js';
|
||||
import { AgentCard } from '../../src/types.js';
|
||||
import { AgentCard as PBAgentCard } from '../../src/types/pb/a2a_types.js';
|
||||
|
||||
describe('DefaultAgentCardResolver', () => {
|
||||
let mockFetch: Mock;
|
||||
|
||||
const testAgentCard: AgentCard = {
|
||||
protocolVersion: '0.3.0',
|
||||
name: 'Test Agent',
|
||||
description: 'An agent for testing purposes',
|
||||
url: 'http://localhost:8080',
|
||||
preferredTransport: 'JSONRPC',
|
||||
version: '1.0.0',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:8080',
|
||||
protocolBinding: 'JSONRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
},
|
||||
],
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: true,
|
||||
extensions: [],
|
||||
},
|
||||
defaultInputModes: ['text/plain'],
|
||||
defaultOutputModes: ['text/plain'],
|
||||
skills: [],
|
||||
documentationUrl: 'http://test-agent.com/docs',
|
||||
securityRequirements: [],
|
||||
securitySchemes: {},
|
||||
signatures: [],
|
||||
provider: { url: '', organization: '' },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
@ -147,4 +137,134 @@ describe('DefaultAgentCardResolver', () => {
|
||||
expect(e.message).to.include('Failed to fetch Agent Card from https://example.com');
|
||||
}
|
||||
});
|
||||
|
||||
const expectedAgentCard: AgentCard = {
|
||||
protocolVersion: '0.3.0',
|
||||
name: 'Unified Agent',
|
||||
description: '',
|
||||
documentationUrl: undefined,
|
||||
version: '1.0.0',
|
||||
capabilities: {},
|
||||
additionalInterfaces: [],
|
||||
provider: undefined,
|
||||
defaultInputModes: [],
|
||||
defaultOutputModes: [],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
signatures: [],
|
||||
url: 'https://unified-agent.example.com/a2a/v1',
|
||||
preferredTransport: 'GRPC',
|
||||
securitySchemes: {
|
||||
google: {
|
||||
type: 'openIdConnect',
|
||||
openIdConnectUrl: 'https://accounts.google.com/.well-known/openid-configuration',
|
||||
},
|
||||
},
|
||||
security: [{ google: ['openid', 'profile', 'email'] }],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
const JsonSchemaAgentCard: AgentCard = {
|
||||
// A JSON Schema shape is essentially identical to the internal format
|
||||
...expectedAgentCard,
|
||||
};
|
||||
|
||||
const ProtoAgentCard: PBAgentCard = {
|
||||
protocolVersion: '0.3.0',
|
||||
name: 'Unified Agent',
|
||||
description: '',
|
||||
documentationUrl: '',
|
||||
version: '1.0.0',
|
||||
capabilities: undefined,
|
||||
additionalInterfaces: [],
|
||||
provider: undefined,
|
||||
defaultInputModes: [],
|
||||
defaultOutputModes: [],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
signatures: [],
|
||||
url: 'https://unified-agent.example.com/a2a/v1',
|
||||
preferredTransport: 'GRPC',
|
||||
securitySchemes: {
|
||||
google: {
|
||||
scheme: {
|
||||
$case: 'openIdConnectSecurityScheme',
|
||||
value: {
|
||||
description: '',
|
||||
openIdConnectUrl: 'https://accounts.google.com/.well-known/openid-configuration',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
security: [
|
||||
{
|
||||
schemes: {
|
||||
google: { list: ['openid', 'profile', 'email'] },
|
||||
},
|
||||
},
|
||||
],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
const expectedAgentCardWithSkill: AgentCard = {
|
||||
...expectedAgentCard,
|
||||
security: [],
|
||||
securitySchemes: {},
|
||||
skills: [
|
||||
{
|
||||
id: 'test-skill',
|
||||
name: 'Test Skill',
|
||||
description: 'A skill for testing',
|
||||
tags: [],
|
||||
examples: [],
|
||||
inputModes: [],
|
||||
outputModes: [],
|
||||
security: [{ google: ['openid'] }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const ProtoAgentCardWithSkill: PBAgentCard = {
|
||||
...ProtoAgentCard,
|
||||
security: [],
|
||||
securitySchemes: {},
|
||||
skills: [
|
||||
{
|
||||
id: 'test-skill',
|
||||
name: 'Test Skill',
|
||||
description: 'A skill for testing',
|
||||
tags: [],
|
||||
examples: [],
|
||||
inputModes: [],
|
||||
outputModes: [],
|
||||
security: [
|
||||
{
|
||||
schemes: {
|
||||
google: { list: ['openid'] },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it.each([
|
||||
['JSON schema', JsonSchemaAgentCard, expectedAgentCard],
|
||||
['protobuf', PBAgentCard.toJSON(ProtoAgentCard), expectedAgentCard],
|
||||
[
|
||||
'protobuf (skills only)',
|
||||
PBAgentCard.toJSON(ProtoAgentCardWithSkill),
|
||||
expectedAgentCardWithSkill,
|
||||
],
|
||||
])('should parse and normalize %s agent card correctly', async (_, payload, expectedResult) => {
|
||||
const resolver = new DefaultAgentCardResolver({ fetchImpl: mockFetch });
|
||||
mockFetch.mockResolvedValue(new Response(JSON.stringify(payload), { status: 200 }));
|
||||
|
||||
const actual = await resolver.resolve('https://example.com');
|
||||
|
||||
// Both should normalize to the exact same internal AgentCard format
|
||||
// Strip undefined properties before comparison using JSON
|
||||
const expected = JSON.parse(JSON.stringify(expectedResult));
|
||||
const actualClean = JSON.parse(JSON.stringify(actual));
|
||||
|
||||
expect(actualClean).to.deep.equal(expected);
|
||||
});
|
||||
});
|
||||
|
||||
755
test/client/client.spec.ts
Normal file
755
test/client/client.spec.ts
Normal file
@ -0,0 +1,755 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi, Mock } from 'vitest';
|
||||
import { A2AClient } from '../../src/client/client.js';
|
||||
import {
|
||||
MessageSendParams,
|
||||
TextPart,
|
||||
SendMessageResponse,
|
||||
SendMessageSuccessResponse,
|
||||
ListTaskPushNotificationConfigResponse,
|
||||
ListTaskPushNotificationConfigSuccessResponse,
|
||||
DeleteTaskPushNotificationConfigResponse,
|
||||
DeleteTaskPushNotificationConfigSuccessResponse,
|
||||
JSONRPCErrorResponse,
|
||||
JSONRPCResponse,
|
||||
} from '../../src/types.js';
|
||||
import { AGENT_CARD_PATH } from '../../src/constants.js';
|
||||
import {
|
||||
extractRequestId,
|
||||
createResponse,
|
||||
createAgentCardResponse,
|
||||
createMockAgentCard,
|
||||
createMockFetch,
|
||||
} from './util.js';
|
||||
|
||||
// Helper functions to check if responses are success responses
|
||||
function isSuccessResponse(response: SendMessageResponse): response is SendMessageSuccessResponse {
|
||||
return 'result' in response;
|
||||
}
|
||||
|
||||
function isListConfigSuccessResponse(
|
||||
response: ListTaskPushNotificationConfigResponse
|
||||
): response is ListTaskPushNotificationConfigSuccessResponse {
|
||||
return 'result' in response;
|
||||
}
|
||||
|
||||
function isDeleteConfigSuccessResponse(
|
||||
response: DeleteTaskPushNotificationConfigResponse
|
||||
): response is DeleteTaskPushNotificationConfigSuccessResponse {
|
||||
return 'result' in response;
|
||||
}
|
||||
|
||||
function isErrorResponse(response: any): response is JSONRPCErrorResponse {
|
||||
return 'error' in response;
|
||||
}
|
||||
|
||||
describe('A2AClient Basic Tests', () => {
|
||||
let client: A2AClient;
|
||||
let mockFetch: Mock & { capturedAuthHeaders: string[] };
|
||||
let originalConsoleError: typeof console.error;
|
||||
const agentCardUrl = `https://test-agent.example.com/${AGENT_CARD_PATH}`;
|
||||
const agentBaseUrl = 'https://test-agent.example.com';
|
||||
|
||||
beforeEach(async () => {
|
||||
// Suppress console.error during tests to avoid noise
|
||||
originalConsoleError = console.error;
|
||||
console.error = () => {};
|
||||
|
||||
// Create a fresh mock fetch for each test
|
||||
mockFetch = createMockFetch();
|
||||
client = await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: mockFetch,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore console.error
|
||||
console.error = originalConsoleError;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('Client Initialization', () => {
|
||||
it('should initialize client with default options', async () => {
|
||||
// Use a mock fetch to avoid real HTTP requests during testing
|
||||
const mockFetchForDefault = createMockFetch();
|
||||
const basicClient = await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: mockFetchForDefault,
|
||||
});
|
||||
expect(basicClient).to.be.instanceOf(A2AClient);
|
||||
});
|
||||
|
||||
it('should initialize client with custom fetch implementation', async () => {
|
||||
const customFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValue(new Response(JSON.stringify(createMockAgentCard()), { status: 200 }));
|
||||
const clientWithCustomFetch = await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: customFetch,
|
||||
});
|
||||
expect(clientWithCustomFetch).to.be.instanceOf(A2AClient);
|
||||
});
|
||||
|
||||
it('should throw an error if no fetch implementation is available', async () => {
|
||||
const originalFetch = global.fetch;
|
||||
const expectedErrorMsg =
|
||||
'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`.';
|
||||
|
||||
let caughtError: Error | undefined;
|
||||
try {
|
||||
// Arrange: Ensure no global fetch is defined for this test
|
||||
global.fetch = undefined;
|
||||
|
||||
// Act: Instantiate the client without providing a custom fetch implementation.
|
||||
// The constructor kicks off an async operation that will fail.
|
||||
const clientWithoutFetch = new A2AClient('https://test-agent.example.com');
|
||||
// Assert: Check that any method relying on the agent card fetch rejects with the expected error.
|
||||
await clientWithoutFetch.getAgentCard();
|
||||
expect.fail('Expected an error to be thrown but it was not.');
|
||||
} catch (error) {
|
||||
caughtError = error as Error;
|
||||
} finally {
|
||||
// Cleanup to not affect other tests
|
||||
global.fetch = originalFetch;
|
||||
}
|
||||
expect(caughtError).to.be.instanceOf(Error);
|
||||
expect(caughtError?.message).to.equal(expectedErrorMsg);
|
||||
});
|
||||
|
||||
it('should fetch agent card during initialization', async () => {
|
||||
// Wait for agent card to be fetched
|
||||
await client.getAgentCard();
|
||||
|
||||
expect(mockFetch.mock.calls.length).to.be.greaterThan(0);
|
||||
const agentCardCall = mockFetch.mock.calls.find((args) =>
|
||||
(args[0] as string).includes(AGENT_CARD_PATH)
|
||||
);
|
||||
expect(agentCardCall).to.exist;
|
||||
});
|
||||
});
|
||||
|
||||
describe('Backward Compatibility', () => {
|
||||
it('should construct with a URL and log a warning', async () => {
|
||||
const consoleWarnSpy = vi.spyOn(console, 'warn');
|
||||
const backwardCompatibleClient = new A2AClient(agentBaseUrl, {
|
||||
fetchImpl: mockFetch,
|
||||
});
|
||||
|
||||
expect(consoleWarnSpy).toHaveBeenCalledExactlyOnceWith(
|
||||
'Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead.'
|
||||
);
|
||||
|
||||
const agentCard = await backwardCompatibleClient.getAgentCard();
|
||||
expect(agentCard).to.have.property('name', 'Test Agent');
|
||||
|
||||
consoleWarnSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Agent Card Handling', () => {
|
||||
it('should fetch and parse agent card correctly', async () => {
|
||||
const agentCard = await client.getAgentCard();
|
||||
|
||||
expect(agentCard).to.have.property('name', 'Test Agent');
|
||||
expect(agentCard).to.have.property('description', 'A test agent for basic client testing');
|
||||
expect(agentCard).to.have.property('url', 'https://test-agent.example.com/api');
|
||||
expect(agentCard).to.have.property('capabilities');
|
||||
expect(agentCard.capabilities).to.have.property('streaming', true);
|
||||
expect(agentCard.capabilities).to.have.property('pushNotifications', true);
|
||||
});
|
||||
|
||||
it('should cache agent card for subsequent requests', async () => {
|
||||
// First call
|
||||
await client.getAgentCard();
|
||||
|
||||
// Second call - should not fetch agent card again
|
||||
await client.getAgentCard();
|
||||
|
||||
const agentCardCalls = mockFetch.mock.calls.filter((args) =>
|
||||
(args[0] as string).includes(AGENT_CARD_PATH)
|
||||
);
|
||||
|
||||
expect(agentCardCalls).to.have.length(1);
|
||||
});
|
||||
|
||||
it('should handle agent card fetch errors', async () => {
|
||||
const errorFetch = vi.fn().mockImplementation(async (url: string) => {
|
||||
if (url.includes(AGENT_CARD_PATH)) {
|
||||
return new Response('Not found', { status: 404 });
|
||||
}
|
||||
return new Response('Not found', { status: 404 });
|
||||
});
|
||||
|
||||
// Create client after setting up the mock to avoid console.error during construction
|
||||
try {
|
||||
await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: errorFetch,
|
||||
});
|
||||
expect.fail('Expected error to be thrown');
|
||||
} catch (error) {
|
||||
expect(error).to.be.instanceOf(Error);
|
||||
expect((error as Error).message).to.include('Failed to fetch Agent Card');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Message Sending', () => {
|
||||
it('should send message successfully', async () => {
|
||||
const messageParams: MessageSendParams = {
|
||||
message: {
|
||||
kind: 'message',
|
||||
messageId: 'test-msg-1',
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
kind: 'text',
|
||||
text: 'Hello, agent!',
|
||||
} as TextPart,
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const result = await client.sendMessage(messageParams);
|
||||
|
||||
// Verify fetch was called
|
||||
expect(mockFetch.mock.calls.length).to.be.greaterThan(0);
|
||||
|
||||
// Verify RPC call was made
|
||||
const rpcCall = mockFetch.mock.calls.find((args) => (args[0] as string).includes('/api'));
|
||||
expect(rpcCall).to.exist;
|
||||
expect(rpcCall[1]).to.deep.include({
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
expect(rpcCall[1].body).to.include('"method":"message/send"');
|
||||
|
||||
// Verify the result
|
||||
expect(isSuccessResponse(result)).to.be.true;
|
||||
if (isSuccessResponse(result)) {
|
||||
expect(result.result).to.have.property('kind', 'message');
|
||||
expect(result.result).to.have.property('messageId', 'msg-123');
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle message sending errors', async () => {
|
||||
const errorFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
|
||||
if (url.includes(AGENT_CARD_PATH)) {
|
||||
const mockAgentCard = createMockAgentCard({
|
||||
description: 'A test agent for error testing',
|
||||
});
|
||||
return createAgentCardResponse(mockAgentCard);
|
||||
}
|
||||
|
||||
if (url.includes('/api')) {
|
||||
// Extract request ID from the request body
|
||||
const requestId = extractRequestId(options);
|
||||
|
||||
return createResponse(
|
||||
requestId,
|
||||
undefined,
|
||||
{
|
||||
code: -32603,
|
||||
message: 'Internal error',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
|
||||
return new Response('Not found', { status: 404 });
|
||||
});
|
||||
|
||||
const errorClient = await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: errorFetch,
|
||||
});
|
||||
|
||||
const messageParams: MessageSendParams = {
|
||||
message: {
|
||||
kind: 'message',
|
||||
messageId: 'test-msg-error',
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
kind: 'text',
|
||||
text: 'This should fail',
|
||||
} as TextPart,
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
await errorClient.sendMessage(messageParams);
|
||||
expect.fail('Expected error to be thrown');
|
||||
} catch (error) {
|
||||
expect(error).to.be.instanceOf(Error);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('should handle network errors gracefully', async () => {
|
||||
const networkErrorFetch = vi.fn().mockRejectedValue(new Error('Network error'));
|
||||
|
||||
try {
|
||||
await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: networkErrorFetch,
|
||||
});
|
||||
expect.fail('Expected error to be thrown');
|
||||
} catch (error) {
|
||||
expect(error).to.be.instanceOf(Error);
|
||||
expect((error as Error).message).to.include('Network error');
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle malformed JSON responses', async () => {
|
||||
const malformedFetch = vi.fn().mockImplementation(async (url: string) => {
|
||||
if (url.includes(AGENT_CARD_PATH)) {
|
||||
return new Response('Invalid JSON', {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
return new Response('Not found', { status: 404 });
|
||||
});
|
||||
|
||||
try {
|
||||
await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: malformedFetch,
|
||||
});
|
||||
expect.fail('Expected error to be thrown');
|
||||
} catch (error) {
|
||||
expect(error).to.be.instanceOf(Error);
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle missing agent card URL', async () => {
|
||||
const missingUrlFetch = vi.fn().mockImplementation(async (url: string) => {
|
||||
if (url.includes(AGENT_CARD_PATH)) {
|
||||
const invalidAgentCard = {
|
||||
name: 'Test Agent',
|
||||
description: 'A test agent without URL',
|
||||
protocolVersion: '1.0.0',
|
||||
version: '1.0.0',
|
||||
// Missing url field
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text'],
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: true,
|
||||
},
|
||||
skills: [
|
||||
{
|
||||
id: 'test_agent',
|
||||
name: 'Test Agent',
|
||||
description: 'Simulate the general flow of a streaming agent.',
|
||||
tags: ['test'],
|
||||
},
|
||||
],
|
||||
};
|
||||
return createAgentCardResponse(invalidAgentCard);
|
||||
}
|
||||
return new Response('Not found', { status: 404 });
|
||||
});
|
||||
|
||||
try {
|
||||
await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: missingUrlFetch,
|
||||
});
|
||||
expect.fail('Expected error to be thrown');
|
||||
} catch (error) {
|
||||
expect(error).to.be.instanceOf(Error);
|
||||
expect((error as Error).message).to.include("does not contain a valid 'url'");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Static Methods', () => {
|
||||
it('should create a client from an agent card using the constructor', async () => {
|
||||
const mockAgentCard = createMockAgentCard({
|
||||
name: 'Static Agent',
|
||||
description: 'An agent created from a static method',
|
||||
url: 'https://static-agent.example.com/api',
|
||||
});
|
||||
const mockFetchForStatic = createMockFetch();
|
||||
|
||||
const clientFromCard = new A2AClient(mockAgentCard, {
|
||||
fetchImpl: mockFetchForStatic,
|
||||
});
|
||||
|
||||
expect(clientFromCard).to.be.instanceOf(A2AClient);
|
||||
|
||||
// Getting the card should return the provided card without a fetch call
|
||||
const agentCard = await clientFromCard.getAgentCard();
|
||||
expect(agentCard).to.deep.equal(mockAgentCard);
|
||||
expect(mockFetchForStatic.mock.calls.length).to.equal(0);
|
||||
|
||||
// Test sending a message to ensure serviceEndpointUrl is set
|
||||
const messageParams: MessageSendParams = {
|
||||
message: {
|
||||
kind: 'message',
|
||||
messageId: 'test-msg-static',
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
kind: 'text',
|
||||
text: 'Hello, static agent!',
|
||||
} as TextPart,
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const result = await clientFromCard.sendMessage(messageParams);
|
||||
|
||||
// Verify fetch was called for the RPC request
|
||||
expect(mockFetchForStatic.mock.calls.length).to.equal(1);
|
||||
const rpcCall = mockFetchForStatic.mock.calls[0];
|
||||
expect(rpcCall[0]).to.equal('https://static-agent.example.com/api');
|
||||
expect(isSuccessResponse(result)).to.be.true;
|
||||
});
|
||||
|
||||
it('should throw an error if agent card is missing url in constructor', () => {
|
||||
const mockAgentCard = {
|
||||
name: 'Test Agent',
|
||||
description: 'A test agent without URL',
|
||||
protocolVersion: '1.0.0',
|
||||
version: '1.0.0',
|
||||
// Missing url field
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text'],
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: true,
|
||||
},
|
||||
skills: [
|
||||
{
|
||||
id: 'test_agent',
|
||||
name: 'Test Agent',
|
||||
description: 'Simulate the general flow of a streaming agent.',
|
||||
tags: ['test'],
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(() => new A2AClient(mockAgentCard as any)).to.throw(
|
||||
"Provided Agent Card does not contain a valid 'url' for the service endpoint."
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Extension Methods', () => {
|
||||
let mockFetch: Mock & { capturedAuthHeaders: string[] };
|
||||
let originalConsoleError: typeof console.error;
|
||||
const agentCardUrl = `https://test-agent.example.com/${AGENT_CARD_PATH}`;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Suppress console.error during tests to avoid noise
|
||||
originalConsoleError = console.error;
|
||||
console.error = () => {};
|
||||
|
||||
// Create a fresh mock fetch for each test
|
||||
mockFetch = createMockFetch();
|
||||
await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: mockFetch,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore console.error
|
||||
console.error = originalConsoleError;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('callExtensionMethod', () => {
|
||||
it('should call a custom extension method successfully', async () => {
|
||||
// Define a custom extension method name
|
||||
const extensionMethod = 'custom/extension/method';
|
||||
|
||||
// Define custom params for the extension method
|
||||
interface CustomExtensionParams {
|
||||
query: string;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
// Set up custom params for the test
|
||||
const customParams: CustomExtensionParams = {
|
||||
query: 'test query',
|
||||
limit: 5,
|
||||
};
|
||||
|
||||
// Create expected response data
|
||||
const expectedResult = {
|
||||
items: [
|
||||
{ id: '1', name: 'Item 1' },
|
||||
{ id: '2', name: 'Item 2' },
|
||||
{ id: '3', name: 'Item 3' },
|
||||
],
|
||||
totalCount: 3,
|
||||
};
|
||||
|
||||
// Setup custom fetch mock for this specific test
|
||||
const customFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
|
||||
if (url.includes(AGENT_CARD_PATH)) {
|
||||
return createAgentCardResponse(createMockAgentCard());
|
||||
}
|
||||
|
||||
if (url.includes('/api')) {
|
||||
const requestId = extractRequestId(options);
|
||||
const requestBody = JSON.parse(options?.body as string);
|
||||
|
||||
// Verify the request was made correctly
|
||||
expect(requestBody.method).to.equal(extensionMethod);
|
||||
expect(requestBody.params).to.deep.equal(customParams);
|
||||
|
||||
// Return the expected result
|
||||
return createResponse(requestId, expectedResult);
|
||||
}
|
||||
|
||||
return new Response('Not found', { status: 404 });
|
||||
});
|
||||
|
||||
// Create a client with our custom fetch
|
||||
const extensionClient = new A2AClient('https://test-agent.example.com', {
|
||||
fetchImpl: customFetch,
|
||||
});
|
||||
|
||||
// Call the extension method
|
||||
const response = await extensionClient.callExtensionMethod<
|
||||
CustomExtensionParams,
|
||||
JSONRPCResponse
|
||||
>(extensionMethod, customParams);
|
||||
|
||||
expect(response).to.have.property('result');
|
||||
|
||||
// Check if we got a success response
|
||||
if ('result' in response) {
|
||||
const expectedResponseResult = {
|
||||
items: [
|
||||
{ id: '1', name: 'Item 1' },
|
||||
{ id: '2', name: 'Item 2' },
|
||||
{ id: '3', name: 'Item 3' },
|
||||
],
|
||||
totalCount: 3,
|
||||
};
|
||||
|
||||
expect(response.result).to.deep.equal(expectedResponseResult);
|
||||
} else {
|
||||
expect.fail('Expected success response but got error response');
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle errors from extension methods', async () => {
|
||||
// Define a custom extension method name
|
||||
const extensionMethod = 'custom/failing/method';
|
||||
|
||||
// Define custom params for the extension method
|
||||
const customParams = {
|
||||
invalid: true,
|
||||
};
|
||||
|
||||
// Setup custom fetch mock for this specific test
|
||||
const errorFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
|
||||
if (url.includes(AGENT_CARD_PATH)) {
|
||||
return createAgentCardResponse(createMockAgentCard());
|
||||
}
|
||||
|
||||
if (url.includes('/api')) {
|
||||
const requestId = extractRequestId(options);
|
||||
|
||||
// Return an error response
|
||||
return createResponse(
|
||||
requestId,
|
||||
undefined,
|
||||
{
|
||||
code: -32603,
|
||||
message: 'Extension method error: Invalid parameters',
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
|
||||
return new Response('Not found', { status: 404 });
|
||||
});
|
||||
|
||||
// Create a client with our error fetch
|
||||
const errorClient = new A2AClient('https://test-agent.example.com', {
|
||||
fetchImpl: errorFetch,
|
||||
});
|
||||
|
||||
// Define the error we expect to get from the server
|
||||
const expectedError = {
|
||||
code: -32603,
|
||||
message: 'Extension method error: Invalid parameters',
|
||||
};
|
||||
|
||||
const response = await errorClient.callExtensionMethod(extensionMethod, customParams);
|
||||
|
||||
// Check that we got a JSON-RPC error response
|
||||
expect(isErrorResponse(response)).to.be.true;
|
||||
if (isErrorResponse(response)) {
|
||||
// Verify the error details match what we expect
|
||||
expect(response.error.code).to.equal(expectedError.code);
|
||||
expect(response.error.message).to.equal(expectedError.message);
|
||||
} else {
|
||||
expect.fail('Expected JSON-RPC error response but got success response');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Push Notification Config Operations', () => {
|
||||
let originalConsoleError: typeof console.error;
|
||||
|
||||
beforeEach(() => {
|
||||
// Suppress console.error during tests to avoid noise
|
||||
originalConsoleError = console.error;
|
||||
console.error = () => {};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore console.error
|
||||
console.error = originalConsoleError;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('listTaskPushNotificationConfig', () => {
|
||||
it('should list push notification configurations successfully', async () => {
|
||||
// Define mock params
|
||||
const params = {
|
||||
id: 'test-task-123',
|
||||
};
|
||||
|
||||
// Define mock response data for the push notification configs
|
||||
const mockConfigsData = [
|
||||
{
|
||||
id: 'config-1',
|
||||
url: 'https://notify1.example.com/webhook',
|
||||
token: 'token-1',
|
||||
},
|
||||
{
|
||||
id: 'config-2',
|
||||
url: 'https://notify2.example.com/webhook',
|
||||
token: 'token-2',
|
||||
},
|
||||
];
|
||||
|
||||
// Setup custom mock fetch for this specific test
|
||||
const customFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
|
||||
if (url.includes(AGENT_CARD_PATH)) {
|
||||
const mockAgentCard = createMockAgentCard({
|
||||
capabilities: { pushNotifications: true },
|
||||
});
|
||||
return createAgentCardResponse(mockAgentCard);
|
||||
}
|
||||
|
||||
if (url.includes('/api')) {
|
||||
const requestId = extractRequestId(options);
|
||||
|
||||
// Check if the request is for the list operation
|
||||
const body = JSON.parse(options?.body as string);
|
||||
if (body.method === 'tasks/pushNotificationConfig/list') {
|
||||
// Verify the params were sent correctly
|
||||
expect(body.params).to.deep.equal(params);
|
||||
|
||||
// Return a successful response with mock configs
|
||||
// The result is an array of TaskPushNotificationConfig objects
|
||||
const configs = mockConfigsData.map((config) => ({
|
||||
taskId: params.id,
|
||||
pushNotificationConfig: config,
|
||||
}));
|
||||
return createResponse(requestId, configs);
|
||||
}
|
||||
}
|
||||
|
||||
return new Response('Not found', { status: 404 });
|
||||
});
|
||||
|
||||
// Use the custom fetch implementation for this test
|
||||
const testClient = new A2AClient('https://test-agent.example.com', {
|
||||
fetchImpl: customFetch,
|
||||
});
|
||||
|
||||
// Call the method and verify the result
|
||||
const result = await testClient.listTaskPushNotificationConfig(params);
|
||||
|
||||
// Verify the result is a success response
|
||||
expect(isListConfigSuccessResponse(result)).to.be.true;
|
||||
if (isListConfigSuccessResponse(result)) {
|
||||
// Define expected result structure
|
||||
const expectedConfigs = [
|
||||
{
|
||||
taskId: params.id,
|
||||
pushNotificationConfig: {
|
||||
id: 'config-1',
|
||||
url: 'https://notify1.example.com/webhook',
|
||||
token: 'token-1',
|
||||
},
|
||||
},
|
||||
{
|
||||
taskId: params.id,
|
||||
pushNotificationConfig: {
|
||||
id: 'config-2',
|
||||
url: 'https://notify2.example.com/webhook',
|
||||
token: 'token-2',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Use deep.equal for more readable assertion
|
||||
expect(result.result).to.deep.equal(expectedConfigs);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteTaskPushNotificationConfig', () => {
|
||||
it('should delete push notification configuration successfully', async () => {
|
||||
// Define mock params
|
||||
const params = {
|
||||
id: 'test-task-123',
|
||||
pushNotificationConfigId: 'config-to-delete',
|
||||
};
|
||||
|
||||
// Setup custom mock fetch for this specific test
|
||||
const customFetch = vi.fn().mockImplementation(async (url: string, options?: RequestInit) => {
|
||||
if (url.includes(AGENT_CARD_PATH)) {
|
||||
const mockAgentCard = createMockAgentCard({
|
||||
capabilities: { pushNotifications: true },
|
||||
});
|
||||
return createAgentCardResponse(mockAgentCard);
|
||||
}
|
||||
|
||||
if (url.includes('/api')) {
|
||||
const requestId = extractRequestId(options);
|
||||
|
||||
// Check if the request is for the delete operation
|
||||
const body = JSON.parse(options?.body as string);
|
||||
if (body.method === 'tasks/pushNotificationConfig/delete') {
|
||||
// Verify the params were sent correctly
|
||||
expect(body.params).to.deep.equal(params);
|
||||
|
||||
// Return a successful response,
|
||||
// 'result' should just be 'null' according to the spec:
|
||||
// https://a2a-protocol.org/latest/specification/#79-taskspushnotificationconfigdelete
|
||||
return createResponse(requestId, null);
|
||||
}
|
||||
}
|
||||
|
||||
return new Response('Not found', { status: 404 });
|
||||
});
|
||||
|
||||
// Use the custom fetch implementation for this test
|
||||
const testClient = new A2AClient('https://test-agent.example.com', {
|
||||
fetchImpl: customFetch,
|
||||
});
|
||||
|
||||
// Call the method and verify the result
|
||||
const result = await testClient.deleteTaskPushNotificationConfig(params);
|
||||
|
||||
// Verify the result is a success response
|
||||
expect(isDeleteConfigSuccessResponse(result)).to.be.true;
|
||||
if (isDeleteConfigSuccessResponse(result)) {
|
||||
expect(result.result).to.be.null;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -1,10 +1,12 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi, type Mock } from 'vitest';
|
||||
import { JsonRpcTransport } from '../../src/client/transports/json_rpc_transport.js';
|
||||
import { A2AClient } from '../../src/client/client.js';
|
||||
import {
|
||||
AuthenticationHandler,
|
||||
HttpHeaders,
|
||||
createAuthenticatingFetchWithRetry,
|
||||
} from '../../src/client/auth-handler.js';
|
||||
import { SendMessageResponse, SendMessageSuccessResponse } from '../../src/types.js';
|
||||
import { AGENT_CARD_PATH } from '../../src/constants.js';
|
||||
import { createMessageParams, createMockFetch } from './util.js';
|
||||
|
||||
// Challenge manager class for authentication testing
|
||||
@ -67,11 +69,17 @@ class MockAuthHandler implements AuthenticationHandler {
|
||||
}
|
||||
}
|
||||
|
||||
describe('JsonRpcTransport Authentication Tests', () => {
|
||||
let client: JsonRpcTransport;
|
||||
// Helper function to check if response is a success response
|
||||
function isSuccessResponse(response: SendMessageResponse): response is SendMessageSuccessResponse {
|
||||
return 'result' in response;
|
||||
}
|
||||
|
||||
describe('A2AClient Authentication Tests', () => {
|
||||
let client: A2AClient;
|
||||
let authHandler: MockAuthHandler;
|
||||
let mockFetch: Mock & { capturedAuthHeaders: string[] };
|
||||
let originalConsoleError: typeof console.error;
|
||||
const agentCardUrl = `https://test-agent.example.com/${AGENT_CARD_PATH}`;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Suppress console.error during tests to avoid noise
|
||||
@ -92,8 +100,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
authHandler = new MockAuthHandler();
|
||||
// Use AuthHandlingFetch to wrap the mock fetch with authentication handling
|
||||
const authHandlingFetch = createAuthenticatingFetchWithRetry(mockFetch, authHandler);
|
||||
client = new JsonRpcTransport({
|
||||
endpoint: 'https://test-agent.example.com/api',
|
||||
client = await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: authHandlingFetch,
|
||||
});
|
||||
});
|
||||
@ -112,41 +119,49 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
});
|
||||
|
||||
// This should trigger the authentication flow
|
||||
const result = await client.sendMessage(messageParams.request);
|
||||
const result = await client.sendMessage(messageParams);
|
||||
|
||||
// Verify fetch was called multiple times
|
||||
expect(mockFetch.mock.calls.length).to.equal(2);
|
||||
expect(mockFetch.mock.calls.length).to.equal(3);
|
||||
|
||||
// First call: RPC request without auth header
|
||||
expect(mockFetch.mock.calls[0][0]).to.equal('https://test-agent.example.com/api');
|
||||
// First call: agent card fetch
|
||||
expect(mockFetch.mock.calls[0][0]).to.equal(agentCardUrl);
|
||||
expect(mockFetch.mock.calls[0][1]).to.deep.include({
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
|
||||
// Second call: RPC request without auth header
|
||||
expect(mockFetch.mock.calls[1][0]).to.equal('https://test-agent.example.com/api');
|
||||
expect(mockFetch.mock.calls[1][1]).to.deep.include({
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
expect(mockFetch.mock.calls[0][1].body).to.include('"method":"SendMessage"');
|
||||
expect(mockFetch.mock.calls[1][1].body).to.include('"method":"message/send"');
|
||||
|
||||
// Second call: RPC request with auth header
|
||||
expect(mockFetch.mock.calls[1][0]).to.equal('https://test-agent.example.com/api');
|
||||
expect(mockFetch.mock.calls[1][1]).to.deep.include({
|
||||
// Third call: RPC request with auth header
|
||||
expect(mockFetch.mock.calls[2][0]).to.equal('https://test-agent.example.com/api');
|
||||
expect(mockFetch.mock.calls[2][1]).to.deep.include({
|
||||
method: 'POST',
|
||||
});
|
||||
// Check headers separately to avoid issues with Authorization header
|
||||
expect(mockFetch.mock.calls[1][1].headers).to.have.property(
|
||||
expect(mockFetch.mock.calls[2][1].headers).to.have.property(
|
||||
'Content-Type',
|
||||
'application/json'
|
||||
);
|
||||
expect(mockFetch.mock.calls[1][1].headers).to.have.property('Accept', 'application/json');
|
||||
expect(mockFetch.mock.calls[1][1].headers).to.have.property('Authorization');
|
||||
expect(mockFetch.mock.calls[2][1].headers).to.have.property('Accept', 'application/json');
|
||||
expect(mockFetch.mock.calls[2][1].headers).to.have.property('Authorization');
|
||||
|
||||
expect(mockFetch.mock.calls[1][1].headers['Authorization']).to.match(/^Bearer .+$/);
|
||||
expect(mockFetch.mock.calls[1][1].body).to.include('"method":"SendMessage"');
|
||||
expect(mockFetch.mock.calls[2][1].headers['Authorization']).to.match(/^Bearer .+$/);
|
||||
expect(mockFetch.mock.calls[2][1].body).to.include('"method":"message/send"');
|
||||
|
||||
// Verify the result
|
||||
expect(result).to.exist;
|
||||
expect(result).to.have.property('messageId', 'msg-123');
|
||||
expect(isSuccessResponse(result)).to.be.true;
|
||||
if (isSuccessResponse(result)) {
|
||||
expect(result.result).to.have.property('kind', 'message');
|
||||
}
|
||||
});
|
||||
|
||||
it('should reuse authentication token for subsequent requests', async () => {
|
||||
@ -156,7 +171,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
});
|
||||
|
||||
// First request - should trigger auth flow
|
||||
await client.sendMessage(messageParams.request);
|
||||
await client.sendMessage(messageParams);
|
||||
|
||||
// Capture the token from the first request
|
||||
const firstRequestAuthCall = mockFetch.mock.calls.find(
|
||||
@ -165,13 +180,13 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
const firstRequestToken = firstRequestAuthCall?.[1]?.headers?.['Authorization'];
|
||||
|
||||
// Second request - should use existing token
|
||||
const result2 = await client.sendMessage(messageParams.request);
|
||||
const result2 = await client.sendMessage(messageParams);
|
||||
|
||||
// Total calls should be 3: 2 for first request + 1 for second request (auth token cached)
|
||||
expect(mockFetch.mock.calls.length).to.equal(3);
|
||||
// Total calls should be 4: 3 for first request + 1 for second request (both agent card and auth token cached)
|
||||
expect(mockFetch.mock.calls.length).to.equal(4);
|
||||
|
||||
// Second request should start from call #3 (after the first 2 calls)
|
||||
const secondRequestCalls = mockFetch.mock.calls.slice(2);
|
||||
// Second request should start from call #4 (after the first 3 calls)
|
||||
const secondRequestCalls = mockFetch.mock.calls.slice(3);
|
||||
|
||||
// Only one call for second request: RPC request with auth header (agent card and token cached)
|
||||
expect(secondRequestCalls[0][0]).to.equal('https://test-agent.example.com/api');
|
||||
@ -180,7 +195,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
// Should use the exact same token from the first request
|
||||
expect(secondRequestCalls[0][1].headers['Authorization']).to.equal(firstRequestToken);
|
||||
|
||||
expect(result2).to.exist;
|
||||
expect(isSuccessResponse(result2)).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
@ -197,7 +212,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
text: 'Test auth handler',
|
||||
});
|
||||
|
||||
await client.sendMessage(messageParams.request);
|
||||
await client.sendMessage(messageParams);
|
||||
|
||||
// Verify auth handler methods were called
|
||||
expect(authHandlerSpy.headers).toHaveBeenCalled();
|
||||
@ -211,8 +226,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
// noRetryHandler.shouldRetryWithHeaders.bind(noRetryHandler);
|
||||
noRetryHandler.shouldRetryWithHeaders = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
const clientNoRetry = new JsonRpcTransport({
|
||||
endpoint: 'https://test-agent.example.com/api',
|
||||
const clientNoRetry = await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: mockFetch,
|
||||
});
|
||||
|
||||
@ -223,7 +237,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
|
||||
// This should fail because we're not retrying with auth
|
||||
try {
|
||||
await clientNoRetry.sendMessage(messageParams.request);
|
||||
await clientNoRetry.sendMessage(messageParams);
|
||||
expect.fail('Expected error to be thrown');
|
||||
} catch (error) {
|
||||
expect(error).to.be.instanceOf(Error);
|
||||
@ -244,8 +258,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
const { capturedAuthHeaders } = authRetryTestFetch;
|
||||
|
||||
const authHandlingFetch = createAuthenticatingFetchWithRetry(authRetryTestFetch, authHandler);
|
||||
const clientAuthTest = new JsonRpcTransport({
|
||||
endpoint: 'https://test-agent.example.com/api',
|
||||
const clientAuthTest = await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: authHandlingFetch,
|
||||
});
|
||||
|
||||
@ -255,7 +268,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
});
|
||||
|
||||
// This should trigger the auth flow and succeed
|
||||
const result = await clientAuthTest.sendMessage(messageParams.request);
|
||||
const result = await clientAuthTest.sendMessage(messageParams);
|
||||
|
||||
// Verify the Authorization headers were sent correctly
|
||||
// With AuthHandlingFetch, the auth handler makes the retry internally, so we see both calls
|
||||
@ -264,7 +277,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
expect(capturedAuthHeaders[1]).to.be.a('string').and.not.be.empty; // Second call: with Authorization header
|
||||
|
||||
// Verify the result
|
||||
expect(result).to.exist;
|
||||
expect(isSuccessResponse(result)).to.be.true;
|
||||
});
|
||||
|
||||
it('should continue without authentication when server does not return 401', async () => {
|
||||
@ -280,8 +293,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
});
|
||||
const { capturedAuthHeaders } = noAuthRequiredFetch;
|
||||
|
||||
const clientNoAuth = new JsonRpcTransport({
|
||||
endpoint: 'https://test-agent.example.com/api',
|
||||
const clientNoAuth = await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: noAuthRequiredFetch,
|
||||
});
|
||||
|
||||
@ -291,17 +303,19 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
});
|
||||
|
||||
// This should succeed without any authentication flow
|
||||
const result = await clientNoAuth.sendMessage(messageParams.request);
|
||||
const result = await clientNoAuth.sendMessage(messageParams);
|
||||
|
||||
// Verify that no Authorization headers were sent
|
||||
expect(capturedAuthHeaders).to.have.length(1);
|
||||
expect(capturedAuthHeaders[0]).to.equal(''); // No auth header sent
|
||||
|
||||
// Verify the result
|
||||
expect(result).to.exist;
|
||||
// Check if result is a Message1 (which has messageId) or Task2
|
||||
if ('messageId' in result) {
|
||||
expect(result.messageId).to.equal('msg-no-auth-required');
|
||||
expect(isSuccessResponse(result)).to.be.true;
|
||||
if (isSuccessResponse(result)) {
|
||||
// Check if result is a Message1 (which has messageId) or Task2
|
||||
if ('messageId' in result.result) {
|
||||
expect(result.result.messageId).to.equal('msg-no-auth-required');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@ -313,8 +327,7 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
});
|
||||
|
||||
// Create client WITHOUT authHandler
|
||||
const clientNoAuthHandler = new JsonRpcTransport({
|
||||
endpoint: 'https://test-agent.example.com/api',
|
||||
const clientNoAuthHandler = await A2AClient.fromCardUrl(agentCardUrl, {
|
||||
fetchImpl: fetchWithApiError,
|
||||
});
|
||||
|
||||
@ -323,18 +336,17 @@ describe('JsonRpcTransport Authentication Tests', () => {
|
||||
text: 'Test without auth handler',
|
||||
});
|
||||
|
||||
// The client should return a TaskNotFoundError (since the error code is -32001) rather than throwing an error directly, but JsonRpcTransport maps it back out to be thrown
|
||||
try {
|
||||
await clientNoAuthHandler.sendMessage(messageParams.request);
|
||||
expect.fail('Expected error to be thrown');
|
||||
} catch (error) {
|
||||
// Verify that the result is a JSON-RPC mapped error
|
||||
expect(error).to.be.instanceOf(Error);
|
||||
expect((error as Error).name).to.equal('TaskNotFoundError');
|
||||
}
|
||||
// The client should return a JSON-RPC error response rather than throwing an error
|
||||
const result = await clientNoAuthHandler.sendMessage(messageParams);
|
||||
|
||||
// Verify that the result is a JSON-RPC error response
|
||||
expect(result).to.have.property('jsonrpc', '2.0');
|
||||
expect(result).to.have.property('error');
|
||||
expect((result as any).error).to.have.property('code', -32001);
|
||||
expect((result as any).error).to.have.property('message', 'Authentication required');
|
||||
|
||||
// Verify that fetch was called only once (no retry attempted)
|
||||
expect(fetchWithApiError.mock.calls.length).to.equal(1); // One for API call
|
||||
expect(fetchWithApiError.mock.calls.length).to.equal(2); // One for agent card, one for API call
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,30 +1,28 @@
|
||||
import { describe, it, beforeEach, expect, vi, Mock } from 'vitest';
|
||||
import { ClientFactory, ClientFactoryOptions } from '../../src/client/factory.js';
|
||||
import { Transport } from '../../src/client/transports/transport.js';
|
||||
import { AgentCard } from '../../src/index.js';
|
||||
import { JsonRpcTransportFactory } from '../../src/client/transports/json_rpc_transport.js';
|
||||
import { AgentCard } from '../../src/types.js';
|
||||
import { Client } from '../../src/client/multitransport-client.js';
|
||||
import { CallInterceptor } from '../../src/client/interceptors.js';
|
||||
|
||||
describe('ClientFactory', () => {
|
||||
let mockTransportFactory1: { protocolName: string; create: Mock };
|
||||
let mockTransportFactory2: { protocolName: string; create: Mock };
|
||||
let mockTransport: Record<Exclude<keyof Transport, 'protocolName'>, Mock> & {
|
||||
protocolName: string;
|
||||
};
|
||||
let mockTransport: Record<keyof Transport, Mock>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockTransport = {
|
||||
getExtendedAgentCard: vi.fn(),
|
||||
sendMessage: vi.fn(),
|
||||
sendMessageStream: vi.fn(),
|
||||
createTaskPushNotificationConfig: vi.fn(),
|
||||
setTaskPushNotificationConfig: vi.fn(),
|
||||
getTaskPushNotificationConfig: vi.fn(),
|
||||
listTaskPushNotificationConfig: vi.fn(),
|
||||
deleteTaskPushNotificationConfig: vi.fn(),
|
||||
getTask: vi.fn(),
|
||||
cancelTask: vi.fn(),
|
||||
resubscribeTask: vi.fn(),
|
||||
protocolName: 'MockTransport',
|
||||
};
|
||||
|
||||
mockTransportFactory1 = {
|
||||
@ -104,30 +102,16 @@ describe('ClientFactory', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
agentCard = {
|
||||
protocolVersion: '0.3.0',
|
||||
name: 'Test Agent',
|
||||
description: 'Test',
|
||||
url: 'http://transport1.com',
|
||||
preferredTransport: 'Transport1',
|
||||
version: '1.0.0',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://transport1.com',
|
||||
protocolBinding: 'Transport1',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
},
|
||||
],
|
||||
capabilities: {
|
||||
extensions: [],
|
||||
streaming: true,
|
||||
pushNotifications: true,
|
||||
},
|
||||
capabilities: {},
|
||||
defaultInputModes: [],
|
||||
defaultOutputModes: [],
|
||||
skills: [],
|
||||
documentationUrl: 'http://test-agent.com/docs',
|
||||
securityRequirements: [],
|
||||
securitySchemes: {},
|
||||
signatures: [],
|
||||
provider: { url: '', organization: '' },
|
||||
};
|
||||
});
|
||||
|
||||
@ -144,12 +128,7 @@ describe('ClientFactory', () => {
|
||||
});
|
||||
|
||||
it('should use factory preferred transport if available', async () => {
|
||||
agentCard.supportedInterfaces.push({
|
||||
url: 'http://transport2.com',
|
||||
protocolBinding: 'Transport2',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
});
|
||||
agentCard.additionalInterfaces = [{ transport: 'Transport2', url: 'http://transport2.com' }];
|
||||
const factory = new ClientFactory({
|
||||
transports: [mockTransportFactory1, mockTransportFactory2],
|
||||
preferredTransports: ['Transport2'],
|
||||
@ -162,14 +141,7 @@ describe('ClientFactory', () => {
|
||||
|
||||
it('should throw error if no compatible transport found', async () => {
|
||||
const factory = new ClientFactory({ transports: [mockTransportFactory1] });
|
||||
agentCard.supportedInterfaces = [
|
||||
{
|
||||
url: 'http://transport2.com',
|
||||
protocolBinding: 'Transport2',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
},
|
||||
];
|
||||
agentCard.preferredTransport = 'Transport2'; // Not supported
|
||||
|
||||
try {
|
||||
await factory.createFromAgentCard(agentCard);
|
||||
@ -190,6 +162,19 @@ describe('ClientFactory', () => {
|
||||
expect(mockTransportFactory1.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should default to JSONRPC transport if agentCard.preferredTransport is undefined', async () => {
|
||||
agentCard.preferredTransport = undefined;
|
||||
const jsonRpcFactory = {
|
||||
protocolName: JsonRpcTransportFactory.name,
|
||||
create: vi.fn().mockResolvedValue(mockTransport),
|
||||
};
|
||||
const factory = new ClientFactory({ transports: [jsonRpcFactory] });
|
||||
|
||||
await factory.createFromAgentCard(agentCard);
|
||||
|
||||
expect(jsonRpcFactory.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should pass clientConfig to the created Client', async () => {
|
||||
const clientConfig = { polling: true };
|
||||
const factory = new ClientFactory({
|
||||
@ -204,14 +189,7 @@ describe('ClientFactory', () => {
|
||||
|
||||
it('should match transport with case-insensitive protocol name', async () => {
|
||||
// Transport factory uses "Transport1" but agent card uses "transport1" (lowercase)
|
||||
agentCard.supportedInterfaces = [
|
||||
{
|
||||
url: 'http://transport1.com',
|
||||
protocolBinding: 'transport1',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
},
|
||||
];
|
||||
agentCard.preferredTransport = 'transport1';
|
||||
const factory = new ClientFactory({ transports: [mockTransportFactory1] });
|
||||
|
||||
const client = await factory.createFromAgentCard(agentCard);
|
||||
@ -228,14 +206,7 @@ describe('ClientFactory', () => {
|
||||
protocolName: 'HTTP+JSON',
|
||||
create: vi.fn().mockResolvedValue(mockTransport),
|
||||
};
|
||||
agentCard.supportedInterfaces = [
|
||||
{
|
||||
url: 'http://transport1.com',
|
||||
protocolBinding: 'http+json',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
},
|
||||
];
|
||||
agentCard.preferredTransport = 'http+json'; // lowercase
|
||||
const factory = new ClientFactory({ transports: [httpJsonFactory] });
|
||||
|
||||
await factory.createFromAgentCard(agentCard);
|
||||
@ -248,14 +219,7 @@ describe('ClientFactory', () => {
|
||||
protocolName: 'JSONRPC',
|
||||
create: vi.fn().mockResolvedValue(mockTransport),
|
||||
};
|
||||
agentCard.supportedInterfaces = [
|
||||
{
|
||||
url: 'http://transport1.com',
|
||||
protocolBinding: 'JsonRpc',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
},
|
||||
];
|
||||
agentCard.preferredTransport = 'JsonRpc'; // mixed case
|
||||
const factory = new ClientFactory({ transports: [jsonRpcFactory] });
|
||||
|
||||
await factory.createFromAgentCard(agentCard);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -4,12 +4,12 @@ import {
|
||||
GrpcTransport,
|
||||
GrpcTransportFactory,
|
||||
} from '../../../src/client/transports/grpc/grpc_transport.js';
|
||||
import { A2AServiceClient } from '../../../src/grpc/pb/a2a.js';
|
||||
import { A2AServiceClient } from '../../../src/grpc/pb/a2a_services.js';
|
||||
import { ToProto } from '../../../src/types/converters/to_proto.js';
|
||||
import { FromProto } from '../../../src/types/converters/from_proto.js';
|
||||
import {
|
||||
TaskNotFoundError,
|
||||
TaskNotCancelableError,
|
||||
RequestMalformedError,
|
||||
PushNotificationNotSupportedError,
|
||||
} from '../../../src/errors.js';
|
||||
import {
|
||||
@ -18,30 +18,40 @@ import {
|
||||
createMockMessage,
|
||||
createMockTask,
|
||||
} from '../util.js';
|
||||
import { TaskState } from '../../../src/index.js';
|
||||
|
||||
// --- Mocks ---
|
||||
|
||||
// Mock the gRPC client class
|
||||
vi.mock('../../../src/grpc/pb/a2a.js', () => {
|
||||
vi.mock('../../../src/grpc/pb/a2a_services.js', () => {
|
||||
const A2AServiceClient = vi.fn();
|
||||
A2AServiceClient.prototype.getExtendedAgentCard = vi.fn();
|
||||
A2AServiceClient.prototype.getAgentCard = vi.fn();
|
||||
A2AServiceClient.prototype.sendMessage = vi.fn();
|
||||
A2AServiceClient.prototype.sendStreamingMessage = vi.fn();
|
||||
A2AServiceClient.prototype.createTaskPushNotificationConfig = vi.fn();
|
||||
A2AServiceClient.prototype.getTaskPushNotificationConfig = vi.fn();
|
||||
A2AServiceClient.prototype.listTaskPushNotificationConfigs = vi.fn();
|
||||
A2AServiceClient.prototype.listTaskPushNotificationConfig = vi.fn();
|
||||
A2AServiceClient.prototype.deleteTaskPushNotificationConfig = vi.fn();
|
||||
A2AServiceClient.prototype.getTask = vi.fn();
|
||||
A2AServiceClient.prototype.cancelTask = vi.fn();
|
||||
A2AServiceClient.prototype.subscribeToTask = vi.fn();
|
||||
A2AServiceClient.prototype.taskSubscription = vi.fn();
|
||||
return { A2AServiceClient };
|
||||
});
|
||||
|
||||
// Mock ToProto and FromProto to act as pass-throughs or return simple objects for testing flow
|
||||
vi.mock('../../../src/types/converters/to_proto.js', () => ({
|
||||
ToProto: {
|
||||
agentCard: vi.fn((x) => x),
|
||||
messageSendParams: vi.fn((x) => x),
|
||||
taskPushNotificationConfig: vi.fn((x) => x),
|
||||
getTaskPushNotificationConfigParams: vi.fn((x) => x),
|
||||
listTaskPushNotificationConfigParams: vi.fn((x) => x),
|
||||
deleteTaskPushNotificationConfigParams: vi.fn((x) => x),
|
||||
getTaskRequest: vi.fn((x) => x),
|
||||
cancelTaskRequest: vi.fn((x) => x),
|
||||
taskIdParams: vi.fn((x) => x),
|
||||
taskPushNotificationConfigCreate: vi.fn((x) => x),
|
||||
taskQueryParams: vi.fn((x) => x),
|
||||
getAgentCardRequest: vi.fn((x) => x),
|
||||
},
|
||||
}));
|
||||
|
||||
@ -50,7 +60,8 @@ vi.mock('../../../src/types/converters/from_proto.js', () => ({
|
||||
agentCard: vi.fn((x) => x),
|
||||
sendMessageResult: vi.fn((x) => x),
|
||||
message: vi.fn((x) => x),
|
||||
getTaskPushNotificationConfig: vi.fn((x) => x),
|
||||
setTaskPushNotificationConfigParams: vi.fn((x) => x),
|
||||
getTaskPushNoticationConfig: vi.fn((x) => x),
|
||||
listTaskPushNotificationConfig: vi.fn((x) => x),
|
||||
task: vi.fn((x) => x),
|
||||
taskStatusUpdate: vi.fn((x) => x),
|
||||
@ -94,21 +105,16 @@ describe('GrpcTransport', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('protocolName', () => {
|
||||
it('should return correct protocol name', () => {
|
||||
expect(transport.protocolName).toBe('GRPC');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getExtendedAgentCard', () => {
|
||||
it('should get agent card successfully', async () => {
|
||||
const mockCard = createMockAgentCard();
|
||||
mockUnarySuccess(mockGrpcClient.getExtendedAgentCard as Mock, mockCard);
|
||||
mockUnarySuccess(mockGrpcClient.getAgentCard as Mock, mockCard);
|
||||
|
||||
const result = await transport.getExtendedAgentCard();
|
||||
|
||||
expect(result).toEqual(mockCard);
|
||||
expect(mockGrpcClient.getExtendedAgentCard).toHaveBeenCalled();
|
||||
expect(mockGrpcClient.getAgentCard).toHaveBeenCalled();
|
||||
expect(FromProto.agentCard).toHaveBeenCalledWith(mockCard);
|
||||
});
|
||||
});
|
||||
|
||||
@ -121,6 +127,7 @@ describe('GrpcTransport', () => {
|
||||
const result = await transport.sendMessage(params);
|
||||
|
||||
expect(result).toEqual(mockResult);
|
||||
expect(ToProto.messageSendParams).toHaveBeenCalledWith(params);
|
||||
expect(mockGrpcClient.sendMessage).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@ -205,7 +212,7 @@ describe('GrpcTransport', () => {
|
||||
(mockGrpcClient.sendStreamingMessage as Mock).mockReturnValue(mockStream);
|
||||
|
||||
const iterator = transport.sendMessageStream(params);
|
||||
await expect(iterator.next()).rejects.toThrow(RequestMalformedError);
|
||||
await expect(iterator.next()).rejects.toThrow('GRPC error for sendStreamingMessage!');
|
||||
});
|
||||
|
||||
it('should cancel stream when signal is aborted', async () => {
|
||||
@ -236,27 +243,26 @@ describe('GrpcTransport', () => {
|
||||
const mockTask = createMockTask(taskId);
|
||||
mockUnarySuccess(mockGrpcClient.getTask as Mock, mockTask);
|
||||
|
||||
const result = await transport.getTask({ id: taskId, tenant: '', historyLength: 0 });
|
||||
const result = await transport.getTask({ id: taskId });
|
||||
|
||||
expect(result).toEqual(mockTask);
|
||||
expect(ToProto.taskQueryParams).toHaveBeenCalled();
|
||||
expect(mockGrpcClient.getTask).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should throw TaskNotFoundError', async () => {
|
||||
mockUnaryError(mockGrpcClient.getTask as Mock, status.NOT_FOUND, 'Not Found');
|
||||
await expect(
|
||||
transport.getTask({ id: 'bad-id', tenant: '', historyLength: 0 })
|
||||
).rejects.toThrow(TaskNotFoundError);
|
||||
await expect(transport.getTask({ id: 'bad-id' })).rejects.toThrow(TaskNotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cancelTask', () => {
|
||||
it('should cancel task successfully', async () => {
|
||||
const taskId = 'task-123';
|
||||
const mockTask = createMockTask(taskId, TaskState.TASK_STATE_CANCELED);
|
||||
const mockTask = createMockTask(taskId, 'canceled');
|
||||
mockUnarySuccess(mockGrpcClient.cancelTask as Mock, mockTask);
|
||||
|
||||
const result = await transport.cancelTask({ id: taskId, tenant: '', metadata: undefined });
|
||||
const result = await transport.cancelTask({ id: taskId });
|
||||
|
||||
expect(result).toEqual(mockTask);
|
||||
expect(mockGrpcClient.cancelTask).toHaveBeenCalled();
|
||||
@ -268,9 +274,9 @@ describe('GrpcTransport', () => {
|
||||
status.FAILED_PRECONDITION,
|
||||
'Cannot cancel'
|
||||
);
|
||||
await expect(
|
||||
transport.cancelTask({ id: 'task-123', tenant: '', metadata: undefined })
|
||||
).rejects.toThrow(TaskNotCancelableError);
|
||||
await expect(transport.cancelTask({ id: 'task-123' })).rejects.toThrow(
|
||||
TaskNotCancelableError
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@ -278,27 +284,15 @@ describe('GrpcTransport', () => {
|
||||
const taskId = 'task-123';
|
||||
const configId = 'config-456';
|
||||
const mockConfig = {
|
||||
name: `tasks/${taskId}/pushNotificationConfigs/${configId}`,
|
||||
pushNotificationConfig: {
|
||||
id: configId,
|
||||
url: 'http://test',
|
||||
token: 'test-token',
|
||||
authentication: { schemes: [] as string[], credentials: '' },
|
||||
},
|
||||
taskId,
|
||||
pushNotificationConfig: { id: configId, url: 'http://test' },
|
||||
};
|
||||
|
||||
describe('createTaskPushNotificationConfig', () => {
|
||||
it('should create config successfully', async () => {
|
||||
describe('setTaskPushNotificationConfig', () => {
|
||||
it('should set config successfully', async () => {
|
||||
mockUnarySuccess(mockGrpcClient.createTaskPushNotificationConfig as Mock, mockConfig);
|
||||
|
||||
const result = await transport.createTaskPushNotificationConfig({
|
||||
tenant: '',
|
||||
id: '',
|
||||
taskId: taskId,
|
||||
url: 'http://test',
|
||||
token: 'test-token',
|
||||
authentication: undefined,
|
||||
});
|
||||
const result = await transport.setTaskPushNotificationConfig(mockConfig);
|
||||
|
||||
expect(result).toEqual(mockConfig);
|
||||
expect(mockGrpcClient.createTaskPushNotificationConfig).toHaveBeenCalled();
|
||||
@ -310,16 +304,9 @@ describe('GrpcTransport', () => {
|
||||
status.UNIMPLEMENTED,
|
||||
'Not supported'
|
||||
);
|
||||
await expect(
|
||||
transport.createTaskPushNotificationConfig({
|
||||
tenant: '',
|
||||
id: '',
|
||||
taskId: taskId,
|
||||
url: 'http://test',
|
||||
token: 'test-token',
|
||||
authentication: undefined,
|
||||
})
|
||||
).rejects.toThrow(PushNotificationNotSupportedError);
|
||||
await expect(transport.setTaskPushNotificationConfig(mockConfig)).rejects.toThrow(
|
||||
PushNotificationNotSupportedError
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@ -328,9 +315,8 @@ describe('GrpcTransport', () => {
|
||||
mockUnarySuccess(mockGrpcClient.getTaskPushNotificationConfig as Mock, mockConfig);
|
||||
|
||||
const result = await transport.getTaskPushNotificationConfig({
|
||||
id: configId,
|
||||
taskId,
|
||||
tenant: '',
|
||||
id: taskId,
|
||||
pushNotificationConfigId: configId,
|
||||
});
|
||||
|
||||
expect(result).toEqual(mockConfig);
|
||||
@ -340,14 +326,9 @@ describe('GrpcTransport', () => {
|
||||
describe('listTaskPushNotificationConfig', () => {
|
||||
it('should list configs successfully', async () => {
|
||||
const mockList = [mockConfig];
|
||||
mockUnarySuccess(mockGrpcClient.listTaskPushNotificationConfigs as Mock, mockList);
|
||||
mockUnarySuccess(mockGrpcClient.listTaskPushNotificationConfig as Mock, mockList);
|
||||
|
||||
const result = await transport.listTaskPushNotificationConfig({
|
||||
taskId,
|
||||
tenant: '',
|
||||
pageSize: 0,
|
||||
pageToken: '',
|
||||
});
|
||||
const result = await transport.listTaskPushNotificationConfig({ id: taskId });
|
||||
|
||||
expect(result).toEqual(mockList);
|
||||
});
|
||||
@ -358,9 +339,8 @@ describe('GrpcTransport', () => {
|
||||
mockUnarySuccess(mockGrpcClient.deleteTaskPushNotificationConfig as Mock, {});
|
||||
|
||||
await transport.deleteTaskPushNotificationConfig({
|
||||
id: configId,
|
||||
taskId: taskId,
|
||||
tenant: '',
|
||||
id: taskId,
|
||||
pushNotificationConfigId: configId,
|
||||
});
|
||||
|
||||
expect(mockGrpcClient.deleteTaskPushNotificationConfig).toHaveBeenCalled();
|
||||
@ -370,7 +350,7 @@ describe('GrpcTransport', () => {
|
||||
|
||||
describe('resubscribeTask', () => {
|
||||
it('should yield task updates from stream', async () => {
|
||||
const params = { id: 'task-123', tenant: '' };
|
||||
const params = { id: 'task-123' };
|
||||
const mockUpdate = createMockTask('task-123');
|
||||
const mockResponse = { payload: { $case: 'task', value: mockUpdate } };
|
||||
|
||||
@ -380,7 +360,7 @@ describe('GrpcTransport', () => {
|
||||
},
|
||||
cancel: vi.fn(),
|
||||
};
|
||||
(mockGrpcClient.subscribeToTask as Mock).mockReturnValue(mockStream);
|
||||
(mockGrpcClient.taskSubscription as Mock).mockReturnValue(mockStream);
|
||||
|
||||
const iterator = transport.resubscribeTask(params);
|
||||
const result = await iterator.next();
|
||||
@ -399,12 +379,8 @@ describe('GrpcTransportFactory', () => {
|
||||
|
||||
it('should create transport with correct endpoint', async () => {
|
||||
const factory = new GrpcTransportFactory();
|
||||
const agentCard = createMockAgentCard({
|
||||
supportedInterfaces: [
|
||||
{ url: 'localhost:50051', protocolBinding: 'GRPC', tenant: '', protocolVersion: '1.0.0' },
|
||||
],
|
||||
});
|
||||
const transport = await factory.create('localhost:50051', agentCard);
|
||||
const agentCard = createMockAgentCard({ url: 'localhost:50051' });
|
||||
const transport = await factory.create(agentCard.url, agentCard);
|
||||
|
||||
expect(transport).toBeInstanceOf(GrpcTransport);
|
||||
});
|
||||
|
||||
@ -1,12 +1,6 @@
|
||||
import { JsonRpcTransport } from '../../../src/client/transports/json_rpc_transport.js';
|
||||
import { describe, it, beforeEach, expect, vi, type Mock } from 'vitest';
|
||||
import { Role } from '../../../src/index.js';
|
||||
import {
|
||||
GetTaskPushNotificationConfigRequest,
|
||||
ListTaskPushNotificationConfigsRequest,
|
||||
SendMessageRequest,
|
||||
TaskPushNotificationConfig,
|
||||
} from '../../../src/types/pb/a2a.js';
|
||||
import { MessageSendParams, TextPart } from '../../../src/types.js';
|
||||
import { RequestOptions } from '../../../src/client/multitransport-client.js';
|
||||
import { HTTP_EXTENSION_HEADER } from '../../../src/constants.js';
|
||||
import { ServiceParameters, withA2AExtensions } from '../../../src/client/service-parameters.js';
|
||||
@ -24,38 +18,20 @@ describe('JsonRpcTransport', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('protocolName', () => {
|
||||
it('should return correct protocol name', () => {
|
||||
expect(transport.protocolName).toBe('JSONRPC');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sendMessage', () => {
|
||||
it('should correctly add the extension headers', async () => {
|
||||
const messageParams: SendMessageRequest = {
|
||||
tenant: '',
|
||||
const messageParams: MessageSendParams = {
|
||||
message: {
|
||||
kind: 'message',
|
||||
messageId: 'test-msg-1',
|
||||
role: Role.ROLE_USER,
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
content: {
|
||||
$case: 'text',
|
||||
value: 'Hello, agent!',
|
||||
},
|
||||
filename: '',
|
||||
mediaType: '',
|
||||
metadata: undefined,
|
||||
},
|
||||
kind: 'text',
|
||||
text: 'Hello, agent!',
|
||||
} as TextPart,
|
||||
],
|
||||
contextId: '',
|
||||
taskId: '',
|
||||
extensions: [],
|
||||
metadata: undefined,
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
configuration: undefined,
|
||||
metadata: {},
|
||||
};
|
||||
|
||||
const expectedExtensions = 'extension1,extension2';
|
||||
@ -65,25 +41,9 @@ describe('JsonRpcTransport', () => {
|
||||
};
|
||||
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
payload: {
|
||||
$case: 'msg',
|
||||
value: {
|
||||
messageId: 'response-msg-1',
|
||||
role: Role.ROLE_AGENT,
|
||||
content: [{ part: { $case: 'text', value: 'Response' } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
id: 1,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
}
|
||||
)
|
||||
new Response(JSON.stringify({ jsonrpc: '2.0', result: {}, id: 1 }), {
|
||||
status: 200,
|
||||
})
|
||||
);
|
||||
await transport.sendMessage(messageParams, options);
|
||||
const fetchArgs = mockFetch.mock.calls[0][1];
|
||||
@ -91,117 +51,4 @@ describe('JsonRpcTransport', () => {
|
||||
expect((headers as any)[HTTP_EXTENSION_HEADER]).to.deep.equal(expectedExtensions);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TaskPushNotificationConfig', () => {
|
||||
it('createTaskPushNotificationConfig should send correct params and return config', async () => {
|
||||
const config: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
id: 'config1',
|
||||
taskId: 'task1',
|
||||
url: 'https://webhook.site',
|
||||
token: 'token123',
|
||||
authentication: undefined,
|
||||
};
|
||||
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
result: config,
|
||||
id: 1,
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
);
|
||||
|
||||
const result = await transport.createTaskPushNotificationConfig(config);
|
||||
|
||||
const fetchArgs = mockFetch.mock.calls[0][1];
|
||||
const body = JSON.parse(fetchArgs.body as string);
|
||||
expect(body.method).toBe('CreateTaskPushNotificationConfig');
|
||||
expect(body.params).toEqual({
|
||||
id: 'config1',
|
||||
taskId: 'task1',
|
||||
url: 'https://webhook.site',
|
||||
token: 'token123',
|
||||
});
|
||||
expect(result).toEqual(config);
|
||||
});
|
||||
|
||||
it('getTaskPushNotificationConfig should return config', async () => {
|
||||
const params: GetTaskPushNotificationConfigRequest = {
|
||||
id: 'config1',
|
||||
taskId: 'task1',
|
||||
tenant: '',
|
||||
};
|
||||
|
||||
const expectedConfig: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
id: 'config1',
|
||||
taskId: 'task1',
|
||||
url: 'https://webhook.site',
|
||||
token: 'token123',
|
||||
authentication: undefined,
|
||||
};
|
||||
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
result: expectedConfig,
|
||||
id: 1,
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
);
|
||||
|
||||
const result = await transport.getTaskPushNotificationConfig(params);
|
||||
|
||||
const fetchArgs = mockFetch.mock.calls[0][1];
|
||||
const body = JSON.parse(fetchArgs.body as string);
|
||||
expect(body.method).toBe('GetTaskPushNotificationConfig');
|
||||
expect(body.params).toEqual({ id: 'config1', taskId: 'task1' });
|
||||
expect(result).toEqual(expectedConfig);
|
||||
});
|
||||
|
||||
it('listTaskPushNotificationConfig should return list of configs', async () => {
|
||||
const params: ListTaskPushNotificationConfigsRequest = {
|
||||
taskId: 'task1',
|
||||
tenant: '',
|
||||
pageSize: 0,
|
||||
pageToken: '',
|
||||
};
|
||||
|
||||
const expectedConfig: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
id: 'config1',
|
||||
taskId: 'task1',
|
||||
url: 'https://webhook.site',
|
||||
token: 'token123',
|
||||
authentication: undefined,
|
||||
};
|
||||
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
configs: [expectedConfig],
|
||||
},
|
||||
id: 1,
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
);
|
||||
|
||||
const result = await transport.listTaskPushNotificationConfig(params);
|
||||
|
||||
const fetchArgs = mockFetch.mock.calls[0][1];
|
||||
const body = JSON.parse(fetchArgs.body as string);
|
||||
expect(body.method).toBe('ListTaskPushNotificationConfigs');
|
||||
expect(body.params).toEqual({ taskId: 'task1' });
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual(expectedConfig);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -3,6 +3,7 @@ import {
|
||||
RestTransportFactory,
|
||||
} from '../../../src/client/transports/rest_transport.js';
|
||||
import { describe, it, beforeEach, afterEach, expect, vi, type Mock } from 'vitest';
|
||||
import { TaskPushNotificationConfig } from '../../../src/types.js';
|
||||
import { RequestOptions } from '../../../src/client/multitransport-client.js';
|
||||
import { HTTP_EXTENSION_HEADER } from '../../../src/constants.js';
|
||||
import { ServiceParameters, withA2AExtensions } from '../../../src/client/service-parameters.js';
|
||||
@ -23,10 +24,11 @@ import {
|
||||
} from '../util.js';
|
||||
import {
|
||||
AgentCard,
|
||||
ListTaskPushNotificationConfigsResponse,
|
||||
ListTaskPushNotificationConfigResponse,
|
||||
TaskPushNotificationConfig as TaskPushNotificationConfigProto,
|
||||
TaskState,
|
||||
TaskPushNotificationConfig,
|
||||
} from '../../../src/types/pb/a2a.js';
|
||||
} from '../../../src/types/pb/a2a_types.js';
|
||||
import { FromProto } from '../../../src/types/converters/from_proto.js';
|
||||
import { ToProto } from '../../../src/types/converters/to_proto.js';
|
||||
|
||||
describe('RestTransport', () => {
|
||||
@ -58,7 +60,7 @@ describe('RestTransport', () => {
|
||||
await trailingSlashTransport.sendMessage(createMessageParams());
|
||||
|
||||
const [url] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal('https://example.com/a2a/rest/message:send');
|
||||
expect(url).to.equal('https://example.com/a2a/rest/v1/message:send');
|
||||
});
|
||||
|
||||
it('should trim multiple trailing slashes from endpoint', async () => {
|
||||
@ -72,13 +74,7 @@ describe('RestTransport', () => {
|
||||
await trailingSlashTransport.sendMessage(createMessageParams());
|
||||
|
||||
const [url] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal('https://example.com/a2a/rest/message:send');
|
||||
});
|
||||
});
|
||||
|
||||
describe('protocolName', () => {
|
||||
it('should return correct protocol name', () => {
|
||||
expect(transport.protocolName).toBe('HTTP+JSON');
|
||||
expect(url).to.equal('https://example.com/a2a/rest/v1/message:send');
|
||||
});
|
||||
});
|
||||
|
||||
@ -95,7 +91,7 @@ describe('RestTransport', () => {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal(`${endpoint}/message:send`);
|
||||
expect(url).to.equal(`${endpoint}/v1/message:send`);
|
||||
expect(options?.method).to.equal('POST');
|
||||
expect((options?.headers as Record<string, string>)['Content-Type']).to.equal(
|
||||
'application/json'
|
||||
@ -132,13 +128,13 @@ describe('RestTransport', () => {
|
||||
|
||||
mockFetch.mockResolvedValue(createRestResponse(mockTask));
|
||||
|
||||
const result = await transport.getTask({ id: taskId, tenant: '', historyLength: 0 });
|
||||
const result = await transport.getTask({ id: taskId });
|
||||
|
||||
expect(result).to.deep.equal(createMockTask(taskId));
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal(`${endpoint}/tasks/${taskId}?historyLength=0`);
|
||||
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}`);
|
||||
expect(options?.method).to.equal('GET');
|
||||
});
|
||||
|
||||
@ -149,48 +145,46 @@ describe('RestTransport', () => {
|
||||
|
||||
mockFetch.mockResolvedValue(createRestResponse(mockTask));
|
||||
|
||||
const result = await transport.getTask({ id: taskId, tenant: '', historyLength });
|
||||
const result = await transport.getTask({ id: taskId, historyLength });
|
||||
|
||||
expect(result).to.deep.equal(createMockTask(taskId));
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal(`${endpoint}/tasks/${taskId}?historyLength=${historyLength}`);
|
||||
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}?historyLength=${historyLength}`);
|
||||
expect(options?.method).to.equal('GET');
|
||||
});
|
||||
|
||||
it('should throw TaskNotFoundError when task does not exist', async () => {
|
||||
mockFetch.mockResolvedValue(createRestErrorResponse(-32001, 'Task not found', 404));
|
||||
|
||||
await expect(
|
||||
transport.getTask({ id: 'nonexistent', tenant: '', historyLength: 0 })
|
||||
).rejects.toThrow(TaskNotFoundError);
|
||||
await expect(transport.getTask({ id: 'nonexistent' })).rejects.toThrow(TaskNotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cancelTask', () => {
|
||||
it('should cancel task successfully', async () => {
|
||||
const taskId = 'task-123';
|
||||
const mockTask = createMockProtoTask(taskId, TaskState.TASK_STATE_CANCELED);
|
||||
const mockTask = createMockProtoTask(taskId, TaskState.TASK_STATE_CANCELLED);
|
||||
|
||||
mockFetch.mockResolvedValue(createRestResponse(mockTask));
|
||||
|
||||
const result = await transport.cancelTask({ id: taskId, tenant: '', metadata: {} });
|
||||
const result = await transport.cancelTask({ id: taskId });
|
||||
|
||||
expect(result).to.deep.equal(createMockTask(taskId, TaskState.TASK_STATE_CANCELED));
|
||||
expect(result).to.deep.equal(createMockTask(taskId, 'canceled'));
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal(`${endpoint}/tasks/${taskId}:cancel`);
|
||||
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}:cancel`);
|
||||
expect(options?.method).to.equal('POST');
|
||||
});
|
||||
|
||||
it('should throw TaskNotCancelableError on -32002', async () => {
|
||||
mockFetch.mockResolvedValue(createRestErrorResponse(-32002, 'Task cannot be canceled', 409));
|
||||
|
||||
await expect(
|
||||
transport.cancelTask({ id: 'task-123', tenant: '', metadata: {} })
|
||||
).rejects.toThrow(TaskNotCancelableError);
|
||||
await expect(transport.cancelTask({ id: 'task-123' })).rejects.toThrow(
|
||||
TaskNotCancelableError
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@ -199,6 +193,7 @@ describe('RestTransport', () => {
|
||||
const mockCard: AgentCard = {
|
||||
name: 'Test Agent',
|
||||
description: 'A test agent for testing',
|
||||
supportsAuthenticatedExtendedCard: true,
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: true,
|
||||
@ -207,20 +202,16 @@ describe('RestTransport', () => {
|
||||
skills: [],
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text'],
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: endpoint,
|
||||
protocolBinding: 'HTTP+JSON',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
},
|
||||
],
|
||||
url: endpoint,
|
||||
version: '1.0.0',
|
||||
protocolVersion: '0.3.0',
|
||||
preferredTransport: 'HTTP+JSON',
|
||||
additionalInterfaces: [],
|
||||
provider: {
|
||||
url: '',
|
||||
organization: '',
|
||||
},
|
||||
securityRequirements: [],
|
||||
security: [],
|
||||
securitySchemes: {},
|
||||
documentationUrl: '',
|
||||
signatures: [],
|
||||
@ -230,11 +221,11 @@ describe('RestTransport', () => {
|
||||
|
||||
const result = await transport.getExtendedAgentCard();
|
||||
|
||||
expect(result).toEqual(expect.objectContaining(mockCard));
|
||||
expect(result).to.deep.equal(FromProto.agentCard(mockCard));
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal(`${endpoint}/extendedAgentCard`);
|
||||
expect(url).to.equal(`${endpoint}/v1/card`);
|
||||
expect(options?.method).to.equal('GET');
|
||||
});
|
||||
});
|
||||
@ -243,25 +234,29 @@ describe('RestTransport', () => {
|
||||
const taskId = 'task-123';
|
||||
const configId = 'config-456';
|
||||
const mockConfig: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
id: configId,
|
||||
taskId: taskId,
|
||||
url: 'https://notify.example.com/webhook',
|
||||
authentication: undefined,
|
||||
token: 'secret-token',
|
||||
taskId,
|
||||
pushNotificationConfig: {
|
||||
id: configId,
|
||||
url: 'https://notify.example.com/webhook',
|
||||
authentication: undefined,
|
||||
token: 'secret-token',
|
||||
},
|
||||
};
|
||||
const mockProtoConfig = ToProto.taskPushNotificationConfig(mockConfig);
|
||||
|
||||
describe('createTaskPushNotificationConfig', () => {
|
||||
it('should create a push notification config successfully', async () => {
|
||||
mockFetch.mockResolvedValue(createRestResponse(mockConfig));
|
||||
describe('setTaskPushNotificationConfig', () => {
|
||||
it('should set push notification config successfully', async () => {
|
||||
mockFetch.mockResolvedValue(
|
||||
createRestResponse(TaskPushNotificationConfigProto.toJSON(mockProtoConfig))
|
||||
);
|
||||
|
||||
const result = await transport.createTaskPushNotificationConfig(mockConfig);
|
||||
const result = await transport.setTaskPushNotificationConfig(mockConfig);
|
||||
|
||||
expect(result).to.deep.equal(mockConfig);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal(`${endpoint}/tasks/${taskId}/pushNotificationConfigs`);
|
||||
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}/pushNotificationConfigs`);
|
||||
expect(options?.method).to.equal('POST');
|
||||
});
|
||||
|
||||
@ -270,7 +265,7 @@ describe('RestTransport', () => {
|
||||
createRestErrorResponse(-32003, 'Push notifications not supported', 400)
|
||||
);
|
||||
|
||||
await expect(transport.createTaskPushNotificationConfig(mockConfig)).rejects.toThrow(
|
||||
await expect(transport.setTaskPushNotificationConfig(mockConfig)).rejects.toThrow(
|
||||
PushNotificationNotSupportedError
|
||||
);
|
||||
});
|
||||
@ -278,67 +273,62 @@ describe('RestTransport', () => {
|
||||
|
||||
describe('getTaskPushNotificationConfig', () => {
|
||||
it('should get push notification config successfully', async () => {
|
||||
mockFetch.mockResolvedValue(createRestResponse(mockConfig));
|
||||
mockFetch.mockResolvedValue(
|
||||
createRestResponse(TaskPushNotificationConfigProto.toJSON(mockProtoConfig))
|
||||
);
|
||||
|
||||
const result = await transport.getTaskPushNotificationConfig({
|
||||
id: configId,
|
||||
taskId,
|
||||
tenant: '',
|
||||
id: taskId,
|
||||
pushNotificationConfigId: configId,
|
||||
});
|
||||
|
||||
expect(result).to.deep.equal(mockConfig);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal(`${endpoint}/tasks/${taskId}/pushNotificationConfigs/${configId}`);
|
||||
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}/pushNotificationConfigs/${configId}`);
|
||||
expect(options?.method).to.equal('GET');
|
||||
});
|
||||
|
||||
it('should throw error when pushNotificationConfigId is missing', async () => {
|
||||
await expect(
|
||||
transport.getTaskPushNotificationConfig({
|
||||
id: taskId,
|
||||
pushNotificationConfigId: undefined as unknown as string,
|
||||
})
|
||||
).rejects.toThrow('pushNotificationConfigId is required');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listTaskPushNotificationConfig', () => {
|
||||
it('should list push notification configs successfully', async () => {
|
||||
const protoConfigs: TaskPushNotificationConfig[] = [
|
||||
const mockConfigs: TaskPushNotificationConfig[] = [
|
||||
mockConfig,
|
||||
{
|
||||
tenant: '',
|
||||
id: 'config-789',
|
||||
taskId: taskId,
|
||||
url: 'https://test.com',
|
||||
authentication: undefined,
|
||||
token: 'secret-token',
|
||||
},
|
||||
];
|
||||
const expectedConfigs: TaskPushNotificationConfig[] = [
|
||||
mockConfig,
|
||||
{
|
||||
tenant: '',
|
||||
id: 'config-789',
|
||||
taskId: taskId,
|
||||
url: 'https://test.com',
|
||||
authentication: undefined,
|
||||
token: 'secret-token',
|
||||
...mockConfig,
|
||||
pushNotificationConfig: {
|
||||
id: 'config-789',
|
||||
url: 'https://test.com',
|
||||
authentication: undefined,
|
||||
token: 'secret-token',
|
||||
},
|
||||
},
|
||||
];
|
||||
mockFetch.mockResolvedValue(
|
||||
createRestResponse(
|
||||
ListTaskPushNotificationConfigsResponse.toJSON(
|
||||
ToProto.listTaskPushNotificationConfig(protoConfigs)
|
||||
ListTaskPushNotificationConfigResponse.toJSON(
|
||||
ToProto.listTaskPushNotificationConfig(mockConfigs)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const result = await transport.listTaskPushNotificationConfig({
|
||||
taskId,
|
||||
tenant: '',
|
||||
pageSize: 0,
|
||||
pageToken: '',
|
||||
});
|
||||
const result = await transport.listTaskPushNotificationConfig({ id: taskId });
|
||||
|
||||
expect(result).to.deep.equal(expectedConfigs);
|
||||
expect(result).to.deep.equal(mockConfigs);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal(`${endpoint}/tasks/${taskId}/pushNotificationConfigs`);
|
||||
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}/pushNotificationConfigs`);
|
||||
expect(options?.method).to.equal('GET');
|
||||
});
|
||||
});
|
||||
@ -348,15 +338,14 @@ describe('RestTransport', () => {
|
||||
mockFetch.mockResolvedValue(new Response(null, { status: 204 }));
|
||||
|
||||
await transport.deleteTaskPushNotificationConfig({
|
||||
id: configId,
|
||||
taskId,
|
||||
tenant: '',
|
||||
id: taskId,
|
||||
pushNotificationConfigId: configId,
|
||||
});
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(url).to.equal(`${endpoint}/tasks/${taskId}/pushNotificationConfigs/${configId}`);
|
||||
expect(url).to.equal(`${endpoint}/v1/tasks/${taskId}/pushNotificationConfigs/${configId}`);
|
||||
expect(options?.method).to.equal('DELETE');
|
||||
});
|
||||
});
|
||||
@ -371,17 +360,13 @@ describe('RestTransport', () => {
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
transport.getTask({ id: 'task-123', tenant: '', historyLength: 0 })
|
||||
).rejects.toThrow('HTTP error');
|
||||
await expect(transport.getTask({ id: 'task-123' })).rejects.toThrow('HTTP error');
|
||||
});
|
||||
|
||||
it('should handle network errors', async () => {
|
||||
mockFetch.mockRejectedValue(new Error('Network error'));
|
||||
|
||||
await expect(
|
||||
transport.getTask({ id: 'task-123', tenant: '', historyLength: 0 })
|
||||
).rejects.toThrow('Network error');
|
||||
await expect(transport.getTask({ id: 'task-123' })).rejects.toThrow('Network error');
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -394,17 +379,8 @@ describe('RestTransportFactory', () => {
|
||||
|
||||
it('should create transport with correct endpoint', async () => {
|
||||
const factory = new RestTransportFactory();
|
||||
const agentCard = createMockAgentCard({
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'https://example.com/api',
|
||||
protocolBinding: 'HTTP+JSON',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
},
|
||||
],
|
||||
});
|
||||
const transport = await factory.create('https://example.com/api', agentCard);
|
||||
const agentCard = createMockAgentCard({ url: 'https://example.com/api' });
|
||||
const transport = await factory.create(agentCard.url, agentCard);
|
||||
expect(transport).to.be.instanceOf(RestTransport);
|
||||
});
|
||||
});
|
||||
|
||||
@ -4,8 +4,8 @@
|
||||
|
||||
import { vi, Mock } from 'vitest';
|
||||
import { AGENT_CARD_PATH } from '../../src/constants.js';
|
||||
import { Role, SendMessageResponse, Task, TaskState } from '../../src/types/pb/a2a.js';
|
||||
import { SendMessageResult } from '../../src/index.js';
|
||||
import { Role, SendMessageResponse, Task, TaskState } from '../../src/types/pb/a2a_types.js';
|
||||
import { SendMessageResult } from '../../src/client/client.js';
|
||||
|
||||
/**
|
||||
* Extracts the request ID from a RequestInit options object.
|
||||
@ -115,6 +115,8 @@ export function createMockAgentCard(
|
||||
options: {
|
||||
name?: string;
|
||||
description?: string;
|
||||
url?: string;
|
||||
protocolVersion?: string;
|
||||
version?: string;
|
||||
defaultInputModes?: string[];
|
||||
defaultOutputModes?: string[];
|
||||
@ -123,37 +125,22 @@ export function createMockAgentCard(
|
||||
pushNotifications?: boolean;
|
||||
};
|
||||
skills?: any[];
|
||||
supportedInterfaces?: {
|
||||
url: string;
|
||||
protocolBinding: string;
|
||||
tenant: string;
|
||||
protocolVersion: string;
|
||||
}[];
|
||||
} = {}
|
||||
): any {
|
||||
return {
|
||||
name: options.name ?? 'Test Agent',
|
||||
description: options.description ?? 'A test agent for testing',
|
||||
protocolVersion: options.protocolVersion ?? '1.0.0',
|
||||
version: options.version ?? '1.0.0',
|
||||
supportedInterfaces: options.supportedInterfaces ?? [
|
||||
{
|
||||
url: 'https://test-agent.example.com/api',
|
||||
protocolBinding: 'JSONRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
},
|
||||
],
|
||||
url: options.url ?? 'https://test-agent.example.com/api',
|
||||
defaultInputModes: options.defaultInputModes ?? ['text'],
|
||||
defaultOutputModes: options.defaultOutputModes ?? ['text'],
|
||||
capabilities: {
|
||||
streaming: options.capabilities?.streaming ?? true,
|
||||
pushNotifications: options.capabilities?.pushNotifications ?? true,
|
||||
extensions: [],
|
||||
...options.capabilities,
|
||||
},
|
||||
skills: options.skills ?? [],
|
||||
securityRequirements: [],
|
||||
signatures: [],
|
||||
provider: { url: '', organization: '' },
|
||||
securitySchemes: {},
|
||||
};
|
||||
}
|
||||
|
||||
@ -180,27 +167,17 @@ export function createMessageParams(
|
||||
const role = options.role ?? 'user';
|
||||
|
||||
return {
|
||||
request: {
|
||||
message: {
|
||||
kind: 'message',
|
||||
messageId: messageId,
|
||||
role: role === 'user' ? Role.ROLE_USER : Role.ROLE_AGENT,
|
||||
role: role,
|
||||
parts: [
|
||||
{
|
||||
content: {
|
||||
$case: 'text',
|
||||
value: text,
|
||||
},
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
metadata: {},
|
||||
kind: 'text',
|
||||
text: text,
|
||||
},
|
||||
],
|
||||
contextId: 'context-123',
|
||||
taskId: 'task-123',
|
||||
metadata: {},
|
||||
extensions: [],
|
||||
},
|
||||
configuration: undefined,
|
||||
metadata: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@ -217,26 +194,22 @@ export function createMockProtoMessage(
|
||||
|
||||
const obj: SendMessageResponse = {
|
||||
payload: {
|
||||
$case: 'message',
|
||||
$case: 'msg',
|
||||
value: {
|
||||
messageId: messageId,
|
||||
contextId: 'context-123',
|
||||
taskId: 'task-123',
|
||||
role: role,
|
||||
parts: [
|
||||
content: [
|
||||
{
|
||||
content: {
|
||||
part: {
|
||||
$case: 'text',
|
||||
value: text,
|
||||
},
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
metadata: {},
|
||||
},
|
||||
],
|
||||
metadata: {},
|
||||
extensions: [],
|
||||
referenceTaskIds: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
@ -259,32 +232,27 @@ export function createMockMessage(
|
||||
options: {
|
||||
messageId?: string;
|
||||
text?: string;
|
||||
role?: Role;
|
||||
role?: 'user' | 'agent';
|
||||
} = {}
|
||||
): SendMessageResult {
|
||||
const messageId = options.messageId ?? 'msg-123';
|
||||
const text = options.text ?? 'Hello, agent!';
|
||||
const role = options.role ?? Role.ROLE_USER;
|
||||
const role = options.role ?? 'user';
|
||||
|
||||
return {
|
||||
kind: 'message',
|
||||
messageId: messageId,
|
||||
contextId: 'context-123',
|
||||
taskId: 'task-123',
|
||||
role: role,
|
||||
parts: [
|
||||
{
|
||||
content: {
|
||||
$case: 'text',
|
||||
value: text,
|
||||
},
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
metadata: {},
|
||||
kind: 'text',
|
||||
text: text,
|
||||
},
|
||||
],
|
||||
metadata: {},
|
||||
extensions: [],
|
||||
referenceTaskIds: [],
|
||||
};
|
||||
}
|
||||
|
||||
@ -420,18 +388,7 @@ export function createMockFetch(
|
||||
text: messageConfig.text || 'Hello, agent!',
|
||||
});
|
||||
|
||||
const requestBody = JSON.parse((options?.body as string) || '{}');
|
||||
const wrappedResult =
|
||||
requestBody.method === 'SendMessage'
|
||||
? {
|
||||
payload: {
|
||||
$case: 'msg',
|
||||
value: mockMessage,
|
||||
},
|
||||
}
|
||||
: mockMessage;
|
||||
|
||||
return createResponse(requestId, wrappedResult);
|
||||
return createResponse(requestId, mockMessage);
|
||||
}
|
||||
|
||||
// Default: return 404 for unknown endpoints
|
||||
@ -492,18 +449,16 @@ export function createRestErrorResponse(
|
||||
* @param status - Task status state (defaults to 'completed')
|
||||
* @returns A mock Task object
|
||||
*/
|
||||
export function createMockTask(
|
||||
id: string = 'task-123',
|
||||
status: TaskState = TaskState.TASK_STATE_COMPLETED
|
||||
): any {
|
||||
export function createMockTask(id: string = 'task-123', status: string = 'completed'): any {
|
||||
return {
|
||||
id,
|
||||
contextId: 'context-123',
|
||||
status: {
|
||||
state: status,
|
||||
timestamp: '2023-01-01T00:00:00.000Z',
|
||||
timestamp: new Date('2023-01-01T00:00:00.000Z').toISOString(),
|
||||
message: undefined,
|
||||
},
|
||||
kind: 'task',
|
||||
artifacts: [],
|
||||
history: [],
|
||||
metadata: {},
|
||||
@ -527,7 +482,7 @@ export function createMockProtoTask(
|
||||
status: {
|
||||
state: status,
|
||||
timestamp: '2023-01-01T00:00:00.000Z',
|
||||
message: undefined,
|
||||
update: undefined,
|
||||
},
|
||||
artifacts: [],
|
||||
history: [],
|
||||
|
||||
@ -9,13 +9,14 @@ import {
|
||||
InMemoryTaskStore,
|
||||
RequestContext,
|
||||
} from '../src/server/index.js';
|
||||
import { AgentCard, Message, Role, TaskState, A2AStreamEventData } from '../src/index.js';
|
||||
import { AgentCard, Message } from '../src/types.js';
|
||||
import { agentCardHandler } from '../src/server/express/agent_card_handler.js';
|
||||
import { jsonRpcHandler } from '../src/server/express/json_rpc_handler.js';
|
||||
import { restHandler } from '../src/server/express/rest_handler.js';
|
||||
import { ClientFactory, ClientFactoryOptions } from '../src/client/factory.js';
|
||||
import { Server } from 'http';
|
||||
import { AddressInfo } from 'net';
|
||||
import { A2AStreamEventData } from '../src/client/client.js';
|
||||
import { UserBuilder } from '../src/server/express/common.js';
|
||||
import { A2AService, grpcService } from '../src/server/grpc/index.js';
|
||||
import { GrpcTransportFactory } from '../src/client/transports/grpc/grpc_transport.js';
|
||||
@ -73,30 +74,19 @@ describe('Client E2E tests', () => {
|
||||
beforeEach(async () => {
|
||||
agentExecutor = new TestAgentExecutor();
|
||||
agentCard = {
|
||||
protocolVersion: '0.3.0',
|
||||
name: 'Test Agent',
|
||||
description: 'An agent for testing purposes',
|
||||
preferredTransport: transportConfig.preferredTransport,
|
||||
url: 'localhost',
|
||||
version: '1.0.0',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'localhost',
|
||||
protocolBinding: transportConfig.preferredTransport,
|
||||
tenant: '',
|
||||
protocolVersion: '1.0.0',
|
||||
},
|
||||
],
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: true,
|
||||
extensions: [],
|
||||
},
|
||||
defaultInputModes: ['text/plain'],
|
||||
defaultOutputModes: ['text/plain'],
|
||||
skills: [],
|
||||
provider: { url: '', organization: '' },
|
||||
documentationUrl: '',
|
||||
securityRequirements: [],
|
||||
securitySchemes: {},
|
||||
signatures: [],
|
||||
};
|
||||
const requestHandler = new DefaultRequestHandler(
|
||||
agentCard,
|
||||
@ -126,7 +116,7 @@ describe('Client E2E tests', () => {
|
||||
|
||||
server = app.listen();
|
||||
const address = server.address() as AddressInfo;
|
||||
agentCard.supportedInterfaces![0].url = `http://localhost:${address.port}${transportConfig.serverPath}`;
|
||||
agentCard.url = `http://localhost:${address.port}${transportConfig.serverPath}`;
|
||||
|
||||
grpcServer = new grpc.Server();
|
||||
grpcServer.addService(
|
||||
@ -146,7 +136,7 @@ describe('Client E2E tests', () => {
|
||||
return;
|
||||
}
|
||||
if (transportConfig.name === 'GRPC') {
|
||||
agentCard.supportedInterfaces![0].url = `localhost:${port}`;
|
||||
agentCard.url = `localhost:${port}`;
|
||||
}
|
||||
resolve();
|
||||
}
|
||||
@ -166,12 +156,9 @@ describe('Client E2E tests', () => {
|
||||
const client = await clientFactory.createFromAgentCard(agentCard);
|
||||
|
||||
const actual = await client.sendMessage({
|
||||
tenant: '',
|
||||
message: createTestMessage('1', 'test'),
|
||||
configuration: undefined,
|
||||
metadata: {},
|
||||
});
|
||||
expect(removeUndefinedFields(actual)).to.deep.equal(removeUndefinedFields(expected));
|
||||
expect(removeUndefinedFields(actual)).to.deep.equal(expected);
|
||||
});
|
||||
});
|
||||
|
||||
@ -183,34 +170,24 @@ describe('Client E2E tests', () => {
|
||||
{
|
||||
id: taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_SUBMITTED,
|
||||
timestamp: undefined,
|
||||
message: undefined,
|
||||
},
|
||||
status: { state: 'submitted' },
|
||||
kind: 'task',
|
||||
artifacts: [],
|
||||
history: [],
|
||||
metadata: {},
|
||||
},
|
||||
{
|
||||
taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_WORKING,
|
||||
timestamp: undefined,
|
||||
message: undefined,
|
||||
},
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
status: { state: 'working' },
|
||||
final: false,
|
||||
},
|
||||
{
|
||||
taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_COMPLETED,
|
||||
timestamp: undefined,
|
||||
message: undefined,
|
||||
},
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
status: { state: 'completed' },
|
||||
final: true,
|
||||
},
|
||||
];
|
||||
agentExecutor.events = expected;
|
||||
@ -218,15 +195,12 @@ describe('Client E2E tests', () => {
|
||||
|
||||
const actual: A2AStreamEventData[] = [];
|
||||
for await (const message of client.sendMessageStream({
|
||||
tenant: '',
|
||||
message: createTestMessage('1', 'test'),
|
||||
configuration: undefined,
|
||||
metadata: {},
|
||||
})) {
|
||||
actual.push(message);
|
||||
}
|
||||
|
||||
expect(removeUndefinedFields(actual)).to.deep.equal(removeUndefinedFields(expected));
|
||||
expect(removeUndefinedFields(actual)).to.deep.equal(expected);
|
||||
});
|
||||
|
||||
it('should fallback to non-streaming sendMessage if agent does not support streaming', async () => {
|
||||
@ -237,19 +211,12 @@ describe('Client E2E tests', () => {
|
||||
const client = await clientFactory.createFromAgentCard(agentCard);
|
||||
|
||||
const actual: A2AStreamEventData[] = [];
|
||||
for await (const message of client.sendMessageStream({
|
||||
tenant: '',
|
||||
message: requestMessage,
|
||||
configuration: undefined,
|
||||
metadata: {},
|
||||
})) {
|
||||
for await (const message of client.sendMessageStream({ message: requestMessage })) {
|
||||
actual.push(message);
|
||||
}
|
||||
|
||||
expect(actual).to.have.lengthOf(1);
|
||||
expect(removeUndefinedFields(actual[0])).to.deep.equal(
|
||||
removeUndefinedFields(responseMessage)
|
||||
);
|
||||
expect(removeUndefinedFields(actual[0])).to.deep.equal(responseMessage);
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -261,21 +228,8 @@ function createTestMessage(id: string, text: string): Message {
|
||||
return {
|
||||
messageId: id,
|
||||
extensions: [],
|
||||
role: Role.ROLE_USER,
|
||||
parts: [
|
||||
{
|
||||
content: {
|
||||
$case: 'text',
|
||||
value: text,
|
||||
},
|
||||
filename: '',
|
||||
mediaType: '',
|
||||
metadata: undefined,
|
||||
},
|
||||
],
|
||||
contextId: '',
|
||||
taskId: '',
|
||||
metadata: undefined,
|
||||
referenceTaskIds: [],
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text }],
|
||||
kind: 'message',
|
||||
};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -4,7 +4,7 @@ import {
|
||||
DefaultExecutionEventBus,
|
||||
AgentExecutionEvent,
|
||||
} from '../../src/server/events/execution_event_bus.js';
|
||||
import { Message, Role } from '../../src/index.js';
|
||||
import { Message } from '../../src/types.js';
|
||||
|
||||
describe('DefaultExecutionEventBus', () => {
|
||||
let eventBus: DefaultExecutionEventBus;
|
||||
@ -16,21 +16,10 @@ describe('DefaultExecutionEventBus', () => {
|
||||
const createMessage = (() => {
|
||||
let counter = 0;
|
||||
return (text: string): Message => ({
|
||||
kind: 'message',
|
||||
messageId: `msg-${counter++}`,
|
||||
role: Role.ROLE_AGENT,
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: text },
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
metadata: {},
|
||||
},
|
||||
],
|
||||
taskId: '',
|
||||
contextId: '',
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
role: 'agent',
|
||||
parts: [{ kind: 'text', text }],
|
||||
});
|
||||
})();
|
||||
|
||||
|
||||
@ -9,52 +9,24 @@ import {
|
||||
Mock,
|
||||
MockInstance,
|
||||
} from 'vitest';
|
||||
import express, {
|
||||
Express,
|
||||
NextFunction,
|
||||
Request,
|
||||
Response,
|
||||
RequestHandler,
|
||||
ErrorRequestHandler,
|
||||
} from 'express';
|
||||
import express, { Express, NextFunction, Request, Response } from 'express';
|
||||
import request from 'supertest';
|
||||
|
||||
import { jsonErrorHandler, jsonRpcHandler } from '../../../src/server/express/json_rpc_handler.js';
|
||||
import { agentCardHandler } from '../../../src/server/express/agent_card_handler.js';
|
||||
import { UserBuilder } from '../../../src/server/express/common.js';
|
||||
import { A2AExpressApp } from '../../../src/server/express/a2a_express_app.js';
|
||||
import { A2ARequestHandler } from '../../../src/server/request_handler/a2a_request_handler.js';
|
||||
import { JsonRpcTransportHandler } from '../../../src/server/transports/jsonrpc/jsonrpc_transport_handler.js';
|
||||
import { AgentCard } from '../../../src/index.js';
|
||||
import { JSONRPCErrorResponse } from '../../../src/core.js';
|
||||
import { AgentCard, JSONRPCSuccessResponse, JSONRPCErrorResponse } from '../../../src/index.js';
|
||||
import { AGENT_CARD_PATH, HTTP_EXTENSION_HEADER } from '../../../src/constants.js';
|
||||
import { A2A_ERROR_CODE, GenericError, RequestMalformedError } from '../../../src/errors.js';
|
||||
import { A2AError } from '../../../src/server/error.js';
|
||||
import { ServerCallContext } from '../../../src/server/context.js';
|
||||
import { User, UnauthenticatedUser } from '../../../src/server/authentication/user.js';
|
||||
|
||||
describe('A2AExpressApp', () => {
|
||||
let mockRequestHandler: A2ARequestHandler;
|
||||
let app: A2AExpressApp;
|
||||
let expressApp: Express;
|
||||
let handleStub: MockInstance;
|
||||
|
||||
const setupA2ARoutes = (
|
||||
expressApp: Express,
|
||||
requestHandler: A2ARequestHandler,
|
||||
userBuilder: UserBuilder = UserBuilder.noAuthentication,
|
||||
baseUrl: string = '',
|
||||
middlewares: Array<RequestHandler | ErrorRequestHandler> = [],
|
||||
agentCardPath: string = AGENT_CARD_PATH
|
||||
): Express => {
|
||||
const router = express.Router();
|
||||
router.use(express.json(), jsonErrorHandler);
|
||||
if (middlewares.length > 0) {
|
||||
router.use(middlewares);
|
||||
}
|
||||
router.use(jsonRpcHandler({ requestHandler, userBuilder }));
|
||||
router.use(`/${agentCardPath}`, agentCardHandler({ agentCardProvider: requestHandler }));
|
||||
expressApp.use(baseUrl, router);
|
||||
return expressApp;
|
||||
};
|
||||
|
||||
// Helper function to create JSON-RPC request bodies
|
||||
const createRpcRequest = (id: string | null, method = 'message/send', params: object = {}) => ({
|
||||
jsonrpc: '2.0',
|
||||
@ -64,30 +36,19 @@ describe('A2AExpressApp', () => {
|
||||
});
|
||||
|
||||
const testAgentCard: AgentCard = {
|
||||
protocolVersion: '0.3.0',
|
||||
name: 'Test Agent',
|
||||
description: 'An agent for testing purposes',
|
||||
url: 'http://localhost:8080',
|
||||
preferredTransport: 'JSONRPC',
|
||||
version: '1.0.0',
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: true,
|
||||
extensions: [],
|
||||
},
|
||||
defaultInputModes: ['text/plain'],
|
||||
defaultOutputModes: ['text/plain'],
|
||||
skills: [],
|
||||
securityRequirements: [],
|
||||
securitySchemes: {},
|
||||
provider: { url: '', organization: '' },
|
||||
signatures: [],
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:8080/jsonrpc',
|
||||
protocolBinding: 'JSONRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0',
|
||||
},
|
||||
],
|
||||
documentationUrl: 'http://test-agent.com/docs',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
@ -98,14 +59,14 @@ describe('A2AExpressApp', () => {
|
||||
sendMessageStream: vi.fn(),
|
||||
getTask: vi.fn(),
|
||||
cancelTask: vi.fn(),
|
||||
createTaskPushNotificationConfig: vi.fn(),
|
||||
setTaskPushNotificationConfig: vi.fn(),
|
||||
getTaskPushNotificationConfig: vi.fn(),
|
||||
listTaskPushNotificationConfigs: vi.fn(),
|
||||
deleteTaskPushNotificationConfig: vi.fn(),
|
||||
resubscribe: vi.fn(),
|
||||
listTasks: vi.fn(),
|
||||
};
|
||||
|
||||
app = new A2AExpressApp(mockRequestHandler);
|
||||
expressApp = express();
|
||||
|
||||
handleStub = vi.spyOn(JsonRpcTransportHandler.prototype, 'handle');
|
||||
@ -115,9 +76,24 @@ describe('A2AExpressApp', () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should create an instance with requestHandler and jsonRpcTransportHandler', () => {
|
||||
const newApp = new A2AExpressApp(mockRequestHandler);
|
||||
assert.instanceOf(newApp, A2AExpressApp);
|
||||
assert.equal((newApp as any).requestHandler, mockRequestHandler);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setupRoutes', () => {
|
||||
it('should setup routes with default parameters', () => {
|
||||
const setupApp = app.setupRoutes(expressApp);
|
||||
assert.equal(setupApp, expressApp);
|
||||
});
|
||||
});
|
||||
|
||||
describe('agent card endpoint', () => {
|
||||
beforeEach(() => {
|
||||
setupA2ARoutes(expressApp, mockRequestHandler);
|
||||
app.setupRoutes(expressApp);
|
||||
});
|
||||
|
||||
it('should return agent card on GET /.well-known/agent-card.json', async () => {
|
||||
@ -130,7 +106,7 @@ describe('A2AExpressApp', () => {
|
||||
it('should return agent card on custom path when agentCardPath is provided', async () => {
|
||||
const customPath = 'custom/agent-card.json';
|
||||
const customExpressApp = express();
|
||||
setupA2ARoutes(customExpressApp, mockRequestHandler, undefined, '', undefined, customPath);
|
||||
app.setupRoutes(customExpressApp, '', undefined, customPath);
|
||||
|
||||
const response = await request(customExpressApp).get(`/${customPath}`).expect(200);
|
||||
|
||||
@ -151,11 +127,11 @@ describe('A2AExpressApp', () => {
|
||||
|
||||
describe('JSON-RPC endpoint', () => {
|
||||
beforeEach(() => {
|
||||
setupA2ARoutes(expressApp, mockRequestHandler);
|
||||
app.setupRoutes(expressApp);
|
||||
});
|
||||
|
||||
it('should handle single JSON-RPC response', async () => {
|
||||
const mockResponse = {
|
||||
const mockResponse: JSONRPCSuccessResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: 'test-id',
|
||||
result: { message: 'success' },
|
||||
@ -198,7 +174,7 @@ describe('A2AExpressApp', () => {
|
||||
const mockErrorStream = {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
yield { jsonrpc: '2.0', id: 'stream-1', result: { step: 1 } };
|
||||
throw new RequestMalformedError('Streaming error');
|
||||
throw new A2AError(-32603, 'Streaming error');
|
||||
},
|
||||
};
|
||||
|
||||
@ -217,7 +193,7 @@ describe('A2AExpressApp', () => {
|
||||
const mockImmediateErrorStream = {
|
||||
// eslint-disable-next-line require-yield
|
||||
async *[Symbol.asyncIterator]() {
|
||||
throw new RequestMalformedError('Immediate streaming error');
|
||||
throw new A2AError(-32603, 'Immediate streaming error');
|
||||
},
|
||||
};
|
||||
|
||||
@ -238,14 +214,14 @@ describe('A2AExpressApp', () => {
|
||||
});
|
||||
|
||||
it('should handle general processing error', async () => {
|
||||
const error = new GenericError('Processing error');
|
||||
const error = new A2AError(-32603, 'Processing error');
|
||||
handleStub.mockRejectedValue(error);
|
||||
|
||||
const requestBody = createRpcRequest('error-test');
|
||||
|
||||
const response = await request(expressApp).post('/').send(requestBody).expect(500);
|
||||
|
||||
const expectedErrorResponse = {
|
||||
const expectedErrorResponse: JSONRPCErrorResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: 'error-test',
|
||||
error: {
|
||||
@ -267,11 +243,11 @@ describe('A2AExpressApp', () => {
|
||||
|
||||
assert.equal(response.body.jsonrpc, '2.0');
|
||||
assert.equal(response.body.id, 'generic-error-test');
|
||||
assert.equal(response.body.error.message, 'Generic error');
|
||||
assert.equal(response.body.error.message, 'General processing error.');
|
||||
});
|
||||
|
||||
it('should handle request without id', async () => {
|
||||
const error = new RequestMalformedError('No ID error');
|
||||
const error = new A2AError(-32600, 'No ID error');
|
||||
handleStub.mockRejectedValue(error);
|
||||
|
||||
const requestBody = createRpcRequest(null);
|
||||
@ -282,7 +258,7 @@ describe('A2AExpressApp', () => {
|
||||
});
|
||||
|
||||
it('should handle extensions headers in request', async () => {
|
||||
const mockResponse = {
|
||||
const mockResponse: JSONRPCSuccessResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: 'test-id',
|
||||
result: { message: 'success' },
|
||||
@ -309,7 +285,7 @@ describe('A2AExpressApp', () => {
|
||||
});
|
||||
|
||||
it('should handle extensions headers in response', async () => {
|
||||
const mockResponse = {
|
||||
const mockResponse: JSONRPCSuccessResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: 'test-id',
|
||||
result: { message: 'success' },
|
||||
@ -347,7 +323,7 @@ describe('A2AExpressApp', () => {
|
||||
};
|
||||
|
||||
const middlewareApp = express();
|
||||
setupA2ARoutes(middlewareApp, mockRequestHandler, undefined, '', [testMiddleware]);
|
||||
app.setupRoutes(middlewareApp, '', [testMiddleware]);
|
||||
|
||||
await request(middlewareApp).get(`/${AGENT_CARD_PATH}`).expect(200);
|
||||
|
||||
@ -360,16 +336,17 @@ describe('A2AExpressApp', () => {
|
||||
};
|
||||
|
||||
const middlewareApp = express();
|
||||
setupA2ARoutes(middlewareApp, mockRequestHandler, undefined, '', [errorMiddleware]);
|
||||
app.setupRoutes(middlewareApp, '', [errorMiddleware]);
|
||||
|
||||
await request(middlewareApp).get(`/${AGENT_CARD_PATH}`).expect(500);
|
||||
});
|
||||
|
||||
it('should handle no authentication middlewares', async () => {
|
||||
app = new A2AExpressApp(mockRequestHandler);
|
||||
const middlewareApp = express();
|
||||
setupA2ARoutes(middlewareApp, mockRequestHandler);
|
||||
app.setupRoutes(middlewareApp);
|
||||
|
||||
const mockResponse = {
|
||||
const mockResponse: JSONRPCSuccessResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: 'test-id',
|
||||
result: { message: 'success' },
|
||||
@ -406,12 +383,11 @@ describe('A2AExpressApp', () => {
|
||||
return Promise.resolve(user as User);
|
||||
};
|
||||
|
||||
app = new A2AExpressApp(mockRequestHandler, userExtractor);
|
||||
const middlewareApp = express();
|
||||
setupA2ARoutes(middlewareApp, mockRequestHandler, userExtractor, '', [
|
||||
authenticationMiddleware,
|
||||
]);
|
||||
app.setupRoutes(middlewareApp, '', [authenticationMiddleware]);
|
||||
|
||||
const mockResponse = {
|
||||
const mockResponse: JSONRPCSuccessResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: 'test-id',
|
||||
result: { message: 'success' },
|
||||
@ -456,12 +432,11 @@ describe('A2AExpressApp', () => {
|
||||
return Promise.resolve(convertedUser as User);
|
||||
};
|
||||
|
||||
app = new A2AExpressApp(mockRequestHandler, userExtractor);
|
||||
const middlewareApp = express();
|
||||
setupA2ARoutes(middlewareApp, mockRequestHandler, userExtractor, '', [
|
||||
authenticationMiddleware,
|
||||
]);
|
||||
app.setupRoutes(middlewareApp, '', [authenticationMiddleware]);
|
||||
|
||||
const mockResponse = {
|
||||
const mockResponse: JSONRPCSuccessResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: 'test-id',
|
||||
result: { message: 'success' },
|
||||
@ -494,13 +469,14 @@ describe('A2AExpressApp', () => {
|
||||
next();
|
||||
};
|
||||
|
||||
app = new A2AExpressApp(mockRequestHandler);
|
||||
const middlewareApp = express();
|
||||
setupA2ARoutes(middlewareApp, mockRequestHandler, undefined, '', [authenticationMiddleware]);
|
||||
app.setupRoutes(middlewareApp, '', [authenticationMiddleware]);
|
||||
|
||||
const mockResponse = {
|
||||
const mockResponse: JSONRPCSuccessResponse = {
|
||||
jsonrpc: '2.0',
|
||||
id: 'test-id',
|
||||
result: { message: 'success' } as any,
|
||||
result: { message: 'success' },
|
||||
};
|
||||
handleStub.mockResolvedValue(mockResponse);
|
||||
|
||||
@ -519,21 +495,21 @@ describe('A2AExpressApp', () => {
|
||||
it('should mount routes at baseUrl', async () => {
|
||||
const baseUrl = '/api/v1';
|
||||
const basedApp = express();
|
||||
setupA2ARoutes(basedApp, mockRequestHandler, undefined, baseUrl);
|
||||
app.setupRoutes(basedApp, baseUrl);
|
||||
|
||||
await request(basedApp).get(`${baseUrl}/${AGENT_CARD_PATH}`).expect(200);
|
||||
});
|
||||
|
||||
it('should handle empty baseUrl', async () => {
|
||||
const emptyBaseApp = express();
|
||||
setupA2ARoutes(emptyBaseApp, mockRequestHandler);
|
||||
app.setupRoutes(emptyBaseApp, '');
|
||||
|
||||
await request(emptyBaseApp).get(`/${AGENT_CARD_PATH}`).expect(200);
|
||||
});
|
||||
|
||||
it('should include express.json() middleware by default', async () => {
|
||||
const jsonApp = express();
|
||||
setupA2ARoutes(jsonApp, mockRequestHandler);
|
||||
app.setupRoutes(jsonApp);
|
||||
|
||||
const requestBody = createRpcRequest('test-id', 'message/send', {
|
||||
test: 'data',
|
||||
@ -546,7 +522,7 @@ describe('A2AExpressApp', () => {
|
||||
|
||||
it('should handle malformed json request', async () => {
|
||||
const jsonApp = express();
|
||||
setupA2ARoutes(jsonApp, mockRequestHandler);
|
||||
app.setupRoutes(jsonApp);
|
||||
|
||||
const requestBody = '{"jsonrpc": "2.0", "method": "message/send", "id": "1"'; // Missing closing brace
|
||||
const response = await request(jsonApp)
|
||||
@ -559,7 +535,7 @@ describe('A2AExpressApp', () => {
|
||||
jsonrpc: '2.0',
|
||||
id: null,
|
||||
error: {
|
||||
code: A2A_ERROR_CODE.INVALID_PARAMS,
|
||||
code: -32700,
|
||||
message: 'Invalid JSON payload.',
|
||||
},
|
||||
};
|
||||
@ -4,31 +4,27 @@ import request from 'supertest';
|
||||
|
||||
import { restHandler, UserBuilder } from '../../../src/server/express/index.js';
|
||||
import { A2ARequestHandler } from '../../../src/server/request_handler/a2a_request_handler.js';
|
||||
import { AgentCard, Task, Message, TaskState } from '../../../src/index.js';
|
||||
import { AgentCard, Task, Message } from '../../../src/types.js';
|
||||
import { A2AError } from '../../../src/server/error.js';
|
||||
import { ToProto } from '../../../src/types/converters/to_proto.js';
|
||||
import {
|
||||
RequestMalformedError,
|
||||
TaskNotFoundError,
|
||||
TaskNotCancelableError,
|
||||
} from '../../../src/errors.js';
|
||||
import {
|
||||
ListTaskPushNotificationConfigsResponse,
|
||||
ListTaskPushNotificationConfigResponse,
|
||||
Message as ProtoMessage,
|
||||
SendMessageResponse,
|
||||
TaskPushNotificationConfig,
|
||||
} from '../../../src/types/pb/a2a.js';
|
||||
} from '../../../src/types/pb/a2a_types.js';
|
||||
import { FromProto } from '../../../src/types/converters/from_proto.js';
|
||||
|
||||
/**
|
||||
* Test suite for restHandler - HTTP+JSON/REST transport implementation
|
||||
*
|
||||
* This suite tests the REST API endpoints following the A2A specification:
|
||||
* - GET /extendedAgentCard - Agent card retrieval
|
||||
* - POST /message:send - Send message (non-streaming)
|
||||
* - POST /message:stream - Send message with SSE streaming
|
||||
* - GET /tasks/:taskId - Get task status
|
||||
* - GET /tasks - List tasks
|
||||
* - POST /tasks/:taskId:cancel - Cancel task
|
||||
* - POST /tasks/:taskId:subscribe - Resubscribe to task updates
|
||||
* - GET /v1/card - Agent card retrieval
|
||||
* - POST /v1/message:send - Send message (non-streaming)
|
||||
* - POST /v1/message:stream - Send message with SSE streaming
|
||||
* - GET /v1/tasks/:taskId - Get task status
|
||||
* - POST /v1/tasks/:taskId:cancel - Cancel task
|
||||
* - POST /v1/tasks/:taskId:subscribe - Resubscribe to task updates
|
||||
* - Push notification config CRUD operations
|
||||
*/
|
||||
describe('restHandler', () => {
|
||||
@ -36,58 +32,35 @@ describe('restHandler', () => {
|
||||
let app: Express;
|
||||
|
||||
const testAgentCard: AgentCard = {
|
||||
protocolVersion: '0.3.0',
|
||||
name: 'Test Agent',
|
||||
description: 'An agent for testing purposes',
|
||||
url: 'http://localhost:8080',
|
||||
preferredTransport: 'HTTP+JSON',
|
||||
version: '1.0.0',
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: true,
|
||||
extensions: [],
|
||||
},
|
||||
defaultInputModes: ['text/plain'],
|
||||
defaultOutputModes: ['text/plain'],
|
||||
skills: [],
|
||||
securityRequirements: [],
|
||||
securitySchemes: {},
|
||||
provider: { url: '', organization: '' },
|
||||
signatures: [],
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:8080/v1',
|
||||
protocolBinding: 'HTTP+JSON',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0',
|
||||
},
|
||||
],
|
||||
documentationUrl: '',
|
||||
};
|
||||
|
||||
// camelCase format (internal type)
|
||||
const testMessage: Message = {
|
||||
messageId: 'msg-1',
|
||||
role: 'user' as any,
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: 'Hello' },
|
||||
filename: '',
|
||||
mediaType: 'text/plain',
|
||||
metadata: {},
|
||||
},
|
||||
],
|
||||
contextId: 'ctx-1',
|
||||
taskId: 'task-1',
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
role: 'user' as const,
|
||||
parts: [{ kind: 'text' as const, text: 'Hello' }],
|
||||
kind: 'message' as const,
|
||||
};
|
||||
|
||||
const testTask: Task = {
|
||||
id: 'task-1',
|
||||
status: { state: TaskState.TASK_STATE_COMPLETED, message: undefined, timestamp: undefined },
|
||||
kind: 'task' as const,
|
||||
status: { state: 'completed' as const },
|
||||
contextId: 'ctx-1',
|
||||
history: [],
|
||||
artifacts: [],
|
||||
metadata: {},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
@ -98,12 +71,11 @@ describe('restHandler', () => {
|
||||
sendMessageStream: vi.fn(),
|
||||
getTask: vi.fn(),
|
||||
cancelTask: vi.fn(),
|
||||
createTaskPushNotificationConfig: vi.fn(),
|
||||
setTaskPushNotificationConfig: vi.fn(),
|
||||
getTaskPushNotificationConfig: vi.fn(),
|
||||
listTaskPushNotificationConfigs: vi.fn(),
|
||||
deleteTaskPushNotificationConfig: vi.fn(),
|
||||
resubscribe: vi.fn(),
|
||||
listTasks: vi.fn(),
|
||||
};
|
||||
|
||||
app = express();
|
||||
@ -119,40 +91,49 @@ describe('restHandler', () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('GET /extendedAgentCard', () => {
|
||||
describe('GET /v1/card', () => {
|
||||
it('should return the agent card with 200 OK', async () => {
|
||||
const response = await request(app).get('/extendedAgentCard').expect(200);
|
||||
const response = await request(app).get('/v1/card').expect(200);
|
||||
|
||||
// REST API returns data (format checked by handler)
|
||||
expect(mockRequestHandler.getAuthenticatedExtendedAgentCard as Mock).toHaveBeenCalledTimes(1);
|
||||
assert.deepEqual(response.body.name, testAgentCard.name);
|
||||
});
|
||||
|
||||
it('should return 400 if getAuthenticatedExtendedAgentCard fails', async () => {
|
||||
it('should return 500 if getAuthenticatedExtendedAgentCard fails', async () => {
|
||||
(mockRequestHandler.getAuthenticatedExtendedAgentCard as Mock).mockRejectedValue(
|
||||
new RequestMalformedError('Card fetch failed')
|
||||
A2AError.internalError('Card fetch failed')
|
||||
);
|
||||
|
||||
const response = await request(app).get('/extendedAgentCard').expect(400);
|
||||
const response = await request(app).get('/v1/card').expect(500);
|
||||
|
||||
assert.property(response.body, 'name');
|
||||
assert.property(response.body, 'code');
|
||||
assert.property(response.body, 'message');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /message:send', () => {
|
||||
describe('POST /v1/message:send', () => {
|
||||
it('should accept camelCase message and return 201 with Task', async () => {
|
||||
const message = ProtoMessage.toJSON(testMessage);
|
||||
const message = ProtoMessage.toJSON(ToProto.message(testMessage));
|
||||
(mockRequestHandler.sendMessage as Mock).mockResolvedValue(testTask);
|
||||
|
||||
const response = await request(app).post('/message:send').send({ message }).expect(201);
|
||||
const response = await request(app).post('/v1/message:send').send({ message }).expect(201);
|
||||
|
||||
expect(mockRequestHandler.sendMessage).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: expect.objectContaining({
|
||||
{
|
||||
message: {
|
||||
messageId: 'msg-1',
|
||||
}),
|
||||
}),
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text: 'Hello' }],
|
||||
kind: 'message',
|
||||
contextId: undefined,
|
||||
extensions: [],
|
||||
metadata: undefined,
|
||||
taskId: undefined,
|
||||
},
|
||||
configuration: undefined,
|
||||
metadata: undefined,
|
||||
},
|
||||
expect.anything()
|
||||
);
|
||||
|
||||
@ -166,32 +147,41 @@ describe('restHandler', () => {
|
||||
|
||||
it('should return 400 when message is invalid', async () => {
|
||||
(mockRequestHandler.sendMessage as Mock).mockRejectedValue(
|
||||
new RequestMalformedError('Message is required')
|
||||
A2AError.invalidParams('Message is required')
|
||||
);
|
||||
|
||||
await request(app).post('/message:send').send({ request: null }).expect(400);
|
||||
await request(app).post('/v1/message:send').send({ message: null }).expect(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /message:stream', () => {
|
||||
describe('POST /v1/message:stream', () => {
|
||||
it('should accept camelCase message and stream via SSE', async () => {
|
||||
const message = ProtoMessage.toJSON(testMessage);
|
||||
const message = ProtoMessage.toJSON(ToProto.message(testMessage));
|
||||
async function* mockStream() {
|
||||
yield testMessage;
|
||||
yield testTask;
|
||||
}
|
||||
(mockRequestHandler.sendMessageStream as Mock).mockResolvedValue(mockStream());
|
||||
|
||||
const response = await request(app).post('/message:stream').send({ message }).expect(200);
|
||||
const response = await request(app).post('/v1/message:stream').send({ message }).expect(200);
|
||||
|
||||
assert.equal(response.headers['content-type'], 'text/event-stream');
|
||||
|
||||
expect(mockRequestHandler.sendMessageStream).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: expect.objectContaining({
|
||||
{
|
||||
message: {
|
||||
messageId: 'msg-1',
|
||||
}),
|
||||
}),
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text: 'Hello' }],
|
||||
kind: 'message',
|
||||
contextId: undefined,
|
||||
extensions: [],
|
||||
metadata: undefined,
|
||||
taskId: undefined,
|
||||
},
|
||||
configuration: undefined,
|
||||
metadata: undefined,
|
||||
},
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
@ -212,15 +202,18 @@ describe('restHandler', () => {
|
||||
})
|
||||
);
|
||||
|
||||
await request(noStreamApp).post('/message:stream').send({ request: testMessage }).expect(400);
|
||||
await request(noStreamApp)
|
||||
.post('/v1/message:stream')
|
||||
.send({ message: testMessage })
|
||||
.expect(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /tasks/:taskId', () => {
|
||||
describe('GET /v1/tasks/:taskId', () => {
|
||||
it('should return task with 200 OK', async () => {
|
||||
(mockRequestHandler.getTask as Mock).mockResolvedValue(testTask);
|
||||
|
||||
const response = await request(app).get('/tasks/task-1').expect(200);
|
||||
const response = await request(app).get('/v1/tasks/task-1').expect(200);
|
||||
|
||||
assert.deepEqual(response.body.id, testTask.id);
|
||||
// Kind is not present in Proto JSON
|
||||
@ -228,7 +221,7 @@ describe('restHandler', () => {
|
||||
// Status state is enum string
|
||||
assert.deepEqual(response.body.status.state, 'TASK_STATE_COMPLETED');
|
||||
expect(mockRequestHandler.getTask as Mock).toHaveBeenCalledWith(
|
||||
{ id: 'task-1', tenant: '', historyLength: 0 },
|
||||
{ id: 'task-1' },
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
@ -236,12 +229,11 @@ describe('restHandler', () => {
|
||||
it('should support historyLength query parameter', async () => {
|
||||
(mockRequestHandler.getTask as Mock).mockResolvedValue(testTask);
|
||||
|
||||
await request(app).get('/tasks/task-1?historyLength=10').expect(200);
|
||||
await request(app).get('/v1/tasks/task-1?historyLength=10').expect(200);
|
||||
|
||||
expect(mockRequestHandler.getTask as Mock).toHaveBeenCalledWith(
|
||||
{
|
||||
id: 'task-1',
|
||||
tenant: '',
|
||||
historyLength: 10,
|
||||
},
|
||||
expect.anything()
|
||||
@ -249,111 +241,57 @@ describe('restHandler', () => {
|
||||
});
|
||||
|
||||
it('should return 400 if historyLength is invalid', async () => {
|
||||
await request(app).get('/tasks/task-1?historyLength=invalid').expect(400);
|
||||
await request(app).get('/v1/tasks/task-1?historyLength=invalid').expect(400);
|
||||
});
|
||||
|
||||
it('should return 404 if task is not found', async () => {
|
||||
(mockRequestHandler.getTask as Mock).mockRejectedValue(new TaskNotFoundError('task-1'));
|
||||
(mockRequestHandler.getTask as Mock).mockRejectedValue(A2AError.taskNotFound('task-1'));
|
||||
|
||||
const response = await request(app).get('/tasks/task-1').expect(404);
|
||||
const response = await request(app).get('/v1/tasks/task-1').expect(404);
|
||||
|
||||
assert.property(response.body, 'name');
|
||||
assert.property(response.body, 'code');
|
||||
assert.property(response.body, 'message');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /tasks/:taskId:cancel', () => {
|
||||
describe('POST /v1/tasks/:taskId:cancel', () => {
|
||||
it('should cancel task and return 202 Accepted', async () => {
|
||||
const cancelledTask = {
|
||||
...testTask,
|
||||
status: { state: TaskState.TASK_STATE_CANCELED },
|
||||
};
|
||||
const cancelledTask = { ...testTask, status: { state: 'canceled' as const } };
|
||||
(mockRequestHandler.cancelTask as Mock).mockResolvedValue(cancelledTask);
|
||||
|
||||
const response = await request(app).post('/tasks/task-1:cancel').expect(202);
|
||||
const response = await request(app).post('/v1/tasks/task-1:cancel').expect(202);
|
||||
|
||||
assert.deepEqual(response.body.id, cancelledTask.id);
|
||||
assert.deepEqual(response.body.status.state, 'TASK_STATE_CANCELED');
|
||||
expect(mockRequestHandler.cancelTask as Mock).toHaveBeenCalledWith(
|
||||
{ id: 'task-1', tenant: '', metadata: {} },
|
||||
assert.deepEqual(response.body.status.state, 'TASK_STATE_CANCELLED');
|
||||
|
||||
expect(mockRequestHandler.cancelTask).toHaveBeenCalledWith(
|
||||
{ id: 'task-1' },
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('should return 404 if task is not found', async () => {
|
||||
(mockRequestHandler.cancelTask as Mock).mockRejectedValue(new TaskNotFoundError('task-1'));
|
||||
(mockRequestHandler.cancelTask as Mock).mockRejectedValue(A2AError.taskNotFound('task-1'));
|
||||
|
||||
const response = await request(app).post('/tasks/task-1:cancel').expect(404);
|
||||
const response = await request(app).post('/v1/tasks/task-1:cancel').expect(404);
|
||||
|
||||
assert.property(response.body, 'name');
|
||||
assert.property(response.body, 'code');
|
||||
assert.property(response.body, 'message');
|
||||
});
|
||||
|
||||
it('should return 409 if task is not cancelable', async () => {
|
||||
(mockRequestHandler.cancelTask as Mock).mockRejectedValue(
|
||||
new TaskNotCancelableError('task-1')
|
||||
A2AError.taskNotCancelable('task-1')
|
||||
);
|
||||
|
||||
const response = await request(app).post('/tasks/task-1:cancel').expect(409);
|
||||
const response = await request(app).post('/v1/tasks/task-1:cancel').expect(409);
|
||||
|
||||
assert.property(response.body, 'name');
|
||||
assert.property(response.body, 'code');
|
||||
assert.property(response.body, 'message');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /tasks', () => {
|
||||
it('should list a single task', async () => {
|
||||
const tasks = [testTask];
|
||||
(mockRequestHandler.listTasks as Mock).mockResolvedValue({ tasks });
|
||||
|
||||
const response = await request(app).get('/tasks').expect(200);
|
||||
|
||||
const expectedResponse = [
|
||||
{
|
||||
id: testTask.id,
|
||||
contextId: testTask.contextId,
|
||||
status: {
|
||||
state: 'TASK_STATE_COMPLETED',
|
||||
},
|
||||
metadata: testTask.metadata,
|
||||
},
|
||||
];
|
||||
|
||||
assert.deepEqual(response.body.tasks, expectedResponse);
|
||||
expect(mockRequestHandler.listTasks as Mock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should list multiple tasks', async () => {
|
||||
const tasks = [testTask, { ...testTask, id: 'task-2' }];
|
||||
(mockRequestHandler.listTasks as Mock).mockResolvedValue({ tasks });
|
||||
|
||||
const response = await request(app).get('/tasks').expect(200);
|
||||
|
||||
const expectedResponse = [
|
||||
{
|
||||
id: testTask.id,
|
||||
contextId: testTask.contextId,
|
||||
status: {
|
||||
state: 'TASK_STATE_COMPLETED',
|
||||
},
|
||||
metadata: testTask.metadata,
|
||||
},
|
||||
{
|
||||
id: 'task-2',
|
||||
contextId: testTask.contextId,
|
||||
status: {
|
||||
state: 'TASK_STATE_COMPLETED',
|
||||
},
|
||||
metadata: testTask.metadata,
|
||||
},
|
||||
];
|
||||
|
||||
assert.deepEqual(response.body.tasks, expectedResponse);
|
||||
expect(mockRequestHandler.listTasks as Mock).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /tasks/:taskId:subscribe', () => {
|
||||
describe('POST /v1/tasks/:taskId:subscribe', () => {
|
||||
it('should resubscribe to task updates via SSE', async () => {
|
||||
async function* mockStream() {
|
||||
yield testTask;
|
||||
@ -361,11 +299,12 @@ describe('restHandler', () => {
|
||||
|
||||
(mockRequestHandler.resubscribe as Mock).mockResolvedValue(mockStream());
|
||||
|
||||
const response = await request(app).post('/tasks/task-1:subscribe').expect(200);
|
||||
const response = await request(app).post('/v1/tasks/task-1:subscribe').expect(200);
|
||||
|
||||
assert.equal(response.headers['content-type'], 'text/event-stream');
|
||||
expect(mockRequestHandler.resubscribe as Mock).toHaveBeenCalledWith(
|
||||
{ id: 'task-1', tenant: '' },
|
||||
|
||||
expect(mockRequestHandler.resubscribe).toHaveBeenCalledWith(
|
||||
{ id: 'task-1' },
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
@ -387,54 +326,77 @@ describe('restHandler', () => {
|
||||
})
|
||||
);
|
||||
|
||||
const response = await request(noStreamApp).post('/tasks/task-1:subscribe').expect(400);
|
||||
const response = await request(noStreamApp).post('/v1/tasks/task-1:subscribe').expect(400);
|
||||
|
||||
assert.property(response.body, 'name');
|
||||
assert.property(response.body, 'code');
|
||||
assert.property(response.body, 'message');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Push Notification Config Endpoints', () => {
|
||||
const mockConfig: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
const mockConfig = {
|
||||
taskId: 'task-1',
|
||||
id: 'config-1',
|
||||
url: 'https://example.com/webhook',
|
||||
token: '',
|
||||
authentication: undefined,
|
||||
pushNotificationConfig: {
|
||||
id: 'config-1',
|
||||
url: 'https://example.com/webhook',
|
||||
},
|
||||
};
|
||||
|
||||
describe('POST /tasks/:taskId/pushNotificationConfigs', () => {
|
||||
describe('POST /v1/tasks/:taskId/pushNotificationConfigs', () => {
|
||||
it.each([
|
||||
{
|
||||
name: 'camelCase',
|
||||
payload: {
|
||||
id: 'push-954f670f-598d-49bf-9981-642d523f7746',
|
||||
url: 'http://127.0.0.1:9999/webhook',
|
||||
taskId: 'task-1',
|
||||
tenant: '',
|
||||
parent: 'tasks/task-1',
|
||||
configId: 'push-954f670f-598d-49bf-9981-642d523f7746',
|
||||
config: {
|
||||
name: 'tasks/task-1/pushNotificationConfigs/push-954f670f-598d-49bf-9981-642d523f7746',
|
||||
pushNotificationConfig: {
|
||||
id: 'push-954f670f-598d-49bf-9981-642d523f7746',
|
||||
url: 'http://127.0.0.1:9999/webhook',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'snake_case',
|
||||
payload: {
|
||||
id: 'push-954f670f-598d-49bf-9981-642d523f7746',
|
||||
url: 'http://127.0.0.1:9999/webhook',
|
||||
taskId: 'task-1',
|
||||
tenant: '',
|
||||
parent: 'tasks/task-1',
|
||||
config_id: 'push-954f670f-598d-49bf-9981-642d523f7746',
|
||||
config: {
|
||||
name: 'tasks/task-1/pushNotificationConfigs/push-954f670f-598d-49bf-9981-642d523f7746',
|
||||
push_notification_config: {
|
||||
id: 'push-954f670f-598d-49bf-9981-642d523f7746',
|
||||
url: 'http://127.0.0.1:9999/webhook',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
])('should accept $name config and return 201', async ({ payload }) => {
|
||||
(mockRequestHandler.createTaskPushNotificationConfig as Mock).mockResolvedValue(mockConfig);
|
||||
(mockRequestHandler.setTaskPushNotificationConfig as Mock).mockResolvedValue(mockConfig);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/tasks/task-1/pushNotificationConfigs')
|
||||
.post('/v1/tasks/task-1/pushNotificationConfigs')
|
||||
.send(payload)
|
||||
.expect(201);
|
||||
|
||||
const protoResponse = TaskPushNotificationConfig.fromJSON(response.body);
|
||||
assert.equal(protoResponse.taskId, 'task-1');
|
||||
assert.equal(protoResponse.id, 'config-1');
|
||||
const protoResponse = FromProto.taskPushNotificationConfig(
|
||||
TaskPushNotificationConfig.fromJSON(response.body)
|
||||
);
|
||||
assert.deepEqual(protoResponse.taskId, mockConfig.taskId);
|
||||
|
||||
expect(mockRequestHandler.setTaskPushNotificationConfig).toHaveBeenCalledWith(
|
||||
{
|
||||
taskId: 'task-1',
|
||||
pushNotificationConfig: {
|
||||
id: 'push-954f670f-598d-49bf-9981-642d523f7746',
|
||||
url: 'http://127.0.0.1:9999/webhook',
|
||||
token: undefined,
|
||||
authentication: undefined,
|
||||
},
|
||||
},
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('should return 400 if push notifications not supported', async () => {
|
||||
@ -454,97 +416,90 @@ describe('restHandler', () => {
|
||||
);
|
||||
|
||||
await request(noPNApp)
|
||||
.post('/tasks/task-1/pushNotificationConfigs')
|
||||
.send({
|
||||
pushNotificationConfig: {
|
||||
id: 'config-1',
|
||||
url: 'https://example.com/webhook',
|
||||
token: '',
|
||||
authentication: undefined,
|
||||
},
|
||||
})
|
||||
.post('/v1/tasks/task-1/pushNotificationConfigs')
|
||||
.send({ pushNotificationConfig: { id: 'config-1', url: 'https://example.com/webhook' } })
|
||||
.expect(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /tasks/:taskId/pushNotificationConfigs', () => {
|
||||
describe('GET /v1/tasks/:taskId/pushNotificationConfigs', () => {
|
||||
it('should list push notification configs and return 200', async () => {
|
||||
const configs = [mockConfig];
|
||||
(mockRequestHandler.listTaskPushNotificationConfigs as Mock).mockResolvedValue(configs);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/tasks/task-1/pushNotificationConfigs')
|
||||
.get('/v1/tasks/task-1/pushNotificationConfigs')
|
||||
.expect(200);
|
||||
|
||||
const convertedResult = ListTaskPushNotificationConfigsResponse.fromJSON(
|
||||
response.body
|
||||
).configs;
|
||||
const convertedResult = FromProto.listTaskPushNotificationConfig(
|
||||
ListTaskPushNotificationConfigResponse.fromJSON(response.body)
|
||||
);
|
||||
assert.isArray(convertedResult);
|
||||
assert.lengthOf(convertedResult, configs.length);
|
||||
|
||||
expect(mockRequestHandler.listTaskPushNotificationConfigs).toHaveBeenCalledWith(
|
||||
{ id: 'task-1' },
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /tasks/:taskId/pushNotificationConfigs/:configId', () => {
|
||||
describe('GET /v1/tasks/:taskId/pushNotificationConfigs/:configId', () => {
|
||||
it('should get specific push notification config and return 200', async () => {
|
||||
(mockRequestHandler.getTaskPushNotificationConfig as Mock).mockResolvedValue(mockConfig);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/tasks/task-1/pushNotificationConfigs/config-1')
|
||||
.get('/v1/tasks/task-1/pushNotificationConfigs/config-1')
|
||||
.expect(200);
|
||||
|
||||
// REST API returns camelCase
|
||||
const convertedResult = TaskPushNotificationConfig.fromJSON(response.body);
|
||||
assert.equal(convertedResult.taskId, 'task-1');
|
||||
expect(mockRequestHandler.getTaskPushNotificationConfig as Mock).toHaveBeenCalledWith(
|
||||
{
|
||||
id: 'config-1',
|
||||
taskId: 'task-1',
|
||||
tenant: '',
|
||||
},
|
||||
const convertedResult = FromProto.taskPushNotificationConfig(
|
||||
TaskPushNotificationConfig.fromJSON(response.body)
|
||||
);
|
||||
assert.deepEqual(convertedResult.taskId, mockConfig.taskId);
|
||||
|
||||
expect(mockRequestHandler.getTaskPushNotificationConfig).toHaveBeenCalledWith(
|
||||
{ id: 'task-1', pushNotificationConfigId: 'config-1' },
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('should return 404 if config not found', async () => {
|
||||
(mockRequestHandler.getTaskPushNotificationConfig as Mock).mockRejectedValue(
|
||||
new TaskNotFoundError('task-1')
|
||||
A2AError.taskNotFound('task-1')
|
||||
);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/tasks/task-1/pushNotificationConfigs/config-1')
|
||||
.get('/v1/tasks/task-1/pushNotificationConfigs/config-1')
|
||||
.expect(404);
|
||||
|
||||
assert.property(response.body, 'name');
|
||||
assert.property(response.body, 'code');
|
||||
assert.property(response.body, 'message');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /tasks/:taskId/pushNotificationConfigs/:configId', () => {
|
||||
describe('DELETE /v1/tasks/:taskId/pushNotificationConfigs/:configId', () => {
|
||||
it('should delete push notification config and return 204', async () => {
|
||||
(mockRequestHandler.deleteTaskPushNotificationConfig as Mock).mockResolvedValue(undefined);
|
||||
|
||||
await request(app).delete('/tasks/task-1/pushNotificationConfigs/config-1').expect(204);
|
||||
await request(app).delete('/v1/tasks/task-1/pushNotificationConfigs/config-1').expect(204);
|
||||
|
||||
expect(mockRequestHandler.deleteTaskPushNotificationConfig as Mock).toHaveBeenCalledWith(
|
||||
{
|
||||
id: 'config-1',
|
||||
taskId: 'task-1',
|
||||
tenant: '',
|
||||
},
|
||||
expect(mockRequestHandler.deleteTaskPushNotificationConfig).toHaveBeenCalledWith(
|
||||
{ id: 'task-1', pushNotificationConfigId: 'config-1' },
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('should return 404 if config not found', async () => {
|
||||
(mockRequestHandler.deleteTaskPushNotificationConfig as Mock).mockRejectedValue(
|
||||
new TaskNotFoundError('task-1')
|
||||
A2AError.taskNotFound('task-1')
|
||||
);
|
||||
|
||||
const response = await request(app)
|
||||
.delete('/tasks/task-1/pushNotificationConfigs/config-1')
|
||||
.delete('/v1/tasks/task-1/pushNotificationConfigs/config-1')
|
||||
.expect(404);
|
||||
|
||||
assert.property(response.body, 'name');
|
||||
assert.property(response.body, 'code');
|
||||
assert.property(response.body, 'message');
|
||||
});
|
||||
});
|
||||
@ -609,7 +564,41 @@ describe('restHandler', () => {
|
||||
},
|
||||
])('should accept $name message parts', async ({ payload }) => {
|
||||
(mockRequestHandler.sendMessage as Mock).mockResolvedValue(testTask);
|
||||
await request(app).post('/message:send').send(payload).expect(201);
|
||||
await request(app).post('/v1/message:send').send(payload).expect(201);
|
||||
|
||||
expect(mockRequestHandler.sendMessage).toHaveBeenCalledWith(
|
||||
{
|
||||
message: {
|
||||
kind: 'message',
|
||||
messageId: 'msg-parts',
|
||||
role: 'user', // ROLE_USER is converted to 'user'
|
||||
parts: [
|
||||
{
|
||||
kind: 'file',
|
||||
file: {
|
||||
uri: 'https://example.com/file.pdf',
|
||||
mimeType: 'application/pdf',
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
text: 'Hello world',
|
||||
},
|
||||
{
|
||||
kind: 'data',
|
||||
data: { foo: 'bar' },
|
||||
},
|
||||
],
|
||||
contextId: undefined,
|
||||
extensions: [],
|
||||
metadata: undefined,
|
||||
taskId: undefined,
|
||||
},
|
||||
configuration: undefined,
|
||||
metadata: undefined,
|
||||
},
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@ -621,49 +610,54 @@ describe('restHandler', () => {
|
||||
{
|
||||
name: 'camelCase',
|
||||
payload: {
|
||||
message: testMessage,
|
||||
message: { messageId: 'msg-1', role: 'ROLE_USER', kind: 'message' },
|
||||
configuration: { acceptedOutputModes: ['text/plain'], historyLength: 5 },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'snake_case',
|
||||
payload: {
|
||||
message: {
|
||||
message_id: 'msg-1',
|
||||
role: 'ROLE_USER',
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: 'Hello' },
|
||||
filename: '',
|
||||
media_type: 'text/plain',
|
||||
metadata: {},
|
||||
},
|
||||
],
|
||||
},
|
||||
message: { message_id: 'msg-1', role: 'ROLE_USER', kind: 'message' },
|
||||
configuration: { accepted_output_modes: ['text/plain'], history_length: 5 },
|
||||
},
|
||||
},
|
||||
])('should accept $name configuration fields', async ({ payload }) => {
|
||||
(mockRequestHandler.sendMessage as Mock).mockResolvedValue(testTask);
|
||||
await request(app).post('/message:send').send(payload).expect(201);
|
||||
await request(app).post('/v1/message:send').send(payload).expect(201);
|
||||
|
||||
const protoMessage = ProtoMessage.toJSON(testMessage);
|
||||
await request(app)
|
||||
.post('/message:send')
|
||||
.send({ message: protoMessage, configuration: payload.configuration })
|
||||
.expect(201);
|
||||
expect(mockRequestHandler.sendMessage).toHaveBeenCalledWith(
|
||||
{
|
||||
message: {
|
||||
kind: 'message',
|
||||
messageId: 'msg-1',
|
||||
role: 'user', // ROLE_USER is converted to 'user'
|
||||
parts: [], // empty content converts to empty parts
|
||||
contextId: undefined,
|
||||
extensions: [],
|
||||
metadata: undefined,
|
||||
taskId: undefined,
|
||||
},
|
||||
configuration: {
|
||||
acceptedOutputModes: ['text/plain'],
|
||||
blocking: false,
|
||||
pushNotificationConfig: undefined,
|
||||
},
|
||||
metadata: undefined,
|
||||
},
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('should return 404 for unknown message action (route not matched)', async () => {
|
||||
// Unknown actions don't match the route pattern, so Express returns default 404
|
||||
await request(app).post('/message:unknown').send({ request: testMessage }).expect(404);
|
||||
await request(app).post('/v1/message:unknown').send({ message: testMessage }).expect(404);
|
||||
});
|
||||
|
||||
it('should return 404 for unknown task action (route not matched)', async () => {
|
||||
// Unknown actions don't match the route pattern, so Express returns default 404
|
||||
await request(app).post('/tasks/task-1:unknown').expect(404);
|
||||
await request(app).post('/v1/tasks/task-1:unknown').expect(404);
|
||||
});
|
||||
|
||||
it('should handle internal server errors gracefully', async () => {
|
||||
@ -671,15 +665,15 @@ describe('restHandler', () => {
|
||||
new Error('Unexpected internal error')
|
||||
);
|
||||
|
||||
const messageProto = ProtoMessage.toJSON(testMessage);
|
||||
const messageProto = ProtoMessage.toJSON(ToProto.message(testMessage));
|
||||
const response = await request(app)
|
||||
.post('/message:send')
|
||||
.post('/v1/message:send')
|
||||
.send({ message: messageProto })
|
||||
.expect(500);
|
||||
|
||||
assert.property(response.body, 'name');
|
||||
assert.property(response.body, 'code');
|
||||
assert.property(response.body, 'message');
|
||||
assert.deepEqual(response.body.name, 'Error'); // Generic Error instance
|
||||
assert.deepEqual(response.body.code, -32603); // Internal error code
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,114 +1,259 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { FromProto } from '../../../src/types/converters/from_proto.js';
|
||||
import * as proto from '../../../src/types/pb/a2a.js';
|
||||
import { GenericError } from '../../../src/errors.js';
|
||||
import * as proto from '../../../src/types/pb/a2a_types.js';
|
||||
import * as idDecoding from '../../../src/types/converters/id_decoding.js';
|
||||
import { A2AError } from '../../../src/server/index.js';
|
||||
|
||||
vi.mock('../../../src/types/converters/id_decoding.js', () => ({
|
||||
extractTaskId: vi.fn(),
|
||||
extractTaskAndPushNotificationConfigId: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('FromProto', () => {
|
||||
describe('sendMessageResult', () => {
|
||||
it('should return task if payload is task', () => {
|
||||
const task: proto.Task = {
|
||||
id: 'task-1',
|
||||
history: [],
|
||||
artifacts: [],
|
||||
metadata: {},
|
||||
status: {
|
||||
state: proto.TaskState.TASK_STATE_COMPLETED,
|
||||
timestamp: undefined,
|
||||
message: undefined,
|
||||
} as proto.TaskStatus,
|
||||
contextId: '',
|
||||
};
|
||||
const response: proto.SendMessageResponse = {
|
||||
payload: { $case: 'task', value: task },
|
||||
};
|
||||
expect(FromProto.sendMessageResult(response)).toEqual(task);
|
||||
beforeEach(() => {
|
||||
vi.mocked(idDecoding.extractTaskId).mockReturnValue('task-123');
|
||||
vi.mocked(idDecoding.extractTaskAndPushNotificationConfigId).mockReturnValue({
|
||||
taskId: 'task-123',
|
||||
configId: 'pnc-456',
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert GetTaskRequest to taskQueryParams', () => {
|
||||
const request: proto.GetTaskRequest = {
|
||||
name: 'tasks/task-123',
|
||||
historyLength: 10,
|
||||
};
|
||||
const result = FromProto.taskQueryParams(request);
|
||||
expect(idDecoding.extractTaskId).toHaveBeenCalledWith('tasks/task-123');
|
||||
expect(result).toEqual({
|
||||
id: 'task-123',
|
||||
historyLength: 10,
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert CancelTaskRequest to taskIdParams', () => {
|
||||
const request: proto.CancelTaskRequest = {
|
||||
name: 'tasks/task-123',
|
||||
};
|
||||
const result = FromProto.taskIdParams(request);
|
||||
expect(idDecoding.extractTaskId).toHaveBeenCalledWith('tasks/task-123');
|
||||
expect(result).toEqual({
|
||||
id: 'task-123',
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert GetTaskPushNotificationConfigRequest to params', () => {
|
||||
const request: proto.GetTaskPushNotificationConfigRequest = {
|
||||
name: 'tasks/task-123/pushNotificationConfigs/pnc-456',
|
||||
};
|
||||
const result = FromProto.getTaskPushNotificationConfigParams(request);
|
||||
expect(idDecoding.extractTaskAndPushNotificationConfigId).toHaveBeenCalledWith(request.name);
|
||||
expect(result).toEqual({
|
||||
id: 'task-123',
|
||||
pushNotificationConfigId: 'pnc-456',
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert ListTaskPushNotificationConfigRequest to params', () => {
|
||||
const request: proto.ListTaskPushNotificationConfigRequest = {
|
||||
parent: 'tasks/task-123',
|
||||
pageToken: '',
|
||||
pageSize: 0,
|
||||
};
|
||||
const result = FromProto.listTaskPushNotificationConfigParams(request);
|
||||
expect(idDecoding.extractTaskId).toHaveBeenCalledWith(request.parent);
|
||||
expect(result).toEqual({
|
||||
id: 'task-123',
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert CreateTaskPushNotificationConfigRequest to params', () => {
|
||||
const request: proto.TaskPushNotificationConfig = {
|
||||
name: 'tasks/task-123/pushNotificationConfigs/pnc-456',
|
||||
pushNotificationConfig: {
|
||||
id: 'pnc-456',
|
||||
url: 'http://example.com',
|
||||
token: 'token-abc',
|
||||
authentication: undefined,
|
||||
},
|
||||
};
|
||||
const result = FromProto.taskPushNotificationConfig(request);
|
||||
expect(idDecoding.extractTaskId).toHaveBeenCalledWith(request.name);
|
||||
expect(result).toEqual({
|
||||
taskId: 'task-123',
|
||||
pushNotificationConfig: {
|
||||
id: 'pnc-456',
|
||||
url: 'http://example.com',
|
||||
token: 'token-abc',
|
||||
authentication: undefined,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert DeleteTaskPushNotificationConfigRequest to params', () => {
|
||||
const request: proto.DeleteTaskPushNotificationConfigRequest = {
|
||||
name: 'tasks/task-123/pushNotificationConfigs/pnc-456',
|
||||
};
|
||||
const result = FromProto.deleteTaskPushNotificationConfigParams(request);
|
||||
expect(idDecoding.extractTaskAndPushNotificationConfigId).toHaveBeenCalledWith(request.name);
|
||||
expect(result).toEqual({
|
||||
id: 'task-123',
|
||||
pushNotificationConfigId: 'pnc-456',
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert proto Message to internal Message', () => {
|
||||
const protoMessage: proto.Message = {
|
||||
messageId: 'msg-1',
|
||||
content: [],
|
||||
contextId: 'ctx-1',
|
||||
taskId: 'task-1',
|
||||
role: proto.Role.ROLE_AGENT,
|
||||
metadata: { key: 'value' },
|
||||
extensions: ['ext1'],
|
||||
};
|
||||
const result = FromProto.message(protoMessage);
|
||||
expect(result).toEqual({
|
||||
kind: 'message',
|
||||
messageId: 'msg-1',
|
||||
parts: [],
|
||||
contextId: 'ctx-1',
|
||||
taskId: 'task-1',
|
||||
role: 'agent',
|
||||
metadata: { key: 'value' },
|
||||
extensions: ['ext1'],
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert proto SendMessageConfiguration to internal type', () => {
|
||||
const protoConfig: proto.SendMessageConfiguration = {
|
||||
blocking: true,
|
||||
acceptedOutputModes: ['text/plain'],
|
||||
pushNotification: {
|
||||
id: 'pnc-1',
|
||||
url: 'http://notify.me',
|
||||
token: 'token',
|
||||
authentication: undefined,
|
||||
},
|
||||
historyLength: 0,
|
||||
};
|
||||
const result = FromProto.messageSendConfiguration(protoConfig);
|
||||
expect(result).toEqual({
|
||||
blocking: true,
|
||||
acceptedOutputModes: ['text/plain'],
|
||||
pushNotificationConfig: {
|
||||
id: 'pnc-1',
|
||||
url: 'http://notify.me',
|
||||
token: 'token',
|
||||
authentication: undefined,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert proto AuthenticationInfo to internal type', () => {
|
||||
const authInfo: proto.AuthenticationInfo = {
|
||||
schemes: ['bearer'],
|
||||
credentials: 'bearer-token',
|
||||
};
|
||||
const result = FromProto.pushNotificationAuthenticationInfo(authInfo);
|
||||
expect(result).toEqual({
|
||||
schemes: ['bearer'],
|
||||
credentials: 'bearer-token',
|
||||
});
|
||||
});
|
||||
|
||||
describe('parts', () => {
|
||||
it('should convert a text part', () => {
|
||||
const part: proto.Part = { part: { $case: 'text', value: 'hello' } };
|
||||
const result = FromProto.part(part);
|
||||
expect(result).toEqual({ kind: 'text', text: 'hello' });
|
||||
});
|
||||
|
||||
it('should return message if payload is msg', () => {
|
||||
const msg: proto.Message = {
|
||||
it('should convert a file part with URI', () => {
|
||||
const part: proto.Part = {
|
||||
part: {
|
||||
$case: 'file',
|
||||
value: {
|
||||
file: { $case: 'fileWithUri', value: 'file://path/to/file' },
|
||||
mimeType: 'text/plain',
|
||||
},
|
||||
},
|
||||
};
|
||||
const result = FromProto.part(part);
|
||||
expect(result).toEqual({
|
||||
kind: 'file',
|
||||
file: { mimeType: 'text/plain', uri: 'file://path/to/file' },
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert a file part with bytes', () => {
|
||||
const bytes = Buffer.from('file content');
|
||||
const part: proto.Part = {
|
||||
part: {
|
||||
$case: 'file',
|
||||
value: { file: { $case: 'fileWithBytes', value: bytes }, mimeType: 'text/plain' },
|
||||
},
|
||||
};
|
||||
const result = FromProto.part(part);
|
||||
expect(result).toEqual({
|
||||
kind: 'file',
|
||||
file: { bytes: bytes.toString('base64'), mimeType: 'text/plain' },
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw for invalid file part', () => {
|
||||
const part: proto.Part = {
|
||||
part: {
|
||||
$case: 'file',
|
||||
value: {
|
||||
file: { $case: 'wrong format', value: 'invalid bytes' } as any,
|
||||
mimeType: 'text/plain',
|
||||
}, // Invalid state
|
||||
},
|
||||
};
|
||||
expect(() => FromProto.part(part)).toThrow(new A2AError(-32602, 'Invalid file part type'));
|
||||
});
|
||||
|
||||
it('should convert a data part', () => {
|
||||
const data = { foo: 'bar' };
|
||||
const part: proto.Part = { part: { $case: 'data', value: { data } } };
|
||||
const result = FromProto.part(part);
|
||||
expect(result).toEqual({ kind: 'data', data });
|
||||
});
|
||||
|
||||
it('should throw for an unknown part type', () => {
|
||||
const part: proto.Part = { part: { $case: 'invalid', value: undefined } as any }; // Invalid state
|
||||
expect(() => FromProto.part(part)).toThrow(new A2AError(-32602, 'Invalid part type'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert SendMessageRequest to messageSendParams', () => {
|
||||
const request: proto.SendMessageRequest = {
|
||||
request: {
|
||||
messageId: 'msg-1',
|
||||
content: [],
|
||||
contextId: 'ctx-1',
|
||||
taskId: 'task-1',
|
||||
role: proto.Role.ROLE_USER,
|
||||
parts: [],
|
||||
metadata: {},
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
taskId: '',
|
||||
contextId: '',
|
||||
referenceTaskIds: [],
|
||||
};
|
||||
const response: proto.SendMessageResponse = {
|
||||
payload: { $case: 'message', value: msg },
|
||||
};
|
||||
expect(FromProto.sendMessageResult(response)).toEqual(msg);
|
||||
});
|
||||
},
|
||||
configuration: {
|
||||
blocking: false,
|
||||
acceptedOutputModes: [],
|
||||
pushNotification: undefined,
|
||||
historyLength: 0,
|
||||
},
|
||||
metadata: { client: 'test' },
|
||||
};
|
||||
|
||||
it('should throw GenericError if payload is missing', () => {
|
||||
const response: proto.SendMessageResponse = {};
|
||||
let err: GenericError | undefined;
|
||||
try {
|
||||
FromProto.sendMessageResult(response);
|
||||
} catch (error) {
|
||||
err = error as GenericError;
|
||||
}
|
||||
expect(err).toBeInstanceOf(GenericError);
|
||||
expect(err?.message).toContain('Invalid SendMessageResponse: missing result');
|
||||
});
|
||||
const result = FromProto.messageSendParams(request);
|
||||
|
||||
it('should throw GenericError if payload case is invalid', () => {
|
||||
const response = {
|
||||
payload: { $case: 'streamError', value: undefined as any },
|
||||
} as unknown as proto.SendMessageResponse;
|
||||
let err: GenericError | undefined;
|
||||
try {
|
||||
FromProto.sendMessageResult(response);
|
||||
} catch (error) {
|
||||
err = error as GenericError;
|
||||
}
|
||||
expect(err).toBeInstanceOf(GenericError);
|
||||
expect(err?.message).toContain('Invalid SendMessageResponse: missing result');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listTaskPushNotificationConfig', () => {
|
||||
it('should return configs array', () => {
|
||||
const configs: proto.TaskPushNotificationConfig[] = [
|
||||
{ tenant: '', taskId: '', id: 'config-1', url: '', token: '', authentication: undefined },
|
||||
];
|
||||
const response: proto.ListTaskPushNotificationConfigsResponse = {
|
||||
configs,
|
||||
nextPageToken: '',
|
||||
};
|
||||
expect(FromProto.listTaskPushNotificationConfig(response)).toEqual(configs);
|
||||
});
|
||||
});
|
||||
|
||||
describe('messageStreamResult', () => {
|
||||
it('should return payload value if payload is present', () => {
|
||||
const task: proto.Task = {
|
||||
id: 'task-1',
|
||||
history: [],
|
||||
artifacts: [],
|
||||
metadata: {},
|
||||
status: {
|
||||
state: proto.TaskState.TASK_STATE_COMPLETED,
|
||||
timestamp: undefined,
|
||||
message: undefined,
|
||||
} as proto.TaskStatus,
|
||||
contextId: '',
|
||||
};
|
||||
const event: proto.StreamResponse = {
|
||||
payload: { $case: 'task', value: task },
|
||||
};
|
||||
expect(FromProto.messageStreamResult(event)).toEqual(task);
|
||||
});
|
||||
|
||||
it('should throw GenericError if payload is missing', () => {
|
||||
const event: proto.StreamResponse = {};
|
||||
try {
|
||||
FromProto.messageStreamResult(event);
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(GenericError);
|
||||
expect((error as GenericError).message).toContain('Invalid event type in StreamResponse');
|
||||
}
|
||||
expect(result).toEqual({
|
||||
message: expect.any(Object),
|
||||
configuration: expect.any(Object),
|
||||
metadata: { client: 'test' },
|
||||
});
|
||||
expect(result.message.role).toBe('user');
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,58 +1,37 @@
|
||||
import { describe, it, beforeEach, afterEach, assert, expect, vi, Mock } from 'vitest';
|
||||
import * as grpc from '@grpc/grpc-js';
|
||||
import * as proto from '../../../src/grpc/pb/a2a.js';
|
||||
import { A2ARequestHandler } from '../../../src/server/index.js';
|
||||
import { TaskNotFoundError } from '../../../src/errors.js';
|
||||
import * as proto from '../../../src/grpc/pb/a2a_services.js';
|
||||
import { A2AError, A2ARequestHandler } from '../../../src/server/index.js';
|
||||
import { grpcService } from '../../../src/server/grpc/grpc_service.js';
|
||||
import {
|
||||
AgentCard,
|
||||
HTTP_EXTENSION_HEADER,
|
||||
Task,
|
||||
Role,
|
||||
TaskState,
|
||||
TaskStatus,
|
||||
ListTasksResponse,
|
||||
} from '../../../src/index.js';
|
||||
import { AgentCard, HTTP_EXTENSION_HEADER, MessageSendParams, Task } from '../../../src/index.js';
|
||||
import { ToProto } from '../../../src/types/converters/to_proto.js';
|
||||
import { FromProto } from '../../../src/types/converters/from_proto.js';
|
||||
|
||||
vi.mock('../../../src/types/converters/from_proto.js');
|
||||
vi.mock('../../../src/types/converters/to_proto.js');
|
||||
describe('grpcHandler', () => {
|
||||
let mockRequestHandler: A2ARequestHandler;
|
||||
let handler: ReturnType<typeof grpcService>;
|
||||
|
||||
const testAgentCard: AgentCard = {
|
||||
protocolVersion: '0.3.0',
|
||||
name: 'Test Agent',
|
||||
description: 'An agent for testing purposes',
|
||||
url: 'http://localhost:8080',
|
||||
preferredTransport: 'gRPC',
|
||||
version: '1.0.0',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:8080',
|
||||
protocolBinding: 'gRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0',
|
||||
},
|
||||
],
|
||||
capabilities: { streaming: true, pushNotifications: true, extensions: [] },
|
||||
capabilities: { streaming: true, pushNotifications: true },
|
||||
defaultInputModes: ['text/plain'],
|
||||
defaultOutputModes: ['text/plain'],
|
||||
skills: [],
|
||||
provider: undefined,
|
||||
documentationUrl: 'http://test-agent.com/docs',
|
||||
securitySchemes: {},
|
||||
securityRequirements: [],
|
||||
signatures: [],
|
||||
};
|
||||
|
||||
const testTask: Task = {
|
||||
id: 'task-1',
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_COMPLETED,
|
||||
timestamp: undefined,
|
||||
message: undefined,
|
||||
} as TaskStatus,
|
||||
kind: 'task' as const,
|
||||
status: { state: 'completed' as const },
|
||||
contextId: 'ctx-1',
|
||||
history: [],
|
||||
artifacts: [],
|
||||
metadata: {},
|
||||
};
|
||||
|
||||
// Helper to create a mock gRPC Unary Call
|
||||
@ -88,9 +67,8 @@ describe('grpcHandler', () => {
|
||||
sendMessage: vi.fn().mockResolvedValue(testTask),
|
||||
sendMessageStream: vi.fn(),
|
||||
getTask: vi.fn(),
|
||||
listTasks: vi.fn(),
|
||||
cancelTask: vi.fn(),
|
||||
createTaskPushNotificationConfig: vi.fn(),
|
||||
setTaskPushNotificationConfig: vi.fn(),
|
||||
getTaskPushNotificationConfig: vi.fn(),
|
||||
listTaskPushNotificationConfigs: vi.fn(),
|
||||
deleteTaskPushNotificationConfig: vi.fn(),
|
||||
@ -107,27 +85,32 @@ describe('grpcHandler', () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('getExtendedAgentCard', () => {
|
||||
describe('getAgentCard', () => {
|
||||
it('should return agent card via gRPC callback', async () => {
|
||||
const call = createMockUnaryCall({});
|
||||
const callback = vi.fn();
|
||||
await handler.getExtendedAgentCard(call, callback);
|
||||
const mockProtoAgentCard = { name: 'Proto Test Agent' } as proto.AgentCard;
|
||||
|
||||
(ToProto.agentCard as Mock).mockReturnValue(mockProtoAgentCard);
|
||||
|
||||
await handler.getAgentCard(call, callback);
|
||||
|
||||
expect(mockRequestHandler.getAuthenticatedExtendedAgentCard).toHaveBeenCalled();
|
||||
expect(ToProto.agentCard).toHaveBeenCalledWith(testAgentCard);
|
||||
const [err, response] = callback.mock.calls[0];
|
||||
assert.isNull(err);
|
||||
assert.deepEqual(response, testAgentCard as unknown as proto.AgentCard);
|
||||
assert.deepEqual(response, mockProtoAgentCard);
|
||||
expect(call.sendMetadata).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return gRPC error code on failure', async () => {
|
||||
(mockRequestHandler.getAuthenticatedExtendedAgentCard as Mock).mockRejectedValue(
|
||||
new TaskNotFoundError('Not Found')
|
||||
new A2AError(-32001, 'Not Found')
|
||||
);
|
||||
const call = createMockUnaryCall({});
|
||||
const callback = vi.fn();
|
||||
|
||||
await handler.getExtendedAgentCard(call, callback);
|
||||
await handler.getAgentCard(call, callback);
|
||||
|
||||
const [err] = callback.mock.calls[0];
|
||||
assert.equal(err.code, grpc.status.NOT_FOUND);
|
||||
@ -137,9 +120,15 @@ describe('grpcHandler', () => {
|
||||
|
||||
describe('sendMessage', () => {
|
||||
it('should successfully send a message and return a task', async () => {
|
||||
const call = createMockUnaryCall({ message: { role: Role.ROLE_USER, parts: [] as any } });
|
||||
const call = createMockUnaryCall({ message: { role: 'user', parts: [] } });
|
||||
const callback = vi.fn();
|
||||
|
||||
const messageSendParams = { message: { role: 'user' } } as MessageSendParams;
|
||||
(FromProto.messageSendParams as Mock).mockReturnValue(messageSendParams);
|
||||
const sendMessageResponse = {
|
||||
payload: { $case: 'task', value: { id: 'task-1' } } as proto.SendMessageResponse,
|
||||
};
|
||||
(ToProto.messageSendResult as Mock).mockReturnValue(sendMessageResponse);
|
||||
await handler.sendMessage(call, callback);
|
||||
|
||||
const [err, response] = callback.mock.calls[0];
|
||||
@ -152,17 +141,12 @@ describe('grpcHandler', () => {
|
||||
describe('sendStreamingMessage', () => {
|
||||
it('should stream multiple parts and end correctly', async () => {
|
||||
async function* mockStream() {
|
||||
yield { messageId: 'm1', role: Role.ROLE_AGENT, parts: [] as any };
|
||||
yield {
|
||||
id: 't1',
|
||||
status: { state: TaskState.TASK_STATE_COMPLETED, message: undefined as any },
|
||||
};
|
||||
yield { kind: 'message', messageId: 'm1' };
|
||||
yield { kind: 'task', id: 't1' };
|
||||
}
|
||||
(mockRequestHandler.sendMessageStream as Mock).mockResolvedValue(mockStream());
|
||||
|
||||
const call = createMockWritableStream({
|
||||
message: { role: Role.ROLE_USER, content: [] as any },
|
||||
});
|
||||
const call = createMockWritableStream({ message: { role: 'user', parts: [] } });
|
||||
|
||||
await handler.sendStreamingMessage(call);
|
||||
|
||||
@ -180,35 +164,13 @@ describe('grpcHandler', () => {
|
||||
expect(call.emit).toHaveBeenCalledWith(
|
||||
'error',
|
||||
expect.objectContaining({
|
||||
code: grpc.status.UNKNOWN,
|
||||
code: grpc.status.INTERNAL,
|
||||
})
|
||||
);
|
||||
expect(call.end).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('listTasks', () => {
|
||||
it('should successfully list tasks', async () => {
|
||||
const mockResponse: ListTasksResponse = {
|
||||
tasks: [testTask],
|
||||
nextPageToken: '',
|
||||
pageSize: 1,
|
||||
totalSize: 1,
|
||||
};
|
||||
(mockRequestHandler.listTasks as Mock).mockResolvedValue(mockResponse);
|
||||
|
||||
const call = createMockUnaryCall({ tenant: '', contextId: '' });
|
||||
const callback = vi.fn();
|
||||
|
||||
await handler.listTasks(call, callback);
|
||||
|
||||
const [err, response] = callback.mock.calls[0];
|
||||
assert.isNull(err);
|
||||
assert.equal(response.tasks.length, 1);
|
||||
assert.equal(response.tasks[0].id, testTask.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Extensions (Metadata) Handling', () => {
|
||||
it('should extract extensions from metadata and pass to context', async () => {
|
||||
// Mocking the header 'x-a2a-extension'
|
||||
@ -220,6 +182,8 @@ describe('grpcHandler', () => {
|
||||
);
|
||||
const callback = vi.fn();
|
||||
|
||||
(FromProto.taskQueryParams as Mock).mockReturnValue({ id: 'task-1' });
|
||||
(ToProto.task as Mock).mockReturnValue({ id: 'task-1', contextId: 'ctx-1' });
|
||||
await handler.getTask(call, callback);
|
||||
|
||||
const contextArg = (mockRequestHandler.getTask as Mock).mock.calls[0][1];
|
||||
@ -242,6 +206,8 @@ describe('grpcHandler', () => {
|
||||
return testTask;
|
||||
});
|
||||
|
||||
(FromProto.taskQueryParams as Mock).mockReturnValue({ id: 'task-1' });
|
||||
(ToProto.task as Mock).mockReturnValue({ id: 'task-1', contextId: 'ctx-1' });
|
||||
await handler.getTask(call, callback);
|
||||
|
||||
const [metadata] = (call.sendMetadata as Mock).mock.calls[0];
|
||||
|
||||
@ -1,63 +1,390 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { ToProto } from '../../../src/types/converters/to_proto.js';
|
||||
import * as proto from '../../../src/types/pb/a2a.js';
|
||||
import * as types from '../../../src/types.js';
|
||||
import * as proto from '../../../src/types/pb/a2a_types.js';
|
||||
import * as idDecoding from '../../../src/types/converters/id_decoding.js';
|
||||
import { A2AError } from '../../../src/server/index.js';
|
||||
|
||||
vi.mock('../../../src/types/converters/id_decoding.js', () => ({
|
||||
generatePushNotificationConfigName: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('ToProto', () => {
|
||||
describe('messageSendResult', () => {
|
||||
it('should wrap Message in SendMessageResponse', () => {
|
||||
const message: proto.Message = {
|
||||
messageId: 'msg-1',
|
||||
parts: [],
|
||||
contextId: '',
|
||||
taskId: '',
|
||||
role: 0,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
};
|
||||
const result = ToProto.messageSendResult(message);
|
||||
expect(result.payload?.$case).toBe('message');
|
||||
expect((result.payload as any).value).toBe(message);
|
||||
beforeEach(() => {
|
||||
vi.mocked(idDecoding.generatePushNotificationConfigName).mockReturnValue(
|
||||
'tasks/task-123/pushNotificationConfigs/pnc-456'
|
||||
);
|
||||
});
|
||||
|
||||
it('should convert internal Task to proto Task', () => {
|
||||
const internalTask: types.Task = {
|
||||
id: 'task-123',
|
||||
kind: 'task',
|
||||
contextId: 'ctx-1',
|
||||
status: {
|
||||
state: 'completed',
|
||||
timestamp: '2023-01-01T00:00:00.000Z',
|
||||
},
|
||||
artifacts: [],
|
||||
history: [],
|
||||
metadata: { key: 'value' },
|
||||
};
|
||||
|
||||
const result = ToProto.task(internalTask);
|
||||
|
||||
expect(result).toEqual({
|
||||
id: 'task-123',
|
||||
contextId: 'ctx-1',
|
||||
status: {
|
||||
state: proto.TaskState.TASK_STATE_COMPLETED,
|
||||
timestamp: '2023-01-01T00:00:00.000Z',
|
||||
update: undefined,
|
||||
},
|
||||
artifacts: [],
|
||||
history: [],
|
||||
metadata: { key: 'value' },
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert internal Message to proto Message', () => {
|
||||
const internalMessage: types.Message = {
|
||||
kind: 'message',
|
||||
messageId: 'msg-1',
|
||||
parts: [{ kind: 'text', text: 'hello' }],
|
||||
contextId: 'ctx-1',
|
||||
taskId: 'task-1',
|
||||
role: 'user',
|
||||
metadata: { key: 'value' },
|
||||
extensions: ['ext1'],
|
||||
};
|
||||
|
||||
const result = ToProto.message(internalMessage);
|
||||
|
||||
expect(result).toEqual({
|
||||
messageId: 'msg-1',
|
||||
content: [{ part: { $case: 'text', value: 'hello' } }],
|
||||
contextId: 'ctx-1',
|
||||
taskId: 'task-1',
|
||||
role: proto.Role.ROLE_USER,
|
||||
metadata: { key: 'value' },
|
||||
extensions: ['ext1'],
|
||||
});
|
||||
});
|
||||
|
||||
describe('taskState', () => {
|
||||
it.each([
|
||||
['submitted', proto.TaskState.TASK_STATE_SUBMITTED],
|
||||
['working', proto.TaskState.TASK_STATE_WORKING],
|
||||
['input-required', proto.TaskState.TASK_STATE_INPUT_REQUIRED],
|
||||
['rejected', proto.TaskState.TASK_STATE_REJECTED],
|
||||
['auth-required', proto.TaskState.TASK_STATE_AUTH_REQUIRED],
|
||||
['completed', proto.TaskState.TASK_STATE_COMPLETED],
|
||||
['failed', proto.TaskState.TASK_STATE_FAILED],
|
||||
['canceled', proto.TaskState.TASK_STATE_CANCELLED],
|
||||
['unknown', proto.TaskState.TASK_STATE_UNSPECIFIED],
|
||||
['invalid-state' as types.TaskState, proto.TaskState.UNRECOGNIZED],
|
||||
])('should convert internal state "%s" to proto state %s', (internalState, expectedState) => {
|
||||
const result = ToProto.taskState(internalState as types.TaskState);
|
||||
expect(result).toBe(expectedState);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parts', () => {
|
||||
it('should convert a text part', () => {
|
||||
const part: types.Part = { kind: 'text', text: 'hello' };
|
||||
const result = ToProto.part(part);
|
||||
expect(result).toEqual({
|
||||
part: { $case: 'text', value: 'hello' },
|
||||
});
|
||||
});
|
||||
|
||||
it('should wrap Task in SendMessageResponse', () => {
|
||||
const task: proto.Task = {
|
||||
it('should convert a file part with URI', () => {
|
||||
const part: types.Part = {
|
||||
kind: 'file',
|
||||
file: { uri: 'file://path', mimeType: 'text/plain' },
|
||||
};
|
||||
const result = ToProto.part(part);
|
||||
expect(result).toEqual({
|
||||
part: {
|
||||
$case: 'file',
|
||||
value: {
|
||||
file: { $case: 'fileWithUri', value: 'file://path' },
|
||||
mimeType: 'text/plain',
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert a file part with bytes', () => {
|
||||
const base64Bytes = Buffer.from('file content').toString('base64');
|
||||
const part: types.Part = {
|
||||
kind: 'file',
|
||||
file: { bytes: base64Bytes, mimeType: 'application/octet-stream' },
|
||||
};
|
||||
const result = ToProto.part(part);
|
||||
expect(result).toEqual({
|
||||
part: {
|
||||
$case: 'file',
|
||||
value: {
|
||||
file: { $case: 'fileWithBytes', value: Buffer.from('file content') },
|
||||
mimeType: 'application/octet-stream',
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw for an invalid file part', () => {
|
||||
const part: types.Part = {
|
||||
kind: 'file',
|
||||
file: {} as any,
|
||||
};
|
||||
expect(() => ToProto.part(part)).toThrow(new A2AError(-32603, 'Invalid file part'));
|
||||
});
|
||||
|
||||
it('should convert a data part', () => {
|
||||
const data = { foo: 'bar' };
|
||||
const part: types.Part = { kind: 'data', data };
|
||||
const result = ToProto.part(part);
|
||||
expect(result).toEqual({
|
||||
part: { $case: 'data', value: { data } },
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw for an unknown part type', () => {
|
||||
const part: types.Part = { kind: 'unknown' } as any;
|
||||
expect(() => ToProto.part(part)).toThrow(new A2AError(-32603, 'Invalid part type'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert internal Artifact to proto Artifact', () => {
|
||||
const internalArtifact: types.Artifact = {
|
||||
artifactId: 'art-1',
|
||||
name: 'My Artifact',
|
||||
description: 'A test artifact',
|
||||
parts: [{ kind: 'text', text: 'artifact content' }],
|
||||
metadata: { key: 'value' },
|
||||
extensions: ['ext1'],
|
||||
};
|
||||
|
||||
const result = ToProto.artifact(internalArtifact);
|
||||
|
||||
expect(result).toEqual({
|
||||
artifactId: 'art-1',
|
||||
name: 'My Artifact',
|
||||
description: 'A test artifact',
|
||||
parts: [{ part: { $case: 'text', value: 'artifact content' } }],
|
||||
metadata: { key: 'value' },
|
||||
extensions: ['ext1'],
|
||||
});
|
||||
});
|
||||
|
||||
describe('messageSendResult', () => {
|
||||
it('should convert a message result', () => {
|
||||
const message: types.Message = {
|
||||
kind: 'message',
|
||||
messageId: 'msg-1',
|
||||
parts: [],
|
||||
role: 'agent',
|
||||
};
|
||||
const result = ToProto.messageSendResult(message);
|
||||
expect(result.payload?.$case).toBe('msg');
|
||||
expect((result.payload as any).value.messageId).toBe('msg-1');
|
||||
});
|
||||
|
||||
it('should convert a task result', () => {
|
||||
const task: types.Task = {
|
||||
kind: 'task',
|
||||
id: 'task-123',
|
||||
contextId: '',
|
||||
status: undefined,
|
||||
contextId: 'ctx-1',
|
||||
status: { state: 'submitted' },
|
||||
history: [],
|
||||
artifacts: [],
|
||||
metadata: undefined,
|
||||
};
|
||||
const result = ToProto.messageSendResult(task);
|
||||
expect(result.payload?.$case).toBe('task');
|
||||
expect((result.payload as any).value).toBe(task);
|
||||
expect((result.payload as any).value.id).toBe('task-123');
|
||||
});
|
||||
|
||||
it('should return undefined for invalid kind', () => {
|
||||
const invalid = { kind: 'invalid' } as any;
|
||||
const result = ToProto.messageSendResult(invalid);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('messageStreamResult', () => {
|
||||
it('should wrap Message in StreamResponse', () => {
|
||||
const message: proto.Message = { messageId: 'm1' } as any;
|
||||
const result = ToProto.messageStreamResult(message);
|
||||
expect(result.payload?.$case).toBe('message');
|
||||
it('should convert a message event', () => {
|
||||
const event: types.Message = {
|
||||
kind: 'message',
|
||||
messageId: 'msg-1',
|
||||
parts: [],
|
||||
role: 'agent',
|
||||
};
|
||||
const result = ToProto.messageStreamResult(event);
|
||||
expect(result.payload?.$case).toBe('msg');
|
||||
});
|
||||
|
||||
it('should wrap Task in StreamResponse', () => {
|
||||
const task: proto.Task = { artifacts: [] } as any; // distinct feature of Task
|
||||
const result = ToProto.messageStreamResult(task);
|
||||
it('should convert a task event', () => {
|
||||
const event: types.Task = {
|
||||
kind: 'task',
|
||||
id: 'task-123',
|
||||
contextId: 'ctx-1',
|
||||
status: { state: 'submitted' },
|
||||
history: [],
|
||||
artifacts: [],
|
||||
};
|
||||
const result = ToProto.messageStreamResult(event);
|
||||
expect(result.payload?.$case).toBe('task');
|
||||
});
|
||||
|
||||
it('should wrap TaskStatusUpdateEvent in StreamResponse', () => {
|
||||
const event: proto.TaskStatusUpdateEvent = { status: {} } as any;
|
||||
it('should convert a status-update event', () => {
|
||||
const event: types.TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: 'task-123',
|
||||
status: { state: 'working' },
|
||||
contextId: 'ctx-1',
|
||||
metadata: {},
|
||||
final: false,
|
||||
};
|
||||
const result = ToProto.messageStreamResult(event);
|
||||
expect(result.payload?.$case).toBe('statusUpdate');
|
||||
});
|
||||
|
||||
it('should wrap TaskArtifactUpdateEvent in StreamResponse', () => {
|
||||
const event: proto.TaskArtifactUpdateEvent = { artifact: {} } as any;
|
||||
it('should convert an artifact-update event', () => {
|
||||
const event: types.TaskArtifactUpdateEvent = {
|
||||
kind: 'artifact-update',
|
||||
taskId: 'task-123',
|
||||
artifact: { artifactId: 'art-1', parts: [] },
|
||||
contextId: 'ctx-1',
|
||||
metadata: {},
|
||||
};
|
||||
const result = ToProto.messageStreamResult(event);
|
||||
expect(result.payload?.$case).toBe('artifactUpdate');
|
||||
});
|
||||
|
||||
it('should throw for an invalid event type', () => {
|
||||
const event = { kind: 'invalid' } as any;
|
||||
expect(() => ToProto.messageStreamResult(event)).toThrow(
|
||||
new A2AError(-32603, 'Invalid event type')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert PushNotificationAuthenticationInfo', () => {
|
||||
const authInfo: types.PushNotificationAuthenticationInfo = {
|
||||
schemes: ['bearer'],
|
||||
credentials: 'my-token',
|
||||
};
|
||||
const result = ToProto.pushNotificationAuthenticationInfo(authInfo);
|
||||
expect(result).toEqual({
|
||||
schemes: ['bearer'],
|
||||
credentials: 'my-token',
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert PushNotificationConfig', () => {
|
||||
const config: types.PushNotificationConfig = {
|
||||
id: 'pnc-456',
|
||||
url: 'https://example.com/notify',
|
||||
token: 'push-token',
|
||||
authentication: {
|
||||
schemes: ['bearer'],
|
||||
credentials: 'my-token',
|
||||
},
|
||||
};
|
||||
const result = ToProto.pushNotificationConfig(config);
|
||||
expect(result).toEqual({
|
||||
id: 'pnc-456',
|
||||
url: 'https://example.com/notify',
|
||||
token: 'push-token',
|
||||
authentication: {
|
||||
schemes: ['bearer'],
|
||||
credentials: 'my-token',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert TaskPushNotificationConfig', () => {
|
||||
const config: types.TaskPushNotificationConfig = {
|
||||
taskId: 'task-123',
|
||||
pushNotificationConfig: {
|
||||
id: 'pnc-456',
|
||||
url: 'https://example.com/notify',
|
||||
},
|
||||
};
|
||||
const result = ToProto.taskPushNotificationConfig(config);
|
||||
expect(idDecoding.generatePushNotificationConfigName).toHaveBeenCalledWith(
|
||||
'task-123',
|
||||
'pnc-456'
|
||||
);
|
||||
expect(result).toEqual({
|
||||
name: 'tasks/task-123/pushNotificationConfigs/pnc-456',
|
||||
pushNotificationConfig: {
|
||||
id: 'pnc-456',
|
||||
url: 'https://example.com/notify',
|
||||
token: '',
|
||||
authentication: undefined,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert a list of TaskPushNotificationConfigs', () => {
|
||||
const configs: types.TaskPushNotificationConfig[] = [
|
||||
{
|
||||
taskId: 'task-123',
|
||||
pushNotificationConfig: { id: 'pnc-456', url: 'https://example.com/notify' },
|
||||
},
|
||||
];
|
||||
const result = ToProto.listTaskPushNotificationConfig(configs);
|
||||
expect(result.configs.length).toBe(1);
|
||||
expect(result.nextPageToken).toBe('');
|
||||
expect(result.configs[0].name).toBe('tasks/task-123/pushNotificationConfigs/pnc-456');
|
||||
});
|
||||
|
||||
describe('securityScheme', () => {
|
||||
it('should convert apiKey scheme', () => {
|
||||
const scheme: types.SecurityScheme = {
|
||||
type: 'apiKey',
|
||||
name: 'X-API-KEY',
|
||||
in: 'header',
|
||||
description: 'API Key auth',
|
||||
};
|
||||
const result = ToProto.securityScheme(scheme);
|
||||
expect(result.scheme?.$case).toBe('apiKeySecurityScheme');
|
||||
});
|
||||
|
||||
it('should convert http scheme', () => {
|
||||
const scheme: types.SecurityScheme = {
|
||||
type: 'http',
|
||||
scheme: 'bearer',
|
||||
bearerFormat: 'JWT',
|
||||
};
|
||||
const result = ToProto.securityScheme(scheme);
|
||||
expect(result.scheme?.$case).toBe('httpAuthSecurityScheme');
|
||||
});
|
||||
|
||||
it('should throw on unsupported security scheme', () => {
|
||||
const scheme: types.SecurityScheme = { type: 'unsupported' } as any;
|
||||
expect(() => ToProto.securityScheme(scheme)).toThrow(
|
||||
A2AError.internalError('Unsupported security scheme type')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('oauthFlows', () => {
|
||||
it('should convert implicit flow', () => {
|
||||
const flows: types.OAuthFlows = {
|
||||
implicit: { authorizationUrl: 'url', scopes: { s1: '' } },
|
||||
};
|
||||
const result = ToProto.oauthFlows(flows);
|
||||
expect(result.flow?.$case).toBe('implicit');
|
||||
});
|
||||
|
||||
it('should throw on unsupported flow', () => {
|
||||
const flows: types.OAuthFlows = {};
|
||||
expect(() => ToProto.oauthFlows(flows)).toThrow(
|
||||
A2AError.internalError('Unsupported OAuth flows')
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -2,19 +2,7 @@ import { describe, it, beforeEach, afterEach, expect, vi, type Mock } from 'vite
|
||||
|
||||
import { JsonRpcTransportHandler } from '../../src/server/transports/jsonrpc/jsonrpc_transport_handler.js';
|
||||
import { A2ARequestHandler } from '../../src/server/request_handler/a2a_request_handler.js';
|
||||
import { JSONRPCErrorResponse } from '../../src/core.js';
|
||||
import {
|
||||
RequestMalformedError,
|
||||
TaskNotFoundError,
|
||||
TaskNotCancelableError,
|
||||
PushNotificationNotSupportedError,
|
||||
UnsupportedOperationError,
|
||||
ContentTypeNotSupportedError,
|
||||
InvalidAgentResponseError,
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
A2A_ERROR_CODE,
|
||||
GenericError,
|
||||
} from '../../src/errors.js';
|
||||
import { JSONRPCErrorResponse, JSONRPCRequest } from '../../src/index.js';
|
||||
|
||||
describe('JsonRpcTransportHandler', () => {
|
||||
let mockRequestHandler: A2ARequestHandler;
|
||||
@ -24,16 +12,15 @@ describe('JsonRpcTransportHandler', () => {
|
||||
mockRequestHandler = {
|
||||
getAgentCard: vi.fn(),
|
||||
getAuthenticatedExtendedAgentCard: vi.fn(),
|
||||
sendMessage: vi.fn().mockResolvedValue({ messageId: 'default-id' }),
|
||||
sendMessage: vi.fn(),
|
||||
sendMessageStream: vi.fn(),
|
||||
getTask: vi.fn(),
|
||||
cancelTask: vi.fn(),
|
||||
createTaskPushNotificationConfig: vi.fn(),
|
||||
setTaskPushNotificationConfig: vi.fn(),
|
||||
getTaskPushNotificationConfig: vi.fn(),
|
||||
listTaskPushNotificationConfigs: vi.fn(),
|
||||
deleteTaskPushNotificationConfig: vi.fn(),
|
||||
resubscribe: vi.fn(),
|
||||
listTasks: vi.fn(),
|
||||
};
|
||||
transportHandler = new JsonRpcTransportHandler(mockRequestHandler);
|
||||
});
|
||||
@ -43,62 +30,62 @@ describe('JsonRpcTransportHandler', () => {
|
||||
});
|
||||
|
||||
describe('Check JSON-RPC request format', () => {
|
||||
it('should return an invalid params error for an invalid JSON string', async () => {
|
||||
it('should return a parse error for an invalid JSON string', async () => {
|
||||
const invalidJson = '{ "jsonrpc": "2.0", "method": "foo", "id": 1, }'; // trailing comma
|
||||
const response = (await transportHandler.handle(invalidJson)) as JSONRPCErrorResponse;
|
||||
expect(response.error.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(response.error.code).to.equal(-32700); // Parse error
|
||||
});
|
||||
|
||||
it('should return an invalid params error for a non-string/non-object request body', async () => {
|
||||
it('should return a parse error for a non-string/non-object request body', async () => {
|
||||
const response = (await transportHandler.handle(123)) as JSONRPCErrorResponse;
|
||||
expect(response.error.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(response.error.code).to.equal(-32700); // Parse error
|
||||
expect(response.error.message).to.equal('Invalid request body type.');
|
||||
});
|
||||
|
||||
it('should return an invalid params error for missing jsonrpc property', async () => {
|
||||
it('should return an invalid request error for missing jsonrpc property', async () => {
|
||||
const request = { method: 'foo', id: 1 };
|
||||
const response = (await transportHandler.handle(request)) as JSONRPCErrorResponse;
|
||||
expect(response.error.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(response.error.code).to.equal(-32600); // Invalid Request
|
||||
expect(response.error.message).to.equal('Invalid JSON-RPC Request.');
|
||||
expect(response.id).to.equal(1);
|
||||
});
|
||||
|
||||
it('should return an invalid params error for incorrect jsonrpc version', async () => {
|
||||
it('should return an invalid request error for incorrect jsonrpc version', async () => {
|
||||
const request = { jsonrpc: '1.0', method: 'foo', id: 1 };
|
||||
const response = (await transportHandler.handle(request)) as JSONRPCErrorResponse;
|
||||
expect(response.error.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(response.error.code).to.equal(-32600); // Invalid Request
|
||||
expect(response.error.message).to.equal('Invalid JSON-RPC Request.');
|
||||
expect(response.id).to.equal(1);
|
||||
});
|
||||
|
||||
it('should return an invalid params error for missing method property', async () => {
|
||||
it('should return an invalid request error for missing method property', async () => {
|
||||
const request = { jsonrpc: '2.0', id: 1 };
|
||||
const response = (await transportHandler.handle(request)) as JSONRPCErrorResponse;
|
||||
expect(response.error.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(response.error.code).to.equal(-32600); // Invalid Request
|
||||
expect(response.error.message).to.equal('Invalid JSON-RPC Request.');
|
||||
expect(response.id).to.equal(1);
|
||||
});
|
||||
|
||||
it('should return an invalid params error for non-string method property', async () => {
|
||||
it('should return an invalid request error for non-string method property', async () => {
|
||||
const request = { jsonrpc: '2.0', method: 123, id: 1 };
|
||||
const response = (await transportHandler.handle(request)) as JSONRPCErrorResponse;
|
||||
expect(response.error.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(response.error.code).to.equal(-32600); // Invalid Request
|
||||
expect(response.error.message).to.equal('Invalid JSON-RPC Request.');
|
||||
expect(response.id).to.equal(1);
|
||||
});
|
||||
|
||||
it('should return an invalid params error for invalid id type (object)', async () => {
|
||||
it('should return an invalid request error for invalid id type (object)', async () => {
|
||||
const request = { jsonrpc: '2.0', method: 'foo', id: {} };
|
||||
const response = (await transportHandler.handle(request)) as JSONRPCErrorResponse;
|
||||
expect(response.error.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(response.error.code).to.equal(-32600); // Invalid Request
|
||||
expect(response.error.message).to.equal('Invalid JSON-RPC Request.');
|
||||
expect(response.id).to.deep.equal({});
|
||||
});
|
||||
|
||||
it('should return an invalid params error for invalid id type (float)', async () => {
|
||||
it('should return an invalid request error for invalid id type (float)', async () => {
|
||||
const request = { jsonrpc: '2.0', method: 'foo', id: 1.23 };
|
||||
const response = (await transportHandler.handle(request)) as JSONRPCErrorResponse;
|
||||
expect(response.error.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(response.error.code).to.equal(-32600); // Invalid Request
|
||||
expect(response.error.message).to.equal('Invalid JSON-RPC Request.');
|
||||
expect(response.id).to.equal(1.23);
|
||||
});
|
||||
@ -106,7 +93,7 @@ describe('JsonRpcTransportHandler', () => {
|
||||
it('should handle valid request with string id', async () => {
|
||||
const request = {
|
||||
jsonrpc: '2.0',
|
||||
method: 'SendMessage',
|
||||
method: 'message/send',
|
||||
id: 'abc-123',
|
||||
params: {},
|
||||
};
|
||||
@ -117,7 +104,7 @@ describe('JsonRpcTransportHandler', () => {
|
||||
it('should handle valid request with integer id', async () => {
|
||||
const request = {
|
||||
jsonrpc: '2.0',
|
||||
method: 'SendMessage',
|
||||
method: 'message/send',
|
||||
id: 456,
|
||||
params: {},
|
||||
};
|
||||
@ -126,12 +113,12 @@ describe('JsonRpcTransportHandler', () => {
|
||||
});
|
||||
|
||||
it('should handle valid request with null id', async () => {
|
||||
const request = {
|
||||
const request: JSONRPCRequest = {
|
||||
jsonrpc: '2.0',
|
||||
method: 'SendMessage',
|
||||
method: 'message/send',
|
||||
id: null,
|
||||
params: {},
|
||||
} as any;
|
||||
};
|
||||
(mockRequestHandler.getAuthenticatedExtendedAgentCard as Mock).mockResolvedValue({
|
||||
card: 'data',
|
||||
});
|
||||
@ -151,12 +138,12 @@ describe('JsonRpcTransportHandler', () => {
|
||||
it(`should return an invalid params error if params are ${name}`, async () => {
|
||||
const request = {
|
||||
jsonrpc: '2.0',
|
||||
method: 'SendMessage',
|
||||
method: 'message/send',
|
||||
id: 1,
|
||||
params,
|
||||
};
|
||||
const response = (await transportHandler.handle(request)) as JSONRPCErrorResponse;
|
||||
expect(response.error.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(response.error.code).to.equal(-32602); // Invalid Params
|
||||
expect(response.error.message).to.equal('Invalid method parameters.');
|
||||
expect(response.id).to.equal(1);
|
||||
});
|
||||
@ -165,7 +152,7 @@ describe('JsonRpcTransportHandler', () => {
|
||||
it('should handle valid request with params as dict', async () => {
|
||||
const request = {
|
||||
jsonrpc: '2.0',
|
||||
method: 'SendMessage',
|
||||
method: 'message/send',
|
||||
id: 456,
|
||||
params: { this: 'is a dict' },
|
||||
};
|
||||
@ -173,88 +160,4 @@ describe('JsonRpcTransportHandler', () => {
|
||||
expect(response).to.have.property('result');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error mapping', () => {
|
||||
it('should map RequestMalformedError to code and message', async () => {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new RequestMalformedError('Error message')
|
||||
);
|
||||
expect(mappedError.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(mappedError.message).to.equal('Error message');
|
||||
});
|
||||
|
||||
it('should map TaskNotFoundError to code and message', async () => {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new TaskNotFoundError('Task Not Found')
|
||||
);
|
||||
expect(mappedError.code).to.equal(A2A_ERROR_CODE.TASK_NOT_FOUND);
|
||||
expect(mappedError.message).to.equal('Task Not Found');
|
||||
});
|
||||
|
||||
it('should map TaskNotCancelableError to code and message', async () => {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new TaskNotCancelableError('Task Not Cancelable')
|
||||
);
|
||||
expect(mappedError.code).to.equal(A2A_ERROR_CODE.TASK_NOT_CANCELABLE);
|
||||
expect(mappedError.message).to.equal('Task Not Cancelable');
|
||||
});
|
||||
|
||||
it('should map PushNotificationNotSupportedError to code and message', async () => {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new PushNotificationNotSupportedError('Push Notification Not Supported')
|
||||
);
|
||||
expect(mappedError.code).to.equal(A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED);
|
||||
expect(mappedError.message).to.equal('Push Notification Not Supported');
|
||||
});
|
||||
|
||||
it('should map UnsupportedOperationError to code and message', async () => {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new UnsupportedOperationError('Unsupported Operation')
|
||||
);
|
||||
expect(mappedError.code).to.equal(A2A_ERROR_CODE.UNSUPPORTED_OPERATION);
|
||||
expect(mappedError.message).to.equal('Unsupported Operation');
|
||||
});
|
||||
|
||||
it('should map ContentTypeNotSupportedError to code and message', async () => {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new ContentTypeNotSupportedError('Content Type Not Supported')
|
||||
);
|
||||
expect(mappedError.code).to.equal(A2A_ERROR_CODE.CONTENT_TYPE_NOT_SUPPORTED);
|
||||
expect(mappedError.message).to.equal('Content Type Not Supported');
|
||||
});
|
||||
|
||||
it('should map InvalidAgentResponseError to code and message', async () => {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new InvalidAgentResponseError('Invalid Agent Response')
|
||||
);
|
||||
expect(mappedError.code).to.equal(A2A_ERROR_CODE.INVALID_AGENT_RESPONSE);
|
||||
expect(mappedError.message).to.equal('Invalid Agent Response');
|
||||
});
|
||||
|
||||
it('should map AuthenticatedExtendedCardNotConfiguredError to code and message', async () => {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new AuthenticatedExtendedCardNotConfiguredError(
|
||||
'Authenticated Extended Card Not Configured'
|
||||
)
|
||||
);
|
||||
expect(mappedError.code).to.equal(A2A_ERROR_CODE.AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED);
|
||||
expect(mappedError.message).to.equal('Authenticated Extended Card Not Configured');
|
||||
});
|
||||
|
||||
it('should map RequestMalformedError to code and message', async () => {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new RequestMalformedError('Request Malformed')
|
||||
);
|
||||
expect(mappedError.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(mappedError.message).to.equal('Request Malformed');
|
||||
});
|
||||
|
||||
it('should map GenericError to code and message', async () => {
|
||||
const mappedError = JsonRpcTransportHandler.mapToJSONRPCError(
|
||||
new GenericError('Generic Error')
|
||||
);
|
||||
expect(mappedError.code).to.equal(A2A_ERROR_CODE.INTERNAL_ERROR);
|
||||
expect(mappedError.message).to.equal('Generic Error');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
import { vi, type Mock, type MockInstance } from 'vitest';
|
||||
import { AgentExecutor } from '../../../src/server/agent_execution/agent_executor.js';
|
||||
import { TaskState } from '../../../src/types/pb/a2a.js';
|
||||
import { RequestContext } from '../../../src/server/agent_execution/request_context.js';
|
||||
import { ExecutionEventBus } from '../../../src/server/events/execution_event_bus.js';
|
||||
import { RequestContext, ExecutionEventBus } from '../../../src/server/index.js';
|
||||
|
||||
/**
|
||||
* A mock implementation of AgentExecutor to control agent behavior during tests.
|
||||
@ -27,26 +25,26 @@ export const fakeTaskExecute = async (ctx: RequestContext, bus: ExecutionEventBu
|
||||
bus.publish({
|
||||
id: taskId,
|
||||
contextId,
|
||||
status: { state: TaskState.TASK_STATE_SUBMITTED, message: undefined, timestamp: undefined },
|
||||
artifacts: [],
|
||||
history: [],
|
||||
metadata: {},
|
||||
status: { state: 'submitted' },
|
||||
kind: 'task',
|
||||
});
|
||||
|
||||
// Publish working status
|
||||
bus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: { state: TaskState.TASK_STATE_WORKING, message: undefined, timestamp: undefined },
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
status: { state: 'working' },
|
||||
final: false,
|
||||
});
|
||||
|
||||
// Publish completion
|
||||
bus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: { state: TaskState.TASK_STATE_COMPLETED, message: undefined, timestamp: undefined },
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
status: { state: 'completed' },
|
||||
final: true,
|
||||
});
|
||||
|
||||
bus.finished();
|
||||
@ -70,46 +68,40 @@ export class CancellableMockAgentExecutor implements AgentExecutor {
|
||||
eventBus.publish({
|
||||
id: taskId,
|
||||
contextId,
|
||||
status: { state: TaskState.TASK_STATE_SUBMITTED, message: undefined, timestamp: undefined },
|
||||
artifacts: [],
|
||||
history: [],
|
||||
metadata: {},
|
||||
status: { state: 'submitted' },
|
||||
kind: 'task',
|
||||
});
|
||||
eventBus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: { state: TaskState.TASK_STATE_WORKING, message: undefined, timestamp: undefined },
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
status: { state: 'working' },
|
||||
final: false,
|
||||
});
|
||||
|
||||
// Simulate a long-running process
|
||||
for (let i = 0; i < 5; i++) {
|
||||
// We can't easily advance timers in a tight loop without yielding, but for test purposes
|
||||
// checking the cancelledTasks set is enough if the test calls cancelTask.
|
||||
if (this.cancelledTasks.has(taskId)) {
|
||||
eventBus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_CANCELED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
},
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
status: { state: 'canceled' },
|
||||
final: true,
|
||||
});
|
||||
eventBus.finished();
|
||||
return;
|
||||
}
|
||||
// Use fake timers to simulate work
|
||||
// In real code we'd need to yield or wait for timer.
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
}
|
||||
|
||||
eventBus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: { state: TaskState.TASK_STATE_COMPLETED, message: undefined, timestamp: undefined },
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
status: { state: 'completed' },
|
||||
final: true,
|
||||
});
|
||||
eventBus.finished();
|
||||
}
|
||||
@ -138,16 +130,15 @@ export class FailingCancellableMockAgentExecutor implements AgentExecutor {
|
||||
eventBus.publish({
|
||||
id: taskId,
|
||||
contextId,
|
||||
status: { state: TaskState.TASK_STATE_SUBMITTED, message: undefined, timestamp: undefined },
|
||||
artifacts: [],
|
||||
history: [],
|
||||
metadata: {},
|
||||
status: { state: 'submitted' },
|
||||
kind: 'task',
|
||||
});
|
||||
eventBus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: { state: TaskState.TASK_STATE_WORKING, message: undefined, timestamp: undefined },
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
status: { state: 'working' },
|
||||
final: false,
|
||||
});
|
||||
|
||||
// Simulate a long-running process
|
||||
@ -156,24 +147,23 @@ export class FailingCancellableMockAgentExecutor implements AgentExecutor {
|
||||
eventBus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_CANCELED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
},
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
status: { state: 'canceled' },
|
||||
final: true,
|
||||
});
|
||||
eventBus.finished();
|
||||
return;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
// Use fake timers to simulate work
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
}
|
||||
|
||||
eventBus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: { state: TaskState.TASK_STATE_COMPLETED, message: undefined, timestamp: undefined },
|
||||
metadata: {},
|
||||
kind: 'status-update',
|
||||
status: { state: 'completed' },
|
||||
final: true,
|
||||
});
|
||||
eventBus.finished();
|
||||
}
|
||||
|
||||
@ -1,12 +1,9 @@
|
||||
import { vi, type Mock } from 'vitest';
|
||||
import { Task, ListTasksRequest, ListTasksResponse } from '../../../src/index.js';
|
||||
import { Task } from '../../../src/index.js';
|
||||
import { TaskStore } from '../../../src/server/store.js';
|
||||
import { ServerCallContext } from '../../../src/server/context.js';
|
||||
|
||||
export class MockTaskStore implements TaskStore {
|
||||
public save: Mock<(task: Task, ctx?: ServerCallContext) => Promise<void>> = vi.fn();
|
||||
public load: Mock<(id: string, ctx?: ServerCallContext) => Promise<Task | undefined>> = vi.fn();
|
||||
public list: Mock<
|
||||
(params: ListTasksRequest, ctx?: ServerCallContext) => Promise<ListTasksResponse>
|
||||
> = vi.fn();
|
||||
}
|
||||
|
||||
@ -11,15 +11,10 @@ import { DefaultExecutionEventBusManager } from '../../src/server/events/executi
|
||||
import {
|
||||
AgentCard,
|
||||
Message,
|
||||
TaskPushNotificationConfig,
|
||||
MessageSendParams,
|
||||
PushNotificationConfig,
|
||||
Task,
|
||||
Role,
|
||||
TaskState,
|
||||
TaskStatus,
|
||||
TaskStatusUpdateEvent,
|
||||
} from '../../src/types/pb/a2a.js';
|
||||
import { SendMessageRequest } from '../../src/index.js';
|
||||
import { ServerCallContext } from '../../src/server/context.js';
|
||||
} from '../../src/index.js';
|
||||
import { fakeTaskExecute, MockAgentExecutor } from './mocks/agent-executor.mock.js';
|
||||
|
||||
type PushNotificationSenderSpy = MockInstance<(task: Task) => Promise<void>>;
|
||||
@ -44,28 +39,16 @@ describe('Push Notification Integration Tests', () => {
|
||||
const testAgentCard: AgentCard = {
|
||||
name: 'Test Agent',
|
||||
description: 'An agent for testing push notifications',
|
||||
url: 'http://localhost:8080',
|
||||
version: '1.0.0',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:8080',
|
||||
protocolBinding: 'JSONRPC',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0',
|
||||
},
|
||||
],
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: true,
|
||||
extensions: [],
|
||||
},
|
||||
defaultInputModes: ['text/plain'],
|
||||
defaultOutputModes: ['text/plain'],
|
||||
skills: [],
|
||||
provider: undefined,
|
||||
documentationUrl: '',
|
||||
securitySchemes: {},
|
||||
securityRequirements: [],
|
||||
signatures: [],
|
||||
};
|
||||
|
||||
// Create test Express server to receive push notifications
|
||||
@ -93,7 +76,7 @@ describe('Push Notification Integration Tests', () => {
|
||||
app.post('/notify/:scenario', async (req: Request, res: Response) => {
|
||||
const scenario = req.params.scenario;
|
||||
// Simulate delay for 'submitted' status to test correct ordering of notifications
|
||||
if (scenario === 'delay_on_submitted' && req.body.status.state === 'TASK_STATE_SUBMITTED') {
|
||||
if (scenario === 'delay_on_submitted' && req.body.status.state === 'submitted') {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
|
||||
@ -158,20 +141,10 @@ describe('Push Notification Integration Tests', () => {
|
||||
|
||||
const createTestMessage = (text: string, taskId?: string): Message => ({
|
||||
messageId: `msg-${Date.now()}`,
|
||||
role: Role.ROLE_USER,
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: text },
|
||||
mediaType: 'text/plain',
|
||||
filename: '',
|
||||
metadata: {},
|
||||
},
|
||||
],
|
||||
contextId: '',
|
||||
taskId: taskId || '',
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text }],
|
||||
kind: 'message',
|
||||
...(taskId && { taskId }),
|
||||
});
|
||||
|
||||
const waitForPushNotifications = async (spy: PushNotificationSenderSpy) => {
|
||||
@ -180,38 +153,28 @@ describe('Push Notification Integration Tests', () => {
|
||||
|
||||
describe('End-to-End Push Notification Flow', () => {
|
||||
it('should send push notifications for task status updates', async () => {
|
||||
const pushConfig: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
taskId: '',
|
||||
const pushConfig: PushNotificationConfig = {
|
||||
id: 'test-push-config',
|
||||
url: `${testServerUrl}/notify/delay_on_submitted`,
|
||||
token: 'test-auth-token',
|
||||
authentication: undefined,
|
||||
};
|
||||
|
||||
const contextId = 'test-push-context';
|
||||
const params: SendMessageRequest = {
|
||||
tenant: '',
|
||||
const params: MessageSendParams = {
|
||||
message: {
|
||||
...createTestMessage('Test task with push notifications'),
|
||||
contextId: contextId,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
},
|
||||
metadata: {},
|
||||
configuration: {
|
||||
taskPushNotificationConfig: pushConfig,
|
||||
historyLength: 0,
|
||||
returnImmediately: false,
|
||||
acceptedOutputModes: [],
|
||||
pushNotificationConfig: pushConfig,
|
||||
},
|
||||
};
|
||||
|
||||
let taskId: string = '';
|
||||
let taskId: string;
|
||||
// Mock the agent executor to publish all three states for this test only
|
||||
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
|
||||
taskId = ctx.taskId;
|
||||
await fakeTaskExecute(ctx, bus);
|
||||
fakeTaskExecute(ctx, bus);
|
||||
});
|
||||
|
||||
// Send message and wait for completion
|
||||
@ -225,13 +188,8 @@ describe('Push Notification Integration Tests', () => {
|
||||
id: taskId,
|
||||
contextId,
|
||||
history: [params.message as Message],
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_COMPLETED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
artifacts: [],
|
||||
metadata: {},
|
||||
status: { state: 'completed' },
|
||||
kind: 'task',
|
||||
};
|
||||
|
||||
// Verify push notifications were sent
|
||||
@ -243,9 +201,9 @@ describe('Push Notification Integration Tests', () => {
|
||||
|
||||
// Verify all three states are present
|
||||
const states = receivedNotifications.map((n) => n.body.status.state);
|
||||
assert.include(states, TaskState.TASK_STATE_SUBMITTED, 'Should include submitted state');
|
||||
assert.include(states, TaskState.TASK_STATE_WORKING, 'Should include working state');
|
||||
assert.include(states, TaskState.TASK_STATE_COMPLETED, 'Should include completed state');
|
||||
assert.include(states, 'submitted', 'Should include submitted state');
|
||||
assert.include(states, 'working', 'Should include working state');
|
||||
assert.include(states, 'completed', 'Should include completed state');
|
||||
|
||||
// Verify first notification has correct format
|
||||
const firstNotification = receivedNotifications[0];
|
||||
@ -255,72 +213,62 @@ describe('Push Notification Integration Tests', () => {
|
||||
assert.equal(firstNotification.headers['x-a2a-notification-token'], 'test-auth-token');
|
||||
assert.deepEqual(firstNotification.body, {
|
||||
...expectedTaskResult,
|
||||
status: { state: TaskState.TASK_STATE_SUBMITTED },
|
||||
status: { state: 'submitted' },
|
||||
});
|
||||
|
||||
const secondNotification = receivedNotifications[1];
|
||||
assert.deepEqual(secondNotification.body, {
|
||||
...expectedTaskResult,
|
||||
status: { state: TaskState.TASK_STATE_WORKING },
|
||||
status: { state: 'working' },
|
||||
});
|
||||
|
||||
const thirdNotification = receivedNotifications[2];
|
||||
assert.deepEqual(thirdNotification.body, {
|
||||
...expectedTaskResult,
|
||||
status: { state: TaskState.TASK_STATE_COMPLETED },
|
||||
status: { state: 'completed' },
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle multiple push notification endpoints for the same task', async () => {
|
||||
const pushConfig1: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
taskId: 'test-multi-endpoints',
|
||||
const pushConfig1: PushNotificationConfig = {
|
||||
id: 'config-1',
|
||||
url: `${testServerUrl}/notify`,
|
||||
token: 'token-1',
|
||||
authentication: undefined,
|
||||
};
|
||||
|
||||
const pushConfig2: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
taskId: 'test-multi-endpoints',
|
||||
const pushConfig2: PushNotificationConfig = {
|
||||
id: 'config-2',
|
||||
url: `${testServerUrl}/notify/second`,
|
||||
token: 'token-2',
|
||||
authentication: undefined,
|
||||
};
|
||||
|
||||
const params: SendMessageRequest = {
|
||||
tenant: '',
|
||||
const params: MessageSendParams = {
|
||||
message: {
|
||||
...createTestMessage('Test task with multiple push endpoints', 'test-multi-endpoints'),
|
||||
...createTestMessage('Test task with multiple push endpoints'),
|
||||
taskId: 'test-multi-endpoints',
|
||||
contextId: 'test-context',
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
},
|
||||
metadata: {},
|
||||
configuration: undefined,
|
||||
};
|
||||
|
||||
// Assume the task is created by a previous message
|
||||
const task: Task = {
|
||||
id: 'test-multi-endpoints',
|
||||
contextId: 'test-context',
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_SUBMITTED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
history: [],
|
||||
artifacts: [],
|
||||
metadata: {},
|
||||
status: { state: 'submitted' },
|
||||
kind: 'task',
|
||||
};
|
||||
await taskStore.save(task);
|
||||
|
||||
// Set multiple push notification configs for this message
|
||||
await handler.createTaskPushNotificationConfig(pushConfig1, new ServerCallContext());
|
||||
await handler.setTaskPushNotificationConfig({
|
||||
taskId: task.id,
|
||||
pushNotificationConfig: pushConfig1,
|
||||
});
|
||||
|
||||
await handler.createTaskPushNotificationConfig(pushConfig2, new ServerCallContext());
|
||||
await handler.setTaskPushNotificationConfig({
|
||||
taskId: task.id,
|
||||
pushNotificationConfig: pushConfig2,
|
||||
});
|
||||
|
||||
// Mock the agent executor to publish only completed state
|
||||
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
|
||||
@ -329,27 +277,20 @@ describe('Push Notification Integration Tests', () => {
|
||||
|
||||
// Publish working status
|
||||
bus.publish({
|
||||
taskId,
|
||||
id: taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_WORKING,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
metadata: {},
|
||||
} as TaskStatusUpdateEvent);
|
||||
status: { state: 'working' },
|
||||
kind: 'task',
|
||||
});
|
||||
|
||||
// Publish completion directly
|
||||
bus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_COMPLETED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
metadata: {},
|
||||
} as TaskStatusUpdateEvent);
|
||||
kind: 'status-update',
|
||||
status: { state: 'completed' },
|
||||
final: true,
|
||||
});
|
||||
|
||||
bus.finished();
|
||||
});
|
||||
@ -385,34 +326,24 @@ describe('Push Notification Integration Tests', () => {
|
||||
});
|
||||
|
||||
it('should complete task successfully even when push notification endpoint returns an error', async () => {
|
||||
const pushConfig: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
taskId: '',
|
||||
const pushConfig: PushNotificationConfig = {
|
||||
id: 'error-endpoint-config',
|
||||
url: `${testServerUrl}/notify/error`,
|
||||
token: 'test-auth-token',
|
||||
authentication: undefined,
|
||||
};
|
||||
|
||||
const contextId = 'test-error-context';
|
||||
const params: SendMessageRequest = {
|
||||
tenant: '',
|
||||
const params: MessageSendParams = {
|
||||
message: {
|
||||
...createTestMessage('Test task with error endpoint'),
|
||||
contextId: contextId,
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
},
|
||||
metadata: {},
|
||||
configuration: {
|
||||
taskPushNotificationConfig: pushConfig,
|
||||
historyLength: 0,
|
||||
returnImmediately: false,
|
||||
acceptedOutputModes: [],
|
||||
pushNotificationConfig: pushConfig,
|
||||
},
|
||||
};
|
||||
|
||||
let taskId: string = '';
|
||||
let taskId: string;
|
||||
// Mock the agent executor to publish task states
|
||||
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
|
||||
taskId = ctx.taskId;
|
||||
@ -421,7 +352,7 @@ describe('Push Notification Integration Tests', () => {
|
||||
|
||||
// Send message and wait for completion - this should not throw an error
|
||||
const result = await handler.sendMessage(params);
|
||||
const taskResult = result as Task;
|
||||
const task = result as Task;
|
||||
|
||||
// Wait for async push notifications to be sent
|
||||
await waitForPushNotifications(pushNotificationSenderSpy);
|
||||
@ -430,19 +361,13 @@ describe('Push Notification Integration Tests', () => {
|
||||
const expectedTaskResult: Task = {
|
||||
id: taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_COMPLETED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
history: [params.message as Message],
|
||||
artifacts: [],
|
||||
metadata: {},
|
||||
status: { state: 'completed' },
|
||||
kind: 'task',
|
||||
};
|
||||
|
||||
// Verify the task payload requires loose matching for timestamps
|
||||
assert.equal(taskResult.id, expectedTaskResult.id);
|
||||
assert.equal(taskResult.status?.state, TaskState.TASK_STATE_COMPLETED);
|
||||
// Verify the task payload
|
||||
assert.deepEqual(task, expectedTaskResult);
|
||||
|
||||
// Verify the error endpoint was hit
|
||||
const errorNotifications = receivedNotifications.filter((n) => n.url === '/notify/error');
|
||||
@ -456,24 +381,16 @@ describe('Push Notification Integration Tests', () => {
|
||||
|
||||
describe('Push Notification Header Configuration Tests', () => {
|
||||
it('should use default header name when tokenHeaderName is not specified', async () => {
|
||||
const pushConfig: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
taskId: '',
|
||||
const pushConfig: PushNotificationConfig = {
|
||||
id: 'default-header-test',
|
||||
url: `${testServerUrl}/notify`,
|
||||
token: 'default-token',
|
||||
authentication: undefined,
|
||||
};
|
||||
|
||||
const params: SendMessageRequest = {
|
||||
tenant: '',
|
||||
const params: MessageSendParams = {
|
||||
message: createTestMessage('Test with default header name'),
|
||||
metadata: {},
|
||||
configuration: {
|
||||
taskPushNotificationConfig: pushConfig,
|
||||
historyLength: 0,
|
||||
returnImmediately: false,
|
||||
acceptedOutputModes: [],
|
||||
pushNotificationConfig: pushConfig,
|
||||
},
|
||||
};
|
||||
|
||||
@ -485,26 +402,17 @@ describe('Push Notification Integration Tests', () => {
|
||||
bus.publish({
|
||||
id: taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_SUBMITTED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
artifacts: [],
|
||||
history: [],
|
||||
metadata: {},
|
||||
} as Task);
|
||||
status: { state: 'submitted' },
|
||||
kind: 'task',
|
||||
});
|
||||
|
||||
bus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_COMPLETED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
metadata: {},
|
||||
} as TaskStatusUpdateEvent);
|
||||
kind: 'status-update',
|
||||
status: { state: 'completed' },
|
||||
final: true,
|
||||
});
|
||||
|
||||
bus.finished();
|
||||
});
|
||||
@ -554,24 +462,16 @@ describe('Push Notification Integration Tests', () => {
|
||||
customPushNotificationSender
|
||||
);
|
||||
|
||||
const pushConfig: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
taskId: '',
|
||||
const pushConfig: PushNotificationConfig = {
|
||||
id: 'custom-header-test',
|
||||
url: `${testServerUrl}/notify`,
|
||||
token: 'custom-token',
|
||||
authentication: undefined,
|
||||
};
|
||||
|
||||
const params: SendMessageRequest = {
|
||||
tenant: '',
|
||||
const params: MessageSendParams = {
|
||||
message: createTestMessage('Test with custom header name'),
|
||||
metadata: {},
|
||||
configuration: {
|
||||
taskPushNotificationConfig: pushConfig,
|
||||
historyLength: 0,
|
||||
returnImmediately: false,
|
||||
acceptedOutputModes: [],
|
||||
pushNotificationConfig: pushConfig,
|
||||
},
|
||||
};
|
||||
|
||||
@ -583,26 +483,17 @@ describe('Push Notification Integration Tests', () => {
|
||||
bus.publish({
|
||||
id: taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_SUBMITTED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
artifacts: [],
|
||||
history: [],
|
||||
metadata: {},
|
||||
} as Task);
|
||||
status: { state: 'submitted' },
|
||||
kind: 'task',
|
||||
});
|
||||
|
||||
bus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_COMPLETED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
metadata: {},
|
||||
} as TaskStatusUpdateEvent);
|
||||
kind: 'status-update',
|
||||
status: { state: 'completed' },
|
||||
final: true,
|
||||
});
|
||||
|
||||
bus.finished();
|
||||
});
|
||||
@ -638,24 +529,16 @@ describe('Push Notification Integration Tests', () => {
|
||||
});
|
||||
|
||||
it('should not send token header when token is not provided', async () => {
|
||||
const pushConfig: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
taskId: '',
|
||||
const pushConfig: PushNotificationConfig = {
|
||||
id: 'no-token-test',
|
||||
url: `${testServerUrl}/notify`,
|
||||
token: '', // Empty token
|
||||
authentication: undefined,
|
||||
// No token provided
|
||||
};
|
||||
|
||||
const params: SendMessageRequest = {
|
||||
tenant: '',
|
||||
const params: MessageSendParams = {
|
||||
message: createTestMessage('Test without token'),
|
||||
metadata: {},
|
||||
configuration: {
|
||||
taskPushNotificationConfig: pushConfig,
|
||||
historyLength: 0,
|
||||
returnImmediately: false,
|
||||
acceptedOutputModes: [],
|
||||
pushNotificationConfig: pushConfig,
|
||||
},
|
||||
};
|
||||
|
||||
@ -667,26 +550,17 @@ describe('Push Notification Integration Tests', () => {
|
||||
bus.publish({
|
||||
id: taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_SUBMITTED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
artifacts: [],
|
||||
history: [],
|
||||
metadata: {},
|
||||
} as Task);
|
||||
status: { state: 'submitted' },
|
||||
kind: 'task',
|
||||
});
|
||||
|
||||
bus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_COMPLETED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
metadata: {},
|
||||
} as TaskStatusUpdateEvent);
|
||||
kind: 'status-update',
|
||||
status: { state: 'completed' },
|
||||
final: true,
|
||||
});
|
||||
|
||||
bus.finished();
|
||||
});
|
||||
@ -735,54 +609,44 @@ describe('Push Notification Integration Tests', () => {
|
||||
customPushNotificationSender
|
||||
);
|
||||
|
||||
const pushConfig1: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
taskId: 'multi-config-test',
|
||||
const pushConfig1: PushNotificationConfig = {
|
||||
id: 'config-with-token',
|
||||
url: `${testServerUrl}/notify`,
|
||||
token: 'token-1',
|
||||
authentication: undefined,
|
||||
};
|
||||
|
||||
const pushConfig2: TaskPushNotificationConfig = {
|
||||
tenant: '',
|
||||
taskId: 'multi-config-test',
|
||||
const pushConfig2: PushNotificationConfig = {
|
||||
id: 'config-without-token',
|
||||
url: `${testServerUrl}/notify/second`,
|
||||
token: '',
|
||||
authentication: undefined,
|
||||
// No token
|
||||
};
|
||||
|
||||
const params: SendMessageRequest = {
|
||||
tenant: '',
|
||||
const params: MessageSendParams = {
|
||||
message: {
|
||||
...createTestMessage('Test with multiple configs', 'multi-config-test'),
|
||||
...createTestMessage('Test with multiple configs'),
|
||||
taskId: 'multi-config-test',
|
||||
contextId: 'test-context',
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
},
|
||||
metadata: {},
|
||||
configuration: undefined,
|
||||
};
|
||||
|
||||
// Create task and set multiple push configs
|
||||
const task: Task = {
|
||||
id: 'multi-config-test',
|
||||
contextId: 'test-context',
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_SUBMITTED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
history: [],
|
||||
artifacts: [],
|
||||
metadata: {},
|
||||
status: { state: 'submitted' },
|
||||
kind: 'task',
|
||||
};
|
||||
await taskStore.save(task);
|
||||
|
||||
await customHandler.createTaskPushNotificationConfig(pushConfig1, new ServerCallContext());
|
||||
await customHandler.setTaskPushNotificationConfig({
|
||||
taskId: task.id,
|
||||
pushNotificationConfig: pushConfig1,
|
||||
});
|
||||
|
||||
await customHandler.createTaskPushNotificationConfig(pushConfig2, new ServerCallContext());
|
||||
await customHandler.setTaskPushNotificationConfig({
|
||||
taskId: task.id,
|
||||
pushNotificationConfig: pushConfig2,
|
||||
});
|
||||
|
||||
// Mock the agent executor to publish completion
|
||||
mockAgentExecutor.execute.mockImplementation(async (ctx, bus) => {
|
||||
@ -792,13 +656,10 @@ describe('Push Notification Integration Tests', () => {
|
||||
bus.publish({
|
||||
taskId,
|
||||
contextId,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_COMPLETED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
metadata: {},
|
||||
} as TaskStatusUpdateEvent);
|
||||
kind: 'status-update',
|
||||
status: { state: 'completed' },
|
||||
final: true,
|
||||
});
|
||||
|
||||
bus.finished();
|
||||
});
|
||||
|
||||
@ -7,14 +7,9 @@ import {
|
||||
HTTP_STATUS,
|
||||
} from '../../src/server/transports/rest/rest_transport_handler.js';
|
||||
import { A2ARequestHandler } from '../../src/server/request_handler/a2a_request_handler.js';
|
||||
import {
|
||||
RequestMalformedError,
|
||||
TaskNotFoundError,
|
||||
TaskNotCancelableError,
|
||||
PushNotificationNotSupportedError,
|
||||
UnsupportedOperationError,
|
||||
} from '../../src/errors.js';
|
||||
import { AgentCard, Task, Message, Role, TaskState, TaskStatus } from '../../src/index.js';
|
||||
import { A2AError } from '../../src/server/error.js';
|
||||
import { A2A_ERROR_CODE } from '../../src/errors.js';
|
||||
import { AgentCard, Task, Message } from '../../src/types.js';
|
||||
import { ServerCallContext } from '../../src/server/context.js';
|
||||
|
||||
describe('RestTransportHandler', () => {
|
||||
@ -23,61 +18,34 @@ describe('RestTransportHandler', () => {
|
||||
let mockContext: ServerCallContext;
|
||||
|
||||
const testAgentCard: AgentCard = {
|
||||
protocolVersion: '0.3.0',
|
||||
name: 'Test Agent',
|
||||
description: 'An agent for testing purposes',
|
||||
url: 'http://localhost:8080',
|
||||
preferredTransport: 'HTTP+JSON',
|
||||
version: '1.0.0',
|
||||
supportedInterfaces: [
|
||||
{
|
||||
url: 'http://localhost:8080/a2a/v1',
|
||||
protocolBinding: 'HTTP+JSON',
|
||||
tenant: '',
|
||||
protocolVersion: '1.0',
|
||||
},
|
||||
],
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: true,
|
||||
extensions: [],
|
||||
},
|
||||
defaultInputModes: ['text/plain'],
|
||||
defaultOutputModes: ['text/plain'],
|
||||
skills: [],
|
||||
provider: undefined,
|
||||
documentationUrl: '',
|
||||
securitySchemes: {},
|
||||
securityRequirements: [],
|
||||
signatures: [],
|
||||
};
|
||||
|
||||
const testMessage: Message = {
|
||||
messageId: 'msg-1',
|
||||
role: Role.ROLE_USER,
|
||||
parts: [
|
||||
{
|
||||
content: { $case: 'text', value: 'Hello' },
|
||||
mediaType: 'text/plain',
|
||||
filename: '',
|
||||
metadata: undefined,
|
||||
},
|
||||
],
|
||||
contextId: 'ctx-1',
|
||||
taskId: '',
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
referenceTaskIds: [],
|
||||
role: 'user' as const,
|
||||
parts: [{ kind: 'text' as const, text: 'Hello' }],
|
||||
kind: 'message' as const,
|
||||
};
|
||||
|
||||
const testTask: Task = {
|
||||
id: 'task-1',
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_COMPLETED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
kind: 'task' as const,
|
||||
status: { state: 'completed' as const },
|
||||
contextId: 'ctx-1',
|
||||
history: [],
|
||||
artifacts: [],
|
||||
metadata: {},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
@ -88,12 +56,11 @@ describe('RestTransportHandler', () => {
|
||||
sendMessageStream: vi.fn(),
|
||||
getTask: vi.fn().mockResolvedValue(testTask),
|
||||
cancelTask: vi.fn().mockResolvedValue(testTask),
|
||||
createTaskPushNotificationConfig: vi.fn(),
|
||||
setTaskPushNotificationConfig: vi.fn(),
|
||||
getTaskPushNotificationConfig: vi.fn(),
|
||||
listTaskPushNotificationConfigs: vi.fn(),
|
||||
deleteTaskPushNotificationConfig: vi.fn(),
|
||||
resubscribe: vi.fn(),
|
||||
listTasks: vi.fn(),
|
||||
};
|
||||
transportHandler = new RestTransportHandler(mockRequestHandler);
|
||||
mockContext = new ServerCallContext();
|
||||
@ -105,24 +72,36 @@ describe('RestTransportHandler', () => {
|
||||
|
||||
describe('mapErrorToStatus', () => {
|
||||
it.each([
|
||||
[new RequestMalformedError(''), HTTP_STATUS.BAD_REQUEST],
|
||||
[new TaskNotFoundError(''), HTTP_STATUS.NOT_FOUND],
|
||||
[new TaskNotCancelableError(''), HTTP_STATUS.CONFLICT],
|
||||
[new PushNotificationNotSupportedError(''), HTTP_STATUS.BAD_REQUEST],
|
||||
[new UnsupportedOperationError(''), HTTP_STATUS.BAD_REQUEST],
|
||||
[new Error(''), HTTP_STATUS.INTERNAL_SERVER_ERROR],
|
||||
])('should map error %s to HTTP status %s', (error, httpStatus) => {
|
||||
expect(mapErrorToStatus(error)).to.equal(httpStatus);
|
||||
[A2A_ERROR_CODE.PARSE_ERROR, HTTP_STATUS.BAD_REQUEST],
|
||||
[A2A_ERROR_CODE.INVALID_REQUEST, HTTP_STATUS.BAD_REQUEST],
|
||||
[A2A_ERROR_CODE.INVALID_PARAMS, HTTP_STATUS.BAD_REQUEST],
|
||||
[A2A_ERROR_CODE.METHOD_NOT_FOUND, HTTP_STATUS.NOT_FOUND],
|
||||
[A2A_ERROR_CODE.TASK_NOT_FOUND, HTTP_STATUS.NOT_FOUND],
|
||||
[A2A_ERROR_CODE.TASK_NOT_CANCELABLE, HTTP_STATUS.CONFLICT],
|
||||
[A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED, HTTP_STATUS.BAD_REQUEST],
|
||||
[A2A_ERROR_CODE.UNSUPPORTED_OPERATION, HTTP_STATUS.BAD_REQUEST],
|
||||
[-99999, HTTP_STATUS.INTERNAL_SERVER_ERROR],
|
||||
])('should map error code %s to HTTP status %s', (errorCode, httpStatus) => {
|
||||
expect(mapErrorToStatus(errorCode)).to.equal(httpStatus);
|
||||
});
|
||||
});
|
||||
|
||||
describe('toHTTPError', () => {
|
||||
it('should convert A2AError to HTTP error format', () => {
|
||||
const error = new RequestMalformedError('Invalid input');
|
||||
const error = A2AError.invalidParams('Invalid input');
|
||||
const httpError = toHTTPError(error);
|
||||
|
||||
expect(httpError.name).to.equal('RequestMalformedError');
|
||||
expect(httpError.code).to.equal(A2A_ERROR_CODE.INVALID_PARAMS);
|
||||
expect(httpError.message).to.equal('Invalid input');
|
||||
expect(httpError.data).to.be.undefined;
|
||||
});
|
||||
|
||||
it('should include data if present in A2AError', () => {
|
||||
const error = A2AError.invalidParams('Invalid input');
|
||||
error.data = { field: 'email' };
|
||||
const httpError = toHTTPError(error);
|
||||
|
||||
expect(httpError.data).to.deep.equal({ field: 'email' });
|
||||
});
|
||||
});
|
||||
|
||||
@ -151,15 +130,10 @@ describe('RestTransportHandler', () => {
|
||||
input: {
|
||||
message: {
|
||||
messageId: 'msg-1',
|
||||
role: Role.ROLE_USER,
|
||||
content: [{ part: { $case: 'text', value: 'Hello' } }],
|
||||
contextId: '',
|
||||
taskId: '',
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
role: 'user' as const,
|
||||
parts: [{ kind: 'text' as const, text: 'Hello' }],
|
||||
kind: 'message' as const,
|
||||
},
|
||||
metadata: {},
|
||||
configuration: undefined,
|
||||
},
|
||||
expectedMessageId: 'msg-1',
|
||||
},
|
||||
@ -184,21 +158,51 @@ describe('RestTransportHandler', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw InvalidParams if request.messageId is missing', async () => {
|
||||
it('should throw InvalidParams if message.messageId is missing', async () => {
|
||||
const invalidMessage = {
|
||||
message: {
|
||||
role: Role.ROLE_USER as const,
|
||||
parts: [{ part: { $case: 'text', text: 'Hello' } }],
|
||||
role: 'user' as const,
|
||||
parts: [{ kind: 'text' as const, text: 'Hello' }],
|
||||
kind: 'message' as const,
|
||||
},
|
||||
metadata: {},
|
||||
configuration: undefined as any,
|
||||
};
|
||||
|
||||
await expect(
|
||||
transportHandler.sendMessage(invalidMessage as any, mockContext)
|
||||
).rejects.toThrow('message.messageId is required');
|
||||
});
|
||||
|
||||
it('should normalize configuration with snake_case fields', async () => {
|
||||
const inputWithConfig = {
|
||||
message: testMessage,
|
||||
configuration: {
|
||||
blocking: true,
|
||||
acceptedOutputModes: ['text/plain'],
|
||||
historyLength: 5,
|
||||
pushNotificationConfig: {
|
||||
id: 'push-1',
|
||||
url: 'https://example.com',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
await transportHandler.sendMessage(inputWithConfig as any, mockContext);
|
||||
|
||||
expect(mockRequestHandler.sendMessage as Mock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
configuration: expect.objectContaining({
|
||||
blocking: true,
|
||||
acceptedOutputModes: ['text/plain'],
|
||||
historyLength: 5,
|
||||
pushNotificationConfig: {
|
||||
id: 'push-1',
|
||||
url: 'https://example.com',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
mockContext
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sendMessageStream', () => {
|
||||
@ -209,10 +213,7 @@ describe('RestTransportHandler', () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
transportHandler.sendMessageStream(
|
||||
{ message: testMessage, metadata: {}, configuration: undefined, tenant: '' },
|
||||
mockContext
|
||||
)
|
||||
transportHandler.sendMessageStream({ message: testMessage }, mockContext)
|
||||
).rejects.toThrow('Agent does not support streaming');
|
||||
});
|
||||
|
||||
@ -223,7 +224,7 @@ describe('RestTransportHandler', () => {
|
||||
(mockRequestHandler.sendMessageStream as Mock).mockResolvedValue(mockStream());
|
||||
|
||||
const stream = await transportHandler.sendMessageStream(
|
||||
{ message: testMessage, metadata: {}, configuration: undefined, tenant: '' },
|
||||
{ message: testMessage },
|
||||
mockContext
|
||||
);
|
||||
|
||||
@ -238,7 +239,7 @@ describe('RestTransportHandler', () => {
|
||||
|
||||
expect(result).to.deep.equal(testTask);
|
||||
expect(mockRequestHandler.getTask as Mock).toHaveBeenCalledWith(
|
||||
{ id: 'task-1', historyLength: 0, tenant: '' },
|
||||
{ id: 'task-1' },
|
||||
mockContext
|
||||
);
|
||||
});
|
||||
@ -247,7 +248,7 @@ describe('RestTransportHandler', () => {
|
||||
await transportHandler.getTask('task-1', mockContext, '10');
|
||||
|
||||
expect(mockRequestHandler.getTask as Mock).toHaveBeenCalledWith(
|
||||
{ id: 'task-1', historyLength: 10, tenant: '' },
|
||||
{ id: 'task-1', historyLength: 10 },
|
||||
mockContext
|
||||
);
|
||||
});
|
||||
@ -267,21 +268,14 @@ describe('RestTransportHandler', () => {
|
||||
|
||||
describe('cancelTask', () => {
|
||||
it('should cancel task by ID', async () => {
|
||||
const cancelledTask = {
|
||||
...testTask,
|
||||
status: {
|
||||
state: TaskState.TASK_STATE_CANCELED,
|
||||
message: undefined,
|
||||
timestamp: undefined,
|
||||
} as TaskStatus,
|
||||
};
|
||||
const cancelledTask = { ...testTask, status: { state: 'canceled' as const } };
|
||||
(mockRequestHandler.cancelTask as Mock).mockResolvedValue(cancelledTask);
|
||||
|
||||
const result = await transportHandler.cancelTask('task-1', mockContext);
|
||||
|
||||
expect(result.status?.state).to.equal(TaskState.TASK_STATE_CANCELED);
|
||||
expect(result.status.state).to.equal('canceled');
|
||||
expect(mockRequestHandler.cancelTask as Mock).toHaveBeenCalledWith(
|
||||
{ id: 'task-1', tenant: '', metadata: {} },
|
||||
{ id: 'task-1' },
|
||||
mockContext
|
||||
);
|
||||
});
|
||||
@ -309,7 +303,7 @@ describe('RestTransportHandler', () => {
|
||||
|
||||
expect(stream).toBeDefined();
|
||||
expect(mockRequestHandler.resubscribe as Mock).toHaveBeenCalledWith(
|
||||
{ id: 'task-1', tenant: '' },
|
||||
{ id: 'task-1' },
|
||||
mockContext
|
||||
);
|
||||
});
|
||||
@ -318,11 +312,13 @@ describe('RestTransportHandler', () => {
|
||||
describe('Push Notification Config', () => {
|
||||
const mockConfig = {
|
||||
taskId: 'task-1',
|
||||
id: 'config-1',
|
||||
url: 'https://example.com/webhook',
|
||||
pushNotificationConfig: {
|
||||
id: 'config-1',
|
||||
url: 'https://example.com/webhook',
|
||||
},
|
||||
};
|
||||
|
||||
describe('createTaskPushNotificationConfig', () => {
|
||||
describe('setTaskPushNotificationConfig', () => {
|
||||
it('should throw PushNotificationNotSupported if not supported', async () => {
|
||||
(mockRequestHandler.getAgentCard as Mock).mockResolvedValue({
|
||||
...testAgentCard,
|
||||
@ -330,30 +326,39 @@ describe('RestTransportHandler', () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
transportHandler.createTaskPushNotificationConfig(mockConfig as any, mockContext)
|
||||
transportHandler.setTaskPushNotificationConfig(mockConfig, mockContext)
|
||||
).rejects.toThrow('Push Notification is not supported');
|
||||
});
|
||||
|
||||
it('should normalize and set config if supported', async () => {
|
||||
(mockRequestHandler.createTaskPushNotificationConfig as Mock).mockResolvedValue(mockConfig);
|
||||
(mockRequestHandler.setTaskPushNotificationConfig as Mock).mockResolvedValue(mockConfig);
|
||||
|
||||
const result = await transportHandler.createTaskPushNotificationConfig(
|
||||
mockConfig as any,
|
||||
const result = await transportHandler.setTaskPushNotificationConfig(
|
||||
mockConfig,
|
||||
mockContext
|
||||
);
|
||||
|
||||
expect(result).to.deep.equal(mockConfig);
|
||||
});
|
||||
|
||||
it('should throw InvalidParams if id is missing', async () => {
|
||||
it('should throw InvalidParams if taskId is missing', async () => {
|
||||
const invalidConfig = {
|
||||
taskId: 'task-1',
|
||||
url: 'https://example.com/webhook',
|
||||
pushNotificationConfig: { id: 'config-1', url: 'https://example.com/webhook' },
|
||||
};
|
||||
|
||||
await expect(
|
||||
transportHandler.createTaskPushNotificationConfig(invalidConfig as any, mockContext)
|
||||
).rejects.toThrow('id is required');
|
||||
transportHandler.setTaskPushNotificationConfig(invalidConfig as any, mockContext)
|
||||
).rejects.toThrow('taskId is required');
|
||||
});
|
||||
|
||||
it('should throw InvalidParams if pushNotificationConfig is missing', async () => {
|
||||
const invalidConfig = {
|
||||
taskId: 'task-1',
|
||||
};
|
||||
|
||||
await expect(
|
||||
transportHandler.setTaskPushNotificationConfig(invalidConfig as any, mockContext)
|
||||
).rejects.toThrow('pushNotificationConfig is required');
|
||||
});
|
||||
});
|
||||
|
||||
@ -367,9 +372,9 @@ describe('RestTransportHandler', () => {
|
||||
mockContext
|
||||
);
|
||||
|
||||
expect(result).to.deep.equal([mockConfig]);
|
||||
expect(result).to.deep.equal(configs);
|
||||
expect(mockRequestHandler.listTaskPushNotificationConfigs as Mock).toHaveBeenCalledWith(
|
||||
{ taskId: 'task-1', pageSize: 0, pageToken: '', tenant: '' },
|
||||
{ id: 'task-1' },
|
||||
mockContext
|
||||
);
|
||||
});
|
||||
@ -387,22 +392,10 @@ describe('RestTransportHandler', () => {
|
||||
|
||||
expect(result).to.deep.equal(mockConfig);
|
||||
expect(mockRequestHandler.getTaskPushNotificationConfig as Mock).toHaveBeenCalledWith(
|
||||
{ taskId: 'task-1', id: 'config-1', tenant: '' },
|
||||
{ id: 'task-1', pushNotificationConfigId: 'config-1' },
|
||||
mockContext
|
||||
);
|
||||
});
|
||||
|
||||
it('should return config with correct name format', async () => {
|
||||
(mockRequestHandler.getTaskPushNotificationConfig as Mock).mockResolvedValue(mockConfig);
|
||||
|
||||
const result = await transportHandler.getTaskPushNotificationConfig(
|
||||
'task-1',
|
||||
'config-1',
|
||||
mockContext
|
||||
);
|
||||
|
||||
expect(result.taskId).to.equal('task-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteTaskPushNotificationConfig', () => {
|
||||
@ -412,7 +405,7 @@ describe('RestTransportHandler', () => {
|
||||
await transportHandler.deleteTaskPushNotificationConfig('task-1', 'config-1', mockContext);
|
||||
|
||||
expect(mockRequestHandler.deleteTaskPushNotificationConfig as Mock).toHaveBeenCalledWith(
|
||||
{ taskId: 'task-1', id: 'config-1', tenant: '' },
|
||||
{ id: 'task-1', pushNotificationConfigId: 'config-1' },
|
||||
mockContext
|
||||
);
|
||||
});
|
||||
@ -425,50 +418,36 @@ describe('RestTransportHandler', () => {
|
||||
name: 'camelCase',
|
||||
message: {
|
||||
messageId: 'msg-file',
|
||||
role: Role.ROLE_USER,
|
||||
role: 'user' as const,
|
||||
parts: [
|
||||
{
|
||||
content: {
|
||||
$case: 'url',
|
||||
value: 'https://example.com/file.pdf',
|
||||
kind: 'file' as const,
|
||||
file: {
|
||||
uri: 'https://example.com/file.pdf',
|
||||
mimeType: 'application/pdf',
|
||||
name: 'document.pdf',
|
||||
},
|
||||
mediaType: 'application/pdf',
|
||||
filename: 'file.pdf',
|
||||
},
|
||||
],
|
||||
contextId: '',
|
||||
taskId: '',
|
||||
extensions: [],
|
||||
metadata: {},
|
||||
kind: 'message' as const,
|
||||
},
|
||||
metadata: {},
|
||||
configuration: undefined,
|
||||
},
|
||||
])(
|
||||
'should normalize $name file parts to camelCase',
|
||||
async ({ message, metadata, configuration }) => {
|
||||
await transportHandler.sendMessage(
|
||||
{ message, metadata, configuration } as any,
|
||||
mockContext
|
||||
);
|
||||
])('should normalize $name file parts to camelCase', async ({ message }) => {
|
||||
await transportHandler.sendMessage({ message } as any, mockContext);
|
||||
|
||||
expect(mockRequestHandler.sendMessage as Mock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: expect.objectContaining({
|
||||
parts: [
|
||||
expect.objectContaining({
|
||||
content: {
|
||||
$case: 'url',
|
||||
value: 'https://example.com/file.pdf',
|
||||
},
|
||||
mediaType: 'application/pdf',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
expect(mockRequestHandler.sendMessage as Mock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: expect.objectContaining({
|
||||
parts: [
|
||||
expect.objectContaining({
|
||||
kind: 'file',
|
||||
file: expect.objectContaining({ mimeType: 'application/pdf' }),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
mockContext
|
||||
);
|
||||
}
|
||||
);
|
||||
}),
|
||||
mockContext
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user