@nevermined-io/payments 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +2 -1
  2. package/dist/a2a/agent-card.d.ts +26 -0
  3. package/dist/a2a/agent-card.d.ts.map +1 -1
  4. package/dist/a2a/agent-card.js +36 -1
  5. package/dist/a2a/agent-card.js.map +1 -1
  6. package/dist/a2a/paymentsClient.d.ts +41 -1
  7. package/dist/a2a/paymentsClient.d.ts.map +1 -1
  8. package/dist/a2a/paymentsClient.js +120 -8
  9. package/dist/a2a/paymentsClient.js.map +1 -1
  10. package/dist/a2a/paymentsRequestHandler.d.ts +25 -2
  11. package/dist/a2a/paymentsRequestHandler.d.ts.map +1 -1
  12. package/dist/a2a/paymentsRequestHandler.js +240 -20
  13. package/dist/a2a/paymentsRequestHandler.js.map +1 -1
  14. package/dist/a2a/server.d.ts +2 -2
  15. package/dist/a2a/server.d.ts.map +1 -1
  16. package/dist/a2a/server.js +70 -20
  17. package/dist/a2a/server.js.map +1 -1
  18. package/dist/a2a/types.d.ts +31 -1
  19. package/dist/a2a/types.d.ts.map +1 -1
  20. package/dist/a2a/types.js.map +1 -1
  21. package/dist/a2a/x402-a2a.d.ts +142 -0
  22. package/dist/a2a/x402-a2a.d.ts.map +1 -0
  23. package/dist/a2a/x402-a2a.js +254 -0
  24. package/dist/a2a/x402-a2a.js.map +1 -0
  25. package/dist/api/agents-api.d.ts +19 -0
  26. package/dist/api/agents-api.d.ts.map +1 -1
  27. package/dist/api/agents-api.js +28 -1
  28. package/dist/api/agents-api.js.map +1 -1
  29. package/dist/api/nvm-api.d.ts +1 -0
  30. package/dist/api/nvm-api.d.ts.map +1 -1
  31. package/dist/api/nvm-api.js +4 -0
  32. package/dist/api/nvm-api.js.map +1 -1
  33. package/dist/api/plans-api.d.ts +12 -2
  34. package/dist/api/plans-api.d.ts.map +1 -1
  35. package/dist/api/plans-api.js +9 -2
  36. package/dist/api/plans-api.js.map +1 -1
  37. package/dist/index.d.ts +2 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +3 -0
  40. package/dist/index.js.map +1 -1
  41. package/dist/mcp/core/auth.d.ts +16 -2
  42. package/dist/mcp/core/auth.d.ts.map +1 -1
  43. package/dist/mcp/core/auth.js +70 -26
  44. package/dist/mcp/core/auth.js.map +1 -1
  45. package/dist/mcp/core/paywall.d.ts +6 -0
  46. package/dist/mcp/core/paywall.d.ts.map +1 -1
  47. package/dist/mcp/core/paywall.js +179 -89
  48. package/dist/mcp/core/paywall.js.map +1 -1
  49. package/dist/mcp/core/server-manager.d.ts.map +1 -1
  50. package/dist/mcp/core/server-manager.js +6 -4
  51. package/dist/mcp/core/server-manager.js.map +1 -1
  52. package/dist/mcp/http/client-registration.d.ts.map +1 -1
  53. package/dist/mcp/http/client-registration.js +4 -2
  54. package/dist/mcp/http/client-registration.js.map +1 -1
  55. package/dist/mcp/http/oauth-metadata.d.ts.map +1 -1
  56. package/dist/mcp/http/oauth-metadata.js +2 -1
  57. package/dist/mcp/http/oauth-metadata.js.map +1 -1
  58. package/dist/mcp/index.d.ts +12 -5
  59. package/dist/mcp/index.d.ts.map +1 -1
  60. package/dist/mcp/index.js +46 -23
  61. package/dist/mcp/index.js.map +1 -1
  62. package/dist/mcp/types/http.types.d.ts +2 -2
  63. package/dist/mcp/types/http.types.d.ts.map +1 -1
  64. package/dist/mcp/types/http.types.js.map +1 -1
  65. package/dist/mcp/types/paywall.types.d.ts +6 -2
  66. package/dist/mcp/types/paywall.types.d.ts.map +1 -1
  67. package/dist/mcp/types/paywall.types.js.map +1 -1
  68. package/dist/mcp/types/server.types.d.ts +4 -2
  69. package/dist/mcp/types/server.types.d.ts.map +1 -1
  70. package/dist/mcp/types/server.types.js.map +1 -1
  71. package/dist/mcp/utils/errors.d.ts +26 -0
  72. package/dist/mcp/utils/errors.d.ts.map +1 -1
  73. package/dist/mcp/utils/errors.js +32 -0
  74. package/dist/mcp/utils/errors.js.map +1 -1
  75. package/dist/mcp/utils/meta.d.ts +54 -0
  76. package/dist/mcp/utils/meta.d.ts.map +1 -0
  77. package/dist/mcp/utils/meta.js +72 -0
  78. package/dist/mcp/utils/meta.js.map +1 -0
  79. package/dist/payments.d.ts.map +1 -1
  80. package/dist/utils.d.ts +27 -0
  81. package/dist/utils.d.ts.map +1 -1
  82. package/dist/utils.js +34 -0
  83. package/dist/utils.js.map +1 -1
  84. package/dist/x402/facilitator-api.d.ts +21 -0
  85. package/dist/x402/facilitator-api.d.ts.map +1 -1
  86. package/dist/x402/facilitator-api.js +39 -0
  87. package/dist/x402/facilitator-api.js.map +1 -1
  88. package/package.json +2 -2
package/README.md CHANGED
@@ -389,7 +389,8 @@ payments.mcp.registerPrompt(
389
389
  ```typescript
390
390
  const { info, stop } = await payments.mcp.start({
391
391
  port: 3002,
392
- agentId: process.env.NVM_AGENT_ID!,
392
+ planId: process.env.NVM_PLAN_ID!,
393
+ agentId: process.env.NVM_AGENT_ID, // optional — informational only
393
394
  serverName: 'weather-mcp',
394
395
  version: '0.1.0',
395
396
  })
@@ -10,6 +10,32 @@
10
10
  * information about pricing, credits, and payment configuration.
11
11
  */
12
12
  import type { AgentCard } from './types.js';
13
+ /**
14
+ * Canonical A2A agent-card discovery path (A2A 0.3+ and `@a2a-js/sdk`'s own
15
+ * default, per RFC 8615). Served by Nevermined A2A agents and used as the
16
+ * default when fetching a remote agent's card.
17
+ */
18
+ export declare const AGENT_CARD_WELL_KNOWN_PATH = ".well-known/agent-card.json";
19
+ /**
20
+ * Legacy pre-0.3 discovery path. Still served as a backward-compat alias and
21
+ * tried as a fetch fallback, so newly-updated clients keep working against
22
+ * Nevermined agents that have not adopted the canonical path yet.
23
+ * TODO(a2a): drop the alias + fallback one release after agents are updated.
24
+ */
25
+ export declare const LEGACY_AGENT_CARD_WELL_KNOWN_PATH = ".well-known/agent.json";
26
+ /**
27
+ * Nevermined's own payment extension URI. Carries the agent/plan params the
28
+ * Nevermined paywall reads (agentId, planId, redemptionConfig, …). Kept for one
29
+ * release alongside the official a2a-x402 extension below for backward compat.
30
+ */
31
+ export declare const NVM_PAYMENT_EXTENSION_URI = "urn:nevermined:payment";
32
+ /**
33
+ * Official a2a-x402 extension URI (x402 v2 A2A transport). Declaring it tells
34
+ * generic A2A clients this agent speaks the standards-compliant in-band x402
35
+ * flow (payment signalled through Task / Message `x402.payment.*` metadata).
36
+ * @see https://github.com/google-agentic-commerce/a2a-x402
37
+ */
38
+ export declare const A2A_X402_EXTENSION_URI = "https://github.com/google-agentic-commerce/a2a-x402/blob/main/spec/v0.2";
13
39
  /**
14
40
  * Payment/pricing information to be included in the AgentCard extensions.
15
41
  *
@@ -1 +1 @@
1
- {"version":3,"file":"agent-card.d.ts","sourceRoot":"","sources":["../../src/a2a/agent-card.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAE3C;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,wBAAwB;IACvC,qFAAqF;IACrF,WAAW,EAAE,OAAO,GAAG,SAAS,CAAA;IAChC,+EAA+E;IAC/E,OAAO,EAAE,MAAM,CAAA;IACf,kDAAkD;IAClD,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,uDAAuD;IACvD,OAAO,EAAE,MAAM,CAAA;IACf,6CAA6C;IAC7C,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,sDAAsD;IACtD,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,0CAA0C;IAC1C,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,SAAS,EACnB,eAAe,EAAE,wBAAwB,GACxC,SAAS,CAyCX"}
1
+ {"version":3,"file":"agent-card.d.ts","sourceRoot":"","sources":["../../src/a2a/agent-card.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAE3C;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,gCAAgC,CAAA;AAEvE;;;;;GAKG;AACH,eAAO,MAAM,iCAAiC,2BAA2B,CAAA;AAEzE;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,2BAA2B,CAAA;AAEjE;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,4EACwC,CAAA;AAE3E;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,wBAAwB;IACvC,qFAAqF;IACrF,WAAW,EAAE,OAAO,GAAG,SAAS,CAAA;IAChC,+EAA+E;IAC/E,OAAO,EAAE,MAAM,CAAA;IACf,kDAAkD;IAClD,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,uDAAuD;IACvD,OAAO,EAAE,MAAM,CAAA;IACf,6CAA6C;IAC7C,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,sDAAsD;IACtD,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,0CAA0C;IAC1C,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,SAAS,EACnB,eAAe,EAAE,wBAAwB,GACxC,SAAS,CAmDX"}
@@ -9,6 +9,32 @@
9
9
  * The payment extension uses the URI 'urn:nevermined:payment' and includes
10
10
  * information about pricing, credits, and payment configuration.
11
11
  */
12
+ /**
13
+ * Canonical A2A agent-card discovery path (A2A 0.3+ and `@a2a-js/sdk`'s own
14
+ * default, per RFC 8615). Served by Nevermined A2A agents and used as the
15
+ * default when fetching a remote agent's card.
16
+ */
17
+ export const AGENT_CARD_WELL_KNOWN_PATH = '.well-known/agent-card.json';
18
+ /**
19
+ * Legacy pre-0.3 discovery path. Still served as a backward-compat alias and
20
+ * tried as a fetch fallback, so newly-updated clients keep working against
21
+ * Nevermined agents that have not adopted the canonical path yet.
22
+ * TODO(a2a): drop the alias + fallback one release after agents are updated.
23
+ */
24
+ export const LEGACY_AGENT_CARD_WELL_KNOWN_PATH = '.well-known/agent.json';
25
+ /**
26
+ * Nevermined's own payment extension URI. Carries the agent/plan params the
27
+ * Nevermined paywall reads (agentId, planId, redemptionConfig, …). Kept for one
28
+ * release alongside the official a2a-x402 extension below for backward compat.
29
+ */
30
+ export const NVM_PAYMENT_EXTENSION_URI = 'urn:nevermined:payment';
31
+ /**
32
+ * Official a2a-x402 extension URI (x402 v2 A2A transport). Declaring it tells
33
+ * generic A2A clients this agent speaks the standards-compliant in-band x402
34
+ * flow (payment signalled through Task / Message `x402.payment.*` metadata).
35
+ * @see https://github.com/google-agentic-commerce/a2a-x402
36
+ */
37
+ export const A2A_X402_EXTENSION_URI = 'https://github.com/google-agentic-commerce/a2a-x402/blob/main/spec/v0.2';
12
38
  /**
13
39
  * Builds an AgentCard with payment/pricing metadata in the capabilities.extensions field.
14
40
  *
@@ -83,12 +109,21 @@ export function buildPaymentAgentCard(baseCard, paymentMetadata) {
83
109
  extensions: [
84
110
  ...(baseCard.capabilities?.extensions || []),
85
111
  {
86
- uri: 'urn:nevermined:payment',
112
+ uri: NVM_PAYMENT_EXTENSION_URI,
87
113
  description: paymentMetadata.costDescription,
88
114
  required: false,
89
115
  // explicit type assertion to satisfy {[key: string]: unknown}
90
116
  params: paymentMetadata,
91
117
  },
118
+ // Official a2a-x402 extension: signals to generic A2A clients that this
119
+ // agent supports the standards-compliant in-band x402 v2 payment flow.
120
+ // Kept additive alongside the Nevermined extension for one release.
121
+ {
122
+ uri: A2A_X402_EXTENSION_URI,
123
+ description: paymentMetadata.costDescription ||
124
+ 'Supports payments using the x402 protocol for on-chain settlement.',
125
+ required: false,
126
+ },
92
127
  ],
93
128
  },
94
129
  };
@@ -1 +1 @@
1
- {"version":3,"file":"agent-card.js","sourceRoot":"","sources":["../../src/a2a/agent-card.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAiCH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,MAAM,UAAU,qBAAqB,CACnC,QAAmB,EACnB,eAAyC;IAEzC,2BAA2B;IAC3B,IAAI,CAAC,eAAe,CAAC,WAAW,EAAE,CAAC;QACjC,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAA;IAC5C,CAAC;IAED,wDAAwD;IACxD,IAAI,eAAe,CAAC,OAAO,GAAG,CAAC,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAA;IAC/C,CAAC;IAED,8CAA8C;IAC9C,IAAI,eAAe,CAAC,WAAW,EAAE,CAAC;QAChC,wEAAwE;IAC1E,CAAC;SAAM,CAAC;QACN,6CAA6C;QAC7C,IAAI,CAAC,eAAe,CAAC,OAAO,IAAI,eAAe,CAAC,OAAO,IAAI,CAAC,EAAE,CAAC;YAC7D,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAA;QACrE,CAAC;IACH,CAAC;IAED,IAAI,CAAC,eAAe,CAAC,OAAO,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAA;IACxC,CAAC;IAED,OAAO;QACL,GAAG,QAAQ;QACX,YAAY,EAAE;YACZ,GAAG,QAAQ,CAAC,YAAY;YACxB,UAAU,EAAE;gBACV,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,UAAU,IAAI,EAAE,CAAC;gBAC5C;oBACE,GAAG,EAAE,wBAAwB;oBAC7B,WAAW,EAAE,eAAe,CAAC,eAAe;oBAC5C,QAAQ,EAAE,KAAK;oBACf,8DAA8D;oBAC9D,MAAM,EAAE,eAA6C;iBACtD;aACF;SACF;KACF,CAAA;AACH,CAAC","sourcesContent":["/**\n * Helper to build an AgentCard with payment/pricing metadata for A2A agents.\n *\n * This module provides utilities for creating A2A agent cards that include\n * payment and pricing information in a standardized way. The payment metadata\n * is embedded in the agent card's capabilities.extensions field following\n * the A2A standard for extensibility.\n *\n * The payment extension uses the URI 'urn:nevermined:payment' and includes\n * information about pricing, credits, and payment configuration.\n */\n\nimport type { AgentCard } from './types.js'\n\n/**\n * Payment/pricing information to be included in the AgentCard extensions.\n *\n * This interface defines the structure for payment metadata that will be\n * embedded in the agent card. The metadata includes information about:\n * - Payment type (fixed or dynamic pricing)\n * - Credit requirements\n * - Plan identification\n * - Cost descriptions\n *\n * Must be compatible with `{[key: string]: unknown}` to comply with A2A standard.\n */\nexport interface PaymentAgentCardMetadata {\n /** Type of payment model - 'fixed' for set prices, 'dynamic' for variable pricing */\n paymentType: 'fixed' | 'dynamic'\n /** Number of credits required for this agent's services (0 for trial plans) */\n credits: number\n /** Optional plan ID associated with this agent */\n planId?: string\n /** The agent ID for payment validation and tracking */\n agentId: string\n /** Human-readable description of the cost */\n costDescription?: string\n /** Whether this is a trial plan (allows 0 credits) */\n isTrialPlan?: boolean\n /** Additional payment-related metadata */\n [key: string]: unknown // For compatibility with AgentExtension.params\n}\n\n/**\n * Builds an AgentCard with payment/pricing metadata in the capabilities.extensions field.\n *\n * This function takes a base agent card and payment metadata, then creates a new\n * agent card that includes the payment information in a standardized extension.\n * The payment extension follows the A2A standard for extensibility and uses the\n * URI 'urn:nevermined:payment' to identify payment-related capabilities.\n *\n * The resulting agent card can be used with the PaymentsA2AServer to provide\n * payment-enabled A2A agent functionality.\n *\n * @param baseCard - The base AgentCard (without payment info)\n * @param paymentMetadata - The payment/pricing metadata to include\n * @returns The AgentCard with payment info in capabilities.extensions\n *\n * @example\n * ```typescript\n * const baseCard: AgentCard = {\n * name: 'My AI Assistant',\n * description: 'An AI assistant that helps with various tasks',\n * capabilities: {\n * tools: ['text-generation', 'image-analysis'],\n * extensions: []\n * }\n * }\n *\n * const paymentMetadata: PaymentAgentCardMetadata = {\n * paymentType: 'fixed',\n * credits: 10,\n * agentId: 'agent-123',\n * planId: 'plan-456',\n * costDescription: '10 credits per request'\n * }\n *\n * const paymentCard = buildPaymentAgentCard(baseCard, paymentMetadata)\n *\n * // Use with PaymentsA2AServer\n * PaymentsA2AServer.start({\n * agentCard: paymentCard,\n * executor: new MyExecutor(),\n * paymentsService: payments,\n * port: 41242\n * })\n * ```\n */\nexport function buildPaymentAgentCard(\n baseCard: AgentCard,\n paymentMetadata: PaymentAgentCardMetadata,\n): AgentCard {\n // Validate required fields\n if (!paymentMetadata.paymentType) {\n throw new Error('paymentType is required')\n }\n\n // Validate credits - negative credits are never allowed\n if (paymentMetadata.credits < 0) {\n throw new Error('credits cannot be negative')\n }\n\n // Validate credits based on trial plan status\n if (paymentMetadata.isTrialPlan) {\n // Trial plans can have 0 credits (already validated not negative above)\n } else {\n // Non-trial plans must have positive credits\n if (!paymentMetadata.credits || paymentMetadata.credits <= 0) {\n throw new Error('credits must be a positive number for paid plans')\n }\n }\n\n if (!paymentMetadata.agentId) {\n throw new Error('agentId is required')\n }\n\n return {\n ...baseCard,\n capabilities: {\n ...baseCard.capabilities,\n extensions: [\n ...(baseCard.capabilities?.extensions || []),\n {\n uri: 'urn:nevermined:payment',\n description: paymentMetadata.costDescription,\n required: false,\n // explicit type assertion to satisfy {[key: string]: unknown}\n params: paymentMetadata as { [key: string]: unknown },\n },\n ],\n },\n }\n}\n"]}
1
+ {"version":3,"file":"agent-card.js","sourceRoot":"","sources":["../../src/a2a/agent-card.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH;;;;GAIG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,6BAA6B,CAAA;AAEvE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,wBAAwB,CAAA;AAEzE;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,wBAAwB,CAAA;AAEjE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,sBAAsB,GACjC,yEAAyE,CAAA;AA+B3E;;;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;SACF;KACF,CAAA;AACH,CAAC","sourcesContent":["/**\n * Helper to build an AgentCard with payment/pricing metadata for A2A agents.\n *\n * This module provides utilities for creating A2A agent cards that include\n * payment and pricing information in a standardized way. The payment metadata\n * is embedded in the agent card's capabilities.extensions field following\n * the A2A standard for extensibility.\n *\n * The payment extension uses the URI 'urn:nevermined:payment' and includes\n * information about pricing, credits, and payment configuration.\n */\n\nimport type { AgentCard } from './types.js'\n\n/**\n * Canonical A2A agent-card discovery path (A2A 0.3+ and `@a2a-js/sdk`'s own\n * default, per RFC 8615). Served by Nevermined A2A agents and used as the\n * default when fetching a remote agent's card.\n */\nexport const AGENT_CARD_WELL_KNOWN_PATH = '.well-known/agent-card.json'\n\n/**\n * Legacy pre-0.3 discovery path. Still served as a backward-compat alias and\n * tried as a fetch fallback, so newly-updated clients keep working against\n * Nevermined agents that have not adopted the canonical path yet.\n * TODO(a2a): drop the alias + fallback one release after agents are updated.\n */\nexport const LEGACY_AGENT_CARD_WELL_KNOWN_PATH = '.well-known/agent.json'\n\n/**\n * Nevermined's own payment extension URI. Carries the agent/plan params the\n * Nevermined paywall reads (agentId, planId, redemptionConfig, …). Kept for one\n * release alongside the official a2a-x402 extension below for backward compat.\n */\nexport const NVM_PAYMENT_EXTENSION_URI = 'urn:nevermined:payment'\n\n/**\n * Official a2a-x402 extension URI (x402 v2 A2A transport). Declaring it tells\n * generic A2A clients this agent speaks the standards-compliant in-band x402\n * flow (payment signalled through Task / Message `x402.payment.*` metadata).\n * @see https://github.com/google-agentic-commerce/a2a-x402\n */\nexport const A2A_X402_EXTENSION_URI =\n 'https://github.com/google-agentic-commerce/a2a-x402/blob/main/spec/v0.2'\n\n/**\n * Payment/pricing information to be included in the AgentCard extensions.\n *\n * This interface defines the structure for payment metadata that will be\n * embedded in the agent card. The metadata includes information about:\n * - Payment type (fixed or dynamic pricing)\n * - Credit requirements\n * - Plan identification\n * - Cost descriptions\n *\n * Must be compatible with `{[key: string]: unknown}` to comply with A2A standard.\n */\nexport interface PaymentAgentCardMetadata {\n /** Type of payment model - 'fixed' for set prices, 'dynamic' for variable pricing */\n paymentType: 'fixed' | 'dynamic'\n /** Number of credits required for this agent's services (0 for trial plans) */\n credits: number\n /** Optional plan ID associated with this agent */\n planId?: string\n /** The agent ID for payment validation and tracking */\n agentId: string\n /** Human-readable description of the cost */\n costDescription?: string\n /** Whether this is a trial plan (allows 0 credits) */\n isTrialPlan?: boolean\n /** Additional payment-related metadata */\n [key: string]: unknown // For compatibility with AgentExtension.params\n}\n\n/**\n * Builds an AgentCard with payment/pricing metadata in the capabilities.extensions field.\n *\n * This function takes a base agent card and payment metadata, then creates a new\n * agent card that includes the payment information in a standardized extension.\n * The payment extension follows the A2A standard for extensibility and uses the\n * URI 'urn:nevermined:payment' to identify payment-related capabilities.\n *\n * The resulting agent card can be used with the PaymentsA2AServer to provide\n * payment-enabled A2A agent functionality.\n *\n * @param baseCard - The base AgentCard (without payment info)\n * @param paymentMetadata - The payment/pricing metadata to include\n * @returns The AgentCard with payment info in capabilities.extensions\n *\n * @example\n * ```typescript\n * const baseCard: AgentCard = {\n * name: 'My AI Assistant',\n * description: 'An AI assistant that helps with various tasks',\n * capabilities: {\n * tools: ['text-generation', 'image-analysis'],\n * extensions: []\n * }\n * }\n *\n * const paymentMetadata: PaymentAgentCardMetadata = {\n * paymentType: 'fixed',\n * credits: 10,\n * agentId: 'agent-123',\n * planId: 'plan-456',\n * costDescription: '10 credits per request'\n * }\n *\n * const paymentCard = buildPaymentAgentCard(baseCard, paymentMetadata)\n *\n * // Use with PaymentsA2AServer\n * PaymentsA2AServer.start({\n * agentCard: paymentCard,\n * executor: new MyExecutor(),\n * paymentsService: payments,\n * port: 41242\n * })\n * ```\n */\nexport function buildPaymentAgentCard(\n baseCard: AgentCard,\n paymentMetadata: PaymentAgentCardMetadata,\n): AgentCard {\n // Validate required fields\n if (!paymentMetadata.paymentType) {\n throw new Error('paymentType is required')\n }\n\n // Validate credits - negative credits are never allowed\n if (paymentMetadata.credits < 0) {\n throw new Error('credits cannot be negative')\n }\n\n // Validate credits based on trial plan status\n if (paymentMetadata.isTrialPlan) {\n // Trial plans can have 0 credits (already validated not negative above)\n } else {\n // Non-trial plans must have positive credits\n if (!paymentMetadata.credits || paymentMetadata.credits <= 0) {\n throw new Error('credits must be a positive number for paid plans')\n }\n }\n\n if (!paymentMetadata.agentId) {\n throw new Error('agentId is required')\n }\n\n return {\n ...baseCard,\n capabilities: {\n ...baseCard.capabilities,\n extensions: [\n ...(baseCard.capabilities?.extensions || []),\n {\n uri: NVM_PAYMENT_EXTENSION_URI,\n description: paymentMetadata.costDescription,\n required: false,\n // explicit type assertion to satisfy {[key: string]: unknown}\n params: paymentMetadata as { [key: string]: unknown },\n },\n // Official a2a-x402 extension: signals to generic A2A clients that this\n // agent supports the standards-compliant in-band x402 v2 payment flow.\n // Kept additive alongside the Nevermined extension for one release.\n {\n uri: A2A_X402_EXTENSION_URI,\n description:\n paymentMetadata.costDescription ||\n 'Supports payments using the x402 protocol for on-chain settlement.',\n required: false,\n },\n ],\n },\n }\n}\n"]}
@@ -18,7 +18,7 @@ export declare class PaymentsClient extends A2AClient {
18
18
  * @param payments - The Payments object.
19
19
  * @param agentId - The ID of the agent.
20
20
  * @param planId - The ID of the plan.
21
- * @param agentCardPath - Optional path to the agent card relative to base URL (defaults to '.well-known/agent.json').
21
+ * @param agentCardPath - Optional path to the agent card relative to base URL (defaults to '.well-known/agent-card.json').
22
22
  */
23
23
  private constructor();
24
24
  /**
@@ -26,6 +26,13 @@ export declare class PaymentsClient extends A2AClient {
26
26
  * constructing the underlying A2AClient with the AgentCard object.
27
27
  */
28
28
  static create(agentBaseUrl: string, payments: Payments, agentId: string, planId: string, agentCardPath?: string, delegationConfig?: DelegationConfig): Promise<PaymentsClient>;
29
+ /**
30
+ * Fetches a remote agent card, trying the requested (canonical) path first and
31
+ * falling back to the legacy '.well-known/agent.json' so updated clients keep
32
+ * working against agents that have not adopted the canonical path yet.
33
+ * TODO(a2a): drop the fallback one release after agents are updated.
34
+ */
35
+ private static _fetchAgentCard;
29
36
  /**
30
37
  * Gets and caches the access token for this client instance.
31
38
  * @returns The access token string.
@@ -35,6 +42,39 @@ export declare class PaymentsClient extends A2AClient {
35
42
  * Clears the cached access token for this client instance.
36
43
  */
37
44
  clearToken(): void;
45
+ /**
46
+ * Build the in-band x402 message metadata (x402 v2 A2A transport).
47
+ *
48
+ * The server consumes the same base64 access token whether it arrives in the
49
+ * deprecated `payment-signature` header or in band, so the in-band
50
+ * `x402.payment.payload` is just the decoded PaymentPayload object. Falls back
51
+ * to wrapping the raw token if it is not decodable (never expected for real
52
+ * Nevermined tokens, which are base64 JSON).
53
+ *
54
+ * @param accessToken - The x402 access token string
55
+ * @returns The message-metadata fragment carrying status + payload
56
+ */
57
+ private _buildInBandPaymentMetadata;
58
+ /**
59
+ * Return a copy of the message params with the in-band x402 payment metadata
60
+ * merged into `message.metadata`, optionally correlating to a taskId returned
61
+ * by a prior `input-required` (payment-required) response. Immutable: the
62
+ * caller's params object is never mutated.
63
+ *
64
+ * @param params - The original message send params
65
+ * @param accessToken - The x402 access token to embed in band
66
+ * @param taskId - Optional taskId to correlate a payment-required follow-up
67
+ */
68
+ private _withInBandPayment;
69
+ /**
70
+ * Detect a payment-required response (x402 v2 A2A transport): an
71
+ * `input-required` task whose status message carries
72
+ * `x402.payment.status: payment-required`. Returns the task id to correlate a
73
+ * follow-up payment, or `undefined` when the response is not payment-required.
74
+ *
75
+ * @param response - The JSON-RPC send-message response
76
+ */
77
+ private _paymentRequiredTaskId;
38
78
  /**
39
79
  * Type guard to check if a JSON-RPC response is an error response.
40
80
  * @param response - The JSON-RPC response to check
@@ -1 +1 @@
1
- {"version":3,"file":"paymentsClient.d.ts","sourceRoot":"","sources":["../../src/a2a/paymentsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAGtC,OAAO,KAAK,EAAoB,gBAAgB,EAAE,MAAM,oBAAo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,OAAO,CAAC,qCAAqC,CAAC;IAUjD;;;;;;OAMG;cACa,0BAA0B,CAAC,OAAO,EAAE,SAAS,EAC3D,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,OAAO,EACf,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC/B,OAAO,CAAC,SAAS,CAAC;CA2CtB;AAED,YAAY,EACV,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,qCAAqC,EACrC,YAAY,EACZ,qCAAqC,GACtC,MAAM,aAAa,CAAA"}
@@ -2,6 +2,9 @@ import { PaymentsError } from '../common/payments.error.js';
2
2
  import { resolveScheme } from '../x402/facilitator-api.js';
3
3
  import { A2AClient } from '@a2a-js/sdk/client';
4
4
  import { v4 as uuidv4 } from 'uuid';
5
+ import { AGENT_CARD_WELL_KNOWN_PATH, LEGACY_AGENT_CARD_WELL_KNOWN_PATH } from './agent-card.js';
6
+ import { decodeAccessToken } from '../utils.js';
7
+ import { PaymentStatus, x402A2AUtils, X402A2AMetadata } from './x402-a2a.js';
5
8
  /**
6
9
  * PaymentsClient is a high-level client for A2A agents with payments integration.
7
10
  * Each instance is bound to a specific agentId and planId.
@@ -13,7 +16,7 @@ export class PaymentsClient extends A2AClient {
13
16
  * @param payments - The Payments object.
14
17
  * @param agentId - The ID of the agent.
15
18
  * @param planId - The ID of the plan.
16
- * @param agentCardPath - Optional path to the agent card relative to base URL (defaults to '.well-known/agent.json').
19
+ * @param agentCardPath - Optional path to the agent card relative to base URL (defaults to '.well-known/agent-card.json').
17
20
  */
18
21
  constructor(agentCard, payments, agentId, planId, delegationConfig) {
19
22
  super(agentCard);
@@ -27,12 +30,44 @@ export class PaymentsClient extends A2AClient {
27
30
  * Creates a PaymentsClient by fetching the AgentCard first and then
28
31
  * constructing the underlying A2AClient with the AgentCard object.
29
32
  */
30
- static async create(agentBaseUrl, payments, agentId, planId, agentCardPath = '.well-known/agent.json', delegationConfig) {
31
- const agentCardUrl = new URL(agentCardPath, agentBaseUrl).toString();
32
- const a2a = await A2AClient.fromCardUrl(agentCardUrl);
33
- const agentCard = await a2a.getAgentCard();
33
+ static async create(agentBaseUrl, payments, agentId, planId, agentCardPath = AGENT_CARD_WELL_KNOWN_PATH, delegationConfig) {
34
+ const agentCard = await PaymentsClient._fetchAgentCard(agentBaseUrl, agentCardPath);
34
35
  return new PaymentsClient(agentCard, payments, agentId, planId, delegationConfig);
35
36
  }
37
+ /**
38
+ * Fetches a remote agent card, trying the requested (canonical) path first and
39
+ * falling back to the legacy '.well-known/agent.json' so updated clients keep
40
+ * working against agents that have not adopted the canonical path yet.
41
+ * TODO(a2a): drop the fallback one release after agents are updated.
42
+ */
43
+ static async _fetchAgentCard(agentBaseUrl, agentCardPath) {
44
+ const load = async (path) => {
45
+ const a2a = await A2AClient.fromCardUrl(new URL(path, agentBaseUrl).toString());
46
+ return (await a2a.getAgentCard());
47
+ };
48
+ try {
49
+ return await load(agentCardPath);
50
+ }
51
+ catch (err) {
52
+ if (agentCardPath === LEGACY_AGENT_CARD_WELL_KNOWN_PATH) {
53
+ throw err;
54
+ }
55
+ // Canonical path failed — fall back to the legacy path. Warn, because a
56
+ // silent fallback to a typosquattable legacy path is a discovery risk.
57
+ console.warn(`[PaymentsA2A] agent card not found at '${agentCardPath}', falling back to '${LEGACY_AGENT_CARD_WELL_KNOWN_PATH}':`, err instanceof Error ? err.message : String(err));
58
+ try {
59
+ return await load(LEGACY_AGENT_CARD_WELL_KNOWN_PATH);
60
+ }
61
+ catch (legacyErr) {
62
+ // Both failed. Surface the legacy error but preserve the canonical-path
63
+ // root cause (a TLS/DNS/5xx there is otherwise masked by a clean 404).
64
+ const message = legacyErr instanceof Error ? legacyErr.message : String(legacyErr);
65
+ // `new Error(msg, { cause })` would be idiomatic but the ES2020 lib target
66
+ // types Error with 0-1 args, so attach `cause` via Object.assign instead.
67
+ throw Object.assign(new Error(`Failed to fetch agent card from '${agentCardPath}' or legacy '${LEGACY_AGENT_CARD_WELL_KNOWN_PATH}': ${message}`), { cause: err });
68
+ }
69
+ }
70
+ }
36
71
  /**
37
72
  * Gets and caches the access token for this client instance.
38
73
  * @returns The access token string.
@@ -62,6 +97,67 @@ export class PaymentsClient extends A2AClient {
62
97
  clearToken() {
63
98
  this.accessToken = null;
64
99
  }
100
+ /**
101
+ * Build the in-band x402 message metadata (x402 v2 A2A transport).
102
+ *
103
+ * The server consumes the same base64 access token whether it arrives in the
104
+ * deprecated `payment-signature` header or in band, so the in-band
105
+ * `x402.payment.payload` is just the decoded PaymentPayload object. Falls back
106
+ * to wrapping the raw token if it is not decodable (never expected for real
107
+ * Nevermined tokens, which are base64 JSON).
108
+ *
109
+ * @param accessToken - The x402 access token string
110
+ * @returns The message-metadata fragment carrying status + payload
111
+ */
112
+ _buildInBandPaymentMetadata(accessToken) {
113
+ const payload = decodeAccessToken(accessToken) ?? { token: accessToken };
114
+ return {
115
+ [X402A2AMetadata.STATUS_KEY]: PaymentStatus.PAYMENT_SUBMITTED,
116
+ [X402A2AMetadata.PAYLOAD_KEY]: payload,
117
+ };
118
+ }
119
+ /**
120
+ * Return a copy of the message params with the in-band x402 payment metadata
121
+ * merged into `message.metadata`, optionally correlating to a taskId returned
122
+ * by a prior `input-required` (payment-required) response. Immutable: the
123
+ * caller's params object is never mutated.
124
+ *
125
+ * @param params - The original message send params
126
+ * @param accessToken - The x402 access token to embed in band
127
+ * @param taskId - Optional taskId to correlate a payment-required follow-up
128
+ */
129
+ _withInBandPayment(params, accessToken, taskId) {
130
+ return {
131
+ ...params,
132
+ message: {
133
+ ...params.message,
134
+ ...(taskId ? { taskId } : {}),
135
+ metadata: {
136
+ ...(params.message.metadata || {}),
137
+ ...this._buildInBandPaymentMetadata(accessToken),
138
+ },
139
+ },
140
+ };
141
+ }
142
+ /**
143
+ * Detect a payment-required response (x402 v2 A2A transport): an
144
+ * `input-required` task whose status message carries
145
+ * `x402.payment.status: payment-required`. Returns the task id to correlate a
146
+ * follow-up payment, or `undefined` when the response is not payment-required.
147
+ *
148
+ * @param response - The JSON-RPC send-message response
149
+ */
150
+ _paymentRequiredTaskId(response) {
151
+ if (this.isErrorResponse(response)) {
152
+ return undefined;
153
+ }
154
+ const result = response.result;
155
+ if (!result || result.kind !== 'task' || result.status?.state !== 'input-required') {
156
+ return undefined;
157
+ }
158
+ const status = x402A2AUtils.getPaymentStatus(result);
159
+ return status === PaymentStatus.PAYMENT_REQUIRED ? result.id : undefined;
160
+ }
65
161
  /**
66
162
  * Type guard to check if a JSON-RPC response is an error response.
67
163
  * @param response - The JSON-RPC response to check
@@ -77,8 +173,21 @@ export class PaymentsClient extends A2AClient {
77
173
  */
78
174
  async sendA2AMessage(params) {
79
175
  const accessToken = await this._getX402AccessToken();
176
+ // Primary path (x402 v2 A2A transport): carry the payment in band. Keep the
177
+ // deprecated `payment-signature` header for one release so servers that have
178
+ // not adopted the in-band transport still authorize the request.
80
179
  const headers = { 'payment-signature': accessToken };
81
- return this._postRpcRequestWithHeaders('message/send', params, headers);
180
+ const inBandParams = this._withInBandPayment(params, accessToken);
181
+ const response = await this._postRpcRequestWithHeaders('message/send', inBandParams, headers);
182
+ // Reactive flow: if the server replied with an `input-required`
183
+ // payment-required task (it did not accept the in-band payload, e.g. it sent
184
+ // requirements first), resubmit the payment correlated to that task id.
185
+ const taskId = this._paymentRequiredTaskId(response);
186
+ if (taskId) {
187
+ const followUp = this._withInBandPayment(params, accessToken, taskId);
188
+ return this._postRpcRequestWithHeaders('message/send', followUp, headers);
189
+ }
190
+ return response;
82
191
  }
83
192
  /**
84
193
  * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
@@ -96,13 +205,16 @@ export class PaymentsClient extends A2AClient {
96
205
  }
97
206
  const endpoint = await this._getServiceEndpoint();
98
207
  const clientRequestId = uuidv4();
208
+ const accessToken = await this._getX402AccessToken();
209
+ // Carry the payment in band (x402 v2 A2A transport); keep the deprecated
210
+ // header for one release as a fallback.
211
+ const inBandParams = this._withInBandPayment(params, accessToken);
99
212
  const rpcRequest = {
100
213
  jsonrpc: '2.0',
101
214
  method: 'message/stream',
102
- params: params,
215
+ params: inBandParams,
103
216
  id: clientRequestId,
104
217
  };
105
- const accessToken = await this._getX402AccessToken();
106
218
  const response = await fetch(endpoint, {
107
219
  method: 'POST',
108
220
  headers: {
@@ -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;AAGnC;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,SAAS;IAO3C;;;;;;;OAOG;IACH,YACE,SAAoB,EACpB,QAAkB,EAClB,OAAe,EACf,MAAc,EACd,gBAAmC;QAEnC,KAAK,CAAC,SAAS,CAAC,CAAA;QAChB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAA;QACxC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAA;IACzB,CAAC;IAED;;;OAGG;IACI,MAAM,CAAC,KAAK,CAAC,MAAM,CACxB,YAAoB,EACpB,QAAkB,EAClB,OAAe,EACf,MAAc,EACd,aAAa,GAAG,wBAAwB,EACxC,gBAAmC;QAEnC,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC,QAAQ,EAAE,CAAA;QACpE,MAAM,GAAG,GAAG,MAAM,SAAS,CAAC,WAAW,CAAC,YAAY,CAAC,CAAA;QACrD,MAAM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a,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 } 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'\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.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 = '.well-known/agent.json',\n delegationConfig?: DelegationConfig,\n ): Promise<PaymentsClient> {\n const agentCardUrl = new URL(agentCardPath, agentBaseUrl).toString()\n const a2a = await A2AClient.fromCardUrl(agentCardUrl)\n const agentCard = await (a2a as any).getAgentCard()\n return new PaymentsClient(agentCard as AgentCard, payments, agentId, planId, delegationConfig)\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 * Type guard to check if a JSON-RPC response is an error response.\n * @param response - The JSON-RPC response to check\n * @returns true if the response contains an error, false otherwise\n */\n isErrorResponse(response: JSONRPCResponse): response is JSONRPCErrorResponse {\n return response != null && typeof response === 'object' && 'error' in response\n }\n\n /**\n * Sends a message to the agent, managing authentication automatically.\n * @param params - The parameters for sending the message.\n * @returns The response from the agent.\n */\n public async sendA2AMessage(params: MessageSendParams): Promise<SendMessageResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { 'payment-signature': accessToken }\n return this._postRpcRequestWithHeaders<MessageSendParams, SendMessageResponse>(\n 'message/send',\n params,\n headers,\n )\n }\n\n /**\n * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).\n * Push notification configuration can be specified in `params.configuration`.\n * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.\n * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).\n * @param params - The parameters for sending the message.\n * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).\n * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.\n */\n public async *sendA2AMessageStream(\n params: MessageSendParams,\n ): AsyncGenerator<any, void, undefined> {\n const agentCard = await (this as any).agentCardPromise\n if (!agentCard.capabilities?.streaming) {\n throw new Error(\n 'Agent does not support streaming (AgentCard.capabilities.streaming is not true).',\n )\n }\n const endpoint = await (this as any)._getServiceEndpoint()\n const clientRequestId = uuidv4()\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'message/stream',\n params: params as { [key: string]: any },\n id: clientRequestId,\n }\n const accessToken = await this._getX402AccessToken()\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n 'payment-signature': accessToken,\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n const errorJson = JSON.parse(errorBody)\n if (errorJson.error) {\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('HTTP error establishing stream')) throw e\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,\n )\n }\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`,\n )\n }\n if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {\n throw new Error(\"Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.\")\n }\n // Parse and yield SSE events\n for await (const event of this._parseA2AStream(response, clientRequestId)) {\n yield event\n }\n }\n\n /**\n * Parses an HTTP response body as an A2A Server-Sent Event stream.\n * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,\n * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).\n * @param response -The HTTP Response object whose body is the SSE stream.\n * @param originalRequestId - The ID of the client's JSON-RPC request that initiated this stream.\n * Used to validate the `id` in the streamed JSON-RPC responses.\n * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.\n */\n private async *_parseA2AStream<TStreamItem>(\n response: Response,\n originalRequestId: number | string | null,\n ): AsyncGenerator<TStreamItem, void, undefined> {\n if (!response.body) {\n throw new Error('SSE response body is undefined. Cannot read stream.')\n }\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()\n let buffer = '' // Holds incomplete lines from the stream\n let eventDataBuffer = '' // Holds accumulated 'data:' lines for the current event\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n // Process any final buffered event data if the stream ends abruptly after a 'data:' line\n if (eventDataBuffer.trim()) {\n const result = this._processEventData<TStreamItem>(eventDataBuffer, originalRequestId)\n yield result\n }\n break // Stream finished\n }\n\n buffer += value // Append new chunk to buffer\n let lineEndIndex\n // Process all complete lines in the buffer\n while ((lineEndIndex = buffer.indexOf('\\n')) >= 0) {\n const line = buffer.substring(0, lineEndIndex).trim() // Get and trim the line\n buffer = buffer.substring(lineEndIndex + 1) // Remove processed line from buffer\n\n if (line === '') {\n // Empty line: signifies the end of an event\n if (eventDataBuffer) {\n // If we have accumulated data for an event\n const result = this._processEventData<TStreamItem>(eventDataBuffer, originalRequestId)\n yield result\n eventDataBuffer = '' // Reset buffer for the next event\n }\n } else if (line.startsWith('data:')) {\n eventDataBuffer += line.substring(5).trimStart() + '\\n' // Append data (multi-line data is possible)\n } else if (line.startsWith(':')) {\n // This is a comment line in SSE, ignore it.\n }\n }\n }\n } catch (error: any) {\n throw new PaymentsError(error.message, 'payments_error')\n } finally {\n reader.releaseLock() // Ensure the reader lock is released\n }\n }\n\n /**\n * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.\n * @param jsonData - The string content from one or more 'data:' lines of an SSE event.\n * @param originalRequestId - The ID of the client's request that initiated the stream.\n * @returns The `result` field of the parsed JSON-RPC success response.\n * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.\n */\n private _processEventData<TStreamItem>(\n jsonData: string,\n originalRequestId: number | string | null,\n ): TStreamItem {\n if (!jsonData.trim()) {\n throw new Error('Attempted to process empty SSE event data.')\n }\n try {\n // SSE data can be multi-line, ensure it's treated as a single JSON string.\n const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\\n$/, ''))\n\n // Type assertion to SendStreamingMessageResponse, as this is the expected structure for A2A streams.\n const a2aStreamResponse: any = sseJsonRpcResponse\n\n if (a2aStreamResponse.id !== originalRequestId) {\n // According to JSON-RPC spec, notifications (which SSE events can be seen as) might not have an ID,\n // or if they do, it should match. A2A spec implies streamed events are tied to the initial request.\n throw new PaymentsError(\n `SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`,\n 'payments_error',\n )\n }\n\n if (this.isErrorResponse && this.isErrorResponse(a2aStreamResponse)) {\n const err = a2aStreamResponse.error\n throw new PaymentsError(\n `SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data)}`,\n )\n }\n\n // Check if 'result' exists, as it's mandatory for successful JSON-RPC responses\n if (!('result' in a2aStreamResponse) || typeof a2aStreamResponse.result === 'undefined') {\n throw new PaymentsError(\n `SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`,\n 'payments_error',\n )\n }\n\n return a2aStreamResponse as TStreamItem\n } catch (e: any) {\n // Catch errors from JSON.parse or if it's an error response that was thrown by this function\n if (\n e.message.startsWith('SSE event contained an error') ||\n e.message.startsWith(\"SSE event JSON-RPC response is missing 'result' field\")\n ) {\n throw new PaymentsError(e.message, 'payments_error')\n }\n\n throw new PaymentsError(\n `Failed to parse SSE event data: \"${jsonData.substring(0, 100)}...\". Original error: ${e.message}`,\n 'payments_error',\n )\n }\n }\n\n /**\n * Resubscribes to a task's event stream using Server-Sent Events (SSE).\n * This is used if a previous SSE connection for an active task was broken.\n * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).\n * @param params - Parameters containing the taskId.\n * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).\n */\n public async *resubscribeA2ATask(params: TaskIdParams): AsyncGenerator<any, void, undefined> {\n const agentCard = await (this as any).agentCardPromise\n if (!agentCard.capabilities?.streaming) {\n throw new Error('Agent does not support streaming (required for tasks/resubscribe).')\n }\n const endpoint = await (this as any)._getServiceEndpoint()\n const clientRequestId = uuidv4()\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'tasks/resubscribe',\n params: params as { [key: string]: any },\n id: clientRequestId,\n }\n const accessToken = await this._getX402AccessToken()\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n 'payment-signature': accessToken,\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n const errorJson = JSON.parse(errorBody)\n if (errorJson.error) {\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('HTTP error establishing stream')) throw e\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,\n )\n }\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`,\n )\n }\n if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {\n throw new Error(\n \"Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.\",\n )\n }\n // Parse and yield SSE events\n for await (const event of this._parseA2AStream(response, clientRequestId)) {\n yield event\n }\n }\n\n /**\n * Retrieves a task by its ID, managing authentication automatically.\n * @param params - The parameters for the task query.\n * @returns The task response.\n */\n public async getA2ATask(params: TaskQueryParams): Promise<GetTaskResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { 'payment-signature': accessToken }\n return this._postRpcRequestWithHeaders<TaskQueryParams, GetTaskResponse>(\n 'tasks/get',\n params,\n headers,\n )\n }\n\n /**\n * Sets or updates the push notification configuration for a given task, managing authentication automatically.\n * @param params - The parameters for the task push notification configuration.\n * @returns The response from the agent.\n */\n public async setA2ATaskPushNotificationConfig(\n params: TaskPushNotificationConfig,\n ): Promise<SetTaskPushNotificationConfigResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { 'payment-signature': accessToken }\n return this._postRpcRequestWithHeaders<\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse\n >('tasks/pushNotificationConfig/set', params, headers)\n }\n\n /**\n * Gets the push notification configuration for a given task, managing authentication automatically.\n * @param params - The parameters for the task push notification configuration.\n * @returns The response from the agent.\n */\n public async getA2ATaskPushNotificationConfig(\n params: TaskIdParams,\n ): Promise<GetTaskPushNotificationConfigResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { 'payment-signature': accessToken }\n return this._postRpcRequestWithHeaders<TaskIdParams, GetTaskPushNotificationConfigResponse>(\n 'tasks/pushNotificationConfig/get',\n params,\n headers,\n )\n }\n\n /**\n * Internal helper to make a JSON-RPC POST request with custom headers.\n * @param method - The RPC method name.\n * @param params - The parameters for the RPC method.\n * @param headers - Optional custom headers.\n * @returns The response from the agent.\n */\n protected async _postRpcRequestWithHeaders<TParams, TResponse>(\n method: string,\n params: TParams,\n headers?: Record<string, string>,\n ): Promise<TResponse> {\n const endpoint = await (this as any)._getServiceEndpoint()\n const requestId = uuidv4()\n const rpcRequest = { jsonrpc: '2.0', method, params, id: requestId }\n const httpResponse = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...(headers || {}),\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!httpResponse.ok) {\n let errorBodyText = '(empty or non-JSON response)'\n try {\n errorBodyText = await httpResponse.text()\n const errorJson = JSON.parse(errorBodyText)\n if (!errorJson.jsonrpc && errorJson.error) {\n throw new Error(\n `RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data)}`,\n )\n } else if (!errorJson.jsonrpc) {\n throw new Error(\n `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('RPC error for') || e.message.startsWith('HTTP error for')) throw e\n throw new Error(\n `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,\n )\n }\n }\n const rpcResponse = await httpResponse.json()\n if (rpcResponse.id !== requestId) {\n throw new PaymentsError(\n `CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`,\n 'payments_error',\n )\n }\n return rpcResponse as TResponse\n }\n}\n\nexport type {\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\n"]}
1
+ {"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;IAO3C;;;;;;;OAOG;IACH,YACE,SAAoB,EACpB,QAAkB,EAClB,OAAe,EACf,MAAc,EACd,gBAAmC;QAEnC,KAAK,CAAC,SAAS,CAAC,CAAA;QAChB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAA;QACxC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAA;IACzB,CAAC;IAED;;;OAGG;IACI,MAAM,CAAC,KAAK,CAAC,MAAM,CACxB,YAAoB,EACpB,QAAkB,EAClB,OAAe,EACf,MAAc,EACd,aAAa,GAAG,0BAA0B,EAC1C,gBAAmC;QAEnC,MAAM,SAAS,GAAG,MAAM,cAAc,CAAC,eAAe,CAAC,YAAY,EAAE,aAAa,CAAC,CAAA;QACnF,OAAO,IAAI,cAAc,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAA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AAC,CAAA;gBAC3C,IAAI,CAAC,SAAS,CAAC,OAAO,IAAI,SAAS,CAAC,KAAK,EAAE,CAAC;oBAC1C,MAAM,IAAI,KAAK,CACb,iBAAiB,MAAM,KAAK,SAAS,CAAC,KAAK,CAAC,OAAO,WAAW,SAAS,CAAC,KAAK,CAAC,IAAI,kBAAkB,YAAY,CAAC,MAAM,WAAW,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CACzK,CAAA;gBACH,CAAC;qBAAM,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;oBAC9B,MAAM,IAAI,KAAK,CACb,kBAAkB,MAAM,aAAa,YAAY,CAAC,MAAM,IAAI,YAAY,CAAC,UAAU,eAAe,aAAa,EAAE,CAClH,CAAA;gBACH,CAAC;YACH,CAAC;YAAC,OAAO,CAAM,EAAE,CAAC;gBAChB,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC;oBAAE,MAAM,CAAC,CAAA;gBAC5F,MAAM,IAAI,KAAK,CACb,kBAAkB,MAAM,aAAa,YAAY,CAAC,MAAM,IAAI,YAAY,CAAC,UAAU,eAAe,aAAa,EAAE,CAClH,CAAA;YACH,CAAC;QACH,CAAC;QACD,MAAM,WAAW,GAAG,MAAM,YAAY,CAAC,IAAI,EAAE,CAAA;QAC7C,IAAI,WAAW,CAAC,EAAE,KAAK,SAAS,EAAE,CAAC;YACjC,MAAM,IAAI,aAAa,CACrB,iDAAiD,MAAM,cAAc,SAAS,SAAS,WAAW,CAAC,EAAE,iDAAiD,EACtJ,gBAAgB,CACjB,CAAA;QACH,CAAC;QACD,OAAO,WAAwB,CAAA;IACjC,CAAC;CACF","sourcesContent":["import { Payments } from '../index.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { resolveScheme } from '../x402/facilitator-api.js'\nimport type { X402TokenOptions, DelegationConfig } 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"]}
@@ -105,6 +105,29 @@ export declare class PaymentsRequestHandler extends DefaultRequestHandler {
105
105
  * @returns Object containing PaymentsRequestContext and related data
106
106
  */
107
107
  private createPaymentsRequestContext;
108
+ /**
109
+ * x402 v2 A2A transport: if the request is payment-gated and arrived with no
110
+ * token (the middleware stored a `paymentRequired` on the HTTP context), build
111
+ * and return the spec-shaped `input-required` task carrying the
112
+ * X402PaymentRequired object under `x402.payment.required` — WITHOUT executing
113
+ * the agent. Returns `undefined` when a token was present (normal flow).
114
+ *
115
+ * @param params - The incoming message send parameters
116
+ * @returns The `input-required` Task to return to the client, or `undefined`
117
+ */
118
+ private buildPaymentRequiredTaskIfNeeded;
119
+ /**
120
+ * Stamp x402 settlement state onto the final task's metadata, in band, per the
121
+ * x402 v2 A2A transport. Only applied when the token arrived in band (so the
122
+ * legacy `payment-signature` header path is unchanged). On success the task
123
+ * carries `x402.payment.status: payment-completed` + `x402.payment.receipts`;
124
+ * on failure `payment-failed` + `x402.payment.error` + receipts.
125
+ *
126
+ * @param task - The current task (mutated in place)
127
+ * @param httpContext - The request's HTTP context
128
+ * @param settlement - The settlement result, or undefined when none ran
129
+ */
130
+ private recordInBandSettlement;
108
131
  /**
109
132
  * Processes streaming events with finalization (credits burning and push notifications).
110
133
  * Similar to processEventsWithFinalization but yields events for streaming.
@@ -115,7 +138,7 @@ export declare class PaymentsRequestHandler extends DefaultRequestHandler {
115
138
  * @param validation - The validation result
116
139
  * @returns Async generator yielding processed events
117
140
  */
118
- protected processStreamingEventsWithFinalization(taskId: string, resultManager: ResultManager, eventQueue: ExecutionEventQueue, bearerToken: string): AsyncGenerator<A2AStreamEvent, void, undefined>;
141
+ protected processStreamingEventsWithFinalization(taskId: string, resultManager: ResultManager, eventQueue: ExecutionEventQueue, bearerToken: string, requestHttpContext?: HttpRequestContext): AsyncGenerator<A2AStreamEvent, void, undefined>;
119
142
  /**
120
143
  * Processes all events, calling handleTaskFinalization when a terminal status-update event is received.
121
144
  * In async mode, it can be launched in background.
@@ -123,7 +146,7 @@ export declare class PaymentsRequestHandler extends DefaultRequestHandler {
123
146
  protected processEventsWithFinalization(taskId: string, resultManager: ResultManager, eventQueue: ExecutionEventQueue, bearerToken: string, validation: StartAgentRequest, options?: {
124
147
  firstResultResolver?: (event: any) => void;
125
148
  firstResultRejector?: (err: any) => void;
126
- }): Promise<void>;
149
+ }, requestHttpContext?: HttpRequestContext): Promise<void>;
127
150
  /**
128
151
  * Sends a message, validating credits before execution and burning credits after.
129
152
  * Also sends a push notification if the task reaches a terminal state.