@nevermined-io/payments 1.0.8 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +7 -14
  2. package/dist/a2a/paymentsClient.d.ts +2 -2
  3. package/dist/a2a/paymentsClient.d.ts.map +1 -1
  4. package/dist/a2a/paymentsClient.js +7 -7
  5. package/dist/a2a/paymentsClient.js.map +1 -1
  6. package/dist/a2a/server.d.ts.map +1 -1
  7. package/dist/a2a/server.js +45 -26
  8. package/dist/a2a/server.js.map +1 -1
  9. package/dist/a2a/types.d.ts +6 -0
  10. package/dist/a2a/types.d.ts.map +1 -1
  11. package/dist/a2a/types.js.map +1 -1
  12. package/dist/api/base-payments.d.ts +2 -1
  13. package/dist/api/base-payments.d.ts.map +1 -1
  14. package/dist/api/base-payments.js +11 -3
  15. package/dist/api/base-payments.js.map +1 -1
  16. package/dist/common/types.d.ts +13 -0
  17. package/dist/common/types.d.ts.map +1 -1
  18. package/dist/common/types.js.map +1 -1
  19. package/dist/environments.d.ts +7 -0
  20. package/dist/environments.d.ts.map +1 -1
  21. package/dist/environments.js +13 -0
  22. package/dist/environments.js.map +1 -1
  23. package/dist/index.d.ts +3 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +2 -0
  26. package/dist/index.js.map +1 -1
  27. package/dist/payments.d.ts.map +1 -1
  28. package/dist/payments.js +10 -2
  29. package/dist/payments.js.map +1 -1
  30. package/dist/x402/express/middleware.d.ts.map +1 -1
  31. package/dist/x402/express/middleware.js +28 -19
  32. package/dist/x402/express/middleware.js.map +1 -1
  33. package/dist/x402/facilitator-api.d.ts +5 -4
  34. package/dist/x402/facilitator-api.d.ts.map +1 -1
  35. package/dist/x402/facilitator-api.js.map +1 -1
  36. package/dist/x402/index.d.ts +4 -0
  37. package/dist/x402/index.d.ts.map +1 -1
  38. package/dist/x402/index.js +3 -0
  39. package/dist/x402/index.js.map +1 -1
  40. package/dist/x402/visa-facilitator-api.d.ts +150 -0
  41. package/dist/x402/visa-facilitator-api.d.ts.map +1 -0
  42. package/dist/x402/visa-facilitator-api.js +206 -0
  43. package/dist/x402/visa-facilitator-api.js.map +1 -0
  44. package/dist/x402/visa-token-api.d.ts +53 -0
  45. package/dist/x402/visa-token-api.d.ts.map +1 -0
  46. package/dist/x402/visa-token-api.js +88 -0
  47. package/dist/x402/visa-token-api.js.map +1 -0
  48. package/package.json +1 -1
package/README.md CHANGED
@@ -45,7 +45,7 @@ Nevermined Payments integrates with the A2A protocol to authorize and charge per
45
45
 
46
46
  - Discovery: publish the Agent Card at `/.well-known/agent.json`.
47
47
  - Streaming and resubscribe: set `capabilities.streaming: true` for `message/stream` and `tasks/resubscribe`.
48
- - Authentication: credentials travel in HTTP headers (e.g., `Authorization: Bearer ...`), not in the JSON‑RPC payload.
48
+ - Authentication: credentials travel in HTTP headers (`payment-signature` header per X402 v2 spec), not in the JSON‑RPC payload.
49
49
  - Authorization/charging: the agent emits a final event with `metadata.creditsUsed`; Nevermined validates and burns credits accordingly.
50
50
 
51
51
  ### Payment extension required in the Agent Card
@@ -100,19 +100,15 @@ import { useEffect } from "react";
100
100
  import { Payments } from "@nevermined-io/payments";
101
101
 
102
102
  export default function Home() {
103
- const payments = new Payments({
103
+ const payments = Payments.getBrowserInstance({
104
104
  returnUrl: "http://localhost:8080",
105
- environment: "staging",
105
+ environment: "sandbox",
106
106
  });
107
107
 
108
108
  const onLogin = () => {
109
109
  payments.connect();
110
110
  };
111
111
 
112
- useEffect(() => {
113
- payments.init();
114
- }, []);
115
-
116
112
  return (
117
113
  <main>
118
114
  <div>
@@ -123,8 +119,6 @@ export default function Home() {
123
119
  }
124
120
  ```
125
121
 
126
- The `init()` method should be called immediately after the app returns the user to `returnUrl`.
127
-
128
122
  ### Initialize the Payments library in an AI Agent
129
123
 
130
124
  ```typescript
@@ -232,7 +226,7 @@ const { agentId, planId, txHash } = await payments.agents.registerAgentAndPlan(
232
226
  planMetadata,
233
227
  priceConfig,
234
228
  creditsConfig,
235
- 'time' // Oexplicitly set access limit to 'time' or 'credits'
229
+ 'time' // Optionally set access limit to 'time' or 'credits'
236
230
  )
237
231
  ```
238
232
 
@@ -258,18 +252,17 @@ console.log(`Balance: ${balance}`)
258
252
  Once the user has purchased a plan, they can query the agent:
259
253
 
260
254
  ```typescript
261
- const params = await payments.agents.getAgentAccessToken(creditsPlanId, agentId)
255
+ const { accessToken } = await payments.x402.getX402AccessToken(creditsPlanId, agentId)
262
256
 
263
257
  const agentHTTPOptions = {
264
258
  method: 'POST',
265
259
  headers: {
266
260
  Accept: 'application/json',
267
261
  'Content-Type': 'application/json',
268
- Authorization: `Bearer ${params.accessToken}`
262
+ 'payment-signature': accessToken
269
263
  },
270
264
  }
271
265
  const response = await fetch(new URL(agentURL), agentHTTPOptions)
272
-
273
266
  ```
274
267
 
275
268
  ## MCP (Model Context Protocol)
@@ -417,7 +410,7 @@ const payments = Payments.getInstance({
417
410
  environment: "sandbox",
418
411
  });
419
412
 
420
- const { accessToken } = await payments.agents.getAgentAccessToken(
413
+ const { accessToken } = await payments.x402.getX402AccessToken(
421
414
  process.env.NVM_PLAN_ID!,
422
415
  process.env.NVM_AGENT_ID!
423
416
  );
@@ -1,5 +1,5 @@
1
1
  import { Payments } from '../index.js';
2
- import { MessageSendParams, SendMessageResponse, TaskQueryParams, GetTaskResponse, TaskPushNotificationConfig, SetTaskPushNotificationConfigResponse, TaskIdParams, GetTaskPushNotificationConfigResponse } from '@a2a-js/sdk';
2
+ import { MessageSendParams, SendMessageResponse, TaskQueryParams, GetTaskResponse, TaskPushNotificationConfig, SetTaskPushNotificationConfigResponse, TaskIdParams, GetTaskPushNotificationConfigResponse, JSONRPCResponse, JSONRPCErrorResponse } from '@a2a-js/sdk';
3
3
  import { A2AClient } from '@a2a-js/sdk/client';
4
4
  /**
5
5
  * PaymentsClient is a high-level client for A2A agents with payments integration.
@@ -38,7 +38,7 @@ export declare class PaymentsClient extends A2AClient {
38
38
  * @param response - The JSON-RPC response to check
39
39
  * @returns true if the response contains an error, false otherwise
40
40
  */
41
- private isErrorResponse;
41
+ isErrorResponse(response: JSONRPCResponse): response is JSONRPCErrorResponse;
42
42
  /**
43
43
  * Sends a message to the agent, managing authentication automatically.
44
44
  * @param params - The parameters for sending the message.
@@ -1 +1 @@
1
- {"version":3,"file":"paymentsClient.d.ts","sourceRoot":"","sources":["../../src/a2a/paymentsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAEtC,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,qCAAqC,EACrC,YAAY,EACZ,qCAAqC,EACtC,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAI9C;;;GAGG;AACH,qBAAa,cAAe,SAAQ,SAAS;IACpC,QAAQ,EAAE,QAAQ,CAAA;IACzB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAQ;IAChC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,WAAW,CAAe;IAElC;;;;;;;OAOG;IACH,OAAO;IAQP;;;OAGG;WACiB,MAAM,CACxB,YAAY,EAAE,MAAM,EACpB,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,aAAa,SAA2B,GACvC,OAAO,CAAC,cAAc,CAAC;IAO1B;;;OAGG;YACW,mBAAmB;IASjC;;OAEG;IACI,UAAU;IAIjB;;;;OAIG;IACH,OAAO,CAAC,eAAe;IAIvB;;;;OAIG;IACU,cAAc,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAUpF;;;;;;;;OAQG;IACW,oBAAoB,CAChC,MAAM,EAAE,iBAAiB,GACxB,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,SAAS,CAAC;IAsD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M,CAAC,MAAM,EAAE,MAAM,CAAC,GAC/B,OAAO,CAAC,SAAS,CAAC;CA2CtB;AAED,YAAY,EACV,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,qCAAqC,EACrC,YAAY,EACZ,qCAAqC,GACtC,MAAM,aAAa,CAAA"}
@@ -55,7 +55,7 @@ export class PaymentsClient extends A2AClient {
55
55
  * @returns true if the response contains an error, false otherwise
56
56
  */
57
57
  isErrorResponse(response) {
58
- return response && typeof response === 'object' && 'error' in response;
58
+ return response != null && typeof response === 'object' && 'error' in response;
59
59
  }
60
60
  /**
61
61
  * Sends a message to the agent, managing authentication automatically.
@@ -64,7 +64,7 @@ export class PaymentsClient extends A2AClient {
64
64
  */
65
65
  async sendA2AMessage(params) {
66
66
  const accessToken = await this._getX402AccessToken();
67
- const headers = { Authorization: `Bearer ${accessToken}` };
67
+ const headers = { 'payment-signature': accessToken };
68
68
  return this._postRpcRequestWithHeaders('message/send', params, headers);
69
69
  }
70
70
  /**
@@ -95,7 +95,7 @@ export class PaymentsClient extends A2AClient {
95
95
  headers: {
96
96
  'Content-Type': 'application/json',
97
97
  Accept: 'text/event-stream',
98
- Authorization: `Bearer ${accessToken}`,
98
+ 'payment-signature': accessToken,
99
99
  },
100
100
  body: JSON.stringify(rpcRequest),
101
101
  });
@@ -247,7 +247,7 @@ export class PaymentsClient extends A2AClient {
247
247
  headers: {
248
248
  'Content-Type': 'application/json',
249
249
  Accept: 'text/event-stream',
250
- Authorization: `Bearer ${accessToken}`,
250
+ 'payment-signature': accessToken,
251
251
  },
252
252
  body: JSON.stringify(rpcRequest),
253
253
  });
@@ -282,7 +282,7 @@ export class PaymentsClient extends A2AClient {
282
282
  */
283
283
  async getA2ATask(params) {
284
284
  const accessToken = await this._getX402AccessToken();
285
- const headers = { Authorization: `Bearer ${accessToken}` };
285
+ const headers = { 'payment-signature': accessToken };
286
286
  return this._postRpcRequestWithHeaders('tasks/get', params, headers);
287
287
  }
288
288
  /**
@@ -292,7 +292,7 @@ export class PaymentsClient extends A2AClient {
292
292
  */
293
293
  async setA2ATaskPushNotificationConfig(params) {
294
294
  const accessToken = await this._getX402AccessToken();
295
- const headers = { Authorization: `Bearer ${accessToken}` };
295
+ const headers = { 'payment-signature': accessToken };
296
296
  return this._postRpcRequestWithHeaders('tasks/pushNotificationConfig/set', params, headers);
297
297
  }
298
298
  /**
@@ -302,7 +302,7 @@ export class PaymentsClient extends A2AClient {
302
302
  */
303
303
  async getA2ATaskPushNotificationConfig(params) {
304
304
  const accessToken = await this._getX402AccessToken();
305
- const headers = { Authorization: `Bearer ${accessToken}` };
305
+ const headers = { 'payment-signature': accessToken };
306
306
  return this._postRpcRequestWithHeaders('tasks/pushNotificationConfig/get', params, headers);
307
307
  }
308
308
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"paymentsClient.js","sourceRoot":"","sources":["../../src/a2a/paymentsClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAW3D,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAA;AAGnC;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,SAAS;IAM3C;;;;;;;OAOG;IACH,YAAoB,SAAoB,EAAE,QAAkB,EAAE,OAAe,EAAE,MAAc;QAC3F,KAAK,CAAC,SAAS,CAAC,CAAA;QAChB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,WAAW,GAAG,IAAI,CAAA;IACzB,CAAC;IAED;;;OAGG;IACI,MAAM,CAAC,KAAK,CAAC,MAAM,CACxB,YAAoB,EACpB,QAAkB,EAClB,OAAe,EACf,MAAc,EACd,aAAa,GAAG,wBAAwB;QAEx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,YAAY,CAAC,UAAU,eAAe,aAAa,EAAE,CAClH,CAAA;YACH,CAAC;QACH,CAAC;QACD,MAAM,WAAW,GAAG,MAAM,YAAY,CAAC,IAAI,EAAE,CAAA;QAC7C,IAAI,WAAW,CAAC,EAAE,KAAK,SAAS,EAAE,CAAC;YACjC,MAAM,IAAI,aAAa,CACrB,iDAAiD,MAAM,cAAc,SAAS,SAAS,WAAW,CAAC,EAAE,iDAAiD,EACtJ,gBAAgB,CACjB,CAAA;QACH,CAAC;QACD,OAAO,WAAwB,CAAA;IACjC,CAAC;CACF","sourcesContent":["import { Payments } from '../index.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport {\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\nimport { A2AClient } from '@a2a-js/sdk/client'\nimport { v4 as uuidv4 } from 'uuid'\nimport type { AgentCard } from './types.js'\n\n/**\n * PaymentsClient is a high-level client for A2A agents with payments integration.\n * Each instance is bound to a specific agentId and planId.\n */\nexport class PaymentsClient extends A2AClient {\n public payments: Payments\n private readonly agentId: string\n private readonly planId: string\n private accessToken: string | null\n\n /**\n * Creates a new PaymentsClient instance.\n * @param agentBaseUrl - The base URL of the agent (e.g. http://localhost:3005/a2a/).\n * @param payments - The Payments object.\n * @param agentId - The ID of the agent.\n * @param planId - The ID of the plan.\n * @param agentCardPath - Optional path to the agent card relative to base URL (defaults to '.well-known/agent.json').\n */\n private constructor(agentCard: AgentCard, payments: Payments, agentId: string, planId: string) {\n super(agentCard)\n this.payments = payments\n this.agentId = agentId\n this.planId = planId\n this.accessToken = null\n }\n\n /**\n * Creates a PaymentsClient by fetching the AgentCard first and then\n * constructing the underlying A2AClient with the AgentCard object.\n */\n public static async create(\n agentBaseUrl: string,\n payments: Payments,\n agentId: string,\n planId: string,\n agentCardPath = '.well-known/agent.json',\n ): Promise<PaymentsClient> {\n const agentCardUrl = new URL(agentCardPath, agentBaseUrl).toString()\n const a2a = await A2AClient.fromCardUrl(agentCardUrl)\n const agentCard = await (a2a as any).getAgentCard()\n return new PaymentsClient(agentCard as AgentCard, payments, agentId, planId)\n }\n\n /**\n * Gets and caches the access token for this client instance.\n * @returns The access token string.\n */\n private async _getX402AccessToken(): Promise<string> {\n if (this.accessToken) {\n return this.accessToken\n }\n const accessParams = await this.payments.x402.getX402AccessToken(this.planId, this.agentId)\n this.accessToken = accessParams.accessToken\n return this.accessToken\n }\n\n /**\n * Clears the cached access token for this client instance.\n */\n public clearToken() {\n this.accessToken = null\n }\n\n /**\n * Type guard to check if a JSON-RPC response is an error response.\n * @param response - The JSON-RPC response to check\n * @returns true if the response contains an error, false otherwise\n */\n private isErrorResponse(response: any): boolean {\n return response && typeof response === 'object' && 'error' in response\n }\n\n /**\n * Sends a message to the agent, managing authentication automatically.\n * @param params - The parameters for sending the message.\n * @returns The response from the agent.\n */\n public async sendA2AMessage(params: MessageSendParams): Promise<SendMessageResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<MessageSendParams, SendMessageResponse>(\n 'message/send',\n params,\n headers,\n )\n }\n\n /**\n * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).\n * Push notification configuration can be specified in `params.configuration`.\n * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.\n * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).\n * @param params - The parameters for sending the message.\n * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).\n * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.\n */\n public async *sendA2AMessageStream(\n params: MessageSendParams,\n ): AsyncGenerator<any, void, undefined> {\n const agentCard = await (this as any).agentCardPromise\n if (!agentCard.capabilities?.streaming) {\n throw new Error(\n 'Agent does not support streaming (AgentCard.capabilities.streaming is not true).',\n )\n }\n const endpoint = await (this as any)._getServiceEndpoint()\n const clientRequestId = uuidv4()\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'message/stream',\n params: params as { [key: string]: any },\n id: clientRequestId,\n }\n const accessToken = await this._getX402AccessToken()\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n const errorJson = JSON.parse(errorBody)\n if (errorJson.error) {\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('HTTP error establishing stream')) throw e\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,\n )\n }\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`,\n )\n }\n if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {\n throw new Error(\"Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.\")\n }\n // Parse and yield SSE events\n for await (const event of this._parseA2AStream(response, clientRequestId)) {\n yield event\n }\n }\n\n /**\n * Parses an HTTP response body as an A2A Server-Sent Event stream.\n * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,\n * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).\n * @param response -The HTTP Response object whose body is the SSE stream.\n * @param originalRequestId - The ID of the client's JSON-RPC request that initiated this stream.\n * Used to validate the `id` in the streamed JSON-RPC responses.\n * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.\n */\n private async *_parseA2AStream<TStreamItem>(\n response: Response,\n originalRequestId: number | string | null,\n ): AsyncGenerator<TStreamItem, void, undefined> {\n if (!response.body) {\n throw new Error('SSE response body is undefined. Cannot read stream.')\n }\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()\n let buffer = '' // Holds incomplete lines from the stream\n let eventDataBuffer = '' // Holds accumulated 'data:' lines for the current event\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n // Process any final buffered event data if the stream ends abruptly after a 'data:' line\n if (eventDataBuffer.trim()) {\n const result = this._processEventData<TStreamItem>(eventDataBuffer, originalRequestId)\n yield result\n }\n break // Stream finished\n }\n\n buffer += value // Append new chunk to buffer\n let lineEndIndex\n // Process all complete lines in the buffer\n while ((lineEndIndex = buffer.indexOf('\\n')) >= 0) {\n const line = buffer.substring(0, lineEndIndex).trim() // Get and trim the line\n buffer = buffer.substring(lineEndIndex + 1) // Remove processed line from buffer\n\n if (line === '') {\n // Empty line: signifies the end of an event\n if (eventDataBuffer) {\n // If we have accumulated data for an event\n const result = this._processEventData<TStreamItem>(eventDataBuffer, originalRequestId)\n yield result\n eventDataBuffer = '' // Reset buffer for the next event\n }\n } else if (line.startsWith('data:')) {\n eventDataBuffer += line.substring(5).trimStart() + '\\n' // Append data (multi-line data is possible)\n } else if (line.startsWith(':')) {\n // This is a comment line in SSE, ignore it.\n }\n }\n }\n } catch (error: any) {\n throw new PaymentsError(error.message, 'payments_error')\n } finally {\n reader.releaseLock() // Ensure the reader lock is released\n }\n }\n\n /**\n * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.\n * @param jsonData - The string content from one or more 'data:' lines of an SSE event.\n * @param originalRequestId - The ID of the client's request that initiated the stream.\n * @returns The `result` field of the parsed JSON-RPC success response.\n * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.\n */\n private _processEventData<TStreamItem>(\n jsonData: string,\n originalRequestId: number | string | null,\n ): TStreamItem {\n if (!jsonData.trim()) {\n throw new Error('Attempted to process empty SSE event data.')\n }\n try {\n // SSE data can be multi-line, ensure it's treated as a single JSON string.\n const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\\n$/, ''))\n\n // Type assertion to SendStreamingMessageResponse, as this is the expected structure for A2A streams.\n const a2aStreamResponse: any = sseJsonRpcResponse\n\n if (a2aStreamResponse.id !== originalRequestId) {\n // According to JSON-RPC spec, notifications (which SSE events can be seen as) might not have an ID,\n // or if they do, it should match. A2A spec implies streamed events are tied to the initial request.\n throw new PaymentsError(\n `SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`,\n 'payments_error',\n )\n }\n\n if (this.isErrorResponse && this.isErrorResponse(a2aStreamResponse)) {\n const err = a2aStreamResponse.error\n throw new PaymentsError(\n `SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data)}`,\n )\n }\n\n // Check if 'result' exists, as it's mandatory for successful JSON-RPC responses\n if (!('result' in a2aStreamResponse) || typeof a2aStreamResponse.result === 'undefined') {\n throw new PaymentsError(\n `SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`,\n 'payments_error',\n )\n }\n\n return a2aStreamResponse as TStreamItem\n } catch (e: any) {\n // Catch errors from JSON.parse or if it's an error response that was thrown by this function\n if (\n e.message.startsWith('SSE event contained an error') ||\n e.message.startsWith(\"SSE event JSON-RPC response is missing 'result' field\")\n ) {\n throw new PaymentsError(e.message, 'payments_error')\n }\n\n throw new PaymentsError(\n `Failed to parse SSE event data: \"${jsonData.substring(0, 100)}...\". Original error: ${e.message}`,\n 'payments_error',\n )\n }\n }\n\n /**\n * Resubscribes to a task's event stream using Server-Sent Events (SSE).\n * This is used if a previous SSE connection for an active task was broken.\n * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).\n * @param params - Parameters containing the taskId.\n * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).\n */\n public async *resubscribeA2ATask(params: TaskIdParams): AsyncGenerator<any, void, undefined> {\n const agentCard = await (this as any).agentCardPromise\n if (!agentCard.capabilities?.streaming) {\n throw new Error('Agent does not support streaming (required for tasks/resubscribe).')\n }\n const endpoint = await (this as any)._getServiceEndpoint()\n const clientRequestId = uuidv4()\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'tasks/resubscribe',\n params: params as { [key: string]: any },\n id: clientRequestId,\n }\n const accessToken = await this._getX402AccessToken()\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n const errorJson = JSON.parse(errorBody)\n if (errorJson.error) {\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('HTTP error establishing stream')) throw e\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,\n )\n }\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`,\n )\n }\n if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {\n throw new Error(\n \"Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.\",\n )\n }\n // Parse and yield SSE events\n for await (const event of this._parseA2AStream(response, clientRequestId)) {\n yield event\n }\n }\n\n /**\n * Retrieves a task by its ID, managing authentication automatically.\n * @param params - The parameters for the task query.\n * @returns The task response.\n */\n public async getA2ATask(params: TaskQueryParams): Promise<GetTaskResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<TaskQueryParams, GetTaskResponse>(\n 'tasks/get',\n params,\n headers,\n )\n }\n\n /**\n * Sets or updates the push notification configuration for a given task, managing authentication automatically.\n * @param params - The parameters for the task push notification configuration.\n * @returns The response from the agent.\n */\n public async setA2ATaskPushNotificationConfig(\n params: TaskPushNotificationConfig,\n ): Promise<SetTaskPushNotificationConfigResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse\n >('tasks/pushNotificationConfig/set', params, headers)\n }\n\n /**\n * Gets the push notification configuration for a given task, managing authentication automatically.\n * @param params - The parameters for the task push notification configuration.\n * @returns The response from the agent.\n */\n public async getA2ATaskPushNotificationConfig(\n params: TaskIdParams,\n ): Promise<GetTaskPushNotificationConfigResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<TaskIdParams, GetTaskPushNotificationConfigResponse>(\n 'tasks/pushNotificationConfig/get',\n params,\n headers,\n )\n }\n\n /**\n * Internal helper to make a JSON-RPC POST request with custom headers.\n * @param method - The RPC method name.\n * @param params - The parameters for the RPC method.\n * @param headers - Optional custom headers.\n * @returns The response from the agent.\n */\n protected async _postRpcRequestWithHeaders<TParams, TResponse>(\n method: string,\n params: TParams,\n headers?: Record<string, string>,\n ): Promise<TResponse> {\n const endpoint = await (this as any)._getServiceEndpoint()\n const requestId = uuidv4()\n const rpcRequest = { jsonrpc: '2.0', method, params, id: requestId }\n const httpResponse = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...(headers || {}),\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!httpResponse.ok) {\n let errorBodyText = '(empty or non-JSON response)'\n try {\n errorBodyText = await httpResponse.text()\n const errorJson = JSON.parse(errorBodyText)\n if (!errorJson.jsonrpc && errorJson.error) {\n throw new Error(\n `RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data)}`,\n )\n } else if (!errorJson.jsonrpc) {\n throw new Error(\n `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('RPC error for') || e.message.startsWith('HTTP error for')) throw e\n throw new Error(\n `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,\n )\n }\n }\n const rpcResponse = await httpResponse.json()\n if (rpcResponse.id !== requestId) {\n throw new PaymentsError(\n `CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`,\n 'payments_error',\n )\n }\n return rpcResponse as TResponse\n }\n}\n\nexport type {\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\n"]}
1
+ {"version":3,"file":"paymentsClient.js","sourceRoot":"","sources":["../../src/a2a/paymentsClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAa3D,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAA;AAGnC;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,SAAS;IAM3C;;;;;;;OAOG;IACH,YAAoB,SAAoB,EAAE,QAAkB,EAAE,OAAe,EAAE,MAAc;QAC3F,KAAK,CAAC,SAAS,CAAC,CAAA;QAChB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,WAAW,GAAG,IAAI,CAAA;IACzB,CAAC;IAED;;;OAGG;IACI,MAAM,CAAC,KAAK,CAAC,MAAM,CACxB,YAAoB,EACpB,QAAkB,EAClB,OAAe,EACf,MAAc,EACd,aAAa,GAAG,wBAAwB;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AA;YACH,CAAC;QACH,CAAC;QACD,MAAM,WAAW,GAAG,MAAM,YAAY,CAAC,IAAI,EAAE,CAAA;QAC7C,IAAI,WAAW,CAAC,EAAE,KAAK,SAAS,EAAE,CAAC;YACjC,MAAM,IAAI,aAAa,CACrB,iDAAiD,MAAM,cAAc,SAAS,SAAS,WAAW,CAAC,EAAE,iDAAiD,EACtJ,gBAAgB,CACjB,CAAA;QACH,CAAC;QACD,OAAO,WAAwB,CAAA;IACjC,CAAC;CACF","sourcesContent":["import { Payments } from '../index.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport {\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n JSONRPCResponse,\n JSONRPCErrorResponse,\n} from '@a2a-js/sdk'\nimport { A2AClient } from '@a2a-js/sdk/client'\nimport { v4 as uuidv4 } from 'uuid'\nimport type { AgentCard } from './types.js'\n\n/**\n * PaymentsClient is a high-level client for A2A agents with payments integration.\n * Each instance is bound to a specific agentId and planId.\n */\nexport class PaymentsClient extends A2AClient {\n public payments: Payments\n private readonly agentId: string\n private readonly planId: string\n private accessToken: string | null\n\n /**\n * Creates a new PaymentsClient instance.\n * @param agentBaseUrl - The base URL of the agent (e.g. http://localhost:3005/a2a/).\n * @param payments - The Payments object.\n * @param agentId - The ID of the agent.\n * @param planId - The ID of the plan.\n * @param agentCardPath - Optional path to the agent card relative to base URL (defaults to '.well-known/agent.json').\n */\n private constructor(agentCard: AgentCard, payments: Payments, agentId: string, planId: string) {\n super(agentCard)\n this.payments = payments\n this.agentId = agentId\n this.planId = planId\n this.accessToken = null\n }\n\n /**\n * Creates a PaymentsClient by fetching the AgentCard first and then\n * constructing the underlying A2AClient with the AgentCard object.\n */\n public static async create(\n agentBaseUrl: string,\n payments: Payments,\n agentId: string,\n planId: string,\n agentCardPath = '.well-known/agent.json',\n ): Promise<PaymentsClient> {\n const agentCardUrl = new URL(agentCardPath, agentBaseUrl).toString()\n const a2a = await A2AClient.fromCardUrl(agentCardUrl)\n const agentCard = await (a2a as any).getAgentCard()\n return new PaymentsClient(agentCard as AgentCard, payments, agentId, planId)\n }\n\n /**\n * Gets and caches the access token for this client instance.\n * @returns The access token string.\n */\n private async _getX402AccessToken(): Promise<string> {\n if (this.accessToken) {\n return this.accessToken\n }\n const accessParams = await this.payments.x402.getX402AccessToken(this.planId, this.agentId)\n this.accessToken = accessParams.accessToken\n return this.accessToken\n }\n\n /**\n * Clears the cached access token for this client instance.\n */\n public clearToken() {\n this.accessToken = null\n }\n\n /**\n * Type guard to check if a JSON-RPC response is an error response.\n * @param response - The JSON-RPC response to check\n * @returns true if the response contains an error, false otherwise\n */\n isErrorResponse(response: JSONRPCResponse): response is JSONRPCErrorResponse {\n return response != null && typeof response === 'object' && 'error' in response\n }\n\n /**\n * Sends a message to the agent, managing authentication automatically.\n * @param params - The parameters for sending the message.\n * @returns The response from the agent.\n */\n public async sendA2AMessage(params: MessageSendParams): Promise<SendMessageResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { 'payment-signature': accessToken }\n return this._postRpcRequestWithHeaders<MessageSendParams, SendMessageResponse>(\n 'message/send',\n params,\n headers,\n )\n }\n\n /**\n * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).\n * Push notification configuration can be specified in `params.configuration`.\n * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.\n * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).\n * @param params - The parameters for sending the message.\n * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).\n * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.\n */\n public async *sendA2AMessageStream(\n params: MessageSendParams,\n ): AsyncGenerator<any, void, undefined> {\n const agentCard = await (this as any).agentCardPromise\n if (!agentCard.capabilities?.streaming) {\n throw new Error(\n 'Agent does not support streaming (AgentCard.capabilities.streaming is not true).',\n )\n }\n const endpoint = await (this as any)._getServiceEndpoint()\n const clientRequestId = uuidv4()\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'message/stream',\n params: params as { [key: string]: any },\n id: clientRequestId,\n }\n const accessToken = await this._getX402AccessToken()\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n 'payment-signature': accessToken,\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n const errorJson = JSON.parse(errorBody)\n if (errorJson.error) {\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('HTTP error establishing stream')) throw e\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,\n )\n }\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`,\n )\n }\n if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {\n throw new Error(\"Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.\")\n }\n // Parse and yield SSE events\n for await (const event of this._parseA2AStream(response, clientRequestId)) {\n yield event\n }\n }\n\n /**\n * Parses an HTTP response body as an A2A Server-Sent Event stream.\n * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,\n * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).\n * @param response -The HTTP Response object whose body is the SSE stream.\n * @param originalRequestId - The ID of the client's JSON-RPC request that initiated this stream.\n * Used to validate the `id` in the streamed JSON-RPC responses.\n * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.\n */\n private async *_parseA2AStream<TStreamItem>(\n response: Response,\n originalRequestId: number | string | null,\n ): AsyncGenerator<TStreamItem, void, undefined> {\n if (!response.body) {\n throw new Error('SSE response body is undefined. Cannot read stream.')\n }\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()\n let buffer = '' // Holds incomplete lines from the stream\n let eventDataBuffer = '' // Holds accumulated 'data:' lines for the current event\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n // Process any final buffered event data if the stream ends abruptly after a 'data:' line\n if (eventDataBuffer.trim()) {\n const result = this._processEventData<TStreamItem>(eventDataBuffer, originalRequestId)\n yield result\n }\n break // Stream finished\n }\n\n buffer += value // Append new chunk to buffer\n let lineEndIndex\n // Process all complete lines in the buffer\n while ((lineEndIndex = buffer.indexOf('\\n')) >= 0) {\n const line = buffer.substring(0, lineEndIndex).trim() // Get and trim the line\n buffer = buffer.substring(lineEndIndex + 1) // Remove processed line from buffer\n\n if (line === '') {\n // Empty line: signifies the end of an event\n if (eventDataBuffer) {\n // If we have accumulated data for an event\n const result = this._processEventData<TStreamItem>(eventDataBuffer, originalRequestId)\n yield result\n eventDataBuffer = '' // Reset buffer for the next event\n }\n } else if (line.startsWith('data:')) {\n eventDataBuffer += line.substring(5).trimStart() + '\\n' // Append data (multi-line data is possible)\n } else if (line.startsWith(':')) {\n // This is a comment line in SSE, ignore it.\n }\n }\n }\n } catch (error: any) {\n throw new PaymentsError(error.message, 'payments_error')\n } finally {\n reader.releaseLock() // Ensure the reader lock is released\n }\n }\n\n /**\n * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.\n * @param jsonData - The string content from one or more 'data:' lines of an SSE event.\n * @param originalRequestId - The ID of the client's request that initiated the stream.\n * @returns The `result` field of the parsed JSON-RPC success response.\n * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.\n */\n private _processEventData<TStreamItem>(\n jsonData: string,\n originalRequestId: number | string | null,\n ): TStreamItem {\n if (!jsonData.trim()) {\n throw new Error('Attempted to process empty SSE event data.')\n }\n try {\n // SSE data can be multi-line, ensure it's treated as a single JSON string.\n const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\\n$/, ''))\n\n // Type assertion to SendStreamingMessageResponse, as this is the expected structure for A2A streams.\n const a2aStreamResponse: any = sseJsonRpcResponse\n\n if (a2aStreamResponse.id !== originalRequestId) {\n // According to JSON-RPC spec, notifications (which SSE events can be seen as) might not have an ID,\n // or if they do, it should match. A2A spec implies streamed events are tied to the initial request.\n throw new PaymentsError(\n `SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`,\n 'payments_error',\n )\n }\n\n if (this.isErrorResponse && this.isErrorResponse(a2aStreamResponse)) {\n const err = a2aStreamResponse.error\n throw new PaymentsError(\n `SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data)}`,\n )\n }\n\n // Check if 'result' exists, as it's mandatory for successful JSON-RPC responses\n if (!('result' in a2aStreamResponse) || typeof a2aStreamResponse.result === 'undefined') {\n throw new PaymentsError(\n `SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`,\n 'payments_error',\n )\n }\n\n return a2aStreamResponse as TStreamItem\n } catch (e: any) {\n // Catch errors from JSON.parse or if it's an error response that was thrown by this function\n if (\n e.message.startsWith('SSE event contained an error') ||\n e.message.startsWith(\"SSE event JSON-RPC response is missing 'result' field\")\n ) {\n throw new PaymentsError(e.message, 'payments_error')\n }\n\n throw new PaymentsError(\n `Failed to parse SSE event data: \"${jsonData.substring(0, 100)}...\". Original error: ${e.message}`,\n 'payments_error',\n )\n }\n }\n\n /**\n * Resubscribes to a task's event stream using Server-Sent Events (SSE).\n * This is used if a previous SSE connection for an active task was broken.\n * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).\n * @param params - Parameters containing the taskId.\n * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).\n */\n public async *resubscribeA2ATask(params: TaskIdParams): AsyncGenerator<any, void, undefined> {\n const agentCard = await (this as any).agentCardPromise\n if (!agentCard.capabilities?.streaming) {\n throw new Error('Agent does not support streaming (required for tasks/resubscribe).')\n }\n const endpoint = await (this as any)._getServiceEndpoint()\n const clientRequestId = uuidv4()\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'tasks/resubscribe',\n params: params as { [key: string]: any },\n id: clientRequestId,\n }\n const accessToken = await this._getX402AccessToken()\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n 'payment-signature': accessToken,\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n const errorJson = JSON.parse(errorBody)\n if (errorJson.error) {\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('HTTP error establishing stream')) throw e\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,\n )\n }\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`,\n )\n }\n if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {\n throw new Error(\n \"Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.\",\n )\n }\n // Parse and yield SSE events\n for await (const event of this._parseA2AStream(response, clientRequestId)) {\n yield event\n }\n }\n\n /**\n * Retrieves a task by its ID, managing authentication automatically.\n * @param params - The parameters for the task query.\n * @returns The task response.\n */\n public async getA2ATask(params: TaskQueryParams): Promise<GetTaskResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { 'payment-signature': accessToken }\n return this._postRpcRequestWithHeaders<TaskQueryParams, GetTaskResponse>(\n 'tasks/get',\n params,\n headers,\n )\n }\n\n /**\n * Sets or updates the push notification configuration for a given task, managing authentication automatically.\n * @param params - The parameters for the task push notification configuration.\n * @returns The response from the agent.\n */\n public async setA2ATaskPushNotificationConfig(\n params: TaskPushNotificationConfig,\n ): Promise<SetTaskPushNotificationConfigResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { 'payment-signature': accessToken }\n return this._postRpcRequestWithHeaders<\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse\n >('tasks/pushNotificationConfig/set', params, headers)\n }\n\n /**\n * Gets the push notification configuration for a given task, managing authentication automatically.\n * @param params - The parameters for the task push notification configuration.\n * @returns The response from the agent.\n */\n public async getA2ATaskPushNotificationConfig(\n params: TaskIdParams,\n ): Promise<GetTaskPushNotificationConfigResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { 'payment-signature': accessToken }\n return this._postRpcRequestWithHeaders<TaskIdParams, GetTaskPushNotificationConfigResponse>(\n 'tasks/pushNotificationConfig/get',\n params,\n headers,\n )\n }\n\n /**\n * Internal helper to make a JSON-RPC POST request with custom headers.\n * @param method - The RPC method name.\n * @param params - The parameters for the RPC method.\n * @param headers - Optional custom headers.\n * @returns The response from the agent.\n */\n protected async _postRpcRequestWithHeaders<TParams, TResponse>(\n method: string,\n params: TParams,\n headers?: Record<string, string>,\n ): Promise<TResponse> {\n const endpoint = await (this as any)._getServiceEndpoint()\n const requestId = uuidv4()\n const rpcRequest = { jsonrpc: '2.0', method, params, id: requestId }\n const httpResponse = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...(headers || {}),\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!httpResponse.ok) {\n let errorBodyText = '(empty or non-JSON response)'\n try {\n errorBodyText = await httpResponse.text()\n const errorJson = JSON.parse(errorBodyText)\n if (!errorJson.jsonrpc && errorJson.error) {\n throw new Error(\n `RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data)}`,\n )\n } else if (!errorJson.jsonrpc) {\n throw new Error(\n `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('RPC error for') || e.message.startsWith('HTTP error for')) throw e\n throw new Error(\n `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,\n )\n }\n }\n const rpcResponse = await httpResponse.json()\n if (rpcResponse.id !== requestId) {\n throw new PaymentsError(\n `CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`,\n 'payments_error',\n )\n }\n return rpcResponse as TResponse\n }\n}\n\nexport type {\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/a2a/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,OAAO,MAAM,SAAS,CAAA;AAC7B,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAA8C,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAC9F,OAAO,KAAK,EAAE,SAAS,EAAsB,MAAM,YAAY,CAAA;AAC/D,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAA;AA4BpE;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC,oEAAoE;IACpE,SAAS,EAAE,SAAS,CAAA;IACpB,uDAAuD;IACvD,QAAQ,EAAE,aAAa,CAAA;IACvB,kEAAkE;IAClE,eAAe,EAAE,GAAG,CAAA;IACpB,wCAAwC;IACxC,qEAAqE;IACrE,IAAI,EAAE,MAAM,CAAA;IACZ,uEAAuE;IACvE,SAAS,CAAC,EAAE,GAAG,CAAA;IACf,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,iEAAiE;IACjE,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,oDAAoD;I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ACpD,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;QACpF,mDAAmD;QACnD,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;QACnF,2CAA2C;QAC3C,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,CAAC,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;KAChF,CAAA;CACF;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC,yCAAyC;IACzC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAA;IACpB,+BAA+B;IAC/B,MAAM,EAAE,IAAI,CAAC,MAAM,CAAA;IACnB,+DAA+D;IAC/D,OAAO,EAAE,sBAAsB,CAAA;IAC/B,iDAAiD;IACjD,IAAI,EAAE,MAAM,CAAA;IACZ;;;OAGG;IACH,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAC3B;AA8GD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,qBAAa,iBAAiB;IAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,wBAAwB,GAAG,uBAAuB;CA0KzE"}
@@ -14,6 +14,8 @@ import express from 'express';
14
14
  import http from 'http';
15
15
  import { InMemoryTaskStore, JsonRpcTransportHandler } from '@a2a-js/sdk/server';
16
16
  import { PaymentsRequestHandler } from './paymentsRequestHandler.js';
17
+ import { buildPaymentRequired } from '../x402/facilitator-api.js';
18
+ import { X402_HEADERS } from '../x402/express/middleware.js';
17
19
  /**
18
20
  * Checks if a value is an AsyncIterable (used to detect streaming responses)
19
21
  */
@@ -31,8 +33,17 @@ async function sendRpcResult(res, result) {
31
33
  const anyRes = res;
32
34
  if (typeof anyRes.flushHeaders === 'function')
33
35
  anyRes.flushHeaders();
34
- for await (const chunk of result) {
35
- res.write(`data: ${JSON.stringify(chunk)}\n\n`);
36
+ try {
37
+ for await (const chunk of result) {
38
+ res.write(`data: ${JSON.stringify(chunk)}\n\n`);
39
+ }
40
+ }
41
+ catch (err) {
42
+ const errorEvent = {
43
+ jsonrpc: '2.0',
44
+ error: { code: err?.code || -32603, message: err?.message || 'Internal streaming error' },
45
+ };
46
+ res.write(`data: ${JSON.stringify(errorEvent)}\n\n`);
36
47
  }
37
48
  res.end();
38
49
  return;
@@ -45,8 +56,7 @@ async function sendRpcResult(res, result) {
45
56
  * information for credit validation.
46
57
  *
47
58
  * Accepts tokens from:
48
- * - PAYMENT-SIGNATURE header (x402 HTTP transport spec v2)
49
- * - Authorization: Bearer header (A2A protocol / general use)
59
+ * - payment-signature header (x402 HTTP transport spec v2)
50
60
  *
51
61
  * @param req - Express request object
52
62
  * @param res - Express response object
@@ -57,27 +67,6 @@ async function bearerTokenMiddleware(handler, req, res, next) {
57
67
  if (req.method !== 'POST') {
58
68
  return next();
59
69
  }
60
- // Try x402 HTTP spec v2 header first, then fall back to Authorization: Bearer
61
- const paymentSignatureHeader = req.headers['payment-signature'];
62
- const authHeader = req.headers['authorization'];
63
- let bearerToken;
64
- if (paymentSignatureHeader) {
65
- // x402 HTTP spec v2: PAYMENT-SIGNATURE header (base64-encoded PaymentPayload)
66
- bearerToken = paymentSignatureHeader;
67
- }
68
- else if (authHeader?.toLowerCase().startsWith('bearer ')) {
69
- // A2A protocol / general use: Authorization: Bearer header
70
- bearerToken = authHeader.slice(7).trim();
71
- }
72
- if (!bearerToken) {
73
- res.status(401).json({
74
- error: {
75
- code: -32001,
76
- message: 'Missing payment token. Provide PAYMENT-SIGNATURE or Authorization: Bearer header.',
77
- },
78
- });
79
- return;
80
- }
81
70
  // Transform relative URL to absolute URL
82
71
  const absoluteUrl = new URL(req.originalUrl, req.protocol + '://' + req.get('host')).toString();
83
72
  const agentCard = await handler.getAgentCard();
@@ -91,6 +80,29 @@ async function bearerTokenMiddleware(handler, req, res, next) {
91
80
  });
92
81
  return;
93
82
  }
83
+ // Build paymentRequired for 402 responses
84
+ const planId = paymentExtension.params?.planId || '';
85
+ const agentId = paymentExtension.params?.agentId;
86
+ const paymentRequired = buildPaymentRequired(planId, {
87
+ endpoint: absoluteUrl,
88
+ agentId,
89
+ httpVerb: 'POST',
90
+ });
91
+ const paymentRequiredHeader = Buffer.from(JSON.stringify(paymentRequired)).toString('base64');
92
+ // x402 HTTP spec v2: payment-signature header
93
+ const bearerToken = req.headers['payment-signature'];
94
+ if (!bearerToken) {
95
+ res
96
+ .status(402)
97
+ .set(X402_HEADERS.PAYMENT_REQUIRED, paymentRequiredHeader)
98
+ .json({
99
+ error: {
100
+ code: -32001,
101
+ message: 'Missing payment-signature header.',
102
+ },
103
+ });
104
+ return;
105
+ }
94
106
  let validation;
95
107
  try {
96
108
  validation = await handler.validateRequest(bearerToken, absoluteUrl, req.method);
@@ -206,7 +218,9 @@ export class PaymentsA2AServer {
206
218
  }
207
219
  if (exposeDefaultRoutes) {
208
220
  // Apply bearer token middleware for all requests under basePath
209
- app.use(basePath, express.json(), bearerTokenMiddleware.bind(null, handler));
221
+ app.use(basePath, express.json(), (req, res, next) => {
222
+ bearerTokenMiddleware(handler, req, res, next).catch(next);
223
+ });
210
224
  // Apply hooks middleware after body parsing and validation
211
225
  if (hooks) {
212
226
  app.use(basePath, (req, res, next) => {
@@ -250,6 +264,11 @@ export class PaymentsA2AServer {
250
264
  await sendRpcResult(res, result);
251
265
  }
252
266
  catch (err) {
267
+ if (res.headersSent) {
268
+ console.error('[PaymentsA2A] Error after headers sent:', err?.message);
269
+ res.end();
270
+ return;
271
+ }
253
272
  res.status(500).json({
254
273
  error: { code: -32603, message: err?.message || 'Internal server error' },
255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B,OAAO,EAAE,CAAA;oBACX,CAAC,CAAC,CAAA;gBACJ,CAAC,EAAE,IAAI,CAAC,CAAA;gBAER,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;oBACrB,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;wBAChB,YAAY,CAAC,OAAO,CAAC,CAAA;wBACrB,6CAA6C;wBAC7C,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;oBAC1B,CAAC,CAAC,CAAA;gBACJ,CAAC;qBAAM,CAAC;oBACN,YAAY,CAAC,OAAO,CAAC,CAAA;oBACrB,OAAO,EAAE,CAAA;gBACX,CAAC;YACH,CAAC,CAAC,CAAA;QACJ,CAAC,CAAA;QAED,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,CAAA;IAC1D,CAAC;CACF","sourcesContent":["/**\n * PaymentsA2AServer sets up and starts the A2A server for payments agents.\n * Handles A2A protocol endpoints and allows optional custom endpoints.\n *\n * The server provides a complete A2A protocol implementation with:\n * - JSON-RPC endpoint for A2A messages\n * - Agent Card endpoint (.well-known/agent.json)\n * - Bearer token extraction and validation\n * - Credit validation and burning\n * - Task execution and streaming\n * - Customizable routes and handlers\n */\nimport express from 'express'\nimport http from 'http'\nimport { InMemoryTaskStore, JsonRpcTransportHandler, AgentExecutor } from '@a2a-js/sdk/server'\nimport type { AgentCard, HttpRequestContext } from './types.js'\nimport { PaymentsRequestHandler } from './paymentsRequestHandler.js'\n\n/**\n * Checks if a value is an AsyncIterable (used to detect streaming responses)\n */\nfunction isAsyncIterable<T>(value: any): value is AsyncIterable<T> {\n return value && typeof value[Symbol.asyncIterator] === 'function'\n}\n\n/**\n * Sends a JSON-RPC result. If it's an async iterator, streams as SSE; otherwise returns JSON.\n */\nasync function sendRpcResult(res: express.Response, result: any): Promise<void> {\n if (isAsyncIterable(result)) {\n res.setHeader('Content-Type', 'text/event-stream')\n res.setHeader('Cache-Control', 'no-cache')\n res.setHeader('Connection', 'keep-alive')\n const anyRes = res as any\n if (typeof anyRes.flushHeaders === 'function') anyRes.flushHeaders()\n for await (const chunk of result as AsyncGenerator<any, void, undefined>) {\n res.write(`data: ${JSON.stringify(chunk)}\\n\\n`)\n }\n res.end()\n return\n }\n res.json(result)\n}\n\n/**\n * Options for starting the PaymentsA2AServer.\n * Provides comprehensive configuration for A2A server setup.\n */\nexport interface PaymentsA2AServerOptions {\n /** The agent card defining the agent's capabilities and metadata */\n agentCard: AgentCard\n /** User-implemented executor for handling A2A tasks */\n executor: AgentExecutor\n /** Payments service instance for credit validation and burning */\n paymentsService: any\n /** Port number to bind the server to */\n /** Port number to listen on. Use 0 for automatic port assignment. */\n port: number\n /** Custom task store implementation (defaults to InMemoryTaskStore) */\n taskStore?: any\n /** Base path for all A2A routes (defaults to '/') */\n basePath?: string\n /** Whether to expose the agent card at .well-known/agent.json */\n exposeAgentCard?: boolean\n /** Whether to expose default A2A JSON-RPC routes */\n exposeDefaultRoutes?: boolean\n /** Custom Express app instance (defaults to new express()) */\n expressApp?: express.Express\n /** Custom request handler to override JSON-RPC method handling */\n customRequestHandler?: any\n /** Options for configuring the PaymentsRequestHandler behavior */\n handlerOptions?: {\n asyncExecution?: boolean\n defaultBatch?: boolean\n defaultMarginPercent?: number\n }\n /** Hooks for intercepting requests before/after processing */\n hooks?: {\n /** Called before processing any JSON-RPC request */\n beforeRequest?: (method: string, params: any, req: express.Request) => Promise<void>\n /** Called after processing any JSON-RPC request */\n afterRequest?: (method: string, result: any, req: express.Request) => Promise<void>\n /** Called when a JSON-RPC request fails */\n onError?: (method: string, error: Error, req: express.Request) => Promise<void>\n }\n}\n\n/**\n * Result returned by the server start method.\n * Contains the Express app and HTTP server instances for further customization.\n */\nexport interface PaymentsA2AServerResult {\n /** The configured Express application */\n app: express.Express\n /** The HTTP server instance */\n server: http.Server\n /** The request handler instance for direct access if needed */\n handler: PaymentsRequestHandler\n /** The actual port the server is listening on */\n port: number\n /**\n * Closes the server and all active connections.\n * @returns Promise that resolves when the server is fully closed\n */\n close: () => Promise<void>\n}\n\n/**\n * Middleware to extract payment token from HTTP headers and store it in the global context.\n * This middleware is applied after A2A routes are set up and extracts authentication\n * information for credit validation.\n *\n * Accepts tokens from:\n * - PAYMENT-SIGNATURE header (x402 HTTP transport spec v2)\n * - Authorization: Bearer header (A2A protocol / general use)\n *\n * @param req - Express request object\n * @param res - Express response object\n * @param next - Express next function\n */\nasync function bearerTokenMiddleware(\n handler: PaymentsRequestHandler,\n req: express.Request,\n res: express.Response,\n next: express.NextFunction,\n) {\n // Only process POST requests (A2A uses POST for all operations)\n if (req.method !== 'POST') {\n return next()\n }\n\n // Try x402 HTTP spec v2 header first, then fall back to Authorization: Bearer\n const paymentSignatureHeader = req.headers['payment-signature'] as string | undefined\n const authHeader = req.headers['authorization'] as string | undefined\n\n let bearerToken: string | undefined\n\n if (paymentSignatureHeader) {\n // x402 HTTP spec v2: PAYMENT-SIGNATURE header (base64-encoded PaymentPayload)\n bearerToken = paymentSignatureHeader\n } else if (authHeader?.toLowerCase().startsWith('bearer ')) {\n // A2A protocol / general use: Authorization: Bearer header\n bearerToken = authHeader.slice(7).trim()\n }\n\n if (!bearerToken) {\n res.status(401).json({\n error: {\n code: -32001,\n message: 'Missing payment token. Provide PAYMENT-SIGNATURE or Authorization: Bearer header.',\n },\n })\n return\n }\n\n // Transform relative URL to absolute URL\n const absoluteUrl = new URL(req.originalUrl, req.protocol + '://' + req.get('host')).toString()\n\n const agentCard = await handler.getAgentCard()\n const paymentExtension = agentCard.capabilities?.extensions?.find(\n (ext) => ext.uri === 'urn:nevermined:payment',\n )\n\n if (!paymentExtension?.params?.agentId) {\n res.status(402).json({\n error: {\n code: -32001,\n message: 'Agent ID not found in agent card payment extension.',\n },\n })\n return\n }\n\n let validation: any\n try {\n validation = await handler.validateRequest(\n bearerToken,\n absoluteUrl,\n req.method,\n )\n if (!validation?.balance?.isSubscriber) {\n res.status(402).json({\n error: {\n code: -32001,\n message: 'Insufficient credits or invalid request.',\n },\n })\n return\n }\n } catch (err) {\n res.status(402).json({\n error: {\n code: -32001,\n message: 'Payment validation failed: ' + (err instanceof Error ? err.message : String(err)),\n },\n })\n return\n }\n\n const context: HttpRequestContext = {\n bearerToken,\n urlRequested: absoluteUrl,\n httpMethodRequested: req.method,\n validation,\n }\n // Try to associate context with taskId or messageId\n const taskId = req.body?.taskId\n const messageId = req.body?.params?.message?.messageId\n\n if (taskId) {\n handler.setHttpRequestContextForTask(taskId, context)\n } else if (messageId) {\n handler.setHttpRequestContextForMessage(messageId, context)\n }\n\n next()\n}\n\n/**\n * PaymentsA2AServer sets up the A2A endpoints and starts the server.\n *\n * This class provides a complete A2A protocol implementation with payment integration.\n * It handles:\n * - JSON-RPC message routing\n * - Agent card exposure\n * - Bearer token extraction\n * - Credit validation and burning\n * - Task execution and streaming\n * - Customizable routes and handlers\n *\n * @example\n * ```typescript\n * const server = PaymentsA2AServer.start({\n * agentCard: myAgentCard,\n * executor: new MyExecutor(),\n * paymentsService: payments,\n * port: 41242,\n * basePath: '/a2a/',\n * hooks: {\n * beforeRequest: async (method, params, req) => {\n * console.log(`Processing ${method} request`)\n * }\n * }\n * })\n * ```\n */\nexport class PaymentsA2AServer {\n /**\n * Starts the A2A server with the given options.\n *\n * This method sets up the complete A2A server infrastructure including:\n * - Express app configuration\n * - A2A route setup\n * - Middleware for bearer token extraction\n * - Agent card endpoint\n * - HTTP server creation and binding\n *\n * @param options - Server configuration options\n * @returns Server result containing app, server, adapter, and handler instances\n *\n * @example\n * ```typescript\n * const result = PaymentsA2AServer.start({\n * agentCard: buildPaymentAgentCard(baseCard, paymentMetadata),\n * executor: new MyPaymentsExecutor(),\n * paymentsService: payments,\n * port: 41242,\n * basePath: '/a2a/',\n * exposeAgentCard: true,\n * exposeDefaultRoutes: true\n * })\n *\n * // Access the Express app for additional routes\n * result.app.get('/health', (req, res) => res.json({ status: 'ok' }))\n * ```\n */\n static start(options: PaymentsA2AServerOptions): PaymentsA2AServerResult {\n const {\n agentCard,\n executor,\n paymentsService,\n port,\n taskStore,\n basePath = '/',\n exposeAgentCard = true,\n exposeDefaultRoutes = true,\n expressApp,\n customRequestHandler,\n handlerOptions,\n hooks,\n } = options\n\n // Initialize components\n const store = taskStore || new InMemoryTaskStore()\n const handler =\n customRequestHandler ||\n new PaymentsRequestHandler(\n agentCard,\n store,\n executor,\n paymentsService,\n undefined,\n handlerOptions,\n )\n const transport = new JsonRpcTransportHandler(handler)\n\n const app = expressApp || express()\n\n if (exposeAgentCard) {\n const agentCardPath =\n basePath === '/'\n ? '/.well-known/agent.json'\n : `${basePath.replace(/\\/$/, '')}/.well-known/agent.json`\n app.get(agentCardPath, (req, res) => {\n res.json(agentCard)\n })\n }\n\n if (exposeDefaultRoutes) {\n // Apply bearer token middleware for all requests under basePath\n app.use(basePath, express.json(), bearerTokenMiddleware.bind(null, handler))\n\n // Apply hooks middleware after body parsing and validation\n if (hooks) {\n app.use(basePath, (req, res, next) => {\n if (req.method === 'POST' && req.body?.method) {\n const { method, params } = req.body\n\n // Apply beforeRequest hook\n if (hooks.beforeRequest) {\n hooks.beforeRequest(method, params, req).catch((err) => {\n console.error('[HOOKS] beforeRequest error:', err)\n })\n }\n\n // Apply afterRequest hook by intercepting res.json\n const originalJson = res.json\n res.json = function (data) {\n if (hooks.afterRequest) {\n hooks.afterRequest(method, data, req).catch((err) => {\n console.error('[HOOKS] afterRequest error:', err)\n })\n }\n return originalJson.call(this, data)\n }\n\n // Apply onError hook by catching errors\n const originalSend = res.send\n res.send = function (data) {\n if (data?.error && hooks.onError) {\n hooks\n .onError(method, new Error(data.error.message || 'Unknown error'), req)\n .catch((err) => {\n console.error('[HOOKS] onError error:', err)\n })\n }\n return originalSend.call(this, data)\n }\n }\n next()\n })\n }\n\n app.post(basePath, async (req, res) => {\n try {\n const result = await transport.handle(req.body)\n await sendRpcResult(res, result)\n } catch (err: any) {\n res.status(500).json({\n error: { code: -32603, message: err?.message || 'Internal server error' },\n })\n }\n })\n }\n\n const server = http.createServer(app)\n\n // Add error handling for server startup\n server.on('error', (error: any) => {\n console.error(`[PaymentsA2A] Server error:`, error)\n if (error.code === 'EADDRINUSE') {\n console.error(`[PaymentsA2A] Port ${port} is already in use`)\n }\n })\n\n // If port is 0, the OS will assign a free port automatically\n let actualPort = port\n let isListening = false\n\n // Only start listening if port is not 0 (0 is used with supertest which doesn't need listening)\n if (port !== 0) {\n server.listen(port, () => {\n const address = server.address()\n if (address && typeof address === 'object') {\n actualPort = address.port\n }\n isListening = true\n })\n }\n\n /**\n * Closes the server and all active connections.\n */\n const close = async (): Promise<void> => {\n if (!isListening && port === 0) {\n return\n }\n\n return new Promise<void>((resolve) => {\n // Close all active connections first\n if (server.listening) {\n server.closeAllConnections()\n }\n\n const timeout = setTimeout(() => {\n // Force close on timeout\n if (server.listening) {\n server.closeAllConnections()\n }\n server.close(() => {\n resolve()\n })\n }, 5000)\n\n if (server.listening) {\n server.close(() => {\n clearTimeout(timeout)\n // Give a moment for all connections to close\n setTimeout(resolve, 100)\n })\n } else {\n clearTimeout(timeout)\n resolve()\n }\n })\n }\n\n return { app, server, handler, port: actualPort, close }\n }\n}\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/a2a/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,OAAO,MAAM,SAAS,CAAA;AAC7B,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAiB,MAAM,oBAAoB,CAAA;AAE9F,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAA;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAA;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAE5D;;GAEG;AACH,SAAS,eAAe,CAAI,KAAU;IACpC,OAAO,KAAK,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,aAAa,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,OAAO,EAAE,EAAE;gBACnC,qCAAqC;gBACrC,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;oBACrB,MAAM,CAAC,mBAAmB,EAAE,CAAA;gBAC9B,CAAC;gBAED,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE;oBAC9B,yBAAyB;oBACzB,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;wBACrB,MAAM,CAAC,mBAAmB,EAAE,CAAA;oBAC9B,CAAC;oBACD,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;wBAChB,OAAO,EAAE,CAAA;oBACX,CAAC,CAAC,CAAA;gBACJ,CAAC,EAAE,IAAI,CAAC,CAAA;gBAER,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;oBACrB,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;wBAChB,YAAY,CAAC,OAAO,CAAC,CAAA;wBACrB,6CAA6C;wBAC7C,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;oBAC1B,CAAC,CAAC,CAAA;gBACJ,CAAC;qBAAM,CAAC;oBACN,YAAY,CAAC,OAAO,CAAC,CAAA;oBACrB,OAAO,EAAE,CAAA;gBACX,CAAC;YACH,CAAC,CAAC,CAAA;QACJ,CAAC,CAAA;QAED,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,CAAA;IAC1D,CAAC;CACF","sourcesContent":["/**\n * PaymentsA2AServer sets up and starts the A2A server for payments agents.\n * Handles A2A protocol endpoints and allows optional custom endpoints.\n *\n * The server provides a complete A2A protocol implementation with:\n * - JSON-RPC endpoint for A2A messages\n * - Agent Card endpoint (.well-known/agent.json)\n * - Bearer token extraction and validation\n * - Credit validation and burning\n * - Task execution and streaming\n * - Customizable routes and handlers\n */\nimport express from 'express'\nimport http from 'http'\nimport { InMemoryTaskStore, JsonRpcTransportHandler, AgentExecutor } from '@a2a-js/sdk/server'\nimport type { AgentCard, HttpRequestContext } from './types.js'\nimport { PaymentsRequestHandler } from './paymentsRequestHandler.js'\nimport { buildPaymentRequired } from '../x402/facilitator-api.js'\nimport { X402_HEADERS } from '../x402/express/middleware.js'\n\n/**\n * Checks if a value is an AsyncIterable (used to detect streaming responses)\n */\nfunction isAsyncIterable<T>(value: any): value is AsyncIterable<T> {\n return value && typeof value[Symbol.asyncIterator] === 'function'\n}\n\n/**\n * Sends a JSON-RPC result. If it's an async iterator, streams as SSE; otherwise returns JSON.\n */\nasync function sendRpcResult(res: express.Response, result: any): Promise<void> {\n if (isAsyncIterable(result)) {\n res.setHeader('Content-Type', 'text/event-stream')\n res.setHeader('Cache-Control', 'no-cache')\n res.setHeader('Connection', 'keep-alive')\n const anyRes = res as any\n if (typeof anyRes.flushHeaders === 'function') anyRes.flushHeaders()\n try {\n for await (const chunk of result as AsyncGenerator<any, void, undefined>) {\n res.write(`data: ${JSON.stringify(chunk)}\\n\\n`)\n }\n } catch (err: any) {\n const errorEvent = {\n jsonrpc: '2.0',\n error: { code: err?.code || -32603, message: err?.message || 'Internal streaming error' },\n }\n res.write(`data: ${JSON.stringify(errorEvent)}\\n\\n`)\n }\n res.end()\n return\n }\n res.json(result)\n}\n\n/**\n * Options for starting the PaymentsA2AServer.\n * Provides comprehensive configuration for A2A server setup.\n */\nexport interface PaymentsA2AServerOptions {\n /** The agent card defining the agent's capabilities and metadata */\n agentCard: AgentCard\n /** User-implemented executor for handling A2A tasks */\n executor: AgentExecutor\n /** Payments service instance for credit validation and burning */\n paymentsService: any\n /** Port number to bind the server to */\n /** Port number to listen on. Use 0 for automatic port assignment. */\n port: number\n /** Custom task store implementation (defaults to InMemoryTaskStore) */\n taskStore?: any\n /** Base path for all A2A routes (defaults to '/') */\n basePath?: string\n /** Whether to expose the agent card at .well-known/agent.json */\n exposeAgentCard?: boolean\n /** Whether to expose default A2A JSON-RPC routes */\n exposeDefaultRoutes?: boolean\n /** Custom Express app instance (defaults to new express()) */\n expressApp?: express.Express\n /** Custom request handler to override JSON-RPC method handling */\n customRequestHandler?: any\n /** Options for configuring the PaymentsRequestHandler behavior */\n handlerOptions?: {\n asyncExecution?: boolean\n defaultBatch?: boolean\n defaultMarginPercent?: number\n }\n /** Hooks for intercepting requests before/after processing */\n hooks?: {\n /** Called before processing any JSON-RPC request */\n beforeRequest?: (method: string, params: any, req: express.Request) => Promise<void>\n /** Called after processing any JSON-RPC request */\n afterRequest?: (method: string, result: any, req: express.Request) => Promise<void>\n /** Called when a JSON-RPC request fails */\n onError?: (method: string, error: Error, req: express.Request) => Promise<void>\n }\n}\n\n/**\n * Result returned by the server start method.\n * Contains the Express app and HTTP server instances for further customization.\n */\nexport interface PaymentsA2AServerResult {\n /** The configured Express application */\n app: express.Express\n /** The HTTP server instance */\n server: http.Server\n /** The request handler instance for direct access if needed */\n handler: PaymentsRequestHandler\n /** The actual port the server is listening on */\n port: number\n /**\n * Closes the server and all active connections.\n * @returns Promise that resolves when the server is fully closed\n */\n close: () => Promise<void>\n}\n\n/**\n * Middleware to extract payment token from HTTP headers and store it in the global context.\n * This middleware is applied after A2A routes are set up and extracts authentication\n * information for credit validation.\n *\n * Accepts tokens from:\n * - payment-signature header (x402 HTTP transport spec v2)\n *\n * @param req - Express request object\n * @param res - Express response object\n * @param next - Express next function\n */\nasync function bearerTokenMiddleware(\n handler: PaymentsRequestHandler,\n req: express.Request,\n res: express.Response,\n next: express.NextFunction,\n) {\n // Only process POST requests (A2A uses POST for all operations)\n if (req.method !== 'POST') {\n return next()\n }\n\n // Transform relative URL to absolute URL\n const absoluteUrl = new URL(req.originalUrl, req.protocol + '://' + req.get('host')).toString()\n\n const agentCard = await handler.getAgentCard()\n const paymentExtension = agentCard.capabilities?.extensions?.find(\n (ext) => ext.uri === 'urn:nevermined:payment',\n )\n\n if (!paymentExtension?.params?.agentId) {\n res.status(402).json({\n error: {\n code: -32001,\n message: 'Agent ID not found in agent card payment extension.',\n },\n })\n return\n }\n\n // Build paymentRequired for 402 responses\n const planId = (paymentExtension.params?.planId as string) || ''\n const agentId = paymentExtension.params?.agentId as string\n const paymentRequired = buildPaymentRequired(planId, {\n endpoint: absoluteUrl,\n agentId,\n httpVerb: 'POST',\n })\n const paymentRequiredHeader = Buffer.from(JSON.stringify(paymentRequired)).toString('base64')\n\n // x402 HTTP spec v2: payment-signature header\n const bearerToken = req.headers['payment-signature'] as string | undefined\n\n if (!bearerToken) {\n res\n .status(402)\n .set(X402_HEADERS.PAYMENT_REQUIRED, paymentRequiredHeader)\n .json({\n error: {\n code: -32001,\n message: 'Missing payment-signature header.',\n },\n })\n return\n }\n\n let validation: any\n try {\n validation = await handler.validateRequest(bearerToken, absoluteUrl, req.method)\n if (!validation?.balance?.isSubscriber) {\n res.status(402).json({\n error: {\n code: -32001,\n message: 'Insufficient credits or invalid request.',\n },\n })\n return\n }\n } catch (err) {\n res.status(402).json({\n error: {\n code: -32001,\n message: 'Payment validation failed: ' + (err instanceof Error ? err.message : String(err)),\n },\n })\n return\n }\n\n const context: HttpRequestContext = {\n bearerToken,\n urlRequested: absoluteUrl,\n httpMethodRequested: req.method,\n validation,\n }\n // Try to associate context with taskId or messageId\n const taskId = req.body?.taskId\n const messageId = req.body?.params?.message?.messageId\n\n if (taskId) {\n handler.setHttpRequestContextForTask(taskId, context)\n } else if (messageId) {\n handler.setHttpRequestContextForMessage(messageId, context)\n }\n\n next()\n}\n\n/**\n * PaymentsA2AServer sets up the A2A endpoints and starts the server.\n *\n * This class provides a complete A2A protocol implementation with payment integration.\n * It handles:\n * - JSON-RPC message routing\n * - Agent card exposure\n * - Bearer token extraction\n * - Credit validation and burning\n * - Task execution and streaming\n * - Customizable routes and handlers\n *\n * @example\n * ```typescript\n * const server = PaymentsA2AServer.start({\n * agentCard: myAgentCard,\n * executor: new MyExecutor(),\n * paymentsService: payments,\n * port: 41242,\n * basePath: '/a2a/',\n * hooks: {\n * beforeRequest: async (method, params, req) => {\n * console.log(`Processing ${method} request`)\n * }\n * }\n * })\n * ```\n */\nexport class PaymentsA2AServer {\n /**\n * Starts the A2A server with the given options.\n *\n * This method sets up the complete A2A server infrastructure including:\n * - Express app configuration\n * - A2A route setup\n * - Middleware for bearer token extraction\n * - Agent card endpoint\n * - HTTP server creation and binding\n *\n * @param options - Server configuration options\n * @returns Server result containing app, server, adapter, and handler instances\n *\n * @example\n * ```typescript\n * const result = PaymentsA2AServer.start({\n * agentCard: buildPaymentAgentCard(baseCard, paymentMetadata),\n * executor: new MyPaymentsExecutor(),\n * paymentsService: payments,\n * port: 41242,\n * basePath: '/a2a/',\n * exposeAgentCard: true,\n * exposeDefaultRoutes: true\n * })\n *\n * // Access the Express app for additional routes\n * result.app.get('/health', (req, res) => res.json({ status: 'ok' }))\n * ```\n */\n static start(options: PaymentsA2AServerOptions): PaymentsA2AServerResult {\n const {\n agentCard,\n executor,\n paymentsService,\n port,\n taskStore,\n basePath = '/',\n exposeAgentCard = true,\n exposeDefaultRoutes = true,\n expressApp,\n customRequestHandler,\n handlerOptions,\n hooks,\n } = options\n\n // Initialize components\n const store = taskStore || new InMemoryTaskStore()\n const handler =\n customRequestHandler ||\n new PaymentsRequestHandler(\n agentCard,\n store,\n executor,\n paymentsService,\n undefined,\n handlerOptions,\n )\n const transport = new JsonRpcTransportHandler(handler)\n\n const app = expressApp || express()\n\n if (exposeAgentCard) {\n const agentCardPath =\n basePath === '/'\n ? '/.well-known/agent.json'\n : `${basePath.replace(/\\/$/, '')}/.well-known/agent.json`\n app.get(agentCardPath, (req, res) => {\n res.json(agentCard)\n })\n }\n\n if (exposeDefaultRoutes) {\n // Apply bearer token middleware for all requests under basePath\n app.use(basePath, express.json(), (req, res, next) => {\n bearerTokenMiddleware(handler, req, res, next).catch(next)\n })\n\n // Apply hooks middleware after body parsing and validation\n if (hooks) {\n app.use(basePath, (req, res, next) => {\n if (req.method === 'POST' && req.body?.method) {\n const { method, params } = req.body\n\n // Apply beforeRequest hook\n if (hooks.beforeRequest) {\n hooks.beforeRequest(method, params, req).catch((err) => {\n console.error('[HOOKS] beforeRequest error:', err)\n })\n }\n\n // Apply afterRequest hook by intercepting res.json\n const originalJson = res.json\n res.json = function (data) {\n if (hooks.afterRequest) {\n hooks.afterRequest(method, data, req).catch((err) => {\n console.error('[HOOKS] afterRequest error:', err)\n })\n }\n return originalJson.call(this, data)\n }\n\n // Apply onError hook by catching errors\n const originalSend = res.send\n res.send = function (data) {\n if (data?.error && hooks.onError) {\n hooks\n .onError(method, new Error(data.error.message || 'Unknown error'), req)\n .catch((err) => {\n console.error('[HOOKS] onError error:', err)\n })\n }\n return originalSend.call(this, data)\n }\n }\n next()\n })\n }\n\n app.post(basePath, async (req, res) => {\n try {\n const result = await transport.handle(req.body)\n await sendRpcResult(res, result)\n } catch (err: any) {\n if (res.headersSent) {\n console.error('[PaymentsA2A] Error after headers sent:', err?.message)\n res.end()\n return\n }\n res.status(500).json({\n error: { code: -32603, message: err?.message || 'Internal server error' },\n })\n }\n })\n }\n\n const server = http.createServer(app)\n\n // Add error handling for server startup\n server.on('error', (error: any) => {\n console.error(`[PaymentsA2A] Server error:`, error)\n if (error.code === 'EADDRINUSE') {\n console.error(`[PaymentsA2A] Port ${port} is already in use`)\n }\n })\n\n // If port is 0, the OS will assign a free port automatically\n let actualPort = port\n let isListening = false\n\n // Only start listening if port is not 0 (0 is used with supertest which doesn't need listening)\n if (port !== 0) {\n server.listen(port, () => {\n const address = server.address()\n if (address && typeof address === 'object') {\n actualPort = address.port\n }\n isListening = true\n })\n }\n\n /**\n * Closes the server and all active connections.\n */\n const close = async (): Promise<void> => {\n if (!isListening && port === 0) {\n return\n }\n\n return new Promise<void>((resolve) => {\n // Close all active connections first\n if (server.listening) {\n server.closeAllConnections()\n }\n\n const timeout = setTimeout(() => {\n // Force close on timeout\n if (server.listening) {\n server.closeAllConnections()\n }\n server.close(() => {\n resolve()\n })\n }, 5000)\n\n if (server.listening) {\n server.close(() => {\n clearTimeout(timeout)\n // Give a moment for all connections to close\n setTimeout(resolve, 100)\n })\n } else {\n clearTimeout(timeout)\n resolve()\n }\n })\n }\n\n return { app, server, handler, port: actualPort, close }\n }\n}\n"]}
@@ -178,6 +178,12 @@ export interface RequestContext {
178
178
  userMessage: Message;
179
179
  /** Unique identifier for the task */
180
180
  taskId: string;
181
+ /** Unique identifier for the context/conversation */
182
+ contextId: string;
183
+ /** Any existing task state (for task continuation scenarios) */
184
+ task?: Task;
185
+ /** Reference tasks for multi-turn conversations */
186
+ referenceTasks?: Task[];
181
187
  /** Additional metadata from the original request */
182
188
  requestMetadata?: Record<string, any>;
183
189
  /** Any existing task state (for task continuation scenarios) */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/a2a/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EACV,SAAS,EACT,IAAI,EACJ,OAAO,EACP,QAAQ,EACR,SAAS,EACT,IAAI,EACJ,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,qCAAqC,EACrC,YAAY,EACZ,qCAAqC,EACtC,MAAM,aAAa,CAAA;AAEpB,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAC1E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAC3D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAE9C;;;;;GAKG;AACH,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,IAAI,GAAG,qBAAqB,GAAG,uBAAuB,CAAA;AAE7F;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,WAAW;IAC1B,gEAAgE;IAChE,WAAW,EAAE,OAAO,CAAA;IACpB,gEAAgE;IAChE,YAAY,CAAC,EAAE,IAAI,CAAA;IACnB,6DAA6D;IAC7D,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,oDAAoD;IACpD,eA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