@nevermined-io/payments 1.11.2 → 1.13.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.
- package/README.md +33 -0
- package/dist/a2a/clientRegistry.d.ts +10 -1
- package/dist/a2a/clientRegistry.d.ts.map +1 -1
- package/dist/a2a/clientRegistry.js +13 -4
- package/dist/a2a/clientRegistry.js.map +1 -1
- package/dist/a2a/paymentsClient.d.ts +60 -3
- package/dist/a2a/paymentsClient.d.ts.map +1 -1
- package/dist/a2a/paymentsClient.js +129 -8
- package/dist/a2a/paymentsClient.js.map +1 -1
- package/dist/a2a/types.d.ts +5 -0
- package/dist/a2a/types.d.ts.map +1 -1
- package/dist/a2a/types.js.map +1 -1
- package/dist/api/nvm-api.d.ts +2 -0
- package/dist/api/nvm-api.d.ts.map +1 -1
- package/dist/api/nvm-api.js +4 -0
- package/dist/api/nvm-api.js.map +1 -1
- package/dist/api/orders-api.d.ts +146 -0
- package/dist/api/orders-api.d.ts.map +1 -0
- package/dist/api/orders-api.js +107 -0
- package/dist/api/orders-api.js.map +1 -0
- package/dist/common/types.d.ts +87 -0
- package/dist/common/types.d.ts.map +1 -1
- package/dist/common/types.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/mcp/core/paywall.d.ts.map +1 -1
- package/dist/mcp/core/paywall.js +10 -0
- package/dist/mcp/core/paywall.js.map +1 -1
- package/dist/mpp/fetch.d.ts +8 -3
- package/dist/mpp/fetch.d.ts.map +1 -1
- package/dist/mpp/fetch.js +6 -0
- package/dist/mpp/fetch.js.map +1 -1
- package/dist/mpp/mpp-api.d.ts +11 -5
- package/dist/mpp/mpp-api.d.ts.map +1 -1
- package/dist/mpp/mpp-api.js +10 -3
- package/dist/mpp/mpp-api.js.map +1 -1
- package/dist/payments.d.ts +3 -0
- package/dist/payments.d.ts.map +1 -1
- package/dist/payments.js +4 -0
- package/dist/payments.js.map +1 -1
- package/dist/x402/express/middleware.d.ts.map +1 -1
- package/dist/x402/express/middleware.js +98 -1
- package/dist/x402/express/middleware.js.map +1 -1
- package/dist/x402/facilitator-api.d.ts +90 -7
- package/dist/x402/facilitator-api.d.ts.map +1 -1
- package/dist/x402/facilitator-api.js +64 -3
- package/dist/x402/facilitator-api.js.map +1 -1
- package/dist/x402/index.d.ts +3 -2
- package/dist/x402/index.d.ts.map +1 -1
- package/dist/x402/index.js +1 -0
- package/dist/x402/index.js.map +1 -1
- package/dist/x402/token-request.d.ts +8 -0
- package/dist/x402/token-request.d.ts.map +1 -1
- package/dist/x402/token-request.js +101 -1
- package/dist/x402/token-request.js.map +1 -1
- package/dist/x402/token-version.d.ts +97 -0
- package/dist/x402/token-version.d.ts.map +1 -0
- package/dist/x402/token-version.js +127 -0
- package/dist/x402/token-version.js.map +1 -0
- package/dist/x402/token.d.ts +33 -2
- package/dist/x402/token.d.ts.map +1 -1
- package/dist/x402/token.js +47 -2
- package/dist/x402/token.js.map +1 -1
- package/package.json +1 -1
|
@@ -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,SAAQ,SAAS;I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AAO,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;IACzB,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I,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"]}
|
package/dist/a2a/types.d.ts
CHANGED
|
@@ -123,6 +123,11 @@ export interface ClientRegistryOptions {
|
|
|
123
123
|
planId: string;
|
|
124
124
|
agentCardPath?: string;
|
|
125
125
|
delegationConfig?: import('../common/types.js').DelegationConfig;
|
|
126
|
+
/**
|
|
127
|
+
* EIP-712 token version to request. `3` mints a single-use token bound to the
|
|
128
|
+
* agent's service endpoint, minted per paid call instead of cached.
|
|
129
|
+
*/
|
|
130
|
+
tokenVersion?: import('../common/types.js').X402TokenVersion;
|
|
126
131
|
}
|
|
127
132
|
/**
|
|
128
133
|
* Options for agent interaction methods (used by PaymentsClient).
|
package/dist/a2a/types.d.ts.map
CHANGED
|
@@ -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,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EAAE,mBAAmB,CAAA;CAC/B;AAED;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,OAAO,CAAC,cAAc,EAAE,sBAAsB,EAAE,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC3F,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CACvE;AAGD,YAAY,EACV,SAAS,EACT,IAAI,EACJ,OAAO,EACP,QAAQ,EACR,SAAS,EACT,IAAI,EACJ,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,qCAAqC,EACrC,YAAY,EACZ,qCAAqC,EACrC,iBAAiB,EACjB,aAAa,GACd,CAAA;AAGD,YAAY,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAA"}
|
package/dist/a2a/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/a2a/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG","sourcesContent":["/**\n * Types and interfaces for the A2A payments integration.\n *\n * This module defines the core types and interfaces used throughout the A2A\n * payments integration. It provides:\n * - Task context structures for user executors\n * - Handler result definitions\n * - Payment metadata interfaces\n * - Re-exports of A2A SDK types for convenience\n *\n * These types ensure type safety and provide clear contracts between\n * the user's executor implementation and the payments system.\n */\n\nimport type {\n AgentCard,\n Task,\n Message,\n Artifact,\n TaskState,\n Part,\n TaskStatusUpdateEvent,\n TaskArtifactUpdateEvent,\n PushNotificationConfig,\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\n\nimport type { ExecutionEventBus, AgentExecutor } from '@a2a-js/sdk/server'\nimport type { StartAgentRequest } from '../common/types.ts'\nimport type { Payments } from '../payments.ts'\n\n/**\n * Union type for A2A streaming events\n *\n * This type represents all possible events that can be yielded by A2A streaming methods.\n * It includes messages, tasks, status updates, and artifact updates.\n */\nexport type A2AStreamEvent = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent\n\n/**\n * Context provided to the user's task handler.\n *\n * This interface contains all the information available to the user's\n * executor when handling an A2A task. It includes:\n * - The original user message\n * - Any existing task state (for continuation)\n * - Authentication information\n * - Request metadata\n *\n * The context is created by the PaymentsA2AAdapter and passed to the\n * user's handleTask method.\n */\nexport interface TaskContext {\n /** The original message from the user containing the request */\n userMessage: Message\n /** Any existing task state (for task continuation scenarios) */\n existingTask?: Task\n /** Bearer token for authentication and payment validation */\n bearerToken?: string\n /** Additional metadata from the original request */\n requestMetadata?: Record<string, any>\n /**\n * Emit a streaming event to the client (SSE, WebSocket, etc.) during task execution.\n * This function allows the executor to send intermediate messages or progress updates.\n *\n * @param parts - Array of message parts (text, etc.) to send as a streaming event\n * @param metadata - Optional metadata to include with the event\n */\n emitStreamingEvent?: (parts: Part[], metadata?: Record<string, any>) => void\n}\n\n/**\n * Result returned by the user's task handler.\n *\n * This interface defines the structure that user executors must return\n * from their handleTask method. The result includes:\n * - Parts that will be converted to A2A Message or Artifact objects\n * - Optional metadata for payment tracking and other purposes\n * - Task state information\n *\n * The result is processed by the PaymentsA2AAdapter to create the\n * appropriate A2A protocol objects and handle payment operations.\n */\nexport interface TaskHandlerResult {\n /** Parts that will be converted to A2A Message or Artifact objects */\n parts: Part[]\n /** Optional metadata including payment information and custom data */\n metadata?: PaymentMetadata & Record<string, any>\n /** The final state of the task */\n state?: TaskState\n}\n\n/**\n * Configuration for credit redemption behavior\n *\n * This interface defines how credits should be redeemed for a specific agent.\n * The configuration is set at the server level and cannot be manipulated by clients.\n */\nexport interface PaymentRedemptionConfig {\n /** Whether to use batch processing for redemptions */\n useBatch?: boolean\n /** Whether to use margin-based redemptions (if false, uses fixed credits) */\n useMargin?: boolean\n /** Margin percentage (0-100) when using margin-based redemptions */\n marginPercent?: number\n}\n\n/**\n * Metadata for payment/credits information to be included in A2A objects.\n *\n * This interface defines the payment-related metadata that can be included\n * in task handler results. This metadata is used for:\n * - Credit tracking and validation\n * - Payment processing\n * - Cost reporting\n * - Plan management\n *\n * The metadata is embedded in A2A Message objects and can be used by\n * clients to understand the cost of operations.\n */\nexport interface PaymentMetadata {\n /** Number of credits used for this operation */\n creditsUsed?: number\n /** ID of the payment plan associated with this operation */\n planId?: string\n /** Type of payment model used */\n paymentType?: 'fixed' | 'dynamic'\n /** Human-readable description of the cost */\n costDescription?: string\n /** Agent ID for payment tracking */\n agentId?: string\n /** Configuration for credit redemption behavior */\n redemptionConfig?: PaymentRedemptionConfig\n}\n\n/**\n * Options required to register or retrieve a client in the registry.\n */\nexport interface ClientRegistryOptions {\n agentBaseUrl: string\n agentId: string\n planId: string\n agentCardPath?: string\n delegationConfig?: import('../common/types.js').DelegationConfig\n}\n\n/**\n * Options for agent interaction methods (used by PaymentsClient).\n */\nexport interface AgentOptions {\n agentId: string\n planId?: string\n}\n\n/**\n * HTTP context associated with a task or message (for internal request tracking).\n *\n * INVARIANT — exactly one of two mutually-exclusive states:\n * - **payment-required**: a payment-gated request arrived with NO token, so only\n * `paymentRequired` is set (`bearerToken`/`validation` are absent). The handler\n * short-circuits to an `input-required` task instead of executing the agent.\n * - **authorized**: a token was supplied (in band via `x402.payment.payload` when\n * `inBand` is true, else the deprecated `payment-signature` header), so\n * `bearerToken` + `validation` are set (`paymentRequired` is absent).\n *\n * A `mode`-discriminated union would enforce this at the type level (tracked as a\n * follow-up); for now consumers guard the field they need — e.g. the settlement\n * path asserts `bearerToken` + `validation` are present.\n */\nexport type HttpRequestContext = {\n /** Set only in the authorized state. */\n bearerToken?: string\n urlRequested?: string\n httpMethodRequested?: string\n /** The validated request — set only in the authorized state. */\n validation?: StartAgentRequest\n /**\n * x402 v2 A2A in-band transport: set by the server middleware when a\n * payment-gated request arrives with NO token (neither in-band\n * `x402.payment.payload` nor the deprecated `payment-signature` header). The\n * handler short-circuits and returns an `input-required` task carrying this\n * X402PaymentRequired object under `x402.payment.required`, instead of\n * executing the agent. Set only in the payment-required state.\n */\n paymentRequired?: import('../x402/facilitator-api.js').X402PaymentRequired\n /**\n * Whether the bearer token was supplied in band (via `x402.payment.payload`\n * message metadata) rather than the deprecated `payment-signature` header.\n * When true, settlement receipts are stamped into the task metadata under the\n * spec-defined `x402.payment.*` keys.\n */\n inBand?: boolean\n}\n\n/**\n * Authentication result for A2A requests (equivalent to MCP AuthResult)\n */\nexport interface A2AAuthResult {\n /** The agent request ID for tracking */\n requestId: string\n /** The bearer token for authentication */\n token: string\n /** The agent ID */\n agentId: string\n /** The agent request data */\n agentRequest: StartAgentRequest\n}\n\n/**\n * Agent request context provided to A2A AgentExecutors\n *\n * This context contains all the payment-related data that an AgentExecutor needs\n * to process requests with payment integration. The agent is responsible for\n * calculating and specifying credits in its final response.\n */\nexport interface AgentRequestContext {\n /** Authentication result with request metadata */\n authResult: A2AAuthResult\n /** The HTTP context with request details */\n httpContext: HttpRequestContext\n /** The payments service instance for observability and other operations */\n paymentsService: Payments\n}\n\n/**\n * Base RequestContext interface (local definition based on actual usage)\n *\n * This defines the structure that the A2A SDK RequestContext actually has\n * based on how it's used in PaymentsRequestHandler.\n */\nexport interface RequestContext {\n /** The original message from the user containing the request */\n userMessage: Message\n /** Unique identifier for the task */\n taskId: string\n /** Unique identifier for the context/conversation */\n contextId: string\n /** Any existing task state (for task continuation scenarios) */\n task?: Task\n /** Reference tasks for multi-turn conversations */\n referenceTasks?: Task[]\n /** Additional metadata from the original request */\n requestMetadata?: Record<string, any>\n /** Any existing task state (for task continuation scenarios) */\n existingTask?: Task\n}\n\n/**\n * Extended RequestContext with agent request data injection\n *\n * This extends the standard A2A RequestContext to include agent request context\n * while maintaining compatibility with the A2A protocol.\n */\nexport interface PaymentsRequestContext extends RequestContext {\n /** Agent request context injection (following MCP pattern) */\n payments?: AgentRequestContext\n}\n\n/**\n * Payments-specific AgentExecutor that uses PaymentsRequestContext\n */\nexport interface PaymentsAgentExecutor {\n execute(requestContext: PaymentsRequestContext, eventBus: ExecutionEventBus): Promise<void>\n cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise<void>\n}\n\n// Re-export A2A SDK types for convenience\nexport type {\n AgentCard,\n Task,\n Message,\n Artifact,\n TaskState,\n Part,\n TaskStatusUpdateEvent,\n PushNotificationConfig,\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n ExecutionEventBus,\n AgentExecutor,\n}\n\n// Re-export server options type for convenience\nexport type { PaymentsA2AServerOptions } from './server.ts'\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/a2a/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG","sourcesContent":["/**\n * Types and interfaces for the A2A payments integration.\n *\n * This module defines the core types and interfaces used throughout the A2A\n * payments integration. It provides:\n * - Task context structures for user executors\n * - Handler result definitions\n * - Payment metadata interfaces\n * - Re-exports of A2A SDK types for convenience\n *\n * These types ensure type safety and provide clear contracts between\n * the user's executor implementation and the payments system.\n */\n\nimport type {\n AgentCard,\n Task,\n Message,\n Artifact,\n TaskState,\n Part,\n TaskStatusUpdateEvent,\n TaskArtifactUpdateEvent,\n PushNotificationConfig,\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\n\nimport type { ExecutionEventBus, AgentExecutor } from '@a2a-js/sdk/server'\nimport type { StartAgentRequest } from '../common/types.ts'\nimport type { Payments } from '../payments.ts'\n\n/**\n * Union type for A2A streaming events\n *\n * This type represents all possible events that can be yielded by A2A streaming methods.\n * It includes messages, tasks, status updates, and artifact updates.\n */\nexport type A2AStreamEvent = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent\n\n/**\n * Context provided to the user's task handler.\n *\n * This interface contains all the information available to the user's\n * executor when handling an A2A task. It includes:\n * - The original user message\n * - Any existing task state (for continuation)\n * - Authentication information\n * - Request metadata\n *\n * The context is created by the PaymentsA2AAdapter and passed to the\n * user's handleTask method.\n */\nexport interface TaskContext {\n /** The original message from the user containing the request */\n userMessage: Message\n /** Any existing task state (for task continuation scenarios) */\n existingTask?: Task\n /** Bearer token for authentication and payment validation */\n bearerToken?: string\n /** Additional metadata from the original request */\n requestMetadata?: Record<string, any>\n /**\n * Emit a streaming event to the client (SSE, WebSocket, etc.) during task execution.\n * This function allows the executor to send intermediate messages or progress updates.\n *\n * @param parts - Array of message parts (text, etc.) to send as a streaming event\n * @param metadata - Optional metadata to include with the event\n */\n emitStreamingEvent?: (parts: Part[], metadata?: Record<string, any>) => void\n}\n\n/**\n * Result returned by the user's task handler.\n *\n * This interface defines the structure that user executors must return\n * from their handleTask method. The result includes:\n * - Parts that will be converted to A2A Message or Artifact objects\n * - Optional metadata for payment tracking and other purposes\n * - Task state information\n *\n * The result is processed by the PaymentsA2AAdapter to create the\n * appropriate A2A protocol objects and handle payment operations.\n */\nexport interface TaskHandlerResult {\n /** Parts that will be converted to A2A Message or Artifact objects */\n parts: Part[]\n /** Optional metadata including payment information and custom data */\n metadata?: PaymentMetadata & Record<string, any>\n /** The final state of the task */\n state?: TaskState\n}\n\n/**\n * Configuration for credit redemption behavior\n *\n * This interface defines how credits should be redeemed for a specific agent.\n * The configuration is set at the server level and cannot be manipulated by clients.\n */\nexport interface PaymentRedemptionConfig {\n /** Whether to use batch processing for redemptions */\n useBatch?: boolean\n /** Whether to use margin-based redemptions (if false, uses fixed credits) */\n useMargin?: boolean\n /** Margin percentage (0-100) when using margin-based redemptions */\n marginPercent?: number\n}\n\n/**\n * Metadata for payment/credits information to be included in A2A objects.\n *\n * This interface defines the payment-related metadata that can be included\n * in task handler results. This metadata is used for:\n * - Credit tracking and validation\n * - Payment processing\n * - Cost reporting\n * - Plan management\n *\n * The metadata is embedded in A2A Message objects and can be used by\n * clients to understand the cost of operations.\n */\nexport interface PaymentMetadata {\n /** Number of credits used for this operation */\n creditsUsed?: number\n /** ID of the payment plan associated with this operation */\n planId?: string\n /** Type of payment model used */\n paymentType?: 'fixed' | 'dynamic'\n /** Human-readable description of the cost */\n costDescription?: string\n /** Agent ID for payment tracking */\n agentId?: string\n /** Configuration for credit redemption behavior */\n redemptionConfig?: PaymentRedemptionConfig\n}\n\n/**\n * Options required to register or retrieve a client in the registry.\n */\nexport interface ClientRegistryOptions {\n agentBaseUrl: string\n agentId: string\n planId: string\n agentCardPath?: string\n delegationConfig?: import('../common/types.js').DelegationConfig\n /**\n * EIP-712 token version to request. `3` mints a single-use token bound to the\n * agent's service endpoint, minted per paid call instead of cached.\n */\n tokenVersion?: import('../common/types.js').X402TokenVersion\n}\n\n/**\n * Options for agent interaction methods (used by PaymentsClient).\n */\nexport interface AgentOptions {\n agentId: string\n planId?: string\n}\n\n/**\n * HTTP context associated with a task or message (for internal request tracking).\n *\n * INVARIANT — exactly one of two mutually-exclusive states:\n * - **payment-required**: a payment-gated request arrived with NO token, so only\n * `paymentRequired` is set (`bearerToken`/`validation` are absent). The handler\n * short-circuits to an `input-required` task instead of executing the agent.\n * - **authorized**: a token was supplied (in band via `x402.payment.payload` when\n * `inBand` is true, else the deprecated `payment-signature` header), so\n * `bearerToken` + `validation` are set (`paymentRequired` is absent).\n *\n * A `mode`-discriminated union would enforce this at the type level (tracked as a\n * follow-up); for now consumers guard the field they need — e.g. the settlement\n * path asserts `bearerToken` + `validation` are present.\n */\nexport type HttpRequestContext = {\n /** Set only in the authorized state. */\n bearerToken?: string\n urlRequested?: string\n httpMethodRequested?: string\n /** The validated request — set only in the authorized state. */\n validation?: StartAgentRequest\n /**\n * x402 v2 A2A in-band transport: set by the server middleware when a\n * payment-gated request arrives with NO token (neither in-band\n * `x402.payment.payload` nor the deprecated `payment-signature` header). The\n * handler short-circuits and returns an `input-required` task carrying this\n * X402PaymentRequired object under `x402.payment.required`, instead of\n * executing the agent. Set only in the payment-required state.\n */\n paymentRequired?: import('../x402/facilitator-api.js').X402PaymentRequired\n /**\n * Whether the bearer token was supplied in band (via `x402.payment.payload`\n * message metadata) rather than the deprecated `payment-signature` header.\n * When true, settlement receipts are stamped into the task metadata under the\n * spec-defined `x402.payment.*` keys.\n */\n inBand?: boolean\n}\n\n/**\n * Authentication result for A2A requests (equivalent to MCP AuthResult)\n */\nexport interface A2AAuthResult {\n /** The agent request ID for tracking */\n requestId: string\n /** The bearer token for authentication */\n token: string\n /** The agent ID */\n agentId: string\n /** The agent request data */\n agentRequest: StartAgentRequest\n}\n\n/**\n * Agent request context provided to A2A AgentExecutors\n *\n * This context contains all the payment-related data that an AgentExecutor needs\n * to process requests with payment integration. The agent is responsible for\n * calculating and specifying credits in its final response.\n */\nexport interface AgentRequestContext {\n /** Authentication result with request metadata */\n authResult: A2AAuthResult\n /** The HTTP context with request details */\n httpContext: HttpRequestContext\n /** The payments service instance for observability and other operations */\n paymentsService: Payments\n}\n\n/**\n * Base RequestContext interface (local definition based on actual usage)\n *\n * This defines the structure that the A2A SDK RequestContext actually has\n * based on how it's used in PaymentsRequestHandler.\n */\nexport interface RequestContext {\n /** The original message from the user containing the request */\n userMessage: Message\n /** Unique identifier for the task */\n taskId: string\n /** Unique identifier for the context/conversation */\n contextId: string\n /** Any existing task state (for task continuation scenarios) */\n task?: Task\n /** Reference tasks for multi-turn conversations */\n referenceTasks?: Task[]\n /** Additional metadata from the original request */\n requestMetadata?: Record<string, any>\n /** Any existing task state (for task continuation scenarios) */\n existingTask?: Task\n}\n\n/**\n * Extended RequestContext with agent request data injection\n *\n * This extends the standard A2A RequestContext to include agent request context\n * while maintaining compatibility with the A2A protocol.\n */\nexport interface PaymentsRequestContext extends RequestContext {\n /** Agent request context injection (following MCP pattern) */\n payments?: AgentRequestContext\n}\n\n/**\n * Payments-specific AgentExecutor that uses PaymentsRequestContext\n */\nexport interface PaymentsAgentExecutor {\n execute(requestContext: PaymentsRequestContext, eventBus: ExecutionEventBus): Promise<void>\n cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise<void>\n}\n\n// Re-export A2A SDK types for convenience\nexport type {\n AgentCard,\n Task,\n Message,\n Artifact,\n TaskState,\n Part,\n TaskStatusUpdateEvent,\n PushNotificationConfig,\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n ExecutionEventBus,\n AgentExecutor,\n}\n\n// Re-export server options type for convenience\nexport type { PaymentsA2AServerOptions } from './server.ts'\n"]}
|
package/dist/api/nvm-api.d.ts
CHANGED
|
@@ -32,6 +32,8 @@ export declare const API_URL_GET_MEMBERS = "/api/v1/organizations/members";
|
|
|
32
32
|
export declare const API_URL_MY_MEMBERSHIPS = "/api/v1/organizations/my-memberships";
|
|
33
33
|
export declare const API_URL_ORG_ACTIVITY = "/api/v1/organizations/:orgId/activity";
|
|
34
34
|
export declare const API_URL_CONNECT_STRIPE_ACCOUNT = "/api/v1/fiat/stripe/account";
|
|
35
|
+
export declare const API_URL_CREATE_ORDER = "/api/v1/orders";
|
|
36
|
+
export declare const API_URL_GET_ORDER = "/api/v1/orders/:orderId";
|
|
35
37
|
export interface BackendApiOptions {
|
|
36
38
|
/**
|
|
37
39
|
* The host of the backend server
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nvm-api.d.ts","sourceRoot":"","sources":["../../src/api/nvm-api.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,qBAAqB,2BAA2B,CAAA;AAC7D,eAAO,MAAM,sBAAsB,4BAA4B,CAAA;AAC/D,eAAO,MAAM,gCAAgC,kCAAkC,CAAA;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GAAE,kBAEX;IAqBG,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,GAAE,kBAA+C;IAI5E,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,UAAU,EAAE,kBAAkB;IAI3D,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,UAAU,EAAE,kBAAkB;IAI1D,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,UAAU,EAAE,kBAAkB;CAGpE"}
|
package/dist/api/nvm-api.js
CHANGED
|
@@ -39,6 +39,10 @@ export const API_URL_GET_MEMBERS = '/api/v1/organizations/members';
|
|
|
39
39
|
export const API_URL_MY_MEMBERSHIPS = '/api/v1/organizations/my-memberships';
|
|
40
40
|
export const API_URL_ORG_ACTIVITY = '/api/v1/organizations/:orgId/activity';
|
|
41
41
|
export const API_URL_CONNECT_STRIPE_ACCOUNT = '/api/v1/fiat/stripe/account';
|
|
42
|
+
// Browser-fiat Orders (nvm-monorepo epic #3238). POST is merchant-authenticated
|
|
43
|
+
// (org-scoped NVM API key); GET is anonymous — the unguessable id is the access control.
|
|
44
|
+
export const API_URL_CREATE_ORDER = '/api/v1/orders';
|
|
45
|
+
export const API_URL_GET_ORDER = '/api/v1/orders/:orderId';
|
|
42
46
|
export class HTTPRequestOptions {
|
|
43
47
|
constructor() {
|
|
44
48
|
this.sendThroughProxy = true;
|
package/dist/api/nvm-api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nvm-api.js","sourceRoot":"","sources":["../../src/api/nvm-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,MAAM,CAAC,MAAM,qBAAqB,GAAG,wBAAwB,CAAA;AAC7D,MAAM,CAAC,MAAM,sBAAsB,GAAG,yBAAyB,CAAA;AAC/D,MAAM,CAAC,MAAM,gCAAgC,GAAG,+BAA+B,CAA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KAAK,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,IAAI,gBAAgB,EAAE,CACjF,CAAA;YACH,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAA;QACxE,CAAC;IACH,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,GAAW,EAAE,aAAiC,EAAE,gBAAgB,EAAE,IAAI,EAAE;QAChF,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,UAAU,CAAC,CAAA;IACxD,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,GAAW,EAAE,IAAS,EAAE,UAA8B;QAC/D,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,CAAC,CAAA;IACpD,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,GAAW,EAAE,IAAS,EAAE,UAA8B;QAC9D,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,CAAC,CAAA;IACnD,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAW,EAAE,IAAS,EAAE,UAA8B;QACjE,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,CAAC,CAAA;IACtD,CAAC;CACF","sourcesContent":["import axios from 'axios'\n\nexport const API_URL_REGISTER_PLAN = '/api/v1/protocol/plans'\nexport const API_URL_REGISTER_AGENT = '/api/v1/protocol/agents'\nexport const API_URL_REGISTER_AGENTS_AND_PLAN = '/api/v1/protocol/agents/plans'\nexport const API_URL_GET_AGENT = '/api/v1/protocol/agents/:agentId'\nexport const API_URL_UPDATE_AGENT = '/api/v1/protocol/agents/:agentId'\nexport const API_URL_GET_AGENT_PLANS = '/api/v1/protocol/agents/:agentId/plans'\n// GET: the caller's own agents (?orgId= scopes to an org the caller belongs to).\n// Same path as API_URL_REGISTER_AGENT (disambiguated by GET vs POST); mirrors\n// the existing API_URL_REGISTER_PLAN / API_URL_GET_PLANS pair below.\nexport const API_URL_GET_AGENTS = '/api/v1/protocol/agents'\nexport const API_URL_GET_PLAN = '/api/v1/protocol/plans/:planId'\nexport const API_URL_GET_PLANS = '/api/v1/protocol/plans'\nexport const API_URL_GET_PLAN_AGENTS = '/api/v1/protocol/plans/:planId/agents'\nexport const API_URL_ORDER_PLAN = '/api/v1/protocol/plans/:planId/order'\nexport const API_URL_MINT_PLAN = '/api/v1/protocol/plans/mint'\nexport const API_URL_MINT_EXPIRABLE_PLAN = '/api/v1/protocol/plans/mintExpirable'\nexport const API_URL_ADD_PLAN_AGENT = '/api/v1/protocol/agents/:agentId/plan/:planId'\nexport const API_URL_REMOVE_PLAN_AGENT = '/api/v1/protocol/agents/:agentId/plan/:planId'\nexport const API_URL_PLAN_BALANCE = '/api/v1/protocol/plans/:planId/balance/:holderAddress'\nexport const API_URL_INITIALIZE_AGENT = '/api/v1/protocol/agents/initialize/:agentId'\nexport const API_URL_SIMULATE_AGENT_REQUEST = '/api/v1/protocol/agents/simulate/start'\nexport const API_URL_SIMULATE_REDEEM_AGENT_REQUEST = '/api/v1/protocol/agents/simulate/finish'\nexport const API_URL_TRACK_AGENT_SUB_TASK = '/api/v1/protocol/agent-sub-tasks'\nexport const API_URL_VALIDATE_AGENT_ACCESS_TOKEN = '/api/v1/protocol/token/validate/:agentId'\nexport const API_URL_CREATE_PERMISSION = '/api/v1/x402/permissions'\nexport const API_URL_VERIFY_PERMISSIONS = '/api/v1/x402/verify'\nexport const API_URL_SETTLE_PERMISSIONS = '/api/v1/x402/settle'\n// MPP seller/buyer surface. Sibling routes of /api/v1/x402, never children:\n// an MPP access token is byte-identical to an x402 one on the wire, so the\n// route is what fixes the protocol. See nvm-monorepo#2641.\nexport const API_URL_MPP_CREATE_PERMISSION = '/api/v1/mpp/permissions'\nexport const API_URL_MPP_CHALLENGE = '/api/v1/mpp/challenge'\nexport const API_URL_MPP_VERIFY = '/api/v1/mpp/verify'\nexport const API_URL_MPP_SETTLE = '/api/v1/mpp/settle'\nexport const API_URL_STRIPE_CHECKOUT = '/api/v1/fiat/stripe/payment'\nexport const API_URL_CREATE_USER = '/api/v1/organizations/account'\nexport const API_URL_GET_MEMBERS = '/api/v1/organizations/members'\nexport const API_URL_MY_MEMBERSHIPS = '/api/v1/organizations/my-memberships'\nexport const API_URL_ORG_ACTIVITY = '/api/v1/organizations/:orgId/activity'\nexport const API_URL_CONNECT_STRIPE_ACCOUNT = '/api/v1/fiat/stripe/account'\n\nexport interface BackendApiOptions {\n /**\n * The host of the backend server\n */\n backendHost: string\n\n /**\n * The Nevermined API Key. This key identify your user and is required to interact with the Nevermined API.\n * You can get your API key by logging in to the Nevermined App.\n * @see https://nevermined.ai/docs/tutorials/integration/nvm-api-keys\n */\n apiKey?: string\n\n /**\n * The host of the Nevermined Proxy\n */\n proxyHost?: string\n\n /**\n * Additional headers to send with the requests\n */\n headers?: { [key: string]: string }\n}\n\nexport class HTTPRequestOptions {\n accessToken?: string\n sendThroughProxy = true\n proxyHost?: string = undefined\n headers?: { [key: string]: string } = {}\n}\n\nexport abstract class AbstractHTTPClient {\n // protected opts: BackendApiOptions\n // private hasKey = false\n // private agentId = ''\n\n // constructor(opts: BackendApiOptions) {\n // const defaultHeaders = {\n // Accept: 'application/json',\n // ...opts.headers,\n // ...(opts.apiKey && { Authorization: `Bearer ${opts.apiKey}` }),\n // }\n\n // this.opts = {\n // ...opts,\n // headers: defaultHeaders,\n // }\n\n // try {\n // if (this.opts.apiKey && this.opts.apiKey.length > 0) {\n // const jwt = decodeJwt(this.opts.apiKey)\n // if (isEthereumAddress(jwt.sub)) {\n // this.hasKey = true\n // }\n // }\n // } catch {\n // this.hasKey = false\n // }\n\n // let backendUrl\n // try {\n // backendUrl = new URL(this.opts.backendHost)\n // this.opts.backendHost = backendUrl.origin\n // } catch (error) {\n // throw new Error(`Invalid URL: ${this.opts.backendHost} - ${(error as Error).message}`)\n // }\n // }\n\n constructor() {\n // Empty constructor - required for abstract class implementation\n }\n\n parseUrl(urlRequested: string, reqOptions: HTTPRequestOptions) {\n let _host: URL\n if (reqOptions.sendThroughProxy) {\n if (!reqOptions.proxyHost)\n throw new Error('Proxy host is required when sendThroughProxy is true')\n return `${new URL(reqOptions.proxyHost).origin}${new URL(urlRequested).href}`\n } else {\n return urlRequested\n }\n }\n\n parseHeaders(requestHeaders: { [key: string]: string }, accessToken?: string) {\n return {\n ...(accessToken && { Authorization: `Bearer ${accessToken}` }),\n ...requestHeaders,\n }\n }\n\n // setBearerToken(token: string) {\n // this.opts.headers = {\n // ...this.opts.headers,\n // Authorization: `Bearer ${token}`,\n // }\n // }\n\n async request(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: string,\n data?: any,\n reqOptions: HTTPRequestOptions = {\n sendThroughProxy: false,\n },\n ) {\n try {\n const response = await axios({\n method,\n url: this.parseUrl(url, reqOptions),\n headers: this.parseHeaders(reqOptions.headers || {}, reqOptions.accessToken),\n ...(data && { data }), // Only include `data` for methods that support it\n })\n\n return response\n } catch (err) {\n if (axios.isAxiosError(err) && err.response) {\n throw new Error(\n `HTTP ${err.response.status}: ${err.response.data?.message || 'Request failed'}`,\n )\n }\n throw new Error('Network error or request failed without a response.')\n }\n }\n\n async get(url: string, reqOptions: HTTPRequestOptions = { sendThroughProxy: true }) {\n return this.request('GET', url, undefined, reqOptions)\n }\n\n async post(url: string, data: any, reqOptions: HTTPRequestOptions) {\n return this.request('POST', url, data, reqOptions)\n }\n\n async put(url: string, data: any, reqOptions: HTTPRequestOptions) {\n return this.request('PUT', url, data, reqOptions)\n }\n\n async delete(url: string, data: any, reqOptions: HTTPRequestOptions) {\n return this.request('DELETE', url, data, reqOptions)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"nvm-api.js","sourceRoot":"","sources":["../../src/api/nvm-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,MAAM,CA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nexport const API_URL_REGISTER_AGENTS_AND_PLAN = '/api/v1/protocol/agents/plans'\nexport const API_URL_GET_AGENT = '/api/v1/protocol/agents/:agentId'\nexport const API_URL_UPDATE_AGENT = '/api/v1/protocol/agents/:agentId'\nexport const API_URL_GET_AGENT_PLANS = '/api/v1/protocol/agents/:agentId/plans'\n// GET: the caller's own agents (?orgId= scopes to an org the caller belongs to).\n// Same path as API_URL_REGISTER_AGENT (disambiguated by GET vs POST); mirrors\n// the existing API_URL_REGISTER_PLAN / API_URL_GET_PLANS pair below.\nexport const API_URL_GET_AGENTS = '/api/v1/protocol/agents'\nexport const API_URL_GET_PLAN = '/api/v1/protocol/plans/:planId'\nexport const API_URL_GET_PLANS = '/api/v1/protocol/plans'\nexport const API_URL_GET_PLAN_AGENTS = '/api/v1/protocol/plans/:planId/agents'\nexport const API_URL_ORDER_PLAN = '/api/v1/protocol/plans/:planId/order'\nexport const API_URL_MINT_PLAN = '/api/v1/protocol/plans/mint'\nexport const API_URL_MINT_EXPIRABLE_PLAN = '/api/v1/protocol/plans/mintExpirable'\nexport const API_URL_ADD_PLAN_AGENT = '/api/v1/protocol/agents/:agentId/plan/:planId'\nexport const API_URL_REMOVE_PLAN_AGENT = '/api/v1/protocol/agents/:agentId/plan/:planId'\nexport const API_URL_PLAN_BALANCE = '/api/v1/protocol/plans/:planId/balance/:holderAddress'\nexport const API_URL_INITIALIZE_AGENT = '/api/v1/protocol/agents/initialize/:agentId'\nexport const API_URL_SIMULATE_AGENT_REQUEST = '/api/v1/protocol/agents/simulate/start'\nexport const API_URL_SIMULATE_REDEEM_AGENT_REQUEST = '/api/v1/protocol/agents/simulate/finish'\nexport const API_URL_TRACK_AGENT_SUB_TASK = '/api/v1/protocol/agent-sub-tasks'\nexport const API_URL_VALIDATE_AGENT_ACCESS_TOKEN = '/api/v1/protocol/token/validate/:agentId'\nexport const API_URL_CREATE_PERMISSION = '/api/v1/x402/permissions'\nexport const API_URL_VERIFY_PERMISSIONS = '/api/v1/x402/verify'\nexport const API_URL_SETTLE_PERMISSIONS = '/api/v1/x402/settle'\n// MPP seller/buyer surface. Sibling routes of /api/v1/x402, never children:\n// an MPP access token is byte-identical to an x402 one on the wire, so the\n// route is what fixes the protocol. See nvm-monorepo#2641.\nexport const API_URL_MPP_CREATE_PERMISSION = '/api/v1/mpp/permissions'\nexport const API_URL_MPP_CHALLENGE = '/api/v1/mpp/challenge'\nexport const API_URL_MPP_VERIFY = '/api/v1/mpp/verify'\nexport const API_URL_MPP_SETTLE = '/api/v1/mpp/settle'\nexport const API_URL_STRIPE_CHECKOUT = '/api/v1/fiat/stripe/payment'\nexport const API_URL_CREATE_USER = '/api/v1/organizations/account'\nexport const API_URL_GET_MEMBERS = '/api/v1/organizations/members'\nexport const API_URL_MY_MEMBERSHIPS = '/api/v1/organizations/my-memberships'\nexport const API_URL_ORG_ACTIVITY = '/api/v1/organizations/:orgId/activity'\nexport const API_URL_CONNECT_STRIPE_ACCOUNT = '/api/v1/fiat/stripe/account'\n// Browser-fiat Orders (nvm-monorepo epic #3238). POST is merchant-authenticated\n// (org-scoped NVM API key); GET is anonymous — the unguessable id is the access control.\nexport const API_URL_CREATE_ORDER = '/api/v1/orders'\nexport const API_URL_GET_ORDER = '/api/v1/orders/:orderId'\n\nexport interface BackendApiOptions {\n /**\n * The host of the backend server\n */\n backendHost: string\n\n /**\n * The Nevermined API Key. This key identify your user and is required to interact with the Nevermined API.\n * You can get your API key by logging in to the Nevermined App.\n * @see https://nevermined.ai/docs/tutorials/integration/nvm-api-keys\n */\n apiKey?: string\n\n /**\n * The host of the Nevermined Proxy\n */\n proxyHost?: string\n\n /**\n * Additional headers to send with the requests\n */\n headers?: { [key: string]: string }\n}\n\nexport class HTTPRequestOptions {\n accessToken?: string\n sendThroughProxy = true\n proxyHost?: string = undefined\n headers?: { [key: string]: string } = {}\n}\n\nexport abstract class AbstractHTTPClient {\n // protected opts: BackendApiOptions\n // private hasKey = false\n // private agentId = ''\n\n // constructor(opts: BackendApiOptions) {\n // const defaultHeaders = {\n // Accept: 'application/json',\n // ...opts.headers,\n // ...(opts.apiKey && { Authorization: `Bearer ${opts.apiKey}` }),\n // }\n\n // this.opts = {\n // ...opts,\n // headers: defaultHeaders,\n // }\n\n // try {\n // if (this.opts.apiKey && this.opts.apiKey.length > 0) {\n // const jwt = decodeJwt(this.opts.apiKey)\n // if (isEthereumAddress(jwt.sub)) {\n // this.hasKey = true\n // }\n // }\n // } catch {\n // this.hasKey = false\n // }\n\n // let backendUrl\n // try {\n // backendUrl = new URL(this.opts.backendHost)\n // this.opts.backendHost = backendUrl.origin\n // } catch (error) {\n // throw new Error(`Invalid URL: ${this.opts.backendHost} - ${(error as Error).message}`)\n // }\n // }\n\n constructor() {\n // Empty constructor - required for abstract class implementation\n }\n\n parseUrl(urlRequested: string, reqOptions: HTTPRequestOptions) {\n let _host: URL\n if (reqOptions.sendThroughProxy) {\n if (!reqOptions.proxyHost)\n throw new Error('Proxy host is required when sendThroughProxy is true')\n return `${new URL(reqOptions.proxyHost).origin}${new URL(urlRequested).href}`\n } else {\n return urlRequested\n }\n }\n\n parseHeaders(requestHeaders: { [key: string]: string }, accessToken?: string) {\n return {\n ...(accessToken && { Authorization: `Bearer ${accessToken}` }),\n ...requestHeaders,\n }\n }\n\n // setBearerToken(token: string) {\n // this.opts.headers = {\n // ...this.opts.headers,\n // Authorization: `Bearer ${token}`,\n // }\n // }\n\n async request(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: string,\n data?: any,\n reqOptions: HTTPRequestOptions = {\n sendThroughProxy: false,\n },\n ) {\n try {\n const response = await axios({\n method,\n url: this.parseUrl(url, reqOptions),\n headers: this.parseHeaders(reqOptions.headers || {}, reqOptions.accessToken),\n ...(data && { data }), // Only include `data` for methods that support it\n })\n\n return response\n } catch (err) {\n if (axios.isAxiosError(err) && err.response) {\n throw new Error(\n `HTTP ${err.response.status}: ${err.response.data?.message || 'Request failed'}`,\n )\n }\n throw new Error('Network error or request failed without a response.')\n }\n }\n\n async get(url: string, reqOptions: HTTPRequestOptions = { sendThroughProxy: true }) {\n return this.request('GET', url, undefined, reqOptions)\n }\n\n async post(url: string, data: any, reqOptions: HTTPRequestOptions) {\n return this.request('POST', url, data, reqOptions)\n }\n\n async put(url: string, data: any, reqOptions: HTTPRequestOptions) {\n return this.request('PUT', url, data, reqOptions)\n }\n\n async delete(url: string, data: any, reqOptions: HTTPRequestOptions) {\n return this.request('DELETE', url, data, reqOptions)\n }\n}\n"]}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { PaymentOptions } from '../common/types.js';
|
|
2
|
+
import { BasePaymentsAPI } from './base-payments.js';
|
|
3
|
+
/**
|
|
4
|
+
* Buyer-facing lifecycle status of an Order, as published on the wire by the
|
|
5
|
+
* Nevermined API (`WireOrderStatus` in nvm-monorepo
|
|
6
|
+
* `apps/api/src/orders/order-status.ts`).
|
|
7
|
+
*/
|
|
8
|
+
export type OrderStatus = 'requires_payment' | 'paid' | 'refunded' | 'partially_refunded' | 'disputed' | 'failed';
|
|
9
|
+
/**
|
|
10
|
+
* Body of `POST /api/v1/orders` (`RegisterOrderDto`). The authenticated
|
|
11
|
+
* merchant key sets the price; the seller's Stripe Connect account is
|
|
12
|
+
* resolved server-side and is deliberately NOT part of this contract.
|
|
13
|
+
*/
|
|
14
|
+
export interface CreateOrderOptions {
|
|
15
|
+
/**
|
|
16
|
+
* Charge amount in USD cents (at least `100`, i.e. $1.00). The API validates
|
|
17
|
+
* the upper bound (`BCK.ORDER.0001`); a deployment may enforce a lower
|
|
18
|
+
* per-order cap (`BCK.ORDER.0003`).
|
|
19
|
+
*/
|
|
20
|
+
amountMinor: number;
|
|
21
|
+
/** ISO currency, lower-cased. Phase 1 is USD-only; defaults to `'usd'`. */
|
|
22
|
+
currency?: 'usd';
|
|
23
|
+
/** Human-readable description of the charge (max 1024 chars). */
|
|
24
|
+
description?: string;
|
|
25
|
+
/** Opaque merchant-supplied buyer reference, e.g. the merchant's own order id (max 255 chars). */
|
|
26
|
+
buyerRef?: string;
|
|
27
|
+
/**
|
|
28
|
+
* Idempotency key (max 255 chars). A retry with the same key returns the
|
|
29
|
+
* original Order unchanged (and its `clientSecret` while the Order is still
|
|
30
|
+
* payable); the other fields of the retry are ignored, not merged. A retry
|
|
31
|
+
* with a different `amountMinor` or `currency` is refused with `BCK.ORDER.0007`.
|
|
32
|
+
*/
|
|
33
|
+
idempotencyKey?: string;
|
|
34
|
+
/** Cart line items — merchant-defined structure, recorded verbatim (keys are not transformed), opaque to the API. */
|
|
35
|
+
lineItems?: Array<Record<string, unknown>>;
|
|
36
|
+
/** Merchant-defined metadata, recorded verbatim (keys are not transformed), opaque to the API. */
|
|
37
|
+
metadata?: Record<string, unknown>;
|
|
38
|
+
/** Stripe capture mode. Phase 1 supports `'automatic'` only (the default). */
|
|
39
|
+
captureMode?: 'automatic';
|
|
40
|
+
/** Payment Service Provider that settles the Order. Phase 1 implements `'stripe'` only (the default). */
|
|
41
|
+
paymentProvider?: 'stripe';
|
|
42
|
+
}
|
|
43
|
+
/** Response of `POST /api/v1/orders` (`CreateOrderResponseDto`). */
|
|
44
|
+
export interface CreateOrderResult {
|
|
45
|
+
/** Unguessable Order id — the buyer-facing access control for {@link OrdersAPI.getOrder}. */
|
|
46
|
+
orderId: string;
|
|
47
|
+
status: OrderStatus;
|
|
48
|
+
/** Stripe PaymentIntent client secret the browser confirms against. Present only while the Order is payable. */
|
|
49
|
+
clientSecret?: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Buyer-safe view of an Order (`OrderResponseDto`). It never carries the
|
|
53
|
+
* merchant identity, the Connect account or the fee breakdown.
|
|
54
|
+
*/
|
|
55
|
+
export interface Order {
|
|
56
|
+
/** Unguessable Order id. */
|
|
57
|
+
id: string;
|
|
58
|
+
/** Charge amount in USD cents. */
|
|
59
|
+
amountMinor: number;
|
|
60
|
+
currency: string;
|
|
61
|
+
status: OrderStatus;
|
|
62
|
+
/** Total refunded so far, in cents. */
|
|
63
|
+
amountRefundedMinor: number;
|
|
64
|
+
description: string | null;
|
|
65
|
+
buyerRef: string | null;
|
|
66
|
+
/** The Stripe PaymentIntent backing this Order; `null` until it is created. */
|
|
67
|
+
paymentIntentId: string | null;
|
|
68
|
+
/** ISO-8601 instant when the Order stops being payable; `null` if it never expires. */
|
|
69
|
+
expiresAt: string | null;
|
|
70
|
+
/** Present only while the Order is payable. */
|
|
71
|
+
clientSecret?: string;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The OrdersAPI class wraps the browser-fiat Orders endpoints. An Order is a
|
|
75
|
+
* merchant-initiated, off-plan charge for an arbitrary amount (the Stripe
|
|
76
|
+
* PaymentIntent analog) that the buyer's browser confirms client-side — no
|
|
77
|
+
* plan, no buyer Nevermined account, no delegation.
|
|
78
|
+
*
|
|
79
|
+
* @remarks
|
|
80
|
+
* `createOrder` requires an **organization-scoped** NVM API key: the API reads
|
|
81
|
+
* the merchant organization from the key's own org tag, so a personal key is
|
|
82
|
+
* refused with `BCK.ORDER.0003`. `Payments.setOrganizationId` (the
|
|
83
|
+
* `X-Current-Org-Id` header) does not substitute for an org-scoped key.
|
|
84
|
+
*
|
|
85
|
+
* This client is the merchant's: a `Payments` instance is always constructed
|
|
86
|
+
* with an NVM API key. The buyer never needs one — the buyer's browser confirms
|
|
87
|
+
* the `clientSecret` with Stripe.js and can poll `GET /api/v1/orders/:id`
|
|
88
|
+
* directly, which is why {@link OrdersAPI.getOrder} sends no key on that call.
|
|
89
|
+
*
|
|
90
|
+
* @see nvm-monorepo `apps/api/src/orders/README.md` (epic #3238)
|
|
91
|
+
*/
|
|
92
|
+
export declare class OrdersAPI extends BasePaymentsAPI {
|
|
93
|
+
static getInstance(options: PaymentOptions): OrdersAPI;
|
|
94
|
+
/**
|
|
95
|
+
* Creates an Order and its PaymentIntent, returning the `clientSecret` a
|
|
96
|
+
* browser confirms against (`POST /api/v1/orders`).
|
|
97
|
+
*
|
|
98
|
+
* @remarks
|
|
99
|
+
* This method is oriented to merchants. The NVM API Key must be scoped to an
|
|
100
|
+
* active organization whose Stripe Connect account can receive card payments.
|
|
101
|
+
*
|
|
102
|
+
* @param options - @see {@link CreateOrderOptions}. `currency` defaults to `'usd'`.
|
|
103
|
+
* @returns The new Order id, its status and — while payable — the `clientSecret`.
|
|
104
|
+
* @throws PaymentsError carrying the backend catalogue code: `BCK.ORDER.0001`
|
|
105
|
+
* (invalid request), `BCK.ORDER.0003` (not an active organization / over the
|
|
106
|
+
* per-order cap), `BCK.ORDER.0007` (idempotency-key conflict),
|
|
107
|
+
* `BCK.ORDER.0010` (velocity cap — retryable), `BCK.ORDER.0004`/`0005`
|
|
108
|
+
* (Connect account / PaymentIntent failure, no money moved). A refusal
|
|
109
|
+
* without a catalogue code (e.g. a gateway or throttle response) carries
|
|
110
|
+
* `http_<status>` instead.
|
|
111
|
+
* @example
|
|
112
|
+
* ```
|
|
113
|
+
* const { orderId, clientSecret } = await payments.orders.createOrder({
|
|
114
|
+
* amountMinor: 3437, // $34.37
|
|
115
|
+
* description: 'Cart checkout — 3 items',
|
|
116
|
+
* idempotencyKey: 'merchant-order-4821',
|
|
117
|
+
* })
|
|
118
|
+
* ```
|
|
119
|
+
*/
|
|
120
|
+
createOrder(options: CreateOrderOptions): Promise<CreateOrderResult>;
|
|
121
|
+
/**
|
|
122
|
+
* Reads the buyer-safe view of an Order by id (`GET /api/v1/orders/:id`).
|
|
123
|
+
*
|
|
124
|
+
* @remarks
|
|
125
|
+
* The endpoint is anonymous — the unguessable id is the sole access control —
|
|
126
|
+
* so this call sends no API key (the `Payments` instance still needs one to
|
|
127
|
+
* be constructed). The response never includes the merchant identity or the
|
|
128
|
+
* fee, and carries `clientSecret` only while the Order is payable.
|
|
129
|
+
*
|
|
130
|
+
* @param orderId - The unguessable Order id returned by {@link createOrder}.
|
|
131
|
+
* @returns @see {@link Order}
|
|
132
|
+
* @throws PaymentsError with code `BCK.ORDER.0002` when no Order has this id.
|
|
133
|
+
* The read endpoint is rate-limited — all anonymous callers behind one IP
|
|
134
|
+
* share a bucket of 60 requests per minute — and a throttled call carries
|
|
135
|
+
* no catalogue code, so it surfaces as code `http_429`. That is distinct
|
|
136
|
+
* from the create-side velocity cap `BCK.ORDER.0010`; poll sparingly and
|
|
137
|
+
* back off on `http_429`.
|
|
138
|
+
* @example
|
|
139
|
+
* ```
|
|
140
|
+
* const order = await payments.orders.getOrder(orderId)
|
|
141
|
+
* if (order.status === 'paid') fulfil(order)
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
getOrder(orderId: string): Promise<Order>;
|
|
145
|
+
}
|
|
146
|
+
//# sourceMappingURL=orders-api.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orders-api.d.ts","sourceRoot":"","sources":["../../src/api/orders-api.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAGpD;;;;GAIG;AACH,MAAM,MAAM,WAAW,GACnB,kBAAkB,GAClB,MAAM,GACN,UAAU,GACV,oBAAoB,GACpB,UAAU,GACV,QAAQ,CAAA;AAEZ;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAA;IACnB,2EAA2E;IAC3E,QAAQ,CAAC,EAAE,KAAK,CAAA;IAChB,iEAAiE;IACjE,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,kGAAkG;IAClG,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,qHAAqH;IACrH,SAAS,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;IAC1C,kGAAkG;IAClG,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;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