@devlab.group/agent-commerce 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +63 -11
  2. package/dist/ap2.d.ts +19 -6
  3. package/dist/ap2.js +56 -18
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-FKQK5XZA.js → chunk-DRLBML7Z.js} +13 -11
  6. package/dist/chunk-DRLBML7Z.js.map +1 -0
  7. package/dist/{chunk-VUCMBGUR.js → chunk-G3EYYHKF.js} +3 -3
  8. package/dist/{chunk-VUCMBGUR.js.map → chunk-G3EYYHKF.js.map} +1 -1
  9. package/dist/{chunk-3OTCFFFT.js → chunk-M52FBNJX.js} +3 -5
  10. package/dist/chunk-M52FBNJX.js.map +1 -0
  11. package/dist/chunk-M6BSXXTF.js +8 -0
  12. package/dist/chunk-M6BSXXTF.js.map +1 -0
  13. package/dist/{chunk-4K7FIBJM.js → chunk-M6MQ3FYS.js} +3 -3
  14. package/dist/{chunk-4K7FIBJM.js.map → chunk-M6MQ3FYS.js.map} +1 -1
  15. package/dist/chunk-M6WW6QIT.js +18 -0
  16. package/dist/chunk-M6WW6QIT.js.map +1 -0
  17. package/dist/cli/{ap2-YAPLERSC.js → ap2-2YMYA2H6.js} +57 -20
  18. package/dist/cli/ap2-2YMYA2H6.js.map +1 -0
  19. package/dist/cli/{chunk-5R7DM5LM.js → chunk-3NOMLMJW.js} +26 -26
  20. package/dist/cli/chunk-3NOMLMJW.js.map +1 -0
  21. package/dist/cli/chunk-4KLYFXMW.js +8 -0
  22. package/dist/cli/{chunk-M7NXVRU5.js.map → chunk-4KLYFXMW.js.map} +1 -1
  23. package/dist/cli/chunk-6R6WJ4FD.js +18 -0
  24. package/dist/cli/chunk-6R6WJ4FD.js.map +1 -0
  25. package/dist/cli/{chunk-2J2IQQ4X.js → chunk-AZL7RPFU.js} +37 -32
  26. package/dist/cli/chunk-AZL7RPFU.js.map +1 -0
  27. package/dist/cli/{chunk-JFVRG2HH.js → chunk-DHFMIBPG.js} +7 -7
  28. package/dist/cli/chunk-DHFMIBPG.js.map +1 -0
  29. package/dist/cli/{chunk-IDY2735M.js → chunk-GET3CZGR.js} +2 -2
  30. package/dist/cli/chunk-GET3CZGR.js.map +1 -0
  31. package/dist/cli/{chunk-QLUCNPRT.js → chunk-NSYSMDQN.js} +831 -169
  32. package/dist/cli/chunk-NSYSMDQN.js.map +1 -0
  33. package/dist/cli/{chunk-Z34UMZBB.js → chunk-PTL7SNOI.js} +83 -57
  34. package/dist/cli/chunk-PTL7SNOI.js.map +1 -0
  35. package/dist/cli/{chunk-2UPPX3FJ.js → chunk-TFV3K6YS.js} +75 -13
  36. package/dist/cli/chunk-TFV3K6YS.js.map +1 -0
  37. package/dist/cli/{chunk-NIU5EMSB.js → chunk-VJH6RYRK.js} +5 -5
  38. package/dist/cli/{chunk-NIU5EMSB.js.map → chunk-VJH6RYRK.js.map} +1 -1
  39. package/dist/cli/{chunk-QA2OPHBF.js → chunk-YOF7IK4V.js} +14 -13
  40. package/dist/cli/chunk-YOF7IK4V.js.map +1 -0
  41. package/dist/cli/{chunk-4H2QLHQI.js → chunk-YWG2ZN3L.js} +3 -3
  42. package/dist/cli/{chunk-4H2QLHQI.js.map → chunk-YWG2ZN3L.js.map} +1 -1
  43. package/dist/cli/config-3K65QJ22.js +12 -0
  44. package/dist/cli/{config-BWFMN2ZB.js.map → config-3K65QJ22.js.map} +1 -1
  45. package/dist/cli/index.js +524 -230
  46. package/dist/cli/index.js.map +1 -1
  47. package/dist/cli/{mcp-KZEMXLHR.js → mcp-6F64A7KE.js} +4 -4
  48. package/dist/cli/{mcp-KZEMXLHR.js.map → mcp-6F64A7KE.js.map} +1 -1
  49. package/dist/cli/payment-providers-2ITS6KNR.js +6 -0
  50. package/dist/cli/{payment-providers-SZL36H3Y.js.map → payment-providers-2ITS6KNR.js.map} +1 -1
  51. package/dist/cli/{provider-6TKB5ADJ.js → provider-5BGG5YKQ.js} +34 -16
  52. package/dist/cli/provider-5BGG5YKQ.js.map +1 -0
  53. package/dist/cli/receipts-I4IIE7U6.js +8 -0
  54. package/dist/cli/{receipts-ZGLJWMQG.js.map → receipts-I4IIE7U6.js.map} +1 -1
  55. package/dist/cli/reconcile-55WNCSFC.js +4 -0
  56. package/dist/cli/{reconcile-IC22MJD5.js.map → reconcile-55WNCSFC.js.map} +1 -1
  57. package/dist/cli/{run-ZTYPQI4D.js → run-2P6ZGFUE.js} +220 -73
  58. package/dist/cli/run-2P6ZGFUE.js.map +1 -0
  59. package/dist/cli/{x402-WLYBLODI.js → x402-4LPIIELI.js} +8 -8
  60. package/dist/cli/{x402-WLYBLODI.js.map → x402-4LPIIELI.js.map} +1 -1
  61. package/dist/index.d.ts +104 -201
  62. package/dist/index.js +1048 -262
  63. package/dist/index.js.map +1 -1
  64. package/dist/logger-CllGwQ8i.d.ts +19 -0
  65. package/dist/mcp.d.ts +3 -1
  66. package/dist/mcp.js +2 -1
  67. package/dist/mcp.js.map +1 -1
  68. package/dist/mpp.d.ts +2 -1
  69. package/dist/mpp.js +31 -12
  70. package/dist/mpp.js.map +1 -1
  71. package/dist/{protocol-adapter-DEXpdp8m.d.ts → protocol-adapter-1WbtM3xG.d.ts} +5 -132
  72. package/dist/{runtime-Dz2fSO-P.d.ts → runtime-B-kARa2f.d.ts} +5 -20
  73. package/dist/store-kIIMpUA-.d.ts +372 -0
  74. package/dist/testing.d.ts +51 -0
  75. package/dist/testing.js +1896 -0
  76. package/dist/testing.js.map +1 -0
  77. package/dist/transaction-Dv0UFGg5.d.ts +129 -0
  78. package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
  79. package/dist/x402.d.ts +2 -1
  80. package/dist/x402.js +5 -4
  81. package/dist/x402.js.map +1 -1
  82. package/package.json +5 -1
  83. package/dist/chunk-3OTCFFFT.js.map +0 -1
  84. package/dist/chunk-FKQK5XZA.js.map +0 -1
  85. package/dist/cli/ap2-YAPLERSC.js.map +0 -1
  86. package/dist/cli/chunk-2J2IQQ4X.js.map +0 -1
  87. package/dist/cli/chunk-2UPPX3FJ.js.map +0 -1
  88. package/dist/cli/chunk-5R7DM5LM.js.map +0 -1
  89. package/dist/cli/chunk-IDY2735M.js.map +0 -1
  90. package/dist/cli/chunk-JFVRG2HH.js.map +0 -1
  91. package/dist/cli/chunk-M7NXVRU5.js +0 -8
  92. package/dist/cli/chunk-QA2OPHBF.js.map +0 -1
  93. package/dist/cli/chunk-QLUCNPRT.js.map +0 -1
  94. package/dist/cli/chunk-Z34UMZBB.js.map +0 -1
  95. package/dist/cli/config-BWFMN2ZB.js +0 -12
  96. package/dist/cli/payment-providers-SZL36H3Y.js +0 -6
  97. package/dist/cli/provider-6TKB5ADJ.js.map +0 -1
  98. package/dist/cli/receipts-ZGLJWMQG.js +0 -8
  99. package/dist/cli/reconcile-IC22MJD5.js +0 -4
  100. package/dist/cli/run-ZTYPQI4D.js.map +0 -1
package/dist/cli/index.js CHANGED
@@ -1,20 +1,23 @@
1
1
  #!/usr/bin/env node
2
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';
3
+ import { A2A_SPEC_VERSION, A2A_PROTOCOL_VERSION, A2A_PROTOCOL_BINDING, A2A_AGENT_CARD_PATH, A2A_UNSUPPORTED, ACP_UNSUPPORTED } from './chunk-VJH6RYRK.js';
4
+ import { DEFAULT_CONFIG_FILENAME, extractPathParameterNames, ACP_SPEC_VERSION, ACP_API_VERSION, ACP_WELL_KNOWN_PATH, findUnparsedBraceToken } from './chunk-PTL7SNOI.js';
7
5
  import { AP2_SPEC_VERSION, AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE } from './chunk-FHCFR2GS.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-NSYSMDQN.js';
8
+ import './chunk-VJ4EO4LE.js';
9
+ import { DEFAULT_RECONCILE_MIN_AGE_MS } from './chunk-TFV3K6YS.js';
9
10
  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';
11
+ import { ANVIL_WELL_KNOWN_ACCOUNTS, describeDeploymentMode, X402_DEFAULT_PAYMENT_FLOW, findX402Network, isEvmAddress, LOCAL_CHAIN_ID, resolveDeploymentMode, sameAddress } from './chunk-3NOMLMJW.js';
12
+ import { PACKAGE_VERSION } from './chunk-4KLYFXMW.js';
13
+ import { PROTOCOL_NAMES, systemClock, NOOP_LOGGER } from './chunk-GET3CZGR.js';
13
14
  import { isCommerceError, redactedErrorText, CommerceError } from './chunk-SYQLJXIU.js';
14
15
  import { isRecord } from './chunk-3M6U7ILB.js';
15
16
  import { CommanderError, Command } from 'commander';
16
- import { existsSync, mkdirSync, readFileSync, accessSync, constants } from 'fs';
17
- import { dirname, resolve, join, basename, extname, win32 } from 'path';
17
+ import { createHash } from 'crypto';
18
+ import { existsSync, writeFileSync, mkdirSync, readFileSync, statSync, readdirSync, closeSync, openSync, createReadStream, accessSync, constants } from 'fs';
19
+ import { resolve, join, dirname, basename, extname, win32 } from 'path';
20
+ import Database from 'better-sqlite3';
18
21
  import { z } from 'zod';
19
22
  import { stringify, parse, Document } from 'yaml';
20
23
  import picocolors from 'picocolors';
@@ -24,64 +27,10 @@ import { validate } from '@scalar/openapi-parser';
24
27
  import * as clack from '@clack/prompts';
25
28
  import { userInfo } from 'os';
26
29
 
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
30
  // src/cli/lib/config-client.ts
82
31
  async function importConfig() {
83
32
  try {
84
- return await import('./config-BWFMN2ZB.js');
33
+ return await import('./config-3K65QJ22.js');
85
34
  } catch (err) {
86
35
  throw new CommerceError(
87
36
  "INTERNAL_ERROR",
@@ -95,26 +44,6 @@ async function loadConfigDynamic(options = {}) {
95
44
  async function parseConfigDynamic(raw, env = process.env) {
96
45
  return (await importConfig()).parseConfig(raw, env);
97
46
  }
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
47
  var LOCAL_CHAIN_MANIFEST_PATH = ".deploy/local.json";
119
48
  var nonEmpty = z.string().min(1, "must be a non-empty string");
120
49
  var keyedAccount = z.object({ address: z.string(), privateKey: z.string(), note: z.string() });
@@ -213,6 +142,256 @@ function unresolvedVariableHint(variable, manifestFound, chainDeploy) {
213
142
  return `set ${variable} in the environment, or in a file passed with --env-file`;
214
143
  }
215
144
 
145
+ // src/cli/commands/validate.ts
146
+ function formatConfigError(err, manifestFound = false, chainDeploy = hasChainDeployScript()) {
147
+ if (isCommerceError(err)) {
148
+ const lines = [`FAIL ${err.code}: ${err.message}`];
149
+ if (err.details !== void 0) {
150
+ lines.push(` details: ${JSON.stringify(err.details)}`);
151
+ }
152
+ const variable = err.details?.["variable"];
153
+ if (typeof variable === "string") {
154
+ lines.push(` hint: ${unresolvedVariableHint(variable, manifestFound, chainDeploy)}`);
155
+ }
156
+ return lines.join("\n");
157
+ }
158
+ if (err instanceof Error) {
159
+ return `FAIL ${err.message}`;
160
+ }
161
+ return `FAIL ${String(err)}`;
162
+ }
163
+ async function runValidate(options, io, deps = {}) {
164
+ const loadConfig = deps.loadConfig ?? loadConfigDynamic;
165
+ const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;
166
+ const { env, filled, manifestFound } = fillEnvFromManifest(process.env);
167
+ if (filled.length > 0) {
168
+ io.stdout(`using local chain manifest ${LOCAL_CHAIN_MANIFEST_PATH} for ${filled.join(", ")}`);
169
+ }
170
+ try {
171
+ const config = await loadConfig({
172
+ ...options.configPath !== void 0 ? { path: options.configPath } : {},
173
+ env
174
+ });
175
+ io.stdout("PASS Configuration is valid");
176
+ io.stdout(` merchant: ${config.merchant.name} (${config.merchant.id})`);
177
+ io.stdout(` resources: ${config.resources.length}`);
178
+ io.stdout(
179
+ ` 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"}`
180
+ );
181
+ const onOff = (enabled) => enabled === true ? "on" : "off";
182
+ io.stdout(
183
+ ` payments: x402=${onOff(config.payments.x402?.enabled)} mpp=${onOff(config.payments.mpp?.enabled)}`
184
+ );
185
+ io.stdout(` authorization: ap2=${onOff(config.authorization?.ap2.enabled)}`);
186
+ return 0;
187
+ } catch (err) {
188
+ io.stderr(
189
+ formatConfigError(err, manifestFound, (deps.hasChainDeployScript ?? hasChainDeployScript)())
190
+ );
191
+ return 1;
192
+ }
193
+ }
194
+
195
+ // src/cli/commands/backup.ts
196
+ var OLDEST_SCHEMA = 4;
197
+ var LEGACY = [
198
+ { file: "ap2-replay.sqlite", source: "authorization.ap2.replay.path", marker: "ap2-replay" },
199
+ {
200
+ file: "acp-idempotency.sqlite",
201
+ source: "protocols.acp.idempotency.path",
202
+ marker: "acp-idempotency"
203
+ }
204
+ ];
205
+ var BackupError = class extends Error {
206
+ };
207
+ async function runBackupCommand(options, io, deps = {}) {
208
+ let config;
209
+ try {
210
+ config = await (deps.loadConfig ?? loadConfigDynamic)(
211
+ options.configPath !== void 0 ? { path: options.configPath } : {}
212
+ );
213
+ } catch (error) {
214
+ io.stderr(formatConfigError(error, false, false));
215
+ return 1;
216
+ }
217
+ try {
218
+ const receipts = config.storage.receipts.path;
219
+ if (receipts === ":memory:") throw new BackupError("the receipt database is in memory");
220
+ if (!existsSync(receipts)) {
221
+ throw new BackupError(`the receipt database "${resolve(receipts)}" does not exist`);
222
+ }
223
+ const ap2 = config.authorization?.ap2;
224
+ const acp = config.protocols.acp;
225
+ const legacyPaths = {
226
+ "authorization.ap2.replay.path": ap2?.enabled ? ap2.replay?.path : void 0,
227
+ "protocols.acp.idempotency.path": acp.enabled ? acp.idempotency.path : void 0
228
+ };
229
+ prepareOut(options.out);
230
+ const files = [];
231
+ const imported = await copy(
232
+ receipts,
233
+ options.out,
234
+ "receipts.sqlite",
235
+ "storage.receipts.path",
236
+ files
237
+ );
238
+ for (const legacy of LEGACY) {
239
+ const path = legacyPaths[legacy.source];
240
+ if (path === void 0 || path === ":memory:" || !existsSync(path)) continue;
241
+ if (imported.has(legacy.marker)) continue;
242
+ await copy(path, options.out, legacy.file, legacy.source, files);
243
+ }
244
+ const manifest = {
245
+ packageVersion: PACKAGE_VERSION,
246
+ createdAt: (deps.clock ?? systemClock).nowIso(),
247
+ files
248
+ };
249
+ writeFileSync(join(options.out, "backup.json"), `${JSON.stringify(manifest, null, 2)}
250
+ `, {
251
+ flag: "wx",
252
+ mode: 384
253
+ });
254
+ if (options.json === true) {
255
+ io.stdout(JSON.stringify({ out: resolve(options.out), ...manifest }, null, 2));
256
+ } else {
257
+ io.stdout(`backup written to ${resolve(options.out)}`);
258
+ for (const file of files) {
259
+ io.stdout(` ${file.file.padEnd(24)} ${file.source} (schema v${file.schemaVersion})`);
260
+ }
261
+ }
262
+ return 0;
263
+ } catch (error) {
264
+ io.stderr(
265
+ `FAIL backup: ${error instanceof BackupError ? error.message : redactedErrorText(error)}`
266
+ );
267
+ return 1;
268
+ }
269
+ }
270
+ function prepareOut(out) {
271
+ if (!existsSync(out)) {
272
+ mkdirSync(out, { mode: 448 });
273
+ return;
274
+ }
275
+ if (!statSync(out).isDirectory()) throw new BackupError(`--out "${out}" is not a directory`);
276
+ if (readdirSync(out).length > 0) throw new BackupError(`--out "${out}" is not empty`);
277
+ }
278
+ async function copy(source, out, file, key, files) {
279
+ const target = join(out, file);
280
+ const markers = /* @__PURE__ */ new Set();
281
+ const db = new Database(source, { readonly: true, fileMustExist: true });
282
+ try {
283
+ if (key === "storage.receipts.path") {
284
+ const version = db.pragma("user_version", { simple: true });
285
+ if (version < OLDEST_SCHEMA || version > SCHEMA_VERSION) {
286
+ throw new BackupError(
287
+ `the receipt database "${resolve(source)}" is at schema v${version}; this version backs up v${OLDEST_SCHEMA} to v${SCHEMA_VERSION}`
288
+ );
289
+ }
290
+ if (hasTable(db, "legacy_imports")) {
291
+ const rows = db.prepare("SELECT source FROM legacy_imports WHERE path IS NOT NULL").all();
292
+ for (const row of rows) markers.add(row.source);
293
+ }
294
+ }
295
+ closeSync(openSync(target, "wx", 384));
296
+ db.prepare("VACUUM INTO ?").run(target);
297
+ } finally {
298
+ db.close();
299
+ }
300
+ const copied = new Database(target, { readonly: true, fileMustExist: true });
301
+ let schemaVersion;
302
+ try {
303
+ const integrity = copied.pragma("integrity_check", { simple: true });
304
+ if (integrity !== "ok") {
305
+ throw new BackupError(`${file} failed its integrity check: ${String(integrity)}`);
306
+ }
307
+ schemaVersion = copied.pragma("user_version", { simple: true });
308
+ } finally {
309
+ copied.close();
310
+ }
311
+ files.push({ file, source: key, schemaVersion, sha256: await sha256(target) });
312
+ return markers;
313
+ }
314
+ function sha256(path) {
315
+ return new Promise((resolveHash, reject) => {
316
+ const hash = createHash("sha256");
317
+ createReadStream(path).on("data", (chunk) => hash.update(chunk)).on("end", () => resolveHash(hash.digest("hex"))).on("error", reject);
318
+ });
319
+ }
320
+
321
+ // src/cli/commands/demo.ts
322
+ function defaultDemoSteps() {
323
+ return [
324
+ {
325
+ name: "Start the local stack: chain, merchant, gateway and dashboard (docker compose)",
326
+ command: "docker",
327
+ args: ["compose", "up", "--build", "--detach", "--wait"]
328
+ },
329
+ { name: "Run the deterministic buyer agent", command: "npm", args: ["run", "demo:agent"] }
330
+ ];
331
+ }
332
+ async function runDemo(io, deps = {}) {
333
+ const steps = deps.steps ?? defaultDemoSteps();
334
+ const run = deps.run ?? execCommand;
335
+ io.stdout("agent-commerce demo: starting the local stack, then running the buyer agent");
336
+ for (const step of steps) {
337
+ io.stdout("");
338
+ io.stdout(`==> ${step.name}`);
339
+ io.stdout(` $ ${step.command} ${step.args.join(" ")}`);
340
+ const result = await run(step.command, step.args);
341
+ if (result.code !== 0) {
342
+ io.stderr(`FAIL "${step.name}" exited with code ${result.code}.`);
343
+ if (result.stderrTail !== void 0 && result.stderrTail.length > 0) {
344
+ io.stderr(result.stderrTail);
345
+ }
346
+ io.stderr("");
347
+ io.stderr("Nothing further was run. To retry manually:");
348
+ io.stderr(` ${step.command} ${step.args.join(" ")}`);
349
+ return 1;
350
+ }
351
+ io.stdout(`OK ${step.name}`);
352
+ }
353
+ io.stdout("");
354
+ io.stdout("PASS Demo is up. Try: agent-commerce doctor --config config-demo.yaml");
355
+ return 0;
356
+ }
357
+ async function execCommand(command, args) {
358
+ const { spawn } = await import('child_process');
359
+ return new Promise((resolvePromise) => {
360
+ let stderr = "";
361
+ const child = spawn(command, args, { stdio: ["ignore", "inherit", "pipe"] });
362
+ child.stderr?.on("data", (chunk) => {
363
+ stderr += chunk.toString("utf8");
364
+ });
365
+ child.on("error", (err) => {
366
+ resolvePromise({ code: 1, stderrTail: err.message });
367
+ });
368
+ child.on("close", (code) => {
369
+ const tail = stderr.trim().split("\n").slice(-10).join("\n");
370
+ resolvePromise({ code: code ?? 1, ...tail.length > 0 ? { stderrTail: tail } : {} });
371
+ });
372
+ });
373
+ }
374
+
375
+ // src/cli/lib/http.ts
376
+ async function fetchJson(fetchImpl, url, timeoutMs = 1500) {
377
+ try {
378
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
379
+ let body;
380
+ try {
381
+ body = await res.json();
382
+ } catch {
383
+ body = void 0;
384
+ }
385
+ return { ok: res.ok, status: res.status, ...body !== void 0 ? { body } : {} };
386
+ } catch (err) {
387
+ return {
388
+ ok: false,
389
+ status: 0,
390
+ error: err instanceof Error ? err.message : "unknown fetch error"
391
+ };
392
+ }
393
+ }
394
+
216
395
  // package.json
217
396
  var package_default = {
218
397
  dependencies: {
@@ -284,85 +463,178 @@ function isWritableFile(path) {
284
463
  return false;
285
464
  }
286
465
  }
287
- function storeFileCheck(name, path, risk, suffix = "") {
466
+ var LEGACY_KEYS = {
467
+ "ap2-replay": { feature: "AP2", key: "authorization.ap2.replay.path" },
468
+ "acp-idempotency": { feature: "ACP", key: "protocols.acp.idempotency.path" }
469
+ };
470
+ function legacyStoreCheck(name, source, path, legacy, pass, note = "") {
471
+ const marker = legacy?.imports.find((entry) => entry.source === source);
472
+ if (marker !== void 0) {
473
+ if (path === void 0) return { name, status: "PASS", detail: pass };
474
+ return path !== ":memory:" && resolve(path) !== marker.path ? {
475
+ name,
476
+ status: "FAIL",
477
+ 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}`
478
+ } : {
479
+ name,
480
+ status: "WARN",
481
+ detail: `deprecated key: ${marker.rows} row(s) moved into the receipt database at ${marker.importedAt}; remove the key${note}`
482
+ };
483
+ }
484
+ const forgotten = legacy?.missing.includes(source) === true;
288
485
  if (path === ":memory:") {
289
486
  return {
290
487
  name,
291
488
  status: "WARN",
292
- detail: `in-memory store: ${risk.inMemory}; use a file path in production${suffix}`
489
+ 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}`
490
+ };
491
+ }
492
+ if (path === void 0 || !existsSync(path)) {
493
+ if (forgotten) {
494
+ const { feature, key } = LEGACY_KEYS[source];
495
+ return {
496
+ name,
497
+ status: "FAIL",
498
+ 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}`
499
+ };
500
+ }
501
+ return path === void 0 ? { name, status: "PASS", detail: pass } : {
502
+ name,
503
+ status: "WARN",
504
+ detail: `deprecated key: no file at "${path}", so there is nothing to import; remove the key${note}`
293
505
  };
294
506
  }
295
- if (existsSync(path)) {
296
- return isWritableFile(path) ? { name, status: "PASS", detail: `writable at "${path}"${suffix}` } : {
507
+ if (!isWritableFile(path)) {
508
+ return {
297
509
  name,
298
510
  status: "FAIL",
299
- detail: `"${path}" exists but is not writable by this user, so ${risk.unwritable}${suffix}`
511
+ detail: `"${path}" exists but is not writable by this user, so the first start cannot lock the file to import it${note}`
300
512
  };
301
513
  }
302
- return { name, status: "WARN", detail: `${missingStoreDetail(path)}${suffix}` };
514
+ return {
515
+ name,
516
+ status: "WARN",
517
+ 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}`
518
+ };
303
519
  }
304
520
  function missingStoreDetail(path) {
305
521
  const directory = dirname(path);
306
522
  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
523
  }
308
- async function storageChecks(config, createStore) {
309
- const checks = [];
524
+ function refusedSchema(err) {
525
+ if (!isCommerceError(err)) return void 0;
526
+ const { schemaVersion, expected } = err.details ?? {};
527
+ return typeof schemaVersion === "number" && typeof expected === "number" ? { schemaVersion, expected } : void 0;
528
+ }
529
+ async function storageChecks(config, openStore) {
310
530
  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
- ) {
531
+ return {
532
+ checks: [{ name: "Storage", status: "WARN", detail: "skipped: config invalid" }],
533
+ legacy: void 0
534
+ };
535
+ }
536
+ const path = config.storage.receipts.path;
537
+ if (path !== ":memory:" && !existsSync(path)) {
538
+ return {
539
+ checks: [
540
+ {
541
+ name: "Storage",
542
+ status: "WARN",
543
+ detail: `${missingStoreDetail(path)}. If the gateway is already running, this path does not match the one it uses.`
544
+ }
545
+ ],
546
+ legacy: { imports: [], missing: [] }
547
+ };
548
+ }
549
+ const checks = [];
550
+ let summary;
551
+ let store;
552
+ try {
553
+ store = openStore(path);
554
+ await store.init();
555
+ const storeHealth = await store.health();
556
+ let receiptCount;
557
+ try {
558
+ receiptCount = await store.countReceipts();
559
+ } catch {
560
+ receiptCount = void 0;
561
+ }
562
+ let undeliveredCount;
563
+ try {
564
+ undeliveredCount = await store.countUndeliveredReceipts();
565
+ } catch {
566
+ undeliveredCount = void 0;
567
+ }
568
+ let uncertainCount;
569
+ try {
570
+ uncertainCount = await store.countUncertainPaymentAttempts();
571
+ } catch {
572
+ uncertainCount = void 0;
573
+ }
574
+ try {
575
+ summary = await store.summary?.({ orphanHoldMinAgeMs: DEFAULT_RECONCILE_MIN_AGE_MS });
576
+ } catch {
577
+ summary = void 0;
578
+ }
579
+ const status = storeHealth.status === "pass" ? "PASS" : storeHealth.status === "warn" ? "WARN" : "FAIL";
580
+ const receiptsSuffix = receiptCount !== void 0 ? `; receipts=${receiptCount}${undeliveredCount !== void 0 && undeliveredCount > 0 ? ` (${undeliveredCount} undelivered)` : ""}` : "";
581
+ 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
582
  checks.push({
321
583
  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.`
584
+ status,
585
+ detail: `${storeHealth.detail ?? "sqlite"}${receiptsSuffix}${uncertainSuffix}`
324
586
  });
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();
587
+ } catch (err) {
588
+ const refused = refusedSchema(err);
589
+ if (refused !== void 0 && refused.schemaVersion < refused.expected) {
590
+ const missing = readMissingLegacyImports(path);
591
+ return {
592
+ checks: [
593
+ {
594
+ name: "Storage",
595
+ status: "WARN",
596
+ 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`
597
+ }
598
+ ],
599
+ legacy: missing !== void 0 ? { imports: [], missing } : void 0
600
+ };
365
601
  }
602
+ checks.push({
603
+ name: "Storage",
604
+ status: "FAIL",
605
+ 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)
606
+ });
607
+ } finally {
608
+ await store?.close();
609
+ }
610
+ if (summary !== void 0) checks.push(...summaryChecks(summary));
611
+ return {
612
+ checks,
613
+ legacy: summary !== void 0 ? { imports: summary.legacyImports, missing: summary.missingLegacyImports } : void 0
614
+ };
615
+ }
616
+ function summaryChecks(summary) {
617
+ const states = Object.entries(summary.unresolvedTransactions);
618
+ const checks = [
619
+ states.length > 0 ? {
620
+ name: "Transactions",
621
+ status: "WARN",
622
+ detail: `unresolved: ${states.map(([state, count]) => `${state}=${count}`).join(", ")}; see GET /api/transactions?unresolved=true or run agent-commerce reconcile`
623
+ } : { name: "Transactions", status: "PASS", detail: "none unresolved" }
624
+ ];
625
+ if (summary.orphanHolds > 0) {
626
+ checks.push({
627
+ name: "Authorization holds",
628
+ status: "WARN",
629
+ 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`
630
+ });
631
+ }
632
+ if (summary.unresolvedIdempotencyKeys > 0) {
633
+ checks.push({
634
+ name: "ACP claims",
635
+ status: "INFO",
636
+ detail: `${summary.unresolvedIdempotencyKeys} unresolved; a retry with the same Idempotency-Key gets 409 idempotency_unresolved`
637
+ });
366
638
  }
367
639
  return checks;
368
640
  }
@@ -374,7 +646,7 @@ function describeIssuers(label, issuers) {
374
646
  ).join(", ");
375
647
  return `${label} issuers: ${described}`;
376
648
  }
377
- function ap2Checks(config) {
649
+ function ap2Checks(config, legacy) {
378
650
  const checks = [];
379
651
  const ap2 = config?.authorization?.ap2;
380
652
  if (config === void 0) {
@@ -393,10 +665,13 @@ function ap2Checks(config) {
393
665
  detail: `${describeIssuers("mandate", ap2.trust.mandateIssuers)} \xB7 ${describeIssuers("checkout", ap2.trust.checkoutIssuers)}`
394
666
  });
395
667
  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
- })
668
+ legacyStoreCheck(
669
+ "AP2 replay store",
670
+ "ap2-replay",
671
+ ap2.replay?.path,
672
+ legacy,
673
+ "mandate holds in the receipt database"
674
+ )
400
675
  );
401
676
  const gated = config.resources.filter(
402
677
  (resource) => resource.authorization?.required.includes("ap2")
@@ -927,7 +1202,7 @@ function acpMappingCheck(config, operations) {
927
1202
  detail: `5 operations mapped to free acp-exposed resources (${Object.values(operations).join(", ")})`
928
1203
  };
929
1204
  }
930
- function protocolChecks(config, wellKnown) {
1205
+ function protocolChecks(config, wellKnown, legacy) {
931
1206
  const checks = [];
932
1207
  if (config === void 0) {
933
1208
  checks.push({ name: "Protocols", status: "WARN", detail: "skipped: config invalid" });
@@ -975,13 +1250,12 @@ function protocolChecks(config, wellKnown) {
975
1250
  detail: `bearer token configured (${acp.auth.token.length} characters, not shown)`
976
1251
  });
977
1252
  checks.push(
978
- storeFileCheck(
1253
+ legacyStoreCheck(
979
1254
  "ACP idempotency",
1255
+ "acp-idempotency",
980
1256
  acp.idempotency.path,
981
- {
982
- inMemory: "replay protection is lost on every restart",
983
- unwritable: "the adapter cannot claim idempotency keys"
984
- },
1257
+ legacy,
1258
+ `claims in the receipt database (retention ${acp.idempotency.retentionHours}h)`,
985
1259
  ` (retention ${acp.idempotency.retentionHours}h)`
986
1260
  )
987
1261
  );
@@ -1041,7 +1315,7 @@ function substitutePathParams(url) {
1041
1315
  async function runDoctor(options, deps = {}) {
1042
1316
  const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
1043
1317
  const loadConfig = deps.loadConfig ?? loadConfigDynamic;
1044
- const createStore = deps.createStore ?? ((path) => createSqliteReceiptStore({ path }));
1318
+ const createStore = deps.createStore ?? ((path) => path === ":memory:" ? createSqliteReceiptStore({ path }) : openSqliteReceiptStoreReadOnly(path));
1045
1319
  const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;
1046
1320
  const chainDeploy = (deps.hasChainDeployScript ?? hasChainDeployScript)();
1047
1321
  const checks = [];
@@ -1110,12 +1384,13 @@ async function runDoctor(options, deps = {}) {
1110
1384
  `${gatewayUrl}/.well-known/agent-commerce`,
1111
1385
  CHECK_TIMEOUT_MS
1112
1386
  ) : void 0;
1113
- checks.push(...protocolChecks(config, wellKnown));
1114
- checks.push(...ap2Checks(config));
1387
+ const storage = await storageChecks(config, createStore);
1388
+ checks.push(...protocolChecks(config, wellKnown, storage.legacy));
1389
+ checks.push(...ap2Checks(config, storage.legacy));
1115
1390
  checks.push(
1116
1391
  ...await paymentChecks(config, wellKnown, gatewayUrl, chainDeploy, deps.loadViemAccounts)
1117
1392
  );
1118
- checks.push(...await storageChecks(config, createStore));
1393
+ checks.push(...storage.checks);
1119
1394
  if (wellKnown?.ok) {
1120
1395
  checks.push({
1121
1396
  name: "Protocol versions",
@@ -2301,58 +2576,6 @@ function printSummary(result, context, io) {
2301
2576
  function describe(error) {
2302
2577
  return error instanceof Error ? error.message : String(error);
2303
2578
  }
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
2579
  async function collectAnswersInteractive() {
2357
2580
  clack.intro("agent-commerce init");
2358
2581
  const backendBaseUrl = await clack.text({
@@ -2508,10 +2731,11 @@ async function runReconcileCommand(options, io, deps = {}) {
2508
2731
  }
2509
2732
  try {
2510
2733
  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);
2734
+ const { runReconcile } = await import('./reconcile-55WNCSFC.js');
2735
+ const providers = await (await import('./payment-providers-2ITS6KNR.js')).createConfiguredPaymentProviders(config.payments, logger);
2736
+ let report;
2513
2737
  await withJournal(config, logger, async (store, authorizationProviders) => {
2514
- const report = await runReconcile({
2738
+ report = await runReconcile({
2515
2739
  store,
2516
2740
  providers,
2517
2741
  authorizationProviders,
@@ -2524,6 +2748,12 @@ async function runReconcileCommand(options, io, deps = {}) {
2524
2748
  });
2525
2749
  printReport(report, io, options.json === true);
2526
2750
  });
2751
+ if (report !== void 0 && report.failedScans.length > 0) {
2752
+ io.stderr(
2753
+ `FAIL reconcile could not finish the ${report.failedScans.join(" and ")} scan; the resolutions above are saved, so run it again`
2754
+ );
2755
+ return 1;
2756
+ }
2527
2757
  return 0;
2528
2758
  } catch (error) {
2529
2759
  io.stderr(`FAIL reconcile could not run: ${redactedErrorText(error)}`);
@@ -2531,24 +2761,54 @@ async function runReconcileCommand(options, io, deps = {}) {
2531
2761
  }
2532
2762
  }
2533
2763
  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')
2764
+ const [
2765
+ { createConfiguredAuthorizationProviders },
2766
+ { createSqliteReceiptStore: createSqliteReceiptStore2, openSqliteReceiptStoreReadOnly: openSqliteReceiptStoreReadOnly2 }
2767
+ ] = await Promise.all([
2768
+ import('./payment-providers-2ITS6KNR.js'),
2769
+ import('./receipts-I4IIE7U6.js')
2537
2770
  ]);
2538
- const authorizationProviders = await createConfiguredAuthorizationProviders(
2539
- config.authorization,
2540
- logger
2541
- );
2771
+ const path = config.storage.receipts.path;
2772
+ if (path !== ":memory:" && existsSync(path)) {
2773
+ try {
2774
+ await openSqliteReceiptStoreReadOnly2(path).close();
2775
+ } catch (error) {
2776
+ const { schemaVersion, expected } = isCommerceError(error) ? error.details ?? {} : {};
2777
+ if (typeof schemaVersion === "number" && typeof expected === "number" && schemaVersion < expected) {
2778
+ throw new CommerceError(
2779
+ "STORAGE_ERROR",
2780
+ `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.`
2781
+ );
2782
+ }
2783
+ throw error;
2784
+ }
2785
+ }
2786
+ const store = createSqliteReceiptStore2({ path, logger });
2542
2787
  try {
2543
- const store = createSqliteReceiptStore2({ path: config.storage.receipts.path, logger });
2788
+ await store.init();
2789
+ const ap2 = config.authorization?.ap2;
2790
+ const replayPath = ap2?.enabled ? ap2.replay?.path : void 0;
2791
+ if (replayPath !== void 0 && replayPath !== ":memory:" && existsSync(replayPath)) {
2792
+ const { legacyImports } = await store.summary({ orphanHoldMinAgeMs: 0 });
2793
+ if (!legacyImports.some((entry) => entry.source === "ap2-replay")) {
2794
+ throw new CommerceError(
2795
+ "STORAGE_ERROR",
2796
+ `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.`
2797
+ );
2798
+ }
2799
+ }
2800
+ const authorizationProviders = await createConfiguredAuthorizationProviders(
2801
+ config.authorization,
2802
+ logger,
2803
+ store
2804
+ );
2544
2805
  try {
2545
- await store.init();
2546
2806
  await fn(store, authorizationProviders);
2547
2807
  } finally {
2548
- await store.close();
2808
+ for (const provider of authorizationProviders) provider.close();
2549
2809
  }
2550
2810
  } finally {
2551
- for (const provider of authorizationProviders) provider.close();
2811
+ await store.close();
2552
2812
  }
2553
2813
  }
2554
2814
  function parseDuration(value) {
@@ -2564,12 +2824,21 @@ function printReport(report, io, json) {
2564
2824
  notSettled: count("not-settled"),
2565
2825
  unknown: count("unknown"),
2566
2826
  resolved: report.entries.filter((e) => e.written).length,
2567
- holdsAligned: report.holds.filter((h) => h.written).length
2827
+ holdsAligned: report.holds.filter((h) => h.written).length,
2828
+ orphanHolds: report.orphanHolds.length,
2829
+ orphanHoldsReleased: report.orphanHolds.filter((h) => h.released).length
2568
2830
  };
2569
2831
  if (json) {
2570
2832
  io.stdout(
2571
2833
  JSON.stringify(
2572
- { dryRun: report.dryRun, counts, entries: report.entries, holds: report.holds },
2834
+ {
2835
+ dryRun: report.dryRun,
2836
+ counts,
2837
+ entries: report.entries,
2838
+ holds: report.holds,
2839
+ orphanHolds: report.orphanHolds,
2840
+ failedScans: report.failedScans
2841
+ },
2573
2842
  null,
2574
2843
  2
2575
2844
  )
@@ -2577,7 +2846,7 @@ function printReport(report, io, json) {
2577
2846
  return;
2578
2847
  }
2579
2848
  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` : "")
2849
+ `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
2850
  );
2582
2851
  for (const entry of report.entries) {
2583
2852
  io.stdout(
@@ -2608,6 +2877,19 @@ function printReport(report, io, json) {
2608
2877
  ].join(" ")
2609
2878
  );
2610
2879
  }
2880
+ for (const hold of report.orphanHolds) {
2881
+ io.stdout(
2882
+ [
2883
+ "ORPHAN".padEnd(11),
2884
+ hold.reference,
2885
+ `request=${hold.requestId}`,
2886
+ `method=${hold.method}`,
2887
+ `updated=${hold.updatedAt}`,
2888
+ ...hold.reason !== void 0 ? [`reason=${hold.reason}`] : [],
2889
+ ...hold.released ? ["released"] : []
2890
+ ].join(" ")
2891
+ );
2892
+ }
2611
2893
  }
2612
2894
  function osUser() {
2613
2895
  try {
@@ -2639,7 +2921,7 @@ async function runResolveCommand(attemptId, options, io, deps = {}) {
2639
2921
  return 1;
2640
2922
  }
2641
2923
  try {
2642
- const { resolveManually } = await import('./reconcile-IC22MJD5.js');
2924
+ const { resolveManually } = await import('./reconcile-55WNCSFC.js');
2643
2925
  const logger = stderrLogger(io);
2644
2926
  let code = 1;
2645
2927
  await withJournal(config, logger, async (store, authorizationProviders) => {
@@ -2712,7 +2994,7 @@ var ENV_FILE_HELP = "load environment variables from this file; variables alread
2712
2994
  function buildProgram(io = processIo) {
2713
2995
  const program = new Command();
2714
2996
  program.name("agent-commerce").description(
2715
- "CLI for the Agent Commerce Gateway: init, import, validate, start, doctor, reconcile, demo."
2997
+ "CLI for the Agent Commerce Gateway: init, import, validate, start, doctor, reconcile, backup, demo."
2716
2998
  ).version(readVersionReport().cliVersion, "-v, --version", "Print the CLI version.").exitOverride().configureOutput({
2717
2999
  writeOut: (str) => io.stdout(str.replace(/\n+$/, "")),
2718
3000
  writeErr: (str) => io.stderr(str.replace(/\n+$/, ""))
@@ -2741,7 +3023,7 @@ function buildProgram(io = processIo) {
2741
3023
  `Start the gateway from ${DEFAULT_CONFIG_FILENAME} and serve until SIGTERM or SIGINT.`
2742
3024
  ).option("--config <path>", `path to ${DEFAULT_CONFIG_FILENAME}`).option("--env-file <path>", ENV_FILE_HELP).action(async (opts) => {
2743
3025
  try {
2744
- const { runGateway } = await import('./run-ZTYPQI4D.js');
3026
+ const { runGateway } = await import('./run-2P6ZGFUE.js');
2745
3027
  await runGateway(opts.config !== void 0 ? { configPath: opts.config } : {});
2746
3028
  } catch (error) {
2747
3029
  io.stderr(formatConfigError(error, false, false));
@@ -2801,6 +3083,18 @@ function buildProgram(io = processIo) {
2801
3083
  );
2802
3084
  }
2803
3085
  );
3086
+ program.command("backup").description(
3087
+ "Copy the receipt database, and deprecated store files not yet imported, into a new directory."
3088
+ ).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) => {
3089
+ process.exitCode = await runBackupCommand(
3090
+ {
3091
+ out: opts.out,
3092
+ ...opts.config !== void 0 ? { configPath: opts.config } : {},
3093
+ json: opts.json
3094
+ },
3095
+ io
3096
+ );
3097
+ });
2804
3098
  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
3099
  const code = await runInit({ outputPath: opts.output, force: opts.force, yes: opts.yes }, io);
2806
3100
  process.exitCode = code;