@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
package/dist/cli/index.js CHANGED
@@ -1,20 +1,24 @@
1
1
  #!/usr/bin/env node
2
- import { AP2_UNSUPPORTED } from './chunk-3EQBCFZY.js';
3
- import { A2A_SPEC_VERSION, A2A_PROTOCOL_VERSION, A2A_PROTOCOL_BINDING, A2A_AGENT_CARD_PATH, A2A_UNSUPPORTED, ACP_UNSUPPORTED } from './chunk-NIU5EMSB.js';
4
- import { createSqliteReceiptStore } from './chunk-QLUCNPRT.js';
5
- import './chunk-VJ4EO4LE.js';
6
- import { DEFAULT_CONFIG_FILENAME, extractPathParameterNames, ACP_SPEC_VERSION, ACP_API_VERSION, ACP_WELL_KNOWN_PATH, findUnparsedBraceToken } from './chunk-Z34UMZBB.js';
7
- import { AP2_SPEC_VERSION, AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE } from './chunk-FHCFR2GS.js';
2
+ import { AP2_UNSUPPORTED } from './chunk-H7EBJ4I3.js';
3
+ import { A2A_SPEC_VERSION, A2A_PROTOCOL_VERSION, A2A_PROTOCOL_BINDING, A2A_AGENT_CARD_PATH, A2A_UNSUPPORTED, ACP_UNSUPPORTED } from './chunk-3NVJAQRO.js';
4
+ import { DEFAULT_CONFIG_FILENAME, extractPathParameterNames, ACP_SPEC_VERSION, ACP_API_VERSION, ACP_WELL_KNOWN_PATH, findUnparsedBraceToken } from './chunk-OETKXDGA.js';
5
+ import { AP2_SPEC_VERSION, AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE } from './chunk-DKWO6LLX.js';
8
6
  import { MCP_TOOL_NAME_MAX_LENGTH, MCP_TOOL_NAME_CHARS } from './chunk-TPC4EJLT.js';
7
+ import { createSqliteReceiptStore, openSqliteReceiptStoreReadOnly, readMissingLegacyImports, SCHEMA_VERSION, hasTable } from './chunk-5TID36YG.js';
8
+ import './chunk-6EBDOH37.js';
9
+ import './chunk-APC5BTQM.js';
10
+ import { DEFAULT_RECONCILE_MIN_AGE_MS } from './chunk-VSSSU4AU.js';
9
11
  import { MPP_PROFILE, MPP_SPEC_DRAFTS, MPPX_VERSION, MPP_SPEC_COMMIT, MPP_DEFAULT_PAYMENT_FLOW } from './chunk-AA3FIEAR.js';
10
- import { PACKAGE_VERSION } from './chunk-M7NXVRU5.js';
11
- import { ANVIL_WELL_KNOWN_ACCOUNTS, describeDeploymentMode, X402_DEFAULT_PAYMENT_FLOW, findX402Network, isEvmAddress, LOCAL_CHAIN_ID, resolveDeploymentMode, sameAddress } from './chunk-5R7DM5LM.js';
12
- import { PROTOCOL_NAMES, systemClock, NOOP_LOGGER } from './chunk-IDY2735M.js';
13
- import { isCommerceError, redactedErrorText, CommerceError } from './chunk-SYQLJXIU.js';
12
+ import { ANVIL_WELL_KNOWN_ACCOUNTS, describeDeploymentMode, X402_DEFAULT_PAYMENT_FLOW, findX402Network, isEvmAddress, LOCAL_CHAIN_ID, resolveDeploymentMode, sameAddress } from './chunk-66NTYSXI.js';
13
+ import { PACKAGE_VERSION } from './chunk-ZCW56PZ3.js';
14
+ import { PROTOCOL_NAMES, systemClock, NOOP_LOGGER } from './chunk-55AI6CLW.js';
15
+ import { isCommerceError, redactedErrorText, CommerceError } from './chunk-C5YISPT6.js';
14
16
  import { isRecord } from './chunk-3M6U7ILB.js';
15
17
  import { CommanderError, Command } from 'commander';
16
- import { existsSync, mkdirSync, readFileSync, accessSync, constants } from 'fs';
17
- import { dirname, resolve, join, basename, extname, win32 } from 'path';
18
+ import { createHash } from 'crypto';
19
+ import { existsSync, writeFileSync, mkdirSync, readFileSync, statSync, readdirSync, closeSync, openSync, createReadStream, accessSync, constants } from 'fs';
20
+ import { resolve, join, dirname, basename, extname, win32 } from 'path';
21
+ import Database from 'better-sqlite3';
18
22
  import { z } from 'zod';
19
23
  import { stringify, parse, Document } from 'yaml';
20
24
  import picocolors from 'picocolors';
@@ -24,64 +28,10 @@ import { validate } from '@scalar/openapi-parser';
24
28
  import * as clack from '@clack/prompts';
25
29
  import { userInfo } from 'os';
26
30
 
27
- // src/cli/commands/demo.ts
28
- function defaultDemoSteps() {
29
- return [
30
- {
31
- name: "Start the local stack: chain, merchant, gateway and dashboard (docker compose)",
32
- command: "docker",
33
- args: ["compose", "up", "--build", "--detach", "--wait"]
34
- },
35
- { name: "Run the deterministic buyer agent", command: "npm", args: ["run", "demo:agent"] }
36
- ];
37
- }
38
- async function runDemo(io, deps = {}) {
39
- const steps = deps.steps ?? defaultDemoSteps();
40
- const run = deps.run ?? execCommand;
41
- io.stdout("agent-commerce demo: starting the local stack, then running the buyer agent");
42
- for (const step of steps) {
43
- io.stdout("");
44
- io.stdout(`==> ${step.name}`);
45
- io.stdout(` $ ${step.command} ${step.args.join(" ")}`);
46
- const result = await run(step.command, step.args);
47
- if (result.code !== 0) {
48
- io.stderr(`FAIL "${step.name}" exited with code ${result.code}.`);
49
- if (result.stderrTail !== void 0 && result.stderrTail.length > 0) {
50
- io.stderr(result.stderrTail);
51
- }
52
- io.stderr("");
53
- io.stderr("Nothing further was run. To retry manually:");
54
- io.stderr(` ${step.command} ${step.args.join(" ")}`);
55
- return 1;
56
- }
57
- io.stdout(`OK ${step.name}`);
58
- }
59
- io.stdout("");
60
- io.stdout("PASS Demo is up. Try: agent-commerce doctor --config config-demo.yaml");
61
- return 0;
62
- }
63
- async function execCommand(command, args) {
64
- const { spawn } = await import('child_process');
65
- return new Promise((resolvePromise) => {
66
- let stderr = "";
67
- const child = spawn(command, args, { stdio: ["ignore", "inherit", "pipe"] });
68
- child.stderr?.on("data", (chunk) => {
69
- stderr += chunk.toString("utf8");
70
- });
71
- child.on("error", (err) => {
72
- resolvePromise({ code: 1, stderrTail: err.message });
73
- });
74
- child.on("close", (code) => {
75
- const tail = stderr.trim().split("\n").slice(-10).join("\n");
76
- resolvePromise({ code: code ?? 1, ...tail.length > 0 ? { stderrTail: tail } : {} });
77
- });
78
- });
79
- }
80
-
81
31
  // src/cli/lib/config-client.ts
82
32
  async function importConfig() {
83
33
  try {
84
- return await import('./config-BWFMN2ZB.js');
34
+ return await import('./config-WT5HHDRR.js');
85
35
  } catch (err) {
86
36
  throw new CommerceError(
87
37
  "INTERNAL_ERROR",
@@ -95,26 +45,6 @@ async function loadConfigDynamic(options = {}) {
95
45
  async function parseConfigDynamic(raw, env = process.env) {
96
46
  return (await importConfig()).parseConfig(raw, env);
97
47
  }
98
-
99
- // src/cli/lib/http.ts
100
- async function fetchJson(fetchImpl, url, timeoutMs = 1500) {
101
- try {
102
- const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
103
- let body;
104
- try {
105
- body = await res.json();
106
- } catch {
107
- body = void 0;
108
- }
109
- return { ok: res.ok, status: res.status, ...body !== void 0 ? { body } : {} };
110
- } catch (err) {
111
- return {
112
- ok: false,
113
- status: 0,
114
- error: err instanceof Error ? err.message : "unknown fetch error"
115
- };
116
- }
117
- }
118
48
  var LOCAL_CHAIN_MANIFEST_PATH = ".deploy/local.json";
119
49
  var nonEmpty = z.string().min(1, "must be a non-empty string");
120
50
  var keyedAccount = z.object({ address: z.string(), privateKey: z.string(), note: z.string() });
@@ -213,6 +143,256 @@ function unresolvedVariableHint(variable, manifestFound, chainDeploy) {
213
143
  return `set ${variable} in the environment, or in a file passed with --env-file`;
214
144
  }
215
145
 
146
+ // src/cli/commands/validate.ts
147
+ function formatConfigError(err, manifestFound = false, chainDeploy = hasChainDeployScript()) {
148
+ if (isCommerceError(err)) {
149
+ const lines = [`FAIL ${err.code}: ${err.message}`];
150
+ if (err.details !== void 0) {
151
+ lines.push(` details: ${JSON.stringify(err.details)}`);
152
+ }
153
+ const variable = err.details?.["variable"];
154
+ if (typeof variable === "string") {
155
+ lines.push(` hint: ${unresolvedVariableHint(variable, manifestFound, chainDeploy)}`);
156
+ }
157
+ return lines.join("\n");
158
+ }
159
+ if (err instanceof Error) {
160
+ return `FAIL ${err.message}`;
161
+ }
162
+ return `FAIL ${String(err)}`;
163
+ }
164
+ async function runValidate(options, io, deps = {}) {
165
+ const loadConfig = deps.loadConfig ?? loadConfigDynamic;
166
+ const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;
167
+ const { env, filled, manifestFound } = fillEnvFromManifest(process.env);
168
+ if (filled.length > 0) {
169
+ io.stdout(`using local chain manifest ${LOCAL_CHAIN_MANIFEST_PATH} for ${filled.join(", ")}`);
170
+ }
171
+ try {
172
+ const config = await loadConfig({
173
+ ...options.configPath !== void 0 ? { path: options.configPath } : {},
174
+ env
175
+ });
176
+ io.stdout("PASS Configuration is valid");
177
+ io.stdout(` merchant: ${config.merchant.name} (${config.merchant.id})`);
178
+ io.stdout(` resources: ${config.resources.length}`);
179
+ io.stdout(
180
+ ` protocols: http=${config.protocols.http.enabled ? "on" : "off"} mcp=${config.protocols.mcp.enabled ? "on" : "off"} a2a=${config.protocols.a2a.enabled ? "on" : "off"} acp=${config.protocols.acp.enabled ? "on" : "off"}`
181
+ );
182
+ const onOff = (enabled) => enabled === true ? "on" : "off";
183
+ io.stdout(
184
+ ` payments: x402=${onOff(config.payments.x402?.enabled)} mpp=${onOff(config.payments.mpp?.enabled)}`
185
+ );
186
+ io.stdout(` authorization: ap2=${onOff(config.authorization?.ap2.enabled)}`);
187
+ return 0;
188
+ } catch (err) {
189
+ io.stderr(
190
+ formatConfigError(err, manifestFound, (deps.hasChainDeployScript ?? hasChainDeployScript)())
191
+ );
192
+ return 1;
193
+ }
194
+ }
195
+
196
+ // src/cli/commands/backup.ts
197
+ var OLDEST_SCHEMA = 4;
198
+ var LEGACY = [
199
+ { file: "ap2-replay.sqlite", source: "authorization.ap2.replay.path", marker: "ap2-replay" },
200
+ {
201
+ file: "acp-idempotency.sqlite",
202
+ source: "protocols.acp.idempotency.path",
203
+ marker: "acp-idempotency"
204
+ }
205
+ ];
206
+ var BackupError = class extends Error {
207
+ };
208
+ async function runBackupCommand(options, io, deps = {}) {
209
+ let config;
210
+ try {
211
+ config = await (deps.loadConfig ?? loadConfigDynamic)(
212
+ options.configPath !== void 0 ? { path: options.configPath } : {}
213
+ );
214
+ } catch (error) {
215
+ io.stderr(formatConfigError(error, false, false));
216
+ return 1;
217
+ }
218
+ try {
219
+ const receipts = config.storage.receipts.path;
220
+ if (receipts === ":memory:") throw new BackupError("the receipt database is in memory");
221
+ if (!existsSync(receipts)) {
222
+ throw new BackupError(`the receipt database "${resolve(receipts)}" does not exist`);
223
+ }
224
+ const ap2 = config.authorization?.ap2;
225
+ const acp = config.protocols.acp;
226
+ const legacyPaths = {
227
+ "authorization.ap2.replay.path": ap2?.enabled ? ap2.replay?.path : void 0,
228
+ "protocols.acp.idempotency.path": acp.enabled ? acp.idempotency.path : void 0
229
+ };
230
+ prepareOut(options.out);
231
+ const files = [];
232
+ const imported = await copy(
233
+ receipts,
234
+ options.out,
235
+ "receipts.sqlite",
236
+ "storage.receipts.path",
237
+ files
238
+ );
239
+ for (const legacy of LEGACY) {
240
+ const path = legacyPaths[legacy.source];
241
+ if (path === void 0 || path === ":memory:" || !existsSync(path)) continue;
242
+ if (imported.has(legacy.marker)) continue;
243
+ await copy(path, options.out, legacy.file, legacy.source, files);
244
+ }
245
+ const manifest = {
246
+ packageVersion: PACKAGE_VERSION,
247
+ createdAt: (deps.clock ?? systemClock).nowIso(),
248
+ files
249
+ };
250
+ writeFileSync(join(options.out, "backup.json"), `${JSON.stringify(manifest, null, 2)}
251
+ `, {
252
+ flag: "wx",
253
+ mode: 384
254
+ });
255
+ if (options.json === true) {
256
+ io.stdout(JSON.stringify({ out: resolve(options.out), ...manifest }, null, 2));
257
+ } else {
258
+ io.stdout(`backup written to ${resolve(options.out)}`);
259
+ for (const file of files) {
260
+ io.stdout(` ${file.file.padEnd(24)} ${file.source} (schema v${file.schemaVersion})`);
261
+ }
262
+ }
263
+ return 0;
264
+ } catch (error) {
265
+ io.stderr(
266
+ `FAIL backup: ${error instanceof BackupError ? error.message : redactedErrorText(error)}`
267
+ );
268
+ return 1;
269
+ }
270
+ }
271
+ function prepareOut(out) {
272
+ if (!existsSync(out)) {
273
+ mkdirSync(out, { mode: 448 });
274
+ return;
275
+ }
276
+ if (!statSync(out).isDirectory()) throw new BackupError(`--out "${out}" is not a directory`);
277
+ if (readdirSync(out).length > 0) throw new BackupError(`--out "${out}" is not empty`);
278
+ }
279
+ async function copy(source, out, file, key, files) {
280
+ const target = join(out, file);
281
+ const markers = /* @__PURE__ */ new Set();
282
+ const db = new Database(source, { readonly: true, fileMustExist: true });
283
+ try {
284
+ if (key === "storage.receipts.path") {
285
+ const version = db.pragma("user_version", { simple: true });
286
+ if (version < OLDEST_SCHEMA || version > SCHEMA_VERSION) {
287
+ throw new BackupError(
288
+ `the receipt database "${resolve(source)}" is at schema v${version}; this version backs up v${OLDEST_SCHEMA} to v${SCHEMA_VERSION}`
289
+ );
290
+ }
291
+ if (hasTable(db, "legacy_imports")) {
292
+ const rows = db.prepare("SELECT source FROM legacy_imports WHERE path IS NOT NULL").all();
293
+ for (const row of rows) markers.add(row.source);
294
+ }
295
+ }
296
+ closeSync(openSync(target, "wx", 384));
297
+ db.prepare("VACUUM INTO ?").run(target);
298
+ } finally {
299
+ db.close();
300
+ }
301
+ const copied = new Database(target, { readonly: true, fileMustExist: true });
302
+ let schemaVersion;
303
+ try {
304
+ const integrity = copied.pragma("integrity_check", { simple: true });
305
+ if (integrity !== "ok") {
306
+ throw new BackupError(`${file} failed its integrity check: ${String(integrity)}`);
307
+ }
308
+ schemaVersion = copied.pragma("user_version", { simple: true });
309
+ } finally {
310
+ copied.close();
311
+ }
312
+ files.push({ file, source: key, schemaVersion, sha256: await sha256(target) });
313
+ return markers;
314
+ }
315
+ function sha256(path) {
316
+ return new Promise((resolveHash, reject) => {
317
+ const hash = createHash("sha256");
318
+ createReadStream(path).on("data", (chunk) => hash.update(chunk)).on("end", () => resolveHash(hash.digest("hex"))).on("error", reject);
319
+ });
320
+ }
321
+
322
+ // src/cli/commands/demo.ts
323
+ function defaultDemoSteps() {
324
+ return [
325
+ {
326
+ name: "Start the local stack: chain, merchant, gateway and dashboard (docker compose)",
327
+ command: "docker",
328
+ args: ["compose", "up", "--build", "--detach", "--wait"]
329
+ },
330
+ { name: "Run the deterministic buyer agent", command: "npm", args: ["run", "demo:agent"] }
331
+ ];
332
+ }
333
+ async function runDemo(io, deps = {}) {
334
+ const steps = deps.steps ?? defaultDemoSteps();
335
+ const run = deps.run ?? execCommand;
336
+ io.stdout("agent-commerce demo: starting the local stack, then running the buyer agent");
337
+ for (const step of steps) {
338
+ io.stdout("");
339
+ io.stdout(`==> ${step.name}`);
340
+ io.stdout(` $ ${step.command} ${step.args.join(" ")}`);
341
+ const result = await run(step.command, step.args);
342
+ if (result.code !== 0) {
343
+ io.stderr(`FAIL "${step.name}" exited with code ${result.code}.`);
344
+ if (result.stderrTail !== void 0 && result.stderrTail.length > 0) {
345
+ io.stderr(result.stderrTail);
346
+ }
347
+ io.stderr("");
348
+ io.stderr("Nothing further was run. To retry manually:");
349
+ io.stderr(` ${step.command} ${step.args.join(" ")}`);
350
+ return 1;
351
+ }
352
+ io.stdout(`OK ${step.name}`);
353
+ }
354
+ io.stdout("");
355
+ io.stdout("PASS Demo is up. Try: agent-commerce doctor --config config-demo.yaml");
356
+ return 0;
357
+ }
358
+ async function execCommand(command, args) {
359
+ const { spawn } = await import('child_process');
360
+ return new Promise((resolvePromise) => {
361
+ let stderr = "";
362
+ const child = spawn(command, args, { stdio: ["ignore", "inherit", "pipe"] });
363
+ child.stderr?.on("data", (chunk) => {
364
+ stderr += chunk.toString("utf8");
365
+ });
366
+ child.on("error", (err) => {
367
+ resolvePromise({ code: 1, stderrTail: err.message });
368
+ });
369
+ child.on("close", (code) => {
370
+ const tail = stderr.trim().split("\n").slice(-10).join("\n");
371
+ resolvePromise({ code: code ?? 1, ...tail.length > 0 ? { stderrTail: tail } : {} });
372
+ });
373
+ });
374
+ }
375
+
376
+ // src/cli/lib/http.ts
377
+ async function fetchJson(fetchImpl, url, timeoutMs = 1500) {
378
+ try {
379
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
380
+ let body;
381
+ try {
382
+ body = await res.json();
383
+ } catch {
384
+ body = void 0;
385
+ }
386
+ return { ok: res.ok, status: res.status, ...body !== void 0 ? { body } : {} };
387
+ } catch (err) {
388
+ return {
389
+ ok: false,
390
+ status: 0,
391
+ error: err instanceof Error ? err.message : "unknown fetch error"
392
+ };
393
+ }
394
+ }
395
+
216
396
  // package.json
217
397
  var package_default = {
218
398
  dependencies: {
@@ -226,17 +406,16 @@ var package_default = {
226
406
  picocolors: "1.1.1",
227
407
  pino: "10.3.1",
228
408
  yaml: "2.9.0",
229
- zod: "3.25.76"
409
+ zod: "4.6.7"
230
410
  },
231
411
  peerDependencies: {
232
- "@coinbase/x402": "2.1.0",
233
412
  "@modelcontextprotocol/server": "2.3.0",
234
413
  "@sd-jwt/core": "0.20.1",
235
- "@solana/kit": "5.5.1",
236
- "@x402/core": "2.25.0",
237
- "@x402/evm": "2.25.0",
238
- "@x402/near": "2.25.0",
239
- "@x402/svm": "2.25.0",
414
+ "@solana/kit": "8.6.0",
415
+ "@x402/core": "2.30.0",
416
+ "@x402/evm": "2.30.0",
417
+ "@x402/near": "2.30.0",
418
+ "@x402/svm": "2.30.0",
240
419
  canonicalize: "5.0.0",
241
420
  jose: "6.2.12",
242
421
  mppx: "0.13.1",
@@ -253,7 +432,6 @@ var PINS = [
253
432
  ["@x402/svm", "payments/x402"],
254
433
  ["@solana/kit", "payments/x402"],
255
434
  ["@x402/near", "payments/x402"],
256
- ["@coinbase/x402", "payments/x402"],
257
435
  ["viem", "payments/x402"],
258
436
  ["mppx", "payments/mpp"],
259
437
  ["jose", "authorization/ap2"],
@@ -284,85 +462,185 @@ function isWritableFile(path) {
284
462
  return false;
285
463
  }
286
464
  }
287
- function storeFileCheck(name, path, risk, suffix = "") {
465
+ var LEGACY_KEYS = {
466
+ "ap2-replay": { feature: "AP2", key: "authorization.ap2.replay.path" },
467
+ "acp-idempotency": { feature: "ACP", key: "protocols.acp.idempotency.path" }
468
+ };
469
+ function legacyStoreCheck(name, source, path, legacy, pass, note = "") {
470
+ const marker = legacy?.imports.find((entry) => entry.source === source);
471
+ if (marker !== void 0) {
472
+ if (path === void 0) return { name, status: "PASS", detail: pass };
473
+ return path !== ":memory:" && resolve(path) !== marker.path ? {
474
+ name,
475
+ status: "FAIL",
476
+ detail: `deprecated key names "${path}", but "${marker.path}" was imported already, so start refuses it. Point the key back at the imported file, or remove the key${note}`
477
+ } : {
478
+ name,
479
+ status: "WARN",
480
+ detail: `deprecated key: ${marker.rows} row(s) moved into the receipt database at ${marker.importedAt}; remove the key${note}`
481
+ };
482
+ }
483
+ const forgotten = legacy?.missing.includes(source) === true;
288
484
  if (path === ":memory:") {
289
485
  return {
290
486
  name,
291
487
  status: "WARN",
292
- detail: `in-memory store: ${risk.inMemory}; use a file path in production${suffix}`
488
+ detail: forgotten ? `deprecated key: an in-memory store has nothing to import. Start the gateway once with this key set, then remove it${note}` : `deprecated key: an in-memory store has nothing to import; remove the key${note}`
293
489
  };
294
490
  }
295
- if (existsSync(path)) {
296
- return isWritableFile(path) ? { name, status: "PASS", detail: `writable at "${path}"${suffix}` } : {
491
+ if (path === void 0 || !existsSync(path)) {
492
+ if (forgotten) {
493
+ const { feature, key } = LEGACY_KEYS[source];
494
+ return {
495
+ name,
496
+ status: "FAIL",
497
+ detail: `${feature} ran on this receipt database before and its records were never imported, so start refuses ${path === void 0 ? "the unset key" : `"${path}", which does not exist`}. Set ${key} to the file the previous version used, or to an empty file to accept the loss${note}`
498
+ };
499
+ }
500
+ return path === void 0 ? { name, status: "PASS", detail: pass } : {
501
+ name,
502
+ status: "WARN",
503
+ detail: `deprecated key: no file at "${path}", so there is nothing to import; remove the key${note}`
504
+ };
505
+ }
506
+ if (!isWritableFile(path)) {
507
+ return {
297
508
  name,
298
509
  status: "FAIL",
299
- detail: `"${path}" exists but is not writable by this user, so ${risk.unwritable}${suffix}`
510
+ detail: `"${path}" exists but is not writable by this user, so the first start cannot lock the file to import it${note}`
300
511
  };
301
512
  }
302
- return { name, status: "WARN", detail: `${missingStoreDetail(path)}${suffix}` };
513
+ return {
514
+ name,
515
+ status: "WARN",
516
+ detail: legacy === void 0 ? `deprecated key: start imports "${path}" into the receipt database once; the receipt database could not be read to tell whether it has${note}` : `deprecated key: rows in "${path}" are not moved yet. Start the gateway once with this key set, then remove it${note}`
517
+ };
303
518
  }
304
519
  function missingStoreDetail(path) {
305
520
  const directory = dirname(path);
306
521
  return directory !== "." && !existsSync(directory) ? `no store at "${path}" and its directory does not exist. Both are created when the gateway starts, provided the path is writable` : `no store at "${path}" yet. It is created the first time the gateway starts`;
307
522
  }
308
- async function storageChecks(config, createStore) {
309
- const checks = [];
523
+ function refusedSchema(err) {
524
+ if (!isCommerceError(err)) return void 0;
525
+ const { schemaVersion, expected } = err.details ?? {};
526
+ return typeof schemaVersion === "number" && typeof expected === "number" ? { schemaVersion, expected } : void 0;
527
+ }
528
+ async function storageChecks(config, openStore) {
310
529
  if (config === void 0) {
311
- checks.push({ name: "Storage", status: "WARN", detail: "skipped: config invalid" });
312
- } else if (
313
- // Diagnose without creating: createSqliteReceiptStore creates the file,
314
- // so opening a wrong path (a typo, or a container path read from the
315
- // host) would leave an empty database and report it healthy, hiding the
316
- // real one. `:memory:` never exists on disk, so it takes the open branch
317
- // below.
318
- config.storage.receipts.path !== ":memory:" && !existsSync(config.storage.receipts.path)
319
- ) {
530
+ return {
531
+ checks: [{ name: "Storage", status: "WARN", detail: "skipped: config invalid" }],
532
+ legacy: void 0
533
+ };
534
+ }
535
+ const path = config.storage.receipts.path;
536
+ if (path !== ":memory:" && !existsSync(path)) {
537
+ return {
538
+ checks: [
539
+ {
540
+ name: "Storage",
541
+ status: "WARN",
542
+ detail: `${missingStoreDetail(path)}. If the gateway is already running, this path does not match the one it uses.`
543
+ }
544
+ ],
545
+ legacy: { imports: [], missing: [] }
546
+ };
547
+ }
548
+ const checks = [];
549
+ let summary;
550
+ let store;
551
+ try {
552
+ store = openStore(path);
553
+ await store.init();
554
+ const storeHealth = await store.health();
555
+ let receiptCount;
556
+ try {
557
+ receiptCount = await store.countReceipts();
558
+ } catch {
559
+ receiptCount = void 0;
560
+ }
561
+ let undeliveredCount;
562
+ try {
563
+ undeliveredCount = await store.countUndeliveredReceipts();
564
+ } catch {
565
+ undeliveredCount = void 0;
566
+ }
567
+ let uncertainCount;
568
+ try {
569
+ uncertainCount = await store.countUncertainPaymentAttempts();
570
+ } catch {
571
+ uncertainCount = void 0;
572
+ }
573
+ try {
574
+ summary = await store.summary?.({ orphanHoldMinAgeMs: DEFAULT_RECONCILE_MIN_AGE_MS });
575
+ } catch {
576
+ summary = void 0;
577
+ }
578
+ const status = storeHealth.status === "pass" ? "PASS" : storeHealth.status === "warn" ? "WARN" : "FAIL";
579
+ const receiptsSuffix = receiptCount !== void 0 ? `; receipts=${receiptCount}${undeliveredCount !== void 0 && undeliveredCount > 0 ? ` (${undeliveredCount} undelivered)` : ""}` : "";
580
+ const uncertainSuffix = uncertainCount !== void 0 && uncertainCount > 0 ? `; ${uncertainCount} payment(s) with unknown settlement outcome, see GET /api/transactions?unresolved=true or run agent-commerce reconcile` : "";
320
581
  checks.push({
321
582
  name: "Storage",
322
- status: "WARN",
323
- detail: `${missingStoreDetail(config.storage.receipts.path)}. If the gateway is already running, this path does not match the one it uses.`
583
+ status,
584
+ detail: `${storeHealth.detail ?? "sqlite"}${receiptsSuffix}${uncertainSuffix}`
324
585
  });
325
- } else {
326
- let store;
327
- try {
328
- store = createStore(config.storage.receipts.path);
329
- await store.init();
330
- const storeHealth = await store.health();
331
- let receiptCount;
332
- try {
333
- receiptCount = await store.countReceipts();
334
- } catch {
335
- receiptCount = void 0;
336
- }
337
- let undeliveredCount;
338
- try {
339
- undeliveredCount = await store.countUndeliveredReceipts();
340
- } catch {
341
- undeliveredCount = void 0;
342
- }
343
- let uncertainCount;
344
- try {
345
- uncertainCount = await store.countUncertainPaymentAttempts();
346
- } catch {
347
- uncertainCount = void 0;
348
- }
349
- const status = storeHealth.status === "pass" ? "PASS" : storeHealth.status === "warn" ? "WARN" : "FAIL";
350
- const receiptsSuffix = receiptCount !== void 0 ? `; receipts=${receiptCount}${undeliveredCount !== void 0 && undeliveredCount > 0 ? ` (${undeliveredCount} undelivered)` : ""}` : "";
351
- const uncertainSuffix = uncertainCount !== void 0 && uncertainCount > 0 ? `; ${uncertainCount} payment(s) with unknown settlement outcome, see GET /api/transactions?unresolved=true or run agent-commerce reconcile` : "";
352
- checks.push({
353
- name: "Storage",
354
- status,
355
- detail: `${storeHealth.detail ?? "sqlite"}${receiptsSuffix}${uncertainSuffix}`
356
- });
357
- } catch (err) {
358
- checks.push({
359
- name: "Storage",
360
- status: "FAIL",
361
- detail: err instanceof Error ? err.message : String(err)
362
- });
363
- } finally {
364
- await store?.close();
586
+ } catch (err) {
587
+ const refused = refusedSchema(err);
588
+ if (refused !== void 0 && refused.schemaVersion < refused.expected) {
589
+ const missing = readMissingLegacyImports(path);
590
+ return {
591
+ checks: [
592
+ {
593
+ name: "Storage",
594
+ status: "WARN",
595
+ detail: `sqlite schema v${refused.schemaVersion}; the next start migrates it to v${refused.expected}, which earlier versions cannot open. Run agent-commerce backup first to keep a copy they can`
596
+ }
597
+ ],
598
+ legacy: missing !== void 0 ? { imports: [], missing } : void 0
599
+ };
365
600
  }
601
+ checks.push({
602
+ name: "Storage",
603
+ status: "FAIL",
604
+ detail: refused !== void 0 ? `sqlite schema v${refused.schemaVersion} is newer than this version reads (v${refused.expected}); run the version that wrote it` : err instanceof Error ? err.message : String(err)
605
+ });
606
+ } finally {
607
+ await store?.close();
608
+ }
609
+ if (summary !== void 0) checks.push(...summaryChecks(summary));
610
+ return {
611
+ checks,
612
+ legacy: summary !== void 0 ? { imports: summary.legacyImports, missing: summary.missingLegacyImports } : void 0
613
+ };
614
+ }
615
+ function summaryChecks(summary) {
616
+ const states = Object.entries(summary.unresolvedTransactions);
617
+ const checks = [
618
+ states.length > 0 ? {
619
+ name: "Transactions",
620
+ status: "WARN",
621
+ detail: `unresolved: ${states.map(([state, count]) => `${state}=${count}`).join(", ")}; see GET /api/transactions?unresolved=true or run agent-commerce reconcile`
622
+ } : { name: "Transactions", status: "PASS", detail: "none unresolved" }
623
+ ];
624
+ if (summary.orphanHolds > 0) {
625
+ checks.push({
626
+ name: "Authorization holds",
627
+ status: "WARN",
628
+ detail: `${summary.orphanHolds} reserved hold(s) older than ${DEFAULT_RECONCILE_MIN_AGE_MS / 6e4} min have no payment attempt and keep their mandates blocked; agent-commerce reconcile releases them while their authorization method is enabled`
629
+ });
630
+ }
631
+ if (summary.unresolvedIdempotencyKeys > 0) {
632
+ checks.push({
633
+ name: "ACP claims",
634
+ status: "INFO",
635
+ detail: `${summary.unresolvedIdempotencyKeys} unresolved; a retry with the same Idempotency-Key gets 409 idempotency_unresolved`
636
+ });
637
+ }
638
+ if (summary.unresolvedPaymentKeys > 0) {
639
+ checks.push({
640
+ name: "Payment retry keys",
641
+ status: "INFO",
642
+ detail: `${summary.unresolvedPaymentKeys} unresolved; a paid retry with the same key gets 409 payment_identifier_unresolved`
643
+ });
366
644
  }
367
645
  return checks;
368
646
  }
@@ -374,7 +652,7 @@ function describeIssuers(label, issuers) {
374
652
  ).join(", ");
375
653
  return `${label} issuers: ${described}`;
376
654
  }
377
- function ap2Checks(config) {
655
+ function ap2Checks(config, legacy) {
378
656
  const checks = [];
379
657
  const ap2 = config?.authorization?.ap2;
380
658
  if (config === void 0) {
@@ -393,10 +671,13 @@ function ap2Checks(config) {
393
671
  detail: `${describeIssuers("mandate", ap2.trust.mandateIssuers)} \xB7 ${describeIssuers("checkout", ap2.trust.checkoutIssuers)}`
394
672
  });
395
673
  checks.push(
396
- storeFileCheck("AP2 replay store", ap2.replay.path, {
397
- inMemory: "every spent mandate is forgotten on restart, so one could authorize a second purchase",
398
- unwritable: "no mandate could be recorded as spent"
399
- })
674
+ legacyStoreCheck(
675
+ "AP2 replay store",
676
+ "ap2-replay",
677
+ ap2.replay?.path,
678
+ legacy,
679
+ "mandate holds in the receipt database"
680
+ )
400
681
  );
401
682
  const gated = config.resources.filter(
402
683
  (resource) => resource.authorization?.required.includes("ap2")
@@ -518,9 +799,9 @@ var HEADER = `# Generated by \`agent-commerce init\`.
518
799
  #
519
800
  # server.adminToken and server.allowedOrigins are left unset, so no secret
520
801
  # lands in a file you might commit. Without a token the operator routes
521
- # (/api/receipts, /api/events, /api/payment-attempts) return 404. These routes
522
- # expose the merchant's commerce ledger: payer addresses, amounts and settlement
523
- # hashes. To enable them, add these keys to the server block below:
802
+ # (/api/receipts, /api/events, /api/payment-attempts, /api/transactions and the
803
+ # resolve route) return 404. They expose payer addresses, amounts and settlement
804
+ # hashes from the merchant's ledger. To enable them, add these keys below:
524
805
  # server:
525
806
  # adminToken: \${ADMIN_TOKEN}
526
807
  # allowedOrigins:
@@ -663,13 +944,13 @@ function describeSettlement(network, facilitator, customNetworks) {
663
944
  const via = facilitator.mode === "local" ? "local (in-process)" : `remote (auth=${facilitator.auth.type})`;
664
945
  return { mode, where, via };
665
946
  }
666
- function mainnetSafetyCheck(name, payToField, facilitator, networks) {
947
+ function mainnetSafetyCheck(name, payToField, facilitator, networks, assetRule) {
667
948
  const unauthenticated = facilitator.mode === "remote" && facilitator.auth.type === "none";
668
949
  const where = `${describeDeploymentMode("mainnet")} on ${networks.join(", ")}`;
669
950
  return {
670
951
  name,
671
952
  status: unauthenticated ? "WARN" : "INFO",
672
- detail: unauthenticated ? `${where}: no credential is sent to the remote facilitator (accepted via allowUnauthenticatedFacilitator); its anonymous-access limits apply. Config load also requires allowMainnet, HTTPS, a non-development ${payToField} and the canonical asset. Payments fail closed.` : `${where}. Enforced at config load: explicit allowMainnet opt-in, remote facilitator over HTTPS with a credential, non-development ${payToField}, and the canonical asset of each network. Payments fail closed.`
953
+ detail: unauthenticated ? `${where}: no credential is sent to the remote facilitator (accepted via allowUnauthenticatedFacilitator); its anonymous-access limits apply. Config load also requires allowMainnet, HTTPS, a non-development ${payToField} and ${assetRule}. Payments fail closed.` : `${where}. Enforced at config load: explicit allowMainnet opt-in, remote facilitator over HTTPS with a credential, non-development ${payToField}, and ${assetRule}. Payments fail closed.`
673
954
  };
674
955
  }
675
956
  function railOffer(option) {
@@ -847,9 +1128,13 @@ async function paymentChecks(config, wellKnown, gatewayUrl, chainDeploy = false,
847
1128
  if (quotes !== void 0) checks.push(quotes);
848
1129
  if (mode === "mainnet") {
849
1130
  checks.push(
850
- mainnetSafetyCheck("Mainnet safety", "payTo", x402.facilitator, [
851
- ...new Set(everyOption.map((option) => named(option.network)))
852
- ])
1131
+ mainnetSafetyCheck(
1132
+ "Mainnet safety",
1133
+ "payTo",
1134
+ x402.facilitator,
1135
+ [...new Set(everyOption.map((option) => named(option.network)))],
1136
+ "each network's USDC, or another EVM token with its own metadata"
1137
+ )
853
1138
  );
854
1139
  }
855
1140
  }
@@ -892,9 +1177,13 @@ async function paymentChecks(config, wellKnown, gatewayUrl, chainDeploy = false,
892
1177
  }
893
1178
  if (mode === "mainnet") {
894
1179
  checks.push(
895
- mainnetSafetyCheck("Mainnet safety (MPP)", "recipient", mpp.facilitator, [
896
- `${findX402Network(mpp.network)?.displayName ?? "unknown network"} (${mpp.network})`
897
- ])
1180
+ mainnetSafetyCheck(
1181
+ "Mainnet safety (MPP)",
1182
+ "recipient",
1183
+ mpp.facilitator,
1184
+ [`${findX402Network(mpp.network)?.displayName ?? "unknown network"} (${mpp.network})`],
1185
+ "the canonical asset"
1186
+ )
898
1187
  );
899
1188
  }
900
1189
  }
@@ -927,7 +1216,7 @@ function acpMappingCheck(config, operations) {
927
1216
  detail: `5 operations mapped to free acp-exposed resources (${Object.values(operations).join(", ")})`
928
1217
  };
929
1218
  }
930
- function protocolChecks(config, wellKnown) {
1219
+ function protocolChecks(config, wellKnown, legacy) {
931
1220
  const checks = [];
932
1221
  if (config === void 0) {
933
1222
  checks.push({ name: "Protocols", status: "WARN", detail: "skipped: config invalid" });
@@ -975,13 +1264,12 @@ function protocolChecks(config, wellKnown) {
975
1264
  detail: `bearer token configured (${acp.auth.token.length} characters, not shown)`
976
1265
  });
977
1266
  checks.push(
978
- storeFileCheck(
1267
+ legacyStoreCheck(
979
1268
  "ACP idempotency",
1269
+ "acp-idempotency",
980
1270
  acp.idempotency.path,
981
- {
982
- inMemory: "replay protection is lost on every restart",
983
- unwritable: "the adapter cannot claim idempotency keys"
984
- },
1271
+ legacy,
1272
+ `claims in the receipt database (retention ${acp.idempotency.retentionHours}h)`,
985
1273
  ` (retention ${acp.idempotency.retentionHours}h)`
986
1274
  )
987
1275
  );
@@ -1041,7 +1329,7 @@ function substitutePathParams(url) {
1041
1329
  async function runDoctor(options, deps = {}) {
1042
1330
  const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
1043
1331
  const loadConfig = deps.loadConfig ?? loadConfigDynamic;
1044
- const createStore = deps.createStore ?? ((path) => createSqliteReceiptStore({ path }));
1332
+ const createStore = deps.createStore ?? ((path) => path === ":memory:" ? createSqliteReceiptStore({ path }) : openSqliteReceiptStoreReadOnly(path));
1045
1333
  const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;
1046
1334
  const chainDeploy = (deps.hasChainDeployScript ?? hasChainDeployScript)();
1047
1335
  const checks = [];
@@ -1110,12 +1398,13 @@ async function runDoctor(options, deps = {}) {
1110
1398
  `${gatewayUrl}/.well-known/agent-commerce`,
1111
1399
  CHECK_TIMEOUT_MS
1112
1400
  ) : void 0;
1113
- checks.push(...protocolChecks(config, wellKnown));
1114
- checks.push(...ap2Checks(config));
1401
+ const storage = await storageChecks(config, createStore);
1402
+ checks.push(...protocolChecks(config, wellKnown, storage.legacy));
1403
+ checks.push(...ap2Checks(config, storage.legacy));
1115
1404
  checks.push(
1116
1405
  ...await paymentChecks(config, wellKnown, gatewayUrl, chainDeploy, deps.loadViemAccounts)
1117
1406
  );
1118
- checks.push(...await storageChecks(config, createStore));
1407
+ checks.push(...storage.checks);
1119
1408
  if (wellKnown?.ok) {
1120
1409
  checks.push({
1121
1410
  name: "Protocol versions",
@@ -2301,58 +2590,6 @@ function printSummary(result, context, io) {
2301
2590
  function describe(error) {
2302
2591
  return error instanceof Error ? error.message : String(error);
2303
2592
  }
2304
-
2305
- // src/cli/commands/validate.ts
2306
- function formatConfigError(err, manifestFound = false, chainDeploy = hasChainDeployScript()) {
2307
- if (isCommerceError(err)) {
2308
- const lines = [`FAIL ${err.code}: ${err.message}`];
2309
- if (err.details !== void 0) {
2310
- lines.push(` details: ${JSON.stringify(err.details)}`);
2311
- }
2312
- const variable = err.details?.["variable"];
2313
- if (typeof variable === "string") {
2314
- lines.push(` hint: ${unresolvedVariableHint(variable, manifestFound, chainDeploy)}`);
2315
- }
2316
- return lines.join("\n");
2317
- }
2318
- if (err instanceof Error) {
2319
- return `FAIL ${err.message}`;
2320
- }
2321
- return `FAIL ${String(err)}`;
2322
- }
2323
- async function runValidate(options, io, deps = {}) {
2324
- const loadConfig = deps.loadConfig ?? loadConfigDynamic;
2325
- const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;
2326
- const { env, filled, manifestFound } = fillEnvFromManifest(process.env);
2327
- if (filled.length > 0) {
2328
- io.stdout(`using local chain manifest ${LOCAL_CHAIN_MANIFEST_PATH} for ${filled.join(", ")}`);
2329
- }
2330
- try {
2331
- const config = await loadConfig({
2332
- ...options.configPath !== void 0 ? { path: options.configPath } : {},
2333
- env
2334
- });
2335
- io.stdout("PASS Configuration is valid");
2336
- io.stdout(` merchant: ${config.merchant.name} (${config.merchant.id})`);
2337
- io.stdout(` resources: ${config.resources.length}`);
2338
- io.stdout(
2339
- ` protocols: http=${config.protocols.http.enabled ? "on" : "off"} mcp=${config.protocols.mcp.enabled ? "on" : "off"} a2a=${config.protocols.a2a.enabled ? "on" : "off"} acp=${config.protocols.acp.enabled ? "on" : "off"}`
2340
- );
2341
- const onOff = (enabled) => enabled === true ? "on" : "off";
2342
- io.stdout(
2343
- ` payments: x402=${onOff(config.payments.x402?.enabled)} mpp=${onOff(config.payments.mpp?.enabled)}`
2344
- );
2345
- io.stdout(` authorization: ap2=${onOff(config.authorization?.ap2.enabled)}`);
2346
- return 0;
2347
- } catch (err) {
2348
- io.stderr(
2349
- formatConfigError(err, manifestFound, (deps.hasChainDeployScript ?? hasChainDeployScript)())
2350
- );
2351
- return 1;
2352
- }
2353
- }
2354
-
2355
- // src/cli/commands/init.ts
2356
2593
  async function collectAnswersInteractive() {
2357
2594
  clack.intro("agent-commerce init");
2358
2595
  const backendBaseUrl = await clack.text({
@@ -2508,10 +2745,11 @@ async function runReconcileCommand(options, io, deps = {}) {
2508
2745
  }
2509
2746
  try {
2510
2747
  const logger = stderrLogger(io);
2511
- const { runReconcile } = await import('./reconcile-IC22MJD5.js');
2512
- const providers = await (await import('./payment-providers-SZL36H3Y.js')).createConfiguredPaymentProviders(config.payments, logger);
2748
+ const { runReconcile } = await import('./reconcile-GS25MQ42.js');
2749
+ const providers = await (await import('./payment-providers-EWXZFBIE.js')).createConfiguredPaymentProviders(config.payments, logger);
2750
+ let report;
2513
2751
  await withJournal(config, logger, async (store, authorizationProviders) => {
2514
- const report = await runReconcile({
2752
+ report = await runReconcile({
2515
2753
  store,
2516
2754
  providers,
2517
2755
  authorizationProviders,
@@ -2524,6 +2762,12 @@ async function runReconcileCommand(options, io, deps = {}) {
2524
2762
  });
2525
2763
  printReport(report, io, options.json === true);
2526
2764
  });
2765
+ if (report !== void 0 && report.failedScans.length > 0) {
2766
+ io.stderr(
2767
+ `FAIL reconcile could not finish the ${report.failedScans.join(" and ")} scan; the resolutions above are saved, so run it again`
2768
+ );
2769
+ return 1;
2770
+ }
2527
2771
  return 0;
2528
2772
  } catch (error) {
2529
2773
  io.stderr(`FAIL reconcile could not run: ${redactedErrorText(error)}`);
@@ -2531,24 +2775,54 @@ async function runReconcileCommand(options, io, deps = {}) {
2531
2775
  }
2532
2776
  }
2533
2777
  async function withJournal(config, logger, fn) {
2534
- const [{ createConfiguredAuthorizationProviders }, { createSqliteReceiptStore: createSqliteReceiptStore2 }] = await Promise.all([
2535
- import('./payment-providers-SZL36H3Y.js'),
2536
- import('./receipts-ZGLJWMQG.js')
2778
+ const [
2779
+ { createConfiguredAuthorizationProviders },
2780
+ { createSqliteReceiptStore: createSqliteReceiptStore2, openSqliteReceiptStoreReadOnly: openSqliteReceiptStoreReadOnly2 }
2781
+ ] = await Promise.all([
2782
+ import('./payment-providers-EWXZFBIE.js'),
2783
+ import('./receipts-3DSV4DIK.js')
2537
2784
  ]);
2538
- const authorizationProviders = await createConfiguredAuthorizationProviders(
2539
- config.authorization,
2540
- logger
2541
- );
2785
+ const path = config.storage.receipts.path;
2786
+ if (path !== ":memory:" && existsSync(path)) {
2787
+ try {
2788
+ await openSqliteReceiptStoreReadOnly2(path).close();
2789
+ } catch (error) {
2790
+ const { schemaVersion, expected } = isCommerceError(error) ? error.details ?? {} : {};
2791
+ if (typeof schemaVersion === "number" && typeof expected === "number" && schemaVersion < expected) {
2792
+ throw new CommerceError(
2793
+ "STORAGE_ERROR",
2794
+ `the receipt database "${resolve(path)}" is at schema v${schemaVersion}, and this version would migrate it to v${expected}, which earlier versions cannot open. Run agent-commerce backup, start the gateway once to migrate it, then retry.`
2795
+ );
2796
+ }
2797
+ throw error;
2798
+ }
2799
+ }
2800
+ const store = createSqliteReceiptStore2({ path, logger });
2542
2801
  try {
2543
- const store = createSqliteReceiptStore2({ path: config.storage.receipts.path, logger });
2802
+ await store.init();
2803
+ const ap2 = config.authorization?.ap2;
2804
+ const replayPath = ap2?.enabled ? ap2.replay?.path : void 0;
2805
+ if (replayPath !== void 0 && replayPath !== ":memory:" && existsSync(replayPath)) {
2806
+ const { legacyImports } = await store.summary({ orphanHoldMinAgeMs: 0 });
2807
+ if (!legacyImports.some((entry) => entry.source === "ap2-replay")) {
2808
+ throw new CommerceError(
2809
+ "STORAGE_ERROR",
2810
+ `the AP2 replay file "${resolve(replayPath)}" has not been imported into the receipt database yet. Run \`agent-commerce start\` once to import it, then retry.`
2811
+ );
2812
+ }
2813
+ }
2814
+ const authorizationProviders = await createConfiguredAuthorizationProviders(
2815
+ config.authorization,
2816
+ logger,
2817
+ store
2818
+ );
2544
2819
  try {
2545
- await store.init();
2546
2820
  await fn(store, authorizationProviders);
2547
2821
  } finally {
2548
- await store.close();
2822
+ for (const provider of authorizationProviders) provider.close();
2549
2823
  }
2550
2824
  } finally {
2551
- for (const provider of authorizationProviders) provider.close();
2825
+ await store.close();
2552
2826
  }
2553
2827
  }
2554
2828
  function parseDuration(value) {
@@ -2564,12 +2838,21 @@ function printReport(report, io, json) {
2564
2838
  notSettled: count("not-settled"),
2565
2839
  unknown: count("unknown"),
2566
2840
  resolved: report.entries.filter((e) => e.written).length,
2567
- holdsAligned: report.holds.filter((h) => h.written).length
2841
+ holdsAligned: report.holds.filter((h) => h.written).length,
2842
+ orphanHolds: report.orphanHolds.length,
2843
+ orphanHoldsReleased: report.orphanHolds.filter((h) => h.released).length
2568
2844
  };
2569
2845
  if (json) {
2570
2846
  io.stdout(
2571
2847
  JSON.stringify(
2572
- { dryRun: report.dryRun, counts, entries: report.entries, holds: report.holds },
2848
+ {
2849
+ dryRun: report.dryRun,
2850
+ counts,
2851
+ entries: report.entries,
2852
+ holds: report.holds,
2853
+ orphanHolds: report.orphanHolds,
2854
+ failedScans: report.failedScans
2855
+ },
2573
2856
  null,
2574
2857
  2
2575
2858
  )
@@ -2577,7 +2860,7 @@ function printReport(report, io, json) {
2577
2860
  return;
2578
2861
  }
2579
2862
  io.stdout(
2580
- `reconcile${report.dryRun ? " (dry run, no resolutions written)" : ""}: ${counts.candidates} candidates, ${counts.settled} settled, ${counts.notSettled} not settled, ${counts.unknown} unknown, ${counts.resolved} resolved` + (report.holds.length > 0 ? `, ${counts.holdsAligned} of ${report.holds.length} holds aligned` : "")
2863
+ `reconcile${report.dryRun ? " (dry run, no resolutions written)" : ""}: ${counts.candidates} candidates, ${counts.settled} settled, ${counts.notSettled} not settled, ${counts.unknown} unknown, ${counts.resolved} resolved` + (report.holds.length > 0 ? `, ${counts.holdsAligned} of ${report.holds.length} holds aligned` : "") + (report.orphanHolds.length > 0 ? `, ${counts.orphanHoldsReleased} of ${report.orphanHolds.length} orphan holds released` : "")
2581
2864
  );
2582
2865
  for (const entry of report.entries) {
2583
2866
  io.stdout(
@@ -2608,6 +2891,19 @@ function printReport(report, io, json) {
2608
2891
  ].join(" ")
2609
2892
  );
2610
2893
  }
2894
+ for (const hold of report.orphanHolds) {
2895
+ io.stdout(
2896
+ [
2897
+ "ORPHAN".padEnd(11),
2898
+ hold.reference,
2899
+ `request=${hold.requestId}`,
2900
+ `method=${hold.method}`,
2901
+ `updated=${hold.updatedAt}`,
2902
+ ...hold.reason !== void 0 ? [`reason=${hold.reason}`] : [],
2903
+ ...hold.released ? ["released"] : []
2904
+ ].join(" ")
2905
+ );
2906
+ }
2611
2907
  }
2612
2908
  function osUser() {
2613
2909
  try {
@@ -2639,7 +2935,7 @@ async function runResolveCommand(attemptId, options, io, deps = {}) {
2639
2935
  return 1;
2640
2936
  }
2641
2937
  try {
2642
- const { resolveManually } = await import('./reconcile-IC22MJD5.js');
2938
+ const { resolveManually } = await import('./reconcile-GS25MQ42.js');
2643
2939
  const logger = stderrLogger(io);
2644
2940
  let code = 1;
2645
2941
  await withJournal(config, logger, async (store, authorizationProviders) => {
@@ -2712,7 +3008,7 @@ var ENV_FILE_HELP = "load environment variables from this file; variables alread
2712
3008
  function buildProgram(io = processIo) {
2713
3009
  const program = new Command();
2714
3010
  program.name("agent-commerce").description(
2715
- "CLI for the Agent Commerce Gateway: init, import, validate, start, doctor, reconcile, demo."
3011
+ "CLI for the Agent Commerce Gateway: init, import, validate, start, doctor, reconcile, backup, demo."
2716
3012
  ).version(readVersionReport().cliVersion, "-v, --version", "Print the CLI version.").exitOverride().configureOutput({
2717
3013
  writeOut: (str) => io.stdout(str.replace(/\n+$/, "")),
2718
3014
  writeErr: (str) => io.stderr(str.replace(/\n+$/, ""))
@@ -2741,7 +3037,7 @@ function buildProgram(io = processIo) {
2741
3037
  `Start the gateway from ${DEFAULT_CONFIG_FILENAME} and serve until SIGTERM or SIGINT.`
2742
3038
  ).option("--config <path>", `path to ${DEFAULT_CONFIG_FILENAME}`).option("--env-file <path>", ENV_FILE_HELP).action(async (opts) => {
2743
3039
  try {
2744
- const { runGateway } = await import('./run-ZTYPQI4D.js');
3040
+ const { runGateway } = await import('./run-7KLKW3HE.js');
2745
3041
  await runGateway(opts.config !== void 0 ? { configPath: opts.config } : {});
2746
3042
  } catch (error) {
2747
3043
  io.stderr(formatConfigError(error, false, false));
@@ -2801,6 +3097,18 @@ function buildProgram(io = processIo) {
2801
3097
  );
2802
3098
  }
2803
3099
  );
3100
+ program.command("backup").description(
3101
+ "Copy the receipt database, and deprecated store files not yet imported, into a new directory."
3102
+ ).requiredOption("--out <dir>", "a new or empty directory for the copies and backup.json").option("--config <path>", `path to ${DEFAULT_CONFIG_FILENAME}`).option("--env-file <path>", ENV_FILE_HELP).option("--json", "emit machine-readable JSON instead of a formatted report", false).action(async (opts) => {
3103
+ process.exitCode = await runBackupCommand(
3104
+ {
3105
+ out: opts.out,
3106
+ ...opts.config !== void 0 ? { configPath: opts.config } : {},
3107
+ json: opts.json
3108
+ },
3109
+ io
3110
+ );
3111
+ });
2804
3112
  program.command("init").description(`Interactively generate ${DEFAULT_CONFIG_FILENAME}.`).option("--output <path>", "output path", DEFAULT_CONFIG_FILENAME).option("--force", "overwrite an existing file", false).option("--yes", "use non-interactive defaults (required for scripting/tests)", false).action(async (opts) => {
2805
3113
  const code = await runInit({ outputPath: opts.output, force: opts.force, yes: opts.yes }, io);
2806
3114
  process.exitCode = code;