@nevermined-io/payments 1.12.0 → 1.14.0

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 (98) hide show
  1. package/README.md +33 -0
  2. package/dist/a2a/clientRegistry.d.ts +10 -1
  3. package/dist/a2a/clientRegistry.d.ts.map +1 -1
  4. package/dist/a2a/clientRegistry.js +13 -4
  5. package/dist/a2a/clientRegistry.js.map +1 -1
  6. package/dist/a2a/paymentsClient.d.ts +60 -3
  7. package/dist/a2a/paymentsClient.d.ts.map +1 -1
  8. package/dist/a2a/paymentsClient.js +129 -8
  9. package/dist/a2a/paymentsClient.js.map +1 -1
  10. package/dist/a2a/paymentsRequestHandler.d.ts +5 -1
  11. package/dist/a2a/paymentsRequestHandler.d.ts.map +1 -1
  12. package/dist/a2a/paymentsRequestHandler.js +156 -13
  13. package/dist/a2a/paymentsRequestHandler.js.map +1 -1
  14. package/dist/a2a/types.d.ts +30 -0
  15. package/dist/a2a/types.d.ts.map +1 -1
  16. package/dist/a2a/types.js.map +1 -1
  17. package/dist/api/agents-api.d.ts +4 -3
  18. package/dist/api/agents-api.d.ts.map +1 -1
  19. package/dist/api/agents-api.js +7 -4
  20. package/dist/api/agents-api.js.map +1 -1
  21. package/dist/api/base-payments.d.ts +7 -2
  22. package/dist/api/base-payments.d.ts.map +1 -1
  23. package/dist/api/base-payments.js +15 -8
  24. package/dist/api/base-payments.js.map +1 -1
  25. package/dist/api/nvm-api.d.ts +5 -5
  26. package/dist/api/observability-api/types.d.ts +34 -6
  27. package/dist/api/observability-api/types.d.ts.map +1 -1
  28. package/dist/api/observability-api/types.js.map +1 -1
  29. package/dist/api/plans-api.d.ts +15 -12
  30. package/dist/api/plans-api.d.ts.map +1 -1
  31. package/dist/api/plans-api.js +17 -14
  32. package/dist/api/plans-api.js.map +1 -1
  33. package/dist/api/query-api.d.ts +1 -1
  34. package/dist/common/types.d.ts +175 -18
  35. package/dist/common/types.d.ts.map +1 -1
  36. package/dist/common/types.js.map +1 -1
  37. package/dist/index.d.ts +2 -1
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +1 -0
  40. package/dist/index.js.map +1 -1
  41. package/dist/mcp/core/paywall.d.ts.map +1 -1
  42. package/dist/mcp/core/paywall.js +69 -8
  43. package/dist/mcp/core/paywall.js.map +1 -1
  44. package/dist/mcp/http/index.d.ts +1 -1
  45. package/dist/mcp/http/index.d.ts.map +1 -1
  46. package/dist/mcp/http/index.js +1 -1
  47. package/dist/mcp/http/index.js.map +1 -1
  48. package/dist/mcp/http/oauth-metadata.d.ts +32 -0
  49. package/dist/mcp/http/oauth-metadata.d.ts.map +1 -1
  50. package/dist/mcp/http/oauth-metadata.js +329 -34
  51. package/dist/mcp/http/oauth-metadata.js.map +1 -1
  52. package/dist/mcp/index.d.ts +4 -4
  53. package/dist/mcp/index.d.ts.map +1 -1
  54. package/dist/mcp/index.js +5 -5
  55. package/dist/mcp/index.js.map +1 -1
  56. package/dist/mcp/types/http.types.d.ts +38 -3
  57. package/dist/mcp/types/http.types.d.ts.map +1 -1
  58. package/dist/mcp/types/http.types.js.map +1 -1
  59. package/dist/mcp/types/paywall.types.d.ts +19 -3
  60. package/dist/mcp/types/paywall.types.d.ts.map +1 -1
  61. package/dist/mcp/types/paywall.types.js.map +1 -1
  62. package/dist/mpp/fetch.d.ts +8 -3
  63. package/dist/mpp/fetch.d.ts.map +1 -1
  64. package/dist/mpp/fetch.js +6 -0
  65. package/dist/mpp/fetch.js.map +1 -1
  66. package/dist/mpp/mpp-api.d.ts +11 -5
  67. package/dist/mpp/mpp-api.d.ts.map +1 -1
  68. package/dist/mpp/mpp-api.js +10 -3
  69. package/dist/mpp/mpp-api.js.map +1 -1
  70. package/dist/payments.d.ts.map +1 -1
  71. package/dist/x402/delegation-api.d.ts +5 -17
  72. package/dist/x402/delegation-api.d.ts.map +1 -1
  73. package/dist/x402/delegation-api.js +2 -2
  74. package/dist/x402/delegation-api.js.map +1 -1
  75. package/dist/x402/express/middleware.d.ts.map +1 -1
  76. package/dist/x402/express/middleware.js +98 -1
  77. package/dist/x402/express/middleware.js.map +1 -1
  78. package/dist/x402/facilitator-api.d.ts +90 -7
  79. package/dist/x402/facilitator-api.d.ts.map +1 -1
  80. package/dist/x402/facilitator-api.js +64 -3
  81. package/dist/x402/facilitator-api.js.map +1 -1
  82. package/dist/x402/index.d.ts +3 -2
  83. package/dist/x402/index.d.ts.map +1 -1
  84. package/dist/x402/index.js +1 -0
  85. package/dist/x402/index.js.map +1 -1
  86. package/dist/x402/token-request.d.ts +8 -0
  87. package/dist/x402/token-request.d.ts.map +1 -1
  88. package/dist/x402/token-request.js +101 -1
  89. package/dist/x402/token-request.js.map +1 -1
  90. package/dist/x402/token-version.d.ts +97 -0
  91. package/dist/x402/token-version.d.ts.map +1 -0
  92. package/dist/x402/token-version.js +127 -0
  93. package/dist/x402/token-version.js.map +1 -0
  94. package/dist/x402/token.d.ts +33 -2
  95. package/dist/x402/token.d.ts.map +1 -1
  96. package/dist/x402/token.js +47 -2
  97. package/dist/x402/token.js.map +1 -1
  98. package/package.json +22 -13
@@ -1 +1 @@
1
- {"version":3,"file":"paymentsClient.js","sourceRoot":"","sources":["../../src/a2a/paymentsClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAA;AAc1D,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAA;AAEnC,OAAO,EAAE,0BAA0B,EAAE,iCAAiC,EAAE,MAAM,iBAAiB,CAAA;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAE5E;;;GAGG;AACH,MAAM,OAAO,cAAe,SAA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AC,CAAC,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC;oBAAE,MAAM,CAAC,CAAA;gBAC5F,MAAM,IAAI,KAAK,CACb,kBAAkB,MAAM,aAAa,YAAY,CAAC,MAAM,IAAI,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 { resolveScheme } from '../x402/facilitator-api.js'\nimport type { X402TokenOptions, DelegationConfig } from '../common/types.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'\nimport { AGENT_CARD_WELL_KNOWN_PATH, LEGACY_AGENT_CARD_WELL_KNOWN_PATH } from './agent-card.js'\nimport { decodeAccessToken } from '../utils.js'\nimport { PaymentStatus, x402A2AUtils, X402A2AMetadata } from './x402-a2a.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 readonly delegationConfig?: DelegationConfig\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-card.json').\n */\n private constructor(\n agentCard: AgentCard,\n payments: Payments,\n agentId: string,\n planId: string,\n delegationConfig?: DelegationConfig,\n ) {\n super(agentCard)\n this.payments = payments\n this.agentId = agentId\n this.planId = planId\n this.delegationConfig = delegationConfig\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 = AGENT_CARD_WELL_KNOWN_PATH,\n delegationConfig?: DelegationConfig,\n ): Promise<PaymentsClient> {\n const agentCard = await PaymentsClient._fetchAgentCard(agentBaseUrl, agentCardPath)\n return new PaymentsClient(agentCard, payments, agentId, planId, delegationConfig)\n }\n\n /**\n * Fetches a remote agent card, trying the requested (canonical) path first and\n * falling back to the legacy '.well-known/agent.json' so updated clients keep\n * working against agents that have not adopted the canonical path yet.\n * TODO(a2a): drop the fallback one release after agents are updated.\n */\n private static async _fetchAgentCard(\n agentBaseUrl: string,\n agentCardPath: string,\n ): Promise<AgentCard> {\n const load = async (path: string): Promise<AgentCard> => {\n const a2a = await A2AClient.fromCardUrl(new URL(path, agentBaseUrl).toString())\n return (await (a2a as any).getAgentCard()) as AgentCard\n }\n try {\n return await load(agentCardPath)\n } catch (err) {\n if (agentCardPath === LEGACY_AGENT_CARD_WELL_KNOWN_PATH) {\n throw err\n }\n // Canonical path failed — fall back to the legacy path. Warn, because a\n // silent fallback to a typosquattable legacy path is a discovery risk.\n console.warn(\n `[PaymentsA2A] agent card not found at '${agentCardPath}', falling back to '${LEGACY_AGENT_CARD_WELL_KNOWN_PATH}':`,\n err instanceof Error ? err.message : String(err),\n )\n try {\n return await load(LEGACY_AGENT_CARD_WELL_KNOWN_PATH)\n } catch (legacyErr) {\n // Both failed. Surface the legacy error but preserve the canonical-path\n // root cause (a TLS/DNS/5xx there is otherwise masked by a clean 404).\n const message = legacyErr instanceof Error ? legacyErr.message : String(legacyErr)\n // `new Error(msg, { cause })` would be idiomatic but the ES2020 lib target\n // types Error with 0-1 args, so attach `cause` via Object.assign instead.\n throw Object.assign(\n new Error(\n `Failed to fetch agent card from '${agentCardPath}' or legacy '${LEGACY_AGENT_CARD_WELL_KNOWN_PATH}': ${message}`,\n ),\n { cause: err },\n )\n }\n }\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 scheme = await resolveScheme(this.payments, this.planId)\n if (!this.delegationConfig) {\n throw PaymentsError.internal(\n `${scheme} scheme requires delegationConfig. Pass it to PaymentsClient.create().`,\n )\n }\n let tokenOptions: X402TokenOptions | undefined\n if (scheme !== 'nvm:erc4337') {\n tokenOptions = { scheme, delegationConfig: this.delegationConfig }\n } else {\n tokenOptions = { delegationConfig: this.delegationConfig }\n }\n const accessParams = await this.payments.x402.getX402AccessToken(\n this.planId,\n this.agentId,\n tokenOptions,\n )\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 * Build the in-band x402 message metadata (x402 v2 A2A transport).\n *\n * The server consumes the same base64 access token whether it arrives in the\n * deprecated `payment-signature` header or in band, so the in-band\n * `x402.payment.payload` is just the decoded PaymentPayload object. Falls back\n * to wrapping the raw token if it is not decodable (never expected for real\n * Nevermined tokens, which are base64 JSON).\n *\n * @param accessToken - The x402 access token string\n * @returns The message-metadata fragment carrying status + payload\n */\n private _buildInBandPaymentMetadata(accessToken: string): Record<string, unknown> {\n const payload = decodeAccessToken(accessToken) ?? { token: accessToken }\n return {\n [X402A2AMetadata.STATUS_KEY]: PaymentStatus.PAYMENT_SUBMITTED,\n [X402A2AMetadata.PAYLOAD_KEY]: payload,\n }\n }\n\n /**\n * Return a copy of the message params with the in-band x402 payment metadata\n * merged into `message.metadata`, optionally correlating to a taskId returned\n * by a prior `input-required` (payment-required) response. Immutable: the\n * caller's params object is never mutated.\n *\n * @param params - The original message send params\n * @param accessToken - The x402 access token to embed in band\n * @param taskId - Optional taskId to correlate a payment-required follow-up\n */\n private _withInBandPayment(\n params: MessageSendParams,\n accessToken: string,\n taskId?: string,\n ): MessageSendParams {\n return {\n ...params,\n message: {\n ...params.message,\n ...(taskId ? { taskId } : {}),\n metadata: {\n ...(params.message.metadata || {}),\n ...this._buildInBandPaymentMetadata(accessToken),\n },\n },\n }\n }\n\n /**\n * Detect a payment-required response (x402 v2 A2A transport): an\n * `input-required` task whose status message carries\n * `x402.payment.status: payment-required`. Returns the task id to correlate a\n * follow-up payment, or `undefined` when the response is not payment-required.\n *\n * @param response - The JSON-RPC send-message response\n */\n private _paymentRequiredTaskId(response: SendMessageResponse): string | undefined {\n if (this.isErrorResponse(response as JSONRPCResponse)) {\n return undefined\n }\n const result = (response as { result?: any }).result\n if (!result || result.kind !== 'task' || result.status?.state !== 'input-required') {\n return undefined\n }\n const status = x402A2AUtils.getPaymentStatus(result)\n return status === PaymentStatus.PAYMENT_REQUIRED ? (result.id as string) : undefined\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 // Primary path (x402 v2 A2A transport): carry the payment in band. Keep the\n // deprecated `payment-signature` header for one release so servers that have\n // not adopted the in-band transport still authorize the request.\n const headers = { 'payment-signature': accessToken }\n const inBandParams = this._withInBandPayment(params, accessToken)\n const response = await this._postRpcRequestWithHeaders<MessageSendParams, SendMessageResponse>(\n 'message/send',\n inBandParams,\n headers,\n )\n\n // Reactive flow: if the server replied with an `input-required`\n // payment-required task (it did not accept the in-band payload, e.g. it sent\n // requirements first), resubmit the payment correlated to that task id.\n const taskId = this._paymentRequiredTaskId(response)\n if (taskId) {\n const followUp = this._withInBandPayment(params, accessToken, taskId)\n return this._postRpcRequestWithHeaders<MessageSendParams, SendMessageResponse>(\n 'message/send',\n followUp,\n headers,\n )\n }\n return response\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 accessToken = await this._getX402AccessToken()\n // Carry the payment in band (x402 v2 A2A transport); keep the deprecated\n // header for one release as a fallback.\n const inBandParams = this._withInBandPayment(params, accessToken)\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'message/stream',\n params: inBandParams as { [key: string]: any },\n id: clientRequestId,\n }\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
+ {"version":3,"file":"paymentsClient.js","sourceRoot":"","sources":["../../src/a2a/paymentsClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAA;AAc1D,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAA;AAEnC,OAAO,EAAE,0BAA0B,EAAE,iCAAiC,EAAE,MAAM,iBAAiB,CAAA;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAE5E;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,SAAS;IAU3C;;;;;;;;OAQG;IACH,YACE,SAAoB,EACpB,QAAkB,EAClB,OAAe,EACf,MAAc,EACd,gBAAmC,EACnC,YAA+B;QAE/B,KAAK,CAAC,SAAS,CAAC,CAAA;QApBV,2BAAsB,GAA4B,IAAI,CAAA;QACtD,oBAAe,GAAG,KAAK,CAAA;QAoB7B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAA;QACxC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAA;IAC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IAAI,kBAAkB,YAAY,CAAC,MAAM,WAAW,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CACzK,CAAA;gBACH,CAAC;qBAAM,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;oBAC9B,MAAM,IAAI,KAAK,CACb,kBAAkB,MAAM,aAAa,YAAY,CAAC,MAAM,IAAI,YAAY,CAAC,UAAU,eAAe,aAAa,EAAE,CAClH,CAAA;gBACH,CAAC;YACH,CAAC;YAAC,OAAO,CAAM,EAAE,CAAC;gBAChB,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC;oBAAE,MAAM,CAAC,CAAA;gBAC5F,MAAM,IAAI,KAAK,CACb,kBAAkB,MAAM,aAAa,YAAY,CAAC,MAAM,IAAI,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 { resolveScheme } from '../x402/facilitator-api.js'\nimport type { X402TokenOptions, DelegationConfig, X402TokenVersion } from '../common/types.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'\nimport { AGENT_CARD_WELL_KNOWN_PATH, LEGACY_AGENT_CARD_WELL_KNOWN_PATH } from './agent-card.js'\nimport { decodeAccessToken } from '../utils.js'\nimport { PaymentStatus, x402A2AUtils, X402A2AMetadata } from './x402-a2a.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 readonly delegationConfig?: DelegationConfig\n private readonly tokenVersion?: X402TokenVersion\n private accessToken: string | null\n private lastMintedTokenVersion: X402TokenVersion | null = null\n private downgradeWarned = false\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-card.json').\n * @param tokenVersion - Optional EIP-712 token version to request (`3` = single-use, bound to this agent's endpoint).\n */\n private constructor(\n agentCard: AgentCard,\n payments: Payments,\n agentId: string,\n planId: string,\n delegationConfig?: DelegationConfig,\n tokenVersion?: X402TokenVersion,\n ) {\n super(agentCard)\n this.payments = payments\n this.agentId = agentId\n this.planId = planId\n this.delegationConfig = delegationConfig\n this.tokenVersion = tokenVersion\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 = AGENT_CARD_WELL_KNOWN_PATH,\n delegationConfig?: DelegationConfig,\n tokenVersion?: X402TokenVersion,\n ): Promise<PaymentsClient> {\n const agentCard = await PaymentsClient._fetchAgentCard(agentBaseUrl, agentCardPath)\n return new PaymentsClient(agentCard, payments, agentId, planId, delegationConfig, tokenVersion)\n }\n\n /**\n * Fetches a remote agent card, trying the requested (canonical) path first and\n * falling back to the legacy '.well-known/agent.json' so updated clients keep\n * working against agents that have not adopted the canonical path yet.\n * TODO(a2a): drop the fallback one release after agents are updated.\n */\n private static async _fetchAgentCard(\n agentBaseUrl: string,\n agentCardPath: string,\n ): Promise<AgentCard> {\n const load = async (path: string): Promise<AgentCard> => {\n const a2a = await A2AClient.fromCardUrl(new URL(path, agentBaseUrl).toString())\n return (await (a2a as any).getAgentCard()) as AgentCard\n }\n try {\n return await load(agentCardPath)\n } catch (err) {\n if (agentCardPath === LEGACY_AGENT_CARD_WELL_KNOWN_PATH) {\n throw err\n }\n // Canonical path failed — fall back to the legacy path. Warn, because a\n // silent fallback to a typosquattable legacy path is a discovery risk.\n console.warn(\n `[PaymentsA2A] agent card not found at '${agentCardPath}', falling back to '${LEGACY_AGENT_CARD_WELL_KNOWN_PATH}':`,\n err instanceof Error ? err.message : String(err),\n )\n try {\n return await load(LEGACY_AGENT_CARD_WELL_KNOWN_PATH)\n } catch (legacyErr) {\n // Both failed. Surface the legacy error but preserve the canonical-path\n // root cause (a TLS/DNS/5xx there is otherwise masked by a clean 404).\n const message = legacyErr instanceof Error ? legacyErr.message : String(legacyErr)\n // `new Error(msg, { cause })` would be idiomatic but the ES2020 lib target\n // types Error with 0-1 args, so attach `cause` via Object.assign instead.\n throw Object.assign(\n new Error(\n `Failed to fetch agent card from '${agentCardPath}' or legacy '${LEGACY_AGENT_CARD_WELL_KNOWN_PATH}': ${message}`,\n ),\n { cause: err },\n )\n }\n }\n }\n\n /**\n * The A2A service endpoint this client talks to — the `resource.url` a v3\n * token is bound to.\n *\n * Resolution failures are RAISED, not swallowed. This runs only on the v3\n * path, where the caller explicitly asked for a seller-bound token: minting\n * without the resource would hand them a single-use token bound to nothing,\n * reporting `tokenVersion: 3`, with no signal that half the guarantee was\n * dropped. Failing here loses a call; failing quietly loses the control.\n *\n * The lookup reaches into `_getServiceEndpoint`, which `@a2a-js/sdk` declares\n * `private` and whose own source says it \"can be made synchronous or\n * deleted\" — so a dependency bump can break it. That is exactly why this must\n * be loud: the alternative is every v3 token silently becoming unbound.\n */\n private async _resolveResourceUrl(): Promise<string> {\n let endpoint: unknown\n try {\n endpoint = await (this as any)._getServiceEndpoint()\n } catch (error) {\n throw PaymentsError.internal(\n 'Could not resolve the A2A service endpoint to bind a tokenVersion 3 access token to: ' +\n `${error instanceof Error ? error.message : String(error)}. A v3 token is bound to one ` +\n 'resource URL, so it cannot be minted without it. Use tokenVersion 2, or fix the agent ' +\n 'card / service endpoint.',\n )\n }\n if (typeof endpoint !== 'string' || endpoint.length === 0) {\n throw PaymentsError.internal(\n 'The A2A service endpoint resolved to an empty value, so a tokenVersion 3 access token ' +\n 'cannot be bound to it. Use tokenVersion 2, or fix the agent card / service endpoint.',\n )\n }\n return endpoint\n }\n\n /**\n * Gets the access token for this client instance, caching it only when the\n * token is reusable.\n *\n * A v2 token is a reusable bearer credential, so it is cached for the client's\n * lifetime exactly as before. A **v3 token is consumed by its first\n * settlement**, so caching one would make every paid call after the first\n * settle against a spent nonce (`BCK.X402.0059`) — a v3 token is therefore\n * minted per request and never stored.\n *\n * The version is read off the minted token, never inferred from what was\n * requested: a backend that predates the v3 struct silently mints v2, and a\n * backend whose default has flipped to v3 mints v3 without being asked.\n *\n * @returns The access token string.\n */\n private async _getX402AccessToken(): Promise<string> {\n if (this.accessToken) {\n return this.accessToken\n }\n const scheme = await resolveScheme(this.payments, this.planId)\n if (!this.delegationConfig) {\n throw PaymentsError.internal(\n `${scheme} scheme requires delegationConfig. Pass it to PaymentsClient.create().`,\n )\n }\n // The resource binding is attached ONLY when v3 was explicitly requested.\n // It is not inert on a v2 token: the backend compares the token's\n // `resource.url` against the seller's `paymentRequired.resource.url`\n // (origin + path, falling back to an exact string compare for anything it\n // cannot parse as a URL), so a resource that does not match what the seller\n // advertises fails verification with `BCK.X402.0013` — a binding nobody\n // asked for can only cost the caller a failed verify.\n //\n // The ABSOLUTE service endpoint is the right string for this client's\n // counterparty specifically: an A2A seller built on this SDK advertises\n // `new URL(req.originalUrl, protocol + host)` (`src/a2a/server.ts`), not\n // the relative `req.originalUrl` that the Express `paymentMiddleware`\n // advertises for plain HTTP agents. Every A2A call is a POST to the one\n // JSON-RPC service endpoint, so a single binding covers all of them.\n let binding: Pick<X402TokenOptions, 'resource' | 'httpVerb' | 'tokenVersion'> = {}\n if (this.tokenVersion === 3) {\n binding = {\n resource: { url: await this._resolveResourceUrl() },\n httpVerb: 'POST',\n tokenVersion: 3,\n }\n }\n let tokenOptions: X402TokenOptions | undefined\n if (scheme !== 'nvm:erc4337') {\n tokenOptions = { scheme, delegationConfig: this.delegationConfig, ...binding }\n } else {\n tokenOptions = { delegationConfig: this.delegationConfig, ...binding }\n }\n const accessParams = await this.payments.x402.getX402AccessToken(\n this.planId,\n this.agentId,\n tokenOptions,\n )\n this.lastMintedTokenVersion = accessParams.tokenVersion ?? null\n // A caller who asked for v3 and got v2 asked for single-use + seller\n // binding and received neither. Caching it is still the correct handling of\n // a genuinely reusable token, but it must not be the only trace: say so\n // once, and expose the minted version so callers can branch the way\n // getX402AccessToken's own return value lets them.\n if (accessParams.tokenVersion === 3) {\n // The current downgrade episode is over: a later one is new information\n // and gets its own warning, rather than being swallowed by a flag set\n // once for the lifetime of the client.\n this.downgradeWarned = false\n } else if (this.tokenVersion === 3 && !this.downgradeWarned) {\n this.downgradeWarned = true\n console.warn(\n `[x402] tokenVersion 3 was requested but the backend minted v${accessParams.tokenVersion}. ` +\n 'This token is reusable and bound to nothing, and it is cached for the lifetime of this ' +\n 'client. Read PaymentsClient.getLastMintedTokenVersion() to branch on it.',\n )\n }\n // Cache unless the token is single-use. Phrased as \"not v3\" rather than\n // \"is v2\" so an unrecognised or missing version keeps today's caching\n // behaviour instead of silently turning every call into a fresh mint.\n if (accessParams.tokenVersion !== 3) {\n this.accessToken = accessParams.accessToken\n }\n return accessParams.accessToken\n }\n\n /**\n * The EIP-712 version of the token this client minted most recently, or\n * `null` before the first paid call.\n *\n * The version a client was constructed with is a *request*; this is what the\n * backend actually minted. They differ whenever a deployment predates the v3\n * struct (it drops the field and mints v2) or once its default flips the\n * other way — so a caller that needs single-use semantics to hold should\n * check this rather than assume its own argument was honoured.\n *\n * Per-client state answering a per-call question: there is no mint lock, so\n * two concurrent paid calls on a fresh client both mint and the last writer\n * wins. Today they agree — the backend does not change its answer mid-flight\n * — but read this before or after a call, not racing one.\n */\n public getLastMintedTokenVersion(): X402TokenVersion | null {\n return this.lastMintedTokenVersion\n }\n\n /**\n * Clears the cached access token for this client instance.\n *\n * A no-op for the token itself when the last one was single-use (v3): those\n * are never cached. `getLastMintedTokenVersion()` resets to `null` either\n * way — after a clear there is no token in use, and reporting the version of\n * one that has been discarded is worse than reporting nothing.\n *\n * The downgrade flag is deliberately NOT reset here: it tracks the current\n * downgrade episode, which a clear does not end. It is cleared when a v3\n * token is actually minted.\n */\n public clearToken() {\n this.accessToken = null\n this.lastMintedTokenVersion = null\n }\n\n /**\n * Build the in-band x402 message metadata (x402 v2 A2A transport).\n *\n * The server consumes the same base64 access token whether it arrives in the\n * deprecated `payment-signature` header or in band, so the in-band\n * `x402.payment.payload` is just the decoded PaymentPayload object. Falls back\n * to wrapping the raw token if it is not decodable (never expected for real\n * Nevermined tokens, which are base64 JSON).\n *\n * @param accessToken - The x402 access token string\n * @returns The message-metadata fragment carrying status + payload\n */\n private _buildInBandPaymentMetadata(accessToken: string): Record<string, unknown> {\n const payload = decodeAccessToken(accessToken) ?? { token: accessToken }\n return {\n [X402A2AMetadata.STATUS_KEY]: PaymentStatus.PAYMENT_SUBMITTED,\n [X402A2AMetadata.PAYLOAD_KEY]: payload,\n }\n }\n\n /**\n * Return a copy of the message params with the in-band x402 payment metadata\n * merged into `message.metadata`, optionally correlating to a taskId returned\n * by a prior `input-required` (payment-required) response. Immutable: the\n * caller's params object is never mutated.\n *\n * @param params - The original message send params\n * @param accessToken - The x402 access token to embed in band\n * @param taskId - Optional taskId to correlate a payment-required follow-up\n */\n private _withInBandPayment(\n params: MessageSendParams,\n accessToken: string,\n taskId?: string,\n ): MessageSendParams {\n return {\n ...params,\n message: {\n ...params.message,\n ...(taskId ? { taskId } : {}),\n metadata: {\n ...(params.message.metadata || {}),\n ...this._buildInBandPaymentMetadata(accessToken),\n },\n },\n }\n }\n\n /**\n * Detect a payment-required response (x402 v2 A2A transport): an\n * `input-required` task whose status message carries\n * `x402.payment.status: payment-required`. Returns the task id to correlate a\n * follow-up payment, or `undefined` when the response is not payment-required.\n *\n * @param response - The JSON-RPC send-message response\n */\n private _paymentRequiredTaskId(response: SendMessageResponse): string | undefined {\n if (this.isErrorResponse(response as JSONRPCResponse)) {\n return undefined\n }\n const result = (response as { result?: any }).result\n if (!result || result.kind !== 'task' || result.status?.state !== 'input-required') {\n return undefined\n }\n const status = x402A2AUtils.getPaymentStatus(result)\n return status === PaymentStatus.PAYMENT_REQUIRED ? (result.id as string) : undefined\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 // Primary path (x402 v2 A2A transport): carry the payment in band. Keep the\n // deprecated `payment-signature` header for one release so servers that have\n // not adopted the in-band transport still authorize the request.\n const headers = { 'payment-signature': accessToken }\n const inBandParams = this._withInBandPayment(params, accessToken)\n const response = await this._postRpcRequestWithHeaders<MessageSendParams, SendMessageResponse>(\n 'message/send',\n inBandParams,\n headers,\n )\n\n // Reactive flow: if the server replied with an `input-required`\n // payment-required task (it did not accept the in-band payload, e.g. it sent\n // requirements first), resubmit the payment correlated to that task id.\n const taskId = this._paymentRequiredTaskId(response)\n if (taskId) {\n const followUp = this._withInBandPayment(params, accessToken, taskId)\n return this._postRpcRequestWithHeaders<MessageSendParams, SendMessageResponse>(\n 'message/send',\n followUp,\n headers,\n )\n }\n return response\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 accessToken = await this._getX402AccessToken()\n // Carry the payment in band (x402 v2 A2A transport); keep the deprecated\n // header for one release as a fallback.\n const inBandParams = this._withInBandPayment(params, accessToken)\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'message/stream',\n params: inBandParams as { [key: string]: any },\n id: clientRequestId,\n }\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"]}
@@ -94,7 +94,11 @@ export declare class PaymentsRequestHandler extends DefaultRequestHandler {
94
94
  * @param bearerToken - The bearer token for authentication
95
95
  * @param creditsUsed - The number of credits to burn
96
96
  * @param httpContext - Optional HTTP context with endpoint and method information
97
- * @returns Promise resolving to the redemption result
97
+ * @returns The settlement receipt, verbatim as the facilitator returned it. A
98
+ * settle the backend accepted but could not complete comes back as
99
+ * `success: false` with an `errorReason` rather than throwing — see
100
+ * {@link SettlePermissionsResult} for which fields evidence a charge under
101
+ * which billing model.
98
102
  */
99
103
  private executeRedemption;
100
104
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"paymentsRequestHandler.d.ts","sourceRoot":"","sources":["../../src/a2a/paymentsRequestHandler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EACP,iBAAiB,EAEjB,IAAI,EACJ,uBAAuB,EACvB,YAAY,EAEZ,qBAAqB,EACtB,MAAM,aAAa,CAAA;AACpB,OAAO,KAAK,EAAE,wBAAwB,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC7E,OAAO,EAEL,aAAa,EACb,qBAAqB,EAErB,mBAAmB,EACnB,aAAa,EACd,MAAM,oBAAoB,CAAA;AAG3B,OAAO,EAAE,iBAAiB,EAAiB,MAAM,oBAAoB,CAAA;AASrE,OAAO,KAAK,EAEV,cAAc,EAEd,kBAAkB,EAGnB,MAAM,YAAY,CAAA;AAInB;;GAEG;AACH,MAAM,WAAW,6BAA6B;IAC5C,8CAA8C;IAC9C,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,0EAA0E;IAC1E,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,iFAAiF;IACjF,oBAAoB,CAAC,EAAE,MAAM,CAAA;CAC9B;AAED;;;;;GAKG;AACH,qBAAa,sBAAuB,SAAQ,qBAAqB;IAC/D,OAAO,CAAC,eAAe,CAAU;IACjC,OAAO,CAAC,mBAAmB,CAA6C;IACxE,OAAO,CAAC,sBAAsB,CAA6C;IAC3E,OAAO,CAAC,cAAc,CAAS;IAC/B,OA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AAO,CAAC,OAAO,GAAG,IAAI,CAAC;IA0GrE;;;;;;;;OAQG;YACW,sBAAsB;IAgJpC;;;;;OAKG;IACI,iBAAiB,CACtB,MAAM,EAAE,iBAAiB,GACxB,cAAc,CAAC,cAAc,EAAE,IAAI,EAAE,SAAS,CAAC;IA8DlD;;;;;;OAMG;YACW,oBAAoB;IAoClC;;;;OAIG;IACI,0CAA0C,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAQ1F;;;OAGG;IACI,kCAAkC,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IAIlE;;;OAGG;IACH,SAAS,CAAC,YAAY,IAAI,SAAS;IAInC;;;OAGG;IACH,SAAS,CAAC,kBAAkB,IAAI,wBAAwB;IAIxD;;;OAGG;cACa,wBAAwB,CACtC,eAAe,EAAE,GAAG,EACpB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,OAAO,GAChB,OAAO,CAAC,GAAG,CAAC;IAIf;;;OAGG;IACH,SAAS,CAAC,iBAAiB,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG;IAIhD;;;;;OAKG;IACI,WAAW,CAChB,MAAM,EAAE,YAAY,GACnB,cAAc,CAAC,IAAI,GAAG,qBAAqB,GAAG,uBAAuB,EAAE,IAAI,EAAE,SAAS,CAAC;CA8D3F"}
@@ -6,6 +6,121 @@ import { decodeAccessToken } from '../utils.js';
6
6
  import { buildPaymentRequired, } from '../x402/facilitator-api.js';
7
7
  import { x402A2AUtils } from './x402-a2a.js';
8
8
  const terminalStates = ['completed', 'failed', 'canceled', 'rejected'];
9
+ /**
10
+ * A decimal string, and nothing else — no sign, no whitespace, no `0x`/`1e3`,
11
+ * no fractional part. `Number()` accepts every one of those, and worse, maps the
12
+ * empty-ish family (`''`, `' '`, `null`, `[]`, `false`) to **0** rather than
13
+ * `NaN`, so `Number.isFinite` does not catch them. Publishing that 0 would say
14
+ * "you were charged nothing" on a settle we simply could not read — the same
15
+ * class of lie this helper exists to prevent on pay-as-you-go.
16
+ *
17
+ * Same reasoning, same shape as `DECIMAL_INTEGER_STRING` in `mpp/mpp-api.ts`.
18
+ */
19
+ const DECIMAL_INTEGER_STRING = /^\d+$/;
20
+ /**
21
+ * The credits a settle actually redeemed, for `event.metadata.creditsCharged`.
22
+ *
23
+ * Reads {@link SettlePermissionsResult.creditsRedeemed} per billing model rather
24
+ * than trusting it flat, because it does not mean the same thing under both:
25
+ *
26
+ * - `credits` — the plan holds a balance and `creditsRedeemed` is what came out
27
+ * of it. Report it. It can legitimately differ from the credits the request
28
+ * asked to burn (margin-based pricing), which is the whole reason to report
29
+ * the settled figure rather than the requested one.
30
+ * - `pay-as-you-go` — the plan holds no credit balance at all, so
31
+ * `creditsRedeemed` is the string `'0'` *even on a settle that charged the
32
+ * buyer*. Returning that `0` would tell a buyer they were charged nothing for
33
+ * a payment that really happened, so report nothing instead. The charge is
34
+ * referenced by `orderTx` (fiat) or `transaction` (crypto); the credits the
35
+ * request asked to burn remain on the event as `creditsUsed`, so nothing is
36
+ * lost by omitting a figure that has no meaning on this billing model.
37
+ *
38
+ * ⚠️ MCP does the OPPOSITE and that is deliberate — a settled decision (repo
39
+ * owner, on the #443 review), not drift. `_meta['nevermined/credits']` reports
40
+ * the `'0'` because it emits `billingModel` BESIDE it, so a consumer can read
41
+ * it; `creditsCharged` here has no discriminator next to it, so a bare `0`
42
+ * would say "you were charged nothing" about a charge that succeeded. Do not
43
+ * reconcile the two.
44
+ * - absent — a Nevermined API older than the discriminator (`creditsRedeemed`
45
+ * has been on the settle response since 2026-03-25, `billingModel` only since
46
+ * 2026-08-06). Apply the `credits` rule: a missing discriminator must never be
47
+ * read as pay-as-you-go.
48
+ *
49
+ * Mind the type: these are **strings**. `'0'` is truthy while `Number('0') > 0`
50
+ * is false, so a truthiness check and a numeric one disagree on exactly the
51
+ * value that matters.
52
+ *
53
+ * Three ways this returns `undefined`, and they mean different things — the
54
+ * first is a design decision, the other two are faults, which is why only the
55
+ * faults warn:
56
+ *
57
+ * 1. the billing model has no credits figure to report (pay-as-you-go, or any
58
+ * discriminator that is present and is not `credits`) — silent, by design;
59
+ * 2. `creditsRedeemed` is absent, or not a plain decimal string — warns;
60
+ * 3. the value is a decimal string too large for a JS number — warns.
61
+ *
62
+ * @param settlement - The settlement receipt as the facilitator returned it
63
+ * @returns The credits redeemed, or `undefined` per the three cases above
64
+ */
65
+ function resolveCreditsCharged(settlement) {
66
+ // ALLOWLIST, not a denylist. `=== 'pay-as-you-go'` let every other value fall
67
+ // into the credits branch and publish a `0`: `null`, `''`, `'PAY-AS-YOU-GO'`,
68
+ // a future third billing model, a non-string. The response is an unchecked
69
+ // `as SettlePermissionsResult` over `response.json()`, so the union type
70
+ // provides no runtime guarantee and the wrong values are reachable.
71
+ //
72
+ // `undefined` still means `credits` — that is the documented ruling above and
73
+ // it is preserved exactly. What changes is that a discriminator which is
74
+ // present but not `credits` now omits rather than reporting a zero.
75
+ if (settlement.billingModel !== undefined && settlement.billingModel !== 'credits') {
76
+ return undefined;
77
+ }
78
+ // A FAILED settle has no measured redemption to report, so it gets no figure.
79
+ // `settlePermissions` does not throw on one — it returns 200 with
80
+ // `success: false` verbatim — so without this a failure published
81
+ // `creditsCharged` as though it were measured: `{success: false,
82
+ // creditsRedeemed: '7'}` reported 7 credits charged for a settle that charged
83
+ // nothing. The published contract makes that a lie rather than merely noise,
84
+ // because `markdown/a2a-integration.md` defines `0` as "a real figure, not an
85
+ // absence" — a number here asserts the settle completed.
86
+ //
87
+ // ⚠️ `!== true`, not `=== false`, and the asymmetry with `billingModel` above
88
+ // is deliberate. An ABSENT `billingModel` is a documented legacy shape (APIs
89
+ // predating the field) and is read as `credits`; an absent `success` is not a
90
+ // legacy shape — the field has always been there and is declared
91
+ // non-optional — so its absence means the response is malformed, and a
92
+ // malformed response is exactly when not to publish a figure.
93
+ //
94
+ // Silent, like the pay-as-you-go branch: a failed settle is a legitimate
95
+ // outcome the caller already sees on `success`, not a reporting fault.
96
+ if (settlement.success !== true) {
97
+ return undefined;
98
+ }
99
+ const raw = settlement.creditsRedeemed;
100
+ if (typeof raw !== 'string' || !DECIMAL_INTEGER_STRING.test(raw)) {
101
+ // Silence here would be indistinguishable from the pay-as-you-go omission,
102
+ // which is a deliberate design decision rather than a fault. Warn, as
103
+ // `x402/express/middleware.ts` does on this same field.
104
+ console.warn(raw === undefined
105
+ ? `[PaymentsRequestHandler] settle reported no creditsRedeemed; omitting ` +
106
+ `creditsCharged rather than publishing a figure`
107
+ : `[PaymentsRequestHandler] settle reported an unusable creditsRedeemed ` +
108
+ `(${JSON.stringify(raw)}); omitting creditsCharged rather than publishing a figure`);
109
+ return undefined;
110
+ }
111
+ const redeemed = Number(raw);
112
+ if (!Number.isSafeInteger(redeemed)) {
113
+ // The wire carries this as a string precisely because it can exceed what a
114
+ // JS number represents. Above 2^53 the conversion is silently wrong
115
+ // (`'9007199254740993'` becomes 9007199254740992), and a wrong number is
116
+ // worse than no number: the exact value is still on the task, verbatim, in
117
+ // the `x402.payment.receipts` entry that `recordPaymentSuccess` writes.
118
+ console.warn(`[PaymentsRequestHandler] creditsRedeemed ${raw} exceeds Number.MAX_SAFE_INTEGER; ` +
119
+ `omitting creditsCharged rather than publishing a rounded figure`);
120
+ return undefined;
121
+ }
122
+ return redeemed;
123
+ }
9
124
  /**
10
125
  * PaymentsRequestHandler extends DefaultRequestHandler to add payments validation and burning.
11
126
  * It validates credits before executing a task and burns credits after successful execution.
@@ -157,7 +272,11 @@ export class PaymentsRequestHandler extends DefaultRequestHandler {
157
272
  * @param bearerToken - The bearer token for authentication
158
273
  * @param creditsUsed - The number of credits to burn
159
274
  * @param httpContext - Optional HTTP context with endpoint and method information
160
- * @returns Promise resolving to the redemption result
275
+ * @returns The settlement receipt, verbatim as the facilitator returned it. A
276
+ * settle the backend accepted but could not complete comes back as
277
+ * `success: false` with an `errorReason` rather than throwing — see
278
+ * {@link SettlePermissionsResult} for which fields evidence a charge under
279
+ * which billing model.
161
280
  */
162
281
  async executeRedemption(bearerToken, creditsUsed, httpContext) {
163
282
  const decodedAccessToken = decodeAccessToken(bearerToken);
@@ -341,7 +460,13 @@ export class PaymentsRequestHandler extends DefaultRequestHandler {
341
460
  if (!task || !httpContext?.inBand) {
342
461
  return;
343
462
  }
344
- if (settlement && settlement.success === false) {
463
+ // `!== true`, not `=== false` — the same rule as `resolveCreditsCharged` above,
464
+ // for the same reason. `success` is declared non-optional, so its absence means
465
+ // a malformed response rather than a legacy shape, and stamping one of those
466
+ // `payment-completed` publishes the settle's figures under a success banner on
467
+ // the surface a buyer is told to read for the authoritative receipt.
468
+ // `settlePermissions` already reasons this way (`src/x402/facilitator-api.ts`).
469
+ if (settlement && settlement.success !== true) {
345
470
  x402A2AUtils.recordPaymentFailure(task, settlement.errorReason || 'SETTLEMENT_FAILED', settlement);
346
471
  }
347
472
  else if (settlement) {
@@ -393,12 +518,24 @@ export class PaymentsRequestHandler extends DefaultRequestHandler {
393
518
  const httpContext = requestHttpContext ?? this.getHttpRequestContextForTask(event.taskId);
394
519
  // Execute redemption with server configuration for non-batch requests
395
520
  const response = await this.executeRedemption(bearerToken, BigInt(event.metadata.creditsUsed), httpContext);
396
- // Update event metadata with response data
521
+ // `txHash` is the A2A metadata key a buyer is shown for payment
522
+ // support; the settle response reports that id as `transaction`.
523
+ // There is no `txHash` on the wire — see handleTaskFinalization.
397
524
  if (response && event.metadata) {
398
- event.metadata.txHash = response.txHash ?? response.transaction;
399
- event.metadata.creditsCharged = response.amountOfCredits
400
- ? Number(response.amountOfCredits)
401
- : event.metadata.creditsUsed;
525
+ // Only on a settle that SUCCEEDED. `transaction` is documented as
526
+ // an empty string when settlement failed, and a blank id beside a
527
+ // completed task is the same defect as publishing `creditsCharged`
528
+ // for a settle that charged nothing — see resolveCreditsCharged.
529
+ if (response.success === true && response.transaction) {
530
+ event.metadata.txHash = response.transaction;
531
+ }
532
+ // Left unset when the billing model has no credits to report —
533
+ // see resolveCreditsCharged. `creditsUsed` still carries what
534
+ // the request asked to burn.
535
+ const creditsCharged = resolveCreditsCharged(response);
536
+ if (creditsCharged !== undefined) {
537
+ event.metadata.creditsCharged = creditsCharged;
538
+ }
402
539
  }
403
540
  // x402 v2 A2A transport: stamp the settlement receipt onto the
404
541
  // persisted task in band. NOTE: a stream cannot retract the event
@@ -632,14 +769,20 @@ export class PaymentsRequestHandler extends DefaultRequestHandler {
632
769
  // Execute redemption with server configuration for non-batch requests
633
770
  const response = await this.executeRedemption(bearerToken, BigInt(creditsToBurn), httpContext);
634
771
  settlement = response;
635
- // Update event metadata with redemption results
772
+ // Update event metadata with redemption results. `txHash` is the A2A
773
+ // metadata key, not a wire field: the settle response reports the
774
+ // transaction id as `transaction`.
775
+ const creditsCharged = resolveCreditsCharged(response);
776
+ const settled = response.success === true;
636
777
  event.metadata = {
637
778
  ...event.metadata,
638
- txHash: response.txHash ?? response.transaction,
639
- // Store the actual credits charged (especially important for margin-based)
640
- creditsCharged: response.amountOfCredits
641
- ? Number(response.amountOfCredits)
642
- : creditsToBurn,
779
+ // Same rule as `creditsCharged` below: a failed settle has no
780
+ // transaction to name, and `transaction` is an empty string there.
781
+ ...(settled && response.transaction ? { txHash: response.transaction } : {}),
782
+ // The credits actually redeemed, omitted entirely when the billing
783
+ // model has none to report — see resolveCreditsCharged. The credits
784
+ // this request asked to burn stay available as `creditsUsed`.
785
+ ...(creditsCharged !== undefined && { creditsCharged }),
643
786
  };
644
787
  }
645
788
  }