@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,4 +1,4 @@
1
- import { CommerceError, redactedErrorText } from './chunk-SYQLJXIU.js';
1
+ import { CommerceError, redactedErrorText } from './chunk-C5YISPT6.js';
2
2
 
3
3
  // src/core/execution/reconcile.ts
4
4
  var DEFAULT_RECONCILE_MIN_AGE_MS = 15 * 60 * 1e3;
@@ -74,10 +74,30 @@ async function runReconcile(options) {
74
74
  }
75
75
  const authorizationProviders = options.authorizationProviders ?? [];
76
76
  const holds = [];
77
+ const orphanHolds = [];
78
+ const failedScans = [];
77
79
  const limit = options.limit ?? Number.POSITIVE_INFINITY;
80
+ const scan = async (name, run) => {
81
+ try {
82
+ await run();
83
+ } catch (err) {
84
+ logger?.warn({ scan: name, err: redactedErrorText(err) }, "reconcile: a hold scan failed");
85
+ failedScans.push(name);
86
+ }
87
+ };
88
+ if (authorizationProviders.length > 0) {
89
+ await scan(
90
+ "holds",
91
+ () => alignPendingHolds(holds, limit, dryRun, { journal, authorizationProviders, clock, logger })
92
+ );
93
+ await scan("orphan-holds", () => releaseOrphanHolds(orphanHolds, options, limit, dryRun));
94
+ }
95
+ return { dryRun, entries, holds, orphanHolds, failedScans };
96
+ }
97
+ async function alignPendingHolds(holds, limit, dryRun, deps) {
78
98
  let cursor;
79
- scan: while (authorizationProviders.length > 0) {
80
- const page = await journal.listTransactions({
99
+ for (; ; ) {
100
+ const page = await deps.journal.listTransactions({
81
101
  pendingHold: true,
82
102
  limit: PAGE,
83
103
  ...cursor !== void 0 ? { cursor } : {}
@@ -85,20 +105,62 @@ async function runReconcile(options) {
85
105
  for (const transaction of page.transactions) {
86
106
  const target = holdTarget(transaction);
87
107
  if (target === void 0) continue;
88
- if (holds.length >= limit) break scan;
108
+ if (holds.length >= limit) return;
89
109
  holds.push(
90
- dryRun ? holdEntry(transaction, target, false) : await alignHold(transaction, target, {
91
- journal,
92
- authorizationProviders,
93
- clock,
94
- logger
95
- })
110
+ dryRun ? holdEntry(transaction, target, false) : await alignHold(transaction, target, deps)
96
111
  );
97
112
  }
98
113
  cursor = page.nextCursor;
99
- if (cursor === void 0) break;
114
+ if (cursor === void 0) return;
115
+ }
116
+ }
117
+ async function releaseOrphanHolds(entries, options, limit, dryRun) {
118
+ const { store, clock, logger } = options;
119
+ if (store.listOrphanAuthorizationHolds === void 0) return;
120
+ const minAgeMs = options.minAgeMs ?? DEFAULT_RECONCILE_MIN_AGE_MS;
121
+ const updatedBefore = new Date(clock.now().getTime() - minAgeMs).toISOString();
122
+ const providers = options.authorizationProviders ?? [];
123
+ const seen = /* @__PURE__ */ new Set();
124
+ while (entries.length < limit) {
125
+ const page = await store.listOrphanAuthorizationHolds({
126
+ updatedBefore,
127
+ limit: Math.min(PAGE, limit - entries.length)
128
+ });
129
+ const fresh = page.filter((hold) => !seen.has(hold.reference));
130
+ if (fresh.length === 0) break;
131
+ for (const hold of fresh) {
132
+ seen.add(hold.reference);
133
+ const entry = {
134
+ reference: hold.reference,
135
+ method: hold.method,
136
+ requestId: hold.requestId,
137
+ resourceId: hold.resourceId,
138
+ updatedAt: hold.updatedAt
139
+ };
140
+ const provider = providers.find((candidate) => candidate.name === hold.method);
141
+ if (provider === void 0) {
142
+ entries.push({ ...entry, released: false, reason: "provider_not_enabled" });
143
+ continue;
144
+ }
145
+ if (dryRun) {
146
+ entries.push({ ...entry, released: false });
147
+ continue;
148
+ }
149
+ try {
150
+ await provider.release(hold.reference, {
151
+ requestId: hold.requestId,
152
+ resourceId: hold.resourceId
153
+ });
154
+ entries.push({ ...entry, released: true });
155
+ } catch (err) {
156
+ logger?.warn(
157
+ { reference: hold.reference, method: hold.method, err: redactedErrorText(err) },
158
+ "reconcile: authorization provider could not release an orphan hold"
159
+ );
160
+ entries.push({ ...entry, released: false, reason: "provider_error" });
161
+ }
162
+ }
100
163
  }
101
- return { dryRun, entries, holds };
102
164
  }
103
165
  var REFUSAL_MESSAGES = {
104
166
  already_resolved: "The payment attempt already has a resolution",
@@ -307,5 +369,5 @@ async function ask(provider, attempt, locator, clock, logger) {
307
369
  }
308
370
 
309
371
  export { DEFAULT_RECONCILE_MIN_AGE_MS, journalOf, resolveManually, runReconcile };
310
- //# sourceMappingURL=chunk-2UPPX3FJ.js.map
311
- //# sourceMappingURL=chunk-2UPPX3FJ.js.map
372
+ //# sourceMappingURL=chunk-VSSSU4AU.js.map
373
+ //# sourceMappingURL=chunk-VSSSU4AU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/execution/reconcile.ts"],"names":["current"],"mappings":";;;AAwBO,IAAM,4BAAA,GAA+B,KAAK,EAAA,GAAK;AAGtD,IAAM,IAAA,GAAO,GAAA;AAEb,IAAM,QAAA,GAA8B,CAAC,SAAA,EAAW,aAAA,EAAe,SAAS,CAAA;AAgGjE,SAAS,UAAU,KAAA,EAA8B;AACtD,EAAA,MAAM;AAAA,IACJ,gBAAA;AAAA,IACA,cAAA;AAAA,IACA,iBAAA;AAAA,IACA,qBAAA;AAAA,IACA;AAAA,GACF,GAAI,KAAA;AACJ,EAAA,IACE,CAAC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AA,CAAO,MAAA,KAAW,QAAA,EAAU;AAC3E,MAAA,OAAO,EAAE,OAAA,EAAS,SAAA,EAAW,MAAA,EAAQ,yBAAA,EAA0B;AAAA,IACjE;AACA,IAAA,OAAO,MAAA;AAAA,EACT,SAAS,GAAA,EAAK;AACZ,IAAA,MAAA,EAAQ,IAAA;AAAA,MACN,EAAE,SAAA,EAAW,OAAA,CAAQ,EAAA,EAAI,QAAA,EAAU,QAAQ,QAAA,EAAU,GAAA,EAAK,iBAAA,CAAkB,GAAG,CAAA,EAAE;AAAA,MACjF;AAAA,KACF;AACA,IAAA,OAAO,EAAE,OAAA,EAAS,SAAA,EAAW,MAAA,EAAQ,gBAAA,EAAiB;AAAA,EACxD;AACF","file":"chunk-VSSSU4AU.js","sourcesContent":["/**\n * Reconciliation records chain-evidence outcomes, and manual resolution\n * records operator verdicts, through conditional payment-attempt updates.\n * Neither path settles, refunds or retries delivery.\n *\n * An `unknown` result leaves the attempt unresolved. Later runs skip resolved\n * attempts as payment candidates but can retry their pending authorization\n * holds. Both paths attempt hold updates after recording payment resolution.\n *\n * Reconciliation also attempts to release old orphan holds: `reserved` holds\n * whose request has no current or archived payment attempt. The pipeline\n * reserves an attempt before calling settlement; the age threshold reduces\n * races with requests still between those steps.\n */\nimport type { AuthorizationProvider } from '../domain/authorization';\nimport type { PaymentProvider, PaymentReconciliationResult } from '../domain/payment';\nimport type { PaymentAttempt } from '../domain/receipt';\nimport type { Transaction } from '../domain/transaction';\nimport { CommerceError, redactedErrorText } from '../errors';\nimport type { Logger } from '../interfaces/logger';\nimport type { Clock } from '../interfaces/runtime';\nimport type { ReceiptStore } from '../interfaces/store';\n\n/** Default age threshold for reserved attempts, to reduce races with a running gateway */\nexport const DEFAULT_RECONCILE_MIN_AGE_MS = 15 * 60 * 1000;\n\n// Journal page size while collecting candidates\nconst PAGE = 200;\n\nconst OUTCOMES: readonly string[] = ['settled', 'not-settled', 'unknown'];\n\nexport interface ReconcileRunOptions {\n readonly store: ReceiptStore;\n readonly providers: readonly PaymentProvider[];\n readonly clock: Clock;\n /** Stored with each resolution */\n readonly actor: string;\n /** Check provider evidence and report without recording resolutions */\n readonly dryRun?: boolean;\n readonly minAgeMs?: number;\n /** Separate caps on payment candidates checked and hold updates attempted */\n readonly limit?: number;\n /** Providers for hold updates; an omitted or empty list skips both hold scans */\n readonly authorizationProviders?: readonly AuthorizationProvider[];\n readonly logger?: Logger;\n}\n\n/** Reconciliation result for one candidate */\nexport interface ReconcileEntry {\n readonly attemptId: string;\n /** Absent for attempts without a journal entry */\n readonly transactionId?: string;\n readonly requestId: string;\n readonly provider: string;\n readonly status: PaymentAttempt['status'];\n readonly outcome: PaymentReconciliationResult['outcome'];\n readonly reason: string;\n /** True when this run saved the attempt's resolution */\n readonly written: boolean;\n /** Set when saving the resolution throws */\n readonly error?: 'storage_error';\n readonly externalReference?: string;\n readonly retryAfter?: string;\n}\n\n/** Requested hold update for one resolved payment */\nexport interface HoldEntry {\n readonly transactionId: string;\n readonly attemptId: string;\n readonly method: string;\n /** `consumed` for a settled payment, `released` for a rejected one */\n readonly hold: 'consumed' | 'released';\n /** True when the provider call succeeded and the journal hold was recorded */\n readonly written: boolean;\n /**\n * Why the journal hold remains pending; `journal_error` means the provider\n * call succeeded but the journal write failed\n */\n readonly reason?: 'provider_not_enabled' | 'provider_error' | 'journal_error';\n}\n\n/** An orphan hold found during reconciliation, with its release result */\nexport interface OrphanHoldEntry {\n readonly reference: string;\n readonly method: string;\n readonly requestId: string;\n readonly resourceId: string;\n readonly updatedAt: string;\n /** True when the provider's release call succeeds */\n readonly released: boolean;\n readonly reason?: 'provider_not_enabled' | 'provider_error';\n}\n\nexport interface ReconcileReport {\n readonly dryRun: boolean;\n readonly entries: readonly ReconcileEntry[];\n readonly holds: readonly HoldEntry[];\n /** Empty when the store provides no orphan-hold listing method */\n readonly orphanHolds: readonly OrphanHoldEntry[];\n /**\n * Hold scans that failed, including on a store read error. Previously saved\n * resolutions remain committed; the report retains partial hold results.\n */\n readonly failedScans: readonly ('holds' | 'orphan-holds')[];\n}\n\ninterface Candidate {\n readonly attempt: PaymentAttempt;\n readonly transactionId?: string;\n readonly locator?: Readonly<Record<string, unknown>>;\n}\n\n/** Store methods required by reconciliation, manual resolution and the operator view */\nexport type Journal = Required<\n Pick<\n ReceiptStore,\n | 'listTransactions'\n | 'getTransaction'\n | 'getPaymentAttempt'\n | 'resolvePaymentAttempt'\n | 'recordTransactionStep'\n >\n>;\n\n/** Binds the required journal methods to the store, or throws `STORAGE_ERROR` if one is missing */\nexport function journalOf(store: ReceiptStore): Journal {\n const {\n listTransactions,\n getTransaction,\n getPaymentAttempt,\n resolvePaymentAttempt,\n recordTransactionStep,\n } = store;\n if (\n !listTransactions ||\n !getTransaction ||\n !getPaymentAttempt ||\n !resolvePaymentAttempt ||\n !recordTransactionStep\n ) {\n throw new CommerceError('STORAGE_ERROR', 'The receipt store has no transaction journal');\n }\n return {\n listTransactions: listTransactions.bind(store),\n getTransaction: getTransaction.bind(store),\n getPaymentAttempt: getPaymentAttempt.bind(store),\n resolvePaymentAttempt: resolvePaymentAttempt.bind(store),\n recordTransactionStep: recordTransactionStep.bind(store),\n };\n}\n\nexport async function runReconcile(options: ReconcileRunOptions): Promise<ReconcileReport> {\n const { store, providers, clock, actor, logger } = options;\n const dryRun = options.dryRun === true;\n const journal = journalOf(store);\n\n const candidates = await collectCandidates(options, journal);\n const entries: ReconcileEntry[] = [];\n for (const { attempt, transactionId, locator } of candidates) {\n const provider = providers.find((candidate) => candidate.name === attempt.provider);\n const result = await ask(provider, attempt, locator, clock, logger);\n let written = false;\n let error: ReconcileEntry['error'];\n if (!dryRun && result.outcome !== 'unknown') {\n // Report a failed resolution write and continue with the remaining candidates\n try {\n written = await journal.resolvePaymentAttempt({\n attemptId: attempt.id,\n expectedStatus: attempt.status,\n status: result.outcome === 'settled' ? 'settled' : 'rejected',\n ...(result.outcome === 'not-settled' ? { rejectionReason: 'not_settled' } : {}),\n resolution: {\n method: 'reconcile',\n actor,\n reason: result.reason,\n at: clock.nowIso(),\n ...(result.externalReference !== undefined\n ? { externalReference: result.externalReference }\n : {}),\n ...(result.evidence !== undefined ? { evidence: result.evidence } : {}),\n },\n });\n } catch (err) {\n logger?.warn(\n { attemptId: attempt.id, err: redactedErrorText(err) },\n 'reconcile: could not save the resolution',\n );\n error = 'storage_error';\n }\n }\n entries.push({\n attemptId: attempt.id,\n ...(transactionId !== undefined ? { transactionId } : {}),\n requestId: attempt.requestId,\n provider: attempt.provider,\n status: attempt.status,\n outcome: result.outcome,\n reason: result.reason,\n written,\n ...(error !== undefined ? { error } : {}),\n ...(result.externalReference !== undefined\n ? { externalReference: result.externalReference }\n : {}),\n ...(result.retryAfter !== undefined ? { retryAfter: result.retryAfter } : {}),\n });\n }\n\n const authorizationProviders = options.authorizationProviders ?? [];\n const holds: HoldEntry[] = [];\n const orphanHolds: OrphanHoldEntry[] = [];\n const failedScans: ReconcileReport['failedScans'][number][] = [];\n const limit = options.limit ?? Number.POSITIVE_INFINITY;\n // Preserve the report and any saved resolutions if a hold scan fails\n const scan = async (name: (typeof failedScans)[number], run: () => Promise<void>) => {\n try {\n await run();\n } catch (err) {\n logger?.warn({ scan: name, err: redactedErrorText(err) }, 'reconcile: a hold scan failed');\n failedScans.push(name);\n }\n };\n if (authorizationProviders.length > 0) {\n await scan('holds', () =>\n alignPendingHolds(holds, limit, dryRun, { journal, authorizationProviders, clock, logger }),\n );\n await scan('orphan-holds', () => releaseOrphanHolds(orphanHolds, options, limit, dryRun));\n }\n return { dryRun, entries, holds, orphanHolds, failedScans };\n}\n\n// Include pending holds left by earlier runs. Hold updates have no age\n// filter: the pipeline attempts finalization before recording a settled or\n// rejected payment status.\nasync function alignPendingHolds(\n holds: HoldEntry[],\n limit: number,\n dryRun: boolean,\n deps: AlignDeps,\n): Promise<void> {\n let cursor: string | undefined;\n for (;;) {\n const page = await deps.journal.listTransactions({\n pendingHold: true,\n limit: PAGE,\n ...(cursor !== undefined ? { cursor } : {}),\n });\n for (const transaction of page.transactions) {\n const target = holdTarget(transaction);\n if (target === undefined) continue;\n if (holds.length >= limit) return;\n holds.push(\n dryRun ? holdEntry(transaction, target, false) : await alignHold(transaction, target, deps),\n );\n }\n cursor = page.nextCursor;\n if (cursor === undefined) return;\n }\n}\n\n// A hold with no payment attempt keeps blocking reuse until it is released.\n// Wait for the age threshold to reduce races with requests between reservations.\nasync function releaseOrphanHolds(\n entries: OrphanHoldEntry[],\n options: ReconcileRunOptions,\n limit: number,\n dryRun: boolean,\n): Promise<void> {\n const { store, clock, logger } = options;\n if (store.listOrphanAuthorizationHolds === undefined) return;\n const minAgeMs = options.minAgeMs ?? DEFAULT_RECONCILE_MIN_AGE_MS;\n const updatedBefore = new Date(clock.now().getTime() - minAgeMs).toISOString();\n const providers = options.authorizationProviders ?? [];\n // Released holds leave the list. Track seen references because unreleased\n // holds can occupy the first page again; stop when it has no unseen holds.\n // A dry run reports at most one PAGE-sized page. Scanning beyond unreleased\n // rows would require a cursor in listOrphanAuthorizationHolds.\n const seen = new Set<string>();\n while (entries.length < limit) {\n const page = await store.listOrphanAuthorizationHolds({\n updatedBefore,\n limit: Math.min(PAGE, limit - entries.length),\n });\n const fresh = page.filter((hold) => !seen.has(hold.reference));\n if (fresh.length === 0) break;\n for (const hold of fresh) {\n seen.add(hold.reference);\n const entry = {\n reference: hold.reference,\n method: hold.method,\n requestId: hold.requestId,\n resourceId: hold.resourceId,\n updatedAt: hold.updatedAt,\n };\n const provider = providers.find((candidate) => candidate.name === hold.method);\n if (provider === undefined) {\n entries.push({ ...entry, released: false, reason: 'provider_not_enabled' });\n continue;\n }\n if (dryRun) {\n entries.push({ ...entry, released: false });\n continue;\n }\n try {\n // The AP2 provider's reservation id is the hold reference\n await provider.release(hold.reference, {\n requestId: hold.requestId,\n resourceId: hold.resourceId,\n });\n entries.push({ ...entry, released: true });\n } catch (err) {\n logger?.warn(\n { reference: hold.reference, method: hold.method, err: redactedErrorText(err) },\n 'reconcile: authorization provider could not release an orphan hold',\n );\n entries.push({ ...entry, released: false, reason: 'provider_error' });\n }\n }\n }\n}\n\n/** Input to {@link resolveManually}; `actor` is a caller-supplied label */\nexport interface ManualResolveOptions {\n readonly store: ReceiptStore;\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly clock: Clock;\n readonly logger?: Logger;\n readonly attemptId: string;\n /** `settled` or `rejected`; anything else is `INPUT_INVALID` */\n readonly status: string;\n readonly actor: string;\n readonly reason: string;\n /** Recorded as the operator's claim without checking the chain */\n readonly externalReference?: string;\n /** Required for rejection when no valid expiry is recorded */\n readonly confirmExpired?: boolean;\n}\n\n/** Why a manual resolution was not written */\nexport type ManualResolveRefusal =\n | 'already_resolved'\n | 'not_resolvable'\n | 'too_recent'\n | 'not_expired'\n | 'expiry_unknown';\n\nexport type ManualResolveResult =\n | {\n readonly resolved: true;\n readonly attempt: PaymentAttempt;\n /** Present when the attempt's transaction holds an authorization to align */\n readonly hold?: HoldEntry;\n }\n | {\n readonly resolved: false;\n readonly refusal: ManualResolveRefusal;\n readonly message: string;\n readonly attempt: PaymentAttempt;\n };\n\nconst REFUSAL_MESSAGES: Record<ManualResolveRefusal, string> = {\n already_resolved: 'The payment attempt already has a resolution',\n not_resolvable: 'Only reserved, settlement-uncertain and failed payment attempts can be resolved',\n too_recent:\n 'The payment attempt is reserved and may still be in flight; retry once it is 15 minutes old',\n not_expired: 'The recorded authorization expiry is still in the future',\n expiry_unknown: 'No expiry is recorded for this authorization; confirm that it has expired',\n};\n\n// Bounds on operator-supplied text stored with the resolution\nconst MAX_ACTOR_LENGTH = 256;\nconst MAX_REASON_LENGTH = 1024;\nconst MAX_REFERENCE_LENGTH = 256;\n\nconst RESOLVABLE: readonly PaymentAttempt['status'][] = [\n 'reserved',\n 'settlement-uncertain',\n 'failed',\n];\n\n/**\n * Record an operator's verdict on an unresolved payment attempt, then try to\n * update its pending authorization hold. A `reserved` attempt younger than\n * {@link DEFAULT_RECONCILE_MIN_AGE_MS} is refused because the gateway may still\n * be settling it. A `rejected` verdict is refused while\n * the recorded expiry is in the future. Without a valid expiry, `confirmExpired`\n * is required. Throws `INPUT_INVALID` for invalid input and\n * `RESOURCE_NOT_FOUND` for an unknown attempt.\n */\nexport async function resolveManually(options: ManualResolveOptions): Promise<ManualResolveResult> {\n const { clock, logger, attemptId, status, externalReference } = options;\n if (status !== 'settled' && status !== 'rejected') {\n throw invalid('status', 'status must be \"settled\" or \"rejected\"');\n }\n const actor = requiredText(options.actor, 'actor', MAX_ACTOR_LENGTH);\n const reason = requiredText(options.reason, 'reason', MAX_REASON_LENGTH);\n if (externalReference !== undefined) {\n requiredText(externalReference, 'externalReference', MAX_REFERENCE_LENGTH);\n }\n const journal = journalOf(options.store);\n\n const attempt = await journal.getPaymentAttempt(attemptId);\n if (attempt === undefined) {\n throw new CommerceError('RESOURCE_NOT_FOUND', `Payment attempt \"${attemptId}\" was not found`);\n }\n const refuse = (refusal: ManualResolveRefusal, current = attempt): ManualResolveResult => ({\n resolved: false,\n refusal,\n message: REFUSAL_MESSAGES[refusal],\n attempt: current,\n });\n if (attempt.resolution !== undefined) return refuse('already_resolved');\n if (!RESOLVABLE.includes(attempt.status)) return refuse('not_resolvable');\n if (\n attempt.status === 'reserved' &&\n !(clock.now().getTime() - Date.parse(attempt.createdAt) >= DEFAULT_RECONCILE_MIN_AGE_MS)\n ) {\n return refuse('too_recent');\n }\n\n const transaction =\n attempt.transactionId !== undefined\n ? await journal.getTransaction(attempt.transactionId)\n : undefined;\n if (status === 'rejected') {\n const expiresAt = Date.parse(transaction?.payment.expiresAt ?? '');\n if (expiresAt > clock.now().getTime()) return refuse('not_expired');\n if (Number.isNaN(expiresAt) && options.confirmExpired !== true) {\n return refuse('expiry_unknown');\n }\n }\n\n const written = await journal.resolvePaymentAttempt({\n attemptId,\n expectedStatus: attempt.status,\n status,\n ...(status === 'rejected' ? { rejectionReason: 'not_settled' } : {}),\n resolution: {\n method: 'manual',\n actor,\n reason,\n at: clock.nowIso(),\n ...(externalReference !== undefined ? { externalReference } : {}),\n },\n });\n const current = (await journal.getPaymentAttempt(attemptId)) ?? attempt;\n // The conditional update lost a race; use the current attempt to classify it\n if (!written) {\n return refuse(\n current.resolution !== undefined ? 'already_resolved' : 'not_resolvable',\n current,\n );\n }\n\n const resolved =\n transaction !== undefined ? await journal.getTransaction(transaction.id) : undefined;\n const target = resolved !== undefined ? holdTarget(resolved) : undefined;\n const hold =\n resolved !== undefined && target !== undefined\n ? await alignHold(resolved, target, {\n journal,\n authorizationProviders: options.authorizationProviders,\n clock,\n logger,\n })\n : undefined;\n return { resolved: true, attempt: current, ...(hold !== undefined ? { hold } : {}) };\n}\n\nfunction requiredText(value: string, field: string, max: number): string {\n if (value.trim() === '' || value.length > max) {\n throw invalid(field, `${field} must be non-empty and at most ${max} characters`);\n }\n return value;\n}\n\nfunction invalid(field: string, message: string): CommerceError {\n return new CommerceError('INPUT_INVALID', message, { details: { field } });\n}\n\n// Desired state for a resolved payment's journal hold still reserved or uncertain\nfunction holdTarget(transaction: Transaction): HoldEntry['hold'] | undefined {\n const hold = transaction.authorization?.hold;\n if (hold !== 'reserved' && hold !== 'uncertain') return undefined;\n if (transaction.payment.status === 'settled') return 'consumed';\n if (transaction.payment.status === 'rejected') return 'released';\n return undefined;\n}\n\nfunction holdEntry(\n transaction: Transaction,\n hold: HoldEntry['hold'],\n written: boolean,\n reason?: HoldEntry['reason'],\n): HoldEntry {\n return {\n transactionId: transaction.id,\n attemptId: transaction.payment.attemptId,\n method: transaction.authorization?.method ?? '',\n hold,\n written,\n ...(reason !== undefined ? { reason } : {}),\n };\n}\n\ninterface AlignDeps {\n readonly journal: Journal;\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly clock: Clock;\n readonly logger: Logger | undefined;\n}\n\n// Call the provider before updating the journal, so a crash can leave the\n// journal hold pending. After an AP2 consume/release succeeds, repeating it\n// leaves replay state unchanged; the request guard protects later reservations.\nasync function alignHold(\n transaction: Transaction,\n target: HoldEntry['hold'],\n deps: AlignDeps,\n): Promise<HoldEntry> {\n const authorization = transaction.authorization;\n const provider = deps.authorizationProviders.find(\n (candidate) => candidate.name === authorization?.method,\n );\n if (authorization === undefined || provider === undefined) {\n return holdEntry(transaction, target, false, 'provider_not_enabled');\n }\n // Bind the update to this transaction's reserving request\n const context = { requestId: transaction.requestId, resourceId: transaction.resourceId };\n try {\n if (target === 'consumed') await provider.consume(authorization.reservationId, context);\n else await provider.release(authorization.reservationId, context);\n } catch (err) {\n deps.logger?.warn(\n { transactionId: transaction.id, method: provider.name, err: redactedErrorText(err) },\n 'reconcile: authorization provider threw',\n );\n return holdEntry(transaction, target, false, 'provider_error');\n }\n // If the provider call succeeded but journaling fails, report the pending\n // journal update so a later run can retry both calls\n try {\n await deps.journal.recordTransactionStep({\n transactionId: transaction.id,\n at: deps.clock.nowIso(),\n kind: 'hold',\n hold: target,\n });\n } catch (err) {\n deps.logger?.warn(\n { transactionId: transaction.id, err: redactedErrorText(err) },\n 'reconcile: could not record the hold update',\n );\n return holdEntry(transaction, target, false, 'journal_error');\n }\n return holdEntry(transaction, target, true);\n}\n\n// Include uncertain and legacy `failed` attempts, plus `reserved` attempts\n// whose journal entries are present and whose age meets the threshold.\n// Journal rows supply locators; older attempts may have none.\nasync function collectCandidates(\n options: ReconcileRunOptions,\n journal: Journal,\n): Promise<readonly Candidate[]> {\n const { store, clock } = options;\n const limit = options.limit ?? Number.POSITIVE_INFINITY;\n const minAgeMs = options.minAgeMs ?? DEFAULT_RECONCILE_MIN_AGE_MS;\n const now = clock.now().getTime();\n const eligible = (attempt: PaymentAttempt) =>\n attempt.resolution === undefined &&\n (attempt.status === 'settlement-uncertain' ||\n attempt.status === 'failed' ||\n (attempt.status === 'reserved' && now - Date.parse(attempt.createdAt) >= minAgeMs));\n\n const candidates: Candidate[] = [];\n const seen = new Set<string>();\n // Scan states that can contain unresolved payments. delivery-started also\n // includes settled payments, which the attempt-status check below skips.\n for (const state of ['payment-uncertain', 'payment-pending', 'delivery-started'] as const) {\n let cursor: string | undefined;\n do {\n const page = await journal.listTransactions({\n state,\n limit: PAGE,\n ...(cursor !== undefined ? { cursor } : {}),\n });\n for (const transaction of page.transactions) {\n if (candidates.length >= limit) return candidates;\n const { attemptId, status, locator } = transaction.payment;\n if (status !== 'settlement-uncertain' && status !== 'failed' && status !== 'reserved') {\n continue;\n }\n const attempt = await journal.getPaymentAttempt(attemptId);\n if (attempt === undefined || !eligible(attempt) || seen.has(attempt.id)) continue;\n seen.add(attempt.id);\n candidates.push({\n attempt,\n transactionId: transaction.id,\n ...(locator !== undefined ? { locator } : {}),\n });\n }\n cursor = page.nextCursor;\n } while (cursor !== undefined);\n }\n\n // ponytail: attempts without journal entries are capped at one page; paginate for larger legacy stores\n for (const attempt of await store.listPaymentAttempts({ uncertain: true, limit: 500 })) {\n if (candidates.length >= limit) break;\n if (attempt.transactionId !== undefined || seen.has(attempt.id) || !eligible(attempt)) continue;\n seen.add(attempt.id);\n candidates.push({ attempt });\n }\n return candidates;\n}\n\nasync function ask(\n provider: PaymentProvider | undefined,\n attempt: PaymentAttempt,\n locator: Readonly<Record<string, unknown>> | undefined,\n clock: Clock,\n logger: Logger | undefined,\n): Promise<PaymentReconciliationResult> {\n if (provider === undefined) return { outcome: 'unknown', reason: 'provider_not_enabled' };\n if (provider.reconcile === undefined) {\n return { outcome: 'unknown', reason: 'reconcile_unsupported' };\n }\n try {\n const result = await provider.reconcile({\n attempt,\n ...(locator !== undefined ? { locator } : {}),\n now: clock.nowIso(),\n });\n if (!OUTCOMES.includes(result.outcome) || typeof result.reason !== 'string') {\n return { outcome: 'unknown', reason: 'invalid_provider_result' };\n }\n return result;\n } catch (err) {\n logger?.warn(\n { attemptId: attempt.id, provider: attempt.provider, err: redactedErrorText(err) },\n 'reconcile: provider threw',\n );\n return { outcome: 'unknown', reason: 'provider_error' };\n }\n}\n"]}
@@ -0,0 +1,8 @@
1
+ import 'module';
2
+
3
+ // src/version.ts
4
+ var PACKAGE_VERSION = "2.7.0" ;
5
+
6
+ export { PACKAGE_VERSION };
7
+ //# sourceMappingURL=chunk-ZCW56PZ3.js.map
8
+ //# sourceMappingURL=chunk-ZCW56PZ3.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/version.ts"],"names":[],"mappings":";;;AAsBO,IAAM,eAAA,GACmC,OAAA","file":"chunk-M7NXVRU5.js","sourcesContent":["/**\n * The package version, resolved once for the whole package.\n *\n * The build injects `__OAC_PACKAGE_VERSION__` (tsup.config.ts), because a\n * relative manifest path resolves from the wrong depth once `src/**` is\n * bundled. From source, the root manifest is read instead. `typeof` on an\n * undeclared identifier is safe, so the source path runs without the constant.\n */\nimport { createRequire } from 'node:module';\n\ndeclare const __OAC_PACKAGE_VERSION__: string | undefined;\n\nfunction readFromManifest(): string {\n try {\n const require = createRequire(import.meta.url);\n // src/version.ts -> repository root\n return (require('../package.json') as { version?: string }).version ?? '0.0.0-unknown';\n } catch {\n return '0.0.0-unknown';\n }\n}\n\nexport const PACKAGE_VERSION: string =\n typeof __OAC_PACKAGE_VERSION__ === 'string' ? __OAC_PACKAGE_VERSION__ : readFromManifest();\n"]}
1
+ {"version":3,"sources":["../../src/version.ts"],"names":[],"mappings":";;;AAsBO,IAAM,eAAA,GACmC,OAAA","file":"chunk-ZCW56PZ3.js","sourcesContent":["/**\n * The package version, resolved once for the whole package.\n *\n * The build injects `__OAC_PACKAGE_VERSION__` (tsup.config.ts), because a\n * relative manifest path resolves from the wrong depth once `src/**` is\n * bundled. From source, the root manifest is read instead. `typeof` on an\n * undeclared identifier is safe, so the source path runs without the constant.\n */\nimport { createRequire } from 'node:module';\n\ndeclare const __OAC_PACKAGE_VERSION__: string | undefined;\n\nfunction readFromManifest(): string {\n try {\n const require = createRequire(import.meta.url);\n // src/version.ts -> repository root\n return (require('../package.json') as { version?: string }).version ?? '0.0.0-unknown';\n } catch {\n return '0.0.0-unknown';\n }\n}\n\nexport const PACKAGE_VERSION: string =\n typeof __OAC_PACKAGE_VERSION__ === 'string' ? __OAC_PACKAGE_VERSION__ : readFromManifest();\n"]}
@@ -1,14 +1,15 @@
1
- import { ACP_WELL_KNOWN_PATH, DEFAULT_CONFIG_FILENAME, ACP_CHECKOUT_OPERATIONS, isObjectSchemaNode, extractPathParameterNames, findUnparsedBraceToken, ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS, ACP_SESSION_ID_INPUT_KEY } from './chunk-Z34UMZBB.js';
2
- import { 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-FHCFR2GS.js';
1
+ import { ACP_WELL_KNOWN_PATH, DEFAULT_CONFIG_FILENAME, ACP_CHECKOUT_OPERATIONS, isObjectSchemaNode, extractPathParameterNames, findUnparsedBraceToken, MAX_REDELIVERY_RETENTION_HOURS, ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS, ACP_SESSION_ID_INPUT_KEY } from './chunk-OETKXDGA.js';
2
+ import { 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-DKWO6LLX.js';
3
3
  import { MCP_TOOL_NAME_PATTERN } from './chunk-TPC4EJLT.js';
4
4
  import { MPP_DEFAULT_NETWORK, isMppNetwork, MPP_NETWORKS, MPP_DEFAULT_PAYMENT_FLOW, MPP_MIN_CHALLENGE_SECRET_LENGTH, MPP_PROFILE } from './chunk-AA3FIEAR.js';
5
- import { resolveX402Deployment, resolveX402Option } from './chunk-4H2QLHQI.js';
6
- import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, isEvmAddress, isEvmZeroAddress } from './chunk-5R7DM5LM.js';
7
- import { PROTOCOL_NAMES, PAYMENT_METHOD_NAMES, RESERVED_INPUT_FIELDS } from './chunk-IDY2735M.js';
8
- import { CommerceError } from './chunk-SYQLJXIU.js';
5
+ import { resolveX402Deployment, resolveX402Option } from './chunk-AGQ4U7IN.js';
6
+ import { X402_PAYMENT_FLOWS, validateCustomNetworks, findX402Network, X402_DEFAULT_PAYMENT_FLOW, isEvmAddress, isEvmZeroAddress } from './chunk-66NTYSXI.js';
7
+ import { PROTOCOL_NAMES, PAYMENT_METHOD_NAMES, RESERVED_INPUT_FIELDS } from './chunk-55AI6CLW.js';
8
+ import { CommerceError } from './chunk-C5YISPT6.js';
9
9
  import { isRecord } from './chunk-3M6U7ILB.js';
10
10
  import { promises } from 'fs';
11
11
  import * as path from 'path';
12
+ import { resolve } from 'path';
12
13
  import { parse, YAMLError } from 'yaml';
13
14
  import { z } from 'zod';
14
15
 
@@ -161,10 +162,10 @@ function normalizeAcp(raw) {
161
162
  'protocols.acp.auth is required when ACP is enabled - every ACP checkout endpoint is authenticated, and "bearer" is the only scheme supported in this release'
162
163
  );
163
164
  }
164
- if (raw.idempotency === void 0) {
165
- throw acpInvalid(
166
- "protocols.acp.idempotency",
167
- "protocols.acp.idempotency is required when ACP is enabled - it names the SQLite file holding checkout idempotency records, and ACP makes the Idempotency-Key mandatory on every checkout POST"
165
+ const idempotency = raw.idempotency ?? {};
166
+ if (idempotency.path !== void 0) {
167
+ console.warn(
168
+ "[agent-commerce] protocols.acp.idempotency.path is deprecated: the receipt database holds ACP idempotency claims. The first start imports this file and keeps it locked while the gateway runs. Remove the key once no 2.5.x gateway uses the file; 3.0.0 stops reading it."
168
169
  );
169
170
  }
170
171
  const discovery = raw.discovery;
@@ -173,13 +174,13 @@ function normalizeAcp(raw) {
173
174
  mountPath,
174
175
  auth: raw.auth,
175
176
  idempotency: {
176
- path: raw.idempotency.path,
177
+ ...idempotency.path !== void 0 ? { path: idempotency.path } : {},
177
178
  retentionHours: toNumber(
178
- raw.idempotency.retentionHours ?? ACP_RETENTION_HOURS,
179
+ idempotency.retentionHours ?? ACP_RETENTION_HOURS,
179
180
  "protocols.acp.idempotency.retentionHours",
180
181
  { min: ACP_RETENTION_HOURS }
181
182
  ),
182
- merchantIdempotent: raw.idempotency.merchantIdempotent ?? false
183
+ merchantIdempotent: idempotency.merchantIdempotent ?? false
183
184
  },
184
185
  checkout: { operations: normalizeAcpOperations(raw.checkout) },
185
186
  // Built key by key so absent metadata stays absent rather than `undefined`
@@ -310,8 +311,6 @@ function closedObjectProperties(schema) {
310
311
  if (!isRecord(schema) || schema["additionalProperties"] !== false) return void 0;
311
312
  return isRecord(schema["properties"]) ? schema["properties"] : {};
312
313
  }
313
-
314
- // src/config/schema/ap2.ts
315
314
  var SUPPORTED_AUTHORIZATION_METHODS = /* @__PURE__ */ new Set(["ap2"]);
316
315
  function ap2Invalid(path2, message, extra = {}) {
317
316
  return new CommerceError("CONFIG_INVALID", message, { details: { path: path2, ...extra } });
@@ -333,10 +332,9 @@ function normalizeAp2(raw) {
333
332
  `authorization.ap2.mode "${mode}" is not supported. Supported: ${AP2_MODES.join(", ")}. Autonomous mode needs open mandates, agent key binding and constraint evaluation, none of which this release implements.`
334
333
  );
335
334
  }
336
- if (raw.replay === void 0) {
337
- throw ap2Invalid(
338
- "authorization.ap2.replay",
339
- "authorization.ap2.replay is required when AP2 is enabled - it names the SQLite file recording which mandates have been spent, and without it a verified mandate could authorize a second settlement"
335
+ if (raw.replay !== void 0) {
336
+ console.warn(
337
+ "[agent-commerce] authorization.ap2.replay.path is deprecated: the receipt database holds AP2 mandate holds. The first start imports this file and keeps it locked while the gateway runs. Remove the key once no 2.5.x gateway uses the file; 3.0.0 stops reading it."
340
338
  );
341
339
  }
342
340
  const mandateIssuers = normalizeIssuers(
@@ -365,7 +363,7 @@ function normalizeAp2(raw) {
365
363
  raw.requireMandateExpiry ?? false,
366
364
  "authorization.ap2.requireMandateExpiry"
367
365
  ),
368
- replay: { path: raw.replay.path }
366
+ ...raw.replay !== void 0 ? { replay: { path: raw.replay.path } } : {}
369
367
  };
370
368
  }
371
369
  function normalizeIssuers(raw, path2) {
@@ -460,16 +458,25 @@ function validateJwk(jwk, kid, path2) {
460
458
  }
461
459
  return normalized;
462
460
  }
463
- function validateReplayStoreIsolated(replayPath, receiptsPath, acp) {
464
- if (replayPath === ":memory:") return;
461
+ function validateLegacyStoresIsolated(ap2, acp, receiptsPath) {
462
+ const files = [
463
+ ["authorization.ap2.replay.path", ap2?.enabled ? ap2.replay?.path : void 0],
464
+ ["protocols.acp.idempotency.path", acp.enabled ? acp.idempotency.path : void 0]
465
+ ];
465
466
  const others = [["storage.receipts.path", receiptsPath]];
466
- if (acp.enabled) others.push(["protocols.acp.idempotency.path", acp.idempotency.path]);
467
- for (const [otherPath, other] of others) {
468
- if (replayPath !== other) continue;
469
- throw ap2Invalid(
470
- "authorization.ap2.replay.path",
471
- `authorization.ap2.replay.path is the same file as ${otherPath} ("${replayPath}") - the AP2 replay store keeps its own schema and must not share a database with another store`
467
+ for (const [key, path2] of files) {
468
+ if (path2 === void 0 || path2 === ":memory:") continue;
469
+ const clash = others.find(
470
+ ([, other]) => other !== ":memory:" && resolve(other) === resolve(path2)
472
471
  );
472
+ if (clash !== void 0) {
473
+ throw new CommerceError(
474
+ "CONFIG_INVALID",
475
+ `${key} is the same file as ${clash[0]} ("${resolve(path2)}") - a deprecated store file is imported into the receipt database and then locked, so it must be a separate file`,
476
+ { details: { path: key } }
477
+ );
478
+ }
479
+ others.push([key, path2]);
473
480
  }
474
481
  }
475
482
  function normalizeResourceAuthorization(id, entry, pricing, ap2) {
@@ -792,8 +799,8 @@ var MerchantSchema = z.object({
792
799
  var ServerSchema = z.object({
793
800
  port: NumberOrString,
794
801
  host: z.string().min(1),
795
- // Required for /api/receipts, /api/events and /api/payment-attempts;
796
- // these routes return 404 when the token is unset
802
+ // Operator routes (/api/receipts, /api/events, /api/payment-attempts,
803
+ // /api/transactions and the resolve route) return 404 without this token
797
804
  adminToken: z.string().min(1).optional(),
798
805
  // Browser origins allowed to call the gateway; none by default. A request
799
806
  // with any other `Origin` gets 403 on every route. Entries match the
@@ -826,7 +833,10 @@ var RESERVED_GATEWAY_PATHS = [
826
833
  "/api/resources/:id/invoke",
827
834
  "/api/receipts",
828
835
  "/api/events",
829
- "/api/payment-attempts"
836
+ "/api/payment-attempts",
837
+ "/api/payment-attempts/:id/resolve",
838
+ "/api/transactions",
839
+ "/api/transactions/:id"
830
840
  ];
831
841
  var MountPathSchema = z.string().min(1).refine((value) => value.startsWith("/"), {
832
842
  message: 'must start with "/" - it is an absolute gateway path, e.g. "/mcp".'
@@ -845,11 +855,11 @@ var MountPathSchema = z.string().min(1).refine((value) => value.startsWith("/"),
845
855
  );
846
856
  var AcpAuthSchema = z.object({ type: z.literal("bearer"), token: z.string().min(1) }).strict();
847
857
  var AcpIdempotencySchema = z.object({
848
- path: z.string().min(1),
858
+ path: z.string().min(1).optional(),
849
859
  retentionHours: NumberOrString.optional(),
850
860
  merchantIdempotent: z.boolean().optional()
851
861
  }).strict();
852
- var AcpCheckoutSchema = z.object({ operations: z.record(z.string().min(1)) }).strict();
862
+ var AcpCheckoutSchema = z.object({ operations: z.record(z.string(), z.string().min(1)) }).strict();
853
863
  var AcpDiscoverySchema = z.object({
854
864
  documentationUrl: z.string().min(1).optional(),
855
865
  supportedCurrencies: z.array(z.string().min(1)).optional(),
@@ -930,14 +940,20 @@ var ResourceEntrySchema = z.object({
930
940
  paymentFlow: z.enum(X402_PAYMENT_FLOWS).optional(),
931
941
  // This resource's own x402 offers, in place of `payments.x402` options
932
942
  x402: z.object({ accepts: z.array(X402OptionSchema) }).strict().optional(),
933
- authorization: z.object({ required: z.array(z.string().min(1)).min(1) }).strict().optional()
943
+ authorization: z.object({ required: z.array(z.string().min(1)).min(1) }).strict().optional(),
944
+ idempotency: z.object({
945
+ merchantKey: BooleanOrString.optional(),
946
+ redelivery: z.object({
947
+ retentionHours: NumberOrString.optional(),
948
+ required: BooleanOrString.optional()
949
+ }).strict().optional()
950
+ }).strict().optional()
934
951
  }).strict();
935
952
  var ResourcesMapSchema = z.record(z.string().min(1), ResourceEntrySchema);
936
953
  var FacilitatorAuthSchema = z.discriminatedUnion("type", [
937
954
  z.object({ type: z.literal("none") }).strict(),
938
955
  z.object({ type: z.literal("bearer"), token: z.string().min(1) }).strict(),
939
- // Coinbase Developer Platform. Needs the optional peer `@coinbase/x402`,
940
- // which signs a fresh JWT per request.
956
+ // Coinbase Developer Platform: the gateway signs a fresh JWT per request
941
957
  z.object({
942
958
  type: z.literal("cdp"),
943
959
  apiKeyId: z.string().min(1),
@@ -1321,6 +1337,7 @@ function validateResourceSchemaKeywords(id, path2, schema) {
1321
1337
  // src/config/schema/resources.ts
1322
1338
  var SUPPORTED_PROTOCOLS = new Set(PROTOCOL_NAMES);
1323
1339
  var SUPPORTED_PAYMENT_METHODS = new Set(PAYMENT_METHOD_NAMES);
1340
+ var DEFAULT_REDELIVERY_RETENTION_HOURS = 24;
1324
1341
  function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
1325
1342
  if (entry.input !== void 0) validateResourceSchemaKeywords(id, "input", entry.input);
1326
1343
  const inputProperties = entry.input?.["properties"];
@@ -1483,6 +1500,7 @@ function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
1483
1500
  { details: { path: `resources.${id}.mimeType`, resourceId: id } }
1484
1501
  );
1485
1502
  }
1503
+ const idempotency = normalizeResourceIdempotency(id, entry, paymentMethods);
1486
1504
  const pricing = entry.pricing.type === "free" ? { type: "free" } : { type: "fixed", amount: entry.pricing.amount, currency: entry.pricing.currency };
1487
1505
  const authorization = normalizeResourceAuthorization(id, entry, pricing, ap2);
1488
1506
  return {
@@ -1506,7 +1524,44 @@ function normalizeResource(id, entry, protocols, x402, mpp, ap2) {
1506
1524
  pricing,
1507
1525
  exposedVia: entry.expose,
1508
1526
  paymentMethods,
1509
- ...authorization !== void 0 ? { authorization } : {}
1527
+ ...authorization !== void 0 ? { authorization } : {},
1528
+ ...idempotency !== void 0 ? { idempotency } : {}
1529
+ };
1530
+ }
1531
+ function normalizeResourceIdempotency(id, entry, paymentMethods) {
1532
+ const raw = entry.idempotency;
1533
+ if (raw === void 0) return void 0;
1534
+ const path2 = `resources.${id}.idempotency`;
1535
+ const refuse = (problem, at) => new CommerceError("CONFIG_INVALID", `Resource "${id}" sets ${problem}`, {
1536
+ details: { path: at, resourceId: id }
1537
+ });
1538
+ if (entry.pricing.type !== "fixed") {
1539
+ throw refuse("idempotency, which requires fixed pricing", path2);
1540
+ }
1541
+ if (raw.merchantKey === void 0 && raw.redelivery === void 0) {
1542
+ throw refuse("idempotency without merchantKey or redelivery", path2);
1543
+ }
1544
+ let redelivery;
1545
+ if (raw.redelivery !== void 0) {
1546
+ const required = toBoolean(raw.redelivery.required ?? false, `${path2}.redelivery.required`);
1547
+ if (required && !paymentMethods.includes("x402")) {
1548
+ throw refuse(
1549
+ 'idempotency.redelivery.required, which requires "x402" in payments',
1550
+ `${path2}.redelivery.required`
1551
+ );
1552
+ }
1553
+ redelivery = {
1554
+ retentionHours: toNumber(
1555
+ raw.redelivery.retentionHours ?? DEFAULT_REDELIVERY_RETENTION_HOURS,
1556
+ `${path2}.redelivery.retentionHours`,
1557
+ { min: 1, max: MAX_REDELIVERY_RETENTION_HOURS }
1558
+ ),
1559
+ required
1560
+ };
1561
+ }
1562
+ return {
1563
+ ...raw.merchantKey !== void 0 ? { merchantKey: toBoolean(raw.merchantKey, `${path2}.merchantKey`) } : {},
1564
+ ...redelivery !== void 0 ? { redelivery } : {}
1510
1565
  };
1511
1566
  }
1512
1567
  var PRICING_AMOUNT_PATTERN = /^\d+(?:\.\d+)?$/;
@@ -1562,9 +1617,7 @@ function normalize(raw) {
1562
1617
  const x402 = x402Settings?.config;
1563
1618
  const mpp = normalizeMpp(raw.payments.mpp);
1564
1619
  const ap2 = normalizeAp2(raw.authorization?.ap2);
1565
- if (ap2?.enabled) {
1566
- validateReplayStoreIsolated(ap2.replay.path, raw.storage.receipts.path, protocols.acp);
1567
- }
1620
+ validateLegacyStoresIsolated(ap2, protocols.acp, raw.storage.receipts.path);
1568
1621
  const resources = Object.entries(raw.resources).map(
1569
1622
  ([id, entry]) => normalizeResource(id, entry, protocols, x402Settings, mpp, ap2)
1570
1623
  );
@@ -1758,5 +1811,5 @@ function resolveConfigPath(explicitPath, env, cwd) {
1758
1811
  }
1759
1812
 
1760
1813
  export { loadConfig, parseConfig, substituteEnv };
1761
- //# sourceMappingURL=chunk-2J2IQQ4X.js.map
1762
- //# sourceMappingURL=chunk-2J2IQQ4X.js.map
1814
+ //# sourceMappingURL=chunk-ZFVQWOGG.js.map
1815
+ //# sourceMappingURL=chunk-ZFVQWOGG.js.map