From 0fe901350c44f4a71d8c8b4286575e94e80d0aca Mon Sep 17 00:00:00 2001 From: Revinand Date: Sun, 22 Nov 2026 16:34:53 +0100 Subject: [PATCH 01/17] test: capture 2.8.0 goldens for A2A answers and refusals --- tests/integration/baseline-goldens.test.ts | 195 +++++- .../goldens/2.8.0/a2a-agent-card.json | 71 +++ tests/integration/goldens/2.8.0/a2a-free.json | 40 ++ .../goldens/2.8.0/a2a-paid-no-proof.json | 95 +++ .../goldens/2.8.0/a2a-refusals.json | 566 ++++++++++++++++++ .../goldens/2.8.0/a2a-x402-completed.json | 77 +++ .../2.8.0/a2a-x402-input-required.json | 124 ++++ 7 files changed, 1167 insertions(+), 1 deletion(-) create mode 100644 tests/integration/goldens/2.8.0/a2a-agent-card.json create mode 100644 tests/integration/goldens/2.8.0/a2a-free.json create mode 100644 tests/integration/goldens/2.8.0/a2a-paid-no-proof.json create mode 100644 tests/integration/goldens/2.8.0/a2a-refusals.json create mode 100644 tests/integration/goldens/2.8.0/a2a-x402-completed.json create mode 100644 tests/integration/goldens/2.8.0/a2a-x402-input-required.json diff --git a/tests/integration/baseline-goldens.test.ts b/tests/integration/baseline-goldens.test.ts index 453fdc8..ac77c94 100644 --- a/tests/integration/baseline-goldens.test.ts +++ b/tests/integration/baseline-goldens.test.ts @@ -6,6 +6,11 @@ * disabled. If a change alters a golden, update its file in the same commit and * explain why. * + * The 2.8.0 baseline captures A2A responses: the Agent Card, free calls, + * paid calls without proof, x402 extension tasks and selected refusal cases + * from the A2A conformance suite. Snapshots replace server-generated UUIDs + * with `` and preserve ID prefixes. + * * The gateway uses the provider and adapter setup from `runGateway`. One loopback * server fakes the JSON-RPC nodes, remote facilitator and merchant backend. */ @@ -157,7 +162,10 @@ function acpResource(method: string, path: string, withPath: boolean, withBody: } // Configure HTTP, MCP, A2A and ACP with x402, MPP and AP2 using the 2.7.2 config format -async function goldenConfig(x402: Record): Promise { +async function goldenConfig( + x402: Record, + extraResources: Record = {}, +): Promise { const parties = await createParties(); const session = '/checkout_sessions/{checkout_session_id}'; return parseConfig( @@ -228,6 +236,7 @@ async function goldenConfig(x402: Record): Promise { it('the well-known document and a healthy doctor --json report', () => expectDiscoveryGoldens(running, 'multi')); }); + +const A2A_GOLDEN = './goldens/2.8.0'; +const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g; + +interface A2aAnswer { + readonly status: number; + readonly extensions: string | null; + readonly body: unknown; +} + +// Send an A2A request and return a normalized `answer` alongside the parsed `raw` body +async function a2aCall( + url: string, + body: unknown, + headers: Record = {}, +): Promise<{ answer: A2aAnswer; raw: Record }> { + const res = await fetch(`${url}/a2a`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'a2a-version': '1.0', ...headers }, + body: typeof body === 'string' ? body : JSON.stringify(body), + }); + const text = await res.text(); + return { + answer: { + status: res.status, + extensions: res.headers.get('a2a-extensions'), + body: JSON.parse(golden(text, url)), + }, + raw: JSON.parse(text) as Record, + }; +} + +function a2aGolden(value: unknown): string { + return `${JSON.stringify(value, null, 2)}\n`.replaceAll(UUID, ''); +} + +function a2aSend(params: unknown, id: string | number = 'golden'): unknown { + return { jsonrpc: '2.0', id, method: 'SendMessage', params }; +} + +function a2aMessage(parts: unknown[], overrides: Record = {}): unknown { + return { message: { role: 'ROLE_USER', messageId: 'msg-golden', parts, ...overrides } }; +} + +const EXTENSION = { 'a2a-extensions': A2A_X402_EXTENSION_URI }; +const FREE_PART = { data: { resource: 'weather_free', input: { city: 'Berlin' } } }; +const BUY_REPORT = a2aMessage([ + { data: { resource: 'market_report', input: { symbol: 'ETH' } }, mediaType: 'application/json' }, +]); + +describe('2.8.0 goldens: A2A answers', () => { + let running: Running; + + beforeAll(async () => { + running = await startGateway( + await goldenConfig(singleOffer(), { + weather_free: { + name: 'Free Weather', + input: { + type: 'object', + properties: { city: { type: 'string' } }, + required: ['city'], + additionalProperties: false, + }, + backend: { type: 'http', method: 'GET', url: `${upstreamUrl}/backend/weather` }, + pricing: { type: 'free' }, + expose: ['a2a'], + }, + }), + ); + }); + afterAll(() => running?.close()); + + it('the Agent Card', async () => { + const res = await fetch(`${running.url}/.well-known/agent-card.json`); + expect(res.status).toBe(200); + await expect(golden(await res.text(), running.url)).toMatchFileSnapshot( + `${A2A_GOLDEN}/a2a-agent-card.json`, + ); + }); + + it('a free call, and a paid call without a proof or the extension', async () => { + const free = await a2aCall(running.url, a2aSend(a2aMessage([FREE_PART]))); + await expect(a2aGolden(free.answer)).toMatchFileSnapshot(`${A2A_GOLDEN}/a2a-free.json`); + const unpaid = await a2aCall(running.url, a2aSend(BUY_REPORT)); + await expect(a2aGolden(unpaid.answer)).toMatchFileSnapshot( + `${A2A_GOLDEN}/a2a-paid-no-proof.json`, + ); + }); + + it('an x402 extension task, from input-required to completed', async () => { + const required = await a2aCall(running.url, a2aSend(BUY_REPORT), EXTENSION); + await expect(a2aGolden(required.answer)).toMatchFileSnapshot( + `${A2A_GOLDEN}/a2a-x402-input-required.json`, + ); + + const { task } = required.raw['result'] as { + task: { + id: string; + contextId: string; + status: { message: { metadata: Record[] }> } }; + }; + }; + const offer = task.status.message.metadata['x402.payment.required']?.accepts[0]; + if (offer === undefined) throw new Error('no offer'); + const signed = await createPaymentProof({ + buyerPrivateKey: BUYER_KEY, + accepts: offer, + overrides: { nonce: NONCE, validBefore: VALID_BEFORE }, + }); + const paid = await a2aCall( + running.url, + a2aSend({ + message: { + role: 'ROLE_USER', + messageId: 'msg-pay', + taskId: task.id, + contextId: task.contextId, + parts: [{ text: 'Here is the payment authorization.' }], + metadata: { + 'x402.payment.status': 'payment-submitted', + 'x402.payment.payload': JSON.parse(Buffer.from(signed, 'base64').toString('utf8')), + }, + }, + }), + EXTENSION, + ); + expect(paid.raw['result']).toMatchObject({ + task: { status: { state: 'TASK_STATE_COMPLETED' } }, + }); + await expect(a2aGolden(paid.answer)).toMatchFileSnapshot( + `${A2A_GOLDEN}/a2a-x402-completed.json`, + ); + }); + + it('each refusal of the A2A conformance suite, and an unknown resource', async () => { + const rpc = (method: string, params: unknown) => ({ jsonrpc: '2.0', id: 1, method, params }); + const cases: Record = { + 'malformed JSON': '{"jsonrpc": "2.0", "id"', + 'jsonrpc 1.0': { jsonrpc: '1.0', id: 1, method: 'SendMessage' }, + 'no method': { jsonrpc: '2.0', id: 1 }, + 'non-object request': '"SendMessage"', + 'params not an object': rpc('SendMessage', 'nope'), + 'no id': { jsonrpc: '2.0', method: 'SendMessage', params: a2aMessage([FREE_PART]) }, + 'legacy message/send': rpc('message/send', a2aMessage([FREE_PART])), + 'unknown method': rpc('Frobnicate', {}), + ListTasks: rpc('ListTasks', {}), + SendStreamingMessage: rpc('SendStreamingMessage', {}), + SubscribeToTask: rpc('SubscribeToTask', {}), + GetExtendedAgentCard: rpc('GetExtendedAgentCard', {}), + GetTask: rpc('GetTask', { id: 'task-1' }), + CancelTask: rpc('CancelTask', { id: 'task-1' }), + CreateTaskPushNotificationConfig: rpc('CreateTaskPushNotificationConfig', {}), + GetTaskPushNotificationConfig: rpc('GetTaskPushNotificationConfig', {}), + ListTaskPushNotificationConfigs: rpc('ListTaskPushNotificationConfigs', {}), + DeleteTaskPushNotificationConfig: rpc('DeleteTaskPushNotificationConfig', {}), + ROLE_AGENT: a2aSend(a2aMessage([FREE_PART], { role: 'ROLE_AGENT' })), + 'text part': a2aSend(a2aMessage([{ text: 'what is the weather' }])), + 'raw part': a2aSend(a2aMessage([{ raw: 'QUFBQQ==', filename: 'a.bin' }])), + 'url part': a2aSend(a2aMessage([{ url: 'https://example.com/a.pdf' }])), + 'v0.3 file part': a2aSend(a2aMessage([{ file: { uri: 'https://example.com/a.pdf' } }])), + 'two parts': a2aSend(a2aMessage([FREE_PART, FREE_PART])), + 'non-JSON data part': a2aSend(a2aMessage([{ ...FREE_PART, mediaType: 'text/csv' }])), + 'no messageId': a2aSend(a2aMessage([FREE_PART], { messageId: undefined })), + 'unknown taskId': a2aSend(a2aMessage([FREE_PART], { taskId: 'task-1' })), + 'contextId without a task': a2aSend(a2aMessage([FREE_PART], { contextId: 'ctx-1' })), + referenceTaskIds: a2aSend(a2aMessage([FREE_PART], { referenceTaskIds: ['task-1'] })), + 'unknown resource': a2aSend( + a2aMessage([{ data: { resource: 'no_such_resource', input: {} } }]), + ), + }; + const answers: Record = {}; + for (const [name, body] of Object.entries(cases)) { + answers[name] = (await a2aCall(running.url, body)).answer; + } + for (const version of ['0.3', '']) { + const { answer } = await a2aCall(running.url, a2aSend(a2aMessage([FREE_PART])), { + 'a2a-version': version, + }); + answers[`A2A-Version "${version}"`] = answer; + } + await expect(a2aGolden(answers)).toMatchFileSnapshot(`${A2A_GOLDEN}/a2a-refusals.json`); + }); +}); diff --git a/tests/integration/goldens/2.8.0/a2a-agent-card.json b/tests/integration/goldens/2.8.0/a2a-agent-card.json new file mode 100644 index 0000000..0a0ab68 --- /dev/null +++ b/tests/integration/goldens/2.8.0/a2a-agent-card.json @@ -0,0 +1,71 @@ +{ + "name": "Golden Store", + "description": "Agent Commerce Gateway: canonical commerce resources exposed as A2A skills. Call a skill by sending one data part {\"resource\": \"\", \"input\": {...}} with media type application/json. Each skill has an example; input schemas are at https://gateway.example/api/resources. For paid skills, retry with a payment proof in \"input._payment\".", + "version": "", + "supportedInterfaces": [ + { + "url": "https://gateway.example/a2a", + "protocolBinding": "JSONRPC", + "protocolVersion": "1.0" + } + ], + "capabilities": { + "streaming": false, + "pushNotifications": false, + "extendedAgentCard": false, + "extensions": [ + { + "uri": "https://github.com/google-a2a/a2a-x402/v0.1", + "description": "x402 payments: input-required tasks carrying x402 v2 documents.", + "required": false, + "params": { + "x402Version": 2 + } + } + ] + }, + "defaultInputModes": [ + "application/json" + ], + "defaultOutputModes": [ + "application/json" + ], + "skills": [ + { + "id": "market_report", + "name": "Market Report", + "description": "Latest market analysis for a symbol. Costs 0.01 USDC per call.", + "tags": [ + "agent-commerce", + "paid" + ], + "examples": [ + "{\"resource\":\"market_report\",\"input\":{\"symbol\":\"\"}}" + ], + "inputModes": [ + "application/json" + ], + "outputModes": [ + "application/json" + ] + }, + { + "id": "weather_free", + "name": "Free Weather", + "description": "Free Weather", + "tags": [ + "agent-commerce", + "free" + ], + "examples": [ + "{\"resource\":\"weather_free\",\"input\":{\"city\":\"\"}}" + ], + "inputModes": [ + "application/json" + ], + "outputModes": [ + "application/json" + ] + } + ] +} diff --git a/tests/integration/goldens/2.8.0/a2a-free.json b/tests/integration/goldens/2.8.0/a2a-free.json new file mode 100644 index 0000000..ca9a85d --- /dev/null +++ b/tests/integration/goldens/2.8.0/a2a-free.json @@ -0,0 +1,40 @@ +{ + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "result": { + "task": { + "id": "a2a_", + "contextId": "a2a-ctx_", + "status": { + "state": "TASK_STATE_COMPLETED", + "timestamp": "" + }, + "artifacts": [ + { + "artifactId": "a2a-artifact_", + "name": "weather_free", + "parts": [ + { + "data": { + "ok": true + }, + "mediaType": "application/json" + } + ], + "metadata": { + "agent-commerce/delivery": { + "requestId": "a2a_", + "resourceId": "weather_free", + "receiptId": "receipt_", + "deliveredAt": "" + } + } + } + ] + } + } + } +} diff --git a/tests/integration/goldens/2.8.0/a2a-paid-no-proof.json b/tests/integration/goldens/2.8.0/a2a-paid-no-proof.json new file mode 100644 index 0000000..0729a78 --- /dev/null +++ b/tests/integration/goldens/2.8.0/a2a-paid-no-proof.json @@ -0,0 +1,95 @@ +{ + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "result": { + "task": { + "id": "a2a_", + "contextId": "a2a-ctx_", + "status": { + "state": "TASK_STATE_FAILED", + "timestamp": "", + "message": { + "role": "ROLE_AGENT", + "messageId": "a2a-msg_", + "contextId": "a2a-ctx_", + "taskId": "a2a_", + "parts": [ + { + "text": "Payment of 0.01 USDC is required for resource \"market_report\". Retry with a x402 payment proof." + } + ] + } + }, + "artifacts": [ + { + "artifactId": "a2a-artifact_", + "name": "market_report", + "parts": [ + { + "data": { + "status": "payment-required", + "code": "PAYMENT_REQUIRED", + "requestId": "a2a_", + "resourceId": "market_report", + "message": "Payment of 0.01 USDC is required for resource \"market_report\". Retry with a x402 payment proof.", + "payment": { + "provider": "x402", + "version": "2", + "amount": "0.01", + "currency": "USDC", + "destination": "0x1111111111111111111111111111111111111111", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "expiresAt": "", + "accepts": [ + { + "scheme": "exact", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "amount": "10000", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + } + ], + "envelope": { + "x402Version": 2, + "resource": { + "url": "resource://agent-commerce/eip155%3A84532/0x1111111111111111111111111111111111111111/resources/market_report", + "description": "Latest market analysis for a symbol.", + "mimeType": "application/json" + }, + "accepts": [ + { + "scheme": "exact", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "amount": "10000", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + } + ] + } + } + }, + "mediaType": "application/json" + } + ] + } + ] + } + } + } +} diff --git a/tests/integration/goldens/2.8.0/a2a-refusals.json b/tests/integration/goldens/2.8.0/a2a-refusals.json new file mode 100644 index 0000000..a058bcb --- /dev/null +++ b/tests/integration/goldens/2.8.0/a2a-refusals.json @@ -0,0 +1,566 @@ +{ + "malformed JSON": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": null, + "error": { + "code": -32700, + "message": "Invalid JSON." + } + } + }, + "jsonrpc 1.0": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32600, + "message": "Request must set \"jsonrpc\" to \"2.0\"." + } + } + }, + "no method": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32600, + "message": "Request must carry a \"method\" string." + } + } + }, + "non-object request": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": null, + "error": { + "code": -32600, + "message": "Request must be a JSON-RPC 2.0 object." + } + } + }, + "params not an object": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32602, + "message": "Request \"params\" must be an object." + } + } + }, + "no id": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": null, + "error": { + "code": -32600, + "message": "Request must include an \"id\"; notifications are unsupported." + } + } + }, + "legacy message/send": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32601, + "message": "Unknown method \"message/send\"." + } + } + }, + "unknown method": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32601, + "message": "Unknown method \"Frobnicate\"." + } + } + }, + "ListTasks": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32004, + "message": "A2A method \"ListTasks\" is not supported by this deployment.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "UNSUPPORTED_OPERATION", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "SendStreamingMessage": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32004, + "message": "A2A method \"SendStreamingMessage\" is not supported by this deployment.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "UNSUPPORTED_OPERATION", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "SubscribeToTask": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32004, + "message": "A2A method \"SubscribeToTask\" is not supported by this deployment.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "UNSUPPORTED_OPERATION", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "GetExtendedAgentCard": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32004, + "message": "A2A method \"GetExtendedAgentCard\" is not supported by this deployment.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "UNSUPPORTED_OPERATION", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "GetTask": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32001, + "message": "Task not found. Finished tasks are not retained; continue a pending payment with SendMessage.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "TASK_NOT_FOUND", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "CancelTask": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32001, + "message": "Task not found. Finished tasks are not retained; continue a pending payment with SendMessage.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "TASK_NOT_FOUND", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "CreateTaskPushNotificationConfig": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32003, + "message": "A2A method \"CreateTaskPushNotificationConfig\" is not supported: this agent does not support push notifications.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "PUSH_NOTIFICATION_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "GetTaskPushNotificationConfig": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32003, + "message": "A2A method \"GetTaskPushNotificationConfig\" is not supported: this agent does not support push notifications.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "PUSH_NOTIFICATION_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "ListTaskPushNotificationConfigs": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32003, + "message": "A2A method \"ListTaskPushNotificationConfigs\" is not supported: this agent does not support push notifications.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "PUSH_NOTIFICATION_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "DeleteTaskPushNotificationConfig": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32003, + "message": "A2A method \"DeleteTaskPushNotificationConfig\" is not supported: this agent does not support push notifications.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "PUSH_NOTIFICATION_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "ROLE_AGENT": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32602, + "message": "Unsupported message role \"ROLE_AGENT\": only ROLE_USER is accepted." + } + } + }, + "text part": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32005, + "message": "Text parts are not supported: send one data part {\"resource\": \"\", \"input\": {...}}.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "CONTENT_TYPE_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "raw part": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32005, + "message": "File and URL parts are not supported: send one data part {\"resource\": \"\", \"input\": {...}}.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "CONTENT_TYPE_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "url part": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32005, + "message": "File and URL parts are not supported: send one data part {\"resource\": \"\", \"input\": {...}}.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "CONTENT_TYPE_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "v0.3 file part": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32005, + "message": "File and URL parts are not supported: send one data part {\"resource\": \"\", \"input\": {...}}.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "CONTENT_TYPE_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "two parts": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32004, + "message": "Multi-part messages are not supported: send exactly one structured data part (received 2).", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "UNSUPPORTED_OPERATION", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "non-JSON data part": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32005, + "message": "Media type \"text/csv\" is not supported: parts must be application/json.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "CONTENT_TYPE_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "no messageId": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32602, + "message": "Message must carry a non-empty \"messageId\"." + } + } + }, + "unknown taskId": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32001, + "message": "Task not found: only a task waiting for payment can be continued, so send a request with no taskId.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "TASK_NOT_FOUND", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "contextId without a task": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32004, + "message": "Multi-turn conversational continuation is not supported: send a request with no contextId.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "UNSUPPORTED_OPERATION", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "referenceTaskIds": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32004, + "message": "Referencing previous tasks is not supported.", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "UNSUPPORTED_OPERATION", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "unknown resource": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "result": { + "task": { + "id": "a2a_", + "contextId": "a2a-ctx_", + "status": { + "state": "TASK_STATE_FAILED", + "timestamp": "", + "message": { + "role": "ROLE_AGENT", + "messageId": "a2a-msg_", + "contextId": "a2a-ctx_", + "taskId": "a2a_", + "parts": [ + { + "text": "Unknown canonical resource \"no_such_resource\"." + } + ] + } + }, + "artifacts": [ + { + "artifactId": "a2a-artifact_", + "parts": [ + { + "data": { + "status": "error", + "code": "RESOURCE_NOT_FOUND", + "message": "Unknown canonical resource \"no_such_resource\".", + "retryable": false + }, + "mediaType": "application/json" + } + ] + } + ] + } + } + } + }, + "A2A-Version \"0.3\"": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32009, + "message": "Unsupported A2A protocol version. Send the A2A-Version header with \"1.0\".", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "VERSION_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + }, + "A2A-Version \"\"": { + "status": 200, + "extensions": null, + "body": { + "jsonrpc": "2.0", + "id": "golden", + "error": { + "code": -32009, + "message": "Unsupported A2A protocol version. Send the A2A-Version header with \"1.0\".", + "data": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "VERSION_NOT_SUPPORTED", + "domain": "a2a-protocol.org" + } + ] + } + } + } +} diff --git a/tests/integration/goldens/2.8.0/a2a-x402-completed.json b/tests/integration/goldens/2.8.0/a2a-x402-completed.json new file mode 100644 index 0000000..feb88c6 --- /dev/null +++ b/tests/integration/goldens/2.8.0/a2a-x402-completed.json @@ -0,0 +1,77 @@ +{ + "status": 200, + "extensions": "https://github.com/google-a2a/a2a-x402/v0.1", + "body": { + "jsonrpc": "2.0", + "id": "golden", + "result": { + "task": { + "id": "a2a_", + "contextId": "a2a-ctx_", + "status": { + "state": "TASK_STATE_COMPLETED", + "timestamp": "", + "message": { + "role": "ROLE_AGENT", + "messageId": "a2a-msg_", + "contextId": "a2a-ctx_", + "taskId": "a2a_", + "parts": [ + { + "text": "Payment settled." + } + ], + "metadata": { + "x402.payment.status": "payment-completed", + "x402.payment.receipts": [ + { + "success": true, + "transaction": "0xabababababababababababababababababababababababababababababababab", + "network": "eip155:84532", + "payer": "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC", + "amount": "10000", + "status": "settled", + "provider": "x402", + "currency": "USDC", + "externalReference": "0xabababababababababababababababababababababababababababababababab" + } + ] + }, + "extensions": [ + "https://github.com/google-a2a/a2a-x402/v0.1" + ] + } + }, + "artifacts": [ + { + "artifactId": "a2a-artifact_", + "name": "market_report", + "parts": [ + { + "data": { + "ok": true + }, + "mediaType": "application/json" + } + ], + "metadata": { + "agent-commerce/delivery": { + "requestId": "a2a_", + "resourceId": "market_report", + "receiptId": "receipt_", + "deliveredAt": "", + "payment": { + "status": "settled", + "amount": "0.01", + "currency": "USDC", + "externalReference": "0xabababababababababababababababababababababababababababababababab", + "network": "eip155:84532" + } + } + } + } + ] + } + } + } +} diff --git a/tests/integration/goldens/2.8.0/a2a-x402-input-required.json b/tests/integration/goldens/2.8.0/a2a-x402-input-required.json new file mode 100644 index 0000000..b8fe1ab --- /dev/null +++ b/tests/integration/goldens/2.8.0/a2a-x402-input-required.json @@ -0,0 +1,124 @@ +{ + "status": 200, + "extensions": "https://github.com/google-a2a/a2a-x402/v0.1", + "body": { + "jsonrpc": "2.0", + "id": "golden", + "result": { + "task": { + "id": "a2a_", + "contextId": "a2a-ctx_", + "status": { + "state": "TASK_STATE_INPUT_REQUIRED", + "timestamp": "", + "message": { + "role": "ROLE_AGENT", + "messageId": "a2a-msg_", + "contextId": "a2a-ctx_", + "taskId": "a2a_", + "parts": [ + { + "text": "Payment is required. Send the x402 payment payload on this task." + } + ], + "metadata": { + "x402.payment.status": "payment-required", + "x402.payment.required": { + "x402Version": 2, + "resource": { + "url": "resource://agent-commerce/eip155%3A84532/0x1111111111111111111111111111111111111111/resources/market_report", + "description": "Latest market analysis for a symbol.", + "mimeType": "application/json" + }, + "accepts": [ + { + "scheme": "exact", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "amount": "10000", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + } + ] + } + }, + "extensions": [ + "https://github.com/google-a2a/a2a-x402/v0.1" + ] + } + }, + "artifacts": [ + { + "artifactId": "a2a-artifact_", + "name": "market_report", + "parts": [ + { + "data": { + "status": "payment-required", + "code": "PAYMENT_REQUIRED", + "requestId": "a2a_", + "resourceId": "market_report", + "message": "Payment of 0.01 USDC is required for resource \"market_report\". Retry with a x402 payment proof.", + "payment": { + "provider": "x402", + "version": "2", + "amount": "0.01", + "currency": "USDC", + "destination": "0x1111111111111111111111111111111111111111", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "expiresAt": "", + "accepts": [ + { + "scheme": "exact", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "amount": "10000", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + } + ], + "envelope": { + "x402Version": 2, + "resource": { + "url": "resource://agent-commerce/eip155%3A84532/0x1111111111111111111111111111111111111111/resources/market_report", + "description": "Latest market analysis for a symbol.", + "mimeType": "application/json" + }, + "accepts": [ + { + "scheme": "exact", + "network": "eip155:84532", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "amount": "10000", + "payTo": "0x1111111111111111111111111111111111111111", + "maxTimeoutSeconds": 120, + "extra": { + "name": "USDC", + "version": "2", + "assetTransferMethod": "eip3009" + } + } + ] + } + } + }, + "mediaType": "application/json" + } + ] + } + ] + } + } + } +} From bf6bf27210ba73d92330d82fe03049f92e946412 Mon Sep 17 00:00:00 2001 From: Revinand Date: Sun, 22 Nov 2026 17:26:03 +0100 Subject: [PATCH 02/17] feat(core): add task records to the store contract --- docs/contract-surface.txt | 15 ++++++++- docs/contracts.md | 18 +++++++++++ src/core/domain/store-records.ts | 24 ++++++++++++++ src/core/interfaces/store.ts | 22 +++++++++++++ src/core/public-types.ts | 1 + src/core/store-method-groups.ts | 1 + src/storage/receipts/store.ts | 5 +-- tests/integration/transaction-journal.test.ts | 5 ++- tests/unit/core/store-method-groups.test.ts | 32 +++++++++++++++++++ .../storage-receipts/transactions.test.ts | 4 +-- 10 files changed, 119 insertions(+), 8 deletions(-) create mode 100644 tests/unit/core/store-method-groups.test.ts diff --git a/docs/contract-surface.txt b/docs/contract-surface.txt index dbc4685..a2e2fbc 100644 --- a/docs/contract-surface.txt +++ b/docs/contract-surface.txt @@ -1,6 +1,6 @@ # Semantic surface of src/core/public-types.ts # Generated by scripts/contract-surface.mjs - do not edit by hand. -# 113 exported symbols. +# 114 exported symbols. interface AdapterDescriptor { readonly capabilities: ReadonlyArray; @@ -522,6 +522,7 @@ interface ReceiptStore { getPaymentAttempt?: (id: string) => Promise; getPendingTask?: (id: string) => Promise; getReceipt: (id: string) => Promise; + getTaskRecord?: (id: string) => Promise; getTransaction?: (id: string) => Promise; health: () => Promise; init: () => Promise; @@ -529,8 +530,10 @@ interface ReceiptStore { listOrphanAuthorizationHolds?: (options: { readonly updatedBefore: IsoTimestamp; readonly limit?: number; }) => Promise; listPaymentAttempts: (options?: PaymentAttemptListOptions) => Promise; listReceipts: (options?: ReceiptListOptions) => Promise; + listTaskRecords?: (filter: { readonly protocol: ProtocolName; readonly groupId: string; }) => Promise; listTransactions?: (options?: TransactionListOptions) => Promise; putPendingTask?: (task: PendingTask, options: { readonly maxTasks: number; }) => Promise; + putTaskRecord?: (record: TaskRecord, options: { readonly maxRecords: number; }) => Promise; readonly descriptor: AdapterDescriptor; recordTransactionStep?: (step: TransactionStep) => Promise; recoverIdempotencyKeys?: (options: { readonly release: boolean; readonly endpointPrefix?: string; }) => Promise; @@ -551,6 +554,16 @@ interface ResourceRegistry { listExposedVia: (protocol: ProtocolName) => readonly CommerceResource[]; } +interface TaskRecord { + readonly document: Readonly>; + readonly expiresAt: string; + readonly groupId: string; + readonly id: string; + readonly protocol: ProtocolName; + readonly state: string; + readonly updatedAt: string; + } + interface Transaction { readonly authorization?: AuthorizationRecord & { readonly reservationId: string; readonly hold: AuthorizationHoldState; }; readonly backend?: { readonly dispatchedAt: IsoTimestamp; readonly deadlineAt: IsoTimestamp; readonly status?: number; readonly errorCode?: string; }; diff --git a/docs/contracts.md b/docs/contracts.md index bc000ee..47a3ec8 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -307,6 +307,24 @@ persistence must not fail the commerce flow. - `AdapterHealthComponent.undetermined` uses `'unreachable'` for a probe that received no response. When set, `status` does not describe the target's health. Without the field, `status` retains its 2.7 meaning. +- 2.9.0 adds the optional `ReceiptStore` method group `task_records` to + `STORE_METHOD_GROUPS`. Existing 2.8 stores need no changes. A store must + implement the whole group or omit it. SQLite omits this group. + - `putTaskRecord`, `getTaskRecord` and `listTaskRecords` store and read + `TaskRecord` values. A record holds the task response last returned by its + adapter for later reads. It does not make the task payable; payment + continuation uses separate pending-task state. + - `putTaskRecord` deletes expired records before storing a record. It + replaces a record with the same ID even at capacity. For a new ID, it + returns `false` without storing when `maxRecords` unexpired records exist. + - `listTaskRecords` returns all unexpired records matching `protocol` and + `groupId`, without pagination. Records are ordered by `updatedAt` and then + `id`, both descending. + - `groupId` is a protocol-neutral grouping key. `document` holds the task as + the adapter returns it and must not contain payment proofs or + authorization presentations. + - These methods and the type are experimental and may change in a minor + release. ### Protocols and gateway diff --git a/src/core/domain/store-records.ts b/src/core/domain/store-records.ts index 22dbca3..e61f4f8 100644 --- a/src/core/domain/store-records.ts +++ b/src/core/domain/store-records.ts @@ -94,3 +94,27 @@ export interface PendingTask { /** Set and bounded by the caller */ readonly expiresAt: IsoTimestamp; } + +/** + * A task response last returned by its protocol adapter, saved for later reads. + * This record does not make the task payable. Experimental: may change in a + * minor release. + */ +export interface TaskRecord { + /** Unique across the store */ + readonly id: string; + readonly protocol: ProtocolName; + /** Groups related tasks for listing */ + readonly groupId: string; + /** State name defined by the adapter */ + readonly state: string; + /** Time of the last state change; used to sort listed records */ + readonly updatedAt: IsoTimestamp; + /** + * JSON-serializable task response. Must not contain payment proofs or + * authorization presentations. + */ + readonly document: Readonly>; + /** Set and bounded by the caller */ + readonly expiresAt: IsoTimestamp; +} diff --git a/src/core/interfaces/store.ts b/src/core/interfaces/store.ts index aa43535..a322ee4 100644 --- a/src/core/interfaces/store.ts +++ b/src/core/interfaces/store.ts @@ -20,6 +20,7 @@ import type { IdempotencyScope, IdempotencyUpdate, PendingTask, + TaskRecord, } from '../domain/store-records'; import type { AuthorizationHoldState, @@ -317,6 +318,27 @@ export interface ReceiptStore { */ takePendingTask?(id: string): Promise; + /** + * Store task responses for later reads by protocol adapters. Implement all + * three methods or none. Experimental: may change in a minor release. + * + * Delete expired records, then store `record`. Replace a record with the same + * ID even at capacity. For a new ID, return false without storing when + * `maxRecords` unexpired records exist. + */ + putTaskRecord?(record: TaskRecord, options: { readonly maxRecords: number }): Promise; + /** Return undefined for a missing or expired record. Experimental: may change in a minor release */ + getTaskRecord?(id: string): Promise; + /** + * Return all unexpired records matching `protocol` and `groupId`, ordered by + * `updatedAt` and then `id`, both descending. Experimental: may change in a + * minor release. + */ + listTaskRecords?(filter: { + readonly protocol: ProtocolName; + readonly groupId: string; + }): Promise; + readonly descriptor: AdapterDescriptor; health(): Promise; close(): Promise; diff --git a/src/core/public-types.ts b/src/core/public-types.ts index 78f7887..cdbf789 100644 --- a/src/core/public-types.ts +++ b/src/core/public-types.ts @@ -76,6 +76,7 @@ export type { IdempotencyScope, IdempotencyUpdate, PendingTask, + TaskRecord, } from './domain/store-records'; export type { AuthorizationHoldState, diff --git a/src/core/store-method-groups.ts b/src/core/store-method-groups.ts index effa1b8..d7513b9 100644 --- a/src/core/store-method-groups.ts +++ b/src/core/store-method-groups.ts @@ -12,6 +12,7 @@ export const STORE_METHOD_GROUPS = { 'listOrphanAuthorizationHolds', ], pending_tasks: ['putPendingTask', 'getPendingTask', 'takePendingTask'], + task_records: ['putTaskRecord', 'getTaskRecord', 'listTaskRecords'], // Separate from `idempotency_claims`: a store can support claims without redelivery response_redelivery: ['getIdempotencyKey'], } as const satisfies Record; diff --git a/src/storage/receipts/store.ts b/src/storage/receipts/store.ts index 4830316..1e485d9 100644 --- a/src/storage/receipts/store.ts +++ b/src/storage/receipts/store.ts @@ -138,8 +138,9 @@ export interface SqliteReceiptStoreSummary { readonly missingLegacyImports: readonly LegacySource[]; } -/** Implements every optional `ReceiptStore` method */ -export interface SqliteReceiptStore extends Required { +/** Implements every optional `ReceiptStore` method except the `task_records` group */ +export interface SqliteReceiptStore + extends Required> { /** Experimental: may change in a minor release */ summary(options: { readonly orphanHoldMinAgeMs: number }): Promise; } diff --git a/tests/integration/transaction-journal.test.ts b/tests/integration/transaction-journal.test.ts index b77f2c2..e1c7e27 100644 --- a/tests/integration/transaction-journal.test.ts +++ b/tests/integration/transaction-journal.test.ts @@ -15,12 +15,11 @@ import { type IdGenerator, isCommerceError, type PaymentProvider, - type ReceiptStore, toDeliverySummary, } from '../../src/core'; import { createExecutionPipeline } from '../../src/core/execution/pipeline'; import { createResourceRegistry } from '../../src/core/execution/registry'; -import { createSqliteReceiptStore } from '../../src/storage/receipts'; +import { createSqliteReceiptStore, type SqliteReceiptStore } from '../../src/storage/receipts'; import { createCapturingLogger, createFakeAuthorizationProvider, @@ -37,7 +36,7 @@ const T0 = '2026-01-01T00:00:00.000Z'; const DEADLINE = '2026-01-01T00:00:15.000Z'; const EXPIRES = '2026-01-01T00:05:00.000Z'; -type JournalStore = Required; +type JournalStore = SqliteReceiptStore; const PAID: CommerceResource = makeResource({ id: 'market_report', diff --git a/tests/unit/core/store-method-groups.test.ts b/tests/unit/core/store-method-groups.test.ts new file mode 100644 index 0000000..ff4e623 --- /dev/null +++ b/tests/unit/core/store-method-groups.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest'; +import type { ReceiptStore } from '../../../src/core'; +import { hasMethodGroup, STORE_METHOD_GROUPS } from '../../../src/core/store-method-groups'; +import { receiptStoreConformanceCases } from '../../../src/testing/store-conformance'; + +const noop = async () => undefined; +const TASK_RECORDS = { putTaskRecord: noop, getTaskRecord: noop, listTaskRecords: noop }; + +describe('the task_records method group', () => { + it('is present only when every method of the group is', () => { + expect(hasMethodGroup(TASK_RECORDS as unknown as ReceiptStore, 'task_records')).toBe(true); + for (const method of STORE_METHOD_GROUPS.task_records) { + const partial = { ...TASK_RECORDS, [method]: undefined } as unknown as ReceiptStore; + expect(hasMethodGroup(partial, 'task_records')).toBe(false); + } + expect(hasMethodGroup(undefined, 'task_records')).toBe(false); + }); + + it('fails the conformance group case for a store implementing part of it', async () => { + const store = { + init: noop, + close: noop, + putTaskRecord: noop, + getTaskRecord: noop, + } as unknown as ReceiptStore; + const cases = await receiptStoreConformanceCases(() => ({ store })); + const group = cases.find((c) => c.name.includes('method group completely or not at all')); + await expect(group?.run()).rejects.toThrow( + 'task_records: implements putTaskRecord, getTaskRecord but not the rest of the group', + ); + }); +}); diff --git a/tests/unit/storage-receipts/transactions.test.ts b/tests/unit/storage-receipts/transactions.test.ts index 590c8ee..4cceb33 100644 --- a/tests/unit/storage-receipts/transactions.test.ts +++ b/tests/unit/storage-receipts/transactions.test.ts @@ -8,12 +8,12 @@ import type { Clock, PaymentAttemptReservation, PaymentAttemptResolution, - ReceiptStore, Transaction, TransactionPage, } from '../../../src/core'; import { createSqliteReceiptStore, + type SqliteReceiptStore, type SqliteReceiptStoreOptions, } from '../../../src/storage/receipts'; import { createFakeIds, makeEvent, makeReceipt } from './helpers'; @@ -67,7 +67,7 @@ const RESOLUTION: PaymentAttemptResolution = { }; // SQLite implements the optional journal methods, so tests can call them directly -type JournalStore = Required; +type JournalStore = SqliteReceiptStore; const openStore = (options: SqliteReceiptStoreOptions) => createSqliteReceiptStore(options) as JournalStore; From 97cd175c88998a44eb1b680646698244fb61df41 Mon Sep 17 00:00:00 2001 From: Revinand Date: Sun, 22 Nov 2026 18:06:12 +0100 Subject: [PATCH 03/17] feat(storage): keep task records in schema v6 --- README.md | 6 +- docs/contracts.md | 9 +- docs/security.md | 4 +- docs/storage.md | 22 ++- src/cli/commands/doctor/storage.ts | 8 +- src/cli/commands/reconcile.ts | 4 +- src/storage/receipts/index.ts | 2 +- src/storage/receipts/legacy-import.ts | 28 ++- src/storage/receipts/schema.ts | 20 ++ src/storage/receipts/store.ts | 31 ++- src/storage/receipts/task-records.ts | 101 ++++++++++ src/testing/conformance/record-cases.ts | 147 +++++++++++++- tests/e2e/payment/upgrade.e2e.test.ts | 15 +- .../goldens/2.7.2/doctor-multi.json | 2 +- .../goldens/2.7.2/doctor-single.json | 2 +- .../goldens/2.7.2/well-known-multi.json | 5 +- .../goldens/2.7.2/well-known-single.json | 5 +- tests/unit/cli/backup.test.ts | 45 +++-- tests/unit/cli/doctor-storage.test.ts | 53 +++-- .../storage-receipts/fixtures/receipts-v5.sql | 187 ++++++++++++++++++ .../storage-receipts/migration-v5.test.ts | 34 ++-- .../storage-receipts/migration-v6.test.ts | 109 ++++++++++ .../storage-receipts/payment-attempts.test.ts | 2 +- .../storage-receipts/record-inputs.test.ts | 52 +++++ 24 files changed, 797 insertions(+), 96 deletions(-) create mode 100644 src/storage/receipts/task-records.ts create mode 100644 tests/unit/storage-receipts/fixtures/receipts-v5.sql create mode 100644 tests/unit/storage-receipts/migration-v6.test.ts diff --git a/README.md b/README.md index 3ddf7f8..7dd46eb 100644 --- a/README.md +++ b/README.md @@ -525,7 +525,7 @@ INFO AP2 disabled PASS Payments x402 v2 (scheme=exact) enabled - LOCAL dev chain (eip155:31337), destination=0x7099…79C8, facilitator=local (in-process), paymentFlow=authorization PASS Payments (offers) 1 offer(s) pass their health checks INFO Payments (MPP) MPP not configured -PASS Storage sqlite schema v5 writable; receipts=2 +PASS Storage sqlite schema v6 writable; receipts=2 PASS Transactions none unresolved PASS Protocol versions reported by gateway /.well-known/agent-commerce @@ -595,8 +595,8 @@ follows. It exits 0 after a completed run, even if attempts remain unresolved, and 1 if the run fails to complete. If a store error stops a hold scan, the command prints the report, preserving any saved resolutions, and exits 1. -`reconcile` and `resolve` refuse receipt databases below schema v5 without -migrating them. Back up the database, then start the gateway once before +`reconcile` and `resolve` reject receipt databases with an older schema +without migrating them. Back up the database, then start the gateway once before retrying either command. Each family needs its own evidence: diff --git a/docs/contracts.md b/docs/contracts.md index 47a3ec8..92bf22b 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -309,7 +309,8 @@ persistence must not fail the commerce flow. target's health. Without the field, `status` retains its 2.7 meaning. - 2.9.0 adds the optional `ReceiptStore` method group `task_records` to `STORE_METHOD_GROUPS`. Existing 2.8 stores need no changes. A store must - implement the whole group or omit it. SQLite omits this group. + implement the whole group or omit it. The SQLite store implements it in + schema v6. - `putTaskRecord`, `getTaskRecord` and `listTaskRecords` store and read `TaskRecord` values. A record holds the task response last returned by its adapter for later reads. It does not make the task payable; payment @@ -637,9 +638,9 @@ export function createSqliteReceiptStore( ): SqliteReceiptStore; ``` -Creating the store upgrades older files to schema v5. `init()` rejects any -version other than v5, just as a 2.5.x store rejects a v5 file because it -requires v4. To downgrade below 2.6.0, restore a copy made before the upgrade. +Creating the store migrates older files to schema v6. `init()` requires v6. +A 2.8.x store requires v5 and rejects v6 files. To downgrade below 2.9.0, +restore a copy made before migration. The store removes the top-level `_payment` and `_authorization` fields from pending task input before writing it. Hold `metadata` values under diff --git a/docs/security.md b/docs/security.md index 28e0e71..7f5d672 100644 --- a/docs/security.md +++ b/docs/security.md @@ -446,7 +446,7 @@ real funds. | **an in-flight `reserved` attempt younger than `--min-age`** | excluded from reconciliation candidates; the default minimum age is 15 minutes. Manual resolution also refuses a `reserved` attempt younger than 15 minutes (`too_recent`) | `tests/unit/core/execution/reconcile.test.ts`, `tests/unit/core/execution/resolve.test.ts` | | **a `reserved` AP2 hold whose request recorded no payment attempt** | eligible for release through an enabled AP2 provider once its last update is older than `--min-age`; the gateway reserves an attempt before calling settlement. Current or replaced attempts exclude a hold. Dry runs report scanned holds without releasing them. An omitted or empty list of authorization providers skips both hold scans | `tests/unit/core/execution/reconcile.test.ts` | | **`reconcile` or `resolve` with AP2 enabled and an existing, unimported AP2 file** | `STORAGE_ERROR` before payment or hold updates; these commands do not import legacy files. The receipt store is initialized after a read-only schema check | `tests/unit/cli/resolve.test.ts` | -| **`reconcile` or `resolve` on a receipt database below schema v5, such as one a 2.5 gateway still uses** | `STORAGE_ERROR` before payment, hold or schema updates; the message directs the operator to run `agent-commerce backup`, then start 2.6.0 once | `tests/unit/cli/reconcile.test.ts` | +| **`reconcile` or `resolve` on a receipt database with an older schema, including files from 2.5 or 2.8** | `STORAGE_ERROR` before payment, hold or schema updates; the message directs the operator to run `agent-commerce backup`, then start the gateway once | `tests/unit/cli/reconcile.test.ts` | | **`reconcile`, `resolve` or `doctor` run beside a live gateway** | These commands neither import legacy files nor recover ACP claims. `reconcile` and `resolve` open the receipt store without legacy import options; `doctor` opens it read-only. They leave the gateway's existing in-flight ACP claims unchanged | `tests/unit/cli/reconcile.test.ts`, `tests/unit/cli/doctor-storage.test.ts` | | **reconciliation calling a facilitator or broadcasting** | x402 and MPP reconciliation read the configured offer's RPC without calling the facilitator or broadcasting | `tests/e2e/payment/x402-reconcile.e2e.test.ts`, `tests/e2e/payment/x402-solana.e2e.test.ts`, `tests/e2e/payment/x402-near.e2e.test.ts` | | **an attempt without a recorded locator** | x402 and MPP return `unknown` (`no_locator`), leaving the attempt unresolved | `tests/unit/payments-x402/reconcile.test.ts`, `tests/unit/core/execution/reconcile.test.ts` | @@ -529,7 +529,7 @@ real funds. | **a deprecated store key removed, or its file missing, before the first 2.6.0 start** | `start` returns `STORAGE_ERROR` for an enabled feature with past-use evidence and no recorded import or prior check. An empty file or `:memory:` explicitly accepts the loss; `doctor` reports that refusal as `FAIL` | `tests/unit/storage-receipts/legacy-import.test.ts`, `tests/unit/cli/doctor-storage.test.ts` | | **an import failing part way** | the failed source's rows and import marker roll back together; earlier source imports remain committed. `start` stops with `STORAGE_ERROR`, releases acquired locks and retries the failed source on the next start | same | | **a 2.5 gateway writing a deprecated file after the import** | refused while `start` holds the file's write lock, which is released at shutdown | same | -| **a 2.5 gateway opening a receipt database 2.6.0 migrated** | refused by its schema version check; the file is unchanged | `tests/unit/storage-receipts/migration-v5.test.ts` | +| **an older gateway opening a migrated receipt database (2.5 after a 2.6.0 upgrade, or 2.8 after a 2.9.0 upgrade)** | refused by its schema version check; the file is unchanged | `tests/unit/storage-receipts/migration-v5.test.ts` | | **a free resource configured to require a mandate** | refused at config load, and again on the execution path | `tests/unit/config/ap2.test.ts`, `tests/unit/core/execution` | | **an oversized `Agent-Authorization` header** | `AUTHORIZATION_INVALID`; the pipeline is not called | `tests/integration/authorization-carrier.test.ts` | | **an MPP challenge edited after issue, or signed with another gateway's secret** | `challenge_not_issued` | `tests/unit/payments-mpp/provider.test.ts` | diff --git a/docs/storage.md b/docs/storage.md index f4af17f..183694e 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -43,9 +43,9 @@ database, except `:memory:`. The 3.0.0 plan removes both keys. failures still stop startup. - With AP2 enabled, `reconcile` and `resolve` refuse an existing AP2 file with no recorded import. Run `start` first; these commands do not import it. -- `reconcile` and `resolve` refuse receipt databases below schema v5 without - migrating them. This preserves access for a 2.5 gateway still using the - file. Back up the database and run `start` once to migrate it. +- `reconcile` and `resolve` reject receipt databases with an older schema + without migrating them, so an earlier gateway can still use the file. + Back up the database and run `start` once to migrate it. - Remove the key after `doctor` confirms the file was imported and no 2.5 gateway still uses it. Changing a recorded source path is refused. @@ -62,9 +62,9 @@ available and the check passes, `start` records that result so later starts can omit the key. A file supplied later can still be imported. `agent-commerce doctor` opens the receipt file read-only, without migrating -its schema or importing legacy records. If the schema is older than v5, -such as a 2.5 database, it warns that the next start will migrate it. For each -enabled AP2 or ACP feature, it checks legacy settings against recorded +its schema or importing legacy records. For schemas older than v6, including +2.5 and 2.8 databases, it warns that the next `start` will migrate the file. For +each enabled AP2 or ACP feature, it checks legacy settings against recorded imports and past-use evidence. It reports recorded imports and warns when it cannot check whether an existing file was imported. It reports `FAIL` for a changed source path or an unset key or missing file that fails the @@ -84,8 +84,9 @@ does not migrate or import records, or take a write lock on the sources. must exist; the command creates it at 0700. An existing directory keeps its permissions. - It writes `receipts.sqlite`, a consistent snapshot taken with - `VACUUM INTO`. It refuses a receipt database at a schema other than v4 (2.5) - or v5 (2.6). The snapshot includes the database's unencrypted stored responses. + `VACUUM INTO`. Supported receipt schemas are v4 (2.5), v5 (2.6 to 2.8) + and v6 (2.9); other versions are refused. The snapshot includes + unencrypted stored responses. - For enabled AP2 or ACP, it also copies any configured legacy file that exists, is not `:memory:` and has no recorded import. The copies are named `ap2-replay.sqlite` or `acp-idempotency.sqlite`. Before the first 2.6.0 @@ -132,8 +133,9 @@ Restoring a backup discards local records written after its snapshot: A transaction recorded as unresolved in the backup still needs `reconcile` or `resolve` to establish its outcome. -A 2.5 gateway refuses a receipt database migrated by 2.6.0. To roll back to -2.5, restore a backup made before the upgrade. +Gateways reject receipt schemas newer than they support. A 2.5 gateway +rejects a database migrated by 2.6.0; gateways from 2.6 to 2.8 reject one +migrated by 2.9.0. To roll back, restore a backup made before migration. ## Shutdown diff --git a/src/cli/commands/doctor/storage.ts b/src/cli/commands/doctor/storage.ts index 2a4bde3..fb5780a 100644 --- a/src/cli/commands/doctor/storage.ts +++ b/src/cli/commands/doctor/storage.ts @@ -5,7 +5,7 @@ import { isCommerceError } from '../../../core'; import { DEFAULT_RECONCILE_MIN_AGE_MS } from '../../../core/execution/reconcile'; import { type LegacySource, - readMissingLegacyImports, + readLegacyImportState, type SqliteLegacyImport, type SqliteReceiptStoreSummary, } from '../../../storage/receipts'; @@ -220,8 +220,8 @@ export async function storageChecks( } catch (err) { const refused = refusedSchema(err); if (refused !== undefined && refused.schemaVersion < refused.expected) { - // Imports begin at schema v5, so an older schema has none recorded - const missing = readMissingLegacyImports(path); + // Read v5 import records without migrating the database; v4 has no import table + const legacy = readLegacyImportState(path); return { checks: [ { @@ -230,7 +230,7 @@ export async function storageChecks( detail: `sqlite schema v${refused.schemaVersion}; the next start migrates it to v${refused.expected}, which earlier versions cannot open. Run agent-commerce backup first to keep a copy they can`, }, ], - legacy: missing !== undefined ? { imports: [], missing } : undefined, + legacy, }; } checks.push({ diff --git a/src/cli/commands/reconcile.ts b/src/cli/commands/reconcile.ts index 5c1be53..dc7a09d 100644 --- a/src/cli/commands/reconcile.ts +++ b/src/cli/commands/reconcile.ts @@ -134,8 +134,8 @@ export async function withJournal( ]); const path = config.storage.receipts.path; if (path !== ':memory:' && existsSync(path)) { - // Check the schema before opening for writes so these commands cannot - // migrate a database still used by a 2.5 gateway + // Check the schema before opening for writes to preserve access for + // gateways that require the older schema try { await openSqliteReceiptStoreReadOnly(path).close(); } catch (error) { diff --git a/src/storage/receipts/index.ts b/src/storage/receipts/index.ts index f2952fb..037151d 100644 --- a/src/storage/receipts/index.ts +++ b/src/storage/receipts/index.ts @@ -1,7 +1,7 @@ export { type LegacySource, type LegacyStoreOptions, - readMissingLegacyImports, + readLegacyImportState, } from './legacy-import'; export { createSqliteReceiptStore, diff --git a/src/storage/receipts/legacy-import.ts b/src/storage/receipts/legacy-import.ts index 75416a8..61162b3 100644 --- a/src/storage/receipts/legacy-import.ts +++ b/src/storage/receipts/legacy-import.ts @@ -12,6 +12,7 @@ import { resolve } from 'node:path'; import Database from 'better-sqlite3'; import { type Clock, CommerceError, type Logger, toCommerceError } from '../../core'; import { hasTable } from './schema'; +import type { SqliteLegacyImport } from './store'; /** Deprecated store files to import. Experimental: through 2.x only */ export interface LegacyStoreOptions { @@ -173,15 +174,34 @@ export function missingLegacyImports(db: Database.Database): LegacySource[] { ).map((source) => source.name); } +/** Return recorded file imports in source order, or an empty list if their table is absent */ +export function recordedLegacyImports(db: Database.Database): SqliteLegacyImport[] { + if (!hasTable(db, 'legacy_imports')) return []; + return db + .prepare<[], { source: string; path: string; rows: number; imported_at: string }>( + 'SELECT source, path, rows, imported_at FROM legacy_imports WHERE path IS NOT NULL ORDER BY source', + ) + .all() + .map((row) => ({ + source: row.source, + path: row.path, + rows: row.rows, + importedAt: row.imported_at, + })); +} + /** - * Reads {@link missingLegacyImports} from an existing file opened read-only. - * Returns undefined if opening the file or querying its tables fails. + * Read {@link recordedLegacyImports} and {@link missingLegacyImports} from an + * existing file without checking its schema version. Open the file read-only + * and return undefined if opening or querying it fails. */ -export function readMissingLegacyImports(path: string): LegacySource[] | undefined { +export function readLegacyImportState( + path: string, +): { imports: SqliteLegacyImport[]; missing: LegacySource[] } | undefined { let db: Database.Database | undefined; try { db = new Database(path, { readonly: true, fileMustExist: true }); - return missingLegacyImports(db); + return { imports: recordedLegacyImports(db), missing: missingLegacyImports(db) }; } catch { return undefined; } finally { diff --git a/src/storage/receipts/schema.ts b/src/storage/receipts/schema.ts index 59fa904..b5c6b19 100644 --- a/src/storage/receipts/schema.ts +++ b/src/storage/receipts/schema.ts @@ -213,6 +213,26 @@ const MIGRATIONS: readonly Migration[] = [ `); }, }, + { + version: 6, + up(db) { + // Add task records without altering existing tables. A 2.8.x gateway + // rejects v6 at init(), which requires v5. + db.exec(` + CREATE TABLE IF NOT EXISTS task_records ( + id TEXT PRIMARY KEY, + protocol TEXT NOT NULL, + group_id TEXT NOT NULL, + state TEXT NOT NULL, + updated_at TEXT NOT NULL, + document_json TEXT NOT NULL, + expires_at TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_task_records_group ON task_records(protocol, group_id, updated_at); + CREATE INDEX IF NOT EXISTS idx_task_records_expires_at ON task_records(expires_at); + `); + }, + }, ]; /** Target schema version: the version of the last migration */ diff --git a/src/storage/receipts/store.ts b/src/storage/receipts/store.ts index 1e485d9..3005b2a 100644 --- a/src/storage/receipts/store.ts +++ b/src/storage/receipts/store.ts @@ -42,6 +42,7 @@ import { type LegacySource, type LegacyStoreOptions, missingLegacyImports, + recordedLegacyImports, } from './legacy-import'; import { clampListLimit } from './params'; import { createPendingTaskMethods, sweepExpiredPendingTasks } from './pending-tasks'; @@ -59,6 +60,7 @@ import { type TransactionRow, } from './rows'; import { migrate, SCHEMA_VERSION } from './schema'; +import { createTaskRecordMethods, sweepExpiredTaskRecords } from './task-records'; // Non-2xx statuses, including 0 (unknown), are undelivered, matching // deliveryResult() in ReceiptList.tsx. NOT NULL prevents NULL comparisons from @@ -138,9 +140,8 @@ export interface SqliteReceiptStoreSummary { readonly missingLegacyImports: readonly LegacySource[]; } -/** Implements every optional `ReceiptStore` method except the `task_records` group */ -export interface SqliteReceiptStore - extends Required> { +/** Implements every optional `ReceiptStore` method */ +export interface SqliteReceiptStore extends Required { /** Experimental: may change in a minor release */ summary(options: { readonly orphanHoldMinAgeMs: number }): Promise; } @@ -522,12 +523,6 @@ function storeOn(db: Database.Database, options: SqliteReceiptStoreOptions): Sql const countLiveTasksStmt = db.prepare<[string], { count: number }>( 'SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?', ); - const legacyImportsStmt = db.prepare< - [], - { source: string; path: string; rows: number; imported_at: string } - >( - 'SELECT source, path, rows, imported_at FROM legacy_imports WHERE path IS NOT NULL ORDER BY source', - ); let closed = false; let releaseLegacyLocks: (() => void) | undefined; @@ -545,6 +540,7 @@ function storeOn(db: Database.Database, options: SqliteReceiptStoreOptions): Sql 'idempotency-keys', 'authorization-holds', 'pending-tasks', + 'task-records', ], status: 'stable', }; @@ -560,8 +556,13 @@ function storeOn(db: Database.Database, options: SqliteReceiptStoreOptions): Sql `Receipt store schema version mismatch (found ${version}, expected ${SCHEMA_VERSION})`, ); } - // Remove expired pending tasks at startup without waiting for A2A traffic - if (!db.readonly) sweepExpiredPendingTasks(db, clock.nowIso()); + // Sweep expired pending tasks and task records during writable-store + // init(), without waiting for protocol traffic + if (!db.readonly) { + const now = clock.nowIso(); + sweepExpiredPendingTasks(db, now); + sweepExpiredTaskRecords(db, now); + } if (options.legacyStores !== undefined && releaseLegacyLocks === undefined) { releaseLegacyLocks = importLegacyStores( db, @@ -812,6 +813,7 @@ function storeOn(db: Database.Database, options: SqliteReceiptStoreOptions): Sql ...createIdempotencyMethods(db, clock), ...createHoldMethods(db, clock), ...createPendingTaskMethods(db, clock), + ...createTaskRecordMethods(db, clock), // Reads all unresolved transactions at once. Page this query if large // journals make operator diagnostics too costly. @@ -833,12 +835,7 @@ function storeOn(db: Database.Database, options: SqliteReceiptStoreOptions): Sql unresolvedIdempotencyKeys: unresolvedKeys?.other ?? 0, unresolvedPaymentKeys: unresolvedKeys?.payment ?? 0, unexpiredPendingTasks: countLiveTasksStmt.get(now)?.count ?? 0, - legacyImports: legacyImportsStmt.all().map((row) => ({ - source: row.source, - path: row.path, - rows: row.rows, - importedAt: row.imported_at, - })), + legacyImports: recordedLegacyImports(db), missingLegacyImports: missingLegacyImports(db), }; }, diff --git a/src/storage/receipts/task-records.ts b/src/storage/receipts/task-records.ts new file mode 100644 index 0000000..838dc4d --- /dev/null +++ b/src/storage/receipts/task-records.ts @@ -0,0 +1,101 @@ +/** + * Store task responses as JSON for later reads. Documents are not redacted; + * callers must exclude payment proofs and authorization presentations. + */ +import type Database from 'better-sqlite3'; +import { type Clock, CommerceError, type TaskRecord, toCommerceError } from '../../core'; +import type { StoreGroupMethods } from '../../core/store-method-groups'; +import { storedIso } from './params'; + +interface RecordRow { + id: string; + protocol: string; + group_id: string; + state: string; + updated_at: string; + document_json: string; + expires_at: string; +} + +type TaskRecordMethods = StoreGroupMethods<'task_records'>; + +function rowToRecord(row: RecordRow): TaskRecord { + return { + id: row.id, + protocol: row.protocol as TaskRecord['protocol'], + groupId: row.group_id, + state: row.state, + updatedAt: row.updated_at, + document: JSON.parse(row.document_json), + expiresAt: row.expires_at, + }; +} + +const SWEEP_EXPIRED = 'DELETE FROM task_records WHERE expires_at <= ?'; + +/** Delete expired task records during writable-store initialization */ +export function sweepExpiredTaskRecords(db: Database.Database, now: string): void { + db.prepare(SWEEP_EXPIRED).run(now); +} + +export function createTaskRecordMethods(db: Database.Database, clock: Clock): TaskRecordMethods { + const sweepExpired = db.prepare(SWEEP_EXPIRED); + // Count after the expiry sweep so expired rows do not consume capacity + const countAll = db.prepare<[], { count: number }>('SELECT COUNT(*) AS count FROM task_records'); + const hasId = db.prepare<[string], { id: string }>('SELECT id FROM task_records WHERE id = ?'); + const upsert = db.prepare( + `INSERT OR REPLACE INTO task_records + (id, protocol, group_id, state, updated_at, document_json, expires_at) + VALUES (@id, @protocol, @group_id, @state, @updated_at, @document_json, @expires_at)`, + ); + const selectLive = db.prepare<[string, string], RecordRow>( + 'SELECT * FROM task_records WHERE id = ? AND expires_at > ?', + ); + // ponytail: read the whole group at once; add store pagination when groups become large + const listLive = db.prepare<[string, string, string], RecordRow>( + `SELECT * FROM task_records WHERE protocol = ? AND group_id = ? AND expires_at > ? + ORDER BY updated_at DESC, id DESC`, + ); + + const put = db.transaction((row: RecordRow, maxRecords: number): boolean => { + sweepExpired.run(clock.nowIso()); + // Replacing an existing ID does not count against the record limit + if (hasId.get(row.id) === undefined && (countAll.get()?.count ?? 0) >= maxRecords) { + return false; + } + upsert.run(row); + return true; + }); + + return { + async putTaskRecord(record, options) { + try { + // Reject NaN, which would bypass the capacity comparison + if (!Number.isInteger(options.maxRecords) || options.maxRecords < 0) { + throw new CommerceError('STORAGE_ERROR', 'maxRecords must be a non-negative integer'); + } + const row: RecordRow = { + id: record.id, + protocol: record.protocol, + group_id: record.groupId, + state: record.state, + updated_at: storedIso(record.updatedAt, 'updatedAt'), + document_json: JSON.stringify(record.document), + expires_at: storedIso(record.expiresAt, 'expiresAt'), + }; + return put.immediate(row, options.maxRecords); + } catch (err) { + throw toCommerceError(err, 'STORAGE_ERROR', 'Failed to store task record'); + } + }, + + async getTaskRecord(id) { + const row = selectLive.get(id, clock.nowIso()); + return row !== undefined ? rowToRecord(row) : undefined; + }, + + async listTaskRecords({ protocol, groupId }) { + return listLive.all(protocol, groupId, clock.nowIso()).map(rowToRecord); + }, + }; +} diff --git a/src/testing/conformance/record-cases.ts b/src/testing/conformance/record-cases.ts index 14ffe29..8414f91 100644 --- a/src/testing/conformance/record-cases.ts +++ b/src/testing/conformance/record-cases.ts @@ -1,11 +1,12 @@ -// Conformance cases for the 2.6.0 records: idempotency claims, authorization -// holds and pending tasks +// Conformance cases for optional store records: idempotency claims, +// authorization holds, pending tasks and task records import assert from 'node:assert/strict'; import type { AuthorizationHoldReservation, IdempotencyScope, PendingTask, ReceiptStore, + TaskRecord, } from '../../core'; import { PAYMENT_KEY_ENDPOINT_PREFIX } from '../../core/domain/store-records'; import { STORE_METHOD_GROUPS, type StoreGroupMethods } from '../../core/store-method-groups'; @@ -15,6 +16,7 @@ const CLAIMS = STORE_METHOD_GROUPS.idempotency_claims; const CLAIM_READS = [...CLAIMS, ...STORE_METHOD_GROUPS.response_redelivery]; const HOLDS = STORE_METHOD_GROUPS.authorization_holds; const TASKS = STORE_METHOD_GROUPS.pending_tasks; +const RECORDS = STORE_METHOD_GROUPS.task_records; const MINUTE = 60_000; const DAY = 24 * 60 * MINUTE; @@ -24,10 +26,12 @@ type Claims = StoreGroupMethods<'idempotency_claims'>; type ClaimReads = Claims & StoreGroupMethods<'response_redelivery'>; type Holds = StoreGroupMethods<'authorization_holds'>; type Tasks = StoreGroupMethods<'pending_tasks'>; +type Records = StoreGroupMethods<'task_records'>; const claims = (store: ReceiptStore) => store as ReceiptStore & Claims; const claimReads = (store: ReceiptStore) => store as ReceiptStore & ClaimReads; const holds = (store: ReceiptStore) => store as ReceiptStore & Holds; const tasks = (store: ReceiptStore) => store as ReceiptStore & Tasks; +const records = (store: ReceiptStore) => store as ReceiptStore & Records; const scope = (key: string, endpoint = '/acp/checkout_sessions'): IdempotencyScope => ({ deployment: 'https://gateway.example', @@ -56,6 +60,17 @@ const task = (id: string, fields: Partial = {}): PendingTask => ({ ...fields, }); +const record = (id: string, fields: Partial = {}): TaskRecord => ({ + id, + protocol: 'a2a', + groupId: 'group-1', + state: 'TASK_STATE_COMPLETED', + updatedAt: isoAt(0), + document: { id, status: { state: 'TASK_STATE_COMPLETED' }, artifacts: [{ data: { ok: true } }] }, + expiresAt: isoAt(10 * MINUTE), + ...fields, +}); + const count = (values: readonly T[], predicate: (value: T) => boolean): number => values.filter(predicate).length; @@ -732,4 +747,130 @@ const TASK_CASES: readonly CaseSpec[] = [ }, ]; -export const RECORD_CASES: readonly CaseSpec[] = [...CLAIM_CASES, ...HOLD_CASES, ...TASK_CASES]; +const ids = (list: readonly TaskRecord[]): string[] => list.map((r) => r.id); + +const TASK_RECORD_CASES: readonly CaseSpec[] = [ + { + name: 'a task record reads back by id and lists in its group', + uses: RECORDS, + async run({ store }) { + const s = records(store); + const stored = record('rec1'); + assert.equal(await s.putTaskRecord(stored, { maxRecords: 10 }), true); + assert.deepEqual(await s.getTaskRecord('rec1'), stored); + assert.deepEqual(await s.listTaskRecords({ protocol: 'a2a', groupId: 'group-1' }), [stored]); + assert.equal(await s.getTaskRecord('rec2'), undefined); + }, + }, + { + name: 'a task record with the same id replaces the earlier one, even at maxRecords', + uses: RECORDS, + async run({ store }) { + const s = records(store); + assert.equal( + await s.putTaskRecord(record('rec1', { state: 'TASK_STATE_WORKING' }), { maxRecords: 1 }), + true, + ); + const finished = record('rec1', { updatedAt: isoAt(MINUTE) }); + assert.equal(await s.putTaskRecord(finished, { maxRecords: 1 }), true); + assert.deepEqual(await s.getTaskRecord('rec1'), finished); + assert.equal(await s.putTaskRecord(record('rec2'), { maxRecords: 1 }), false); + assert.deepEqual(ids(await s.listTaskRecords({ protocol: 'a2a', groupId: 'group-1' })), [ + 'rec1', + ]); + }, + }, + { + name: 'an expired task record cannot be read or listed', + uses: RECORDS, + async run({ store, clock }) { + const s = records(store); + const stored = record('rec1', { expiresAt: isoAt(MINUTE) }); + await s.putTaskRecord(stored, { maxRecords: 10 }); + clock.advance(MINUTE - 1); + assert.deepEqual(await s.getTaskRecord('rec1'), stored); + clock.advance(2); + assert.equal(await s.getTaskRecord('rec1'), undefined); + assert.deepEqual(await s.listTaskRecords({ protocol: 'a2a', groupId: 'group-1' }), []); + }, + }, + { + name: 'maxRecords refuses a new task record while that many are unexpired', + uses: RECORDS, + async run({ store, clock }) { + const s = records(store); + const soon = { expiresAt: isoAt(MINUTE) }; + assert.equal(await s.putTaskRecord(record('a', soon), { maxRecords: 2 }), true); + assert.equal(await s.putTaskRecord(record('b', soon), { maxRecords: 2 }), true); + assert.equal(await s.putTaskRecord(record('c'), { maxRecords: 2 }), false); + assert.equal(await s.getTaskRecord('c'), undefined); + + // Expired records free capacity for new records + clock.advance(MINUTE + 1); + assert.equal(await s.putTaskRecord(record('c'), { maxRecords: 2 }), true); + assert.equal(await s.putTaskRecord(record('d'), { maxRecords: 2 }), true); + assert.equal(await s.putTaskRecord(record('e'), { maxRecords: 2 }), false); + }, + }, + { + name: 'task records list one protocol and group, by updatedAt then id, both descending', + uses: RECORDS, + async run({ store }) { + const s = records(store); + const put = (r: TaskRecord) => s.putTaskRecord(r, { maxRecords: 10 }); + await put(record('r1', { updatedAt: isoAt(1) })); + await put(record('r2', { updatedAt: isoAt(3) })); + await put(record('r3', { updatedAt: isoAt(3) })); + await put(record('r4', { updatedAt: isoAt(2), groupId: 'group-2' })); + await put(record('r5', { updatedAt: isoAt(2), protocol: 'mcp' })); + assert.deepEqual(ids(await s.listTaskRecords({ protocol: 'a2a', groupId: 'group-1' })), [ + 'r3', + 'r2', + 'r1', + ]); + assert.deepEqual(ids(await s.listTaskRecords({ protocol: 'a2a', groupId: 'group-2' })), [ + 'r4', + ]); + assert.deepEqual(ids(await s.listTaskRecords({ protocol: 'mcp', groupId: 'group-1' })), [ + 'r5', + ]); + assert.deepEqual(await s.listTaskRecords({ protocol: 'a2a', groupId: 'group-3' }), []); + }, + }, + { + name: 'concurrent task record puts at maxRecords store only as many as fit', + uses: RECORDS, + async run({ store }) { + const s = records(store); + await s.putTaskRecord(record('first'), { maxRecords: 3 }); + const results = await Promise.all( + Array.from({ length: 8 }, (_, i) => s.putTaskRecord(record(`rec${i}`), { maxRecords: 3 })), + ); + assert.equal( + count(results, (r) => r), + 2, + ); + const listed = await s.listTaskRecords({ protocol: 'a2a', groupId: 'group-1' }); + assert.equal(listed.length, 3); + }, + }, + { + name: 'task records survive a reopen', + uses: RECORDS, + needsReopen: true, + async run({ store, reopen }) { + const s = records(store); + const stored = record('rec1'); + await s.putTaskRecord(stored, { maxRecords: 10 }); + const reopened = records(await reopen()); + assert.deepEqual(await reopened.getTaskRecord('rec1'), stored); + }, + }, +]; + +export const RECORD_CASES: readonly CaseSpec[] = [ + ...CLAIM_CASES, + ...HOLD_CASES, + ...TASK_CASES, + ...TASK_RECORD_CASES, +]; diff --git a/tests/e2e/payment/upgrade.e2e.test.ts b/tests/e2e/payment/upgrade.e2e.test.ts index 383b191..72c146f 100644 --- a/tests/e2e/payment/upgrade.e2e.test.ts +++ b/tests/e2e/payment/upgrade.e2e.test.ts @@ -3,7 +3,7 @@ * * Current AP2 and ACP implementations write history to their legacy replay * and idempotency files. Store factories seed records representing interrupted - * requests. Dropping the tables added in schema v5 + * requests. Dropping the tables added after schema v4 * recreates schema v4, which is checked against the 2.5.0 fixture. * Upgraded gateways run `agent-commerce start` in child processes on these * files. @@ -45,6 +45,7 @@ import { createAcpAdapter } from '../../../src/protocols/acp'; import { requestFingerprint } from '../../../src/protocols/acp/idempotency/fingerprint'; import { createAcpIdempotencyStore } from '../../../src/protocols/acp/idempotency/store'; import { createSqliteReceiptStore } from '../../../src/storage/receipts'; +import { SCHEMA_VERSION } from '../../../src/storage/receipts/schema'; import { dumpTables } from '../../fixtures/sqlite-dump'; import { type LoopbackFacilitator, @@ -77,7 +78,13 @@ const HOUR_MS = 3_600_000; const FINALITY_BLOCKS = 65; const IMPORTED = 'imported deprecated store file; it stays locked against writes while this gateway runs'; -const V5_TABLES = ['authorization_holds', 'idempotency_keys', 'legacy_imports', 'pending_tasks']; +const TABLES_AFTER_V4 = [ + 'authorization_holds', + 'idempotency_keys', + 'legacy_imports', + 'pending_tasks', + 'task_records', +]; const FIXTURE_V4 = readFileSync( new URL('../../unit/storage-receipts/fixtures/receipts-v4.sql', import.meta.url), 'utf8', @@ -679,7 +686,7 @@ async function record25(dir: string): Promise { past.close(); const db = new Database(receipts); - for (const table of V5_TABLES) db.exec(`DROP TABLE ${table}`); + for (const table of TABLES_AFTER_V4) db.exec(`DROP TABLE ${table}`); db.pragma('user_version = 4'); db.close(); @@ -792,7 +799,7 @@ describe('upgrading a 2.5.0 deployment', () => { for (const file of added) { expect(file).toMatch(/^(receipts|ap2-replay|acp-idempotency)\.sqlite-(wal|shm)$/); } - expect(schemaOf(receiptsOf(live)).version).toBe(5); + expect(schemaOf(receiptsOf(live)).version).toBe(SCHEMA_VERSION); }); it.each(FLOWS)( diff --git a/tests/integration/goldens/2.7.2/doctor-multi.json b/tests/integration/goldens/2.7.2/doctor-multi.json index 24b6a3e..99a55f3 100644 --- a/tests/integration/goldens/2.7.2/doctor-multi.json +++ b/tests/integration/goldens/2.7.2/doctor-multi.json @@ -103,7 +103,7 @@ { "name": "Storage", "status": "PASS", - "detail": "sqlite schema v5 writable; receipts=0" + "detail": "sqlite schema v6 writable; receipts=0" }, { "name": "Transactions", diff --git a/tests/integration/goldens/2.7.2/doctor-single.json b/tests/integration/goldens/2.7.2/doctor-single.json index 6228ecd..02fa614 100644 --- a/tests/integration/goldens/2.7.2/doctor-single.json +++ b/tests/integration/goldens/2.7.2/doctor-single.json @@ -103,7 +103,7 @@ { "name": "Storage", "status": "PASS", - "detail": "sqlite schema v5 writable; receipts=0" + "detail": "sqlite schema v6 writable; receipts=0" }, { "name": "Transactions", diff --git a/tests/integration/goldens/2.7.2/well-known-multi.json b/tests/integration/goldens/2.7.2/well-known-multi.json index 7396c9a..2d3e404 100644 --- a/tests/integration/goldens/2.7.2/well-known-multi.json +++ b/tests/integration/goldens/2.7.2/well-known-multi.json @@ -259,7 +259,7 @@ "name": "sqlite-receipt-store", "kind": "storage", "implementationVersion": "", - "supportedSpec": "sqlite-schema-v5", + "supportedSpec": "sqlite-schema-v6", "capabilities": [ "receipts", "events", @@ -267,7 +267,8 @@ "transactions", "idempotency-keys", "authorization-holds", - "pending-tasks" + "pending-tasks", + "task-records" ], "status": "stable" }, diff --git a/tests/integration/goldens/2.7.2/well-known-single.json b/tests/integration/goldens/2.7.2/well-known-single.json index 2d3b4cb..a91ecee 100644 --- a/tests/integration/goldens/2.7.2/well-known-single.json +++ b/tests/integration/goldens/2.7.2/well-known-single.json @@ -257,7 +257,7 @@ "name": "sqlite-receipt-store", "kind": "storage", "implementationVersion": "", - "supportedSpec": "sqlite-schema-v5", + "supportedSpec": "sqlite-schema-v6", "capabilities": [ "receipts", "events", @@ -265,7 +265,8 @@ "transactions", "idempotency-keys", "authorization-holds", - "pending-tasks" + "pending-tasks", + "task-records" ], "status": "stable" }, diff --git a/tests/unit/cli/backup.test.ts b/tests/unit/cli/backup.test.ts index 5bbdef4..a3060fd 100644 --- a/tests/unit/cli/backup.test.ts +++ b/tests/unit/cli/backup.test.ts @@ -20,6 +20,7 @@ import { type BackupManifest, runBackupCommand } from '../../../src/cli/commands import type { GatewayConfig } from '../../../src/config'; import { createAcpIdempotencyStore } from '../../../src/protocols/acp/idempotency/store'; import { createSqliteReceiptStore } from '../../../src/storage/receipts'; +import { SCHEMA_VERSION } from '../../../src/storage/receipts/schema'; import { dumpTables } from '../../fixtures/sqlite-dump'; import { createCapturingIo, makeGatewayConfig } from './fixtures'; @@ -28,6 +29,16 @@ const FIXTURE_V4 = readFileSync( 'utf8', ); const NOW = '2026-11-01T12:00:00.000Z'; +// Keep this record valid when the backup is read with the system clock +const TASK_RECORD = { + id: 'task_backup', + protocol: 'a2a' as const, + groupId: 'ctx_backup', + state: 'TASK_STATE_COMPLETED', + updatedAt: NOW, + document: { id: 'task_backup' }, + expiresAt: '2100-01-01T00:00:00.000Z', +}; const clock = { now: () => new Date(NOW), nowIso: () => NOW, monotonicMs: () => 0 }; let dir: string; @@ -119,6 +130,10 @@ function mode(path: string): number { describe('agent-commerce backup', () => { it('copies a database a writer is changing into a consistent, owner-only snapshot', async () => { await startedOnce(); + const seeded = createSqliteReceiptStore({ path: receipts }); + await seeded.init(); + await seeded.putTaskRecord(TASK_RECORD, { maxRecords: 1 }); + await seeded.close(); const live = new Database(receipts); live.exec('CREATE TABLE writer_probe (n INTEGER PRIMARY KEY)'); live.close(); @@ -162,7 +177,7 @@ describe('agent-commerce backup', () => { { file: 'receipts.sqlite', source: 'storage.receipts.path', - schemaVersion: 5, + schemaVersion: SCHEMA_VERSION, sha256: sha256(join(out, 'receipts.sqlite')), }, ], @@ -174,7 +189,8 @@ describe('agent-commerce backup', () => { // Reopen last: the store switches the copy to WAL but needs no migration const reopened = createSqliteReceiptStore({ path: join(out, 'receipts.sqlite') }); await reopened.init(); - expect((await reopened.health()).detail).toBe('sqlite schema v5 writable'); + expect((await reopened.health()).detail).toBe(`sqlite schema v${SCHEMA_VERSION} writable`); + expect(await reopened.getTaskRecord(TASK_RECORD.id)).toEqual(TASK_RECORD); await reopened.close(); }); @@ -202,7 +218,7 @@ describe('agent-commerce backup', () => { expect(dumpTables(join(out, 'ap2-replay.sqlite'))).toEqual(dumpTables(ap2)); expect(dumpTables(join(out, 'acp-idempotency.sqlite'))).toEqual(dumpTables(acp)); for (const file of manifest().files) expect(mode(join(out, file.file))).toBe(0o600); - // Read-only: no migration to v5, no import marker, no rewritten file + // Read-only: no migration, no import marker, no rewritten file expect([receipts, ap2, acp].map(sha256)).toEqual(before); }); @@ -268,17 +284,22 @@ describe('agent-commerce backup', () => { expect(readFileSync(out, 'utf8')).toBe('not a directory'); }); - it.each([3, 6])('refuses a receipt database at schema v%i, copying nothing', async (version) => { - const db = new Database(receipts); - db.pragma(`user_version = ${version}`); - db.close(); + it.each([3, SCHEMA_VERSION + 1])( + 'refuses a receipt database at schema v%i, copying nothing', + async (version) => { + const db = new Database(receipts); + db.pragma(`user_version = ${version}`); + db.close(); - const { code, io } = await backup(); + const { code, io } = await backup(); - expect(code).toBe(1); - expect(io.err.join('\n')).toContain(`schema v${version}; this version backs up v4 to v5`); - expect(readdirSync(out)).toEqual([]); - }); + expect(code).toBe(1); + expect(io.err.join('\n')).toContain( + `schema v${version}; this version backs up v4 to v${SCHEMA_VERSION}`, + ); + expect(readdirSync(out)).toEqual([]); + }, + ); it('refuses a receipt database that does not exist, without creating it', async () => { const { code, io } = await backup(); diff --git a/tests/unit/cli/doctor-storage.test.ts b/tests/unit/cli/doctor-storage.test.ts index 291ff61..8167c66 100644 --- a/tests/unit/cli/doctor-storage.test.ts +++ b/tests/unit/cli/doctor-storage.test.ts @@ -15,6 +15,7 @@ import { type SqliteLegacyImport, type SqliteReceiptStoreSummary, } from '../../../src/storage/receipts'; +import { SCHEMA_VERSION } from '../../../src/storage/receipts/schema'; import { createFakeFetch, jsonResponse, makeFakeReceiptStore, makeGatewayConfig } from './fixtures'; const GATEWAY = 'http://127.0.0.1:8080'; @@ -364,7 +365,7 @@ describe('runDoctor: the receipt database is read, never changed', () => { db.close(); } - async function seedV5(legacy?: { readonly acpIdempotency: string }): Promise { + async function seedCurrent(legacy?: { readonly acpIdempotency: string }): Promise { const store = createSqliteReceiptStore({ path: receipts, ...(legacy !== undefined ? { legacyStores: { ...legacy, enabled: { acp: true } } } : {}), @@ -385,8 +386,7 @@ describe('runDoctor: the receipt database is read, never changed', () => { expect(check(report, 'Storage')).toEqual({ name: 'Storage', status: 'WARN', - detail: - 'sqlite schema v4; the next start migrates it to v5, which earlier versions cannot open. Run agent-commerce backup first to keep a copy they can', + detail: `sqlite schema v4; the next start migrates it to v${SCHEMA_VERSION}, which earlier versions cannot open. Run agent-commerce backup first to keep a copy they can`, }); // The v4 fixture has no import record for the legacy file expect(check(report, 'ACP idempotency')?.detail).toContain('are not moved yet'); @@ -420,8 +420,38 @@ describe('runDoctor: the receipt database is read, never changed', () => { } }); - it('reads a v5 database without importing a deprecated file it has not imported', async () => { - await seedV5(); + it('reads the imports a v5 (2.8) database recorded, and leaves it at v5', async () => { + await seedCurrent({ acpIdempotency: acp }); + // Remove the task-record table to recreate schema v5 (2.8.0) + const db = new Database(receipts); + db.exec('DROP TABLE task_records'); + db.pragma('user_version = 5'); + db.close(); + const [marker] = imports() as { imported_at: string }[]; + const before = sha(receipts); + + const report = await doctorWith(acpConfig(receipts, acp)); + + expect(check(report, 'Storage')?.detail).toContain( + `sqlite schema v5; the next start migrates it to v${SCHEMA_VERSION}`, + ); + expect(check(report, 'ACP idempotency')).toEqual({ + name: 'ACP idempotency', + status: 'WARN', + detail: `deprecated key: 0 row(s) moved into the receipt database at ${marker?.imported_at}; remove the key (retention 24h)`, + }); + const moved = join(dir, 'acp-moved.sqlite'); + writeFileSync(moved, ''); + expect(check(await doctorWith(acpConfig(receipts, moved)), 'ACP idempotency')).toMatchObject({ + status: 'FAIL', + detail: expect.stringContaining('was imported already, so start refuses it'), + }); + expect(sha(receipts)).toBe(before); + expect(version()).toBe(5); + }); + + it('reads a current database without importing a deprecated file it has not imported', async () => { + await seedCurrent(); const before = sha(receipts); const report = await doctorWith(acpConfig(receipts, acp)); @@ -429,7 +459,7 @@ describe('runDoctor: the receipt database is read, never changed', () => { expect(check(report, 'Storage')).toEqual({ name: 'Storage', status: 'PASS', - detail: 'sqlite schema v5 writable; receipts=0', + detail: `sqlite schema v${SCHEMA_VERSION} writable; receipts=0`, }); expect(check(report, 'Transactions')?.status).toBe('PASS'); expect(check(report, 'ACP idempotency')?.detail).toBe( @@ -440,7 +470,7 @@ describe('runDoctor: the receipt database is read, never changed', () => { }); it('reports the import that start recorded', async () => { - await seedV5({ acpIdempotency: acp }); + await seedCurrent({ acpIdempotency: acp }); const [marker] = imports() as { imported_at: string }[]; const report = await doctorWith(acpConfig(receipts, acp)); @@ -453,9 +483,9 @@ describe('runDoctor: the receipt database is read, never changed', () => { }); it('fails a database a newer version wrote, and leaves its version alone', async () => { - await seedV5(); + await seedCurrent(); const db = new Database(receipts); - db.pragma('user_version = 6'); + db.pragma(`user_version = ${SCHEMA_VERSION + 1}`); db.close(); const report = await doctorWith(acpConfig(receipts)); @@ -463,10 +493,9 @@ describe('runDoctor: the receipt database is read, never changed', () => { expect(check(report, 'Storage')).toEqual({ name: 'Storage', status: 'FAIL', - detail: - 'sqlite schema v6 is newer than this version reads (v5); run the version that wrote it', + detail: `sqlite schema v${SCHEMA_VERSION + 1} is newer than this version reads (v${SCHEMA_VERSION}); run the version that wrote it`, }); - expect(version()).toBe(6); + expect(version()).toBe(SCHEMA_VERSION + 1); expect(report.exitCode).toBe(1); }); diff --git a/tests/unit/storage-receipts/fixtures/receipts-v5.sql b/tests/unit/storage-receipts/fixtures/receipts-v5.sql new file mode 100644 index 0000000..146c1e2 --- /dev/null +++ b/tests/unit/storage-receipts/fixtures/receipts-v5.sql @@ -0,0 +1,187 @@ +-- Fixed 2.8.0 (schema v5) fixture: the 2.5.0 fixture migrated by the 2.8.0 +-- store, plus a reserved and a consumed hold, a completed ACP claim, an +-- in-flight payment retry claim and an unexpired A2A pending task. Keep this +-- SQL fixed: migration changes must not alter the upgrade test's input. +PRAGMA foreign_keys=OFF; +BEGIN TRANSACTION; +CREATE TABLE receipts ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + id TEXT NOT NULL UNIQUE, + request_id TEXT NOT NULL, + resource_id TEXT NOT NULL, + payment_json TEXT, + delivered_at TEXT NOT NULL, + backend_status INTEGER NOT NULL, + duration_ms INTEGER, + protocol TEXT, + metadata_json TEXT + , authorization_json TEXT, transaction_id TEXT); +INSERT INTO receipts VALUES(1,'receipt_paid','req_paid','resource.report','{"status":"settled","provider":"x402","amount":"0.01","currency":"USDC","externalReference":"0xsettled","network":"eip155:31337"}','2026-10-01T10:00:00.000Z',200,12,'mcp','{"adapter":"mcp"}','{"method":"ap2","reference":"sha256:mandate"}',NULL); +INSERT INTO receipts VALUES(2,'receipt_failed','req_failed','resource.report',NULL,'2026-10-01T11:00:00.000Z',502,NULL,NULL,NULL,NULL,NULL); +INSERT INTO receipts VALUES(3,'receipt_v4_delivered','req_v4_delivered','resource.report','{"status":"settled","provider":"x402","amount":"0.01","currency":"USDC","externalReference":"0xtx_v4"}','2026-10-20T12:00:07.000Z',200,NULL,NULL,NULL,NULL,'txn_v4_delivered'); +CREATE TABLE events ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + id TEXT NOT NULL UNIQUE, + type TEXT NOT NULL, + request_id TEXT NOT NULL, + resource_id TEXT, + at TEXT NOT NULL, + adapter TEXT, + payment_provider TEXT, + duration_ms INTEGER, + status TEXT, + data_json TEXT + , transaction_id TEXT); +INSERT INTO events VALUES(1,'event_requested','resource.requested','req_paid',NULL,'2026-10-01T09:59:00.000Z',NULL,NULL,NULL,NULL,NULL,NULL); +INSERT INTO events VALUES(2,'event_settled','payment.settled','req_paid','resource.report','2026-10-01T10:00:00.000Z','mcp','x402',5,'ok','{"externalReference":"0xsettled"}',NULL); +INSERT INTO events VALUES(3,'event_v4_delivered','resource.delivered','req_v4_delivered','resource.report','2026-10-20T12:00:10.000Z',NULL,NULL,NULL,NULL,NULL,'txn_v4_delivered'); +CREATE TABLE payment_attempts ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + id TEXT NOT NULL UNIQUE, + request_id TEXT NOT NULL, + resource_id TEXT NOT NULL, + provider TEXT NOT NULL, + replay_key TEXT NOT NULL UNIQUE, + status TEXT NOT NULL, + amount TEXT NOT NULL, + currency TEXT NOT NULL, + payer TEXT, + payee TEXT, + external_reference TEXT, + rejection_reason TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + , transaction_id TEXT, resolution_json TEXT); +INSERT INTO payment_attempts VALUES(1,'attempt_settled','req_paid','resource.report','x402','replay_settled','settled','0.01','USDC','0xbuyer','0xmerchant','0xsettled',NULL,'2026-10-01T10:00:00.000Z','2026-10-01T10:00:01.000Z',NULL,NULL); +INSERT INTO payment_attempts VALUES(2,'attempt_reserved','req_reserved','resource.report','x402','replay_reserved','reserved','0.01','USDC',NULL,NULL,NULL,NULL,'2026-10-01T10:01:00.000Z','2026-10-01T10:01:00.000Z',NULL,NULL); +INSERT INTO payment_attempts VALUES(3,'attempt_rejected','req_rejected','resource.report','x402','replay_rejected','rejected','0.01','USDC',NULL,NULL,NULL,'backend_failed','2026-10-01T10:02:00.000Z','2026-10-01T10:02:01.000Z',NULL,NULL); +INSERT INTO payment_attempts VALUES(4,'attempt_uncertain','req_uncertain','resource.report','mpp','replay_uncertain','settlement-uncertain','0.01','USDC',NULL,NULL,'0xpending',NULL,'2026-10-01T10:03:00.000Z','2026-10-01T10:03:01.000Z',NULL,NULL); +INSERT INTO payment_attempts VALUES(5,'attempt_failed','req_legacy','resource.report','x402','replay_failed','failed','0.01','USDC',NULL,NULL,NULL,NULL,'2026-10-01T10:04:00.000Z','2026-10-01T10:04:01.000Z',NULL,NULL); +INSERT INTO payment_attempts VALUES(6,'attempt_v4_1','req_v4_delivered','resource.report','x402','replay_v4_delivered','settled','0.01','USDC','0xbuyer','0xmerchant','0xtx_v4',NULL,'2026-10-20T12:00:01.000Z','2026-10-20T12:00:03.000Z','txn_v4_delivered',NULL); +INSERT INTO payment_attempts VALUES(7,'attempt_v4_2','req_v4_uncertain','resource.report','mpp','replay_v4_uncertain','settlement-uncertain','0.01','USDC',NULL,NULL,'0xmaybe',NULL,'2026-10-20T12:00:11.000Z','2026-10-20T12:00:13.000Z','txn_v4_uncertain',NULL); +INSERT INTO payment_attempts VALUES(8,'attempt_v4_4','req_v4_second','resource.report','near','replay_v4_reclaim','reserved','0.01','USDC',NULL,NULL,NULL,NULL,'2026-10-20T12:00:20.000Z','2026-10-20T12:00:20.000Z','txn_v4_second',NULL); +INSERT INTO payment_attempts VALUES(9,'attempt_v4_5','req_v4_resolved','resource.report','x402','replay_v4_resolved','settled','0.01','USDC',NULL,NULL,NULL,NULL,'2026-10-20T12:00:21.000Z','2026-10-20T12:00:24.000Z','txn_v4_resolved','{"method":"manual","actor":"ops","reason":"checked the explorer","at":"2026-10-20T12:00:23.000Z","externalReference":"0xmanual"}'); +CREATE TABLE payment_attempt_history ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + id TEXT NOT NULL, + request_id TEXT NOT NULL, + resource_id TEXT NOT NULL, + provider TEXT NOT NULL, + replay_key TEXT NOT NULL, + status TEXT NOT NULL, + amount TEXT NOT NULL, + currency TEXT NOT NULL, + payer TEXT, + payee TEXT, + external_reference TEXT, + rejection_reason TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + superseded_at TEXT NOT NULL + , transaction_id TEXT, resolution_json TEXT); +INSERT INTO payment_attempt_history VALUES(1,'attempt_archived','req_first_try','resource.report','x402','replay_rejected','rejected','0.01','USDC',NULL,NULL,NULL,'insufficient_funds','2026-10-01T09:00:00.000Z','2026-10-01T09:00:01.000Z','2026-10-01T10:02:00.000Z',NULL,NULL); +INSERT INTO payment_attempt_history VALUES(2,'attempt_v4_3','req_v4_first','resource.report','near','replay_v4_reclaim','rejected','0.01','USDC',NULL,NULL,NULL,'backend_failed','2026-10-20T12:00:16.000Z','2026-10-20T12:00:17.000Z','2026-10-20T12:00:20.000Z','txn_v4_first',NULL); +CREATE TABLE transactions ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + id TEXT NOT NULL UNIQUE, + request_id TEXT NOT NULL, + resource_id TEXT NOT NULL, + protocol TEXT NOT NULL, + state TEXT NOT NULL, + provider TEXT NOT NULL, + attempt_id TEXT NOT NULL, + replay_key TEXT NOT NULL, + network TEXT, + asset TEXT, + authorization_json TEXT, + reservation_id TEXT, + locator_json TEXT, + expires_at TEXT, + input_digest TEXT, + config_digest TEXT NOT NULL, + settling_at TEXT, + backend_dispatched_at TEXT, + backend_deadline_at TEXT, + backend_status INTEGER, + backend_error_code TEXT, + receipt_id TEXT, + persistence_failures_json TEXT, + completed_at TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); +INSERT INTO transactions VALUES(1,'txn_v4_delivered','req_v4_delivered','resource.report','mcp','delivered','x402','attempt_v4_1','replay_v4_delivered','eip155:31337','0xasset','{"method":"ap2","reference":"sha256:mandate_v4","hold":"consumed"}','hold_v4_delivered','{"kind":"eip3009","nonce":"0xnonce","from":"0xbuyer"}','2026-10-20T13:00:00.000Z','sha256:input','sha256:terms','2026-10-20T12:00:02.000Z','2026-10-20T12:00:05.000Z','2026-10-20T12:10:00.000Z',200,NULL,'receipt_v4_delivered',NULL,'2026-10-20T12:00:09.000Z','2026-10-20T12:00:01.000Z','2026-10-20T12:00:09.000Z'); +INSERT INTO transactions VALUES(2,'txn_v4_uncertain','req_v4_uncertain','resource.report','mcp','payment-uncertain','mpp','attempt_v4_2','replay_v4_uncertain',NULL,NULL,'{"method":"ap2","reference":"sha256:mandate_v4_u","hold":"uncertain"}','hold_v4_uncertain',NULL,NULL,NULL,'sha256:terms','2026-10-20T12:00:12.000Z',NULL,NULL,NULL,NULL,NULL,'["receipt"]','2026-10-20T12:00:15.000Z','2026-10-20T12:00:11.000Z','2026-10-20T12:00:15.000Z'); +INSERT INTO transactions VALUES(3,'txn_v4_first','req_v4_first','resource.report','mcp','payment-failed','near','attempt_v4_3','replay_v4_reclaim',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'sha256:terms',NULL,'2026-10-20T12:00:18.000Z','2026-10-20T12:00:18.000Z',502,'BACKEND_ERROR',NULL,NULL,'2026-10-20T12:00:19.000Z','2026-10-20T12:00:16.000Z','2026-10-20T12:00:19.000Z'); +INSERT INTO transactions VALUES(4,'txn_v4_second','req_v4_second','resource.report','mcp','payment-pending','near','attempt_v4_4','replay_v4_reclaim',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'sha256:terms',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2026-10-20T12:00:20.000Z','2026-10-20T12:00:20.000Z'); +INSERT INTO transactions VALUES(5,'txn_v4_resolved','req_v4_resolved','resource.report','mcp','settled-undelivered','x402','attempt_v4_5','replay_v4_resolved',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'sha256:terms',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'2026-10-20T12:00:21.000Z','2026-10-20T12:00:21.000Z'); +CREATE TABLE authorization_holds ( + reference TEXT PRIMARY KEY, + method TEXT NOT NULL, + binding_reference TEXT NOT NULL, + resource_id TEXT NOT NULL, + request_id TEXT NOT NULL, + state TEXT NOT NULL + CHECK (state IN ('reserved', 'consumed', 'released', 'uncertain')), + metadata_json TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); +INSERT INTO authorization_holds VALUES('sha256:mandate_v5_reserved','ap2','jti_v5_reserved','resource.report','req_v5_hold','reserved','{"issuer":"did:example:issuer"}','2026-01-01T00:00:00.001Z','2026-01-01T00:00:00.001Z'); +INSERT INTO authorization_holds VALUES('sha256:mandate_v5_consumed','ap2','jti_v5_consumed','resource.report','req_v5_consumed','consumed',NULL,'2026-01-01T00:00:00.002Z','2026-01-01T00:00:00.003Z'); +CREATE TABLE idempotency_keys ( + deployment TEXT NOT NULL, + endpoint TEXT NOT NULL, + idempotency_key TEXT NOT NULL, + fingerprint TEXT NOT NULL, + state TEXT NOT NULL, + status INTEGER, + body_json TEXT, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + PRIMARY KEY (deployment, endpoint, idempotency_key) + ); +INSERT INTO idempotency_keys VALUES('https://gateway.example','/checkout_sessions','acp-key-v5','sha256:fp_acp','completed',201,'{"id":"cs_v5"}','2026-01-01T00:00:00.004Z','2027-01-01T00:00:00.000Z'); +INSERT INTO idempotency_keys VALUES('https://gateway.example','payment:resource.report','retry-v5','sha256:fp_retry','in_flight',NULL,'{"owner":"sha256:proof_v5"}','2026-01-01T00:00:00.005Z','2027-01-01T00:00:00.000Z'); +CREATE TABLE pending_tasks ( + id TEXT PRIMARY KEY, + protocol TEXT NOT NULL, + resource_id TEXT NOT NULL, + input_json TEXT NOT NULL, + adapter_data_json TEXT, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL + ); +INSERT INTO pending_tasks VALUES('a2a_v5_pending','a2a','resource.report','{"symbol":"ETH"}','{"contextId":"a2a-ctx_v5","messageId":"msg-v5"}','2026-01-01T00:00:00.006Z','2027-01-01T00:00:00.000Z'); +CREATE TABLE legacy_imports ( + source TEXT PRIMARY KEY, + path TEXT, + rows INTEGER NOT NULL, + imported_at TEXT NOT NULL + ); +DELETE FROM sqlite_sequence; +INSERT INTO sqlite_sequence VALUES('receipts',3); +INSERT INTO sqlite_sequence VALUES('events',3); +INSERT INTO sqlite_sequence VALUES('payment_attempts',9); +INSERT INTO sqlite_sequence VALUES('payment_attempt_history',2); +INSERT INTO sqlite_sequence VALUES('transactions',5); +CREATE INDEX idx_receipts_request_id ON receipts(request_id); +CREATE INDEX idx_receipts_delivered_at ON receipts(delivered_at); +CREATE INDEX idx_events_request_id ON events(request_id); +CREATE INDEX idx_events_at ON events(at); +CREATE INDEX idx_payment_attempts_request_id ON payment_attempts(request_id); +CREATE INDEX idx_payment_attempts_created_at ON payment_attempts(created_at); +CREATE INDEX idx_payment_attempt_history_replay_key ON payment_attempt_history(replay_key); +CREATE INDEX idx_payment_attempt_history_request_id ON payment_attempt_history(request_id); +CREATE INDEX idx_transactions_state_seq ON transactions(state, seq); +CREATE INDEX idx_transactions_request_id ON transactions(request_id); +CREATE INDEX idx_transactions_replay_key ON transactions(replay_key); +CREATE INDEX idx_payment_attempt_history_id ON payment_attempt_history(id); +CREATE INDEX idx_authorization_holds_binding ON authorization_holds(binding_reference); +CREATE INDEX idx_authorization_holds_request_id ON authorization_holds(request_id); +CREATE INDEX idx_authorization_holds_state_updated ON authorization_holds(state, updated_at); +CREATE INDEX idx_idempotency_keys_expires_at ON idempotency_keys(expires_at); +CREATE INDEX idx_pending_tasks_expires_at ON pending_tasks(expires_at); +COMMIT; + +PRAGMA user_version = 5; diff --git a/tests/unit/storage-receipts/migration-v5.test.ts b/tests/unit/storage-receipts/migration-v5.test.ts index 6b920f8..d0551ad 100644 --- a/tests/unit/storage-receipts/migration-v5.test.ts +++ b/tests/unit/storage-receipts/migration-v5.test.ts @@ -1,15 +1,22 @@ -// Test schema v5 upgrades using a fixed 2.5.0 (schema v4) SQL fixture +// Test upgrades from the fixed 2.5.0 (schema v4) SQL fixture to SCHEMA_VERSION import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import Database from 'better-sqlite3'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { createSqliteReceiptStore } from '../../../src/storage/receipts'; +import { SCHEMA_VERSION } from '../../../src/storage/receipts/schema'; import { dumpTables } from '../../fixtures/sqlite-dump'; import { createFakeClock, createFakeIds } from './helpers'; const FIXTURE = readFileSync(new URL('./fixtures/receipts-v4.sql', import.meta.url), 'utf8'); -const NEW_TABLES = ['authorization_holds', 'idempotency_keys', 'legacy_imports', 'pending_tasks']; +const NEW_TABLES = [ + 'authorization_holds', + 'idempotency_keys', + 'legacy_imports', + 'pending_tasks', + 'task_records', +]; const schemaOf = (path: string) => { const db = new Database(path, { readonly: true }); @@ -55,7 +62,7 @@ describe('schema v5 migration', () => { } const after = dumpTables(path); - expect(schemaOf(path).version).toBe(5); + expect(schemaOf(path).version).toBe(SCHEMA_VERSION); for (const table of NEW_TABLES) expect(after[table]).toEqual([]); const existing = Object.fromEntries( Object.entries(after).filter(([table]) => !NEW_TABLES.includes(table)), @@ -101,24 +108,29 @@ describe('schema v5 migration', () => { } }); - it('reports schema v5 and its record capabilities', async () => { + it('reports the current schema and its record capabilities', async () => { const store = open(); try { await store.init(); - expect(store.descriptor.supportedSpec).toBe('sqlite-schema-v5'); + expect(store.descriptor.supportedSpec).toBe(`sqlite-schema-v${SCHEMA_VERSION}`); expect(store.descriptor.capabilities).toEqual( - expect.arrayContaining(['idempotency-keys', 'authorization-holds', 'pending-tasks']), + expect.arrayContaining([ + 'idempotency-keys', + 'authorization-holds', + 'pending-tasks', + 'task-records', + ]), ); expect(await store.health()).toMatchObject({ status: 'pass', - detail: 'sqlite schema v5 writable', + detail: `sqlite schema v${SCHEMA_VERSION} writable`, }); } finally { await store.close(); } }); - it('leaves a v5 file unchanged when reopened', async () => { + it('leaves a migrated file unchanged when reopened', async () => { const first = open(); await first.init(); await first.reserveAuthorizationHold?.({ @@ -150,7 +162,7 @@ describe('schema v5 migration', () => { await upgraded.init(); await upgraded.close(); const db = new Database(path); - db.pragma('user_version = 6'); + db.pragma(`user_version = ${SCHEMA_VERSION + 1}`); db.close(); const rows = dumpTables(path); @@ -158,7 +170,7 @@ describe('schema v5 migration', () => { try { await expect(store.init()).rejects.toMatchObject({ code: 'STORAGE_ERROR', - message: expect.stringContaining('found 6, expected 5'), + message: expect.stringContaining(`found ${SCHEMA_VERSION + 1}, expected ${SCHEMA_VERSION}`), }); expect(await store.health()).toMatchObject({ status: 'fail', @@ -168,6 +180,6 @@ describe('schema v5 migration', () => { await store.close(); } expect(dumpTables(path)).toStrictEqual(rows); - expect(schemaOf(path).version).toBe(6); + expect(schemaOf(path).version).toBe(SCHEMA_VERSION + 1); }); }); diff --git a/tests/unit/storage-receipts/migration-v6.test.ts b/tests/unit/storage-receipts/migration-v6.test.ts new file mode 100644 index 0000000..cc85250 --- /dev/null +++ b/tests/unit/storage-receipts/migration-v6.test.ts @@ -0,0 +1,109 @@ +// Test schema v6 upgrades using a fixed 2.8.0 (schema v5) SQL fixture +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import Database from 'better-sqlite3'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { createSqliteReceiptStore } from '../../../src/storage/receipts'; +import { SCHEMA_VERSION } from '../../../src/storage/receipts/schema'; +import { dumpTables } from '../../fixtures/sqlite-dump'; +import { createFakeClock, createFakeIds } from './helpers'; + +const FIXTURE = readFileSync(new URL('./fixtures/receipts-v5.sql', import.meta.url), 'utf8'); +const DEPLOYMENT = 'https://gateway.example'; + +const versionOf = (path: string): number => { + const db = new Database(path, { readonly: true }); + try { + return db.pragma('user_version', { simple: true }) as number; + } finally { + db.close(); + } +}; + +describe('schema v6 migration', () => { + let dir: string; + let path: string; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'receipt-store-v6-')); + path = join(dir, 'receipts.sqlite'); + const v5 = new Database(path); + v5.exec(FIXTURE); + v5.close(); + }); + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + const open = () => + createSqliteReceiptStore({ path, clock: createFakeClock(), ids: createFakeIds() }); + + it('upgrades a 2.8.0 file and leaves every existing row unchanged', async () => { + const before = dumpTables(path); + expect(versionOf(path)).toBe(5); + expect(before['authorization_holds']).toHaveLength(2); + expect(before['idempotency_keys']).toHaveLength(2); + expect(before['pending_tasks']).toHaveLength(1); + expect(before['transactions']).toHaveLength(5); + + const store = open(); + try { + await store.init(); + } finally { + await store.close(); + } + + const { task_records: added, ...existing } = dumpTables(path); + expect(versionOf(path)).toBe(SCHEMA_VERSION); + expect(added).toEqual([]); + expect(existing).toStrictEqual(before); + }); + + it('reads the 2.8.0 records back and stores task records in the upgraded file', async () => { + const store = open(); + try { + await store.init(); + expect(await store.getPendingTask('a2a_v5_pending')).toEqual({ + id: 'a2a_v5_pending', + protocol: 'a2a', + resourceId: 'resource.report', + input: { symbol: 'ETH' }, + adapterData: { contextId: 'a2a-ctx_v5', messageId: 'msg-v5' }, + expiresAt: '2027-01-01T00:00:00.000Z', + }); + expect(await store.getAuthorizationHoldState('sha256:mandate_v5_reserved')).toBe('reserved'); + expect(await store.getAuthorizationHoldState('sha256:mandate_v5_consumed')).toBe('consumed'); + const acp = { deployment: DEPLOYMENT, endpoint: '/checkout_sessions', key: 'acp-key-v5' }; + expect(await store.getIdempotencyKey(acp, 'sha256:fp_acp')).toEqual({ + kind: 'replay', + status: 201, + body: { id: 'cs_v5' }, + }); + const retry = { + deployment: DEPLOYMENT, + endpoint: 'payment:resource.report', + key: 'retry-v5', + }; + expect(await store.getIdempotencyKey(retry, 'sha256:fp_retry')).toEqual({ + kind: 'in-flight', + owner: 'sha256:proof_v5', + }); + + const record = { + id: 'task_v6', + protocol: 'a2a' as const, + groupId: 'ctx_v6', + state: 'TASK_STATE_COMPLETED', + updatedAt: '2026-01-01T00:00:01.000Z', + document: { id: 'task_v6' }, + expiresAt: '2026-01-02T00:00:00.000Z', + }; + expect(await store.putTaskRecord(record, { maxRecords: 1 })).toBe(true); + expect(await store.listTaskRecords({ protocol: 'a2a', groupId: 'ctx_v6' })).toEqual([record]); + } finally { + await store.close(); + } + }); +}); diff --git a/tests/unit/storage-receipts/payment-attempts.test.ts b/tests/unit/storage-receipts/payment-attempts.test.ts index be99539..b04e180 100644 --- a/tests/unit/storage-receipts/payment-attempts.test.ts +++ b/tests/unit/storage-receipts/payment-attempts.test.ts @@ -63,7 +63,7 @@ describe('reservePaymentAttempt', () => { currency: 'USDC', payer: '0xbuyer', payee: '0xmerchant', - // init() read the clock once, to sweep expired pending tasks + // init() read the clock once, to sweep expired pending tasks and task records createdAt: '2026-01-01T00:00:00.001Z', updatedAt: '2026-01-01T00:00:00.001Z', }; diff --git a/tests/unit/storage-receipts/record-inputs.test.ts b/tests/unit/storage-receipts/record-inputs.test.ts index 7f1fbfc..8a1cafd 100644 --- a/tests/unit/storage-receipts/record-inputs.test.ts +++ b/tests/unit/storage-receipts/record-inputs.test.ts @@ -15,6 +15,15 @@ import { dumpTables } from '../../fixtures/sqlite-dump'; const MINUTE = 60_000; const SCOPE = { deployment: 'https://gateway.test', endpoint: '/checkout_sessions', key: 'k1' }; const task = { id: 'task_1', protocol: 'a2a' as const, resourceId: 'r', input: {} }; +const record = (id: string, updatedAt: string, expiresAt = isoAt(10 * MINUTE)) => ({ + id, + protocol: 'a2a' as const, + groupId: 'ctx_1', + state: 'TASK_STATE_COMPLETED', + updatedAt, + document: { id }, + expiresAt, +}); describe('SQLite record method inputs', () => { let dir: string; @@ -43,6 +52,13 @@ describe('SQLite record method inputs', () => { expect(dumpTables(path).pending_tasks).toEqual([]); }); + it.each([Number.NaN, -1, 1.5])('refuses maxRecords %s and stores nothing', async (maxRecords) => { + await expect( + store.putTaskRecord(record('rec_1', isoAt(0)), { maxRecords }), + ).rejects.toMatchObject({ code: 'STORAGE_ERROR' }); + expect(dumpTables(path).task_records).toEqual([]); + }); + it('writes nothing when reading a claim, even one past its expiry', async () => { await store.claimIdempotencyKey(SCOPE, 'fp', isoAt(MINUTE)); await store.updateIdempotencyKey(SCOPE, { kind: 'completed', status: 200, body: {} }); @@ -77,9 +93,16 @@ describe('SQLite record method inputs', () => { await expect( store.listOrphanAuthorizationHolds({ updatedBefore: 'not-a-date' }), ).rejects.toMatchObject({ code: 'STORAGE_ERROR' }); + await expect( + store.putTaskRecord(record('rec_1', 'not-a-date'), { maxRecords: 10 }), + ).rejects.toMatchObject({ code: 'STORAGE_ERROR' }); + await expect( + store.putTaskRecord(record('rec_1', isoAt(0), 'not-a-date'), { maxRecords: 10 }), + ).rejects.toMatchObject({ code: 'STORAGE_ERROR' }); const tables = dumpTables(path); expect(tables.idempotency_keys).toEqual([]); expect(tables.pending_tasks).toEqual([]); + expect(tables.task_records).toEqual([]); }); // Timestamps are compared as text, so an offset form must be stored as UTC @@ -104,4 +127,33 @@ describe('SQLite record method inputs', () => { clock.advance(20 * MINUTE); expect(await store.getPendingTask('task_1')).toBeUndefined(); }); + + it('stops serving a task record at the instant an offset timestamp names', async () => { + await store.putTaskRecord(record('rec_1', isoAt(0), '2026-01-01T01:10:00+01:00'), { + maxRecords: 1, + }); + clock.advance(20 * MINUTE); + expect(await store.getTaskRecord('rec_1')).toBeUndefined(); + expect(await store.listTaskRecords({ protocol: 'a2a', groupId: 'ctx_1' })).toEqual([]); + }); + + it('lists task records by the instant an offset updatedAt names', async () => { + // 00:30+01:00 is 23:30Z the day before; raw timestamp strings sort in the wrong order + await store.putTaskRecord(record('earlier', '2026-01-01T00:30:00+01:00'), { maxRecords: 2 }); + await store.putTaskRecord(record('later', '2026-01-01T00:10:00.000Z'), { maxRecords: 2 }); + const listed = await store.listTaskRecords({ protocol: 'a2a', groupId: 'ctx_1' }); + expect(listed.map((r) => [r.id, r.updatedAt])).toEqual([ + ['later', '2026-01-01T00:10:00.000Z'], + ['earlier', '2025-12-31T23:30:00.000Z'], + ]); + }); + + it('deletes expired task records when a writable store starts', async () => { + await store.putTaskRecord(record('rec_1', isoAt(0), isoAt(MINUTE)), { maxRecords: 1 }); + await store.close(); + clock.advance(MINUTE + 1); + store = createSqliteReceiptStore({ path, clock }); + await store.init(); + expect(dumpTables(path).task_records).toEqual([]); + }); }); From cbf86bf77845b4376271eb8288fc7f16dca954dc Mon Sep 17 00:00:00 2001 From: Revinand Date: Sun, 22 Nov 2026 18:31:59 +0100 Subject: [PATCH 04/17] feat(config): add A2A task retention --- docs/configuration.md | 4 +- docs/contracts.md | 10 ++- src/config/schema/normalize.ts | 33 ++++++++- src/config/schema/raw.ts | 7 ++ src/config/schema/types.ts | 12 +++- src/protocols/a2a/constants.ts | 6 ++ tests/conformance/a2a/support/gateway.ts | 92 +++--------------------- tests/unit/config/schema.test.ts | 57 +++++++++++++++ 8 files changed, 135 insertions(+), 86 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 1dd0407..f61b41e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -932,7 +932,9 @@ serves, including the A2A Agent Card and ACP discovery paths · a `protocols.mcp.registry` value that breaks the field rules above · an ACP checkout mapping that is incomplete, names a missing or non-`acp` resource, reuses one resource for two operations, or maps a paid one · an ACP idempotency retention -below 24 hours · an invalid or zero `payTo`/`asset`/`recipient` · an +below 24 hours · a `protocols.a2a.tasks.retentionHours` that is not an integer +from 1 to 8760, or a `protocols.a2a.tasks.maxRetained` that is not an integer +from 1 to 1,000,000 · an invalid or zero `payTo`/`asset`/`recipient` · an `x402.accepts` list that is empty or on a resource that cannot use it · a `mimeType` that is not a media type, or on a resource that is not fixed-price with `x402` in `payments` · an `idempotency` block on a resource that is not diff --git a/docs/contracts.md b/docs/contracts.md index 92bf22b..948c5b4 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -521,6 +521,10 @@ persistence must not fail the commerce flow. `agent-commerce export mcp-registry` and `doctor --registry` use the metadata. `runGateway` passes `name` and `version` to the MCP adapter as `serverName` and `serverVersion`; an adapter built without them keeps its defaults. +- 2.9.0: `GatewayConfig.protocols.a2a.tasks` contains only limits set in + `protocols.a2a.tasks`. The block and individual keys stay absent when + omitted. Config loading requires integers from 1 to 8760 for `retentionHours` + and from 1 to 1,000,000 for `maxRetained`. ### Authorization and AP2 @@ -1083,7 +1087,11 @@ export interface GatewayConfig { readonly description: string; }; }; - readonly a2a: { readonly enabled: boolean; readonly mountPath: string }; + readonly a2a: { + readonly enabled: boolean; + readonly mountPath: string; + readonly tasks?: { readonly retentionHours?: number; readonly maxRetained?: number }; + }; readonly acp: AcpProtocolConfig; }; readonly resources: readonly CommerceResource[]; diff --git a/src/config/schema/normalize.ts b/src/config/schema/normalize.ts index 0cacdae..0a47d25 100644 --- a/src/config/schema/normalize.ts +++ b/src/config/schema/normalize.ts @@ -2,19 +2,49 @@ import type { CommerceResource } from '../../core'; import { CommerceError } from '../../core'; import { bazaarMetadata } from '../../payments/x402/provider/bazaar'; +import { A2A_MAX_RETAINED_TASKS, A2A_TASK_RETENTION_HOURS } from '../../protocols/a2a/constants'; import { publicEndpointUrl } from '../../protocols/http'; import { normalizeAcp, validateAcpCheckoutMapping } from './acp'; import { normalizeAp2, validateLegacyStoresIsolated } from './ap2'; import { normalizeMpp } from './mpp'; import { isHttpUrl, type RawConfig, SUPPORTED_CONFIG_VERSION } from './raw'; import { normalizeResource, servingRailOf } from './resources'; -import type { GatewayConfig, NormalizedProtocols } from './types'; +import type { A2aProtocolConfig, GatewayConfig, NormalizedProtocols } from './types'; import { toBoolean, toNumber } from './values'; import { normalizeX402 } from './x402'; // Applied when `protocols.a2a` is absent or names no mount const DEFAULT_A2A_MOUNT_PATH = '/a2a'; +// Preserve configured limits and leave unset keys absent +function normalizeA2aTasks( + tasks: NonNullable['tasks'], +): Pick { + if (tasks === undefined) return {}; + return { + tasks: { + ...(tasks.retentionHours !== undefined + ? { + retentionHours: toNumber( + tasks.retentionHours, + 'protocols.a2a.tasks.retentionHours', + A2A_TASK_RETENTION_HOURS, + ), + } + : {}), + ...(tasks.maxRetained !== undefined + ? { + maxRetained: toNumber( + tasks.maxRetained, + 'protocols.a2a.tasks.maxRetained', + A2A_MAX_RETAINED_TASKS, + ), + } + : {}), + }, + }; +} + export function normalize(raw: RawConfig): GatewayConfig { const protocols = { http: { enabled: toBoolean(raw.protocols.http.enabled, 'protocols.http.enabled') }, @@ -26,6 +56,7 @@ export function normalize(raw: RawConfig): GatewayConfig { a2a: { enabled: toBoolean(raw.protocols.a2a?.enabled ?? false, 'protocols.a2a.enabled'), mountPath: raw.protocols.a2a?.mountPath ?? DEFAULT_A2A_MOUNT_PATH, + ...normalizeA2aTasks(raw.protocols.a2a?.tasks), }, acp: normalizeAcp(raw.protocols.acp), }; diff --git a/src/config/schema/raw.ts b/src/config/schema/raw.ts index 090e93c..50973ee 100644 --- a/src/config/schema/raw.ts +++ b/src/config/schema/raw.ts @@ -174,6 +174,13 @@ const ProtocolsSchema = z .object({ enabled: BooleanOrString, mountPath: MountPathSchema.optional(), + tasks: z + .object({ + retentionHours: NumberOrString.optional(), + maxRetained: NumberOrString.optional(), + }) + .strict() + .optional(), }) .strict() .optional(), diff --git a/src/config/schema/types.ts b/src/config/schema/types.ts index 7eb36ae..122412d 100644 --- a/src/config/schema/types.ts +++ b/src/config/schema/types.ts @@ -69,7 +69,7 @@ export interface GatewayConfig { readonly protocols: { readonly http: { readonly enabled: boolean }; readonly mcp: McpProtocolConfig; - readonly a2a: { readonly enabled: boolean; readonly mountPath: string }; + readonly a2a: A2aProtocolConfig; readonly acp: AcpProtocolConfig; }; /** Canonical resources, already normalized */ @@ -151,6 +151,14 @@ export interface GatewayConfig { readonly authorization?: { readonly ap2: Ap2AuthorizationConfig }; } +/** `protocols.a2a` after normalization */ +export interface A2aProtocolConfig { + readonly enabled: boolean; + readonly mountPath: string; + /** Set only when `protocols.a2a.tasks` is configured; unset limits stay absent */ + readonly tasks?: { readonly retentionHours?: number; readonly maxRetained?: number }; +} + /** `protocols.mcp` after normalization */ export interface McpProtocolConfig { readonly enabled: boolean; @@ -169,6 +177,6 @@ export interface McpProtocolConfig { export interface NormalizedProtocols { readonly http: { readonly enabled: boolean }; readonly mcp: McpProtocolConfig; - readonly a2a: { readonly enabled: boolean; readonly mountPath: string }; + readonly a2a: A2aProtocolConfig; readonly acp: AcpProtocolConfig; } diff --git a/src/protocols/a2a/constants.ts b/src/protocols/a2a/constants.ts index 4ce9879..97180cc 100644 --- a/src/protocols/a2a/constants.ts +++ b/src/protocols/a2a/constants.ts @@ -87,3 +87,9 @@ export const A2A_TASK_STATE_INPUT_REQUIRED = 'TASK_STATE_INPUT_REQUIRED'; /** Extension activation header, a comma-separated list of extension URIs */ export const A2A_EXTENSIONS_HEADER = 'a2a-extensions'; + +/** Bounds for `protocols.a2a.tasks.retentionHours`, the retention period for answered tasks */ +export const A2A_TASK_RETENTION_HOURS = { min: 1, max: 8760 } as const; + +/** Bounds for `protocols.a2a.tasks.maxRetained`, the cap on unexpired task records */ +export const A2A_MAX_RETAINED_TASKS = { min: 1, max: 1_000_000 } as const; diff --git a/tests/conformance/a2a/support/gateway.ts b/tests/conformance/a2a/support/gateway.ts index 3f4c28b..b325c6a 100644 --- a/tests/conformance/a2a/support/gateway.ts +++ b/tests/conformance/a2a/support/gateway.ts @@ -1,100 +1,27 @@ /** * A real, listening gateway for the SDK to talk to. * - * The official client uses global `fetch` against a URL, so unlike the - * `inject()`-based integration tests this suite needs a socket. The gateway, - * pipeline and A2A adapter are real; the merchant backend, payment provider - * and receipt store are faked, since the endpoint's conformance does not - * depend on them. + * The official client sends requests through global `fetch`, so the suite + * needs a listening socket instead of `inject()`. It runs the gateway, + * pipeline and A2A adapter with an in-memory SQLite receipt store. The merchant + * backend and payment provider are faked to isolate protocol behavior. */ import { createServer } from 'node:net'; import type { GatewayConfig } from '../../../../src/config'; import type { AdapterDescriptor, BackendExecutor, - CommerceEvent, - CommerceReceipt, - PaymentAttempt, PaymentContext, PaymentProvider, PaymentRequirement, PaymentResult, PaymentSettlementContext, PaymentVerificationContext, - ReceiptStore, } from '../../../../src/core'; import { CommerceError } from '../../../../src/core'; import { createGateway, type GatewayInstance } from '../../../../src/gateway'; import { createA2aAdapter } from '../../../../src/protocols/a2a'; - -const descriptor: AdapterDescriptor = { - name: 'fake-store', - kind: 'storage', - implementationVersion: '0.0.0-test', - supportedSpec: 'n/a', - capabilities: [], - status: 'experimental', -}; - -function createFakeStore(): ReceiptStore { - const events: CommerceEvent[] = []; - const receipts: CommerceReceipt[] = []; - const attempts = new Map(); - return { - async init() {}, - async appendEvent(event) { - events.push(event); - }, - async reservePaymentAttempt(reservation) { - const attempt: PaymentAttempt = { - id: `attempt-${attempts.size + 1}`, - requestId: reservation.requestId, - resourceId: reservation.resourceId, - provider: reservation.provider, - replayKey: reservation.replayKey, - status: 'reserved', - amount: reservation.amount, - currency: reservation.currency, - createdAt: '2026-01-01T00:00:00.000Z', - updatedAt: '2026-01-01T00:00:00.000Z', - }; - attempts.set(reservation.replayKey, attempt); - return attempt; - }, - async updatePaymentAttempt() {}, - async saveReceipt(receipt) { - receipts.push(receipt); - }, - async getReceipt(id) { - return receipts.find((r) => r.id === id); - }, - async listReceipts() { - return receipts; - }, - async countReceipts() { - return receipts.length; - }, - async countUndeliveredReceipts() { - return 0; - }, - async countUncertainPaymentAttempts() { - return [...attempts.values()].filter( - (a) => a.status === 'settlement-uncertain' || a.status === 'failed', - ).length; - }, - async listEvents() { - return events; - }, - async listPaymentAttempts() { - return [...attempts.values()]; - }, - async health() { - return { status: 'pass', checkedAt: '2026-01-01T00:00:00.000Z' }; - }, - async close() {}, - descriptor, - }; -} +import { createSqliteReceiptStore } from '../../../../src/storage/receipts'; /** Fixed merchant response, so an assertion about the artifact is about the artifact */ export const MERCHANT_BODY = { city: 'Berlin', forecast: 'sunny', celsius: 21 }; @@ -279,16 +206,18 @@ export async function startConformanceGateway(): Promise { }; const backend = countingBackend(); const provider = fakeProvider(); + const store = createSqliteReceiptStore({ path: ':memory:' }); + await store.init(); const gateway = await createGateway({ config: gatewayConfig, - store: createFakeStore(), + store, paymentProviders: [provider], - // Built as src/gateway/run.ts builds it, so the suite certifies the - // adapter production runs + // Match the adapter setup in src/gateway/run.ts, including its store protocolAdapters: [ createA2aAdapter({ mountPath: gatewayConfig.protocols.a2a.mountPath, agentName: gatewayConfig.merchant.name, + store, }), ], backend, @@ -302,6 +231,7 @@ export async function startConformanceGateway(): Promise { settleCalls: provider.settleCalls, async close() { await gateway.close(); + await store.close(); }, }; } diff --git a/tests/unit/config/schema.test.ts b/tests/unit/config/schema.test.ts index 5c6ed01..73fb6f5 100644 --- a/tests/unit/config/schema.test.ts +++ b/tests/unit/config/schema.test.ts @@ -1620,6 +1620,63 @@ describe('protocols.a2a', () => { const config = parseConfig(withA2a({ enabled: false, mountPath: '/mcp' }), {}); expect(config.protocols.a2a.enabled).toBe(false); }); + + describe('tasks', () => { + it('keeps the task limits it sets, including env-substituted strings', () => { + const config = parseConfig( + withA2a({ + enabled: true, + tasks: { retentionHours: '${A2A_RETENTION}', maxRetained: 5000 }, + }), + { A2A_RETENTION: '48' }, + ); + expect(config.protocols.a2a).toEqual({ + enabled: true, + mountPath: '/a2a', + tasks: { retentionHours: 48, maxRetained: 5000 }, + }); + }); + + it('leaves an unset limit absent for the adapter default', () => { + const config = parseConfig(withA2a({ enabled: true, tasks: { maxRetained: 1 } }), {}); + expect(config.protocols.a2a.tasks).toEqual({ maxRetained: 1 }); + }); + + it.each([ + ['retentionHours', 1], + ['retentionHours', 8760], + ['maxRetained', 1], + ['maxRetained', 1_000_000], + ])('accepts %s at its bound %s', (key, value) => { + const config = parseConfig(withA2a({ enabled: true, tasks: { [key]: value } }), {}); + expect(config.protocols.a2a.tasks).toEqual({ [key]: value }); + }); + + it.each([ + ['retentionHours', 0, '>= 1'], + ['retentionHours', 8761, '<= 8760'], + ['retentionHours', '8761', '<= 8760'], + ['retentionHours', 1.5, 'must be an integer'], + ['retentionHours', 'soon', 'decimal digits'], + ['maxRetained', 0, '>= 1'], + ['maxRetained', 1_000_001, '<= 1000000'], + ['maxRetained', -1, '>= 1'], + ])('refuses %s %s', (key, value, message) => { + expectConfigInvalid( + () => parseConfig(withA2a({ enabled: true, tasks: { [key]: value } }), {}), + `protocols.a2a.tasks.${key}`, + message, + ); + }); + + it('rejects an unknown key inside the tasks block', () => { + expectConfigInvalid( + () => parseConfig(withA2a({ enabled: true, tasks: { history: true } }), {}), + 'protocols.a2a.tasks', + /history/, + ); + }); + }); }); describe('protocols.acp', () => { From 536c4c5c6d8093b6bd817bac18424bee2679c9f7 Mon Sep 17 00:00:00 2001 From: Revinand Date: Sun, 22 Nov 2026 19:10:28 +0100 Subject: [PATCH 05/17] feat(a2a): validate every parameter and accept proto field names --- docs/protocols/a2a.md | 41 ++- docs/security.md | 11 +- src/protocols/a2a/adapter.ts | 60 +++- src/protocols/a2a/message-mapping.ts | 14 +- src/protocols/a2a/params.ts | 317 +++++++++++++++++++ tests/conformance/a2a/params.test.ts | 201 ++++++++++++ tests/conformance/a2a/support/gateway.ts | 32 +- tests/integration/a2a-over-gateway.test.ts | 3 +- tests/integration/a2a-x402-extension.test.ts | 48 +++ tests/unit/protocols-a2a/params.test.ts | 175 ++++++++++ 10 files changed, 862 insertions(+), 40 deletions(-) create mode 100644 src/protocols/a2a/params.ts create mode 100644 tests/conformance/a2a/params.test.ts create mode 100644 tests/unit/protocols-a2a/params.test.ts diff --git a/docs/protocols/a2a.md b/docs/protocols/a2a.md index 4d31f54..7d6f288 100644 --- a/docs/protocols/a2a.md +++ b/docs/protocols/a2a.md @@ -60,6 +60,33 @@ parts, multipart messages, non-user roles, and task or context continuation. The text and file refusals name the expected part shape. A payment message can resume a pending x402 extension task. +## Request parameters + +The adapter validates the parameters below before reading the task store or +calling a backend. For these parameters, `null` counts as absent. Type errors +return `-32602`, except that any non-null +`configuration.taskPushNotificationConfig` returns `-32003`. Unknown parameters +are ignored after field-name checks. + +Requests may use proto field names, such as `context_id` for `contextId`. +The adapter converts request, `configuration`, message and part keys to JSON +names. Keys within `data` and `metadata` values stay unchanged, preserving +merchant input and extension metadata. Sending both names for a field returns +`-32602`. Integer parameters accept JSON numbers or decimal integer strings. + +| Parameter | Accepted | Otherwise | +| ---------------------------------------------- | ------------------------------------------------------------------------------------- | --------- | +| `tenant` | absent or `""` | `-32004` | +| `configuration.acceptedOutputModes` | absent, empty, or a list that includes `application/json`, `application/*` or `*/*` | `-32005` | +| `configuration.taskPushNotificationConfig` | absent | `-32003` | +| `configuration.historyLength`, `historyLength` | absent or an integer from 0 to 2,147,483,647; ignored because no task history is kept | `-32602` | +| `configuration.returnImmediately` | absent or a boolean; ignored, so responses remain synchronous | `-32602` | +| `metadata` on `SendMessage` and `CancelTask` | absent or an object; ignored | `-32602` | +| `id` on `GetTask` and `CancelTask` | a non-empty string | `-32602` | + +The adapter also validates `ListTasks` filters and pagination parameters. +A valid request returns `-32004`; listing tasks is unsupported. + ## x402 extension A client activates the extension with @@ -170,13 +197,13 @@ The adapter returns JSON-RPC errors for invalid requests and A2A features it cannot serve. Alongside `-32700`, `-32600`, `-32601`, `-32602` and `-32603`, it uses these A2A codes: -| Code | A2A error | Returned for | -| -------- | ----------------------------------- | ----------------------------------------------------------------------------------------------- | -| `-32001` | `TaskNotFoundError` | an unknown, expired or completed `taskId`; `GetTask` and `CancelTask` for any id | -| `-32003` | `PushNotificationNotSupportedError` | the four push notification configuration methods | -| `-32004` | `UnsupportedOperationError` | other unsupported methods and message features listed below | -| `-32005` | `ContentTypeNotSupportedError` | a text, file, inline-byte or URL part, or a non-JSON `mediaType` | -| `-32009` | `VersionNotSupportedError` | an unsupported version; a missing header and parameter, or an empty header, is treated as `0.3` | +| Code | A2A error | Returned for | +| -------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| `-32001` | `TaskNotFoundError` | an unknown, expired or completed `taskId`; `GetTask` and `CancelTask` for any valid `id` | +| `-32003` | `PushNotificationNotSupportedError` | the four push notification configuration methods; any non-null `configuration.taskPushNotificationConfig` | +| `-32004` | `UnsupportedOperationError` | other unsupported methods; a non-empty `tenant`; the message features listed below | +| `-32005` | `ContentTypeNotSupportedError` | a text, file, inline-byte or URL part; a non-JSON `mediaType`; an `acceptedOutputModes` list that excludes JSON | +| `-32009` | `VersionNotSupportedError` | an unsupported version; a missing header and parameter, or an empty header, is treated as `0.3` | Multipart messages, a `contextId` and non-empty `referenceTaskIds` return `-32004`. Missing `messageId` or a non-user role returns `-32602`. A request diff --git a/docs/security.md b/docs/security.md index 7f5d672..f3b7e42 100644 --- a/docs/security.md +++ b/docs/security.md @@ -343,7 +343,7 @@ real funds. | **a generated Bazaar example the gateway would refuse, silently dropping the listing** | config loading omits the resource's metadata and warns with its id, affected surfaces and reason; payment behavior is unchanged | `tests/unit/payments-x402/bazaar.test.ts`, `tests/unit/config/schema.test.ts`, `tests/integration/x402-bazaar.test.ts` | | **an input schema the gateway accepts and a facilitator cannot compile, silently dropping the listing** | config loading omits metadata for malformed keyword values detected by the JSON Schema 2020-12 checks or an empty `enum`; warnings name the keyword and its path | `tests/unit/core/execution/validation.test.ts`, `tests/unit/payments-x402/bazaar.test.ts` ("leaves out a resource whose input schema has ..., which upstream validation refuses") | | **a facilitator that does not implement Bazaar refusing a payment over the forwarded fields, and the buyer blamed for it** | verify and settle forward `resource` and `extensions.bazaar` only to a remote facilitator that lists `bazaar` in `/supported`; when that read fails or takes over one second, the call sends neither | `tests/unit/payments-x402/bazaar-challenge.test.ts` ("Bazaar metadata and the facilitator /supported list"), `tests/integration/x402-bazaar.test.ts`, `tests/e2e/payment/x402-bazaar.e2e.test.ts` | -| **a facilitator rejecting a Bazaar listing unnoticed, or adding unbounded reason text to the gateway log** | the gateway logs a `rejected` outcome in `EXTENSION-RESPONSES` at `warn` once per resource and provider instance; it redacts URLs in the reason to scheme and host before truncating it to 200 characters. This metadata outcome does not change the payment result | `tests/unit/payments-x402/bazaar-challenge.test.ts` ("Bazaar outcome from the facilitator") | +| **a facilitator rejecting a Bazaar listing unnoticed, or adding unbounded reason text to the gateway log** | the gateway logs a `rejected` outcome in `EXTENSION-RESPONSES` at `warn` once per resource and provider instance; it redacts URLs in the reason to scheme and host before truncating it to 200 characters. This metadata outcome does not change the payment result | `tests/unit/payments-x402/bazaar-challenge.test.ts` ("Bazaar outcome from the facilitator") | | **a resource served on MPP described in config as an x402 listing** | public URLs and Bazaar metadata are built only for resources whose first enabled rail is x402; a resource that lists `x402` behind an enabled `mpp` gets a warning naming the serving rail | `tests/unit/config/schema.test.ts`, `tests/integration/x402-bazaar.test.ts` | | **an AP2 mandate approved for one x402 offer, presented with a proof for another** | selected destination, network or asset fails mandate binding; no settlement | `tests/unit/core/execution/pipeline-authorization.test.ts` | | **an EIP-3009 authorization signed for one EVM chain, presented as another chain's offer** | `invalid_exact_evm_signature`: signature fails against the other chain's EIP-712 domain; neither chain's balances change | `tests/e2e/payment/x402-multichain.e2e.test.ts` | @@ -446,7 +446,7 @@ real funds. | **an in-flight `reserved` attempt younger than `--min-age`** | excluded from reconciliation candidates; the default minimum age is 15 minutes. Manual resolution also refuses a `reserved` attempt younger than 15 minutes (`too_recent`) | `tests/unit/core/execution/reconcile.test.ts`, `tests/unit/core/execution/resolve.test.ts` | | **a `reserved` AP2 hold whose request recorded no payment attempt** | eligible for release through an enabled AP2 provider once its last update is older than `--min-age`; the gateway reserves an attempt before calling settlement. Current or replaced attempts exclude a hold. Dry runs report scanned holds without releasing them. An omitted or empty list of authorization providers skips both hold scans | `tests/unit/core/execution/reconcile.test.ts` | | **`reconcile` or `resolve` with AP2 enabled and an existing, unimported AP2 file** | `STORAGE_ERROR` before payment or hold updates; these commands do not import legacy files. The receipt store is initialized after a read-only schema check | `tests/unit/cli/resolve.test.ts` | -| **`reconcile` or `resolve` on a receipt database with an older schema, including files from 2.5 or 2.8** | `STORAGE_ERROR` before payment, hold or schema updates; the message directs the operator to run `agent-commerce backup`, then start the gateway once | `tests/unit/cli/reconcile.test.ts` | +| **`reconcile` or `resolve` on a receipt database with an older schema, including files from 2.5 or 2.8** | `STORAGE_ERROR` before payment, hold or schema updates; the message directs the operator to run `agent-commerce backup`, then start the gateway once | `tests/unit/cli/reconcile.test.ts` | | **`reconcile`, `resolve` or `doctor` run beside a live gateway** | These commands neither import legacy files nor recover ACP claims. `reconcile` and `resolve` open the receipt store without legacy import options; `doctor` opens it read-only. They leave the gateway's existing in-flight ACP claims unchanged | `tests/unit/cli/reconcile.test.ts`, `tests/unit/cli/doctor-storage.test.ts` | | **reconciliation calling a facilitator or broadcasting** | x402 and MPP reconciliation read the configured offer's RPC without calling the facilitator or broadcasting | `tests/e2e/payment/x402-reconcile.e2e.test.ts`, `tests/e2e/payment/x402-solana.e2e.test.ts`, `tests/e2e/payment/x402-near.e2e.test.ts` | | **an attempt without a recorded locator** | x402 and MPP return `unknown` (`no_locator`), leaving the attempt unresolved | `tests/unit/payments-x402/reconcile.test.ts`, `tests/unit/core/execution/reconcile.test.ts` | @@ -496,6 +496,9 @@ real funds. | **an A2A `GetTask` or `CancelTask` naming a pending x402 task** | `-32001` `TaskNotFoundError`; the task stays payable | `tests/integration/a2a-x402-extension.test.ts` | | **an A2A 0.x follow-up, with a non-user role, on a pending task** | `-32602`; the task stays pending | same | | **an A2A message carrying a large array of invalid parts or task references** | refused by its length (`PROTOCOL_UNSUPPORTED`) before any element is validated, so no validation issue is built per element | `tests/unit/protocols-a2a/message-mapping.test.ts` | +| **an A2A field sent under its proto and JSON names, such as `context_id` beside `contextId`** | `-32602` identifies both spellings before task-store reads or backend calls | `tests/conformance/a2a/params.test.ts` | +| **normalizing A2A proto field names inside merchant input or x402 extension metadata** | normalization changes request, `configuration`, message and part keys; keys within `data` and `metadata` values, including `_payment` and `_authorization`, stay unchanged | `tests/integration/a2a-x402-extension.test.ts` | +| **an A2A request with a non-null push notification config, an output list that excludes JSON, or a non-empty `tenant`** | `-32003`, `-32005` or `-32004`, respectively, before task-store reads or backend calls | `tests/conformance/a2a/params.test.ts` | | **an AP2 mandate on an x402 extension payment message beside another resource or input** | verified against the stored purchase; the other resource and input are ignored | same | | **an MCP placeholder `_payment` beside a real proof in `_meta`** | the `_meta` proof settles; `_payment` is ignored | `tests/integration/mcp-payment-bindings.test.ts` | | **an MCP `_meta["x402/payment"]` string that is not base64 `PaymentPayload` JSON** | `PAYMENT_INVALID` with a fresh challenge; nothing settles | same | @@ -529,7 +532,7 @@ real funds. | **a deprecated store key removed, or its file missing, before the first 2.6.0 start** | `start` returns `STORAGE_ERROR` for an enabled feature with past-use evidence and no recorded import or prior check. An empty file or `:memory:` explicitly accepts the loss; `doctor` reports that refusal as `FAIL` | `tests/unit/storage-receipts/legacy-import.test.ts`, `tests/unit/cli/doctor-storage.test.ts` | | **an import failing part way** | the failed source's rows and import marker roll back together; earlier source imports remain committed. `start` stops with `STORAGE_ERROR`, releases acquired locks and retries the failed source on the next start | same | | **a 2.5 gateway writing a deprecated file after the import** | refused while `start` holds the file's write lock, which is released at shutdown | same | -| **an older gateway opening a migrated receipt database (2.5 after a 2.6.0 upgrade, or 2.8 after a 2.9.0 upgrade)** | refused by its schema version check; the file is unchanged | `tests/unit/storage-receipts/migration-v5.test.ts` | +| **an older gateway opening a migrated receipt database (2.5 after a 2.6.0 upgrade, or 2.8 after a 2.9.0 upgrade)** | refused by its schema version check; the file is unchanged | `tests/unit/storage-receipts/migration-v5.test.ts` | | **a free resource configured to require a mandate** | refused at config load, and again on the execution path | `tests/unit/config/ap2.test.ts`, `tests/unit/core/execution` | | **an oversized `Agent-Authorization` header** | `AUTHORIZATION_INVALID`; the pipeline is not called | `tests/integration/authorization-carrier.test.ts` | | **an MPP challenge edited after issue, or signed with another gateway's secret** | `challenge_not_issued` | `tests/unit/payments-mpp/provider.test.ts` | @@ -589,7 +592,7 @@ real funds. | **`doctor` reporting a gateway that answered as unreachable** | marks `Gateway` `unreachable` for recognized transport failures, including refused or reset connections and timeouts. Unresolvable hostnames, ports rejected by fetch, non-2xx `/health` responses and Host refusals fail unmarked; checks that need the discovery document are `skipped`. Responses with unusable document content leave those checks unmarked | `tests/unit/cli/doctor-certainty.test.ts` ("when %s", "says a gateway that answered non-2xx is unhealthy, not unreachable"), `tests/integration/doctor-certainty.test.ts` ("leaves Gateway unmarked, and says why, when fetch refuses the port") | | **the `doctor` Secrets check printing a value or a default** | reports placeholder names in text and JSON, never variable values or defaults | `tests/unit/cli/doctor-certainty.test.ts` ("FAILs naming every missing variable, and prints no value or default"), `tests/unit/config/env.test.ts` ("returns names only: no value and no default") | | **an MCP Registry answer injecting text into `doctor` output** | `doctor --registry` names differing fields and uses fixed messages for known lifecycle statuses, without echoing arbitrary answer values or request error messages in text or JSON | `tests/unit/cli/doctor-registry.test.ts` ("prints no value from a hostile answer, in text or JSON", "leaves a TLS failure unmarked and does not print its message") | -| **`doctor --registry` sending more than the server name** | sends a GET to `/v0.1/servers//versions/latest?include_deleted=true` with no custom headers or body, only when the flag is set and config yields a listing | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "adds no check and sends nothing to the registry without the flag", "sends nothing for an http public URL") | +| **`doctor --registry` sending more than the server name** | sends a GET to `/v0.1/servers//versions/latest?include_deleted=true` with no custom headers or body, only when the flag is set and config yields a listing | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "adds no check and sends nothing to the registry without the flag", "sends nothing for an http public URL") | | **another server name listing the gateway's URL, taken for the merchant's listing** | `doctor --registry` looks up the configured name only and reports a response with another name as a difference in `name` | `tests/unit/cli/doctor-registry.test.ts` ("asks for the configured name only, with no header or body", "reports a listing under another name") | | **a support record citing a test or doc file that does not exist** | the drift check in `npm test` fails and names the record and the missing path | `tests/integration/support-record.test.ts` ("names the place of %s") | | **a generated support table or list edited by hand in the README or docs** | the drift check fails and names the file and region; `npm run support:write` restores the region from the records | `tests/integration/support-record.test.ts` ("names the place of %s", "--write restores a hand-edited region and refuses a file with missing markers") | diff --git a/src/protocols/a2a/adapter.ts b/src/protocols/a2a/adapter.ts index 6cb41ec..a937af6 100644 --- a/src/protocols/a2a/adapter.ts +++ b/src/protocols/a2a/adapter.ts @@ -60,6 +60,13 @@ import { parseJsonRpcRequest, } from './jsonrpc'; import { type A2aInvocation, parseInvocation } from './message-mapping'; +import { + readCancelTaskParams, + readGetTaskParams, + readListTasksParams, + readSendMessageParams, + type SendMessageParams, +} from './params'; import { resumePayment, taskResult } from './payment-resume'; import { completedTask, @@ -106,6 +113,27 @@ export interface A2aAdapterOptions { readonly store?: ReceiptStore; } +// Parameter validators for task operations +const TASK_PARAM_READERS = new Map) => unknown>([ + ['GetTask', readGetTaskParams], + ['CancelTask', readCancelTaskParams], + ['ListTasks', readListTasksParams], +]); + +// Map parameter and message failures to JSON-RPC errors. Keep CommerceError +// messages; use a generic message for other thrown values. +function refusal(id: JsonRpcId, err: unknown): Record { + const error = toCommerceError(err); + const a2aErrorCode = error.details?.['a2aErrorCode']; + const code = + typeof a2aErrorCode === 'number' + ? a2aErrorCode + : error.code === 'PROTOCOL_UNSUPPORTED' + ? A2A_ERROR_UNSUPPORTED_OPERATION + : JSONRPC_INVALID_PARAMS; + return jsonRpcError(id, code, error.message); +} + const DEFAULT_AGENT_DESCRIPTION = 'Agent Commerce Gateway: canonical commerce resources exposed as A2A skills.'; @@ -321,6 +349,15 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { `A2A method "${method}" is not supported: this agent does not support push notifications.`, ); } + // Validate task parameters before returning task-not-found or unsupported-operation errors + const readTaskParams = TASK_PARAM_READERS.get(method); + if (readTaskParams !== undefined) { + try { + readTaskParams(isRecord(params) ? params : {}); + } catch (err) { + return refusal(id, err); + } + } if (A2A_TASK_LOOKUP_METHODS.includes(method)) { return jsonRpcError( id, @@ -339,24 +376,21 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { return jsonRpcError(id, JSONRPC_METHOD_NOT_FOUND, `Unknown method "${method}".`); } - const resumed = await resumePayment(this.context, this.pendingPayments, id, params); + let request: SendMessageParams; + try { + request = readSendMessageParams(isRecord(params) ? params : {}); + } catch (err) { + return refusal(id, err); + } + + const resumed = await resumePayment(this.context, this.pendingPayments, id, request.params); if (resumed !== undefined) return resumed; let invocation: ReturnType; try { - invocation = parseInvocation(params); + invocation = parseInvocation(request.params); } catch (err) { - const error = toCommerceError(err); - const a2aErrorCode = error.details?.['a2aErrorCode']; - const code = - typeof a2aErrorCode === 'number' - ? a2aErrorCode - : error.code === 'PROTOCOL_UNSUPPORTED' - ? A2A_ERROR_UNSUPPORTED_OPERATION - : JSONRPC_INVALID_PARAMS; - // CommerceError messages are written for a client; nothing else is - // relayed - return jsonRpcError(id, code, error.message); + return refusal(id, err); } return this.execute(id, invocation, x402Extension); diff --git a/src/protocols/a2a/message-mapping.ts b/src/protocols/a2a/message-mapping.ts index a387907..9fac6cf 100644 --- a/src/protocols/a2a/message-mapping.ts +++ b/src/protocols/a2a/message-mapping.ts @@ -25,10 +25,10 @@ * to make. */ import { z } from 'zod'; -import { CommerceError } from '../../core'; import { isRecord } from '../../core/is-record'; import { A2A_JSON_MEDIA_TYPE } from './constants'; import { A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED, A2A_ERROR_TASK_NOT_FOUND } from './jsonrpc'; +import { invalid, unsupported } from './params'; // The only role a request message may carry. A2A v1 spells roles this way const A2A_USER_ROLE = 'ROLE_USER'; @@ -75,18 +75,6 @@ const ParamsSchema = z.object({ contextId: z.string().optional(), }); -function invalid(message: string): CommerceError { - return new CommerceError('INPUT_INVALID', message); -} - -function unsupported(message: string, a2aErrorCode?: number): CommerceError { - return new CommerceError( - 'PROTOCOL_UNSUPPORTED', - message, - a2aErrorCode !== undefined ? { details: { a2aErrorCode } } : {}, - ); -} - /** * Continuation is refused rather than ignored: a caller resuming a task would * otherwise get a fresh, independently billed execution back and no signal diff --git a/src/protocols/a2a/params.ts b/src/protocols/a2a/params.ts new file mode 100644 index 0000000..2ccb40b --- /dev/null +++ b/src/protocols/a2a/params.ts @@ -0,0 +1,317 @@ +/** + * Normalize field names and validate parameters for `SendMessage`, `GetTask`, + * `ListTasks` and `CancelTask` before task lookup or execution. A2A 1.0.1 + * section 3.3.2 requires parameter validation before processing. + * + * Accept proto names (`context_id`) and JSON names (`contextId`). Normalize + * request, `configuration`, message and part keys while preserving keys within + * `data` and `metadata` values, which hold merchant input and extension JSON. + * Reject fields sent under both names to avoid choosing between their values. + * + * Ignore unknown parameters after checking for name collisions (section 5.7). + * Treat `null` as absent in the request and configuration parameters read here; + * message fields are validated separately. + */ +import { CommerceError } from '../../core'; +import { isRecord } from '../../core/is-record'; +import { A2A_JSON_MEDIA_TYPE } from './constants'; +import { + A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED, + A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED, +} from './jsonrpc'; + +/** Create an error for a malformed parameter, mapped to JSON-RPC invalid params */ +export function invalid(message: string): CommerceError { + return new CommerceError('INPUT_INVALID', message); +} + +/** + * Create an error for a valid A2A request this adapter cannot serve. Map it to + * `UnsupportedOperationError` unless `a2aErrorCode` specifies another error. + */ +export function unsupported(message: string, a2aErrorCode?: number): CommerceError { + return new CommerceError( + 'PROTOCOL_UNSUPPORTED', + message, + a2aErrorCode !== undefined ? { details: { a2aErrorCode } } : {}, + ); +} + +// Remove an underscore and uppercase the following lowercase letter or digit +const PROTO_NAME_WORD = /_([a-z0-9])/g; + +// Normalize one object's field names and reject collisions +function jsonNames(value: Record, where: string): Record { + const sentAs = new Map(); + const entries: [string, unknown][] = []; + for (const [key, field] of Object.entries(value)) { + const name = key.replace(PROTO_NAME_WORD, (_, next: string) => next.toUpperCase()); + const earlier = sentAs.get(name); + if (earlier !== undefined) { + throw invalid(`${where} sends "${earlier}" and "${key}", two names for one field: send one.`); + } + sentAs.set(name, key); + entries.push([name, field]); + } + return Object.fromEntries(entries); +} + +function read(params: Record, key: string): unknown { + const value = params[key]; + return value === null ? undefined : value; +} + +function checkTenant(params: Record): void { + const tenant = read(params, 'tenant'); + if (tenant === undefined || tenant === '') return; + if (typeof tenant !== 'string') throw invalid('"tenant" must be a string.'); + throw unsupported('Tenants are not supported: omit "tenant" or send an empty string.'); +} + +function checkMetadata(params: Record): void { + const metadata = read(params, 'metadata'); + if (metadata !== undefined && !isRecord(metadata)) { + throw invalid('"metadata" must be a JSON object.'); + } +} + +const INT32_MAX = 2_147_483_647; + +// Read an int32 from a JSON number or a decimal integer string +function readInteger(value: unknown, name: string, min: number, max = INT32_MAX) { + if (value === undefined) return undefined; + const n = + typeof value === 'number' + ? value + : typeof value === 'string' && /^-?\d+$/.test(value) + ? Number(value) + : Number.NaN; + if (!Number.isInteger(n) || n < min || n > max) { + throw invalid(`"${name}" must be an integer from ${min} to ${max}.`); + } + return n; +} + +function readBoolean(value: unknown, name: string): boolean | undefined { + if (value === undefined) return undefined; + if (typeof value !== 'boolean') throw invalid(`"${name}" must be true or false.`); + return value; +} + +// Section 5.6.1: UTC with a `Z`, fractional seconds optional +const UTC_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/; + +// `Date.parse` rolls 30 February over to March; the round trip catches it +function isUtcTimestamp(value: string): boolean { + if (!UTC_TIMESTAMP.test(value)) return false; + const ms = Date.parse(value); + return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 19) === value.slice(0, 19); +} + +// A media range admitting JSON: the type itself, `application/*` or `*/*` +function admitsJson(range: string): boolean { + const type = (range.split(';')[0] ?? '').trim().toLowerCase(); + return type === A2A_JSON_MEDIA_TYPE || type === 'application/*' || type === '*/*'; +} + +/** Normalized and validated `SendMessage` parameters; message validation follows separately */ +export interface SendMessageParams { + /** Request with normalized top-level, message and part field names */ + readonly params: Record; + readonly historyLength?: number; + readonly returnImmediately: boolean; +} + +export function readSendMessageParams(raw: Record): SendMessageParams { + const params = jsonNames(raw, 'The request'); + const message = params['message']; + if (isRecord(message)) { + const named = jsonNames(message, 'The message'); + const parts = named['parts']; + params['message'] = Array.isArray(parts) + ? { + ...named, + parts: parts.map((part) => (isRecord(part) ? jsonNames(part, 'A message part') : part)), + } + : named; + } + checkTenant(params); + checkMetadata(params); + + const configuration = read(params, 'configuration'); + if (configuration === undefined) return { params, returnImmediately: false }; + if (!isRecord(configuration)) throw invalid('"configuration" must be a JSON object.'); + const options = jsonNames(configuration, 'The configuration'); + if (read(options, 'taskPushNotificationConfig') !== undefined) { + throw unsupported( + 'Push notifications are not supported: omit "configuration.taskPushNotificationConfig".', + A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED, + ); + } + const modes = read(options, 'acceptedOutputModes'); + if (modes !== undefined) { + if (!Array.isArray(modes) || !modes.every((mode) => typeof mode === 'string')) { + throw invalid('"configuration.acceptedOutputModes" must be an array of media types.'); + } + // An empty list leaves the output mode to the agent + if (modes.length > 0 && !modes.some(admitsJson)) { + throw unsupported( + `This agent answers in ${A2A_JSON_MEDIA_TYPE} only: list it in "configuration.acceptedOutputModes", or omit the field.`, + A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED, + ); + } + } + const historyLength = readInteger( + read(options, 'historyLength'), + 'configuration.historyLength', + 0, + ); + return { + params, + ...(historyLength !== undefined ? { historyLength } : {}), + returnImmediately: + readBoolean(read(options, 'returnImmediately'), 'configuration.returnImmediately') ?? false, + }; +} + +function taskOperationParams(raw: Record): Record { + const params = jsonNames(raw, 'The request'); + checkTenant(params); + return params; +} + +function readTaskId(params: Record): string { + const id = read(params, 'id'); + if (typeof id !== 'string' || id.length === 0) { + throw invalid('The request must carry a non-empty task "id".'); + } + return id; +} + +export interface GetTaskParams { + readonly id: string; + readonly historyLength?: number; +} + +export function readGetTaskParams(raw: Record): GetTaskParams { + const params = taskOperationParams(raw); + const id = readTaskId(params); + const historyLength = readInteger(read(params, 'historyLength'), 'historyLength', 0); + return { id, ...(historyLength !== undefined ? { historyLength } : {}) }; +} + +export interface CancelTaskParams { + readonly id: string; +} + +export function readCancelTaskParams(raw: Record): CancelTaskParams { + const params = taskOperationParams(raw); + checkMetadata(params); + return { id: readTaskId(params) }; +} + +// Accepted proto `TaskState` names; treat `TASK_STATE_UNSPECIFIED` as no filter +const TASK_STATES: readonly string[] = [ + 'TASK_STATE_SUBMITTED', + 'TASK_STATE_WORKING', + 'TASK_STATE_COMPLETED', + 'TASK_STATE_FAILED', + 'TASK_STATE_CANCELED', + 'TASK_STATE_INPUT_REQUIRED', + 'TASK_STATE_REJECTED', + 'TASK_STATE_AUTH_REQUIRED', +]; + +/** Proto `ListTasksRequest.page_size`: 50 when unset, at most 100 */ +export const A2A_LIST_PAGE_SIZE = { default: 50, max: 100 } as const; + +/** Task position encoded in a pagination token */ +export interface ListCursor { + readonly updatedAt: string; + readonly id: string; +} + +export function encodePageToken(cursor: ListCursor): string { + return Buffer.from(JSON.stringify([cursor.updatedAt, cursor.id]), 'utf8').toString('base64url'); +} + +function decodePageToken(token: string): ListCursor | undefined { + // `Buffer.from` skips characters outside the alphabet instead of failing + if (!/^[A-Za-z0-9_-]+$/.test(token)) return undefined; + let value: unknown; + try { + value = JSON.parse(Buffer.from(token, 'base64url').toString('utf8')); + } catch { + return undefined; + } + if (!Array.isArray(value) || value.length !== 2) return undefined; + const [updatedAt, id] = value as unknown[]; + return typeof updatedAt === 'string' && + isUtcTimestamp(updatedAt) && + typeof id === 'string' && + id.length > 0 + ? { updatedAt, id } + : undefined; +} + +export interface ListTasksParams { + /** Absent when `contextId` is omitted, null or empty */ + readonly contextId?: string; + readonly status?: string; + readonly pageSize: number; + /** Decoded cursor; absent when no page token is supplied */ + readonly after?: ListCursor; + readonly historyLength?: number; + /** UTC timestamp supplied as the inclusive lower bound, preserved as sent */ + readonly statusTimestampAfter?: string; + readonly includeArtifacts: boolean; +} + +export function readListTasksParams(raw: Record): ListTasksParams { + const params = taskOperationParams(raw); + + const contextId = read(params, 'contextId'); + if (contextId !== undefined && typeof contextId !== 'string') { + throw invalid('"contextId" must be a string.'); + } + const status = read(params, 'status'); + if ( + status !== undefined && + status !== 'TASK_STATE_UNSPECIFIED' && + !(typeof status === 'string' && TASK_STATES.includes(status)) + ) { + throw invalid('"status" must be a TaskState name, such as "TASK_STATE_COMPLETED".'); + } + const pageSize = + readInteger(read(params, 'pageSize'), 'pageSize', 1, A2A_LIST_PAGE_SIZE.max) ?? + A2A_LIST_PAGE_SIZE.default; + const pageToken = read(params, 'pageToken'); + let after: ListCursor | undefined; + if (pageToken !== undefined && pageToken !== '') { + after = typeof pageToken === 'string' ? decodePageToken(pageToken) : undefined; + if (after === undefined) { + throw invalid('"pageToken" must be a nextPageToken this agent returned.'); + } + } + const historyLength = readInteger(read(params, 'historyLength'), 'historyLength', 0); + const statusTimestampAfter = read(params, 'statusTimestampAfter'); + if ( + statusTimestampAfter !== undefined && + !(typeof statusTimestampAfter === 'string' && isUtcTimestamp(statusTimestampAfter)) + ) { + throw invalid( + '"statusTimestampAfter" must be a UTC timestamp such as "2026-01-01T00:00:00.000Z".', + ); + } + const includeArtifacts = readBoolean(read(params, 'includeArtifacts'), 'includeArtifacts'); + + return { + ...(typeof contextId === 'string' && contextId !== '' ? { contextId } : {}), + ...(typeof status === 'string' && status !== 'TASK_STATE_UNSPECIFIED' ? { status } : {}), + pageSize, + ...(after !== undefined ? { after } : {}), + ...(historyLength !== undefined ? { historyLength } : {}), + ...(typeof statusTimestampAfter === 'string' ? { statusTimestampAfter } : {}), + includeArtifacts: includeArtifacts ?? false, + }; +} diff --git a/tests/conformance/a2a/params.test.ts b/tests/conformance/a2a/params.test.ts new file mode 100644 index 0000000..a6b3e33 --- /dev/null +++ b/tests/conformance/a2a/params.test.ts @@ -0,0 +1,201 @@ +/** + * Check parameter refusals over raw HTTP and verify that they make no backend + * calls or task-store reads. The `SendMessage` cases include a task ID, which + * would trigger a lookup if parameter validation ran too late. + */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { type RunningGateway, startConformanceGateway } from './support/gateway'; + +let running: RunningGateway; + +beforeAll(async () => { + running = await startConformanceGateway(); +}); + +afterAll(async () => { + await running?.close(); +}); + +interface JsonRpcResponse { + readonly result?: { task?: { status?: { state?: string } } }; + readonly error?: { code: number; message: string }; +} + +async function post(method: string, params: unknown): Promise { + const response = await fetch(`${running.url}/a2a`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'A2A-Version': '1.0' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 'p-1', method, params }), + }); + return (await response.json()) as JsonRpcResponse; +} + +// Check the refusal code and confirm that backend and task-read counts stay unchanged +async function expectRefused(method: string, params: unknown, code: number): Promise { + const backendBefore = running.backendCalls(); + const readsBefore = running.taskReads(); + const body = await post(method, params); + expect(body.error?.code, JSON.stringify(body)).toBe(code); + expect(running.backendCalls()).toBe(backendBefore); + expect(running.taskReads()).toBe(readsBefore); + return body.error?.message ?? ''; +} + +const PART = { data: { resource: 'weather_basic', input: { city: 'Berlin' } } }; +const MESSAGE = { role: 'ROLE_USER', messageId: 'msg-1', parts: [PART] }; +// Include a task ID so a request that passes parameter checks would trigger a lookup +const ON_TASK = { ...MESSAGE, taskId: 'task-1' }; + +describe('SendMessage parameters', () => { + it.each([ + ['a non-empty tenant', { tenant: 'acme' }, -32004], + ['a tenant that is not a string', { tenant: 7 }, -32602], + ['a configuration that is not an object', { configuration: [] }, -32602], + [ + 'output modes without JSON', + { configuration: { acceptedOutputModes: ['text/plain'] } }, + -32005, + ], + [ + 'output modes that are not a list', + { configuration: { acceptedOutputModes: 'application/json' } }, + -32602, + ], + [ + 'a push notification config', + { configuration: { taskPushNotificationConfig: { url: 'https://hooks.example' } } }, + -32003, + ], + ['a negative historyLength', { configuration: { historyLength: -1 } }, -32602], + ['a fractional historyLength', { configuration: { historyLength: 1.5 } }, -32602], + [ + 'a returnImmediately that is not a boolean', + { configuration: { returnImmediately: 'yes' } }, + -32602, + ], + ['metadata that is not an object', { metadata: 'note' }, -32602], + ])('refuses %s', async (_label, fields, code) => { + await expectRefused('SendMessage', { message: ON_TASK, ...fields }, code); + }); + + it('runs a request whose optional parameters all hold accepted values', async () => { + const before = running.backendCalls(); + const body = await post('SendMessage', { + tenant: '', + message: MESSAGE, + configuration: { + acceptedOutputModes: ['text/plain', 'application/*'], + historyLength: '3', + returnImmediately: false, + taskPushNotificationConfig: null, + }, + metadata: {}, + }); + expect(body.result?.task?.status?.state).toBe('TASK_STATE_COMPLETED'); + expect(running.backendCalls()).toBe(before + 1); + }); +}); + +describe('task operation parameters', () => { + it.each([ + ['GetTask', 'a non-empty tenant', { id: 'task-1', tenant: 'acme' }, -32004], + ['GetTask', 'no id', {}, -32602], + ['GetTask', 'an empty id', { id: '' }, -32602], + ['GetTask', 'an id that is not a string', { id: 7 }, -32602], + ['GetTask', 'a negative historyLength', { id: 'task-1', historyLength: -1 }, -32602], + ['CancelTask', 'a non-empty tenant', { id: 'task-1', tenant: 'acme' }, -32004], + ['CancelTask', 'no id', {}, -32602], + ['CancelTask', 'metadata that is not an object', { id: 'task-1', metadata: [] }, -32602], + ['ListTasks', 'a non-empty tenant', { tenant: 'acme' }, -32004], + ['ListTasks', 'a contextId that is not a string', { contextId: 5 }, -32602], + ['ListTasks', 'an unknown status', { status: 'TASK_STATE_DONE' }, -32602], + ['ListTasks', 'a pageSize of 0', { pageSize: 0 }, -32602], + ['ListTasks', 'a pageSize of 101', { pageSize: 101 }, -32602], + ['ListTasks', 'a pageToken it never issued', { pageToken: 'not-a-token' }, -32602], + [ + 'ListTasks', + 'a statusTimestampAfter with an offset', + { statusTimestampAfter: '2026-01-01T01:00:00+01:00' }, + -32602, + ], + [ + 'ListTasks', + 'an includeArtifacts that is not a boolean', + { includeArtifacts: 'true' }, + -32602, + ], + ['ListTasks', 'a negative historyLength', { historyLength: -1 }, -32602], + ])('%s refuses %s', async (method, _label, params, code) => { + await expectRefused(method, params, code); + }); +}); + +describe('proto field names', () => { + it('runs a request sent with proto field names', async () => { + const before = running.backendCalls(); + const body = await post('SendMessage', { + message: { + role: 'ROLE_USER', + message_id: 'msg-proto', + parts: [{ ...PART, media_type: 'application/json' }], + }, + configuration: { accepted_output_modes: ['application/json'], history_length: 0 }, + }); + expect(body.result?.task?.status?.state).toBe('TASK_STATE_COMPLETED'); + expect(running.backendCalls()).toBe(before + 1); + }); + + it('checks a parameter sent under its proto name', async () => { + await expectRefused( + 'SendMessage', + { message: ON_TASK, configuration: { accepted_output_modes: ['text/plain'] } }, + -32005, + ); + await expectRefused('ListTasks', { page_size: 0 }, -32602); + }); + + it('refuses context_id as it refuses contextId, in the message and in the params', async () => { + const camel = await expectRefused( + 'SendMessage', + { message: { ...MESSAGE, contextId: 'ctx-1' } }, + -32004, + ); + expect( + await expectRefused('SendMessage', { message: { ...MESSAGE, context_id: 'ctx-1' } }, -32004), + ).toBe(camel); + expect( + await expectRefused('SendMessage', { message: MESSAGE, context_id: 'ctx-1' }, -32004), + ).toBe(camel); + }); + + it('answers an unknown task_id as it answers an unknown taskId', async () => { + const answer = async (message: Record) => + (await post('SendMessage', { message })).error; + expect(await answer({ ...MESSAGE, task_id: 'task-1' })).toEqual( + await answer({ ...MESSAGE, taskId: 'task-1' }), + ); + expect((await answer({ ...MESSAGE, task_id: 'task-1' }))?.code).toBe(-32001); + }); + + it.each([ + ['SendMessage', 'the message', { message: { ...ON_TASK, message_id: 'msg-2' } }, 'messageId'], + [ + 'SendMessage', + 'a message part', + { message: { ...ON_TASK, parts: [{ ...PART, mediaType: 'a', media_type: 'b' }] } }, + 'mediaType', + ], + ['ListTasks', 'the params', { pageSize: 10, page_size: 20 }, 'pageSize'], + [ + 'GetTask', + 'the params', + { id: 'task-1', history_length: 1, historyLength: 2 }, + 'historyLength', + ], + ])('%s refuses a field that %s sends under both names', async (method, _where, params, field) => { + const message = await expectRefused(method, params, -32602); + const proto = field.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`); + expect(message).toContain(`"${field}"`); + expect(message).toContain(`"${proto}"`); + }); +}); diff --git a/tests/conformance/a2a/support/gateway.ts b/tests/conformance/a2a/support/gateway.ts index b325c6a..ea58515 100644 --- a/tests/conformance/a2a/support/gateway.ts +++ b/tests/conformance/a2a/support/gateway.ts @@ -17,6 +17,7 @@ import type { PaymentResult, PaymentSettlementContext, PaymentVerificationContext, + ReceiptStore, } from '../../../../src/core'; import { CommerceError } from '../../../../src/core'; import { createGateway, type GatewayInstance } from '../../../../src/gateway'; @@ -179,9 +180,34 @@ export interface RunningGateway { backendCalls(): number; /** Successful settlements so far */ settleCalls(): number; + /** Pending-task and task-record reads from the store so far */ + taskReads(): number; close(): Promise; } +const TASK_READS = new Set([ + 'getPendingTask', + 'takePendingTask', + 'getTaskRecord', + 'listTaskRecords', +]); + +// Count task-store reads to check that parameter refusals happen before lookup +function countingTaskReads(store: ReceiptStore): { store: ReceiptStore; reads: () => number } { + let reads = 0; + const counted = new Proxy(store, { + get(target, key, receiver) { + const value: unknown = Reflect.get(target, key, receiver); + if (typeof value !== 'function') return value; + return (...args: unknown[]) => { + if (typeof key === 'string' && TASK_READS.has(key)) reads += 1; + return value.apply(target, args); + }; + }, + }); + return { store: counted, reads: () => reads }; +} + /** * A port nothing else holds. The card's `supportedInterfaces[].url` is built * from `publicBaseUrl` at adapter start, before `listen()` returns, and the @@ -206,8 +232,9 @@ export async function startConformanceGateway(): Promise { }; const backend = countingBackend(); const provider = fakeProvider(); - const store = createSqliteReceiptStore({ path: ':memory:' }); - await store.init(); + const sqlite = createSqliteReceiptStore({ path: ':memory:' }); + await sqlite.init(); + const { store, reads } = countingTaskReads(sqlite); const gateway = await createGateway({ config: gatewayConfig, store, @@ -229,6 +256,7 @@ export async function startConformanceGateway(): Promise { url, backendCalls: backend.calls, settleCalls: provider.settleCalls, + taskReads: reads, async close() { await gateway.close(); await store.close(); diff --git a/tests/integration/a2a-over-gateway.test.ts b/tests/integration/a2a-over-gateway.test.ts index 1369160..04d1ed2 100644 --- a/tests/integration/a2a-over-gateway.test.ts +++ b/tests/integration/a2a-over-gateway.test.ts @@ -222,7 +222,8 @@ describe('A2A JSON-RPC transport over the real gateway', () => { ['a completely unknown method', 'DoSomething', -32601], ])('distinguishes %s', async (_label, method, code) => { const gw = await startGateway(); - const { body } = await rpc(gw, { jsonrpc: '2.0', id: 1, method, params: {} }); + // GetTask and CancelTask require an id + const { body } = await rpc(gw, { jsonrpc: '2.0', id: 1, method, params: { id: 'task-1' } }); expect(body.error?.code).toBe(code); }); diff --git a/tests/integration/a2a-x402-extension.test.ts b/tests/integration/a2a-x402-extension.test.ts index 67d9bdb..923482b 100644 --- a/tests/integration/a2a-x402-extension.test.ts +++ b/tests/integration/a2a-x402-extension.test.ts @@ -390,6 +390,54 @@ describe('x402 A2A extension', () => { expect(body.result?.task.status.state).toBe('TASK_STATE_COMPLETED'); }); + it('pays a task named with proto field names', async () => { + const task = await challenged(); + const { taskId, contextId, messageId, ...rest } = pay(task, { + 'x402.payment.status': 'payment-submitted', + 'x402.payment.payload': await paymentPayload(task), + }); + + const { body } = await rpc({ + ...rest, + task_id: taskId, + context_id: contextId, + message_id: messageId, + }); + + expect(body.result?.task).toMatchObject({ + id: task.id, + status: { state: 'TASK_STATE_COMPLETED' }, + }); + expect(facilitator.settle).toHaveBeenCalledTimes(1); + }); + + it('leaves snake_case keys in the merchant input and the payment metadata as sent', async () => { + const requests = spyOnPipeline(); + const purchase = buy('x402_report'); + const [part] = purchase['parts'] as Record[]; + const { body: challenge } = await rpc({ + ...purchase, + parts: [{ ...part, data: { resource: 'x402_report', input: { symbol: 'ETH', max_age: 5 } } }], + }); + const task = challenge.result?.task as A2aTask; + const payload = await paymentPayload(task); + const signed = { ...(payload['payload'] as Record), buyer_note: 'n' }; + + const { body } = await rpc( + pay(task, { + 'x402.payment.status': 'payment-submitted', + 'x402.payment.payload': { ...payload, payload: signed }, + }), + ); + + expect(body.result?.task.status.state).toBe('TASK_STATE_COMPLETED'); + expect(requests.map((request) => request.input)).toEqual([ + { symbol: 'ETH', max_age: 5 }, + { symbol: 'ETH', max_age: 5 }, + ]); + expect(facilitator.verify.mock.calls[0]?.[0]).toMatchObject({ payload: { buyer_note: 'n' } }); + }); + it('answers a task id it never issued with TaskNotFoundError', async () => { const { body } = await rpc( pay( diff --git a/tests/unit/protocols-a2a/params.test.ts b/tests/unit/protocols-a2a/params.test.ts new file mode 100644 index 0000000..8405721 --- /dev/null +++ b/tests/unit/protocols-a2a/params.test.ts @@ -0,0 +1,175 @@ +// Check parsed values, defaults, page cursors and accepted input forms. +// HTTP refusal codes are covered in tests/conformance/a2a/params.test.ts. +import { describe, expect, it } from 'vitest'; +import type { CommerceError } from '../../../src/core'; +import { + encodePageToken, + readGetTaskParams, + readListTasksParams, + readSendMessageParams, +} from '../../../src/protocols/a2a/params'; + +function refusal(read: () => unknown): string | undefined { + try { + read(); + } catch (err) { + return (err as CommerceError).code; + } + return undefined; +} + +const CURSOR = { updatedAt: '2026-11-22T10:00:00.000Z', id: 'f3b1c2d4-task' }; + +describe('readListTasksParams', () => { + it('applies the defaults to an empty request', () => { + expect(readListTasksParams({})).toEqual({ pageSize: 50, includeArtifacts: false }); + }); + + it('treats an empty contextId, an unspecified status and an empty pageToken as absent', () => { + expect( + readListTasksParams({ contextId: '', status: 'TASK_STATE_UNSPECIFIED', pageToken: '' }), + ).toEqual({ pageSize: 50, includeArtifacts: false }); + }); + + it('reads every field, under either name', () => { + const expected = { + contextId: 'ctx-1', + status: 'TASK_STATE_COMPLETED', + pageSize: 100, + after: CURSOR, + historyLength: 0, + statusTimestampAfter: '2026-11-22T10:00:00.123456789Z', + includeArtifacts: true, + }; + expect( + readListTasksParams({ + contextId: 'ctx-1', + status: 'TASK_STATE_COMPLETED', + pageSize: 100, + pageToken: encodePageToken(CURSOR), + historyLength: 0, + statusTimestampAfter: '2026-11-22T10:00:00.123456789Z', + includeArtifacts: true, + }), + ).toEqual(expected); + expect( + readListTasksParams({ + context_id: 'ctx-1', + status: 'TASK_STATE_COMPLETED', + page_size: '100', + page_token: encodePageToken(CURSOR), + history_length: '0', + status_timestamp_after: '2026-11-22T10:00:00.123456789Z', + include_artifacts: true, + }), + ).toEqual(expected); + }); + + it.each([ + // Without the alphabet check, Buffer.from would skip `!` and decode the cursor + [ + 'an issued token with a character outside base64url', + `${encodePageToken(CURSOR).slice(0, 4)}!${encodePageToken(CURSOR).slice(4)}`, + ], + ['base64url that is not JSON', Buffer.from('not json').toString('base64url')], + ['an object, not a pair', Buffer.from(JSON.stringify(CURSOR)).toString('base64url')], + ['an offset timestamp', encodePageToken({ ...CURSOR, updatedAt: '2026-11-22T11:00:00+01:00' })], + ['an empty id', encodePageToken({ ...CURSOR, id: '' })], + ['a number', 7], + ])('refuses a pageToken that is %s', (_label, pageToken) => { + expect(refusal(() => readListTasksParams({ pageToken }))).toBe('INPUT_INVALID'); + }); + + it.each([ + ['30 February', '2026-02-30T10:00:00Z'], + ['hour 24', '2026-11-22T24:00:00Z'], + ['no seconds', '2026-11-22T10:00Z'], + ['a lowercase z', '2026-11-22T10:00:00z'], + ['ten fraction digits', '2026-11-22T10:00:00.1234567890Z'], + ])('refuses a statusTimestampAfter with %s', (_label, statusTimestampAfter) => { + expect(refusal(() => readListTasksParams({ statusTimestampAfter }))).toBe('INPUT_INVALID'); + }); + + it('accepts pageSize 1 and refuses 101, as a number or a string', () => { + expect(readListTasksParams({ pageSize: 1 }).pageSize).toBe(1); + expect(readListTasksParams({ pageSize: '1' }).pageSize).toBe(1); + expect(refusal(() => readListTasksParams({ pageSize: '101' }))).toBe('INPUT_INVALID'); + }); +}); + +describe('ProtoJSON integers', () => { + it.each([ + ['a decimal string', '12', 12], + ['the int32 maximum', 2_147_483_647, 2_147_483_647], + ])('reads %s', (_label, historyLength, expected) => { + expect(readGetTaskParams({ id: 't', historyLength }).historyLength).toBe(expected); + }); + + it.each([ + ['a hex string', '0x10'], + ['an exponent string', '1e2'], + ['a padded string', ' 3'], + ['an empty string', ''], + ['a value past int32', 2_147_483_648], + ['a boolean', true], + ['an array', [3]], + ])('refuses %s', (_label, historyLength) => { + expect(refusal(() => readGetTaskParams({ id: 't', historyLength }))).toBe('INPUT_INVALID'); + }); +}); + +describe('field names', () => { + it('renames only an underscore before a lowercase letter or digit', () => { + // `history_Length` is not a proto name: it is an unknown field, ignored + expect(readGetTaskParams({ id: 't', history_Length: -1 })).toEqual({ id: 't' }); + }); + + it('keeps an own __proto__ key from changing the prototype', () => { + const params = readSendMessageParams(JSON.parse('{"__proto__": {"polluted": true}}')).params; + expect(Object.getPrototypeOf(params)).toBe(Object.prototype); + expect((params as { polluted?: unknown }).polluted).toBeUndefined(); + }); +}); + +describe('readSendMessageParams', () => { + it('reads the configuration it will act on', () => { + expect( + readSendMessageParams({ + configuration: { history_length: '2', return_immediately: true }, + }), + ).toMatchObject({ historyLength: 2, returnImmediately: true }); + }); + + it('defaults returnImmediately to false', () => { + expect(readSendMessageParams({ configuration: {} })).toMatchObject({ + returnImmediately: false, + }); + expect(readSendMessageParams({})).toMatchObject({ returnImmediately: false }); + }); + + it.each([ + ['parts that are not a list', { message_id: 'm', parts: 'p' }, { messageId: 'm', parts: 'p' }], + ['a part that is not an object', { parts: [7] }, { parts: [7] }], + ])('passes on %s for the message check to refuse', (_label, message, expected) => { + expect(readSendMessageParams({ message }).params).toEqual({ message: expected }); + }); + + it('renames the message and its parts, and leaves data and metadata values alone', () => { + const { params } = readSendMessageParams({ + message: { + message_id: 'm', + metadata: { some_key: 1 }, + parts: [{ data: { resource: 'r', input: { max_age: 5 } }, media_type: 'application/json' }], + }, + metadata: { request_note: 'x' }, + }); + expect(params).toEqual({ + message: { + messageId: 'm', + metadata: { some_key: 1 }, + parts: [{ data: { resource: 'r', input: { max_age: 5 } }, mediaType: 'application/json' }], + }, + metadata: { request_note: 'x' }, + }); + }); +}); From cff54629141cc2516d94806cdd7f85338e26e183 Mon Sep 17 00:00:00 2001 From: Revinand Date: Sun, 22 Nov 2026 20:23:57 +0100 Subject: [PATCH 06/17] feat(a2a): serve GetTask, ListTasks and CancelTask from stored tasks --- README.md | 2 +- config.example.yaml | 11 +- docs/configuration.md | 20 + docs/contracts.md | 7 + docs/protocols.md | 2 +- docs/protocols/a2a.md | 152 +- docs/security.md | 12 +- docs/storage.md | 14 +- src/gateway/run.ts | 1 + src/protocols/a2a/adapter.ts | 366 ++- src/protocols/a2a/constants.ts | 35 +- src/protocols/a2a/descriptor.ts | 3 + src/protocols/a2a/jsonrpc.ts | 6 +- src/protocols/a2a/message-mapping.ts | 49 +- src/protocols/a2a/payment-resume.ts | 120 +- src/protocols/a2a/task-mapping.ts | 58 +- src/protocols/a2a/task-operations.ts | 142 ++ src/protocols/a2a/task-store.ts | 82 + src/protocols/a2a/x402-extension.ts | 10 +- src/support/a2a.json | 20 +- tests/conformance/a2a/errors.test.ts | 17 +- tests/conformance/a2a/support/gateway.ts | 3 + tests/conformance/a2a/support/task-schema.ts | 42 + tests/conformance/a2a/task-schema.test.ts | 44 + tests/conformance/a2a/tasks.test.ts | 369 ++++ tests/fixtures/a2a/tck-5e6f37c2/README.md | 32 + tests/fixtures/a2a/tck-5e6f37c2/a2a.json | 1961 +++++++++++++++++ tests/integration/a2a-over-gateway.test.ts | 4 +- tests/integration/a2a-x402-extension.test.ts | 90 +- .../goldens/2.7.2/doctor-multi.json | 2 +- .../goldens/2.7.2/doctor-single.json | 2 +- .../goldens/2.7.2/well-known-multi.json | 8 +- .../goldens/2.7.2/well-known-single.json | 8 +- tests/integration/goldens/2.8.0/a2a-free.json | 4 +- .../goldens/2.8.0/a2a-paid-no-proof.json | 8 +- .../goldens/2.8.0/a2a-refusals.json | 29 +- .../goldens/2.8.0/a2a-x402-completed.json | 8 +- .../2.8.0/a2a-x402-input-required.json | 8 +- tests/integration/payment-retries.test.ts | 5 +- tests/unit/cli/doctor.test.ts | 7 +- tests/unit/gateway/main.test.ts | 54 +- tests/unit/protocols-a2a/agent-card.test.ts | 7 +- .../unit/protocols-a2a/payment-resume.test.ts | 6 +- .../unit/protocols-a2a/pending-store.test.ts | 229 +- .../protocols-a2a/pipeline-mapping.test.ts | 78 +- tests/unit/protocols-a2a/task-store.test.ts | 134 ++ 46 files changed, 3917 insertions(+), 354 deletions(-) create mode 100644 src/protocols/a2a/task-operations.ts create mode 100644 src/protocols/a2a/task-store.ts create mode 100644 tests/conformance/a2a/support/task-schema.ts create mode 100644 tests/conformance/a2a/task-schema.test.ts create mode 100644 tests/conformance/a2a/tasks.test.ts create mode 100644 tests/fixtures/a2a/tck-5e6f37c2/README.md create mode 100644 tests/fixtures/a2a/tck-5e6f37c2/a2a.json create mode 100644 tests/unit/protocols-a2a/task-store.test.ts diff --git a/README.md b/README.md index 7dd46eb..5996bc7 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ See [docs/configuration.md](docs/configuration.md). | **MCP** | Supported | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | | **x402** | Supported | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | | **MPP** | Experimental | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A | -| **A2A** | Experimental | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, paid flow and the x402 extension | +| **A2A** | Experimental | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension | | **ACP** | Experimental | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | | **AP2** | Experimental | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement | | **ERC-8409** | Experimental | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | diff --git a/config.example.yaml b/config.example.yaml index 7a13df6..b68dc80 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -52,13 +52,18 @@ protocols: # version: 1.0.0 # description: Weather forecasts, paid per call # A2A (Agent2Agent) v1.0.1 - experimental, off by default. - # Serves JSON-RPC `SendMessage` at mountPath and the Agent Card at - # /.well-known/agent-card.json. Enable at least one resource with - # `expose: [a2a]`. Clients send `A2A-Version: 1.0`. + # Serves JSON-RPC `SendMessage`, `GetTask`, `ListTasks` and `CancelTask` at + # mountPath and the Agent Card at /.well-known/agent-card.json. Enable at + # least one resource with `expose: [a2a]`. Clients send `A2A-Version: 1.0`. # See docs/protocols/a2a.md for supported features. a2a: enabled: false mountPath: /a2a + # Retain task responses in the receipt database for later reads. + # At capacity, refuse new records and keep existing ones. + # tasks: + # retentionHours: 24 # 1 to 8760 + # maxRetained: 1000 # 1 to 1,000,000 # ACP (Agentic Commerce Protocol), stable snapshot 2026-04-17 - experimental, # off by default. Enabling it serves the five checkout routes under mountPath # and the specification-fixed discovery document at /.well-known/acp.json. diff --git a/docs/configuration.md b/docs/configuration.md index f61b41e..f5150b4 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -251,6 +251,26 @@ keys: Lengths count Unicode code points. +## `protocols.a2a` + +Experimental and off by default. The optional `tasks` block limits retention +for `GetTask`, `ListTasks` and `CancelTask`; see [Tasks](protocols/a2a.md#tasks). + +```yaml +protocols: + a2a: + enabled: true + mountPath: /a2a # default + tasks: # optional + retentionHours: 24 # default; 1 to 8760 + maxRetained: 1000 # default; 1 to 1,000,000 +``` + +- `retentionHours`: how long a task stays readable after it is stored or updated. +- `maxRetained`: the limit on unexpired task records when admitting a new + record. At capacity, the store refuses new records and permits replacements. + Lowering the limit does not evict existing records. + ## `protocols.acp` Experimental, off by default, and absent from a config that predates it. The diff --git a/docs/contracts.md b/docs/contracts.md index 948c5b4..1993cae 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -525,6 +525,13 @@ persistence must not fail the commerce flow. `protocols.a2a.tasks`. The block and individual keys stay absent when omitted. Config loading requires integers from 1 to 8760 for `retentionHours` and from 1 to 1,000,000 for `maxRetained`. + - `A2aAdapterOptions.tasks` accepts the same limits; `runGateway` passes the + config block. Omitted `retentionHours` defaults to 24; omitted `maxRetained` + defaults to 1000. The adapter constructor throws `CONFIG_INVALID` for + non-integer or out-of-range values, naming `tasks.retentionHours` or + `tasks.maxRetained`. + - The adapter retains task responses in a supplied store with the complete + `task_records` group, or in process memory otherwise. ### Authorization and AP2 diff --git a/docs/protocols.md b/docs/protocols.md index 713d85e..ac44c9f 100644 --- a/docs/protocols.md +++ b/docs/protocols.md @@ -13,7 +13,7 @@ subset. Each protocol's page describes that subset in detail. | **MCP** | Supported | Transport that carries x402 and MPP payments in tool calls. | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | | **x402** | Supported | Payment rail, carried by HTTP, MCP and A2A. | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | | **MPP** | Experimental | Payment rail, carried by HTTP, MCP and A2A. | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A | -| **A2A** | Experimental | Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension. | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, paid flow and the x402 extension | +| **A2A** | Experimental | Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension. | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension | | **ACP** | Experimental | Checkout API that forwards checkout operations to the merchant, whose payment handler receives `payment_data`. Gateway checkout routes are free and carry no x402 or MPP payment. | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | | **AP2** | Experimental | Authorization method, not a payment rail: a paid resource can require a verified mandate in addition to its x402 or MPP payment, never instead of it. | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement | | **ERC-8409** | Experimental | x402 feature: EIP-712 signed quotes on the EVM offers of a challenge. | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | diff --git a/docs/protocols/a2a.md b/docs/protocols/a2a.md index 7d6f288..bc91600 100644 --- a/docs/protocols/a2a.md +++ b/docs/protocols/a2a.md @@ -5,11 +5,11 @@ | Property | Value | | ------------- | --------------------------------------------------------------------------------------------------------------------------------- | | Binding | JSON-RPC 2.0 over HTTP(S) | -| Method | `SendMessage`, not legacy `message/send` | +| Methods | `SendMessage`, `GetTask`, `ListTasks`, `CancelTask`; not legacy `message/send` | | Version | `A2A-Version: 1.0` header, or an `A2A-Version` query parameter when the header is absent; patch suffixes are accepted but ignored | | Agent Card | `GET /.well-known/agent-card.json` | | Default mount | `/a2a` | -| Task model | synchronous; terminal except an unpaid x402 extension task | +| Task model | synchronous calls; task responses retained for later reads (see [Tasks](#tasks)) | Each A2A resource becomes an Agent Card skill. Paid skills have a `paid` tag and a price in their description. A2A v1.0 has no input-schema field for @@ -83,9 +83,12 @@ merchant input and extension metadata. Sending both names for a field returns | `configuration.returnImmediately` | absent or a boolean; ignored, so responses remain synchronous | `-32602` | | `metadata` on `SendMessage` and `CancelTask` | absent or an object; ignored | `-32602` | | `id` on `GetTask` and `CancelTask` | a non-empty string | `-32602` | - -The adapter also validates `ListTasks` filters and pagination parameters. -A valid request returns `-32004`; listing tasks is unsupported. +| `contextId` on `ListTasks` | absent or a string; absent, `null` and `""` list nothing | `-32602` | +| `status` on `ListTasks` | absent or a `TaskState` name; `TASK_STATE_UNSPECIFIED` filters nothing | `-32602` | +| `pageSize` on `ListTasks` | absent (50) or an integer from 1 to 100 | `-32602` | +| `pageToken` on `ListTasks` | absent, `""`, or a valid base64url cursor; use `nextPageToken` to continue | `-32602` | +| `statusTimestampAfter` on `ListTasks` | absent or a UTC timestamp such as `2026-01-01T00:00:00.000Z` | `-32602` | +| `includeArtifacts` on `ListTasks` | absent or a boolean | `-32602` | ## x402 extension @@ -100,9 +103,10 @@ Its examples use lowercase task states and roles, `kind` on parts, and the `params: { "x402Version": 2 }`, when x402 is a skill's selected payment rail. A response carries the `A2A-Extensions` header when its task status message -lists the extension: the input-required task, and every task answered to a -payment message, even one sent without the header. Other responses, such as an -MPP skill's task or a JSON-RPC error, omit it. An extension status message +lists the extension. This includes input-required tasks, payment-message +responses even when the request omits the header, and `GetTask` reads of those +tasks. Other responses, such as MPP tasks and JSON-RPC errors, omit it. +An extension status message carries `contextId`, `taskId`, `extensions: []` and the `x402.payment.*` metadata. @@ -129,16 +133,17 @@ purchase fails with `GATEWAY_BUSY`; no waiting task is evicted to make room. An unexpired stored task can survive a restart. The SQLite store deletes expired tasks when initializing a writable store and when storing or taking a task. After validating a follow-up message, the adapter atomically takes -the task before running the purchase. A competing message that loses the take -finds no task. The adapter stores the purchase input but keeps the parsed AP2 -mandate in process memory. +the task before running the purchase. A competing payment message or +`CancelTask` that loses the take receives the response for the retained task's +state (see [Tasks](#tasks)). The adapter stores the purchase input but keeps +the parsed AP2 mandate in process memory. After a restart, a payment for a resource requiring a mandate must carry `_authorization` again. An otherwise valid payment without it fails with `AUTHORIZATION_REQUIRED` after the task has been taken. A payment sent to an instance with its own receipt database also finds no task; the client gets `TaskNotFoundError` and must start a new purchase. -`GetTask` and `CancelTask` also answer `TaskNotFoundError` for a pending task, -which stays payable. +`GetTask` returns a pending task as it was sent, and the task stays payable. +`CancelTask` ends it without a payment. These follow-ups return `-32602` and keep the task pending: a malformed payment message, a `contextId` that differs from the task's, a role other than @@ -156,10 +161,11 @@ mandate from the first message takes precedence. On a resource with [`idempotency.redelivery`](../configuration.md#resources) (experimental), `x402.payment.required` declares the [payment identifier](x402.md#payment-identifier). Each pending task accepts one -payment submission; a resend returns `TaskNotFoundError`. To retry, start a new -task with the same input and submit a proof with the same `id`. Redelivery -completes the new task with `payment-completed` and the original settlement -entry, without another settlement. If the resource requires a mandate, the new +payment submission; a resend while its record is retained returns +`UnsupportedOperationError`. To retry, start a new task with the same input +and submit a proof with the same `id`. Redelivery completes the new task with +`payment-completed` and the original settlement entry, without another +settlement. If the resource requires a mandate, the new task must carry the same `_authorization`. A refusal fails the task and records its `payment_identifier_*` reason in `x402.payment.error`. An in-flight refusal reports `retryable: false` without `retryAfterSeconds`, because the task has @@ -193,23 +199,102 @@ summary. A non-object merchant body is wrapped as `{ "value": ... }`. Without the x402 extension, payment required is terminal; the buyer sends a new message with the proof. +## Tasks + +`SendMessage` generates task and context ids with `randomUUID()`, independently +of the gateway's `IdGenerator`. Receipts correlate with tasks through the +artifact's `requestId`. Each new purchase starts a new context containing one +adapter-created task. + +The adapter retains task responses in a receipt store with the complete +`task_records` group, including the built-in SQLite store. A durable store +can preserve unexpired records across restarts. Without that group, tasks +stay in process memory under the same limits and are lost on restart. + +Records contain the merchant response, status messages and x402 metadata. +Settlement receipts can include the payer address and transaction hash. The +adapter does not separately attach request input, payment proofs or AP2 +mandates. Merchant response content is retained without redaction. + +`protocols.a2a.tasks.retentionHours` controls how long a task remains readable +after it is stored or updated (default 24 hours). An unpaid x402 extension +task uses the pending-payment expiry described above instead. See +[`protocols.a2a`](../configuration.md#protocolsa2a). + +Once the store has `protocols.a2a.tasks.maxRetained` unexpired records (default +1000), it refuses new records and permits replacements. It does not evict +records, even if the limit is lowered. Free calls cannot evict an unexpired +paid result. A new extension purchase at capacity fails with `GATEWAY_BUSY` +without holding a pending purchase. Other responses are returned without being +retained, and the adapter logs at `warn`. Write exceptions are logged at `error`. +Retention changes affect subsequent writes. + +### Access + +The adapter has no A2A authentication. A task id acts as an access key: anyone +holding it can read the task or request cancellation. An unknown id and +another protocol's task get the same `TaskNotFoundError`. `ListTasks` reads +only the named context and returns no tasks without one. The adapter logs +request ids for correlation; it does not add task or context ids as dedicated +log fields. + +### Operations + +`GetTask` returns the task without `history`, which the adapter does not keep. +A task waiting for payment retains its x402 metadata and remains payable. + +`ListTasks` returns `tasks`, `nextPageToken`, `pageSize` and `totalSize` on +every page. It filters the context's tasks by `status` and the inclusive +`statusTimestampAfter` bound. Tasks are sorted newest first by status timestamp, +then by id in descending order. `totalSize` counts the tasks that match the +filters, and `nextPageToken` is `""` on the last page. Tasks omit `artifacts` +unless `includeArtifacts` is `true`. + +`CancelTask` atomically takes a task waiting for an x402 extension payment, +using the same operation as a payment message. Only the call that takes the +pending task proceeds. The canceled task has no artifacts and carries the +status message "Task canceled." Repeating the cancellation returns it +unchanged. A running or finished task returns `TaskNotCancelableError`. If +the canceled task cannot be recorded, the call returns `-32603`; the pending +purchase has already been removed and can no longer be paid. + +A `SendMessage` that names a task gets these answers: + +| The `taskId` names | Answer | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| a task waiting for payment | the payment path above; a missing `contextId` is inferred | +| a task waiting for payment, with another `contextId` | `-32602`; the task stays payable | +| any other kept task, with another `contextId` | `-32602` | +| any other kept task | `UnsupportedOperationError`: the task takes no more messages | +| no kept task | `TaskNotFoundError` | + +A stored `TASK_STATE_WORKING` task that is absent from this process's running +set is reported by `GetTask` and `ListTasks` as `TASK_STATE_FAILED`. This can +follow a restart or a failed final-result write. Its `INTERNAL_ERROR` envelope +tells the buyer to check with the merchant before paying again. Reads do not +rewrite the record. This assumes one gateway per receipt store. `reconcile` +and manual resolution update the payment attempt, not the task. + +## Errors + The adapter returns JSON-RPC errors for invalid requests and A2A features it cannot serve. Alongside `-32700`, `-32600`, `-32601`, `-32602` and `-32603`, it uses these A2A codes: -| Code | A2A error | Returned for | -| -------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------- | -| `-32001` | `TaskNotFoundError` | an unknown, expired or completed `taskId`; `GetTask` and `CancelTask` for any valid `id` | -| `-32003` | `PushNotificationNotSupportedError` | the four push notification configuration methods; any non-null `configuration.taskPushNotificationConfig` | -| `-32004` | `UnsupportedOperationError` | other unsupported methods; a non-empty `tenant`; the message features listed below | -| `-32005` | `ContentTypeNotSupportedError` | a text, file, inline-byte or URL part; a non-JSON `mediaType`; an `acceptedOutputModes` list that excludes JSON | -| `-32009` | `VersionNotSupportedError` | an unsupported version; a missing header and parameter, or an empty header, is treated as `0.3` | - -Multipart messages, a `contextId` and non-empty `referenceTaskIds` return -`-32004`. Missing `messageId` or a non-user role returns `-32602`. A request -without an `id` returns `-32600` without running. Each A2A error carries a -`google.rpc.ErrorInfo` in `error.data`, with a reason such as -`VERSION_NOT_SUPPORTED` and the domain `a2a-protocol.org`. +| Code | A2A error | Returned for | +| -------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `-32001` | `TaskNotFoundError` | a task id with no unexpired task, on `GetTask`, `CancelTask` or `SendMessage` | +| `-32002` | `TaskNotCancelableError` | `CancelTask` on a running or finished task | +| `-32003` | `PushNotificationNotSupportedError` | the four push notification configuration methods; any non-null `configuration.taskPushNotificationConfig` | +| `-32004` | `UnsupportedOperationError` | other unsupported methods; a non-empty `tenant`; a message on a kept task not waiting for payment; the message features listed below | +| `-32005` | `ContentTypeNotSupportedError` | a text, file, inline-byte or URL part; a non-JSON `mediaType`; an `acceptedOutputModes` list that excludes JSON | +| `-32009` | `VersionNotSupportedError` | an unsupported version; a missing header and parameter, or an empty header, is treated as `0.3` | + +Multipart messages, a `contextId` without a task and non-empty +`referenceTaskIds` return `-32004`. Missing `messageId` or a non-user role +returns `-32602`. A request without an `id` returns `-32600` without running. +Each A2A error carries a `google.rpc.ErrorInfo` in `error.data`, with a reason +such as `VERSION_NOT_SUPPORTED` and the domain `a2a-protocol.org`. ## Pins @@ -233,9 +318,6 @@ The A2A descriptor in `GET /.well-known/agent-commerce` lists these names in - `SendStreamingMessage` -- `GetTask` -- `ListTasks` -- `CancelTask` - `SubscribeToTask` - `CreateTaskPushNotificationConfig` - `GetTaskPushNotificationConfig` @@ -256,11 +338,11 @@ The A2A descriptor in `GET /.well-known/agent-commerce` lists these names in - `authenticated extended agent cards` - `A2A authentication schemes` - `artifact types beyond Agent Commerce outcome data` -- `x402 extension payments across gateway instances`: Instances with separate receipt stores cannot resume each other's tasks. +- `tasks across gateway instances`: Instances with separate receipt stores cannot read, cancel or pay each other's tasks. -Only pending x402 payment tasks can be stored and resumed. +Only a task waiting for an x402 extension payment accepts another message. The A2A adapter accepts `_payment` but does not verify or settle payments or call merchant backends. `@a2a-js/sdk` is a test-only dependency. diff --git a/docs/security.md b/docs/security.md index f3b7e42..199028f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -398,7 +398,7 @@ real funds. | **a backend failure after an MPP settlement** (`upfront` flow) | the error omits `Payment-Receipt`; `PAYMENT-RESPONSE` reports the settlement | `tests/integration/mpp-carriers.test.ts` | | **a backend failure under the MPP `authorization` flow** | nothing settles; the same credential again gets 402 `PAYMENT_REPLAYED` with a fresh challenge and moves no funds | `tests/integration/mpp-carriers.test.ts`, `tests/e2e/payment/mpp-settlement.e2e.test.ts` | | **an MPP settlement refused after the backend ran** (`authorization` flow) | the response is withheld; 402 with a fresh `WWW-Authenticate` and a failed `PAYMENT-RESPONSE` | `tests/integration/mpp-carriers.test.ts`, `tests/unit/payments-mpp/provider.test.ts` | -| **an x402 A2A extension payment sent twice on one task** | after validating a follow-up message, the adapter atomically takes its task before execution; a competing message that loses the take gets `TaskNotFoundError` without another settlement | `tests/integration/a2a-x402-extension.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | +| **an x402 A2A extension payment sent twice on one task** | after validating a follow-up message, the adapter atomically takes its task before execution; a competing message that loses the take gets `UnsupportedOperationError` (`-32004`) while the task record is retained, without another settlement | `tests/integration/a2a-x402-extension.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | | **unauthenticated callers filling the store with unpaid A2A extension tasks** | new unpaid tasks are refused with `GATEWAY_BUSY` when the receipt store already holds 256 unexpired tasks. Tasks expire with their requirement or within an hour; expired tasks cannot be paid, and waiting tasks are not evicted | `tests/unit/protocols-a2a/x402-extension.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/integration/a2a-x402-extension.test.ts` | | expired authorization (`validBefore` in the past) | refused before settlement | `tests/e2e/payment` | | not-yet-valid authorization (`validAfter` in the future) | refused before settlement | `tests/e2e/payment` | @@ -493,7 +493,15 @@ real funds. | **an AP2 mandate with a holder-key binding (`cnf`)** | `AUTHORIZATION_INVALID`, `unsupported_mandate_type`; nothing settles | `tests/unit/authorization-ap2/verifier.test.ts` | | **an A2A request sent without an `id`, as a notification** | `-32600`; nothing runs | `tests/conformance/a2a/errors.test.ts` | | **an x402 A2A extension payment whose `contextId` is not the task's** | `-32602`; the task stays pending | `tests/integration/a2a-x402-extension.test.ts` | -| **an A2A `GetTask` or `CancelTask` naming a pending x402 task** | `-32001` `TaskNotFoundError`; the task stays payable | `tests/integration/a2a-x402-extension.test.ts` | +| **an A2A `GetTask` naming a pending x402 task** | the task as sent, with its x402 metadata; the task stays payable | `tests/integration/a2a-x402-extension.test.ts` | +| **a guessed or sequential A2A task id** | task and context ids use `randomUUID()` independently of `IdGenerator`; the adapter does not add them as dedicated log fields. Unknown ids and another protocol's tasks both get `-32001` | `tests/unit/protocols-a2a/pipeline-mapping.test.ts`, `tests/conformance/a2a/tasks.test.ts` | +| **an A2A `ListTasks` without a context, or naming another buyer's** | an omitted or empty context returns no tasks; a random context id acts as an access key, and each page contains only that context's tasks | `tests/conformance/a2a/tasks.test.ts` | +| **an A2A `CancelTask` raced against a payment message on one task** | both use the same atomic take; only the call that takes the pending purchase proceeds. If cancellation wins, no payment is verified or settled; if payment wins, cancellation returns `-32002` | `tests/unit/protocols-a2a/pending-store.test.ts` (concurrent calls with SQLite and memory), `tests/integration/a2a-x402-extension.test.ts` | +| **an A2A payment message on a retained canceled or finished task** | `-32004` before verification; nothing settles and the backend is not called | `tests/integration/a2a-x402-extension.test.ts`, `tests/conformance/a2a/tasks.test.ts` | +| **free A2A calls filling task retention to push out a paid result** | at capacity, the store refuses new records and permits replacements without evicting unexpired records; a new x402 extension purchase gets `GATEWAY_BUSY` without a pending hold, while other responses are returned without retention | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/task-store.test.ts`, `tests/unit/gateway/main.test.ts` | +| **a payment proof, an AP2 mandate or the request input in a stored A2A task** | the adapter does not separately attach request input, payment proofs or AP2 mandates; merchant response content is retained without redaction | `tests/unit/protocols-a2a/pending-store.test.ts` ("keeps no payment proof, mandate or request input in any task record") | +| **an A2A task read after its retention ends** | `GetTask` returns `-32001` and `ListTasks` omits the record; writable SQLite stores delete expired records during initialization and before storing a record | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/task-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | +| **an A2A payment interrupted before its result is recorded** | a stored working task absent from the local running set is reported as failed with `INTERNAL_ERROR`; the message tells the buyer to check with the merchant before paying again. This assumes one gateway per receipt store | `tests/conformance/a2a/tasks.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts` | | **an A2A 0.x follow-up, with a non-user role, on a pending task** | `-32602`; the task stays pending | same | | **an A2A message carrying a large array of invalid parts or task references** | refused by its length (`PROTOCOL_UNSUPPORTED`) before any element is validated, so no validation issue is built per element | `tests/unit/protocols-a2a/message-mapping.test.ts` | | **an A2A field sent under its proto and JSON names, such as `context_id` beside `contextId`** | `-32602` identifies both spellings before task-store reads or backend calls | `tests/conformance/a2a/params.test.ts` | diff --git a/docs/storage.md b/docs/storage.md index 183694e..fea2599 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -11,6 +11,12 @@ across restarts: [`idempotency.redelivery`](configuration.md#resources), responses delivered with a client retry key, unencrypted. `retentionHours` limits reuse; a later claim sweep deletes expired rows (see [security.md](security.md#buyer-protection)); +- from 2.9.0, retained A2A task responses, subject to + [`protocols.a2a.tasks.retentionHours`](configuration.md#protocolsa2a) and + pending-payment expiry. Records include merchant content and x402 receipts, + which can name the payer address and transaction hash. The adapter does not + separately attach request input, payment proofs or AP2 mandates; merchant + content is stored without redaction (see [A2A tasks](protocols/a2a.md#tasks)); - a record of each deprecated store file it imported. The gateway creates the file at 0600, and any missing directory at 0700, and @@ -86,7 +92,7 @@ does not migrate or import records, or take a write lock on the sources. - It writes `receipts.sqlite`, a consistent snapshot taken with `VACUUM INTO`. Supported receipt schemas are v4 (2.5), v5 (2.6 to 2.8) and v6 (2.9); other versions are refused. The snapshot includes - unencrypted stored responses. + unencrypted stored responses and A2A tasks. - For enabled AP2 or ACP, it also copies any configured legacy file that exists, is not `:memory:` and has no recorded import. The copies are named `ap2-replay.sqlite` or `acp-idempotency.sqlite`. Before the first 2.6.0 @@ -114,8 +120,10 @@ Exit 0 means the backup is complete; 1 means it is not. Restoring a backup discards local records written after its snapshot: -- Later receipts, events, payment attempts, holds, idempotency claims and - pending tasks are lost. Transfers remain on chain. +- Later receipts, events, payment attempts, holds, idempotency claims, + pending tasks and A2A tasks are lost. Transfers remain on chain. Unexpired + restored A2A records retain their snapshot contents and expiry; a restored + `TASK_STATE_WORKING` record is reported as failed. - A proof spent after the backup reaches the facilitator again. On EVM, verification rejects the spent authorization. Solana and NEAR rely on the chain rejecting a transaction or nonce it has already processed. If a replay diff --git a/src/gateway/run.ts b/src/gateway/run.ts index ccfc479..42c367d 100644 --- a/src/gateway/run.ts +++ b/src/gateway/run.ts @@ -123,6 +123,7 @@ export async function runGateway(options: RunGatewayOptions = {}): Promise // picking between agents is choosing whose resources to buy agentName: config.merchant.name, store, + ...(config.protocols.a2a.tasks !== undefined ? { tasks: config.protocols.a2a.tasks } : {}), }), ); } diff --git a/src/protocols/a2a/adapter.ts b/src/protocols/a2a/adapter.ts index a937af6..7b5b97d 100644 --- a/src/protocols/a2a/adapter.ts +++ b/src/protocols/a2a/adapter.ts @@ -5,11 +5,12 @@ * lives, and the specification-fixed `/.well-known/agent-card.json`, declared * through `additionalHttpRoutes` so the gateway needs no A2A-specific routing. * - * Only the synchronous `SendMessage` path is served; every other A2A method - * is listed in `descriptor.unsupported`. This adapter maps reserved payment - * fields but leaves verification, settlement and merchant calls to the pipeline. + * `SendMessage` runs synchronously. `GetTask` and `ListTasks` read retained + * tasks; `CancelTask` ends pending payments. Other A2A methods are listed in + * `descriptor.unsupported`. This adapter maps reserved payment fields but + * leaves verification, settlement and merchant calls to the pipeline. */ -import { createHash } from 'node:crypto'; +import { createHash, randomUUID } from 'node:crypto'; import type { IncomingMessage, ServerResponse } from 'node:http'; import { type AdapterDescriptor, @@ -37,17 +38,20 @@ import { A2A_DEFAULT_MOUNT_PATH, A2A_EXTENSIONS_HEADER, A2A_JSON_MEDIA_TYPE, + A2A_MAX_RETAINED_TASKS, + A2A_METHOD_CANCEL_TASK, + A2A_METHOD_GET_TASK, + A2A_METHOD_LIST_TASKS, A2A_METHOD_SEND_MESSAGE, A2A_PROTOCOL_VERSION, A2A_PUSH_CONFIG_METHODS, - A2A_TASK_LOOKUP_METHODS, + A2A_TASK_RETENTION_HOURS, A2A_UNSUPPORTED_METHODS, A2A_VERSION_HEADER, } from './constants'; import { buildDescriptor } from './descriptor'; import { A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED, - A2A_ERROR_TASK_NOT_FOUND, A2A_ERROR_UNSUPPORTED_OPERATION, A2A_ERROR_VERSION_NOT_SUPPORTED, JSONRPC_INTERNAL_ERROR, @@ -59,7 +63,7 @@ import { jsonRpcError, parseJsonRpcRequest, } from './jsonrpc'; -import { type A2aInvocation, parseInvocation } from './message-mapping'; +import { type A2aInvocation, parseInvocation, readMessage } from './message-mapping'; import { readCancelTaskParams, readGetTaskParams, @@ -67,7 +71,7 @@ import { readSendMessageParams, type SendMessageParams, } from './params'; -import { resumePayment, taskResult } from './payment-resume'; +import { type PaymentResume, resumePayment, taskResult } from './payment-resume'; import { completedTask, failedTask, @@ -75,6 +79,8 @@ import { paymentRequiredTask, type TaskIdentity, } from './task-mapping'; +import { cancelTask, getTask, listTasks, type TaskOperations } from './task-operations'; +import { type A2aTaskStore, createMemoryTasks, createStoredTasks } from './task-store'; import type { A2aAgentCard, A2aTask } from './types'; import { A2A_X402_EXTENSION_URI, @@ -82,6 +88,7 @@ import { createStoredPendingPayments, type PendingPayments, paymentRequiredMetadata, + pendingExpiresAt, requestsX402Extension, } from './x402-extension'; @@ -106,19 +113,52 @@ export interface A2aAdapterOptions { /** Version published on the card. Defaults to this package's version */ readonly agentVersion?: string; /** - * Stores x402 tasks awaiting payment when all pending-task methods are - * present. Durable stores can preserve unexpired tasks across restarts; - * otherwise tasks stay in memory. The adapter never closes this store. + * Store task responses through the complete `task_records` group and unpaid + * x402 purchases through the complete `pending_tasks` group. Each missing + * group falls back to process memory. A durable store can preserve unexpired + * records across restarts. The caller owns and closes the store. */ readonly store?: ReceiptStore; + /** + * Task retention in hours (default 24, range 1 to 8760) and the limit on + * unexpired records when admitting new tasks (default 1000, range 1 to + * 1,000,000). At capacity, new records are refused and replacements allowed; + * existing records are not evicted. + */ + readonly tasks?: { readonly retentionHours?: number; readonly maxRetained?: number }; } -// Parameter validators for task operations -const TASK_PARAM_READERS = new Map) => unknown>([ - ['GetTask', readGetTaskParams], - ['CancelTask', readCancelTaskParams], - ['ListTasks', readListTasksParams], -]); +// Validate an integer option against its bounds, using the default when omitted +function taskLimit( + value: number | undefined, + name: string, + bounds: { readonly min: number; readonly max: number; readonly default: number }, +): number { + if (value === undefined) return bounds.default; + if (!Number.isInteger(value) || value < bounds.min || value > bounds.max) { + throw new CommerceError( + 'CONFIG_INVALID', + `A2A adapter option "tasks.${name}" must be an integer from ${bounds.min} to ${bounds.max}`, + { details: { path: `tasks.${name}` } }, + ); + } + return value; +} + +// Reject invalid parameters before running an operation that reads tasks +async function withParams

( + id: JsonRpcId, + read: () => P, + run: (params: P) => Promise>, +): Promise> { + let params: P; + try { + params = read(); + } catch (err) { + return refusal(id, err); + } + return run(params); +} // Map parameter and message failures to JSON-RPC errors. Keep CommerceError // messages; use a generic message for other thrown values. @@ -147,6 +187,8 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { private readonly agentDescription: string; private readonly agentVersion: string; private readonly store: ReceiptStore | undefined; + private readonly retentionMs: number; + private readonly maxRetained: number; private context: ProtocolAdapterContext | undefined; private started = false; @@ -160,6 +202,10 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { private cardEtag = ''; // Purchases waiting for an x402 extension payment private pendingPayments: PendingPayments | undefined; + // Retained responses for task lookup, listing and cancellation + private tasks: A2aTaskStore | undefined; + // Tasks this process is paying; see `TaskOperations.running` + private readonly running = new Set(); constructor(options: A2aAdapterOptions = {}) { this.mountPath = options.mountPath ?? A2A_DEFAULT_MOUNT_PATH; @@ -167,6 +213,10 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { this.agentDescription = options.agentDescription ?? DEFAULT_AGENT_DESCRIPTION; this.agentVersion = options.agentVersion ?? PACKAGE_VERSION; this.store = options.store; + this.retentionMs = + taskLimit(options.tasks?.retentionHours, 'retentionHours', A2A_TASK_RETENTION_HOURS) * + 3_600_000; + this.maxRetained = taskLimit(options.tasks?.maxRetained, 'maxRetained', A2A_MAX_RETAINED_TASKS); this.descriptor = buildDescriptor(PACKAGE_VERSION); this.additionalHttpRoutes = [ { @@ -205,6 +255,9 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { this.pendingPayments = hasMethodGroup(this.store, 'pending_tasks') ? createStoredPendingPayments(this.store, context.clock) : createPendingPayments(context.clock); + this.tasks = hasMethodGroup(this.store, 'task_records') + ? createStoredTasks(this.store, this.maxRetained) + : createMemoryTasks(context.clock, this.maxRetained); this.cardBody = JSON.stringify(this.card); this.cardEtag = `"${createHash('sha256').update(this.cardBody).digest('base64url')}"`; this.started = true; @@ -242,6 +295,8 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { /** `POST `: the A2A JSON-RPC endpoint */ async handleHttp(req: IncomingMessage, res: ServerResponse): Promise { + // Echo the parsed request id if later processing fails + let requestId: JsonRpcId = null; try { if (!this.started) { this.writeJson( @@ -291,6 +346,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { this.writeJson(res, 200, jsonRpcError(parsed.id, parsed.error.code, parsed.error.message)); return; } + requestId = parsed.request.id; // Parse first to echo the request id on version errors. The query // parameter substitutes for an absent version header. @@ -331,7 +387,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { this.writeJson( res, 200, - jsonRpcError(null, JSONRPC_INTERNAL_ERROR, 'Internal server error.'), + jsonRpcError(requestId, JSONRPC_INTERNAL_ERROR, 'Internal server error.'), ); } } @@ -349,22 +405,6 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { `A2A method "${method}" is not supported: this agent does not support push notifications.`, ); } - // Validate task parameters before returning task-not-found or unsupported-operation errors - const readTaskParams = TASK_PARAM_READERS.get(method); - if (readTaskParams !== undefined) { - try { - readTaskParams(isRecord(params) ? params : {}); - } catch (err) { - return refusal(id, err); - } - } - if (A2A_TASK_LOOKUP_METHODS.includes(method)) { - return jsonRpcError( - id, - A2A_ERROR_TASK_NOT_FOUND, - 'Task not found. Finished tasks are not retained; continue a pending payment with SendMessage.', - ); - } if (A2A_UNSUPPORTED_METHODS.includes(method)) { return jsonRpcError( id, @@ -372,19 +412,45 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { `A2A method "${method}" is not supported by this deployment.`, ); } - if (method !== A2A_METHOD_SEND_MESSAGE) { - return jsonRpcError(id, JSONRPC_METHOD_NOT_FOUND, `Unknown method "${method}".`); + const raw = isRecord(params) ? params : {}; + const ops = this.operations(); + switch (method) { + case A2A_METHOD_SEND_MESSAGE: + break; + case A2A_METHOD_GET_TASK: + return withParams( + id, + () => readGetTaskParams(raw), + (read) => getTask(ops, id, read), + ); + case A2A_METHOD_LIST_TASKS: + return withParams( + id, + () => readListTasksParams(raw), + (read) => listTasks(ops, id, read), + ); + case A2A_METHOD_CANCEL_TASK: + return withParams( + id, + () => readCancelTaskParams(raw), + (read) => cancelTask(ops, id, read), + ); + default: + return jsonRpcError(id, JSONRPC_METHOD_NOT_FOUND, `Unknown method "${method}".`); } let request: SendMessageParams; try { - request = readSendMessageParams(isRecord(params) ? params : {}); + request = readSendMessageParams(raw); + readMessage(request.params); } catch (err) { return refusal(id, err); } - const resumed = await resumePayment(this.context, this.pendingPayments, id, request.params); + const resumed = await resumePayment(this.resume(ops), id, request.params); if (resumed !== undefined) return resumed; + const known = await this.answerKnownTask(ops, id, request.params); + if (known !== undefined) return known; let invocation: ReturnType; try { @@ -393,11 +459,95 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { return refusal(id, err); } - return this.execute(id, invocation, x402Extension); + return this.execute(ops, id, invocation, x402Extension); + } + + // Collect task-operation state after startup; handleHttp returns 503 before startup + private operations(): TaskOperations { + const { context, tasks, pendingPayments } = this; + if (context === undefined || tasks === undefined || pendingPayments === undefined) { + throw new CommerceError('INTERNAL_ERROR', 'A2A adapter is not running.'); + } + return { + tasks, + pendingPayments, + running: this.running, + clock: context.clock, + retainedUntil: () => this.retainedUntil(context), + nextMessageId: () => context.ids.next('a2a-msg'), + }; + } + + private resume(ops: TaskOperations): PaymentResume { + const context = this.context; + if (context === undefined) { + throw new CommerceError('INTERNAL_ERROR', 'A2A adapter is not running.'); + } + return { + context, + pendingPayments: ops.pendingPayments, + keep: (task) => this.keep(ops, task), + running: this.running, + }; + } + + private retainedUntil(context: ProtocolAdapterContext): string { + return new Date(context.clock.now().getTime() + this.retentionMs).toISOString(); } - // One accepted invocation, one `pipeline.execute()` + // Retain a response without failing the call. Log capacity refusals at warn + // and write exceptions at error; return false in either case. + private async keep(ops: TaskOperations, task: A2aTask): Promise { + const logger = this.context?.logger; + try { + if (await ops.tasks.put(task, ops.retainedUntil())) return true; + logger?.warn( + { state: task.status.state }, + 'a2a adapter: task not retained: the task store is full', + ); + } catch (err) { + logger?.error( + { state: task.status.state, err: toLogInfo(err) }, + 'a2a adapter: task not retained', + ); + } + return false; + } + + /** + * Reject further messages on a retained task after the pending-payment path + * declines it, including tasks taken by another call. Terminal tasks accept + * no further messages (A2A 1.0.1 section 3.1.1). Missing records fall through + * to `parseInvocation`, which returns `TaskNotFoundError`. + */ + private async answerKnownTask( + ops: TaskOperations, + id: JsonRpcId, + params: Record, + ): Promise | undefined> { + const message = params['message']; + const taskId = isRecord(message) ? message['taskId'] : undefined; + if (typeof taskId !== 'string') return undefined; + const task = await ops.tasks.get(taskId); + if (task === undefined) return undefined; + const contextId = isRecord(message) ? message['contextId'] : undefined; + if (contextId !== undefined && contextId !== task.contextId) { + return jsonRpcError( + id, + JSONRPC_INVALID_PARAMS, + 'Message "contextId" does not match the task.', + ); + } + return jsonRpcError( + id, + A2A_ERROR_UNSUPPORTED_OPERATION, + 'This task accepts no further messages: send a new message without a taskId.', + ); + } + + // Execute a new purchase and retain its response when storage permits private async execute( + ops: TaskOperations, id: JsonRpcId, invocation: A2aInvocation, x402Extension: boolean, @@ -406,27 +556,27 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { if (context === undefined) { return jsonRpcError(id, JSONRPC_INTERNAL_ERROR, 'A2A adapter is not running.'); } + const ids = this.taskIds(context); + const now = (): TaskIdentity => ({ ...ids, timestamp: context.clock.nowIso() }); const resource = this.skillsById.get(invocation.resourceId); if (resource === undefined) { // A commerce outcome, so a failed task rather than a JSON-RPC error. It // reads the same whether the resource is missing or scoped to another // protocol, so a caller cannot probe what A2A does not expose. - return taskResult( - id, - failedTask( - new CommerceError( - 'RESOURCE_NOT_FOUND', - `Unknown canonical resource "${invocation.resourceId}".`, - ), - this.taskIdentity(context, context.ids.next('a2a')), + const unknown = failedTask( + new CommerceError( + 'RESOURCE_NOT_FOUND', + `Unknown canonical resource "${invocation.resourceId}".`, ), + now(), ); + await this.keep(ops, unknown); + return taskResult(id, unknown); } const requestId = context.ids.next('a2a'); - const identity = this.taskIdentity(context, requestId); - + let task: A2aTask; // Reserved-field extraction sits inside the try: a malformed // `_authorization` envelope becomes a failed task like any other outcome try { @@ -445,43 +595,33 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { ...(authorization !== undefined ? { authorization } : {}), }; const outcome: ExecutionOutcome = await context.pipeline.execute(request); + const identity = now(); if (outcome.kind !== 'payment-required') { - return taskResult(id, completedTask(outcome, identity)); - } - const task = paymentRequiredTask(outcome, identity); - const envelope = outcome.requirement.challenge.envelope; - // The extension carries x402 only; any other rail keeps the terminal task - if (!x402Extension || outcome.requirement.provider !== 'x402' || !isRecord(envelope)) { - return taskResult(id, task); - } - const network = outcome.requirement.network; - const held = await this.pendingPayments?.put( - identity.taskId, - { - contextId: identity.contextId, - resourceId: invocation.resourceId, - input, - ...(authorization !== undefined ? { authorization } : {}), - ...(network !== undefined ? { network } : {}), - }, - outcome.requirement.expiresAt, - ); - if (held === false) { - return taskResult( - id, - failedTask( - new CommerceError( - 'GATEWAY_BUSY', - 'Too many unpaid purchases are waiting for payment; retry shortly.', + task = completedTask(outcome, identity); + } else { + task = paymentRequiredTask(outcome, identity); + const envelope = outcome.requirement.challenge.envelope; + // The extension carries x402 only; any other rail keeps the terminal task + if (x402Extension && outcome.requirement.provider === 'x402' && isRecord(envelope)) { + const network = outcome.requirement.network; + return taskResult( + id, + await this.awaitPayment( + ops, + identity, + inputRequired(task, paymentRequiredMetadata(envelope), identity.statusMessageId), + { + contextId: identity.contextId, + resourceId: invocation.resourceId, + input, + ...(authorization !== undefined ? { authorization } : {}), + ...(network !== undefined ? { network } : {}), + }, + pendingExpiresAt(context.clock.now().getTime(), outcome.requirement.expiresAt), ), - identity, - ), - ); + ); + } } - return taskResult( - id, - inputRequired(task, paymentRequiredMetadata(envelope), identity.statusMessageId), - ); } catch (err) { // A downstream failure is the caller's answer, not a broken frame. // `toCommerceError` replaces a non-commerce error's message, so nothing @@ -491,17 +631,53 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { { resourceId: invocation.resourceId, requestId, err: toLogInfo(error) }, 'a2a adapter: execution failed', ); - return taskResult(id, failedTask(error, identity)); + task = failedTask(error, now()); + } + await this.keep(ops, task); + return taskResult(id, task); + } + + /** + * Record the input-required response before holding its pending purchase, + * using the same expiry. Refuse the purchase if the record does not fit. + * If pending storage throws, `execute` returns a failed task and attempts + * to replace the waiting response with it. + */ + private async awaitPayment( + ops: TaskOperations, + identity: TaskIdentity, + waiting: A2aTask, + purchase: Parameters[1], + expiresAt: string, + ): Promise { + if (!(await ops.tasks.put(waiting, expiresAt))) { + // Capacity also prevents retaining this failure response + return failedTask( + new CommerceError('GATEWAY_BUSY', 'Too many answered tasks are retained; retry shortly.'), + identity, + ); + } + if (!(await ops.pendingPayments.put(waiting.id, purchase, expiresAt))) { + const busy = failedTask( + new CommerceError( + 'GATEWAY_BUSY', + 'Too many unpaid purchases are waiting for payment; retry shortly.', + ), + identity, + ); + await this.keep(ops, busy); + return busy; } + return waiting; } - private taskIdentity(context: ProtocolAdapterContext, requestId: string): TaskIdentity { + // Generate access keys independently of IdGenerator; keep them out of log fields + private taskIds(context: ProtocolAdapterContext): Omit { return { - taskId: requestId, - contextId: context.ids.next('a2a-ctx'), + taskId: randomUUID(), + contextId: randomUUID(), artifactId: context.ids.next('a2a-artifact'), statusMessageId: context.ids.next('a2a-msg'), - timestamp: context.clock.nowIso(), }; } @@ -520,6 +696,8 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { this.cardEtag = ''; this.pendingPayments?.clear(); this.pendingPayments = undefined; + this.tasks = undefined; + this.running.clear(); this.skillsById = new Map(); this.context = undefined; } @@ -536,10 +714,14 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { } } -// True when the response is a task whose status message lists the extension +// True when the response is a task whose status message lists the extension: +// `{ task }` from SendMessage, or the task itself from GetTask function usesX402Extension(response: Record): boolean { - const result = response['result'] as { readonly task?: A2aTask } | undefined; - return result?.task?.status.message?.extensions?.includes(A2A_X402_EXTENSION_URI) === true; + const result = response['result']; + const task = (isRecord(result) && isRecord(result['task']) ? result['task'] : result) as + | Partial + | undefined; + return task?.status?.message?.extensions?.includes(A2A_X402_EXTENSION_URI) === true; } // Compare entity tags weakly; `*` matches any current card diff --git a/src/protocols/a2a/constants.ts b/src/protocols/a2a/constants.ts index 97180cc..ae65d55 100644 --- a/src/protocols/a2a/constants.ts +++ b/src/protocols/a2a/constants.ts @@ -38,9 +38,14 @@ export const A2A_DEFAULT_AGENT_NAME = 'agent-commerce'; */ export const A2A_VERSION_HEADER = 'a2a-version'; -/** The one JSON-RPC method this adapter serves, not the legacy `message/send` */ +/** JSON-RPC method for sending a message */ export const A2A_METHOD_SEND_MESSAGE = 'SendMessage'; +/** Methods for reading, listing and canceling retained tasks */ +export const A2A_METHOD_GET_TASK = 'GetTask'; +export const A2A_METHOD_LIST_TASKS = 'ListTasks'; +export const A2A_METHOD_CANCEL_TASK = 'CancelTask'; + /** * Push notification configuration methods. The card declares no push * support, so these return `PushNotificationNotSupportedError`. @@ -56,31 +61,21 @@ export const A2A_PUSH_CONFIG_METHODS: readonly string[] = [ * A2A methods that exist and are not served here, kept apart from unknown * methods so a caller learns whether it hit a refused method or a typo. The * descriptor and the transport both read this one list. - * `A2A_TASK_LOOKUP_METHODS` get a different error code on the wire. */ export const A2A_UNSUPPORTED_METHODS: readonly string[] = [ 'SendStreamingMessage', - 'GetTask', - 'ListTasks', - 'CancelTask', 'SubscribeToTask', ...A2A_PUSH_CONFIG_METHODS, 'GetExtendedAgentCard', ]; -/** - * Methods A2A gives an agent no capability flag to decline. No task can be - * read back or canceled, so they answer `TaskNotFoundError`. - */ -export const A2A_TASK_LOOKUP_METHODS: readonly string[] = ['GetTask', 'CancelTask']; - -/** - * Terminal states for completed and failed calls. An unpaid x402 extension - * task instead waits in `TASK_STATE_INPUT_REQUIRED`. `GetTask` finds no task - * in any state. - */ +/** Terminal states for completed, failed and canceled tasks */ export const A2A_TASK_STATE_COMPLETED = 'TASK_STATE_COMPLETED'; export const A2A_TASK_STATE_FAILED = 'TASK_STATE_FAILED'; +export const A2A_TASK_STATE_CANCELED = 'TASK_STATE_CANCELED'; + +/** A task processing an x402 payment submission */ +export const A2A_TASK_STATE_WORKING = 'TASK_STATE_WORKING'; /** An unpaid x402 extension task waiting for a payment message */ export const A2A_TASK_STATE_INPUT_REQUIRED = 'TASK_STATE_INPUT_REQUIRED'; @@ -88,8 +83,8 @@ export const A2A_TASK_STATE_INPUT_REQUIRED = 'TASK_STATE_INPUT_REQUIRED'; /** Extension activation header, a comma-separated list of extension URIs */ export const A2A_EXTENSIONS_HEADER = 'a2a-extensions'; -/** Bounds for `protocols.a2a.tasks.retentionHours`, the retention period for answered tasks */ -export const A2A_TASK_RETENTION_HOURS = { min: 1, max: 8760 } as const; +/** Hour bounds and default for task retention in `protocols.a2a.tasks.retentionHours` */ +export const A2A_TASK_RETENTION_HOURS = { min: 1, max: 8760, default: 24 } as const; -/** Bounds for `protocols.a2a.tasks.maxRetained`, the cap on unexpired task records */ -export const A2A_MAX_RETAINED_TASKS = { min: 1, max: 1_000_000 } as const; +/** Bounds and default for the record admission limit, `protocols.a2a.tasks.maxRetained` */ +export const A2A_MAX_RETAINED_TASKS = { min: 1, max: 1_000_000, default: 1000 } as const; diff --git a/src/protocols/a2a/descriptor.ts b/src/protocols/a2a/descriptor.ts index c66b9f7..6ebf0e1 100644 --- a/src/protocols/a2a/descriptor.ts +++ b/src/protocols/a2a/descriptor.ts @@ -14,6 +14,9 @@ const A2A_CAPABILITIES: readonly string[] = [ 'agent-card', 'jsonrpc', 'SendMessage', + 'GetTask', + 'ListTasks', + 'CancelTask', // The x402 A2A transport, opt-in per request 'x402-extension', ]; diff --git a/src/protocols/a2a/jsonrpc.ts b/src/protocols/a2a/jsonrpc.ts index 3aa6ab6..6dc771e 100644 --- a/src/protocols/a2a/jsonrpc.ts +++ b/src/protocols/a2a/jsonrpc.ts @@ -20,7 +20,7 @@ export const JSONRPC_METHOD_NOT_FOUND = -32601; export const JSONRPC_INVALID_PARAMS = -32602; export const JSONRPC_INTERNAL_ERROR = -32603; -/** A2A `TaskNotFoundError` for a task id this stateless adapter cannot find */ +/** A2A `TaskNotFoundError` for a task id with no unexpired task */ export const A2A_ERROR_TASK_NOT_FOUND = -32001; /** A2A `PushNotificationNotSupportedError` for push configuration methods */ @@ -32,6 +32,9 @@ export const A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED = -32003; */ export const A2A_ERROR_UNSUPPORTED_OPERATION = -32004; +/** A2A `TaskNotCancelableError` for a task that is running or finished */ +export const A2A_ERROR_TASK_NOT_CANCELABLE = -32002; + /** A2A `ContentTypeNotSupportedError` for a non-JSON structured data part */ export const A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED = -32005; @@ -42,6 +45,7 @@ export const A2A_ERROR_VERSION_NOT_SUPPORTED = -32009; // Standard JSON-RPC codes carry no A2A error detail. const A2A_ERROR_REASONS: ReadonlyMap = new Map([ [A2A_ERROR_TASK_NOT_FOUND, 'TASK_NOT_FOUND'], + [A2A_ERROR_TASK_NOT_CANCELABLE, 'TASK_NOT_CANCELABLE'], [A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED, 'PUSH_NOTIFICATION_NOT_SUPPORTED'], [A2A_ERROR_UNSUPPORTED_OPERATION, 'UNSUPPORTED_OPERATION'], [A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED, 'CONTENT_TYPE_NOT_SUPPORTED'], diff --git a/src/protocols/a2a/message-mapping.ts b/src/protocols/a2a/message-mapping.ts index 9fac6cf..73797b0 100644 --- a/src/protocols/a2a/message-mapping.ts +++ b/src/protocols/a2a/message-mapping.ts @@ -75,18 +75,43 @@ const ParamsSchema = z.object({ contextId: z.string().optional(), }); +/** SendMessage parameters with a validated message shape, id and role */ +export type A2aMessageParams = z.infer & { + readonly message: { readonly messageId: string }; +}; + +/** + * Validate message shape, a non-empty `messageId` and the user role before + * looking up any named task + */ +export function readMessage(rawParams: unknown): A2aMessageParams { + const parsed = ParamsSchema.safeParse(rawParams); + if (!parsed.success) { + throw invalid( + 'Request must carry a "message" with a "role" and a "parts" array of structured data parts.', + ); + } + const message = parsed.data.message; + // A2A requires a message id. This adapter also rejects an empty one. + if (message.messageId === undefined || message.messageId.length === 0) { + throw invalid('Message must carry a non-empty "messageId".'); + } + const roleProblem = userRoleProblem(message.role); + if (roleProblem !== undefined) throw invalid(roleProblem); + return parsed.data as A2aMessageParams; +} + /** * Continuation is refused rather than ignored: a caller resuming a task would * otherwise get a fresh, independently billed execution back and no signal - * that their task id meant nothing here. Pending payments are handled before - * this check. Unknown or expired task IDs, and competing messages that lost - * the task, receive `TaskNotFoundError`. + * that their task id meant nothing here. The adapter handles pending and + * retained task ids first; any task id reaching this check is unknown or expired. */ -function assertNoContinuation(params: z.infer): void { +function assertNoContinuation(params: A2aMessageParams): void { const message = params.message; if (params.taskId !== undefined || message.taskId !== undefined) { throw unsupported( - 'Task not found: only a task waiting for payment can be continued, so send a request with no taskId.', + 'Task not found: send the message without a taskId to start a new task.', A2A_ERROR_TASK_NOT_FOUND, ); } @@ -138,24 +163,12 @@ function assertSupportedPart(part: Record): void { * a `CommerceError`. Pure: it resolves no resource and touches no payment. */ export function parseInvocation(rawParams: unknown): A2aInvocation { - const parsed = ParamsSchema.safeParse(rawParams); - if (!parsed.success) { - throw invalid( - 'Request must carry a "message" with a "role" and a "parts" array of structured data parts.', - ); - } - const params = parsed.data; + const params = readMessage(rawParams); const message = params.message; - // A2A requires a message id. This adapter also rejects an empty one. - if (message.messageId === undefined || message.messageId.length === 0) { - throw invalid('Message must carry a non-empty "messageId".'); - } const messageId = message.messageId; assertNoContinuation(params); - const roleProblem = userRoleProblem(message.role); - if (roleProblem !== undefined) throw invalid(roleProblem); if (message.parts.length === 0) { throw invalid('Message carries no parts: send exactly one structured data part.'); } diff --git a/src/protocols/a2a/payment-resume.ts b/src/protocols/a2a/payment-resume.ts index ff19da4..b7bced9 100644 --- a/src/protocols/a2a/payment-resume.ts +++ b/src/protocols/a2a/payment-resume.ts @@ -5,8 +5,13 @@ import { toLogInfo } from '../../core/errors'; import { isRecord } from '../../core/is-record'; import { A2A_TASK_STATE_FAILED } from './constants'; import { JSONRPC_INVALID_PARAMS, type JsonRpcId, jsonRpcError, jsonRpcResult } from './jsonrpc'; -import { userRoleProblem } from './message-mapping'; -import { completedTask, failedTask, type TaskIdentity, withStatusMessage } from './task-mapping'; +import { + completedTask, + failedTask, + type TaskIdentity, + withStatusMessage, + workingTask, +} from './task-mapping'; import type { A2aTask } from './types'; import { type PendingPayment, @@ -25,31 +30,34 @@ export function taskResult(id: JsonRpcId, task: A2aTask): Record Promise; + /** Task ids whose payments are running in this process */ + readonly running: Set; +} + /** - * A message on a task waiting for an x402 extension payment, recognized by - * its `taskId` whether or not the header activated the extension again. Any - * other task id falls through to `parseInvocation`, which answers TaskNotFoundError. + * Resume an unpaid x402 task identified by `taskId`, even without the extension + * header. Return undefined if the message names no pending task or loses the + * atomic take to another call. Call after `readMessage` validates the message. */ export async function resumePayment( - context: ProtocolAdapterContext | undefined, - pendingPayments: PendingPayments | undefined, + resume: PaymentResume, id: JsonRpcId, params: unknown, ): Promise | undefined> { + const { context, pendingPayments } = resume; const message = isRecord(params) ? params['message'] : undefined; const taskId = isRecord(message) ? message['taskId'] : undefined; - if (context === undefined || typeof taskId !== 'string') return undefined; - const pending = await pendingPayments?.get(taskId); + if (typeof taskId !== 'string') return undefined; + const pending = await pendingPayments.get(taskId); if (pending === undefined) return undefined; - const messageId = isRecord(message) ? message['messageId'] : undefined; - if (typeof messageId !== 'string' || messageId.length === 0) { - return jsonRpcError(id, JSONRPC_INVALID_PARAMS, 'Message must carry a non-empty "messageId".'); - } - // Apply the same role check as a new purchase - const roleProblem = userRoleProblem(isRecord(message) ? message['role'] : undefined); - if (roleProblem !== undefined) return jsonRpcError(id, JSONRPC_INVALID_PARAMS, roleProblem); - // Reject a mismatched context without consuming the pending task. + // Reject a mismatched context without consuming the pending task const contextId = isRecord(message) ? message['contextId'] : undefined; if (contextId !== undefined && contextId !== pending.contextId) { return jsonRpcError(id, JSONRPC_INVALID_PARAMS, 'Message "contextId" does not match the task.'); @@ -73,51 +81,54 @@ export async function resumePayment( return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message); } } - // Take only after message validation and before execution. The earlier - // read did not claim the task; a competing message that loses this take - // follows the unknown-task path. - const taken = await pendingPayments?.take(taskId); + // Take after validation and before execution; the earlier read did not claim + // the purchase. If another payment or cancellation took it, let the adapter + // respond from the retained task record. + const taken = await pendingPayments.take(taskId); if (taken === undefined) return undefined; const authorization = taken.authorization ?? followUp; - const statusMessageId = context.ids.next('a2a-msg'); - const identity: TaskIdentity = { - taskId, - contextId: taken.contextId, - artifactId: context.ids.next('a2a-artifact'), - statusMessageId, - timestamp: context.clock.nowIso(), - }; if (submission.kind === 'rejected') { - const declined: A2aTask = { - id: taskId, - contextId: taken.contextId, - status: { state: A2A_TASK_STATE_FAILED, timestamp: identity.timestamp }, - artifacts: [], - }; - return taskResult( - id, - withStatusMessage( - declined, - 'Payment was declined.', - statusMessageId, - paymentRejectedMetadata(), - ), + const timestamp = context.clock.nowIso(); + const declined = withStatusMessage( + { + id: taskId, + contextId: taken.contextId, + status: { state: A2A_TASK_STATE_FAILED, timestamp }, + artifacts: [], + }, + 'Payment was declined.', + context.ids.next('a2a-msg'), + paymentRejectedMetadata(), ); + await resume.keep(declined); + return taskResult(id, declined); } - return taskResult( - id, - await payPending( + + resume.running.add(taskId); + try { + await resume.keep(workingTask(taskId, taken.contextId, context.clock.nowIso())); + const paid = await payPending( context, { ...taken, ...(authorization !== undefined ? { authorization } : {}) }, submission.payload, - identity, - ), - ); + { + taskId, + contextId: taken.contextId, + artifactId: context.ids.next('a2a-artifact'), + statusMessageId: context.ids.next('a2a-msg'), + }, + ); + await resume.keep(paid); + return taskResult(id, paid); + } finally { + resume.running.delete(taskId); + } } -// The follow-up consumes the task before the pipeline runs; resends get TaskNotFoundError. -// Suppress its retry delay so the client starts a new task with the same payment id. +// The pending purchase is consumed before execution; resends to a retained +// task get UnsupportedOperationError. Omit the retry delay so the client can +// start a new task with the same payment id. function withoutRetryDelay(error: CommerceError): CommerceError { if (error.details?.['reason'] !== 'payment_identifier_in_flight') return error; const { retryAfterSeconds: _delay, ...details } = error.details; @@ -130,12 +141,13 @@ function withoutRetryDelay(error: CommerceError): CommerceError { }); } -// The pending purchase, now with the x402 `PaymentPayload` as its proof +// Execute the pending purchase with the submitted x402 PaymentPayload. +// Timestamp the returned task when payment processing ends. async function payPending( context: ProtocolAdapterContext, pending: PendingPayment, payload: Record, - identity: TaskIdentity, + ids: Omit, ): Promise { const requestId = context.ids.next('a2a'); const request: CanonicalRequest = { @@ -155,6 +167,7 @@ async function payPending( try { const outcome = await context.pipeline.execute(request); if (outcome.kind === 'delivered' && outcome.payment !== undefined) { + const identity = { ...ids, timestamp: context.clock.nowIso() }; return withStatusMessage( completedTask(outcome, identity), 'Payment settled.', @@ -172,6 +185,7 @@ async function payPending( 'a2a adapter: x402 extension payment failed', ); } + const identity = { ...ids, timestamp: context.clock.nowIso() }; const metadata = paymentFailureMetadata(error, pending.network); const reason = error.details?.['reason']; let text = 'Payment failed.'; diff --git a/src/protocols/a2a/task-mapping.ts b/src/protocols/a2a/task-mapping.ts index a533985..b037e55 100644 --- a/src/protocols/a2a/task-mapping.ts +++ b/src/protocols/a2a/task-mapping.ts @@ -1,5 +1,5 @@ /** - * Execution outcomes as terminal A2A Tasks. + * Execution outcomes as A2A Tasks. * * A2A models an execution's output as a Task carrying Artifacts, so a * completed purchase comes back as one, not as a plain Message, which models @@ -15,7 +15,7 @@ * no A2A-specific delivery, payment-required or error schema. */ import { - type CommerceError, + CommerceError, DELIVERY_SUMMARY_META_KEY, type DeliveredOutcome, type PaymentRequiredOutcome, @@ -26,17 +26,23 @@ import { import { isRecord } from '../../core/is-record'; import { A2A_JSON_MEDIA_TYPE, + A2A_TASK_STATE_CANCELED, A2A_TASK_STATE_COMPLETED, A2A_TASK_STATE_FAILED, A2A_TASK_STATE_INPUT_REQUIRED, + A2A_TASK_STATE_WORKING, } from './constants'; import type { A2aArtifact, A2aTask } from './types'; import { A2A_X402_EXTENSION_URI } from './x402-extension'; export interface TaskIdentity { - /** Gateway request id, reused so a task correlates with receipts and events */ + /** + * Adapter-generated UUID used as the access key for reads and cancellation. + * Receipt and event correlation uses the gateway request id in delivery + * summaries and error envelopes. + */ readonly taskId: string; - /** Fresh for each purchase; a pending x402 payment keeps this context */ + /** A random UUID, fresh for each purchase; a pending x402 payment keeps it */ readonly contextId: string; readonly artifactId: string; /** Id of the agent message on the task status */ @@ -144,3 +150,47 @@ export function failedTask(error: CommerceError, identity: TaskIdentity): A2aTas identity.statusMessageId, ); } + +/** A task processing an x402 payment submission */ +export function workingTask(taskId: string, contextId: string, timestamp: string): A2aTask { + return { + id: taskId, + contextId, + status: { state: A2A_TASK_STATE_WORKING, timestamp }, + artifacts: [], + }; +} + +/** A canceled pending task, without x402 extension status metadata */ +export function canceledTask( + taskId: string, + contextId: string, + timestamp: string, + messageId: string, +): A2aTask { + return withStatusMessage( + { id: taskId, contextId, status: { state: A2A_TASK_STATE_CANCELED, timestamp }, artifacts: [] }, + 'Task canceled.', + messageId, + ); +} + +/** + * Present an interrupted working record as failed at its original timestamp. + * Payment may have settled before the gateway stopped or the final write + * failed, so tell the buyer to check with the merchant before paying again. + * Derived artifact and message ids keep repeated reads of the same record stable. + */ +export function interruptedTask(task: A2aTask): A2aTask { + const error = new CommerceError( + 'INTERNAL_ERROR', + 'This task stopped before its result was recorded. Any payment is in the gateway records: check with the merchant before paying again.', + ); + return failedTask(error, { + taskId: task.id, + contextId: task.contextId, + artifactId: `${task.id}-interrupted`, + statusMessageId: `${task.id}-interrupted`, + timestamp: task.status.timestamp, + }); +} diff --git a/src/protocols/a2a/task-operations.ts b/src/protocols/a2a/task-operations.ts new file mode 100644 index 0000000..e4cce4d --- /dev/null +++ b/src/protocols/a2a/task-operations.ts @@ -0,0 +1,142 @@ +/** + * Serve `GetTask`, `ListTasks` and `CancelTask` from retained task responses + * and pending-payment state, without verification, settlement or backend calls. + * + * The adapter has no A2A authentication. Random task and context ids act as + * access keys: task ids permit reads and cancellation requests; listing is + * limited to the named context. Unknown ids and another protocol's records + * both return task-not-found. Listing without a context returns no tasks. + */ +import { type Clock, CommerceError } from '../../core'; +import { A2A_TASK_STATE_CANCELED, A2A_TASK_STATE_WORKING } from './constants'; +import { + A2A_ERROR_TASK_NOT_CANCELABLE, + A2A_ERROR_TASK_NOT_FOUND, + type JsonRpcId, + jsonRpcError, + jsonRpcResult, +} from './jsonrpc'; +import { + type CancelTaskParams, + encodePageToken, + type GetTaskParams, + type ListTasksParams, +} from './params'; +import { canceledTask, interruptedTask } from './task-mapping'; +import type { A2aTaskStore } from './task-store'; +import type { A2aTask } from './types'; +import type { PendingPayments } from './x402-extension'; + +export interface TaskOperations { + readonly tasks: A2aTaskStore; + readonly pendingPayments: PendingPayments; + /** Task ids whose payments are running in this process */ + readonly running: ReadonlySet; + readonly clock: Clock; + /** Expiry to assign when recording a task now */ + readonly retainedUntil: () => string; + readonly nextMessageId: () => string; +} + +const NOT_FOUND = 'Task not found.'; + +// Report a stored working task as failed when it has no local running entry. +// ponytail: this assumes one gateway per store; shared stores need a lease. +function reported(task: A2aTask, running: ReadonlySet): A2aTask { + return task.status.state === A2A_TASK_STATE_WORKING && !running.has(task.id) + ? interruptedTask(task) + : task; +} + +export async function getTask( + ops: TaskOperations, + id: JsonRpcId, + params: GetTaskParams, +): Promise> { + const task = await ops.tasks.get(params.id); + if (task === undefined) return jsonRpcError(id, A2A_ERROR_TASK_NOT_FOUND, NOT_FOUND); + // No history is retained, so historyLength has no effect + return jsonRpcResult(id, reported(task, ops.running)); +} + +// Compare timestamps newest first, then ids descending, for both sorting and cursors +function before(a: { at: number; id: string }, b: { at: number; id: string }): boolean { + return a.at > b.at || (a.at === b.at && a.id > b.id); +} + +export async function listTasks( + ops: TaskOperations, + id: JsonRpcId, + params: ListTasksParams, +): Promise> { + // Require a context access key before reading its tasks + const recorded = params.contextId === undefined ? [] : await ops.tasks.list(params.contextId); + const after = + params.statusTimestampAfter !== undefined ? Date.parse(params.statusTimestampAfter) : undefined; + const matching = recorded + .map((task) => reported(task, ops.running)) + .filter((task) => params.status === undefined || task.status.state === params.status) + .filter((task) => after === undefined || Date.parse(task.status.timestamp) >= after) + .map((task) => ({ task, key: { at: Date.parse(task.status.timestamp), id: task.id } })) + .sort((a, b) => (before(a.key, b.key) ? -1 : before(b.key, a.key) ? 1 : 0)); + + // Start at the first matching task after the cursor + let start = 0; + if (params.after !== undefined) { + const key = { at: Date.parse(params.after.updatedAt), id: params.after.id }; + start = matching.findIndex((entry) => before(key, entry.key)); + if (start === -1) start = matching.length; + } + const page = matching.slice(start, start + params.pageSize); + const last = page.at(-1); + const more = start + page.length < matching.length; + + return jsonRpcResult(id, { + tasks: page.map(({ task }) => { + if (params.includeArtifacts) return task; + const { artifacts: _artifacts, ...rest } = task; + return rest; + }), + nextPageToken: + more && last !== undefined + ? encodePageToken({ updatedAt: last.task.status.timestamp, id: last.task.id }) + : '', + pageSize: params.pageSize, + totalSize: matching.length, + }); +} + +/** + * Use the same atomic take as payment messages, so only the call that takes + * the pending purchase proceeds. Repeated cancellation returns the canceled + * task unchanged (A2A 1.0.1 section 3.3.1). + */ +export async function cancelTask( + ops: TaskOperations, + id: JsonRpcId, + params: CancelTaskParams, +): Promise> { + const taken = await ops.pendingPayments.take(params.id); + if (taken !== undefined) { + const canceled = canceledTask( + params.id, + taken.contextId, + ops.clock.nowIso(), + ops.nextMessageId(), + ); + // The pending purchase is already removed. If this write fails, the caller + // gets an internal error and the old response keeps its original expiry. + if (!(await ops.tasks.put(canceled, ops.retainedUntil()))) { + throw new CommerceError('STORAGE_ERROR', 'The canceled task did not fit in the task store.'); + } + return jsonRpcResult(id, canceled); + } + const task = await ops.tasks.get(params.id); + if (task === undefined) return jsonRpcError(id, A2A_ERROR_TASK_NOT_FOUND, NOT_FOUND); + if (task.status.state === A2A_TASK_STATE_CANCELED) return jsonRpcResult(id, task); + return jsonRpcError( + id, + A2A_ERROR_TASK_NOT_CANCELABLE, + 'Only a task waiting for payment can be canceled; this one is running or finished.', + ); +} diff --git a/src/protocols/a2a/task-store.ts b/src/protocols/a2a/task-store.ts new file mode 100644 index 0000000..22f98ea --- /dev/null +++ b/src/protocols/a2a/task-store.ts @@ -0,0 +1,82 @@ +/** + * Retain task responses for `GetTask`, `ListTasks` and `CancelTask` until expiry. + * + * Use the receipt store's complete task-record group, or process memory under + * the same capacity and expiry rules. A durable store can preserve records + * across restarts; process memory cannot. At capacity, refuse new records and + * allow replacements without evicting unexpired paid results. These response + * records are separate from the pending state that permits payment. + */ +import type { Clock } from '../../core'; +import type { StoreGroupMethods } from '../../core/store-method-groups'; +import type { A2aTask } from './types'; + +export interface A2aTaskStore { + /** + * Retain the task until `expiresAt`, replacing any record with the same id. + * Return false without storing a new id when the store is full. + */ + put(task: A2aTask, expiresAt: string): Promise; + get(id: string): Promise; + /** Unexpired tasks in the named context, with no ordering guarantee */ + list(contextId: string): Promise; +} + +/** Store tasks as `TaskRecord`s, using the context id as `groupId` */ +export function createStoredTasks( + store: StoreGroupMethods<'task_records'>, + maxRecords: number, +): A2aTaskStore { + return { + put: (task, expiresAt) => + store.putTaskRecord( + { + id: task.id, + protocol: 'a2a', + groupId: task.contextId, + state: task.status.state, + updatedAt: task.status.timestamp, + document: task as unknown as Readonly>, + expiresAt, + }, + { maxRecords }, + ), + async get(id) { + const record = await store.getTaskRecord(id); + // Treat another protocol's record as a missing task + return record?.protocol === 'a2a' ? (record.document as unknown as A2aTask) : undefined; + }, + async list(contextId) { + const records = await store.listTaskRecords({ protocol: 'a2a', groupId: contextId }); + return records.map((record) => record.document as unknown as A2aTask); + }, + }; +} + +/** Retain tasks in a map owned by this process */ +export function createMemoryTasks(clock: Clock, maxRecords: number): A2aTaskStore { + const tasks = new Map(); + const live = (expiresAtMs: number): boolean => expiresAtMs > clock.now().getTime(); + + return { + async put(task, expiresAt) { + // Sweep expired records when capacity would block a new id + if (!tasks.has(task.id) && tasks.size >= maxRecords) { + for (const [id, held] of tasks) if (!live(held.expiresAtMs)) tasks.delete(id); + if (tasks.size >= maxRecords) return false; + } + tasks.set(task.id, { task, expiresAtMs: Date.parse(expiresAt) }); + return true; + }, + async get(id) { + const held = tasks.get(id); + return held !== undefined && live(held.expiresAtMs) ? held.task : undefined; + }, + // ponytail: listing scans all tasks; add a context index if large stores become slow + async list(contextId) { + return [...tasks.values()] + .filter((held) => held.task.contextId === contextId && live(held.expiresAtMs)) + .map((held) => held.task); + }, + }; +} diff --git a/src/protocols/a2a/x402-extension.ts b/src/protocols/a2a/x402-extension.ts index d8720d7..33ebe62 100644 --- a/src/protocols/a2a/x402-extension.ts +++ b/src/protocols/a2a/x402-extension.ts @@ -71,14 +71,20 @@ function expiryMs(nowMs: number, expiresAt: string | undefined): number { return nowMs + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS); } +/** When a purchase waiting for payment expires, as an ISO timestamp */ +export function pendingExpiresAt(nowMs: number, expiresAt: string | undefined): string { + return new Date(expiryMs(nowMs, expiresAt)).toISOString(); +} + type Awaitable = T | Promise; /** * Pending purchases use the supplied receipt store when it has the pending-task * methods, or process memory otherwise. Memory tasks are lost on restart and * are unavailable to other instances. Durable stored tasks can survive - * restarts until expiry. A missing task returns `TaskNotFoundError` before verification or - * settlement, so the client must start a new purchase. + * restarts until expiry. A message on a task that is no longer pending gets an + * error before verification or settlement, and the client must start a new + * purchase. */ export interface PendingPayments { /** Holds a purchase until `expiresAt`; returns false, holding nothing, when full */ diff --git a/src/support/a2a.json b/src/support/a2a.json index db12234..0b7538b 100644 --- a/src/support/a2a.json +++ b/src/support/a2a.json @@ -4,7 +4,7 @@ "title": "A2A", "status": "experimental", "role": "Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension.", - "subset": "Agent Card, `SendMessage`, paid flow and the x402 extension", + "subset": "Agent Card, `SendMessage`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension", "spec": { "revisions": ["1.0.1"], "display": "v1.0.1; negotiation `1.0`; `JSONRPC` binding", @@ -22,13 +22,13 @@ { "name": "agent-card", "status": "experimental" }, { "name": "jsonrpc", "status": "experimental" }, { "name": "SendMessage", "status": "experimental" }, + { "name": "GetTask", "status": "experimental" }, + { "name": "ListTasks", "status": "experimental" }, + { "name": "CancelTask", "status": "experimental" }, { "name": "x402-extension", "status": "experimental" } ], "exclusions": [ { "name": "SendStreamingMessage" }, - { "name": "GetTask" }, - { "name": "ListTasks" }, - { "name": "CancelTask" }, { "name": "SubscribeToTask" }, { "name": "CreateTaskPushNotificationConfig" }, { "name": "GetTaskPushNotificationConfig" }, @@ -50,8 +50,8 @@ { "name": "A2A authentication schemes" }, { "name": "artifact types beyond Agent Commerce outcome data" }, { - "name": "x402 extension payments across gateway instances", - "note": "Instances with separate receipt stores cannot resume each other's tasks." + "name": "tasks across gateway instances", + "note": "Instances with separate receipt stores cannot read, cancel or pay each other's tasks." } ], "deviations": [], @@ -62,14 +62,16 @@ "tests/conformance/a2a/errors.test.ts", "tests/conformance/a2a/free-resource.test.ts", "tests/conformance/a2a/paid-resource.test.ts", - "tests/conformance/a2a/protocol-version.test.ts" + "tests/conformance/a2a/params.test.ts", + "tests/conformance/a2a/protocol-version.test.ts", + "tests/conformance/a2a/tasks.test.ts" ], "skipped": [] }, "gaps": [ { "requirement": "§3.1: GetTask, ListTasks and CancelTask, which every agent implements", - "state": "open" + "state": "closed" }, { "requirement": "§3.2.2: returnImmediately as well as the blocking default", @@ -77,7 +79,7 @@ }, { "requirement": "§3.3.2: validate all input parameters, including tenant and configuration", - "state": "open" + "state": "closed" }, { "requirement": "§7.1: encrypted communication in production; merchant.publicBaseUrl accepts http", diff --git a/tests/conformance/a2a/errors.test.ts b/tests/conformance/a2a/errors.test.ts index 37faa3c..a344aa3 100644 --- a/tests/conformance/a2a/errors.test.ts +++ b/tests/conformance/a2a/errors.test.ts @@ -78,7 +78,7 @@ describe('method routing', () => { expect(body.error?.code).toBe(-32601); }); - it.each(['ListTasks', 'SendStreamingMessage', 'SubscribeToTask', 'GetExtendedAgentCard'])( + it.each(['SendStreamingMessage', 'SubscribeToTask', 'GetExtendedAgentCard'])( 'returns UnsupportedOperationError for known method %s', async (method) => { const { body } = await post({ jsonrpc: '2.0', id: 1, method, params: {} }); @@ -88,13 +88,14 @@ describe('method routing', () => { }, ); - // A2A has no capability flag for declining these two - it.each(['GetTask', 'CancelTask'])('returns TaskNotFoundError for %s', async (method) => { - const { body } = await post({ jsonrpc: '2.0', id: 1, method, params: { id: 'task-1' } }); - expect(body.error?.code).toBe(-32001); - expect(body.error?.message).toContain('not retained'); - expect(body.error?.data).toEqual(errorInfo('TASK_NOT_FOUND')); - }); + it.each(['GetTask', 'CancelTask'])( + 'returns TaskNotFoundError for %s on an unknown id', + async (method) => { + const { body } = await post({ jsonrpc: '2.0', id: 1, method, params: { id: 'task-1' } }); + expect(body.error?.code).toBe(-32001); + expect(body.error?.data).toEqual(errorInfo('TASK_NOT_FOUND')); + }, + ); // Push configuration methods return -32003 when the card disables them it.each([ diff --git a/tests/conformance/a2a/support/gateway.ts b/tests/conformance/a2a/support/gateway.ts index ea58515..766b30f 100644 --- a/tests/conformance/a2a/support/gateway.ts +++ b/tests/conformance/a2a/support/gateway.ts @@ -182,6 +182,8 @@ export interface RunningGateway { settleCalls(): number; /** Pending-task and task-record reads from the store so far */ taskReads(): number; + /** The receipt store, for records a test writes or inspects directly */ + readonly store: ReceiptStore; close(): Promise; } @@ -257,6 +259,7 @@ export async function startConformanceGateway(): Promise { backendCalls: backend.calls, settleCalls: provider.settleCalls, taskReads: reads, + store: sqlite, async close() { await gateway.close(); await store.close(); diff --git a/tests/conformance/a2a/support/task-schema.ts b/tests/conformance/a2a/support/task-schema.ts new file mode 100644 index 0000000..4a4340c --- /dev/null +++ b/tests/conformance/a2a/support/task-schema.ts @@ -0,0 +1,42 @@ +/** + * Validate responses offline with the TCK schema vendored in + * `tests/fixtures/a2a/`, resolving filename references to local definitions. + * Task and response-envelope definitions reject undeclared properties; + * definitions for arbitrary JSON payloads remain open. + */ +import { readFileSync } from 'node:fs'; +import Ajv2020 from 'ajv/dist/2020.js'; +import addFormats from 'ajv-formats'; + +const SCHEMA_PATH = 'tests/fixtures/a2a/tck-5e6f37c2/a2a.json'; + +/** Vendored schema definitions used by the tests, identified by title */ +export type TckDefinition = 'Task' | 'Send Message Response' | 'List Tasks Response'; + +// Map lf.a2a.v1.TaskStatus.jsonschema.json to "Task Status" +// and google.protobuf.Value.jsonschema.json to "Value" +function localRefs(schema: { definitions: Record }): unknown { + const byFile = new Map(); + for (const name of Object.keys(schema.definitions)) { + byFile.set(`lf.a2a.v1.${name.replaceAll(' ', '')}.jsonschema.json`, name); + byFile.set(`google.protobuf.${name}.jsonschema.json`, name); + } + return JSON.parse(JSON.stringify(schema), (key, value: unknown) => { + if (key !== '$ref' || typeof value !== 'string') return value; + const name = byFile.get(value); + if (name === undefined) throw new Error(`Unmapped $ref ${value}`); + return `#/definitions/${encodeURIComponent(name)}`; + }); +} + +const ajv = new Ajv2020({ strict: false, allErrors: true }); +addFormats(ajv); +ajv.addSchema(localRefs(JSON.parse(readFileSync(SCHEMA_PATH, 'utf8'))) as object, 'a2a'); + +/** Return validation errors against the named definition, or an empty list */ +export function tckErrors(definition: TckDefinition, value: unknown): string[] { + const validate = ajv.getSchema(`a2a#/definitions/${encodeURIComponent(definition)}`); + if (validate === undefined) throw new Error(`No TCK definition "${definition}"`); + if (validate(value)) return []; + return (validate.errors ?? []).map((error) => `${error.instancePath} ${error.message}`); +} diff --git a/tests/conformance/a2a/task-schema.test.ts b/tests/conformance/a2a/task-schema.test.ts new file mode 100644 index 0000000..1fc37bb --- /dev/null +++ b/tests/conformance/a2a/task-schema.test.ts @@ -0,0 +1,44 @@ +/** + * Pin the vendored TCK schema to the blob hash recorded in + * tests/fixtures/a2a/tck-5e6f37c2/README.md and check representative valid and + * invalid task responses + */ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import { tckErrors } from './support/task-schema'; + +// Git identifies file contents by hashing the blob header and bytes with SHA-1 +function gitBlobHash(path: string): string { + const content = readFileSync(path); + return createHash('sha1').update(`blob ${content.length}\0`).update(content).digest('hex'); +} + +const TASK = { + id: 'task-1', + contextId: 'context-1', + status: { state: 'TASK_STATE_COMPLETED', timestamp: '2026-11-22T10:00:00.000Z' }, + artifacts: [{ artifactId: 'artifact-1', parts: [{ data: { ok: true } }] }], +}; + +describe('A2A TCK schema at 5e6f37c2', () => { + it('is upstream specification/a2a.json', () => { + expect(gitBlobHash('tests/fixtures/a2a/tck-5e6f37c2/a2a.json')).toBe( + 'd6ea1ed438d788614b597f28009acfc8308aa8db', + ); + }); + + it('accepts a task the proto declares', () => { + expect(tckErrors('Task', TASK)).toEqual([]); + expect(tckErrors('Send Message Response', { task: TASK })).toEqual([]); + }); + + it.each([ + ['a property the proto does not declare', { ...TASK, requestId: 'a2a-1' }], + ['a state outside TaskState', { ...TASK, status: { ...TASK.status, state: 'DONE' } }], + ['a timestamp that is not RFC 3339', { ...TASK, status: { ...TASK.status, timestamp: 'now' } }], + ['a part property inside an artifact', { ...TASK, artifacts: [{ parts: [{ json: {} }] }] }], + ])('rejects a task with %s', (_label, task) => { + expect(tckErrors('Task', task)).not.toEqual([]); + }); +}); diff --git a/tests/conformance/a2a/tasks.test.ts b/tests/conformance/a2a/tasks.test.ts new file mode 100644 index 0000000..1a36556 --- /dev/null +++ b/tests/conformance/a2a/tasks.test.ts @@ -0,0 +1,369 @@ +/** + * Exercise `GetTask`, `ListTasks` and `CancelTask` through raw HTTP and the + * official SDK, using a listening gateway and an in-memory SQLite receipt + * store. The HTTP helper checks successful results against the vendored TCK + * response schema. Tasks waiting for an x402 extension payment are covered in + * `tests/integration/a2a-x402-extension.test.ts`. + */ +import { randomUUID } from 'node:crypto'; +import { TaskState } from '@a2a-js/sdk'; +import { ClientFactory } from '@a2a-js/sdk/client'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import type { TaskRecord } from '../../../src/core'; +import type { A2aTask } from '../../../src/protocols/a2a/types'; +import { MERCHANT_BODY, type RunningGateway, startConformanceGateway } from './support/gateway'; +import { type TckDefinition, tckErrors } from './support/task-schema'; + +let running: RunningGateway; + +beforeAll(async () => { + running = await startConformanceGateway(); +}); + +afterAll(async () => { + await running?.close(); +}); + +interface JsonRpcResponse { + readonly result?: unknown; + readonly error?: { code: number; message: string }; +} + +interface TaskPage { + readonly tasks: Partial[]; + readonly nextPageToken: string; + readonly pageSize: number; + readonly totalSize: number; +} + +// Schema definition for each method's result +const RESULT_SCHEMA: Record = { + SendMessage: 'Send Message Response', + GetTask: 'Task', + CancelTask: 'Task', + ListTasks: 'List Tasks Response', +}; + +async function post(method: string, params: unknown): Promise { + const response = await fetch(`${running.url}/a2a`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'A2A-Version': '1.0' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 't-1', method, params }), + }); + const body = (await response.json()) as JsonRpcResponse; + const schema = RESULT_SCHEMA[method]; + if (body.result !== undefined && schema !== undefined) { + expect(tckErrors(schema, body.result), `${method} result against the TCK schema`).toEqual([]); + } + return body; +} + +function invocation(data: unknown, overrides: Record = {}) { + return { + message: { + role: 'ROLE_USER', + messageId: randomUUID(), + parts: [{ data, mediaType: 'application/json' }], + ...overrides, + }, + }; +} + +async function send(data: unknown): Promise { + const body = await post('SendMessage', invocation(data)); + return (body.result as { task: A2aTask }).task; +} + +const free = () => send({ resource: 'weather_basic', input: { city: 'Berlin' } }); + +function withoutArtifacts(task: A2aTask): Partial { + const { artifacts: _artifacts, ...rest } = task; + return rest; +} + +const HOUR_10 = '2026-11-22T10:00:00.000Z'; +const HOUR_11 = '2026-11-22T11:00:00.000Z'; +const FAR = '2999-01-01T00:00:00.000Z'; + +// A task written to the store as the adapter writes one +async function recorded( + contextId: string, + id: string, + state: string, + timestamp: string, + overrides: Partial = {}, +): Promise { + const task: A2aTask = { id, contextId, status: { state, timestamp }, artifacts: [] }; + await running.store.putTaskRecord?.( + { + id, + protocol: 'a2a', + groupId: contextId, + state, + updatedAt: timestamp, + document: task as unknown as Record, + expiresAt: FAR, + ...overrides, + }, + { maxRecords: 1000 }, + ); + return task; +} + +describe('GetTask', () => { + it('returns a completed task as SendMessage answered it', async () => { + const task = await free(); + + const { result } = await post('GetTask', { id: task.id }); + + expect(task.status.state).toBe('TASK_STATE_COMPLETED'); + expect(result).toEqual(task); + }); + + it.each([ + ['a paid resource asked for without a proof', 'market_report'], + ['an unknown resource', 'no_such_resource'], + ])('returns a failed task: %s', async (_label, resource) => { + const task = await send({ resource, input: { symbol: 'ETH' } }); + + const { result } = await post('GetTask', { id: task.id }); + + expect(task.status.state).toBe('TASK_STATE_FAILED'); + expect(result).toEqual(task); + }); + + it('reads the task through the SDK client', async () => { + const task = await free(); + const client = await new ClientFactory().createFromUrl(running.url); + + const read = await client.getTask({ tenant: '', id: task.id }); + + expect(read.id).toBe(task.id); + expect(read.contextId).toBe(task.contextId); + expect(read.status?.state).toBe(TaskState.TASK_STATE_COMPLETED); + expect(read.artifacts[0]?.parts[0]?.content?.value).toEqual(MERCHANT_BODY); + }); + + it('reports a working task that no process is running as failed, and leaves the record', async () => { + const contextId = randomUUID(); + const id = randomUUID(); + await recorded(contextId, id, 'TASK_STATE_WORKING', HOUR_10); + + const { result } = await post('GetTask', { id }); + + const task = result as A2aTask; + expect(task).toMatchObject({ + id, + contextId, + status: { state: 'TASK_STATE_FAILED', timestamp: HOUR_10 }, + }); + const reason = + 'This task stopped before its result was recorded. Any payment is in the gateway records: check with the merchant before paying again.'; + expect(task.status.message?.parts).toEqual([{ text: reason }]); + expect(task.artifacts[0]?.parts[0]?.data).toEqual({ + status: 'error', + code: 'INTERNAL_ERROR', + message: reason, + retryable: false, + }); + expect((await running.store.getTaskRecord?.(id))?.state).toBe('TASK_STATE_WORKING'); + }); + + it("answers another protocol's task as it answers an unknown id", async () => { + const id = randomUUID(); + await recorded(randomUUID(), id, 'TASK_STATE_COMPLETED', HOUR_10, { protocol: 'acp' }); + + const other = await post('GetTask', { id }); + const unknown = await post('GetTask', { id: randomUUID() }); + + expect(other.error?.code).toBe(-32001); + expect(other).toEqual(unknown); + }); +}); + +describe('ListTasks', () => { + it.each([ + ['no context', {}], + ['an empty context', { contextId: '' }], + ['an unknown context', { contextId: randomUUID() }], + ])('lists nothing for %s, with all four fields', async (_label, params) => { + await free(); + + const { result } = await post('ListTasks', params); + + expect(result).toEqual({ tasks: [], nextPageToken: '', pageSize: 50, totalSize: 0 }); + }); + + it("lists the context's task without its artifacts unless asked", async () => { + const task = await free(); + + const plain = await post('ListTasks', { contextId: task.contextId }); + const full = await post('ListTasks', { contextId: task.contextId, includeArtifacts: true }); + + expect(plain.result).toEqual({ + tasks: [withoutArtifacts(task)], + nextPageToken: '', + pageSize: 50, + totalSize: 1, + }); + expect((full.result as TaskPage).tasks).toEqual([task]); + }); + + it('pages newest first, a tie by id, with a cursor to the next page', async () => { + const contextId = randomUUID(); + const a = await recorded(contextId, 'task-a', 'TASK_STATE_COMPLETED', HOUR_10); + const b = await recorded(contextId, 'task-b', 'TASK_STATE_FAILED', HOUR_11); + const c = await recorded(contextId, 'task-c', 'TASK_STATE_COMPLETED', HOUR_11); + + const first = (await post('ListTasks', { contextId, pageSize: 2 })).result as TaskPage; + const second = ( + await post('ListTasks', { contextId, pageSize: 2, pageToken: first.nextPageToken }) + ).result as TaskPage; + + expect(first).toMatchObject({ pageSize: 2, totalSize: 3 }); + expect(first.tasks).toEqual([withoutArtifacts(c), withoutArtifacts(b)]); + expect(first.nextPageToken).not.toBe(''); + expect(second).toEqual({ + tasks: [withoutArtifacts(a)], + nextPageToken: '', + pageSize: 2, + totalSize: 3, + }); + }); + + it('filters by state, and by status timestamp inclusively', async () => { + const contextId = randomUUID(); + await recorded(contextId, 'task-a', 'TASK_STATE_COMPLETED', HOUR_10); + await recorded(contextId, 'task-b', 'TASK_STATE_FAILED', HOUR_11); + await recorded(contextId, 'task-c', 'TASK_STATE_COMPLETED', HOUR_11); + const ids = async (filter: Record) => { + const page = (await post('ListTasks', { contextId, ...filter })).result as TaskPage; + return { ids: page.tasks.map((task) => task.id), totalSize: page.totalSize }; + }; + + expect(await ids({ status: 'TASK_STATE_COMPLETED' })).toEqual({ + ids: ['task-c', 'task-a'], + totalSize: 2, + }); + expect(await ids({ statusTimestampAfter: HOUR_11 })).toEqual({ + ids: ['task-c', 'task-b'], + totalSize: 2, + }); + expect(await ids({ status: 'TASK_STATE_UNSPECIFIED' })).toEqual({ + ids: ['task-c', 'task-b', 'task-a'], + totalSize: 3, + }); + }); + + it('filters a stale working task by the state it is reported in', async () => { + const contextId = randomUUID(); + await recorded(contextId, 'task-w', 'TASK_STATE_WORKING', HOUR_10); + + const working = (await post('ListTasks', { contextId, status: 'TASK_STATE_WORKING' })) + .result as TaskPage; + const failed = (await post('ListTasks', { contextId, status: 'TASK_STATE_FAILED' })) + .result as TaskPage; + + expect(working.tasks).toEqual([]); + expect(failed.tasks.map((task) => [task.id, task.status?.state])).toEqual([ + ['task-w', 'TASK_STATE_FAILED'], + ]); + }); + + it('lists through the SDK client, which sends every field', async () => { + const task = await free(); + const client = await new ClientFactory().createFromUrl(running.url); + + const page = await client.listTasks({ + tenant: '', + contextId: task.contextId, + status: TaskState.TASK_STATE_UNSPECIFIED, + pageToken: '', + statusTimestampAfter: undefined, + }); + + expect(page.tasks.map((listed) => listed.id)).toEqual([task.id]); + expect(page).toMatchObject({ nextPageToken: '', pageSize: 50, totalSize: 1 }); + }); +}); + +describe('CancelTask', () => { + it.each([ + ['completed', () => free()], + ['failed', () => send({ resource: 'market_report', input: { symbol: 'ETH' } })], + ])('refuses a %s task, which stays as it was', async (_label, make) => { + const task = await make(); + + const { error } = await post('CancelTask', { id: task.id }); + + expect(error?.code).toBe(-32002); + expect((await post('GetTask', { id: task.id })).result).toEqual(task); + }); + + it('returns a canceled task unchanged through the SDK client', async () => { + const contextId = randomUUID(); + const canceled = await recorded(contextId, randomUUID(), 'TASK_STATE_CANCELED', HOUR_10); + const client = await new ClientFactory().createFromUrl(running.url); + + const again = await client.cancelTask({ tenant: '', id: canceled.id, metadata: undefined }); + + expect(again.id).toBe(canceled.id); + expect(again.status?.state).toBe(TaskState.TASK_STATE_CANCELED); + expect((await post('GetTask', { id: canceled.id })).result).toEqual(canceled); + }); +}); + +describe('SendMessage naming a recorded task', () => { + it('refuses a message on a finished task and runs nothing', async () => { + const task = await free(); + const calls = running.backendCalls(); + + const inferred = await post('SendMessage', invocation({}, { taskId: task.id })); + const matching = await post( + 'SendMessage', + invocation({}, { taskId: task.id, contextId: task.contextId }), + ); + + expect(inferred.error?.code).toBe(-32004); + expect(matching.error?.code).toBe(-32004); + expect(running.backendCalls()).toBe(calls); + }); + + it('refuses a context that does not match the task', async () => { + const task = await free(); + + const { error } = await post( + 'SendMessage', + invocation({}, { taskId: task.id, contextId: randomUUID() }), + ); + + expect(error?.code).toBe(-32602); + }); +}); + +describe('task and context ids', () => { + it('gives every task its own random ids, apart from the request id', async () => { + const [one, two] = await Promise.all([free(), free()]); + const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + + for (const task of [one, two]) { + expect(task?.id).toMatch(uuid); + expect(task?.contextId).toMatch(uuid); + } + expect(new Set([one?.id, one?.contextId, two?.id, two?.contextId]).size).toBe(4); + const summary = one?.artifacts[0]?.metadata?.['agent-commerce/delivery'] as + | { requestId?: string } + | undefined; + expect(summary?.requestId).toMatch(/^a2a/); + expect(summary?.requestId).not.toBe(one?.id); + }); + + it("lists nothing from another task's context", async () => { + const mine = await free(); + await free(); + + const page = (await post('ListTasks', { contextId: mine.contextId })).result as TaskPage; + + expect(page.tasks.map((task) => task.id)).toEqual([mine.id]); + }); +}); diff --git a/tests/fixtures/a2a/tck-5e6f37c2/README.md b/tests/fixtures/a2a/tck-5e6f37c2/README.md new file mode 100644 index 0000000..0a629da --- /dev/null +++ b/tests/fixtures/a2a/tck-5e6f37c2/README.md @@ -0,0 +1,32 @@ +# Vendored A2A TCK schema - `a2a-tck@5e6f37c2` + +`a2a.json` is the vendored response schema recorded below. The HTTP helpers in +`tests/conformance/a2a/tasks.test.ts` and +`tests/integration/a2a-x402-extension.test.ts` validate successful results +against it offline. Task and response-envelope definitions reject undeclared +properties; arbitrary JSON payloads remain open. + +| | | +|---|---| +| Upstream repository | https://github.com/a2aproject/a2a-tck | +| Upstream path | `specification/a2a.json` | +| Upstream commit | `5e6f37c2d38eb3d7684686243c34d365c83df49b` (2026-11-18) | +| Git blob | `d6ea1ed438d788614b597f28009acfc8308aa8db` | +| A2A revision | v1.0.1, `3303592588e388e62e0f69f701af531d2f4e3991` (the TCK's `specification/version.json`) | +| Date vendored | 2026-11-22 | +| License | Apache-2.0, (c) the a2a-tck contributors - see the upstream `LICENSE` | + +The schema's `$ref` values use filenames such as +`lf.a2a.v1.Task.jsonschema.json`. The local helper, +`tests/conformance/a2a/support/task-schema.ts`, maps these filenames to titled +definitions, such as `Task`, for offline validation. The upstream resolver is +`tck/validators/json_schema.py`. + +`biome.json` excludes this directory to preserve the copied bytes. +`tests/conformance/a2a/task-schema.test.ts` checks the file's git blob hash. + +## Updating + +Copy the file from the chosen TCK commit into a new directory named after +that commit. Update the blob hash in the pin test and the schema path in +`task-schema.ts`. Prefer a TCK tag that vendors A2A v1.0.1. diff --git a/tests/fixtures/a2a/tck-5e6f37c2/a2a.json b/tests/fixtures/a2a/tck-5e6f37c2/a2a.json new file mode 100644 index 0000000..d6ea1ed --- /dev/null +++ b/tests/fixtures/a2a/tck-5e6f37c2/a2a.json @@ -0,0 +1,1961 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "A2A Protocol Schemas", + "description": "Non-normative JSON Schema bundle extracted from proto definitions.", + "version": "v1", + "definitions": { + "Struct": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Struct", + "type": "object" + }, + "Timestamp": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "date-time", + "title": "Timestamp", + "type": "string" + }, + "Value": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Value" + }, + "API Key Security Scheme": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines a security scheme using an API key.", + "properties": { + "description": { + "default": "", + "description": "An optional description for the security scheme.", + "type": "string" + }, + "location": { + "default": "", + "description": "The location of the API key. Valid values are \"query\", \"header\", or \"cookie\".", + "type": "string" + }, + "name": { + "default": "", + "description": "The name of the header, query, or cookie parameter to be used.", + "type": "string" + } + }, + "title": "API Key Security Scheme", + "type": "object" + }, + "Agent Capabilities": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines optional capabilities supported by an agent.", + "patternProperties": { + "^(extended_agent_card)$": { + "description": "Indicates if the agent supports providing an extended agent card when authenticated.", + "type": "boolean" + }, + "^(push_notifications)$": { + "description": "Indicates if the agent supports sending push notifications for asynchronous task updates.", + "type": "boolean" + } + }, + "properties": { + "extendedAgentCard": { + "description": "Indicates if the agent supports providing an extended agent card when authenticated.", + "type": "boolean" + }, + "extensions": { + "description": "A list of protocol extensions supported by the agent.", + "items": { + "$ref": "lf.a2a.v1.AgentExtension.jsonschema.json" + }, + "type": "array" + }, + "pushNotifications": { + "description": "Indicates if the agent supports sending push notifications for asynchronous task updates.", + "type": "boolean" + }, + "streaming": { + "description": "Indicates if the agent supports streaming responses.", + "type": "boolean" + } + }, + "title": "Agent Capabilities", + "type": "object" + }, + "Agent Card": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A self-describing manifest for an agent. It provides essential\n metadata including the agent's identity, capabilities, skills, supported\n communication methods, and security requirements.\n Next ID: 20", + "patternProperties": { + "^(default_input_modes)$": { + "description": "The set of interaction modes that the agent supports across all skills.\n This can be overridden per skill. Defined as media types.", + "items": { + "type": "string" + }, + "type": "array" + }, + "^(default_output_modes)$": { + "description": "The media types supported as outputs from this agent.", + "items": { + "type": "string" + }, + "type": "array" + }, + "^(documentation_url)$": { + "description": "A URL providing additional documentation about the agent.", + "type": "string" + }, + "^(icon_url)$": { + "description": "Optional. A URL to an icon for the agent.", + "type": "string" + }, + "^(security_requirements)$": { + "description": "Security requirements for contacting the agent.", + "items": { + "$ref": "lf.a2a.v1.SecurityRequirement.jsonschema.json" + }, + "type": "array" + }, + "^(security_schemes)$": { + "additionalProperties": { + "$ref": "lf.a2a.v1.SecurityScheme.jsonschema.json" + }, + "description": "The security scheme details used for authenticating with this agent.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "^(supported_interfaces)$": { + "description": "Ordered list of supported interfaces. The first entry is preferred.", + "items": { + "$ref": "lf.a2a.v1.AgentInterface.jsonschema.json" + }, + "type": "array" + } + }, + "properties": { + "capabilities": { + "$ref": "lf.a2a.v1.AgentCapabilities.jsonschema.json", + "description": "A2A Capability set supported by the agent." + }, + "defaultInputModes": { + "description": "The set of interaction modes that the agent supports across all skills.\n This can be overridden per skill. Defined as media types.", + "items": { + "type": "string" + }, + "type": "array" + }, + "defaultOutputModes": { + "description": "The media types supported as outputs from this agent.", + "items": { + "type": "string" + }, + "type": "array" + }, + "description": { + "default": "", + "description": "A human-readable description of the agent, assisting users and other agents\n in understanding its purpose.\n Example: \"Agent that helps users with recipes and cooking.\"", + "type": "string" + }, + "documentationUrl": { + "description": "A URL providing additional documentation about the agent.", + "type": "string" + }, + "iconUrl": { + "description": "Optional. A URL to an icon for the agent.", + "type": "string" + }, + "name": { + "default": "", + "description": "A human readable name for the agent.\n Example: \"Recipe Agent\"", + "type": "string" + }, + "provider": { + "$ref": "lf.a2a.v1.AgentProvider.jsonschema.json", + "description": "The service provider of the agent." + }, + "securityRequirements": { + "description": "Security requirements for contacting the agent.", + "items": { + "$ref": "lf.a2a.v1.SecurityRequirement.jsonschema.json" + }, + "type": "array" + }, + "securitySchemes": { + "additionalProperties": { + "$ref": "lf.a2a.v1.SecurityScheme.jsonschema.json" + }, + "description": "The security scheme details used for authenticating with this agent.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "signatures": { + "description": "JSON Web Signatures computed for this `AgentCard`.", + "items": { + "$ref": "lf.a2a.v1.AgentCardSignature.jsonschema.json" + }, + "type": "array" + }, + "skills": { + "description": "Skills represent the abilities of an agent.\n It is largely a descriptive concept but represents a more focused set of behaviors that the\n agent is likely to succeed at.", + "items": { + "$ref": "lf.a2a.v1.AgentSkill.jsonschema.json" + }, + "type": "array" + }, + "supportedInterfaces": { + "description": "Ordered list of supported interfaces. The first entry is preferred.", + "items": { + "$ref": "lf.a2a.v1.AgentInterface.jsonschema.json" + }, + "type": "array" + }, + "version": { + "default": "", + "description": "The version of the agent.\n Example: \"1.0.0\"", + "type": "string" + } + }, + "title": "Agent Card", + "type": "object" + }, + "Agent Card Signature": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "AgentCardSignature represents a JWS signature of an AgentCard.\n This follows the JSON format of an RFC 7515 JSON Web Signature (JWS).", + "properties": { + "header": { + "$ref": "google.protobuf.Struct.jsonschema.json", + "description": "The unprotected JWS header values." + }, + "protected": { + "default": "", + "description": "(-- api-linter: core::0140::reserved-words=disabled\n aip.dev/not-precedent: Backwards compatibility --)\n Required. The protected JWS header for the signature. This is always a\n base64url-encoded JSON object.", + "type": "string" + }, + "signature": { + "default": "", + "description": "Required. The computed signature, base64url-encoded.", + "type": "string" + } + }, + "title": "Agent Card Signature", + "type": "object" + }, + "Agent Extension": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A declaration of a protocol extension supported by an Agent.", + "properties": { + "description": { + "default": "", + "description": "A human-readable description of how this agent uses the extension.", + "type": "string" + }, + "params": { + "$ref": "google.protobuf.Struct.jsonschema.json", + "description": "Optional. Extension-specific configuration parameters." + }, + "required": { + "default": false, + "description": "If true, the client must understand and comply with the extension's requirements.", + "type": "boolean" + }, + "uri": { + "default": "", + "description": "The unique URI identifying the extension.", + "type": "string" + } + }, + "title": "Agent Extension", + "type": "object" + }, + "Agent Interface": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Declares a combination of a target URL, transport and protocol version for interacting with the agent.\n This allows agents to expose the same functionality over multiple protocol binding mechanisms.", + "patternProperties": { + "^(protocol_binding)$": { + "default": "", + "description": "The protocol binding supported at this URL. This is an open form string, to be\n easily extended for other protocol bindings. The core ones officially\n supported are `JSONRPC`, `GRPC` and `HTTP+JSON`.", + "type": "string" + }, + "^(protocol_version)$": { + "default": "", + "description": "The version of the A2A protocol this interface exposes.\n Use the latest supported minor version per major version.\n Examples: \"0.3\", \"1.0\"", + "type": "string" + } + }, + "properties": { + "protocolBinding": { + "default": "", + "description": "The protocol binding supported at this URL. This is an open form string, to be\n easily extended for other protocol bindings. The core ones officially\n supported are `JSONRPC`, `GRPC` and `HTTP+JSON`.", + "type": "string" + }, + "protocolVersion": { + "default": "", + "description": "The version of the A2A protocol this interface exposes.\n Use the latest supported minor version per major version.\n Examples: \"0.3\", \"1.0\"", + "type": "string" + }, + "tenant": { + "default": "", + "description": "Optional. An opaque string used for routing requests to a specific agent\n or tenant when multiple agents are served behind a single A2A endpoint.\n When set, clients MUST include this value in the `tenant` field of all\n request messages sent to this interface. The server is responsible for\n interpreting the value and routing requests accordingly; the protocol\n does not define its format or semantics.", + "type": "string" + }, + "url": { + "default": "", + "description": "The URL where this interface is available. Must be a valid absolute HTTPS URL in production.\n Example: \"https://api.example.com/a2a/v1\", \"https://grpc.example.com/a2a\"", + "type": "string" + } + }, + "title": "Agent Interface", + "type": "object" + }, + "Agent Provider": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents the service provider of an agent.", + "properties": { + "organization": { + "default": "", + "description": "The name of the agent provider's organization.\n Example: \"Google\"", + "type": "string" + }, + "url": { + "default": "", + "description": "A URL for the agent provider's website or relevant documentation.\n Example: \"https://ai.google.dev\"", + "type": "string" + } + }, + "title": "Agent Provider", + "type": "object" + }, + "Agent Skill": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents a distinct capability or function that an agent can perform.", + "patternProperties": { + "^(input_modes)$": { + "description": "The set of supported input media types for this skill, overriding the agent's defaults.", + "items": { + "type": "string" + }, + "type": "array" + }, + "^(output_modes)$": { + "description": "The set of supported output media types for this skill, overriding the agent's defaults.", + "items": { + "type": "string" + }, + "type": "array" + }, + "^(security_requirements)$": { + "description": "Security schemes necessary for this skill.", + "items": { + "$ref": "lf.a2a.v1.SecurityRequirement.jsonschema.json" + }, + "type": "array" + } + }, + "properties": { + "description": { + "default": "", + "description": "A detailed description of the skill.", + "type": "string" + }, + "examples": { + "description": "Example prompts or scenarios that this skill can handle.", + "items": { + "type": "string" + }, + "type": "array" + }, + "id": { + "default": "", + "description": "A unique identifier for the agent's skill.", + "type": "string" + }, + "inputModes": { + "description": "The set of supported input media types for this skill, overriding the agent's defaults.", + "items": { + "type": "string" + }, + "type": "array" + }, + "name": { + "default": "", + "description": "A human-readable name for the skill.", + "type": "string" + }, + "outputModes": { + "description": "The set of supported output media types for this skill, overriding the agent's defaults.", + "items": { + "type": "string" + }, + "type": "array" + }, + "securityRequirements": { + "description": "Security schemes necessary for this skill.", + "items": { + "$ref": "lf.a2a.v1.SecurityRequirement.jsonschema.json" + }, + "type": "array" + }, + "tags": { + "description": "A set of keywords describing the skill's capabilities.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "title": "Agent Skill", + "type": "object" + }, + "Artifact": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Artifacts represent task outputs.", + "patternProperties": { + "^(artifact_id)$": { + "default": "", + "description": "Unique identifier (e.g. UUID) for the artifact. It must be unique within a task.", + "type": "string" + } + }, + "properties": { + "artifactId": { + "default": "", + "description": "Unique identifier (e.g. UUID) for the artifact. It must be unique within a task.", + "type": "string" + }, + "description": { + "default": "", + "description": "Optional. A human readable description of the artifact.", + "type": "string" + }, + "extensions": { + "description": "The URIs of extensions that are present or contributed to this Artifact.", + "items": { + "type": "string" + }, + "type": "array" + }, + "metadata": { + "$ref": "google.protobuf.Struct.jsonschema.json", + "description": "Optional. Metadata included with the artifact." + }, + "name": { + "default": "", + "description": "A human readable name for the artifact.", + "type": "string" + }, + "parts": { + "description": "The content of the artifact. Must contain at least one part.", + "items": { + "$ref": "lf.a2a.v1.Part.jsonschema.json" + }, + "type": "array" + } + }, + "title": "Artifact", + "type": "object" + }, + "Authentication Info": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines authentication details, used for push notifications.", + "properties": { + "credentials": { + "default": "", + "description": "Push Notification credentials. Format depends on the scheme (e.g., token for Bearer).", + "type": "string" + }, + "scheme": { + "default": "", + "description": "HTTP Authentication Scheme from the [IANA registry](https://www.iana.org/assignments/http-authschemes/).\n Examples: `Bearer`, `Basic`, `Digest`.\n Scheme names are case-insensitive per [RFC 9110 Section 11.1](https://www.rfc-editor.org/rfc/rfc9110#section-11.1).", + "type": "string" + } + }, + "title": "Authentication Info", + "type": "object" + }, + "Authorization CodeO Auth Flow": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines configuration details for the OAuth 2.0 Authorization Code flow.", + "patternProperties": { + "^(authorization_url)$": { + "default": "", + "description": "The authorization URL to be used for this flow.", + "type": "string" + }, + "^(pkce_required)$": { + "default": false, + "description": "Indicates if PKCE (RFC 7636) is required for this flow.\n PKCE should always be used for public clients and is recommended for all clients.", + "type": "boolean" + }, + "^(refresh_url)$": { + "default": "", + "description": "The URL to be used for obtaining refresh tokens.", + "type": "string" + }, + "^(token_url)$": { + "default": "", + "description": "The token URL to be used for this flow.", + "type": "string" + } + }, + "properties": { + "authorizationUrl": { + "default": "", + "description": "The authorization URL to be used for this flow.", + "type": "string" + }, + "pkceRequired": { + "default": false, + "description": "Indicates if PKCE (RFC 7636) is required for this flow.\n PKCE should always be used for public clients and is recommended for all clients.", + "type": "boolean" + }, + "refreshUrl": { + "default": "", + "description": "The URL to be used for obtaining refresh tokens.", + "type": "string" + }, + "scopes": { + "additionalProperties": { + "type": "string" + }, + "description": "The available scopes for the OAuth2 security scheme.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "tokenUrl": { + "default": "", + "description": "The token URL to be used for this flow.", + "type": "string" + } + }, + "title": "Authorization CodeO Auth Flow", + "type": "object" + }, + "Cancel Task Request": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents a request for the `CancelTask` method.", + "properties": { + "id": { + "default": "", + "description": "The resource ID of the task to cancel.", + "type": "string" + }, + "metadata": { + "$ref": "google.protobuf.Struct.jsonschema.json", + "description": "A flexible key-value map for passing additional context or parameters." + }, + "tenant": { + "default": "", + "description": "Optional. Opaque routing identifier. Must match the `tenant` value from\n the selected `AgentInterface` in the Agent Card when that field is set.", + "type": "string" + } + }, + "title": "Cancel Task Request", + "type": "object" + }, + "Client CredentialsO Auth Flow": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines configuration details for the OAuth 2.0 Client Credentials flow.", + "patternProperties": { + "^(refresh_url)$": { + "default": "", + "description": "The URL to be used for obtaining refresh tokens.", + "type": "string" + }, + "^(token_url)$": { + "default": "", + "description": "The token URL to be used for this flow.", + "type": "string" + } + }, + "properties": { + "refreshUrl": { + "default": "", + "description": "The URL to be used for obtaining refresh tokens.", + "type": "string" + }, + "scopes": { + "additionalProperties": { + "type": "string" + }, + "description": "The available scopes for the OAuth2 security scheme.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "tokenUrl": { + "default": "", + "description": "The token URL to be used for this flow.", + "type": "string" + } + }, + "title": "Client CredentialsO Auth Flow", + "type": "object" + }, + "Delete Task Push Notification Config Request": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents a request for the `DeleteTaskPushNotificationConfig` method.", + "patternProperties": { + "^(task_id)$": { + "default": "", + "description": "The parent task resource ID.", + "type": "string" + } + }, + "properties": { + "id": { + "default": "", + "description": "The resource ID of the configuration to delete.", + "type": "string" + }, + "taskId": { + "default": "", + "description": "The parent task resource ID.", + "type": "string" + }, + "tenant": { + "default": "", + "description": "Optional. Opaque routing identifier. Must match the `tenant` value from\n the selected `AgentInterface` in the Agent Card when that field is set.", + "type": "string" + } + }, + "title": "Delete Task Push Notification Config Request", + "type": "object" + }, + "Device CodeO Auth Flow": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines configuration details for the OAuth 2.0 Device Code flow (RFC 8628).\n This flow is designed for input-constrained devices such as IoT devices,\n and CLI tools where the user authenticates on a separate device.", + "patternProperties": { + "^(device_authorization_url)$": { + "default": "", + "description": "The device authorization endpoint URL.", + "type": "string" + }, + "^(refresh_url)$": { + "default": "", + "description": "The URL to be used for obtaining refresh tokens.", + "type": "string" + }, + "^(token_url)$": { + "default": "", + "description": "The token URL to be used for this flow.", + "type": "string" + } + }, + "properties": { + "deviceAuthorizationUrl": { + "default": "", + "description": "The device authorization endpoint URL.", + "type": "string" + }, + "refreshUrl": { + "default": "", + "description": "The URL to be used for obtaining refresh tokens.", + "type": "string" + }, + "scopes": { + "additionalProperties": { + "type": "string" + }, + "description": "The available scopes for the OAuth2 security scheme.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "tokenUrl": { + "default": "", + "description": "The token URL to be used for this flow.", + "type": "string" + } + }, + "title": "Device CodeO Auth Flow", + "type": "object" + }, + "Get Extended Agent Card Request": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents a request for the `GetExtendedAgentCard` method.", + "properties": { + "tenant": { + "default": "", + "description": "Optional. Opaque routing identifier. Must match the `tenant` value from\n the selected `AgentInterface` in the Agent Card when that field is set.", + "type": "string" + } + }, + "title": "Get Extended Agent Card Request", + "type": "object" + }, + "Get Task Push Notification Config Request": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents a request for the `GetTaskPushNotificationConfig` method.", + "patternProperties": { + "^(task_id)$": { + "default": "", + "description": "The parent task resource ID.", + "type": "string" + } + }, + "properties": { + "id": { + "default": "", + "description": "The resource ID of the configuration to retrieve.", + "type": "string" + }, + "taskId": { + "default": "", + "description": "The parent task resource ID.", + "type": "string" + }, + "tenant": { + "default": "", + "description": "Optional. Opaque routing identifier. Must match the `tenant` value from\n the selected `AgentInterface` in the Agent Card when that field is set.", + "type": "string" + } + }, + "title": "Get Task Push Notification Config Request", + "type": "object" + }, + "Get Task Request": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents a request for the `GetTask` method.", + "patternProperties": { + "^(history_length)$": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "description": "The maximum number of most recent messages from the task's history to retrieve. An\n unset value means the client does not impose any limit. A value of zero is\n a request to not include any messages. The server MUST NOT return more\n messages than the provided value, but MAY apply a lower limit." + } + }, + "properties": { + "historyLength": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "description": "The maximum number of most recent messages from the task's history to retrieve. An\n unset value means the client does not impose any limit. A value of zero is\n a request to not include any messages. The server MUST NOT return more\n messages than the provided value, but MAY apply a lower limit." + }, + "id": { + "default": "", + "description": "The resource ID of the task to retrieve.", + "type": "string" + }, + "tenant": { + "default": "", + "description": "Optional. Opaque routing identifier. Must match the `tenant` value from\n the selected `AgentInterface` in the Agent Card when that field is set.", + "type": "string" + } + }, + "title": "Get Task Request", + "type": "object" + }, + "HTTP Auth Security Scheme": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines a security scheme using HTTP authentication.", + "patternProperties": { + "^(bearer_format)$": { + "default": "", + "description": "A hint to the client to identify how the bearer token is formatted (e.g., \"JWT\").\n Primarily for documentation purposes.", + "type": "string" + } + }, + "properties": { + "bearerFormat": { + "default": "", + "description": "A hint to the client to identify how the bearer token is formatted (e.g., \"JWT\").\n Primarily for documentation purposes.", + "type": "string" + }, + "description": { + "default": "", + "description": "An optional description for the security scheme.", + "type": "string" + }, + "scheme": { + "default": "", + "description": "The name of the HTTP Authentication scheme to be used in the Authorization header,\n as defined in RFC7235 (e.g., \"Bearer\").\n This value should be registered in the IANA Authentication Scheme registry.", + "type": "string" + } + }, + "title": "HTTP Auth Security Scheme", + "type": "object" + }, + "ImplicitO Auth Flow": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Deprecated: Use Authorization Code + PKCE instead.", + "patternProperties": { + "^(authorization_url)$": { + "default": "", + "description": "The authorization URL to be used for this flow. This MUST be in the\n form of a URL. The OAuth2 standard requires the use of TLS", + "type": "string" + }, + "^(refresh_url)$": { + "default": "", + "description": "The URL to be used for obtaining refresh tokens. This MUST be in the\n form of a URL. The OAuth2 standard requires the use of TLS.", + "type": "string" + } + }, + "properties": { + "authorizationUrl": { + "default": "", + "description": "The authorization URL to be used for this flow. This MUST be in the\n form of a URL. The OAuth2 standard requires the use of TLS", + "type": "string" + }, + "refreshUrl": { + "default": "", + "description": "The URL to be used for obtaining refresh tokens. This MUST be in the\n form of a URL. The OAuth2 standard requires the use of TLS.", + "type": "string" + }, + "scopes": { + "additionalProperties": { + "type": "string" + }, + "description": "The available scopes for the OAuth2 security scheme. A map between the\n scope name and a short description for it. The map MAY be empty.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "title": "ImplicitO Auth Flow", + "type": "object" + }, + "List Task Push Notification Configs Request": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents a request for the `ListTaskPushNotificationConfigs` method.", + "patternProperties": { + "^(page_size)$": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "default": 0, + "description": "The maximum number of configurations to return." + }, + "^(page_token)$": { + "default": "", + "description": "A page token received from a previous `ListTaskPushNotificationConfigsRequest` call.", + "type": "string" + }, + "^(task_id)$": { + "default": "", + "description": "The parent task resource ID.", + "type": "string" + } + }, + "properties": { + "pageSize": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "default": 0, + "description": "The maximum number of configurations to return." + }, + "pageToken": { + "default": "", + "description": "A page token received from a previous `ListTaskPushNotificationConfigsRequest` call.", + "type": "string" + }, + "taskId": { + "default": "", + "description": "The parent task resource ID.", + "type": "string" + }, + "tenant": { + "default": "", + "description": "Optional. Opaque routing identifier. Must match the `tenant` value from\n the selected `AgentInterface` in the Agent Card when that field is set.", + "type": "string" + } + }, + "title": "List Task Push Notification Configs Request", + "type": "object" + }, + "List Task Push Notification Configs Response": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents a successful response for the `ListTaskPushNotificationConfigs`\n method.", + "patternProperties": { + "^(next_page_token)$": { + "default": "", + "description": "A token to retrieve the next page of results, or empty if there are no more results in the list.", + "type": "string" + } + }, + "properties": { + "configs": { + "description": "The list of push notification configurations.", + "items": { + "$ref": "lf.a2a.v1.TaskPushNotificationConfig.jsonschema.json" + }, + "type": "array" + }, + "nextPageToken": { + "default": "", + "description": "A token to retrieve the next page of results, or empty if there are no more results in the list.", + "type": "string" + } + }, + "title": "List Task Push Notification Configs Response", + "type": "object" + }, + "List Tasks Request": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Parameters for listing tasks with optional filtering criteria.", + "patternProperties": { + "^(context_id)$": { + "default": "", + "description": "Filter tasks by context ID to get tasks from a specific conversation or session.", + "type": "string" + }, + "^(history_length)$": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "description": "The maximum number of messages to include in each task's history." + }, + "^(include_artifacts)$": { + "description": "Whether to include artifacts in the returned tasks.\n Defaults to false to reduce payload size.", + "type": "boolean" + }, + "^(page_size)$": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "description": "The maximum number of tasks to return. The service may return fewer than this value.\n If unspecified, at most 50 tasks will be returned.\n The minimum value is 1.\n The maximum value is 100." + }, + "^(page_token)$": { + "default": "", + "description": "A page token, received from a previous `ListTasks` call.\n `ListTasksResponse.next_page_token`.\n Provide this to retrieve the subsequent page.", + "type": "string" + }, + "^(status_timestamp_after)$": { + "$ref": "google.protobuf.Timestamp.jsonschema.json", + "description": "Filter tasks which have a status updated after the provided timestamp in ISO 8601 format (e.g., \"2023-10-27T10:00:00Z\").\n Only tasks with a status timestamp time greater than or equal to this value will be returned." + } + }, + "properties": { + "contextId": { + "default": "", + "description": "Filter tasks by context ID to get tasks from a specific conversation or session.", + "type": "string" + }, + "historyLength": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "description": "The maximum number of messages to include in each task's history." + }, + "includeArtifacts": { + "description": "Whether to include artifacts in the returned tasks.\n Defaults to false to reduce payload size.", + "type": "boolean" + }, + "pageSize": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "description": "The maximum number of tasks to return. The service may return fewer than this value.\n If unspecified, at most 50 tasks will be returned.\n The minimum value is 1.\n The maximum value is 100." + }, + "pageToken": { + "default": "", + "description": "A page token, received from a previous `ListTasks` call.\n `ListTasksResponse.next_page_token`.\n Provide this to retrieve the subsequent page.", + "type": "string" + }, + "status": { + "anyOf": [ + { + "pattern": "^TASK_STATE_UNSPECIFIED$", + "type": "string" + }, + { + "enum": [ + "TASK_STATE_SUBMITTED", + "TASK_STATE_WORKING", + "TASK_STATE_COMPLETED", + "TASK_STATE_FAILED", + "TASK_STATE_CANCELED", + "TASK_STATE_INPUT_REQUIRED", + "TASK_STATE_REJECTED", + "TASK_STATE_AUTH_REQUIRED" + ], + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ], + "default": 0, + "description": "Filter tasks by their current status state.", + "title": "Task State" + }, + "statusTimestampAfter": { + "$ref": "google.protobuf.Timestamp.jsonschema.json", + "description": "Filter tasks which have a status updated after the provided timestamp in ISO 8601 format (e.g., \"2023-10-27T10:00:00Z\").\n Only tasks with a status timestamp time greater than or equal to this value will be returned." + }, + "tenant": { + "default": "", + "description": "Optional. Opaque routing identifier. Must match the `tenant` value from\n the selected `AgentInterface` in the Agent Card when that field is set.", + "type": "string" + } + }, + "title": "List Tasks Request", + "type": "object" + }, + "List Tasks Response": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Result object for `ListTasks` method containing an array of tasks and pagination information.", + "patternProperties": { + "^(next_page_token)$": { + "default": "", + "description": "A token to retrieve the next page of results, or empty if there are no more results in the list.", + "type": "string" + }, + "^(page_size)$": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "default": 0, + "description": "The page size used for this response." + }, + "^(total_size)$": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "default": 0, + "description": "Total number of tasks available (before pagination)." + } + }, + "properties": { + "nextPageToken": { + "default": "", + "description": "A token to retrieve the next page of results, or empty if there are no more results in the list.", + "type": "string" + }, + "pageSize": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "default": 0, + "description": "The page size used for this response." + }, + "tasks": { + "description": "Array of tasks matching the specified criteria.", + "items": { + "$ref": "lf.a2a.v1.Task.jsonschema.json" + }, + "type": "array" + }, + "totalSize": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "default": 0, + "description": "Total number of tasks available (before pagination)." + } + }, + "title": "List Tasks Response", + "type": "object" + }, + "Message": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "`Message` is one unit of communication between client and server. It can be\n associated with a context and/or a task. For server messages, `context_id` must\n be provided, and `task_id` only if a task was created. For client messages, both\n fields are optional, with the caveat that if both are provided, they have to\n match (the `context_id` has to be the one that is set on the task). If only\n `task_id` is provided, the server will infer `context_id` from it.", + "patternProperties": { + "^(context_id)$": { + "default": "", + "description": "Optional. The context id of the message. If set, the message will be associated with the given context.", + "type": "string" + }, + "^(message_id)$": { + "default": "", + "description": "The unique identifier (e.g. UUID) of the message. This is created by the message creator.", + "type": "string" + }, + "^(reference_task_ids)$": { + "description": "A list of task IDs that this message references for additional context.", + "items": { + "type": "string" + }, + "type": "array" + }, + "^(task_id)$": { + "default": "", + "description": "Optional. The task id of the message. If set, the message will be associated with the given task.", + "type": "string" + } + }, + "properties": { + "contextId": { + "default": "", + "description": "Optional. The context id of the message. If set, the message will be associated with the given context.", + "type": "string" + }, + "extensions": { + "description": "The URIs of extensions that are present or contributed to this Message.", + "items": { + "type": "string" + }, + "type": "array" + }, + "messageId": { + "default": "", + "description": "The unique identifier (e.g. UUID) of the message. This is created by the message creator.", + "type": "string" + }, + "metadata": { + "$ref": "google.protobuf.Struct.jsonschema.json", + "description": "Optional. Any metadata to provide along with the message." + }, + "parts": { + "description": "Parts is the container of the message content.", + "items": { + "$ref": "lf.a2a.v1.Part.jsonschema.json" + }, + "type": "array" + }, + "referenceTaskIds": { + "description": "A list of task IDs that this message references for additional context.", + "items": { + "type": "string" + }, + "type": "array" + }, + "role": { + "anyOf": [ + { + "pattern": "^ROLE_UNSPECIFIED$", + "type": "string" + }, + { + "enum": [ + "ROLE_USER", + "ROLE_AGENT" + ], + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ], + "default": 0, + "description": "Identifies the sender of the message.", + "title": "Role" + }, + "taskId": { + "default": "", + "description": "Optional. The task id of the message. If set, the message will be associated with the given task.", + "type": "string" + } + }, + "title": "Message", + "type": "object" + }, + "Mutual Tls Security Scheme": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines a security scheme using mTLS authentication.", + "properties": { + "description": { + "default": "", + "description": "An optional description for the security scheme.", + "type": "string" + } + }, + "title": "Mutual Tls Security Scheme", + "type": "object" + }, + "O Auth2 Security Scheme": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines a security scheme using OAuth 2.0.", + "patternProperties": { + "^(oauth2_metadata_url)$": { + "default": "", + "description": "URL to the OAuth2 authorization server metadata [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414).\n TLS is required.", + "type": "string" + } + }, + "properties": { + "description": { + "default": "", + "description": "An optional description for the security scheme.", + "type": "string" + }, + "flows": { + "$ref": "lf.a2a.v1.OAuthFlows.jsonschema.json", + "description": "An object containing configuration information for the supported OAuth 2.0 flows." + }, + "oauth2MetadataUrl": { + "default": "", + "description": "URL to the OAuth2 authorization server metadata [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414).\n TLS is required.", + "type": "string" + } + }, + "title": "O Auth2 Security Scheme", + "type": "object" + }, + "O Auth Flows": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines the configuration for the supported OAuth 2.0 flows.", + "patternProperties": { + "^(authorization_code)$": { + "$ref": "lf.a2a.v1.AuthorizationCodeOAuthFlow.jsonschema.json", + "description": "Configuration for the OAuth Authorization Code flow." + }, + "^(client_credentials)$": { + "$ref": "lf.a2a.v1.ClientCredentialsOAuthFlow.jsonschema.json", + "description": "Configuration for the OAuth Client Credentials flow." + }, + "^(device_code)$": { + "$ref": "lf.a2a.v1.DeviceCodeOAuthFlow.jsonschema.json", + "description": "Configuration for the OAuth Device Code flow." + } + }, + "properties": { + "authorizationCode": { + "$ref": "lf.a2a.v1.AuthorizationCodeOAuthFlow.jsonschema.json", + "description": "Configuration for the OAuth Authorization Code flow." + }, + "clientCredentials": { + "$ref": "lf.a2a.v1.ClientCredentialsOAuthFlow.jsonschema.json", + "description": "Configuration for the OAuth Client Credentials flow." + }, + "deviceCode": { + "$ref": "lf.a2a.v1.DeviceCodeOAuthFlow.jsonschema.json", + "description": "Configuration for the OAuth Device Code flow." + }, + "implicit": { + "$ref": "lf.a2a.v1.ImplicitOAuthFlow.jsonschema.json", + "description": "Deprecated: Use Authorization Code + PKCE instead." + }, + "password": { + "$ref": "lf.a2a.v1.PasswordOAuthFlow.jsonschema.json", + "description": "Deprecated: Use Authorization Code + PKCE or Device Code." + } + }, + "title": "O Auth Flows", + "type": "object" + }, + "Open Id Connect Security Scheme": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines a security scheme using OpenID Connect.", + "patternProperties": { + "^(open_id_connect_url)$": { + "default": "", + "description": "The [OpenID Connect Discovery URL](https://openid.net/specs/openid-connect-discovery-1_0.html) for the OIDC provider's metadata.", + "type": "string" + } + }, + "properties": { + "description": { + "default": "", + "description": "An optional description for the security scheme.", + "type": "string" + }, + "openIdConnectUrl": { + "default": "", + "description": "The [OpenID Connect Discovery URL](https://openid.net/specs/openid-connect-discovery-1_0.html) for the OIDC provider's metadata.", + "type": "string" + } + }, + "title": "Open Id Connect Security Scheme", + "type": "object" + }, + "Part": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "`Part` represents a container for a section of communication content.\n Parts can be purely textual, some sort of file (image, video, etc) or\n a structured data blob (i.e. JSON).", + "patternProperties": { + "^(media_type)$": { + "default": "", + "description": "The `media_type` (MIME type) of the part content (e.g., \"text/plain\", \"application/json\", \"image/png\").\n This field is available for all part types.", + "type": "string" + } + }, + "properties": { + "data": { + "$ref": "google.protobuf.Value.jsonschema.json", + "description": "Arbitrary structured `data` as a JSON value (object, array, string, number, boolean, or null)." + }, + "filename": { + "default": "", + "description": "An optional `filename` for the file (e.g., \"document.pdf\").", + "type": "string" + }, + "mediaType": { + "default": "", + "description": "The `media_type` (MIME type) of the part content (e.g., \"text/plain\", \"application/json\", \"image/png\").\n This field is available for all part types.", + "type": "string" + }, + "metadata": { + "$ref": "google.protobuf.Struct.jsonschema.json", + "description": "Optional. metadata associated with this part." + }, + "raw": { + "description": "The `raw` byte content of a file. In JSON serialization, this is encoded as a base64 string.", + "pattern": "^[A-Za-z0-9+/]*={0,2}$", + "type": "string" + }, + "text": { + "description": "The string content of the `text` part.", + "type": "string" + }, + "url": { + "description": "A `url` pointing to the file's content.", + "type": "string" + } + }, + "title": "Part", + "type": "object" + }, + "PasswordO Auth Flow": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Deprecated: Use Authorization Code + PKCE or Device Code.", + "patternProperties": { + "^(refresh_url)$": { + "default": "", + "description": "The URL to be used for obtaining refresh tokens. This MUST be in the\n form of a URL. The OAuth2 standard requires the use of TLS.", + "type": "string" + }, + "^(token_url)$": { + "default": "", + "description": "The token URL to be used for this flow. This MUST be in the form of a URL.\n The OAuth2 standard requires the use of TLS.", + "type": "string" + } + }, + "properties": { + "refreshUrl": { + "default": "", + "description": "The URL to be used for obtaining refresh tokens. This MUST be in the\n form of a URL. The OAuth2 standard requires the use of TLS.", + "type": "string" + }, + "scopes": { + "additionalProperties": { + "type": "string" + }, + "description": "The available scopes for the OAuth2 security scheme. A map between the\n scope name and a short description for it. The map MAY be empty.", + "propertyNames": { + "type": "string" + }, + "type": "object" + }, + "tokenUrl": { + "default": "", + "description": "The token URL to be used for this flow. This MUST be in the form of a URL.\n The OAuth2 standard requires the use of TLS.", + "type": "string" + } + }, + "title": "PasswordO Auth Flow", + "type": "object" + }, + "Security Requirement": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines the security requirements for an agent.", + "properties": { + "schemes": { + "additionalProperties": { + "$ref": "lf.a2a.v1.StringList.jsonschema.json" + }, + "description": "A map of security schemes to the required scopes.", + "propertyNames": { + "type": "string" + }, + "type": "object" + } + }, + "title": "Security Requirement", + "type": "object" + }, + "Security Scheme": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Defines a security scheme that can be used to secure an agent's endpoints.\n This is a discriminated union type based on the OpenAPI 3.2 Security Scheme Object.\n See: https://spec.openapis.org/oas/v3.2.0.html#security-scheme-object", + "patternProperties": { + "^(api_key_security_scheme)$": { + "$ref": "lf.a2a.v1.APIKeySecurityScheme.jsonschema.json", + "description": "API key-based authentication." + }, + "^(http_auth_security_scheme)$": { + "$ref": "lf.a2a.v1.HTTPAuthSecurityScheme.jsonschema.json", + "description": "HTTP authentication (Basic, Bearer, etc.)." + }, + "^(mtls_security_scheme)$": { + "$ref": "lf.a2a.v1.MutualTlsSecurityScheme.jsonschema.json", + "description": "Mutual TLS authentication." + }, + "^(oauth2_security_scheme)$": { + "$ref": "lf.a2a.v1.OAuth2SecurityScheme.jsonschema.json", + "description": "OAuth 2.0 authentication." + }, + "^(open_id_connect_security_scheme)$": { + "$ref": "lf.a2a.v1.OpenIdConnectSecurityScheme.jsonschema.json", + "description": "OpenID Connect authentication." + } + }, + "properties": { + "apiKeySecurityScheme": { + "$ref": "lf.a2a.v1.APIKeySecurityScheme.jsonschema.json", + "description": "API key-based authentication." + }, + "httpAuthSecurityScheme": { + "$ref": "lf.a2a.v1.HTTPAuthSecurityScheme.jsonschema.json", + "description": "HTTP authentication (Basic, Bearer, etc.)." + }, + "mtlsSecurityScheme": { + "$ref": "lf.a2a.v1.MutualTlsSecurityScheme.jsonschema.json", + "description": "Mutual TLS authentication." + }, + "oauth2SecurityScheme": { + "$ref": "lf.a2a.v1.OAuth2SecurityScheme.jsonschema.json", + "description": "OAuth 2.0 authentication." + }, + "openIdConnectSecurityScheme": { + "$ref": "lf.a2a.v1.OpenIdConnectSecurityScheme.jsonschema.json", + "description": "OpenID Connect authentication." + } + }, + "title": "Security Scheme", + "type": "object" + }, + "Send Message Configuration": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Configuration of a send message request.", + "patternProperties": { + "^(accepted_output_modes)$": { + "description": "A list of media types the client is prepared to accept for response parts.\n Agents SHOULD use this to tailor their output.", + "items": { + "type": "string" + }, + "type": "array" + }, + "^(history_length)$": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "description": "The maximum number of most recent messages from the task's history to retrieve in\n the response. An unset value means the client does not impose any limit. A\n value of zero is a request to not include any messages. The server MUST NOT\n return more messages than the provided value, but MAY apply a lower limit." + }, + "^(return_immediately)$": { + "default": false, + "description": "If `true`, the operation returns immediately after creating the task,\n even if processing is still in progress.\n If `false` (default), the operation MUST wait until the task reaches a\n terminal (`COMPLETED`, `FAILED`, `CANCELED`, `REJECTED`) or interrupted\n (`INPUT_REQUIRED`, `AUTH_REQUIRED`) state before returning.", + "type": "boolean" + }, + "^(task_push_notification_config)$": { + "$ref": "lf.a2a.v1.TaskPushNotificationConfig.jsonschema.json", + "description": "Configuration for the agent to send push notifications for task updates.\n Task id should be empty when sending this configuration in a `SendMessage` request." + } + }, + "properties": { + "acceptedOutputModes": { + "description": "A list of media types the client is prepared to accept for response parts.\n Agents SHOULD use this to tailor their output.", + "items": { + "type": "string" + }, + "type": "array" + }, + "historyLength": { + "anyOf": [ + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ], + "description": "The maximum number of most recent messages from the task's history to retrieve in\n the response. An unset value means the client does not impose any limit. A\n value of zero is a request to not include any messages. The server MUST NOT\n return more messages than the provided value, but MAY apply a lower limit." + }, + "returnImmediately": { + "default": false, + "description": "If `true`, the operation returns immediately after creating the task,\n even if processing is still in progress.\n If `false` (default), the operation MUST wait until the task reaches a\n terminal (`COMPLETED`, `FAILED`, `CANCELED`, `REJECTED`) or interrupted\n (`INPUT_REQUIRED`, `AUTH_REQUIRED`) state before returning.", + "type": "boolean" + }, + "taskPushNotificationConfig": { + "$ref": "lf.a2a.v1.TaskPushNotificationConfig.jsonschema.json", + "description": "Configuration for the agent to send push notifications for task updates.\n Task id should be empty when sending this configuration in a `SendMessage` request." + } + }, + "title": "Send Message Configuration", + "type": "object" + }, + "Send Message Request": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents a request for the `SendMessage` method.", + "properties": { + "configuration": { + "$ref": "lf.a2a.v1.SendMessageConfiguration.jsonschema.json", + "description": "Configuration for the send request." + }, + "message": { + "$ref": "lf.a2a.v1.Message.jsonschema.json", + "description": "The message to send to the agent." + }, + "metadata": { + "$ref": "google.protobuf.Struct.jsonschema.json", + "description": "A flexible key-value map for passing additional context or parameters." + }, + "tenant": { + "default": "", + "description": "Optional. Opaque routing identifier. Must match the `tenant` value from\n the selected `AgentInterface` in the Agent Card when that field is set.", + "type": "string" + } + }, + "title": "Send Message Request", + "type": "object" + }, + "Send Message Response": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents the response for the `SendMessage` method.", + "properties": { + "message": { + "$ref": "lf.a2a.v1.Message.jsonschema.json", + "description": "A message from the agent." + }, + "task": { + "$ref": "lf.a2a.v1.Task.jsonschema.json", + "description": "The task created or updated by the message." + } + }, + "title": "Send Message Response", + "type": "object" + }, + "Stream Response": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A wrapper object used in streaming operations to encapsulate different types of response data.", + "patternProperties": { + "^(artifact_update)$": { + "$ref": "lf.a2a.v1.TaskArtifactUpdateEvent.jsonschema.json", + "description": "An event indicating a task artifact update." + }, + "^(status_update)$": { + "$ref": "lf.a2a.v1.TaskStatusUpdateEvent.jsonschema.json", + "description": "An event indicating a task status update." + } + }, + "properties": { + "artifactUpdate": { + "$ref": "lf.a2a.v1.TaskArtifactUpdateEvent.jsonschema.json", + "description": "An event indicating a task artifact update." + }, + "message": { + "$ref": "lf.a2a.v1.Message.jsonschema.json", + "description": "A Message object containing a message from the agent." + }, + "statusUpdate": { + "$ref": "lf.a2a.v1.TaskStatusUpdateEvent.jsonschema.json", + "description": "An event indicating a task status update." + }, + "task": { + "$ref": "lf.a2a.v1.Task.jsonschema.json", + "description": "A Task object containing the current state of the task." + } + }, + "title": "Stream Response", + "type": "object" + }, + "String List": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A list of strings.", + "properties": { + "list": { + "description": "The individual string values.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "title": "String List", + "type": "object" + }, + "Subscribe To Task Request": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Represents a request for the `SubscribeToTask` method.", + "properties": { + "id": { + "default": "", + "description": "The resource ID of the task to subscribe to.", + "type": "string" + }, + "tenant": { + "default": "", + "description": "Optional. Opaque routing identifier. Must match the `tenant` value from\n the selected `AgentInterface` in the Agent Card when that field is set.", + "type": "string" + } + }, + "title": "Subscribe To Task Request", + "type": "object" + }, + "Task": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "`Task` is the core unit of action for A2A. It has a current status\n and when results are created for the task they are stored in the\n artifact. If there are multiple turns for a task, these are stored in\n history.", + "patternProperties": { + "^(context_id)$": { + "default": "", + "description": "Unique identifier (e.g. UUID) for the contextual collection of interactions\n (tasks and messages).", + "type": "string" + } + }, + "properties": { + "artifacts": { + "description": "A set of output artifacts for a `Task`.", + "items": { + "$ref": "lf.a2a.v1.Artifact.jsonschema.json" + }, + "type": "array" + }, + "contextId": { + "default": "", + "description": "Unique identifier (e.g. UUID) for the contextual collection of interactions\n (tasks and messages).", + "type": "string" + }, + "history": { + "description": "The history of interactions from a `Task`.", + "items": { + "$ref": "lf.a2a.v1.Message.jsonschema.json" + }, + "type": "array" + }, + "id": { + "default": "", + "description": "Unique identifier (e.g. UUID) for the task, generated by the server for a\n new task.", + "type": "string" + }, + "metadata": { + "$ref": "google.protobuf.Struct.jsonschema.json", + "description": "A key/value object to store custom metadata about a task." + }, + "status": { + "$ref": "lf.a2a.v1.TaskStatus.jsonschema.json", + "description": "The current status of a `Task`, including `state` and a `message`." + } + }, + "title": "Task", + "type": "object" + }, + "Task Artifact Update Event": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A task delta where an artifact has been generated.", + "patternProperties": { + "^(context_id)$": { + "default": "", + "description": "The ID of the context that this task belongs to.", + "type": "string" + }, + "^(last_chunk)$": { + "default": false, + "description": "If true, this is the final chunk of the artifact.", + "type": "boolean" + }, + "^(task_id)$": { + "default": "", + "description": "The ID of the task for this artifact.", + "type": "string" + } + }, + "properties": { + "append": { + "default": false, + "description": "If true, the content of this artifact should be appended to a previously\n sent artifact with the same ID.", + "type": "boolean" + }, + "artifact": { + "$ref": "lf.a2a.v1.Artifact.jsonschema.json", + "description": "The artifact that was generated or updated." + }, + "contextId": { + "default": "", + "description": "The ID of the context that this task belongs to.", + "type": "string" + }, + "lastChunk": { + "default": false, + "description": "If true, this is the final chunk of the artifact.", + "type": "boolean" + }, + "metadata": { + "$ref": "google.protobuf.Struct.jsonschema.json", + "description": "Optional. Metadata associated with the artifact update." + }, + "taskId": { + "default": "", + "description": "The ID of the task for this artifact.", + "type": "string" + } + }, + "title": "Task Artifact Update Event", + "type": "object" + }, + "Task Push Notification Config": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A container associating a push notification configuration with a specific task.", + "patternProperties": { + "^(task_id)$": { + "default": "", + "description": "The ID of the task this configuration is associated with.", + "type": "string" + } + }, + "properties": { + "authentication": { + "$ref": "lf.a2a.v1.AuthenticationInfo.jsonschema.json", + "description": "Authentication information required to send the notification." + }, + "id": { + "default": "", + "description": "The push notification configuration details.\n A unique identifier (e.g. UUID) for this push notification configuration.", + "type": "string" + }, + "taskId": { + "default": "", + "description": "The ID of the task this configuration is associated with.", + "type": "string" + }, + "tenant": { + "default": "", + "description": "Optional. Opaque routing identifier. Must match the `tenant` value from\n the selected `AgentInterface` in the Agent Card when that field is set.", + "type": "string" + }, + "token": { + "default": "", + "description": "A token unique for this task or session.", + "type": "string" + }, + "url": { + "default": "", + "description": "The URL where the notification should be sent.", + "type": "string" + } + }, + "title": "Task Push Notification Config", + "type": "object" + }, + "Task Status": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A container for the status of a task", + "properties": { + "message": { + "$ref": "lf.a2a.v1.Message.jsonschema.json", + "description": "A message associated with the status." + }, + "state": { + "anyOf": [ + { + "pattern": "^TASK_STATE_UNSPECIFIED$", + "type": "string" + }, + { + "enum": [ + "TASK_STATE_SUBMITTED", + "TASK_STATE_WORKING", + "TASK_STATE_COMPLETED", + "TASK_STATE_FAILED", + "TASK_STATE_CANCELED", + "TASK_STATE_INPUT_REQUIRED", + "TASK_STATE_REJECTED", + "TASK_STATE_AUTH_REQUIRED" + ], + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ], + "default": 0, + "description": "The current state of this task.", + "title": "Task State" + }, + "timestamp": { + "$ref": "google.protobuf.Timestamp.jsonschema.json", + "description": "ISO 8601 Timestamp when the status was recorded.\n Example: \"2023-10-27T10:00:00Z\"" + } + }, + "title": "Task Status", + "type": "object" + }, + "Task Status Update Event": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "An event sent by the agent to notify the client of a change in a task's status.", + "patternProperties": { + "^(context_id)$": { + "default": "", + "description": "The ID of the context that the task belongs to.", + "type": "string" + }, + "^(task_id)$": { + "default": "", + "description": "The ID of the task that has changed.", + "type": "string" + } + }, + "properties": { + "contextId": { + "default": "", + "description": "The ID of the context that the task belongs to.", + "type": "string" + }, + "metadata": { + "$ref": "google.protobuf.Struct.jsonschema.json", + "description": "Optional. Metadata associated with the task update." + }, + "status": { + "$ref": "lf.a2a.v1.TaskStatus.jsonschema.json", + "description": "The new status of the task." + }, + "taskId": { + "default": "", + "description": "The ID of the task that has changed.", + "type": "string" + } + }, + "title": "Task Status Update Event", + "type": "object" + } + } +} diff --git a/tests/integration/a2a-over-gateway.test.ts b/tests/integration/a2a-over-gateway.test.ts index 04d1ed2..fd613c4 100644 --- a/tests/integration/a2a-over-gateway.test.ts +++ b/tests/integration/a2a-over-gateway.test.ts @@ -217,8 +217,8 @@ describe('A2A JSON-RPC transport over the real gateway', () => { it.each([ ['a known but unsupported operation', 'SendStreamingMessage', -32004], - ['a task lookup, which finds no retained task', 'GetTask', -32001], - ['a task cancellation', 'CancelTask', -32001], + ['a lookup of an unknown task', 'GetTask', -32001], + ['a cancellation of an unknown task', 'CancelTask', -32001], ['a completely unknown method', 'DoSomething', -32601], ])('distinguishes %s', async (_label, method, code) => { const gw = await startGateway(); diff --git a/tests/integration/a2a-x402-extension.test.ts b/tests/integration/a2a-x402-extension.test.ts index 923482b..6eccd0a 100644 --- a/tests/integration/a2a-x402-extension.test.ts +++ b/tests/integration/a2a-x402-extension.test.ts @@ -26,6 +26,7 @@ import { createA2aAdapter } from '../../src/protocols/a2a'; import type { A2aAgentCard, A2aTask } from '../../src/protocols/a2a/types'; import { A2A_X402_EXTENSION_URI } from '../../src/protocols/a2a/x402-extension'; import { createSqliteReceiptStore } from '../../src/storage/receipts'; +import { tckErrors } from '../conformance/a2a/support/task-schema'; import { createFakeStore } from '../unit/gateway/helpers'; process.env['NODE_ENV'] = 'test'; @@ -140,6 +141,7 @@ afterEach(async () => { interface RpcResult { readonly headers: Record; readonly body: { + // `{ task }` for SendMessage; the task itself for GetTask and CancelTask result?: { task: A2aTask }; error?: { code: number; message: string }; }; @@ -160,7 +162,13 @@ async function call( }, payload: JSON.stringify({ jsonrpc: '2.0', id: 'req-1', method, params }), }); - return { headers: res.headers, body: res.json() }; + const body: RpcResult['body'] = res.json(); + // Every task answered here passes the TCK's response schema + if (body.result !== undefined) { + const schema = method === 'SendMessage' ? 'Send Message Response' : 'Task'; + expect(tckErrors(schema, body.result), `${method} result against the TCK schema`).toEqual([]); + } + return { headers: res.headers, body }; } function rpc(message: Record, extension = true): Promise { @@ -293,7 +301,8 @@ describe('x402 A2A extension', () => { const { body } = await rpc(message); - expect(body.error?.code).toBe(-32001); + // The task's record remains: it accepts no further messages + expect(body.error?.code).toBe(-32004); expect(facilitator.settle).toHaveBeenCalledTimes(1); }); @@ -335,7 +344,7 @@ describe('x402 A2A extension', () => { message: { metadata: { 'x402.payment.status': 'payment-rejected' } }, }); const again = await rpc(pay(task, { 'x402.payment.status': 'payment-rejected' })); - expect(again.body.error?.code).toBe(-32001); + expect(again.body.error?.code).toBe(-32004); }); // A full store must preserve purchases whose buyers may have signed. @@ -351,6 +360,8 @@ describe('x402 A2A extension', () => { code: 'GATEWAY_BUSY', retryable: true, }); + // The refused task's record shows the refusal, not a payment it cannot take + expect((await call('GetTask', { id: busy?.id })).body.result).toEqual(busy); const paid = await rpc( pay(first, { @@ -531,24 +542,65 @@ describe('x402 A2A extension', () => { expect(body.result?.task.status.state).toBe('TASK_STATE_COMPLETED'); }); - it.each(['GetTask', 'CancelTask'])( - 'answers %s on a pending task with TaskNotFoundError and keeps it payable', - async (method) => { - const task = await challenged(); + it('answers GetTask on a pending task with the task as sent, and keeps it payable', async () => { + const task = await challenged(); - const lookup = await call(method, { id: task.id }); - expect(lookup.body.error?.code).toBe(-32001); - expect(lookup.headers['a2a-extensions']).toBeUndefined(); + const lookup = await call('GetTask', { id: task.id }, false); + expect(lookup.body.result).toEqual(task); + // The task's metadata keys belong to the extension, which the response names + expect(lookup.headers['a2a-extensions']).toBe(A2A_X402_EXTENSION_URI); - const { body } = await rpc( - pay(task, { - 'x402.payment.status': 'payment-submitted', - 'x402.payment.payload': await paymentPayload(task), - }), - ); - expect(body.result?.task.status.state).toBe('TASK_STATE_COMPLETED'); - }, - ); + const { body } = await rpc( + pay(task, { + 'x402.payment.status': 'payment-submitted', + 'x402.payment.payload': await paymentPayload(task), + }), + ); + expect(body.result?.task.status.state).toBe('TASK_STATE_COMPLETED'); + expect((await call('GetTask', { id: task.id })).body.result).toEqual(body.result?.task); + }); + + it('cancels a pending task, which then takes no payment, and cancels it again unchanged', async () => { + const task = await challenged(); + + const canceled = (await call('CancelTask', { id: task.id })).body.result as unknown as A2aTask; + expect(canceled).toMatchObject({ + id: task.id, + contextId: task.contextId, + status: { state: 'TASK_STATE_CANCELED', message: { parts: [{ text: 'Task canceled.' }] } }, + artifacts: [], + }); + expect(canceled.status.message).not.toHaveProperty('metadata'); + + const payment = await rpc( + pay(task, { + 'x402.payment.status': 'payment-submitted', + 'x402.payment.payload': await paymentPayload(task), + }), + ); + expect(payment.body.error?.code).toBe(-32004); + expect(facilitator.verify).not.toHaveBeenCalled(); + expect(backendCalls).toBe(0); + expect((await call('CancelTask', { id: task.id })).body.result).toEqual(canceled); + expect((await call('GetTask', { id: task.id })).body.result).toEqual(canceled); + }); + + it('refuses to cancel a paid task', async () => { + const task = await challenged(); + await rpc( + pay(task, { + 'x402.payment.status': 'payment-submitted', + 'x402.payment.payload': await paymentPayload(task), + }), + ); + + const { body } = await call('CancelTask', { id: task.id }); + + expect(body.error?.code).toBe(-32002); + expect((await call('GetTask', { id: task.id })).body.result).toMatchObject({ + status: { state: 'TASK_STATE_COMPLETED' }, + }); + }); }); describe('an AP2 mandate sent with the x402 extension payment', () => { diff --git a/tests/integration/goldens/2.7.2/doctor-multi.json b/tests/integration/goldens/2.7.2/doctor-multi.json index 99a55f3..f9f0840 100644 --- a/tests/integration/goldens/2.7.2/doctor-multi.json +++ b/tests/integration/goldens/2.7.2/doctor-multi.json @@ -28,7 +28,7 @@ { "name": "A2A unsupported", "status": "INFO", - "detail": "SendStreamingMessage, GetTask, ListTasks, CancelTask, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, x402 extension payments across gateway instances" + "detail": "SendStreamingMessage, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, tasks across gateway instances" }, { "name": "ACP", diff --git a/tests/integration/goldens/2.7.2/doctor-single.json b/tests/integration/goldens/2.7.2/doctor-single.json index 02fa614..4f8c3fc 100644 --- a/tests/integration/goldens/2.7.2/doctor-single.json +++ b/tests/integration/goldens/2.7.2/doctor-single.json @@ -28,7 +28,7 @@ { "name": "A2A unsupported", "status": "INFO", - "detail": "SendStreamingMessage, GetTask, ListTasks, CancelTask, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, x402 extension payments across gateway instances" + "detail": "SendStreamingMessage, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, tasks across gateway instances" }, { "name": "ACP", diff --git a/tests/integration/goldens/2.7.2/well-known-multi.json b/tests/integration/goldens/2.7.2/well-known-multi.json index 2d3e404..81c0aea 100644 --- a/tests/integration/goldens/2.7.2/well-known-multi.json +++ b/tests/integration/goldens/2.7.2/well-known-multi.json @@ -69,14 +69,14 @@ "agent-card", "jsonrpc", "SendMessage", + "GetTask", + "ListTasks", + "CancelTask", "x402-extension" ], "status": "experimental", "unsupported": [ "SendStreamingMessage", - "GetTask", - "ListTasks", - "CancelTask", "SubscribeToTask", "CreateTaskPushNotificationConfig", "GetTaskPushNotificationConfig", @@ -97,7 +97,7 @@ "authenticated extended agent cards", "A2A authentication schemes", "artifact types beyond Agent Commerce outcome data", - "x402 extension payments across gateway instances" + "tasks across gateway instances" ], "health": { "status": "pass", diff --git a/tests/integration/goldens/2.7.2/well-known-single.json b/tests/integration/goldens/2.7.2/well-known-single.json index a91ecee..d44b86e 100644 --- a/tests/integration/goldens/2.7.2/well-known-single.json +++ b/tests/integration/goldens/2.7.2/well-known-single.json @@ -69,14 +69,14 @@ "agent-card", "jsonrpc", "SendMessage", + "GetTask", + "ListTasks", + "CancelTask", "x402-extension" ], "status": "experimental", "unsupported": [ "SendStreamingMessage", - "GetTask", - "ListTasks", - "CancelTask", "SubscribeToTask", "CreateTaskPushNotificationConfig", "GetTaskPushNotificationConfig", @@ -97,7 +97,7 @@ "authenticated extended agent cards", "A2A authentication schemes", "artifact types beyond Agent Commerce outcome data", - "x402 extension payments across gateway instances" + "tasks across gateway instances" ], "health": { "status": "pass", diff --git a/tests/integration/goldens/2.8.0/a2a-free.json b/tests/integration/goldens/2.8.0/a2a-free.json index ca9a85d..e9e6ddb 100644 --- a/tests/integration/goldens/2.8.0/a2a-free.json +++ b/tests/integration/goldens/2.8.0/a2a-free.json @@ -6,8 +6,8 @@ "id": "golden", "result": { "task": { - "id": "a2a_", - "contextId": "a2a-ctx_", + "id": "", + "contextId": "", "status": { "state": "TASK_STATE_COMPLETED", "timestamp": "" diff --git a/tests/integration/goldens/2.8.0/a2a-paid-no-proof.json b/tests/integration/goldens/2.8.0/a2a-paid-no-proof.json index 0729a78..0694bac 100644 --- a/tests/integration/goldens/2.8.0/a2a-paid-no-proof.json +++ b/tests/integration/goldens/2.8.0/a2a-paid-no-proof.json @@ -6,16 +6,16 @@ "id": "golden", "result": { "task": { - "id": "a2a_", - "contextId": "a2a-ctx_", + "id": "", + "contextId": "", "status": { "state": "TASK_STATE_FAILED", "timestamp": "", "message": { "role": "ROLE_AGENT", "messageId": "a2a-msg_", - "contextId": "a2a-ctx_", - "taskId": "a2a_", + "contextId": "", + "taskId": "", "parts": [ { "text": "Payment of 0.01 USDC is required for resource \"market_report\". Retry with a x402 payment proof." diff --git a/tests/integration/goldens/2.8.0/a2a-refusals.json b/tests/integration/goldens/2.8.0/a2a-refusals.json index a058bcb..51282ac 100644 --- a/tests/integration/goldens/2.8.0/a2a-refusals.json +++ b/tests/integration/goldens/2.8.0/a2a-refusals.json @@ -101,16 +101,11 @@ "body": { "jsonrpc": "2.0", "id": 1, - "error": { - "code": -32004, - "message": "A2A method \"ListTasks\" is not supported by this deployment.", - "data": [ - { - "@type": "type.googleapis.com/google.rpc.ErrorInfo", - "reason": "UNSUPPORTED_OPERATION", - "domain": "a2a-protocol.org" - } - ] + "result": { + "tasks": [], + "nextPageToken": "", + "pageSize": 50, + "totalSize": 0 } } }, @@ -179,7 +174,7 @@ "id": 1, "error": { "code": -32001, - "message": "Task not found. Finished tasks are not retained; continue a pending payment with SendMessage.", + "message": "Task not found.", "data": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", @@ -198,7 +193,7 @@ "id": 1, "error": { "code": -32001, - "message": "Task not found. Finished tasks are not retained; continue a pending payment with SendMessage.", + "message": "Task not found.", "data": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", @@ -431,7 +426,7 @@ "id": "golden", "error": { "code": -32001, - "message": "Task not found: only a task waiting for payment can be continued, so send a request with no taskId.", + "message": "Task not found: send the message without a taskId to start a new task.", "data": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", @@ -488,16 +483,16 @@ "id": "golden", "result": { "task": { - "id": "a2a_", - "contextId": "a2a-ctx_", + "id": "", + "contextId": "", "status": { "state": "TASK_STATE_FAILED", "timestamp": "", "message": { "role": "ROLE_AGENT", "messageId": "a2a-msg_", - "contextId": "a2a-ctx_", - "taskId": "a2a_", + "contextId": "", + "taskId": "", "parts": [ { "text": "Unknown canonical resource \"no_such_resource\"." diff --git a/tests/integration/goldens/2.8.0/a2a-x402-completed.json b/tests/integration/goldens/2.8.0/a2a-x402-completed.json index feb88c6..2ff1c29 100644 --- a/tests/integration/goldens/2.8.0/a2a-x402-completed.json +++ b/tests/integration/goldens/2.8.0/a2a-x402-completed.json @@ -6,16 +6,16 @@ "id": "golden", "result": { "task": { - "id": "a2a_", - "contextId": "a2a-ctx_", + "id": "", + "contextId": "", "status": { "state": "TASK_STATE_COMPLETED", "timestamp": "", "message": { "role": "ROLE_AGENT", "messageId": "a2a-msg_", - "contextId": "a2a-ctx_", - "taskId": "a2a_", + "contextId": "", + "taskId": "", "parts": [ { "text": "Payment settled." diff --git a/tests/integration/goldens/2.8.0/a2a-x402-input-required.json b/tests/integration/goldens/2.8.0/a2a-x402-input-required.json index b8fe1ab..ae322f3 100644 --- a/tests/integration/goldens/2.8.0/a2a-x402-input-required.json +++ b/tests/integration/goldens/2.8.0/a2a-x402-input-required.json @@ -6,16 +6,16 @@ "id": "golden", "result": { "task": { - "id": "a2a_", - "contextId": "a2a-ctx_", + "id": "", + "contextId": "", "status": { "state": "TASK_STATE_INPUT_REQUIRED", "timestamp": "", "message": { "role": "ROLE_AGENT", "messageId": "a2a-msg_", - "contextId": "a2a-ctx_", - "taskId": "a2a_", + "contextId": "", + "taskId": "", "parts": [ { "text": "Payment is required. Send the x402 payment payload on this task." diff --git a/tests/integration/payment-retries.test.ts b/tests/integration/payment-retries.test.ts index b2a3ccd..9089440 100644 --- a/tests/integration/payment-retries.test.ts +++ b/tests/integration/payment-retries.test.ts @@ -1077,14 +1077,15 @@ describe('x402 redelivery over MCP and A2A', () => { expect(backendCalls).toHaveLength(1); }); - it('answers a resend to the consumed extension task with TaskNotFoundError', async () => { + it('answers a resend to the consumed extension task with UnsupportedOperationError', async () => { const task = await a2aChallenge('x402_report'); const proof = await signX402(challengeOf(task), ID); await a2aPay(task, proof); const resend = await a2aPay(task, proof); - expect(resend.error?.code).toBe(-32001); + // The paid task's record remains, and it takes no further messages + expect(resend.error?.code).toBe(-32004); expect(resend.result).toBeUndefined(); expect(facilitator.settle).toHaveBeenCalledTimes(1); expect(backendCalls).toHaveLength(1); diff --git a/tests/unit/cli/doctor.test.ts b/tests/unit/cli/doctor.test.ts index d2b7b1c..b8e9f1f 100644 --- a/tests/unit/cli/doctor.test.ts +++ b/tests/unit/cli/doctor.test.ts @@ -1653,9 +1653,14 @@ describe('runDoctor: A2A', () => { const unsupported = report.checks.find((c) => c.name === 'A2A unsupported'); expect(unsupported?.status).toBe('INFO'); expect(unsupported?.detail).toBe(A2A_UNSUPPORTED.join(', ')); - for (const operation of ['SendStreamingMessage', 'GetTask', 'CancelTask', 'gRPC binding']) { + for (const operation of ['SendStreamingMessage', 'SubscribeToTask', 'gRPC binding']) { expect(unsupported?.detail).toContain(operation); } + // Served from stored tasks, which leaves them off the list + const names = unsupported?.detail?.split(', ') ?? []; + for (const served of ['GetTask', 'ListTasks', 'CancelTask']) { + expect(names).not.toContain(served); + } }); }); diff --git a/tests/unit/gateway/main.test.ts b/tests/unit/gateway/main.test.ts index b52f911..1d724b3 100644 --- a/tests/unit/gateway/main.test.ts +++ b/tests/unit/gateway/main.test.ts @@ -127,7 +127,8 @@ function acpResource(keys: readonly string[], optional: readonly string[] = []) // Configure every protocol, both payment rails and AP2 with one receipt database function fullConfig(dir: string) { const config = baseConfig(dir); - config.protocols['a2a'] = { enabled: true, mountPath: '/a2a' }; + // One retained task, which the A2A check below fills to show the option arrives + config.protocols['a2a'] = { enabled: true, mountPath: '/a2a', tasks: { maxRetained: 1 } }; config.protocols['acp'] = { enabled: true, auth: { type: 'bearer', token: 'acp-token' }, @@ -346,29 +347,33 @@ describe.concurrent('gateway entry points (main.ts and agent-commerce start)', ( ]); // An x402 extension task waits for payment in the receipt database - const sent = await fetch(`${gateway.url()}/a2a`, { - method: 'POST', - headers: { - 'content-type': 'application/json', - 'a2a-version': '1.0', - 'a2a-extensions': A2A_X402_EXTENSION_URI, - }, - body: JSON.stringify({ - jsonrpc: '2.0', - id: 'req-1', - method: 'SendMessage', - params: { - message: { - role: 'ROLE_USER', - messageId: 'msg-buy', - parts: [{ data: { resource: 'market_report', input: {} } }], - }, + const buy = async () => { + const sent = await fetch(`${gateway.url()}/a2a`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'a2a-version': '1.0', + 'a2a-extensions': A2A_X402_EXTENSION_URI, }, - }), - }); - const task = ((await sent.json()) as { result?: { task?: { status: { state: string } } } }) - .result?.task; - expect(task?.status.state).toBe('TASK_STATE_INPUT_REQUIRED'); + body: JSON.stringify({ + jsonrpc: '2.0', + id: 'req-1', + method: 'SendMessage', + params: { + message: { + role: 'ROLE_USER', + messageId: 'msg-buy', + parts: [{ data: { resource: 'market_report', input: {} } }], + }, + }, + }), + }); + type Task = { status: { state: string }; artifacts: { parts: { data?: unknown }[] }[] }; + return ((await sent.json()) as { result?: { task?: Task } }).result?.task; + }; + expect((await buy())?.status.state).toBe('TASK_STATE_INPUT_REQUIRED'); + // `protocols.a2a.tasks.maxRetained: 1` reached the adapter + expect((await buy())?.artifacts[0]?.parts[0]?.data).toMatchObject({ code: 'GATEWAY_BUSY' }); expect(names('paymentProviders')).toEqual(['mpp', 'x402']); expect(names('authorizationProviders')).toEqual(['ap2']); @@ -391,6 +396,9 @@ describe.concurrent('gateway entry points (main.ts and agent-commerce start)', ( const db = new Database(join(dir, 'receipts.sqlite'), { readonly: true }); try { expect(db.prepare('SELECT COUNT(*) AS n FROM pending_tasks').get()).toEqual({ n: 1 }); + expect(db.prepare('SELECT state FROM task_records').all()).toEqual([ + { state: 'TASK_STATE_INPUT_REQUIRED' }, + ]); } finally { db.close(); } diff --git a/tests/unit/protocols-a2a/agent-card.test.ts b/tests/unit/protocols-a2a/agent-card.test.ts index 0b6f00a..c66d193 100644 --- a/tests/unit/protocols-a2a/agent-card.test.ts +++ b/tests/unit/protocols-a2a/agent-card.test.ts @@ -287,14 +287,19 @@ describe('A2A adapter lifecycle', () => { 'agent-card', 'jsonrpc', 'SendMessage', + 'GetTask', + 'ListTasks', + 'CancelTask', 'x402-extension', ]); + for (const served of ['GetTask', 'ListTasks', 'CancelTask']) { + expect(descriptor.unsupported).not.toContain(served); + } // Every A2A feature the project scope leaves out is named, so no client // reads the descriptor as full protocol support expect(descriptor.unsupported).toEqual( expect.arrayContaining([ 'SendStreamingMessage', - 'GetTask', 'long-running task persistence', 'push notifications', 'multi-turn conversational continuation', diff --git a/tests/unit/protocols-a2a/payment-resume.test.ts b/tests/unit/protocols-a2a/payment-resume.test.ts index ad68219..c9fbd3a 100644 --- a/tests/unit/protocols-a2a/payment-resume.test.ts +++ b/tests/unit/protocols-a2a/payment-resume.test.ts @@ -44,7 +44,11 @@ async function resumeWith(refusal: CommerceError) { }, }; - const response = await resumePayment(context, pendingPayments, 1, { message }); + const response = await resumePayment( + { context, pendingPayments, keep: async () => true, running: new Set() }, + 1, + { message }, + ); const task = (response as { result: { task: A2aTask } }).result.task; const envelope = task.artifacts?.[0]?.parts[0]?.data as Record; return { task, envelope, pendingPayments }; diff --git a/tests/unit/protocols-a2a/pending-store.test.ts b/tests/unit/protocols-a2a/pending-store.test.ts index bfc22bd..1212f5c 100644 --- a/tests/unit/protocols-a2a/pending-store.test.ts +++ b/tests/unit/protocols-a2a/pending-store.test.ts @@ -7,7 +7,7 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import Database from 'better-sqlite3'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { GatewayConfig } from '../../../src/config'; import type { AdapterDescriptor, @@ -24,7 +24,7 @@ import type { ReceiptStore, } from '../../../src/core'; import { createGateway, type GatewayInstance } from '../../../src/gateway'; -import { createA2aAdapter } from '../../../src/protocols/a2a'; +import { type A2aAdapterOptions, createA2aAdapter } from '../../../src/protocols/a2a'; import type { A2aTask } from '../../../src/protocols/a2a/types'; import { A2A_X402_EXTENSION_URI, @@ -188,6 +188,8 @@ let calls: Calls; let backendCalls: number; let time: ReturnType; let ids: IdGenerator; +// Set to hold every backend call until it resolves +let backendGate: Promise | undefined; let open: Node[]; beforeEach(() => { @@ -195,6 +197,7 @@ beforeEach(() => { path = join(dir, 'receipts.db'); calls = { verify: 0, settle: 0, mandates: [] }; backendCalls = 0; + backendGate = undefined; time = createClock(); // Keep test IDs distinct across gateway restarts let n = 0; @@ -208,7 +211,10 @@ afterEach(async () => { }); // The adapter's store defaults to the gateway's own -async function boot(adapterStore?: (store: ReceiptStore) => ReceiptStore): Promise { +async function boot( + adapterStore?: (store: ReceiptStore) => ReceiptStore, + tasks?: A2aAdapterOptions['tasks'], +): Promise { const store = createSqliteReceiptStore({ path, clock: time.clock, ids, logger: NOOP_LOGGER }); await store.init(); const gateway = await createGateway({ @@ -216,13 +222,16 @@ async function boot(adapterStore?: (store: ReceiptStore) => ReceiptStore): Promi store, paymentProviders: [fakePayments(time.clock, calls)], authorizationProviders: [fakeMandates(time.clock, calls)], - protocolAdapters: [createA2aAdapter({ store: adapterStore?.(store) ?? store })], + protocolAdapters: [ + createA2aAdapter({ store: adapterStore?.(store) ?? store, ...(tasks ? { tasks } : {}) }), + ], logger: NOOP_LOGGER, clock: time.clock, ids, backend: { async call() { backendCalls += 1; + await backendGate; return { status: 200, body: { report: 'paid' }, headers: {}, durationMs: 1 }; }, }, @@ -239,6 +248,22 @@ async function shutdown(node: Node): Promise { await node.store.close(); } +interface Answer { + // `{ task }` from SendMessage, a task from GetTask and CancelTask, a page from ListTasks + readonly result?: Partial & { readonly task?: A2aTask; readonly tasks?: A2aTask[] }; + readonly error?: { code: number; message: string }; +} + +async function call(node: Node, method: string, params: Record): Promise { + const res = await node.gateway.server.inject({ + method: 'POST', + url: '/a2a', + headers: { 'content-type': 'application/json', 'a2a-version': '1.0' }, + payload: JSON.stringify({ jsonrpc: '2.0', id: 'req-1', method, params }), + }); + return res.json(); +} + async function rpc(node: Node, message: Record): Promise { const res = await node.gateway.server.inject({ method: 'POST', @@ -304,6 +329,8 @@ function decline(task: A2aTask): Record { } const TASK_NOT_FOUND = -32001; +// A message on a recorded task that is no longer waiting for payment +const NO_FURTHER_MESSAGES = -32004; describe('a task waiting for payment, held in the receipt store', () => { it('is paid after a restart, and the purchase settles once', async () => { @@ -325,7 +352,7 @@ describe('a task waiting for payment, held in the receipt store', () => { // The payment consumed the task const again = await rpc(second, pay(task, 'nonce-2')); - expect(again.error?.code).toBe(TASK_NOT_FOUND); + expect(again.error?.code).toBe(NO_FURTHER_MESSAGES); expect(calls.settle).toBe(1); }); @@ -359,7 +386,7 @@ describe('a task waiting for payment, held in the receipt store', () => { ]); const paid = answers.filter((answer) => answer.result !== undefined); - const missing = answers.filter((answer) => answer.error?.code === TASK_NOT_FOUND); + const missing = answers.filter((answer) => answer.error?.code === NO_FURTHER_MESSAGES); expect(paid).toHaveLength(1); expect(paid[0]?.result?.task.status.state).toBe('TASK_STATE_COMPLETED'); expect(missing).toHaveLength(1); @@ -390,7 +417,7 @@ describe('a task waiting for payment, held in the receipt store', () => { }); expect(await node.store.getPendingTask?.(task.id)).toBeUndefined(); const later = await rpc(node, pay(task)); - expect(later.error?.code).toBe(TASK_NOT_FOUND); + expect(later.error?.code).toBe(NO_FURTHER_MESSAGES); expect(calls).toMatchObject({ verify: 0, settle: 0 }); }); @@ -403,6 +430,8 @@ describe('a task waiting for payment, held in the receipt store', () => { const { error } = await rpc(node, pay(task)); expect(error?.code).toBe(TASK_NOT_FOUND); expect(calls.verify).toBe(0); + // Its record expires with it, which leaves nothing that looks payable + expect((await call(node, 'GetTask', { id: task.id })).error?.code).toBe(TASK_NOT_FOUND); }); it('stays payable after a malformed payment message', async () => { @@ -489,6 +518,189 @@ describe('a task waiting for payment, held in the receipt store', () => { }); }); +// Neither group: pending tasks and answered tasks both live in memory +const memoryOnly = (store: ReceiptStore): ReceiptStore => + Object.assign(Object.create(store) as ReceiptStore, { + putPendingTask: undefined, + getPendingTask: undefined, + takePendingTask: undefined, + putTaskRecord: undefined, + getTaskRecord: undefined, + listTaskRecords: undefined, + }); + +describe('answered tasks, kept in the receipt store', () => { + it('reads a paid task after a restart, until its retention ends', async () => { + const first = await boot(); + const task = await challenged(first, 'report'); + const paid = (await rpc(first, pay(task))).result?.task; + await shutdown(first); + const second = await boot(); + + expect((await call(second, 'GetTask', { id: task.id })).result).toEqual(paid); + time.advance(24 * HOUR - 1); + expect((await call(second, 'GetTask', { id: task.id })).result).toEqual(paid); + time.advance(1); + expect((await call(second, 'GetTask', { id: task.id })).error?.code).toBe(TASK_NOT_FOUND); + expect((await call(second, 'ListTasks', { contextId: task.contextId })).result).toEqual({ + tasks: [], + nextPageToken: '', + pageSize: 50, + totalSize: 0, + }); + }); + + it('keeps a task for the configured retention', async () => { + const node = await boot(undefined, { retentionHours: 1 }); + const task = await challenged(node, 'report'); + await rpc(node, pay(task)); + + time.advance(HOUR - 1); + expect((await call(node, 'GetTask', { id: task.id })).result?.status?.state).toBe( + 'TASK_STATE_COMPLETED', + ); + time.advance(1); + expect((await call(node, 'GetTask', { id: task.id })).error?.code).toBe(TASK_NOT_FOUND); + }); + + it('reads as working while its payment runs, then as its result', async () => { + const node = await boot(); + const task = await challenged(node, 'report'); + let release = () => {}; + backendGate = new Promise((resolve) => { + release = resolve; + }); + + const paying = rpc(node, pay(task)); + await vi.waitFor(async () => { + const read = await call(node, 'GetTask', { id: task.id }); + expect(read.result?.status?.state).toBe('TASK_STATE_WORKING'); + }); + const working = await call(node, 'ListTasks', { + contextId: task.contextId, + status: 'TASK_STATE_WORKING', + }); + const cancel = await call(node, 'CancelTask', { id: task.id }); + release(); + const paid = (await paying).result?.task; + + expect(working.result?.tasks?.map((listed) => listed.id)).toEqual([task.id]); + expect(cancel.error?.code).toBe(-32002); + expect(paid?.status.state).toBe('TASK_STATE_COMPLETED'); + expect((await call(node, 'GetTask', { id: task.id })).result).toEqual(paid); + expect(calls.settle).toBe(1); + }); + + it('answers an internal error when the canceled task cannot be recorded, and stays canceled', async () => { + let failPuts = false; + const node = await boot((store) => + Object.assign(Object.create(store) as ReceiptStore, { + async putTaskRecord(...args: Parameters>) { + if (failPuts) throw new Error('disk full'); + return store.putTaskRecord?.(...args) ?? false; + }, + }), + ); + const task = await challenged(node, 'report'); + failPuts = true; + + const cancel = await call(node, 'CancelTask', { id: task.id }); + const payment = await rpc(node, pay(task)); + + expect(cancel).toMatchObject({ id: 'req-1', error: { code: -32603 } }); + expect(await node.store.getPendingTask?.(task.id)).toBeUndefined(); + expect(payment.error?.code).toBe(NO_FURTHER_MESSAGES); + expect(calls.verify).toBe(0); + }); + + it('refuses a purchase when the task store is full, and holds nothing for it', async () => { + const node = await boot(undefined, { maxRetained: 1 }); + const waiting = await challenged(node, 'report'); + + const { result } = await rpc(node, buy('report')); + + const busy = result?.task as A2aTask; + expect(busy.status.state).toBe('TASK_STATE_FAILED'); + expect(busy.artifacts[0]?.parts[0]?.data).toMatchObject({ code: 'GATEWAY_BUSY' }); + expect(await node.store.getPendingTask?.(busy.id)).toBeUndefined(); + expect((await call(node, 'GetTask', { id: busy.id })).error?.code).toBe(TASK_NOT_FOUND); + // The waiting task replaces its own record, which always fits + const paid = await rpc(node, pay(waiting)); + expect(paid.result?.task.status.state).toBe('TASK_STATE_COMPLETED'); + }); + + it('keeps no payment proof, mandate or request input in any task record', async () => { + const node = await boot(); + const input = { _authorization: MANDATE, note: 'private-input' }; + const paid = await challenged(node, 'mandated', input); + const declined = await challenged(node, 'mandated', input); + const canceled = await challenged(node, 'mandated', input); + await rpc(node, pay(paid, 'secret-nonce')); + await rpc(node, decline(declined)); + await call(node, 'CancelTask', { id: canceled.id }); + + const db = new Database(path, { readonly: true }); + try { + const rows = db.prepare('SELECT id, state, document_json FROM task_records').all() as { + id: string; + state: string; + }[]; + expect(rows.map((row) => [row.id, row.state]).sort()).toEqual( + [ + [paid.id, 'TASK_STATE_COMPLETED'], + [declined.id, 'TASK_STATE_FAILED'], + [canceled.id, 'TASK_STATE_CANCELED'], + ].sort(), + ); + const text = JSON.stringify(rows); + for (const secret of [ + MANDATE.payload, + '_authorization', + '_payment', + 'secret-nonce', + 'x402.payment.payload', + 'private-input', + ]) { + expect(text).not.toContain(secret); + } + } finally { + db.close(); + } + }); + + it.each([ + ['SQLite', undefined], + ['memory', memoryOnly], + ])( + 'lets one of eight racing cancel and payment messages take a task, in %s', + async (_label, wrap) => { + const node = await boot(wrap); + const task = await challenged(node, 'report'); + + const answers = await Promise.all( + Array.from({ length: 8 }, (_, i) => + i % 2 === 0 + ? call(node, 'CancelTask', { id: task.id }) + : (rpc(node, pay(task, `nonce-${i}`)) as Promise), + ), + ); + + const paid = answers.filter((a) => a.result?.task?.status.state === 'TASK_STATE_COMPLETED'); + const canceled = answers.filter((a) => a.result?.status?.state === 'TASK_STATE_CANCELED'); + const refused = answers.filter((a) => a.error?.code === -32002 || a.error?.code === -32004); + expect(paid.length).toBeLessThanOrEqual(1); + // A cancel and a payment never both succeed + expect(paid.length * canceled.length).toBe(0); + expect(paid.length + canceled.length + refused.length).toBe(8); + expect(calls).toMatchObject({ verify: paid.length, settle: paid.length }); + expect(backendCalls).toBe(paid.length); + expect((await call(node, 'GetTask', { id: task.id })).result?.status?.state).toBe( + paid.length === 1 ? 'TASK_STATE_COMPLETED' : 'TASK_STATE_CANCELED', + ); + }, + ); +}); + describe('a store without the pending-task methods', () => { const noTasks = (store: ReceiptStore): ReceiptStore => Object.assign(Object.create(store) as ReceiptStore, { @@ -516,8 +728,9 @@ describe('a store without the pending-task methods', () => { const lost = await challenged(first, 'report'); await shutdown(first); const second = await boot(wrap); + // The receipt store still holds the task's record, without its pending purchase const { error } = await rpc(second, pay(lost, 'nonce-2')); - expect(error?.code).toBe(TASK_NOT_FOUND); + expect(error?.code).toBe(NO_FURTHER_MESSAGES); expect(calls.verify).toBe(1); }); }); diff --git a/tests/unit/protocols-a2a/pipeline-mapping.test.ts b/tests/unit/protocols-a2a/pipeline-mapping.test.ts index 735c1c7..bffa537 100644 --- a/tests/unit/protocols-a2a/pipeline-mapping.test.ts +++ b/tests/unit/protocols-a2a/pipeline-mapping.test.ts @@ -16,6 +16,7 @@ import type { IdGenerator, Logger, ProtocolAdapterContext, + ReceiptStore, ResourceRegistry, } from '../../../src/core'; import { CommerceError, DELIVERY_SUMMARY_META_KEY, PAYMENT_INPUT_FIELD } from '../../../src/core'; @@ -98,6 +99,8 @@ const delivered: ExecutionOutcome = { durationMs: 3, }; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + // An Error is thrown by the pipeline; anything else is returned as its outcome function setup(outcome: ExecutionOutcome | Error = delivered) { const execute = vi.fn(async (_request: CanonicalRequest): Promise => { @@ -214,8 +217,6 @@ describe('A2A SendMessage onto the execution pipeline', () => { expect(request.resourceId).toBe('market_report'); expect(request.input).toEqual({ symbol: 'ETH' }); expect(request.requestId).toMatch(/^a2a-/); - // The task id is the request id, so a task correlates with its receipt - expect(task(response).id).toBe(request.requestId); expect(task(response).status.state).toBe('TASK_STATE_COMPLETED'); }); @@ -326,6 +327,17 @@ describe('A2A SendMessage onto the execution pipeline', () => { expect(response.error).toBeUndefined(); expect(task(response).status.state).toBe('TASK_STATE_FAILED'); expect(artifactData(response)['code']).toBe(error.code); + // The failed task is kept like any other answer + const read = await post( + adapter, + JSON.stringify({ + jsonrpc: '2.0', + id: 'req-2', + method: 'GetTask', + params: { id: task(response).id }, + }), + ); + expect(read.body.result).toEqual(task(response)); }, ); @@ -371,6 +383,61 @@ describe('A2A adapter is not a client of anything', () => { }); }); +describe('an answered task the store does not keep', () => { + function getTask(id: string): string { + return JSON.stringify({ jsonrpc: '2.0', id: 'req-2', method: 'GetTask', params: { id } }); + } + + function loggingSetup() { + const { context } = setup(); + const warn = vi.fn(); + const error = vi.fn(); + const logger: Logger = { ...NOOP_LOGGER, warn, error }; + return { context: { ...context, logger }, warn, error }; + } + + it('is returned but not kept when the store is full, and the gateway logs a warning', async () => { + const { context, warn } = loggingSetup(); + const adapter = createA2aAdapter({ tasks: { maxRetained: 1 } }); + await adapter.start(context); + const kept = task(await send(adapter, { resource: 'market_report', input: {} })); + + const refused = task(await send(adapter, { resource: 'market_report', input: {} })); + + expect(refused.status.state).toBe('TASK_STATE_COMPLETED'); + expect((await post(adapter, getTask(refused.id))).body.error?.code).toBe(-32001); + expect((await post(adapter, getTask(kept.id))).body.result).toEqual(kept); + expect(warn).toHaveBeenCalledWith( + { state: 'TASK_STATE_COMPLETED' }, + 'a2a adapter: task not retained: the task store is full', + ); + }); + + it('is returned but not kept when the store write fails, and the gateway logs an error', async () => { + const { context, error } = loggingSetup(); + const store = { + putTaskRecord: async () => { + throw new CommerceError('STORAGE_ERROR', 'disk full'); + }, + getTaskRecord: async () => undefined, + listTaskRecords: async () => [], + } as unknown as ReceiptStore; + const adapter = createA2aAdapter({ store }); + await adapter.start(context); + + const answered = task(await send(adapter, { resource: 'market_report', input: {} })); + + expect(answered.status.state).toBe('TASK_STATE_COMPLETED'); + expect(error).toHaveBeenCalledWith( + expect.objectContaining({ state: 'TASK_STATE_COMPLETED' }), + 'a2a adapter: task not retained', + ); + // No task or context id reaches the log + expect(JSON.stringify(error.mock.calls)).not.toContain(answered.id); + expect(JSON.stringify(error.mock.calls)).not.toContain(answered.contextId); + }); +}); + describe('A2A terminal task representation', () => { it('returns a completed task whose artifact carries the canonical body', async () => { const { context } = setup(); @@ -380,8 +447,11 @@ describe('A2A terminal task representation', () => { const response = await send(adapter, { resource: 'market_report', input: { symbol: 'ETH' } }); const result = task(response); - expect(result.id).toMatch(/^a2a-/); - expect(result.contextId).toMatch(/^a2a-ctx-/); + // The task and context ids are access keys: random UUIDs, never the + // predictable `IdGenerator` sequence this context uses + expect(result.id).toMatch(UUID); + expect(result.contextId).toMatch(UUID); + expect(result.contextId).not.toBe(result.id); expect(result.status).toEqual({ state: 'TASK_STATE_COMPLETED', timestamp: '2026-01-01T00:00:00.000Z', diff --git a/tests/unit/protocols-a2a/task-store.test.ts b/tests/unit/protocols-a2a/task-store.test.ts new file mode 100644 index 0000000..0ce46fc --- /dev/null +++ b/tests/unit/protocols-a2a/task-store.test.ts @@ -0,0 +1,134 @@ +// Test the memory fallback for task records and the adapter's retention limits +import { describe, expect, it } from 'vitest'; +import type { Clock } from '../../../src/core'; +import { createA2aAdapter } from '../../../src/protocols/a2a'; +import { createMemoryTasks, createStoredTasks } from '../../../src/protocols/a2a/task-store'; +import type { A2aTask } from '../../../src/protocols/a2a/types'; + +const START = Date.parse('2026-11-22T10:00:00.000Z'); + +function createClock() { + let now = START; + const clock: Clock = { + now: () => new Date(now), + nowIso: () => new Date(now).toISOString(), + monotonicMs: () => now, + }; + return { clock, advance: (ms: number) => (now += ms) }; +} + +function task(id: string, contextId = 'context-1', state = 'TASK_STATE_COMPLETED'): A2aTask { + return { + id, + contextId, + status: { state, timestamp: new Date(START).toISOString() }, + artifacts: [], + }; +} + +const at = (ms: number) => new Date(START + ms).toISOString(); + +describe('createMemoryTasks', () => { + it('returns a task until it expires, and not at its expiry', async () => { + const time = createClock(); + const tasks = createMemoryTasks(time.clock, 10); + await tasks.put(task('a'), at(1000)); + + time.advance(999); + expect(await tasks.get('a')).toEqual(task('a')); + expect(await tasks.list('context-1')).toEqual([task('a')]); + time.advance(1); + expect(await tasks.get('a')).toBeUndefined(); + expect(await tasks.list('context-1')).toEqual([]); + }); + + it("lists only the named context's tasks", async () => { + const tasks = createMemoryTasks(createClock().clock, 10); + await tasks.put(task('a', 'context-1'), at(1000)); + await tasks.put(task('b', 'context-2'), at(1000)); + + expect(await tasks.list('context-2')).toEqual([task('b', 'context-2')]); + expect(await tasks.list('context-3')).toEqual([]); + }); + + it('refuses a new task at the cap and keeps the ones it holds', async () => { + const tasks = createMemoryTasks(createClock().clock, 2); + await tasks.put(task('a'), at(1000)); + await tasks.put(task('b'), at(1000)); + + expect(await tasks.put(task('c'), at(1000))).toBe(false); + expect(await tasks.get('c')).toBeUndefined(); + expect(await tasks.get('a')).toEqual(task('a')); + expect(await tasks.get('b')).toEqual(task('b')); + }); + + it('replaces a task at the cap, since it takes no new place', async () => { + const tasks = createMemoryTasks(createClock().clock, 1); + await tasks.put(task('a'), at(1000)); + + const failed = task('a', 'context-1', 'TASK_STATE_FAILED'); + expect(await tasks.put(failed, at(2000))).toBe(true); + expect(await tasks.get('a')).toEqual(failed); + }); + + it('frees the places of expired tasks at the cap', async () => { + const time = createClock(); + const tasks = createMemoryTasks(time.clock, 1); + await tasks.put(task('a'), at(1000)); + + time.advance(1000); + expect(await tasks.put(task('b'), at(5000))).toBe(true); + expect(await tasks.get('b')).toEqual(task('b')); + }); +}); + +describe('createStoredTasks', () => { + it("reads another protocol's record as no task", async () => { + const record = { + id: 'a', + protocol: 'acp' as const, + groupId: 'context-1', + state: 'completed', + updatedAt: at(0), + document: { id: 'a' }, + expiresAt: at(1000), + }; + const tasks = createStoredTasks( + { + putTaskRecord: async () => true, + getTaskRecord: async () => record, + listTaskRecords: async () => [], + }, + 10, + ); + + expect(await tasks.get('a')).toBeUndefined(); + }); +}); + +describe('the adapter tasks option', () => { + it.each([ + ['retentionHours', 0], + ['retentionHours', 8761], + ['retentionHours', 1.5], + ['maxRetained', 0], + ['maxRetained', 1_000_001], + ['maxRetained', Number.NaN], + ])('refuses %s %d with CONFIG_INVALID naming the option', (name, value) => { + expect(() => createA2aAdapter({ tasks: { [name]: value } })).toThrow( + expect.objectContaining({ + code: 'CONFIG_INVALID', + details: { path: `tasks.${name}` }, + }), + ); + }); + + it.each([ + ['retentionHours', 1], + ['retentionHours', 8760], + ['maxRetained', 1], + ['maxRetained', 1_000_000], + ])('accepts %s %d', (name, value) => { + expect(() => createA2aAdapter({ tasks: { [name]: value } })).not.toThrow(); + }); +}); From 4e021e3f864c294b163c743d630e98de98c18837 Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 11:29:58 +0100 Subject: [PATCH 07/17] feat(a2a): return immediately and finish tasks in the background --- README.md | 2 +- biome.json | 1 + docs/protocols.md | 2 +- docs/protocols/a2a.md | 56 +++- docs/security.md | 5 +- docs/storage.md | 5 +- src/gateway/run.ts | 3 +- src/protocols/a2a/adapter.ts | 132 ++++++--- src/protocols/a2a/background.ts | 48 ++++ src/protocols/a2a/constants.ts | 8 +- src/protocols/a2a/descriptor.ts | 1 + src/protocols/a2a/jsonrpc.ts | 35 ++- src/protocols/a2a/payment-resume.ts | 94 +++++-- src/protocols/a2a/task-mapping.ts | 2 +- src/protocols/a2a/task-operations.ts | 2 +- src/support/a2a.json | 10 +- tests/conformance/a2a/free-resource.test.ts | 23 +- tests/conformance/a2a/tasks.test.ts | 36 ++- tests/e2e/payment/x402-settlement.e2e.test.ts | 121 ++++++-- .../goldens/2.7.2/doctor-multi.json | 2 +- .../goldens/2.7.2/doctor-single.json | 2 +- .../goldens/2.7.2/well-known-multi.json | 3 +- .../goldens/2.7.2/well-known-single.json | 3 +- tests/unit/protocols-a2a/agent-card.test.ts | 3 +- tests/unit/protocols-a2a/background.test.ts | 84 ++++++ .../unit/protocols-a2a/payment-resume.test.ts | 94 ++++++- .../unit/protocols-a2a/pending-store.test.ts | 265 +++++++++++++++++- 27 files changed, 907 insertions(+), 135 deletions(-) create mode 100644 src/protocols/a2a/background.ts create mode 100644 tests/unit/protocols-a2a/background.test.ts diff --git a/README.md b/README.md index 5996bc7..1ee8bcc 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ See [docs/configuration.md](docs/configuration.md). | **MCP** | Supported | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | | **x402** | Supported | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | | **MPP** | Experimental | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A | -| **A2A** | Experimental | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension | +| **A2A** | Experimental | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage` with `returnImmediately`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension | | **ACP** | Experimental | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | | **AP2** | Experimental | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement | | **ERC-8409** | Experimental | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | diff --git a/biome.json b/biome.json index fb7ff14..bf5fe6e 100644 --- a/biome.json +++ b/biome.json @@ -19,6 +19,7 @@ "!package-lock.json", "!src/protocols/acp/spec", "!tests/fixtures/acp", + "!tests/fixtures/a2a", "!tests/fixtures/mcp-registry", "!tests/integration/goldens" ] diff --git a/docs/protocols.md b/docs/protocols.md index ac44c9f..e6b7201 100644 --- a/docs/protocols.md +++ b/docs/protocols.md @@ -13,7 +13,7 @@ subset. Each protocol's page describes that subset in detail. | **MCP** | Supported | Transport that carries x402 and MPP payments in tool calls. | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | | **x402** | Supported | Payment rail, carried by HTTP, MCP and A2A. | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | | **MPP** | Experimental | Payment rail, carried by HTTP, MCP and A2A. | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A | -| **A2A** | Experimental | Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension. | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension | +| **A2A** | Experimental | Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension. | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage` with `returnImmediately`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension | | **ACP** | Experimental | Checkout API that forwards checkout operations to the merchant, whose payment handler receives `payment_data`. Gateway checkout routes are free and carry no x402 or MPP payment. | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | | **AP2** | Experimental | Authorization method, not a payment rail: a paid resource can require a verified mandate in addition to its x402 or MPP payment, never instead of it. | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement | | **ERC-8409** | Experimental | x402 feature: EIP-712 signed quotes on the EVM offers of a challenge. | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | diff --git a/docs/protocols/a2a.md b/docs/protocols/a2a.md index bc91600..783d5b8 100644 --- a/docs/protocols/a2a.md +++ b/docs/protocols/a2a.md @@ -9,7 +9,7 @@ | Version | `A2A-Version: 1.0` header, or an `A2A-Version` query parameter when the header is absent; patch suffixes are accepted but ignored | | Agent Card | `GET /.well-known/agent-card.json` | | Default mount | `/a2a` | -| Task model | synchronous calls; task responses retained for later reads (see [Tasks](#tasks)) | +| Task model | blocking by default; `returnImmediately: true` enables background execution; responses retained for reads (see [Tasks](#tasks)) | Each A2A resource becomes an Agent Card skill. Paid skills have a `paid` tag and a price in their description. A2A v1.0 has no input-schema field for @@ -80,7 +80,7 @@ merchant input and extension metadata. Sending both names for a field returns | `configuration.acceptedOutputModes` | absent, empty, or a list that includes `application/json`, `application/*` or `*/*` | `-32005` | | `configuration.taskPushNotificationConfig` | absent | `-32003` | | `configuration.historyLength`, `historyLength` | absent or an integer from 0 to 2,147,483,647; ignored because no task history is kept | `-32602` | -| `configuration.returnImmediately` | absent or a boolean; ignored, so responses remain synchronous | `-32602` | +| `configuration.returnImmediately` | absent or a boolean; see [Background tasks](#background-tasks) | `-32602` | | `metadata` on `SendMessage` and `CancelTask` | absent or an object; ignored | `-32602` | | `id` on `GetTask` and `CancelTask` | a non-empty string | `-32602` | | `contextId` on `ListTasks` | absent or a string; absent, `null` and `""` list nothing | `-32602` | @@ -110,7 +110,7 @@ An extension status message carries `contextId`, `taskId`, `extensions: []` and the `x402.payment.*` metadata. -1. An x402 paid call without a proof returns `TASK_STATE_INPUT_REQUIRED`. The status +1. A blocking x402 paid call without a proof returns `TASK_STATE_INPUT_REQUIRED`. The status message carries `x402.payment.status: payment-required` and the v2 `PaymentRequired` in `x402.payment.required`. 2. The client sends a message with that `taskId` and sets @@ -225,9 +225,10 @@ Once the store has `protocols.a2a.tasks.maxRetained` unexpired records (default 1000), it refuses new records and permits replacements. It does not evict records, even if the limit is lowered. Free calls cannot evict an unexpired paid result. A new extension purchase at capacity fails with `GATEWAY_BUSY` -without holding a pending purchase. Other responses are returned without being -retained, and the adapter logs at `warn`. Write exceptions are logged at `error`. -Retention changes affect subsequent writes. +without holding a pending purchase. Other blocking responses are returned +without being retained, and the adapter logs at `warn`. Write exceptions are +logged at `error`. Background startup refusals are described below. Retention +changes affect subsequent writes. ### Access @@ -268,18 +269,45 @@ A `SendMessage` that names a task gets these answers: | any other kept task | `UnsupportedOperationError`: the task takes no more messages | | no kept task | `TaskNotFoundError` | +### Background tasks + +With `configuration.returnImmediately: true`, `SendMessage` stores and returns +a `TASK_STATE_WORKING` task without waiting for the purchase result. +`GetTask` and `ListTasks` expose the result once recorded: a finished task or +one waiting for an x402 extension payment. The option also lets a payment +submission run in the background. Declined payments and unknown resources +still return failed tasks immediately. + +Background work can outlive its HTTP request, so each adapter has a separate +limit of 20 background slots. Startup refusals happen before payment +verification, settlement or backend calls: + +- A new purchase returns an unretained failed `GATEWAY_BUSY` task if no slot + is free or its working record does not fit in the task store. +- A payment submission refused because no slot is free returns JSON-RPC + `-32603` with a `google.rpc.RetryInfo` delay instead of a task. A failed + task would be terminal, while this one stays unchanged and payable; resend + the payment after the delay. +- If storing the working task fails for another reason, the call returns a + failed task. A payment submission has already taken its pending purchase, + which is no longer payable. + +Graceful shutdown waits for started background work to settle, including its +result-write attempts. `agent-commerce start` then closes the receipt store. + A stored `TASK_STATE_WORKING` task that is absent from this process's running set is reported by `GetTask` and `ListTasks` as `TASK_STATE_FAILED`. This can -follow a restart or a failed final-result write. Its `INTERNAL_ERROR` envelope -tells the buyer to check with the merchant before paying again. Reads do not -rewrite the record. This assumes one gateway per receipt store. `reconcile` -and manual resolution update the payment attempt, not the task. +follow a forced shutdown during background work or a failed final-result +write. Its `INTERNAL_ERROR` envelope tells the buyer to check with the +merchant before paying again. Reads do not rewrite the record. This assumes +one gateway per receipt store. `reconcile` and manual resolution update the +payment attempt, not the task. ## Errors -The adapter returns JSON-RPC errors for invalid requests and A2A features it -cannot serve. Alongside `-32700`, `-32600`, `-32601`, `-32602` and `-32603`, it -uses these A2A codes: +The adapter returns JSON-RPC errors for invalid requests, A2A features it +cannot serve and calls it is too busy to start. Alongside `-32700`, `-32600`, +`-32601`, `-32602` and `-32603`, it uses these A2A codes: | Code | A2A error | Returned for | | -------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | @@ -327,7 +355,7 @@ The A2A descriptor in `GET /.well-known/agent-commerce` lists these names in - `HTTP+JSON/REST binding` - `gRPC binding` - `SSE` -- `long-running task persistence` +- `resuming a background task after a restart`: A task the gateway stopped in reads as failed; any payment is in the gateway records. - `task resumption other than an x402 extension payment` - `push notifications` - `multi-turn conversational continuation` diff --git a/docs/security.md b/docs/security.md index 199028f..5514490 100644 --- a/docs/security.md +++ b/docs/security.md @@ -429,7 +429,7 @@ real funds. | **a payment-attempt, receipt or journal write fails after the replay reservation** | Delivery or the original commerce error is preserved. Delivered outcomes and terminal events carry known failure labels; each write failure is logged at `error` level. A failed `completed` step adds no detail to those snapshots. The pipeline does not add the list to thrown errors | `tests/integration/transaction-journal.test.ts`, `tests/e2e/payment/crash-matrix.e2e.test.ts` | | **a gateway crash during a paid purchase, from before settlement to before the receipt commit, in either payment flow** | after restart, operator state reflects recorded steps and unresolved entries remain visible. `reconcile` can resolve `reserved` attempts at least `--min-age` old from final chain evidence, marking them `rejected` only with proof of an expired, unused authorization. It can also retry pending AP2 holds. After a payment and its hold are resolved, later runs leave them unchanged. Unknown delivery remains for operator review | `tests/e2e/payment/crash-matrix.e2e.test.ts` | | **SIGTERM while a settlement is held, in either payment flow, then SIGKILL after the grace period** | With AP2 disabled, the gateway drains until killed. After restart, the attempt remains `reserved`; its replay returns 409 without a challenge and moves no funds, whether or not the original transfer landed | `tests/e2e/payment/crash-matrix.e2e.test.ts` | -| **shutdown with a request in flight** | In-flight requests finish before adapters stop; `close()` resolves after both. A second SIGTERM or SIGINT exits immediately with status 1 | `tests/unit/gateway/shutdown.test.ts`, `tests/unit/gateway/main.test.ts` | +| **shutdown with a request in flight** | `close()` drains in-flight requests, then stops adapters; the A2A adapter waits for started background work to settle. A second SIGTERM or SIGINT exits immediately with status 1 | `tests/unit/gateway/shutdown.test.ts`, `tests/unit/gateway/main.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts` | | **a backup taken while the gateway writes, into a directory that holds files, or of a 2.5 database** | Each copy is a consistent snapshot at 0600, hashed in `backup.json`; a new directory is created at 0700. A non-empty `--out` is refused without writing files. Read-only sources keep their schema and import state, including v4 for 2.5 | `tests/unit/cli/backup.test.ts` | | **a restore of a backup older than some purchases** | Spent EVM proofs cannot pay again, including those absent from the backup. Attempts restored as uncertain still need `reconcile` or `resolve`. An AP2 mandate consumed after the backup can authorize again until it expires | `tests/e2e/payment/restore.e2e.test.ts` | | **a receipt write fails before a paid MCP or A2A response** | The `agent-commerce/delivery` summary retains the receipt ID and adds `receiptCommitted: false`; a successful receipt save leaves the field absent | `tests/integration/receipt-committed.test.ts`, `demo/agent/test/run.test.ts` | @@ -501,7 +501,8 @@ real funds. | **free A2A calls filling task retention to push out a paid result** | at capacity, the store refuses new records and permits replacements without evicting unexpired records; a new x402 extension purchase gets `GATEWAY_BUSY` without a pending hold, while other responses are returned without retention | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/task-store.test.ts`, `tests/unit/gateway/main.test.ts` | | **a payment proof, an AP2 mandate or the request input in a stored A2A task** | the adapter does not separately attach request input, payment proofs or AP2 mandates; merchant response content is retained without redaction | `tests/unit/protocols-a2a/pending-store.test.ts` ("keeps no payment proof, mandate or request input in any task record") | | **an A2A task read after its retention ends** | `GetTask` returns `-32001` and `ListTasks` omits the record; writable SQLite stores delete expired records during initialization and before storing a record | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/task-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | -| **an A2A payment interrupted before its result is recorded** | a stored working task absent from the local running set is reported as failed with `INTERNAL_ERROR`; the message tells the buyer to check with the merchant before paying again. This assumes one gateway per receipt store | `tests/conformance/a2a/tasks.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts` | +| **an A2A payment or background task interrupted before its result is recorded** | a stored working task absent from the local running set is reported as failed with `INTERNAL_ERROR`; the message tells the buyer to check with the merchant before paying again. A retry that reaches an existing reserved payment attempt gets `PAYMENT_REPLAYED` before another settlement. This assumes one gateway per receipt store | `tests/conformance/a2a/tasks.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts` | +| **A2A `returnImmediately` calls outliving the gateway mount's request limit** | each adapter has 20 background slots. If none is free, a new purchase gets a failed `GATEWAY_BUSY` task and a payment submission gets `-32603` with a retry delay, both before payment verification, settlement or backend execution; the refused submission leaves its pending purchase payable. Graceful shutdown waits for started background work before closing the store | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/background.test.ts` | | **an A2A 0.x follow-up, with a non-user role, on a pending task** | `-32602`; the task stays pending | same | | **an A2A message carrying a large array of invalid parts or task references** | refused by its length (`PROTOCOL_UNSUPPORTED`) before any element is validated, so no validation issue is built per element | `tests/unit/protocols-a2a/message-mapping.test.ts` | | **an A2A field sent under its proto and JSON names, such as `context_id` beside `contextId`** | `-32602` identifies both spellings before task-store reads or backend calls | `tests/conformance/a2a/params.test.ts` | diff --git a/docs/storage.md b/docs/storage.md index fea2599..7f1ee86 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -149,8 +149,9 @@ migrated by 2.9.0. To roll back, restore a backup made before migration. On the first SIGTERM or SIGINT, the gateway stops accepting connections and waits for in-flight requests without a time limit. It then stops protocol -adapters, closes authorization providers and the database, and exits 0 on -success. A shutdown error exits 1. +adapters, waiting for A2A background work to settle, before closing +authorization providers and the database. Successful shutdown exits 0; a +shutdown error exits 1. A second SIGTERM or SIGINT exits immediately with status 1. An orchestrator can also send SIGKILL when its grace period expires, terminating the process diff --git a/src/gateway/run.ts b/src/gateway/run.ts index 42c367d..5b0f131 100644 --- a/src/gateway/run.ts +++ b/src/gateway/run.ts @@ -199,7 +199,8 @@ export async function runGateway(options: RunGatewayOptions = {}): Promise console.log(''); } - // The first signal waits for in-flight requests without a time limit. + // The first signal waits for in-flight requests and A2A background tasks + // without a time limit. // A second exits immediately with status 1, skipping cleanup as a crash would. let shuttingDown = false; const shutdown = (signal: string): void => { diff --git a/src/protocols/a2a/adapter.ts b/src/protocols/a2a/adapter.ts index 7b5b97d..08b7d60 100644 --- a/src/protocols/a2a/adapter.ts +++ b/src/protocols/a2a/adapter.ts @@ -5,10 +5,12 @@ * lives, and the specification-fixed `/.well-known/agent-card.json`, declared * through `additionalHttpRoutes` so the gateway needs no A2A-specific routing. * - * `SendMessage` runs synchronously. `GetTask` and `ListTasks` read retained - * tasks; `CancelTask` ends pending payments. Other A2A methods are listed in - * `descriptor.unsupported`. This adapter maps reserved payment fields but - * leaves verification, settlement and merchant calls to the pipeline. + * `SendMessage` blocks by default and supports background execution with + * `returnImmediately`. + * `GetTask` and `ListTasks` read retained tasks; `CancelTask` ends pending + * payments. Other A2A methods are listed in `descriptor.unsupported`. + * This adapter maps reserved payment fields but leaves verification, + * settlement and merchant calls to the pipeline. */ import { createHash, randomUUID } from 'node:crypto'; import type { IncomingMessage, ServerResponse } from 'node:http'; @@ -32,12 +34,14 @@ import { hasMethodGroup } from '../../core/store-method-groups'; import { PACKAGE_VERSION } from '../../version'; import { readCappedBody } from '../http'; import { buildAgentCard } from './agent-card'; +import { type BackgroundRuns, createBackgroundRuns } from './background'; import { A2A_AGENT_CARD_PATH, A2A_DEFAULT_AGENT_NAME, A2A_DEFAULT_MOUNT_PATH, A2A_EXTENSIONS_HEADER, A2A_JSON_MEDIA_TYPE, + A2A_MAX_BACKGROUND_RUNS, A2A_MAX_RETAINED_TASKS, A2A_METHOD_CANCEL_TASK, A2A_METHOD_GET_TASK, @@ -71,13 +75,14 @@ import { readSendMessageParams, type SendMessageParams, } from './params'; -import { type PaymentResume, resumePayment, taskResult } from './payment-resume'; +import { BACKGROUND_FULL, type PaymentResume, resumePayment, taskResult } from './payment-resume'; import { completedTask, failedTask, inputRequired, paymentRequiredTask, type TaskIdentity, + workingTask, } from './task-mapping'; import { cancelTask, getTask, listTasks, type TaskOperations } from './task-operations'; import { type A2aTaskStore, createMemoryTasks, createStoredTasks } from './task-store'; @@ -145,6 +150,11 @@ function taskLimit( return value; } +// Capacity error for a task record that does not fit +function storeFull(): CommerceError { + return new CommerceError('GATEWAY_BUSY', 'Too many answered tasks are retained; retry shortly.'); +} + // Reject invalid parameters before running an operation that reads tasks async function withParams

( id: JsonRpcId, @@ -204,8 +214,9 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { private pendingPayments: PendingPayments | undefined; // Retained responses for task lookup, listing and cancellation private tasks: A2aTaskStore | undefined; - // Tasks this process is paying; see `TaskOperations.running` + // Active task ids; see TaskOperations.running private readonly running = new Set(); + private background: BackgroundRuns | undefined; constructor(options: A2aAdapterOptions = {}) { this.mountPath = options.mountPath ?? A2A_DEFAULT_MOUNT_PATH; @@ -258,6 +269,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { this.tasks = hasMethodGroup(this.store, 'task_records') ? createStoredTasks(this.store, this.maxRetained) : createMemoryTasks(context.clock, this.maxRetained); + this.background = createBackgroundRuns(A2A_MAX_BACKGROUND_RUNS, context.logger); this.cardBody = JSON.stringify(this.card); this.cardEtag = `"${createHash('sha256').update(this.cardBody).digest('base64url')}"`; this.started = true; @@ -447,7 +459,12 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { return refusal(id, err); } - const resumed = await resumePayment(this.resume(ops), id, request.params); + const resumed = await resumePayment( + this.resume(ops), + id, + request.params, + request.returnImmediately, + ); if (resumed !== undefined) return resumed; const known = await this.answerKnownTask(ops, id, request.params); if (known !== undefined) return known; @@ -459,7 +476,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { return refusal(id, err); } - return this.execute(ops, id, invocation, x402Extension); + return this.execute(ops, id, invocation, x402Extension, request.returnImmediately); } // Collect task-operation state after startup; handleHttp returns 503 before startup @@ -479,8 +496,8 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { } private resume(ops: TaskOperations): PaymentResume { - const context = this.context; - if (context === undefined) { + const { context, background } = this; + if (context === undefined || background === undefined) { throw new CommerceError('INTERNAL_ERROR', 'A2A adapter is not running.'); } return { @@ -488,6 +505,8 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { pendingPayments: ops.pendingPayments, keep: (task) => this.keep(ops, task), running: this.running, + background, + recordWorking: (task) => this.recordWorking(ops, task), }; } @@ -514,6 +533,20 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { return false; } + // Store the working response before starting background work; return any + // failure so the caller can stop admission + private async recordWorking( + ops: TaskOperations, + task: A2aTask, + ): Promise { + try { + return (await ops.tasks.put(task, ops.retainedUntil())) ? undefined : storeFull(); + } catch (err) { + this.context?.logger.error({ err: toLogInfo(err) }, 'a2a adapter: working task not recorded'); + return toCommerceError(err); + } + } + /** * Reject further messages on a retained task after the pending-payment path * declines it, including tasks taken by another call. Terminal tasks accept @@ -545,15 +578,16 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { ); } - // Execute a new purchase and retain its response when storage permits + // Return the purchase result, or a stored working task for returnImmediately private async execute( ops: TaskOperations, id: JsonRpcId, invocation: A2aInvocation, x402Extension: boolean, + returnImmediately: boolean, ): Promise> { - const context = this.context; - if (context === undefined) { + const { context, background } = this; + if (context === undefined || background === undefined) { return jsonRpcError(id, JSONRPC_INTERNAL_ERROR, 'A2A adapter is not running.'); } const ids = this.taskIds(context); @@ -574,7 +608,42 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { await this.keep(ops, unknown); return taskResult(id, unknown); } + const run = () => this.purchase(ops, context, ids, invocation, resource, x402Extension); + if (!returnImmediately) return taskResult(id, await run()); + // Return the busy task without retaining it; no purchase has started + if (!background.reserve()) { + return taskResult(id, failedTask(new CommerceError('GATEWAY_BUSY', BACKGROUND_FULL), now())); + } + const working = workingTask(ids.taskId, ids.contextId, context.clock.nowIso()); + // Add the running entry before publishing the working record + this.running.add(ids.taskId); + const refused = await this.recordWorking(ops, working); + if (refused !== undefined) { + this.running.delete(ids.taskId); + background.release(); + return taskResult(id, failedTask(refused, now())); + } + background.start(async () => { + try { + await run(); + } finally { + this.running.delete(ids.taskId); + } + }); + return taskResult(id, working); + } + + // Execute the purchase through the pipeline and retain its response when possible + private async purchase( + ops: TaskOperations, + context: ProtocolAdapterContext, + ids: Omit, + invocation: A2aInvocation, + resource: CommerceResource, + x402Extension: boolean, + ): Promise { + const now = (): TaskIdentity => ({ ...ids, timestamp: context.clock.nowIso() }); const requestId = context.ids.next('a2a'); let task: A2aTask; // Reserved-field extraction sits inside the try: a malformed @@ -604,21 +673,18 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { // The extension carries x402 only; any other rail keeps the terminal task if (x402Extension && outcome.requirement.provider === 'x402' && isRecord(envelope)) { const network = outcome.requirement.network; - return taskResult( - id, - await this.awaitPayment( - ops, - identity, - inputRequired(task, paymentRequiredMetadata(envelope), identity.statusMessageId), - { - contextId: identity.contextId, - resourceId: invocation.resourceId, - input, - ...(authorization !== undefined ? { authorization } : {}), - ...(network !== undefined ? { network } : {}), - }, - pendingExpiresAt(context.clock.now().getTime(), outcome.requirement.expiresAt), - ), + return await this.awaitPayment( + ops, + identity, + inputRequired(task, paymentRequiredMetadata(envelope), identity.statusMessageId), + { + contextId: identity.contextId, + resourceId: invocation.resourceId, + input, + ...(authorization !== undefined ? { authorization } : {}), + ...(network !== undefined ? { network } : {}), + }, + pendingExpiresAt(context.clock.now().getTime(), outcome.requirement.expiresAt), ); } } @@ -634,7 +700,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { task = failedTask(error, now()); } await this.keep(ops, task); - return taskResult(id, task); + return task; } /** @@ -652,10 +718,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { ): Promise { if (!(await ops.tasks.put(waiting, expiresAt))) { // Capacity also prevents retaining this failure response - return failedTask( - new CommerceError('GATEWAY_BUSY', 'Too many answered tasks are retained; retry shortly.'), - identity, - ); + return failedTask(storeFull(), identity); } if (!(await ops.pendingPayments.put(waiting.id, purchase, expiresAt))) { const busy = failedTask( @@ -691,6 +754,9 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { async stop(): Promise { this.started = false; + // Wait for background work to settle before releasing adapter state + await this.background?.settled(); + this.background = undefined; this.card = undefined; this.cardBody = ''; this.cardEtag = ''; diff --git a/src/protocols/a2a/background.ts b/src/protocols/a2a/background.ts new file mode 100644 index 0000000..9e6a912 --- /dev/null +++ b/src/protocols/a2a/background.ts @@ -0,0 +1,48 @@ +// Track returnImmediately work independently of HTTP request completion. +// Bound it per adapter because the gateway mount counts only active requests. +import type { Logger } from '../../core'; +import { toLogInfo } from '../../core/errors'; + +export interface BackgroundRuns { + /** Reserve capacity before returning a working task; false when full */ + reserve(): boolean; + /** Release an unused reservation */ + release(): void; + /** Start work in a reserved slot; release it when the returned promise settles */ + start(work: () => Promise): void; + /** Wait for started runs to settle, including those started while waiting */ + settled(): Promise; +} + +export function createBackgroundRuns(limit: number, logger: Logger): BackgroundRuns { + let claimed = 0; + const runs = new Set>(); + return { + reserve() { + if (claimed >= limit) return false; + claimed += 1; + return true; + }, + release() { + claimed -= 1; + }, + start(work) { + const run: Promise = work() + .then( + () => undefined, + // Callers record task outcomes; log unexpected rejections at error + (err: unknown) => { + logger.error({ err: toLogInfo(err) }, 'a2a adapter: background task failed'); + }, + ) + .finally(() => { + claimed -= 1; + runs.delete(run); + }); + runs.add(run); + }, + async settled() { + while (runs.size > 0) await Promise.allSettled([...runs]); + }, + }; +} diff --git a/src/protocols/a2a/constants.ts b/src/protocols/a2a/constants.ts index ae65d55..54cb914 100644 --- a/src/protocols/a2a/constants.ts +++ b/src/protocols/a2a/constants.ts @@ -74,7 +74,7 @@ export const A2A_TASK_STATE_COMPLETED = 'TASK_STATE_COMPLETED'; export const A2A_TASK_STATE_FAILED = 'TASK_STATE_FAILED'; export const A2A_TASK_STATE_CANCELED = 'TASK_STATE_CANCELED'; -/** A task processing an x402 payment submission */ +/** An active payment or a purchase running with returnImmediately */ export const A2A_TASK_STATE_WORKING = 'TASK_STATE_WORKING'; /** An unpaid x402 extension task waiting for a payment message */ @@ -88,3 +88,9 @@ export const A2A_TASK_RETENTION_HOURS = { min: 1, max: 8760, default: 24 } as co /** Bounds and default for the record admission limit, `protocols.a2a.tasks.maxRetained` */ export const A2A_MAX_RETAINED_TASKS = { min: 1, max: 1_000_000, default: 1000 } as const; + +/** + * Per-adapter limit for background runs, which can outlive HTTP requests and + * need a separate cap from the gateway mount's in-flight request limit + */ +export const A2A_MAX_BACKGROUND_RUNS = 20; diff --git a/src/protocols/a2a/descriptor.ts b/src/protocols/a2a/descriptor.ts index 6ebf0e1..146ffa3 100644 --- a/src/protocols/a2a/descriptor.ts +++ b/src/protocols/a2a/descriptor.ts @@ -17,6 +17,7 @@ const A2A_CAPABILITIES: readonly string[] = [ 'GetTask', 'ListTasks', 'CancelTask', + 'returnImmediately', // The x402 A2A transport, opt-in per request 'x402-extension', ]; diff --git a/src/protocols/a2a/jsonrpc.ts b/src/protocols/a2a/jsonrpc.ts index 6dc771e..1719efe 100644 --- a/src/protocols/a2a/jsonrpc.ts +++ b/src/protocols/a2a/jsonrpc.ts @@ -82,32 +82,37 @@ export function jsonRpcResult(id: JsonRpcId, result: unknown): Record[] = [], ): Record { const reason = A2A_ERROR_REASONS.get(code); - const error: JsonRpcErrorBody = { - code, - message, + const data = [ ...(reason !== undefined - ? { - data: [ - { - '@type': 'type.googleapis.com/google.rpc.ErrorInfo', - reason, - domain: 'a2a-protocol.org', - }, - ], - } - : {}), - }; + ? [ + { + '@type': 'type.googleapis.com/google.rpc.ErrorInfo', + reason, + domain: 'a2a-protocol.org', + }, + ] + : []), + ...details, + ]; + const error: JsonRpcErrorBody = { code, message, ...(data.length > 0 ? { data } : {}) }; return { jsonrpc: '2.0', id, error }; } +/** `google.rpc.RetryInfo`: when a client may retry a temporarily refused call */ +export function retryInfo(seconds: number): Record { + return { '@type': 'type.googleapis.com/google.rpc.RetryInfo', retryDelay: `${seconds}s` }; +} + export function parseJsonRpcRequest(rawBody: string): JsonRpcParseResult { let payload: unknown; try { diff --git a/src/protocols/a2a/payment-resume.ts b/src/protocols/a2a/payment-resume.ts index b7bced9..224aaaa 100644 --- a/src/protocols/a2a/payment-resume.ts +++ b/src/protocols/a2a/payment-resume.ts @@ -3,8 +3,16 @@ import type { AuthorizationSubmission, CanonicalRequest, ProtocolAdapterContext import { CommerceError, toCommerceError } from '../../core'; import { toLogInfo } from '../../core/errors'; import { isRecord } from '../../core/is-record'; +import type { BackgroundRuns } from './background'; import { A2A_TASK_STATE_FAILED } from './constants'; -import { JSONRPC_INVALID_PARAMS, type JsonRpcId, jsonRpcError, jsonRpcResult } from './jsonrpc'; +import { + JSONRPC_INTERNAL_ERROR, + JSONRPC_INVALID_PARAMS, + type JsonRpcId, + jsonRpcError, + jsonRpcResult, + retryInfo, +} from './jsonrpc'; import { completedTask, failedTask, @@ -36,19 +44,31 @@ export interface PaymentResume { readonly pendingPayments: PendingPayments; /** Retain a response; log write failures and return false instead of throwing */ readonly keep: (task: A2aTask) => Promise; - /** Task ids whose payments are running in this process */ + /** Active task ids, including blocking payments and background runs */ readonly running: Set; + readonly background: BackgroundRuns; + /** Store a working response; return an error if the write fails */ + readonly recordWorking: (task: A2aTask) => Promise; } +/** Refusal message when no background slot is free */ +export const BACKGROUND_FULL = 'Too many tasks are running in the background; retry shortly.'; + +// Seconds a payment refused for want of a background slot waits before a resend +const BACKGROUND_RETRY_SECONDS = 1; + /** * Resume an unpaid x402 task identified by `taskId`, even without the extension * header. Return undefined if the message names no pending task or loses the * atomic take to another call. Call after `readMessage` validates the message. + * For a payment submission with `returnImmediately`, return a working task + * without waiting for the payment result. */ export async function resumePayment( resume: PaymentResume, id: JsonRpcId, params: unknown, + returnImmediately: boolean, ): Promise | undefined> { const { context, pendingPayments } = resume; const message = isRecord(params) ? params['message'] : undefined; @@ -81,11 +101,24 @@ export async function resumePayment( return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message); } } + // Reserve capacity before taking the purchase so a full runner leaves it + // payable. Refuse with a system error, not a failed task: a terminal state + // would tell the client the task takes no more messages (A2A 1.0.1 + // sections 3.1.1 and 3.3.2). + const immediate = returnImmediately && submission.kind === 'submitted'; + if (immediate && !resume.background.reserve()) { + return jsonRpcError(id, JSONRPC_INTERNAL_ERROR, BACKGROUND_FULL, [ + retryInfo(BACKGROUND_RETRY_SECONDS), + ]); + } // Take after validation and before execution; the earlier read did not claim // the purchase. If another payment or cancellation took it, let the adapter // respond from the retained task record. const taken = await pendingPayments.take(taskId); - if (taken === undefined) return undefined; + if (taken === undefined) { + if (immediate) resume.background.release(); + return undefined; + } const authorization = taken.authorization ?? followUp; if (submission.kind === 'rejected') { @@ -105,25 +138,46 @@ export async function resumePayment( return taskResult(id, declined); } + const ids = { + taskId, + contextId: taken.contextId, + artifactId: context.ids.next('a2a-artifact'), + statusMessageId: context.ids.next('a2a-msg'), + }; + const working = workingTask(taskId, taken.contextId, context.clock.nowIso()); + // Add the running entry before publishing the working record resume.running.add(taskId); - try { - await resume.keep(workingTask(taskId, taken.contextId, context.clock.nowIso())); - const paid = await payPending( - context, - { ...taken, ...(authorization !== undefined ? { authorization } : {}) }, - submission.payload, - { - taskId, - contextId: taken.contextId, - artifactId: context.ids.next('a2a-artifact'), - statusMessageId: context.ids.next('a2a-msg'), - }, - ); - await resume.keep(paid); - return taskResult(id, paid); - } finally { - resume.running.delete(taskId); + if (!immediate) { + await resume.keep(working); + } else { + // Require a working record before background payment processing. The + // purchase has been taken, but payment verification has not started. + const refused = await resume.recordWorking(working); + if (refused !== undefined) { + resume.running.delete(taskId); + resume.background.release(); + const failed = failedTask(refused, { ...ids, timestamp: context.clock.nowIso() }); + await resume.keep(failed); + return taskResult(id, failed); + } } + const pay = async (): Promise => { + try { + const paid = await payPending( + context, + { ...taken, ...(authorization !== undefined ? { authorization } : {}) }, + submission.payload, + ids, + ); + await resume.keep(paid); + return paid; + } finally { + resume.running.delete(taskId); + } + }; + if (!immediate) return taskResult(id, await pay()); + resume.background.start(pay); + return taskResult(id, working); } // The pending purchase is consumed before execution; resends to a retained diff --git a/src/protocols/a2a/task-mapping.ts b/src/protocols/a2a/task-mapping.ts index b037e55..a21c77c 100644 --- a/src/protocols/a2a/task-mapping.ts +++ b/src/protocols/a2a/task-mapping.ts @@ -151,7 +151,7 @@ export function failedTask(error: CommerceError, identity: TaskIdentity): A2aTas ); } -/** A task processing an x402 payment submission */ +/** A task whose execution is still in progress */ export function workingTask(taskId: string, contextId: string, timestamp: string): A2aTask { return { id: taskId, diff --git a/src/protocols/a2a/task-operations.ts b/src/protocols/a2a/task-operations.ts index e4cce4d..17fbf5b 100644 --- a/src/protocols/a2a/task-operations.ts +++ b/src/protocols/a2a/task-operations.ts @@ -30,7 +30,7 @@ import type { PendingPayments } from './x402-extension'; export interface TaskOperations { readonly tasks: A2aTaskStore; readonly pendingPayments: PendingPayments; - /** Task ids whose payments are running in this process */ + /** Active task ids, including blocking payments and background runs */ readonly running: ReadonlySet; readonly clock: Clock; /** Expiry to assign when recording a task now */ diff --git a/src/support/a2a.json b/src/support/a2a.json index 0b7538b..9463819 100644 --- a/src/support/a2a.json +++ b/src/support/a2a.json @@ -4,7 +4,7 @@ "title": "A2A", "status": "experimental", "role": "Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension.", - "subset": "Agent Card, `SendMessage`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension", + "subset": "Agent Card, `SendMessage` with `returnImmediately`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension", "spec": { "revisions": ["1.0.1"], "display": "v1.0.1; negotiation `1.0`; `JSONRPC` binding", @@ -25,6 +25,7 @@ { "name": "GetTask", "status": "experimental" }, { "name": "ListTasks", "status": "experimental" }, { "name": "CancelTask", "status": "experimental" }, + { "name": "returnImmediately", "status": "experimental" }, { "name": "x402-extension", "status": "experimental" } ], "exclusions": [ @@ -38,7 +39,10 @@ { "name": "HTTP+JSON/REST binding" }, { "name": "gRPC binding" }, { "name": "SSE" }, - { "name": "long-running task persistence" }, + { + "name": "resuming a background task after a restart", + "note": "A task the gateway stopped in reads as failed; any payment is in the gateway records." + }, { "name": "task resumption other than an x402 extension payment" }, { "name": "push notifications" }, { "name": "multi-turn conversational continuation" }, @@ -75,7 +79,7 @@ }, { "requirement": "§3.2.2: returnImmediately as well as the blocking default", - "state": "open" + "state": "closed" }, { "requirement": "§3.3.2: validate all input parameters, including tenant and configuration", diff --git a/tests/conformance/a2a/free-resource.test.ts b/tests/conformance/a2a/free-resource.test.ts index a0dacaf..ef93677 100644 --- a/tests/conformance/a2a/free-resource.test.ts +++ b/tests/conformance/a2a/free-resource.test.ts @@ -6,7 +6,7 @@ */ import { Role, type SendMessageRequest, TaskState } from '@a2a-js/sdk'; import { ClientFactory } from '@a2a-js/sdk/client'; -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { MERCHANT_BODY, type RunningGateway, startConformanceGateway } from './support/gateway'; let running: RunningGateway; @@ -84,6 +84,27 @@ describe('free resource, invoked by the official SDK client', () => { expect(metadata?.['agent-commerce/delivery']).toMatchObject({ resourceId: 'weather_basic' }); }); + it('answers a working task with returnImmediately, and reads the result with getTask', async () => { + const sdk = await client(); + const result = await sdk.sendMessage({ + ...invocation('weather_basic', { city: 'Berlin' }), + configuration: { + acceptedOutputModes: [], + taskPushNotificationConfig: undefined, + historyLength: undefined, + returnImmediately: true, + }, + }); + if (!('status' in result)) throw new Error('expected a task'); + + expect(result.status?.state).toBe(TaskState.TASK_STATE_WORKING); + await vi.waitFor(async () => { + const read = await sdk.getTask({ tenant: '', id: result.id, historyLength: undefined }); + expect(read.status?.state).toBe(TaskState.TASK_STATE_COMPLETED); + expect(read.artifacts[0]?.parts[0]?.content?.value).toEqual(MERCHANT_BODY); + }); + }); + it('answers a resource that is not exposed over a2a with a failed task, not a transport error', async () => { const result = await (await client()).sendMessage(invocation('http_only', {})); if (!('status' in result)) throw new Error('expected a task'); diff --git a/tests/conformance/a2a/tasks.test.ts b/tests/conformance/a2a/tasks.test.ts index 1a36556..983fd78 100644 --- a/tests/conformance/a2a/tasks.test.ts +++ b/tests/conformance/a2a/tasks.test.ts @@ -8,7 +8,7 @@ import { randomUUID } from 'node:crypto'; import { TaskState } from '@a2a-js/sdk'; import { ClientFactory } from '@a2a-js/sdk/client'; -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import type { TaskRecord } from '../../../src/core'; import type { A2aTask } from '../../../src/protocols/a2a/types'; import { MERCHANT_BODY, type RunningGateway, startConformanceGateway } from './support/gateway'; @@ -341,6 +341,40 @@ describe('SendMessage naming a recorded task', () => { }); }); +describe('SendMessage with returnImmediately', () => { + it('answers a working task at once, and GetTask then reads the result', async () => { + const body = await post('SendMessage', { + ...invocation({ resource: 'weather_basic', input: { city: 'Berlin' } }), + configuration: { returnImmediately: true }, + }); + const working = (body.result as { task: A2aTask }).task; + + expect(working).toEqual({ + id: working.id, + contextId: working.contextId, + status: { state: 'TASK_STATE_WORKING', timestamp: expect.any(String) }, + artifacts: [], + }); + await vi.waitFor(async () => { + const read = (await post('GetTask', { id: working.id })).result as A2aTask; + expect(read.status.state).toBe('TASK_STATE_COMPLETED'); + expect(read.contextId).toBe(working.contextId); + expect(read.artifacts[0]?.parts[0]?.data).toEqual(MERCHANT_BODY); + }); + }); + + it('answers an unknown resource with its failed task, without a background run', async () => { + const body = await post('SendMessage', { + ...invocation({ resource: 'no_such_resource', input: {} }), + configuration: { returnImmediately: true }, + }); + + const task = (body.result as { task: A2aTask }).task; + expect(task.status.state).toBe('TASK_STATE_FAILED'); + expect(task.artifacts[0]?.parts[0]?.data).toMatchObject({ code: 'RESOURCE_NOT_FOUND' }); + }); +}); + describe('task and context ids', () => { it('gives every task its own random ids, apart from the request id', async () => { const [one, two] = await Promise.all([free(), free()]); diff --git a/tests/e2e/payment/x402-settlement.e2e.test.ts b/tests/e2e/payment/x402-settlement.e2e.test.ts index 5afbc12..6441d39 100644 --- a/tests/e2e/payment/x402-settlement.e2e.test.ts +++ b/tests/e2e/payment/x402-settlement.e2e.test.ts @@ -13,7 +13,7 @@ import { x402Client, x402HTTPClient } from '@x402/core/client'; import type { PaymentRequired } from '@x402/core/types'; import { registerExactEvmScheme } from '@x402/evm/exact/client'; import { privateKeyToAccount } from 'viem/accounts'; -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { parseConfig } from '../../../src/config'; import { type BackendExecutor, @@ -159,6 +159,34 @@ async function invoke( return { statusCode: res.statusCode, headers: res.headers, body: res.json() }; } +// Send an A2A JSON-RPC call with the x402 extension header and return its result +async function a2a(method: string, params: Record): Promise { + const res = await gateway.server.inject({ + method: 'POST', + url: '/a2a', + headers: { + 'content-type': 'application/json', + 'a2a-version': '1.0', + 'a2a-extensions': A2A_X402_EXTENSION_URI, + }, + payload: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), + }); + return res.json<{ result: T }>().result; +} + +// Sign an A2A x402 extension challenge with the funded buyer's key +async function a2aPayment(waiting: A2aTask) { + const client = new x402Client(); + registerExactEvmScheme(client, { + signer: privateKeyToAccount(deployment.buyer.privateKey), + networks: ['eip155:31337'], + }); + client.setSpendControls(false); // MockUSDC is not in the SDK's asset list + return client.createPaymentPayload( + waiting.status.message?.metadata?.['x402.payment.required'] as PaymentRequired, + ); +} + // Asks the gateway for the resource unpaid and signs the challenge it returns async function gatewayProof( overrides?: Parameters[0]['overrides'], @@ -693,24 +721,8 @@ describe('x402 settlement - real local chain', () => { }); it('14. settles an A2A x402 payment on the local chain', async () => { - async function sendMessage(message: Record): Promise { - const res = await gateway.server.inject({ - method: 'POST', - url: '/a2a', - headers: { - 'content-type': 'application/json', - 'a2a-version': '1.0', - 'a2a-extensions': A2A_X402_EXTENSION_URI, - }, - payload: JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'SendMessage', - params: { message }, - }), - }); - return res.json<{ result: { task: A2aTask } }>().result.task; - } + const sendMessage = async (message: Record) => + (await a2a<{ task: A2aTask }>('SendMessage', { message })).task; const callsBefore = backendCalls; const waiting = await sendMessage({ @@ -721,15 +733,7 @@ describe('x402 settlement - real local chain', () => { expect(waiting.status.state).toBe('TASK_STATE_INPUT_REQUIRED'); expect(backendCalls).toBe(callsBefore); - const client = new x402Client(); - registerExactEvmScheme(client, { - signer: privateKeyToAccount(deployment.buyer.privateKey), - networks: ['eip155:31337'], - }); - client.setSpendControls(false); // MockUSDC is not in the SDK's asset list - const payload = await client.createPaymentPayload( - waiting.status.message?.metadata?.['x402.payment.required'] as PaymentRequired, - ); + const payload = await a2aPayment(waiting); const before = await balances(); const paid = await sendMessage({ @@ -761,6 +765,67 @@ describe('x402 settlement - real local chain', () => { }); }); + it('14b. settles an A2A x402 payment sent with returnImmediately, read back with GetTask', async () => { + const immediately = { returnImmediately: true }; + const read = (id: string) => a2a('GetTask', { id }); + const callsBefore = backendCalls; + + const started = await a2a<{ task: A2aTask }>('SendMessage', { + message: { + role: 'ROLE_USER', + messageId: 'msg-buy-later', + parts: [{ data: { resource: RESOURCE_ID }, mediaType: 'application/json' }], + }, + configuration: immediately, + }); + expect(started.task.status.state).toBe('TASK_STATE_WORKING'); + let waiting: A2aTask | undefined; + await vi.waitFor(async () => { + waiting = await read(started.task.id); + expect(waiting.status.state).toBe('TASK_STATE_INPUT_REQUIRED'); + }); + const payload = await a2aPayment(waiting as A2aTask); + + const before = await balances(); + const paying = await a2a<{ task: A2aTask }>('SendMessage', { + message: { + role: 'ROLE_USER', + messageId: 'msg-pay-later', + taskId: started.task.id, + parts: [{ text: 'Here is the payment authorization.' }], + metadata: { 'x402.payment.status': 'payment-submitted', 'x402.payment.payload': payload }, + }, + configuration: immediately, + }); + expect(paying.task.status.state).toBe('TASK_STATE_WORKING'); + let paid: A2aTask | undefined; + await vi.waitFor( + async () => { + paid = await read(started.task.id); + expect(paid.status.state).toBe('TASK_STATE_COMPLETED'); + }, + { timeout: 30_000 }, + ); + const after = await balances(); + + const [receipt] = (paid?.status.message?.metadata?.['x402.payment.receipts'] ?? []) as { + success: boolean; + transaction: string; + }[]; + expect(receipt?.success).toBe(true); + expect(backendCalls).toBe(callsBefore + 1); + await expectRealSettlement({ + rpcUrl: anvil.rpcUrl, + asset: deployment.asset, + buyer: deployment.buyer.address, + merchant: deployment.merchant.address, + before, + after, + amountBaseUnits: 1_000_000n, + txHash: receipt?.transaction as string, + }); + }); + it('15. leaves funds untouched when the backend fails before settlement, and the same proof pays once on retry', async () => { const proof = await gatewayProof(); const receiptsBefore = (await store.listReceipts()).length; diff --git a/tests/integration/goldens/2.7.2/doctor-multi.json b/tests/integration/goldens/2.7.2/doctor-multi.json index f9f0840..052a955 100644 --- a/tests/integration/goldens/2.7.2/doctor-multi.json +++ b/tests/integration/goldens/2.7.2/doctor-multi.json @@ -28,7 +28,7 @@ { "name": "A2A unsupported", "status": "INFO", - "detail": "SendStreamingMessage, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, tasks across gateway instances" + "detail": "SendStreamingMessage, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, resuming a background task after a restart, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, tasks across gateway instances" }, { "name": "ACP", diff --git a/tests/integration/goldens/2.7.2/doctor-single.json b/tests/integration/goldens/2.7.2/doctor-single.json index 4f8c3fc..b342495 100644 --- a/tests/integration/goldens/2.7.2/doctor-single.json +++ b/tests/integration/goldens/2.7.2/doctor-single.json @@ -28,7 +28,7 @@ { "name": "A2A unsupported", "status": "INFO", - "detail": "SendStreamingMessage, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, long-running task persistence, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, tasks across gateway instances" + "detail": "SendStreamingMessage, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, resuming a background task after a restart, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, tasks across gateway instances" }, { "name": "ACP", diff --git a/tests/integration/goldens/2.7.2/well-known-multi.json b/tests/integration/goldens/2.7.2/well-known-multi.json index 81c0aea..a97314d 100644 --- a/tests/integration/goldens/2.7.2/well-known-multi.json +++ b/tests/integration/goldens/2.7.2/well-known-multi.json @@ -72,6 +72,7 @@ "GetTask", "ListTasks", "CancelTask", + "returnImmediately", "x402-extension" ], "status": "experimental", @@ -86,7 +87,7 @@ "HTTP+JSON/REST binding", "gRPC binding", "SSE", - "long-running task persistence", + "resuming a background task after a restart", "task resumption other than an x402 extension payment", "push notifications", "multi-turn conversational continuation", diff --git a/tests/integration/goldens/2.7.2/well-known-single.json b/tests/integration/goldens/2.7.2/well-known-single.json index d44b86e..d3b3ffa 100644 --- a/tests/integration/goldens/2.7.2/well-known-single.json +++ b/tests/integration/goldens/2.7.2/well-known-single.json @@ -72,6 +72,7 @@ "GetTask", "ListTasks", "CancelTask", + "returnImmediately", "x402-extension" ], "status": "experimental", @@ -86,7 +87,7 @@ "HTTP+JSON/REST binding", "gRPC binding", "SSE", - "long-running task persistence", + "resuming a background task after a restart", "task resumption other than an x402 extension payment", "push notifications", "multi-turn conversational continuation", diff --git a/tests/unit/protocols-a2a/agent-card.test.ts b/tests/unit/protocols-a2a/agent-card.test.ts index c66d193..f4ee815 100644 --- a/tests/unit/protocols-a2a/agent-card.test.ts +++ b/tests/unit/protocols-a2a/agent-card.test.ts @@ -290,6 +290,7 @@ describe('A2A adapter lifecycle', () => { 'GetTask', 'ListTasks', 'CancelTask', + 'returnImmediately', 'x402-extension', ]); for (const served of ['GetTask', 'ListTasks', 'CancelTask']) { @@ -300,7 +301,7 @@ describe('A2A adapter lifecycle', () => { expect(descriptor.unsupported).toEqual( expect.arrayContaining([ 'SendStreamingMessage', - 'long-running task persistence', + 'resuming a background task after a restart', 'push notifications', 'multi-turn conversational continuation', 'HTTP+JSON/REST binding', diff --git a/tests/unit/protocols-a2a/background.test.ts b/tests/unit/protocols-a2a/background.test.ts new file mode 100644 index 0000000..f0fbc65 --- /dev/null +++ b/tests/unit/protocols-a2a/background.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Logger } from '../../../src/core'; +import { createBackgroundRuns } from '../../../src/protocols/a2a/background'; + +function logger(): Logger & { error: ReturnType } { + const log = { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + child: () => log, + }; + return log; +} + +// Let the test resolve or reject a run on demand +function deferred() { + let resolve = () => {}; + let reject: (err: unknown) => void = () => {}; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +describe('createBackgroundRuns', () => { + it('refuses a slot at the limit and gives one back on release', () => { + const runs = createBackgroundRuns(2, logger()); + + expect([runs.reserve(), runs.reserve(), runs.reserve()]).toEqual([true, true, false]); + runs.release(); + expect(runs.reserve()).toBe(true); + }); + + it('frees a slot when its run settles, whether it resolves or rejects', async () => { + const log = logger(); + const runs = createBackgroundRuns(2, log); + const ok = deferred(); + const bad = deferred(); + runs.reserve(); + runs.start(() => ok.promise); + runs.reserve(); + runs.start(() => bad.promise); + expect(runs.reserve()).toBe(false); + + ok.resolve(); + bad.reject(new Error('backend gone')); + await runs.settled(); + + expect([runs.reserve(), runs.reserve(), runs.reserve()]).toEqual([true, true, false]); + expect(log.error).toHaveBeenCalledOnce(); + expect(log.error).toHaveBeenCalledWith( + { err: expect.objectContaining({ code: 'INTERNAL_ERROR' }) }, + 'a2a adapter: background task failed', + ); + }); + + it('settles only after every run, including one started while it waits', async () => { + const runs = createBackgroundRuns(2, logger()); + const first = deferred(); + const second = deferred(); + runs.reserve(); + runs.start(() => first.promise); + let settled = false; + const waiting = runs.settled().then(() => { + settled = true; + }); + + runs.reserve(); + runs.start(() => second.promise); + first.resolve(); + for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setImmediate(resolve)); + expect(settled).toBe(false); + second.resolve(); + await waiting; + + expect(settled).toBe(true); + }); + + it('settles at once with no runs', async () => { + await expect(createBackgroundRuns(1, logger()).settled()).resolves.toBeUndefined(); + }); +}); diff --git a/tests/unit/protocols-a2a/payment-resume.test.ts b/tests/unit/protocols-a2a/payment-resume.test.ts index c9fbd3a..5261285 100644 --- a/tests/unit/protocols-a2a/payment-resume.test.ts +++ b/tests/unit/protocols-a2a/payment-resume.test.ts @@ -6,9 +6,13 @@ import { type Logger, type ProtocolAdapterContext, } from '../../../src/core'; +import { createBackgroundRuns } from '../../../src/protocols/a2a/background'; import { resumePayment } from '../../../src/protocols/a2a/payment-resume'; import type { A2aTask } from '../../../src/protocols/a2a/types'; -import { createPendingPayments } from '../../../src/protocols/a2a/x402-extension'; +import { + createPendingPayments, + type PendingPayments, +} from '../../../src/protocols/a2a/x402-extension'; const NOW = Date.parse('2026-11-07T00:00:00.000Z'); const clock: Clock = { @@ -45,9 +49,17 @@ async function resumeWith(refusal: CommerceError) { }; const response = await resumePayment( - { context, pendingPayments, keep: async () => true, running: new Set() }, + { + context, + pendingPayments, + keep: async () => true, + running: new Set(), + background: createBackgroundRuns(1, logger), + recordWorking: async () => undefined, + }, 1, { message }, + false, ); const task = (response as { result: { task: A2aTask } }).result.task; const envelope = task.artifacts?.[0]?.parts[0]?.data as Record; @@ -95,3 +107,81 @@ describe('resumePayment pipeline refusals', () => { expect((await resumeWith(backend)).envelope.retryable).toBe(true); }); }); + +describe('resumePayment with returnImmediately', () => { + // Use one slot to check that refused calls release their reservations + async function answer( + status: string, + pendingPayments: PendingPayments, + recordWorking: () => Promise = async () => undefined, + ) { + const background = createBackgroundRuns(1, logger); + const context = { + pipeline: { execute: vi.fn() }, + logger, + clock, + ids: { next: (prefix = 'id') => `${prefix}-1` }, + } as unknown as ProtocolAdapterContext; + const message = { + taskId: 'task-1', + messageId: 'msg-1', + role: 'ROLE_USER', + metadata: { 'x402.payment.status': status, 'x402.payment.payload': { scheme: 'exact' } }, + }; + const response = await resumePayment( + { + context, + pendingPayments, + keep: async () => true, + running: new Set(), + background, + recordWorking, + }, + 1, + { message }, + true, + ); + return { response, background, execute: context.pipeline.execute }; + } + + it('frees the slot when another call took the task first', async () => { + const pendingPayments = createPendingPayments(clock); + await pendingPayments.put('task-1', { contextId: 'ctx-1', resourceId: 'report', input: {} }); + // Simulate another call taking the task between the read and the take + const lost: PendingPayments = { ...pendingPayments, take: async () => undefined }; + + const { response, background, execute } = await answer('payment-submitted', lost); + + expect(response).toBeUndefined(); + expect(background.reserve()).toBe(true); + expect(execute).not.toHaveBeenCalled(); + }); + + it('frees the slot and runs nothing when the working task cannot be recorded', async () => { + const pendingPayments = createPendingPayments(clock); + await pendingPayments.put('task-1', { contextId: 'ctx-1', resourceId: 'report', input: {} }); + + const { response, background, execute } = await answer( + 'payment-submitted', + pendingPayments, + async () => new CommerceError('STORAGE_ERROR', 'The task store is unavailable.'), + ); + + const task = (response as { result: { task: A2aTask } }).result.task; + expect(task.status.state).toBe('TASK_STATE_FAILED'); + expect(task.artifacts[0]?.parts[0]?.data).toMatchObject({ code: 'STORAGE_ERROR' }); + expect(background.reserve()).toBe(true); + expect(execute).not.toHaveBeenCalled(); + }); + + it('declines at once without taking a slot', async () => { + const pendingPayments = createPendingPayments(clock); + await pendingPayments.put('task-1', { contextId: 'ctx-1', resourceId: 'report', input: {} }); + + const { response, background } = await answer('payment-rejected', pendingPayments); + + const task = (response as { result: { task: A2aTask } }).result.task; + expect(task.status.state).toBe('TASK_STATE_FAILED'); + expect(background.reserve()).toBe(true); + }); +}); diff --git a/tests/unit/protocols-a2a/pending-store.test.ts b/tests/unit/protocols-a2a/pending-store.test.ts index 1212f5c..6116839 100644 --- a/tests/unit/protocols-a2a/pending-store.test.ts +++ b/tests/unit/protocols-a2a/pending-store.test.ts @@ -179,7 +179,7 @@ interface Node { interface JsonRpc { readonly result?: { task: A2aTask }; - readonly error?: { code: number; message: string }; + readonly error?: { code: number; message: string; data?: Record[] }; } let dir: string; @@ -190,6 +190,8 @@ let time: ReturnType; let ids: IdGenerator; // Set to hold every backend call until it resolves let backendGate: Promise | undefined; +// Release the backend gate so teardown can finish waiting for background work +let releaseBackend: () => void; let open: Node[]; beforeEach(() => { @@ -198,6 +200,7 @@ beforeEach(() => { calls = { verify: 0, settle: 0, mandates: [] }; backendCalls = 0; backendGate = undefined; + releaseBackend = () => {}; time = createClock(); // Keep test IDs distinct across gateway restarts let n = 0; @@ -206,6 +209,7 @@ beforeEach(() => { }); afterEach(async () => { + releaseBackend(); for (const node of open) await shutdown(node); rmSync(dir, { recursive: true, force: true }); }); @@ -264,7 +268,11 @@ async function call(node: Node, method: string, params: Record) return res.json(); } -async function rpc(node: Node, message: Record): Promise { +async function rpc( + node: Node, + message: Record, + configuration?: Record, +): Promise { const res = await node.gateway.server.inject({ method: 'POST', url: '/a2a', @@ -277,7 +285,7 @@ async function rpc(node: Node, message: Record): Promise { ); }); +// Block backend calls until the returned release function is called +function holdBackend(): () => void { + backendGate = new Promise((resolve) => { + releaseBackend = resolve; + }); + return releaseBackend; +} + +const IMMEDIATELY = { returnImmediately: true }; + +// Submit a purchase with its proof and returnImmediately, without the x402 extension +function buyNow(node: Node, proof: string, resource = 'report'): Promise { + return call(node, 'SendMessage', { + message: buy(resource, { _payment: proof }), + configuration: IMMEDIATELY, + }); +} + +async function stateOf(node: Node, id: string): Promise { + return (await call(node, 'GetTask', { id })).result?.status?.state; +} + +function code(task: A2aTask | undefined): unknown { + return (task?.artifacts[0]?.parts[0]?.data as Record | undefined)?.['code']; +} + +describe('tasks finished in the background with returnImmediately', () => { + it('answers a working task before the backend returns, then records the result', async () => { + const node = await boot(); + const release = holdBackend(); + + const working = (await buyNow(node, 'proof-1')).result?.task as A2aTask; + + expect(working).toEqual({ + id: working.id, + contextId: working.contextId, + status: { state: 'TASK_STATE_WORKING', timestamp: time.clock.nowIso() }, + artifacts: [], + }); + await vi.waitFor(() => expect(backendCalls).toBe(1)); + expect(await stateOf(node, working.id)).toBe('TASK_STATE_WORKING'); + release(); + await vi.waitFor(async () => + expect(await stateOf(node, working.id)).toBe('TASK_STATE_COMPLETED'), + ); + const done = (await call(node, 'GetTask', { id: working.id })).result as A2aTask; + expect(done.contextId).toBe(working.contextId); + expect(done.artifacts[0]?.parts[0]?.data).toEqual({ report: 'paid' }); + expect(calls.settle).toBe(1); + }); + + it('records the failed task a blocking call would answer when the purchase fails', async () => { + const node = await boot(); + const blocking = ( + await call(node, 'SendMessage', { message: buy('mandated', { _payment: 'proof-a' }) }) + ).result?.task; + + const working = (await buyNow(node, 'proof-b', 'mandated')).result?.task as A2aTask; + + expect(working.status.state).toBe('TASK_STATE_WORKING'); + await vi.waitFor(async () => expect(await stateOf(node, working.id)).toBe('TASK_STATE_FAILED')); + const failed = (await call(node, 'GetTask', { id: working.id })).result as A2aTask; + expect(blocking?.status.state).toBe('TASK_STATE_FAILED'); + expect(code(failed)).toBe(code(blocking)); + expect(backendCalls).toBe(0); + }); + + it('reaches input-required in the background, then is paid in the background', async () => { + const node = await boot(); + const working = (await rpc(node, buy('report'), IMMEDIATELY)).result?.task as A2aTask; + expect(working.status.state).toBe('TASK_STATE_WORKING'); + await vi.waitFor(async () => + expect(await stateOf(node, working.id)).toBe('TASK_STATE_INPUT_REQUIRED'), + ); + const release = holdBackend(); + + const paying = (await rpc(node, pay(working), IMMEDIATELY)).result?.task as A2aTask; + + expect(paying).toMatchObject({ id: working.id, status: { state: 'TASK_STATE_WORKING' } }); + await vi.waitFor(() => expect(backendCalls).toBe(1)); + expect(await stateOf(node, working.id)).toBe('TASK_STATE_WORKING'); + release(); + await vi.waitFor(async () => + expect(await stateOf(node, working.id)).toBe('TASK_STATE_COMPLETED'), + ); + const paid = (await call(node, 'GetTask', { id: working.id })).result as A2aTask; + expect(paid.status.message?.metadata).toMatchObject({ + 'x402.payment.status': 'payment-completed', + }); + expect(calls).toMatchObject({ verify: 1, settle: 1 }); + }); + + it('refuses a 21st purchase or payment while 20 run in the background, and runs nothing for it', async () => { + const node = await boot(); + const waiting = await challenged(node, 'report'); + const release = holdBackend(); + const running: string[] = []; + for (let i = 0; i < 20; i += 1) { + const answer = await buyNow(node, `proof-${i}`); + running.push(answer.result?.task?.id as string); + } + await vi.waitFor(() => expect(backendCalls).toBe(20)); + + const purchase = (await buyNow(node, 'proof-20')).result?.task; + const payment = await rpc(node, pay(waiting), IMMEDIATELY); + + expect(purchase?.status.state).toBe('TASK_STATE_FAILED'); + expect(code(purchase)).toBe('GATEWAY_BUSY'); + expect((await call(node, 'GetTask', { id: purchase?.id })).error?.code).toBe(TASK_NOT_FOUND); + // A system error, not a failed task: the task is not terminal + expect(payment).toEqual({ + jsonrpc: '2.0', + id: 'req-1', + error: { + code: -32603, + message: 'Too many tasks are running in the background; retry shortly.', + data: [{ '@type': 'type.googleapis.com/google.rpc.RetryInfo', retryDelay: '1s' }], + }, + }); + // Capacity refusal leaves the pending purchase and its retained response unchanged + expect(await stateOf(node, waiting.id)).toBe('TASK_STATE_INPUT_REQUIRED'); + expect(calls.verify).toBe(20); + expect(backendCalls).toBe(20); + + release(); + for (const id of running) { + await vi.waitFor(async () => expect(await stateOf(node, id)).toBe('TASK_STATE_COMPLETED')); + } + // Completed runs release their slots + const retried = (await rpc(node, pay(waiting), IMMEDIATELY)).result?.task; + expect(retried?.status.state).toBe('TASK_STATE_WORKING'); + await vi.waitFor(async () => + expect(await stateOf(node, waiting.id)).toBe('TASK_STATE_COMPLETED'), + ); + expect(calls.settle).toBe(21); + }); + + it('refuses a purchase whose working task does not fit, runs nothing and keeps no slot', async () => { + const node = await boot(undefined, { maxRetained: 1 }); + await buyNow(node, 'proof-1'); + await vi.waitFor(() => expect(calls.settle).toBe(1)); + + // Repeated refusals must release their slot reservations + for (let i = 0; i < 21; i += 1) { + const refused = (await buyNow(node, `proof-${i + 2}`)).result?.task; + expect(refused?.status.state).toBe('TASK_STATE_FAILED'); + expect(refused?.artifacts[0]?.parts[0]?.data).toMatchObject({ + code: 'GATEWAY_BUSY', + message: 'Too many answered tasks are retained; retry shortly.', + }); + expect((await call(node, 'GetTask', { id: refused?.id })).error?.code).toBe(TASK_NOT_FOUND); + } + expect(calls.verify).toBe(1); + }); + + it('reads as failed when a background run cannot record its result', async () => { + const node = await boot((store) => + Object.assign(Object.create(store) as ReceiptStore, { + async putTaskRecord(...args: Parameters>) { + if (args[0].state === 'TASK_STATE_COMPLETED') throw new Error('disk full'); + return store.putTaskRecord?.(...args) ?? false; + }, + }), + ); + + const working = (await buyNow(node, 'proof-1')).result?.task as A2aTask; + + await vi.waitFor(async () => expect(await stateOf(node, working.id)).toBe('TASK_STATE_FAILED')); + const read = (await call(node, 'GetTask', { id: working.id })).result as A2aTask; + expect(code(read)).toBe('INTERNAL_ERROR'); + expect(calls.settle).toBe(1); + }); + + it('answers a failed task and runs nothing when the working task cannot be written', async () => { + let failPuts = false; + const node = await boot((store) => + Object.assign(Object.create(store) as ReceiptStore, { + async putTaskRecord(...args: Parameters>) { + if (failPuts) throw new Error('disk full at /var/lib/receipts.db'); + return store.putTaskRecord?.(...args) ?? false; + }, + }), + ); + const waiting = await challenged(node, 'report'); + failPuts = true; + + const purchase = (await buyNow(node, 'proof-1')).result?.task; + const payment = (await rpc(node, pay(waiting), IMMEDIATELY)).result?.task; + + for (const task of [purchase, payment]) { + expect(task?.status.state).toBe('TASK_STATE_FAILED'); + expect(code(task)).toBe('INTERNAL_ERROR'); + expect(JSON.stringify(task)).not.toContain('disk full'); + } + expect(payment?.id).toBe(waiting.id); + // The failed write follows the take, so the purchase is no longer pending + expect(await node.store.getPendingTask?.(waiting.id)).toBeUndefined(); + expect(calls.verify).toBe(0); + expect(backendCalls).toBe(0); + }); + + it('waits on stop for a background run, which records its result', async () => { + const node = await boot(); + const release = holdBackend(); + const working = (await buyNow(node, 'proof-1')).result?.task as A2aTask; + await vi.waitFor(() => expect(backendCalls).toBe(1)); + open = open.filter((candidate) => candidate !== node); + + let closed = false; + const closing = node.gateway.close().then(() => { + closed = true; + }); + for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setImmediate(resolve)); + expect(closed).toBe(false); + release(); + await closing; + + const record = await node.store.getTaskRecord?.(working.id); + await node.store.close(); + expect(record?.state).toBe('TASK_STATE_COMPLETED'); + expect(calls.settle).toBe(1); + }); + + it('reads a run another gateway stopped in as failed, and the same proof does not settle again', async () => { + const first = await boot(); + const release = holdBackend(); + const working = (await buyNow(first, 'proof-1')).result?.task as A2aTask; + await vi.waitFor(() => expect(backendCalls).toBe(1)); + + // A second adapter has no local running entry, simulating a restart + const second = await boot(); + const read = (await call(second, 'GetTask', { id: working.id })).result as A2aTask; + const replay = ( + await call(second, 'SendMessage', { message: buy('report', { _payment: 'proof-1' }) }) + ).result?.task; + + expect(read.status.state).toBe('TASK_STATE_FAILED'); + expect(code(read)).toBe('INTERNAL_ERROR'); + expect(read.status.message?.parts[0]?.text).toContain( + 'check with the merchant before paying again', + ); + expect(code(replay)).toBe('PAYMENT_REPLAYED'); + expect(backendCalls).toBe(1); + release(); + await vi.waitFor(async () => + expect(await stateOf(first, working.id)).toBe('TASK_STATE_COMPLETED'), + ); + expect(calls.settle).toBe(1); + }); +}); + describe('a store without the pending-task methods', () => { const noTasks = (store: ReceiptStore): ReceiptStore => Object.assign(Object.create(store) as ReceiptStore, { From 851725b5b996acc01cdd9c64bf430b2aa2e6e606 Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 12:44:39 +0100 Subject: [PATCH 08/17] feat(a2a): accept X-A2A-Extensions and warn on a public http base URL --- docs/protocols/a2a.md | 40 ++++++++----- docs/security.md | 2 + src/cli/commands/doctor/protocols.ts | 29 +++++++++ src/gateway/access-control.ts | 8 ++- src/protocols/a2a/adapter.ts | 17 +++--- src/protocols/a2a/constants.ts | 6 ++ src/support/a2a.json | 4 +- tests/integration/a2a-x402-extension.test.ts | 63 +++++++++++++++++--- tests/unit/cli/doctor.test.ts | 52 ++++++++++++++++ tests/unit/gateway/access-control.test.ts | 6 +- 10 files changed, 190 insertions(+), 37 deletions(-) diff --git a/docs/protocols/a2a.md b/docs/protocols/a2a.md index 783d5b8..f083cc5 100644 --- a/docs/protocols/a2a.md +++ b/docs/protocols/a2a.md @@ -22,6 +22,12 @@ least one A2A resource. The card has a content-based `ETag` and `Cache-Control: public, max-age=300`. A matching `If-None-Match` request receives `304` without a body. +The card builds its advertised endpoint from `merchant.publicBaseUrl` and +`mountPath`. A2A 1.0.1 requires encrypted transport in production (section 7.1). +Config still accepts HTTP URLs in 2.x. When A2A is enabled, +`agent-commerce doctor` warns about an HTTP base URL unless its host is +`localhost`, a subdomain of `localhost`, an address in `127.0.0.0/8`, or `::1`. + ## Invocation and payment The adapter requires a non-empty `messageId` and exactly one structured data @@ -92,23 +98,25 @@ merchant input and extension metadata. Sending both names for a field returns ## x402 extension -A client activates the extension with -`A2A-Extensions: https://github.com/google-a2a/a2a-x402/v0.1` and can then -pay without `_payment`. The gateway uses x402 v2 documents from the +A client activates the extension by including +`https://github.com/google-a2a/a2a-x402/v0.1` in either `A2A-Extensions` +(A2A 1.0) or `X-A2A-Extensions` (a2a-x402 v0.1). Both accept comma-separated +URI lists and repeated headers. Activation lets the client pay without +`_payment`. The gateway uses x402 v2 documents from the [x402 A2A transport](https://github.com/x402-foundation/x402/blob/main/specs/transports-v2/a2a.md). -Its examples use lowercase task states and roles, `kind` on parts, and the -`X-A2A-Extensions` header. This gateway uses the A2A 1.0 forms: -`TASK_STATE_INPUT_REQUIRED`, `ROLE_AGENT`, parts without `kind`, and -`A2A-Extensions`. The Agent Card advertises the extension as optional, with -`params: { "x402Version": 2 }`, when x402 is a skill's selected payment rail. - -A response carries the `A2A-Extensions` header when its task status message -lists the extension. This includes input-required tasks, payment-message -responses even when the request omits the header, and `GetTask` reads of those -tasks. Other responses, such as MPP tasks and JSON-RPC errors, omit it. -An extension status message -carries `contextId`, `taskId`, `extensions: []` and the -`x402.payment.*` metadata. +The transport's examples use lowercase task states and roles, with `kind` on +parts. This gateway uses the A2A 1.0 forms: `TASK_STATE_INPUT_REQUIRED`, +`ROLE_AGENT` and parts without `kind`. The Agent Card advertises the extension +as optional, with `params: { "x402Version": 2 }`, when x402 is a skill's selected +payment rail. + +Responses echo the extension URI under both header names when the task's status +message lists the extension. This includes input-required tasks, payment +responses even when the request omits activation headers, and `GetTask` reads +of those tasks. MPP tasks and JSON-RPC errors carry neither header. For origins +in `server.allowedOrigins`, CORS permits both request headers and exposes both +response headers to browser code. Extension status messages carry `contextId`, +`taskId`, `extensions: []` and `x402.payment.*` metadata. 1. A blocking x402 paid call without a proof returns `TASK_STATE_INPUT_REQUIRED`. The status message carries `x402.payment.status: payment-required` and the v2 diff --git a/docs/security.md b/docs/security.md index 5514490..e53158f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -503,6 +503,8 @@ real funds. | **an A2A task read after its retention ends** | `GetTask` returns `-32001` and `ListTasks` omits the record; writable SQLite stores delete expired records during initialization and before storing a record | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/task-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | | **an A2A payment or background task interrupted before its result is recorded** | a stored working task absent from the local running set is reported as failed with `INTERNAL_ERROR`; the message tells the buyer to check with the merchant before paying again. A retry that reaches an existing reserved payment attempt gets `PAYMENT_REPLAYED` before another settlement. This assumes one gateway per receipt store | `tests/conformance/a2a/tasks.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts` | | **A2A `returnImmediately` calls outliving the gateway mount's request limit** | each adapter has 20 background slots. If none is free, a new purchase gets a failed `GATEWAY_BUSY` task and a payment submission gets `-32603` with a retry delay, both before payment verification, settlement or backend execution; the refused submission leaves its pending purchase payable. Graceful shutdown waits for started background work before closing the store | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/background.test.ts` | +| **the x402 A2A extension requested under only one header name** | `A2A-Extensions` or `X-A2A-Extensions` must list the exact URI to activate the extension; other URIs do not activate it. Responses whose task status message names the extension echo the URI under both headers; MPP tasks and JSON-RPC errors carry neither | `tests/integration/a2a-x402-extension.test.ts`, `tests/unit/protocols-a2a/x402-extension.test.ts` | +| **an Agent Card publishing an unencrypted public endpoint** | with A2A enabled, `doctor` warns about an HTTP `merchant.publicBaseUrl` unless the host is loopback; 2.x config still accepts the URL | `tests/unit/cli/doctor.test.ts` | | **an A2A 0.x follow-up, with a non-user role, on a pending task** | `-32602`; the task stays pending | same | | **an A2A message carrying a large array of invalid parts or task references** | refused by its length (`PROTOCOL_UNSUPPORTED`) before any element is validated, so no validation issue is built per element | `tests/unit/protocols-a2a/message-mapping.test.ts` | | **an A2A field sent under its proto and JSON names, such as `context_id` beside `contextId`** | `-32602` identifies both spellings before task-store reads or backend calls | `tests/conformance/a2a/params.test.ts` | diff --git a/src/cli/commands/doctor/protocols.ts b/src/cli/commands/doctor/protocols.ts index 6f533e0..9c2ab1c 100644 --- a/src/cli/commands/doctor/protocols.ts +++ b/src/cli/commands/doctor/protocols.ts @@ -26,6 +26,25 @@ import { type WellKnownResult, } from './types'; +// Return the host of a non-loopback HTTP base URL; config accepts these URLs +// for 2.x compatibility +function unencryptedPublicHost(publicBaseUrl: string): string | undefined { + let url: URL; + try { + url = new URL(publicBaseUrl); + } catch { + return undefined; + } + if (url.protocol !== 'http:') return undefined; + const host = url.hostname.replace(/^\[|\]$/g, ''); + const loopback = + host === 'localhost' || + host.endsWith('.localhost') || + host === '::1' || + /^127\.\d+\.\d+\.\d+$/.test(host); + return loopback ? undefined : host; +} + /** * The resource mapped to each checkout operation, re-checked against the rules * config enforces: present, acp-exposed and free to invoke. Resource ids are @@ -116,6 +135,16 @@ export function protocolChecks( status: 'INFO', detail: exclusionNames(a2aRecord).join(', '), }); + // Check the base used for the Agent Card endpoint; A2A 1.0.1 section 7.1 + // requires encrypted transport in production + const host = unencryptedPublicHost(config.merchant.publicBaseUrl); + if (host !== undefined) { + checks.push({ + name: 'A2A transport', + status: 'WARN', + detail: `merchant.publicBaseUrl uses http:// on ${host}, which is not a loopback host: the Agent Card publishes an unencrypted endpoint, and A2A requires encryption in production (spec section 7.1). Serve the gateway at an https:// URL.`, + }); + } } // 5c. ACP specifics, from config and the pins: the well-known document omits diff --git a/src/gateway/access-control.ts b/src/gateway/access-control.ts index 61d8334..47bacf6 100644 --- a/src/gateway/access-control.ts +++ b/src/gateway/access-control.ts @@ -34,6 +34,7 @@ const CORS_HEADERS = [ 'mcp-name', 'a2a-version', 'a2a-extensions', + 'x-a2a-extensions', 'api-version', 'idempotency-key', 'request-id', @@ -41,9 +42,8 @@ const CORS_HEADERS = [ 'timestamp', 'access-control-expose-headers', ].join(','); -// Cross-origin JS sees only CORS-safelisted response headers unless they are -// named here, so a browser client could read neither the challenge, the -// settlement result, nor ACP's echoed correlation and replay headers +// Let cross-origin browser code read payment challenges and settlement results, +// A2A extension echoes, and ACP correlation and replay headers const CORS_EXPOSED_HEADERS = [ 'payment-required', 'payment-response', @@ -53,6 +53,8 @@ const CORS_EXPOSED_HEADERS = [ 'request-id', 'idempotent-replayed', 'retry-after', + 'a2a-extensions', + 'x-a2a-extensions', ].join(','); export interface AccessControlOptions { diff --git a/src/protocols/a2a/adapter.ts b/src/protocols/a2a/adapter.ts index 08b7d60..d1540ab 100644 --- a/src/protocols/a2a/adapter.ts +++ b/src/protocols/a2a/adapter.ts @@ -52,6 +52,7 @@ import { A2A_TASK_RETENTION_HOURS, A2A_UNSUPPORTED_METHODS, A2A_VERSION_HEADER, + A2A_X_EXTENSIONS_HEADER, } from './constants'; import { buildDescriptor } from './descriptor'; import { @@ -107,6 +108,12 @@ const VERSION_PATTERN = /^(\d+\.\d+)(?:\.\d+)?$/; // A2A version parameter; the header is matched case-insensitively const A2A_VERSION_PARAMETER = 'A2A-Version'; +// Echo activation under both accepted names so clients can read either header +const X402_EXTENSION_ECHO = { + [A2A_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI, + [A2A_X_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI, +}; + // Cache the card until the adapter starts again with new configuration const AGENT_CARD_CACHE_CONTROL = 'public, max-age=300'; @@ -383,16 +390,12 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { parsed.request.id, parsed.request.method, parsed.request.params, - requestsX402Extension(req.headers[A2A_EXTENSIONS_HEADER]), + requestsX402Extension(req.headers[A2A_EXTENSIONS_HEADER]) || + requestsX402Extension(req.headers[A2A_X_EXTENSIONS_HEADER]), ); // Echo the extension when it shaped the task, even without the // request header on a payment follow-up - this.writeJson( - res, - 200, - response, - usesX402Extension(response) ? { [A2A_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI } : {}, - ); + this.writeJson(res, 200, response, usesX402Extension(response) ? X402_EXTENSION_ECHO : {}); } catch (err) { // Nothing from `err` reaches the client this.context?.logger.error({ err: toLogInfo(err) }, 'a2a adapter: request handling failed'); diff --git a/src/protocols/a2a/constants.ts b/src/protocols/a2a/constants.ts index 54cb914..5af5666 100644 --- a/src/protocols/a2a/constants.ts +++ b/src/protocols/a2a/constants.ts @@ -83,6 +83,12 @@ export const A2A_TASK_STATE_INPUT_REQUIRED = 'TASK_STATE_INPUT_REQUIRED'; /** Extension activation header, a comma-separated list of extension URIs */ export const A2A_EXTENSIONS_HEADER = 'a2a-extensions'; +/** + * Activation header named by a2a-x402 v0.1 and the x402 A2A transport. + * The adapter accepts either header name and echoes activation under both. + */ +export const A2A_X_EXTENSIONS_HEADER = 'x-a2a-extensions'; + /** Hour bounds and default for task retention in `protocols.a2a.tasks.retentionHours` */ export const A2A_TASK_RETENTION_HOURS = { min: 1, max: 8760, default: 24 } as const; diff --git a/src/support/a2a.json b/src/support/a2a.json index 9463819..4ca9939 100644 --- a/src/support/a2a.json +++ b/src/support/a2a.json @@ -86,8 +86,8 @@ "state": "closed" }, { - "requirement": "§7.1: encrypted communication in production; merchant.publicBaseUrl accepts http", - "state": "open" + "requirement": "§7.1: encrypted communication in production; config accepts an http merchant.publicBaseUrl, and doctor warns when its host is not loopback", + "state": "closed" } ], "docs": ["docs/protocols/a2a.md"] diff --git a/tests/integration/a2a-x402-extension.test.ts b/tests/integration/a2a-x402-extension.test.ts index 6eccd0a..7e6bfe7 100644 --- a/tests/integration/a2a-x402-extension.test.ts +++ b/tests/integration/a2a-x402-extension.test.ts @@ -147,18 +147,23 @@ interface RpcResult { }; } +// Use A2A-Extensions for true, omit activation for false, or send explicit headers +type Activation = boolean | Readonly>; + async function call( method: string, params: Record, - extension = true, + extension: Activation = true, ): Promise { + const activation = + extension === true ? { 'a2a-extensions': A2A_X402_EXTENSION_URI } : extension || {}; const res = await gateway.server.inject({ method: 'POST', url: '/a2a', headers: { 'content-type': 'application/json', 'a2a-version': '1.0', - ...(extension ? { 'a2a-extensions': A2A_X402_EXTENSION_URI } : {}), + ...activation, }, payload: JSON.stringify({ jsonrpc: '2.0', id: 'req-1', method, params }), }); @@ -171,10 +176,17 @@ async function call( return { headers: res.headers, body }; } -function rpc(message: Record, extension = true): Promise { +function rpc(message: Record, extension: Activation = true): Promise { return call('SendMessage', { message }, extension); } +// Read the response values for both extension header names +function echoed(headers: Record): unknown[] { + return [headers['a2a-extensions'], headers['x-a2a-extensions']]; +} + +const ECHO = [A2A_X402_EXTENSION_URI, A2A_X402_EXTENSION_URI]; + // The requests the adapter hands the pipeline function spyOnPipeline(): CanonicalRequest[] { const captured: CanonicalRequest[] = []; @@ -243,7 +255,7 @@ describe('x402 A2A extension', () => { it('asks for payment with an input-required task carrying the x402 v2 document', async () => { const { headers, body } = await rpc(buy('x402_report')); - expect(headers['a2a-extensions']).toBe(A2A_X402_EXTENSION_URI); + expect(echoed(headers)).toEqual(ECHO); const task = body.result?.task; expect(task?.status.state).toBe('TASK_STATE_INPUT_REQUIRED'); expect(task?.status.message).toMatchObject({ @@ -479,7 +491,44 @@ describe('x402 A2A extension', () => { expect(task?.status.message?.parts[0]?.text).toContain('Payment of 0.01 USDC is required'); expect(task?.status.message).not.toHaveProperty('metadata'); expect(task?.status.message).not.toHaveProperty('extensions'); - expect(headers['a2a-extensions']).toBeUndefined(); + expect(echoed(headers)).toEqual([undefined, undefined]); + }); + + it.each([ + ['A2A-Extensions', { 'A2A-Extensions': A2A_X402_EXTENSION_URI }], + ['X-A2A-Extensions', { 'X-A2A-Extensions': A2A_X402_EXTENSION_URI }], + [ + 'a comma-separated list', + { 'x-a2a-extensions': `https://example.com/other/v1, ${A2A_X402_EXTENSION_URI}` }, + ], + [ + 'a repeated header', + { 'x-a2a-extensions': ['https://example.com/other/v1', A2A_X402_EXTENSION_URI] }, + ], + ])('activates the extension with %s and echoes it under both names', async (_label, headers) => { + const answer = await rpc(buy('x402_report'), headers); + + expect(answer.body.result?.task.status.state).toBe('TASK_STATE_INPUT_REQUIRED'); + expect(echoed(answer.headers)).toEqual(ECHO); + }); + + it('does not activate the extension for another URI under either name', async () => { + const answer = await rpc(buy('x402_report'), { + 'a2a-extensions': 'https://example.com/other/v1', + 'x-a2a-extensions': `${A2A_X402_EXTENSION_URI}/extra`, + }); + + expect(answer.body.result?.task.status.state).toBe('TASK_STATE_FAILED'); + expect(echoed(answer.headers)).toEqual([undefined, undefined]); + }); + + it('echoes neither header on a JSON-RPC error', async () => { + const task = await challenged(); + + const answer = await rpc(pay(task, { 'x402.payment.status': 'payment-submitted' })); + + expect(answer.body.error?.code).toBe(-32602); + expect(echoed(answer.headers)).toEqual([undefined, undefined]); }); it('echoes the extension header on a follow-up sent without it', async () => { @@ -494,7 +543,7 @@ describe('x402 A2A extension', () => { ); expect(body.result?.task.status.state).toBe('TASK_STATE_COMPLETED'); - expect(headers['a2a-extensions']).toBe(A2A_X402_EXTENSION_URI); + expect(echoed(headers)).toEqual(ECHO); }); it('names the version when the payload is x402 v1', async () => { @@ -548,7 +597,7 @@ describe('x402 A2A extension', () => { const lookup = await call('GetTask', { id: task.id }, false); expect(lookup.body.result).toEqual(task); // The task's metadata keys belong to the extension, which the response names - expect(lookup.headers['a2a-extensions']).toBe(A2A_X402_EXTENSION_URI); + expect(echoed(lookup.headers)).toEqual(ECHO); const { body } = await rpc( pay(task, { diff --git a/tests/unit/cli/doctor.test.ts b/tests/unit/cli/doctor.test.ts index b8e9f1f..8101133 100644 --- a/tests/unit/cli/doctor.test.ts +++ b/tests/unit/cli/doctor.test.ts @@ -1664,6 +1664,58 @@ describe('runDoctor: A2A', () => { }); }); +describe('runDoctor: A2A transport', () => { + async function transport(publicBaseUrl: string, a2aEnabled = true) { + const base = makeGatewayConfig(); + const report = await runDoctor( + { gatewayUrl: GATEWAY }, + { + fetchImpl: healthyFetch(), + loadConfig: async () => ({ + ...base, + merchant: { ...base.merchant, publicBaseUrl }, + protocols: { ...base.protocols, a2a: { enabled: a2aEnabled, mountPath: '/a2a' } }, + }), + createStore: () => makeFakeReceiptStore(), + }, + ); + return { report, check: report.checks.find((c) => c.name === 'A2A transport') }; + } + + it.each([ + ['a public hostname', 'http://api.example.com', 'api.example.com'], + ['a private address', 'http://10.0.0.5:8080', '10.0.0.5'], + ['a public IPv6 address', 'http://[2001:db8::1]:8080', '2001:db8::1'], + ])('warns when the base URL is http:// on %s', async (_label, url, host) => { + const { report, check } = await transport(url); + + expect(check).toEqual({ + name: 'A2A transport', + status: 'WARN', + detail: `merchant.publicBaseUrl uses http:// on ${host}, which is not a loopback host: the Agent Card publishes an unencrypted endpoint, and A2A requires encryption in production (spec section 7.1). Serve the gateway at an https:// URL.`, + }); + // A transport warning alone does not fail the command + expect(report.exitCode).toBe(0); + }); + + it.each([ + 'http://localhost:8080', + 'http://app.localhost:8080', + 'http://127.0.0.1:8080', + 'http://127.8.9.10', + 'http://[::1]:8080', + 'https://api.example.com', + // Config loading already warns about malformed URLs + 'not a url', + ])('does not warn for %s', async (url) => { + expect((await transport(url)).check).toBeUndefined(); + }); + + it('does not warn when A2A is disabled', async () => { + expect((await transport('http://api.example.com', false)).check).toBeUndefined(); + }); +}); + describe('runDoctor: ACP', () => { const OPERATIONS = { createCheckoutSession: 'acp_create', diff --git a/tests/unit/gateway/access-control.test.ts b/tests/unit/gateway/access-control.test.ts index 83f4b68..2d975cd 100644 --- a/tests/unit/gateway/access-control.test.ts +++ b/tests/unit/gateway/access-control.test.ts @@ -165,14 +165,14 @@ describe('buildAccessControlHook (Host and CORS only)', () => { 'mcp-name', 'a2a-version', 'a2a-extensions', + 'x-a2a-extensions', 'api-version', 'idempotency-key', 'request-id', 'access-control-expose-headers', ]), ); - // Browser code can read only the response headers named here: the - // challenge, the settlement result and ACP's echoed headers + // Expose these headers in addition to CORS-safelisted response headers const exposed = String(reply.headers['access-control-expose-headers']).split(','); expect(exposed).toEqual( expect.arrayContaining([ @@ -184,6 +184,8 @@ describe('buildAccessControlHook (Host and CORS only)', () => { 'request-id', 'idempotent-replayed', 'retry-after', + 'a2a-extensions', + 'x-a2a-extensions', ]), ); }); From 11965c694ea0ab8fe93cb7400660d2fc59a5b093 Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 13:18:35 +0100 Subject: [PATCH 09/17] ci: run the A2A TCK at MUST level --- .github/workflows/ci.yml | 62 +++++++ CONTRIBUTING.md | 23 +++ scripts/support-record.ts | 31 +++- scripts/tck-compare.ts | 141 ++++++++++++++++ src/support/a2a.json | 230 +++++++++++++++++++++++++- tests/integration/tck-compare.test.ts | 163 ++++++++++++++++++ tests/tck/config.yaml | 79 +++++++++ 7 files changed, 726 insertions(+), 3 deletions(-) create mode 100644 scripts/tck-compare.ts create mode 100644 tests/integration/tck-compare.test.ts create mode 100644 tests/tck/config.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f539932..9791149 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -125,6 +125,68 @@ jobs: # with deployed or preloaded tokens and no public RPC or facilitator. - run: npm run test:e2e + tck: + name: A2A TCK + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: ${{ env.NODE_VERSION }} + cache: npm + - run: npm ci + # Use the same record for the TCK revision and expected outcomes + - name: Read the TCK pin + id: pin + run: | + node -p "'repo=' + require('./src/support/a2a.json').conformance.upstream.repo" >> "$GITHUB_OUTPUT" + node -p "'commit=' + require('./src/support/a2a.json').conformance.upstream.commit" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + repository: ${{ steps.pin.outputs.repo }} + ref: ${{ steps.pin.outputs.commit }} + path: tck + persist-credentials: false + # Use the TCK lockfile to key the uv cache + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + with: + version: '0.13.9' + python-version: '3.15.2' + enable-cache: true + cache-dependency-glob: tck/uv.lock + - run: uv sync --frozen + working-directory: tck + # The gateway's backend, RPC and facilitator URLs use loopback + # addresses in tests/tck/config.yaml + - name: Start the demo merchant and the gateway + run: | + npx tsx demo/merchant/src/main.ts > "$RUNNER_TEMP/merchant.log" 2>&1 & + AGENT_COMMERCE_CONFIG=tests/tck/config.yaml npx tsx src/gateway/main.ts > "$RUNNER_TEMP/gateway.log" 2>&1 & + for url in http://127.0.0.1:3000/api/report http://127.0.0.1:8099/health; do + for _ in $(seq 60); do + node -e "fetch('$url').then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))" && break + sleep 1 + done + node -e "fetch('$url').then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))" + done + # Run the comparison even if expected failures make the TCK exit + # non-zero. A missing report or one with no test cases fails the job. + - name: Run the TCK at MUST level + working-directory: tck + run: uv run --frozen ./run_tck.py --sut-host http://127.0.0.1:8099 --transport jsonrpc --level must || true + - name: Compare the run with the record + run: npx tsx scripts/tck-compare.ts tck/reports/junitreport.xml + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + if: always() + with: + name: tck-reports + path: | + tck/reports/ + ${{ runner.temp }}/gateway.log + retention-days: 7 + package: name: npm package runs-on: ubuntu-latest diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 317ea2d..9c438f0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,6 +53,29 @@ A change is not mergeable if the contract surface changed unannounced, TypeScript fails, lint fails, required tests fail, or the deterministic E2E fails. +### A2A TCK + +The `tck` CI job runs the [A2A TCK](https://github.com/a2aproject/a2a-tck) at +MUST level against the gateway configured by `tests/tck/config.yaml`. It +compares failures and skips with `conformance.upstream` in +`src/support/a2a.json` and fails on a mismatch. The record lists individual +outcomes and shared skip messages, with a reason for each. Update it in the +same commit when these outcomes change. + +To run locally, check out the TCK at the recorded commit and install Python +3.15 and [uv](https://docs.astral.sh/uv/). Run the comparison even if the TCK +command exits non-zero: + +```bash +npm run demo:merchant & +AGENT_COMMERCE_CONFIG=tests/tck/config.yaml npx tsx src/gateway/main.ts & +# in the TCK checkout +uv sync --frozen +uv run --frozen ./run_tck.py --sut-host http://127.0.0.1:8099 --transport jsonrpc --level must +# back in this repository +npx tsx scripts/tck-compare.ts /reports/junitreport.xml +``` + ## Architecture you need to know before writing code Read, in order: diff --git a/scripts/support-record.ts b/scripts/support-record.ts index 23fee4d..926c372 100644 --- a/scripts/support-record.ts +++ b/scripts/support-record.ts @@ -22,12 +22,14 @@ export const REPO_ROOT = join(import.meta.dirname, '..'); const text = z.string().min(1); +const COMMIT = z.string().regex(/^[0-9a-f]{40}$/); + const SpecSchema = z.strictObject({ // Revision identifiers for comparison with code revisions: z.array(text).min(1), // Display text for the pinned revision display: text, - source: z.strictObject({ repo: text, commit: z.string().regex(/^[0-9a-f]{40}$/) }), + source: z.strictObject({ repo: text, commit: COMMIT }), // Whether upstream calls the pinned revision stable; null when unspecified stable: z.boolean().nullable(), // Upstream's own words on the revision's status @@ -99,6 +101,32 @@ const SupportRecordSchema = z upstream: text.optional(), }), ), + // CI suite revision, expected failures and skips, and shared skip messages + upstream: z + .strictObject({ + repo: text, + commit: COMMIT, + command: text, + workflow: text, + job: text, + // Identify tests by the JUnit report's `classname::name`. Match + // `message` as a substring of the failure or skip message. + results: z.array( + z.strictObject({ + test: text, + id: text.optional(), + outcome: z.enum(['failed', 'skipped']), + message: text, + reason: text, + spec: text.optional(), + upstream: text.optional(), + }), + ), + // Group accepted skips by exact message, such as those for unsupported + // capabilities or transports + skipClasses: z.array(z.strictObject({ reason: text, messages: z.array(text).min(1) })), + }) + .optional(), }) .optional(), // Known MUST-level gaps against the pinned revision @@ -177,6 +205,7 @@ export function citedPaths(record: SupportRecord): string[] { ...(record.combinations ?? []).map((combination) => combination.evidence), ...(record.conformance?.tests ?? []), ...(record.conformance?.skipped ?? []).map((skipped) => skipped.test), + ...(record.conformance?.upstream !== undefined ? [record.conformance.upstream.workflow] : []), ...record.deviations.flatMap((deviation) => deviation.tests), ...record.docs, ]), diff --git a/scripts/tck-compare.ts b/scripts/tck-compare.ts new file mode 100644 index 0000000..b260095 --- /dev/null +++ b/scripts/tck-compare.ts @@ -0,0 +1,141 @@ +// Compare A2A TCK results with the expected failures, skips and shared skip +// messages in src/support/a2a.json +// +// npx tsx scripts/tck-compare.ts +import { existsSync, readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { readSupportRecord, type SupportRecord } from './support-record'; + +export type UpstreamSuite = NonNullable['upstream']>; + +export interface TckCase { + /** The JUnit report's `classname::name` */ + readonly test: string; + readonly outcome: 'passed' | 'failed' | 'skipped'; + /** The failure, error or skip message; empty for a pass */ + readonly message: string; +} + +// Read attributes one quoted value at a time: a value may contain `>` +const ATTRIBUTES = String.raw`((?:\s+[\w:.-]+="[^"]*")*)\s*`; +const TESTCASE = new RegExp( + String.raw`|>([\s\S]*?)<\/testcase>)`, + 'g', +); +const RESULT = new RegExp(String.raw`<(failure|error|skipped)\b${ATTRIBUTES}\/?>`); +const ENTITIES: Readonly> = { + quot: '"', + apos: "'", + lt: '<', + gt: '>', + amp: '&', +}; + +function decode(value: string): string { + return value.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (entity, name: string) => { + if (name.startsWith('#x') || name.startsWith('#X')) { + return String.fromCodePoint(Number.parseInt(name.slice(2), 16)); + } + if (name.startsWith('#')) return String.fromCodePoint(Number(name.slice(1))); + return ENTITIES[name] ?? entity; + }); +} + +function attributes(text: string): Map { + return new Map( + [...text.matchAll(/([\w:.-]+)="([^"]*)"/g)].map(([, name = '', value = '']) => [ + name, + decode(value), + ]), + ); +} + +/** Parse pytest JUnit cases, treating error entries as failures */ +export function parseJunit(xml: string): TckCase[] { + return [...xml.matchAll(TESTCASE)].map(([, attrs = '', body = '']) => { + const testcase = attributes(attrs); + const result = RESULT.exec(body); + const test = `${testcase.get('classname') ?? ''}::${testcase.get('name') ?? ''}`; + if (result === null) return { test, outcome: 'passed', message: '' }; + const message = attributes(result[2] ?? '').get('message') ?? ''; + return { test, outcome: result[1] === 'skipped' ? 'skipped' : 'failed', message }; + }); +} + +/** Check recorded outcomes and shared skip messages; return any mismatches */ +export function compareTck(cases: readonly TckCase[], suite: UpstreamSuite): string[] { + if (cases.length === 0) return ['the report holds no test cases']; + const tests = suite.results.map((result) => result.test); + const messages = suite.skipClasses.flatMap((skipClass) => skipClass.messages); + const twice = (values: readonly string[]) => values.filter((v, i) => values.indexOf(v) !== i); + const problems = [ + ...twice(tests).map((test) => `${test}: listed more than once in the record`), + ...twice(messages).map((message) => `skip message "${message}": listed more than once`), + ]; + const listed = new Map(suite.results.map((result) => [result.test, result])); + const skipMessages = new Set(messages); + const ran = new Set(); + const seenMessages = new Set(); + for (const run of cases) { + ran.add(run.test); + const entry = listed.get(run.test); + if (entry === undefined) { + if (run.outcome === 'skipped' && skipMessages.has(run.message)) { + seenMessages.add(run.message); + } else if (run.outcome !== 'passed') { + problems.push( + `${run.test}: ${run.outcome}, and the record does not list it: ${run.message}`, + ); + } + } else if (run.outcome === 'passed') { + problems.push(`${run.test}: passed, but the record lists it as ${entry.outcome}`); + } else if (run.outcome !== entry.outcome) { + problems.push( + `${run.test}: ${run.outcome}, but the record lists it as ${entry.outcome}: ${run.message}`, + ); + } else if (!run.message.includes(entry.message)) { + problems.push( + `${run.test}: ${run.outcome} with a message that does not contain "${entry.message}": ${run.message}`, + ); + } + } + for (const entry of suite.results) { + if (!ran.has(entry.test)) problems.push(`${entry.test}: in the record, but not in the run`); + } + for (const message of skipMessages) { + if (!seenMessages.has(message)) { + problems.push(`skip message "${message}": in the record, but no test skipped with it`); + } + } + return problems; +} + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const path = process.argv[2]; + if (path === undefined) { + console.error('usage: tsx scripts/tck-compare.ts '); + process.exit(2); + } + if (!existsSync(path)) { + console.error(`no report at ${path}: the TCK did not finish`); + process.exit(1); + } + const suite = readSupportRecord('a2a').conformance?.upstream; + if (suite === undefined) { + console.error('src/support/a2a.json records no upstream suite'); + process.exit(2); + } + const cases = parseJunit(readFileSync(path, 'utf8')); + const count = (outcome: TckCase['outcome']) => cases.filter((c) => c.outcome === outcome).length; + console.log( + `TCK: ${count('passed')} passed, ${count('failed')} failed, ${count('skipped')} skipped`, + ); + const problems = compareTck(cases, suite); + for (const problem of problems) console.error(problem); + if (problems.length > 0) { + console.error(`${problems.length} difference(s) from src/support/a2a.json`); + process.exit(1); + } + console.log('The run matches src/support/a2a.json'); +} diff --git a/src/support/a2a.json b/src/support/a2a.json index 4ca9939..8f6f1ea 100644 --- a/src/support/a2a.json +++ b/src/support/a2a.json @@ -60,7 +60,7 @@ ], "deviations": [], "conformance": { - "suite": "Our tests against the A2A 1.0.1 specification; the A2A TCK has not been run.", + "suite": "Our tests against the A2A 1.0.1 specification, and the A2A TCK at MUST level in CI.", "tests": [ "tests/conformance/a2a/agent-card.test.ts", "tests/conformance/a2a/errors.test.ts", @@ -70,7 +70,233 @@ "tests/conformance/a2a/protocol-version.test.ts", "tests/conformance/a2a/tasks.test.ts" ], - "skipped": [] + "skipped": [], + "upstream": { + "repo": "a2aproject/a2a-tck", + "commit": "5e6f37c2d38eb3d7684686243c34d365c83df49b", + "command": "run_tck.py --sut-host http://127.0.0.1:8099 --transport jsonrpc --level must", + "workflow": ".github/workflows/ci.yml", + "job": "tck", + "results": [ + { + "test": "tests.compatibility.core_operations.test_requirements::test_must_requirement[CORE-SEND-001-jsonrpc]", + "id": "CORE-SEND-001", + "outcome": "failed", + "message": "Text parts are not supported", + "reason": "The test sends a text part, and the Agent Card declares only application/json input", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_requirements::test_must_requirement[CORE-EXECUTION-MODE-001-jsonrpc]", + "id": "CORE-EXECUTION-MODE-001", + "outcome": "failed", + "message": "Text parts are not supported", + "reason": "The test sends a text part, and the Agent Card declares only application/json input", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_requirements::test_must_requirement[CORE-EXECUTION-MODE-002-jsonrpc]", + "id": "CORE-EXECUTION-MODE-002", + "outcome": "failed", + "message": "Text parts are not supported", + "reason": "The test sends a text part, and the Agent Card declares only application/json input", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_requirements::test_must_requirement[CORE-MULTI-001a-jsonrpc]", + "id": "CORE-MULTI-001a", + "outcome": "failed", + "message": "Text parts are not supported", + "reason": "The test sends a text part, and the Agent Card declares only application/json input", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_requirements::test_must_requirement[CORE-MULTI-003-jsonrpc]", + "id": "CORE-MULTI-003", + "outcome": "failed", + "message": "Text parts are not supported", + "reason": "The test sends a text part, and the Agent Card declares only application/json input", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_requirements::test_must_requirement[CORE-MULTI-002a-jsonrpc]", + "id": "CORE-MULTI-002a", + "outcome": "failed", + "message": "Multi-turn conversational continuation is not supported", + "reason": "The adapter refuses the client contextId with -32004, as the requirement asks, but the requirement sets no expected error and the runner fails on any error. Its sample input also sends a text part.", + "spec": "A2A 1.0.1 §3.4.1", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_transport_behavior.TestJsonRpcFormat::test_response_validates_jsonrpc_envelope", + "id": "JSONRPC-FMT-001", + "outcome": "failed", + "message": "Text parts are not supported", + "reason": "The test sends a text part, and the Agent Card declares only application/json input", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_artifacts.TestTextArtifact::test_task_has_text_artifact[jsonrpc]", + "id": "DM-ART-001", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_artifacts.TestFileArtifact::test_task_has_file_artifact[jsonrpc]", + "id": "DM-ART-001", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_artifacts.TestFileUrlArtifact::test_task_has_file_url_artifact[jsonrpc]", + "id": "DM-ART-001", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_artifacts.TestDataArtifact::test_task_has_data_artifact[jsonrpc]", + "id": "DM-ART-001", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_artifacts.TestMessageResponse::test_returns_message_with_text_part[jsonrpc]", + "id": "DM-MSG-001", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_task_history.TestHistoryLengthLimit::test_get_task_history_does_not_exceed_limit[jsonrpc]", + "id": "CORE-HIST-002", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_task_lifecycle.TestGetTask::test_get_task_returns_current_state[jsonrpc]", + "id": "CORE-GET-001", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_task_lifecycle.TestCancelTask::test_cancel_task_returns_updated_state[jsonrpc]", + "id": "CORE-CANCEL-001", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_task_lifecycle.TestCancelTask::test_cancel_terminal_task_returns_error[jsonrpc]", + "id": "CORE-CANCEL-002", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_task_lifecycle.TestMultiTurn::test_send_message_to_terminal_task[jsonrpc]", + "id": "CORE-SEND-002", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_task_lifecycle.TestMultiTurn::test_infer_context_from_task[jsonrpc]", + "id": "CORE-MULTI-005", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_task_lifecycle.TestMultiTurn::test_reject_mismatching_context[jsonrpc]", + "id": "CORE-MULTI-006", + "outcome": "skipped", + "message": "send_message failed: Text parts are not supported", + "reason": "The test creates its task with a text part, which the adapter refuses", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_data_model.TestSendMessageResponseSchema::test_response_validates_against_schema", + "outcome": "skipped", + "message": "No successful send_message responses", + "reason": "Every message in the run sends a text part, which leaves no successful response to check", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_data_model.TestCamelCaseFieldNames::test_no_snake_case_keys", + "id": "DM-SERIAL-001", + "outcome": "skipped", + "message": "No successful send_message responses", + "reason": "Every message in the run sends a text part, which leaves no successful response to check", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_data_model.TestEnumSerialization::test_enum_values_are_strings", + "id": "DM-SERIAL-002", + "outcome": "skipped", + "message": "No successful send_message responses", + "reason": "Every message in the run sends a text part, which leaves no successful response to check", + "upstream": "Report drafted, not filed" + }, + { + "test": "tests.compatibility.core_operations.test_data_model.TestTimestampFormat::test_timestamps_are_iso8601_utc", + "id": "DM-SERIAL-003", + "outcome": "skipped", + "message": "No successful send_message responses", + "reason": "Every message in the run sends a text part, which leaves no successful response to check", + "upstream": "Report drafted, not filed" + } + ], + "skipClasses": [ + { + "reason": "The gateway serves only the JSON-RPC binding", + "messages": [ + "Transport 'http_json' not configured", + "Transport 'grpc' not configured", + "Transport 'grpc' not configured (filtered by --transport)", + "Transport 'http_json' not configured (filtered by --transport)", + "HTTP+JSON transport not configured", + "gRPC transport not configured" + ] + }, + { + "reason": "The Agent Card declares streaming false (excluded)", + "messages": [ + "Agent does not support streaming", + "Agent card does not declare capabilities for: ['streaming']", + "Streaming not supported: A2A method \"SendStreamingMessage\" is not supported by this deployment." + ] + }, + { + "reason": "The Agent Card declares push notifications false (excluded)", + "messages": ["Agent does not support push notifications"] + }, + { + "reason": "The Agent Card declares no extended card (excluded)", + "messages": ["Agent does not declare extendedAgentCard capability"] + }, + { + "reason": "The TCK's probe for an agent that requires its test extension; this card requires none", + "messages": ["Agent card does not declare urn:a2a:tck:required-extension as required"] + } + ] + } }, "gaps": [ { diff --git a/tests/integration/tck-compare.test.ts b/tests/integration/tck-compare.test.ts new file mode 100644 index 0000000..8ffc3a9 --- /dev/null +++ b/tests/integration/tck-compare.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it } from 'vitest'; +import { readSupportRecord } from '../../scripts/support-record'; +import { compareTck, parseJunit, type UpstreamSuite } from '../../scripts/tck-compare'; + +const SUITE: UpstreamSuite = { + repo: 'a2aproject/a2a-tck', + commit: '5e6f37c2d38eb3d7684686243c34d365c83df49b', + command: 'run_tck.py --level must', + workflow: '.github/workflows/ci.yml', + job: 'tck', + results: [ + { + test: 'm.TestSend::test_send', + outcome: 'failed', + message: 'Text parts are not supported', + reason: 'text part', + }, + { + test: 'm.TestGet::test_get', + outcome: 'skipped', + message: 'send_message failed', + reason: 'prerequisite', + }, + ], + skipClasses: [{ reason: 'transport', messages: ["Transport 'grpc' not configured"] }], +}; + +const FAILED_SEND = + 'trace'; +const SKIPPED_GET = + 'at line 1'; +const GRPC_SKIP = + 'x'; +const PASSED = ''; + +function report(...cases: string[]): string { + return `${cases.join('')}`; +} + +function compare(...cases: string[]): string[] { + return compareTck(parseJunit(report(...cases)), SUITE); +} + +describe('parseJunit', () => { + it('reads passes, failures, errors and skips with decoded messages', () => { + const xml = report( + PASSED, + 't', + 't', + GRPC_SKIP, + ); + + expect(parseJunit(xml)).toEqual([ + { test: 'm.TestCard::test_card[jsonrpc]', outcome: 'passed', message: '' }, + { test: 'm.A::test_a[x]', outcome: 'failed', message: 'a > b &\nc A' }, + { test: 'm.B::test_b', outcome: 'failed', message: 'setup broke' }, + { + test: 'm.TestCard::test_card[grpc]', + outcome: 'skipped', + message: "Transport 'grpc' not configured", + }, + ]); + }); + + it('keeps a raw > inside an attribute value', () => { + const xml = report( + '', + ); + + expect(parseJunit(xml)).toEqual([{ test: 'm.C::test_c', outcome: 'skipped', message: 'a>b' }]); + }); +}); + +describe('compareTck', () => { + it('finds no difference when every failure and skip is recorded', () => { + expect(compare(FAILED_SEND, SKIPPED_GET, GRPC_SKIP, PASSED)).toEqual([]); + }); + + it('reports a failure the record does not list', () => { + const extra = + 't'; + + expect(compare(FAILED_SEND, SKIPPED_GET, GRPC_SKIP, extra)).toEqual([ + 'm.TestNew::test_new: failed, and the record does not list it: boom', + ]); + }); + + it('reports a skip whose message is in no skip class', () => { + const extra = + 't'; + + expect(compare(FAILED_SEND, SKIPPED_GET, GRPC_SKIP, extra)).toEqual([ + "m.TestNew::test_new: skipped, and the record does not list it: Transport 'grpc' not ready", + ]); + }); + + it('reports a listed test that now passes', () => { + const passing = ''; + + expect(compare(passing, SKIPPED_GET, GRPC_SKIP)).toEqual([ + 'm.TestSend::test_send: passed, but the record lists it as failed', + ]); + }); + + it('reports a listed test that is missing from the run', () => { + expect(compare(FAILED_SEND, GRPC_SKIP)).toEqual([ + 'm.TestGet::test_get: in the record, but not in the run', + ]); + }); + + it('reports a listed test whose outcome changed between failed and skipped', () => { + const skipped = + 't'; + + expect(compare(skipped, SKIPPED_GET, GRPC_SKIP)).toEqual([ + 'm.TestSend::test_send: skipped, but the record lists it as failed: Text parts are not supported', + ]); + }); + + it('reports a listed failure that now fails for another reason', () => { + const other = + 't'; + + expect(compare(other, SKIPPED_GET, GRPC_SKIP)).toEqual([ + 'm.TestSend::test_send: failed with a message that does not contain "Text parts are not supported": Operation failed: Internal error', + ]); + }); + + it('reports a skip message no test skipped with', () => { + expect(compare(FAILED_SEND, SKIPPED_GET, PASSED)).toEqual([ + `skip message "Transport 'grpc' not configured": in the record, but no test skipped with it`, + ]); + }); + + it('reports a test or skip message the record lists twice', () => { + const doubled: UpstreamSuite = { + ...SUITE, + results: [...SUITE.results, ...SUITE.results.slice(0, 1)], + skipClasses: [...SUITE.skipClasses, ...SUITE.skipClasses], + }; + + expect(compareTck(parseJunit(report(FAILED_SEND, SKIPPED_GET, GRPC_SKIP)), doubled)).toEqual([ + 'm.TestSend::test_send: listed more than once in the record', + `skip message "Transport 'grpc' not configured": listed more than once`, + ]); + }); + + it('refuses a report with no test cases', () => { + expect(compare()).toEqual(['the report holds no test cases']); + }); +}); + +describe('the A2A record', () => { + it('records the TCK run the tck job checks', () => { + const suite = readSupportRecord('a2a').conformance?.upstream; + + expect(suite).toMatchObject({ + repo: 'a2aproject/a2a-tck', + workflow: '.github/workflows/ci.yml', + job: 'tck', + }); + }); +}); diff --git a/tests/tck/config.yaml b/tests/tck/config.yaml new file mode 100644 index 0000000..1c7ccba --- /dev/null +++ b/tests/tck/config.yaml @@ -0,0 +1,79 @@ +version: 1 + +# Gateway fixture for the `tck` CI job. It exposes one free resource and +# one x402 resource, which adds the payment extension to the Agent Card. +# Both backends use the demo merchant on loopback port 3000. RPC and +# facilitator URLs point to loopback port 9. +merchant: + id: tck-store + name: TCK Store + publicBaseUrl: http://127.0.0.1:8099 + +server: + port: 8099 + host: 127.0.0.1 + +storage: + receipts: + driver: sqlite + path: ':memory:' + +protocols: + http: + enabled: false + mcp: + enabled: false + mountPath: /mcp + a2a: + enabled: true + mountPath: /a2a + +resources: + weather_basic: + name: Basic Weather + description: Current basic weather for a city. Free. + input: + type: object + properties: + city: + type: string + required: [city] + additionalProperties: false + backend: + type: http + method: GET + url: http://127.0.0.1:3000/api/weather/{city} + timeoutMs: 5000 + pricing: + type: free + expose: [a2a] + + market_report: + name: Premium Market Report + description: Latest premium market analysis. Paid resource. + input: + type: object + properties: {} + additionalProperties: false + backend: + type: http + method: GET + url: http://127.0.0.1:3000/api/report + timeoutMs: 5000 + pricing: + type: fixed + amount: '0.01' + currency: USDC + expose: [a2a] + payments: [x402] + +payments: + x402: + enabled: true + network: eip155:84532 + rpcUrl: http://127.0.0.1:9/rpc + payTo: '0x1111111111111111111111111111111111111111' + maxTimeoutSeconds: 120 + facilitator: + mode: remote + url: http://127.0.0.1:9/facilitator From 9771092419c061dd2bbbea511ca425fe59b11c39 Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 13:46:44 +0100 Subject: [PATCH 10/17] feat(support): gate promotion on the criteria and promote core A2A --- CONTRIBUTING.md | 7 +- README.md | 30 ++++--- config.example.yaml | 2 +- docs/architecture.md | 2 +- docs/configuration.md | 4 +- docs/protocols.md | 26 +++--- docs/protocols/a2a.md | 18 +++- .../skills/agent-commerce/SKILL.md | 6 +- scripts/support-record.ts | 19 ++++ src/index.ts | 2 +- src/protocols/a2a/adapter.ts | 2 +- src/protocols/a2a/index.ts | 6 +- src/support/a2a.json | 39 ++++++--- tests/integration/a2a-over-gateway.test.ts | 2 +- .../goldens/2.7.2/doctor-multi.json | 4 +- .../goldens/2.7.2/doctor-single.json | 4 +- .../goldens/2.7.2/well-known-multi.json | 6 +- .../goldens/2.7.2/well-known-single.json | 6 +- tests/integration/support-record.test.ts | 86 +++++++++++++++++-- tests/unit/cli/doctor.test.ts | 2 +- tests/unit/protocols-a2a/agent-card.test.ts | 8 +- 21 files changed, 216 insertions(+), 65 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9c438f0..5b8dfad 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,9 +5,10 @@ support, payment behavior and area boundaries consistent. ## Ground rules -1. **Scope discipline is a release requirement.** Supported: MCP, HTTP and - x402. Experimental and off by default: MPP, A2A, ACP and AP2; OpenAPI import - is an experimental CLI command. New protocols and rails land after the +1. **Scope discipline is a release requirement.** Supported: MCP, HTTP, x402 + and A2A. A2A is off by default; its x402 extension is experimental. + MPP, ACP and AP2 are experimental and off by default. OpenAPI import is an + experimental CLI command. New protocols and rails land after the adapter model survives real use. Classify every proposal as `BLOCKER` / `QUALITY` / `NICE-TO-HAVE` / `POST-1.0` - the default answer to a new capability is `POST-1.0`. diff --git a/README.md b/README.md index 1ee8bcc..bf2527f 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ MCP x402 + A2A MPP - A2A ACP AP2 @@ -25,7 +25,7 @@ call and pay for it without adding those protocols to your backend. Run the gateway in your infrastructure and describe each endpoint in YAML, or generate draft resource definitions from OpenAPI. Resources can be exposed over -HTTP, MCP or experimental A2A; dedicated resources can implement experimental +HTTP, MCP or A2A; dedicated resources can implement experimental ACP checkout operations. Paid resources use x402 or experimental MPP and can also require an AP2 mandate proving that the buyer approved the purchase. Funds go directly to the merchant wallet, and the gateway needs neither the buyer's @@ -308,16 +308,16 @@ See [docs/configuration.md](docs/configuration.md). -| Protocol | Status | Pinned revision | Implemented subset | -| ------------ | ------------ | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| **HTTP** | Supported | native | resource routes and rail-specific payment headers | -| **MCP** | Supported | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | -| **x402** | Supported | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | -| **MPP** | Experimental | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A | -| **A2A** | Experimental | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage` with `returnImmediately`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension | -| **ACP** | Experimental | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | -| **AP2** | Experimental | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement | -| **ERC-8409** | Experimental | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | +| Protocol | Status | Pinned revision | Implemented subset | +| ------------ | ------------ | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| **HTTP** | Supported | native | resource routes and rail-specific payment headers | +| **MCP** | Supported | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | +| **x402** | Supported | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | +| **MPP** | Experimental | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A | +| **A2A** | Supported | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage` with `returnImmediately`, `GetTask`, `ListTasks`, `CancelTask` and the paid flow; the x402 extension is experimental | +| **ACP** | Experimental | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | +| **AP2** | Experimental | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement | +| **ERC-8409** | Experimental | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | @@ -342,7 +342,8 @@ prints the `unsupported` lists for A2A, ACP and AP2 when they are enabled. ### Versioning Minor releases may break experimental configurations, integrations or types. -This includes MPP, A2A, ACP, AP2, ERC-8409 quotes, the +This includes MPP, ACP, AP2, the +[a2a-x402 extension](docs/protocols/a2a.md#x402-extension), ERC-8409 quotes, the [public resource URL](docs/configuration.md#public-resource-url) and [Bazaar metadata](docs/configuration.md#bazaar-metadata) in payment challenges, and these interfaces: @@ -356,6 +357,7 @@ challenges, and these interfaces: in 2.7.0. - `PaymentContext.protocol` and `AdapterHealthComponent.undetermined` (added in 2.8.0), and the `./testing` entry. +- `TaskRecord` and the task storage methods on `ReceiptStore`, added in 2.9.0. A profile moves from experimental to supported only when it meets the [promotion criteria](docs/protocols.md#promotion-criteria). @@ -719,7 +721,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md). **Now** - MCP, x402 v2, settlement on the local chain, Base Sepolia, Base mainnet, Solana devnet and Solana mainnet, receipts, doctor, deterministic -demo, experimental A2A v1.0.1 and ACP `2026-04-17` checkout adapters, +demo, the A2A v1.0.1 adapter, the experimental ACP `2026-04-17` checkout adapter, experimental AP2 v0.2.0 mandate verification, experimental MPP `charge` payments, experimental OpenAPI import, experimental retries after a lost response, and experimental discovery metadata for x402 Bazaar and MCP Registry diff --git a/config.example.yaml b/config.example.yaml index b68dc80..43bd22e 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -51,7 +51,7 @@ protocols: # name: io.github.acme/weather # version: 1.0.0 # description: Weather forecasts, paid per call - # A2A (Agent2Agent) v1.0.1 - experimental, off by default. + # A2A (Agent2Agent) v1.0.1 is off by default; its x402 extension is experimental # Serves JSON-RPC `SendMessage`, `GetTask`, `ListTasks` and `CancelTask` at # mountPath and the Agent Card at /.well-known/agent-card.json. Enable at # least one resource with `expose: [a2a]`. Clients send `A2A-Version: 1.0`. diff --git a/docs/architecture.md b/docs/architecture.md index b8527e3..80771f2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -178,7 +178,7 @@ public RPC or real funds. | config schema, loader, env substitution | `src/config` | | Fastify server, routes, adapter mounting | `src/gateway` | | MCP adapter | `src/protocols/mcp` | -| A2A adapter (experimental) | `src/protocols/a2a` | +| A2A adapter | `src/protocols/a2a` | | ACP checkout adapter (experimental) | `src/protocols/acp` | | shared bearer check, body reader, URL join | `src/protocols/http.ts` | | x402 provider + local/remote facilitator | `src/payments/x402` | diff --git a/docs/configuration.md b/docs/configuration.md index f5150b4..246b2e2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -253,8 +253,8 @@ Lengths count Unicode code points. ## `protocols.a2a` -Experimental and off by default. The optional `tasks` block limits retention -for `GetTask`, `ListTasks` and `CancelTask`; see [Tasks](protocols/a2a.md#tasks). +Off by default. The optional `tasks` block limits retention for `GetTask`, +`ListTasks` and `CancelTask`; see [Tasks](protocols/a2a.md#tasks). ```yaml protocols: diff --git a/docs/protocols.md b/docs/protocols.md index e6b7201..b9cb763 100644 --- a/docs/protocols.md +++ b/docs/protocols.md @@ -7,16 +7,16 @@ subset. Each protocol's page describes that subset in detail. -| Protocol | Status | Role | Revision | Implemented subset | -| ------------ | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| **HTTP** | Supported | Transport that carries x402 and MPP payments on each resource's invoke route. | native | resource routes and rail-specific payment headers | -| **MCP** | Supported | Transport that carries x402 and MPP payments in tool calls. | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | -| **x402** | Supported | Payment rail, carried by HTTP, MCP and A2A. | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | -| **MPP** | Experimental | Payment rail, carried by HTTP, MCP and A2A. | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A | -| **A2A** | Experimental | Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension. | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage` with `returnImmediately`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension | -| **ACP** | Experimental | Checkout API that forwards checkout operations to the merchant, whose payment handler receives `payment_data`. Gateway checkout routes are free and carry no x402 or MPP payment. | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | -| **AP2** | Experimental | Authorization method, not a payment rail: a paid resource can require a verified mandate in addition to its x402 or MPP payment, never instead of it. | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement | -| **ERC-8409** | Experimental | x402 feature: EIP-712 signed quotes on the EVM offers of a challenge. | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | +| Protocol | Status | Role | Revision | Implemented subset | +| ------------ | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| **HTTP** | Supported | Transport that carries x402 and MPP payments on each resource's invoke route. | native | resource routes and rail-specific payment headers | +| **MCP** | Supported | Transport that carries x402 and MPP payments in tool calls. | MCP `2026-07-28` and `2025-11-25`; `@modelcontextprotocol/server@2.3.0` | tool discovery, invocation, payment-required and error mapping | +| **x402** | Supported | Payment rail, carried by HTTP, MCP and A2A. | x402 v2; `@x402/core@2.30.0`, `@x402/evm@2.30.0`, `@x402/svm@2.30.0`, `@x402/near@2.30.0` | `exact` on EVM through EIP-3009 or Permit2, on Solana, and on NEAR (partial): challenge, verification, settlement and replay binding | +| **MPP** | Experimental | Payment rail, carried by HTTP, MCP and A2A. | drafts at `tempoxyz/mpp-specs@806fdb8`; `mppx@0.13.1` | `charge`/`evm`/EIP-3009 with USDC on Base Sepolia and Base, over HTTP, MCP and A2A | +| **A2A** | Supported | Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension. | v1.0.1; negotiation `1.0`; `JSONRPC` binding | Agent Card, `SendMessage` with `returnImmediately`, `GetTask`, `ListTasks`, `CancelTask` and the paid flow; the x402 extension is experimental | +| **ACP** | Experimental | Checkout API that forwards checkout operations to the merchant, whose payment handler receives `payment_data`. Gateway checkout routes are free and carry no x402 or MPP payment. | stable snapshot `2026-04-17`; REST binding | discovery and the five checkout operations | +| **AP2** | Experimental | Authorization method, not a payment rail: a paid resource can require a verified mandate in addition to its x402 or MPP payment, never instead of it. | v0.2.0, tag 2026-04-28, commit `b4587ac`; Direct mode; `jose@6.2.12`, `@sd-jwt/core@0.20.1`, `canonicalize@5.0.0` | closed Checkout Mandate verification before settlement | +| **ERC-8409** | Experimental | x402 feature: EIP-712 signed quotes on the EVM offers of a challenge. | draft `SergeevDmitry/ERCs@0ee33230` | signed quotes on x402 EVM offers; issuer published in `/.well-known/agent-commerce` | @@ -84,6 +84,12 @@ Each reads fields of the profile's record in `src/support/`: MCP and x402 were supported before 2.8.0 introduced these criteria, and keep that status. Upstream does not label x402 v2 stable, and its record states that. +For other supported profiles, `npm test` fails if `spec.stable` is not `true`, +a gap is open, `conformance` is missing or `docs` is empty. + +A2A is the first profile promoted under these criteria (2.9.0). CI runs the +A2A TCK at MUST level and compares failures and skips with the record. + ## Protocol pages - [HTTP surface](protocols/http.md): routes, and the payment headers each rail diff --git a/docs/protocols/a2a.md b/docs/protocols/a2a.md index f083cc5..c0ef03e 100644 --- a/docs/protocols/a2a.md +++ b/docs/protocols/a2a.md @@ -1,6 +1,7 @@ # A2A -**Experimental.** Enable with `protocols.a2a.enabled: true`. +Enable with `protocols.a2a.enabled: true`. The [x402 extension](#x402-extension) +is experimental and may change in a minor release. | Property | Value | | ------------- | --------------------------------------------------------------------------------------------------------------------------------- | @@ -346,6 +347,17 @@ such as `VERSION_NOT_SUPPORTED` and the domain `a2a-protocol.org`. +## Deviations + +Each entry cites the section of the pinned revision the gateway departs from +and the tests that verify the behavior. + + + +- **A2A 1.0.1 §5.7; `ListTasksResponse.tasks`**: A `ListTasks` page with no matching task has an empty `tasks` array. The proto marks `tasks` REQUIRED, and §5.7 requires a REQUIRED array to hold an element, but an empty result has none to return. Tests: `tests/conformance/a2a/tasks.test.ts`. + + + ## A2A exclusions The A2A descriptor in `GET /.well-known/agent-commerce` lists these names in @@ -367,6 +379,10 @@ The A2A descriptor in `GET /.well-known/agent-commerce` lists these names in - `task resumption other than an x402 extension payment` - `push notifications` - `multi-turn conversational continuation` +- `client-chosen contextId`: A `contextId` without a task gets `UnsupportedOperationError`; each new task opens a context the gateway generates. +- `listing tasks across contexts`: `ListTasks` reads only the given `contextId`; without one, the page is empty. +- `task history`: Tasks omit `history`; `historyLength` is validated but has nothing to cap. +- `non-empty tenant` - `text parts` - `file and URL parts (including inline bytes)` - `multi-part messages` diff --git a/plugins/agent-commerce-gateway/skills/agent-commerce/SKILL.md b/plugins/agent-commerce-gateway/skills/agent-commerce/SKILL.md index 3db80fd..219c193 100644 --- a/plugins/agent-commerce-gateway/skills/agent-commerce/SKILL.md +++ b/plugins/agent-commerce-gateway/skills/agent-commerce/SKILL.md @@ -21,9 +21,9 @@ metadata: The merchant's and buyer's wallet keys stay outside the gateway; some facilitators require separate API credentials. - **Fixed prices, x402 `exact`.** No dynamic pricing, refunds, orders or - custody. MPP, A2A, ACP and AP2 exist but are experimental: use them only when - the user asks, and read the upstream docs first. Say plainly when a request - is out of scope. + custody. MPP, ACP, AP2 and the a2a-x402 extension exist but are experimental. + Use them only when the user asks, and read the upstream docs first. Say + plainly when a request is out of scope. ## Rules diff --git a/scripts/support-record.ts b/scripts/support-record.ts index 926c372..27b6e4a 100644 --- a/scripts/support-record.ts +++ b/scripts/support-record.ts @@ -601,6 +601,24 @@ function handWrittenProblems(tree: SupportTree): string[] { return problems; } +// Profiles supported before 2.8.0 are exempt from promotion checks +const SUPPORTED_BEFORE_CRITERIA: ReadonlySet = new Set(['http', 'mcp', 'x402']); + +// Report unmet promotion checks from docs/protocols.md +function promotionProblems(record: SupportRecord): string[] { + if (record.status !== 'supported' || SUPPORTED_BEFORE_CRITERIA.has(record.name)) return []; + const open = record.gaps.filter((gap) => gap.state === 'open'); + const unmet = [ + ...(record.spec?.stable !== true + ? ['criterion 1: upstream does not declare the pinned revision stable (spec.stable)'] + : []), + ...open.map((gap) => `criterion 2: the gap "${gap.requirement}" is open`), + ...(record.conformance === undefined ? ['criterion 3: no conformance evidence'] : []), + ...(record.docs.length === 0 ? ['criterion 4: no operational docs'] : []), + ]; + return unmet.map((problem) => `src/support/${record.name}.json: supported, but ${problem}`); +} + /** Every disagreement between the records, package.json and the docs, each naming its place */ export function supportProblems(tree: SupportTree): string[] { const problems: string[] = []; @@ -622,6 +640,7 @@ export function supportProblems(tree: SupportTree): string[] { for (const path of citedPaths(record)) { if (!tree.exists(path)) problems.push(`${source}: cites ${path}, which does not exist`); } + problems.push(...promotionProblems(record)); } for (const [path, regions] of renderRegions(tree.records, manifest)) { const content = tree.read(path); diff --git a/src/index.ts b/src/index.ts index 536f5ad..9c0b52f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -24,7 +24,7 @@ export * from './core/public-types'; export type { GatewayInstance, GatewayOptions } from './gateway'; // --- run a gateway --------------------------------------------------------- export { createGateway } from './gateway'; -// --- the A2A adapter (experimental; no peer dependency) -------------------- +// --- the A2A adapter (no peer dependency) --------------------------------- export type { A2aAdapterOptions } from './protocols/a2a'; export { A2A_AGENT_CARD_PATH, diff --git a/src/protocols/a2a/adapter.ts b/src/protocols/a2a/adapter.ts index d1540ab..6d61f2d 100644 --- a/src/protocols/a2a/adapter.ts +++ b/src/protocols/a2a/adapter.ts @@ -1,5 +1,5 @@ /** - * A2A (Agent2Agent) protocol adapter, experimental. + * A2A (Agent2Agent) protocol adapter. * * Serves two paths: the configured mount (`/a2a`), where the JSON-RPC endpoint * lives, and the specification-fixed `/.well-known/agent-card.json`, declared diff --git a/src/protocols/a2a/index.ts b/src/protocols/a2a/index.ts index 2f514e2..50e2e86 100644 --- a/src/protocols/a2a/index.ts +++ b/src/protocols/a2a/index.ts @@ -1,9 +1,9 @@ /** * src/protocols/a2a * - * A2A (Agent2Agent) v1 adapter, experimental: publishes canonical resources as - * A2A skills on the specification-fixed Agent Card path and serves the - * JSON-RPC endpoint at its mount. `descriptor.ts` lists what it does not do. + * A2A (Agent2Agent) v1 adapter. Publishes canonical resources as A2A skills at + * `/.well-known/agent-card.json` and serves JSON-RPC at its configured mount. + * See `descriptor.ts` for unsupported features. */ export type { A2aAdapterOptions } from './adapter'; diff --git a/src/support/a2a.json b/src/support/a2a.json index 8f6f1ea..136a9b6 100644 --- a/src/support/a2a.json +++ b/src/support/a2a.json @@ -2,9 +2,9 @@ "name": "a2a", "kind": "protocol", "title": "A2A", - "status": "experimental", + "status": "supported", "role": "Transport that carries x402 and MPP payments in `SendMessage`, including through the x402 extension.", - "subset": "Agent Card, `SendMessage` with `returnImmediately`, `GetTask`, `ListTasks`, `CancelTask`, paid flow and the x402 extension", + "subset": "Agent Card, `SendMessage` with `returnImmediately`, `GetTask`, `ListTasks`, `CancelTask` and the paid flow; the x402 extension is experimental", "spec": { "revisions": ["1.0.1"], "display": "v1.0.1; negotiation `1.0`; `JSONRPC` binding", @@ -19,13 +19,13 @@ "packages": [{ "name": "@a2a-js/sdk", "use": "test" }], "artifacts": [], "features": [ - { "name": "agent-card", "status": "experimental" }, - { "name": "jsonrpc", "status": "experimental" }, - { "name": "SendMessage", "status": "experimental" }, - { "name": "GetTask", "status": "experimental" }, - { "name": "ListTasks", "status": "experimental" }, - { "name": "CancelTask", "status": "experimental" }, - { "name": "returnImmediately", "status": "experimental" }, + { "name": "agent-card", "status": "supported" }, + { "name": "jsonrpc", "status": "supported" }, + { "name": "SendMessage", "status": "supported" }, + { "name": "GetTask", "status": "supported" }, + { "name": "ListTasks", "status": "supported" }, + { "name": "CancelTask", "status": "supported" }, + { "name": "returnImmediately", "status": "supported" }, { "name": "x402-extension", "status": "experimental" } ], "exclusions": [ @@ -46,6 +46,19 @@ { "name": "task resumption other than an x402 extension payment" }, { "name": "push notifications" }, { "name": "multi-turn conversational continuation" }, + { + "name": "client-chosen contextId", + "note": "A `contextId` without a task gets `UnsupportedOperationError`; each new task opens a context the gateway generates." + }, + { + "name": "listing tasks across contexts", + "note": "`ListTasks` reads only the given `contextId`; without one, the page is empty." + }, + { + "name": "task history", + "note": "Tasks omit `history`; `historyLength` is validated but has nothing to cap." + }, + { "name": "non-empty tenant" }, { "name": "text parts" }, { "name": "file and URL parts (including inline bytes)" }, { "name": "multi-part messages" }, @@ -58,7 +71,13 @@ "note": "Instances with separate receipt stores cannot read, cancel or pay each other's tasks." } ], - "deviations": [], + "deviations": [ + { + "summary": "A `ListTasks` page with no matching task has an empty `tasks` array. The proto marks `tasks` REQUIRED, and §5.7 requires a REQUIRED array to hold an element, but an empty result has none to return.", + "spec": "A2A 1.0.1 §5.7; `ListTasksResponse.tasks`", + "tests": ["tests/conformance/a2a/tasks.test.ts"] + } + ], "conformance": { "suite": "Our tests against the A2A 1.0.1 specification, and the A2A TCK at MUST level in CI.", "tests": [ diff --git a/tests/integration/a2a-over-gateway.test.ts b/tests/integration/a2a-over-gateway.test.ts index fd613c4..181bd89 100644 --- a/tests/integration/a2a-over-gateway.test.ts +++ b/tests/integration/a2a-over-gateway.test.ts @@ -330,7 +330,7 @@ describe('A2A in gateway discovery', () => { }>(); const a2a = doc.adapters.find((adapter) => adapter.name === 'a2a'); - expect(a2a?.status).toBe('experimental'); + expect(a2a?.status).toBe('stable'); expect(a2a?.supportedSpec).toBe('1.0.1'); expect(a2a?.unsupported).toContain('SendStreamingMessage'); expect(a2a?.health.status).toBe('pass'); diff --git a/tests/integration/goldens/2.7.2/doctor-multi.json b/tests/integration/goldens/2.7.2/doctor-multi.json index 052a955..c386df7 100644 --- a/tests/integration/goldens/2.7.2/doctor-multi.json +++ b/tests/integration/goldens/2.7.2/doctor-multi.json @@ -23,12 +23,12 @@ { "name": "A2A", "status": "PASS", - "detail": "experimental · spec 1.0.1 · protocol 1.0 · binding JSONRPC · mount /a2a · card /.well-known/agent-card.json" + "detail": "supported · spec 1.0.1 · protocol 1.0 · binding JSONRPC · mount /a2a · card /.well-known/agent-card.json" }, { "name": "A2A unsupported", "status": "INFO", - "detail": "SendStreamingMessage, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, resuming a background task after a restart, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, tasks across gateway instances" + "detail": "SendStreamingMessage, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, resuming a background task after a restart, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, client-chosen contextId, listing tasks across contexts, task history, non-empty tenant, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, tasks across gateway instances" }, { "name": "ACP", diff --git a/tests/integration/goldens/2.7.2/doctor-single.json b/tests/integration/goldens/2.7.2/doctor-single.json index b342495..d222b60 100644 --- a/tests/integration/goldens/2.7.2/doctor-single.json +++ b/tests/integration/goldens/2.7.2/doctor-single.json @@ -23,12 +23,12 @@ { "name": "A2A", "status": "PASS", - "detail": "experimental · spec 1.0.1 · protocol 1.0 · binding JSONRPC · mount /a2a · card /.well-known/agent-card.json" + "detail": "supported · spec 1.0.1 · protocol 1.0 · binding JSONRPC · mount /a2a · card /.well-known/agent-card.json" }, { "name": "A2A unsupported", "status": "INFO", - "detail": "SendStreamingMessage, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, resuming a background task after a restart, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, tasks across gateway instances" + "detail": "SendStreamingMessage, SubscribeToTask, CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig, GetExtendedAgentCard, HTTP+JSON/REST binding, gRPC binding, SSE, resuming a background task after a restart, task resumption other than an x402 extension payment, push notifications, multi-turn conversational continuation, client-chosen contextId, listing tasks across contexts, task history, non-empty tenant, text parts, file and URL parts (including inline bytes), multi-part messages, message roles other than ROLE_USER, authenticated extended agent cards, A2A authentication schemes, artifact types beyond Agent Commerce outcome data, tasks across gateway instances" }, { "name": "ACP", diff --git a/tests/integration/goldens/2.7.2/well-known-multi.json b/tests/integration/goldens/2.7.2/well-known-multi.json index a97314d..d0ee7cb 100644 --- a/tests/integration/goldens/2.7.2/well-known-multi.json +++ b/tests/integration/goldens/2.7.2/well-known-multi.json @@ -75,7 +75,7 @@ "returnImmediately", "x402-extension" ], - "status": "experimental", + "status": "stable", "unsupported": [ "SendStreamingMessage", "SubscribeToTask", @@ -91,6 +91,10 @@ "task resumption other than an x402 extension payment", "push notifications", "multi-turn conversational continuation", + "client-chosen contextId", + "listing tasks across contexts", + "task history", + "non-empty tenant", "text parts", "file and URL parts (including inline bytes)", "multi-part messages", diff --git a/tests/integration/goldens/2.7.2/well-known-single.json b/tests/integration/goldens/2.7.2/well-known-single.json index d3b3ffa..7a71e6a 100644 --- a/tests/integration/goldens/2.7.2/well-known-single.json +++ b/tests/integration/goldens/2.7.2/well-known-single.json @@ -75,7 +75,7 @@ "returnImmediately", "x402-extension" ], - "status": "experimental", + "status": "stable", "unsupported": [ "SendStreamingMessage", "SubscribeToTask", @@ -91,6 +91,10 @@ "task resumption other than an x402 extension payment", "push notifications", "multi-turn conversational continuation", + "client-chosen contextId", + "listing tasks across contexts", + "task history", + "non-empty tenant", "text parts", "file and URL parts (including inline bytes)", "multi-part messages", diff --git a/tests/integration/support-record.test.ts b/tests/integration/support-record.test.ts index 8c3ad16..0408633 100644 --- a/tests/integration/support-record.test.ts +++ b/tests/integration/support-record.test.ts @@ -309,18 +309,94 @@ describe('drift between the records, package.json and the docs', () => { 'an experimental profile recorded as supported', { records: (records) => { - record(records, 'a2a').status = 'supported'; + record(records, 'acp').status = 'supported'; }, }, [ + // ACP's upstream snapshot is not declared stable + 'src/support/acp.json: supported, but criterion 1: upstream does not declare the pinned revision stable (spec.stable)', stale('README.md', 'badges', 'src/support/*.json'), stale('README.md', 'matrix', ALL), stale('docs/protocols.md', 'matrix', ALL), - 'README.md: the Versioning sentence names A2A, which src/support/a2a.json records as supported', - 'plugins/agent-commerce-gateway/skills/agent-commerce/SKILL.md: the "exist but are experimental" sentence names A2A, which src/support/a2a.json records as supported', - 'docs/protocols/a2a.md: says **Experimental.**, but src/support/a2a.json records supported', + 'README.md: the Versioning sentence names ACP, which src/support/acp.json records as supported', + 'plugins/agent-commerce-gateway/skills/agent-commerce/SKILL.md: the "exist but are experimental" sentence names ACP, which src/support/acp.json records as supported', + 'docs/protocols/acp.md: says **Experimental.**, but src/support/acp.json records supported', ], ], + [ + 'a supported profile whose upstream revision is not stable', + { + records: (records) => { + const a2a = record(records, 'a2a'); + if (a2a.spec !== undefined) a2a.spec.stable = false; + }, + }, + [ + 'src/support/a2a.json: supported, but criterion 1: upstream does not declare the pinned revision stable (spec.stable)', + stale('docs/protocols/a2a.md', 'pins', 'src/support/a2a.json and package.json'), + ], + ], + [ + 'a supported profile with no pinned revision', + { + records: (records) => { + delete record(records, 'a2a').spec; + }, + }, + [ + 'src/support/a2a.json: supported, but criterion 1: upstream does not declare the pinned revision stable (spec.stable)', + // Badges show only the profiles that pin a specification + stale('README.md', 'badges', 'src/support/*.json'), + stale('README.md', 'matrix', ALL), + stale('docs/protocols.md', 'matrix', ALL), + stale('docs/protocols/a2a.md', 'pins', 'src/support/a2a.json and package.json'), + ], + ], + [ + 'a supported profile whose only remaining gap is excluded', + { + records: (records) => { + record(records, 'a2a').gaps.push({ requirement: '§9.9: something', state: 'excluded' }); + }, + }, + [], + ], + [ + 'a supported profile with an open gap', + { + records: (records) => { + record(records, 'a2a').gaps.push({ requirement: '§9.9: something', state: 'open' }); + }, + }, + ['src/support/a2a.json: supported, but criterion 2: the gap "§9.9: something" is open'], + ], + [ + 'a supported profile without conformance evidence', + { + records: (records) => { + delete record(records, 'a2a').conformance; + }, + }, + ['src/support/a2a.json: supported, but criterion 3: no conformance evidence'], + ], + [ + 'a supported profile without docs', + { + records: (records) => { + record(records, 'a2a').docs = []; + }, + }, + ['src/support/a2a.json: supported, but criterion 4: no operational docs'], + ], + [ + 'an open gap on a profile supported before the criteria', + { + records: (records) => { + record(records, 'mcp').gaps.push({ requirement: '§9.9: something', state: 'open' }); + }, + }, + [], + ], ['a hand edit inside a generated region', HAND_EDIT, [stale('README.md', 'matrix', ALL)]], [ 'a deleted evidence file', @@ -333,7 +409,7 @@ describe('drift between the records, package.json and the docs', () => { 'an experimental profile missing from the Versioning sentence', { edit: { - 'README.md': (content) => content.replace('MPP, A2A, ACP, AP2,', 'A2A, ACP, AP2,'), + 'README.md': (content) => content.replace('MPP, ACP, AP2,', 'ACP, AP2,'), }, }, [ diff --git a/tests/unit/cli/doctor.test.ts b/tests/unit/cli/doctor.test.ts index 8101133..aa12f14 100644 --- a/tests/unit/cli/doctor.test.ts +++ b/tests/unit/cli/doctor.test.ts @@ -1630,7 +1630,7 @@ describe('runDoctor: A2A', () => { expect(a2a?.detail).toContain('binding JSONRPC'); expect(a2a?.detail).toContain('mount /agents/a2a'); expect(a2a?.detail).toContain('card /.well-known/agent-card.json'); - expect(a2a?.detail).toContain('experimental'); + expect(a2a?.detail).toMatch(/^supported · /); const protocols = report.checks.find((c) => c.name === 'Protocols'); expect(protocols?.detail).toContain('a2a=on (/agents/a2a)'); diff --git a/tests/unit/protocols-a2a/agent-card.test.ts b/tests/unit/protocols-a2a/agent-card.test.ts index f4ee815..c6a653e 100644 --- a/tests/unit/protocols-a2a/agent-card.test.ts +++ b/tests/unit/protocols-a2a/agent-card.test.ts @@ -278,11 +278,11 @@ describe('A2A agent card', () => { }); describe('A2A adapter lifecycle', () => { - it('reports the pinned spec revision, experimental status and a complete unsupported list', () => { + it('reports the pinned spec revision, stable status and a complete unsupported list', () => { const { descriptor } = createA2aAdapter(); expect(descriptor.name).toBe('a2a'); expect(descriptor.supportedSpec).toBe('1.0.1'); - expect(descriptor.status).toBe('experimental'); + expect(descriptor.status).toBe('stable'); expect(descriptor.capabilities).toEqual([ 'agent-card', 'jsonrpc', @@ -307,6 +307,10 @@ describe('A2A adapter lifecycle', () => { 'HTTP+JSON/REST binding', 'gRPC binding', 'A2A authentication schemes', + 'client-chosen contextId', + 'listing tasks across contexts', + 'task history', + 'non-empty tenant', ]), ); }); From 624a3f8fe58a81d1db04b7cac9a8f4c154eeb65a Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 14:20:05 +0100 Subject: [PATCH 11/17] fix(a2a): name the x402 error code in a failed payment's status text --- docs/protocols/a2a.md | 4 +- docs/security.md | 1 + src/protocols/a2a/payment-resume.ts | 11 +++-- tests/integration/a2a-x402-extension.test.ts | 30 ++++++++++++- .../unit/protocols-a2a/payment-resume.test.ts | 42 +++++++++++++++++++ 5 files changed, 83 insertions(+), 5 deletions(-) diff --git a/docs/protocols/a2a.md b/docs/protocols/a2a.md index c0ef03e..5915d32 100644 --- a/docs/protocols/a2a.md +++ b/docs/protocols/a2a.md @@ -196,7 +196,9 @@ These outcomes return a terminal task with one artifact: Every `TASK_STATE_FAILED` task has a `ROLE_AGENT` status message. Ordinary failures and `payment_identifier_*` refusals use the envelope's `message` as -their text. Other extension payment failures summarize the payment outcome. +their text. Other extension payment failures summarize the outcome. Their +`payment-failed` messages end with the `x402.payment.error` code, for example +`Payment failed: insufficient_funds.` Only extension status messages carry `metadata` and `extensions`. With the x402 extension, an unpaid task is `TASK_STATE_INPUT_REQUIRED`; its diff --git a/docs/security.md b/docs/security.md index e53158f..eea2574 100644 --- a/docs/security.md +++ b/docs/security.md @@ -399,6 +399,7 @@ real funds. | **a backend failure under the MPP `authorization` flow** | nothing settles; the same credential again gets 402 `PAYMENT_REPLAYED` with a fresh challenge and moves no funds | `tests/integration/mpp-carriers.test.ts`, `tests/e2e/payment/mpp-settlement.e2e.test.ts` | | **an MPP settlement refused after the backend ran** (`authorization` flow) | the response is withheld; 402 with a fresh `WWW-Authenticate` and a failed `PAYMENT-RESPONSE` | `tests/integration/mpp-carriers.test.ts`, `tests/unit/payments-mpp/provider.test.ts` | | **an x402 A2A extension payment sent twice on one task** | after validating a follow-up message, the adapter atomically takes its task before execution; a competing message that loses the take gets `UnsupportedOperationError` (`-32004`) while the task record is retained, without another settlement | `tests/integration/a2a-x402-extension.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | +| **a settled x402 proof reused on another A2A extension task for the same resource, with redelivery disabled** | `TASK_STATE_FAILED` with `payment-failed`; the status text and `x402.payment.error` carry the network's replay code. No second settlement or backend call. | `tests/integration/a2a-x402-extension.test.ts` | | **unauthenticated callers filling the store with unpaid A2A extension tasks** | new unpaid tasks are refused with `GATEWAY_BUSY` when the receipt store already holds 256 unexpired tasks. Tasks expire with their requirement or within an hour; expired tasks cannot be paid, and waiting tasks are not evicted | `tests/unit/protocols-a2a/x402-extension.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/integration/a2a-x402-extension.test.ts` | | expired authorization (`validBefore` in the past) | refused before settlement | `tests/e2e/payment` | | not-yet-valid authorization (`validAfter` in the future) | refused before settlement | `tests/e2e/payment` | diff --git a/src/protocols/a2a/payment-resume.ts b/src/protocols/a2a/payment-resume.ts index 224aaaa..5a42ed7 100644 --- a/src/protocols/a2a/payment-resume.ts +++ b/src/protocols/a2a/payment-resume.ts @@ -29,6 +29,7 @@ import { paymentRejectedMetadata, readFollowUpAuthorization, readPaymentSubmission, + X402_PAYMENT_ERROR_KEY, X402_PAYMENT_PAYLOAD_KEY, X402_PAYMENT_STATUS_KEY, } from './x402-extension'; @@ -242,14 +243,18 @@ async function payPending( const identity = { ...ids, timestamp: context.clock.nowIso() }; const metadata = paymentFailureMetadata(error, pending.network); const reason = error.details?.['reason']; - let text = 'Payment failed.'; + let text: string; if (metadata[X402_PAYMENT_STATUS_KEY] === 'payment-completed') { text = 'Payment settled, but the resource could not be delivered.'; } else if (typeof reason === 'string' && reason.startsWith('payment_identifier_')) { // Retry-key refusals make no new charge; show the specific error message text = error.message; - } else if (!error.code.startsWith('PAYMENT_')) { - text = 'The resource could not be delivered.'; + } else { + // Show the metadata's failure reason in the status text (a2a-x402 v0.1 §8) + const outcome = error.code.startsWith('PAYMENT_') + ? 'Payment failed' + : 'The resource could not be delivered'; + text = `${outcome}: ${String(metadata[X402_PAYMENT_ERROR_KEY])}.`; } return withStatusMessage(failedTask(error, identity), text, identity.statusMessageId, metadata); } diff --git a/tests/integration/a2a-x402-extension.test.ts b/tests/integration/a2a-x402-extension.test.ts index 7e6bfe7..dc6b3de 100644 --- a/tests/integration/a2a-x402-extension.test.ts +++ b/tests/integration/a2a-x402-extension.test.ts @@ -318,6 +318,32 @@ describe('x402 A2A extension', () => { expect(facilitator.settle).toHaveBeenCalledTimes(1); }); + it('refuses a proof that already paid another task, settling once', async () => { + const first = await challenged(); + const payload = await paymentPayload(first); + await rpc( + pay(first, { 'x402.payment.status': 'payment-submitted', 'x402.payment.payload': payload }), + ); + const second = await challenged(); + + const { body } = await rpc( + pay(second, { 'x402.payment.status': 'payment-submitted', 'x402.payment.payload': payload }), + ); + + const failed = body.result?.task; + expect(failed?.id).toBe(second.id); + expect(failed?.status.state).toBe('TASK_STATE_FAILED'); + expect(failed?.status.message?.parts).toEqual([ + { text: 'Payment failed: invalid_exact_evm_nonce_already_used.' }, + ]); + expect(failed?.status.message?.metadata).toMatchObject({ + 'x402.payment.status': 'payment-failed', + 'x402.payment.error': 'invalid_exact_evm_nonce_already_used', + }); + expect(backendCalls).toBe(1); + expect(facilitator.settle).toHaveBeenCalledTimes(1); + }); + it('fails the task with the reason when the payment is refused', async () => { facilitator.verify.mockResolvedValueOnce({ isValid: false, @@ -334,7 +360,9 @@ describe('x402 A2A extension', () => { const failed = body.result?.task; expect(failed?.status.state).toBe('TASK_STATE_FAILED'); - expect(failed?.status.message?.parts).toEqual([{ text: 'Payment failed.' }]); + expect(failed?.status.message?.parts).toEqual([ + { text: 'Payment failed: insufficient_funds.' }, + ]); expect(failed?.status.message?.metadata).toMatchObject({ 'x402.payment.status': 'payment-failed', 'x402.payment.error': 'insufficient_funds', diff --git a/tests/unit/protocols-a2a/payment-resume.test.ts b/tests/unit/protocols-a2a/payment-resume.test.ts index 5261285..56158ed 100644 --- a/tests/unit/protocols-a2a/payment-resume.test.ts +++ b/tests/unit/protocols-a2a/payment-resume.test.ts @@ -108,6 +108,48 @@ describe('resumePayment pipeline refusals', () => { }); }); +describe('resumePayment failure text', () => { + const settled = { + payment: { status: 'settled', provider: 'x402', currency: 'USDC', externalReference: '0xabc' }, + }; + + it.each([ + [ + 'a refused payment, with its x402 error code', + new CommerceError('PAYMENT_INVALID', 'Refused', { + details: { reason: 'insufficient_funds' }, + }), + 'Payment failed: insufficient_funds.', + ], + [ + 'a replayed EVM proof, with the nonce code', + new CommerceError('PAYMENT_REPLAYED', 'Used', { details: { network: 'eip155:8453' } }), + 'Payment failed: invalid_exact_evm_nonce_already_used.', + ], + [ + 'a failure before settlement, with its commerce code', + new CommerceError('BACKEND_TIMEOUT', 'Timed out'), + 'The resource could not be delivered: backend_timeout.', + ], + [ + 'a retry-key refusal, with its own message', + new CommerceError('PAYMENT_REPLAYED', 'A request is in progress', { + details: { reason: 'payment_identifier_in_flight' }, + }), + 'A request is in progress', + ], + [ + 'a backend failure after settlement, as a settled payment', + new CommerceError('BACKEND_ERROR', 'Backend failed', { details: settled }), + 'Payment settled, but the resource could not be delivered.', + ], + ])('states %s', async (_label, refusal, text) => { + const { task } = await resumeWith(refusal); + + expect(task.status.message?.parts).toEqual([{ text }]); + }); +}); + describe('resumePayment with returnImmediately', () => { // Use one slot to check that refused calls release their reservations async function answer( From 7e87a24db6fe6701042c14a86390d019070d8d00 Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 14:20:40 +0100 Subject: [PATCH 12/17] fix(support): list supported badges first --- scripts/support-record.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/support-record.ts b/scripts/support-record.ts index 27b6e4a..b300140 100644 --- a/scripts/support-record.ts +++ b/scripts/support-record.ts @@ -328,8 +328,11 @@ function matrixRows(records: readonly SupportRecord[], manifest: PackageManifest } function badges(records: readonly SupportRecord[]): string { + const experimental = (record: SupportRecord) => Number(record.status === 'experimental'); + // Supported badges first, each group in record order return records .filter((record) => record.spec !== undefined) + .sort((a, b) => experimental(a) - experimental(b)) .map((record) => { const color = record.status === 'experimental' From 5aac86df16618facf41398e5965fb9bc3e0c7982 Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 14:39:03 +0100 Subject: [PATCH 13/17] docs: note A2A task access and stored-task privacy --- docs/security.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/security.md b/docs/security.md index eea2574..480a917 100644 --- a/docs/security.md +++ b/docs/security.md @@ -188,6 +188,11 @@ The operator routes carry the merchant's commerce ledger. With no `server.adminToken` configured they return **404**, not open data - a missing control must not read as an absent restriction. +An A2A task ID acts as an access key: anyone holding it can call `GetTask` +or `CancelTask` without an ownership check. `ListTasks` returns tasks only +for the supplied context ID. The gateway generates both IDs randomly; see +[Access](protocols/a2a.md#access). + An allowed browser origin receives CORS headers. Requests without `Origin` do not. The shared `onRequest` hook covers raw mounts such as MCP and uses Host validation to limit DNS-rebinding attacks. @@ -732,6 +737,13 @@ reuse, not how long every copy exists: a later claim sweep deletes expired rows, and backups persist until separately removed. Enable `redelivery` per resource with this in mind, and set the window only as long as buyers need to retry. +A2A task documents can hold merchant content and x402 receipts with payer +addresses and transaction hashes. With SQLite storage, these documents and +their backups are unencrypted. `protocols.a2a.tasks.retentionHours` controls +readability after storage or updates (default 24 hours); unpaid tasks expire +with their payment requirement, capped at one hour (10 minutes without an +expiry). + ## Threats we are not addressing Buyer identity and screening · fraud and disputes · refunds and chargebacks · From 69ba34345f691756e1afe84c8a6bf6f963eb7592 Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 16:20:37 +0100 Subject: [PATCH 14/17] fix(a2a): release the background slot when taking a pending payment fails --- src/protocols/a2a/payment-resume.ts | 16 +++++++----- .../unit/protocols-a2a/pending-store.test.ts | 26 +++++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/src/protocols/a2a/payment-resume.ts b/src/protocols/a2a/payment-resume.ts index 5a42ed7..a1c3f97 100644 --- a/src/protocols/a2a/payment-resume.ts +++ b/src/protocols/a2a/payment-resume.ts @@ -112,14 +112,16 @@ export async function resumePayment( retryInfo(BACKGROUND_RETRY_SECONDS), ]); } - // Take after validation and before execution; the earlier read did not claim - // the purchase. If another payment or cancellation took it, let the adapter - // respond from the retained task record. - const taken = await pendingPayments.take(taskId); - if (taken === undefined) { - if (immediate) resume.background.release(); - return undefined; + // The earlier read did not claim the purchase. Take it after validation, + // before execution; if another call won, use the retained task response. + let taken: PendingPayment | undefined; + try { + taken = await pendingPayments.take(taskId); + } finally { + // An empty or failed take must release the reserved background slot + if (immediate && taken === undefined) resume.background.release(); } + if (taken === undefined) return undefined; const authorization = taken.authorization ?? followUp; if (submission.kind === 'rejected') { diff --git a/tests/unit/protocols-a2a/pending-store.test.ts b/tests/unit/protocols-a2a/pending-store.test.ts index 6116839..cd8a1fe 100644 --- a/tests/unit/protocols-a2a/pending-store.test.ts +++ b/tests/unit/protocols-a2a/pending-store.test.ts @@ -910,6 +910,32 @@ describe('tasks finished in the background with returnImmediately', () => { expect(backendCalls).toBe(0); }); + it('keeps no slot when taking the pending purchase throws', async () => { + let failTakes = true; + const node = await boot((store) => + Object.assign(Object.create(store) as ReceiptStore, { + async takePendingTask(id: string) { + if (failTakes) throw new Error('database is locked'); + return store.takePendingTask?.(id); + }, + }), + ); + const waiting = await challenged(node, 'report'); + + // More failures than there are slots + for (let i = 0; i < 21; i += 1) { + const { error } = await rpc(node, pay(waiting), IMMEDIATELY); + expect(error?.code).toBe(-32603); + } + failTakes = false; + + expect((await buyNow(node, 'proof-1')).result?.task?.status.state).toBe('TASK_STATE_WORKING'); + expect((await rpc(node, pay(waiting), IMMEDIATELY)).result?.task.status.state).toBe( + 'TASK_STATE_WORKING', + ); + await vi.waitFor(() => expect(calls.settle).toBe(2)); + }); + it('waits on stop for a background run, which records its result', async () => { const node = await boot(); const release = holdBackend(); From 9d061a6bfc66748c442cbd09140e864747a0d94a Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 16:40:15 +0100 Subject: [PATCH 15/17] feat(storage): let a full task store evict records marked evictable --- docs/contract-surface.txt | 1 + docs/contracts.md | 9 +++- src/core/domain/store-records.ts | 5 ++ src/core/interfaces/store.ts | 7 +-- src/storage/receipts/schema.ts | 4 +- src/storage/receipts/task-records.ts | 22 +++++++-- src/testing/conformance/record-cases.ts | 65 +++++++++++++++++++++++++ 7 files changed, 103 insertions(+), 10 deletions(-) diff --git a/docs/contract-surface.txt b/docs/contract-surface.txt index a2e2fbc..0eaeb1e 100644 --- a/docs/contract-surface.txt +++ b/docs/contract-surface.txt @@ -556,6 +556,7 @@ interface ResourceRegistry { interface TaskRecord { readonly document: Readonly>; + readonly evictable?: boolean; readonly expiresAt: string; readonly groupId: string; readonly id: string; diff --git a/docs/contracts.md b/docs/contracts.md index 1993cae..66a5f35 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -316,8 +316,13 @@ persistence must not fail the commerce flow. adapter for later reads. It does not make the task payable; payment continuation uses separate pending-task state. - `putTaskRecord` deletes expired records before storing a record. It - replaces a record with the same ID even at capacity. For a new ID, it - returns `false` without storing when `maxRecords` unexpired records exist. + replaces an existing ID even at capacity. For a new ID, it evicts eligible + records by `updatedAt` and then `id`, both ascending, until the count is + below `maxRecords`. If too few can be evicted, it returns `false` without + storing the new record. + - `evictable: true` allows capacity eviction of an uncharged response. + Records with the flag omitted or set to `false` are protected from capacity + eviction. A replacement uses the new record's flag. - `listTaskRecords` returns all unexpired records matching `protocol` and `groupId`, without pagination. Records are ordered by `updatedAt` and then `id`, both descending. diff --git a/src/core/domain/store-records.ts b/src/core/domain/store-records.ts index e61f4f8..ec59c66 100644 --- a/src/core/domain/store-records.ts +++ b/src/core/domain/store-records.ts @@ -117,4 +117,9 @@ export interface TaskRecord { readonly document: Readonly>; /** Set and bounded by the caller */ readonly expiresAt: IsoTimestamp; + /** + * Mark an uncharged response for eviction at capacity. Omit this flag or + * set it to false to protect the record from capacity eviction. + */ + readonly evictable?: boolean; } diff --git a/src/core/interfaces/store.ts b/src/core/interfaces/store.ts index a322ee4..b557fba 100644 --- a/src/core/interfaces/store.ts +++ b/src/core/interfaces/store.ts @@ -322,9 +322,10 @@ export interface ReceiptStore { * Store task responses for later reads by protocol adapters. Implement all * three methods or none. Experimental: may change in a minor release. * - * Delete expired records, then store `record`. Replace a record with the same - * ID even at capacity. For a new ID, return false without storing when - * `maxRecords` unexpired records exist. + * Delete expired records, then store `record`. Replace an existing ID even + * at capacity. For a new ID, evict eligible records by `updatedAt` and then + * `id`, both ascending, until the count is below `maxRecords`. Return false + * without storing the new record if too few can be evicted. */ putTaskRecord?(record: TaskRecord, options: { readonly maxRecords: number }): Promise; /** Return undefined for a missing or expired record. Experimental: may change in a minor release */ diff --git a/src/storage/receipts/schema.ts b/src/storage/receipts/schema.ts index b5c6b19..c37c405 100644 --- a/src/storage/receipts/schema.ts +++ b/src/storage/receipts/schema.ts @@ -226,10 +226,12 @@ const MIGRATIONS: readonly Migration[] = [ state TEXT NOT NULL, updated_at TEXT NOT NULL, document_json TEXT NOT NULL, - expires_at TEXT NOT NULL + expires_at TEXT NOT NULL, + evictable INTEGER NOT NULL DEFAULT 0 ); CREATE INDEX IF NOT EXISTS idx_task_records_group ON task_records(protocol, group_id, updated_at); CREATE INDEX IF NOT EXISTS idx_task_records_expires_at ON task_records(expires_at); + CREATE INDEX IF NOT EXISTS idx_task_records_evictable ON task_records(updated_at, id) WHERE evictable = 1; `); }, }, diff --git a/src/storage/receipts/task-records.ts b/src/storage/receipts/task-records.ts index 838dc4d..46b84c9 100644 --- a/src/storage/receipts/task-records.ts +++ b/src/storage/receipts/task-records.ts @@ -15,6 +15,7 @@ interface RecordRow { updated_at: string; document_json: string; expires_at: string; + evictable: number; } type TaskRecordMethods = StoreGroupMethods<'task_records'>; @@ -28,6 +29,7 @@ function rowToRecord(row: RecordRow): TaskRecord { updatedAt: row.updated_at, document: JSON.parse(row.document_json), expiresAt: row.expires_at, + ...(row.evictable === 1 ? { evictable: true } : {}), }; } @@ -45,8 +47,12 @@ export function createTaskRecordMethods(db: Database.Database, clock: Clock): Ta const hasId = db.prepare<[string], { id: string }>('SELECT id FROM task_records WHERE id = ?'); const upsert = db.prepare( `INSERT OR REPLACE INTO task_records - (id, protocol, group_id, state, updated_at, document_json, expires_at) - VALUES (@id, @protocol, @group_id, @state, @updated_at, @document_json, @expires_at)`, + (id, protocol, group_id, state, updated_at, document_json, expires_at, evictable) + VALUES (@id, @protocol, @group_id, @state, @updated_at, @document_json, @expires_at, @evictable)`, + ); + const evictOldest = db.prepare<[number]>( + `DELETE FROM task_records WHERE id IN + (SELECT id FROM task_records WHERE evictable = 1 ORDER BY updated_at, id LIMIT ?)`, ); const selectLive = db.prepare<[string, string], RecordRow>( 'SELECT * FROM task_records WHERE id = ? AND expires_at > ?', @@ -60,8 +66,15 @@ export function createTaskRecordMethods(db: Database.Database, clock: Clock): Ta const put = db.transaction((row: RecordRow, maxRecords: number): boolean => { sweepExpired.run(clock.nowIso()); // Replacing an existing ID does not count against the record limit - if (hasId.get(row.id) === undefined && (countAll.get()?.count ?? 0) >= maxRecords) { - return false; + if (hasId.get(row.id) === undefined) { + const count = countAll.get()?.count ?? 0; + // A lower limit may require evicting more than one record + if ( + count >= maxRecords && + count - evictOldest.run(count - maxRecords + 1).changes >= maxRecords + ) { + return false; + } } upsert.run(row); return true; @@ -82,6 +95,7 @@ export function createTaskRecordMethods(db: Database.Database, clock: Clock): Ta updated_at: storedIso(record.updatedAt, 'updatedAt'), document_json: JSON.stringify(record.document), expires_at: storedIso(record.expiresAt, 'expiresAt'), + evictable: record.evictable === true ? 1 : 0, }; return put.immediate(row, options.maxRecords); } catch (err) { diff --git a/src/testing/conformance/record-cases.ts b/src/testing/conformance/record-cases.ts index 8414f91..7f08d30 100644 --- a/src/testing/conformance/record-cases.ts +++ b/src/testing/conformance/record-cases.ts @@ -812,6 +812,71 @@ const TASK_RECORD_CASES: readonly CaseSpec[] = [ assert.equal(await s.putTaskRecord(record('e'), { maxRecords: 2 }), false); }, }, + { + name: 'at maxRecords, a new task record evicts the oldest evictable one', + uses: RECORDS, + async run({ store }) { + const s = records(store); + const put = (r: TaskRecord) => s.putTaskRecord(r, { maxRecords: 3 }); + const paid = record('paid', { updatedAt: isoAt(0) }); + const older = record('older', { updatedAt: isoAt(1), evictable: true }); + const newer = record('newer', { updatedAt: isoAt(2), evictable: true }); + assert.equal(await put(paid), true); + assert.equal(await put(newer), true); + assert.equal(await put(older), true); + assert.deepEqual(await s.getTaskRecord('older'), older); + + assert.equal(await put(record('next', { updatedAt: isoAt(3) })), true); + assert.equal(await s.getTaskRecord('older'), undefined); + assert.equal(await put(record('last', { updatedAt: isoAt(4) })), true); + assert.equal(await s.getTaskRecord('newer'), undefined); + // No evictable record is left + assert.equal(await put(record('refused', { evictable: true })), false); + assert.deepEqual(ids(await s.listTaskRecords({ protocol: 'a2a', groupId: 'group-1' })), [ + 'last', + 'next', + 'paid', + ]); + }, + }, + { + name: 'a lower maxRecords evicts enough evictable task records for a new one to fit', + uses: RECORDS, + async run({ store }) { + const s = records(store); + for (const [i, id] of ['e1', 'e2', 'e3'].entries()) { + await s.putTaskRecord(record(id, { updatedAt: isoAt(i), evictable: true }), { + maxRecords: 10, + }); + } + await s.putTaskRecord(record('paid', { updatedAt: isoAt(0) }), { maxRecords: 10 }); + + assert.equal( + await s.putTaskRecord(record('new', { updatedAt: isoAt(5) }), { maxRecords: 2 }), + true, + ); + assert.deepEqual(ids(await s.listTaskRecords({ protocol: 'a2a', groupId: 'group-1' })), [ + 'new', + 'paid', + ]); + }, + }, + { + name: 'replacing a task record sets whether it is evictable', + uses: RECORDS, + async run({ store }) { + const s = records(store); + const put = (r: TaskRecord) => s.putTaskRecord(r, { maxRecords: 2 }); + await put(record('kept', { state: 'TASK_STATE_WORKING' })); + await put(record('working', { state: 'TASK_STATE_WORKING', evictable: true })); + await put(record('kept', { evictable: true })); + await put(record('working')); + + assert.equal(await put(record('new')), true); + assert.equal(await s.getTaskRecord('kept'), undefined); + assert.notEqual(await s.getTaskRecord('working'), undefined); + }, + }, { name: 'task records list one protocol and group, by updatedAt then id, both descending', uses: RECORDS, From 1195bb844223a0b648588d05470fca674e89a5ae Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 16:46:28 +0100 Subject: [PATCH 16/17] fix(a2a): mark task records nothing was charged for as evictable --- docs/configuration.md | 6 +- docs/protocols/a2a.md | 33 ++++++-- docs/security.md | 26 +++--- src/protocols/a2a/adapter.ts | 22 +++-- src/protocols/a2a/payment-resume.ts | 33 +++++--- src/protocols/a2a/task-mapping.ts | 26 ++++++ src/protocols/a2a/task-operations.ts | 3 +- src/protocols/a2a/task-store.ts | 43 +++++++--- .../unit/protocols-a2a/pending-store.test.ts | 77 ++++++++++++++++++ .../protocols-a2a/pipeline-mapping.test.ts | 81 ++++++++++++++++++- tests/unit/protocols-a2a/task-store.test.ts | 29 +++++++ 11 files changed, 319 insertions(+), 60 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 246b2e2..c36b1aa 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -268,8 +268,10 @@ protocols: - `retentionHours`: how long a task stays readable after it is stored or updated. - `maxRetained`: the limit on unexpired task records when admitting a new - record. At capacity, the store refuses new records and permits replacements. - Lowering the limit does not evict existing records. + record. At capacity, the store evicts eligible uncharged responses to make + room, or refuses the new record if too few can be evicted. Existing IDs can + still be replaced. [A2A tasks](protocols/a2a.md#tasks) describes eligibility + and eviction order. ## `protocols.acp` diff --git a/docs/protocols/a2a.md b/docs/protocols/a2a.md index 5915d32..d589f2a 100644 --- a/docs/protocols/a2a.md +++ b/docs/protocols/a2a.md @@ -232,14 +232,31 @@ after it is stored or updated (default 24 hours). An unpaid x402 extension task uses the pending-payment expiry described above instead. See [`protocols.a2a`](../configuration.md#protocolsa2a). -Once the store has `protocols.a2a.tasks.maxRetained` unexpired records (default -1000), it refuses new records and permits replacements. It does not evict -records, even if the limit is lowered. Free calls cannot evict an unexpired -paid result. A new extension purchase at capacity fails with `GATEWAY_BUSY` -without holding a pending purchase. Other blocking responses are returned -without being retained, and the adapter logs at `warn`. Write exceptions are -logged at `error`. Background startup refusals are described below. Retention -changes affect subsequent writes. +At `protocols.a2a.tasks.maxRetained` unexpired records (default 1000), new +records can evict responses known to have charged nothing: + +- Free deliveries, terminal payment-required responses, declined payments and + canceled tasks. +- Failed requests without a payment proof, or refused before settlement with + `RESOURCE_NOT_FOUND`, `INPUT_INVALID`, `PAYMENT_INVALID`, `PAYMENT_REPLAYED` + or an `AUTHORIZATION_*` code. +- Backend failures in the `authorization` flow, which abandons settlement. + +Waiting and working tasks and responses that may have charged a payment are +protected until expiry. Evictable responses make room for purchases, but a +free response may disappear before its client reads it. + +SQLite evicts by `updatedAt` and then `id`, both ascending, and may remove +multiple eligible records after a limit reduction. The memory fallback +evicts the earliest written eligible response; replacing a record counts +as a new write. + +Existing IDs can be replaced at capacity. If too few records are evictable, +the store refuses a new record. A new extension purchase then fails with +`GATEWAY_BUSY` without holding a pending purchase. Other blocking responses +are returned without retention; the adapter logs capacity refusals at `warn` +and write exceptions at `error`. Background startup refusals are described +below. Retention changes affect subsequent writes. ### Access diff --git a/docs/security.md b/docs/security.md index 480a917..a0459ca 100644 --- a/docs/security.md +++ b/docs/security.md @@ -403,8 +403,8 @@ real funds. | **a backend failure after an MPP settlement** (`upfront` flow) | the error omits `Payment-Receipt`; `PAYMENT-RESPONSE` reports the settlement | `tests/integration/mpp-carriers.test.ts` | | **a backend failure under the MPP `authorization` flow** | nothing settles; the same credential again gets 402 `PAYMENT_REPLAYED` with a fresh challenge and moves no funds | `tests/integration/mpp-carriers.test.ts`, `tests/e2e/payment/mpp-settlement.e2e.test.ts` | | **an MPP settlement refused after the backend ran** (`authorization` flow) | the response is withheld; 402 with a fresh `WWW-Authenticate` and a failed `PAYMENT-RESPONSE` | `tests/integration/mpp-carriers.test.ts`, `tests/unit/payments-mpp/provider.test.ts` | -| **an x402 A2A extension payment sent twice on one task** | after validating a follow-up message, the adapter atomically takes its task before execution; a competing message that loses the take gets `UnsupportedOperationError` (`-32004`) while the task record is retained, without another settlement | `tests/integration/a2a-x402-extension.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | -| **a settled x402 proof reused on another A2A extension task for the same resource, with redelivery disabled** | `TASK_STATE_FAILED` with `payment-failed`; the status text and `x402.payment.error` carry the network's replay code. No second settlement or backend call. | `tests/integration/a2a-x402-extension.test.ts` | +| **an x402 A2A extension payment sent twice on one task** | after validating a follow-up message, the adapter atomically takes its task before execution; a competing message that loses the take gets `UnsupportedOperationError` (`-32004`) while the task record is retained, without another settlement | `tests/integration/a2a-x402-extension.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | +| **a settled x402 proof reused on another A2A extension task for the same resource, with redelivery disabled** | `TASK_STATE_FAILED` with `payment-failed`; the status text and `x402.payment.error` carry the network's replay code. No second settlement or backend call. | `tests/integration/a2a-x402-extension.test.ts` | | **unauthenticated callers filling the store with unpaid A2A extension tasks** | new unpaid tasks are refused with `GATEWAY_BUSY` when the receipt store already holds 256 unexpired tasks. Tasks expire with their requirement or within an hour; expired tasks cannot be paid, and waiting tasks are not evicted | `tests/unit/protocols-a2a/x402-extension.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/integration/a2a-x402-extension.test.ts` | | expired authorization (`validBefore` in the past) | refused before settlement | `tests/e2e/payment` | | not-yet-valid authorization (`validAfter` in the future) | refused before settlement | `tests/e2e/payment` | @@ -435,7 +435,7 @@ real funds. | **a payment-attempt, receipt or journal write fails after the replay reservation** | Delivery or the original commerce error is preserved. Delivered outcomes and terminal events carry known failure labels; each write failure is logged at `error` level. A failed `completed` step adds no detail to those snapshots. The pipeline does not add the list to thrown errors | `tests/integration/transaction-journal.test.ts`, `tests/e2e/payment/crash-matrix.e2e.test.ts` | | **a gateway crash during a paid purchase, from before settlement to before the receipt commit, in either payment flow** | after restart, operator state reflects recorded steps and unresolved entries remain visible. `reconcile` can resolve `reserved` attempts at least `--min-age` old from final chain evidence, marking them `rejected` only with proof of an expired, unused authorization. It can also retry pending AP2 holds. After a payment and its hold are resolved, later runs leave them unchanged. Unknown delivery remains for operator review | `tests/e2e/payment/crash-matrix.e2e.test.ts` | | **SIGTERM while a settlement is held, in either payment flow, then SIGKILL after the grace period** | With AP2 disabled, the gateway drains until killed. After restart, the attempt remains `reserved`; its replay returns 409 without a challenge and moves no funds, whether or not the original transfer landed | `tests/e2e/payment/crash-matrix.e2e.test.ts` | -| **shutdown with a request in flight** | `close()` drains in-flight requests, then stops adapters; the A2A adapter waits for started background work to settle. A second SIGTERM or SIGINT exits immediately with status 1 | `tests/unit/gateway/shutdown.test.ts`, `tests/unit/gateway/main.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts` | +| **shutdown with a request in flight** | `close()` drains in-flight requests, then stops adapters; the A2A adapter waits for started background work to settle. A second SIGTERM or SIGINT exits immediately with status 1 | `tests/unit/gateway/shutdown.test.ts`, `tests/unit/gateway/main.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts` | | **a backup taken while the gateway writes, into a directory that holds files, or of a 2.5 database** | Each copy is a consistent snapshot at 0600, hashed in `backup.json`; a new directory is created at 0700. A non-empty `--out` is refused without writing files. Read-only sources keep their schema and import state, including v4 for 2.5 | `tests/unit/cli/backup.test.ts` | | **a restore of a backup older than some purchases** | Spent EVM proofs cannot pay again, including those absent from the backup. Attempts restored as uncertain still need `reconcile` or `resolve`. An AP2 mandate consumed after the backup can authorize again until it expires | `tests/e2e/payment/restore.e2e.test.ts` | | **a receipt write fails before a paid MCP or A2A response** | The `agent-commerce/delivery` summary retains the receipt ID and adds `receiptCommitted: false`; a successful receipt save leaves the field absent | `tests/integration/receipt-committed.test.ts`, `demo/agent/test/run.test.ts` | @@ -500,17 +500,17 @@ real funds. | **an A2A request sent without an `id`, as a notification** | `-32600`; nothing runs | `tests/conformance/a2a/errors.test.ts` | | **an x402 A2A extension payment whose `contextId` is not the task's** | `-32602`; the task stays pending | `tests/integration/a2a-x402-extension.test.ts` | | **an A2A `GetTask` naming a pending x402 task** | the task as sent, with its x402 metadata; the task stays payable | `tests/integration/a2a-x402-extension.test.ts` | -| **a guessed or sequential A2A task id** | task and context ids use `randomUUID()` independently of `IdGenerator`; the adapter does not add them as dedicated log fields. Unknown ids and another protocol's tasks both get `-32001` | `tests/unit/protocols-a2a/pipeline-mapping.test.ts`, `tests/conformance/a2a/tasks.test.ts` | -| **an A2A `ListTasks` without a context, or naming another buyer's** | an omitted or empty context returns no tasks; a random context id acts as an access key, and each page contains only that context's tasks | `tests/conformance/a2a/tasks.test.ts` | -| **an A2A `CancelTask` raced against a payment message on one task** | both use the same atomic take; only the call that takes the pending purchase proceeds. If cancellation wins, no payment is verified or settled; if payment wins, cancellation returns `-32002` | `tests/unit/protocols-a2a/pending-store.test.ts` (concurrent calls with SQLite and memory), `tests/integration/a2a-x402-extension.test.ts` | -| **an A2A payment message on a retained canceled or finished task** | `-32004` before verification; nothing settles and the backend is not called | `tests/integration/a2a-x402-extension.test.ts`, `tests/conformance/a2a/tasks.test.ts` | -| **free A2A calls filling task retention to push out a paid result** | at capacity, the store refuses new records and permits replacements without evicting unexpired records; a new x402 extension purchase gets `GATEWAY_BUSY` without a pending hold, while other responses are returned without retention | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/task-store.test.ts`, `tests/unit/gateway/main.test.ts` | -| **a payment proof, an AP2 mandate or the request input in a stored A2A task** | the adapter does not separately attach request input, payment proofs or AP2 mandates; merchant response content is retained without redaction | `tests/unit/protocols-a2a/pending-store.test.ts` ("keeps no payment proof, mandate or request input in any task record") | -| **an A2A task read after its retention ends** | `GetTask` returns `-32001` and `ListTasks` omits the record; writable SQLite stores delete expired records during initialization and before storing a record | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/task-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | -| **an A2A payment or background task interrupted before its result is recorded** | a stored working task absent from the local running set is reported as failed with `INTERNAL_ERROR`; the message tells the buyer to check with the merchant before paying again. A retry that reaches an existing reserved payment attempt gets `PAYMENT_REPLAYED` before another settlement. This assumes one gateway per receipt store | `tests/conformance/a2a/tasks.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts` | -| **A2A `returnImmediately` calls outliving the gateway mount's request limit** | each adapter has 20 background slots. If none is free, a new purchase gets a failed `GATEWAY_BUSY` task and a payment submission gets `-32603` with a retry delay, both before payment verification, settlement or backend execution; the refused submission leaves its pending purchase payable. Graceful shutdown waits for started background work before closing the store | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/background.test.ts` | +| **a guessed or sequential A2A task id** | task and context ids use `randomUUID()` independently of `IdGenerator`; the adapter does not add them as dedicated log fields. Unknown ids and another protocol's tasks both get `-32001` | `tests/unit/protocols-a2a/pipeline-mapping.test.ts`, `tests/conformance/a2a/tasks.test.ts` | +| **an A2A `ListTasks` without a context, or naming another buyer's** | an omitted or empty context returns no tasks; a random context id acts as an access key, and each page contains only that context's tasks | `tests/conformance/a2a/tasks.test.ts` | +| **an A2A `CancelTask` raced against a payment message on one task** | both use the same atomic take; only the call that takes the pending purchase proceeds. If cancellation wins, no payment is verified or settled; if payment wins, cancellation returns `-32002` | `tests/unit/protocols-a2a/pending-store.test.ts` (concurrent calls with SQLite and memory), `tests/integration/a2a-x402-extension.test.ts` | +| **an A2A payment message on a retained canceled or finished task** | `-32004` before verification; nothing settles and the backend is not called | `tests/integration/a2a-x402-extension.test.ts`, `tests/conformance/a2a/tasks.test.ts` | +| **unpaid A2A calls filling task retention to push out a paid result or block purchases** | at capacity, eligible uncharged responses are evicted to admit new records. Paid or uncertain outcomes and waiting or working tasks are protected. If protected records fill storage, a new x402 extension purchase gets `GATEWAY_BUSY` without a pending hold; other blocking responses are returned without retention. See [A2A tasks](protocols/a2a.md#tasks) for eviction criteria | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/pipeline-mapping.test.ts`, `tests/unit/protocols-a2a/task-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts`, `tests/unit/gateway/main.test.ts` | +| **a payment proof, an AP2 mandate or the request input in a stored A2A task** | the adapter does not separately attach request input, payment proofs or AP2 mandates; merchant response content is retained without redaction | `tests/unit/protocols-a2a/pending-store.test.ts` ("keeps no payment proof, mandate or request input in any task record") | +| **an A2A task read after its retention ends** | `GetTask` returns `-32001` and `ListTasks` omits the record; writable SQLite stores delete expired records during initialization and before storing a record | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/task-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | +| **an A2A payment or background task interrupted before its result is recorded** | a stored working task absent from the local running set is reported as failed with `INTERNAL_ERROR`; the message tells the buyer to check with the merchant before paying again. A retry that reaches an existing reserved payment attempt gets `PAYMENT_REPLAYED` before another settlement. This assumes one gateway per receipt store | `tests/conformance/a2a/tasks.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts` | +| **A2A `returnImmediately` calls outliving the gateway mount's request limit** | each adapter has 20 background slots. If none is free, a new purchase gets a failed `GATEWAY_BUSY` task and a payment submission gets `-32603` with a retry delay, both before payment verification, settlement or backend execution; the refused submission leaves its pending purchase payable. Graceful shutdown waits for started background work before closing the store | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/background.test.ts` | | **the x402 A2A extension requested under only one header name** | `A2A-Extensions` or `X-A2A-Extensions` must list the exact URI to activate the extension; other URIs do not activate it. Responses whose task status message names the extension echo the URI under both headers; MPP tasks and JSON-RPC errors carry neither | `tests/integration/a2a-x402-extension.test.ts`, `tests/unit/protocols-a2a/x402-extension.test.ts` | -| **an Agent Card publishing an unencrypted public endpoint** | with A2A enabled, `doctor` warns about an HTTP `merchant.publicBaseUrl` unless the host is loopback; 2.x config still accepts the URL | `tests/unit/cli/doctor.test.ts` | +| **an Agent Card publishing an unencrypted public endpoint** | with A2A enabled, `doctor` warns about an HTTP `merchant.publicBaseUrl` unless the host is loopback; 2.x config still accepts the URL | `tests/unit/cli/doctor.test.ts` | | **an A2A 0.x follow-up, with a non-user role, on a pending task** | `-32602`; the task stays pending | same | | **an A2A message carrying a large array of invalid parts or task references** | refused by its length (`PROTOCOL_UNSUPPORTED`) before any element is validated, so no validation issue is built per element | `tests/unit/protocols-a2a/message-mapping.test.ts` | | **an A2A field sent under its proto and JSON names, such as `context_id` beside `contextId`** | `-32602` identifies both spellings before task-store reads or backend calls | `tests/conformance/a2a/params.test.ts` | diff --git a/src/protocols/a2a/adapter.ts b/src/protocols/a2a/adapter.ts index 6d61f2d..9499b61 100644 --- a/src/protocols/a2a/adapter.ts +++ b/src/protocols/a2a/adapter.ts @@ -78,6 +78,7 @@ import { } from './params'; import { BACKGROUND_FULL, type PaymentResume, resumePayment, taskResult } from './payment-resume'; import { + chargedNothing, completedTask, failedTask, inputRequired, @@ -134,8 +135,8 @@ export interface A2aAdapterOptions { /** * Task retention in hours (default 24, range 1 to 8760) and the limit on * unexpired records when admitting new tasks (default 1000, range 1 to - * 1,000,000). At capacity, new records are refused and replacements allowed; - * existing records are not evicted. + * 1,000,000). At capacity, a new record evicts eligible uncharged responses + * or is refused if too few are available. Existing IDs can still be replaced. */ readonly tasks?: { readonly retentionHours?: number; readonly maxRetained?: number }; } @@ -506,7 +507,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { return { context, pendingPayments: ops.pendingPayments, - keep: (task) => this.keep(ops, task), + keep: (task, evictable) => this.keep(ops, task, evictable), running: this.running, background, recordWorking: (task) => this.recordWorking(ops, task), @@ -519,10 +520,10 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { // Retain a response without failing the call. Log capacity refusals at warn // and write exceptions at error; return false in either case. - private async keep(ops: TaskOperations, task: A2aTask): Promise { + private async keep(ops: TaskOperations, task: A2aTask, evictable: boolean): Promise { const logger = this.context?.logger; try { - if (await ops.tasks.put(task, ops.retainedUntil())) return true; + if (await ops.tasks.put(task, ops.retainedUntil(), evictable)) return true; logger?.warn( { state: task.status.state }, 'a2a adapter: task not retained: the task store is full', @@ -608,7 +609,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { ), now(), ); - await this.keep(ops, unknown); + await this.keep(ops, unknown, true); return taskResult(id, unknown); } const run = () => this.purchase(ops, context, ids, invocation, resource, x402Extension); @@ -649,6 +650,8 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { const now = (): TaskIdentity => ({ ...ids, timestamp: context.clock.nowIso() }); const requestId = context.ids.next('a2a'); let task: A2aTask; + let evictable = true; + let proofSent = false; // Reserved-field extraction sits inside the try: a malformed // `_authorization` envelope becomes a failed task like any other outcome try { @@ -657,6 +660,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { resource, requestId, ); + proofSent = payment !== undefined; const request: CanonicalRequest = { requestId, resourceId: invocation.resourceId, @@ -670,6 +674,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { const identity = now(); if (outcome.kind !== 'payment-required') { task = completedTask(outcome, identity); + evictable = outcome.payment === undefined; } else { task = paymentRequiredTask(outcome, identity); const envelope = outcome.requirement.challenge.envelope; @@ -701,8 +706,9 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { 'a2a adapter: execution failed', ); task = failedTask(error, now()); + evictable = chargedNothing(error, proofSent); } - await this.keep(ops, task); + await this.keep(ops, task, evictable); return task; } @@ -731,7 +737,7 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { ), identity, ); - await this.keep(ops, busy); + await this.keep(ops, busy, true); return busy; } return waiting; diff --git a/src/protocols/a2a/payment-resume.ts b/src/protocols/a2a/payment-resume.ts index a1c3f97..de04ab8 100644 --- a/src/protocols/a2a/payment-resume.ts +++ b/src/protocols/a2a/payment-resume.ts @@ -14,6 +14,7 @@ import { retryInfo, } from './jsonrpc'; import { + chargedNothing, completedTask, failedTask, type TaskIdentity, @@ -43,8 +44,11 @@ export function taskResult(id: JsonRpcId, task: A2aTask): Record Promise; + /** + * Retain the response with its eviction flag. Log write failures and + * return false instead of throwing. + */ + readonly keep: (task: A2aTask, evictable: boolean) => Promise; /** Active task ids, including blocking payments and background runs */ readonly running: Set; readonly background: BackgroundRuns; @@ -137,7 +141,7 @@ export async function resumePayment( context.ids.next('a2a-msg'), paymentRejectedMetadata(), ); - await resume.keep(declined); + await resume.keep(declined, true); return taskResult(id, declined); } @@ -151,7 +155,7 @@ export async function resumePayment( // Add the running entry before publishing the working record resume.running.add(taskId); if (!immediate) { - await resume.keep(working); + await resume.keep(working, false); } else { // Require a working record before background payment processing. The // purchase has been taken, but payment verification has not started. @@ -159,20 +163,21 @@ export async function resumePayment( if (refused !== undefined) { resume.running.delete(taskId); resume.background.release(); + // Verification has not started, so this failure is uncharged and evictable const failed = failedTask(refused, { ...ids, timestamp: context.clock.nowIso() }); - await resume.keep(failed); + await resume.keep(failed, true); return taskResult(id, failed); } } const pay = async (): Promise => { try { - const paid = await payPending( + const { task: paid, evictable } = await payPending( context, { ...taken, ...(authorization !== undefined ? { authorization } : {}) }, submission.payload, ids, ); - await resume.keep(paid); + await resume.keep(paid, evictable); return paid; } finally { resume.running.delete(taskId); @@ -198,14 +203,14 @@ function withoutRetryDelay(error: CommerceError): CommerceError { }); } -// Execute the pending purchase with the submitted x402 PaymentPayload. -// Timestamp the returned task when payment processing ends. +// Execute the submitted x402 PaymentPayload and timestamp the task when +// processing ends. Mark it evictable only when this request charged nothing. async function payPending( context: ProtocolAdapterContext, pending: PendingPayment, payload: Record, ids: Omit, -): Promise { +): Promise<{ readonly task: A2aTask; readonly evictable: boolean }> { const requestId = context.ids.next('a2a'); const request: CanonicalRequest = { requestId, @@ -225,12 +230,13 @@ async function payPending( const outcome = await context.pipeline.execute(request); if (outcome.kind === 'delivered' && outcome.payment !== undefined) { const identity = { ...ids, timestamp: context.clock.nowIso() }; - return withStatusMessage( + const task = withStatusMessage( completedTask(outcome, identity), 'Payment settled.', identity.statusMessageId, paymentCompletedMetadata(outcome.payment), ); + return { task, evictable: false }; } // A proof was sent, so neither a free delivery nor a new challenge is a // payment this task can report @@ -258,5 +264,8 @@ async function payPending( : 'The resource could not be delivered'; text = `${outcome}: ${String(metadata[X402_PAYMENT_ERROR_KEY])}.`; } - return withStatusMessage(failedTask(error, identity), text, identity.statusMessageId, metadata); + return { + task: withStatusMessage(failedTask(error, identity), text, identity.statusMessageId, metadata), + evictable: chargedNothing(error, true), + }; } diff --git a/src/protocols/a2a/task-mapping.ts b/src/protocols/a2a/task-mapping.ts index a21c77c..892238c 100644 --- a/src/protocols/a2a/task-mapping.ts +++ b/src/protocols/a2a/task-mapping.ts @@ -151,6 +151,32 @@ export function failedTask(error: CommerceError, identity: TaskIdentity): A2aTas ); } +// Refusals raised before settlement. Mandate checks also precede the +// payment attempt reservation. +const UNCHARGED_CODES: ReadonlySet = new Set([ + 'RESOURCE_NOT_FOUND', + 'INPUT_INVALID', + 'PAYMENT_INVALID', + 'PAYMENT_REPLAYED', + 'AUTHORIZATION_REQUIRED', + 'AUTHORIZATION_INVALID', + 'AUTHORIZATION_REPLAYED', + 'AUTHORIZATION_PROVIDER_UNAVAILABLE', +]); + +/** + * Whether a failed task can be evicted without discarding a paid result. + * A request without a payment proof or with a listed refusal is uncharged. + * Backend failures are evictable only without `details.payment`, which the + * pipeline attaches after upfront settlement; the `authorization` flow + * abandons settlement when the backend fails. + */ +export function chargedNothing(error: CommerceError, proofSent: boolean): boolean { + if (!proofSent || UNCHARGED_CODES.has(error.code)) return true; + const backend = error.code === 'BACKEND_ERROR' || error.code === 'BACKEND_TIMEOUT'; + return backend && error.details?.['payment'] === undefined; +} + /** A task whose execution is still in progress */ export function workingTask(taskId: string, contextId: string, timestamp: string): A2aTask { return { diff --git a/src/protocols/a2a/task-operations.ts b/src/protocols/a2a/task-operations.ts index 17fbf5b..ca1d3d9 100644 --- a/src/protocols/a2a/task-operations.ts +++ b/src/protocols/a2a/task-operations.ts @@ -126,7 +126,8 @@ export async function cancelTask( ); // The pending purchase is already removed. If this write fails, the caller // gets an internal error and the old response keeps its original expiry. - if (!(await ops.tasks.put(canceled, ops.retainedUntil()))) { + // Nothing was charged, so the record is evictable. + if (!(await ops.tasks.put(canceled, ops.retainedUntil(), true))) { throw new CommerceError('STORAGE_ERROR', 'The canceled task did not fit in the task store.'); } return jsonRpcResult(id, canceled); diff --git a/src/protocols/a2a/task-store.ts b/src/protocols/a2a/task-store.ts index 22f98ea..46cd99a 100644 --- a/src/protocols/a2a/task-store.ts +++ b/src/protocols/a2a/task-store.ts @@ -3,9 +3,10 @@ * * Use the receipt store's complete task-record group, or process memory under * the same capacity and expiry rules. A durable store can preserve records - * across restarts; process memory cannot. At capacity, refuse new records and - * allow replacements without evicting unexpired paid results. These response - * records are separate from the pending state that permits payment. + * across restarts; process memory cannot. At capacity, evict eligible + * uncharged responses to admit new records, or refuse a new record if too few + * can be evicted. Existing IDs can still be replaced. Response records are + * separate from the pending state that permits payment. */ import type { Clock } from '../../core'; import type { StoreGroupMethods } from '../../core/store-method-groups'; @@ -13,10 +14,11 @@ import type { A2aTask } from './types'; export interface A2aTaskStore { /** - * Retain the task until `expiresAt`, replacing any record with the same id. - * Return false without storing a new id when the store is full. + * Store the task with `expiresAt`, replacing an existing ID even at capacity. + * Mark uncharged responses `evictable` to allow early eviction. Return false + * if too few records are evictable to admit a new ID. */ - put(task: A2aTask, expiresAt: string): Promise; + put(task: A2aTask, expiresAt: string, evictable?: boolean): Promise; get(id: string): Promise; /** Unexpired tasks in the named context, with no ordering guarantee */ list(contextId: string): Promise; @@ -28,7 +30,7 @@ export function createStoredTasks( maxRecords: number, ): A2aTaskStore { return { - put: (task, expiresAt) => + put: (task, expiresAt, evictable) => store.putTaskRecord( { id: task.id, @@ -38,6 +40,7 @@ export function createStoredTasks( updatedAt: task.status.timestamp, document: task as unknown as Readonly>, expiresAt, + ...(evictable === true ? { evictable } : {}), }, { maxRecords }, ), @@ -55,17 +58,33 @@ export function createStoredTasks( /** Retain tasks in a map owned by this process */ export function createMemoryTasks(clock: Clock, maxRecords: number): A2aTaskStore { - const tasks = new Map(); + // Map order is write order: a replacement is deleted and set again + const tasks = new Map< + string, + { readonly task: A2aTask; readonly expiresAtMs: number; readonly evictable: boolean } + >(); const live = (expiresAtMs: number): boolean => expiresAtMs > clock.now().getTime(); return { - async put(task, expiresAt) { - // Sweep expired records when capacity would block a new id + async put(task, expiresAt, evictable = false) { + // Sweep expired records, then the earliest written evictable one, when + // capacity would block a new id if (!tasks.has(task.id) && tasks.size >= maxRecords) { for (const [id, held] of tasks) if (!live(held.expiresAtMs)) tasks.delete(id); - if (tasks.size >= maxRecords) return false; + if (tasks.size >= maxRecords) { + let oldest: string | undefined; + for (const [id, held] of tasks) { + if (held.evictable) { + oldest = id; + break; + } + } + if (oldest === undefined) return false; + tasks.delete(oldest); + } } - tasks.set(task.id, { task, expiresAtMs: Date.parse(expiresAt) }); + tasks.delete(task.id); + tasks.set(task.id, { task, expiresAtMs: Date.parse(expiresAt), evictable }); return true; }, async get(id) { diff --git a/tests/unit/protocols-a2a/pending-store.test.ts b/tests/unit/protocols-a2a/pending-store.test.ts index cd8a1fe..0ecc3dc 100644 --- a/tests/unit/protocols-a2a/pending-store.test.ts +++ b/tests/unit/protocols-a2a/pending-store.test.ts @@ -986,6 +986,83 @@ describe('tasks finished in the background with returnImmediately', () => { }); }); +describe('a task store full of answers nothing was charged for', () => { + it('evicts them for a waiting purchase, a background run and a paid answer, but not those', async () => { + const node = await boot(undefined, { maxRetained: 3 }); + const send = async (configuration?: Record, resource = 'report') => + ( + await call(node, 'SendMessage', { + message: buy(resource), + ...(configuration ? { configuration } : {}), + }) + ).result?.task as A2aTask; + const unpaid = [await send(undefined, 'missing'), await send(), await send(IMMEDIATELY)]; + // The background run's working record becomes evictable when it ends unpaid + await vi.waitFor(async () => + expect(await stateOf(node, unpaid[2]?.id as string)).toBe('TASK_STATE_FAILED'), + ); + + const waiting = await challenged(node, 'report'); + const working = (await buyNow(node, 'proof-1')).result?.task as A2aTask; + expect(working.status.state).toBe('TASK_STATE_WORKING'); + await vi.waitFor(async () => + expect(await stateOf(node, working.id)).toBe('TASK_STATE_COMPLETED'), + ); + const paid = ( + await call(node, 'SendMessage', { message: buy('report', { _payment: 'proof-2' }) }) + ).result?.task as A2aTask; + + expect(paid.status.state).toBe('TASK_STATE_COMPLETED'); + for (const task of unpaid) { + expect((await call(node, 'GetTask', { id: task.id })).error?.code).toBe(TASK_NOT_FOUND); + } + // A store full of waiting and paid records admits nothing new + const refused = await send(undefined, 'missing'); + const busy = (await rpc(node, buy('report'))).result?.task; + expect((await call(node, 'GetTask', { id: refused.id })).error?.code).toBe(TASK_NOT_FOUND); + expect(code(busy)).toBe('GATEWAY_BUSY'); + expect(await stateOf(node, waiting.id)).toBe('TASK_STATE_INPUT_REQUIRED'); + expect(await stateOf(node, paid.id)).toBe('TASK_STATE_COMPLETED'); + expect(await stateOf(node, working.id)).toBe('TASK_STATE_COMPLETED'); + }); + + it('marks extension tasks evictable only when nothing was charged for them', async () => { + const node = await boot(); + const evictable = async (id: string) => (await node.store.getTaskRecord?.(id))?.evictable; + const waiting = await challenged(node, 'report'); + const declined = await challenged(node, 'report'); + const canceled = await challenged(node, 'report'); + const replayed = await challenged(node, 'report'); + expect(await evictable(waiting.id)).toBeUndefined(); + + await rpc(node, pay(waiting, 'nonce-1')); + await rpc(node, decline(declined)); + await call(node, 'CancelTask', { id: canceled.id }); + const failed = (await rpc(node, pay(replayed, 'nonce-1'))).result?.task; + + expect(await stateOf(node, waiting.id)).toBe('TASK_STATE_COMPLETED'); + expect(code(failed)).toBe('PAYMENT_REPLAYED'); + expect({ + paid: await evictable(waiting.id), + declined: await evictable(declined.id), + canceled: await evictable(canceled.id), + replayed: await evictable(replayed.id), + }).toEqual({ paid: undefined, declined: true, canceled: true, replayed: true }); + expect(calls.settle).toBe(1); + }); + + it('marks the busy answer that replaces a waiting task evictable when no payment can be held', async () => { + const node = await boot((store) => + Object.assign(Object.create(store) as ReceiptStore, { putPendingTask: async () => false }), + ); + + const busy = (await rpc(node, buy('report'))).result?.task as A2aTask; + + expect(code(busy)).toBe('GATEWAY_BUSY'); + expect((await node.store.getTaskRecord?.(busy.id))?.evictable).toBe(true); + }); +}); + describe('a store without the pending-task methods', () => { const noTasks = (store: ReceiptStore): ReceiptStore => Object.assign(Object.create(store) as ReceiptStore, { diff --git a/tests/unit/protocols-a2a/pipeline-mapping.test.ts b/tests/unit/protocols-a2a/pipeline-mapping.test.ts index bffa537..9c27e78 100644 --- a/tests/unit/protocols-a2a/pipeline-mapping.test.ts +++ b/tests/unit/protocols-a2a/pipeline-mapping.test.ts @@ -18,6 +18,7 @@ import type { ProtocolAdapterContext, ReceiptStore, ResourceRegistry, + TaskRecord, } from '../../../src/core'; import { CommerceError, DELIVERY_SUMMARY_META_KEY, PAYMENT_INPUT_FIELD } from '../../../src/core'; import { createResourceRegistry } from '../../../src/core/execution'; @@ -383,21 +384,93 @@ describe('A2A adapter is not a client of anything', () => { }); }); +describe('the task record of a blocking answer', () => { + const PROOF = { [PAYMENT_INPUT_FIELD]: 'base64-proof' }; + const charged = { payment: { status: 'settled', provider: 'x402' } }; + const paidDelivery = { + ...delivered, + payment: { status: 'settled', provider: 'x402', amount: '0.01', currency: 'USDC' }, + } as ExecutionOutcome; + const fail = (code: CommerceError['code'], details?: Record) => + new CommerceError(code, 'refused', details ? { details } : {}); + + // Evictable only when nothing was charged for the answer + it.each([ + ['a free delivery', true, delivered, {}], + ['a paid delivery', false, paidDelivery, PROOF], + ['a payment-required answer', true, paymentRequired, {}], + ['a failure without a proof', true, fail('BACKEND_ERROR'), {}], + ['a proof the provider rejected', true, fail('PAYMENT_INVALID'), PROOF], + ['a replayed proof', true, fail('PAYMENT_REPLAYED'), PROOF], + ['input refused before pricing', true, fail('INPUT_INVALID'), PROOF], + ['a refused mandate', true, fail('AUTHORIZATION_INVALID'), PROOF], + ['a missing mandate', true, fail('AUTHORIZATION_REQUIRED'), PROOF], + ['a backend failure that abandoned settlement', true, fail('BACKEND_TIMEOUT'), PROOF], + ['a backend failure after an upfront settlement', false, fail('BACKEND_ERROR', charged), PROOF], + ['a failed settlement', false, fail('PAYMENT_SETTLEMENT_FAILED'), PROOF], + ['a provider outage after a proof', false, fail('PAYMENT_PROVIDER_UNAVAILABLE'), PROOF], + ] as const)('marks %s evictable: %s', async (_label, evictable, outcome, input) => { + const written: TaskRecord[] = []; + const store = { + putTaskRecord: async (record: TaskRecord) => written.push(record) > 0, + getTaskRecord: async () => undefined, + listTaskRecords: async () => [], + } as unknown as ReceiptStore; + const adapter = createA2aAdapter({ store }); + await adapter.start(setup(outcome).context); + + await send(adapter, { resource: 'market_report', input }); + + expect(written.map((record) => record.evictable === true)).toEqual([evictable]); + }); + + it('marks an unknown resource evictable', async () => { + const written: TaskRecord[] = []; + const store = { + putTaskRecord: async (record: TaskRecord) => written.push(record) > 0, + getTaskRecord: async () => undefined, + listTaskRecords: async () => [], + } as unknown as ReceiptStore; + const adapter = createA2aAdapter({ store }); + await adapter.start(setup().context); + + await send(adapter, { resource: 'no_such_resource', input: PROOF }); + + expect(written.map((record) => record.evictable)).toEqual([true]); + }); +}); + describe('an answered task the store does not keep', () => { function getTask(id: string): string { return JSON.stringify({ jsonrpc: '2.0', id: 'req-2', method: 'GetTask', params: { id } }); } - function loggingSetup() { - const { context } = setup(); + function loggingSetup(outcome: ExecutionOutcome = delivered) { + const { context } = setup(outcome); const warn = vi.fn(); const error = vi.fn(); const logger: Logger = { ...NOOP_LOGGER, warn, error }; return { context: { ...context, logger }, warn, error }; } - it('is returned but not kept when the store is full, and the gateway logs a warning', async () => { - const { context, warn } = loggingSetup(); + const paidDelivery: ExecutionOutcome = { + ...delivered, + payment: { status: 'settled', provider: 'x402', amount: '0.01', currency: 'USDC' }, + } as ExecutionOutcome; + + it('replaces the oldest free answer with a new one when the store is full', async () => { + const adapter = createA2aAdapter({ tasks: { maxRetained: 1 } }); + await adapter.start(setup().context); + const first = task(await send(adapter, { resource: 'market_report', input: {} })); + + const second = task(await send(adapter, { resource: 'market_report', input: {} })); + + expect((await post(adapter, getTask(first.id))).body.error?.code).toBe(-32001); + expect((await post(adapter, getTask(second.id))).body.result).toEqual(second); + }); + + it('is returned but not kept when paid answers fill the store, and the gateway logs a warning', async () => { + const { context, warn } = loggingSetup(paidDelivery); const adapter = createA2aAdapter({ tasks: { maxRetained: 1 } }); await adapter.start(context); const kept = task(await send(adapter, { resource: 'market_report', input: {} })); diff --git a/tests/unit/protocols-a2a/task-store.test.ts b/tests/unit/protocols-a2a/task-store.test.ts index 0ce46fc..45b885d 100644 --- a/tests/unit/protocols-a2a/task-store.test.ts +++ b/tests/unit/protocols-a2a/task-store.test.ts @@ -80,6 +80,35 @@ describe('createMemoryTasks', () => { expect(await tasks.put(task('b'), at(5000))).toBe(true); expect(await tasks.get('b')).toEqual(task('b')); }); + + it('evicts the earliest written evictable task at the cap, then refuses', async () => { + const tasks = createMemoryTasks(createClock().clock, 3); + await tasks.put(task('free-1'), at(1000), true); + await tasks.put(task('paid'), at(1000)); + await tasks.put(task('free-2'), at(1000), true); + + expect(await tasks.put(task('next'), at(1000))).toBe(true); + expect(await tasks.get('free-1')).toBeUndefined(); + expect(await tasks.put(task('last'), at(1000), true)).toBe(true); + expect(await tasks.get('free-2')).toBeUndefined(); + // `last` is evictable, then nothing is + expect(await tasks.put(task('one-more'), at(1000))).toBe(true); + expect(await tasks.put(task('refused'), at(1000), true)).toBe(false); + expect(await tasks.get('paid')).toEqual(task('paid')); + }); + + it('counts a replacement as a new write, and takes its evictable flag', async () => { + const tasks = createMemoryTasks(createClock().clock, 2); + await tasks.put(task('a', 'context-1', 'TASK_STATE_WORKING'), at(1000), true); + await tasks.put(task('b'), at(1000), true); + await tasks.put(task('a'), at(1000), true); + + // `b` is now the earliest written + expect(await tasks.put(task('c'), at(1000))).toBe(true); + expect(await tasks.get('b')).toBeUndefined(); + await tasks.put(task('a'), at(1000)); + expect(await tasks.put(task('d'), at(1000))).toBe(false); + }); }); describe('createStoredTasks', () => { From 91522403feb65302c1273ffeba2d89d49a54b40f Mon Sep 17 00:00:00 2001 From: Revinand Date: Mon, 23 Nov 2026 16:50:24 +0100 Subject: [PATCH 17/17] fix(a2a): echo the x402 extension on every result to an activating request --- docs/protocols/a2a.md | 17 +++-- docs/security.md | 2 +- src/protocols/a2a/adapter.ts | 14 ++-- src/protocols/a2a/payment-resume.ts | 9 ++- tests/integration/a2a-x402-extension.test.ts | 67 ++++++++++++++++---- 5 files changed, 84 insertions(+), 25 deletions(-) diff --git a/docs/protocols/a2a.md b/docs/protocols/a2a.md index d589f2a..8335e19 100644 --- a/docs/protocols/a2a.md +++ b/docs/protocols/a2a.md @@ -111,10 +111,11 @@ parts. This gateway uses the A2A 1.0 forms: `TASK_STATE_INPUT_REQUIRED`, as optional, with `params: { "x402Version": 2 }`, when x402 is a skill's selected payment rail. -Responses echo the extension URI under both header names when the task's status -message lists the extension. This includes input-required tasks, payment -responses even when the request omits activation headers, and `GetTask` reads -of those tasks. MPP tasks and JSON-RPC errors carry neither header. For origins +Every result to a request that activates the extension echoes its URI under +both header names, whatever rail the task uses. A task whose status message +lists the extension echoes it even without activation headers: a payment +response, or a `GetTask` read of such a task. JSON-RPC errors carry neither +header. For origins in `server.allowedOrigins`, CORS permits both request headers and exposes both response headers to browser code. Extension status messages carry `contextId`, `taskId`, `extensions: []` and `x402.payment.*` metadata. @@ -302,9 +303,11 @@ A `SendMessage` that names a task gets these answers: With `configuration.returnImmediately: true`, `SendMessage` stores and returns a `TASK_STATE_WORKING` task without waiting for the purchase result. `GetTask` and `ListTasks` expose the result once recorded: a finished task or -one waiting for an x402 extension payment. The option also lets a payment -submission run in the background. Declined payments and unknown resources -still return failed tasks immediately. +one waiting for an x402 extension payment. Payment submissions can also run +in the background. Their working tasks carry +`x402.payment.status: payment-submitted` in the status message metadata, and +the HTTP response echoes the extension. Declined payments and unknown +resources still return failed tasks immediately. Background work can outlive its HTTP request, so each adapter has a separate limit of 20 background slots. Startup refusals happen before payment diff --git a/docs/security.md b/docs/security.md index a0459ca..a9e5347 100644 --- a/docs/security.md +++ b/docs/security.md @@ -509,7 +509,7 @@ real funds. | **an A2A task read after its retention ends** | `GetTask` returns `-32001` and `ListTasks` omits the record; writable SQLite stores delete expired records during initialization and before storing a record | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/task-store.test.ts`, `tests/unit/storage-receipts/conformance.test.ts` | | **an A2A payment or background task interrupted before its result is recorded** | a stored working task absent from the local running set is reported as failed with `INTERNAL_ERROR`; the message tells the buyer to check with the merchant before paying again. A retry that reaches an existing reserved payment attempt gets `PAYMENT_REPLAYED` before another settlement. This assumes one gateway per receipt store | `tests/conformance/a2a/tasks.test.ts`, `tests/unit/protocols-a2a/pending-store.test.ts` | | **A2A `returnImmediately` calls outliving the gateway mount's request limit** | each adapter has 20 background slots. If none is free, a new purchase gets a failed `GATEWAY_BUSY` task and a payment submission gets `-32603` with a retry delay, both before payment verification, settlement or backend execution; the refused submission leaves its pending purchase payable. Graceful shutdown waits for started background work before closing the store | `tests/unit/protocols-a2a/pending-store.test.ts`, `tests/unit/protocols-a2a/background.test.ts` | -| **the x402 A2A extension requested under only one header name** | `A2A-Extensions` or `X-A2A-Extensions` must list the exact URI to activate the extension; other URIs do not activate it. Responses whose task status message names the extension echo the URI under both headers; MPP tasks and JSON-RPC errors carry neither | `tests/integration/a2a-x402-extension.test.ts`, `tests/unit/protocols-a2a/x402-extension.test.ts` | +| **the x402 A2A extension requested under only one header name** | `A2A-Extensions` or `X-A2A-Extensions` must list the exact URI to activate the extension; other URIs do not activate it. An activated request's JSON-RPC result echoes the URI under both headers for any payment rail. Task results marked with the extension also echo it without an activation header. JSON-RPC errors echo neither header | `tests/integration/a2a-x402-extension.test.ts`, `tests/unit/protocols-a2a/x402-extension.test.ts` | | **an Agent Card publishing an unencrypted public endpoint** | with A2A enabled, `doctor` warns about an HTTP `merchant.publicBaseUrl` unless the host is loopback; 2.x config still accepts the URL | `tests/unit/cli/doctor.test.ts` | | **an A2A 0.x follow-up, with a non-user role, on a pending task** | `-32602`; the task stays pending | same | | **an A2A message carrying a large array of invalid parts or task references** | refused by its length (`PROTOCOL_UNSUPPORTED`) before any element is validated, so no validation issue is built per element | `tests/unit/protocols-a2a/message-mapping.test.ts` | diff --git a/src/protocols/a2a/adapter.ts b/src/protocols/a2a/adapter.ts index 9499b61..ecfd002 100644 --- a/src/protocols/a2a/adapter.ts +++ b/src/protocols/a2a/adapter.ts @@ -387,16 +387,20 @@ export class A2aProtocolAdapter implements HttpProtocolAdapter { return; } + const activated = + requestsX402Extension(req.headers[A2A_EXTENSIONS_HEADER]) || + requestsX402Extension(req.headers[A2A_X_EXTENSIONS_HEADER]); const response = await this.dispatch( parsed.request.id, parsed.request.method, parsed.request.params, - requestsX402Extension(req.headers[A2A_EXTENSIONS_HEADER]) || - requestsX402Extension(req.headers[A2A_X_EXTENSIONS_HEADER]), + activated, ); - // Echo the extension when it shaped the task, even without the - // request header on a payment follow-up - this.writeJson(res, 200, response, usesX402Extension(response) ? X402_EXTENSION_ECHO : {}); + // Echo activation on JSON-RPC results for any rail (a2a-x402 v0.1 section 7). + // A task's extension marker also triggers the echo on payment follow-ups + // without activation headers. JSON-RPC errors do not echo activation. + const echo = usesX402Extension(response) || (activated && response['error'] === undefined); + this.writeJson(res, 200, response, echo ? X402_EXTENSION_ECHO : {}); } catch (err) { // Nothing from `err` reaches the client this.context?.logger.error({ err: toLogInfo(err) }, 'a2a adapter: request handling failed'); diff --git a/src/protocols/a2a/payment-resume.ts b/src/protocols/a2a/payment-resume.ts index de04ab8..cd44885 100644 --- a/src/protocols/a2a/payment-resume.ts +++ b/src/protocols/a2a/payment-resume.ts @@ -151,7 +151,14 @@ export async function resumePayment( artifactId: context.ids.next('a2a-artifact'), statusMessageId: context.ids.next('a2a-msg'), }; - const working = workingTask(taskId, taken.contextId, context.clock.nowIso()); + // Mark the payload received and tag the status message for the extension + // response headers (a2a-x402 v0.1 sections 6 and 7) + const working = withStatusMessage( + workingTask(taskId, taken.contextId, context.clock.nowIso()), + 'Payment received; processing it.', + context.ids.next('a2a-msg'), + { [X402_PAYMENT_STATUS_KEY]: 'payment-submitted' }, + ); // Add the running entry before publishing the working record resume.running.add(taskId); if (!immediate) { diff --git a/tests/integration/a2a-x402-extension.test.ts b/tests/integration/a2a-x402-extension.test.ts index dc6b3de..eb6c79d 100644 --- a/tests/integration/a2a-x402-extension.test.ts +++ b/tests/integration/a2a-x402-extension.test.ts @@ -507,19 +507,40 @@ describe('x402 A2A extension', () => { expect(body.error?.code).toBe(-32001); }); + // Echo the activated extension on JSON-RPC results regardless of payment rail it.each([ - ['a client that does not activate the extension', 'x402_report', false], - ['a resource paid with MPP', 'mpp_report', true], - ])('keeps the terminal payment-required task for %s', async (_label, resourceId, extension) => { - const { headers, body } = await rpc(buy(resourceId), extension); + ['a client that does not activate the extension', 'x402_report', false, [undefined, undefined]], + ['a resource paid with MPP', 'mpp_report', true, ECHO], + ])( + 'keeps the terminal payment-required task for %s', + async (_label, resourceId, extension, echo) => { + const { headers, body } = await rpc(buy(resourceId), extension); + + const task = body.result?.task; + expect(task?.status.state).toBe('TASK_STATE_FAILED'); + // The task message has no extension metadata or marker + expect(task?.status.message?.parts[0]?.text).toContain('Payment of 0.01 USDC is required'); + expect(task?.status.message).not.toHaveProperty('metadata'); + expect(task?.status.message).not.toHaveProperty('extensions'); + expect(echoed(headers)).toEqual(echo); + }, + ); - const task = body.result?.task; - expect(task?.status.state).toBe('TASK_STATE_FAILED'); - // A plain reason, with nothing from the extension and no echoed header - expect(task?.status.message?.parts[0]?.text).toContain('Payment of 0.01 USDC is required'); - expect(task?.status.message).not.toHaveProperty('metadata'); - expect(task?.status.message).not.toHaveProperty('extensions'); - expect(echoed(headers)).toEqual([undefined, undefined]); + it('echoes the extension on a purchase returned immediately, before its rail is known', async () => { + const { headers, body } = await call('SendMessage', { + message: buy('x402_report'), + configuration: { returnImmediately: true }, + }); + + const working = body.result?.task as A2aTask; + expect(working.status.state).toBe('TASK_STATE_WORKING'); + expect(echoed(headers)).toEqual(ECHO); + await vi.waitFor(async () => { + const read = await call('GetTask', { id: working.id }, false); + expect((read.body.result as unknown as A2aTask).status.state).toBe( + 'TASK_STATE_INPUT_REQUIRED', + ); + }); }); it.each([ @@ -574,6 +595,30 @@ describe('x402 A2A extension', () => { expect(echoed(headers)).toEqual(ECHO); }); + it('echoes the extension on a payment returned immediately, with payment-submitted', async () => { + const task = await challenged(); + + const { headers, body } = await call('SendMessage', { + message: pay(task, { + 'x402.payment.status': 'payment-submitted', + 'x402.payment.payload': await paymentPayload(task), + }), + configuration: { returnImmediately: true }, + }); + + const working = body.result?.task; + expect(working?.status.state).toBe('TASK_STATE_WORKING'); + expect(working?.status.message).toMatchObject({ + extensions: [A2A_X402_EXTENSION_URI], + metadata: { 'x402.payment.status': 'payment-submitted' }, + }); + expect(echoed(headers)).toEqual(ECHO); + await vi.waitFor(async () => { + const read = await call('GetTask', { id: task.id }); + expect((read.body.result as unknown as A2aTask).status.state).toBe('TASK_STATE_COMPLETED'); + }); + }); + it('names the version when the payload is x402 v1', async () => { const task = await challenged();