@devlab.group/agent-commerce 2.5.0 → 2.6.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 (100) hide show
  1. package/README.md +63 -11
  2. package/dist/ap2.d.ts +19 -6
  3. package/dist/ap2.js +56 -18
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-FKQK5XZA.js → chunk-DRLBML7Z.js} +13 -11
  6. package/dist/chunk-DRLBML7Z.js.map +1 -0
  7. package/dist/{chunk-VUCMBGUR.js → chunk-G3EYYHKF.js} +3 -3
  8. package/dist/{chunk-VUCMBGUR.js.map → chunk-G3EYYHKF.js.map} +1 -1
  9. package/dist/{chunk-3OTCFFFT.js → chunk-M52FBNJX.js} +3 -5
  10. package/dist/chunk-M52FBNJX.js.map +1 -0
  11. package/dist/chunk-M6BSXXTF.js +8 -0
  12. package/dist/chunk-M6BSXXTF.js.map +1 -0
  13. package/dist/{chunk-4K7FIBJM.js → chunk-M6MQ3FYS.js} +3 -3
  14. package/dist/{chunk-4K7FIBJM.js.map → chunk-M6MQ3FYS.js.map} +1 -1
  15. package/dist/chunk-M6WW6QIT.js +18 -0
  16. package/dist/chunk-M6WW6QIT.js.map +1 -0
  17. package/dist/cli/{ap2-YAPLERSC.js → ap2-2YMYA2H6.js} +57 -20
  18. package/dist/cli/ap2-2YMYA2H6.js.map +1 -0
  19. package/dist/cli/{chunk-5R7DM5LM.js → chunk-3NOMLMJW.js} +26 -26
  20. package/dist/cli/chunk-3NOMLMJW.js.map +1 -0
  21. package/dist/cli/chunk-4KLYFXMW.js +8 -0
  22. package/dist/cli/{chunk-M7NXVRU5.js.map → chunk-4KLYFXMW.js.map} +1 -1
  23. package/dist/cli/chunk-6R6WJ4FD.js +18 -0
  24. package/dist/cli/chunk-6R6WJ4FD.js.map +1 -0
  25. package/dist/cli/{chunk-2J2IQQ4X.js → chunk-AZL7RPFU.js} +37 -32
  26. package/dist/cli/chunk-AZL7RPFU.js.map +1 -0
  27. package/dist/cli/{chunk-JFVRG2HH.js → chunk-DHFMIBPG.js} +7 -7
  28. package/dist/cli/chunk-DHFMIBPG.js.map +1 -0
  29. package/dist/cli/{chunk-IDY2735M.js → chunk-GET3CZGR.js} +2 -2
  30. package/dist/cli/chunk-GET3CZGR.js.map +1 -0
  31. package/dist/cli/{chunk-QLUCNPRT.js → chunk-NSYSMDQN.js} +831 -169
  32. package/dist/cli/chunk-NSYSMDQN.js.map +1 -0
  33. package/dist/cli/{chunk-Z34UMZBB.js → chunk-PTL7SNOI.js} +83 -57
  34. package/dist/cli/chunk-PTL7SNOI.js.map +1 -0
  35. package/dist/cli/{chunk-2UPPX3FJ.js → chunk-TFV3K6YS.js} +75 -13
  36. package/dist/cli/chunk-TFV3K6YS.js.map +1 -0
  37. package/dist/cli/{chunk-NIU5EMSB.js → chunk-VJH6RYRK.js} +5 -5
  38. package/dist/cli/{chunk-NIU5EMSB.js.map → chunk-VJH6RYRK.js.map} +1 -1
  39. package/dist/cli/{chunk-QA2OPHBF.js → chunk-YOF7IK4V.js} +14 -13
  40. package/dist/cli/chunk-YOF7IK4V.js.map +1 -0
  41. package/dist/cli/{chunk-4H2QLHQI.js → chunk-YWG2ZN3L.js} +3 -3
  42. package/dist/cli/{chunk-4H2QLHQI.js.map → chunk-YWG2ZN3L.js.map} +1 -1
  43. package/dist/cli/config-3K65QJ22.js +12 -0
  44. package/dist/cli/{config-BWFMN2ZB.js.map → config-3K65QJ22.js.map} +1 -1
  45. package/dist/cli/index.js +524 -230
  46. package/dist/cli/index.js.map +1 -1
  47. package/dist/cli/{mcp-KZEMXLHR.js → mcp-6F64A7KE.js} +4 -4
  48. package/dist/cli/{mcp-KZEMXLHR.js.map → mcp-6F64A7KE.js.map} +1 -1
  49. package/dist/cli/payment-providers-2ITS6KNR.js +6 -0
  50. package/dist/cli/{payment-providers-SZL36H3Y.js.map → payment-providers-2ITS6KNR.js.map} +1 -1
  51. package/dist/cli/{provider-6TKB5ADJ.js → provider-5BGG5YKQ.js} +34 -16
  52. package/dist/cli/provider-5BGG5YKQ.js.map +1 -0
  53. package/dist/cli/receipts-I4IIE7U6.js +8 -0
  54. package/dist/cli/{receipts-ZGLJWMQG.js.map → receipts-I4IIE7U6.js.map} +1 -1
  55. package/dist/cli/reconcile-55WNCSFC.js +4 -0
  56. package/dist/cli/{reconcile-IC22MJD5.js.map → reconcile-55WNCSFC.js.map} +1 -1
  57. package/dist/cli/{run-ZTYPQI4D.js → run-2P6ZGFUE.js} +220 -73
  58. package/dist/cli/run-2P6ZGFUE.js.map +1 -0
  59. package/dist/cli/{x402-WLYBLODI.js → x402-4LPIIELI.js} +8 -8
  60. package/dist/cli/{x402-WLYBLODI.js.map → x402-4LPIIELI.js.map} +1 -1
  61. package/dist/index.d.ts +104 -201
  62. package/dist/index.js +1048 -262
  63. package/dist/index.js.map +1 -1
  64. package/dist/logger-CllGwQ8i.d.ts +19 -0
  65. package/dist/mcp.d.ts +3 -1
  66. package/dist/mcp.js +2 -1
  67. package/dist/mcp.js.map +1 -1
  68. package/dist/mpp.d.ts +2 -1
  69. package/dist/mpp.js +31 -12
  70. package/dist/mpp.js.map +1 -1
  71. package/dist/{protocol-adapter-DEXpdp8m.d.ts → protocol-adapter-1WbtM3xG.d.ts} +5 -132
  72. package/dist/{runtime-Dz2fSO-P.d.ts → runtime-B-kARa2f.d.ts} +5 -20
  73. package/dist/store-kIIMpUA-.d.ts +372 -0
  74. package/dist/testing.d.ts +51 -0
  75. package/dist/testing.js +1896 -0
  76. package/dist/testing.js.map +1 -0
  77. package/dist/transaction-Dv0UFGg5.d.ts +129 -0
  78. package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
  79. package/dist/x402.d.ts +2 -1
  80. package/dist/x402.js +5 -4
  81. package/dist/x402.js.map +1 -1
  82. package/package.json +5 -1
  83. package/dist/chunk-3OTCFFFT.js.map +0 -1
  84. package/dist/chunk-FKQK5XZA.js.map +0 -1
  85. package/dist/cli/ap2-YAPLERSC.js.map +0 -1
  86. package/dist/cli/chunk-2J2IQQ4X.js.map +0 -1
  87. package/dist/cli/chunk-2UPPX3FJ.js.map +0 -1
  88. package/dist/cli/chunk-5R7DM5LM.js.map +0 -1
  89. package/dist/cli/chunk-IDY2735M.js.map +0 -1
  90. package/dist/cli/chunk-JFVRG2HH.js.map +0 -1
  91. package/dist/cli/chunk-M7NXVRU5.js +0 -8
  92. package/dist/cli/chunk-QA2OPHBF.js.map +0 -1
  93. package/dist/cli/chunk-QLUCNPRT.js.map +0 -1
  94. package/dist/cli/chunk-Z34UMZBB.js.map +0 -1
  95. package/dist/cli/config-BWFMN2ZB.js +0 -12
  96. package/dist/cli/payment-providers-SZL36H3Y.js +0 -6
  97. package/dist/cli/provider-6TKB5ADJ.js.map +0 -1
  98. package/dist/cli/receipts-ZGLJWMQG.js +0 -8
  99. package/dist/cli/reconcile-IC22MJD5.js +0 -4
  100. package/dist/cli/run-ZTYPQI4D.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/gateway/optional-peer.ts","../../src/gateway/payment-providers.ts"],"names":[],"mappings":";;;AAGA,IAAM,eAAA,GAAkB,+BAAA;AAQxB,eAAsB,kBAAA,CAAsB,SAAiB,IAAA,EAAoC;AAC/F,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,IAAA,EAAK;AAAA,EACpB,SAAS,KAAA,EAAO;AACd,IAAA,IAAK,KAAA,EAAwC,IAAA,KAAS,sBAAA,EAAwB,MAAM,KAAA;AACpF,IAAA,MAAM,MAAM,eAAA,CAAgB,IAAA,CAAM,KAAA,CAAgB,OAAO,IAAI,CAAC,CAAA;AAC9D,IAAA,IAAI,GAAA,KAAQ,QAAW,MAAM,KAAA;AAC7B,IAAA,MAAM,IAAI,aAAA;AAAA,MACR,gBAAA;AAAA,MACA,CAAA,EAAG,OAAO,CAAA,8BAAA,EAAiC,GAAG,CAAA,wHAAA,CAAA;AAAA,MAG9C,EAAE,KAAA;AAAM,KACV;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AA;AACxE","file":"chunk-DHFMIBPG.js","sourcesContent":["import { CommerceError } from '../core';\n\n// Node's ERR_MODULE_NOT_FOUND message for a bare specifier it could not resolve\nconst MISSING_PACKAGE = /Cannot find package '([^']+)'/;\n\n/**\n * Loads the module behind an enabled config feature. A package that is not\n * installed becomes a CONFIG_INVALID naming the feature and the package,\n * instead of a resolver error pointing into a bundled chunk. Any other\n * failure, such as a missing file inside an installed package, is rethrown.\n */\nexport async function importOptionalPeer<T>(feature: string, load: () => Promise<T>): Promise<T> {\n try {\n return await load();\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException | null)?.code !== 'ERR_MODULE_NOT_FOUND') throw cause;\n const pkg = MISSING_PACKAGE.exec((cause as Error).message)?.[1];\n if (pkg === undefined) throw cause;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `${feature} is enabled, but the package \"${pkg}\" is not installed. Install the ` +\n 'optional peers it needs at the versions `agent-commerce version` lists, or ' +\n 'disable it.',\n { cause },\n );\n }\n}\n","/**\n * Builds enabled payment rails on demand. x402 needs no `mppx`; MPP uses\n * x402 internally and needs its EVM peers. Peer loading follows each rail's\n * `enabled` flag, not resource prices: an enabled rail needs its peers even\n * when every resource is free.\n */\nimport type { Ap2AuthorizationProvider } from '../authorization/ap2';\nimport type { GatewayConfig } from '../config';\nimport type { X402OptionConfig } from '../config/schema';\nimport type { Logger, PaymentProvider, ReceiptStore } from '../core';\nimport type { X402OfferOptions } from '../payments/x402';\nimport { importOptionalPeer } from './optional-peer';\n\nfunction offerOptions(option: X402OptionConfig): X402OfferOptions {\n return {\n network: option.network,\n rpcUrl: option.rpcUrl,\n asset: option.asset,\n assetDecimals: option.assetDecimals,\n payTo: option.payTo,\n ...(option.assetName !== undefined ? { assetName: option.assetName } : {}),\n ...(option.assetVersion !== undefined ? { assetVersion: option.assetVersion } : {}),\n ...(option.assetTransferMethod !== undefined\n ? { assetTransferMethod: option.assetTransferMethod }\n : {}),\n };\n}\n\nexport async function createConfiguredPaymentProviders(\n payments: GatewayConfig['payments'],\n logger: Logger,\n): Promise<PaymentProvider[]> {\n const providers: PaymentProvider[] = [];\n const { x402, mpp } = payments;\n if (x402?.enabled) {\n const { createX402PaymentProvider } = await importOptionalPeer(\n 'payments.x402',\n () => import('../payments/x402'),\n );\n providers.push(\n createX402PaymentProvider({\n // Support manually built single-option configs without `options`\n offers: (x402.options ?? [x402]).map(offerOptions),\n ...(x402.resourceOptions !== undefined\n ? {\n resourceOffers: Object.fromEntries(\n Object.entries(x402.resourceOptions).map(([id, list]) => [\n id,\n list.map(offerOptions),\n ]),\n ),\n }\n : {}),\n maxTimeoutSeconds: x402.maxTimeoutSeconds,\n ...(x402.paymentFlow !== undefined ? { paymentFlow: x402.paymentFlow } : {}),\n ...(x402.resourcePaymentFlows !== undefined\n ? { resourcePaymentFlows: x402.resourcePaymentFlows }\n : {}),\n ...(x402.resourceMimeTypes !== undefined\n ? { resourceMimeTypes: x402.resourceMimeTypes }\n : {}),\n facilitator: x402.facilitator,\n ...(x402.allowMainnet !== undefined ? { allowMainnet: x402.allowMainnet } : {}),\n ...(x402.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: x402.allowUnauthenticatedFacilitator }\n : {}),\n ...(x402.networks !== undefined ? { customNetworks: x402.networks } : {}),\n // Pass quote settings only to x402; MPP builds a separate settlement\n // provider without quotes\n ...(x402.quote !== undefined ? { quote: x402.quote } : {}),\n logger,\n }),\n );\n }\n if (mpp?.enabled) {\n const { createMppPaymentProvider } = await importOptionalPeer(\n 'payments.mpp',\n () => import('../payments/mpp/provider'),\n );\n providers.push(\n createMppPaymentProvider({\n recipient: mpp.recipient as `0x${string}`,\n asset: mpp.asset as `0x${string}`,\n assetName: mpp.assetName,\n assetVersion: mpp.assetVersion,\n network: mpp.network,\n realm: mpp.realm,\n challengeSecret: mpp.challengeSecret,\n ...(mpp.challengeTtlSeconds !== undefined\n ? { challengeTtlSeconds: mpp.challengeTtlSeconds }\n : {}),\n rpcUrl: mpp.rpcUrl,\n facilitator: mpp.facilitator,\n ...(mpp.allowMainnet !== undefined ? { allowMainnet: mpp.allowMainnet } : {}),\n ...(mpp.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: mpp.allowUnauthenticatedFacilitator }\n : {}),\n ...(mpp.paymentFlow !== undefined ? { paymentFlow: mpp.paymentFlow } : {}),\n ...(mpp.resourcePaymentFlows !== undefined\n ? { resourcePaymentFlows: mpp.resourcePaymentFlows }\n : {}),\n logger,\n }),\n );\n }\n return providers;\n}\n\n/**\n * Build enabled authorization providers for CLI hold updates. AP2 uses\n * `store` when it has the hold methods, otherwise its configured legacy file.\n * The caller must close each provider; providers leave the shared store open.\n */\nexport async function createConfiguredAuthorizationProviders(\n authorization: GatewayConfig['authorization'],\n logger: Logger,\n store: ReceiptStore,\n): Promise<Ap2AuthorizationProvider[]> {\n const ap2 = authorization?.ap2;\n if (!ap2?.enabled) return [];\n const { createAp2AuthorizationProvider } = await importOptionalPeer(\n 'authorization.ap2',\n () => import('../authorization/ap2'),\n );\n return [createAp2AuthorizationProvider({ config: ap2, logger, store })];\n}\n"]}
@@ -199,5 +199,5 @@ function isHttpProtocolAdapter(adapter) {
199
199
  }
200
200
 
201
201
  export { AUTHORIZATION_HEADER, AUTHORIZATION_INPUT_FIELD, DEFAULT_BACKEND_TIMEOUT_MS, DELIVERY_SUMMARY_META_KEY, NOOP_LOGGER, PAYMENT_HEADER, PAYMENT_INPUT_FIELD, PAYMENT_METHOD_NAMES, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PROTOCOL_NAMES, RECONCILIATION_METADATA_KEY, RESERVED_INPUT_FIELDS, TRANSACTION_STATES, extractReservedInputFields, isHttpProtocolAdapter, parseAuthorizationHeader, parseAuthorizationSubmission, systemClock, toDeliverySummary, toErrorEnvelope, toPaymentRequiredEnvelope, transactionState };
202
- //# sourceMappingURL=chunk-IDY2735M.js.map
203
- //# sourceMappingURL=chunk-IDY2735M.js.map
202
+ //# sourceMappingURL=chunk-GET3CZGR.js.map
203
+ //# sourceMappingURL=chunk-GET3CZGR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/domain/payment.ts","../../src/core/interfaces/runtime.ts","../../src/core/domain/common.ts","../../src/core/domain/resource.ts","../../src/core/domain/transaction.ts","../../src/core/domain/wire.ts","../../src/core/interfaces/logger.ts","../../src/core/interfaces/protocol-adapter.ts"],"names":[],"mappings":";;;;AAuBO,IAAM,2BAAA,GAA8B;;;ACRpC,IAAM,WAAA,GAAqB;AAAA,EAChC,GAAA,EAAK,sBAAM,IAAI,IAAA,EAAK;AAAA,EACpB,MAAA,EAAQ,MAAA,iBAAM,IAAI,IAAA,IAAO,WAAA,EAAY;AAAA,EACrC,WAAA,EAAa,MAAM,WAAA,CAAY,GAAA;AACjC;;;ACNA,IAAM,kBAAA,GAAiD;AAAA,EACrD,IAAA,EAAM,IAAA;AAAA,EACN,GAAA,EAAK,IAAA;AAAA,EACL,GAAA,EAAK,IAAA;AAAA,EACL,GAAA,EAAK;AACP,CAAA;AAMO,IAAM,iBAA0C,MAAA,CAAO,IAAA;AAAA,EAC5D;AACF;AAaA,IAAM,wBAAA,GAA4D,EAAE,IAAA,EAAM,IAAA,EAAM,KAAK,IAAA,EAAK;AAGnF,IAAM,uBAAqD,MAAA,CAAO,IAAA;AAAA,EACvE;AACF;;;ACCO,IAAM,0BAAA,GAA6B;;;AChCnC,IAAM,kBAAA,GAAqB;AAAA,EAChC,iBAAA;AAAA,EACA,gBAAA;AAAA,EACA,mBAAA;AAAA,EACA,qBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA;AACF;AAkFA,IAAM,SAAA,GAAY,CAAC,MAAA,KAA4B,MAAA,IAAU,OAAO,MAAA,IAAU,GAAA;AAOnE,SAAS,gBAAA,CACd,OACA,GAAA,EACqC;AACrC,EAAA,MAAM,EAAE,OAAA,EAAS,OAAA,EAAS,WAAA,EAAY,GAAI,KAAA;AA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AA,KAAiB,QAAA,IAAY,YAAA,CAAa,MAAA,GAAS,CAAA,IAAK,MAAA,KAAW,MAAA,GACrE,EAAE,MAAA,EAAQ,OAAA,EAAS,cAAa,GACjC,MAAA;AACN,EAAA,MAAM,aAAA,GAAgB,4BAAA,CAA6B,kBAAA,EAAoB,SAAS,CAAA;AAEhF,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,GAAI,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,KAAY,EAAC;AAAA,IAC3C,GAAI,aAAA,KAAkB,MAAA,GAAY,EAAE,aAAA,KAAkB;AAAC,GACzD;AACF;;;ACzVO,IAAM,WAAA,GAAsB;AAAA,EACjC,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AACf;;;AC0DO,SAAS,sBAAsB,OAAA,EAA0D;AAC9F,EAAA,OAAO,OAAQ,QAAgC,UAAA,KAAe,UAAA;AAChE","file":"chunk-GET3CZGR.js","sourcesContent":["/**\n * Canonical payment model. FROZEN CONTRACT.\n *\n * Core decides that a payment is required and for how much. Payment providers\n * decide how the challenge is encoded, verified and settled. No x402- or\n * EVM-specific type may appear in this file.\n */\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n DecimalAmount,\n IsoTimestamp,\n PaymentMethodName,\n} from './common';\nimport type { PaymentAttempt } from './receipt';\nimport type { CommerceResource } from './resource';\n\n/**\n * `PaymentResult.metadata` key for public coordinates returned by `verify`\n * for later provider reconciliation. Core must store the value unchanged and\n * interpret only `expiresAt`. Never include signatures, payloads or\n * transaction bytes. Experimental: may change in a minor release.\n */\nexport const RECONCILIATION_METADATA_KEY = 'reconciliation';\n\n/**\n * Provider-native payment challenge, opaque to core. For x402 the `accepts`\n * entries are x402 `PaymentRequirements` objects, passed to protocol adapters\n * verbatim.\n */\nexport interface PaymentChallenge {\n readonly provider: PaymentMethodName;\n /** Provider protocol version, e.g. the x402 `x402Version` value as a string */\n readonly version: string;\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim: for x402 v2 the\n * `PaymentRequired` object a buyer's client consumes, for MPP an object\n * carrying the serialized `WWW-Authenticate` challenge. Opaque to core.\n *\n * `accepts` alone is not that document: x402 v2 carries the resource\n * description and protocol version on the envelope. Adapters with a native\n * channel for it (x402's `PAYMENT-REQUIRED` header, MPP's `WWW-Authenticate`)\n * send it there as is, so every surface offers the same challenge.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What the buyer must pay, in canonical terms, plus the provider-native\n * challenge the buyer's client needs to construct a payment\n */\nexport interface PaymentRequirement {\n readonly id: string;\n readonly requestId: string;\n readonly resourceId: string;\n readonly provider: PaymentMethodName;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * Merchant-controlled settlement destination, never a gateway-owned wallet.\n * Multi-offer challenges omit this, `network` and `asset`; selection\n * supplies the chosen offer's terms.\n */\n readonly destination?: string;\n readonly network?: string;\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n readonly challenge: PaymentChallenge;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Opaque payment proof supplied by the buyer's client. For x402 over HTTP it is\n * the base64 `PAYMENT-SIGNATURE` header value; over MCP and A2A it is the same\n * string in the reserved `_payment` input field.\n */\nexport interface PaymentSubmission {\n readonly method: PaymentMethodName;\n readonly payload: string;\n}\n\n/** Outcome of verification or settlement */\nexport interface PaymentResult {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly provider: PaymentMethodName;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly payer?: string;\n readonly payee?: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly network?: string;\n readonly asset?: string;\n /**\n * Stable, provider-computed identity of the payment authorization.\n *\n * The pipeline reserves this key before settlement and rejects a second\n * request presenting it with `PAYMENT_REPLAYED`. Providers must derive it\n * only from the authorization (payer, nonce, asset, network), so the same\n * authorization always maps to the same key. A `rejected` result may also\n * carry it so a store lookup can identify an unfinished attempt even when\n * verification rejects the proof because its transfer has landed.\n */\n readonly replayKey?: string;\n /** Machine-readable rejection reason when status is `rejected` */\n readonly rejectionReason?: string;\n readonly settledAt?: IsoTimestamp;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Input to {@link PaymentProvider.createRequirement} */\nexport interface PaymentContext {\n readonly requestId: string;\n readonly resource: CommerceResource;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly requestedAt: IsoTimestamp;\n /**\n * Validated resource input used to build the backend request. The pipeline\n * sets this field on every createRequirement call. A rail may bind its\n * challenge to the input but must not send it to a third party.\n */\n readonly input?: unknown;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Input to {@link PaymentProvider.verify} */\nexport interface PaymentVerificationContext {\n readonly requestId: string;\n readonly resource: CommerceResource;\n readonly requirement: PaymentRequirement;\n readonly submission: PaymentSubmission;\n}\n\n/** Input to {@link PaymentProvider.settle} */\nexport interface PaymentSettlementContext extends PaymentVerificationContext {\n readonly verification: PaymentResult;\n}\n\n/** Input to {@link PaymentProvider.reconcile}. Experimental: may change in a minor release */\nexport interface PaymentReconciliationContext {\n readonly attempt: PaymentAttempt;\n /** Coordinates from `verify`; optional for compatibility with pre-2.5.0 attempts */\n readonly locator?: Readonly<Record<string, unknown>>;\n readonly now: IsoTimestamp;\n}\n\n/** Chain evidence for resolving an attempt. Experimental: may change in a minor release */\nexport interface PaymentReconciliationResult {\n /**\n * Report `settled` only with a final transfer record for this authorization.\n * Report `not-settled` only when a state read proves it unused after it can\n * no longer land; missing logs or receipts are insufficient. Otherwise,\n * report `unknown`.\n */\n readonly outcome: 'settled' | 'not-settled' | 'unknown';\n /** A machine-readable token, such as `not_final` */\n readonly reason: string;\n readonly externalReference?: string;\n /** Public chain facts only */\n readonly evidence?: Readonly<Record<string, unknown>>;\n /** For `unknown`, the earliest time a different answer is possible, if known */\n readonly retryAfter?: IsoTimestamp;\n}\n\n/**\n * Contract every payment rail implements. Implementations must be\n * non-custodial: they orchestrate an external payment protocol and never hold\n * buyer or merchant production signing keys.\n */\nexport interface PaymentProvider {\n readonly name: PaymentMethodName;\n readonly descriptor: AdapterDescriptor;\n\n /**\n * Build the requirement and its challenge. The pipeline calls it for every\n * paid request, including one that already carries a proof to verify.\n */\n createRequirement(context: PaymentContext): Promise<PaymentRequirement>;\n\n /**\n * Selects a proof's offer before verification, returning its destination,\n * network, asset and metadata while preserving `id` and the full `challenge`.\n * Verification, authorization, replay reservation and settlement use the result.\n * This hook must not verify, reserve or settle. If no unique offer matches,\n * return the original requirement for `verify` to reject.\n */\n selectRequirement?(context: PaymentVerificationContext): Promise<PaymentRequirement>;\n\n /**\n * Validate a submitted proof against the requirement. Must return `rejected`\n * or throw a `CommerceError` rather than an untyped error, and must never\n * move funds.\n */\n verify(context: PaymentVerificationContext): Promise<PaymentResult>;\n\n /**\n * Execute settlement. Called only after `verify` returned `verified` and the\n * replay key was reserved. A settlement verdict, including a rejection, is a\n * returned result; the pipeline records any throw as settlement-uncertain.\n */\n settle(context: PaymentSettlementContext): Promise<PaymentResult>;\n\n /**\n * Read chain evidence for an attempt with an unknown outcome. Implementations\n * must not write, broadcast or call a facilitator. Providers without this\n * hook require manual resolution. Experimental: may change in a minor release.\n */\n reconcile?(context: PaymentReconciliationContext): Promise<PaymentReconciliationResult>;\n\n health(): Promise<AdapterHealth>;\n}\n","// Time and ids are injected so tests can be deterministic\nimport type { IsoTimestamp } from '../domain/common';\n\nexport interface Clock {\n now(): Date;\n nowIso(): IsoTimestamp;\n /** Milliseconds since an arbitrary origin; use for durations only */\n monotonicMs(): number;\n}\n\nexport interface IdGenerator {\n /** Opaque, collision-resistant identifier */\n next(prefix?: string): string;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n nowIso: () => new Date().toISOString(),\n monotonicMs: () => performance.now(),\n};\n","// Shared primitive aliases for the canonical domain model. FROZEN CONTRACT\n\n/**\n * A JSON Schema document (in practice a draft 2020-12 subset). Deliberately\n * loose: adapters translate it to their own schema representation. Never treat\n * it as trusted input without validation.\n */\nexport type JsonSchema = Record<string, unknown>;\n\n/** Protocol surfaces a resource can be exposed through */\nexport type ProtocolName = 'http' | 'mcp' | 'a2a' | 'acp';\n\n// A Record over the union fails to compile when a name is missing or extra\nconst PROTOCOL_NAME_KEYS: Record<ProtocolName, true> = {\n http: true,\n mcp: true,\n a2a: true,\n acp: true,\n};\n\n/**\n * The same names as a value, for code that checks one at runtime: config\n * validation and the OpenAPI importer's `--expose`\n */\nexport const PROTOCOL_NAMES: readonly ProtocolName[] = Object.keys(\n PROTOCOL_NAME_KEYS,\n) as ProtocolName[];\n\n/**\n * Payment rails a resource can accept.\n *\n * A resource's list is an ordered candidate list, not a buyer-selected menu.\n * The pipeline uses the first method with an enabled provider, and a\n * rejection ends the request instead of trying another rail. Config requires at\n * least one named rail to be enabled and permits others that are not.\n */\nexport type PaymentMethodName = 'x402' | 'mpp';\n\n// Checked for completeness the same way as PROTOCOL_NAME_KEYS\nconst PAYMENT_METHOD_NAME_KEYS: Record<PaymentMethodName, true> = { x402: true, mpp: true };\n\n/** The same names as a value, for config validation */\nexport const PAYMENT_METHOD_NAMES: readonly PaymentMethodName[] = Object.keys(\n PAYMENT_METHOD_NAME_KEYS,\n) as PaymentMethodName[];\n\n/**\n * Authorization methods a resource can require. Neither a transport nor a\n * payment rail: it proves the purchase was approved, and sits beside the\n * payment rather than replacing it.\n */\nexport type AuthorizationMethodName = 'ap2';\n\n/** ISO-8601 timestamp string, always UTC with millisecond precision */\nexport type IsoTimestamp = string;\n\n/**\n * A decimal amount as a string in the currency's display unit (for example\n * \"0.01\" USDC), never a float and never base units. Payment providers convert\n * it to on-chain base units.\n */\nexport type DecimalAmount = string;\n\n/** Health of an individual adapter or subsystem */\nexport interface AdapterHealth {\n readonly status: 'pass' | 'warn' | 'fail';\n readonly detail?: string;\n readonly checkedAt: IsoTimestamp;\n readonly durationMs?: number;\n /**\n * Results per checked part, such as each x402 offer. Names and statuses\n * may be published; exclude diagnostic detail.\n */\n readonly components?: readonly AdapterHealthComponent[];\n}\n\n/** One part of an {@link AdapterHealth} result */\nexport interface AdapterHealthComponent {\n readonly name: string;\n readonly status: 'pass' | 'warn' | 'fail';\n}\n\n/** Describes an adapter's supported surface for diagnostics */\nexport interface AdapterDescriptor {\n readonly name: string;\n readonly kind: 'protocol' | 'payment' | 'storage' | 'authorization';\n /** Version of this adapter implementation, independent of the spec */\n readonly implementationVersion: string;\n /** Exact pinned specification revision this adapter targets */\n readonly supportedSpec: string;\n readonly capabilities: readonly string[];\n readonly status: 'stable' | 'experimental' | 'planned';\n /** Capabilities explicitly not implemented, printed by `doctor` */\n readonly unsupported?: readonly string[];\n}\n","// Canonical resource model. FROZEN CONTRACT\nimport type {\n AuthorizationMethodName,\n DecimalAmount,\n JsonSchema,\n PaymentMethodName,\n ProtocolName,\n} from './common';\n\n/** HTTP methods a backend handler may use */\nexport type BackendMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * How the gateway calls the merchant's existing backend.\n *\n * Backend URLs come from operator configuration only, never from users or\n * agents (docs/security.md, SSRF). Secret header values belong in `${ENV_VAR}`\n * placeholders resolved by the config loader, not in plaintext configuration.\n */\nexport interface BackendHandler {\n readonly type: 'http';\n readonly method: BackendMethod;\n readonly url: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Hard upper bound on the backend call. Defaults to `DEFAULT_BACKEND_TIMEOUT_MS` */\n readonly timeoutMs?: number;\n /**\n * Names the top-level input properties carrying each part of the request.\n *\n * When absent, `{param}` values come from top-level input and everything left\n * over becomes the query string (GET/DELETE) or the whole JSON body\n * (POST/PUT/PATCH). That cannot express an operation with path, query and\n * body at once, such as `POST /users/{userId}/orders?notify=true`.\n *\n * When present, each group comes from its named property, and top-level input\n * that no binding names is not forwarded.\n */\n readonly inputBindings?: {\n readonly path?: string;\n readonly query?: string;\n readonly body?: string;\n };\n}\n\n/** Default backend timeout when a resource does not specify one */\nexport const DEFAULT_BACKEND_TIMEOUT_MS = 10_000;\n\n/**\n * Canonical pricing. `dynamic` exists in the type for forward compatibility;\n * config validation rejects it and the pipeline refuses it as defense in depth.\n */\nexport type Pricing =\n | { readonly type: 'free' }\n | {\n readonly type: 'fixed';\n readonly amount: DecimalAmount;\n readonly currency: string;\n }\n | {\n readonly type: 'dynamic';\n readonly resolver: string;\n };\n\n/**\n * A merchant capability exposed to agents. Protocol adapters map it outward and\n * never define their own parallel notion of a resource.\n */\nexport interface CommerceResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly handler: BackendHandler;\n readonly pricing: Pricing;\n readonly exposedVia: readonly ProtocolName[];\n readonly paymentMethods: readonly PaymentMethodName[];\n /**\n * Authorization the buyer must present in addition to payment. Opt-in per\n * resource. It sits beside `paymentMethods`, not inside it, because an\n * authorization method is not a payment rail and must never be selectable as\n * one.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationMethodName[];\n };\n}\n\n/** Read-only view of every configured resource */\nexport interface ResourceRegistry {\n get(id: string): CommerceResource | undefined;\n list(): readonly CommerceResource[];\n /** Resources exposed through a given protocol surface */\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[];\n has(id: string): boolean;\n}\n","/**\n * Canonical transaction model. FROZEN CONTRACT.\n *\n * A transaction links a paid purchase's request, payment attempt, optional\n * authorization hold, backend call and receipt by ID. PaymentAttempt owns the\n * payment status; journal readers must read it from the attempt rather than\n * maintain a separate copy.\n */\nimport type { AuthorizationRecord } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName, ProtocolName } from './common';\nimport type { PaymentAttempt } from './receipt';\n\n/** States derived by {@link transactionState} */\nexport const TRANSACTION_STATES = [\n 'payment-pending',\n 'payment-failed',\n 'payment-uncertain',\n 'settled-undelivered',\n 'delivery-started',\n 'delivery-unknown',\n 'delivered',\n] as const;\n\n/**\n * Open to state names added by later releases; consumers must handle values\n * outside {@link TRANSACTION_STATES}\n */\nexport type TransactionState = (typeof TRANSACTION_STATES)[number] | (string & {});\n\n/** Last hold state communicated to the authorization provider */\nexport type AuthorizationHoldState = 'reserved' | 'consumed' | 'released' | 'uncertain';\n\n/**\n * Store writes reported as failed during an execution. Consumers must handle\n * unlisted labels that later releases may add.\n */\nexport type PersistenceFailure = 'payment-attempt' | 'receipt' | 'journal' | (string & {});\n\n/**\n * Journal record for a paid purchase, starting with replay reservation.\n * Store only references and digests, never payment proofs, signatures, mandates\n * or input bodies.\n */\nexport interface Transaction {\n readonly id: string;\n /** The request that created it */\n readonly requestId: string;\n readonly resourceId: string;\n readonly protocol: ProtocolName;\n /** Cached derived state; readers must recompute it with {@link transactionState} */\n readonly state: TransactionState;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly attemptId: string;\n readonly replayKey: string;\n /** Read from PaymentAttempt, not maintained independently */\n readonly status: PaymentAttempt['status'];\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly network?: string;\n readonly asset?: string;\n readonly payee?: string;\n readonly externalReference?: string;\n /**\n * Public coordinates for the provider's `reconcile` hook, governed by\n * `RECONCILIATION_METADATA_KEY`\n */\n readonly locator?: Readonly<Record<string, unknown>>;\n /** When the provider's `settle` was called */\n readonly settlingAt?: IsoTimestamp;\n /** The authorization cannot land after this */\n readonly expiresAt?: IsoTimestamp;\n };\n readonly authorization?: AuthorizationRecord & {\n /** The handle the authorization provider consumes or releases */\n readonly reservationId: string;\n readonly hold: AuthorizationHoldState;\n };\n readonly backend?: {\n readonly dispatchedAt: IsoTimestamp;\n /** Dispatch time plus the backend timeout and a margin */\n readonly deadlineAt: IsoTimestamp;\n /** 0 if the call ended without a status, such as a timeout or transport failure */\n readonly status?: number;\n readonly errorCode?: string;\n };\n readonly receiptId?: string;\n /** `sha256:` followed by the canonical JSON input digest in hex; omit for non-I-JSON input */\n readonly inputDigest?: string;\n /** Digest of pricing and settlement terms, excluding credentials */\n readonly configDigest: string;\n readonly persistenceFailures?: readonly PersistenceFailure[];\n readonly createdAt: IsoTimestamp;\n readonly updatedAt: IsoTimestamp;\n /** Time of the pipeline's last journal write before returning the outcome */\n readonly completedAt?: IsoTimestamp;\n}\n\n/** What {@link transactionState} reads */\nexport type TransactionFacts = Pick<Transaction, 'backend' | 'completedAt'> & {\n readonly payment: Pick<Transaction['payment'], 'status'>;\n};\n\nconst isSuccess = (status: number): boolean => status >= 200 && status <= 299;\n\n/**\n * Derive state from payment status, backend facts and pipeline completion.\n * For a settled payment, a dispatched call with no result after `deadlineAt`\n * means `delivery-unknown`; a timeout does not prove that the backend never ran.\n */\nexport function transactionState(\n facts: TransactionFacts,\n now: IsoTimestamp,\n): (typeof TRANSACTION_STATES)[number] {\n const { payment, backend, completedAt } = facts;\n if (payment.status === 'settlement-uncertain' || payment.status === 'failed') {\n return 'payment-uncertain';\n }\n if (payment.status === 'rejected') return 'payment-failed';\n\n // Invalid timestamps make the comparison false, treating the deadline as passed\n const waiting =\n backend !== undefined &&\n completedAt === undefined &&\n Date.parse(now) < Date.parse(backend.deadlineAt);\n if (payment.status !== 'settled') {\n return waiting && backend?.status === undefined ? 'delivery-started' : 'payment-pending';\n }\n\n if (backend === undefined) return 'settled-undelivered';\n const { status } = backend;\n if (status !== undefined && status !== 0 && !isSuccess(status)) return 'settled-undelivered';\n if (status !== undefined && isSuccess(status) && completedAt !== undefined) return 'delivered';\n // Wait until the deadline for a missing result or an unfinished 2xx flow.\n // Status 0 means the call already ended without a response.\n if (status !== 0 && waiting) return 'delivery-started';\n return 'delivery-unknown';\n}\n","/**\n * Gateway-defined wire envelopes and carriers. FROZEN CONTRACT.\n *\n * The HTTP routes and the MCP and A2A adapters build their \"payment required\"\n * and \"error\" bodies with these helpers, so those surfaces send the same\n * shapes. The ACP adapter maps errors to ACP's own error format instead.\n */\n\nimport { CommerceError, type CommerceErrorCode } from '../errors';\nimport { isRecord } from '../is-record';\nimport type { AuthorizationRequirement, AuthorizationSubmission } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName } from './common';\nimport type { PaymentSubmission } from './payment';\nimport type { DeliveredOutcome, PaymentRequiredOutcome } from './request';\nimport type { CommerceResource } from './resource';\n\n/**\n * Reserved input property carrying a payment proof on protocols with no header\n * channel (MCP tool calls, A2A message data). HTTP uses a header instead.\n */\nexport const PAYMENT_INPUT_FIELD = '_payment';\n\n/**\n * HTTP request header carrying an x402 payment proof. MPP proofs use\n * `Authorization: Payment ...` instead.\n *\n * The x402 v2 header names, lowercased as Node presents incoming headers. v1's\n * `X-PAYMENT` / `X-PAYMENT-RESPONSE` pair is not accepted: honoring both\n * versions would mean two verification paths for the same money.\n */\nexport const PAYMENT_HEADER = 'payment-signature';\n\n/** HTTP response header carrying the settlement result */\nexport const PAYMENT_RESPONSE_HEADER = 'payment-response';\n\n/**\n * Reserved input property carrying an authorization proof, the counterpart of\n * {@link PAYMENT_INPUT_FIELD}.\n *\n * `_payment` is a bare string whose method is taken from the resource's first\n * payment method. This field is a `{ method, payload }` object, because the\n * method of a security control should be stated, not inferred.\n */\nexport const AUTHORIZATION_INPUT_FIELD = '_authorization';\n\n/**\n * Every input property name the gateway claims for itself. The config loader\n * rejects a resource declaring one, protocol adapters lift them out of client\n * input, and the pipeline strips them again as defense in depth.\n */\nexport const RESERVED_INPUT_FIELDS: readonly string[] = [\n PAYMENT_INPUT_FIELD,\n AUTHORIZATION_INPUT_FIELD,\n];\n\n/**\n * HTTP request header carrying the authorization proof: base64url-encoded JSON\n * of the same `{ method, payload }` object the reserved input field carries.\n *\n * An Agent Commerce carrier, not a header from any authorization\n * specification. It is namespaced rather than reusing `Authorization`, which\n * already carries other credentials, including MPP payment proofs.\n */\nexport const AUTHORIZATION_HEADER = 'agent-authorization';\n\n/**\n * Hard cap on the encoded `Agent-Authorization` header.\n *\n * Node's default limit is 16 KiB across all request headers, and a request over\n * it is refused before the gateway sees it. Capping well below that gives an\n * oversized proof a deterministic `AUTHORIZATION_INVALID` naming the limit.\n */\nexport const MAX_AUTHORIZATION_HEADER_BYTES = 8192;\n\n/**\n * HTTP response header carrying the base64 x402 challenge on a 402.\n *\n * The body still carries the richer {@link PaymentRequiredEnvelope}, the only\n * channel MCP has, but an x402 v2 client reads the challenge from this header\n * and ignores the body, so both are sent.\n */\nexport const PAYMENT_REQUIRED_HEADER = 'payment-required';\n\n/**\n * Key under which a protocol adapter attaches a {@link DeliverySummary} to its\n * result metadata: MCP's `CallToolResult._meta` and the A2A task artifact's\n * metadata.\n *\n * Part of the frozen contract because producer and consumer must agree on it;\n * both import this constant. Follows MCP's `<namespace>/<name>` convention for\n * `_meta` keys.\n */\nexport const DELIVERY_SUMMARY_META_KEY = 'agent-commerce/delivery';\n\nexport interface PaymentRequiredEnvelope {\n readonly status: 'payment-required';\n readonly code: 'PAYMENT_REQUIRED';\n readonly requestId: string;\n readonly resourceId: string;\n readonly message: string;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly version: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `payTo`; MPP challenges use\n * `request.recipient`. Omitted for multi-offer x402 challenges.\n */\n readonly destination?: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `network`; MPP challenges use\n * the numeric `request.methodDetails.chainId`\n */\n readonly network?: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `asset`; MPP challenges use\n * `request.currency`\n */\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n /** Provider-native requirement objects, passed through verbatim */\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim (see\n * {@link PaymentChallenge.envelope}). Present for providers that have one;\n * a buyer's protocol client can hand it straight to its SDK.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n };\n /**\n * Present only when the resource also requires an authorization proof, so a\n * client learns before it spends anything that paying alone will not get the\n * resource delivered. A client that ignores the field sees the plain\n * envelope. The proof comes from the merchant's own approval flow, outside\n * the gateway.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationRequirement[];\n };\n}\n\nexport interface ErrorEnvelope {\n readonly status: 'error';\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a buyer learns about their own completed purchase: the request, whether\n * it settled, and the settlement reference they can check on-chain. The\n * merchant's ledger is not theirs to read, which is why `/api/receipts` is an\n * operator route behind `server.adminToken`.\n */\nexport interface DeliverySummary {\n readonly requestId: string;\n readonly resourceId: string;\n readonly receiptId: string;\n /** `false` marks a failed receipt write; do not treat `receiptId` as proof of persistence */\n readonly receiptCommitted?: false;\n readonly deliveredAt: IsoTimestamp;\n readonly payment?: {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly amount: DecimalAmount;\n readonly currency: string;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly network?: string;\n };\n}\n\n/** Build the payer-facing summary of a delivered outcome */\nexport function toDeliverySummary(outcome: DeliveredOutcome): DeliverySummary {\n const p = outcome.payment;\n return {\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n receiptId: outcome.receipt.id,\n ...(outcome.persistenceFailures?.includes('receipt') ? { receiptCommitted: false } : {}),\n deliveredAt: outcome.receipt.deliveredAt,\n ...(p !== undefined\n ? {\n payment: {\n status: p.status,\n amount: p.amount,\n currency: p.currency,\n ...(p.externalReference !== undefined\n ? { externalReference: p.externalReference }\n : {}),\n ...(p.network !== undefined ? { network: p.network } : {}),\n },\n }\n : {}),\n };\n}\n\nexport function toPaymentRequiredEnvelope(\n outcome: PaymentRequiredOutcome,\n): PaymentRequiredEnvelope {\n const r = outcome.requirement;\n return {\n status: 'payment-required',\n code: 'PAYMENT_REQUIRED',\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n message: `Payment of ${r.amount} ${r.currency} is required for resource \"${outcome.resourceId}\". Retry with a ${r.provider} payment proof.`,\n payment: {\n provider: r.provider,\n version: r.challenge.version,\n amount: r.amount,\n currency: r.currency,\n ...(r.destination !== undefined ? { destination: r.destination } : {}),\n ...(r.network !== undefined ? { network: r.network } : {}),\n ...(r.asset !== undefined ? { asset: r.asset } : {}),\n ...(r.expiresAt !== undefined ? { expiresAt: r.expiresAt } : {}),\n accepts: r.challenge.accepts,\n ...(r.challenge.envelope !== undefined ? { envelope: r.challenge.envelope } : {}),\n },\n ...(outcome.authorization !== undefined && outcome.authorization.length > 0\n ? { authorization: { required: outcome.authorization } }\n : {}),\n };\n}\n\nexport function toErrorEnvelope(error: CommerceError): ErrorEnvelope {\n const info = error.toInfo();\n return {\n status: 'error',\n code: info.code,\n message: info.message,\n retryable: info.retryable,\n ...(info.requestId !== undefined ? { requestId: info.requestId } : {}),\n ...(info.resourceId !== undefined ? { resourceId: info.resourceId } : {}),\n ...(info.details !== undefined ? { details: info.details } : {}),\n };\n}\n\nexport function isPaymentRequiredEnvelope(value: unknown): value is PaymentRequiredEnvelope {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as PaymentRequiredEnvelope).status === 'payment-required' &&\n typeof (value as PaymentRequiredEnvelope).payment === 'object'\n );\n}\n\n/**\n * Parses the `{ method, payload }` authorization object, whichever carrier\n * brought it. Absent returns `undefined`; malformed throws\n * `AUTHORIZATION_INVALID`.\n *\n * An unusable `_payment` is dropped, which leaves the buyer a 402 to act on. A\n * dropped authorization would instead come back as \"not authorized\", with no\n * way to tell a rejected mandate from a typo in the object around it.\n */\nexport function parseAuthorizationSubmission(\n value: unknown,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n if (value === undefined || value === null) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (!isRecord(value)) {\n return fail(`expected an object with \"method\" and \"payload\", got ${typeof value}`);\n }\n const method = value['method'];\n const payload = value['payload'];\n\n // Compared against the literal rather than a registry: a second method needs\n // a second verifier, a deliberate addition rather than a string that starts\n // working because a client sent it\n if (method !== 'ap2') {\n fail(`unsupported method ${typeof method === 'string' ? `\"${method}\"` : typeof method}`);\n }\n if (typeof payload !== 'string' || payload.length === 0) {\n fail('\"payload\" must be a non-empty string');\n }\n\n return { method: 'ap2', payload: payload as string };\n}\n\n/**\n * Decodes the base64url JSON `Agent-Authorization` header. The size check runs\n * on the encoded value, so an oversized header costs a length comparison rather\n * than a decode and a JSON parse.\n */\nexport function parseAuthorizationHeader(\n raw: string | readonly string[] | undefined,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n const value = Array.isArray(raw) ? raw[0] : (raw as string | undefined);\n if (value === undefined || value.length === 0) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (Buffer.byteLength(value, 'utf8') > MAX_AUTHORIZATION_HEADER_BYTES) {\n fail(`header exceeds the ${MAX_AUTHORIZATION_HEADER_BYTES}-byte limit`);\n }\n\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));\n } catch {\n // Nothing from the exception is repeated back: a JSON parse error quotes\n // the input it choked on, which here is whatever the caller sent\n fail('header is not base64url-encoded JSON');\n }\n return parseAuthorizationSubmission(decoded, requestId);\n}\n\n/**\n * Splits raw client input into resource input plus the reserved fields, for\n * protocols that carry them in the input object (MCP tool arguments, A2A\n * message data). HTTP carries both in headers.\n *\n * A payment proof is labeled with the resource's first payment method.\n * `createGateway` puts provider-backed methods first so the label matches the\n * pipeline's selection; a custom registry must keep that order. A resource with\n * no payment method gets no payment proof, so the request reaches the pipeline\n * unpaid.\n */\nexport function extractReservedInputFields(\n rawInput: Record<string, unknown>,\n resource: CommerceResource | undefined,\n requestId?: string,\n): {\n input: Record<string, unknown>;\n payment?: PaymentSubmission;\n authorization?: AuthorizationSubmission;\n} {\n const {\n [PAYMENT_INPUT_FIELD]: paymentValue,\n [AUTHORIZATION_INPUT_FIELD]: authorizationValue,\n ...input\n } = rawInput;\n\n const method = resource?.paymentMethods[0];\n const payment =\n typeof paymentValue === 'string' && paymentValue.length > 0 && method !== undefined\n ? ({ method, payload: paymentValue } satisfies PaymentSubmission)\n : undefined;\n const authorization = parseAuthorizationSubmission(authorizationValue, requestId);\n\n return {\n input,\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n","/**\n * Minimal structural logger. Core does not depend on pino; the gateway injects\n * a pino instance that satisfies this shape.\n *\n * Never log secrets: private keys, seed phrases, Authorization headers or\n * payment authorization payloads.\n */\nexport interface Logger {\n debug(obj: Record<string, unknown>, msg?: string): void;\n info(obj: Record<string, unknown>, msg?: string): void;\n warn(obj: Record<string, unknown>, msg?: string): void;\n error(obj: Record<string, unknown>, msg?: string): void;\n child(bindings: Record<string, unknown>): Logger;\n}\n\n/** A logger that discards everything */\nexport const NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n","/**\n * Protocol adapter boundary. FROZEN CONTRACT.\n *\n * An adapter translates a protocol's wire format into a `CanonicalRequest`,\n * hands it to the execution pipeline and maps the outcome back. It must not\n * call merchant backends, implement payment logic or hold its own copy of the\n * canonical model. A failure while starting or serving one adapter must not\n * stop the others.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AdapterDescriptor, AdapterHealth, ProtocolName } from '../domain/common';\nimport type { EventSink } from '../domain/event';\nimport type { ExecutionPipeline } from '../domain/request';\nimport type { ResourceRegistry } from '../domain/resource';\nimport type { Logger } from './logger';\nimport type { Clock, IdGenerator } from './runtime';\n\n/** Everything an adapter is given. Nothing else is available to it */\nexport interface ProtocolAdapterContext {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n /** Externally reachable base URL of the gateway, from config */\n readonly publicBaseUrl: string;\n}\n\nexport interface ProtocolAdapter {\n readonly name: ProtocolName;\n readonly descriptor: AdapterDescriptor;\n\n start(context: ProtocolAdapterContext): Promise<void>;\n health(): Promise<AdapterHealth>;\n stop(): Promise<void>;\n}\n\n/**\n * A protocol adapter served over HTTP. The gateway mounts `handleHttp` at\n * `mountPath` with raw Node request and response objects, so adapters stay\n * independent of the HTTP framework.\n *\n * Guarantee: `req` arrives with its body stream unread. The gateway suppresses\n * every body parser on the mount, so an adapter whose SDK reads the body itself\n * (MCP's Streamable HTTP transport) can do so. The adapter owns reading,\n * size-limiting beyond the gateway's own cap, and parsing.\n *\n * The guarantee can break silently. Fastify prefers its exact-match\n * `application/json` and `text/plain` parsers over a `'*'` wildcard, so a\n * wildcard no-op alone lets the JSON parser drain the body and the adapter\n * reads an empty stream. The MCP conformance suite drives `handleHttp` over a\n * bare `node:http` server and cannot catch it, so any change to adapter mounting\n * needs a test that POSTs a JSON body through the real gateway and asserts the\n * adapter received it intact.\n */\nexport interface HttpProtocolAdapter extends ProtocolAdapter {\n /** Path prefix the gateway mounts this adapter at, e.g. '/mcp' */\n readonly mountPath: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n /**\n * Fixed paths this adapter owns outside its mount, for protocols whose\n * specification pins a discovery URL (A2A's `/.well-known/agent-card.json`).\n * The gateway mounts them with the same guarantees as `mountPath`: unread\n * body, concurrency cap and failure isolation.\n */\n readonly additionalHttpRoutes?: readonly AdapterHttpRoute[];\n}\n\n/**\n * One fixed, method-scoped route owned by an adapter. Unlike `mountPath` it\n * registers no wildcard and matches exactly the path given.\n */\nexport interface AdapterHttpRoute {\n readonly method: 'GET' | 'POST';\n /** Absolute gateway path, e.g. '/.well-known/agent-card.json' */\n readonly path: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n}\n\nexport function isHttpProtocolAdapter(adapter: ProtocolAdapter): adapter is HttpProtocolAdapter {\n return typeof (adapter as HttpProtocolAdapter).handleHttp === 'function';\n}\n"]}