@dvmkit/dvm-cli 0.13.0 → 0.15.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 (28) hide show
  1. package/dist/{chunk-GWLOO5XD.js → chunk-2MCZ4QOK.js} +2 -2
  2. package/dist/{chunk-C2BJETRG.js → chunk-57PXJ56K.js} +4 -4
  3. package/dist/{chunk-PS4AUWK3.js → chunk-D5CGDS3V.js} +2 -2
  4. package/dist/{chunk-ZDWZT6NA.js → chunk-EZL4IVCU.js} +3 -3
  5. package/dist/{chunk-I2C3YEUN.js → chunk-HJ2JYBTT.js} +4 -4
  6. package/dist/{chunk-CCF4QONY.js → chunk-HXTASGHL.js} +2 -2
  7. package/dist/{chunk-C2EZ3VY2.js → chunk-I7ZBID4L.js} +2 -2
  8. package/dist/{chunk-RPM5XEVS.js → chunk-LPILVPFG.js} +15 -3
  9. package/dist/{chunk-ZV57FFIL.js → chunk-UCCT5IKU.js} +9 -1
  10. package/dist/{chunk-KQQALLOL.js → chunk-UWVMG4VG.js} +3 -3
  11. package/dist/{chunk-SEJWBDGY.js → chunk-YQJRKWNT.js} +1739 -788
  12. package/dist/{chunk-NLUOHCX2.js → chunk-ZKC6KN36.js} +339 -53
  13. package/dist/{client-6JRGRKFQ.js → client-RSHQFXCA.js} +6 -6
  14. package/dist/dvm.js +858 -599
  15. package/dist/{internal-KPPGYK5N.js → internal-O7IQD6EQ.js} +5 -5
  16. package/dist/{lifecycle-7YRNRLDQ.js → lifecycle-MIJH3JE4.js} +6 -6
  17. package/dist/{payout-reporter-KTLBNJJ7-WDT6M4GN.js → payout-reporter-Y6OW3FYD-K6MRWQXK.js} +2 -2
  18. package/dist/{pocket-refill-E2QVQDME.js → pocket-refill-7Q6CR6I4.js} +10 -10
  19. package/dist/{revenue-reporter-FD3GDQZS-COUBEUDN.js → revenue-reporter-CIG2MEDN-ZXMO6NWG.js} +2 -2
  20. package/dist/{tempo-lifecycle-EOP5IHJT.js → tempo-lifecycle-FMBCHD2M.js} +8 -8
  21. package/dist/{tempo-wallet-4A5M3FVO.js → tempo-wallet-U3WBWIIH.js} +7 -7
  22. package/dist/{wallet-LASVQ72F.js → wallet-Z3FDX43V.js} +7 -7
  23. package/dist/{x402-MFBRORHG-34VE7EWO.js → x402-ARXZQ5BD-H6PNJYYT.js} +2 -2
  24. package/package.json +4 -2
  25. package/skills/dvm/SKILL.md +2 -0
  26. package/skills/dvm/calling.md +12 -1
  27. package/skills/dvm/credit.md +3 -1
  28. package/skills/dvm/recovery.md +52 -0
@@ -3,8 +3,9 @@ import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
5
  connectedTempoAccount
6
- } from "./chunk-I2C3YEUN.js";
6
+ } from "./chunk-HJ2JYBTT.js";
7
7
  import {
8
+ addOutputWarnings,
8
9
  costAnchor,
9
10
  formatAmount,
10
11
  formatPaymentAmount,
@@ -15,15 +16,15 @@ import {
15
16
  resolveBtcUsdRate,
16
17
  tryResolveBtcUsdRate,
17
18
  tryX402Payment
18
- } from "./chunk-RPM5XEVS.js";
19
+ } from "./chunk-LPILVPFG.js";
19
20
  import {
20
21
  loadX402Wallet,
21
22
  x402NetworkLabel
22
- } from "./chunk-KQQALLOL.js";
23
+ } from "./chunk-UWVMG4VG.js";
23
24
  import {
24
25
  isCreditPosture,
25
26
  loadConfig
26
- } from "./chunk-GWLOO5XD.js";
27
+ } from "./chunk-2MCZ4QOK.js";
27
28
  import {
28
29
  BUDGET_FILE,
29
30
  CONFIG_DIR,
@@ -75,6 +76,7 @@ import {
75
76
  ensureConfigSubdir,
76
77
  entryKind,
77
78
  findX402Channel,
79
+ formatFiat,
78
80
  formatUsd,
79
81
  fundingModeForTempoIntent,
80
82
  fundingModeForX402Flavour,
@@ -178,7 +180,7 @@ import {
178
180
  x402PendingUnsettled,
179
181
  x402RequiredFromError,
180
182
  x402VoucherPendingState
181
- } from "./chunk-SEJWBDGY.js";
183
+ } from "./chunk-YQJRKWNT.js";
182
184
  import {
183
185
  Challenge_exports,
184
186
  Credential_exports
@@ -197,7 +199,7 @@ import {
197
199
  redactUrlsInText,
198
200
  usdToMsats,
199
201
  x402NetworkToCaip2
200
- } from "./chunk-C2BJETRG.js";
202
+ } from "./chunk-57PXJ56K.js";
201
203
  import {
202
204
  privateKeyToAccount
203
205
  } from "./chunk-EVQERRCP.js";
@@ -1773,7 +1775,7 @@ async function approvalSteps(args, base, deps) {
1773
1775
  "--spt -"
1774
1776
  ].join(" ");
1775
1777
  const display = `This is a card top-up of $${usd(args.amountMicro)}, so it has to be approved in Stripe Link first. Nothing has been charged. The card is charged when the approved top-up is sent to the DVM, and any credit left unspent can be refunded to the card later, less its share of Stripe's processing fee.`;
1776
- const hint = `Run '${create}' and ask your human to approve it in Link (they have 30 minutes). Then run '${retrieve}' with the spend request id the first command printed, and pipe the shared_payment_token.id value from its JSON into '${fund}': that command charges the card. Never pay this with 'link-cli mpp pay': a signed dvm request expires long before an approval arrives.`;
1778
+ const hint = `Run '${create}' and ask your human to approve it in Link (they have 30 minutes). Then run '${retrieve}' with the spend request id the first command printed, and pipe the shared_payment_token.id value from its JSON into '${fund}': that command charges the card. Never pay this with 'link-cli mpp pay': a signed dvm request expires long before an approval arrives. Link connects agents only in some regions (the US and Canada as of November 2026). If Link says your region isn't supported, fund over another rail with --rail.`;
1777
1779
  return {
1778
1780
  ...base,
1779
1781
  status: "unavailable",
@@ -2471,8 +2473,17 @@ function loadAnsweredYieldSeqs(jobId) {
2471
2473
  const job = loadJob(jobId);
2472
2474
  for (const seq of job?.paidPaymentRequestSeqs ?? []) answered.add(seq);
2473
2475
  for (const payment of job?.bookedCreditPayments ?? []) answered.add(payment.authorization.request_seq);
2476
+ if (job?.callerDeclined) for (const seq of declinedYieldSeqs(loadMessages(jobId))) answered.add(seq);
2474
2477
  return answered;
2475
2478
  }
2479
+ function declinedYieldSeqs(messages) {
2480
+ const sorted = [...messages].sort((a, b) => a.seq - b.seq);
2481
+ const decline = sorted.findLast((message) => message.from === "requester" && message.type === "decline");
2482
+ if (!decline) return [];
2483
+ const before = sorted.filter((message) => message.from === "provider" && message.seq < decline.seq);
2484
+ const ask = before.findLast((message) => message.type === "payment-request");
2485
+ return [...ask ? [ask.seq] : [], ...before.filter((message) => message.type === "prompt").map((message) => message.seq)];
2486
+ }
2476
2487
  async function reconcileInFlightPaymentRequest(jobId, requestSeq, transport, provider, options) {
2477
2488
  const boundedOptions = { ...options, timeoutMs: options.timeoutMs ?? JOB_READ_TIMEOUT_MS };
2478
2489
  const history = await boundedPaymentRead(jobId, () => transport.getMessages(jobId, 0, provider, boundedOptions), boundedOptions.timeoutMs);
@@ -2593,17 +2604,24 @@ function computeNextAction(jobId, messages, nowMs = Date.now(), context) {
2593
2604
  const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
2594
2605
  const policy = context?.policy;
2595
2606
  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.` : "";
2607
+ const stopping = declineTerms(c);
2608
+ const providerFields2 = [];
2609
+ if (c.fiat_amount && c.fiat_amount.amount > 0) providerFields2.push("fiat_amount");
2610
+ if (stopping?.credit) providerFields2.push("credit");
2611
+ if (stopping) providerFields2.push("charged_if_declined_micro");
2612
+ const declineHint = stopping ? ` If your human does not approve, run \`dvm decline ${guidanceJobArg(jobId)}\`: ${stopping.clause} Letting the deadline pass also ends the job.` : "";
2596
2613
  return {
2597
2614
  type: "pay",
2598
2615
  job_id: jobId,
2599
2616
  amount_msats: c.amount_msats,
2600
- // Mirror only a fiat figure the display actually led with: echoing a
2601
- // zero amount would tell an agent doing budget math the charge is free.
2602
- ...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount, _provider_fields: ["fiat_amount"] } : {},
2617
+ ...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount } : {},
2618
+ ...stopping?.credit ? { credit: stopping.credit } : {},
2619
+ ...stopping ? { charged_if_declined_micro: stopping.micro } : {},
2620
+ ...providerFields2.length ? { _provider_fields: providerFields2 } : {},
2603
2621
  ...expiresAtMs !== void 0 ? { expires_at_ms: expiresAtMs } : {},
2604
- display: withDeadline(display, deadline),
2622
+ display: withDeadline(stopping ? `${withPeriod(display)} ${stopping.clause}` : display, deadline),
2605
2623
  reason: asProviderText(c.reason),
2606
- 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.`, deadline) + thresholdHint
2624
+ 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
2607
2625
  };
2608
2626
  }
2609
2627
  case "working": {
@@ -2619,6 +2637,18 @@ function computeNextAction(jobId, messages, nowMs = Date.now(), context) {
2619
2637
  }
2620
2638
  return null;
2621
2639
  }
2640
+ function declineTerms(ask) {
2641
+ const micro = ask.charged_if_declined_micro;
2642
+ if (typeof micro !== "number" || !Number.isSafeInteger(micro) || micro < 0) return void 0;
2643
+ const price = ask.credit;
2644
+ const credit = price && Number.isSafeInteger(price.amount_micro) && price.amount_micro >= 0 && typeof price.currency === "string" ? { amount_micro: price.amount_micro, currency: price.currency } : void 0;
2645
+ const amount = credit && /^[A-Z]{3}$/i.test(credit.currency) ? formatFiat(micro / 1e6, credit.currency) : void 0;
2646
+ const clause = micro === 0 ? "Declining ends the job with no charge for finished work." : amount ? `Declining ends the job and charges ${amount} for the work already finished.` : "Declining ends the job and charges for the work already finished (next_action.charged_if_declined_micro).";
2647
+ return { micro, ...credit ? { credit } : {}, clause };
2648
+ }
2649
+ function withPeriod(text) {
2650
+ return /[.!?]$/.test(text) ? text : `${text}.`;
2651
+ }
2622
2652
  function pendingDeadline(messages, answered) {
2623
2653
  const prompts = /* @__PURE__ */ new Map();
2624
2654
  let payment;
@@ -2656,6 +2686,143 @@ function deadlineClause(action, expiresAtMs, nowMs, jobId) {
2656
2686
  return `${action} by ${deadline} (in ${remaining}), or the provider cancels the job.`;
2657
2687
  }
2658
2688
 
2689
+ // src/lib/piece-settlement.ts
2690
+ function pieceSettlement(receipt, context = {}) {
2691
+ const settlement = receipt.settlement;
2692
+ if (!isSettlement(settlement)) return void 0;
2693
+ const job = context.job ?? void 0;
2694
+ const messages = [...context.messages ?? []].sort((a, b) => a.seq - b.seq);
2695
+ const currency = settlementCurrency(receipt, job, messages, context.currency);
2696
+ const stopped = settlement.pieces.filter((piece) => piece.state === "stopped").reduce((sum, piece) => sum + piece.charged, 0);
2697
+ const callerStop = receipt.outcome === "cancelled" && !job?.callerDeclined && (job?.callerCancelled === true || receipt.ended_by === "caller");
2698
+ const ending = receipt.outcome === "completed" ? "finish" : callerStop ? "stop" : "release";
2699
+ const paid = currency && job && context.messages !== void 0 && settlement.pieces.length > 0 ? paidCeiling(job, messages, settlement, currency, ending) : void 0;
2700
+ const listed = settlement.pieces.length > 0 ? settlement.pieces.filter((piece) => piece.state === "finished" || piece.state === "stopped").reduce((sum, piece) => sum + Math.min(piece.charged, piece.amount), 0) : void 0;
2701
+ const declined = ending === "release" && job ? declineCap(job, messages) : void 0;
2702
+ const bounds = [["payments", paid], ["declined_ask", declined], ["receipt_pieces", listed]].filter((entry) => entry[1] !== void 0);
2703
+ const lowest = bounds.reduce(
2704
+ (best, entry) => best === void 0 || entry[1] < best[1] ? entry : best,
2705
+ void 0
2706
+ );
2707
+ const basis = lowest?.[0];
2708
+ const ceiling = lowest?.[1];
2709
+ const overcharged = ceiling !== void 0 && settlement.charged > ceiling;
2710
+ const money = (micro) => formatMicro(micro, currency);
2711
+ let display = `Charged ${money(settlement.charged)} of ${money(settlement.held)} held, ${money(settlement.released)} released.`;
2712
+ if (overcharged) display += ` ${overchargeClause(basis, money(ceiling))}`;
2713
+ return {
2714
+ held_micro: settlement.held,
2715
+ charged_micro: settlement.charged,
2716
+ released_micro: settlement.released,
2717
+ stopped_micro: stopped,
2718
+ currency,
2719
+ ...ceiling !== void 0 ? { ceiling_micro: ceiling, ceiling_basis: basis } : {},
2720
+ overcharged,
2721
+ display
2722
+ };
2723
+ }
2724
+ function overchargeClause(basis, ceiling) {
2725
+ return basis === "payments" ? `This charge exceeds the finished pieces this CLI paid for (at most ${ceiling}).` : basis === "declined_ask" ? `This charge exceeds what the job's last ask said stopping would cost (at most ${ceiling}).` : `This charge exceeds what the receipt's own pieces add up to (${ceiling}).`;
2726
+ }
2727
+ function formatMicro(micro, currency) {
2728
+ if (currency) return formatFiat(micro / 1e6, currency);
2729
+ const units = (micro / 1e6).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 6 });
2730
+ return `${units} ${UNKNOWN_CURRENCY_LABEL}`;
2731
+ }
2732
+ var UNKNOWN_CURRENCY_LABEL = "(currency not recorded)";
2733
+ function settlementCurrencyHint(settlement, endpoint) {
2734
+ return settlement?.charged_micro !== void 0 && !settlement.currency ? unknownCurrencyHint(endpoint) : void 0;
2735
+ }
2736
+ function unknownCurrencyHint(endpoint) {
2737
+ const describe = endpoint ? `'dvm describe ${endpoint}'` : "'dvm describe <endpoint>'";
2738
+ return `This receipt does not name the currency it was charged in, and no local record of the job's prices or of its credit names one this CLI can show. The amounts are in the provider's credit currency: for a US-dollar credit, 2.06 means $2.06. Run ${describe} to see which currency this DVM's credits use.`;
2739
+ }
2740
+ function paidCeiling(job, messages, settlement, currency, ending) {
2741
+ let upfront = 0;
2742
+ if (job.upfrontPayment?.amount_micro !== void 0) {
2743
+ if (!sameCurrency(job.upfrontPayment.currency, currency)) return void 0;
2744
+ upfront = job.upfrontPayment.amount_micro;
2745
+ } else if (job.upfrontPayment || settlement.pieces.some((piece) => piece.paid_seq === 0)) {
2746
+ return void 0;
2747
+ }
2748
+ const logged = new Set(messages.filter((message) => message.from === "requester" && message.type === "payment").map((message) => message.seq));
2749
+ if (!wholeThroughEnd(messages) && settlement.pieces.some((piece) => piece.paid_seq !== 0 && !logged.has(piece.paid_seq))) return void 0;
2750
+ let paid = upfront;
2751
+ let finished;
2752
+ let afterAsk = upfront;
2753
+ const asks = /* @__PURE__ */ new Map();
2754
+ let latestAsk;
2755
+ for (const message of messages) {
2756
+ if (message.from === "provider" && message.type === "payment-request") {
2757
+ asks.set(message.seq, message.content);
2758
+ latestAsk = message.seq;
2759
+ const declined = message.content.charged_if_declined_micro;
2760
+ if (validMicro(declined) && sameCurrency(message.content.credit?.currency, currency)) {
2761
+ finished = declined;
2762
+ afterAsk = 0;
2763
+ }
2764
+ } else if (message.from === "requester" && message.type === "payment") {
2765
+ const credit = message.content.credit;
2766
+ const ask = asks.get(credit?.request_seq ?? latestAsk ?? -1)?.credit;
2767
+ const price = credit ? credit : ask;
2768
+ if (!price || !validMicro(price.amount_micro) || !sameCurrency(price.currency, currency)) return void 0;
2769
+ paid += price.amount_micro;
2770
+ afterAsk += price.amount_micro;
2771
+ }
2772
+ }
2773
+ if (ending !== "release") return paid;
2774
+ return wholeThroughEnd(messages) ? finished ?? 0 : (finished ?? 0) + afterAsk;
2775
+ }
2776
+ function declineCap(job, messages) {
2777
+ const ask = messages.findLast((message) => message.from === "provider" && message.type === "payment-request");
2778
+ if (!ask || !validMicro(ask.content.charged_if_declined_micro)) return void 0;
2779
+ const recorded = [
2780
+ ...job.paidPaymentRequestSeqs ?? [],
2781
+ ...job.inFlightPaymentRequestSeqs ?? [],
2782
+ ...(job.bookedCreditPayments ?? []).map((payment) => payment.authorization.request_seq)
2783
+ ];
2784
+ if (recorded.some((seq) => seq > ask.seq)) return void 0;
2785
+ const paidAsk = answeredYieldSeqs(messages).has(ask.seq) || recorded.includes(ask.seq);
2786
+ if (!paidAsk) return ask.content.charged_if_declined_micro;
2787
+ const price = ask.content.credit?.amount_micro;
2788
+ return validMicro(price) ? ask.content.charged_if_declined_micro + price : void 0;
2789
+ }
2790
+ function wholeThroughEnd(messages) {
2791
+ if (messages.length === 0 || messages[0].seq > 1) return false;
2792
+ if (!messages.every((message, index) => index === 0 || message.seq === messages[index - 1].seq + 1)) return false;
2793
+ return messages.some((message) => message.type === "complete" || message.type === "cancel" || message.type === "decline");
2794
+ }
2795
+ function settlementCurrency(receipt, job, messages, hint) {
2796
+ const candidates = [job?.upfrontPayment?.currency];
2797
+ for (const message of [...messages].reverse()) {
2798
+ if (message.type === "payment-request" && message.from === "provider") candidates.push(message.content.credit?.currency);
2799
+ if (message.type === "payment" && message.from === "requester") candidates.push(message.content.credit?.currency);
2800
+ }
2801
+ candidates.push(hint);
2802
+ const creditId = receipt.credit?.credit_id;
2803
+ if (creditId) candidates.push(safeCredits().find((credit) => credit.creditId === creditId)?.currency);
2804
+ const found = candidates.find((currency) => typeof currency === "string" && /^[a-z]{3}$/i.test(currency));
2805
+ return found ? found.toLowerCase() : null;
2806
+ }
2807
+ function safeCredits() {
2808
+ try {
2809
+ return listCredits();
2810
+ } catch {
2811
+ return [];
2812
+ }
2813
+ }
2814
+ function sameCurrency(a, b) {
2815
+ return typeof a === "string" && a.toLowerCase() === b;
2816
+ }
2817
+ function validMicro(value) {
2818
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
2819
+ }
2820
+ function isSettlement(value) {
2821
+ if (!value || typeof value !== "object") return false;
2822
+ const s = value;
2823
+ 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");
2824
+ }
2825
+
2659
2826
  // src/lib/job-settlement.ts
2660
2827
  function amountDisplay(msats, rail, rate) {
2661
2828
  const amount = rate === void 0 ? formatPaymentAmount(msats, void 0, { anchor: false }) : rate > 0 ? formatAmount(msats, rate, { anchor: false }) : formatSats(msats);
@@ -2671,9 +2838,29 @@ function unknownSettlement(rail) {
2671
2838
  display: "Settlement unknown; recorded payments do not prove a final charge or return."
2672
2839
  };
2673
2840
  }
2674
- function receiptSettlement(receipt, verification, rate) {
2841
+ function receiptSettlement(receipt, verification, rate, context) {
2675
2842
  const rail = receipt.paid.rail;
2676
2843
  if (verification !== "verified" && verification !== "verified_unattested") return unknownSettlement(rail);
2844
+ const pieces = pieceSettlement(receipt, context);
2845
+ if (pieces && !(receipt.outcome === "completed" && receipt.paid.msats === 0 && pieces.held_micro === 0)) {
2846
+ const whole = receipt.outcome === "completed" && pieces.released_micro === 0;
2847
+ return {
2848
+ status: pieces.charged_micro === 0 ? "released" : "settled",
2849
+ settled_msats: whole ? receipt.paid.msats : pieces.charged_micro === 0 ? 0 : null,
2850
+ ...pieces.charged_micro === 0 ? { released_msats: receipt.paid.msats } : {},
2851
+ refunded_msats: 0,
2852
+ rail,
2853
+ evidence: "receipt",
2854
+ held_micro: pieces.held_micro,
2855
+ charged_micro: pieces.charged_micro,
2856
+ released_micro: pieces.released_micro,
2857
+ stopped_micro: pieces.stopped_micro,
2858
+ currency: pieces.currency,
2859
+ ...pieces.ceiling_micro !== void 0 ? { ceiling_micro: pieces.ceiling_micro, ceiling_basis: pieces.ceiling_basis } : {},
2860
+ overcharged: pieces.overcharged,
2861
+ display: pieces.display
2862
+ };
2863
+ }
2677
2864
  const amount = amountDisplay(receipt.paid.msats, rail, rate);
2678
2865
  if (receipt.outcome === "completed") {
2679
2866
  return {
@@ -2713,7 +2900,7 @@ function jobSettlement(job, offeredReceipt) {
2713
2900
  else pending = true;
2714
2901
  }
2715
2902
  const verified = receipt ? verifyJobReceipt({ receipt, expectedJobId: job.id, builder: job.builderAnchor }) : void 0;
2716
- const summary = receipt && verified ? receiptSettlement(receipt, verified.status) : void 0;
2903
+ const summary = receipt && verified ? receiptSettlement(receipt, verified.status, void 0, { job, messages: log }) : void 0;
2717
2904
  const matching = receipt?.outcome === job.status;
2718
2905
  if (!isTerminalJobStatus(job.status)) {
2719
2906
  return {
@@ -2764,7 +2951,14 @@ function terminalSettlementFields(jobId, options = {}) {
2764
2951
  const status = options.status ?? stored?.status ?? options.receipt?.outcome;
2765
2952
  if (!status || !isTerminalJobStatus(status)) return {};
2766
2953
  const job = stored ? { ...stored, status } : { id: jobId, endpoint: "", submittedAt: 0, status };
2767
- return { settlement: options.persistLocalState === false ? options.receipt && options.receipt.outcome === status ? receiptSettlement(options.receipt, verifyJobReceipt({ receipt: options.receipt, expectedJobId: jobId }).status) : unknownSettlement(null) : jobSettlement(job, options.receipt) };
2954
+ const settlement = options.persistLocalState === false ? options.receipt && options.receipt.outcome === status ? receiptSettlement(
2955
+ options.receipt,
2956
+ verifyJobReceipt({ receipt: options.receipt, expectedJobId: jobId }).status,
2957
+ void 0,
2958
+ { currency: options.currency }
2959
+ ) : unknownSettlement(null) : jobSettlement(job, options.receipt);
2960
+ const hint = settlementCurrencyHint(settlement, stored?.endpoint || void 0);
2961
+ return { settlement, ...hint ? { settlement_hint: hint } : {} };
2768
2962
  }
2769
2963
 
2770
2964
  // src/lib/receipt-verify.ts
@@ -2793,13 +2987,21 @@ function drainReceiptsHint(status) {
2793
2987
  return "This DVM countersigned nothing, so the only artifact behind this reclaim is the drain request the caller signed. Weaker evidence than a countersigned drain, and worth weighing before funding here again.";
2794
2988
  }
2795
2989
  }
2796
- function receiptDisplay(receipt, status, rate = 0) {
2990
+ function receiptDisplay(receipt, status, rate = 0, context = receiptPieceContext(receipt)) {
2797
2991
  const what = `${receipt.dvm}/${receipt.capability} (DVM ID ${receipt.dvm_id})`;
2798
2992
  const when = receiptIssuedAtIso(receipt)?.slice(0, 10);
2799
- const settlement = receiptSettlement(receipt, status, rate);
2800
- const payment = settlement.status === "settled" ? `Settled ${formatPaid(receipt.paid.msats, rate)}` : settlement.status === "free" ? "free job" : settlement.display.replace(/\.$/, "");
2993
+ const settlement = receiptSettlement(receipt, status, rate, context);
2994
+ const payment = settlement.charged_micro !== void 0 ? `Charged ${formatMicro(settlement.charged_micro, settlement.currency ?? null)}` : settlement.status === "settled" ? `Settled ${formatPaid(receipt.paid.msats, rate)}` : settlement.status === "free" ? "free job" : settlement.display.replace(/\.$/, "");
2801
2995
  return `${VERDICT_PREFIX[status]}: ${payment} for ${what}, ${receipt.outcome}${when ? ` ${when}` : ""}.`;
2802
2996
  }
2997
+ function receiptPieceContext(receipt, currency) {
2998
+ const job = loadJob(receipt.job_id);
2999
+ return { job, messages: job ? loadMessages(receipt.job_id) : void 0, ...currency ? { currency } : {} };
3000
+ }
3001
+ function receiptCurrencyHint(receipt, status, context, endpoint) {
3002
+ const settlement = receiptSettlement(receipt, status, void 0, context);
3003
+ return settlement.charged_micro !== void 0 && !settlement.currency ? unknownCurrencyHint(endpoint) : void 0;
3004
+ }
2803
3005
  function receiptIssuedAtIso(receipt) {
2804
3006
  const seconds = receipt.issued_at;
2805
3007
  return typeof seconds === "number" ? epochMsToIso(seconds * 1e3) : null;
@@ -3514,7 +3716,7 @@ function redactJobTokenFromError(err, jobToken) {
3514
3716
  if (!jobToken || !(err instanceof DvmError)) return err;
3515
3717
  const redact = (value) => value.replaceAll(jobToken, "[REDACTED]");
3516
3718
  return new DvmError(
3517
- err.code,
3719
+ redact(err.code),
3518
3720
  redact(err.message),
3519
3721
  err.hint === void 0 ? void 0 : redact(err.hint),
3520
3722
  err.data === void 0 ? void 0 : redactRecord(err.data, redact),
@@ -3577,10 +3779,56 @@ function redactValue(value, redact) {
3577
3779
  }
3578
3780
 
3579
3781
  // src/lib/draw-funding.ts
3580
- function verifiedFunding(job, receipt, fundId) {
3782
+ function isImplicitCreditId(creditId) {
3783
+ return creditId.startsWith("imp:");
3784
+ }
3785
+ var MISMATCH_FIELDS = {
3786
+ credit_id_mismatch: "credit_id",
3787
+ job_id_mismatch: "job_id",
3788
+ draw_id_mismatch: "draw_id",
3789
+ fund_id_mismatch: "fund_id",
3790
+ caller_pubkey_mismatch: "caller_pubkey"
3791
+ };
3792
+ function nextAction(job) {
3793
+ return `Nothing is owed or lost: the job's terminal receipt still decides the charge. Refresh your credit balances with \`dvm credit balance ${shellQuoteArg(job.endpoint)}\` once the job ends; if this repeats, report job ${JSON.stringify(job.id)} and the reason to the provider.`;
3794
+ }
3795
+ function invalidFunding(job, receipt, reason, expected) {
3796
+ const field = MISMATCH_FIELDS[reason];
3797
+ const detail = field ? `The provider signed ${field} ${JSON.stringify(String(receipt[field]))}; this job expects ${JSON.stringify(expected[field])}.` : "The provider's funding evidence failed verification.";
3798
+ return { kind: "invalid", reason, hint: `${detail} ${nextAction(job)}` };
3799
+ }
3800
+ function verdictReason(verdict) {
3801
+ if (verdict.status === "verified" || verdict.status === "verified_unattested") return void 0;
3802
+ return (verdict.status === "invalid" ? verdict.reason : void 0) ?? verdict.status;
3803
+ }
3804
+ function checkFunding(job, receipt, fundId) {
3805
+ if (!isDrawFundingReceipt(receipt)) return { kind: "not_applicable" };
3581
3806
  const binding = job.creditBinding;
3582
- if (!binding || "unbound" in binding || !isDrawFundingReceipt(receipt)) return;
3583
- const verdict = verifyDrawFundingReceiptChain({
3807
+ if (!binding || "unbound" in binding) {
3808
+ if (isImplicitCreditId(receipt.credit_id)) {
3809
+ const expected2 = { job_id: job.id, ...fundId ? { fund_id: fundId } : {} };
3810
+ const reason2 = verdictReason(verifyDrawFundingReceiptChain({
3811
+ receipt,
3812
+ builder: job.builderAnchor,
3813
+ expectedJobId: job.id,
3814
+ ...fundId ? { expectedFundId: fundId } : {}
3815
+ }));
3816
+ return reason2 ? invalidFunding(job, receipt, reason2, expected2) : { kind: "not_applicable" };
3817
+ }
3818
+ return {
3819
+ kind: "invalid",
3820
+ reason: "no_bound_draw",
3821
+ hint: `The provider signed funding for credit ${JSON.stringify(receipt.credit_id)}, but this job records no draw on it, so the local balance of that credit was not reconciled. ${nextAction(job)}`
3822
+ };
3823
+ }
3824
+ const expected = {
3825
+ job_id: job.id,
3826
+ credit_id: binding.creditId,
3827
+ draw_id: binding.drawId,
3828
+ caller_pubkey: binding.callerPubkey,
3829
+ ...fundId ? { fund_id: fundId } : {}
3830
+ };
3831
+ const reason = verdictReason(verifyDrawFundingReceiptChain({
3584
3832
  receipt,
3585
3833
  builder: job.builderAnchor,
3586
3834
  expectedJobId: job.id,
@@ -3588,8 +3836,12 @@ function verifiedFunding(job, receipt, fundId) {
3588
3836
  expectedDrawId: binding.drawId,
3589
3837
  expectedCallerPubkey: binding.callerPubkey,
3590
3838
  ...fundId ? { expectedFundId: fundId } : {}
3591
- });
3592
- if (verdict.status === "verified" || verdict.status === "verified_unattested") return receipt;
3839
+ }));
3840
+ return reason ? invalidFunding(job, receipt, reason, expected) : { kind: "verified", receipt };
3841
+ }
3842
+ function verifiedFunding(job, receipt) {
3843
+ const check = checkFunding(job, receipt);
3844
+ return check.kind === "verified" ? check.receipt : void 0;
3593
3845
  }
3594
3846
  function captureDrawFundingReceipts(jobId, receipts, opts) {
3595
3847
  if (!receipts?.length || !loadJob(jobId)) return;
@@ -3597,11 +3849,15 @@ function captureDrawFundingReceipts(jobId, receipts, opts) {
3597
3849
  mutateCreditPayment(jobId, (job) => {
3598
3850
  if (opts?.endpoint && !sameEndpoint(job.endpoint, opts.endpoint)) return;
3599
3851
  for (const raw of receipts) {
3600
- const receipt = verifiedFunding(job, raw, opts?.fundId);
3601
- if (!receipt) {
3602
- info("Warning: mid-job funding evidence did not verify; credit comparisons remain unchanged.");
3852
+ const check = checkFunding(job, raw, opts?.fundId);
3853
+ if (check.kind === "not_applicable") continue;
3854
+ if (check.kind === "invalid") {
3855
+ const display = `mid-job funding evidence did not verify (${check.reason}); credit comparisons remain unchanged. Hint: ${check.hint}`;
3856
+ const added = addOutputWarnings([{ code: "draw_funding_unverified", job_id: job.id, reason: check.reason, hint: check.hint, display }]);
3857
+ if (added.length) info(`Warning: ${display}`);
3603
3858
  continue;
3604
3859
  }
3860
+ const { receipt } = check;
3605
3861
  const held = (Array.isArray(job.drawFundingReceipts) ? job.drawFundingReceipts : []).filter((entry) => verifiedFunding(job, entry) !== void 0);
3606
3862
  if (!held.some((entry) => entry.fund_id === receipt.fund_id)) {
3607
3863
  held.push(receipt);
@@ -3653,8 +3909,8 @@ function completionFromMessages(messages) {
3653
3909
  payloadIn: artifactCount > 0 ? "messages" : "summary"
3654
3910
  };
3655
3911
  if (summary !== void 0) out.summary = summary;
3656
- const terminal = messages.findLast((m) => m.type === "complete" || m.type === "cancel");
3657
- if (terminal?.type === "cancel" && terminal.content.reason !== void 0)
3912
+ const terminal = messages.findLast((m) => m.type === "complete" || m.type === "cancel" || m.type === "decline");
3913
+ if ((terminal?.type === "cancel" || terminal?.type === "decline") && terminal.content.reason !== void 0)
3658
3914
  out.message = terminal.content.reason;
3659
3915
  if (artifactCount > 0) out.artifactCount = artifactCount;
3660
3916
  return out;
@@ -3740,9 +3996,20 @@ function captureJobReceipt(jobId, receipt, parseError) {
3740
3996
  info(
3741
3997
  `Warning: this job's receipt did not verify. ${receiptFailureDetail(result.reason ?? "signature_invalid")}`
3742
3998
  );
3999
+ } else if (result.reason !== "job_id_mismatch") {
4000
+ warnPieceOvercharge(jobId, receipt, job);
3743
4001
  }
3744
4002
  return toCapture(receipt, result);
3745
4003
  }
4004
+ function warnPieceOvercharge(jobId, receipt, job) {
4005
+ const pieces = pieceSettlement(receipt, { job, messages: loadMessages(jobId) });
4006
+ if (!pieces?.overcharged || pieces.ceiling_micro === void 0) return;
4007
+ const ceiling = formatMicro(pieces.ceiling_micro, pieces.currency);
4008
+ const basis = pieces.ceiling_basis === "payments" ? `the ${ceiling} of finished pieces this CLI paid for` : pieces.ceiling_basis === "declined_ask" ? `the ${ceiling} the job's last ask said stopping would cost` : `the ${ceiling} its own pieces add up to`;
4009
+ info(
4010
+ `Warning: the signed receipt for job ${jobId} charges ${formatMicro(pieces.charged_micro, pieces.currency)}, more than ${basis}. Keep the receipt as evidence ('dvm receipts show ${jobId}') and raise it with the provider.` + (pieces.currency ? "" : ` ${settlementCurrencyHint(pieces, job?.endpoint)}`)
4011
+ );
4012
+ }
3746
4013
  function captureTransportReceipt(jobId, response) {
3747
4014
  captureDrawFundingReceipts(jobId, response.drawFundingReceipts);
3748
4015
  if (response.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
@@ -3753,6 +4020,10 @@ function receiptJsonFields(capture, jobId) {
3753
4020
  if (jobId) Object.assign(out, terminalSettlementFields(jobId, { receipt: capture.receipt }));
3754
4021
  else if (capture.receipt) out.settlement = receiptSettlement(capture.receipt, capture.status);
3755
4022
  if (capture.status !== "absent") out.receipt_display = capture.display;
4023
+ if (capture.currencyHint) {
4024
+ out.receipt_hint = capture.currencyHint;
4025
+ delete out.settlement_hint;
4026
+ }
3756
4027
  if (capture.receipt) {
3757
4028
  out.receipt = capture.receipt;
3758
4029
  if (capture.checks) out.receipt_checks = capture.checks;
@@ -3761,16 +4032,19 @@ function receiptJsonFields(capture, jobId) {
3761
4032
  return out;
3762
4033
  }
3763
4034
  function renderReceiptHuman(capture, jobId) {
3764
- if (jobId) {
3765
- const { settlement } = terminalSettlementFields(jobId, { receipt: capture.receipt });
3766
- if (settlement) info(settlement.display);
3767
- }
3768
- if (capture.status === "absent") return;
3769
- info(`\u{1F9FE} ${capture.display}`);
4035
+ const fields = jobId ? terminalSettlementFields(jobId, { receipt: capture.receipt }) : {};
4036
+ if (fields.settlement) info(fields.settlement.display);
4037
+ if (capture.status !== "absent") info(`\u{1F9FE} ${capture.display}`);
4038
+ const hint = capture.status !== "absent" && capture.currencyHint ? capture.currencyHint : fields.settlement_hint;
4039
+ if (hint) info(` ${hint}`);
3770
4040
  }
3771
- function observedSettlementFields(jobId, response, persistLocalState = true) {
4041
+ function renderSettlementHuman(fields) {
4042
+ if (fields.settlement) info(fields.settlement.display);
4043
+ if (fields.settlement_hint) info(` ${fields.settlement_hint}`);
4044
+ }
4045
+ function observedSettlementFields(jobId, response, persistLocalState = true, currency) {
3772
4046
  if (persistLocalState && response?.status && isTerminalJobStatus(response.status) && (response.receipt || response.receiptParseError)) captureTransportReceipt(jobId, response);
3773
- return terminalSettlementFields(jobId, { status: response?.status, receipt: response?.receipt, persistLocalState });
4047
+ return terminalSettlementFields(jobId, { status: response?.status, receipt: response?.receipt, persistLocalState, currency });
3774
4048
  }
3775
4049
  function receiptTrustFields(provider) {
3776
4050
  return {
@@ -3842,13 +4116,15 @@ function unparseableCapture(reason) {
3842
4116
  const display = "UNREADABLE receipt: this DVM returned a receipt block that does not match the signed receipt protocol shape. The job itself is unaffected.";
3843
4117
  return { status: "unparseable", reason, display };
3844
4118
  }
3845
- function toCapture(receipt, result) {
4119
+ function toCapture(receipt, result, context = receiptPieceContext(receipt), endpoint = context.job?.endpoint) {
4120
+ const currencyHint = receiptCurrencyHint(receipt, result.status, context, endpoint || void 0);
3846
4121
  return {
3847
4122
  status: result.status,
3848
4123
  receipt,
3849
4124
  checks: result.checks,
3850
4125
  ...result.reason ? { reason: result.reason } : {},
3851
- display: receiptDisplay(receipt, result.status, getLastKnownBtcRate()?.rate ?? 0)
4126
+ display: receiptDisplay(receipt, result.status, getLastKnownBtcRate()?.rate ?? 0, context),
4127
+ ...currencyHint ? { currencyHint } : {}
3852
4128
  };
3853
4129
  }
3854
4130
  function persist(jobId, receipt, verification, job) {
@@ -8178,10 +8454,6 @@ export {
8178
8454
  providerFields,
8179
8455
  guidanceJobArg,
8180
8456
  providerJobJson,
8181
- appendMessages,
8182
- createMessageAppendSession,
8183
- loadMessages,
8184
- maxSeq,
8185
8457
  normalizeProviderEndpoint,
8186
8458
  sameEndpoint,
8187
8459
  parseUpfrontRailPayment,
@@ -8203,16 +8475,6 @@ export {
8203
8475
  markPaymentRequestPaid,
8204
8476
  mutateCreditPayment,
8205
8477
  bookCreditPayment,
8206
- JOB_READ_TIMEOUT_MS,
8207
- answeredYieldSeqs,
8208
- pendingPaymentRequest,
8209
- loadAnsweredYieldSeqs,
8210
- reconcileInFlightPaymentRequest,
8211
- reconcilePaymentRequestHistory,
8212
- isTerminalJobStatus,
8213
- pollNextAction,
8214
- paymentInFlightHint,
8215
- computeNextAction,
8216
8478
  loadFavorites,
8217
8479
  saveFavorite,
8218
8480
  removeFavorite,
@@ -8239,6 +8501,21 @@ export {
8239
8501
  resolveJobAccess,
8240
8502
  resolveStoredJobAccess,
8241
8503
  withJobTokenRedaction,
8504
+ redactJobTokenFromError,
8505
+ appendMessages,
8506
+ createMessageAppendSession,
8507
+ loadMessages,
8508
+ maxSeq,
8509
+ JOB_READ_TIMEOUT_MS,
8510
+ answeredYieldSeqs,
8511
+ pendingPaymentRequest,
8512
+ loadAnsweredYieldSeqs,
8513
+ reconcileInFlightPaymentRequest,
8514
+ reconcilePaymentRequestHistory,
8515
+ isTerminalJobStatus,
8516
+ pollNextAction,
8517
+ paymentInFlightHint,
8518
+ computeNextAction,
8242
8519
  buildTempoCredential,
8243
8520
  loadLedger,
8244
8521
  saveLedger,
@@ -8254,6 +8531,7 @@ export {
8254
8531
  walletHistory,
8255
8532
  dvmLabelFromEndpoint,
8256
8533
  listPendingCardFundings,
8534
+ CARD_MIN_MICRO,
8257
8535
  floatPaymentJson,
8258
8536
  floatPaymentDisplay,
8259
8537
  unrecordedFloatBudgetWarning,
@@ -8267,16 +8545,22 @@ export {
8267
8545
  parseStatedBudget,
8268
8546
  floatBudgetJson,
8269
8547
  toFloatError,
8548
+ formatMicro,
8549
+ settlementCurrencyHint,
8550
+ unknownCurrencyHint,
8270
8551
  receiptSettlement,
8271
8552
  jobSettlement,
8272
8553
  terminalSettlementFields,
8273
8554
  drainReceiptsDisplay,
8274
8555
  drainReceiptsHint,
8275
8556
  receiptDisplay,
8557
+ receiptPieceContext,
8558
+ receiptCurrencyHint,
8276
8559
  receiptIssuedAtIso,
8277
8560
  epochMsToIso,
8278
8561
  receiptHint,
8279
8562
  receiptFailureDetail,
8563
+ isImplicitCreditId,
8280
8564
  captureDrawFundingReceipts,
8281
8565
  jobDrawFundings,
8282
8566
  buildCompletionHintFields,
@@ -8290,12 +8574,14 @@ export {
8290
8574
  captureTransportReceipt,
8291
8575
  receiptJsonFields,
8292
8576
  renderReceiptHuman,
8577
+ renderSettlementHuman,
8293
8578
  observedSettlementFields,
8294
8579
  receiptTrustFields,
8295
8580
  fetchTrustAnchor,
8296
8581
  fetchMissingJobReceipt,
8297
8582
  backfillTrustAnchor,
8298
8583
  replayStoredReceipt,
8584
+ toCapture,
8299
8585
  extractBuilderHandle,
8300
8586
  reservedForMarker,
8301
8587
  inFlightTimeoutSeconds,
@@ -3,8 +3,8 @@ import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
5
  tryX402Payment
6
- } from "./chunk-RPM5XEVS.js";
7
- import "./chunk-SEJWBDGY.js";
6
+ } from "./chunk-LPILVPFG.js";
7
+ import "./chunk-YQJRKWNT.js";
8
8
  import "./chunk-JBU7RKQ3.js";
9
9
  import "./chunk-KDNFUDOG.js";
10
10
  import "./chunk-IUTVV6N5.js";
@@ -13,11 +13,11 @@ import "./chunk-6LP4EGKA.js";
13
13
  import "./chunk-N3UJT2NJ.js";
14
14
  import "./chunk-SYFKO6BA.js";
15
15
  import "./chunk-PUOXBKY2.js";
16
- import "./chunk-C2BJETRG.js";
17
- import "./chunk-CCF4QONY.js";
18
- import "./chunk-PS4AUWK3.js";
16
+ import "./chunk-57PXJ56K.js";
17
+ import "./chunk-HXTASGHL.js";
18
+ import "./chunk-D5CGDS3V.js";
19
19
  import "./chunk-R2DSAZBO.js";
20
- import "./chunk-ZV57FFIL.js";
20
+ import "./chunk-UCCT5IKU.js";
21
21
  import "./chunk-EVQERRCP.js";
22
22
  import "./chunk-RA24J4QM.js";
23
23
  import "./chunk-B4WHUMZM.js";