z-zero-mcp-server 1.12.4 → 1.12.6

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.
@@ -496,11 +496,22 @@ async function cancelTokenRemote(token) {
496
496
  });
497
497
  if (data?.error)
498
498
  return data;
499
+ // The refund is SENT only when the server names its transaction. With none, the card is
500
+ // closed but the money has not moved yet: held for a check (the issuer reported activity
501
+ // on the card, or a daily limit was reached) or waiting for a retry. Until 1.12.6 this
502
+ // function said "refunded on-chain" either way, and dropped the unused-card fee and rule
503
+ // the server sends — so cancel_payment_token never told the agent a fee had been kept.
504
+ const sent = typeof data?.tx_hash === "string" && data.tx_hash.length > 0;
499
505
  return {
500
506
  success: !!data,
501
507
  refunded_amount: data?.refunded_amount || 0,
502
- tx_hash: data?.tx_hash || null, // On-chain refund tx hash
503
- note: 'Stablecoin (USDC) refunded on-chain to your Base wallet.'
508
+ tx_hash: sent ? data.tx_hash : null,
509
+ refund_sent: sent,
510
+ ...(data?.unused_card_fee ? { unused_card_fee: data.unused_card_fee } : {}),
511
+ ...(data?.unused_card_policy ? { unused_card_policy: data.unused_card_policy } : {}),
512
+ note: sent
513
+ ? 'Stablecoin (USDC) refunded on-chain to your Base wallet.'
514
+ : 'The card is closed, but the refund has NOT been sent yet: it is held for a check or will be retried automatically. The money is not in the wallet yet.',
504
515
  };
505
516
  }
506
517
  // ──────────────────────────────────────────────────────────────────────────────
package/dist/index.js CHANGED
@@ -364,6 +364,11 @@ server.registerTool("request_payment_token", {
364
364
  .max(50)
365
365
  .optional()
366
366
  .describe("RECOMMENDED: the items you are buying, as the USER agreed to them. This becomes a signed intent bound to the card — proof of what was authorized."),
367
+ currency: zod_1.z
368
+ .string()
369
+ .regex(/^[A-Za-z]{3}$/, "3-letter currency code, e.g. 'JPY'")
370
+ .optional()
371
+ .describe("Only when the cart's unit prices are NOT in US dollars: the currency they are in (ISO 4217, e.g. 'JPY', 'EUR'). `amount` is always USD. Leave it out for a USD shop."),
367
372
  ship_to: zod_1.z
368
373
  .string()
369
374
  .optional()
@@ -394,7 +399,7 @@ server.registerTool("request_payment_token", {
394
399
  idempotentHint: false,
395
400
  openWorldHint: true,
396
401
  },
397
- }, async ({ card_alias, amount, merchant, merchant_country, cart, ship_to, criteria, deal, list_total }) => {
402
+ }, async ({ card_alias, amount, merchant, merchant_country, cart, ship_to, criteria, deal, list_total, currency }) => {
398
403
  // An ordinary purchase names its amount; a deal order names its items and the checkout
399
404
  // total and lets the server compute the amount. One or the other — refused here, before
400
405
  // anything is sent.
@@ -421,6 +426,9 @@ server.registerTool("request_payment_token", {
421
426
  : undefined,
422
427
  ship_to,
423
428
  criteria,
429
+ // The server reads unit prices as USD unless told otherwise (it refuses a card
430
+ // smaller than the cart it was shown). Sent only for a non-USD cart.
431
+ ...(currency && currency.toUpperCase() !== "USD" ? { currency: currency.toUpperCase() } : {}),
424
432
  }
425
433
  : undefined;
426
434
  const token = await issueTokenRemote(card_alias, isDeal ? undefined : amount, merchant, intentInput, {
@@ -1253,7 +1261,10 @@ server.registerTool("cancel_payment_token", {
1253
1261
  refunded_amount: result.refunded_amount,
1254
1262
  ...(result.unused_card_fee ? { unused_card_fee: result.unused_card_fee } : {}),
1255
1263
  reason,
1256
- message: `Token cancelled. $${result.refunded_amount} has been returned to the wallet.`
1264
+ refund_sent: result.refund_sent !== false,
1265
+ message: (result.refund_sent === false
1266
+ ? `Token cancelled. The $${result.refunded_amount} refund has NOT been sent yet — it is held for a check or will be retried automatically, and is not in the wallet yet. Tell the user; no action is needed from you.`
1267
+ : `Token cancelled. $${result.refunded_amount} has been returned to the wallet.`)
1257
1268
  + (result.unused_card_fee ? ` An unused-card fee of $${result.unused_card_fee} was kept — tell the user.` : "")
1258
1269
  + " You may request a new token with the correct amount.",
1259
1270
  ...(result.unused_card_policy ? { unused_card_policy: result.unused_card_policy } : {}),
@@ -1501,6 +1512,7 @@ server.registerTool("auto_pay_checkout", {
1501
1512
  description: "⚠️ MANDATORY: Read mcp://resources/sop first. One call for a PAYMENT page whose final total is already visible (digital goods / SaaS): issues a JIT card and completes the payment. " +
1502
1513
  "You MUST pass max_amount: the most, in US dollars, the owner agreed to pay for this — read the total on the page yourself, convert it to USD if the page is in another currency, and include tax/shipping. " +
1503
1514
  "The card is never larger than max_amount. On a USD page Z-Zero also reads the visible total and stops (no card) if it is above max_amount or cannot be read. " +
1515
+ "If Pay was pressed and no confirmation was seen, the status is UNCONFIRMED and the card is KEPT (an order may exist): the result hands you the token — verify, then cancel_payment_token if there is no order. Any other failure cancels the card for you. " +
1504
1516
  "Card only: it never sends crypto to an address found on a page. For physical goods (Shopify, Etsy), use get_merchant_hints + request_payment_token + execute_payment instead.",
1505
1517
  inputSchema: {
1506
1518
  checkout_url: zod_1.z
@@ -1636,15 +1648,26 @@ server.registerTool("auto_pay_checkout", {
1636
1648
  }
1637
1649
  // STEP 4: fill the form (reusing the same page).
1638
1650
  const fillResult = await (0, playwright_bridge_js_1.fillCheckoutForm)(checkout_url, cardData, page);
1639
- // Burn ONLY on a confirmed charge. Any other outcome releases the JIT token.
1651
+ // Three ways out, the same as execute_payment (until 1.12.6 this tool had two: paid, or
1652
+ // "cancel the card whatever happened" — independent review, 27/11/2026):
1653
+ // confirmed → record it, and say so if the server could not;
1654
+ // unconfirmed → Pay was pressed and nothing came back. An order MAY exist, so the
1655
+ // card is KEPT: closing it could fail a charge the shop takes a
1656
+ // moment later, and would file a card that was used as "unused".
1657
+ // The token goes back to the agent, who verifies and then cancels.
1658
+ // anything else (declined, no fields, blocked, …) → no order can exist: cancel now.
1640
1659
  let autoReceipt = null;
1660
+ let recorded = null;
1661
+ let released = null;
1662
+ const confirmed = fillResult.success && fillResult.status === 'confirmed';
1663
+ const keptForCheck = !confirmed && fillResult.status === 'unconfirmed';
1641
1664
  // Same rule as execute_payment: burning needs both the flag and the
1642
1665
  // observed status to say confirmed (backtest E07).
1643
- if (fillResult.success && fillResult.status === 'confirmed') {
1666
+ if (confirmed) {
1644
1667
  tokenSettled = true;
1645
- const burnOk = await burnTokenRemote(token.token, fillResult.receipt_id);
1646
- if (!burnOk)
1647
- console.error(`[WARN] Token burn failed for …${String(token.token).slice(-6)} — manual check needed`);
1668
+ recorded = await recordPaymentRemote(token.token, fillResult.receipt_id);
1669
+ if (!recorded.recorded)
1670
+ console.error(`[WARN] Payment of …${String(token.token).slice(-6)} was confirmed by the shop but not recorded by the server — manual check needed`);
1648
1671
  // Signed receipt (Primitive 3) — never blocks the confirmed result
1649
1672
  autoReceipt = await postReceiptRemote({
1650
1673
  token: token.token,
@@ -1655,9 +1678,14 @@ server.registerTool("auto_pay_checkout", {
1655
1678
  }).catch(() => null);
1656
1679
  }
1657
1680
  else {
1658
- // Release the freshly-issued JIT token so the funds don't sit locked on a non-payment.
1659
- await cancelTokenRemote(token.token).catch(() => { });
1660
- tokenSettled = true;
1681
+ if (keptForCheck) {
1682
+ tokenSettled = true; // deliberately NOT cancelled — see above
1683
+ }
1684
+ else {
1685
+ // Release the freshly-issued JIT token so the funds don't sit locked on a non-payment.
1686
+ released = await cancelTokenRemote(token.token).catch(() => null);
1687
+ tokenSettled = true;
1688
+ }
1661
1689
  // 📊 Auto-label the failed run (Primitive 2 corpus)
1662
1690
  const label = (0, failure_taxonomy_js_1.classifyBridgeResult)(fillResult.status, fillResult.message);
1663
1691
  if (label) {
@@ -1673,9 +1701,47 @@ server.registerTool("auto_pay_checkout", {
1673
1701
  });
1674
1702
  }
1675
1703
  }
1704
+ // What became of the card and its hold, in words that are true for each case.
1705
+ const releaseSaid = keptForCheck
1706
+ ? "The card was NOT cancelled: Pay was pressed, so an order may exist."
1707
+ : !released || released.error || !released.success
1708
+ ? "The card could not be cancelled automatically — call cancel_payment_token with the token below."
1709
+ : released.refund_sent === false
1710
+ ? "The card was cancelled; its refund has NOT been sent yet (held for a check, or retried automatically) and is not in the wallet yet." + (released.unused_card_fee ? ` An unused-card fee of $${released.unused_card_fee} was kept — tell the user.` : "")
1711
+ : `The card was cancelled and $${released.refunded_amount} returned to the wallet.` + (released.unused_card_fee ? ` An unused-card fee of $${released.unused_card_fee} was kept — tell the user.` : "");
1712
+ const cancelFailed = !confirmed && !keptForCheck && (!released || released.error || !released.success);
1713
+ // The visible USD total is what the shop charges; a card issued above it leaves a surplus.
1714
+ const charged = detected && !nonUsd ? detected.amount : undefined;
1715
+ const surplus = confirmed && charged !== undefined ? Math.max(0, Math.round((issueAmount - charged) * 100) / 100) : 0;
1676
1716
  return reply({
1677
1717
  route: "CARD",
1678
- status: fillResult.success ? "SUCCESS" : (fillResult.status || "FILL_FAILED").toUpperCase(),
1718
+ status: confirmed ? "SUCCESS" : (fillResult.status || "FILL_FAILED").toUpperCase(),
1719
+ ...(confirmed ? { token_status: recorded?.recorded ? "BURNED" : "PAID_BUT_NOT_RECORDED" } : {}),
1720
+ ...(keptForCheck ? {
1721
+ token_status: "ACTIVE",
1722
+ token: token.token,
1723
+ next: "Do NOT pay again. Check whether the order exists (the shop's confirmation page, the order email, or the owner). If it does NOT, call cancel_payment_token with this token to get the hold back; if it does, tell the owner and leave the card alone.",
1724
+ } : {}),
1725
+ ...(cancelFailed ? { token_status: "ACTIVE", token: token.token } : {}),
1726
+ ...(!confirmed && !keptForCheck && !cancelFailed ? { token_status: "CANCELLED", refund_sent: released?.refund_sent !== false } : {}),
1727
+ ...(released?.unused_card_fee ? { unused_card_fee: released.unused_card_fee } : {}),
1728
+ ...(released?.unused_card_policy ? { unused_card_policy: released.unused_card_policy } : {}),
1729
+ ...(confirmed && recorded && !recorded.recorded ? {
1730
+ not_recorded: {
1731
+ what: "The shop CONFIRMED this payment and the card has been charged, but Z-ZERO's server did not record it after " + recorded.attempts + " attempts.",
1732
+ server_said: [recorded.status ?? "no answer", recorded.error ?? ""].join(" ").trim(),
1733
+ do: "Tell your owner now, with the order id and this message. The order at the shop is real.",
1734
+ do_not: "Do NOT pay again, and do NOT cancel anything for it: the money is with the shop, not on hold.",
1735
+ },
1736
+ } : {}),
1737
+ ...(surplus > 0 ? {
1738
+ surplus: {
1739
+ card_amount: issueAmount,
1740
+ charged,
1741
+ coming_back: surplus,
1742
+ when: "Not yet. The unused part of the hold returns to the wallet after the shop settles the charge with the card issuer — usually 1 to 3 days. Nothing to do; do not cancel or re-request anything for it.",
1743
+ },
1744
+ } : {}),
1679
1745
  max_amount,
1680
1746
  detected_price: detected ? detected.amount : null,
1681
1747
  detected_currency: detected ? (nonUsd ? "NON_USD" : "USD") : null,
@@ -1685,9 +1751,9 @@ server.registerTool("auto_pay_checkout", {
1685
1751
  : (issueAmount > (detected?.amount ?? issueAmount)
1686
1752
  ? `Locked $${issueAmount} = visible $${detected?.amount} + rounding buffer (never above max_amount); the unspent part returns after the charge settles.`
1687
1753
  : undefined),
1688
- message: fillResult.success
1689
- ? `✅ Confirmed: JIT card issued (limit $${issueAmount}) and the merchant showed an order confirmation.`
1690
- : `❌ Not confirmed (${fillResult.status}): ${(0, failure_taxonomy_js_1.redactCardData)(fillResult.message)} Token released.`,
1754
+ message: confirmed
1755
+ ? `✅ Confirmed: JIT card issued (limit $${issueAmount}) and the merchant showed an order confirmation. ${(0, failure_taxonomy_js_1.redactCardData)(fillResult.message)}`
1756
+ : `❌ Not confirmed (${fillResult.status}): ${(0, failure_taxonomy_js_1.redactCardData)(fillResult.message)} ${releaseSaid}`,
1691
1757
  ...untrusted(fillResult.page_detail),
1692
1758
  // Order number as read off the page: page data, already card-scrubbed.
1693
1759
  receipt_id: fillResult.receipt_id || null,
@@ -1699,7 +1765,7 @@ server.registerTool("auto_pay_checkout", {
1699
1765
  verify_url: autoReceipt.verify_url || null,
1700
1766
  },
1701
1767
  } : {}),
1702
- }, !fillResult.success);
1768
+ }, !confirmed);
1703
1769
  }
1704
1770
  catch (err) {
1705
1771
  const raw = err?.message || String(err);
@@ -123,7 +123,9 @@ async function extractTotalPrice(page) {
123
123
  if (el.children.length >= 5)
124
124
  continue;
125
125
  const t = textOf(el).toLowerCase();
126
- if ((t.includes("total") || t.includes("amount due") || t.includes("you pay")) && t.length < 200 && visible(el)) {
126
+ // "total" as a WORD: includes("total") also took a bare "Subtotal $2.00" row for
127
+ // the total, and the card was sized for the goods without shipping (review, round 6).
128
+ if ((/\btotal\b/.test(t) || t.includes("amount due") || t.includes("you pay")) && t.length < 200 && visible(el)) {
127
129
  out.push({ strategy: 2, text: textOf(el) });
128
130
  }
129
131
  }
@@ -204,10 +206,17 @@ function parsePricesText(text) {
204
206
  */
205
207
  async function extractCheckoutTotalStrict(page, selector) {
206
208
  const found = await page.evaluate((sel) => {
209
+ const docW = Math.max(document.documentElement.scrollWidth, window.innerWidth);
210
+ const docH = Math.max(document.documentElement.scrollHeight, window.innerHeight);
207
211
  const visible = (el) => {
208
212
  const r = el.getBoundingClientRect();
209
213
  if (r.width < 1 || r.height < 1)
210
214
  return false;
215
+ // Parked off-screen (a screen-reader-only copy at left:-9999px) is not on the page
216
+ // a person sees — the same rule extractTotalPrice applies (review, 27/11/2026).
217
+ const left = r.left + window.scrollX, top = r.top + window.scrollY;
218
+ if (left + r.width <= 0 || top + r.height <= 0 || left >= docW || top >= docH)
219
+ return false;
211
220
  let opacity = 1;
212
221
  for (let n = el; n; n = n.parentElement) {
213
222
  const s = getComputedStyle(n);
@@ -18,6 +18,14 @@ type Page = import("playwright").Page;
18
18
  * code is a secret like the card number and is stripped from everything returned too.
19
19
  */
20
20
  export declare function fillCheckoutForm(checkoutUrl: string, cardData: CardData, existingPage?: Page, hints?: CheckoutHints, deal?: DealPayment): Promise<PaymentResult>;
21
+ /**
22
+ * Once Pay has been pressed (or may have been — the flag is set before the click), an attempt
23
+ * that then breaks off is 'unconfirmed', whatever it broke on: the browser failing, or a click
24
+ * that threw and left "no button was clicked". An order may exist. Reported as 'error' or
25
+ * 'not_submitted' it read as "nothing happened", and auto_pay_checkout cancelled the card on it
26
+ * (independent review, round 6). Only the hard timeout had this rule before.
27
+ */
28
+ export declare function mayHavePaid(r: PaymentResult, payPressed: boolean): PaymentResult;
21
29
  /**
22
30
  * Cut THIS card's expiry out of a text, in the spellings a page or a browser error would use
23
31
  * (08/29, 08 / 29, 08-29, 08/2029). An expiry alone pays for nothing, but it is the card's and
@@ -4,6 +4,7 @@
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.PAY_WORDS_RE = exports.APPLY_WORDS_RE = void 0;
6
6
  exports.fillCheckoutForm = fillCheckoutForm;
7
+ exports.mayHavePaid = mayHavePaid;
7
8
  exports.hideExpiry = hideExpiry;
8
9
  exports.hideDealCode = hideDealCode;
9
10
  exports.readReceiptId = readReceiptId;
@@ -82,7 +83,7 @@ async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints, deal
82
83
  await browser.close().catch(() => { });
83
84
  });
84
85
  // Deal orders: the total read off the page after the code was applied.
85
- return finish(await settleDealCode(dealState.total !== undefined ? { ...result, amount: dealState.total } : result), secrets);
86
+ return finish(await settleDealCode(mayHavePaid(dealState.total !== undefined ? { ...result, amount: dealState.total } : result, dealState.payPressed === true)), secrets);
86
87
  }
87
88
  catch (err) {
88
89
  if (err instanceof with_timeout_js_1.TimeoutError) {
@@ -103,12 +104,12 @@ async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints, deal
103
104
  message: `Checkout timed out after ${CHECKOUT_HARD_TIMEOUT_MS / 1000}s. The merchant page may be too slow or blocking automation.`,
104
105
  }), secrets);
105
106
  }
106
- return finish(await settleDealCode({
107
+ return finish(await settleDealCode(mayHavePaid({
107
108
  success: false,
108
109
  status: 'error',
109
110
  message: 'The browser failed during the checkout attempt.',
110
111
  page_detail: err instanceof Error ? err.message : String(err),
111
- }), secrets);
112
+ }, dealState.payPressed === true)), secrets);
112
113
  }
113
114
  finally {
114
115
  if (browser)
@@ -119,6 +120,24 @@ async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints, deal
119
120
  secrets.code = undefined;
120
121
  }
121
122
  }
123
+ /**
124
+ * Once Pay has been pressed (or may have been — the flag is set before the click), an attempt
125
+ * that then breaks off is 'unconfirmed', whatever it broke on: the browser failing, or a click
126
+ * that threw and left "no button was clicked". An order may exist. Reported as 'error' or
127
+ * 'not_submitted' it read as "nothing happened", and auto_pay_checkout cancelled the card on it
128
+ * (independent review, round 6). Only the hard timeout had this rule before.
129
+ */
130
+ function mayHavePaid(r, payPressed) {
131
+ if (!payPressed || (r.status !== 'error' && r.status !== 'not_submitted'))
132
+ return r;
133
+ return {
134
+ ...r,
135
+ success: false,
136
+ status: 'unconfirmed',
137
+ message: `Pay was pressed, then the attempt broke off before any order confirmation was seen (${r.status}: ${r.message}) ` +
138
+ `The token was NOT burned — verify whether the order went through before retrying (avoid double-charge).`,
139
+ };
140
+ }
122
141
  /**
123
142
  * Cut THIS card's expiry out of a text, in the spellings a page or a browser error would use
124
143
  * (08/29, 08 / 29, 08-29, 08/2029). An expiry alone pays for nothing, but it is the card's and
@@ -156,7 +175,10 @@ function finish(r, secrets) {
156
175
  const clean = (t) => hideExpiry((0, failure_taxonomy_js_1.scrubCardValues)(hideDealCode(t, secrets.code), secrets), secrets);
157
176
  const out = { ...r, message: clean(r.message) };
158
177
  if (r.page_detail) {
159
- out.page_detail = clean(r.page_detail).slice(0, PAGE_DETAIL_MAX);
178
+ // Cut AFTER cleaning, at a space where there is one (a long address has none: plain cut).
179
+ const cleaned = clean(r.page_detail);
180
+ const at = cleaned.length > PAGE_DETAIL_MAX ? cleaned.slice(0, PAGE_DETAIL_MAX + 1).lastIndexOf(" ") : -1;
181
+ out.page_detail = cleaned.length <= PAGE_DETAIL_MAX ? cleaned : cleaned.slice(0, at > PAGE_DETAIL_MAX / 2 ? at : PAGE_DETAIL_MAX);
160
182
  }
161
183
  if (r.receipt_id !== undefined) {
162
184
  // An "order number" that holds the code is dropped outright, like one that holds the card.
@@ -442,18 +464,54 @@ async function readPageAlerts(page) {
442
464
  return at > 0 ? head.slice(0, at) : "";
443
465
  };
444
466
  const seen = new Set();
467
+ const docW = Math.max(document.documentElement.scrollWidth, window.innerWidth);
468
+ const docH = Math.max(document.documentElement.scrollHeight, window.innerHeight);
445
469
  for (const el of Array.from(document.querySelectorAll('[role="alert"], [aria-live="assertive"], [role="status"][aria-live], [class*="error" i][class*="banner" i], [class*="notice" i][class*="error" i]'))) {
446
470
  const r = el.getBoundingClientRect();
447
- const st = getComputedStyle(el);
448
- if (r.width < 1 || r.height < 1 || st.display === "none" || st.visibility === "hidden" || parseFloat(st.opacity || "1") < 0.1)
471
+ if (r.width < 1 || r.height < 1)
449
472
  continue;
473
+ // Something a person can actually see: not parked off-screen, and not inside a
474
+ // parent that is hidden or faded out (a toast kept in the page until it is needed
475
+ // sits in such a parent; its text is not what the shop is saying now).
476
+ let opacity = 1, hidden = false, fixed = false;
477
+ for (let n = el; n; n = n.parentElement) {
478
+ const s = getComputedStyle(n);
479
+ if (s.display === "none" || s.visibility === "hidden") {
480
+ hidden = true;
481
+ break;
482
+ }
483
+ opacity *= parseFloat(s.opacity || "1");
484
+ if (s.position === "fixed")
485
+ fixed = true;
486
+ }
487
+ if (hidden || opacity < 0.1)
488
+ continue;
489
+ // Where it is. An element pinned to the window (position: fixed, itself or a parent)
490
+ // is judged against the WINDOW: a toast waiting above the top edge
491
+ // (top: 0; transform: translateY(-100%)) is at -60px however far the page has been
492
+ // scrolled — adding the scroll offset put it "on the page" once the buyer had
493
+ // scrolled down to the Pay button (review, round 6). Anything else is judged
494
+ // against the whole document.
495
+ if (fixed) {
496
+ if (r.right <= 0 || r.bottom <= 0 || r.left >= window.innerWidth || r.top >= window.innerHeight)
497
+ continue;
498
+ }
499
+ else {
500
+ const left = r.left + window.scrollX, top = r.top + window.scrollY;
501
+ if (left + r.width <= 0 || top + r.height <= 0 || left >= docW || top >= docH)
502
+ continue;
503
+ }
450
504
  const t = (el.innerText || "").replace(/\s+/g, " ").trim();
451
505
  if (t.length >= 8)
452
- seen.add(cutAtSpace(t, 200));
506
+ seen.add(cutAtSpace(t, 600));
453
507
  if (seen.size >= 3)
454
508
  break;
455
509
  }
456
- return cutAtSpace(Array.from(seen).join(" | "), 300);
510
+ // Far longer than what is handed back (PAGE_DETAIL_MAX): the short cut is made in
511
+ // finish(), AFTER card values and deal codes are scrubbed from the whole text. A value
512
+ // written with spaces ("4242 4242 4242 4242") that sat across an early cut left its
513
+ // first groups behind, where the scrubbing no longer saw a card number (review, round 4).
514
+ return cutAtSpace(Array.from(seen).join(" | "), 1500);
457
515
  }).catch(() => "");
458
516
  }
459
517
  /** The whole line a decline phrase sits on (readableText puts one text node per line). */
@@ -473,8 +531,11 @@ function cutWords(t, max) {
473
531
  function textNewSince(before, now) {
474
532
  if (before === undefined)
475
533
  return now;
476
- const old = new Set(before.split("\n").map((l) => l.trim()).filter(Boolean));
477
- return now.split("\n").map((l) => l.trim()).filter((l) => l && !old.has(l)).join("\n");
534
+ // Lines are compared with their inner whitespace collapsed: a page that redraws itself may
535
+ // space the same sentence differently, and that must not make old help text "new".
536
+ const norm = (l) => l.replace(/\s+/g, " ").trim();
537
+ const old = new Set(before.split("\n").map(norm).filter(Boolean));
538
+ return now.split("\n").map(norm).filter((l) => l && !old.has(l)).join("\n");
478
539
  }
479
540
  /**
480
541
  * The text a person looking at the page can actually read (audit T12 F6, M.7).
@@ -574,19 +635,29 @@ async function detectPaymentOutcome(page, checkoutUrl) {
574
635
  return false;
575
636
  }
576
637
  })();
577
- const urlSignal = movedOff && SUCCESS_URL_RE.test(currentUrl);
638
+ // The address is judged by its PATH only. A query string names where the shop would go
639
+ // next ("?return_url=/thank-you", "?next=confirmation"), not where the buyer is.
640
+ const urlSignal = movedOff && SUCCESS_URL_RE.test((() => { try {
641
+ return new URL(currentUrl).pathname;
642
+ }
643
+ catch {
644
+ return '';
645
+ } })());
578
646
  const textSignal = SUCCESS_TEXT_RE.test(bodyText);
579
- // Order of judgement (changed in 1.12.4, independent review 27/11/2026). Until then the
580
- // page-wide decline words were tested FIRST and on ALL the text: a thank-you page or a
581
- // checkout whose help text says "What if my card was declined?" was reported 'declined'
582
- // for an order that had gone through — an invitation to pay twice.
583
- // 1. The page has MOVED to a confirmation address → confirmed.
584
- // 2. The page's own ERROR BANNER says the card did not go through → declined.
585
- // 3. Confirmation words on the page → confirmed.
586
- // 4. Decline words in text that was NOT on the page before Pay was pressed → declined.
647
+ // Order of judgement. Until 1.12.4 the page-wide decline words were tested FIRST and on
648
+ // ALL the text: a thank-you page or a checkout whose help text says "What if my card was
649
+ // declined?" was reported 'declined' for an order that had gone through — an invitation
650
+ // to pay twice. 1.12.4 fixed that but let a confirmation ADDRESS win over the page's
651
+ // error banner: a shop that answers a refusal at /orders/123/payment?error=declined, or
652
+ // at any address holding "confirmation", was reported 'confirmed' for a declined card —
653
+ // the token burned, the hold stranded (independent review, round 4; fixed in 1.12.5).
654
+ // 1. The page's own ERROR BANNER says the card did not go through → declined. A real
655
+ // thank-you page does not carry an alert saying the card was refused.
656
+ // 2. The page has moved to a confirmation address, or says so in words → confirmed.
657
+ // 3. Decline words in text that was NOT on the page before Pay was pressed → declined.
587
658
  // Help text, FAQs and product notes were there before; a shop's refusal is new.
588
659
  const alertDeclined = ALERT_DECLINE_RE.test(alerts) || DECLINE_TEXT_RE.test(alerts);
589
- if (!urlSignal && alertDeclined) {
660
+ if (alertDeclined) {
590
661
  return { kind: 'declined', page_said: alerts || undefined };
591
662
  }
592
663
  if (!urlSignal && !textSignal) {
@@ -1113,6 +1184,10 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints, deal,
1113
1184
  // no_fields on the first real deal order (26/11/2026). Selectors the agent did pass
1114
1185
  // are kept — the preset only fills what is missing.
1115
1186
  let cardFieldsFrom = 'agent hints';
1187
+ // ONE allowance for card frames to appear and load, shared by the two waits below (the
1188
+ // Shopify look-out, then "every attached frame has its page"). They used to run one
1189
+ // after the other with a fresh 8 seconds each (review, round 4).
1190
+ let cardFramesUntil = 0;
1116
1191
  if (!(hints && (hints.card_selector || hints.exp_selector || hints.cvv_selector))) {
1117
1192
  await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => { });
1118
1193
  const hasShopifyCardFrames = () => page.frames().some((f) => f !== page.mainFrame() && /^card-fields-number/.test(f.name()) &&
@@ -1123,8 +1198,8 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints, deal,
1123
1198
  // building them, give them a few seconds.
1124
1199
  let shopifyCardFrames = hasShopifyCardFrames();
1125
1200
  if (!shopifyCardFrames && (/\/checkouts\//.test(page.url()) || await page.$('iframe[name^="card-fields"], [id*="card-fields" i]').catch(() => null))) {
1126
- const until = Date.now() + 8_000;
1127
- while (!shopifyCardFrames && Date.now() < until) {
1201
+ cardFramesUntil = Date.now() + CARD_FRAMES_WAIT_MS;
1202
+ while (!shopifyCardFrames && Date.now() < cardFramesUntil) {
1128
1203
  await page.waitForTimeout(400).catch(() => { });
1129
1204
  shopifyCardFrames = hasShopifyCardFrames();
1130
1205
  }
@@ -1150,7 +1225,7 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints, deal,
1150
1225
  // wait at all, so an agent that followed the hints was the one more likely to
1151
1226
  // fail (independent review, 27/11/2026).
1152
1227
  const attachedCardFrames = () => page.$$eval('iframe', (els, n) => els.filter((e) => (e.getAttribute('name') || '').includes(n)).length, frameName).catch(() => 0);
1153
- const framesUntil = Date.now() + CARD_FRAMES_WAIT_MS;
1228
+ const framesUntil = cardFramesUntil || Date.now() + CARD_FRAMES_WAIT_MS;
1154
1229
  for (;;) {
1155
1230
  const attached = await attachedCardFrames();
1156
1231
  if (attached > 0 && loadedCardFrames().length >= attached)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "z-zero-mcp-server",
3
- "version": "1.12.4",
3
+ "version": "1.12.6",
4
4
  "description": "Z-ZERO MCP Server — Secure JIT Virtual Card Payment tools for AI Agents (Claude, Cursor, AutoGPT) — Real Single-Use Virtual Cards, settled in USDC on Base",
5
5
  "main": "dist/index.js",
6
6
  "bin": {