@visa/cli 4.1.0-rc.25 → 4.1.0-rc.250

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 (89) hide show
  1. package/README.md +273 -227
  2. package/dist/checkout-engine/adapters/generic.d.ts +69 -0
  3. package/dist/checkout-engine/adapters/generic.js +383 -58
  4. package/dist/checkout-engine/adapters/index.d.ts +4 -1
  5. package/dist/checkout-engine/adapters/index.js +10 -3
  6. package/dist/checkout-engine/adapters/shopify.d.ts +80 -0
  7. package/dist/checkout-engine/adapters/shopify.js +688 -0
  8. package/dist/checkout-engine/amount.d.ts +15 -0
  9. package/dist/checkout-engine/amount.js +72 -0
  10. package/dist/checkout-engine/browser-launch.d.ts +9 -4
  11. package/dist/checkout-engine/browser-launch.js +19 -4
  12. package/dist/checkout-engine/browserbase-browser.d.ts +24 -0
  13. package/dist/checkout-engine/browserbase-browser.js +186 -0
  14. package/dist/checkout-engine/cli-engine.d.ts +297 -4
  15. package/dist/checkout-engine/cli-engine.js +942 -48
  16. package/dist/checkout-engine/confirmed-merchants.d.ts +31 -0
  17. package/dist/checkout-engine/confirmed-merchants.js +165 -0
  18. package/dist/checkout-engine/detect.d.ts +1 -1
  19. package/dist/checkout-engine/detect.js +26 -0
  20. package/dist/checkout-engine/evidence.d.ts +4 -1
  21. package/dist/checkout-engine/evidence.js +51 -6
  22. package/dist/checkout-engine/executor.d.ts +64 -4
  23. package/dist/checkout-engine/executor.js +625 -146
  24. package/dist/checkout-engine/hosted-approval.d.ts +124 -7
  25. package/dist/checkout-engine/hosted-approval.js +384 -54
  26. package/dist/checkout-engine/index.d.ts +9 -2
  27. package/dist/checkout-engine/index.js +8 -1
  28. package/dist/checkout-engine/instrument.d.ts +7 -0
  29. package/dist/checkout-engine/instrument.js +4 -0
  30. package/dist/checkout-engine/known-merchants.d.ts +10 -0
  31. package/dist/checkout-engine/known-merchants.js +38 -0
  32. package/dist/checkout-engine/live-fill-approval.d.ts +5 -20
  33. package/dist/checkout-engine/live-fill-approval.js +20 -51
  34. package/dist/checkout-engine/mandate/card-mandate.d.ts +121 -0
  35. package/dist/checkout-engine/mandate/card-mandate.js +226 -0
  36. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +174 -0
  37. package/dist/checkout-engine/mandate/mandate-ledger.js +410 -0
  38. package/dist/checkout-engine/outcome.d.ts +2 -2
  39. package/dist/checkout-engine/outcome.js +36 -1
  40. package/dist/checkout-engine/owner-only-file.d.ts +9 -0
  41. package/dist/checkout-engine/owner-only-file.js +20 -1
  42. package/dist/checkout-engine/receipt-dir.d.ts +6 -0
  43. package/dist/checkout-engine/receipt-dir.js +8 -0
  44. package/dist/checkout-engine/receipt.d.ts +56 -2
  45. package/dist/checkout-engine/receipt.js +55 -16
  46. package/dist/checkout-engine/shopify-primary-domain.d.ts +25 -0
  47. package/dist/checkout-engine/shopify-primary-domain.js +96 -0
  48. package/dist/checkout-engine/trace-handles.d.ts +8 -0
  49. package/dist/checkout-engine/trace-handles.js +12 -0
  50. package/dist/checkout-engine/types.d.ts +28 -2
  51. package/dist/checkout-engine/unresolved-charges.d.ts +34 -0
  52. package/dist/checkout-engine/unresolved-charges.js +134 -0
  53. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +53 -1
  54. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +78 -10
  55. package/dist/checkout-engine/vgs-live-instrument.d.ts +38 -35
  56. package/dist/checkout-engine/vgs-live-instrument.js +51 -74
  57. package/dist/checkout-engine/vic-confirmation.d.ts +18 -0
  58. package/dist/checkout-engine/vic-confirmation.js +9 -3
  59. package/dist/checkout-engine/web-bot-auth.d.ts +98 -0
  60. package/dist/checkout-engine/web-bot-auth.js +218 -0
  61. package/dist/cli.js +905 -505
  62. package/dist/mcp-apps/ucp-checkout.html +280 -0
  63. package/dist/mcp-server/index.js +744 -175
  64. package/dist/merchant-ucp-mcp/index.js +6 -0
  65. package/dist/skills/pair-visa-agent/RUNTIMES.md +122 -79
  66. package/dist/skills/pair-visa-agent/SKILL.md +436 -279
  67. package/dist/skills/pair-visa-agent/scripts/__tests__/setup.test.mjs +407 -0
  68. package/dist/skills/pair-visa-agent/scripts/setup.mjs +310 -30
  69. package/dist/skills/visa-shopify-checkout/SKILL.md +122 -0
  70. package/dist/skills/visa-shopify-checkout/references/evidence-and-states.md +37 -0
  71. package/dist/skills/visa-ucp-shopping/SKILL.md +86 -0
  72. package/dist/subway-direct.mjs +1 -0
  73. package/install.ps1 +9 -46
  74. package/install.sh +5 -37
  75. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  76. package/package.json +32 -28
  77. package/server.json +4 -4
  78. package/dist/checkout-engine/inline-target.d.ts +0 -13
  79. package/dist/checkout-engine/inline-target.js +0 -37
  80. package/dist/checkout-engine/pay-args.d.ts +0 -14
  81. package/dist/checkout-engine/pay-args.js +0 -44
  82. package/dist/checkout-engine/pay.d.ts +0 -1
  83. package/dist/checkout-engine/pay.js +0 -13
  84. package/dist/checkout-engine/repo-env.d.ts +0 -11
  85. package/dist/checkout-engine/repo-env.js +0 -23
  86. package/dist/checkout-engine/run-live-fill.d.ts +0 -1
  87. package/dist/checkout-engine/run-live-fill.js +0 -443
  88. package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +0 -74
  89. package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +0 -248
@@ -10,32 +10,264 @@
10
10
  //
11
11
  // Every browser/network primitive is injectable (CliEngineDeps) so the session/
12
12
  // timer/store lifecycle is unit-testable without launching Chromium.
13
- import { homedir } from 'node:os';
14
- import { join } from 'node:path';
15
13
  import { readFile } from 'node:fs/promises';
14
+ import { randomUUID } from 'node:crypto';
16
15
  import { launchCheckoutBrowser } from './browser-launch.js';
16
+ import { RECEIPT_DIR } from './receipt-dir.js';
17
17
  import { prepareCheckout as realPrepareCheckout, submitApprovedCheckout as realSubmitApprovedCheckout, InMemoryPreparedCheckoutStore, } from './executor.js';
18
- import { runHostedApproval as realRunHostedApproval } from './hosted-approval.js';
19
- import { VgsAssuranceInstrument, decimalToMinor, } from './vgs-live-instrument.js';
18
+ import { claimMandatePickup as realClaimMandatePickup, runHostedApproval as realRunHostedApproval, } from './hosted-approval.js';
19
+ import { VgsLiveInstrument, decimalToMinor, minorToDecimal, } from './vgs-live-instrument.js';
20
20
  import { serverCreateIntent, serverFetchCryptogram, serverPostConfirmation, } from './vgs-gateway/server-mint-client.js';
21
- import { buildReceipt, writeReceipt as realWriteReceipt } from './receipt.js';
21
+ import { createCardMandate, DEFAULT_MANDATE_MAX_DRAWS, drawFromMandate, MandateDrawDeclinedError, } from './mandate/card-mandate.js';
22
+ import { MandateLedger } from './mandate/mandate-ledger.js';
23
+ import { buildReceipt, writeReceipt as realWriteReceipt, } from './receipt.js';
22
24
  import { reportVicOutcome as realReportVicOutcome, } from './vic-confirmation.js';
23
- const RECEIPT_DIR = join(homedir(), '.visa-mcp', 'checkout-receipts');
25
+ /**
26
+ * A card-mandate draw failed transiently (retryable) rather than definitively.
27
+ * Gateway 5xx, "server cryptogram not completed / try again", and network
28
+ * reset/timeout errors are transient: the mandate stays healthy and must NOT be
29
+ * disabled. Walks the error's cause chain so a wrapped MandateDrawDeclinedError
30
+ * is classified by its underlying gateway error. Exported for tests.
31
+ */
32
+ export function isTransientDrawFailure(err) {
33
+ const msgs = [];
34
+ let e = err;
35
+ for (let i = 0; i < 5 && e; i++) {
36
+ // A refusal that declared itself TERMINAL wins outright, before any message
37
+ // matching. Message text is not a safe carrier for this decision: the mint
38
+ // client interpolates provider-supplied `upstream_codes` into its message
39
+ // for diagnosability, and an identifier like `request_timeout` would match
40
+ // the unanchored `tim(e|ed)-out` alternative below and silently reclassify
41
+ // a permanent 422 as transient — skipping markUnhonored and stranding the
42
+ // mandate in the retry-forever loop this classifier exists to prevent.
43
+ // Duck-typed rather than instanceof so it survives bundling and any
44
+ // re-wrapping across package boundaries. Optional chaining rather than an
45
+ // explicit null guard: the loop condition already proved `e` truthy, so a
46
+ // `e !== null` test is dead code, and `?.` stays safe on a primitive or a
47
+ // nullish link if that guard ever changes.
48
+ if (e?.terminal === true) {
49
+ return false;
50
+ }
51
+ if (e instanceof Error && typeof e.message === 'string')
52
+ msgs.push(e.message);
53
+ e = e.cause;
54
+ }
55
+ // Transient = a gateway 5xx / 429 in the mint client's "(last: <status>: …)"
56
+ // framing, or an unambiguous network reset/timeout error name. The status is
57
+ // ANCHORED to `(last:` so a bare 3-digit token elsewhere (an amount, a ref id,
58
+ // an attempt count) can never be mistaken for a status code, and so the
59
+ // advisory DRAW_REMEDY wrapper text ("gateway 5xx / try again") cannot
60
+ // self-classify a hard decline as transient. A hard decline (4xx / a
61
+ // card-decline reason) matches nothing here → the mandate is correctly disabled.
62
+ return /\(last:\s*(?:5\d\d|429)\b|\bETIMEDOUT\b|\bECONNRESET\b|\bECONNREFUSED\b|\bEAI_AGAIN\b|socket hang up|tim(?:e|ed)[ -]?out/i.test(msgs.join(' '));
63
+ }
64
+ /**
65
+ * Refusals that are about the OUTER card GRANT's remaining capacity, not about
66
+ * this mandate and not about the card network (#7491).
67
+ *
68
+ * The atomic reserve (#7233) charges the grant's shared `agent_grant_usage`
69
+ * epoch, so an exhausted or replaced grant refuses BEFORE any credential is
70
+ * minted: no cryptogram is issued, no processor intent is created, no money
71
+ * moves. Treating that as a mandate decline burned the budget the human had
72
+ * just approved and told the caller to create another mandate — which, over the
73
+ * same exhausted grant, is guaranteed to fail identically. The honest remedy is
74
+ * a new/replacement card grant, and the mandate must stay honored so it can
75
+ * draw once the owner supplies one.
76
+ */
77
+ // Deliberately NARROW. `grant_aggregate_no_mandate` is NOT here: that refusal
78
+ // means the mandate row itself vanished between the read and the reserve, which
79
+ // is a statement about the mandate, not about the grant's capacity.
80
+ const GRANT_CAPACITY_REASONS = new Set([
81
+ 'over_grant_aggregate',
82
+ 'no_active_grant',
83
+ 'no_active_grant_or_card_scope',
84
+ 'card_grant_exhausted',
85
+ ]);
86
+ function isGrantCapacityReason(reason) {
87
+ return GRANT_CAPACITY_REASONS.has(reason);
88
+ }
89
+ /**
90
+ * A verdict refusal may be wrapped by drawFromMandate after its local
91
+ * reservation is released. Walk the cause chain so the original auth status +
92
+ * reasons still decide whether the mandate is permanently disabled.
93
+ */
94
+ // Exported for the cross-package pin in test/cli-engine.test.ts: the CLI's
95
+ // card-draw client decides the `status` this reads, so the two move together
96
+ // and a test that spans the boundary is the only one that would catch a drift.
97
+ // Not re-exported from index.ts — the public @visa/checkout-engine surface is
98
+ // the explicit allowlist there, same as isTransientDrawFailure above.
99
+ export function classifyCardDrawVerdictFailure(err) {
100
+ const transientReasons = new Set(['challenge_failed', 'challenge_malformed', 'verdict_refused']);
101
+ let current = err;
102
+ for (let i = 0; i < 5 && current; i++) {
103
+ const candidate = current;
104
+ const status = typeof candidate.status === 'number' ? candidate.status : 0;
105
+ const reasons = Array.isArray(candidate.reasons)
106
+ ? candidate.reasons.filter((reason) => typeof reason === 'string')
107
+ : [];
108
+ if (status !== 0 || reasons.length > 0) {
109
+ const transient = status === 503 ||
110
+ reasons.length === 0 ||
111
+ reasons.every((reason) => transientReasons.has(reason));
112
+ return {
113
+ transient,
114
+ // A capacity refusal is NEITHER transient nor a decline. Retrying now
115
+ // fails identically (so it is not transient), but nothing about the
116
+ // MANDATE was refused (so it is not a decline). Only a refusal that is
117
+ // exclusively about the outer grant qualifies: a mixed reason list
118
+ // still carries a real mandate/network refusal and stays a decline.
119
+ grantCapacity: !transient && reasons.length > 0 && reasons.every(isGrantCapacityReason),
120
+ reasons,
121
+ };
122
+ }
123
+ current = candidate.cause;
124
+ }
125
+ return null;
126
+ }
127
+ /**
128
+ * Resolve the card instrument for one flow. Fail-closed: an unusable legacy file
129
+ * with no grant token rethrows (never silently proceeds), and the ONLY thing the
130
+ * fallback contributes is a token id — a non-secret handle the server
131
+ * re-authorizes against the owner (`requireTokenOwnership`) and against the live
132
+ * grant on every draw. Nothing here authorizes anything.
133
+ */
134
+ async function resolveCardInstrument(input) {
135
+ if (typeof input.cardTokenId === 'string' && input.cardTokenId.trim()) {
136
+ return { tokenId: input.cardTokenId.trim(), source: 'card-grant' };
137
+ }
138
+ let credential = null;
139
+ let readError = null;
140
+ try {
141
+ credential = JSON.parse(await readFile(input.credentialPath, 'utf8'));
142
+ }
143
+ catch (err) {
144
+ readError = err;
145
+ }
146
+ if (credential && typeof credential.tokenId === 'string' && credential.tokenId.trim()) {
147
+ return credential;
148
+ }
149
+ throw new Error('no card instrument is available to this runtime: there is no usable credential at ' +
150
+ `${input.credentialPath} and no activated card:vic grant token was supplied. Run ` +
151
+ '`visa agent grant-card <agent-id> --ceiling <usd> --per-transaction <usd> --wait` to ' +
152
+ 'attach one, or use a pre-provisioned VIC runtime.', readError instanceof Error ? { cause: readError } : undefined);
153
+ }
154
+ /**
155
+ * A checkout was inspected successfully but cannot be reviewed safely.
156
+ *
157
+ * The explicit fields survive the CLI's copied-engine boundary structurally,
158
+ * so MCP callers do not have to parse the human-readable message.
159
+ */
160
+ export class CheckoutReviewRefusedError extends Error {
161
+ code = 'CHECKOUT_REVIEW_REFUSED';
162
+ checkoutOutcome;
163
+ failureCode;
164
+ requiresAdapter;
165
+ detectedRoles;
166
+ receiptWrite;
167
+ detail;
168
+ constructor(result, receiptWrite) {
169
+ super(result.detail
170
+ ? `review refused: ${result.outcome} — ${result.detail}`
171
+ : `review refused: ${result.outcome}`);
172
+ this.name = 'CheckoutReviewRefusedError';
173
+ this.checkoutOutcome = result.outcome;
174
+ this.failureCode = result.failureCode;
175
+ this.requiresAdapter = [...result.requiresAdapter];
176
+ this.detectedRoles = Object.keys(result.fields);
177
+ this.receiptWrite = receiptWrite;
178
+ this.detail = result.detail;
179
+ }
180
+ }
181
+ function payAttemptFingerprint(input) {
182
+ return JSON.stringify([
183
+ input.url,
184
+ input.checkoutRoute,
185
+ input.amount,
186
+ input.currency,
187
+ input.credentialPath,
188
+ input.cardTokenId ?? null,
189
+ input.agentJkt ?? null,
190
+ input.contact,
191
+ input.approvalBaseUrl,
192
+ input.merchantName ?? null,
193
+ input.merchantCountryCode ?? null,
194
+ input.submit,
195
+ ]);
196
+ }
197
+ function failedPay(detail) {
198
+ return {
199
+ outcome: 'failed',
200
+ confirmationRef: null,
201
+ receiptPath: null,
202
+ detail,
203
+ vicConfirmation: null,
204
+ source: null,
205
+ remainingMinor: null,
206
+ credentialIssued: false,
207
+ credentialDisclosed: false,
208
+ };
209
+ }
210
+ function boundedReceiptWriteErrorCode(reason) {
211
+ return reason.match(/\b(?:EACCES|EEXIST|ENOSPC|ENOTDIR|EPERM|EROFS)\b/)?.[0] ?? 'UNKNOWN';
212
+ }
24
213
  // Must match the prepared-checkout store TTL so a session and its store entry
25
214
  // expire together — an abandoned review can't leak the browser + state.
26
215
  const PREPARED_TTL_MS = 5 * 60 * 1000;
27
216
  const defaultStore = new InMemoryPreparedCheckoutStore({ ttlMs: PREPARED_TTL_MS });
28
217
  const defaultSessions = new Map();
218
+ const defaultPayAttempts = new Map();
219
+ const defaultLedger = new MandateLedger();
29
220
  export function createCliCheckoutEngine(deps = {}) {
30
221
  const store = deps.store ?? defaultStore;
31
222
  const sessions = deps.sessions ?? defaultSessions;
223
+ const payAttempts = deps.payAttempts ?? defaultPayAttempts;
32
224
  const ttlMs = deps.ttlMs ?? PREPARED_TTL_MS;
33
225
  const launchBrowser = deps.launchBrowser ?? (() => launchCheckoutBrowser());
34
226
  const prepareCheckout = deps.prepareCheckout ?? realPrepareCheckout;
35
227
  const submitApprovedCheckout = deps.submitApprovedCheckout ?? realSubmitApprovedCheckout;
36
228
  const runHostedApproval = deps.runHostedApproval ?? realRunHostedApproval;
229
+ const claimMandatePickup = deps.claimMandatePickup ?? realClaimMandatePickup;
37
230
  const reportVicOutcome = deps.reportVicOutcome ?? realReportVicOutcome;
38
231
  const writeReceipt = deps.writeReceipt ?? realWriteReceipt;
232
+ const ledger = deps.ledger ?? defaultLedger;
233
+ const now = deps.now ?? (() => new Date());
234
+ const fetchMandateCryptogram = deps.serverFetchCryptogram ?? serverFetchCryptogram;
235
+ const postServerConfirmation = deps.serverPostConfirmation ?? serverPostConfirmation;
236
+ const createObservationId = deps.createObservationId ?? randomUUID;
237
+ async function writeObservedReceipt(mode, receipt) {
238
+ let report;
239
+ try {
240
+ report = await writeReceipt(RECEIPT_DIR, receipt);
241
+ }
242
+ catch (err) {
243
+ // The real writer is fail-open already. Keep that invariant even for an
244
+ // injected writer so a filesystem or test-double failure cannot replace
245
+ // the checkout result after a charge may have completed.
246
+ report = { written: false, reason: err instanceof Error ? err.message : String(err) };
247
+ }
248
+ const event = {
249
+ event: 'checkout_receipt_write',
250
+ status: report.written ? 'written' : 'failed',
251
+ mode,
252
+ checkoutOutcome: receipt.outcome,
253
+ merchantHost: receipt.merchant.host,
254
+ observationId: receipt.observationId ?? receipt.receiptId ?? createObservationId(),
255
+ failureCode: receipt.capability?.failureCode ?? null,
256
+ errorCode: report.written ? null : boundedReceiptWriteErrorCode(report.reason),
257
+ panRedactions: report.written ? report.panRedactions : null,
258
+ };
259
+ try {
260
+ const observerResult = deps.onReceiptWrite?.(event);
261
+ if (observerResult)
262
+ void Promise.resolve(observerResult).catch(() => undefined);
263
+ }
264
+ catch {
265
+ // Observability is non-authoritative and must not affect payment state.
266
+ }
267
+ return { report, event };
268
+ }
269
+ const cardDrawVerdict = deps.cardDrawVerdict ?? null;
270
+ const cardMandateRegister = deps.cardMandateRegister ?? null;
39
271
  async function closeSession(reviewId) {
40
272
  const session = sessions.get(reviewId);
41
273
  if (!session)
@@ -53,7 +285,288 @@ export function createCliCheckoutEngine(deps = {}) {
53
285
  transactionCurrencyCode: input.currency,
54
286
  };
55
287
  }
288
+ /**
289
+ * Restate the facts at the ceiling the SERVER approved, when it lowered the
290
+ * one that was requested. Nothing has been spent or reserved on a mandate this
291
+ * new, so its remaining headroom IS its ceiling — see `createCardMandate`,
292
+ * which records `spentMinor: 0` with no reservations.
293
+ *
294
+ * Only ever lowers, mirroring `applyApprovedCeiling`: the server clamps
295
+ * downward, so a higher number means an unexpected response and is ignored
296
+ * rather than reported as headroom no human approved.
297
+ */
298
+ function approvedCeilingFacts(facts, approvedCeilingMinor) {
299
+ if (approvedCeilingMinor === undefined || approvedCeilingMinor >= facts.ceilingMinor)
300
+ return {};
301
+ return { ceilingMinor: approvedCeilingMinor, remainingMinor: approvedCeilingMinor };
302
+ }
303
+ // Seed the one server-authoritative cumulative store keyed by the VGS intent
304
+ // ID (#5942). On failure the local record is marked register-failed so
305
+ // findCovering() SKIPS it — the mandate exists but is never drawn tap-free —
306
+ // and the caller reports the failure honestly. Shared by mandate-start and
307
+ // pickup-claim; both refuse before their ceremony/claim when no capability
308
+ // can register, so registerCap is always present here.
309
+ async function registerMandateOrDisable(args) {
310
+ if (!cardMandateRegister)
311
+ return { registerFailed: true, registerFailureReason: 'no_seam' };
312
+ const reg = await cardMandateRegister
313
+ .register({
314
+ authBaseUrl: args.registerCap.authBaseUrl,
315
+ agentKey: args.registerCap.agentKey,
316
+ ...(args.registerCap.runtimeCertificate
317
+ ? { runtimeCertificate: args.registerCap.runtimeCertificate }
318
+ : {}),
319
+ mandateId: args.mandateId,
320
+ mintToken: args.mintToken,
321
+ ceiling: args.ceiling,
322
+ currency: args.currency,
323
+ })
324
+ .catch((err) => ({
325
+ ok: false,
326
+ reason: err instanceof Error ? err.message : String(err),
327
+ }));
328
+ if (reg.ok) {
329
+ // ONE SPENDING LIMIT: auth just clamped the requested ceiling to the
330
+ // owner's live grant cap and told us what it committed. Adopt it, so the
331
+ // local record — which findCovering() selects on and `mandate list`
332
+ // prints — states the budget the owner actually approved. Best-effort:
333
+ // the mandate is registered and drawable either way, and auth's verdict
334
+ // remains the enforcing cap, so a failed local write must not abort the
335
+ // ceremony. It leaves the record overstating headroom, which is exactly
336
+ // the pre-existing behaviour.
337
+ //
338
+ // If that write fails the returned facts still carry the approved figure —
339
+ // telling the human the truth beats echoing a ceiling their grant refused,
340
+ // and the ledger is left exactly as overstated as it was before this
341
+ // existed. But the two then disagree, so say so out loud rather than let
342
+ // `mandate list` quietly contradict what `mandate start` just printed.
343
+ // Same posture as the mark-failed escalation below.
344
+ if (reg.approvedCeilingMinor !== undefined) {
345
+ const applied = await ledger
346
+ .applyApprovedCeiling(args.mandateId, reg.approvedCeilingMinor)
347
+ .then(() => true)
348
+ .catch(() => false);
349
+ if (!applied) {
350
+ // Rendered through minorToDecimal, never raw /100 — and only when the
351
+ // value is a sane integer, because THIS branch is also where an
352
+ // unusable value lands (applyApprovedCeiling rejects it). A warning
353
+ // must not throw on its way out. The currency is omitted deliberately:
354
+ // both mandate paths refuse anything but USD long before register, so
355
+ // it is known, and passing it would let a non-2-decimal code throw here.
356
+ const approved = Number.isSafeInteger(reg.approvedCeilingMinor) && reg.approvedCeilingMinor > 0
357
+ ? ` (${args.currency} ${minorToDecimal(reg.approvedCeilingMinor)})`
358
+ : '';
359
+ process.stderr.write(`warning: your owner's approved limit for this budget${approved} could NOT be saved ` +
360
+ `locally — 'mandate list' will overstate the remaining balance until you re-run ` +
361
+ `'mandate start'. Spending is still capped at the approved limit; a draw over it ` +
362
+ `is refused. mandateId=${args.mandateId}\n`);
363
+ }
364
+ }
365
+ return {
366
+ registerFailed: false,
367
+ ...(reg.approvedCeilingMinor !== undefined
368
+ ? { approvedCeilingMinor: reg.approvedCeilingMinor }
369
+ : {}),
370
+ };
371
+ }
372
+ // Register failed: the server `card_mandate_spend` row was never created, so
373
+ // a delegated draw against this mandate would 404 `no_mandate`. Mark it
374
+ // register-failed so findCovering() SKIPS it rather than silently selecting
375
+ // a mandate that can't be drawn. A v4 grant then refuses until a usable
376
+ // mandate exists; only a legacy credential-file runtime can still use the
377
+ // old per-purchase approval. Marking is best-effort too.
378
+ const marked = await ledger
379
+ .markRegisterFailed(args.mandateId, now())
380
+ .then(() => true)
381
+ .catch(() => false);
382
+ process.stderr.write(marked
383
+ ? `warning: card-mandate register failed (${reg.reason ?? 'unknown'}) — this mandate ` +
384
+ `will NOT be used for draws. A v4 card grant cannot spend until a usable mandate ` +
385
+ `is registered. Re-run 'mandate start' to try again.\n`
386
+ : // Escalate: the mark write ALSO failed, so the mandate is persisted but
387
+ // NOT disabled — findCovering could still select an undrawable mandate.
388
+ // Tell the owner loudly not to rely on it and how to recover.
389
+ `warning: card-mandate register failed (${reg.reason ?? 'unknown'}) AND the mandate ` +
390
+ `could NOT be disabled locally — do not rely on it. Run 'mandate list' and re-run ` +
391
+ `'mandate start'. mandateId=${args.mandateId}\n`);
392
+ return {
393
+ registerFailed: true,
394
+ ...(reg.reason !== undefined ? { registerFailureReason: reg.reason } : {}),
395
+ };
396
+ }
56
397
  return {
398
+ // BUDGET step: one passkey approves a CEILING; a VGS intent is minted with
399
+ // that ceiling as its decline threshold and the owner-only ledger records
400
+ // the cumulative budget. No browser checkout is prepared — this is purely
401
+ // the passkey ceremony + intent, so later pay() draws need no fresh tap.
402
+ async startCardMandate(input) {
403
+ const ceilingMinor = decimalToMinor(input.ceiling);
404
+ if (ceilingMinor === null || ceilingMinor <= 0) {
405
+ throw new Error(`invalid mandate ceiling ${JSON.stringify(input.ceiling)}`);
406
+ }
407
+ if (input.currency.toUpperCase() !== 'USD') {
408
+ throw new Error('card spend budgets currently support USD only');
409
+ }
410
+ if (input.perTransaction !== undefined) {
411
+ const perTxMinor = decimalToMinor(input.perTransaction);
412
+ if (perTxMinor === null || perTxMinor <= 0 || perTxMinor > ceilingMinor) {
413
+ throw new Error(`invalid mandate perTransaction ${JSON.stringify(input.perTransaction)} — ` +
414
+ 'must be a positive amount at or under the ceiling');
415
+ }
416
+ }
417
+ // A budget token can bootstrap one VGS intent and its register handshake,
418
+ // but it is never payable draw authority. Refuse before the passkey
419
+ // ceremony unless this runtime can both prove the separately provisioned
420
+ // card capability and register the resulting intent server-side.
421
+ const registerCap = cardMandateRegister?.loadCapability(input.agentRef) ?? null;
422
+ if (!cardMandateRegister || !registerCap) {
423
+ throw new Error('startCardMandate requires separately provisioned card authority in this runtime; ' +
424
+ 'identity pairing alone does not grant a card mandate');
425
+ }
426
+ // There is one budget product: eligible retail merchants under the
427
+ // provider's required Retail/5999 network category, with total,
428
+ // per-purchase, count, and time bounds stated on the approval page. The
429
+ // sentinel is provider metadata, never a user-entered merchant route.
430
+ const merchant = {
431
+ name: 'retail spend budget',
432
+ url: 'https://retail-budget.visa/budget',
433
+ countryCode: 'US',
434
+ };
435
+ // Legacy credential file OR the activated card:vic grant's token — see
436
+ // resolveCardInstrument. A v2-paired runtime only ever has the latter.
437
+ const credential = await resolveCardInstrument(input);
438
+ // The passkey ceremony is scoped to the CEILING + merchant (not one
439
+ // charge) — that scope is the unproven part of the spike.
440
+ const ceilingTarget = {
441
+ merchantName: merchant.name,
442
+ merchantUrl: merchant.url,
443
+ merchantCountryCode: merchant.countryCode,
444
+ transactionAmount: input.ceiling,
445
+ transactionCurrencyCode: input.currency,
446
+ };
447
+ // BUDGET mode: the ceiling target's amount IS the approved ceiling, so the
448
+ // server mints a budget mint token bound to that ceiling — later draws pull
449
+ // sub-ceiling amounts against it tap-free.
450
+ const assurance = await runHostedApproval({
451
+ baseUrl: input.approvalBaseUrl,
452
+ tokenId: credential.tokenId,
453
+ target: ceilingTarget,
454
+ consumerEmail: input.contact.email,
455
+ budget: true,
456
+ agentJkt: registerCap.agentJkt,
457
+ onApprovalUrl: input.onApprovalUrl ?? deps.onApprovalUrl,
458
+ maxDraws: DEFAULT_MANDATE_MAX_DRAWS,
459
+ ...(input.perTransaction !== undefined ? { perTransaction: input.perTransaction } : {}),
460
+ ...(input.intent !== undefined ? { intent: input.intent } : {}),
461
+ });
462
+ const mintToken = assurance.mintToken;
463
+ if (!mintToken) {
464
+ throw new Error('the approval server issued no mint token — server-side minting requires the ' +
465
+ 'verify-web deployment to run real/turnkey auth (not the dev stub). Retry once it does.');
466
+ }
467
+ if (!Number.isSafeInteger(assurance.validUntil) ||
468
+ assurance.validUntil <= Math.floor(now().getTime() / 1000)) {
469
+ throw new Error('the approval server issued no valid budget expiry');
470
+ }
471
+ const expiresAt = new Date(assurance.validUntil * 1000).toISOString();
472
+ const facts = await createCardMandate({
473
+ agentJkt: registerCap.agentJkt,
474
+ tokenId: credential.tokenId,
475
+ assuranceData: assurance.assuranceData,
476
+ ceilingMinor,
477
+ merchant,
478
+ currencyCode: input.currency,
479
+ expiresAt,
480
+ maxDraws: DEFAULT_MANDATE_MAX_DRAWS,
481
+ crossMerchant: true,
482
+ }, {
483
+ createIntent: (i) => serverCreateIntent(input.approvalBaseUrl, mintToken, i),
484
+ ledger,
485
+ approvalBaseUrl: input.approvalBaseUrl,
486
+ now,
487
+ });
488
+ // Seed the one server-authoritative cumulative store keyed by the VGS
489
+ // intent ID. A later draw requires its PoP verdict; the budget token never
490
+ // falls back as payable authority.
491
+ const registered = await registerMandateOrDisable({
492
+ registerCap,
493
+ mandateId: facts.mandateId,
494
+ mintToken,
495
+ ceiling: input.ceiling,
496
+ currency: input.currency,
497
+ });
498
+ return {
499
+ ...facts,
500
+ ...approvedCeilingFacts(facts, registered.approvedCeilingMinor),
501
+ merchantHost: new URL(merchant.url).hostname,
502
+ registerFailed: registered.registerFailed,
503
+ ...(registered.registerFailureReason !== undefined
504
+ ? { registerFailureReason: registered.registerFailureReason }
505
+ : {}),
506
+ };
507
+ },
508
+ // PICKUP leg: the owner already approved the ceiling in the account panel
509
+ // and handed this runtime a single-use pickup code. Claim it, verify it was
510
+ // minted for exactly this runtime's request key + card token, then run the
511
+ // same intent → register → ledger sequence as startCardMandate. No approval
512
+ // page, no passkey, no contact profile — the human side already happened.
513
+ async claimCardMandate(input) {
514
+ const registerCap = cardMandateRegister?.loadCapability(input.agentRef) ?? null;
515
+ if (!cardMandateRegister || !registerCap) {
516
+ throw new Error('claimCardMandate requires separately provisioned card authority in this runtime; ' +
517
+ 'identity pairing alone does not grant a card mandate');
518
+ }
519
+ const credential = await resolveCardInstrument(input);
520
+ const claim = await claimMandatePickup({
521
+ baseUrl: input.approvalBaseUrl,
522
+ pickupCode: input.pickupCode,
523
+ agentJkt: registerCap.agentJkt,
524
+ ...(input.expectedHandoffId ? { expectedHandoffId: input.expectedHandoffId } : {}),
525
+ tokenId: credential.tokenId,
526
+ });
527
+ const ceilingMinor = decimalToMinor(claim.ceiling);
528
+ if (ceilingMinor === null || ceilingMinor <= 0) {
529
+ throw new Error(`the handoff carried an invalid ceiling ${JSON.stringify(claim.ceiling)}`);
530
+ }
531
+ // Same single-product bound as mandate-start (the panel initiate route
532
+ // enforces it too; a divergent store entry must not widen it here).
533
+ if (claim.currency.toUpperCase() !== 'USD') {
534
+ throw new Error('card spend budgets currently support USD only');
535
+ }
536
+ const expiresAt = new Date(claim.validUntil * 1000).toISOString();
537
+ const facts = await createCardMandate({
538
+ agentJkt: registerCap.agentJkt,
539
+ tokenId: credential.tokenId,
540
+ assuranceData: claim.assuranceData,
541
+ ceilingMinor,
542
+ merchant: claim.merchant,
543
+ currencyCode: claim.currency,
544
+ expiresAt,
545
+ maxDraws: claim.maxDraws,
546
+ crossMerchant: true,
547
+ }, {
548
+ createIntent: (i) => serverCreateIntent(input.approvalBaseUrl, claim.mintToken, i),
549
+ ledger,
550
+ approvalBaseUrl: input.approvalBaseUrl,
551
+ now,
552
+ });
553
+ const registered = await registerMandateOrDisable({
554
+ registerCap,
555
+ mandateId: facts.mandateId,
556
+ mintToken: claim.mintToken,
557
+ ceiling: claim.ceiling,
558
+ currency: claim.currency,
559
+ });
560
+ return {
561
+ ...facts,
562
+ ...approvedCeilingFacts(facts, registered.approvedCeilingMinor),
563
+ merchantHost: new URL(claim.merchant.url).hostname,
564
+ registerFailed: registered.registerFailed,
565
+ ...(registered.registerFailureReason !== undefined
566
+ ? { registerFailureReason: registered.registerFailureReason }
567
+ : {}),
568
+ };
569
+ },
57
570
  async review(input) {
58
571
  const amountMinor = decimalToMinor(input.amount);
59
572
  if (amountMinor === null)
@@ -63,6 +576,7 @@ export function createCliCheckoutEngine(deps = {}) {
63
576
  try {
64
577
  const prep = await prepareCheckout({
65
578
  url: input.url,
579
+ checkoutRoute: input.checkoutRoute,
66
580
  mandate: {
67
581
  maxAmountMinor: amountMinor,
68
582
  currency: input.currency,
@@ -72,22 +586,61 @@ export function createCliCheckoutEngine(deps = {}) {
72
586
  amountMinor,
73
587
  currency: input.currency,
74
588
  browser,
589
+ contact: input.contact,
590
+ ...(input.trustedMerchantIdentity
591
+ ? { trustedMerchantIdentity: input.trustedMerchantIdentity }
592
+ : {}),
75
593
  }, store);
76
594
  if (prep.status !== 'ready') {
77
- await browser.close();
78
- throw new Error(`review refused: ${prep.result.outcome} ${prep.result.detail ?? ''}`);
595
+ // A terminal review is still a capability observation. Persist the
596
+ // same compact, owner-only artifact as a pay attempt so the local
597
+ // ledger records unsupported merchant surfaces and the safe card
598
+ // display identity instead of retaining successes only.
599
+ const observationId = createObservationId();
600
+ const receiptWrite = await writeObservedReceipt('dry-run', buildReceipt({
601
+ mode: 'dry-run',
602
+ reviewId: null,
603
+ observationId,
604
+ merchant: {
605
+ name: input.merchantName ?? host,
606
+ host,
607
+ url: input.url,
608
+ },
609
+ transaction: {
610
+ amount: input.amount,
611
+ amountMinor,
612
+ currency: input.currency,
613
+ },
614
+ result: prep.result,
615
+ vicConfirmation: null,
616
+ agentName: input.agentName,
617
+ cardLast4: input.cardLast4,
618
+ recordedAt: now(),
619
+ }));
620
+ throw new CheckoutReviewRefusedError(prep.result, receiptWrite.event);
79
621
  }
80
622
  const r = prep.checkout.review;
81
623
  // Expire the companion session on the SAME schedule as the store entry
82
624
  // (unref'd so a pending timer never keeps the process alive).
83
625
  const cleanupTimer = setTimeout(() => void closeSession(r.id), ttlMs);
84
626
  cleanupTimer.unref?.();
627
+ const target = buildTarget(input);
628
+ if (r.merchantOrigin) {
629
+ // The credential and mandate bind to the exact origin the browser
630
+ // actually reviewed, not the Shopify service continuation that led
631
+ // there. Keep the latter separately for review/pay replay binding.
632
+ target.merchantUrl = r.merchantOrigin;
633
+ target.merchantName = input.merchantName ?? r.merchantHost;
634
+ }
85
635
  sessions.set(r.id, {
86
636
  browser,
87
- target: buildTarget(input),
637
+ requestUrl: new URL(input.url).toString(),
638
+ checkoutRoute: input.checkoutRoute,
639
+ target,
88
640
  amountMinor,
89
641
  currency: input.currency,
90
642
  contact: input.contact,
643
+ ...(input.agentJkt ? { agentJkt: input.agentJkt } : {}),
91
644
  cleanupTimer,
92
645
  });
93
646
  return {
@@ -104,8 +657,43 @@ export function createCliCheckoutEngine(deps = {}) {
104
657
  throw err;
105
658
  }
106
659
  },
660
+ /**
661
+ * Give up a prepared review without paying it (#7100).
662
+ *
663
+ * The retained browser is what lets a same-process MCP `review` → `pay`
664
+ * draw against the checkout it already inspected. A TERMINAL review-only
665
+ * run has no such second call — that process tells the operator to re-RUN
666
+ * with `--submit`, and the new process cannot reach this one's in-memory
667
+ * session. So the browser sat open for the full TTL, and because a live
668
+ * browser connection keeps the event loop alive, a command that had already
669
+ * succeeded looked hung until Ctrl-C.
670
+ *
671
+ * Idempotent and non-throwing: an unknown or already-released id is a
672
+ * no-op, so it is safe on an error path that may not have prepared anything
673
+ * and safe to call twice.
674
+ */
675
+ async releaseReview(reviewId) {
676
+ await closeSession(reviewId);
677
+ payAttempts.delete(reviewId);
678
+ },
107
679
  async pay(input) {
680
+ const noCredentialFacts = {
681
+ credentialIssued: false,
682
+ credentialDisclosed: false,
683
+ };
684
+ const fingerprint = payAttemptFingerprint(input);
685
+ const priorAttempt = payAttempts.get(input.reviewId);
686
+ if (priorAttempt) {
687
+ return priorAttempt.fingerprint === fingerprint
688
+ ? priorAttempt.promise
689
+ : failedPay(`review ${input.reviewId} is already executing with different payment facts — wait for that exact attempt and inspect its receipt`);
690
+ }
108
691
  const session = sessions.get(input.reviewId);
692
+ // One signal for the whole pay lifecycle. `cardTokenId` is populated only
693
+ // by the resolved v4 card-grant authority; legacy credential-file calls
694
+ // omit it. Keeping the classification here prevents copy and fallback
695
+ // behavior from drifting onto different grant detectors.
696
+ const isV4CardGrant = typeof input.cardTokenId === 'string' && input.cardTokenId.trim() !== '';
109
697
  if (!session) {
110
698
  return {
111
699
  outcome: 'failed',
@@ -113,6 +701,85 @@ export function createCliCheckoutEngine(deps = {}) {
113
701
  receiptPath: null,
114
702
  detail: `no prepared review ${input.reviewId} — call review first (a review does not survive a restart)`,
115
703
  vicConfirmation: null,
704
+ source: null,
705
+ remainingMinor: null,
706
+ ...noCredentialFacts,
707
+ };
708
+ }
709
+ // The reviewId selects the prepared browser session, but the pay call also
710
+ // repeats the target facts. Refuse if any repeated fact disagrees so the
711
+ // caller cannot submit one reviewed checkout while labeling the result or
712
+ // telemetry as another. Never echo the full URLs: payment links can carry
713
+ // claimable secrets in their path/query.
714
+ let payUrl;
715
+ let reviewedUrl;
716
+ try {
717
+ payUrl = new URL(input.url).toString();
718
+ reviewedUrl = session.requestUrl;
719
+ }
720
+ catch {
721
+ await closeSession(input.reviewId);
722
+ return {
723
+ outcome: 'failed',
724
+ confirmationRef: null,
725
+ receiptPath: null,
726
+ detail: 'pay merchant URL is invalid or does not match the reviewed checkout — start a fresh review',
727
+ vicConfirmation: null,
728
+ source: null,
729
+ remainingMinor: null,
730
+ ...noCredentialFacts,
731
+ };
732
+ }
733
+ if (payUrl !== reviewedUrl) {
734
+ await closeSession(input.reviewId);
735
+ return {
736
+ outcome: 'failed',
737
+ confirmationRef: null,
738
+ receiptPath: null,
739
+ detail: 'pay merchant URL does not match the reviewed checkout — start a fresh review',
740
+ vicConfirmation: null,
741
+ source: null,
742
+ remainingMinor: null,
743
+ ...noCredentialFacts,
744
+ };
745
+ }
746
+ if (input.currency.toUpperCase() !== session.currency.toUpperCase()) {
747
+ await closeSession(input.reviewId);
748
+ return {
749
+ outcome: 'failed',
750
+ confirmationRef: null,
751
+ receiptPath: null,
752
+ detail: `pay currency ${JSON.stringify(input.currency)} does not match the reviewed currency (${session.currency}) — start a fresh review`,
753
+ vicConfirmation: null,
754
+ source: null,
755
+ remainingMinor: null,
756
+ ...noCredentialFacts,
757
+ };
758
+ }
759
+ if (input.agentJkt !== session.agentJkt) {
760
+ await closeSession(input.reviewId);
761
+ return {
762
+ outcome: 'failed',
763
+ confirmationRef: null,
764
+ receiptPath: null,
765
+ detail: 'pay agent authority does not match the reviewed request key — start a fresh review',
766
+ vicConfirmation: null,
767
+ source: null,
768
+ remainingMinor: null,
769
+ ...noCredentialFacts,
770
+ };
771
+ }
772
+ if (input.checkoutRoute !== session.checkoutRoute) {
773
+ await closeSession(input.reviewId);
774
+ return {
775
+ outcome: 'failed',
776
+ confirmationRef: null,
777
+ receiptPath: null,
778
+ detail: 'pay checkout route does not match the reviewed guest-card route — start a fresh review',
779
+ vicConfirmation: null,
780
+ source: null,
781
+ remainingMinor: null,
782
+ ...noCredentialFacts,
116
783
  };
117
784
  }
118
785
  // Amount-bind the confirmation: the pay-call amount must match the
@@ -128,6 +795,9 @@ export function createCliCheckoutEngine(deps = {}) {
128
795
  receiptPath: null,
129
796
  detail: `pay amount ${JSON.stringify(input.amount)} does not match the reviewed amount (${session.amountMinor} minor units) — start a fresh review`,
130
797
  vicConfirmation: null,
798
+ source: null,
799
+ remainingMinor: null,
800
+ ...noCredentialFacts,
131
801
  };
132
802
  }
133
803
  // Reject an expired prepared checkout BEFORE running the hosted passkey
@@ -141,72 +811,267 @@ export function createCliCheckoutEngine(deps = {}) {
141
811
  receiptPath: null,
142
812
  detail: `prepared review ${input.reviewId} expired — start a fresh review`,
143
813
  vicConfirmation: null,
814
+ source: null,
815
+ remainingMinor: null,
816
+ ...noCredentialFacts,
144
817
  };
145
818
  }
819
+ let resolveAttempt;
820
+ let rejectAttempt;
821
+ const sharedResult = new Promise((resolve, reject) => {
822
+ resolveAttempt = resolve;
823
+ rejectAttempt = reject;
824
+ });
825
+ // The first caller still receives the direct execution result below; this
826
+ // retained promise exists for overlapping and bounded late duplicates.
827
+ // Mark its rejection handled even when there is no duplicate consumer.
828
+ void sharedResult.catch(() => undefined);
829
+ payAttempts.set(input.reviewId, { fingerprint, promise: sharedResult });
830
+ let completedAttempt;
831
+ const finishAttempt = (result) => {
832
+ completedAttempt = result;
833
+ resolveAttempt(result);
834
+ return result;
835
+ };
146
836
  clearTimeout(session.cleanupTimer);
147
837
  try {
148
- const credential = JSON.parse(await readFile(input.credentialPath, 'utf8'));
149
- const assurance = await runHostedApproval({
150
- baseUrl: input.approvalBaseUrl,
151
- tokenId: credential.tokenId,
152
- target: session.target,
153
- consumerEmail: session.contact.email,
838
+ // NO instrument read here. A tap-free mandate draw spends `covering
839
+ // .tokenId` (frozen into the mandate at start) and needs neither the
840
+ // legacy credential file nor a grant token, so a grant-only device with
841
+ // an as-yet-unrefreshed token can still draw on a mandate it already
842
+ // holds.
843
+ const host = new URL(session.target.merchantUrl).hostname;
844
+ // Does an ACTIVE card mandate already cover this exact purchase? If so,
845
+ // draw against it TAP-FREE (no hosted passkey). Else refuse with the
846
+ // mandate remedy (#7348). Mandates no longer persist the bootstrap
847
+ // token: it is consumed by intent creation + register and has no draw
848
+ // power.
849
+ const covering = await ledger.findCovering({
850
+ merchantHost: host,
851
+ currencyCode: session.currency,
852
+ amountMinor: session.amountMinor,
853
+ agentJkt: session.agentJkt,
854
+ now: now(),
154
855
  });
155
- // Server-side mint (Phase 1): the approval claim releases a scoped mint
156
- // token; the credential is minted by the verify-web deployment (which
157
- // holds the VGS secret), never on this machine. No token means the
158
- // deployment ran the dev-auth stub refuse loudly rather than reach for
159
- // a client-held secret (there is none anymore).
160
- const approvalBase = input.approvalBaseUrl;
161
- const mintToken = assurance.mintToken;
162
- if (!mintToken) {
163
- return {
856
+ let source;
857
+ let confirmBase;
858
+ // Mandate draws set this only after the local reserve succeeds and auth
859
+ // returns the exact per-draw verdict used to mint the credential.
860
+ let confirmationAuthority = null;
861
+ let drawnRemaining = null;
862
+ let instrument;
863
+ if (covering) {
864
+ // --- Tap-free mandate draw ------------------------------------------
865
+ source = 'mandate';
866
+ confirmBase = covering.approvalBaseUrl;
867
+ const mandateId = covering.mandateId;
868
+ // A mandate cryptogram is authorized only by a PoP-signed verdict.
869
+ // The budget mint token is bootstrap-only and cannot bypass the
870
+ // server reserve/commit ledger when local draw authority is absent.
871
+ //
872
+ // #5928 CRITICAL-2: the CLI does NOT settle the reservation. verify-web
873
+ // (which knows whether the cryptogram was payable) commits it on a
874
+ // payable mint and releases it on a decline, server-authoritatively, so
875
+ // the drawer can never release after a payable mint to dodge the ceiling.
876
+ const verdictSeam = cardDrawVerdict;
877
+ const capability = verdictSeam?.loadCapability(covering.agentJkt) ?? null;
878
+ if (!capability || !verdictSeam) {
879
+ return finishAttempt({
880
+ outcome: 'failed',
881
+ confirmationRef: null,
882
+ receiptPath: null,
883
+ detail: 'this mandate cannot draw because its delegated card authority is unavailable; ' +
884
+ 're-pair this runtime to restore the binding, or start a new mandate for this agent',
885
+ vicConfirmation: null,
886
+ source,
887
+ remainingMinor: null,
888
+ ...noCredentialFacts,
889
+ });
890
+ }
891
+ if (covering.agentJkt && capability.agentJkt !== covering.agentJkt) {
892
+ return finishAttempt({
893
+ outcome: 'failed',
894
+ confirmationRef: null,
895
+ receiptPath: null,
896
+ detail: 'this budget belongs to a different request key than the selected card capability; ' +
897
+ 'restore that exact runtime key, or start a new mandate from the current runtime',
898
+ vicConfirmation: null,
899
+ source,
900
+ remainingMinor: null,
901
+ ...noCredentialFacts,
902
+ });
903
+ }
904
+ // VgsLiveInstrument mints against an EXISTING intent (the mandate) with
905
+ // no fresh assurance — exactly the draw semantics. The fetchCredential
906
+ // seam routes through drawFromMandate so the ledger accounting (reserve
907
+ // -> commit on payable, release on reject) wraps the cryptogram pull.
908
+ const reference = {
909
+ tokenId: covering.tokenId,
910
+ intentId: mandateId,
911
+ merchantName: session.target.merchantName,
912
+ merchantUrl: session.target.merchantUrl,
913
+ merchantCountryCode: session.target.merchantCountryCode,
914
+ transactionAmount: session.target.transactionAmount,
915
+ transactionCurrencyCode: session.currency,
916
+ };
917
+ const fetchCredential = async ({ transaction }) => {
918
+ let draw;
919
+ try {
920
+ draw = await drawFromMandate({
921
+ mandateId,
922
+ amountMinor: session.amountMinor,
923
+ transaction: { ...transaction, transactionCurrencyCode: session.currency },
924
+ }, {
925
+ // Ordering matters: reserve the local ledger FIRST, then ask
926
+ // auth to reserve the server-authoritative budget immediately
927
+ // before the payable mint. A local reserve race/expiry/file
928
+ // failure therefore makes zero auth/verdict calls and cannot
929
+ // strand a server reservation until its sweep.
930
+ fetchCryptogram: async (i) => {
931
+ const { verdict } = await verdictSeam.fetchVerdict({
932
+ authBaseUrl: capability.authBaseUrl,
933
+ agentKey: capability.agentKey,
934
+ ...(capability.runtimeCertificate
935
+ ? { runtimeCertificate: capability.runtimeCertificate }
936
+ : {}),
937
+ mandateId,
938
+ // One draw per review; the reviewId is auth's idempotency key.
939
+ drawId: input.reviewId,
940
+ draw: {
941
+ tokenId: covering.tokenId,
942
+ amount: session.target.transactionAmount,
943
+ currency: session.currency,
944
+ merchantName: session.target.merchantName,
945
+ merchantUrl: session.target.merchantUrl,
946
+ merchantCountryCode: session.target.merchantCountryCode,
947
+ },
948
+ });
949
+ confirmationAuthority = verdict;
950
+ return fetchMandateCryptogram(confirmBase, verdict, i);
951
+ },
952
+ ledger,
953
+ now,
954
+ });
955
+ }
956
+ catch (err) {
957
+ // Disable the mandate ONLY for a post-reservation NETWORK decline
958
+ // (MandateDrawDeclinedError). That case leaves the mandate
959
+ // active+covering, so a naive retry would re-select it and fail
960
+ // identically — trapping the caller; marking it unhonored makes the
961
+ // next pay_merchant skip it and surface the no-covering-mandate refusal
962
+ // (#7348) instead of re-failing identically. We do
963
+ // NOT attempt an unsafe same-call browser fallback mid-submit.
964
+ //
965
+ // A PRE-network failure — reserve() failing closed on a concurrent
966
+ // over-budget race or expiry, or commit() throwing on file I/O —
967
+ // is NOT a network decline: the mandate is HEALTHY, so we must
968
+ // rethrow WITHOUT disabling it (michaelyang1 M1). drawFromMandate
969
+ // has already released any reservation, so the budget is intact.
970
+ // Only a DEFINITIVE (hard) decline disables the mandate. A TRANSIENT
971
+ // failure — a gateway 5xx / "not completed, try again" / network
972
+ // reset/timeout — must NOT permanently kill the budget: the mandate
973
+ // may be perfectly healthy (it can have committed a draw seconds
974
+ // earlier) and the rails may recover on retry. Over-disabling on a
975
+ // transient 502 threw away good budgets and forced a fresh passkey
976
+ // every time.
977
+ // Classify on the underlying gateway CAUSE, not the MandateDrawDeclinedError
978
+ // wrapper — the wrapper's own advisory text mentions "try again"/"network",
979
+ // which would otherwise self-classify every decline as transient.
980
+ if (err instanceof MandateDrawDeclinedError) {
981
+ const verdictFailure = classifyCardDrawVerdictFailure(err);
982
+ if (verdictFailure) {
983
+ // #7491: a GRANT-capacity refusal is pre-credential and says
984
+ // nothing about this mandate, so it must NOT disable it. The
985
+ // mandate is healthy and becomes drawable again the moment the
986
+ // owner supplies a grant with room; disabling it here threw
987
+ // away a just-approved budget and pointed the caller at a new
988
+ // mandate that would die on the same wall.
989
+ if (!verdictFailure.transient && !verdictFailure.grantCapacity) {
990
+ await ledger.markUnhonored(mandateId, now()).catch(() => { });
991
+ }
992
+ if (verdictFailure.grantCapacity) {
993
+ throw new Error(`this agent's card grant has no remaining capacity (${verdictFailure.reasons.join(', ') || 'grant exhausted'}) — nothing was charged and the mandate is still valid; ask the owner for a new or replenished card grant (visa agent grant-card) before retrying this checkout`, { cause: err });
994
+ }
995
+ throw new Error(verdictFailure.transient
996
+ ? `the card-mandate draw could not be authorized right now (${verdictFailure.reasons.join(', ') || 'temporary error'}) — retry shortly`
997
+ : `this card mandate can no longer be drawn (${verdictFailure.reasons.join(', ') || 'refused'}); it has been disabled — create and claim a new mandate before retrying this checkout`, { cause: err });
998
+ }
999
+ if (!isTransientDrawFailure(err.cause ?? err)) {
1000
+ await ledger.markUnhonored(mandateId, now());
1001
+ }
1002
+ }
1003
+ // #5928 CRITICAL-2: the server-side reservation is released by
1004
+ // verify-web (it saw the mint fail), not here — the CLI never settles.
1005
+ throw err;
1006
+ }
1007
+ drawnRemaining = draw.remainingMinor;
1008
+ // #5928 CRITICAL-2: the reservation is committed by verify-web on the
1009
+ // payable mint (server-authoritative); the CLI does not settle.
1010
+ return draw.payment;
1011
+ };
1012
+ instrument = new VgsLiveInstrument(reference, session.contact.fullName ?? '', fetchCredential);
1013
+ }
1014
+ else {
1015
+ // #7348 single-purchase retirement: card spend is mandate-only for
1016
+ // EVERY runtime. The legacy 1:1 single-purchase flow here minted a
1017
+ // payable credential outside the grant/mandate ledger — invisible to
1018
+ // spending controls. The server now refuses non-budget approvals at
1019
+ // registration and non-budget mint tokens at verification; this
1020
+ // client refusal exists to give the honest remedy up front instead
1021
+ // of a mid-flow server error.
1022
+ return finishAttempt({
164
1023
  outcome: 'failed',
165
1024
  confirmationRef: null,
166
1025
  receiptPath: null,
167
- detail: 'the approval server issued no mint token — server-side minting requires the ' +
168
- 'verify-web deployment to run real/turnkey auth (not the dev stub). Retry once it does.',
1026
+ detail: isV4CardGrant
1027
+ ? 'this v4 card grant has no active mandate covering the purchase; run ' +
1028
+ '`visa mandate start --ceiling <usd> --per-transaction <usd>` for the selected ' +
1029
+ 'agent, approve and claim the mandate, then retry this checkout. No payment ' +
1030
+ 'credential was requested and no charge was made.'
1031
+ : 'one-off card approvals are retired (#7348): card spending always runs through ' +
1032
+ 'an owner-approved mandate now. Attach card authority to this agent ' +
1033
+ '(`visa agent grant-card <agent-id> --ceiling <usd> --per-transaction <usd> --wait`), ' +
1034
+ 'then start and claim a mandate (`visa mandate start <usd> --per-transaction <usd>`), ' +
1035
+ 'and retry the checkout. No payment credential was requested and no charge was made.',
169
1036
  vicConfirmation: null,
170
- };
1037
+ source: null,
1038
+ remainingMinor: null,
1039
+ ...noCredentialFacts,
1040
+ });
171
1041
  }
172
- const instrument = new VgsAssuranceInstrument(credential, assurance, session.target, session.contact.fullName ?? '', async (mintInput) => {
173
- const { intentId, status } = await serverCreateIntent(approvalBase, mintToken, mintInput);
174
- try {
175
- const payment = await serverFetchCryptogram(approvalBase, mintToken, {
176
- tokenId: mintInput.tokenId,
177
- intentId,
178
- transaction: mintInput.transaction,
179
- });
180
- return { payment, intentId };
181
- }
182
- catch (err) {
183
- throw new Error(`${err.message} (intent status at creation: ${status ?? 'unknown'})`);
184
- }
185
- });
186
1042
  const mode = input.submit ? 'submit' : 'dry-run';
187
1043
  const result = await submitApprovedCheckout(input.reviewId, {
188
1044
  approval: { approved: true, reviewId: input.reviewId },
189
1045
  instrument,
190
1046
  contact: session.contact,
191
1047
  mode,
1048
+ ...(deps.resolveEmailOtp ? { resolveEmailOtp: deps.resolveEmailOtp } : {}),
192
1049
  }, store);
193
1050
  // Report the observed submit outcome to VIC for the consumed intent
194
1051
  // (APPROVED/DECLINED). Only definitive submit answers post. Mirrors
195
1052
  // run-live-fill.ts.
196
1053
  let vicConfirmation = null;
1054
+ let processorIntentId = null;
197
1055
  if (mode === 'submit') {
1056
+ const confirmationTarget = instrument.confirmationTarget();
1057
+ processorIntentId = confirmationTarget?.intentId ?? null;
198
1058
  vicConfirmation = await reportVicOutcome({
199
- target: instrument.confirmationTarget(),
1059
+ target: confirmationTarget,
200
1060
  outcome: result.outcome,
201
1061
  transaction: {
202
1062
  transactionAmount: session.target.transactionAmount,
203
1063
  transactionCurrencyCode: session.currency,
204
1064
  },
205
- post: (confInput) => serverPostConfirmation(approvalBase, mintToken, confInput),
1065
+ post: (confInput) => {
1066
+ if (!confirmationAuthority) {
1067
+ throw new Error('confirmation authority missing for the consumed VIC intent');
1068
+ }
1069
+ return postServerConfirmation(confirmBase, confirmationAuthority, confInput);
1070
+ },
206
1071
  });
207
1072
  }
208
1073
  let receiptPath = null;
209
- const report = await writeReceipt(RECEIPT_DIR, buildReceipt({
1074
+ const receiptWrite = await writeObservedReceipt(mode, buildReceipt({
210
1075
  mode,
211
1076
  reviewId: input.reviewId,
212
1077
  // Derive BOTH name and host from the reviewed session target (not
@@ -215,6 +1080,7 @@ export function createCliCheckoutEngine(deps = {}) {
215
1080
  merchant: {
216
1081
  name: session.target.merchantName,
217
1082
  host: new URL(session.target.merchantUrl).hostname,
1083
+ url: session.target.merchantUrl,
218
1084
  },
219
1085
  transaction: {
220
1086
  amount: session.target.transactionAmount,
@@ -223,19 +1089,47 @@ export function createCliCheckoutEngine(deps = {}) {
223
1089
  },
224
1090
  result,
225
1091
  vicConfirmation,
1092
+ agentName: input.agentName,
1093
+ cardLast4: input.cardLast4,
226
1094
  }));
227
- if (report.written)
228
- receiptPath = report.path;
229
- return {
1095
+ if (receiptWrite.report.written)
1096
+ receiptPath = receiptWrite.report.path;
1097
+ return finishAttempt({
230
1098
  outcome: result.outcome,
231
1099
  confirmationRef: result.confirmationRef ?? null,
232
1100
  receiptPath,
233
1101
  detail: result.detail ?? null,
234
1102
  vicConfirmation,
235
- };
1103
+ source,
1104
+ remainingMinor: drawnRemaining,
1105
+ processorIntentId,
1106
+ credentialIssued: result.credentialLifecycle !== 'not-requested',
1107
+ credentialDisclosed: result.credentialLifecycle === 'partially-exposed' ||
1108
+ result.credentialLifecycle === 'fully-filled',
1109
+ receiptWrite: receiptWrite.event,
1110
+ });
1111
+ }
1112
+ catch (error) {
1113
+ rejectAttempt(error);
1114
+ throw error;
236
1115
  }
237
1116
  finally {
238
1117
  await closeSession(input.reviewId);
1118
+ if (!completedAttempt ||
1119
+ completedAttempt.outcome === 'failed' ||
1120
+ completedAttempt.outcome === 'declined') {
1121
+ if (payAttempts.get(input.reviewId)?.promise === sharedResult) {
1122
+ payAttempts.delete(input.reviewId);
1123
+ }
1124
+ }
1125
+ else {
1126
+ const expiry = setTimeout(() => {
1127
+ if (payAttempts.get(input.reviewId)?.promise === sharedResult) {
1128
+ payAttempts.delete(input.reviewId);
1129
+ }
1130
+ }, ttlMs);
1131
+ expiry.unref?.();
1132
+ }
239
1133
  }
240
1134
  },
241
1135
  };