@dvmkit/dvm-cli 0.18.0 → 0.19.1

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 +8 -0
  2. package/dist/{chunk-ESQ6DCS3.js → chunk-3NXAIRFF.js} +2 -2
  3. package/dist/{chunk-RYFCHR6Z.js → chunk-7HJ5ZR3D.js} +9 -4
  4. package/dist/{chunk-REIUNZQX.js → chunk-B5KW2TPR.js} +2 -2
  5. package/dist/{chunk-DGA5EFKU.js → chunk-DF2OWCRY.js} +6 -6
  6. package/dist/{chunk-OEWENVJ7.js → chunk-MM646MFM.js} +4 -4
  7. package/dist/{chunk-VSOIBYBF.js → chunk-NCX4JVLU.js} +345 -49
  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-PVRLAMI3.js → client-PY4T2DOA.js} +6 -6
  15. package/dist/dvm.js +396 -74
  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-6UL6CHD5.js → pocket-refill-U4VK5WGO.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 +3 -1
  27. package/skills/dvm/credit.md +4 -0
  28. package/skills/dvm/recovery.md +4 -0
  29. package/skills/dvm/wallets.md +3 -1
@@ -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-RYFCHR6Z.js";
29
+ } from "./chunk-7HJ5ZR3D.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";
@@ -1411,6 +1411,7 @@ function fail(mode, refusal) {
1411
1411
  }
1412
1412
 
1413
1413
  // src/lib/card-credit/journal.ts
1414
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
1414
1415
  import { createHash as createHash2 } from "crypto";
1415
1416
  import {
1416
1417
  closeSync,
@@ -1418,13 +1419,98 @@ import {
1418
1419
  fsyncSync,
1419
1420
  openSync,
1420
1421
  readdirSync,
1422
+ renameSync,
1421
1423
  linkSync,
1422
1424
  readFileSync,
1423
1425
  rmSync,
1424
1426
  writeFileSync
1425
1427
  } from "fs";
1426
- import { join } from "path";
1428
+ import { dirname, join } from "path";
1427
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
+ }
1428
1514
  function sha256Hex(value) {
1429
1515
  return createHash2("sha256").update(value, "utf8").digest("hex");
1430
1516
  }
@@ -1486,7 +1572,7 @@ function readEntry(path) {
1486
1572
  if (!existsSync(path)) return void 0;
1487
1573
  try {
1488
1574
  const parsed = JSON.parse(readFileSync(path, "utf8"));
1489
- 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") {
1490
1576
  return void 0;
1491
1577
  }
1492
1578
  return parsed;
@@ -1505,6 +1591,145 @@ function fsyncDirectory(path) {
1505
1591
  }
1506
1592
  }
1507
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
+
1508
1733
  // src/lib/card-credit/fund.ts
1509
1734
  var CARD_MIN_MICRO = 5e5;
1510
1735
  var MICRO_PER_CENT = 1e4;
@@ -1527,6 +1752,12 @@ function pendingCardFundingForCredit(args) {
1527
1752
  }
1528
1753
  async function fundOverStripe(args, fundId, deps) {
1529
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
+ }
1530
1761
  if (journalled) return resumeCardFunding(args, journalled, deps);
1531
1762
  const base = { creditId: args.creditId, fundId, rail: "stripe" };
1532
1763
  if (args.menu && !args.menu.funding.includes("stripe")) {
@@ -1683,11 +1914,12 @@ async function present(args, pending, credential, deps, history) {
1683
1914
  }
1684
1915
  async function booked(args, pending, outcome) {
1685
1916
  await recordCardSpend(args, pending);
1686
- clearPendingCardFunding(pending);
1917
+ if (pending.v === 2) await retireCheckoutFunding(pending);
1918
+ else clearPendingCardFunding(pending);
1687
1919
  return {
1688
1920
  ...outcome,
1689
1921
  chargedMicro: pending.amountMicro,
1690
- 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"}.`,
1691
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()
1692
1924
  };
1693
1925
  }
@@ -2494,9 +2726,9 @@ function notifyPaymentBooked(booking) {
2494
2726
  }
2495
2727
 
2496
2728
  // src/lib/job-store.ts
2497
- import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3, renameSync, openSync as openSync3, closeSync as closeSync3, fsyncSync as fsyncSync3 } from "fs";
2498
- var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
2499
- 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";
2500
2732
 
2501
2733
  // src/lib/upfront-payment.ts
2502
2734
  function upfrontRailPayment(method, amountMsats, usdMicro2) {
@@ -2854,9 +3086,9 @@ function writeJobs(jobs) {
2854
3086
  } finally {
2855
3087
  closeSync3(fd);
2856
3088
  }
2857
- renameSync(temporary, JOBS_FILE);
3089
+ renameSync2(temporary, JOBS_FILE);
2858
3090
  if (process.platform !== "win32") {
2859
- const directory = openSync3(dirname(JOBS_FILE), "r");
3091
+ const directory = openSync3(dirname2(JOBS_FILE), "r");
2860
3092
  try {
2861
3093
  fsyncSync3(directory);
2862
3094
  } finally {
@@ -2869,7 +3101,7 @@ function acquireJobsLock() {
2869
3101
  const deadline = performance.now() + 1e3;
2870
3102
  for (let attempt = 0; ; attempt++) {
2871
3103
  try {
2872
- return import_proper_lockfile.default.lockSync(JOBS_FILE, { realpath: false });
3104
+ return import_proper_lockfile2.default.lockSync(JOBS_FILE, { realpath: false });
2873
3105
  } catch (error) {
2874
3106
  if (error.code !== "ELOCKED" || attempt >= 40 || performance.now() >= deadline) throw error;
2875
3107
  Atomics.wait(lockWait, 0, 0, Math.min(25, Math.max(0, deadline - performance.now())));
@@ -3047,19 +3279,19 @@ function bookCreditPayment(jobId, intent) {
3047
3279
  }
3048
3280
 
3049
3281
  // src/lib/favorites.ts
3050
- var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
3282
+ var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
3051
3283
  import {
3052
3284
  closeSync as closeSync4,
3053
3285
  fchmodSync,
3054
3286
  fsyncSync as fsyncSync4,
3055
3287
  openSync as openSync4,
3056
3288
  readFileSync as readFileSync4,
3057
- renameSync as renameSync2,
3289
+ renameSync as renameSync3,
3058
3290
  statSync,
3059
3291
  unlinkSync as unlinkSync2,
3060
3292
  writeFileSync as writeFileSync4
3061
3293
  } from "fs";
3062
- import { dirname as dirname2 } from "path";
3294
+ import { dirname as dirname3 } from "path";
3063
3295
  var DEFAULT_FILE_MODE = 384;
3064
3296
  function loadFavorites() {
3065
3297
  let raw;
@@ -3127,7 +3359,7 @@ async function withFavoritesLock(fn) {
3127
3359
  ensureConfigDir();
3128
3360
  let release;
3129
3361
  try {
3130
- release = await import_proper_lockfile2.default.lock(FAVORITES_FILE, {
3362
+ release = await import_proper_lockfile3.default.lock(FAVORITES_FILE, {
3131
3363
  lockfilePath: `${FAVORITES_FILE}.lock`,
3132
3364
  realpath: false,
3133
3365
  stale: 3e4,
@@ -3158,8 +3390,8 @@ function writeFavorites(favorites) {
3158
3390
  fsyncSync4(fd);
3159
3391
  closeSync4(fd);
3160
3392
  fd = void 0;
3161
- renameSync2(temporary, FAVORITES_FILE);
3162
- fsyncDirectory3(dirname2(FAVORITES_FILE));
3393
+ renameSync3(temporary, FAVORITES_FILE);
3394
+ fsyncDirectory3(dirname3(FAVORITES_FILE));
3163
3395
  } catch (error) {
3164
3396
  if (fd !== void 0) {
3165
3397
  try {
@@ -3648,11 +3880,11 @@ function providerJobJson(data, providerJob = true) {
3648
3880
  }
3649
3881
 
3650
3882
  // src/lib/wallet-agent/journal-file.ts
3651
- var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
3652
- import { closeSync as closeSync6, existsSync as existsSync5, fsyncSync as fsyncSync5, openSync as openSync6, readFileSync as readFileSync6, renameSync as renameSync3, writeFileSync as writeFileSync5 } from "fs";
3653
- 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";
3654
3886
  function journalFile(name) {
3655
- const file = () => join4(dirname3(JOBS_FILE), name);
3887
+ const file = () => join4(dirname4(JOBS_FILE), name);
3656
3888
  function read() {
3657
3889
  if (!existsSync5(file())) return [];
3658
3890
  try {
@@ -3668,7 +3900,7 @@ function journalFile(name) {
3668
3900
  let release;
3669
3901
  for (let attempt = 0; !release; attempt++) {
3670
3902
  try {
3671
- release = import_proper_lockfile3.default.lockSync(file(), { realpath: false });
3903
+ release = import_proper_lockfile4.default.lockSync(file(), { realpath: false });
3672
3904
  } catch (error) {
3673
3905
  if (attempt >= 40) throw error;
3674
3906
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
@@ -3689,7 +3921,7 @@ function journalFile(name) {
3689
3921
  } finally {
3690
3922
  closeSync6(fd);
3691
3923
  }
3692
- renameSync3(temporary, file());
3924
+ renameSync4(temporary, file());
3693
3925
  }
3694
3926
  return { read, withLock, write };
3695
3927
  }
@@ -5077,12 +5309,12 @@ async function stablecoinRemaining(rail) {
5077
5309
  const balance = await Promise.race([
5078
5310
  (async () => {
5079
5311
  if (rail === "x402") {
5080
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
5312
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
5081
5313
  const wallet = loadX402Wallet2();
5082
5314
  if (!wallet) return;
5083
5315
  return (await getX402Balance(await ensureAddress(wallet))).usdc;
5084
5316
  }
5085
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-OTB2YSWE.js");
5317
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-GDDZZP5S.js");
5086
5318
  const account = await connectedTempoAccount2();
5087
5319
  if (account) return (await getTempoUsdcBalance(account)).usdc;
5088
5320
  })(),
@@ -5910,7 +6142,7 @@ async function runCreditFunding(args) {
5910
6142
  ...pick.source ? { railSource: pick.source } : {}
5911
6143
  };
5912
6144
  if (args.rail && pick.order.length === 0) {
5913
- const hint = forcedRailHint(args, args.rail);
6145
+ const hint = cardCheckoutAlternative(args) + forcedRailHint(args, args.rail);
5914
6146
  const walletFunding = args.rail === "lightning" && (!args.menu || args.menu.funding.includes("lightning")) ? walletInvoiceFundingAdvice(args.amountMicro) : void 0;
5915
6147
  return {
5916
6148
  ...base,
@@ -5941,7 +6173,7 @@ async function runCreditFunding(args) {
5941
6173
  ...railFields,
5942
6174
  status: "unavailable",
5943
6175
  display: unavailableDisplay(args),
5944
- 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."
5945
6177
  };
5946
6178
  }
5947
6179
  async function pollPendingCreditFundings(args) {
@@ -7812,7 +8044,8 @@ async function fundOverLightning(args, fundId, resumed) {
7812
8044
  return {
7813
8045
  ...base,
7814
8046
  status: "unavailable",
7815
- 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 } : {}
7816
8049
  };
7817
8050
  }
7818
8051
  const rate = (await tryResolveBtcUsdRate())?.rate ?? 0;
@@ -8355,6 +8588,9 @@ function budgetRefusal(base, err) {
8355
8588
  hint: mapped?.hint
8356
8589
  };
8357
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
+ }
8358
8594
  function forcedRailHint(args, rail) {
8359
8595
  const release = releaseForcedRailHint(args);
8360
8596
  const advertised = args.menu?.funding;
@@ -8969,6 +9205,9 @@ function fundTimeoutMs() {
8969
9205
  if (!Number.isFinite(n) || n <= 0) return DEFAULT_TIMEOUT_SEC * 1e3;
8970
9206
  return Math.floor(n) * 1e3;
8971
9207
  }
9208
+ function withoutPendingMint(wallet, quoteId) {
9209
+ return { ...wallet, pending_mints: wallet.pending_mints.filter((p) => p.quote_id !== quoteId) };
9210
+ }
8972
9211
  function upsertPending(wallet, entry) {
8973
9212
  const others = wallet.pending_mints.filter((p) => p.quote_id !== entry.quote_id);
8974
9213
  return { ...wallet, pending_mints: [...others, entry] };
@@ -9130,18 +9369,19 @@ async function findFundableAlternatives(configured, skip, sats) {
9130
9369
 
9131
9370
  // src/lib/wallet-agent/recovery.ts
9132
9371
  var DEFAULT_SWEEP_QUOTE_RETRY_TIMEOUT_MS = 1e4;
9372
+ var MINT_QUOTE_EXPIRY_GRACE_MS = 24 * 60 * 60 * 1e3;
9133
9373
  async function sweepPendingMints(opts = {}) {
9134
9374
  const wallet = loadAgentWallet();
9135
9375
  if (!wallet || wallet.pending_mints.length === 0) {
9136
- return { outcomes: [], recovered_proofs: [], still_pending: [], errors: [] };
9376
+ return { outcomes: [], recovered_proofs: [], still_pending: [], refused: [], errors: [] };
9137
9377
  }
9138
9378
  const now = opts.now ?? (() => Date.now());
9139
- const expirationMs = opts.expirationMs ?? fundTimeoutMs();
9379
+ const expiryGraceMs = opts.expiryGraceMs ?? MINT_QUOTE_EXPIRY_GRACE_MS;
9140
9380
  const getWalletForMint = opts.getWalletForMint ?? getWallet;
9141
9381
  const quoteRetryTimeoutMs = opts.quoteRetryTimeoutMs ?? DEFAULT_SWEEP_QUOTE_RETRY_TIMEOUT_MS;
9142
9382
  const outcomes = [];
9143
9383
  for (const entry of wallet.pending_mints) {
9144
- const outcome = await processEntry(wallet, entry, now(), expirationMs, getWalletForMint, {
9384
+ const outcome = await processEntry(wallet, entry, now(), expiryGraceMs, getWalletForMint, {
9145
9385
  now,
9146
9386
  sleep: opts.sleep,
9147
9387
  timeoutMs: quoteRetryTimeoutMs
@@ -9165,10 +9405,11 @@ async function sweepPendingMints(opts = {}) {
9165
9405
  still_pending: outcomes.filter(
9166
9406
  (o) => o.kind === "still_pending"
9167
9407
  ).map((o) => o.entry),
9408
+ refused: outcomes.filter((o) => o.kind === "paid_refused").map((o) => o.entry),
9168
9409
  errors: outcomes.filter((o) => o.kind === "error").map((o) => ({ quote_id: o.entry.quote_id, error: o.error }))
9169
9410
  };
9170
9411
  }
9171
- async function processEntry(wallet, entry, nowMs, expirationMs, getWalletForMint, retry) {
9412
+ async function processEntry(wallet, entry, nowMs, expiryGraceMs, getWalletForMint, retry) {
9172
9413
  let cashuWallet;
9173
9414
  let quoteResponse;
9174
9415
  try {
@@ -9186,6 +9427,15 @@ async function processEntry(wallet, entry, nowMs, expirationMs, getWalletForMint
9186
9427
  }
9187
9428
  ));
9188
9429
  } catch (err) {
9430
+ const refusal = mintQuoteRefusal(err);
9431
+ if (refusal !== void 0) {
9432
+ return finalAnswer(
9433
+ wallet,
9434
+ entry,
9435
+ refusal === "unknown" ? "mint_unknown" : "mint_expired",
9436
+ () => getWalletForMint(entry.mint)
9437
+ );
9438
+ }
9189
9439
  return { kind: "error", entry, error: errorMessage(err) };
9190
9440
  }
9191
9441
  const state = quoteResponse.state;
@@ -9239,29 +9489,72 @@ async function processEntry(wallet, entry, nowMs, expirationMs, getWalletForMint
9239
9489
  const agentProofs = proofs.map((p) => toAgentProof(p, entry.mint, wallet.lock_pubkey));
9240
9490
  return { kind: "minted", entry, proofs: agentProofs };
9241
9491
  } catch (err) {
9492
+ if (mintQuoteRefusal(err) === "expired") {
9493
+ return { kind: "paid_refused", entry, reason: "quote_expired" };
9494
+ }
9242
9495
  return { kind: "error", entry, error: errorMessage(err) };
9243
9496
  }
9244
9497
  }
9498
+ if (state === "EXPIRED") {
9499
+ return finalAnswer(wallet, entry, "mint_expired", async () => cashuWallet);
9500
+ }
9245
9501
  const quoteExpiry = entry.expires_at;
9246
- if (quoteExpiry !== void 0 && Number.isFinite(quoteExpiry)) {
9247
- if (nowMs > quoteExpiry * 1e3) {
9248
- return { kind: "expired", entry };
9249
- }
9502
+ if (quoteExpiry === void 0 || !Number.isFinite(quoteExpiry)) {
9503
+ return { kind: "still_pending", entry };
9504
+ }
9505
+ const expiredAtMs = quoteExpiry * 1e3;
9506
+ if (nowMs <= expiredAtMs) {
9250
9507
  return { kind: "still_pending", entry };
9251
9508
  }
9252
- const requestedAtMs = Date.parse(entry.requested_at);
9253
- const ageMs = Number.isFinite(requestedAtMs) ? nowMs - requestedAtMs : Infinity;
9254
- if (ageMs > expirationMs) {
9255
- return { kind: "expired", entry };
9509
+ const dropAfterMs = expiredAtMs + expiryGraceMs;
9510
+ if (nowMs > dropAfterMs) {
9511
+ return finalAnswer(wallet, entry, "grace_elapsed", async () => cashuWallet);
9256
9512
  }
9257
- return { kind: "still_pending", entry };
9513
+ return {
9514
+ kind: "still_pending",
9515
+ entry,
9516
+ past_expiry: { expired_at_ms: expiredAtMs, drop_after_ms: dropAfterMs }
9517
+ };
9518
+ }
9519
+ async function finalAnswer(wallet, entry, reason, getCashuWallet) {
9520
+ if (!entry.minting) return { kind: "expired", entry, reason };
9521
+ try {
9522
+ const restored = await restoreFromMintingState(
9523
+ await getCashuWallet(),
9524
+ entry.minting,
9525
+ wallet.lock_pubkey,
9526
+ entry.mint
9527
+ );
9528
+ if (restored.length > 0) return { kind: "restored", entry, proofs: restored };
9529
+ } catch (err) {
9530
+ return { kind: "error", entry, error: errorMessage(err) };
9531
+ }
9532
+ if (reason === "mint_expired") return { kind: "paid_refused", entry, reason: "quote_expired" };
9533
+ return {
9534
+ kind: "error",
9535
+ entry,
9536
+ error: reason === "mint_unknown" ? "The mint reported this quote paid earlier and no longer knows it; nothing could be restored, so the quote is kept." : "The mint reported this quote paid earlier and now reports it unpaid; nothing could be restored, so the quote is kept."
9537
+ };
9538
+ }
9539
+ var MINT_QUOTE_EXPIRED_CODE = 20007;
9540
+ var QUOTE_UNKNOWN_TEXT = /\bquote\b[^.]*\b(not found|unknown|does not exist)\b|\b(unknown|no such) quote\b/i;
9541
+ var QUOTE_EXPIRED_TEXT = /\bquote\b[^.]*\bexpired\b|\bexpired quote\b/i;
9542
+ function mintQuoteRefusal(err) {
9543
+ if (typeof err !== "object" || err === null) return void 0;
9544
+ const { name, status, code, message } = err;
9545
+ const answered = name === "MintOperationError" && status === 400 && typeof code === "number";
9546
+ if (!answered) return void 0;
9547
+ const text = typeof message === "string" ? message : "";
9548
+ if (code === MINT_QUOTE_EXPIRED_CODE || QUOTE_EXPIRED_TEXT.test(text)) return "expired";
9549
+ if (QUOTE_UNKNOWN_TEXT.test(text)) return "unknown";
9550
+ return void 0;
9258
9551
  }
9259
9552
  async function restoreFromMintingState(cashuWallet, minting, lockPubkey, mintUrl) {
9260
9553
  const proofs = await restoreProofsFromOutputs(cashuWallet, minting.keyset_id, minting.outputs);
9261
9554
  return proofs.map((proof) => toAgentProof(proof, mintUrl, lockPubkey));
9262
9555
  }
9263
9556
  function applyOutcome(wallet, outcome) {
9264
- if (outcome.kind === "still_pending" || outcome.kind === "error") {
9557
+ if (outcome.kind === "still_pending" || outcome.kind === "paid_refused" || outcome.kind === "error") {
9265
9558
  return wallet;
9266
9559
  }
9267
9560
  const next = {
@@ -9401,6 +9694,7 @@ export {
9401
9694
  paymentCountHint,
9402
9695
  overBudgetHint,
9403
9696
  buildTempoCredential,
9697
+ listPendingCardFundings,
9404
9698
  completedCreditHistory,
9405
9699
  completedDrainMatches,
9406
9700
  completedServiceMatches,
@@ -9409,7 +9703,6 @@ export {
9409
9703
  formatDurationMs,
9410
9704
  walletHistory,
9411
9705
  dvmLabelFromEndpoint,
9412
- listPendingCardFundings,
9413
9706
  CARD_MIN_MICRO,
9414
9707
  walletInvoiceFundingAdvice,
9415
9708
  floatPaymentJson,
@@ -9483,8 +9776,11 @@ export {
9483
9776
  createPendingMintQuote,
9484
9777
  fundAgentWallet,
9485
9778
  fundTimeoutMs,
9779
+ withoutPendingMint,
9486
9780
  pollUntilPaidOrTimeout,
9487
9781
  resolveFundMint,
9488
9782
  describeMintBounds,
9489
- sweepPendingMints
9783
+ MINT_QUOTE_EXPIRY_GRACE_MS,
9784
+ sweepPendingMints,
9785
+ mintQuoteRefusal
9490
9786
  };