@devlab.group/agent-commerce 2.5.0 → 2.7.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 (129) hide show
  1. package/README.md +78 -21
  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-ES3V6ECS.js → chunk-77HLISG4.js} +3 -2
  6. package/dist/chunk-77HLISG4.js.map +1 -0
  7. package/dist/{chunk-5ZYXBCDX.js → chunk-D7FPSGUQ.js} +25 -4
  8. package/dist/chunk-D7FPSGUQ.js.map +1 -0
  9. package/dist/{chunk-VUCMBGUR.js → chunk-DJRWYDKJ.js} +3 -3
  10. package/dist/{chunk-VUCMBGUR.js.map → chunk-DJRWYDKJ.js.map} +1 -1
  11. package/dist/{chunk-4K7FIBJM.js → chunk-EMKITGVV.js} +4 -4
  12. package/dist/chunk-EMKITGVV.js.map +1 -0
  13. package/dist/chunk-IWXVQYG5.js +6 -0
  14. package/dist/chunk-IWXVQYG5.js.map +1 -0
  15. package/dist/chunk-O3ACF45K.js +8 -0
  16. package/dist/chunk-O3ACF45K.js.map +1 -0
  17. package/dist/chunk-WDD2ZUR3.js +20 -0
  18. package/dist/chunk-WDD2ZUR3.js.map +1 -0
  19. package/dist/{chunk-3OTCFFFT.js → chunk-YHNTTMED.js} +7 -7
  20. package/dist/chunk-YHNTTMED.js.map +1 -0
  21. package/dist/{chunk-FKQK5XZA.js → chunk-ZSIUZPNB.js} +183 -80
  22. package/dist/chunk-ZSIUZPNB.js.map +1 -0
  23. package/dist/cli/{ap2-YAPLERSC.js → ap2-5FFGSW6F.js} +61 -25
  24. package/dist/cli/ap2-5FFGSW6F.js.map +1 -0
  25. package/dist/cli/{chunk-5K4XEAZV.js → chunk-3IEXJ7I3.js} +25 -4
  26. package/dist/cli/chunk-3IEXJ7I3.js.map +1 -0
  27. package/dist/cli/{chunk-NIU5EMSB.js → chunk-3NVJAQRO.js} +5 -5
  28. package/dist/cli/{chunk-NIU5EMSB.js.map → chunk-3NVJAQRO.js.map} +1 -1
  29. package/dist/cli/{chunk-IDY2735M.js → chunk-55AI6CLW.js} +6 -4
  30. package/dist/cli/chunk-55AI6CLW.js.map +1 -0
  31. package/dist/cli/{chunk-QA2OPHBF.js → chunk-5K2JDM4G.js} +185 -83
  32. package/dist/cli/chunk-5K2JDM4G.js.map +1 -0
  33. package/dist/cli/{chunk-QLUCNPRT.js → chunk-5TID36YG.js} +860 -170
  34. package/dist/cli/chunk-5TID36YG.js.map +1 -0
  35. package/dist/cli/{chunk-5R7DM5LM.js → chunk-66NTYSXI.js} +27 -27
  36. package/dist/cli/chunk-66NTYSXI.js.map +1 -0
  37. package/dist/cli/{chunk-VJ4EO4LE.js → chunk-6EBDOH37.js} +3 -3
  38. package/dist/cli/{chunk-VJ4EO4LE.js.map → chunk-6EBDOH37.js.map} +1 -1
  39. package/dist/cli/{chunk-4H2QLHQI.js → chunk-AGQ4U7IN.js} +5 -5
  40. package/dist/cli/chunk-AGQ4U7IN.js.map +1 -0
  41. package/dist/cli/chunk-APC5BTQM.js +6 -0
  42. package/dist/cli/chunk-APC5BTQM.js.map +1 -0
  43. package/dist/cli/{chunk-SYQLJXIU.js → chunk-C5YISPT6.js} +3 -3
  44. package/dist/cli/chunk-C5YISPT6.js.map +1 -0
  45. package/dist/cli/chunk-DKWO6LLX.js +34 -0
  46. package/dist/cli/chunk-DKWO6LLX.js.map +1 -0
  47. package/dist/cli/{chunk-SPAYKVUP.js → chunk-FL4HPCD4.js} +3 -2
  48. package/dist/cli/chunk-FL4HPCD4.js.map +1 -0
  49. package/dist/cli/{chunk-3EQBCFZY.js → chunk-H7EBJ4I3.js} +3 -3
  50. package/dist/cli/{chunk-3EQBCFZY.js.map → chunk-H7EBJ4I3.js.map} +1 -1
  51. package/dist/cli/{chunk-Z34UMZBB.js → chunk-OETKXDGA.js} +546 -175
  52. package/dist/cli/chunk-OETKXDGA.js.map +1 -0
  53. package/dist/cli/{chunk-JFVRG2HH.js → chunk-PLHPKXAT.js} +8 -8
  54. package/dist/cli/chunk-PLHPKXAT.js.map +1 -0
  55. package/dist/cli/{chunk-2UPPX3FJ.js → chunk-VSSSU4AU.js} +76 -14
  56. package/dist/cli/chunk-VSSSU4AU.js.map +1 -0
  57. package/dist/cli/chunk-ZCW56PZ3.js +8 -0
  58. package/dist/cli/{chunk-M7NXVRU5.js.map → chunk-ZCW56PZ3.js.map} +1 -1
  59. package/dist/cli/{chunk-2J2IQQ4X.js → chunk-ZFVQWOGG.js} +95 -42
  60. package/dist/cli/chunk-ZFVQWOGG.js.map +1 -0
  61. package/dist/cli/config-WT5HHDRR.js +13 -0
  62. package/dist/cli/{config-BWFMN2ZB.js.map → config-WT5HHDRR.js.map} +1 -1
  63. package/dist/cli/index.js +560 -252
  64. package/dist/cli/index.js.map +1 -1
  65. package/dist/cli/{mcp-KZEMXLHR.js → mcp-HHGNOUKE.js} +7 -7
  66. package/dist/cli/{mcp-KZEMXLHR.js.map → mcp-HHGNOUKE.js.map} +1 -1
  67. package/dist/cli/payment-providers-EWXZFBIE.js +6 -0
  68. package/dist/cli/{payment-providers-SZL36H3Y.js.map → payment-providers-EWXZFBIE.js.map} +1 -1
  69. package/dist/cli/{provider-6TKB5ADJ.js → provider-XUPLYNQ7.js} +36 -18
  70. package/dist/cli/provider-XUPLYNQ7.js.map +1 -0
  71. package/dist/cli/receipts-3DSV4DIK.js +9 -0
  72. package/dist/cli/{receipts-ZGLJWMQG.js.map → receipts-3DSV4DIK.js.map} +1 -1
  73. package/dist/cli/reconcile-GS25MQ42.js +4 -0
  74. package/dist/cli/{reconcile-IC22MJD5.js.map → reconcile-GS25MQ42.js.map} +1 -1
  75. package/dist/cli/{run-ZTYPQI4D.js → run-7KLKW3HE.js} +310 -91
  76. package/dist/cli/run-7KLKW3HE.js.map +1 -0
  77. package/dist/cli/{x402-WLYBLODI.js → x402-HP4E3QET.js} +11 -10
  78. package/dist/cli/x402-HP4E3QET.js.map +1 -0
  79. package/dist/{guardrails-CX_jYXvZ.d.ts → guardrails-CeyLS1ou.d.ts} +2 -2
  80. package/dist/index.d.ts +119 -206
  81. package/dist/index.js +1703 -427
  82. package/dist/index.js.map +1 -1
  83. package/dist/logger-CllGwQ8i.d.ts +19 -0
  84. package/dist/mcp.d.ts +3 -1
  85. package/dist/mcp.js +4 -3
  86. package/dist/mcp.js.map +1 -1
  87. package/dist/mpp.d.ts +2 -1
  88. package/dist/mpp.js +32 -13
  89. package/dist/mpp.js.map +1 -1
  90. package/dist/{protocol-adapter-DEXpdp8m.d.ts → protocol-adapter-DdFL5LBU.d.ts} +15 -132
  91. package/dist/{runtime-Dz2fSO-P.d.ts → runtime-BmaSp2Ce.d.ts} +36 -23
  92. package/dist/store-BVvMzpuV.d.ts +389 -0
  93. package/dist/testing.d.ts +51 -0
  94. package/dist/testing.js +2050 -0
  95. package/dist/testing.js.map +1 -0
  96. package/dist/transaction-BXXJltZ-.d.ts +129 -0
  97. package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
  98. package/dist/x402.d.ts +9 -3
  99. package/dist/x402.js +7 -5
  100. package/dist/x402.js.map +1 -1
  101. package/package.json +17 -29
  102. package/dist/chunk-3OTCFFFT.js.map +0 -1
  103. package/dist/chunk-4K7FIBJM.js.map +0 -1
  104. package/dist/chunk-5ZYXBCDX.js.map +0 -1
  105. package/dist/chunk-ES3V6ECS.js.map +0 -1
  106. package/dist/chunk-FKQK5XZA.js.map +0 -1
  107. package/dist/cli/ap2-YAPLERSC.js.map +0 -1
  108. package/dist/cli/chunk-2J2IQQ4X.js.map +0 -1
  109. package/dist/cli/chunk-2UPPX3FJ.js.map +0 -1
  110. package/dist/cli/chunk-4H2QLHQI.js.map +0 -1
  111. package/dist/cli/chunk-5K4XEAZV.js.map +0 -1
  112. package/dist/cli/chunk-5R7DM5LM.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-IDY2735M.js.map +0 -1
  116. package/dist/cli/chunk-JFVRG2HH.js.map +0 -1
  117. package/dist/cli/chunk-M7NXVRU5.js +0 -8
  118. package/dist/cli/chunk-QA2OPHBF.js.map +0 -1
  119. package/dist/cli/chunk-QLUCNPRT.js.map +0 -1
  120. package/dist/cli/chunk-SPAYKVUP.js.map +0 -1
  121. package/dist/cli/chunk-SYQLJXIU.js.map +0 -1
  122. package/dist/cli/chunk-Z34UMZBB.js.map +0 -1
  123. package/dist/cli/config-BWFMN2ZB.js +0 -12
  124. package/dist/cli/payment-providers-SZL36H3Y.js +0 -6
  125. package/dist/cli/provider-6TKB5ADJ.js.map +0 -1
  126. package/dist/cli/receipts-ZGLJWMQG.js +0 -8
  127. package/dist/cli/reconcile-IC22MJD5.js +0 -4
  128. package/dist/cli/run-ZTYPQI4D.js.map +0 -1
  129. package/dist/cli/x402-WLYBLODI.js.map +0 -1
@@ -1,20 +1,21 @@
1
- import { createConfiguredPaymentProviders, importOptionalPeer } from './chunk-JFVRG2HH.js';
2
- import { readCappedBody, createBearerCheck, joinUrl, settlementResponse, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-SPAYKVUP.js';
3
- import { A2A_DEFAULT_MOUNT_PATH, A2A_DEFAULT_AGENT_NAME, buildDescriptor, A2A_AGENT_CARD_PATH, A2A_JSON_MEDIA_TYPE, A2A_VERSION_HEADER, A2A_PROTOCOL_VERSION, A2A_EXTENSIONS_HEADER, A2A_PUSH_CONFIG_METHODS, A2A_TASK_LOOKUP_METHODS, A2A_UNSUPPORTED_METHODS, A2A_METHOD_SEND_MESSAGE, buildDescriptor2, A2A_PROTOCOL_BINDING, A2A_TASK_STATE_FAILED, A2A_TASK_STATE_COMPLETED, A2A_TASK_STATE_INPUT_REQUIRED } from './chunk-NIU5EMSB.js';
4
- import { createSqliteReceiptStore } from './chunk-QLUCNPRT.js';
5
- import { openSqliteDatabase } from './chunk-VJ4EO4LE.js';
6
- import { loadConfig } from './chunk-2J2IQQ4X.js';
7
- import { HttpBackendExecutor, createResourceRegistry, createStoreEventSink, createExecutionPipeline, ACP_WELL_KNOWN_PATH, ACP_CHECKOUT_OPERATIONS, ACP_IN_FLIGHT_RETRY_AFTER_SECONDS, ACP_IDEMPOTENT_REPLAYED_HEADER, ACP_IDEMPOTENCY_KEY_HEADER, ACP_REQUEST_ID_HEADER, ACP_SPEC_VERSION, ACP_JSON_MEDIA_TYPE, ACP_API_VERSION, ACP_API_VERSION_HEADER, ACP_MAX_REQUEST_ID_LENGTH, ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS, ACP_SESSION_ID_INPUT_KEY, ACP_FORWARDED_HEADERS, ACP_MAX_FORWARDED_HEADER_LENGTH, BackendErrorResponse, ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS, ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS } from './chunk-Z34UMZBB.js';
8
- import './chunk-FHCFR2GS.js';
1
+ import { createConfiguredPaymentProviders, importOptionalPeer } from './chunk-PLHPKXAT.js';
2
+ import { readCappedBody, createBearerCheck, joinUrl, settlementResponse, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-FL4HPCD4.js';
3
+ import { A2A_DEFAULT_MOUNT_PATH, A2A_DEFAULT_AGENT_NAME, buildDescriptor, A2A_AGENT_CARD_PATH, A2A_JSON_MEDIA_TYPE, A2A_VERSION_HEADER, A2A_PROTOCOL_VERSION, A2A_EXTENSIONS_HEADER, A2A_PUSH_CONFIG_METHODS, A2A_TASK_LOOKUP_METHODS, A2A_UNSUPPORTED_METHODS, A2A_METHOD_SEND_MESSAGE, buildDescriptor2, A2A_PROTOCOL_BINDING, A2A_TASK_STATE_FAILED, A2A_TASK_STATE_COMPLETED, A2A_TASK_STATE_INPUT_REQUIRED } from './chunk-3NVJAQRO.js';
4
+ import { loadConfig } from './chunk-ZFVQWOGG.js';
5
+ import { HttpBackendExecutor, createResourceRegistry, assertRetrySupport, createStoreEventSink, createExecutionPipeline, ACP_WELL_KNOWN_PATH, ACP_CHECKOUT_OPERATIONS, ACP_IN_FLIGHT_RETRY_AFTER_SECONDS, ACP_IDEMPOTENT_REPLAYED_HEADER, ACP_IDEMPOTENCY_KEY_HEADER, ACP_REQUEST_ID_HEADER, ACP_SPEC_VERSION, ACP_JSON_MEDIA_TYPE, ACP_API_VERSION, ACP_API_VERSION_HEADER, ACP_MAX_REQUEST_ID_LENGTH, ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS, ACP_SESSION_ID_INPUT_KEY, ACP_FORWARDED_HEADERS, ACP_MAX_FORWARDED_HEADER_LENGTH, BackendErrorResponse, ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS, ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS } from './chunk-OETKXDGA.js';
6
+ import { hasMethodGroup } from './chunk-DKWO6LLX.js';
9
7
  import './chunk-TPC4EJLT.js';
10
- import { resolveManually, journalOf } from './chunk-2UPPX3FJ.js';
11
- import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-5K4XEAZV.js';
8
+ import { createSqliteReceiptStore } from './chunk-5TID36YG.js';
9
+ import { openSqliteDatabase } from './chunk-6EBDOH37.js';
10
+ import { PAYMENT_KEY_ENDPOINT_PREFIX } from './chunk-APC5BTQM.js';
11
+ import { resolveManually, journalOf } from './chunk-VSSSU4AU.js';
12
+ import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-3IEXJ7I3.js';
12
13
  import { MPP_DEFAULT_PAYMENT_FLOW, MPP_PROFILE } from './chunk-AA3FIEAR.js';
13
- import { PACKAGE_VERSION } from './chunk-M7NXVRU5.js';
14
- import { x402OfferName } from './chunk-4H2QLHQI.js';
15
- import { X402_DEFAULT_PAYMENT_FLOW, resolveDeploymentMode, requireX402Network } from './chunk-5R7DM5LM.js';
16
- import { PAYMENT_HEADER, AUTHORIZATION_HEADER, systemClock, extractReservedInputFields, isHttpProtocolAdapter, toErrorEnvelope, DELIVERY_SUMMARY_META_KEY, toDeliverySummary, toPaymentRequiredEnvelope, NOOP_LOGGER, parseAuthorizationHeader, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PAYMENT_INPUT_FIELD, AUTHORIZATION_INPUT_FIELD, parseAuthorizationSubmission, TRANSACTION_STATES } from './chunk-IDY2735M.js';
17
- import { CommerceError, isCommerceError, toLogInfo, toCommerceError } from './chunk-SYQLJXIU.js';
14
+ import { x402OfferName } from './chunk-AGQ4U7IN.js';
15
+ import { X402_DEFAULT_PAYMENT_FLOW, resolveDeploymentMode, requireX402Network } from './chunk-66NTYSXI.js';
16
+ import { PACKAGE_VERSION } from './chunk-ZCW56PZ3.js';
17
+ import { PAYMENT_HEADER, AUTHORIZATION_HEADER, systemClock, extractReservedInputFields, isHttpProtocolAdapter, toErrorEnvelope, DELIVERY_SUMMARY_META_KEY, toDeliverySummary, toPaymentRequiredEnvelope, NOOP_LOGGER, parseAuthorizationHeader, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PAYMENT_INPUT_FIELD, AUTHORIZATION_INPUT_FIELD, parseAuthorizationSubmission, TRANSACTION_STATES } from './chunk-55AI6CLW.js';
18
+ import { CommerceError, isCommerceError, toLogInfo, toCommerceError } from './chunk-C5YISPT6.js';
18
19
  import { isRecord } from './chunk-3M6U7ILB.js';
19
20
  import { createHash, randomUUID } from 'crypto';
20
21
  import { z } from 'zod';
@@ -164,7 +165,7 @@ function assertNoContinuation(params) {
164
165
  const message = params.message;
165
166
  if (params.taskId !== void 0 || message.taskId !== void 0) {
166
167
  throw unsupported(
167
- "Task not found: tasks are not persisted, so send a request with no taskId.",
168
+ "Task not found: only a task waiting for payment can be continued, so send a request with no taskId.",
168
169
  A2A_ERROR_TASK_NOT_FOUND
169
170
  );
170
171
  }
@@ -264,6 +265,11 @@ function requestsX402Extension(header2) {
264
265
  (value) => value.split(",").some((uri) => uri.trim() === A2A_X402_EXTENSION_URI)
265
266
  );
266
267
  }
268
+ function expiryMs(nowMs, expiresAt) {
269
+ const requested = expiresAt !== void 0 ? Date.parse(expiresAt) : Number.NaN;
270
+ const ttl = Number.isFinite(requested) ? requested - nowMs : DEFAULT_PENDING_TTL_MS;
271
+ return nowMs + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);
272
+ }
267
273
  function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
268
274
  const tasks = /* @__PURE__ */ new Map();
269
275
  const now = () => clock.now().getTime();
@@ -273,28 +279,27 @@ function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
273
279
  if (pending.expiresAtMs <= at) tasks.delete(taskId);
274
280
  }
275
281
  }
282
+ function get(taskId) {
283
+ const pending = tasks.get(taskId);
284
+ if (pending === void 0) return void 0;
285
+ if (pending.expiresAtMs <= now()) {
286
+ tasks.delete(taskId);
287
+ return void 0;
288
+ }
289
+ return pending;
290
+ }
276
291
  return {
277
- /** Holds a purchase until `expiresAt`; returns false, holding nothing, when full */
278
292
  put(taskId, pending, expiresAt) {
279
293
  purgeExpired();
280
294
  if (tasks.size >= maxEntries) return false;
281
- const requested = expiresAt !== void 0 ? Date.parse(expiresAt) : Number.NaN;
282
- const ttl = Number.isFinite(requested) ? requested - now() : DEFAULT_PENDING_TTL_MS;
283
- const expiresAtMs = now() + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);
284
- tasks.set(taskId, { ...pending, expiresAtMs });
295
+ tasks.set(taskId, { ...pending, expiresAtMs: expiryMs(now(), expiresAt) });
285
296
  return true;
286
297
  },
287
- get(taskId) {
288
- const pending = tasks.get(taskId);
289
- if (pending === void 0) return void 0;
290
- if (pending.expiresAtMs <= now()) {
291
- tasks.delete(taskId);
292
- return void 0;
293
- }
294
- return pending;
295
- },
296
- delete(taskId) {
298
+ get,
299
+ take(taskId) {
300
+ const pending = get(taskId);
297
301
  tasks.delete(taskId);
302
+ return pending;
298
303
  },
299
304
  size() {
300
305
  return tasks.size;
@@ -304,6 +309,73 @@ function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
304
309
  }
305
310
  };
306
311
  }
312
+ function createStoredPendingPayments(store, clock, maxTasks = MAX_PENDING_PAYMENTS) {
313
+ const mandates = /* @__PURE__ */ new Map();
314
+ const now = () => clock.now().getTime();
315
+ function purgeExpired() {
316
+ const at = now();
317
+ for (const [taskId, held] of mandates) {
318
+ if (held.expiresAtMs <= at) mandates.delete(taskId);
319
+ }
320
+ }
321
+ function toPending(task2) {
322
+ const { contextId, network } = task2.adapterData ?? {};
323
+ if (task2.protocol !== "a2a" || typeof contextId !== "string") return void 0;
324
+ purgeExpired();
325
+ const authorization = mandates.get(task2.id)?.authorization;
326
+ return {
327
+ contextId,
328
+ resourceId: task2.resourceId,
329
+ input: task2.input,
330
+ ...authorization !== void 0 ? { authorization } : {},
331
+ ...typeof network === "string" ? { network } : {},
332
+ expiresAtMs: Date.parse(task2.expiresAt)
333
+ };
334
+ }
335
+ return {
336
+ async put(taskId, pending, expiresAt) {
337
+ const expiresAtMs = expiryMs(now(), expiresAt);
338
+ const held = await store.putPendingTask(
339
+ {
340
+ id: taskId,
341
+ protocol: "a2a",
342
+ resourceId: pending.resourceId,
343
+ input: pending.input,
344
+ adapterData: {
345
+ contextId: pending.contextId,
346
+ ...pending.network !== void 0 ? { network: pending.network } : {}
347
+ },
348
+ expiresAt: new Date(expiresAtMs).toISOString()
349
+ },
350
+ { maxTasks }
351
+ );
352
+ purgeExpired();
353
+ mandates.delete(taskId);
354
+ if (held && pending.authorization !== void 0) {
355
+ mandates.set(taskId, { authorization: pending.authorization, expiresAtMs });
356
+ }
357
+ return held;
358
+ },
359
+ async get(taskId) {
360
+ const task2 = await store.getPendingTask(taskId);
361
+ return task2 !== void 0 ? toPending(task2) : void 0;
362
+ },
363
+ async take(taskId) {
364
+ const task2 = await store.takePendingTask(taskId);
365
+ if (task2 === void 0) return void 0;
366
+ const pending = toPending(task2);
367
+ if (pending === void 0) {
368
+ await store.putPendingTask(task2, { maxTasks: Number.MAX_SAFE_INTEGER });
369
+ return void 0;
370
+ }
371
+ mandates.delete(taskId);
372
+ return pending;
373
+ },
374
+ clear() {
375
+ mandates.clear();
376
+ }
377
+ };
378
+ }
307
379
  function readPaymentSubmission(message) {
308
380
  const metadata = isRecord(message) ? message["metadata"] : void 0;
309
381
  if (!isRecord(metadata)) return void 0;
@@ -345,7 +417,8 @@ function paymentFailureMetadata(error, network) {
345
417
  [X402_PAYMENT_RECEIPTS_KEY]: [settled]
346
418
  };
347
419
  }
348
- const code = error.code.startsWith("PAYMENT_") ? x402ErrorCode(error.code, error.details?.["reason"], error.details?.["network"]) : error.code.toLowerCase();
420
+ const reason = error.details?.["reason"];
421
+ const code = error.code.startsWith("PAYMENT_") || typeof reason === "string" && reason.startsWith("payment_identifier_") ? x402ErrorCode(error.code, reason, error.details?.["network"]) : error.code.toLowerCase();
349
422
  const failure = settlementFailure(error.details);
350
423
  const receipt = failure["network"] === "" && network !== void 0 ? { ...failure, network } : failure;
351
424
  return {
@@ -545,7 +618,7 @@ async function resumePayment(context, pendingPayments, id, params) {
545
618
  const message = isRecord(params) ? params["message"] : void 0;
546
619
  const taskId = isRecord(message) ? message["taskId"] : void 0;
547
620
  if (context === void 0 || typeof taskId !== "string") return void 0;
548
- const pending = pendingPayments?.get(taskId);
621
+ const pending = await pendingPayments?.get(taskId);
549
622
  if (pending === void 0) return void 0;
550
623
  const messageId = isRecord(message) ? message["messageId"] : void 0;
551
624
  if (typeof messageId !== "string" || messageId.length === 0) {
@@ -565,19 +638,21 @@ async function resumePayment(context, pendingPayments, id, params) {
565
638
  `For a pending task, set "${X402_PAYMENT_STATUS_KEY}" to "payment-submitted" and provide a "${X402_PAYMENT_PAYLOAD_KEY}" object, or set it to "payment-rejected".`
566
639
  );
567
640
  }
568
- let authorization = pending.authorization;
569
- if (authorization === void 0 && submission.kind === "submitted") {
641
+ let followUp;
642
+ if (pending.authorization === void 0 && submission.kind === "submitted") {
570
643
  try {
571
- authorization = readFollowUpAuthorization(message);
644
+ followUp = readFollowUpAuthorization(message);
572
645
  } catch (err) {
573
646
  return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message);
574
647
  }
575
648
  }
576
- pendingPayments?.delete(taskId);
649
+ const taken = await pendingPayments?.take(taskId);
650
+ if (taken === void 0) return void 0;
651
+ const authorization = taken.authorization ?? followUp;
577
652
  const statusMessageId = context.ids.next("a2a-msg");
578
653
  const identity = {
579
654
  taskId,
580
- contextId: pending.contextId,
655
+ contextId: taken.contextId,
581
656
  artifactId: context.ids.next("a2a-artifact"),
582
657
  statusMessageId,
583
658
  timestamp: context.clock.nowIso()
@@ -585,7 +660,7 @@ async function resumePayment(context, pendingPayments, id, params) {
585
660
  if (submission.kind === "rejected") {
586
661
  const declined = {
587
662
  id: taskId,
588
- contextId: pending.contextId,
663
+ contextId: taken.contextId,
589
664
  status: { state: A2A_TASK_STATE_FAILED, timestamp: identity.timestamp },
590
665
  artifacts: []
591
666
  };
@@ -603,12 +678,23 @@ async function resumePayment(context, pendingPayments, id, params) {
603
678
  id,
604
679
  await payPending(
605
680
  context,
606
- { ...pending, ...authorization !== void 0 ? { authorization } : {} },
681
+ { ...taken, ...authorization !== void 0 ? { authorization } : {} },
607
682
  submission.payload,
608
683
  identity
609
684
  )
610
685
  );
611
686
  }
687
+ function withoutRetryDelay(error) {
688
+ if (error.details?.["reason"] !== "payment_identifier_in_flight") return error;
689
+ const { retryAfterSeconds: _delay, ...details } = error.details;
690
+ return new CommerceError(error.code, error.message, {
691
+ httpStatus: error.httpStatus,
692
+ retryable: false,
693
+ details,
694
+ ...error.requestId !== void 0 ? { requestId: error.requestId } : {},
695
+ ...error.resourceId !== void 0 ? { resourceId: error.resourceId } : {}
696
+ });
697
+ }
612
698
  async function payPending(context, pending, payload, identity) {
613
699
  const requestId = context.ids.next("a2a");
614
700
  const request = {
@@ -637,16 +723,19 @@ async function payPending(context, pending, payload, identity) {
637
723
  }
638
724
  error = new CommerceError("PAYMENT_INVALID", "The payment was not accepted.", { requestId });
639
725
  } catch (err) {
640
- error = toCommerceError(err);
726
+ error = withoutRetryDelay(toCommerceError(err));
641
727
  context.logger.warn(
642
728
  { resourceId: pending.resourceId, requestId, err: toLogInfo(error) },
643
729
  "a2a adapter: x402 extension payment failed"
644
730
  );
645
731
  }
646
732
  const metadata = paymentFailureMetadata(error, pending.network);
733
+ const reason = error.details?.["reason"];
647
734
  let text = "Payment failed.";
648
735
  if (metadata[X402_PAYMENT_STATUS_KEY] === "payment-completed") {
649
736
  text = "Payment settled, but the resource could not be delivered.";
737
+ } else if (typeof reason === "string" && reason.startsWith("payment_identifier_")) {
738
+ text = error.message;
650
739
  } else if (!error.code.startsWith("PAYMENT_")) {
651
740
  text = "The resource could not be delivered.";
652
741
  }
@@ -667,6 +756,7 @@ var A2aProtocolAdapter = class {
667
756
  agentName;
668
757
  agentDescription;
669
758
  agentVersion;
759
+ store;
670
760
  context;
671
761
  started = false;
672
762
  // The card lists only a2a-exposed resources, but a caller can name any id,
@@ -684,6 +774,7 @@ var A2aProtocolAdapter = class {
684
774
  this.agentName = options.agentName ?? A2A_DEFAULT_AGENT_NAME;
685
775
  this.agentDescription = options.agentDescription ?? DEFAULT_AGENT_DESCRIPTION;
686
776
  this.agentVersion = options.agentVersion ?? PACKAGE_VERSION;
777
+ this.store = options.store;
687
778
  this.descriptor = buildDescriptor(PACKAGE_VERSION);
688
779
  this.additionalHttpRoutes = [
689
780
  {
@@ -715,7 +806,7 @@ var A2aProtocolAdapter = class {
715
806
  mountPath: this.mountPath,
716
807
  resources
717
808
  });
718
- this.pendingPayments = createPendingPayments(context.clock);
809
+ this.pendingPayments = hasMethodGroup(this.store, "pending_tasks") ? createStoredPendingPayments(this.store, context.clock) : createPendingPayments(context.clock);
719
810
  this.cardBody = JSON.stringify(this.card);
720
811
  this.cardEtag = `"${createHash("sha256").update(this.cardBody).digest("base64url")}"`;
721
812
  this.started = true;
@@ -916,7 +1007,7 @@ var A2aProtocolAdapter = class {
916
1007
  return taskResult(id, task2);
917
1008
  }
918
1009
  const network = outcome.requirement.network;
919
- const held = this.pendingPayments?.put(
1010
+ const held = await this.pendingPayments?.put(
920
1011
  identity.taskId,
921
1012
  {
922
1013
  contextId: identity.contextId,
@@ -1087,9 +1178,16 @@ function sha256(value) {
1087
1178
  return createHash("sha256").update(value, "utf8").digest("hex");
1088
1179
  }
1089
1180
 
1181
+ // src/core/idempotency-key.ts
1182
+ var MAX_IDEMPOTENCY_KEY_LENGTH = 255;
1183
+ var USABLE_KEY = new RegExp(`^[\\x20-\\x7e]{1,${MAX_IDEMPOTENCY_KEY_LENGTH}}$`);
1184
+ function isUsableIdempotencyKey(value) {
1185
+ return USABLE_KEY.test(value);
1186
+ }
1187
+
1090
1188
  // src/protocols/acp/idempotency/store.ts
1091
1189
  var SCHEMA_VERSION = 2;
1092
- var ACP_MAX_IDEMPOTENCY_KEY_LENGTH = 255;
1190
+ var ACP_MAX_IDEMPOTENCY_KEY_LENGTH = MAX_IDEMPOTENCY_KEY_LENGTH;
1093
1191
  function createAcpIdempotencyStore(options) {
1094
1192
  const logger = options.logger ?? NOOP_LOGGER;
1095
1193
  const now = options.now ?? (() => Date.now());
@@ -1183,23 +1281,22 @@ function createAcpIdempotencyStore(options) {
1183
1281
  };
1184
1282
  }
1185
1283
  function resolveOrphanedClaims(db, logger, release) {
1284
+ const { changes } = release ? db.prepare("DELETE FROM acp_idempotency WHERE state = 'in_flight'").run() : db.prepare("UPDATE acp_idempotency SET state = 'unresolved' WHERE state = 'in_flight'").run();
1285
+ warnOrphanedClaims(logger, changes, release);
1286
+ }
1287
+ function warnOrphanedClaims(logger, count, release) {
1288
+ if (count === 0) return;
1186
1289
  if (release) {
1187
- const { changes: changes2 } = db.prepare("DELETE FROM acp_idempotency WHERE state = 'in_flight'").run();
1188
- if (changes2 > 0) {
1189
- logger.warn(
1190
- { released: changes2 },
1191
- "acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled"
1192
- );
1193
- }
1194
- return;
1195
- }
1196
- const { changes } = db.prepare("UPDATE acp_idempotency SET state = 'unresolved' WHERE state = 'in_flight'").run();
1197
- if (changes > 0) {
1198
1290
  logger.warn(
1199
- { unresolved: changes },
1200
- "acp idempotency: marked claims left in flight by an earlier process as unresolved; reconcile these operations against the merchant before trusting a retry"
1291
+ { released: count },
1292
+ "acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled"
1201
1293
  );
1294
+ return;
1202
1295
  }
1296
+ logger.warn(
1297
+ { unresolved: count },
1298
+ "acp idempotency: marked claims left in flight by an earlier process as unresolved; reconcile these operations against the merchant before trusting a retry"
1299
+ );
1203
1300
  }
1204
1301
  function migrate(db, logger) {
1205
1302
  const current = db.pragma("user_version", { simple: true });
@@ -5511,9 +5608,6 @@ function forwardedHeaders(req, requestId) {
5511
5608
  }
5512
5609
  return forwarded;
5513
5610
  }
5514
- function isUsableIdempotencyKey(value) {
5515
- return value.length > 0 && value.length <= ACP_MAX_IDEMPOTENCY_KEY_LENGTH && isVisibleAscii(value);
5516
- }
5517
5611
  function normalizeRequestId(value) {
5518
5612
  if (value === void 0) return void 0;
5519
5613
  const trimmed = value.trim().slice(0, ACP_MAX_REQUEST_ID_LENGTH);
@@ -5754,6 +5848,27 @@ function reachedFor(error) {
5754
5848
  function notReached(failure) {
5755
5849
  return { response: asResponse(failure), reached: "no" };
5756
5850
  }
5851
+ function backendOverReceiptStore(store, clock, retentionHours) {
5852
+ const retentionMs = retentionHours * 60 * 60 * 1e3;
5853
+ return {
5854
+ claim: (scope, fingerprint) => store.claimIdempotencyKey(
5855
+ scope,
5856
+ fingerprint,
5857
+ new Date(clock.now().getTime() + retentionMs).toISOString()
5858
+ ),
5859
+ complete: (scope, { status, body }) => store.updateIdempotencyKey(scope, { kind: "completed", status, body }),
5860
+ markUnresolved: (scope) => store.updateIdempotencyKey(scope, { kind: "unresolved" }),
5861
+ release: (scope) => store.updateIdempotencyKey(scope, { kind: "released" })
5862
+ };
5863
+ }
5864
+ function backendOverFileStore(store) {
5865
+ return {
5866
+ claim: async (scope, fingerprint) => store.claim(scope, fingerprint),
5867
+ complete: async (scope, response) => store.complete(scope, response),
5868
+ markUnresolved: async (scope) => store.markUnresolved(scope),
5869
+ release: async (scope) => store.release(scope)
5870
+ };
5871
+ }
5757
5872
  var AcpProtocolAdapter = class {
5758
5873
  name = "acp";
5759
5874
  mountPath;
@@ -5768,7 +5883,10 @@ var AcpProtocolAdapter = class {
5768
5883
  */
5769
5884
  deployment;
5770
5885
  discoveryMetadata;
5886
+ store;
5771
5887
  idempotency;
5888
+ // Track the file opened by this adapter so borrowed receipt stores stay open
5889
+ fileStore;
5772
5890
  resources = /* @__PURE__ */ new Map();
5773
5891
  context;
5774
5892
  started = false;
@@ -5780,6 +5898,7 @@ var AcpProtocolAdapter = class {
5780
5898
  this.isAuthorized = createBearerCheck(options.token);
5781
5899
  this.operations = options.operations;
5782
5900
  this.idempotencyOptions = options.idempotency;
5901
+ this.store = options.store;
5783
5902
  this.discoveryMetadata = options.discovery;
5784
5903
  this.descriptor = buildDescriptor2(PACKAGE_VERSION);
5785
5904
  this.additionalHttpRoutes = [
@@ -5824,12 +5943,7 @@ var AcpProtocolAdapter = class {
5824
5943
  }
5825
5944
  this.resources = resolved;
5826
5945
  this.deployment = context.publicBaseUrl;
5827
- this.idempotency = createAcpIdempotencyStore({
5828
- path: this.idempotencyOptions.path,
5829
- retentionHours: this.idempotencyOptions.retentionHours,
5830
- releaseOrphans: this.idempotencyOptions.merchantIdempotent === true,
5831
- logger: context.logger
5832
- });
5946
+ this.idempotency = await this.openIdempotency(context);
5833
5947
  this.discovery = document;
5834
5948
  this.started = true;
5835
5949
  context.logger.info(
@@ -5841,6 +5955,32 @@ var AcpProtocolAdapter = class {
5841
5955
  "acp adapter started"
5842
5956
  );
5843
5957
  }
5958
+ // Recover claims at adapter start, not when the shared store opens for
5959
+ // another consumer
5960
+ async openIdempotency(context) {
5961
+ const { path, retentionHours, merchantIdempotent } = this.idempotencyOptions;
5962
+ const release = merchantIdempotent === true;
5963
+ const store = this.store;
5964
+ if (hasMethodGroup(store, "idempotency_claims")) {
5965
+ const recovered = await store.recoverIdempotencyKeys({ release, endpointPrefix: "/" });
5966
+ warnOrphanedClaims(context.logger, recovered, release);
5967
+ return backendOverReceiptStore(store, context.clock, retentionHours);
5968
+ }
5969
+ if (path === void 0) {
5970
+ throw new CommerceError(
5971
+ "CONFIG_INVALID",
5972
+ "ACP idempotency needs a receipt store with idempotency methods or a file - set protocols.acp.idempotency.path",
5973
+ { details: { path: "protocols.acp.idempotency.path" } }
5974
+ );
5975
+ }
5976
+ this.fileStore = createAcpIdempotencyStore({
5977
+ path,
5978
+ retentionHours,
5979
+ releaseOrphans: release,
5980
+ logger: context.logger
5981
+ });
5982
+ return backendOverFileStore(this.fileStore);
5983
+ }
5844
5984
  /** `GET /.well-known/acp.json`: public, unauthenticated, cacheable */
5845
5985
  async handleDiscovery(req, res) {
5846
5986
  try {
@@ -5918,7 +6058,7 @@ var AcpProtocolAdapter = class {
5918
6058
  return (await this.runCheckout(request)).response;
5919
6059
  }
5920
6060
  const scope = { deployment, endpoint: request.route.path, key };
5921
- const claim = store.claim(scope, requestFingerprint(request.body));
6061
+ const claim = await store.claim(scope, requestFingerprint(request.body));
5922
6062
  switch (claim.kind) {
5923
6063
  case "in-flight":
5924
6064
  return {
@@ -5957,15 +6097,15 @@ var AcpProtocolAdapter = class {
5957
6097
  try {
5958
6098
  outcome = await this.runCheckout(request, operationKey(scope));
5959
6099
  } catch (err) {
5960
- store.markUnresolved(scope);
6100
+ await store.markUnresolved(scope);
5961
6101
  throw err;
5962
6102
  }
5963
6103
  if (outcome.response.status < 500) {
5964
- store.complete(scope, outcome.response);
6104
+ await store.complete(scope, outcome.response);
5965
6105
  } else if (outcome.reached === "no" || this.idempotencyOptions.merchantIdempotent === true) {
5966
- store.release(scope);
6106
+ await store.release(scope);
5967
6107
  } else {
5968
- store.markUnresolved(scope);
6108
+ await store.markUnresolved(scope);
5969
6109
  }
5970
6110
  return outcome.response;
5971
6111
  }
@@ -6065,7 +6205,8 @@ var AcpProtocolAdapter = class {
6065
6205
  this.started = false;
6066
6206
  this.discovery = void 0;
6067
6207
  this.resources = /* @__PURE__ */ new Map();
6068
- this.idempotency?.close();
6208
+ this.fileStore?.close();
6209
+ this.fileStore = void 0;
6069
6210
  this.idempotency = void 0;
6070
6211
  this.deployment = void 0;
6071
6212
  this.context = void 0;
@@ -6093,7 +6234,12 @@ var SECRET_FIELD_NAMES = [
6093
6234
  "adminToken",
6094
6235
  "token"
6095
6236
  ];
6096
- var SECRET_HEADERS = ["authorization", PAYMENT_HEADER, AUTHORIZATION_HEADER];
6237
+ var SECRET_HEADERS = [
6238
+ "authorization",
6239
+ PAYMENT_HEADER,
6240
+ AUTHORIZATION_HEADER,
6241
+ "idempotency-key"
6242
+ ];
6097
6243
  var REDACT_PATHS = [
6098
6244
  ...SECRET_HEADERS.map((name) => `req.headers[${JSON.stringify(name)}]`),
6099
6245
  ...SECRET_FIELD_NAMES,
@@ -6918,6 +7064,7 @@ async function handleInvoke(request, reply, options) {
6918
7064
  paymentMethod = resource.paymentMethods[0];
6919
7065
  const paymentValue = paymentProof(request, paymentMethod);
6920
7066
  const payment = paymentValue !== void 0 && paymentMethod !== void 0 ? { method: paymentMethod, payload: paymentValue } : void 0;
7067
+ const retryKey = paymentMethod === "mpp" && resource.idempotency?.redelivery !== void 0 ? mppRetryKey(request, resourceId) : void 0;
6921
7068
  const authorization = parseAuthorizationHeader(
6922
7069
  request.headers[AUTHORIZATION_HEADER],
6923
7070
  request.id
@@ -6930,6 +7077,7 @@ async function handleInvoke(request, reply, options) {
6930
7077
  protocol: "http",
6931
7078
  receivedAt: options.clock.nowIso(),
6932
7079
  ...payment !== void 0 ? { payment } : {},
7080
+ ...retryKey !== void 0 ? { retryKey } : {},
6933
7081
  ...authorization !== void 0 ? { authorization } : {},
6934
7082
  ...digest !== void 0 ? { metadata: { [CONTENT_DIGEST_METADATA_KEY]: digest } } : {}
6935
7083
  };
@@ -6968,11 +7116,13 @@ async function handleInvoke(request, reply, options) {
6968
7116
  encodeHeaderDocument(settlementResponse(outcome.payment))
6969
7117
  );
6970
7118
  const receipt = outcome.payment.metadata?.["receipt"];
6971
- if (outcome.payment.provider === "mpp" && typeof receipt === "string") {
7119
+ const success = outcome.backendStatus >= 200 && outcome.backendStatus < 300;
7120
+ if (outcome.payment.provider === "mpp" && typeof receipt === "string" && (success || outcome.redelivered !== true)) {
6972
7121
  reply.header("payment-receipt", receipt);
6973
7122
  }
6974
7123
  reply.header("cache-control", "private");
6975
7124
  }
7125
+ if (outcome.redelivered === true) reply.header("idempotent-replayed", "true");
6976
7126
  const contentType = relayedContentType(outcome.headers?.["content-type"], outcome.body);
6977
7127
  if (contentType !== void 0) reply.type(contentType);
6978
7128
  if (typeof outcome.body === "string") {
@@ -7012,9 +7162,14 @@ var MPP_PROBLEM_CODES = /* @__PURE__ */ new Set([
7012
7162
  ]);
7013
7163
  function sendInvokeError(reply, error, paymentMethod) {
7014
7164
  const details = error.details;
7165
+ const reason = typeof details?.["reason"] === "string" ? details["reason"] : void 0;
7015
7166
  if (PROVIDER_UNAVAILABLE_CODES.has(error.code)) {
7016
7167
  reply.header("retry-after", String(PROVIDER_RETRY_AFTER_SECONDS));
7017
7168
  }
7169
+ const retryAfter = details?.["retryAfterSeconds"];
7170
+ if (typeof retryAfter === "number" && Number.isSafeInteger(retryAfter) && retryAfter >= 0) {
7171
+ reply.header("retry-after", String(retryAfter));
7172
+ }
7018
7173
  const settled = settlementResponseFromDetails(details);
7019
7174
  if (settled !== void 0) {
7020
7175
  reply.header(PAYMENT_RESPONSE_HEADER, encodeHeaderDocument(settled));
@@ -7038,12 +7193,12 @@ function sendInvokeError(reply, error, paymentMethod) {
7038
7193
  reply.header("cache-control", "no-store");
7039
7194
  }
7040
7195
  const envelope = toErrorEnvelope(error);
7041
- if (paymentMethod === "mpp" && MPP_PROBLEM_CODES.has(error.code)) {
7196
+ if (paymentMethod === "mpp" && (MPP_PROBLEM_CODES.has(error.code) || reason?.startsWith("payment_identifier_") === true)) {
7042
7197
  const { status: _envelopeStatus, ...members } = envelope;
7043
- const reason = typeof details?.["reason"] === "string" ? details["reason"] : void 0;
7044
- reply.header("content-type", "application/problem+json").status(error.httpStatus).send({
7045
- ...mppProblem(error.code, error.httpStatus, reason),
7046
- status: error.httpStatus,
7198
+ const problemStatus = reason === "payment_identifier_conflict" ? 422 : error.httpStatus;
7199
+ reply.header("content-type", "application/problem+json").status(problemStatus).send({
7200
+ ...mppProblem(error.code, problemStatus, reason),
7201
+ status: problemStatus,
7047
7202
  // The reason token stays in `message` and `details.reason`
7048
7203
  detail: mppProblemDetail(reason, error.message),
7049
7204
  ...members
@@ -7053,6 +7208,21 @@ function sendInvokeError(reply, error, paymentMethod) {
7053
7208
  const status = paymentMethod === "x402" ? x402RefusalStatus(error.code, error.httpStatus, details?.["reason"]) : error.httpStatus;
7054
7209
  reply.status(status).send(envelope);
7055
7210
  }
7211
+ var SF_STRING = /^"((?:[\x20\x21\x23-\x5b\x5d-\x7e]|\\["\\])*)"$/;
7212
+ function mppRetryKey(request, resourceId) {
7213
+ const value = request.headers["idempotency-key"];
7214
+ if (value === void 0) return void 0;
7215
+ if (typeof value === "string") {
7216
+ const trimmed = value.trim();
7217
+ const key = trimmed.startsWith('"') ? SF_STRING.exec(trimmed)?.[1]?.replace(/\\(["\\])/g, "$1") : trimmed;
7218
+ if (key !== void 0 && isUsableIdempotencyKey(key)) return key;
7219
+ }
7220
+ throw new CommerceError(
7221
+ "INPUT_INVALID",
7222
+ "The Idempotency-Key header must be 1 to 255 printable ASCII characters",
7223
+ { requestId: request.id, resourceId, details: { reason: "payment_identifier_invalid" } }
7224
+ );
7225
+ }
7056
7226
  function paymentProof(request, method) {
7057
7227
  if (method === "mpp") {
7058
7228
  const value2 = request.headers.authorization;
@@ -7113,6 +7283,25 @@ function withProviderBackedMethodsFirst(resource, providers) {
7113
7283
  ];
7114
7284
  return ordered.some((method, i) => method !== resource.paymentMethods[i]) ? { ...resource, paymentMethods: ordered } : resource;
7115
7285
  }
7286
+ async function recoverPaymentKeys(store, logger) {
7287
+ if (!hasMethodGroup(store, "idempotency_claims") || !hasMethodGroup(store, "response_redelivery")) {
7288
+ return;
7289
+ }
7290
+ let recovered;
7291
+ try {
7292
+ recovered = await store.recoverIdempotencyKeys({
7293
+ release: false,
7294
+ endpointPrefix: PAYMENT_KEY_ENDPOINT_PREFIX
7295
+ });
7296
+ } catch (error) {
7297
+ throw new CommerceError("STORAGE_ERROR", "Payment retry keys could not be recovered", {
7298
+ cause: error
7299
+ });
7300
+ }
7301
+ if (recovered > 0) {
7302
+ logger.warn({ recovered }, "Payment retry keys left in flight are now unresolved");
7303
+ }
7304
+ }
7116
7305
  async function createGateway(options) {
7117
7306
  const clock = options.clock ?? systemClock;
7118
7307
  const ids = options.ids ?? createDefaultIdGenerator();
@@ -7124,6 +7313,10 @@ async function createGateway(options) {
7124
7313
  (resource) => withProviderBackedMethodsFirst(resource, options.paymentProviders)
7125
7314
  )
7126
7315
  );
7316
+ for (const resource of resources.list()) {
7317
+ assertRetrySupport(resource, options.store, options.config.merchant.publicBaseUrl);
7318
+ }
7319
+ await recoverPaymentKeys(options.store, logger);
7127
7320
  const events = createStoreEventSink({ store: options.store, logger });
7128
7321
  const pipeline = createExecutionPipeline({
7129
7322
  resources,
@@ -7134,7 +7327,8 @@ async function createGateway(options) {
7134
7327
  events,
7135
7328
  logger,
7136
7329
  clock,
7137
- ids
7330
+ ids,
7331
+ deployment: options.config.merchant.publicBaseUrl
7138
7332
  });
7139
7333
  const server = Fastify({
7140
7334
  // Same cap as adapter mounts, which enforce it on the socket instead
@@ -7199,8 +7393,14 @@ async function createGateway(options) {
7199
7393
  return { url };
7200
7394
  },
7201
7395
  async close() {
7396
+ const sweep = setInterval(() => server.server.closeIdleConnections(), 100);
7397
+ sweep.unref();
7398
+ try {
7399
+ await server.close();
7400
+ } finally {
7401
+ clearInterval(sweep);
7402
+ }
7202
7403
  await stopAdapters(adapterRuntimes, logger);
7203
- await server.close();
7204
7404
  },
7205
7405
  server
7206
7406
  };
@@ -7221,17 +7421,32 @@ async function runGateway(options = {}) {
7221
7421
  const { core: logger } = createGatewayLogger({ name: config.merchant.id });
7222
7422
  const paymentProviders = await createConfiguredPaymentProviders(config.payments, logger);
7223
7423
  const ap2 = config.authorization?.ap2;
7224
- const ap2Module = ap2?.enabled ? await importOptionalPeer("authorization.ap2", () => import('./ap2-YAPLERSC.js')) : void 0;
7424
+ const ap2Module = ap2?.enabled ? await importOptionalPeer("authorization.ap2", () => import('./ap2-5FFGSW6F.js')) : void 0;
7225
7425
  const mcp = config.protocols.mcp;
7226
- const mcpModule = mcp.enabled ? await importOptionalPeer("protocols.mcp", () => import('./mcp-KZEMXLHR.js')) : void 0;
7426
+ const mcpModule = mcp.enabled ? await importOptionalPeer("protocols.mcp", () => import('./mcp-HHGNOUKE.js')) : void 0;
7427
+ const acp = config.protocols.acp;
7428
+ const ap2Replay = ap2?.enabled ? ap2.replay?.path : void 0;
7429
+ const acpIdempotency = acp.enabled ? acp.idempotency.path : void 0;
7227
7430
  const store = createSqliteReceiptStore({
7228
7431
  path: config.storage.receipts.path,
7229
- logger
7432
+ logger,
7433
+ legacyStores: {
7434
+ ...ap2Replay !== void 0 ? { ap2Replay } : {},
7435
+ ...acpIdempotency !== void 0 ? { acpIdempotency } : {},
7436
+ enabled: { ap2: ap2?.enabled === true, acp: acp.enabled }
7437
+ }
7230
7438
  });
7231
- await store.init();
7439
+ try {
7440
+ await store.init();
7441
+ } catch (error) {
7442
+ await store.close();
7443
+ throw error;
7444
+ }
7232
7445
  const authorizationProviders = [];
7233
7446
  if (ap2?.enabled && ap2Module !== void 0) {
7234
- authorizationProviders.push(ap2Module.createAp2AuthorizationProvider({ config: ap2, logger }));
7447
+ authorizationProviders.push(
7448
+ ap2Module.createAp2AuthorizationProvider({ config: ap2, logger, store })
7449
+ );
7235
7450
  }
7236
7451
  const paidWithoutProvider = config.resources.filter(
7237
7452
  (resource) => resource.pricing.type !== "free" && !resource.paymentMethods.some(
@@ -7254,11 +7469,11 @@ async function runGateway(options = {}) {
7254
7469
  mountPath: config.protocols.a2a.mountPath,
7255
7470
  // The Agent Card names the merchant, not the software: a client
7256
7471
  // picking between agents is choosing whose resources to buy
7257
- agentName: config.merchant.name
7472
+ agentName: config.merchant.name,
7473
+ store
7258
7474
  })
7259
7475
  );
7260
7476
  }
7261
- const acp = config.protocols.acp;
7262
7477
  if (acp.enabled) {
7263
7478
  protocolAdapters.push(
7264
7479
  createAcpAdapter({
@@ -7266,6 +7481,7 @@ async function runGateway(options = {}) {
7266
7481
  token: acp.auth.token,
7267
7482
  operations: acp.checkout.operations,
7268
7483
  idempotency: acp.idempotency,
7484
+ store,
7269
7485
  ...acp.discovery !== void 0 ? { discovery: acp.discovery } : {}
7270
7486
  })
7271
7487
  );
@@ -7322,7 +7538,10 @@ async function runGateway(options = {}) {
7322
7538
  }
7323
7539
  let shuttingDown = false;
7324
7540
  const shutdown = (signal) => {
7325
- if (shuttingDown) return;
7541
+ if (shuttingDown) {
7542
+ logger.warn({ signal }, "second signal, exiting without waiting for in-flight requests");
7543
+ process.exit(1);
7544
+ }
7326
7545
  shuttingDown = true;
7327
7546
  logger.info({ signal }, "shutting down");
7328
7547
  void (async () => {
@@ -7354,5 +7573,5 @@ function printStartupError(error) {
7354
7573
  }
7355
7574
 
7356
7575
  export { printStartupError, runGateway };
7357
- //# sourceMappingURL=run-ZTYPQI4D.js.map
7358
- //# sourceMappingURL=run-ZTYPQI4D.js.map
7576
+ //# sourceMappingURL=run-7KLKW3HE.js.map
7577
+ //# sourceMappingURL=run-7KLKW3HE.js.map