@devlab.group/agent-commerce 2.4.1 → 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 (126) hide show
  1. package/README.md +168 -16
  2. package/dist/ap2.d.ts +42 -17
  3. package/dist/ap2.js +83 -27
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-CXWC5LWM.js → chunk-DRLBML7Z.js} +661 -75
  6. package/dist/chunk-DRLBML7Z.js.map +1 -0
  7. package/dist/{chunk-WZW5ORZH.js → chunk-G3EYYHKF.js} +3 -3
  8. package/dist/{chunk-WZW5ORZH.js.map → chunk-G3EYYHKF.js.map} +1 -1
  9. package/dist/chunk-GA3O2A7R.js +92 -0
  10. package/dist/chunk-GA3O2A7R.js.map +1 -0
  11. package/dist/{chunk-DTKU3Z2M.js → chunk-M52FBNJX.js} +36 -5
  12. package/dist/chunk-M52FBNJX.js.map +1 -0
  13. package/dist/chunk-M6BSXXTF.js +8 -0
  14. package/dist/chunk-M6BSXXTF.js.map +1 -0
  15. package/dist/{chunk-QPV3EGJO.js → chunk-M6MQ3FYS.js} +25 -4
  16. package/dist/chunk-M6MQ3FYS.js.map +1 -0
  17. package/dist/chunk-M6WW6QIT.js +18 -0
  18. package/dist/chunk-M6WW6QIT.js.map +1 -0
  19. package/dist/cli/{ap2-GWSP4LYY.js → ap2-2YMYA2H6.js} +85 -29
  20. package/dist/cli/ap2-2YMYA2H6.js.map +1 -0
  21. package/dist/cli/{chunk-OZ4LAWBK.js → chunk-3NOMLMJW.js} +29 -8
  22. package/dist/cli/chunk-3NOMLMJW.js.map +1 -0
  23. package/dist/cli/chunk-4KLYFXMW.js +8 -0
  24. package/dist/cli/{chunk-ITWNSS2B.js.map → chunk-4KLYFXMW.js.map} +1 -1
  25. package/dist/cli/chunk-663ALDZA.js +92 -0
  26. package/dist/cli/chunk-663ALDZA.js.map +1 -0
  27. package/dist/cli/chunk-6R6WJ4FD.js +18 -0
  28. package/dist/cli/chunk-6R6WJ4FD.js.map +1 -0
  29. package/dist/cli/{chunk-G2JEY7MB.js → chunk-AZL7RPFU.js} +39 -33
  30. package/dist/cli/chunk-AZL7RPFU.js.map +1 -0
  31. package/dist/cli/chunk-DHFMIBPG.js +107 -0
  32. package/dist/cli/chunk-DHFMIBPG.js.map +1 -0
  33. package/dist/cli/{chunk-QQ3WY5L3.js → chunk-GET3CZGR.js} +36 -104
  34. package/dist/cli/chunk-GET3CZGR.js.map +1 -0
  35. package/dist/cli/chunk-NSYSMDQN.js +1544 -0
  36. package/dist/cli/chunk-NSYSMDQN.js.map +1 -0
  37. package/dist/cli/{chunk-PIMFPCNZ.js → chunk-PTL7SNOI.js} +313 -138
  38. package/dist/cli/chunk-PTL7SNOI.js.map +1 -0
  39. package/dist/cli/chunk-SYQLJXIU.js +105 -0
  40. package/dist/cli/chunk-SYQLJXIU.js.map +1 -0
  41. package/dist/cli/chunk-TFV3K6YS.js +373 -0
  42. package/dist/cli/chunk-TFV3K6YS.js.map +1 -0
  43. package/dist/cli/{chunk-3MGAJ5FX.js → chunk-VJ4EO4LE.js} +3 -3
  44. package/dist/cli/{chunk-3MGAJ5FX.js.map → chunk-VJ4EO4LE.js.map} +1 -1
  45. package/dist/cli/chunk-VJH6RYRK.js +119 -0
  46. package/dist/cli/chunk-VJH6RYRK.js.map +1 -0
  47. package/dist/cli/{chunk-TNMLDPUO.js → chunk-YOF7IK4V.js} +663 -77
  48. package/dist/cli/chunk-YOF7IK4V.js.map +1 -0
  49. package/dist/cli/{chunk-WYOGIANL.js → chunk-YWG2ZN3L.js} +4 -4
  50. package/dist/cli/{chunk-WYOGIANL.js.map → chunk-YWG2ZN3L.js.map} +1 -1
  51. package/dist/cli/config-3K65QJ22.js +12 -0
  52. package/dist/cli/{config-UI4EDG4L.js.map → config-3K65QJ22.js.map} +1 -1
  53. package/dist/cli/index.js +753 -212
  54. package/dist/cli/index.js.map +1 -1
  55. package/dist/cli/{mcp-PGBRWZVA.js → mcp-6F64A7KE.js} +5 -4
  56. package/dist/cli/mcp-6F64A7KE.js.map +1 -0
  57. package/dist/cli/{near-5AY3HWYF.js → near-U6365VFX.js} +15 -4
  58. package/dist/cli/near-U6365VFX.js.map +1 -0
  59. package/dist/cli/payment-providers-2ITS6KNR.js +6 -0
  60. package/dist/cli/payment-providers-2ITS6KNR.js.map +1 -0
  61. package/dist/cli/{provider-I2ESL6RS.js → provider-5BGG5YKQ.js} +53 -24
  62. package/dist/cli/provider-5BGG5YKQ.js.map +1 -0
  63. package/dist/cli/receipts-I4IIE7U6.js +8 -0
  64. package/dist/cli/receipts-I4IIE7U6.js.map +1 -0
  65. package/dist/cli/reconcile-55WNCSFC.js +4 -0
  66. package/dist/cli/reconcile-55WNCSFC.js.map +1 -0
  67. package/dist/cli/{run-JK4ERPJV.js → run-2P6ZGFUE.js} +356 -173
  68. package/dist/cli/run-2P6ZGFUE.js.map +1 -0
  69. package/dist/cli/svm-KDSPDFJG.js +48 -0
  70. package/dist/cli/svm-KDSPDFJG.js.map +1 -0
  71. package/dist/cli/{x402-7WBFZQXV.js → x402-4LPIIELI.js} +10 -9
  72. package/dist/cli/x402-4LPIIELI.js.map +1 -0
  73. package/dist/index.d.ts +116 -113
  74. package/dist/index.js +1928 -351
  75. package/dist/index.js.map +1 -1
  76. package/dist/logger-CllGwQ8i.d.ts +19 -0
  77. package/dist/mcp.d.ts +3 -2
  78. package/dist/mcp.js +2 -1
  79. package/dist/mcp.js.map +1 -1
  80. package/dist/mpp.d.ts +2 -1
  81. package/dist/mpp.js +48 -19
  82. package/dist/mpp.js.map +1 -1
  83. package/dist/{near-D6C42VPE.js → near-FH7HPZV3.js} +15 -4
  84. package/dist/near-FH7HPZV3.js.map +1 -0
  85. package/dist/{protocol-adapter-C9odYl6l.d.ts → protocol-adapter-1WbtM3xG.d.ts} +12 -85
  86. package/dist/{runtime-Cl_BLVZV.d.ts → runtime-B-kARa2f.d.ts} +218 -15
  87. package/dist/store-kIIMpUA-.d.ts +372 -0
  88. package/dist/svm-KNC3PHMS.js +48 -0
  89. package/dist/svm-KNC3PHMS.js.map +1 -0
  90. package/dist/testing.d.ts +51 -0
  91. package/dist/testing.js +1896 -0
  92. package/dist/testing.js.map +1 -0
  93. package/dist/transaction-Dv0UFGg5.d.ts +129 -0
  94. package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
  95. package/dist/x402.d.ts +2 -1
  96. package/dist/x402.js +6 -5
  97. package/dist/x402.js.map +1 -1
  98. package/package.json +5 -1
  99. package/dist/authorization-DjAecwuW.d.ts +0 -115
  100. package/dist/chunk-CXWC5LWM.js.map +0 -1
  101. package/dist/chunk-DTKU3Z2M.js.map +0 -1
  102. package/dist/chunk-KA2AX5FH.js +0 -44
  103. package/dist/chunk-KA2AX5FH.js.map +0 -1
  104. package/dist/chunk-QPV3EGJO.js.map +0 -1
  105. package/dist/cli/ap2-GWSP4LYY.js.map +0 -1
  106. package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
  107. package/dist/cli/chunk-GJIMDMYT.js +0 -639
  108. package/dist/cli/chunk-GJIMDMYT.js.map +0 -1
  109. package/dist/cli/chunk-ITWNSS2B.js +0 -8
  110. package/dist/cli/chunk-OSTCU6ZK.js +0 -44
  111. package/dist/cli/chunk-OSTCU6ZK.js.map +0 -1
  112. package/dist/cli/chunk-OZ4LAWBK.js.map +0 -1
  113. package/dist/cli/chunk-PIMFPCNZ.js.map +0 -1
  114. package/dist/cli/chunk-QQ3WY5L3.js.map +0 -1
  115. package/dist/cli/chunk-TNMLDPUO.js.map +0 -1
  116. package/dist/cli/config-UI4EDG4L.js +0 -11
  117. package/dist/cli/mcp-PGBRWZVA.js.map +0 -1
  118. package/dist/cli/near-5AY3HWYF.js.map +0 -1
  119. package/dist/cli/provider-I2ESL6RS.js.map +0 -1
  120. package/dist/cli/run-JK4ERPJV.js.map +0 -1
  121. package/dist/cli/svm-3MMYFPC7.js +0 -33
  122. package/dist/cli/svm-3MMYFPC7.js.map +0 -1
  123. package/dist/cli/x402-7WBFZQXV.js.map +0 -1
  124. package/dist/near-D6C42VPE.js.map +0 -1
  125. package/dist/svm-QEUAUNPQ.js +0 -33
  126. package/dist/svm-QEUAUNPQ.js.map +0 -1
package/dist/cli/index.js CHANGED
@@ -1,18 +1,23 @@
1
1
  #!/usr/bin/env node
2
- import { createSqliteReceiptStore, A2A_SPEC_VERSION, A2A_PROTOCOL_VERSION, A2A_PROTOCOL_BINDING, A2A_AGENT_CARD_PATH, A2A_UNSUPPORTED, ACP_UNSUPPORTED } from './chunk-GJIMDMYT.js';
3
- import { DEFAULT_CONFIG_FILENAME, extractPathParameterNames, ACP_SPEC_VERSION, ACP_API_VERSION, ACP_WELL_KNOWN_PATH, findUnparsedBraceToken } from './chunk-PIMFPCNZ.js';
4
- import { MPP_PROFILE, MPP_SPEC_DRAFTS, MPPX_VERSION, MPP_SPEC_COMMIT, MPP_DEFAULT_PAYMENT_FLOW } from './chunk-AA3FIEAR.js';
5
- import { ANVIL_WELL_KNOWN_ACCOUNTS, describeDeploymentMode, X402_DEFAULT_PAYMENT_FLOW, findX402Network, isEvmAddress, LOCAL_CHAIN_ID, resolveDeploymentMode, sameAddress } from './chunk-OZ4LAWBK.js';
6
2
  import { AP2_UNSUPPORTED } from './chunk-3EQBCFZY.js';
7
- import './chunk-3MGAJ5FX.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';
8
5
  import { AP2_SPEC_VERSION, AP2_CHECKOUT_MANDATE_VCT, AP2_CHECKOUT_PROFILE } from './chunk-FHCFR2GS.js';
9
6
  import { MCP_TOOL_NAME_MAX_LENGTH, MCP_TOOL_NAME_CHARS } from './chunk-TPC4EJLT.js';
10
- import { PACKAGE_VERSION } from './chunk-ITWNSS2B.js';
11
- import { PROTOCOL_NAMES, isCommerceError, CommerceError } from './chunk-QQ3WY5L3.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';
10
+ import { MPP_PROFILE, MPP_SPEC_DRAFTS, MPPX_VERSION, MPP_SPEC_COMMIT, MPP_DEFAULT_PAYMENT_FLOW } from './chunk-AA3FIEAR.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';
14
+ import { isCommerceError, redactedErrorText, CommerceError } from './chunk-SYQLJXIU.js';
12
15
  import { isRecord } from './chunk-3M6U7ILB.js';
13
16
  import { CommanderError, Command } from 'commander';
14
- import { existsSync, mkdirSync, readFileSync, accessSync, constants } from 'fs';
15
- 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';
16
21
  import { z } from 'zod';
17
22
  import { stringify, parse, Document } from 'yaml';
18
23
  import picocolors from 'picocolors';
@@ -20,65 +25,12 @@ import { writeFile, stat, mkdir, rename, rm, open } from 'fs/promises';
20
25
  import { isDeepStrictEqual } from 'util';
21
26
  import { validate } from '@scalar/openapi-parser';
22
27
  import * as clack from '@clack/prompts';
23
-
24
- // src/cli/commands/demo.ts
25
- function defaultDemoSteps() {
26
- return [
27
- {
28
- name: "Start the local stack: chain, merchant, gateway and dashboard (docker compose)",
29
- command: "docker",
30
- args: ["compose", "up", "--build", "--detach", "--wait"]
31
- },
32
- { name: "Run the deterministic buyer agent", command: "npm", args: ["run", "demo:agent"] }
33
- ];
34
- }
35
- async function runDemo(io, deps = {}) {
36
- const steps = deps.steps ?? defaultDemoSteps();
37
- const run = deps.run ?? execCommand;
38
- io.stdout("agent-commerce demo: starting the local stack, then running the buyer agent");
39
- for (const step of steps) {
40
- io.stdout("");
41
- io.stdout(`==> ${step.name}`);
42
- io.stdout(` $ ${step.command} ${step.args.join(" ")}`);
43
- const result = await run(step.command, step.args);
44
- if (result.code !== 0) {
45
- io.stderr(`FAIL "${step.name}" exited with code ${result.code}.`);
46
- if (result.stderrTail !== void 0 && result.stderrTail.length > 0) {
47
- io.stderr(result.stderrTail);
48
- }
49
- io.stderr("");
50
- io.stderr("Nothing further was run. To retry manually:");
51
- io.stderr(` ${step.command} ${step.args.join(" ")}`);
52
- return 1;
53
- }
54
- io.stdout(`OK ${step.name}`);
55
- }
56
- io.stdout("");
57
- io.stdout("PASS Demo is up. Try: agent-commerce doctor --config config-demo.yaml");
58
- return 0;
59
- }
60
- async function execCommand(command, args) {
61
- const { spawn } = await import('child_process');
62
- return new Promise((resolvePromise) => {
63
- let stderr = "";
64
- const child = spawn(command, args, { stdio: ["ignore", "inherit", "pipe"] });
65
- child.stderr?.on("data", (chunk) => {
66
- stderr += chunk.toString("utf8");
67
- });
68
- child.on("error", (err) => {
69
- resolvePromise({ code: 1, stderrTail: err.message });
70
- });
71
- child.on("close", (code) => {
72
- const tail = stderr.trim().split("\n").slice(-10).join("\n");
73
- resolvePromise({ code: code ?? 1, ...tail.length > 0 ? { stderrTail: tail } : {} });
74
- });
75
- });
76
- }
28
+ import { userInfo } from 'os';
77
29
 
78
30
  // src/cli/lib/config-client.ts
79
31
  async function importConfig() {
80
32
  try {
81
- return await import('./config-UI4EDG4L.js');
33
+ return await import('./config-3K65QJ22.js');
82
34
  } catch (err) {
83
35
  throw new CommerceError(
84
36
  "INTERNAL_ERROR",
@@ -92,26 +44,6 @@ async function loadConfigDynamic(options = {}) {
92
44
  async function parseConfigDynamic(raw, env = process.env) {
93
45
  return (await importConfig()).parseConfig(raw, env);
94
46
  }
95
-
96
- // src/cli/lib/http.ts
97
- async function fetchJson(fetchImpl, url, timeoutMs = 1500) {
98
- try {
99
- const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
100
- let body;
101
- try {
102
- body = await res.json();
103
- } catch {
104
- body = void 0;
105
- }
106
- return { ok: res.ok, status: res.status, ...body !== void 0 ? { body } : {} };
107
- } catch (err) {
108
- return {
109
- ok: false,
110
- status: 0,
111
- error: err instanceof Error ? err.message : "unknown fetch error"
112
- };
113
- }
114
- }
115
47
  var LOCAL_CHAIN_MANIFEST_PATH = ".deploy/local.json";
116
48
  var nonEmpty = z.string().min(1, "must be a non-empty string");
117
49
  var keyedAccount = z.object({ address: z.string(), privateKey: z.string(), note: z.string() });
@@ -210,6 +142,256 @@ function unresolvedVariableHint(variable, manifestFound, chainDeploy) {
210
142
  return `set ${variable} in the environment, or in a file passed with --env-file`;
211
143
  }
212
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
+
213
395
  // package.json
214
396
  var package_default = {
215
397
  dependencies: {
@@ -281,85 +463,178 @@ function isWritableFile(path) {
281
463
  return false;
282
464
  }
283
465
  }
284
- 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;
285
485
  if (path === ":memory:") {
286
486
  return {
287
487
  name,
288
488
  status: "WARN",
289
- 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}`
290
505
  };
291
506
  }
292
- if (existsSync(path)) {
293
- return isWritableFile(path) ? { name, status: "PASS", detail: `writable at "${path}"${suffix}` } : {
507
+ if (!isWritableFile(path)) {
508
+ return {
294
509
  name,
295
510
  status: "FAIL",
296
- 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}`
297
512
  };
298
513
  }
299
- 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
+ };
300
519
  }
301
520
  function missingStoreDetail(path) {
302
521
  const directory = dirname(path);
303
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`;
304
523
  }
305
- async function storageChecks(config, createStore) {
306
- 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) {
307
530
  if (config === void 0) {
308
- checks.push({ name: "Storage", status: "WARN", detail: "skipped: config invalid" });
309
- } else if (
310
- // Diagnose without creating: createSqliteReceiptStore creates the file,
311
- // so opening a wrong path (a typo, or a container path read from the
312
- // host) would leave an empty database and report it healthy, hiding the
313
- // real one. `:memory:` never exists on disk, so it takes the open branch
314
- // below.
315
- config.storage.receipts.path !== ":memory:" && !existsSync(config.storage.receipts.path)
316
- ) {
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` : "";
317
582
  checks.push({
318
583
  name: "Storage",
319
- status: "WARN",
320
- 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}`
321
586
  });
322
- } else {
323
- let store;
324
- try {
325
- store = createStore(config.storage.receipts.path);
326
- await store.init();
327
- const storeHealth = await store.health();
328
- let receiptCount;
329
- try {
330
- receiptCount = await store.countReceipts();
331
- } catch {
332
- receiptCount = void 0;
333
- }
334
- let undeliveredCount;
335
- try {
336
- undeliveredCount = await store.countUndeliveredReceipts();
337
- } catch {
338
- undeliveredCount = void 0;
339
- }
340
- let uncertainCount;
341
- try {
342
- uncertainCount = await store.countUncertainPaymentAttempts();
343
- } catch {
344
- uncertainCount = void 0;
345
- }
346
- const status = storeHealth.status === "pass" ? "PASS" : storeHealth.status === "warn" ? "WARN" : "FAIL";
347
- const receiptsSuffix = receiptCount !== void 0 ? `; receipts=${receiptCount}${undeliveredCount !== void 0 && undeliveredCount > 0 ? ` (${undeliveredCount} undelivered)` : ""}` : "";
348
- const uncertainSuffix = uncertainCount !== void 0 && uncertainCount > 0 ? `; ${uncertainCount} payment(s) with unknown settlement outcome, see GET /api/payment-attempts?uncertain=true` : "";
349
- checks.push({
350
- name: "Storage",
351
- status,
352
- detail: `${storeHealth.detail ?? "sqlite"}${receiptsSuffix}${uncertainSuffix}`
353
- });
354
- } catch (err) {
355
- checks.push({
356
- name: "Storage",
357
- status: "FAIL",
358
- detail: err instanceof Error ? err.message : String(err)
359
- });
360
- } finally {
361
- 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
+ };
362
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
+ });
363
638
  }
364
639
  return checks;
365
640
  }
@@ -371,7 +646,7 @@ function describeIssuers(label, issuers) {
371
646
  ).join(", ");
372
647
  return `${label} issuers: ${described}`;
373
648
  }
374
- function ap2Checks(config) {
649
+ function ap2Checks(config, legacy) {
375
650
  const checks = [];
376
651
  const ap2 = config?.authorization?.ap2;
377
652
  if (config === void 0) {
@@ -390,10 +665,13 @@ function ap2Checks(config) {
390
665
  detail: `${describeIssuers("mandate", ap2.trust.mandateIssuers)} \xB7 ${describeIssuers("checkout", ap2.trust.checkoutIssuers)}`
391
666
  });
392
667
  checks.push(
393
- storeFileCheck("AP2 replay store", ap2.replay.path, {
394
- inMemory: "every spent mandate is forgotten on restart, so one could authorize a second purchase",
395
- unwritable: "no mandate could be recorded as spent"
396
- })
668
+ legacyStoreCheck(
669
+ "AP2 replay store",
670
+ "ap2-replay",
671
+ ap2.replay?.path,
672
+ legacy,
673
+ "mandate holds in the receipt database"
674
+ )
397
675
  );
398
676
  const gated = config.resources.filter(
399
677
  (resource) => resource.authorization?.required.includes("ap2")
@@ -924,7 +1202,7 @@ function acpMappingCheck(config, operations) {
924
1202
  detail: `5 operations mapped to free acp-exposed resources (${Object.values(operations).join(", ")})`
925
1203
  };
926
1204
  }
927
- function protocolChecks(config, wellKnown) {
1205
+ function protocolChecks(config, wellKnown, legacy) {
928
1206
  const checks = [];
929
1207
  if (config === void 0) {
930
1208
  checks.push({ name: "Protocols", status: "WARN", detail: "skipped: config invalid" });
@@ -972,13 +1250,12 @@ function protocolChecks(config, wellKnown) {
972
1250
  detail: `bearer token configured (${acp.auth.token.length} characters, not shown)`
973
1251
  });
974
1252
  checks.push(
975
- storeFileCheck(
1253
+ legacyStoreCheck(
976
1254
  "ACP idempotency",
1255
+ "acp-idempotency",
977
1256
  acp.idempotency.path,
978
- {
979
- inMemory: "replay protection is lost on every restart",
980
- unwritable: "the adapter cannot claim idempotency keys"
981
- },
1257
+ legacy,
1258
+ `claims in the receipt database (retention ${acp.idempotency.retentionHours}h)`,
982
1259
  ` (retention ${acp.idempotency.retentionHours}h)`
983
1260
  )
984
1261
  );
@@ -1038,7 +1315,7 @@ function substitutePathParams(url) {
1038
1315
  async function runDoctor(options, deps = {}) {
1039
1316
  const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
1040
1317
  const loadConfig = deps.loadConfig ?? loadConfigDynamic;
1041
- const createStore = deps.createStore ?? ((path) => createSqliteReceiptStore({ path }));
1318
+ const createStore = deps.createStore ?? ((path) => path === ":memory:" ? createSqliteReceiptStore({ path }) : openSqliteReceiptStoreReadOnly(path));
1042
1319
  const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;
1043
1320
  const chainDeploy = (deps.hasChainDeployScript ?? hasChainDeployScript)();
1044
1321
  const checks = [];
@@ -1107,12 +1384,13 @@ async function runDoctor(options, deps = {}) {
1107
1384
  `${gatewayUrl}/.well-known/agent-commerce`,
1108
1385
  CHECK_TIMEOUT_MS
1109
1386
  ) : void 0;
1110
- checks.push(...protocolChecks(config, wellKnown));
1111
- 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));
1112
1390
  checks.push(
1113
1391
  ...await paymentChecks(config, wellKnown, gatewayUrl, chainDeploy, deps.loadViemAccounts)
1114
1392
  );
1115
- checks.push(...await storageChecks(config, createStore));
1393
+ checks.push(...storage.checks);
1116
1394
  if (wellKnown?.ok) {
1117
1395
  checks.push({
1118
1396
  name: "Protocol versions",
@@ -2298,58 +2576,6 @@ function printSummary(result, context, io) {
2298
2576
  function describe(error) {
2299
2577
  return error instanceof Error ? error.message : String(error);
2300
2578
  }
2301
-
2302
- // src/cli/commands/validate.ts
2303
- function formatConfigError(err, manifestFound = false, chainDeploy = hasChainDeployScript()) {
2304
- if (isCommerceError(err)) {
2305
- const lines = [`FAIL ${err.code}: ${err.message}`];
2306
- if (err.details !== void 0) {
2307
- lines.push(` details: ${JSON.stringify(err.details)}`);
2308
- }
2309
- const variable = err.details?.["variable"];
2310
- if (typeof variable === "string") {
2311
- lines.push(` hint: ${unresolvedVariableHint(variable, manifestFound, chainDeploy)}`);
2312
- }
2313
- return lines.join("\n");
2314
- }
2315
- if (err instanceof Error) {
2316
- return `FAIL ${err.message}`;
2317
- }
2318
- return `FAIL ${String(err)}`;
2319
- }
2320
- async function runValidate(options, io, deps = {}) {
2321
- const loadConfig = deps.loadConfig ?? loadConfigDynamic;
2322
- const fillEnvFromManifest = deps.fillEnvFromManifest ?? fillEnvFromLocalChainManifest;
2323
- const { env, filled, manifestFound } = fillEnvFromManifest(process.env);
2324
- if (filled.length > 0) {
2325
- io.stdout(`using local chain manifest ${LOCAL_CHAIN_MANIFEST_PATH} for ${filled.join(", ")}`);
2326
- }
2327
- try {
2328
- const config = await loadConfig({
2329
- ...options.configPath !== void 0 ? { path: options.configPath } : {},
2330
- env
2331
- });
2332
- io.stdout("PASS Configuration is valid");
2333
- io.stdout(` merchant: ${config.merchant.name} (${config.merchant.id})`);
2334
- io.stdout(` resources: ${config.resources.length}`);
2335
- io.stdout(
2336
- ` 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"}`
2337
- );
2338
- const onOff = (enabled) => enabled === true ? "on" : "off";
2339
- io.stdout(
2340
- ` payments: x402=${onOff(config.payments.x402?.enabled)} mpp=${onOff(config.payments.mpp?.enabled)}`
2341
- );
2342
- io.stdout(` authorization: ap2=${onOff(config.authorization?.ap2.enabled)}`);
2343
- return 0;
2344
- } catch (err) {
2345
- io.stderr(
2346
- formatConfigError(err, manifestFound, (deps.hasChainDeployScript ?? hasChainDeployScript)())
2347
- );
2348
- return 1;
2349
- }
2350
- }
2351
-
2352
- // src/cli/commands/init.ts
2353
2579
  async function collectAnswersInteractive() {
2354
2580
  clack.intro("agent-commerce init");
2355
2581
  const backendBaseUrl = await clack.text({
@@ -2476,6 +2702,265 @@ async function runInit(options, io, deps = {}) {
2476
2702
  io.stdout(" docker compose up # or the whole local demo stack, from a repo clone");
2477
2703
  return 0;
2478
2704
  }
2705
+ var DURATION = /^(\d{1,9})(s|m|h|d)$/;
2706
+ var UNIT_MS = { s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
2707
+ async function runReconcileCommand(options, io, deps = {}) {
2708
+ const minAgeMs = options.minAge !== void 0 ? parseDuration(options.minAge) : void 0;
2709
+ if (minAgeMs === null) {
2710
+ io.stderr(`FAIL --min-age must be a duration such as 30s, 15m or 2h, got "${options.minAge}"`);
2711
+ return 1;
2712
+ }
2713
+ const limit = options.limit !== void 0 ? Number(options.limit) : void 0;
2714
+ if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 1)) {
2715
+ io.stderr(`FAIL --limit must be a positive integer, got "${options.limit}"`);
2716
+ return 1;
2717
+ }
2718
+ const actor = options.actor ?? osUser();
2719
+ if (actor.trim() === "") {
2720
+ io.stderr("FAIL --actor must not be empty");
2721
+ return 1;
2722
+ }
2723
+ let config;
2724
+ try {
2725
+ config = await (deps.loadConfig ?? loadConfigDynamic)(
2726
+ options.configPath !== void 0 ? { path: options.configPath } : {}
2727
+ );
2728
+ } catch (error) {
2729
+ io.stderr(formatConfigError(error, false, false));
2730
+ return 1;
2731
+ }
2732
+ try {
2733
+ const logger = stderrLogger(io);
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;
2737
+ await withJournal(config, logger, async (store, authorizationProviders) => {
2738
+ report = await runReconcile({
2739
+ store,
2740
+ providers,
2741
+ authorizationProviders,
2742
+ clock: systemClock,
2743
+ actor,
2744
+ dryRun: options.dryRun === true,
2745
+ ...minAgeMs !== void 0 ? { minAgeMs } : {},
2746
+ ...limit !== void 0 ? { limit } : {},
2747
+ logger
2748
+ });
2749
+ printReport(report, io, options.json === true);
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
+ }
2757
+ return 0;
2758
+ } catch (error) {
2759
+ io.stderr(`FAIL reconcile could not run: ${redactedErrorText(error)}`);
2760
+ return 1;
2761
+ }
2762
+ }
2763
+ async function withJournal(config, logger, fn) {
2764
+ const [
2765
+ { createConfiguredAuthorizationProviders },
2766
+ { createSqliteReceiptStore: createSqliteReceiptStore2, openSqliteReceiptStoreReadOnly: openSqliteReceiptStoreReadOnly2 }
2767
+ ] = await Promise.all([
2768
+ import('./payment-providers-2ITS6KNR.js'),
2769
+ import('./receipts-I4IIE7U6.js')
2770
+ ]);
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 });
2787
+ try {
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
+ );
2805
+ try {
2806
+ await fn(store, authorizationProviders);
2807
+ } finally {
2808
+ for (const provider of authorizationProviders) provider.close();
2809
+ }
2810
+ } finally {
2811
+ await store.close();
2812
+ }
2813
+ }
2814
+ function parseDuration(value) {
2815
+ if (value === "0") return 0;
2816
+ const match = DURATION.exec(value);
2817
+ return match ? Number(match[1]) * UNIT_MS[match[2]] : null;
2818
+ }
2819
+ function printReport(report, io, json) {
2820
+ const count = (outcome) => report.entries.filter((e) => e.outcome === outcome).length;
2821
+ const counts = {
2822
+ candidates: report.entries.length,
2823
+ settled: count("settled"),
2824
+ notSettled: count("not-settled"),
2825
+ unknown: count("unknown"),
2826
+ resolved: report.entries.filter((e) => e.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
2830
+ };
2831
+ if (json) {
2832
+ io.stdout(
2833
+ JSON.stringify(
2834
+ {
2835
+ dryRun: report.dryRun,
2836
+ counts,
2837
+ entries: report.entries,
2838
+ holds: report.holds,
2839
+ orphanHolds: report.orphanHolds,
2840
+ failedScans: report.failedScans
2841
+ },
2842
+ null,
2843
+ 2
2844
+ )
2845
+ );
2846
+ return;
2847
+ }
2848
+ io.stdout(
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` : "")
2850
+ );
2851
+ for (const entry of report.entries) {
2852
+ io.stdout(
2853
+ [
2854
+ entry.outcome.toUpperCase().padEnd(11),
2855
+ entry.attemptId,
2856
+ `request=${entry.requestId}`,
2857
+ `provider=${entry.provider}`,
2858
+ `status=${entry.status}`,
2859
+ `reason=${entry.reason}`,
2860
+ ...entry.externalReference !== void 0 ? [`reference=${entry.externalReference}`] : [],
2861
+ ...entry.retryAfter !== void 0 ? [`retryAfter=${entry.retryAfter}`] : [],
2862
+ ...entry.error !== void 0 ? [`error=${entry.error}`] : [],
2863
+ ...entry.written ? ["resolved"] : []
2864
+ ].join(" ")
2865
+ );
2866
+ }
2867
+ for (const hold of report.holds) {
2868
+ io.stdout(
2869
+ [
2870
+ "HOLD".padEnd(11),
2871
+ hold.transactionId,
2872
+ `attempt=${hold.attemptId}`,
2873
+ `method=${hold.method}`,
2874
+ `hold=${hold.hold}`,
2875
+ ...hold.reason !== void 0 ? [`reason=${hold.reason}`] : [],
2876
+ ...hold.written ? ["aligned"] : []
2877
+ ].join(" ")
2878
+ );
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
+ }
2893
+ }
2894
+ function osUser() {
2895
+ try {
2896
+ return userInfo().username;
2897
+ } catch {
2898
+ return "unknown";
2899
+ }
2900
+ }
2901
+ function stderrLogger(io) {
2902
+ const write = (level) => (obj, msg) => io.stderr(`${level} ${msg ?? ""} ${JSON.stringify(obj)}`.trimEnd());
2903
+ return {
2904
+ ...NOOP_LOGGER,
2905
+ warn: write("WARN"),
2906
+ error: write("ERROR"),
2907
+ child: () => stderrLogger(io)
2908
+ };
2909
+ }
2910
+
2911
+ // src/cli/commands/resolve.ts
2912
+ var OPERATOR_ERRORS = /* @__PURE__ */ new Set(["INPUT_INVALID", "RESOURCE_NOT_FOUND"]);
2913
+ async function runResolveCommand(attemptId, options, io, deps = {}) {
2914
+ let config;
2915
+ try {
2916
+ config = await (deps.loadConfig ?? loadConfigDynamic)(
2917
+ options.configPath !== void 0 ? { path: options.configPath } : {}
2918
+ );
2919
+ } catch (error) {
2920
+ io.stderr(formatConfigError(error, false, false));
2921
+ return 1;
2922
+ }
2923
+ try {
2924
+ const { resolveManually } = await import('./reconcile-55WNCSFC.js');
2925
+ const logger = stderrLogger(io);
2926
+ let code = 1;
2927
+ await withJournal(config, logger, async (store, authorizationProviders) => {
2928
+ const result = await resolveManually({
2929
+ store,
2930
+ authorizationProviders,
2931
+ clock: systemClock,
2932
+ logger,
2933
+ attemptId,
2934
+ status: options.status,
2935
+ actor: options.actor ?? osUser(),
2936
+ reason: options.reason,
2937
+ ...options.reference !== void 0 ? { externalReference: options.reference } : {},
2938
+ ...options.confirmExpired === true ? { confirmExpired: true } : {}
2939
+ });
2940
+ if (!result.resolved) {
2941
+ const hint = result.refusal === "expiry_unknown" ? " (pass --confirm-expired)" : "";
2942
+ io.stderr(
2943
+ `FAIL ${attemptId} not resolved: ${result.message}${hint} [${result.refusal}, status=${result.attempt.status}]`
2944
+ );
2945
+ return;
2946
+ }
2947
+ io.stdout(`RESOLVED ${attemptId} status=${result.attempt.status}`);
2948
+ const { hold } = result;
2949
+ if (hold !== void 0) {
2950
+ io.stdout(
2951
+ hold.written ? `HOLD ${hold.method} ${hold.hold}` : `WARN ${hold.method} hold not ${hold.hold} (${hold.reason}); agent-commerce reconcile aligns it once the provider is available`
2952
+ );
2953
+ }
2954
+ code = 0;
2955
+ });
2956
+ return code;
2957
+ } catch (error) {
2958
+ io.stderr(
2959
+ isCommerceError(error) && OPERATOR_ERRORS.has(error.code) ? `FAIL ${error.code}: ${error.message}` : `FAIL resolve could not run: ${redactedErrorText(error)}`
2960
+ );
2961
+ return 1;
2962
+ }
2963
+ }
2479
2964
 
2480
2965
  // src/cli/commands/version.ts
2481
2966
  function runVersion(io, deps = {}) {
@@ -2508,7 +2993,9 @@ var processIo = {
2508
2993
  var ENV_FILE_HELP = "load environment variables from this file; variables already set win";
2509
2994
  function buildProgram(io = processIo) {
2510
2995
  const program = new Command();
2511
- program.name("agent-commerce").description("CLI for the Agent Commerce Gateway: init, import, validate, start, doctor, demo.").version(readVersionReport().cliVersion, "-v, --version", "Print the CLI version.").exitOverride().configureOutput({
2996
+ program.name("agent-commerce").description(
2997
+ "CLI for the Agent Commerce Gateway: init, import, validate, start, doctor, reconcile, backup, demo."
2998
+ ).version(readVersionReport().cliVersion, "-v, --version", "Print the CLI version.").exitOverride().configureOutput({
2512
2999
  writeOut: (str) => io.stdout(str.replace(/\n+$/, "")),
2513
3000
  writeErr: (str) => io.stderr(str.replace(/\n+$/, ""))
2514
3001
  }).hook("preAction", (_program, command) => {
@@ -2536,7 +3023,7 @@ function buildProgram(io = processIo) {
2536
3023
  `Start the gateway from ${DEFAULT_CONFIG_FILENAME} and serve until SIGTERM or SIGINT.`
2537
3024
  ).option("--config <path>", `path to ${DEFAULT_CONFIG_FILENAME}`).option("--env-file <path>", ENV_FILE_HELP).action(async (opts) => {
2538
3025
  try {
2539
- const { runGateway } = await import('./run-JK4ERPJV.js');
3026
+ const { runGateway } = await import('./run-2P6ZGFUE.js');
2540
3027
  await runGateway(opts.config !== void 0 ? { configPath: opts.config } : {});
2541
3028
  } catch (error) {
2542
3029
  io.stderr(formatConfigError(error, false, false));
@@ -2554,6 +3041,60 @@ function buildProgram(io = processIo) {
2554
3041
  printDoctorReport(report, io, opts.json === true);
2555
3042
  process.exitCode = report.exitCode;
2556
3043
  });
3044
+ program.command("reconcile").description(
3045
+ "Resolve uncertain payment attempts using chain evidence. Never settles or refunds."
3046
+ ).option("--config <path>", `path to ${DEFAULT_CONFIG_FILENAME}`).option("--env-file <path>", ENV_FILE_HELP).option("--dry-run", "read evidence and report without recording resolutions", false).option("--json", "emit machine-readable JSON instead of a formatted report", false).option("--actor <name>", "who ran it, stored with each resolution (default: the OS user)").option(
3047
+ "--min-age <duration>",
3048
+ "skip reserved attempts younger than this, such as 30s, 15m or 2h (default: 15m)"
3049
+ ).option("--limit <n>", "check at most this many attempts, and update at most this many holds").action(
3050
+ async (opts) => {
3051
+ process.exitCode = await runReconcileCommand(
3052
+ {
3053
+ ...opts.config !== void 0 ? { configPath: opts.config } : {},
3054
+ dryRun: opts.dryRun,
3055
+ json: opts.json,
3056
+ ...opts.actor !== void 0 ? { actor: opts.actor } : {},
3057
+ ...opts.minAge !== void 0 ? { minAge: opts.minAge } : {},
3058
+ ...opts.limit !== void 0 ? { limit: opts.limit } : {}
3059
+ },
3060
+ io
3061
+ );
3062
+ }
3063
+ );
3064
+ program.command("resolve <attemptId>").description(
3065
+ "Record a verdict on one unresolved payment attempt and align its hold. Never settles or refunds."
3066
+ ).requiredOption("--status <status>", "settled or rejected").requiredOption("--reason <text>", "why, stored with the resolution").option("--reference <ref>", "transaction reference, stored as your unchecked claim").option("--actor <name>", "who resolved it, stored with the resolution (default: the OS user)").option(
3067
+ "--confirm-expired",
3068
+ "confirm that an authorization with no recorded expiry can no longer land",
3069
+ false
3070
+ ).option("--config <path>", `path to ${DEFAULT_CONFIG_FILENAME}`).option("--env-file <path>", ENV_FILE_HELP).action(
3071
+ async (attemptId, opts) => {
3072
+ process.exitCode = await runResolveCommand(
3073
+ attemptId,
3074
+ {
3075
+ ...opts.config !== void 0 ? { configPath: opts.config } : {},
3076
+ status: opts.status,
3077
+ reason: opts.reason,
3078
+ ...opts.reference !== void 0 ? { reference: opts.reference } : {},
3079
+ ...opts.actor !== void 0 ? { actor: opts.actor } : {},
3080
+ confirmExpired: opts.confirmExpired
3081
+ },
3082
+ io
3083
+ );
3084
+ }
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
+ });
2557
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) => {
2558
3099
  const code = await runInit({ outputPath: opts.output, force: opts.force, yes: opts.yes }, io);
2559
3100
  process.exitCode = code;