@visa/cli 4.1.0-rc.20 → 4.1.0-rc.201

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