@devlab.group/agent-commerce 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +63 -11
  2. package/dist/ap2.d.ts +19 -6
  3. package/dist/ap2.js +56 -18
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-FKQK5XZA.js → chunk-DRLBML7Z.js} +13 -11
  6. package/dist/chunk-DRLBML7Z.js.map +1 -0
  7. package/dist/{chunk-VUCMBGUR.js → chunk-G3EYYHKF.js} +3 -3
  8. package/dist/{chunk-VUCMBGUR.js.map → chunk-G3EYYHKF.js.map} +1 -1
  9. package/dist/{chunk-3OTCFFFT.js → chunk-M52FBNJX.js} +3 -5
  10. package/dist/chunk-M52FBNJX.js.map +1 -0
  11. package/dist/chunk-M6BSXXTF.js +8 -0
  12. package/dist/chunk-M6BSXXTF.js.map +1 -0
  13. package/dist/{chunk-4K7FIBJM.js → chunk-M6MQ3FYS.js} +3 -3
  14. package/dist/{chunk-4K7FIBJM.js.map → chunk-M6MQ3FYS.js.map} +1 -1
  15. package/dist/chunk-M6WW6QIT.js +18 -0
  16. package/dist/chunk-M6WW6QIT.js.map +1 -0
  17. package/dist/cli/{ap2-YAPLERSC.js → ap2-2YMYA2H6.js} +57 -20
  18. package/dist/cli/ap2-2YMYA2H6.js.map +1 -0
  19. package/dist/cli/{chunk-5R7DM5LM.js → chunk-3NOMLMJW.js} +26 -26
  20. package/dist/cli/chunk-3NOMLMJW.js.map +1 -0
  21. package/dist/cli/chunk-4KLYFXMW.js +8 -0
  22. package/dist/cli/{chunk-M7NXVRU5.js.map → chunk-4KLYFXMW.js.map} +1 -1
  23. package/dist/cli/chunk-6R6WJ4FD.js +18 -0
  24. package/dist/cli/chunk-6R6WJ4FD.js.map +1 -0
  25. package/dist/cli/{chunk-2J2IQQ4X.js → chunk-AZL7RPFU.js} +37 -32
  26. package/dist/cli/chunk-AZL7RPFU.js.map +1 -0
  27. package/dist/cli/{chunk-JFVRG2HH.js → chunk-DHFMIBPG.js} +7 -7
  28. package/dist/cli/chunk-DHFMIBPG.js.map +1 -0
  29. package/dist/cli/{chunk-IDY2735M.js → chunk-GET3CZGR.js} +2 -2
  30. package/dist/cli/chunk-GET3CZGR.js.map +1 -0
  31. package/dist/cli/{chunk-QLUCNPRT.js → chunk-NSYSMDQN.js} +831 -169
  32. package/dist/cli/chunk-NSYSMDQN.js.map +1 -0
  33. package/dist/cli/{chunk-Z34UMZBB.js → chunk-PTL7SNOI.js} +83 -57
  34. package/dist/cli/chunk-PTL7SNOI.js.map +1 -0
  35. package/dist/cli/{chunk-2UPPX3FJ.js → chunk-TFV3K6YS.js} +75 -13
  36. package/dist/cli/chunk-TFV3K6YS.js.map +1 -0
  37. package/dist/cli/{chunk-NIU5EMSB.js → chunk-VJH6RYRK.js} +5 -5
  38. package/dist/cli/{chunk-NIU5EMSB.js.map → chunk-VJH6RYRK.js.map} +1 -1
  39. package/dist/cli/{chunk-QA2OPHBF.js → chunk-YOF7IK4V.js} +14 -13
  40. package/dist/cli/chunk-YOF7IK4V.js.map +1 -0
  41. package/dist/cli/{chunk-4H2QLHQI.js → chunk-YWG2ZN3L.js} +3 -3
  42. package/dist/cli/{chunk-4H2QLHQI.js.map → chunk-YWG2ZN3L.js.map} +1 -1
  43. package/dist/cli/config-3K65QJ22.js +12 -0
  44. package/dist/cli/{config-BWFMN2ZB.js.map → config-3K65QJ22.js.map} +1 -1
  45. package/dist/cli/index.js +524 -230
  46. package/dist/cli/index.js.map +1 -1
  47. package/dist/cli/{mcp-KZEMXLHR.js → mcp-6F64A7KE.js} +4 -4
  48. package/dist/cli/{mcp-KZEMXLHR.js.map → mcp-6F64A7KE.js.map} +1 -1
  49. package/dist/cli/payment-providers-2ITS6KNR.js +6 -0
  50. package/dist/cli/{payment-providers-SZL36H3Y.js.map → payment-providers-2ITS6KNR.js.map} +1 -1
  51. package/dist/cli/{provider-6TKB5ADJ.js → provider-5BGG5YKQ.js} +34 -16
  52. package/dist/cli/provider-5BGG5YKQ.js.map +1 -0
  53. package/dist/cli/receipts-I4IIE7U6.js +8 -0
  54. package/dist/cli/{receipts-ZGLJWMQG.js.map → receipts-I4IIE7U6.js.map} +1 -1
  55. package/dist/cli/reconcile-55WNCSFC.js +4 -0
  56. package/dist/cli/{reconcile-IC22MJD5.js.map → reconcile-55WNCSFC.js.map} +1 -1
  57. package/dist/cli/{run-ZTYPQI4D.js → run-2P6ZGFUE.js} +220 -73
  58. package/dist/cli/run-2P6ZGFUE.js.map +1 -0
  59. package/dist/cli/{x402-WLYBLODI.js → x402-4LPIIELI.js} +8 -8
  60. package/dist/cli/{x402-WLYBLODI.js.map → x402-4LPIIELI.js.map} +1 -1
  61. package/dist/index.d.ts +104 -201
  62. package/dist/index.js +1048 -262
  63. package/dist/index.js.map +1 -1
  64. package/dist/logger-CllGwQ8i.d.ts +19 -0
  65. package/dist/mcp.d.ts +3 -1
  66. package/dist/mcp.js +2 -1
  67. package/dist/mcp.js.map +1 -1
  68. package/dist/mpp.d.ts +2 -1
  69. package/dist/mpp.js +31 -12
  70. package/dist/mpp.js.map +1 -1
  71. package/dist/{protocol-adapter-DEXpdp8m.d.ts → protocol-adapter-1WbtM3xG.d.ts} +5 -132
  72. package/dist/{runtime-Dz2fSO-P.d.ts → runtime-B-kARa2f.d.ts} +5 -20
  73. package/dist/store-kIIMpUA-.d.ts +372 -0
  74. package/dist/testing.d.ts +51 -0
  75. package/dist/testing.js +1896 -0
  76. package/dist/testing.js.map +1 -0
  77. package/dist/transaction-Dv0UFGg5.d.ts +129 -0
  78. package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
  79. package/dist/x402.d.ts +2 -1
  80. package/dist/x402.js +5 -4
  81. package/dist/x402.js.map +1 -1
  82. package/package.json +5 -1
  83. package/dist/chunk-3OTCFFFT.js.map +0 -1
  84. package/dist/chunk-FKQK5XZA.js.map +0 -1
  85. package/dist/cli/ap2-YAPLERSC.js.map +0 -1
  86. package/dist/cli/chunk-2J2IQQ4X.js.map +0 -1
  87. package/dist/cli/chunk-2UPPX3FJ.js.map +0 -1
  88. package/dist/cli/chunk-5R7DM5LM.js.map +0 -1
  89. package/dist/cli/chunk-IDY2735M.js.map +0 -1
  90. package/dist/cli/chunk-JFVRG2HH.js.map +0 -1
  91. package/dist/cli/chunk-M7NXVRU5.js +0 -8
  92. package/dist/cli/chunk-QA2OPHBF.js.map +0 -1
  93. package/dist/cli/chunk-QLUCNPRT.js.map +0 -1
  94. package/dist/cli/chunk-Z34UMZBB.js.map +0 -1
  95. package/dist/cli/config-BWFMN2ZB.js +0 -12
  96. package/dist/cli/payment-providers-SZL36H3Y.js +0 -6
  97. package/dist/cli/provider-6TKB5ADJ.js.map +0 -1
  98. package/dist/cli/receipts-ZGLJWMQG.js +0 -8
  99. package/dist/cli/reconcile-IC22MJD5.js +0 -4
  100. package/dist/cli/run-ZTYPQI4D.js.map +0 -1
@@ -1,19 +1,20 @@
1
- import { createConfiguredPaymentProviders, importOptionalPeer } from './chunk-JFVRG2HH.js';
1
+ import { hasMethodGroup } from './chunk-6R6WJ4FD.js';
2
+ import { createConfiguredPaymentProviders, importOptionalPeer } from './chunk-DHFMIBPG.js';
2
3
  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';
4
+ 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-VJH6RYRK.js';
5
+ import { loadConfig } from './chunk-AZL7RPFU.js';
6
+ 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-PTL7SNOI.js';
8
7
  import './chunk-FHCFR2GS.js';
9
8
  import './chunk-TPC4EJLT.js';
10
- import { resolveManually, journalOf } from './chunk-2UPPX3FJ.js';
9
+ import { createSqliteReceiptStore } from './chunk-NSYSMDQN.js';
10
+ import { openSqliteDatabase } from './chunk-VJ4EO4LE.js';
11
+ import { resolveManually, journalOf } from './chunk-TFV3K6YS.js';
11
12
  import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-5K4XEAZV.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';
14
+ import { x402OfferName } from './chunk-YWG2ZN3L.js';
15
+ import { X402_DEFAULT_PAYMENT_FLOW, resolveDeploymentMode, requireX402Network } from './chunk-3NOMLMJW.js';
16
+ import { PACKAGE_VERSION } from './chunk-4KLYFXMW.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-GET3CZGR.js';
17
18
  import { CommerceError, isCommerceError, toLogInfo, toCommerceError } from './chunk-SYQLJXIU.js';
18
19
  import { isRecord } from './chunk-3M6U7ILB.js';
19
20
  import { createHash, randomUUID } from 'crypto';
@@ -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;
@@ -545,7 +617,7 @@ async function resumePayment(context, pendingPayments, id, params) {
545
617
  const message = isRecord(params) ? params["message"] : void 0;
546
618
  const taskId = isRecord(message) ? message["taskId"] : void 0;
547
619
  if (context === void 0 || typeof taskId !== "string") return void 0;
548
- const pending = pendingPayments?.get(taskId);
620
+ const pending = await pendingPayments?.get(taskId);
549
621
  if (pending === void 0) return void 0;
550
622
  const messageId = isRecord(message) ? message["messageId"] : void 0;
551
623
  if (typeof messageId !== "string" || messageId.length === 0) {
@@ -565,19 +637,21 @@ async function resumePayment(context, pendingPayments, id, params) {
565
637
  `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
638
  );
567
639
  }
568
- let authorization = pending.authorization;
569
- if (authorization === void 0 && submission.kind === "submitted") {
640
+ let followUp;
641
+ if (pending.authorization === void 0 && submission.kind === "submitted") {
570
642
  try {
571
- authorization = readFollowUpAuthorization(message);
643
+ followUp = readFollowUpAuthorization(message);
572
644
  } catch (err) {
573
645
  return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message);
574
646
  }
575
647
  }
576
- pendingPayments?.delete(taskId);
648
+ const taken = await pendingPayments?.take(taskId);
649
+ if (taken === void 0) return void 0;
650
+ const authorization = taken.authorization ?? followUp;
577
651
  const statusMessageId = context.ids.next("a2a-msg");
578
652
  const identity = {
579
653
  taskId,
580
- contextId: pending.contextId,
654
+ contextId: taken.contextId,
581
655
  artifactId: context.ids.next("a2a-artifact"),
582
656
  statusMessageId,
583
657
  timestamp: context.clock.nowIso()
@@ -585,7 +659,7 @@ async function resumePayment(context, pendingPayments, id, params) {
585
659
  if (submission.kind === "rejected") {
586
660
  const declined = {
587
661
  id: taskId,
588
- contextId: pending.contextId,
662
+ contextId: taken.contextId,
589
663
  status: { state: A2A_TASK_STATE_FAILED, timestamp: identity.timestamp },
590
664
  artifacts: []
591
665
  };
@@ -603,7 +677,7 @@ async function resumePayment(context, pendingPayments, id, params) {
603
677
  id,
604
678
  await payPending(
605
679
  context,
606
- { ...pending, ...authorization !== void 0 ? { authorization } : {} },
680
+ { ...taken, ...authorization !== void 0 ? { authorization } : {} },
607
681
  submission.payload,
608
682
  identity
609
683
  )
@@ -667,6 +741,7 @@ var A2aProtocolAdapter = class {
667
741
  agentName;
668
742
  agentDescription;
669
743
  agentVersion;
744
+ store;
670
745
  context;
671
746
  started = false;
672
747
  // The card lists only a2a-exposed resources, but a caller can name any id,
@@ -684,6 +759,7 @@ var A2aProtocolAdapter = class {
684
759
  this.agentName = options.agentName ?? A2A_DEFAULT_AGENT_NAME;
685
760
  this.agentDescription = options.agentDescription ?? DEFAULT_AGENT_DESCRIPTION;
686
761
  this.agentVersion = options.agentVersion ?? PACKAGE_VERSION;
762
+ this.store = options.store;
687
763
  this.descriptor = buildDescriptor(PACKAGE_VERSION);
688
764
  this.additionalHttpRoutes = [
689
765
  {
@@ -715,7 +791,7 @@ var A2aProtocolAdapter = class {
715
791
  mountPath: this.mountPath,
716
792
  resources
717
793
  });
718
- this.pendingPayments = createPendingPayments(context.clock);
794
+ this.pendingPayments = hasMethodGroup(this.store, "pending_tasks") ? createStoredPendingPayments(this.store, context.clock) : createPendingPayments(context.clock);
719
795
  this.cardBody = JSON.stringify(this.card);
720
796
  this.cardEtag = `"${createHash("sha256").update(this.cardBody).digest("base64url")}"`;
721
797
  this.started = true;
@@ -916,7 +992,7 @@ var A2aProtocolAdapter = class {
916
992
  return taskResult(id, task2);
917
993
  }
918
994
  const network = outcome.requirement.network;
919
- const held = this.pendingPayments?.put(
995
+ const held = await this.pendingPayments?.put(
920
996
  identity.taskId,
921
997
  {
922
998
  contextId: identity.contextId,
@@ -1183,23 +1259,22 @@ function createAcpIdempotencyStore(options) {
1183
1259
  };
1184
1260
  }
1185
1261
  function resolveOrphanedClaims(db, logger, release) {
1262
+ 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();
1263
+ warnOrphanedClaims(logger, changes, release);
1264
+ }
1265
+ function warnOrphanedClaims(logger, count, release) {
1266
+ if (count === 0) return;
1186
1267
  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
1268
  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"
1269
+ { released: count },
1270
+ "acp idempotency: freed claims left in flight by an earlier process; merchant deduplication is enabled"
1201
1271
  );
1272
+ return;
1202
1273
  }
1274
+ logger.warn(
1275
+ { unresolved: count },
1276
+ "acp idempotency: marked claims left in flight by an earlier process as unresolved; reconcile these operations against the merchant before trusting a retry"
1277
+ );
1203
1278
  }
1204
1279
  function migrate(db, logger) {
1205
1280
  const current = db.pragma("user_version", { simple: true });
@@ -5754,6 +5829,27 @@ function reachedFor(error) {
5754
5829
  function notReached(failure) {
5755
5830
  return { response: asResponse(failure), reached: "no" };
5756
5831
  }
5832
+ function backendOverReceiptStore(store, clock, retentionHours) {
5833
+ const retentionMs = retentionHours * 60 * 60 * 1e3;
5834
+ return {
5835
+ claim: (scope, fingerprint) => store.claimIdempotencyKey(
5836
+ scope,
5837
+ fingerprint,
5838
+ new Date(clock.now().getTime() + retentionMs).toISOString()
5839
+ ),
5840
+ complete: (scope, { status, body }) => store.updateIdempotencyKey(scope, { kind: "completed", status, body }),
5841
+ markUnresolved: (scope) => store.updateIdempotencyKey(scope, { kind: "unresolved" }),
5842
+ release: (scope) => store.updateIdempotencyKey(scope, { kind: "released" })
5843
+ };
5844
+ }
5845
+ function backendOverFileStore(store) {
5846
+ return {
5847
+ claim: async (scope, fingerprint) => store.claim(scope, fingerprint),
5848
+ complete: async (scope, response) => store.complete(scope, response),
5849
+ markUnresolved: async (scope) => store.markUnresolved(scope),
5850
+ release: async (scope) => store.release(scope)
5851
+ };
5852
+ }
5757
5853
  var AcpProtocolAdapter = class {
5758
5854
  name = "acp";
5759
5855
  mountPath;
@@ -5768,7 +5864,10 @@ var AcpProtocolAdapter = class {
5768
5864
  */
5769
5865
  deployment;
5770
5866
  discoveryMetadata;
5867
+ store;
5771
5868
  idempotency;
5869
+ // Track the file opened by this adapter so borrowed receipt stores stay open
5870
+ fileStore;
5772
5871
  resources = /* @__PURE__ */ new Map();
5773
5872
  context;
5774
5873
  started = false;
@@ -5780,6 +5879,7 @@ var AcpProtocolAdapter = class {
5780
5879
  this.isAuthorized = createBearerCheck(options.token);
5781
5880
  this.operations = options.operations;
5782
5881
  this.idempotencyOptions = options.idempotency;
5882
+ this.store = options.store;
5783
5883
  this.discoveryMetadata = options.discovery;
5784
5884
  this.descriptor = buildDescriptor2(PACKAGE_VERSION);
5785
5885
  this.additionalHttpRoutes = [
@@ -5824,12 +5924,7 @@ var AcpProtocolAdapter = class {
5824
5924
  }
5825
5925
  this.resources = resolved;
5826
5926
  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
- });
5927
+ this.idempotency = await this.openIdempotency(context);
5833
5928
  this.discovery = document;
5834
5929
  this.started = true;
5835
5930
  context.logger.info(
@@ -5841,6 +5936,32 @@ var AcpProtocolAdapter = class {
5841
5936
  "acp adapter started"
5842
5937
  );
5843
5938
  }
5939
+ // Recover claims at adapter start, not when the shared store opens for
5940
+ // another consumer
5941
+ async openIdempotency(context) {
5942
+ const { path, retentionHours, merchantIdempotent } = this.idempotencyOptions;
5943
+ const release = merchantIdempotent === true;
5944
+ const store = this.store;
5945
+ if (hasMethodGroup(store, "idempotency_claims")) {
5946
+ const recovered = await store.recoverIdempotencyKeys({ release });
5947
+ warnOrphanedClaims(context.logger, recovered, release);
5948
+ return backendOverReceiptStore(store, context.clock, retentionHours);
5949
+ }
5950
+ if (path === void 0) {
5951
+ throw new CommerceError(
5952
+ "CONFIG_INVALID",
5953
+ "ACP idempotency needs a receipt store with idempotency methods or a file - set protocols.acp.idempotency.path",
5954
+ { details: { path: "protocols.acp.idempotency.path" } }
5955
+ );
5956
+ }
5957
+ this.fileStore = createAcpIdempotencyStore({
5958
+ path,
5959
+ retentionHours,
5960
+ releaseOrphans: release,
5961
+ logger: context.logger
5962
+ });
5963
+ return backendOverFileStore(this.fileStore);
5964
+ }
5844
5965
  /** `GET /.well-known/acp.json`: public, unauthenticated, cacheable */
5845
5966
  async handleDiscovery(req, res) {
5846
5967
  try {
@@ -5918,7 +6039,7 @@ var AcpProtocolAdapter = class {
5918
6039
  return (await this.runCheckout(request)).response;
5919
6040
  }
5920
6041
  const scope = { deployment, endpoint: request.route.path, key };
5921
- const claim = store.claim(scope, requestFingerprint(request.body));
6042
+ const claim = await store.claim(scope, requestFingerprint(request.body));
5922
6043
  switch (claim.kind) {
5923
6044
  case "in-flight":
5924
6045
  return {
@@ -5957,15 +6078,15 @@ var AcpProtocolAdapter = class {
5957
6078
  try {
5958
6079
  outcome = await this.runCheckout(request, operationKey(scope));
5959
6080
  } catch (err) {
5960
- store.markUnresolved(scope);
6081
+ await store.markUnresolved(scope);
5961
6082
  throw err;
5962
6083
  }
5963
6084
  if (outcome.response.status < 500) {
5964
- store.complete(scope, outcome.response);
6085
+ await store.complete(scope, outcome.response);
5965
6086
  } else if (outcome.reached === "no" || this.idempotencyOptions.merchantIdempotent === true) {
5966
- store.release(scope);
6087
+ await store.release(scope);
5967
6088
  } else {
5968
- store.markUnresolved(scope);
6089
+ await store.markUnresolved(scope);
5969
6090
  }
5970
6091
  return outcome.response;
5971
6092
  }
@@ -6065,7 +6186,8 @@ var AcpProtocolAdapter = class {
6065
6186
  this.started = false;
6066
6187
  this.discovery = void 0;
6067
6188
  this.resources = /* @__PURE__ */ new Map();
6068
- this.idempotency?.close();
6189
+ this.fileStore?.close();
6190
+ this.fileStore = void 0;
6069
6191
  this.idempotency = void 0;
6070
6192
  this.deployment = void 0;
6071
6193
  this.context = void 0;
@@ -7199,8 +7321,14 @@ async function createGateway(options) {
7199
7321
  return { url };
7200
7322
  },
7201
7323
  async close() {
7324
+ const sweep = setInterval(() => server.server.closeIdleConnections(), 100);
7325
+ sweep.unref();
7326
+ try {
7327
+ await server.close();
7328
+ } finally {
7329
+ clearInterval(sweep);
7330
+ }
7202
7331
  await stopAdapters(adapterRuntimes, logger);
7203
- await server.close();
7204
7332
  },
7205
7333
  server
7206
7334
  };
@@ -7221,17 +7349,32 @@ async function runGateway(options = {}) {
7221
7349
  const { core: logger } = createGatewayLogger({ name: config.merchant.id });
7222
7350
  const paymentProviders = await createConfiguredPaymentProviders(config.payments, logger);
7223
7351
  const ap2 = config.authorization?.ap2;
7224
- const ap2Module = ap2?.enabled ? await importOptionalPeer("authorization.ap2", () => import('./ap2-YAPLERSC.js')) : void 0;
7352
+ const ap2Module = ap2?.enabled ? await importOptionalPeer("authorization.ap2", () => import('./ap2-2YMYA2H6.js')) : void 0;
7225
7353
  const mcp = config.protocols.mcp;
7226
- const mcpModule = mcp.enabled ? await importOptionalPeer("protocols.mcp", () => import('./mcp-KZEMXLHR.js')) : void 0;
7354
+ const mcpModule = mcp.enabled ? await importOptionalPeer("protocols.mcp", () => import('./mcp-6F64A7KE.js')) : void 0;
7355
+ const acp = config.protocols.acp;
7356
+ const ap2Replay = ap2?.enabled ? ap2.replay?.path : void 0;
7357
+ const acpIdempotency = acp.enabled ? acp.idempotency.path : void 0;
7227
7358
  const store = createSqliteReceiptStore({
7228
7359
  path: config.storage.receipts.path,
7229
- logger
7360
+ logger,
7361
+ legacyStores: {
7362
+ ...ap2Replay !== void 0 ? { ap2Replay } : {},
7363
+ ...acpIdempotency !== void 0 ? { acpIdempotency } : {},
7364
+ enabled: { ap2: ap2?.enabled === true, acp: acp.enabled }
7365
+ }
7230
7366
  });
7231
- await store.init();
7367
+ try {
7368
+ await store.init();
7369
+ } catch (error) {
7370
+ await store.close();
7371
+ throw error;
7372
+ }
7232
7373
  const authorizationProviders = [];
7233
7374
  if (ap2?.enabled && ap2Module !== void 0) {
7234
- authorizationProviders.push(ap2Module.createAp2AuthorizationProvider({ config: ap2, logger }));
7375
+ authorizationProviders.push(
7376
+ ap2Module.createAp2AuthorizationProvider({ config: ap2, logger, store })
7377
+ );
7235
7378
  }
7236
7379
  const paidWithoutProvider = config.resources.filter(
7237
7380
  (resource) => resource.pricing.type !== "free" && !resource.paymentMethods.some(
@@ -7254,11 +7397,11 @@ async function runGateway(options = {}) {
7254
7397
  mountPath: config.protocols.a2a.mountPath,
7255
7398
  // The Agent Card names the merchant, not the software: a client
7256
7399
  // picking between agents is choosing whose resources to buy
7257
- agentName: config.merchant.name
7400
+ agentName: config.merchant.name,
7401
+ store
7258
7402
  })
7259
7403
  );
7260
7404
  }
7261
- const acp = config.protocols.acp;
7262
7405
  if (acp.enabled) {
7263
7406
  protocolAdapters.push(
7264
7407
  createAcpAdapter({
@@ -7266,6 +7409,7 @@ async function runGateway(options = {}) {
7266
7409
  token: acp.auth.token,
7267
7410
  operations: acp.checkout.operations,
7268
7411
  idempotency: acp.idempotency,
7412
+ store,
7269
7413
  ...acp.discovery !== void 0 ? { discovery: acp.discovery } : {}
7270
7414
  })
7271
7415
  );
@@ -7322,7 +7466,10 @@ async function runGateway(options = {}) {
7322
7466
  }
7323
7467
  let shuttingDown = false;
7324
7468
  const shutdown = (signal) => {
7325
- if (shuttingDown) return;
7469
+ if (shuttingDown) {
7470
+ logger.warn({ signal }, "second signal, exiting without waiting for in-flight requests");
7471
+ process.exit(1);
7472
+ }
7326
7473
  shuttingDown = true;
7327
7474
  logger.info({ signal }, "shutting down");
7328
7475
  void (async () => {
@@ -7354,5 +7501,5 @@ function printStartupError(error) {
7354
7501
  }
7355
7502
 
7356
7503
  export { printStartupError, runGateway };
7357
- //# sourceMappingURL=run-ZTYPQI4D.js.map
7358
- //# sourceMappingURL=run-ZTYPQI4D.js.map
7504
+ //# sourceMappingURL=run-2P6ZGFUE.js.map
7505
+ //# sourceMappingURL=run-2P6ZGFUE.js.map