@devlab.group/agent-commerce 2.6.0 → 2.7.1

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 (129) hide show
  1. package/README.md +17 -12
  2. package/dist/ap2.d.ts +1 -1
  3. package/dist/ap2.js +5 -5
  4. package/dist/{chunk-M6MQ3FYS.js → chunk-5AO5N2XY.js} +11 -5
  5. package/dist/chunk-5AO5N2XY.js.map +1 -0
  6. package/dist/{chunk-DRLBML7Z.js → chunk-5VW32JPV.js} +191 -78
  7. package/dist/chunk-5VW32JPV.js.map +1 -0
  8. package/dist/{chunk-ES3V6ECS.js → chunk-77HLISG4.js} +3 -2
  9. package/dist/chunk-77HLISG4.js.map +1 -0
  10. package/dist/{chunk-5ZYXBCDX.js → chunk-D7FPSGUQ.js} +25 -4
  11. package/dist/chunk-D7FPSGUQ.js.map +1 -0
  12. package/dist/{chunk-G3EYYHKF.js → chunk-DJRWYDKJ.js} +3 -3
  13. package/dist/{chunk-G3EYYHKF.js.map → chunk-DJRWYDKJ.js.map} +1 -1
  14. package/dist/chunk-IGXQMAKM.js +8 -0
  15. package/dist/{chunk-M6BSXXTF.js.map → chunk-IGXQMAKM.js.map} +1 -1
  16. package/dist/chunk-IWXVQYG5.js +6 -0
  17. package/dist/chunk-IWXVQYG5.js.map +1 -0
  18. package/dist/{chunk-M6WW6QIT.js → chunk-WDD2ZUR3.js} +5 -3
  19. package/dist/chunk-WDD2ZUR3.js.map +1 -0
  20. package/dist/{chunk-M52FBNJX.js → chunk-YHNTTMED.js} +6 -4
  21. package/dist/chunk-YHNTTMED.js.map +1 -0
  22. package/dist/cli/{ap2-2YMYA2H6.js → ap2-NTYL7H4I.js} +10 -11
  23. package/dist/cli/ap2-NTYL7H4I.js.map +1 -0
  24. package/dist/cli/chunk-2M2RF3CT.js +8 -0
  25. package/dist/cli/{chunk-4KLYFXMW.js.map → chunk-2M2RF3CT.js.map} +1 -1
  26. package/dist/cli/{chunk-5K4XEAZV.js → chunk-3IEXJ7I3.js} +25 -4
  27. package/dist/cli/chunk-3IEXJ7I3.js.map +1 -0
  28. package/dist/cli/{chunk-VJH6RYRK.js → chunk-3NVJAQRO.js} +3 -3
  29. package/dist/cli/{chunk-VJH6RYRK.js.map → chunk-3NVJAQRO.js.map} +1 -1
  30. package/dist/cli/{chunk-GET3CZGR.js → chunk-55AI6CLW.js} +6 -4
  31. package/dist/cli/chunk-55AI6CLW.js.map +1 -0
  32. package/dist/cli/{chunk-3NOMLMJW.js → chunk-66NTYSXI.js} +3 -3
  33. package/dist/cli/{chunk-3NOMLMJW.js.map → chunk-66NTYSXI.js.map} +1 -1
  34. package/dist/cli/{chunk-VJ4EO4LE.js → chunk-6EBDOH37.js} +3 -3
  35. package/dist/cli/{chunk-VJ4EO4LE.js.map → chunk-6EBDOH37.js.map} +1 -1
  36. package/dist/cli/{chunk-NSYSMDQN.js → chunk-A42BCWZ2.js} +57 -29
  37. package/dist/cli/chunk-A42BCWZ2.js.map +1 -0
  38. package/dist/cli/chunk-APC5BTQM.js +6 -0
  39. package/dist/cli/chunk-APC5BTQM.js.map +1 -0
  40. package/dist/cli/{chunk-SYQLJXIU.js → chunk-C5YISPT6.js} +3 -3
  41. package/dist/cli/chunk-C5YISPT6.js.map +1 -0
  42. package/dist/cli/chunk-DKWO6LLX.js +34 -0
  43. package/dist/cli/chunk-DKWO6LLX.js.map +1 -0
  44. package/dist/cli/{chunk-YOF7IK4V.js → chunk-EVCIEKHN.js} +193 -80
  45. package/dist/cli/chunk-EVCIEKHN.js.map +1 -0
  46. package/dist/cli/{chunk-YWG2ZN3L.js → chunk-FETTSOMT.js} +12 -6
  47. package/dist/cli/chunk-FETTSOMT.js.map +1 -0
  48. package/dist/cli/{chunk-SPAYKVUP.js → chunk-FL4HPCD4.js} +3 -2
  49. package/dist/cli/chunk-FL4HPCD4.js.map +1 -0
  50. package/dist/cli/{chunk-AZL7RPFU.js → chunk-GBBG66O6.js} +77 -16
  51. package/dist/cli/chunk-GBBG66O6.js.map +1 -0
  52. package/dist/cli/{chunk-3EQBCFZY.js → chunk-H7EBJ4I3.js} +3 -3
  53. package/dist/cli/{chunk-3EQBCFZY.js.map → chunk-H7EBJ4I3.js.map} +1 -1
  54. package/dist/cli/{chunk-DHFMIBPG.js → chunk-MBPOKPQM.js} +6 -6
  55. package/dist/cli/{chunk-DHFMIBPG.js.map → chunk-MBPOKPQM.js.map} +1 -1
  56. package/dist/cli/{chunk-PTL7SNOI.js → chunk-OETKXDGA.js} +467 -122
  57. package/dist/cli/chunk-OETKXDGA.js.map +1 -0
  58. package/dist/cli/{chunk-TFV3K6YS.js → chunk-VSSSU4AU.js} +3 -3
  59. package/dist/cli/{chunk-TFV3K6YS.js.map → chunk-VSSSU4AU.js.map} +1 -1
  60. package/dist/cli/config-ODN4IEMZ.js +13 -0
  61. package/dist/cli/{config-3K65QJ22.js.map → config-ODN4IEMZ.js.map} +1 -1
  62. package/dist/cli/index.js +51 -37
  63. package/dist/cli/index.js.map +1 -1
  64. package/dist/cli/{mcp-6F64A7KE.js → mcp-V27OKTOV.js} +7 -7
  65. package/dist/cli/{mcp-6F64A7KE.js.map → mcp-V27OKTOV.js.map} +1 -1
  66. package/dist/cli/payment-providers-SUATT75K.js +6 -0
  67. package/dist/cli/{payment-providers-2ITS6KNR.js.map → payment-providers-SUATT75K.js.map} +1 -1
  68. package/dist/cli/{provider-5BGG5YKQ.js → provider-C3QDAXMR.js} +9 -9
  69. package/dist/cli/{provider-5BGG5YKQ.js.map → provider-C3QDAXMR.js.map} +1 -1
  70. package/dist/cli/receipts-ZS3VZ2D4.js +9 -0
  71. package/dist/cli/{receipts-I4IIE7U6.js.map → receipts-ZS3VZ2D4.js.map} +1 -1
  72. package/dist/cli/reconcile-GS25MQ42.js +4 -0
  73. package/dist/cli/{reconcile-55WNCSFC.js.map → reconcile-GS25MQ42.js.map} +1 -1
  74. package/dist/cli/{run-2P6ZGFUE.js → run-WYFZUO5D.js} +142 -46
  75. package/dist/cli/run-WYFZUO5D.js.map +1 -0
  76. package/dist/cli/{svm-KDSPDFJG.js → svm-NBZY7H6W.js} +9 -6
  77. package/dist/cli/svm-NBZY7H6W.js.map +1 -0
  78. package/dist/cli/{x402-4LPIIELI.js → x402-UGLZ3LA7.js} +11 -10
  79. package/dist/cli/x402-UGLZ3LA7.js.map +1 -0
  80. package/dist/{guardrails-CX_jYXvZ.d.ts → guardrails-CeyLS1ou.d.ts} +2 -2
  81. package/dist/index.d.ts +23 -13
  82. package/dist/index.js +708 -181
  83. package/dist/index.js.map +1 -1
  84. package/dist/mcp.d.ts +2 -2
  85. package/dist/mcp.js +4 -4
  86. package/dist/mpp.js +5 -5
  87. package/dist/{protocol-adapter-1WbtM3xG.d.ts → protocol-adapter-DdFL5LBU.d.ts} +12 -2
  88. package/dist/{runtime-B-kARa2f.d.ts → runtime-BmaSp2Ce.d.ts} +31 -3
  89. package/dist/{store-kIIMpUA-.d.ts → store-DQwbKhnc.d.ts} +25 -8
  90. package/dist/{svm-KNC3PHMS.js → svm-4HR5OEP7.js} +9 -6
  91. package/dist/svm-4HR5OEP7.js.map +1 -0
  92. package/dist/testing.d.ts +1 -1
  93. package/dist/testing.js +156 -2
  94. package/dist/testing.js.map +1 -1
  95. package/dist/{transaction-Dv0UFGg5.d.ts → transaction-BXXJltZ-.d.ts} +1 -1
  96. package/dist/x402.d.ts +7 -2
  97. package/dist/x402.js +7 -6
  98. package/dist/x402.js.map +1 -1
  99. package/package.json +13 -29
  100. package/dist/chunk-5ZYXBCDX.js.map +0 -1
  101. package/dist/chunk-DRLBML7Z.js.map +0 -1
  102. package/dist/chunk-ES3V6ECS.js.map +0 -1
  103. package/dist/chunk-M52FBNJX.js.map +0 -1
  104. package/dist/chunk-M6BSXXTF.js +0 -8
  105. package/dist/chunk-M6MQ3FYS.js.map +0 -1
  106. package/dist/chunk-M6WW6QIT.js.map +0 -1
  107. package/dist/cli/ap2-2YMYA2H6.js.map +0 -1
  108. package/dist/cli/chunk-4KLYFXMW.js +0 -8
  109. package/dist/cli/chunk-5K4XEAZV.js.map +0 -1
  110. package/dist/cli/chunk-6R6WJ4FD.js +0 -18
  111. package/dist/cli/chunk-6R6WJ4FD.js.map +0 -1
  112. package/dist/cli/chunk-AZL7RPFU.js.map +0 -1
  113. package/dist/cli/chunk-FHCFR2GS.js +0 -17
  114. package/dist/cli/chunk-FHCFR2GS.js.map +0 -1
  115. package/dist/cli/chunk-GET3CZGR.js.map +0 -1
  116. package/dist/cli/chunk-NSYSMDQN.js.map +0 -1
  117. package/dist/cli/chunk-PTL7SNOI.js.map +0 -1
  118. package/dist/cli/chunk-SPAYKVUP.js.map +0 -1
  119. package/dist/cli/chunk-SYQLJXIU.js.map +0 -1
  120. package/dist/cli/chunk-YOF7IK4V.js.map +0 -1
  121. package/dist/cli/chunk-YWG2ZN3L.js.map +0 -1
  122. package/dist/cli/config-3K65QJ22.js +0 -12
  123. package/dist/cli/payment-providers-2ITS6KNR.js +0 -6
  124. package/dist/cli/receipts-I4IIE7U6.js +0 -8
  125. package/dist/cli/reconcile-55WNCSFC.js +0 -4
  126. package/dist/cli/run-2P6ZGFUE.js.map +0 -1
  127. package/dist/cli/svm-KDSPDFJG.js.map +0 -1
  128. package/dist/cli/x402-4LPIIELI.js.map +0 -1
  129. package/dist/svm-KNC3PHMS.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,12 +1,13 @@
1
- import { openSqliteDatabase, AP2_SPEC_VERSION, AP2_MODES, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_JWK_MEMBERS, AP2_KEY_TYPE, AP2_SIGNING_ALGORITHM, AP2_JWK_CURVE, AP2_JWK_COORDINATE_BYTES, AP2_MAX_CLOCK_SKEW_SECONDS } from './chunk-G3EYYHKF.js';
2
- import { readCappedBody, createBearerCheck, MCP_TOOL_NAME_PATTERN, settlementResponse, joinUrl, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-ES3V6ECS.js';
1
+ import { openSqliteDatabase, AP2_SPEC_VERSION, AP2_MODES, AP2_DEFAULT_CLOCK_SKEW_SECONDS, AP2_JWK_MEMBERS, AP2_KEY_TYPE, AP2_SIGNING_ALGORITHM, AP2_JWK_CURVE, AP2_JWK_COORDINATE_BYTES, AP2_MAX_CLOCK_SKEW_SECONDS } from './chunk-DJRWYDKJ.js';
2
+ import { readCappedBody, createBearerCheck, MCP_TOOL_NAME_PATTERN, settlementResponse, joinUrl, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-77HLISG4.js';
3
3
  import { MPP_DEFAULT_NETWORK, isMppNetwork, MPP_NETWORKS, MPP_DEFAULT_PAYMENT_FLOW, MPP_MIN_CHALLENGE_SECRET_LENGTH, MPP_PROFILE } from './chunk-6Z2H53CG.js';
4
- import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-5ZYXBCDX.js';
5
- import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, resolveX402Deployment, resolveDeploymentMode, requireX402Network, resolveX402Option, isEvmAddress, isEvmZeroAddress, SETTLE_AFTER_BACKEND_METADATA_KEY, x402OfferName, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, canonicalJson } from './chunk-M6MQ3FYS.js';
6
- import { PACKAGE_VERSION } from './chunk-M6BSXXTF.js';
7
- import { hasMethodGroup } from './chunk-M6WW6QIT.js';
8
- import { RESERVED_INPUT_FIELDS, PROTOCOL_NAMES, PAYMENT_METHOD_NAMES, PAYMENT_HEADER, AUTHORIZATION_HEADER, CommerceError, systemClock, NOOP_LOGGER, transactionState, DEFAULT_BACKEND_TIMEOUT_MS, isCommerceError, describeError, isHttpProtocolAdapter, toLogInfo, toCommerceError, extractReservedInputFields, parseAuthorizationHeader, toPaymentRequiredEnvelope, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, toErrorEnvelope, DELIVERY_SUMMARY_META_KEY, toDeliverySummary, PAYMENT_INPUT_FIELD, AUTHORIZATION_INPUT_FIELD, parseAuthorizationSubmission, RECONCILIATION_METADATA_KEY, TRANSACTION_STATES, redactedErrorText } from './chunk-M52FBNJX.js';
9
- export { AUTHORIZATION_HEADER, AUTHORIZATION_INPUT_FIELD, COMMERCE_ERROR_CODES, COMMERCE_ERROR_HTTP_STATUS, COMMERCE_EVENT_TYPES, CommerceError, DEFAULT_BACKEND_TIMEOUT_MS, DELIVERY_SUMMARY_META_KEY, MAX_AUTHORIZATION_HEADER_BYTES, NOOP_LOGGER, PAYMENT_HEADER, PAYMENT_INPUT_FIELD, PAYMENT_METHOD_NAMES, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PROTOCOL_NAMES, RECONCILIATION_METADATA_KEY, RESERVED_INPUT_FIELDS, RETRYABLE_ERROR_CODES, TRANSACTION_STATES, extractReservedInputFields, isCommerceError, isHttpProtocolAdapter, isPaymentRequiredEnvelope, parseAuthorizationHeader, parseAuthorizationSubmission, systemClock, toCommerceError, toDeliverySummary, toErrorEnvelope, toPaymentRequiredEnvelope, transactionState } from './chunk-M52FBNJX.js';
4
+ import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-D7FPSGUQ.js';
5
+ import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, resolveX402Deployment, resolveDeploymentMode, requireX402Network, resolveX402Option, isEvmAddress, isEvmZeroAddress, SETTLE_AFTER_BACKEND_METADATA_KEY, x402OfferName, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, canonicalJson } from './chunk-5AO5N2XY.js';
6
+ import { PACKAGE_VERSION } from './chunk-IGXQMAKM.js';
7
+ import { PAYMENT_KEY_ENDPOINT_PREFIX } from './chunk-IWXVQYG5.js';
8
+ import { hasMethodGroup } from './chunk-WDD2ZUR3.js';
9
+ import { RESERVED_INPUT_FIELDS, PROTOCOL_NAMES, PAYMENT_METHOD_NAMES, PAYMENT_HEADER, AUTHORIZATION_HEADER, CommerceError, systemClock, NOOP_LOGGER, transactionState, DEFAULT_BACKEND_TIMEOUT_MS, isCommerceError, describeError, isHttpProtocolAdapter, toLogInfo, toCommerceError, extractReservedInputFields, parseAuthorizationHeader, toPaymentRequiredEnvelope, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, toErrorEnvelope, DELIVERY_SUMMARY_META_KEY, toDeliverySummary, PAYMENT_INPUT_FIELD, AUTHORIZATION_INPUT_FIELD, parseAuthorizationSubmission, RECONCILIATION_METADATA_KEY, TRANSACTION_STATES, redactedErrorText } from './chunk-YHNTTMED.js';
10
+ export { AUTHORIZATION_HEADER, AUTHORIZATION_INPUT_FIELD, COMMERCE_ERROR_CODES, COMMERCE_ERROR_HTTP_STATUS, COMMERCE_EVENT_TYPES, CommerceError, DEFAULT_BACKEND_TIMEOUT_MS, DELIVERY_SUMMARY_META_KEY, MAX_AUTHORIZATION_HEADER_BYTES, NOOP_LOGGER, PAYMENT_HEADER, PAYMENT_INPUT_FIELD, PAYMENT_METHOD_NAMES, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PROTOCOL_NAMES, RECONCILIATION_METADATA_KEY, RESERVED_INPUT_FIELDS, RETRYABLE_ERROR_CODES, TRANSACTION_STATES, extractReservedInputFields, isCommerceError, isHttpProtocolAdapter, isPaymentRequiredEnvelope, parseAuthorizationHeader, parseAuthorizationSubmission, systemClock, toCommerceError, toDeliverySummary, toErrorEnvelope, toPaymentRequiredEnvelope, transactionState } from './chunk-YHNTTMED.js';
10
11
  import { isRecord } from './chunk-2CJNA7MS.js';
11
12
  import { promises, accessSync, constants, existsSync } from 'fs';
12
13
  import * as path from 'path';
@@ -853,8 +854,8 @@ var MerchantSchema = z.object({
853
854
  var ServerSchema = z.object({
854
855
  port: NumberOrString,
855
856
  host: z.string().min(1),
856
- // Required for /api/receipts, /api/events and /api/payment-attempts;
857
- // these routes return 404 when the token is unset
857
+ // Operator routes (/api/receipts, /api/events, /api/payment-attempts,
858
+ // /api/transactions and the resolve route) return 404 without this token
858
859
  adminToken: z.string().min(1).optional(),
859
860
  // Browser origins allowed to call the gateway; none by default. A request
860
861
  // with any other `Origin` gets 403 on every route. Entries match the
@@ -887,7 +888,10 @@ var RESERVED_GATEWAY_PATHS = [
887
888
  "/api/resources/:id/invoke",
888
889
  "/api/receipts",
889
890
  "/api/events",
890
- "/api/payment-attempts"
891
+ "/api/payment-attempts",
892
+ "/api/payment-attempts/:id/resolve",
893
+ "/api/transactions",
894
+ "/api/transactions/:id"
891
895
  ];
892
896
  var MountPathSchema = z.string().min(1).refine((value) => value.startsWith("/"), {
893
897
  message: 'must start with "/" - it is an absolute gateway path, e.g. "/mcp".'
@@ -910,7 +914,7 @@ var AcpIdempotencySchema = z.object({
910
914
  retentionHours: NumberOrString.optional(),
911
915
  merchantIdempotent: z.boolean().optional()
912
916
  }).strict();
913
- var AcpCheckoutSchema = z.object({ operations: z.record(z.string().min(1)) }).strict();
917
+ var AcpCheckoutSchema = z.object({ operations: z.record(z.string(), z.string().min(1)) }).strict();
914
918
  var AcpDiscoverySchema = z.object({
915
919
  documentationUrl: z.string().min(1).optional(),
916
920
  supportedCurrencies: z.array(z.string().min(1)).optional(),
@@ -991,14 +995,20 @@ var ResourceEntrySchema = z.object({
991
995
  paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),
992
996
  // This resource's own x402 offers, in place of `payments.x402` options
993
997
  x402: z.object({ accepts: z.array(X402OptionSchema) }).strict().optional(),
994
- authorization: z.object({ required: z.array(z.string().min(1)).min(1) }).strict().optional()
998
+ authorization: z.object({ required: z.array(z.string().min(1)).min(1) }).strict().optional(),
999
+ idempotency: z.object({
1000
+ merchantKey: BooleanOrString.optional(),
1001
+ redelivery: z.object({
1002
+ retentionHours: NumberOrString.optional(),
1003
+ required: BooleanOrString.optional()
1004
+ }).strict().optional()
1005
+ }).strict().optional()
995
1006
  }).strict();
996
1007
  var ResourcesMapSchema = z.record(z.string().min(1), ResourceEntrySchema);
997
1008
  var FacilitatorAuthSchema = z.discriminatedUnion("type", [
998
1009
  z.object({ type: z.literal("none") }).strict(),
999
1010
  z.object({ type: z.literal("bearer"), token: z.string().min(1) }).strict(),
1000
- // Coinbase Developer Platform. Needs the optional peer `@coinbase/x402`,
1001
- // which signs a fresh JWT per request.
1011
+ // Coinbase Developer Platform: the gateway signs a fresh JWT per request
1002
1012
  z.object({
1003
1013
  type: z.literal("cdp"),
1004
1014
  apiKeyId: z.string().min(1),
@@ -1109,6 +1119,333 @@ var RawConfigSchema = z.object({
1109
1119
  payments: PaymentsSchema,
1110
1120
  authorization: AuthorizationSchema.optional()
1111
1121
  }).strict();
1122
+ function createFlow(request, transactionId) {
1123
+ return { request, transactionId, persistenceFailures: [], journaled: false, chargeRisk: false };
1124
+ }
1125
+ function failuresOf(flow) {
1126
+ return flow.persistenceFailures.length > 0 ? { persistenceFailures: [...flow.persistenceFailures] } : {};
1127
+ }
1128
+ function sha256(text) {
1129
+ return `sha256:${createHash("sha256").update(text, "utf8").digest("hex")}`;
1130
+ }
1131
+ function inputDigest(input) {
1132
+ const json = canonicalJson(input);
1133
+ return json !== void 0 ? sha256(json) : void 0;
1134
+ }
1135
+ function configDigest(resource, requirement) {
1136
+ const terms = {
1137
+ resourceId: resource.id,
1138
+ pricing: resource.pricing,
1139
+ paymentMethods: resource.paymentMethods,
1140
+ authorization: resource.authorization?.required ?? [],
1141
+ requirement: {
1142
+ provider: requirement.provider,
1143
+ amount: requirement.amount,
1144
+ currency: requirement.currency,
1145
+ destination: requirement.destination ?? null,
1146
+ network: requirement.network ?? null,
1147
+ asset: requirement.asset ?? null,
1148
+ settleAfterBackend: requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true
1149
+ }
1150
+ };
1151
+ return sha256(canonicalJson(terms) ?? JSON.stringify(terms));
1152
+ }
1153
+ function newTransaction(flow, resource, requirement, verification, digest, authorization) {
1154
+ const raw = verification.metadata?.[RECONCILIATION_METADATA_KEY];
1155
+ const locator = isRecord(raw) ? raw : void 0;
1156
+ const expiresAt = typeof locator?.["expiresAt"] === "string" ? locator["expiresAt"] : void 0;
1157
+ const network = verification.network ?? requirement.network;
1158
+ const asset = verification.asset ?? requirement.asset;
1159
+ return {
1160
+ id: flow.transactionId,
1161
+ protocol: flow.request.protocol,
1162
+ ...network !== void 0 ? { network } : {},
1163
+ ...asset !== void 0 ? { asset } : {},
1164
+ ...locator !== void 0 ? { locator } : {},
1165
+ ...expiresAt !== void 0 ? { expiresAt } : {},
1166
+ ...authorization !== void 0 ? { authorization } : {},
1167
+ ...digest !== void 0 ? { inputDigest: digest } : {},
1168
+ configDigest: configDigest(resource, requirement)
1169
+ };
1170
+ }
1171
+ function sha256Hex(text) {
1172
+ return createHash("sha256").update(text).digest("hex");
1173
+ }
1174
+ function paidOperationKey(operation) {
1175
+ const { deployment, resourceId, replayKey, inputDigest: digest, clientKey, payer } = operation;
1176
+ if (digest === void 0) return void 0;
1177
+ const identity = clientKey && payer ? `retry:${sha256Hex(clientKey)}:${payer}` : replayKey;
1178
+ return sha256Hex(JSON.stringify(["paid-operation", deployment, resourceId, identity, digest]));
1179
+ }
1180
+
1181
+ // src/core/execution/pipeline/retry.ts
1182
+ var MAX_REDELIVERY_RETENTION_HOURS = 8760;
1183
+ var IN_FLIGHT_RETRY_AFTER_SECONDS = 1;
1184
+ var REFUSALS = {
1185
+ conflict: {
1186
+ reason: "payment_identifier_conflict",
1187
+ message: "This payment identifier belongs to another request"
1188
+ },
1189
+ "in-flight": {
1190
+ reason: "payment_identifier_in_flight",
1191
+ message: "A request with this payment identifier is in progress"
1192
+ },
1193
+ unresolved: {
1194
+ reason: "payment_identifier_unresolved",
1195
+ message: "The earlier request with this payment identifier may have been charged and has no stored response"
1196
+ }
1197
+ };
1198
+ function assertRetrySupport(resource, store, deployment, requestId) {
1199
+ const { merchantKey, redelivery } = resource.idempotency ?? {};
1200
+ if (merchantKey !== true && redelivery === void 0) return void 0;
1201
+ const invalid3 = (message) => new CommerceError("CONFIG_INVALID", message, {
1202
+ ...requestId !== void 0 ? { requestId } : {},
1203
+ resourceId: resource.id
1204
+ });
1205
+ const unsupported2 = (needs) => invalid3(`Resource "${resource.id}" sets idempotency, which requires ${needs}`);
1206
+ const hours = redelivery?.retentionHours;
1207
+ if (hours !== void 0 && !(Number.isInteger(hours) && hours >= 1 && hours <= MAX_REDELIVERY_RETENTION_HOURS)) {
1208
+ throw invalid3(
1209
+ `Resource "${resource.id}" sets idempotency.redelivery.retentionHours outside 1 to ${MAX_REDELIVERY_RETENTION_HOURS}`
1210
+ );
1211
+ }
1212
+ if (deployment === void 0) throw unsupported2("the pipeline's deployment option");
1213
+ if (redelivery === void 0) return { deployment };
1214
+ if (!hasMethodGroup(store, "idempotency_claims") || !hasMethodGroup(store, "response_redelivery")) {
1215
+ throw unsupported2("a store with idempotency claims and getIdempotencyKey");
1216
+ }
1217
+ return { deployment, store };
1218
+ }
1219
+ function createRetryGate(ctx) {
1220
+ const { options, safeEmit, safePersist, buildEvent } = ctx;
1221
+ async function open(flow, resource, provider, validInput, support, pipelineStart) {
1222
+ const { request } = flow;
1223
+ const retentionHours = resource.idempotency?.redelivery?.retentionHours;
1224
+ const { payment } = request;
1225
+ if (support?.store === void 0 || retentionHours === void 0 || payment === void 0) {
1226
+ return void 0;
1227
+ }
1228
+ const clientKey = request.retryKey ?? await providerRetryKey(flow, resource, provider, payment);
1229
+ if (clientKey === void 0) return void 0;
1230
+ const fingerprint = inputDigest(validInput);
1231
+ if (fingerprint === void 0) {
1232
+ throw await rejected(
1233
+ flow,
1234
+ resource,
1235
+ provider,
1236
+ new CommerceError(
1237
+ "INPUT_INVALID",
1238
+ `Input for resource "${resource.id}" is not I-JSON, so a retry key cannot identify it`,
1239
+ { requestId: request.requestId, resourceId: resource.id }
1240
+ )
1241
+ );
1242
+ }
1243
+ const { store } = support;
1244
+ const { authorization } = request;
1245
+ const ticket = {
1246
+ kind: "retry",
1247
+ store,
1248
+ scope: {
1249
+ deployment: support.deployment,
1250
+ endpoint: `${PAYMENT_KEY_ENDPOINT_PREFIX}${resource.id}`,
1251
+ key: sha256Hex(clientKey)
1252
+ },
1253
+ fingerprint,
1254
+ expiresAt: new Date(
1255
+ options.clock.now().getTime() + retentionHours * 60 * 60 * 1e3
1256
+ ).toISOString(),
1257
+ clientKey,
1258
+ proofDigest: sha256Hex(`${payment.method}:${payment.payload}`),
1259
+ ...authorization !== void 0 ? { authorizationDigest: sha256Hex(`${authorization.method}:${authorization.payload}`) } : {}
1260
+ };
1261
+ const existing = await reading(
1262
+ flow,
1263
+ resource,
1264
+ () => store.getIdempotencyKey(ticket.scope, fingerprint)
1265
+ );
1266
+ if (existing?.kind === "in-flight" || existing?.kind === "unresolved") {
1267
+ if (existing.owner !== ticket.proofDigest) return ticket;
1268
+ throw await refusal(flow, resource, provider, existing.kind);
1269
+ }
1270
+ if (existing?.kind !== "replay") return ticket;
1271
+ const stored = readStoredDelivery(existing.body);
1272
+ return stored?.proofDigest === ticket.proofDigest && authorizes(resource, stored, ticket) ? redeliver(flow, resource, provider, existing.status, stored, pipelineStart) : ticket;
1273
+ }
1274
+ async function claim(flow, resource, provider, ticket, verification, pipelineStart) {
1275
+ const { scope, fingerprint, expiresAt, proofDigest } = ticket;
1276
+ const claimed = await reading(
1277
+ flow,
1278
+ resource,
1279
+ () => ticket.store.claimIdempotencyKey(scope, fingerprint, expiresAt, proofDigest)
1280
+ );
1281
+ const replay = await acceptOrRefuse(flow, resource, provider, claimed);
1282
+ if (replay === void 0) return void 0;
1283
+ const stored = await storedDelivery(flow, resource, provider, replay);
1284
+ const samePayer = verification.payer !== void 0 && verification.payer === stored.payer;
1285
+ if (!samePayer || !authorizes(resource, stored, ticket)) {
1286
+ throw await refusal(flow, resource, provider, "conflict");
1287
+ }
1288
+ return redeliver(flow, resource, provider, replay.status, stored, pipelineStart);
1289
+ }
1290
+ async function finishDelivered(flow, ticket, verification, response, receipt) {
1291
+ const contentType = response.headers["content-type"];
1292
+ const stored = {
1293
+ proofDigest: ticket.proofDigest,
1294
+ ...ticket.authorizationDigest !== void 0 ? { authorizationDigest: ticket.authorizationDigest } : {},
1295
+ // Record the verified buyer; settlement may name a fee payer instead
1296
+ ...verification.payer !== void 0 ? { payer: verification.payer } : {},
1297
+ // Keep only Content-Type; never persist a backend Set-Cookie header
1298
+ ...contentType !== void 0 ? { contentType } : {},
1299
+ body: response.body ?? null,
1300
+ receiptId: receipt.id
1301
+ };
1302
+ const receiptSaved = !flow.persistenceFailures.includes("receipt");
1303
+ const update = { kind: "completed", status: response.status, body: stored };
1304
+ if (receiptSaved && await write(flow, ticket, update)) return;
1305
+ if (!flow.persistenceFailures.includes("response")) flow.persistenceFailures.push("response");
1306
+ await write(flow, ticket, { kind: "unresolved" });
1307
+ }
1308
+ async function finishFailed(flow, ticket) {
1309
+ await write(flow, ticket, { kind: flow.chargeRisk ? "unresolved" : "released" });
1310
+ }
1311
+ function write(flow, ticket, update) {
1312
+ return safePersist(
1313
+ flow,
1314
+ () => ticket.store.updateIdempotencyKey(ticket.scope, update),
1315
+ `updateIdempotencyKey(${update.kind})`,
1316
+ "response"
1317
+ );
1318
+ }
1319
+ async function reading(flow, resource, read) {
1320
+ try {
1321
+ return await read();
1322
+ } catch (error) {
1323
+ throw new CommerceError("STORAGE_ERROR", "Payment retry state could not be read", {
1324
+ requestId: flow.request.requestId,
1325
+ resourceId: resource.id,
1326
+ cause: error
1327
+ });
1328
+ }
1329
+ }
1330
+ async function acceptOrRefuse(flow, resource, provider, claimed) {
1331
+ if (claimed === void 0 || claimed.kind === "reserved") return void 0;
1332
+ if (claimed.kind === "replay") return claimed;
1333
+ throw await refusal(flow, resource, provider, claimed.kind);
1334
+ }
1335
+ async function storedDelivery(flow, resource, provider, replay) {
1336
+ const stored = readStoredDelivery(replay.body);
1337
+ if (stored === void 0) throw await refusal(flow, resource, provider, "unresolved");
1338
+ return stored;
1339
+ }
1340
+ function refusal(flow, resource, provider, kind) {
1341
+ const { reason, message } = REFUSALS[kind];
1342
+ const inFlight = kind === "in-flight";
1343
+ return rejected(
1344
+ flow,
1345
+ resource,
1346
+ provider,
1347
+ new CommerceError("PAYMENT_REPLAYED", message, {
1348
+ requestId: flow.request.requestId,
1349
+ resourceId: resource.id,
1350
+ details: {
1351
+ reason,
1352
+ ...inFlight ? { retryAfterSeconds: IN_FLIGHT_RETRY_AFTER_SECONDS } : {}
1353
+ },
1354
+ ...inFlight ? { retryable: true } : {}
1355
+ })
1356
+ );
1357
+ }
1358
+ async function rejected(flow, resource, provider, error) {
1359
+ const reason = error.details?.["reason"];
1360
+ await safeEmit(
1361
+ buildEvent(flow, {
1362
+ type: "payment.rejected",
1363
+ resourceId: resource.id,
1364
+ adapter: flow.request.protocol,
1365
+ paymentProvider: provider.name,
1366
+ status: "error",
1367
+ data: { reason: typeof reason === "string" ? reason : error.code }
1368
+ })
1369
+ );
1370
+ if (error.requestId !== void 0) return error;
1371
+ return new CommerceError(error.code, error.message, {
1372
+ requestId: flow.request.requestId,
1373
+ resourceId: error.resourceId ?? resource.id,
1374
+ httpStatus: error.httpStatus,
1375
+ retryable: error.retryable,
1376
+ ...error.details !== void 0 ? { details: error.details } : {},
1377
+ ...error.cause !== void 0 ? { cause: error.cause } : {}
1378
+ });
1379
+ }
1380
+ async function providerRetryKey(flow, resource, provider, submission) {
1381
+ try {
1382
+ return provider.retryKey?.({ resource, submission });
1383
+ } catch (error) {
1384
+ const typed = isCommerceError(error) ? error : new CommerceError("PAYMENT_PROVIDER_UNAVAILABLE", "Payment provider is unavailable", {
1385
+ cause: error
1386
+ });
1387
+ throw await rejected(flow, resource, provider, typed);
1388
+ }
1389
+ }
1390
+ async function redeliver(flow, resource, provider, status, stored, pipelineStart) {
1391
+ const { request } = flow;
1392
+ const receipt = await reading(flow, resource, () => options.store.getReceipt(stored.receiptId));
1393
+ if (receipt?.payment === void 0) {
1394
+ throw await refusal(flow, resource, provider, "unresolved");
1395
+ }
1396
+ const durationMs = Math.round(options.clock.monotonicMs() - pipelineStart);
1397
+ const original = receipt.transactionId;
1398
+ await safeEmit(
1399
+ buildEvent(flow, {
1400
+ type: "resource.delivered",
1401
+ resourceId: resource.id,
1402
+ adapter: request.protocol,
1403
+ status: "ok",
1404
+ durationMs,
1405
+ data: {
1406
+ redelivered: true,
1407
+ ...original !== void 0 ? { originalTransactionId: original } : {}
1408
+ }
1409
+ })
1410
+ );
1411
+ return {
1412
+ kind: "delivered",
1413
+ requestId: request.requestId,
1414
+ transactionId: flow.transactionId,
1415
+ resourceId: resource.id,
1416
+ backendStatus: status,
1417
+ body: stored.body,
1418
+ headers: stored.contentType !== void 0 ? { "content-type": stored.contentType } : {},
1419
+ payment: receipt.payment,
1420
+ receipt,
1421
+ durationMs,
1422
+ redelivered: true
1423
+ };
1424
+ }
1425
+ return { open, claim, finishDelivered, finishFailed };
1426
+ }
1427
+ function authorizes(resource, stored, ticket) {
1428
+ if ((resource.authorization?.required.length ?? 0) === 0) return true;
1429
+ return stored.authorizationDigest !== void 0 && stored.authorizationDigest === ticket.authorizationDigest;
1430
+ }
1431
+ function readStoredDelivery(value) {
1432
+ if (!isRecord(value) || !Object.hasOwn(value, "body")) return void 0;
1433
+ const { proofDigest, authorizationDigest, payer, contentType, body, receiptId } = value;
1434
+ if (typeof proofDigest !== "string" || typeof receiptId !== "string") return void 0;
1435
+ if (authorizationDigest !== void 0 && typeof authorizationDigest !== "string") {
1436
+ return void 0;
1437
+ }
1438
+ if (payer !== void 0 && typeof payer !== "string") return void 0;
1439
+ if (contentType !== void 0 && typeof contentType !== "string") return void 0;
1440
+ return {
1441
+ proofDigest,
1442
+ ...authorizationDigest !== void 0 ? { authorizationDigest } : {},
1443
+ ...payer !== void 0 ? { payer } : {},
1444
+ ...contentType !== void 0 ? { contentType } : {},
1445
+ body,
1446
+ receiptId
1447
+ };
1448
+ }
1112
1449
 
1113
1450
  // src/core/execution/backend-request.ts
1114
1451
  var NEVER_FORWARDED_HEADER = /^(authorization|cookie|set-cookie|host|content-length|content-type|connection|keep-alive|te|trailer|transfer-encoding|upgrade|idempotency-key|proxy-.*)$/;
@@ -1456,56 +1793,6 @@ function safeStringify(value) {
1456
1793
  function isAbortError(error) {
1457
1794
  return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
1458
1795
  }
1459
- function createFlow(request, transactionId) {
1460
- return { request, transactionId, persistenceFailures: [], journaled: false };
1461
- }
1462
- function failuresOf(flow) {
1463
- return flow.persistenceFailures.length > 0 ? { persistenceFailures: [...flow.persistenceFailures] } : {};
1464
- }
1465
- function sha256(text) {
1466
- return `sha256:${createHash("sha256").update(text, "utf8").digest("hex")}`;
1467
- }
1468
- function inputDigest(input) {
1469
- const json = canonicalJson(input);
1470
- return json !== void 0 ? sha256(json) : void 0;
1471
- }
1472
- function configDigest(resource, requirement) {
1473
- const terms = {
1474
- resourceId: resource.id,
1475
- pricing: resource.pricing,
1476
- paymentMethods: resource.paymentMethods,
1477
- authorization: resource.authorization?.required ?? [],
1478
- requirement: {
1479
- provider: requirement.provider,
1480
- amount: requirement.amount,
1481
- currency: requirement.currency,
1482
- destination: requirement.destination ?? null,
1483
- network: requirement.network ?? null,
1484
- asset: requirement.asset ?? null,
1485
- settleAfterBackend: requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true
1486
- }
1487
- };
1488
- return sha256(canonicalJson(terms) ?? JSON.stringify(terms));
1489
- }
1490
- function newTransaction(flow, resource, requirement, verification, validInput, authorization) {
1491
- const raw = verification.metadata?.[RECONCILIATION_METADATA_KEY];
1492
- const locator = isRecord(raw) ? raw : void 0;
1493
- const expiresAt = typeof locator?.["expiresAt"] === "string" ? locator["expiresAt"] : void 0;
1494
- const network = verification.network ?? requirement.network;
1495
- const asset = verification.asset ?? requirement.asset;
1496
- const digest = inputDigest(validInput);
1497
- return {
1498
- id: flow.transactionId,
1499
- protocol: flow.request.protocol,
1500
- ...network !== void 0 ? { network } : {},
1501
- ...asset !== void 0 ? { asset } : {},
1502
- ...locator !== void 0 ? { locator } : {},
1503
- ...expiresAt !== void 0 ? { expiresAt } : {},
1504
- ...authorization !== void 0 ? { authorization } : {},
1505
- ...digest !== void 0 ? { inputDigest: digest } : {},
1506
- configDigest: configDigest(resource, requirement)
1507
- };
1508
- }
1509
1796
  var SUPPORTED_TYPES = /* @__PURE__ */ new Set([
1510
1797
  "object",
1511
1798
  "string",
@@ -1770,9 +2057,15 @@ function replayError(error, requirement) {
1770
2057
  }
1771
2058
 
1772
2059
  // src/core/execution/pipeline/admission.ts
1773
- function createPaymentAdmission(ctx, authorizeAndReserve) {
2060
+ function createPaymentAdmission(ctx, authorizeAndReserve, retryGate) {
1774
2061
  const { options, safeEmit, buildEvent } = ctx;
1775
- return async function admitPayment(flow, request, resource, pricing, validInput) {
2062
+ return async function admitPayment(flow, request, resource, pricing, validInput, pipelineStart) {
2063
+ const support = assertRetrySupport(
2064
+ resource,
2065
+ options.store,
2066
+ options.deployment,
2067
+ request.requestId
2068
+ );
1776
2069
  const provider = pickProvider(options.paymentProviders, resource.paymentMethods);
1777
2070
  if (!provider) {
1778
2071
  throw new CommerceError(
@@ -1790,6 +2083,15 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
1790
2083
  resource,
1791
2084
  request.requestId
1792
2085
  );
2086
+ const retry = await retryGate.open(
2087
+ flow,
2088
+ resource,
2089
+ provider,
2090
+ validInput,
2091
+ support,
2092
+ pipelineStart
2093
+ );
2094
+ if (retry?.kind === "delivered") return retry;
1793
2095
  let requirement;
1794
2096
  try {
1795
2097
  requirement = await provider.createRequirement({
@@ -1894,77 +2196,104 @@ function createPaymentAdmission(ctx, authorizeAndReserve) {
1894
2196
  });
1895
2197
  }
1896
2198
  const replayKey = verification.replayKey;
1897
- const hold = await authorizeAndReserve(
1898
- flow,
1899
- request,
1900
- resource,
1901
- authProviders,
1902
- requirement,
1903
- validInput
1904
- );
2199
+ const digest = retry?.fingerprint ?? inputDigest(validInput);
2200
+ if (retry !== void 0) {
2201
+ const stored = await retryGate.claim(
2202
+ flow,
2203
+ resource,
2204
+ provider,
2205
+ retry,
2206
+ verification,
2207
+ pipelineStart
2208
+ );
2209
+ if (stored !== void 0) return stored;
2210
+ }
1905
2211
  try {
1906
- const attempt = await options.store.reservePaymentAttempt({
1907
- requestId: request.requestId,
1908
- resourceId: resource.id,
1909
- provider: provider.name,
1910
- replayKey,
1911
- amount: verification.amount,
1912
- currency: verification.currency,
1913
- ...verification.payer !== void 0 ? { payer: verification.payer } : {},
1914
- ...verification.payee !== void 0 ? { payee: verification.payee } : {},
1915
- ...requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true ? { reclaimRejected: true } : {},
1916
- transaction: newTransaction(
1917
- flow,
1918
- resource,
1919
- requirement,
1920
- verification,
1921
- validInput,
1922
- hold !== void 0 ? { ...hold.record, reservationId: hold.reservationId } : void 0
1923
- )
1924
- });
1925
- flow.journaled = attempt.transactionId === flow.transactionId && options.store.recordTransactionStep !== void 0;
1926
- } catch (error) {
1927
- const mapped = toCommerceError(
1928
- error,
1929
- "STORAGE_ERROR",
1930
- "Payment attempt could not be recorded"
2212
+ const hold = await authorizeAndReserve(
2213
+ flow,
2214
+ request,
2215
+ resource,
2216
+ authProviders,
2217
+ requirement,
2218
+ validInput
1931
2219
  );
1932
- await hold?.finalize("release");
2220
+ try {
2221
+ const attempt = await options.store.reservePaymentAttempt({
2222
+ requestId: request.requestId,
2223
+ resourceId: resource.id,
2224
+ provider: provider.name,
2225
+ replayKey,
2226
+ amount: verification.amount,
2227
+ currency: verification.currency,
2228
+ ...verification.payer !== void 0 ? { payer: verification.payer } : {},
2229
+ ...verification.payee !== void 0 ? { payee: verification.payee } : {},
2230
+ ...requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true ? { reclaimRejected: true } : {},
2231
+ transaction: newTransaction(
2232
+ flow,
2233
+ resource,
2234
+ requirement,
2235
+ verification,
2236
+ digest,
2237
+ hold !== void 0 ? { ...hold.record, reservationId: hold.reservationId } : void 0
2238
+ )
2239
+ });
2240
+ flow.journaled = attempt.transactionId === flow.transactionId && options.store.recordTransactionStep !== void 0;
2241
+ } catch (error) {
2242
+ const mapped = toCommerceError(
2243
+ error,
2244
+ "STORAGE_ERROR",
2245
+ "Payment attempt could not be recorded"
2246
+ );
2247
+ await hold?.finalize("release");
2248
+ await safeEmit(
2249
+ buildEvent(flow, {
2250
+ type: "payment.rejected",
2251
+ resourceId: resource.id,
2252
+ adapter: request.protocol,
2253
+ paymentProvider: provider.name,
2254
+ status: "error",
2255
+ data: { reason: mapped.code }
2256
+ })
2257
+ );
2258
+ throw replayError(mapped, requirement);
2259
+ }
1933
2260
  await safeEmit(
1934
2261
  buildEvent(flow, {
1935
- type: "payment.rejected",
2262
+ type: "payment.verified",
1936
2263
  resourceId: resource.id,
1937
2264
  adapter: request.protocol,
1938
2265
  paymentProvider: provider.name,
1939
- status: "error",
1940
- data: { reason: mapped.code }
2266
+ status: "ok"
1941
2267
  })
1942
2268
  );
1943
- throw replayError(mapped, requirement);
1944
- }
1945
- await safeEmit(
1946
- buildEvent(flow, {
1947
- type: "payment.verified",
2269
+ const merchantKey = support !== void 0 && resource.idempotency?.merchantKey === true ? paidOperationKey({
2270
+ deployment: support.deployment,
1948
2271
  resourceId: resource.id,
1949
- adapter: request.protocol,
1950
- paymentProvider: provider.name,
1951
- status: "ok"
1952
- })
1953
- );
1954
- return {
1955
- kind: "admitted",
1956
- settleArgs: {
1957
- flow,
1958
- request,
1959
- resource,
1960
- provider,
1961
- requirement,
1962
- payment,
1963
- verification,
1964
2272
  replayKey,
1965
- hold
1966
- }
1967
- };
2273
+ inputDigest: digest,
2274
+ ...retry !== void 0 ? { clientKey: retry.clientKey } : {},
2275
+ ...verification.payer !== void 0 ? { payer: verification.payer } : {}
2276
+ }) : void 0;
2277
+ return {
2278
+ kind: "admitted",
2279
+ settleArgs: {
2280
+ flow,
2281
+ request,
2282
+ resource,
2283
+ provider,
2284
+ requirement,
2285
+ payment,
2286
+ verification,
2287
+ replayKey,
2288
+ hold,
2289
+ ...merchantKey !== void 0 ? { merchantKey } : {},
2290
+ ...retry !== void 0 ? { retry } : {}
2291
+ }
2292
+ };
2293
+ } catch (error) {
2294
+ if (retry !== void 0) await retryGate.finishFailed(flow, retry);
2295
+ throw error;
2296
+ }
1968
2297
  };
1969
2298
  async function refusalFor(verification, requirement, request, resource) {
1970
2299
  const ids = { requestId: request.requestId, resourceId: resource.id };
@@ -2090,6 +2419,7 @@ function createSettlement(ctx) {
2090
2419
  hold
2091
2420
  } = args;
2092
2421
  await recordStep(flow, { kind: "settling" });
2422
+ flow.chargeRisk = true;
2093
2423
  let settlement;
2094
2424
  try {
2095
2425
  settlement = await provider.settle({
@@ -2102,6 +2432,7 @@ function createSettlement(ctx) {
2102
2432
  } catch (error) {
2103
2433
  const notSubmitted = notSubmittedReason(error);
2104
2434
  if (notSubmitted !== void 0) {
2435
+ flow.chargeRisk = false;
2105
2436
  await finalizeHold(flow, hold, "release");
2106
2437
  await safePersist(
2107
2438
  flow,
@@ -2172,6 +2503,7 @@ function createSettlement(ctx) {
2172
2503
  });
2173
2504
  }
2174
2505
  if (settlement.status !== "settled") {
2506
+ flow.chargeRisk = false;
2175
2507
  await finalizeHold(flow, hold, "release");
2176
2508
  await safePersist(
2177
2509
  flow,
@@ -2293,7 +2625,8 @@ function createExecutionPipeline(options) {
2293
2625
  const ctx = createPipelineContext(options);
2294
2626
  const { safeEmit, safePersist, recordStep, buildEvent } = ctx;
2295
2627
  const { settle, abandonSettlement } = createSettlement(ctx);
2296
- const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx));
2628
+ const retryGate = createRetryGate(ctx);
2629
+ const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx), retryGate);
2297
2630
  async function execute(request) {
2298
2631
  const pipelineStart = options.clock.monotonicMs();
2299
2632
  const resource = options.resources.get(request.resourceId);
@@ -2357,12 +2690,22 @@ function createExecutionPipeline(options) {
2357
2690
  }
2358
2691
  let settleArgs;
2359
2692
  if (resource.pricing.type === "fixed") {
2360
- const admission = await admitPayment(flow, request, resource, resource.pricing, validInput);
2361
- if (admission.kind === "payment-required") return admission;
2693
+ const admission = await admitPayment(
2694
+ flow,
2695
+ request,
2696
+ resource,
2697
+ resource.pricing,
2698
+ validInput,
2699
+ pipelineStart
2700
+ );
2701
+ if (admission.kind !== "admitted") return admission;
2362
2702
  settleArgs = admission.settleArgs;
2363
2703
  }
2364
2704
  try {
2365
2705
  return await settleAndDeliver(flow, resource, validInput, settleArgs, pipelineStart);
2706
+ } catch (error) {
2707
+ if (settleArgs?.retry !== void 0) await retryGate.finishFailed(flow, settleArgs.retry);
2708
+ throw error;
2366
2709
  } finally {
2367
2710
  await recordStep(flow, { kind: "completed", ...failuresOf(flow) });
2368
2711
  }
@@ -2384,13 +2727,14 @@ function createExecutionPipeline(options) {
2384
2727
  deadlineAt: backendDeadline(options.clock.now(), resource)
2385
2728
  });
2386
2729
  const backendStart = options.clock.monotonicMs();
2730
+ const idempotencyKey = request.idempotencyKey ?? settleArgs?.merchantKey;
2387
2731
  let backendResponse;
2388
2732
  try {
2389
2733
  backendResponse = await options.backend.call(resource.handler, {
2390
2734
  requestId: request.requestId,
2391
2735
  resourceId: resource.id,
2392
2736
  input: validInput,
2393
- ...request.idempotencyKey !== void 0 ? { idempotencyKey: request.idempotencyKey } : {},
2737
+ ...idempotencyKey !== void 0 ? { idempotencyKey } : {},
2394
2738
  ...request.backendHeaders !== void 0 ? { backendHeaders: request.backendHeaders } : {}
2395
2739
  });
2396
2740
  } catch (error) {
@@ -2483,6 +2827,15 @@ function createExecutionPipeline(options) {
2483
2827
  transactionId: flow.transactionId
2484
2828
  };
2485
2829
  await saveReceipt(flow, receipt, "saveReceipt");
2830
+ if (settleArgs?.retry !== void 0) {
2831
+ await retryGate.finishDelivered(
2832
+ flow,
2833
+ settleArgs.retry,
2834
+ settleArgs.verification,
2835
+ backendResponse,
2836
+ receipt
2837
+ );
2838
+ }
2486
2839
  const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);
2487
2840
  const failures = failuresOf(flow);
2488
2841
  await safeEmit(
@@ -2856,6 +3209,7 @@ function validateResourceSchemaKeywords(id, path2, schema) {
2856
3209
  // src/config/schema/resources.ts
2857
3210
  var SUPPORTED_PROTOCOLS = new Set(PROTOCOL_NAMES);
2858
3211
  var SUPPORTED_PAYMENT_METHODS = new Set(PAYMENT_METHOD_NAMES);
3212
+ var DEFAULT_REDELIVERY_RETENTION_HOURS = 24;
2859
3213
  function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
2860
3214
  if (entry.input !== void 0) validateResourceSchemaKeywords(id, "input", entry.input);
2861
3215
  const inputProperties = entry.input?.["properties"];
@@ -3018,6 +3372,10 @@ function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
3018
3372
  { details: { path: `resources.${id}.mimeType`, resourceId: id } }
3019
3373
  );
3020
3374
  }
3375
+ const servingRail = paymentMethods.find(
3376
+ (method) => method === "x402" && x402?.config.enabled === true || method === "mpp" && mpp?.enabled === true
3377
+ );
3378
+ const idempotency = normalizeResourceIdempotency(id, entry, paymentMethods, servingRail);
3021
3379
  const pricing = entry.pricing.type === "free" ? { type: "free" } : { type: "fixed", amount: entry.pricing.amount, currency: entry.pricing.currency };
3022
3380
  const authorization = normalizeResourceAuthorization(id, entry, pricing, ap2);
3023
3381
  return {
@@ -3041,7 +3399,49 @@ function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
3041
3399
  pricing,
3042
3400
  exposedVia: entry.expose,
3043
3401
  paymentMethods,
3044
- ...authorization !== void 0 ? { authorization } : {}
3402
+ ...authorization !== void 0 ? { authorization } : {},
3403
+ ...idempotency !== void 0 ? { idempotency } : {}
3404
+ };
3405
+ }
3406
+ function normalizeResourceIdempotency(id, entry, paymentMethods, servingRail) {
3407
+ const raw = entry.idempotency;
3408
+ if (raw === void 0) return void 0;
3409
+ const path2 = `resources.${id}.idempotency`;
3410
+ const refuse = (problem, at) => new CommerceError("CONFIG_INVALID", `Resource "${id}" sets ${problem}`, {
3411
+ details: { path: at, resourceId: id }
3412
+ });
3413
+ if (entry.pricing.type !== "fixed") {
3414
+ throw refuse("idempotency, which requires fixed pricing", path2);
3415
+ }
3416
+ if (raw.merchantKey === void 0 && raw.redelivery === void 0) {
3417
+ throw refuse("idempotency without merchantKey or redelivery", path2);
3418
+ }
3419
+ let redelivery;
3420
+ if (raw.redelivery !== void 0) {
3421
+ const required = toBoolean(raw.redelivery.required ?? false, `${path2}.redelivery.required`);
3422
+ if (required && !paymentMethods.includes("x402")) {
3423
+ throw refuse(
3424
+ 'idempotency.redelivery.required, which requires "x402" in payments',
3425
+ `${path2}.redelivery.required`
3426
+ );
3427
+ }
3428
+ if (required && servingRail !== void 0 && servingRail !== "x402") {
3429
+ console.warn(
3430
+ `[agent-commerce] Resource "${id}" sets idempotency.redelivery.required, which applies to x402 only, but the gateway serves it on ${servingRail}, the first enabled rail in its payments. The setting has no effect; list "x402" first or remove it.`
3431
+ );
3432
+ }
3433
+ redelivery = {
3434
+ retentionHours: toNumber(
3435
+ raw.redelivery.retentionHours ?? DEFAULT_REDELIVERY_RETENTION_HOURS,
3436
+ `${path2}.redelivery.retentionHours`,
3437
+ { min: 1, max: MAX_REDELIVERY_RETENTION_HOURS }
3438
+ ),
3439
+ required
3440
+ };
3441
+ }
3442
+ return {
3443
+ ...raw.merchantKey !== void 0 ? { merchantKey: toBoolean(raw.merchantKey, `${path2}.merchantKey`) } : {},
3444
+ ...redelivery !== void 0 ? { redelivery } : {}
3045
3445
  };
3046
3446
  }
3047
3447
  var PRICING_AMOUNT_PATTERN = /^\d+(?:\.\d+)?$/;
@@ -3130,6 +3530,11 @@ function normalize(raw) {
3130
3530
  { details: { path: "protocols.a2a.enabled" } }
3131
3531
  );
3132
3532
  }
3533
+ if (!isHttpUrl(raw.merchant.publicBaseUrl)) {
3534
+ console.warn(
3535
+ `[agent-commerce] merchant.publicBaseUrl ${JSON.stringify(raw.merchant.publicBaseUrl)} is not an http:// or https:// URL. The Host check may then refuse every caller but loopback, and the A2A Agent Card and ACP discovery publish broken URLs.`
3536
+ );
3537
+ }
3133
3538
  return {
3134
3539
  version: SUPPORTED_CONFIG_VERSION,
3135
3540
  merchant: {
@@ -3589,7 +3994,12 @@ var SECRET_FIELD_NAMES = [
3589
3994
  "adminToken",
3590
3995
  "token"
3591
3996
  ];
3592
- var SECRET_HEADERS = ["authorization", PAYMENT_HEADER, AUTHORIZATION_HEADER];
3997
+ var SECRET_HEADERS = [
3998
+ "authorization",
3999
+ PAYMENT_HEADER,
4000
+ AUTHORIZATION_HEADER,
4001
+ "idempotency-key"
4002
+ ];
3593
4003
  var REDACT_PATHS = [
3594
4004
  ...SECRET_HEADERS.map((name) => `req.headers[${JSON.stringify(name)}]`),
3595
4005
  ...SECRET_FIELD_NAMES,
@@ -3811,6 +4221,13 @@ async function alignHold(transaction, target, deps) {
3811
4221
  return holdEntry(transaction, target, true);
3812
4222
  }
3813
4223
 
4224
+ // src/core/idempotency-key.ts
4225
+ var MAX_IDEMPOTENCY_KEY_LENGTH = 255;
4226
+ var USABLE_KEY = new RegExp(`^[\\x20-\\x7e]{1,${MAX_IDEMPOTENCY_KEY_LENGTH}}$`);
4227
+ function isUsableIdempotencyKey(value) {
4228
+ return USABLE_KEY.test(value);
4229
+ }
4230
+
3814
4231
  // src/gateway/public-resource.ts
3815
4232
  function toPublicResource(resource) {
3816
4233
  return {
@@ -3848,7 +4265,7 @@ var AUTHORIZATION_PROVIDER_DETAIL = {
3848
4265
  warn: "authorization-provider-degraded",
3849
4266
  fail: "authorization-provider-unreachable"
3850
4267
  };
3851
- async function probe(target, kind, details, options) {
4268
+ async function probe(target, kind, details, options, failing) {
3852
4269
  let health;
3853
4270
  let threw = false;
3854
4271
  try {
@@ -3859,7 +4276,16 @@ async function probe(target, kind, details, options) {
3859
4276
  health = { status: "fail", checkedAt: options.clock.nowIso() };
3860
4277
  threw = true;
3861
4278
  }
3862
- if (health.detail !== void 0) {
4279
+ const key = `${kind}:${target.name}`;
4280
+ const startsFailing = health.status === "fail" && !failing.has(key);
4281
+ if (health.status === "fail") failing.add(key);
4282
+ else failing.delete(key);
4283
+ if (startsFailing && !threw) {
4284
+ options.logger.warn(
4285
+ { name: target.name, ...health.detail !== void 0 ? { detail: health.detail } : {} },
4286
+ `${kind} health check failed (detail not sent to the client)`
4287
+ );
4288
+ } else if (health.detail !== void 0) {
3863
4289
  options.logger.debug(
3864
4290
  { name: target.name, detail: health.detail },
3865
4291
  `${kind} health detail (not sent to the client)`
@@ -3875,25 +4301,32 @@ async function probe(target, kind, details, options) {
3875
4301
  health
3876
4302
  };
3877
4303
  }
3878
- async function evaluate(options) {
4304
+ async function evaluate(options, failing) {
3879
4305
  const [store, adapters, paymentProviders, authorizationProviders] = await Promise.all([
3880
- probe({ name: "store", health: () => options.store.health() }, "store", STORE_DETAIL, options),
4306
+ probe(
4307
+ { name: "store", health: () => options.store.health() },
4308
+ "store",
4309
+ STORE_DETAIL,
4310
+ options,
4311
+ failing
4312
+ ),
3881
4313
  Promise.all(
3882
4314
  options.adapterRuntimes.map(async (runtime) => ({
3883
4315
  runtime,
3884
4316
  probed: await probe(
3885
- // getAdapterHealth turns a throw into a failed result, so an adapter
3886
- // failure is logged at debug as a detail rather than at error
4317
+ // getAdapterHealth converts throws to failed results, which use
4318
+ // the logging rules for returned results
3887
4319
  { name: runtime.adapter.name, health: () => getAdapterHealth(runtime, options.clock) },
3888
4320
  "adapter",
3889
4321
  ADAPTER_DETAIL,
3890
- options
4322
+ options,
4323
+ failing
3891
4324
  )
3892
4325
  }))
3893
4326
  ),
3894
4327
  Promise.all(
3895
4328
  options.paymentProviders.map(
3896
- (provider) => probe(provider, "payment provider", PAYMENT_PROVIDER_DETAIL, options)
4329
+ (provider) => probe(provider, "payment provider", PAYMENT_PROVIDER_DETAIL, options, failing)
3897
4330
  )
3898
4331
  ),
3899
4332
  // An unusable authorization provider blocks readiness on the same threshold
@@ -3901,7 +4334,7 @@ async function evaluate(options) {
3901
4334
  // without it, and serving the challenge anyway promises what we cannot honor
3902
4335
  Promise.all(
3903
4336
  options.authorizationProviders.map(
3904
- (provider) => probe(provider, "authorization provider", AUTHORIZATION_PROVIDER_DETAIL, options)
4337
+ (provider) => probe(provider, "authorization provider", AUTHORIZATION_PROVIDER_DETAIL, options, failing)
3905
4338
  )
3906
4339
  )
3907
4340
  ]);
@@ -3933,11 +4366,12 @@ var READINESS_TTL_MS = 2e3;
3933
4366
  function createReadinessProbe(options, ttlMs = READINESS_TTL_MS) {
3934
4367
  let cached;
3935
4368
  let inFlight;
4369
+ const failing = /* @__PURE__ */ new Set();
3936
4370
  const current = async () => {
3937
4371
  const now = options.clock.monotonicMs();
3938
4372
  if (cached && now - cached.at < ttlMs) return cached.evaluation;
3939
4373
  if (inFlight) return inFlight;
3940
- inFlight = evaluate(options).then((evaluation) => {
4374
+ inFlight = evaluate(options, failing).then((evaluation) => {
3941
4375
  cached = { evaluation, at: options.clock.monotonicMs() };
3942
4376
  return evaluation;
3943
4377
  }).finally(() => {
@@ -4295,6 +4729,7 @@ async function handleInvoke(request, reply, options) {
4295
4729
  paymentMethod = resource.paymentMethods[0];
4296
4730
  const paymentValue = paymentProof(request, paymentMethod);
4297
4731
  const payment = paymentValue !== void 0 && paymentMethod !== void 0 ? { method: paymentMethod, payload: paymentValue } : void 0;
4732
+ const retryKey = paymentMethod === "mpp" && resource.idempotency?.redelivery !== void 0 ? mppRetryKey(request, resourceId) : void 0;
4298
4733
  const authorization = parseAuthorizationHeader(
4299
4734
  request.headers[AUTHORIZATION_HEADER],
4300
4735
  request.id
@@ -4307,6 +4742,7 @@ async function handleInvoke(request, reply, options) {
4307
4742
  protocol: "http",
4308
4743
  receivedAt: options.clock.nowIso(),
4309
4744
  ...payment !== void 0 ? { payment } : {},
4745
+ ...retryKey !== void 0 ? { retryKey } : {},
4310
4746
  ...authorization !== void 0 ? { authorization } : {},
4311
4747
  ...digest !== void 0 ? { metadata: { [CONTENT_DIGEST_METADATA_KEY]: digest } } : {}
4312
4748
  };
@@ -4345,11 +4781,13 @@ async function handleInvoke(request, reply, options) {
4345
4781
  encodeHeaderDocument(settlementResponse(outcome.payment))
4346
4782
  );
4347
4783
  const receipt = outcome.payment.metadata?.["receipt"];
4348
- if (outcome.payment.provider === "mpp" && typeof receipt === "string") {
4784
+ const success = outcome.backendStatus >= 200 && outcome.backendStatus < 300;
4785
+ if (outcome.payment.provider === "mpp" && typeof receipt === "string" && (success || outcome.redelivered !== true)) {
4349
4786
  reply.header("payment-receipt", receipt);
4350
4787
  }
4351
4788
  reply.header("cache-control", "private");
4352
4789
  }
4790
+ if (outcome.redelivered === true) reply.header("idempotent-replayed", "true");
4353
4791
  const contentType = relayedContentType(outcome.headers?.["content-type"], outcome.body);
4354
4792
  if (contentType !== void 0) reply.type(contentType);
4355
4793
  if (typeof outcome.body === "string") {
@@ -4358,7 +4796,14 @@ async function handleInvoke(request, reply, options) {
4358
4796
  }
4359
4797
  reply.status(outcome.backendStatus).send(outcome.body);
4360
4798
  } catch (error) {
4361
- sendInvokeError(reply, toCommerceError(error), paymentMethod);
4799
+ const commerceError = toCommerceError(error);
4800
+ const entry = { resourceId, requestId: request.id, err: toLogInfo(commerceError) };
4801
+ if (commerceError.httpStatus >= 500) {
4802
+ options.logger.warn(entry, "http adapter: execution failed");
4803
+ } else {
4804
+ options.logger.debug(entry, "http adapter: execution failed");
4805
+ }
4806
+ sendInvokeError(reply, commerceError, paymentMethod);
4362
4807
  }
4363
4808
  }
4364
4809
  function relayedContentType(header2, body) {
@@ -4389,9 +4834,14 @@ var MPP_PROBLEM_CODES = /* @__PURE__ */ new Set([
4389
4834
  ]);
4390
4835
  function sendInvokeError(reply, error, paymentMethod) {
4391
4836
  const details = error.details;
4837
+ const reason = typeof details?.["reason"] === "string" ? details["reason"] : void 0;
4392
4838
  if (PROVIDER_UNAVAILABLE_CODES.has(error.code)) {
4393
4839
  reply.header("retry-after", String(PROVIDER_RETRY_AFTER_SECONDS));
4394
4840
  }
4841
+ const retryAfter = details?.["retryAfterSeconds"];
4842
+ if (typeof retryAfter === "number" && Number.isSafeInteger(retryAfter) && retryAfter >= 0) {
4843
+ reply.header("retry-after", String(retryAfter));
4844
+ }
4395
4845
  const settled = settlementResponseFromDetails(details);
4396
4846
  if (settled !== void 0) {
4397
4847
  reply.header(PAYMENT_RESPONSE_HEADER, encodeHeaderDocument(settled));
@@ -4415,12 +4865,12 @@ function sendInvokeError(reply, error, paymentMethod) {
4415
4865
  reply.header("cache-control", "no-store");
4416
4866
  }
4417
4867
  const envelope = toErrorEnvelope(error);
4418
- if (paymentMethod === "mpp" && MPP_PROBLEM_CODES.has(error.code)) {
4868
+ if (paymentMethod === "mpp" && (MPP_PROBLEM_CODES.has(error.code) || reason?.startsWith("payment_identifier_") === true)) {
4419
4869
  const { status: _envelopeStatus, ...members } = envelope;
4420
- const reason = typeof details?.["reason"] === "string" ? details["reason"] : void 0;
4421
- reply.header("content-type", "application/problem+json").status(error.httpStatus).send({
4422
- ...mppProblem(error.code, error.httpStatus, reason),
4423
- status: error.httpStatus,
4870
+ const problemStatus = reason === "payment_identifier_conflict" ? 422 : error.httpStatus;
4871
+ reply.header("content-type", "application/problem+json").status(problemStatus).send({
4872
+ ...mppProblem(error.code, problemStatus, reason),
4873
+ status: problemStatus,
4424
4874
  // The reason token stays in `message` and `details.reason`
4425
4875
  detail: mppProblemDetail(reason, error.message),
4426
4876
  ...members
@@ -4430,6 +4880,21 @@ function sendInvokeError(reply, error, paymentMethod) {
4430
4880
  const status = paymentMethod === "x402" ? x402RefusalStatus(error.code, error.httpStatus, details?.["reason"]) : error.httpStatus;
4431
4881
  reply.status(status).send(envelope);
4432
4882
  }
4883
+ var SF_STRING = /^"((?:[\x20\x21\x23-\x5b\x5d-\x7e]|\\["\\])*)"$/;
4884
+ function mppRetryKey(request, resourceId) {
4885
+ const value = request.headers["idempotency-key"];
4886
+ if (value === void 0) return void 0;
4887
+ if (typeof value === "string") {
4888
+ const trimmed = value.trim();
4889
+ const key = trimmed.startsWith('"') ? SF_STRING.exec(trimmed)?.[1]?.replace(/\\(["\\])/g, "$1") : trimmed;
4890
+ if (key !== void 0 && isUsableIdempotencyKey(key)) return key;
4891
+ }
4892
+ throw new CommerceError(
4893
+ "INPUT_INVALID",
4894
+ "The Idempotency-Key header must be 1 to 255 printable ASCII characters",
4895
+ { requestId: request.id, resourceId, details: { reason: "payment_identifier_invalid" } }
4896
+ );
4897
+ }
4433
4898
  function paymentProof(request, method) {
4434
4899
  if (method === "mpp") {
4435
4900
  const value2 = request.headers.authorization;
@@ -4490,6 +4955,25 @@ function withProviderBackedMethodsFirst(resource, providers) {
4490
4955
  ];
4491
4956
  return ordered.some((method, i) => method !== resource.paymentMethods[i]) ? { ...resource, paymentMethods: ordered } : resource;
4492
4957
  }
4958
+ async function recoverPaymentKeys(store, logger) {
4959
+ if (!hasMethodGroup(store, "idempotency_claims") || !hasMethodGroup(store, "response_redelivery")) {
4960
+ return;
4961
+ }
4962
+ let recovered;
4963
+ try {
4964
+ recovered = await store.recoverIdempotencyKeys({
4965
+ release: false,
4966
+ endpointPrefix: PAYMENT_KEY_ENDPOINT_PREFIX
4967
+ });
4968
+ } catch (error) {
4969
+ throw new CommerceError("STORAGE_ERROR", "Payment retry keys could not be recovered", {
4970
+ cause: error
4971
+ });
4972
+ }
4973
+ if (recovered > 0) {
4974
+ logger.warn({ recovered }, "Payment retry keys left in flight are now unresolved");
4975
+ }
4976
+ }
4493
4977
  async function createGateway(options) {
4494
4978
  const clock = options.clock ?? systemClock;
4495
4979
  const ids = options.ids ?? createDefaultIdGenerator();
@@ -4501,6 +4985,10 @@ async function createGateway(options) {
4501
4985
  (resource) => withProviderBackedMethodsFirst(resource, options.paymentProviders)
4502
4986
  )
4503
4987
  );
4988
+ for (const resource of resources.list()) {
4989
+ assertRetrySupport(resource, options.store, options.config.merchant.publicBaseUrl);
4990
+ }
4991
+ await recoverPaymentKeys(options.store, logger);
4504
4992
  const events = createStoreEventSink({ store: options.store, logger });
4505
4993
  const pipeline = createExecutionPipeline({
4506
4994
  resources,
@@ -4511,7 +4999,8 @@ async function createGateway(options) {
4511
4999
  events,
4512
5000
  logger,
4513
5001
  clock,
4514
- ids
5002
+ ids,
5003
+ deployment: options.config.merchant.publicBaseUrl
4515
5004
  });
4516
5005
  const server = Fastify({
4517
5006
  // Same cap as adapter mounts, which enforce it on the socket instead
@@ -5011,7 +5500,8 @@ function paymentFailureMetadata(error, network) {
5011
5500
  [X402_PAYMENT_RECEIPTS_KEY]: [settled]
5012
5501
  };
5013
5502
  }
5014
- const code = error.code.startsWith("PAYMENT_") ? x402ErrorCode(error.code, error.details?.["reason"], error.details?.["network"]) : error.code.toLowerCase();
5503
+ const reason = error.details?.["reason"];
5504
+ const code = error.code.startsWith("PAYMENT_") || typeof reason === "string" && reason.startsWith("payment_identifier_") ? x402ErrorCode(error.code, reason, error.details?.["network"]) : error.code.toLowerCase();
5015
5505
  const failure = settlementFailure(error.details);
5016
5506
  const receipt = failure["network"] === "" && network !== void 0 ? { ...failure, network } : failure;
5017
5507
  return {
@@ -5315,6 +5805,17 @@ async function resumePayment(context, pendingPayments, id, params) {
5315
5805
  )
5316
5806
  );
5317
5807
  }
5808
+ function withoutRetryDelay(error) {
5809
+ if (error.details?.["reason"] !== "payment_identifier_in_flight") return error;
5810
+ const { retryAfterSeconds: _delay, ...details } = error.details;
5811
+ return new CommerceError(error.code, error.message, {
5812
+ httpStatus: error.httpStatus,
5813
+ retryable: false,
5814
+ details,
5815
+ ...error.requestId !== void 0 ? { requestId: error.requestId } : {},
5816
+ ...error.resourceId !== void 0 ? { resourceId: error.resourceId } : {}
5817
+ });
5818
+ }
5318
5819
  async function payPending(context, pending, payload, identity) {
5319
5820
  const requestId = context.ids.next("a2a");
5320
5821
  const request = {
@@ -5343,16 +5844,19 @@ async function payPending(context, pending, payload, identity) {
5343
5844
  }
5344
5845
  error = new CommerceError("PAYMENT_INVALID", "The payment was not accepted.", { requestId });
5345
5846
  } catch (err) {
5346
- error = toCommerceError(err);
5847
+ error = withoutRetryDelay(toCommerceError(err));
5347
5848
  context.logger.warn(
5348
5849
  { resourceId: pending.resourceId, requestId, err: toLogInfo(error) },
5349
5850
  "a2a adapter: x402 extension payment failed"
5350
5851
  );
5351
5852
  }
5352
5853
  const metadata = paymentFailureMetadata(error, pending.network);
5854
+ const reason = error.details?.["reason"];
5353
5855
  let text = "Payment failed.";
5354
5856
  if (metadata[X402_PAYMENT_STATUS_KEY] === "payment-completed") {
5355
5857
  text = "Payment settled, but the resource could not be delivered.";
5858
+ } else if (typeof reason === "string" && reason.startsWith("payment_identifier_")) {
5859
+ text = error.message;
5356
5860
  } else if (!error.code.startsWith("PAYMENT_")) {
5357
5861
  text = "The resource could not be delivered.";
5358
5862
  }
@@ -5842,7 +6346,7 @@ function sha2562(value) {
5842
6346
 
5843
6347
  // src/protocols/acp/idempotency/store.ts
5844
6348
  var SCHEMA_VERSION = 2;
5845
- var ACP_MAX_IDEMPOTENCY_KEY_LENGTH = 255;
6349
+ var ACP_MAX_IDEMPOTENCY_KEY_LENGTH = MAX_IDEMPOTENCY_KEY_LENGTH;
5846
6350
  function createAcpIdempotencyStore(options) {
5847
6351
  const logger = options.logger ?? NOOP_LOGGER;
5848
6352
  const now = options.now ?? (() => Date.now());
@@ -10263,9 +10767,6 @@ function forwardedHeaders(req, requestId) {
10263
10767
  }
10264
10768
  return forwarded;
10265
10769
  }
10266
- function isUsableIdempotencyKey(value) {
10267
- return value.length > 0 && value.length <= ACP_MAX_IDEMPOTENCY_KEY_LENGTH && isVisibleAscii(value);
10268
- }
10269
10770
  function normalizeRequestId(value) {
10270
10771
  if (value === void 0) return void 0;
10271
10772
  const trimmed = value.trim().slice(0, ACP_MAX_REQUEST_ID_LENGTH);
@@ -10620,7 +11121,7 @@ var AcpProtocolAdapter = class {
10620
11121
  const release = merchantIdempotent === true;
10621
11122
  const store = this.store;
10622
11123
  if (hasMethodGroup(store, "idempotency_claims")) {
10623
- const recovered = await store.recoverIdempotencyKeys({ release });
11124
+ const recovered = await store.recoverIdempotencyKeys({ release, endpointPrefix: "/" });
10624
11125
  warnOrphanedClaims(context.logger, recovered, release);
10625
11126
  return backendOverReceiptStore(store, context.clock, retentionHours);
10626
11127
  }
@@ -11433,23 +11934,37 @@ function createHoldMethods(db, clock) {
11433
11934
  }
11434
11935
 
11435
11936
  // src/storage/receipts/idempotency.ts
11937
+ var ENDPOINT_HAS_PREFIX = "substr(endpoint, 1, length(@prefix)) = @prefix";
11436
11938
  var scopeParams = (scope) => ({
11437
11939
  deployment: scope.deployment,
11438
11940
  endpoint: scope.endpoint,
11439
11941
  idempotency_key: scope.key
11440
11942
  });
11943
+ function claimOf(row, fingerprint) {
11944
+ if (row.fingerprint !== fingerprint) return { kind: "conflict" };
11945
+ const body = row.body_json === null ? null : JSON.parse(row.body_json);
11946
+ if (row.state === "completed") return { kind: "replay", status: row.status ?? 500, body };
11947
+ const kind = row.state === "unresolved" ? "unresolved" : "in-flight";
11948
+ const owner = isRecord(body) ? body["owner"] : void 0;
11949
+ return typeof owner === "string" ? { kind, owner } : { kind };
11950
+ }
11951
+ function hasExpired(row, endpoint, now) {
11952
+ if (row.expires_at > now) return false;
11953
+ return row.state === "completed" || row.state === "unresolved" && endpoint.startsWith(PAYMENT_KEY_ENDPOINT_PREFIX);
11954
+ }
11441
11955
  function createIdempotencyMethods(db, clock) {
11442
11956
  const SCOPE = "deployment = @deployment AND endpoint = @endpoint AND idempotency_key = @idempotency_key";
11443
11957
  const selectClaim = db.prepare(
11444
- `SELECT state, fingerprint, status, body_json FROM idempotency_keys WHERE ${SCOPE}`
11958
+ `SELECT state, fingerprint, status, body_json, expires_at FROM idempotency_keys WHERE ${SCOPE}`
11445
11959
  );
11446
11960
  const insertClaim = db.prepare(
11447
11961
  `INSERT INTO idempotency_keys
11448
- (deployment, endpoint, idempotency_key, fingerprint, state, created_at, expires_at)
11449
- VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, 'in_flight', @created_at, @expires_at)`
11962
+ (deployment, endpoint, idempotency_key, fingerprint, state, body_json, created_at, expires_at)
11963
+ VALUES (@deployment, @endpoint, @idempotency_key, @fingerprint, 'in_flight', @body_json, @created_at, @expires_at)`
11450
11964
  );
11451
- const expireCompleted = db.prepare(
11452
- "DELETE FROM idempotency_keys WHERE expires_at <= ? AND state = 'completed'"
11965
+ const expireFinished = db.prepare(
11966
+ `DELETE FROM idempotency_keys WHERE expires_at <= @now
11967
+ AND (state = 'completed' OR (state = 'unresolved' AND ${ENDPOINT_HAS_PREFIX}))`
11453
11968
  );
11454
11969
  const completeClaim = db.prepare(
11455
11970
  `UPDATE idempotency_keys SET state = 'completed', status = @status, body_json = @body_json
@@ -11459,42 +11974,46 @@ function createIdempotencyMethods(db, clock) {
11459
11974
  `UPDATE idempotency_keys SET state = 'unresolved' WHERE ${SCOPE}`
11460
11975
  );
11461
11976
  const deleteClaim = db.prepare(`DELETE FROM idempotency_keys WHERE ${SCOPE}`);
11462
- const releaseInFlight = db.prepare("DELETE FROM idempotency_keys WHERE state = 'in_flight'");
11977
+ const IN_FLIGHT = `state = 'in_flight' AND ${ENDPOINT_HAS_PREFIX}`;
11978
+ const releaseInFlight = db.prepare(`DELETE FROM idempotency_keys WHERE ${IN_FLIGHT}`);
11463
11979
  const unresolveInFlight = db.prepare(
11464
- "UPDATE idempotency_keys SET state = 'unresolved' WHERE state = 'in_flight'"
11980
+ `UPDATE idempotency_keys SET state = 'unresolved' WHERE ${IN_FLIGHT}`
11465
11981
  );
11466
11982
  const claim = db.transaction(
11467
- (scope, fingerprint, expiresAt) => {
11983
+ (scope, fingerprint, expiresAt, owner) => {
11468
11984
  const now = clock.nowIso();
11469
- expireCompleted.run(now);
11985
+ expireFinished.run({ now, prefix: PAYMENT_KEY_ENDPOINT_PREFIX });
11470
11986
  const existing = selectClaim.get(scopeParams(scope));
11471
11987
  if (existing === void 0) {
11472
11988
  insertClaim.run({
11473
11989
  ...scopeParams(scope),
11474
11990
  fingerprint,
11991
+ body_json: owner !== void 0 ? JSON.stringify({ owner }) : null,
11475
11992
  created_at: now,
11476
11993
  expires_at: expiresAt
11477
11994
  });
11478
11995
  return { kind: "reserved" };
11479
11996
  }
11480
- if (existing.fingerprint !== fingerprint) return { kind: "conflict" };
11481
- if (existing.state === "unresolved") return { kind: "unresolved" };
11482
- if (existing.state !== "completed") return { kind: "in-flight" };
11483
- return {
11484
- kind: "replay",
11485
- status: existing.status ?? 500,
11486
- body: existing.body_json === null ? null : JSON.parse(existing.body_json)
11487
- };
11997
+ return claimOf(existing, fingerprint);
11488
11998
  }
11489
11999
  );
11490
12000
  return {
11491
- async claimIdempotencyKey(scope, fingerprint, expiresAt) {
12001
+ async claimIdempotencyKey(scope, fingerprint, expiresAt, owner) {
11492
12002
  try {
11493
- return claim.immediate(scope, fingerprint, storedIso(expiresAt, "expiresAt"));
12003
+ return claim.immediate(scope, fingerprint, storedIso(expiresAt, "expiresAt"), owner);
11494
12004
  } catch (err) {
11495
12005
  throw toCommerceError(err, "STORAGE_ERROR", "Failed to claim idempotency key");
11496
12006
  }
11497
12007
  },
12008
+ async getIdempotencyKey(scope, fingerprint) {
12009
+ try {
12010
+ const existing = selectClaim.get(scopeParams(scope));
12011
+ if (existing === void 0) return void 0;
12012
+ return hasExpired(existing, scope.endpoint, clock.nowIso()) ? void 0 : claimOf(existing, fingerprint);
12013
+ } catch (err) {
12014
+ throw toCommerceError(err, "STORAGE_ERROR", "Failed to read idempotency key");
12015
+ }
12016
+ },
11498
12017
  async updateIdempotencyKey(scope, update) {
11499
12018
  try {
11500
12019
  switch (update.kind) {
@@ -11516,9 +12035,10 @@ function createIdempotencyMethods(db, clock) {
11516
12035
  throw toCommerceError(err, "STORAGE_ERROR", "Failed to update idempotency key");
11517
12036
  }
11518
12037
  },
11519
- async recoverIdempotencyKeys(options) {
12038
+ async recoverIdempotencyKeys({ release, endpointPrefix = "" }) {
11520
12039
  try {
11521
- return (options.release ? releaseInFlight : unresolveInFlight).run().changes;
12040
+ const recover = release ? releaseInFlight : unresolveInFlight;
12041
+ return recover.run({ prefix: endpointPrefix }).changes;
11522
12042
  } catch (err) {
11523
12043
  throw toCommerceError(err, "STORAGE_ERROR", "Failed to recover idempotency keys");
11524
12044
  }
@@ -12040,7 +12560,9 @@ function storeOn(db, options) {
12040
12560
  `SELECT COUNT(*) AS count FROM authorization_holds h WHERE ${ORPHAN_HOLD_WHERE}`
12041
12561
  );
12042
12562
  const countUnresolvedKeysStmt = db.prepare(
12043
- "SELECT COUNT(*) AS count FROM idempotency_keys WHERE state = 'unresolved'"
12563
+ `SELECT COUNT(*) FILTER (WHERE ${ENDPOINT_HAS_PREFIX} AND expires_at > @now) AS payment,
12564
+ COUNT(*) FILTER (WHERE NOT ${ENDPOINT_HAS_PREFIX}) AS other
12565
+ FROM idempotency_keys WHERE state = 'unresolved'`
12044
12566
  );
12045
12567
  const countLiveTasksStmt = db.prepare(
12046
12568
  "SELECT COUNT(*) AS count FROM pending_tasks WHERE expires_at > ?"
@@ -12291,10 +12813,15 @@ function storeOn(db, options) {
12291
12813
  unresolvedTransactions[state] = (unresolvedTransactions[state] ?? 0) + 1;
12292
12814
  }
12293
12815
  const orphansBefore = new Date(Date.parse(now) - orphanHoldMinAgeMs).toISOString();
12816
+ const unresolvedKeys = countUnresolvedKeysStmt.get({
12817
+ prefix: PAYMENT_KEY_ENDPOINT_PREFIX,
12818
+ now
12819
+ });
12294
12820
  return {
12295
12821
  unresolvedTransactions,
12296
12822
  orphanHolds: countOrphanHoldsStmt.get(orphansBefore)?.count ?? 0,
12297
- unresolvedIdempotencyKeys: countUnresolvedKeysStmt.get()?.count ?? 0,
12823
+ unresolvedIdempotencyKeys: unresolvedKeys?.other ?? 0,
12824
+ unresolvedPaymentKeys: unresolvedKeys?.payment ?? 0,
12298
12825
  unexpiredPendingTasks: countLiveTasksStmt.get(now)?.count ?? 0,
12299
12826
  legacyImports: legacyImportsStmt.all().map((row) => ({
12300
12827
  source: row.source,