@dvmkit/dvm-cli 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +1 -1
  2. package/dist/{chunk-ESQ6DCS3.js → chunk-3NXAIRFF.js} +2 -2
  3. package/dist/{chunk-REIUNZQX.js → chunk-B5KW2TPR.js} +2 -2
  4. package/dist/{chunk-DGA5EFKU.js → chunk-DF2OWCRY.js} +6 -6
  5. package/dist/{chunk-R6FZT6S2.js → chunk-DJDONOMG.js} +9 -5
  6. package/dist/{chunk-DE7TEOUR.js → chunk-J3HYNDMI.js} +424 -51
  7. package/dist/{chunk-OEWENVJ7.js → chunk-MM646MFM.js} +4 -4
  8. package/dist/{chunk-VLD7OKSH.js → chunk-NKD4NEUF.js} +3 -3
  9. package/dist/{chunk-ZGBCVQF2.js → chunk-OCVRCWBL.js} +3 -3
  10. package/dist/{chunk-IK7RI645.js → chunk-W4ADV3HW.js} +449 -5
  11. package/dist/{chunk-UFMAHF6T.js → chunk-WCX4PNEF.js} +127 -40
  12. package/dist/{chunk-THTPKBZX.js → chunk-X6BETQ7V.js} +1252 -737
  13. package/dist/{chunk-A2B7QDMS.js → chunk-ZZCYSYXR.js} +2 -2
  14. package/dist/{client-3JOMNAIQ.js → client-S3FEXAWD.js} +6 -6
  15. package/dist/dvm.js +687 -249
  16. package/dist/{internal-L362ZUWL.js → internal-WAQ3LZN4.js} +10 -8
  17. package/dist/{lifecycle-BH4OA5I3.js → lifecycle-NOK3MKL4.js} +6 -6
  18. package/dist/{payout-reporter-F5LFV5W4-EJ7E5ALO.js → payout-reporter-5PH53T44-7IA4NGIN.js} +2 -2
  19. package/dist/{pocket-refill-5BEM22UM.js → pocket-refill-KUBHM7MR.js} +10 -10
  20. package/dist/{revenue-reporter-2U55YH2I-EUB6PBRN.js → revenue-reporter-4XV3OO5O-RYHS3M34.js} +2 -2
  21. package/dist/{tempo-lifecycle-WGTX6MJR.js → tempo-lifecycle-QGJ4JEHN.js} +8 -8
  22. package/dist/{tempo-wallet-OTB2YSWE.js → tempo-wallet-GDDZZP5S.js} +7 -7
  23. package/dist/{wallet-73EJBUSO.js → wallet-2M3H75UP.js} +7 -7
  24. package/dist/{x402-G6C4N2BN-TAJEBQGU.js → x402-FHHB3V4V-CM6OMLHE.js} +2 -2
  25. package/package.json +2 -2
  26. package/skills/dvm/calling.md +13 -2
  27. package/skills/dvm/credit.md +5 -1
  28. package/skills/dvm/recovery.md +2 -0
  29. package/skills/dvm/wallets.md +2 -0
@@ -3,15 +3,15 @@ import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
5
  connectedTempoAccount
6
- } from "./chunk-OEWENVJ7.js";
6
+ } from "./chunk-MM646MFM.js";
7
7
  import {
8
8
  loadX402Wallet,
9
9
  x402NetworkLabel
10
- } from "./chunk-VLD7OKSH.js";
10
+ } from "./chunk-NKD4NEUF.js";
11
11
  import {
12
12
  isCreditPosture,
13
13
  loadConfig
14
- } from "./chunk-ESQ6DCS3.js";
14
+ } from "./chunk-3NXAIRFF.js";
15
15
  import {
16
16
  addOutputWarnings,
17
17
  costAnchor,
@@ -26,7 +26,7 @@ import {
26
26
  resolveBtcUsdRate,
27
27
  tryResolveBtcUsdRate,
28
28
  tryX402Payment
29
- } from "./chunk-R6FZT6S2.js";
29
+ } from "./chunk-DJDONOMG.js";
30
30
  import {
31
31
  BUDGET_FILE,
32
32
  CONFIG_DIR,
@@ -183,7 +183,7 @@ import {
183
183
  x402PendingUnsettled,
184
184
  x402RequiredFromError,
185
185
  x402VoucherPendingState
186
- } from "./chunk-THTPKBZX.js";
186
+ } from "./chunk-X6BETQ7V.js";
187
187
  import {
188
188
  Challenge_exports,
189
189
  Credential_exports
@@ -204,7 +204,7 @@ import {
204
204
  redactUrlsInText,
205
205
  usdToMsats,
206
206
  x402NetworkToCaip2
207
- } from "./chunk-DGA5EFKU.js";
207
+ } from "./chunk-DF2OWCRY.js";
208
208
  import {
209
209
  privateKeyToAccount
210
210
  } from "./chunk-EVQERRCP.js";
@@ -352,6 +352,11 @@ function parseDurationMs(input) {
352
352
  };
353
353
  return count * unitMs[match[2]];
354
354
  }
355
+ function formatDurationMs(ms) {
356
+ for (const [unit, size] of [["d", 864e5], ["h", 36e5], ["m", 6e4]])
357
+ if (ms >= size && ms % size === 0) return `${ms / size}${unit}`;
358
+ return `${Math.ceil(ms / 1e3)}s`;
359
+ }
355
360
 
356
361
  // src/commands/wallet-history.ts
357
362
  var DEFAULT_LIMIT = 50;
@@ -1406,6 +1411,7 @@ function fail(mode, refusal) {
1406
1411
  }
1407
1412
 
1408
1413
  // src/lib/card-credit/journal.ts
1414
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
1409
1415
  import { createHash as createHash2 } from "crypto";
1410
1416
  import {
1411
1417
  closeSync,
@@ -1413,13 +1419,98 @@ import {
1413
1419
  fsyncSync,
1414
1420
  openSync,
1415
1421
  readdirSync,
1422
+ renameSync,
1416
1423
  linkSync,
1417
1424
  readFileSync,
1418
1425
  rmSync,
1419
1426
  writeFileSync
1420
1427
  } from "fs";
1421
- import { join } from "path";
1428
+ import { dirname, join } from "path";
1422
1429
  var CARD_FUNDINGS_DIR = join(CONFIG_DIR, "card-fundings");
1430
+ var RETIRED_CHECKOUTS_DIR = join(CARD_FUNDINGS_DIR, "retired");
1431
+ var RETIRED_CHECKOUT_TTL_MS = 24 * 60 * 60 * 1e3;
1432
+ async function withCardFundingLock(scope, reserve) {
1433
+ ensureConfigSubdir(CARD_FUNDINGS_DIR);
1434
+ const key = sha256Hex(`${normalizeCreditEndpoint(scope.endpoint)}
1435
+ ${scope.callerPubkey}`);
1436
+ const release = await import_proper_lockfile.default.lock(join(CARD_FUNDINGS_DIR, `scope-${key}`), {
1437
+ realpath: false,
1438
+ stale: 3e4,
1439
+ retries: { retries: 100, factor: 1, minTimeout: 50, maxTimeout: 50 }
1440
+ });
1441
+ try {
1442
+ return reserve();
1443
+ } finally {
1444
+ await release();
1445
+ }
1446
+ }
1447
+ function checkoutRetiredSince(scope, startedAt) {
1448
+ const endpoint = normalizeCreditEndpoint(scope.endpoint);
1449
+ return recentCheckoutRetirements().filter((entry) => normalizeCreditEndpoint(entry.endpoint) === endpoint && entry.callerPubkey === scope.callerPubkey && entry.retiredAt > startedAt).sort((a, b) => b.retiredAt - a.retiredAt)[0];
1450
+ }
1451
+ async function retireCheckoutFunding(entry) {
1452
+ await withCardFundingLock(entry, () => {
1453
+ if (loadPendingCardFunding(entry.endpoint, entry.callerPubkey, entry.creditId)?.fundId !== entry.fundId) return;
1454
+ const previous = recentCheckoutRetirements().find((retired2) => normalizeCreditEndpoint(retired2.endpoint) === normalizeCreditEndpoint(entry.endpoint) && retired2.callerPubkey === entry.callerPubkey && retired2.creditId === entry.creditId && retired2.fundId === entry.fundId);
1455
+ ensureConfigSubdir(RETIRED_CHECKOUTS_DIR);
1456
+ const retired = previous ?? {
1457
+ endpoint: entry.endpoint,
1458
+ callerPubkey: entry.callerPubkey,
1459
+ creditId: entry.creditId,
1460
+ fundId: entry.fundId,
1461
+ retiredAt: Date.now()
1462
+ };
1463
+ const key = sha256Hex(`${normalizeCreditEndpoint(entry.endpoint)}
1464
+ ${entry.callerPubkey}
1465
+ ${entry.creditId}
1466
+ ${entry.fundId}`);
1467
+ writeSyncedJson(join(RETIRED_CHECKOUTS_DIR, `${key}.json`), retired);
1468
+ fsyncDirectory(CARD_FUNDINGS_DIR);
1469
+ clearPendingCardFunding(entry);
1470
+ fsyncDirectory(CARD_FUNDINGS_DIR);
1471
+ });
1472
+ }
1473
+ function recentCheckoutRetirements() {
1474
+ if (!existsSync(RETIRED_CHECKOUTS_DIR)) return [];
1475
+ const entries = [];
1476
+ let pruned = false;
1477
+ for (const name of readdirSync(RETIRED_CHECKOUTS_DIR).filter((name2) => name2.endsWith(".json"))) {
1478
+ const path = join(RETIRED_CHECKOUTS_DIR, name);
1479
+ let parsed;
1480
+ try {
1481
+ parsed = JSON.parse(readFileSync(path, "utf8"));
1482
+ } catch (error) {
1483
+ if (error.code === "ENOENT") continue;
1484
+ throw error;
1485
+ }
1486
+ if (!parsed || typeof parsed.endpoint !== "string" || typeof parsed.callerPubkey !== "string" || typeof parsed.creditId !== "string" || typeof parsed.fundId !== "string" || typeof parsed.retiredAt !== "number" || !Number.isSafeInteger(parsed.retiredAt)) {
1487
+ throw new Error("Invalid checkout retirement record");
1488
+ }
1489
+ if (parsed.retiredAt <= Date.now() - RETIRED_CHECKOUT_TTL_MS) {
1490
+ rmSync(path, { force: true });
1491
+ pruned = true;
1492
+ } else entries.push(parsed);
1493
+ }
1494
+ if (pruned) fsyncDirectory(RETIRED_CHECKOUTS_DIR);
1495
+ return entries;
1496
+ }
1497
+ function updatePendingCheckout(entry) {
1498
+ const path = entryPath(entry.endpoint, entry.callerPubkey, entry.creditId);
1499
+ if (readEntry(path)?.fundId !== entry.fundId) throw new Error("Checkout journal changed during funding");
1500
+ writeSyncedJson(path, entry);
1501
+ }
1502
+ function writeSyncedJson(path, value) {
1503
+ const temp = `${path}.${String(process.pid)}.tmp`;
1504
+ const fd = openSync(temp, "w", 384);
1505
+ try {
1506
+ writeFileSync(fd, JSON.stringify(value, null, 2) + "\n");
1507
+ fsyncSync(fd);
1508
+ } finally {
1509
+ closeSync(fd);
1510
+ }
1511
+ renameSync(temp, path);
1512
+ fsyncDirectory(dirname(path));
1513
+ }
1423
1514
  function sha256Hex(value) {
1424
1515
  return createHash2("sha256").update(value, "utf8").digest("hex");
1425
1516
  }
@@ -1481,7 +1572,7 @@ function readEntry(path) {
1481
1572
  if (!existsSync(path)) return void 0;
1482
1573
  try {
1483
1574
  const parsed = JSON.parse(readFileSync(path, "utf8"));
1484
- if (parsed.v !== 1 || typeof parsed.endpoint !== "string" || typeof parsed.callerPubkey !== "string" || typeof parsed.creditId !== "string" || typeof parsed.fundId !== "string" || typeof parsed.amountMicro !== "number" || typeof parsed.challenge !== "string" || typeof parsed.sptSha256 !== "string" || typeof parsed.commitment !== "string" || typeof parsed.presentedAt !== "number") {
1575
+ if (parsed.v !== 1 && parsed.v !== 2 || typeof parsed.endpoint !== "string" || typeof parsed.callerPubkey !== "string" || typeof parsed.creditId !== "string" || typeof parsed.fundId !== "string" || typeof parsed.amountMicro !== "number" || parsed.v === 1 && (typeof parsed.challenge !== "string" || typeof parsed.sptSha256 !== "string" || typeof parsed.commitment !== "string") || parsed.v === 2 && parsed.checkout !== void 0 && (typeof parsed.checkout.url !== "string" || !Number.isFinite(parsed.checkout.expires_at)) || typeof parsed.presentedAt !== "number") {
1485
1576
  return void 0;
1486
1577
  }
1487
1578
  return parsed;
@@ -1500,6 +1591,145 @@ function fsyncDirectory(path) {
1500
1591
  }
1501
1592
  }
1502
1593
 
1594
+ // src/lib/card-credit/checkout.ts
1595
+ function checkoutHandoff(entry, identity) {
1596
+ const amount = `$${formatUsd(entry.amountMicro / 1e6)}`;
1597
+ const caller = identity ? ` --as ${shellQuoteArg(identity)}` : "";
1598
+ const balanceCommand = `dvm credit balance ${shellQuoteArg(entry.endpoint)}${caller}`;
1599
+ return {
1600
+ status: "awaiting_payment",
1601
+ credit_id: entry.creditId,
1602
+ fund_id: entry.fundId,
1603
+ rail: "stripe",
1604
+ amount_micro: entry.amountMicro,
1605
+ amount_usd: amount,
1606
+ checkout: entry.checkout,
1607
+ expires_at: entry.checkout ? new Date(entry.checkout.expires_at * 1e3).toISOString() : void 0,
1608
+ relay: { copy_text: entry.checkout?.url, standalone: true },
1609
+ next_step: `dvm credit fund ${shellQuoteArg(entry.endpoint)} --rail stripe --credit-id ${shellQuoteArg(entry.creditId)} --amount ${shellQuoteArg(amount)}${caller}`,
1610
+ balance_command: balanceCommand,
1611
+ display: `Pay ${amount} by card at ${entry.checkout?.url ?? "the checkout link"}, then confirm the balance with ${balanceCommand}. The link is not proof of payment.`
1612
+ };
1613
+ }
1614
+ function checkoutExpiryDisplay(hint) {
1615
+ return `The card checkout expired. No credit was added. ${hint ?? "Start a new top-up."}`;
1616
+ }
1617
+ async function fundOverCheckout(args, fundId, deps, prior, booked2) {
1618
+ if (!prior && args.amountMicro % 1e4 !== 0) {
1619
+ const error = new DvmError("invalid_argument", "Card top-ups must be whole USD cents.");
1620
+ return { creditId: args.creditId, fundId, rail: "stripe", status: "refused", error, display: error.message };
1621
+ }
1622
+ const minimum = Math.max(args.menu?.stripe?.min_micro ?? 5e5, args.menu?.min_micro ?? 0);
1623
+ const amountMicro = prior?.amountMicro ?? Math.max(args.amountMicro, minimum);
1624
+ const startedAt = args.cardInvocationStartedAt ?? Date.now();
1625
+ const reserved = await withCardFundingLock({ endpoint: args.ref.endpoint, callerPubkey: args.signing.pubkey }, () => {
1626
+ const retired = args.cardCreditIdExplicit ? void 0 : checkoutRetiredSince(
1627
+ { endpoint: args.ref.endpoint, callerPubkey: args.signing.pubkey },
1628
+ startedAt
1629
+ );
1630
+ if (retired) return { retired };
1631
+ const existing = listPendingCardFundings({ endpoint: args.ref.endpoint, callerPubkey: args.signing.pubkey }).find((entry3) => entry3.v === 2 && (!args.cardCreditIdExplicit || entry3.creditId === args.creditId));
1632
+ if (existing) return { entry: existing, created: false };
1633
+ if (prior) return { entry: prior, created: false };
1634
+ const entry2 = {
1635
+ v: 2,
1636
+ endpoint: args.ref.endpoint,
1637
+ callerPubkey: args.signing.pubkey,
1638
+ creditId: args.creditId,
1639
+ fundId,
1640
+ amountMicro,
1641
+ targetMicro: args.targetMicro ?? amountMicro,
1642
+ presentedAt: Date.now()
1643
+ };
1644
+ return recordPendingCardFunding(entry2) ? { entry: entry2, created: true } : void 0;
1645
+ });
1646
+ if (!reserved) {
1647
+ return {
1648
+ creditId: args.creditId,
1649
+ fundId,
1650
+ rail: "stripe",
1651
+ status: "refused",
1652
+ display: "Another card top-up is already in progress. Re-run to resume it."
1653
+ };
1654
+ }
1655
+ if (reserved.retired) {
1656
+ const caller = args.cardIdentity ? ` --as ${shellQuoteArg(args.cardIdentity)}` : "";
1657
+ const balance = `dvm credit balance ${shellQuoteArg(args.ref.endpoint)}${caller}`;
1658
+ return {
1659
+ creditId: reserved.retired.creditId,
1660
+ fundId: reserved.retired.fundId,
1661
+ rail: "stripe",
1662
+ status: "refused",
1663
+ display: `A card top-up for this DVM completed while this command was starting. Check the balance with ${balance}. Re-run this command to start another top-up.`
1664
+ };
1665
+ }
1666
+ const { entry } = reserved;
1667
+ const raised = reserved.created && entry.amountMicro > args.amountMicro ? `Raised the requested $${formatUsd(args.amountMicro / 1e6)} to this DVM's card minimum of $${formatUsd(entry.amountMicro / 1e6)}.` : void 0;
1668
+ const base = { creditId: entry.creditId, fundId: entry.fundId, rail: "stripe" };
1669
+ const body = {
1670
+ op: "fund",
1671
+ credit_id: entry.creditId,
1672
+ fund: { method: "stripe", via: "checkout", fund_id: entry.fundId, amount_micro: entry.amountMicro }
1673
+ };
1674
+ let announced = false;
1675
+ let delay = 1e3;
1676
+ const sleep2 = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1677
+ for (; ; ) {
1678
+ try {
1679
+ const result = await deps.post(body);
1680
+ const pending = result;
1681
+ if (pending.status !== "pending") {
1682
+ if (!result.credit || result.funded_micro === void 0) {
1683
+ throw new DvmError("provider_error", "The DVM returned no confirmed card credit.");
1684
+ }
1685
+ const outcome = await booked2(entry, result);
1686
+ return {
1687
+ ...outcome,
1688
+ display: [raised, outcome.display].filter(Boolean).join(" "),
1689
+ hint: `${outcome.hint ?? ""} Confirm the balance with ${String(checkoutHandoff(entry, args.cardIdentity).balance_command)}.`.trim()
1690
+ };
1691
+ }
1692
+ if (!pending.checkout || typeof pending.checkout.url !== "string" || !Number.isFinite(pending.checkout.expires_at) || pending.credit_id !== entry.creditId) {
1693
+ throw new DvmError("provider_error", "The DVM returned an invalid checkout hand-off.");
1694
+ }
1695
+ entry.checkout = { url: pending.checkout.url, expires_at: pending.checkout.expires_at };
1696
+ updatePendingCheckout(entry);
1697
+ const handoff = checkoutHandoff(entry, args.cardIdentity);
1698
+ const display = [raised, handoff.display].filter(Boolean).join(" ");
1699
+ if (args.cardWait === false || Date.now() >= entry.checkout.expires_at * 1e3) {
1700
+ return { ...base, status: "checkout_pending", checkoutHandoff: { ...handoff, display }, display };
1701
+ }
1702
+ if (!announced) {
1703
+ args.cardCheckoutProgress?.({ ...handoff, display });
1704
+ announced = true;
1705
+ }
1706
+ } catch (err) {
1707
+ const error = err instanceof DvmError ? err : new DvmError("provider_error", "Could not confirm the card top-up.");
1708
+ const terminal = await withCardFundingLock(entry, () => {
1709
+ const latest = loadPendingCardFunding(entry.endpoint, entry.callerPubkey, entry.creditId);
1710
+ if (latest?.v === 2 && latest.checkout) entry.checkout = latest.checkout;
1711
+ const closed = error.code === "checkout_expired" || !entry.checkout && (error.code === "checkout_not_supported" || error.data?.retryable === false);
1712
+ if (closed) clearPendingCardFunding(entry);
1713
+ return closed;
1714
+ });
1715
+ const unresolved = entry.checkout !== void 0 && !terminal;
1716
+ const recovery = "Re-run the same command to resume this unresolved top-up before starting another payment. The server keeps a paid session bookable for 24 hours and refunds it to the card after that if it was never booked.";
1717
+ const display = error.code === "checkout_expired" ? checkoutExpiryDisplay(error.hint) : unresolved ? `The card top-up is unresolved (${String(error.data?.cause ?? error.code)}). ${recovery}` : error.code === "checkout_unavailable" ? `Card checkout is unavailable (${String(error.data?.cause ?? "unknown cause")}). ${terminal ? "Use another rail." : "Re-run the same command to resume this top-up before starting another payment."}` : error.message;
1718
+ if (terminal || error.data?.retryable === false || error.code === "checkout_not_supported" || args.cardWait === false || !entry.checkout || Date.now() >= entry.checkout.expires_at * 1e3) {
1719
+ return {
1720
+ ...base,
1721
+ status: "refused",
1722
+ error,
1723
+ display,
1724
+ hint: unresolved ? recovery : terminal ? error.code === "checkout_unavailable" ? "Use another funding rail." : error.hint : "Re-run the same command to resume this top-up before starting another payment."
1725
+ };
1726
+ }
1727
+ }
1728
+ await sleep2(Math.max(0, Math.min(delay, entry.checkout.expires_at * 1e3 - Date.now())));
1729
+ delay = Math.min(delay * 2, 1e4);
1730
+ }
1731
+ }
1732
+
1503
1733
  // src/lib/card-credit/fund.ts
1504
1734
  var CARD_MIN_MICRO = 5e5;
1505
1735
  var MICRO_PER_CENT = 1e4;
@@ -1522,6 +1752,12 @@ function pendingCardFundingForCredit(args) {
1522
1752
  }
1523
1753
  async function fundOverStripe(args, fundId, deps) {
1524
1754
  const journalled = pendingCardFundingForCredit(args);
1755
+ if (journalled?.v === 2 && !args.cardApprovalSteps) {
1756
+ return approvalNeededOutcome(args, { creditId: journalled.creditId, fundId: journalled.fundId, rail: "stripe" });
1757
+ }
1758
+ if (journalled?.v === 2 || !journalled && args.menu?.stripe?.checkout && args.cardSpt === void 0 && args.cardApprovalSteps) {
1759
+ return fundOverCheckout(args, fundId, deps, journalled, async (pending2, result) => booked(args, pending2, deps.settled({ creditId: pending2.creditId, fundId: pending2.fundId, rail: "stripe" }, result)));
1760
+ }
1525
1761
  if (journalled) return resumeCardFunding(args, journalled, deps);
1526
1762
  const base = { creditId: args.creditId, fundId, rail: "stripe" };
1527
1763
  if (args.menu && !args.menu.funding.includes("stripe")) {
@@ -1678,11 +1914,12 @@ async function present(args, pending, credential, deps, history) {
1678
1914
  }
1679
1915
  async function booked(args, pending, outcome) {
1680
1916
  await recordCardSpend(args, pending);
1681
- clearPendingCardFunding(pending);
1917
+ if (pending.v === 2) await retireCheckoutFunding(pending);
1918
+ else clearPendingCardFunding(pending);
1682
1919
  return {
1683
1920
  ...outcome,
1684
1921
  chargedMicro: pending.amountMicro,
1685
- display: `${outcome.display} $${usd(pending.amountMicro)} was charged to the card approved in Stripe Link.`,
1922
+ display: `${outcome.display} $${usd(pending.amountMicro)} was charged to the card${pending.v === 1 ? " approved in Stripe Link" : " through checkout"}.`,
1686
1923
  hint: `${outcome.hint ?? ""} Unspent credit goes back to that card, less its share of Stripe's processing fee: 'dvm credit drain ${shellQuoteArg(args.ref.endpoint)} --method stripe'.`.trim()
1687
1924
  };
1688
1925
  }
@@ -2476,17 +2713,36 @@ function fsyncDirectory2(path) {
2476
2713
  }
2477
2714
  }
2478
2715
 
2716
+ // src/lib/payment-bookings.ts
2717
+ var listeners = /* @__PURE__ */ new Set();
2718
+ function observePaymentBookings(listener) {
2719
+ listeners.add(listener);
2720
+ return () => {
2721
+ listeners.delete(listener);
2722
+ };
2723
+ }
2724
+ function notifyPaymentBooked(booking) {
2725
+ for (const listener of listeners) listener(booking);
2726
+ }
2727
+
2479
2728
  // src/lib/job-store.ts
2480
- import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3, renameSync, openSync as openSync3, closeSync as closeSync3, fsyncSync as fsyncSync3 } from "fs";
2481
- var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
2482
- import { dirname } from "path";
2729
+ import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3, renameSync as renameSync2, openSync as openSync3, closeSync as closeSync3, fsyncSync as fsyncSync3 } from "fs";
2730
+ var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
2731
+ import { dirname as dirname2 } from "path";
2483
2732
 
2484
2733
  // src/lib/upfront-payment.ts
2734
+ function upfrontRailPayment(method, amountMsats, usdMicro2) {
2735
+ return { method, amountMsats, ...usdMicro2 !== void 0 ? { usdMicro: usdMicro2 } : {} };
2736
+ }
2485
2737
  function parseUpfrontRailPayment(value) {
2486
2738
  if (!value || typeof value !== "object") return void 0;
2487
2739
  const raw = value;
2488
2740
  if (!["cashu", "x402", "tempo"].includes(raw.method) || !Number.isSafeInteger(raw.amountMsats) || raw.amountMsats < 0) return void 0;
2489
- return { method: raw.method, amountMsats: raw.amountMsats };
2741
+ return {
2742
+ method: raw.method,
2743
+ amountMsats: raw.amountMsats,
2744
+ ...Number.isSafeInteger(raw.usdMicro) && raw.usdMicro >= 0 ? { usdMicro: raw.usdMicro } : {}
2745
+ };
2490
2746
  }
2491
2747
  function parseUpfrontPayment(value) {
2492
2748
  if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
@@ -2511,6 +2767,52 @@ function parseUpfrontPayment(value) {
2511
2767
  };
2512
2768
  }
2513
2769
 
2770
+ // src/lib/job-budget.ts
2771
+ var ASK_SAT_ROUNDING_MSATS = 1e3;
2772
+ function budgetVerdict(policy, ledger, ask) {
2773
+ const spentMsats = ledger?.totalPaidMsats ?? 0;
2774
+ const cap = policy.maxTotalUsdMicro;
2775
+ const paidUsd = ledger?.paidUsdMicro ?? 0;
2776
+ const askUsd = dollarBoundUsdMicro(ask);
2777
+ if (validMicro(cap) && askUsd !== void 0 && dollarLedgerComplete(ledger) && validMicro(paidUsd)) {
2778
+ const total2 = paidUsd + askUsd;
2779
+ return total2 > cap ? { fits: false, unit: "usd", spent: paidUsd, ask: askUsd, total: total2, cap } : { fits: true, unit: "usd" };
2780
+ }
2781
+ const total = spentMsats + ask.msats;
2782
+ return total > policy.maxTotalMsats ? { fits: false, unit: "msats", spent: spentMsats, ask: ask.msats, total, cap: policy.maxTotalMsats } : { fits: true, unit: "msats" };
2783
+ }
2784
+ function dollarBoundUsdMicro(ask) {
2785
+ const { msats, usdMicro: dollars, rate } = ask;
2786
+ if (dollars === void 0 || !validMicro(dollars) || dollars <= 0 || !Number.isSafeInteger(msats) || msats < 0 || rate === void 0 || !Number.isFinite(rate) || rate <= 0) return void 0;
2787
+ return msats <= usdToMsats(dollars / 1e6, rate) + ASK_SAT_ROUNDING_MSATS ? dollars : void 0;
2788
+ }
2789
+ function askUsdMicro(request) {
2790
+ const credit = request.credit;
2791
+ if (credit) return usdMicro(credit.amount_micro, credit.currency);
2792
+ const required = request.x402?.required_usdc_micro;
2793
+ return typeof required === "string" && /^\d+$/.test(required) ? usdMicro(Number(required), "usd") : void 0;
2794
+ }
2795
+ function usdMicro(amountMicro, currency) {
2796
+ return typeof currency === "string" && currency.toLowerCase() === "usd" && validMicro(amountMicro) ? amountMicro : void 0;
2797
+ }
2798
+ function describeBudgetOverrun(verdict, policy) {
2799
+ const figures = [verdict.spent, verdict.ask, verdict.total, verdict.cap];
2800
+ const format = verdict.unit === "usd" ? formatUsdMicro : figures.every((msats) => msats % 1e3 === 0) ? formatSats : (msats) => `${msats.toLocaleString("en-US")} msats`;
2801
+ const declared = verdict.unit === "msats" && policy?.maxTotalUsdMicro !== void 0 ? ` (your ${formatUsdMicro(policy.maxTotalUsdMicro)} budget, converted to sats when the budget was set)` : "";
2802
+ return `This charge would take the job past its budget: ${format(verdict.spent)} spent so far plus ${format(verdict.ask)} asked comes to ${format(verdict.total)}, ${format(verdict.total - verdict.cap)} over the ${format(verdict.cap)} budget${declared}.`;
2803
+ }
2804
+ function formatUsdMicro(micro) {
2805
+ const whole = Math.floor(micro / 1e6);
2806
+ const fraction = String(micro % 1e6).padStart(6, "0").replace(/0+$/, "").padEnd(2, "0");
2807
+ return `$${whole.toLocaleString("en-US")}.${fraction}`;
2808
+ }
2809
+ function dollarLedgerComplete(ledger) {
2810
+ return (ledger?.paidUsdMsats ?? 0) === (ledger?.totalPaidMsats ?? 0);
2811
+ }
2812
+ function validMicro(value) {
2813
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
2814
+ }
2815
+
2514
2816
  // src/lib/job-store.ts
2515
2817
  function saveJob(job) {
2516
2818
  mutateJobs((jobs) => {
@@ -2556,6 +2858,7 @@ function recordUpfrontCreditPayment(jobId, value, paidOnRail = false) {
2556
2858
  job.paymentMethod = "credit";
2557
2859
  if (job.upfrontCreditBooked) return;
2558
2860
  job.totalPaidMsats = (job.totalPaidMsats ?? 0) + payment.amount_msats;
2861
+ bookUsd(job, payment.amount_msats, usdMicro(payment.amount_micro, payment.currency));
2559
2862
  job.paymentsHonoured = (job.paymentsHonoured ?? 0) + (payment.amount_msats > 0 ? 1 : 0);
2560
2863
  job.upfrontCreditBooked = true;
2561
2864
  }, true);
@@ -2583,6 +2886,7 @@ function recordUpfrontRailPayment(jobId, value, freshSubmit = false) {
2583
2886
  return;
2584
2887
  }
2585
2888
  job.totalPaidMsats = (job.totalPaidMsats ?? 0) + payment.amountMsats;
2889
+ bookUsd(job, payment.amountMsats, payment.usdMicro);
2586
2890
  job.paymentsHonoured = (job.paymentsHonoured ?? 0) + (payment.amountMsats > 0 ? 1 : 0);
2587
2891
  job.paymentMethod = payment.method;
2588
2892
  job.upfrontRailPayment = payment;
@@ -2633,18 +2937,30 @@ function loadAllJobs() {
2633
2937
  return [];
2634
2938
  }
2635
2939
  }
2636
- function addPayment(jobId, amountMsats, approval) {
2940
+ function addPayment(jobId, amountMsats, approval, usdMicro2) {
2637
2941
  mutateJobs((jobs) => {
2638
2942
  const job = jobs.find((entry) => entry.id === jobId);
2639
- if (job) bookPayment(job, amountMsats, approval);
2943
+ if (job) bookPayment(job, amountMsats, approval, usdMicro2);
2640
2944
  }, true);
2641
2945
  }
2642
- function bookPayment(job, amountMsats, approval) {
2946
+ function bookPayment(job, amountMsats, approval, usdMicro2) {
2643
2947
  job.totalPaidMsats = (job.totalPaidMsats ?? 0) + amountMsats;
2948
+ bookUsd(job, amountMsats, usdMicro2);
2644
2949
  job.paymentsHonoured = (job.paymentsHonoured ?? 0) + 1;
2645
2950
  if (approval) (job.paymentApprovals ??= []).push(approval);
2646
2951
  if (job.creditBinding && "unbound" in job.creditBinding) delete job.creditBinding;
2647
2952
  }
2953
+ function bookUsd(job, amountMsats, usdMicro2) {
2954
+ if (usdMicro2 === void 0 || !Number.isSafeInteger(usdMicro2) || usdMicro2 < 0) return;
2955
+ job.paidUsdMicro = (job.paidUsdMicro ?? 0) + usdMicro2;
2956
+ job.paidUsdMsats = (job.paidUsdMsats ?? 0) + amountMsats;
2957
+ }
2958
+ function recordBudgetRefusal(jobId, requestSeq, overrun) {
2959
+ mutateJobs((jobs) => {
2960
+ const job = jobs.find((entry) => entry.id === jobId);
2961
+ if (job) (job.budgetRefusals ??= {})[String(requestSeq)] = overrun;
2962
+ }, true);
2963
+ }
2648
2964
  function markPaymentRequestInFlight(jobId, requestSeq, submission) {
2649
2965
  mutateJobs((jobs) => {
2650
2966
  const job = jobs.find((entry) => entry.id === jobId);
@@ -2685,14 +3001,24 @@ function markPaymentRequestPaid(jobId, requestSeq) {
2685
3001
  clearPaymentRequestStartTime(job, requestSeq);
2686
3002
  const booked3 = job.unconfirmedPaymentSubmissions?.[requestSeq];
2687
3003
  clearUnconfirmedSubmission(job, requestSeq);
2688
- if (booked3) bookPayment(job, booked3.amountMsats, booked3.approval ? { requestSeq, approval: booked3.approval } : void 0);
3004
+ if (booked3) bookPayment(job, booked3.amountMsats, booked3.approval ? { requestSeq, approval: booked3.approval } : void 0, booked3.usdMicro);
2689
3005
  if (booked3 && !booked3.blocked && job.askPaymentBlocks?.[requestSeq]) {
2690
3006
  delete job.askPaymentBlocks[requestSeq];
2691
3007
  if (!Object.keys(job.askPaymentBlocks).length) delete job.askPaymentBlocks;
2692
3008
  }
2693
3009
  return booked3;
2694
3010
  }, true);
2695
- return hasUnsavedJobState() ? void 0 : booked2;
3011
+ if (!booked2 || hasUnsavedJobState()) return void 0;
3012
+ notifyPaymentBooked({
3013
+ jobId,
3014
+ requestSeq,
3015
+ approval: booked2.approval,
3016
+ rail: booked2.rail,
3017
+ amountMsats: booked2.amountMsats,
3018
+ reason: booked2.reason,
3019
+ ...booked2.rail !== "cashu_p2pk" && booked2.amountUsdcMicro !== void 0 ? { amountUsdcMicro: booked2.amountUsdcMicro } : {}
3020
+ });
3021
+ return booked2;
2696
3022
  }
2697
3023
  function markPaymentRequestAnswered(jobId, requestSeq) {
2698
3024
  mutateJobs((jobs) => {
@@ -2760,9 +3086,9 @@ function writeJobs(jobs) {
2760
3086
  } finally {
2761
3087
  closeSync3(fd);
2762
3088
  }
2763
- renameSync(temporary, JOBS_FILE);
3089
+ renameSync2(temporary, JOBS_FILE);
2764
3090
  if (process.platform !== "win32") {
2765
- const directory = openSync3(dirname(JOBS_FILE), "r");
3091
+ const directory = openSync3(dirname2(JOBS_FILE), "r");
2766
3092
  try {
2767
3093
  fsyncSync3(directory);
2768
3094
  } finally {
@@ -2775,7 +3101,7 @@ function acquireJobsLock() {
2775
3101
  const deadline = performance.now() + 1e3;
2776
3102
  for (let attempt = 0; ; attempt++) {
2777
3103
  try {
2778
- return import_proper_lockfile.default.lockSync(JOBS_FILE, { realpath: false });
3104
+ return import_proper_lockfile2.default.lockSync(JOBS_FILE, { realpath: false });
2779
3105
  } catch (error) {
2780
3106
  if (error.code !== "ELOCKED" || attempt >= 40 || performance.now() >= deadline) throw error;
2781
3107
  Atomics.wait(lockWait, 0, 0, Math.min(25, Math.max(0, deadline - performance.now())));
@@ -2924,9 +3250,13 @@ function mutateCreditPayment(jobId, change, observed = false) {
2924
3250
  }, observed);
2925
3251
  }
2926
3252
  function bookCreditPayment(jobId, intent) {
2927
- mutateCreditPayment(jobId, (job) => {
3253
+ const booked2 = mutateCreditPayment(jobId, (job) => {
3254
+ let booked3 = false;
2928
3255
  if (!job.bookedCreditPayments?.some((entry) => entry.authorization.payment_id === intent.authorization.payment_id)) {
2929
- job.totalPaidMsats = (job.totalPaidMsats ?? 0) + (intent.amountMsats ?? intent.request.amount_msats);
3256
+ booked3 = true;
3257
+ const amountMsats = intent.amountMsats ?? intent.request.amount_msats;
3258
+ job.totalPaidMsats = (job.totalPaidMsats ?? 0) + amountMsats;
3259
+ bookUsd(job, amountMsats, usdMicro(intent.authorization.amount_micro, intent.authorization.currency));
2930
3260
  job.paymentsHonoured = (job.paymentsHonoured ?? 0) + 1;
2931
3261
  (job.bookedCreditPayments ??= []).push(intent);
2932
3262
  if (intent.approval) (job.paymentApprovals ??= []).push({
@@ -2936,23 +3266,32 @@ function bookCreditPayment(jobId, intent) {
2936
3266
  }
2937
3267
  if (job.pendingCreditPayment?.authorization.payment_id === intent.authorization.payment_id)
2938
3268
  delete job.pendingCreditPayment;
3269
+ return booked3;
2939
3270
  }, true);
3271
+ if (booked2 && !hasUnsavedJobState()) notifyPaymentBooked({
3272
+ jobId,
3273
+ requestSeq: intent.authorization.request_seq,
3274
+ approval: intent.approval,
3275
+ rail: "credit",
3276
+ amountMsats: intent.amountMsats ?? intent.request.amount_msats,
3277
+ reason: intent.request.reason
3278
+ });
2940
3279
  }
2941
3280
 
2942
3281
  // src/lib/favorites.ts
2943
- var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
3282
+ var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
2944
3283
  import {
2945
3284
  closeSync as closeSync4,
2946
3285
  fchmodSync,
2947
3286
  fsyncSync as fsyncSync4,
2948
3287
  openSync as openSync4,
2949
3288
  readFileSync as readFileSync4,
2950
- renameSync as renameSync2,
3289
+ renameSync as renameSync3,
2951
3290
  statSync,
2952
3291
  unlinkSync as unlinkSync2,
2953
3292
  writeFileSync as writeFileSync4
2954
3293
  } from "fs";
2955
- import { dirname as dirname2 } from "path";
3294
+ import { dirname as dirname3 } from "path";
2956
3295
  var DEFAULT_FILE_MODE = 384;
2957
3296
  function loadFavorites() {
2958
3297
  let raw;
@@ -3020,7 +3359,7 @@ async function withFavoritesLock(fn) {
3020
3359
  ensureConfigDir();
3021
3360
  let release;
3022
3361
  try {
3023
- release = await import_proper_lockfile2.default.lock(FAVORITES_FILE, {
3362
+ release = await import_proper_lockfile3.default.lock(FAVORITES_FILE, {
3024
3363
  lockfilePath: `${FAVORITES_FILE}.lock`,
3025
3364
  realpath: false,
3026
3365
  stale: 3e4,
@@ -3051,8 +3390,8 @@ function writeFavorites(favorites) {
3051
3390
  fsyncSync4(fd);
3052
3391
  closeSync4(fd);
3053
3392
  fd = void 0;
3054
- renameSync2(temporary, FAVORITES_FILE);
3055
- fsyncDirectory3(dirname2(FAVORITES_FILE));
3393
+ renameSync3(temporary, FAVORITES_FILE);
3394
+ fsyncDirectory3(dirname3(FAVORITES_FILE));
3056
3395
  } catch (error) {
3057
3396
  if (fd !== void 0) {
3058
3397
  try {
@@ -3541,11 +3880,11 @@ function providerJobJson(data, providerJob = true) {
3541
3880
  }
3542
3881
 
3543
3882
  // src/lib/wallet-agent/journal-file.ts
3544
- var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
3545
- import { closeSync as closeSync6, existsSync as existsSync5, fsyncSync as fsyncSync5, openSync as openSync6, readFileSync as readFileSync6, renameSync as renameSync3, writeFileSync as writeFileSync5 } from "fs";
3546
- import { dirname as dirname3, join as join4 } from "path";
3883
+ var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
3884
+ import { closeSync as closeSync6, existsSync as existsSync5, fsyncSync as fsyncSync5, openSync as openSync6, readFileSync as readFileSync6, renameSync as renameSync4, writeFileSync as writeFileSync5 } from "fs";
3885
+ import { dirname as dirname4, join as join4 } from "path";
3547
3886
  function journalFile(name) {
3548
- const file = () => join4(dirname3(JOBS_FILE), name);
3887
+ const file = () => join4(dirname4(JOBS_FILE), name);
3549
3888
  function read() {
3550
3889
  if (!existsSync5(file())) return [];
3551
3890
  try {
@@ -3561,7 +3900,7 @@ function journalFile(name) {
3561
3900
  let release;
3562
3901
  for (let attempt = 0; !release; attempt++) {
3563
3902
  try {
3564
- release = import_proper_lockfile3.default.lockSync(file(), { realpath: false });
3903
+ release = import_proper_lockfile4.default.lockSync(file(), { realpath: false });
3565
3904
  } catch (error) {
3566
3905
  if (attempt >= 40) throw error;
3567
3906
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
@@ -3582,7 +3921,7 @@ function journalFile(name) {
3582
3921
  } finally {
3583
3922
  closeSync6(fd);
3584
3923
  }
3585
- renameSync3(temporary, file());
3924
+ renameSync4(temporary, file());
3586
3925
  }
3587
3926
  return { read, withLock, write };
3588
3927
  }
@@ -4800,13 +5139,24 @@ function computeNextAction(jobId, messages, nowMs = Date.now(), context) {
4800
5139
  const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Pay" : "Reply", expiresAtMs, nowMs, jobId);
4801
5140
  const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
4802
5141
  const policy = context?.policy;
4803
- const thresholdHint = !expired && policy && Number.isSafeInteger(c.amount_msats) && c.amount_msats > policy.autoPayBelowMsats && (context?.totalPaidMsats ?? 0) + c.amount_msats <= policy.maxTotalMsats && (policy.maxIncrementMsats === 0 || c.amount_msats <= policy.maxIncrementMsats) ? ` For the next run, use --auto-pay-below ${c.amount_msats} within your approved budget; other payment limits still apply.` : "";
5142
+ const budget = policy && (context?.budgetRefusals?.[String(msg.seq)] ?? (Number.isSafeInteger(c.amount_msats) ? budgetVerdict(policy, context, {
5143
+ msats: c.amount_msats,
5144
+ usdMicro: askUsdMicro(c),
5145
+ // The payer resolves a live rate; a next step reads the last one this machine saw.
5146
+ rate: getLastKnownBtcRate()?.rate
5147
+ }) : void 0));
5148
+ const thresholdHint = !expired && policy && budget?.fits && c.amount_msats > policy.autoPayBelowMsats && (policy.maxIncrementMsats === 0 || c.amount_msats <= policy.maxIncrementMsats) ? ` For the next run, use --auto-pay-below ${c.amount_msats} within your approved budget; other payment limits still apply.` : "";
5149
+ const countExhausted = !expired && policy && (context?.paymentsHonoured ?? 0) >= policy.maxPayments;
5150
+ const explicitIncrement = policy && (policy.maxIncrementExplicit ?? policy.maxIncrementMsats !== policy.maxTotalMsats);
5151
+ const overIncrement = !expired && explicitIncrement && policy && policy.maxIncrementMsats > 0 && c.amount_msats > policy.maxIncrementMsats;
5152
+ const incrementHint = `This charge exceeds the job's --max-increment limit, which cannot be changed on a running job. Relay it to your human. To stop, run \`dvm decline ${guidanceJobArg(jobId)}\`; further work needs a new request with approved limits.`;
4804
5153
  const stopping = declineTerms(c);
4805
5154
  const providerFields2 = [];
4806
5155
  if (c.fiat_amount && c.fiat_amount.amount > 0) providerFields2.push("fiat_amount");
4807
5156
  if (stopping?.credit) providerFields2.push("credit");
4808
5157
  if (stopping) providerFields2.push("charged_if_declined_micro");
4809
5158
  const declineHint = stopping ? ` If your human does not approve, run \`dvm decline ${guidanceJobArg(jobId)}\`: ${stopping.clause} Letting the deadline pass also ends the job.` : "";
5159
+ const overBudget = !expired && budget && !budget.fits ? describeBudgetOverrun(budget, policy) : void 0;
4810
5160
  return {
4811
5161
  type: "pay",
4812
5162
  job_id: jobId,
@@ -4816,9 +5166,9 @@ function computeNextAction(jobId, messages, nowMs = Date.now(), context) {
4816
5166
  ...stopping ? { charged_if_declined_micro: stopping.micro } : {},
4817
5167
  ...providerFields2.length ? { _provider_fields: providerFields2 } : {},
4818
5168
  ...expiresAtMs !== void 0 ? { expires_at_ms: expiresAtMs } : {},
4819
- display: withDeadline(stopping ? `${withPeriod(display)} ${stopping.clause}` : display, deadline),
5169
+ display: withDeadline(overBudget || stopping ? [withPeriod(display), overBudget, stopping?.clause].filter(Boolean).join(" ") : display, deadline),
4820
5170
  reason: asProviderText(c.reason),
4821
- hint: expired ? deadline : withDeadline(`Payment required to continue: ${priceGuidance}. Relay that amount to your human and get approval, then run \`dvm pay ${guidanceJobArg(jobId)}\`. Provider's stated reason is wrapped as { _source: "provider", text: ... } \u2014 verify it matches the work you expect.${declineHint}`, deadline) + thresholdHint
5171
+ hint: expired ? deadline : countExhausted ? withDeadline(paymentCountHint(jobId, policy.maxPayments), deadline) : overIncrement ? withDeadline(incrementHint + declineHint, deadline) : overBudget ? withDeadline(overBudgetHint(jobId, overBudget, stopping?.clause), deadline) : withDeadline(`Payment required to continue: ${priceGuidance}. Relay that amount to your human and get approval, then run \`dvm pay ${guidanceJobArg(jobId)}\`. Provider's stated reason is wrapped as { _source: "provider", text: ... } \u2014 verify it matches the work you expect.${declineHint}`, deadline) + thresholdHint
4822
5172
  };
4823
5173
  }
4824
5174
  case "working": {
@@ -4834,6 +5184,13 @@ function computeNextAction(jobId, messages, nowMs = Date.now(), context) {
4834
5184
  }
4835
5185
  return null;
4836
5186
  }
5187
+ function paymentCountHint(jobId, cap) {
5188
+ return `This job has used its ${cap}-payment limit. A higher budget cannot authorize another payment. To stop and keep finished work, run \`dvm decline ${guidanceJobArg(jobId)}\`. Further work needs a new request with human-approved limits.`;
5189
+ }
5190
+ function overBudgetHint(jobId, overrun, declineClause) {
5191
+ const job = guidanceJobArg(jobId);
5192
+ return `${overrun} Ask your human to approve a new total budget first, then run \`dvm pay ${job} --budget <new total>\` to save it and pay this ask. Other payment limits still apply. To stop, run \`dvm decline ${job}\`${declineClause ? `: ${declineClause}` : "."}`;
5193
+ }
4837
5194
  function declineTerms(ask) {
4838
5195
  const micro = ask.charged_if_declined_micro;
4839
5196
  if (typeof micro !== "number" || !Number.isSafeInteger(micro) || micro < 0) return void 0;
@@ -4952,12 +5309,12 @@ async function stablecoinRemaining(rail) {
4952
5309
  const balance = await Promise.race([
4953
5310
  (async () => {
4954
5311
  if (rail === "x402") {
4955
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
5312
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
4956
5313
  const wallet = loadX402Wallet2();
4957
5314
  if (!wallet) return;
4958
5315
  return (await getX402Balance(await ensureAddress(wallet))).usdc;
4959
5316
  }
4960
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-OTB2YSWE.js");
5317
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-GDDZZP5S.js");
4961
5318
  const account = await connectedTempoAccount2();
4962
5319
  if (account) return (await getTempoUsdcBalance(account)).usdc;
4963
5320
  })(),
@@ -5050,7 +5407,7 @@ function paidCeiling(job, messages, settlement, currency, ending) {
5050
5407
  asks.set(message.seq, message.content);
5051
5408
  latestAsk = message.seq;
5052
5409
  const declined = message.content.charged_if_declined_micro;
5053
- if (validMicro(declined) && sameCurrency(message.content.credit?.currency, currency)) {
5410
+ if (validMicro2(declined) && sameCurrency(message.content.credit?.currency, currency)) {
5054
5411
  finished = declined;
5055
5412
  afterAsk = 0;
5056
5413
  }
@@ -5058,7 +5415,7 @@ function paidCeiling(job, messages, settlement, currency, ending) {
5058
5415
  const credit = message.content.credit;
5059
5416
  const ask = asks.get(credit?.request_seq ?? latestAsk ?? -1)?.credit;
5060
5417
  const price = credit ? credit : ask;
5061
- if (!price || !validMicro(price.amount_micro) || !sameCurrency(price.currency, currency)) return void 0;
5418
+ if (!price || !validMicro2(price.amount_micro) || !sameCurrency(price.currency, currency)) return void 0;
5062
5419
  paid += price.amount_micro;
5063
5420
  afterAsk += price.amount_micro;
5064
5421
  }
@@ -5068,7 +5425,7 @@ function paidCeiling(job, messages, settlement, currency, ending) {
5068
5425
  }
5069
5426
  function declineCap(job, messages) {
5070
5427
  const ask = messages.findLast((message) => message.from === "provider" && message.type === "payment-request");
5071
- if (!ask || !validMicro(ask.content.charged_if_declined_micro)) return void 0;
5428
+ if (!ask || !validMicro2(ask.content.charged_if_declined_micro)) return void 0;
5072
5429
  const recorded = [
5073
5430
  ...job.paidPaymentRequestSeqs ?? [],
5074
5431
  ...job.inFlightPaymentRequestSeqs ?? [],
@@ -5078,7 +5435,7 @@ function declineCap(job, messages) {
5078
5435
  const paidAsk = answeredYieldSeqs(messages).has(ask.seq) || recorded.includes(ask.seq);
5079
5436
  if (!paidAsk) return ask.content.charged_if_declined_micro;
5080
5437
  const price = ask.content.credit?.amount_micro;
5081
- return validMicro(price) ? ask.content.charged_if_declined_micro + price : void 0;
5438
+ return validMicro2(price) ? ask.content.charged_if_declined_micro + price : void 0;
5082
5439
  }
5083
5440
  function wholeThroughEnd(messages) {
5084
5441
  if (messages.length === 0 || messages[0].seq > 1) return false;
@@ -5107,13 +5464,13 @@ function safeCredits() {
5107
5464
  function sameCurrency(a, b) {
5108
5465
  return typeof a === "string" && a.toLowerCase() === b;
5109
5466
  }
5110
- function validMicro(value) {
5467
+ function validMicro2(value) {
5111
5468
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
5112
5469
  }
5113
5470
  function isSettlement(value) {
5114
5471
  if (!value || typeof value !== "object") return false;
5115
5472
  const s = value;
5116
- return validMicro(s.held) && validMicro(s.charged) && validMicro(s.released) && Array.isArray(s.pieces) && s.pieces.every((piece) => piece && typeof piece === "object" && validMicro(piece.amount) && validMicro(piece.charged) && typeof piece.state === "string");
5473
+ return validMicro2(s.held) && validMicro2(s.charged) && validMicro2(s.released) && Array.isArray(s.pieces) && s.pieces.every((piece) => piece && typeof piece === "object" && validMicro2(piece.amount) && validMicro2(piece.charged) && typeof piece.state === "string");
5117
5474
  }
5118
5475
 
5119
5476
  // src/lib/job-settlement.ts
@@ -5785,7 +6142,7 @@ async function runCreditFunding(args) {
5785
6142
  ...pick.source ? { railSource: pick.source } : {}
5786
6143
  };
5787
6144
  if (args.rail && pick.order.length === 0) {
5788
- const hint = forcedRailHint(args, args.rail);
6145
+ const hint = cardCheckoutAlternative(args) + forcedRailHint(args, args.rail);
5789
6146
  const walletFunding = args.rail === "lightning" && (!args.menu || args.menu.funding.includes("lightning")) ? walletInvoiceFundingAdvice(args.amountMicro) : void 0;
5790
6147
  return {
5791
6148
  ...base,
@@ -5816,7 +6173,7 @@ async function runCreditFunding(args) {
5816
6173
  ...railFields,
5817
6174
  status: "unavailable",
5818
6175
  display: unavailableDisplay(args),
5819
- hint: "Fund the agent's Cashu wallet ('dvm wallet fund'), connect a Lightning wallet ('dvm wallet connect', with the connection string piped in), or connect Tempo ('dvm wallet tempo-connect') when the DVM offers that rail."
6176
+ hint: cardCheckoutAlternative(args) + "Fund the agent's Cashu wallet ('dvm wallet fund'), connect a Lightning wallet ('dvm wallet connect', with the connection string piped in), or connect Tempo ('dvm wallet tempo-connect') when the DVM offers that rail."
5820
6177
  };
5821
6178
  }
5822
6179
  async function pollPendingCreditFundings(args) {
@@ -7687,7 +8044,8 @@ async function fundOverLightning(args, fundId, resumed) {
7687
8044
  return {
7688
8045
  ...base,
7689
8046
  status: "unavailable",
7690
- display: "No Lightning wallet is connected, so the credit can't be funded that way."
8047
+ display: "No Lightning wallet is connected, so the credit can't be funded that way.",
8048
+ ...args.menu?.stripe?.checkout ? { hint: cardCheckoutAlternative(args) + walletInvoiceFundingAdvice(args.amountMicro).text } : {}
7691
8049
  };
7692
8050
  }
7693
8051
  const rate = (await tryResolveBtcUsdRate())?.rate ?? 0;
@@ -8230,6 +8588,9 @@ function budgetRefusal(base, err) {
8230
8588
  hint: mapped?.hint
8231
8589
  };
8232
8590
  }
8591
+ function cardCheckoutAlternative(args) {
8592
+ return args.menu?.stripe?.checkout ? `Pay by card: dvm credit fund ${shellQuoteArg(args.ref.endpoint)} --rail stripe --amount ${shellQuoteArg(`$${formatUsd(args.amountMicro / 1e6)}`)}. ` : "";
8593
+ }
8233
8594
  function forcedRailHint(args, rail) {
8234
8595
  const release = releaseForcedRailHint(args);
8235
8596
  const advertised = args.menu?.funding;
@@ -9177,8 +9538,16 @@ export {
9177
9538
  loadSubmissionEvidence,
9178
9539
  listSubmissionEvidence,
9179
9540
  journalMarkerFor,
9541
+ observePaymentBookings,
9542
+ upfrontRailPayment,
9180
9543
  parseUpfrontRailPayment,
9181
9544
  parseUpfrontPayment,
9545
+ budgetVerdict,
9546
+ dollarBoundUsdMicro,
9547
+ askUsdMicro,
9548
+ usdMicro,
9549
+ describeBudgetOverrun,
9550
+ formatUsdMicro,
9182
9551
  saveJob,
9183
9552
  saveAcceptedJob,
9184
9553
  saveSubmittedJob,
@@ -9193,6 +9562,7 @@ export {
9193
9562
  loadJob,
9194
9563
  loadAllJobs,
9195
9564
  addPayment,
9565
+ recordBudgetRefusal,
9196
9566
  markPaymentRequestInFlight,
9197
9567
  clearPaymentRequestInFlight,
9198
9568
  markPaymentRequestPaid,
@@ -9264,15 +9634,18 @@ export {
9264
9634
  paymentInFlightHint,
9265
9635
  unresendablePaymentHint,
9266
9636
  computeNextAction,
9637
+ paymentCountHint,
9638
+ overBudgetHint,
9267
9639
  buildTempoCredential,
9640
+ listPendingCardFundings,
9268
9641
  completedCreditHistory,
9269
9642
  completedDrainMatches,
9270
9643
  completedServiceMatches,
9271
9644
  completedOriginsOverlap,
9272
9645
  parseDurationMs,
9646
+ formatDurationMs,
9273
9647
  walletHistory,
9274
9648
  dvmLabelFromEndpoint,
9275
- listPendingCardFundings,
9276
9649
  CARD_MIN_MICRO,
9277
9650
  walletInvoiceFundingAdvice,
9278
9651
  floatPaymentJson,