@visa/cli 4.1.0-rc.15 → 4.1.0-rc.151

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