@dvmkit/dvm-cli 0.13.0 → 0.14.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 (27) 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-RPM5XEVS.js → chunk-CO2TD5RO.js} +2 -2
  4. package/dist/{chunk-PS4AUWK3.js → chunk-D5CGDS3V.js} +2 -2
  5. package/dist/{chunk-NLUOHCX2.js → chunk-DU7YCGCQ.js} +214 -21
  6. package/dist/{chunk-ZDWZT6NA.js → chunk-EZL4IVCU.js} +3 -3
  7. package/dist/{chunk-I2C3YEUN.js → chunk-HJ2JYBTT.js} +4 -4
  8. package/dist/{chunk-CCF4QONY.js → chunk-HXTASGHL.js} +2 -2
  9. package/dist/{chunk-C2EZ3VY2.js → chunk-I7ZBID4L.js} +2 -2
  10. package/dist/{chunk-ZV57FFIL.js → chunk-UCCT5IKU.js} +9 -1
  11. package/dist/{chunk-KQQALLOL.js → chunk-UWVMG4VG.js} +3 -3
  12. package/dist/{chunk-SEJWBDGY.js → chunk-YQJRKWNT.js} +1739 -788
  13. package/dist/{client-6JRGRKFQ.js → client-DC7TVYNU.js} +6 -6
  14. package/dist/dvm.js +690 -487
  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-HEVLAMKN.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 +2 -2
  25. package/skills/dvm/SKILL.md +2 -0
  26. package/skills/dvm/calling.md +12 -1
  27. package/skills/dvm/recovery.md +3 -0
package/dist/dvm.js CHANGED
@@ -5,10 +5,7 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-ZDWZT6NA.js";
9
- import {
10
- assertX402WalletIdle
11
- } from "./chunk-C2EZ3VY2.js";
8
+ } from "./chunk-EZL4IVCU.js";
12
9
  import {
13
10
  DEFAULT_CREDIT_POSTURE,
14
11
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
@@ -57,6 +54,7 @@ import {
57
54
  floatPaymentDisplay,
58
55
  floatPaymentJson,
59
56
  formatLocktime,
57
+ formatMicro,
60
58
  fundAgentWallet,
61
59
  fundCredit,
62
60
  fundTimeoutMs,
@@ -169,13 +167,13 @@ import {
169
167
  withIdentityRecovery,
170
168
  withJobTokenRedaction,
171
169
  withRequestResultRecovery
172
- } from "./chunk-NLUOHCX2.js";
170
+ } from "./chunk-DU7YCGCQ.js";
173
171
  import {
174
172
  connectedTempoAccount,
175
173
  generateTempoKey,
176
174
  tempoBalanceCheckHint,
177
175
  tempoWrongAssetHint
178
- } from "./chunk-I2C3YEUN.js";
176
+ } from "./chunk-HJ2JYBTT.js";
179
177
  import {
180
178
  addOutputWarnings,
181
179
  assertValidBudget,
@@ -195,7 +193,7 @@ import {
195
193
  tryResolveBtcUsdRate,
196
194
  tryX402Payment,
197
195
  withOutputWarnings
198
- } from "./chunk-RPM5XEVS.js";
196
+ } from "./chunk-CO2TD5RO.js";
199
197
  import {
200
198
  assertSupportedX402Network,
201
199
  connectedX402Payer,
@@ -204,7 +202,7 @@ import {
204
202
  repinX402WalletNetwork,
205
203
  saveX402Wallet,
206
204
  x402NetworkLabel
207
- } from "./chunk-KQQALLOL.js";
205
+ } from "./chunk-UWVMG4VG.js";
208
206
  import {
209
207
  CREDIT_POSTURES,
210
208
  FEEDBACK_POSTURES,
@@ -221,7 +219,10 @@ import {
221
219
  retireConfigBackup,
222
220
  rollbackConfig,
223
221
  updateConfig
224
- } from "./chunk-GWLOO5XD.js";
222
+ } from "./chunk-2MCZ4QOK.js";
223
+ import {
224
+ assertX402WalletIdle
225
+ } from "./chunk-I7ZBID4L.js";
225
226
  import {
226
227
  A,
227
228
  AGENT_MNEMONIC_FILE,
@@ -458,7 +459,7 @@ import {
458
459
  x402PendingUnsettled,
459
460
  x402RequiredFromError,
460
461
  x402ReservationRelease
461
- } from "./chunk-SEJWBDGY.js";
462
+ } from "./chunk-YQJRKWNT.js";
462
463
  import "./chunk-JBU7RKQ3.js";
463
464
  import "./chunk-KDNFUDOG.js";
464
465
  import "./chunk-IUTVV6N5.js";
@@ -742,11 +743,11 @@ import {
742
743
  usdToMsats,
743
744
  usdcToMsats,
744
745
  x402NetworkByCaip2
745
- } from "./chunk-C2BJETRG.js";
746
- import "./chunk-CCF4QONY.js";
747
- import "./chunk-PS4AUWK3.js";
746
+ } from "./chunk-57PXJ56K.js";
747
+ import "./chunk-HXTASGHL.js";
748
+ import "./chunk-D5CGDS3V.js";
748
749
  import "./chunk-R2DSAZBO.js";
749
- import "./chunk-ZV57FFIL.js";
750
+ import "./chunk-UCCT5IKU.js";
750
751
  import {
751
752
  privateKeyToAccount
752
753
  } from "./chunk-EVQERRCP.js";
@@ -11376,8 +11377,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11376
11377
  }
11377
11378
  }
11378
11379
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11379
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-LASVQ72F.js");
11380
- const { tryX402Payment: tryX402Payment2 } = await import("./client-6JRGRKFQ.js");
11380
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
11381
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-DC7TVYNU.js");
11381
11382
  const wallet = loadX402Wallet2();
11382
11383
  if (wallet) {
11383
11384
  let proof;
@@ -11775,6 +11776,7 @@ async function streamLoop(opts) {
11775
11776
  let cursor = opts.afterSeq;
11776
11777
  let messageAppendSession = opts.messageAppendSession;
11777
11778
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
11779
+ const declined = () => persistLocalState && loadJob(jobId)?.callerDeclined === true;
11778
11780
  function recordAutoPayment(result, request2, seq) {
11779
11781
  autoPayments.push({
11780
11782
  amount_msats: result.amountMsats,
@@ -11894,7 +11896,7 @@ async function streamLoop(opts) {
11894
11896
  break;
11895
11897
  }
11896
11898
  }
11897
- if (lastYield2?.type === "payment-request" && lastYield2.seq === pendingPayment?.seq && policy) {
11899
+ if (lastYield2?.type === "payment-request" && lastYield2.seq === pendingPayment?.seq && policy && !declined()) {
11898
11900
  const req = lastYield2.content;
11899
11901
  if (req.amount_msats <= policy.autoPayBelowMsats && (policy.maxIncrementMsats === 0 || req.amount_msats <= policy.maxIncrementMsats)) {
11900
11902
  let result;
@@ -11964,7 +11966,7 @@ async function streamLoop(opts) {
11964
11966
  }
11965
11967
  if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
11966
11968
  for (const seq of answeredYieldSeqs(allMessages)) answeredSeqs.add(seq);
11967
- const terminal = allMessages.some((msg) => msg.type === "complete" || msg.type === "cancel");
11969
+ const terminal = allMessages.some((msg) => msg.type === "complete" || msg.type === "cancel") || declined();
11968
11970
  const yieldAction = computeNextAction(jobId, allMessages.filter((message2) => !answeredSeqs.has(message2.seq)), void 0, policy ? { policy, totalPaidMsats: loadJob(jobId)?.totalPaidMsats } : void 0) ?? (terminal ? null : pendingAction);
11969
11971
  let nextAction = withRefundNextAction(jobId, yieldAction ?? (terminal ? null : pollNextAction(jobId)), refunds);
11970
11972
  const lastYield = findLastYield(allMessages);
@@ -12802,6 +12804,8 @@ var HttpsTransport = class {
12802
12804
  error.data = { ...error.data, http_status: res.status };
12803
12805
  throw error;
12804
12806
  }
12807
+ const conflict = jobEndingConflict(jobId, body2, res.headers.get("retry-after"));
12808
+ if (conflict) throw conflict;
12805
12809
  throw new DvmError(
12806
12810
  "job_terminal",
12807
12811
  "Job is no longer active.",
@@ -12870,6 +12874,10 @@ var HttpsTransport = class {
12870
12874
  const res = await dvmFetch(url2, { method: "DELETE", headers, body });
12871
12875
  if (!res.ok) {
12872
12876
  const text = await res.text();
12877
+ if (res.status === 409) {
12878
+ const conflict = jobEndingConflict(jobId, parseJsonObject(text), res.headers.get("retry-after"));
12879
+ if (conflict) throw conflict;
12880
+ }
12873
12881
  const credentialErr = jobCredentialError(res.status, text);
12874
12882
  if (credentialErr) throw credentialErr;
12875
12883
  throw providerResponseError("provider_error", `Cancel failed (${res.status}): ${text}`);
@@ -13149,6 +13157,38 @@ function routerProse(structured) {
13149
13157
  const display = typeof structured.data?.display === "string" ? structured.data.display : void 0;
13150
13158
  return display !== void 0 ? { display, proseSources: { display: "provider" } } : {};
13151
13159
  }
13160
+ function jobEndingConflict(jobId, body, retryAfter) {
13161
+ const job = shellQuoteArg(jobId);
13162
+ if (body?.error === "payment_in_progress") {
13163
+ return new DvmError(
13164
+ "payment_in_progress",
13165
+ "A payment for this job is still being verified, so the job cannot end yet.",
13166
+ `Nothing changed. Retry the same command in a few seconds; the payment will either pay the job's request or be held as balance on your credit. Check the job with \`dvm status ${job}\`.`,
13167
+ { retryable: true, retry_after_ms: retryAfterMs(retryAfter) }
13168
+ );
13169
+ }
13170
+ if (body?.error === "no_open_ask") {
13171
+ return new DvmError(
13172
+ "no_open_ask",
13173
+ "The job has no open payment request or prompt to decline.",
13174
+ `Decline answers an open ask. To stop at the next one, wait for it with \`dvm messages ${job} --wait\` and decline then. To halt the work now, run \`dvm cancel ${job}\`; the work in progress is charged.`
13175
+ );
13176
+ }
13177
+ if (body?.error === "decline_unavailable") {
13178
+ return new DvmError(
13179
+ "decline_unavailable",
13180
+ "This DVM cannot end this job at a decline; the job is still running.",
13181
+ `Pay the open ask with \`dvm pay ${job}\`, let it expire, or stop the work now with \`dvm cancel ${job}\`; the work in progress is charged.`
13182
+ );
13183
+ }
13184
+ return void 0;
13185
+ }
13186
+ function retryAfterMs(header, nowMs = Date.now()) {
13187
+ const value = header?.trim();
13188
+ if (value && /^\d+$/.test(value)) return Number(value) * 1e3;
13189
+ const date4 = value ? Date.parse(value) : Number.NaN;
13190
+ return Number.isFinite(date4) ? Math.max(0, date4 - nowMs) : 2e3;
13191
+ }
13152
13192
  function parseJsonObject(body) {
13153
13193
  try {
13154
13194
  const parsed = JSON.parse(body);
@@ -13746,6 +13786,489 @@ function capabilityRetryHint(caps, dvmId, endpoint) {
13746
13786
  return `Try \`${command} --data '{}'\` using a name from available_capabilities. Replace --data '{}' with the input for that capability.${alternate}`;
13747
13787
  }
13748
13788
 
13789
+ // src/lib/credit-defer.ts
13790
+ function noteDeferredFunding(funding) {
13791
+ pending2 = funding;
13792
+ }
13793
+ function takeDeferredFunding() {
13794
+ const taken = pending2;
13795
+ pending2 = void 0;
13796
+ return taken;
13797
+ }
13798
+ var pending2;
13799
+
13800
+ // src/lib/credit-reclaim.ts
13801
+ function adoptWedgedChannelDrain(args) {
13802
+ const drainId = args.data?.settlement_drain_id;
13803
+ if (typeof drainId !== "string" || drainId === "") return void 0;
13804
+ const identityArg = args.identity ? [args.identity] : [];
13805
+ const stored = loadCredit(args.endpoint, args.callerPubkey, args.identity);
13806
+ if (!stored) {
13807
+ ensureProvisionalCredit({
13808
+ endpoint: args.endpoint,
13809
+ ...args.identity ? { identity: args.identity } : {},
13810
+ callerPubkey: args.callerPubkey,
13811
+ creditId: args.creditId,
13812
+ currency: "usd",
13813
+ targetMicro: 0
13814
+ });
13815
+ }
13816
+ const recorded = pendingDrainFor(stored, args.creditId);
13817
+ if (recorded && recorded.drainId !== drainId) {
13818
+ clearPendingDrain(args.endpoint, args.callerPubkey, recorded, ...identityArg);
13819
+ }
13820
+ recordPendingDrain(
13821
+ args.endpoint,
13822
+ args.callerPubkey,
13823
+ {
13824
+ drainId,
13825
+ creditId: args.creditId,
13826
+ method: "x402",
13827
+ payout: {},
13828
+ requestedAt: Date.now()
13829
+ },
13830
+ ...identityArg
13831
+ );
13832
+ recordCreditX402Instrument(
13833
+ args.endpoint,
13834
+ args.callerPubkey,
13835
+ args.creditId,
13836
+ "x402_channel",
13837
+ args.identity
13838
+ );
13839
+ const command = reclaimCommand(args.handle ?? args.endpoint, stored, args.creditId);
13840
+ return {
13841
+ drainId,
13842
+ command,
13843
+ // Written to be appended to the server's own refusal, never to replace it:
13844
+ // that copy is the one saying nothing was charged and that paying per call
13845
+ // still works, which is what a human needs to hear. What it cannot know is
13846
+ // that this CLI just recorded the id, so the reclaim no longer carries it.
13847
+ advice: `Drain ${drainId} is now this credit's recorded reclaim here, so '${command}' posts it \u2014 no --drain-id needed.`
13848
+ };
13849
+ }
13850
+ function reclaimCommand(handle, tracked, creditId) {
13851
+ return !tracked || tracked.creditId === creditId ? `dvm credit drain ${shellQuoteArg(handle)}` : creditDrainCommand(handle, creditId);
13852
+ }
13853
+ function creditDrainCommand(handle, creditId) {
13854
+ return `dvm credit drain ${shellQuoteArg(handle)} --credit-id ${shellQuoteArg(creditId)}`;
13855
+ }
13856
+
13857
+ // src/lib/credit-topup.ts
13858
+ async function settleCreditAfterJob(args) {
13859
+ const deferred = args.deferred ?? takeDeferredFunding();
13860
+ try {
13861
+ await settle(args);
13862
+ } catch (err) {
13863
+ info(
13864
+ `Credit bookkeeping failed (job outcome unaffected): ${err instanceof Error ? err.message : String(err)}`
13865
+ );
13866
+ }
13867
+ if (deferred) {
13868
+ try {
13869
+ await fundDeferred(args, deferred);
13870
+ } catch (err) {
13871
+ info(
13872
+ `Credit funding failed (job outcome unaffected): ${err instanceof Error ? err.message : String(err)}`
13873
+ );
13874
+ }
13875
+ }
13876
+ if (args.allowTopup !== false) {
13877
+ const refill = args.refillPocket ?? (await import("./pocket-refill-HEVLAMKN.js")).refillPocketIfLow;
13878
+ await refill({ human: args.human }).catch(() => void 0);
13879
+ }
13880
+ }
13881
+ async function settleCreditAfterRead(args) {
13882
+ const { job, capture } = args;
13883
+ const binding = job.creditBinding;
13884
+ const receipt = capture.receipt;
13885
+ if (job.strictPerCall || !binding || "unbound" in binding || !receipt?.credit || receipt.job_id !== job.id || receipt.requester_pubkey !== binding.callerPubkey || receipt.credit.credit_id !== binding.creditId || receipt.credit.draw_id !== binding.drawId || receipt.credit.credit_id.startsWith("imp:")) return;
13886
+ const builder = loadJob(job.id)?.builderAnchor ?? job.builderAnchor;
13887
+ await settleCreditAfterJob({
13888
+ capture,
13889
+ transport: args.transport,
13890
+ ref: { endpoint: job.endpoint },
13891
+ dvmId: job.dvmId,
13892
+ providerInfo: builder ? { builder } : void 0,
13893
+ callerPubkey: binding.callerPubkey,
13894
+ allowTopup: false,
13895
+ human: args.human
13896
+ });
13897
+ }
13898
+ function settleIdentity(args) {
13899
+ return providerDvmIdentity(args.providerInfo);
13900
+ }
13901
+ function settleIdentityArgs(args) {
13902
+ const identity = settleIdentity(args);
13903
+ return identity ? { identity } : {};
13904
+ }
13905
+ function settleIdentityArg(args) {
13906
+ const identity = settleIdentity(args);
13907
+ return identity ? [identity] : [];
13908
+ }
13909
+ function noticeDvm(args) {
13910
+ return args.dvmId ?? args.ref.endpoint;
13911
+ }
13912
+ async function settle(args) {
13913
+ const receipt = args.capture?.receipt;
13914
+ const credit = receipt?.credit;
13915
+ const callerPubkey = args.signing?.pubkey ?? args.callerPubkey;
13916
+ if (!receipt || !credit || !callerPubkey || args.capture?.status !== "verified" && args.capture?.status !== "verified_unattested" || receipt.requester_pubkey !== callerPubkey) return;
13917
+ if (credit.credit_id.startsWith("imp:")) {
13918
+ const applied2 = applyImplicitReceiptCredit({
13919
+ endpoint: args.ref.endpoint,
13920
+ ...settleIdentityArgs(args),
13921
+ callerPubkey,
13922
+ jobId: receipt.job_id,
13923
+ outcome: receipt.outcome,
13924
+ credit,
13925
+ currency: args.providerInfo?.pricing?.max?.currency ?? args.providerInfo?.credit?.currency ?? "usd",
13926
+ issuedAtMs: receipt.issued_at * 1e3
13927
+ });
13928
+ if (applied2.mismatch) renderBalanceMismatch(args.ref.endpoint, applied2.mismatch);
13929
+ return;
13930
+ }
13931
+ const applied = applyReceiptCredit({
13932
+ endpoint: args.ref.endpoint,
13933
+ ...settleIdentityArgs(args),
13934
+ callerPubkey,
13935
+ jobId: receipt.job_id,
13936
+ outcome: receipt.outcome,
13937
+ credit,
13938
+ // A piece-settled draw can charge on a failed or cancelled job too; the
13939
+ // SDK checks every ending whose settlement charged anything.
13940
+ ...receipt.settlement ? { settlement: { charged: receipt.settlement.charged } } : {},
13941
+ drawFundings: jobDrawFundings(receipt.job_id, args.ref.endpoint, callerPubkey, credit)
13942
+ });
13943
+ if (!applied.credit) return;
13944
+ if (applied.mismatch) {
13945
+ renderBalanceMismatch(args.ref.endpoint, applied.mismatch);
13946
+ }
13947
+ if (args.allowTopup === false || !args.signing) return;
13948
+ if (receipt.outcome !== "completed") return;
13949
+ const record2 = applied.credit;
13950
+ if (record2.status !== "active") return;
13951
+ if (record2.reconciliationPending) return;
13952
+ if (!needsTopup(record2.remainingMicro, record2.targetMicro)) return;
13953
+ const posture = effectiveCreditPosture(
13954
+ args.config ?? loadConfig()?.credit,
13955
+ args.ref.endpoint,
13956
+ providerDvmIdentity(args.providerInfo)
13957
+ );
13958
+ if (posture.posture === "off") return;
13959
+ const held = pendingDrainFor(record2, record2.creditId);
13960
+ if (held) {
13961
+ reportRefillHeldByDrain(args, record2, held, args.signing.pubkey);
13962
+ return;
13963
+ }
13964
+ await fundTopup(args, record2, posture);
13965
+ }
13966
+ function renderBalanceMismatch(endpoint, mismatch) {
13967
+ const prior = mismatch.priorJobId ? `the previous countersigned receipt (job ${mismatch.priorJobId})` : "the recorded balance projection";
13968
+ info(
13969
+ `Warning: credit balance mismatch at ${endpoint}. The DVM-signed receipt for job ${mismatch.jobId} (draw ${mismatch.drawId}, ledger seq ${String(mismatch.ledgerSeq)}) reports $${formatUsd(mismatch.reportedMicro / 1e6)} remaining, but ${prior} implies $${formatUsd(mismatch.expectedMicro / 1e6)}. Both signed artifacts are stored \u2014 inspect them with 'dvm receipts show <job-id>' and re-read the server with 'dvm credit balance'.`
13970
+ );
13971
+ }
13972
+ function reportRefillHeldByDrain(args, record2, held, callerPubkey) {
13973
+ const identityArg = settleIdentityArg(args);
13974
+ if (!markRefillDrainNoticed(
13975
+ args.ref.endpoint,
13976
+ callerPubkey,
13977
+ record2.creditId,
13978
+ held.drainId,
13979
+ ...identityArg
13980
+ )) {
13981
+ return;
13982
+ }
13983
+ noteCreditRefillUnavailable(
13984
+ buildCreditRefillDrainPending({
13985
+ dvm: noticeDvm(args),
13986
+ endpoint: args.ref.endpoint,
13987
+ creditId: record2.creditId,
13988
+ drainId: held.drainId,
13989
+ // The reclaim as the doors that record one spell it ,
13990
+ // rather than a third spelling of the same command.
13991
+ drainCommand: reclaimCommand(noticeDvm(args), record2, record2.creditId),
13992
+ balanceMicro: record2.remainingMicro,
13993
+ currency: record2.currency
13994
+ }),
13995
+ args.human
13996
+ );
13997
+ }
13998
+ async function fundTopup(args, record2, posture) {
13999
+ const menu = record2.menu;
14000
+ if (!menu) return;
14001
+ if (!args.transport.credit) return;
14002
+ const signing = args.signing;
14003
+ if (!signing) return;
14004
+ const identityArg = settleIdentityArg(args);
14005
+ const boundRail = isCreditFundRail(record2.rail) ? record2.rail : void 0;
14006
+ const boundRailAvailable = boundRail ? availableRails({
14007
+ menu,
14008
+ ...args.providerInfo ? { providerInfo: args.providerInfo } : {}
14009
+ }).includes(boundRail) : void 0;
14010
+ if (boundRail && !boundRailAvailable) {
14011
+ if (!markRefillRailUnavailable(
14012
+ args.ref.endpoint,
14013
+ signing.pubkey,
14014
+ record2.creditId,
14015
+ boundRail,
14016
+ ...identityArg
14017
+ )) {
14018
+ return;
14019
+ }
14020
+ noteCreditRefillUnavailable(
14021
+ buildCreditRefillUnavailable({
14022
+ dvm: noticeDvm(args),
14023
+ endpoint: args.ref.endpoint,
14024
+ creditId: record2.creditId,
14025
+ boundRail,
14026
+ balanceMicro: record2.remainingMicro,
14027
+ currency: record2.currency
14028
+ }),
14029
+ args.human
14030
+ );
14031
+ return;
14032
+ }
14033
+ if (boundRail) {
14034
+ clearRefillRailUnavailable(args.ref.endpoint, signing.pubkey, record2.creditId, ...identityArg);
14035
+ }
14036
+ const forced = forcedRefillRail(args, record2);
14037
+ const railFloorMicro = forced.rail === "lightning" && menu.lightning_min_micro !== void 0 ? Math.max(menu.min_micro, menu.lightning_min_micro) : menu.min_micro;
14038
+ let fundMicro = Math.max(record2.targetMicro - record2.remainingMicro, railFloorMicro);
14039
+ fundMicro = Math.min(fundMicro, menu.max_micro - record2.remainingMicro);
14040
+ if (fundMicro < railFloorMicro) {
14041
+ if (railFloorMicro > menu.min_micro) {
14042
+ info(
14043
+ `Credit top-up at ${args.ref.endpoint} deferred: this credit refills over Lightning, which needs at least $${formatUsd(railFloorMicro / 1e6)} per funding, but only $${formatUsd(Math.max(0, menu.max_micro - record2.remainingMicro) / 1e6)} of headroom remains under the DVM's balance ceiling. It retries after a later job.`
14044
+ );
14045
+ }
14046
+ return;
14047
+ }
14048
+ if (posture.posture === "suggest") {
14049
+ noteCreditSuggestion(
14050
+ buildCreditSuggestion({
14051
+ dvm: noticeDvm(args),
14052
+ endpoint: args.ref.endpoint,
14053
+ posture: posture.posture,
14054
+ postureSource: posture.source,
14055
+ suppressed: {
14056
+ reason: "refill",
14057
+ fundMicro,
14058
+ targetMicro: record2.targetMicro,
14059
+ currency: record2.currency
14060
+ }
14061
+ }),
14062
+ args.human
14063
+ );
14064
+ return;
14065
+ }
14066
+ const outcome = await fundCredit({
14067
+ transport: args.transport,
14068
+ ref: args.ref,
14069
+ signing,
14070
+ creditId: record2.creditId,
14071
+ amountMicro: fundMicro,
14072
+ menu,
14073
+ targetMicro: record2.targetMicro,
14074
+ maxDepositMicro: fundMicro,
14075
+ human: args.human,
14076
+ ...forced.rail ? { rail: forced.rail, railSource: forced.source } : {},
14077
+ ...args.providerInfo ? { providerInfo: args.providerInfo } : {},
14078
+ ...args.signBody ? { signBody: args.signBody } : {}
14079
+ });
14080
+ reportFunding(args, outcome, {
14081
+ reason: "below_refill_target",
14082
+ fundMicro,
14083
+ currency: record2.currency,
14084
+ menu
14085
+ });
14086
+ }
14087
+ async function fundDeferred(args, deferred) {
14088
+ if (args.allowTopup === false) return;
14089
+ if (args.capture?.receipt?.outcome !== "completed") return;
14090
+ if (!args.transport.credit) return;
14091
+ const signing = args.signing;
14092
+ if (!signing) return;
14093
+ const posture = effectiveCreditPosture(
14094
+ args.config ?? loadConfig()?.credit,
14095
+ args.ref.endpoint,
14096
+ providerDvmIdentity(args.providerInfo)
14097
+ );
14098
+ if (posture.posture !== "auto") return;
14099
+ const outcome = await fundCredit({
14100
+ transport: args.transport,
14101
+ ref: args.ref,
14102
+ signing,
14103
+ creditId: deferred.creditId,
14104
+ amountMicro: deferred.fundMicro,
14105
+ menu: deferred.menu,
14106
+ targetMicro: deferred.targetMicro,
14107
+ maxDepositMicro: deferred.maxDepositMicro ?? deferred.fundMicro,
14108
+ human: args.human,
14109
+ ...deferred.pinnedRail ? { rail: deferred.pinnedRail, railSource: deferred.pinnedRailSource } : {},
14110
+ ...args.providerInfo ? { providerInfo: args.providerInfo } : {},
14111
+ ...args.signBody ? { signBody: args.signBody } : {}
14112
+ });
14113
+ reportFunding(args, outcome, {
14114
+ reason: deferred.reason === "open" ? "no_credit_open" : "below_refill_target",
14115
+ fundMicro: deferred.fundMicro,
14116
+ currency: deferred.currency,
14117
+ menu: deferred.menu,
14118
+ label: deferred.reason === "open" ? "Credit opening" : "Credit top-up"
14119
+ });
14120
+ }
14121
+ function forcedRefillRail(args, record2) {
14122
+ if (isCreditFundRail(record2.rail)) return { rail: record2.rail, source: "credit_bound" };
14123
+ const pin = effectiveFundingRail(
14124
+ args.config ?? loadConfig()?.credit,
14125
+ args.ref.endpoint,
14126
+ providerDvmIdentity(args.providerInfo)
14127
+ );
14128
+ return pin.rail && pin.source !== "default" ? { rail: pin.rail, source: pin.source } : {};
14129
+ }
14130
+ function reportFunding(args, outcome, ctx) {
14131
+ const what = ctx.label ?? "Credit top-up";
14132
+ const hint = outcome.hint ? ` ${outcome.hint}` : "";
14133
+ const incomplete = (code, adoptedDrain) => {
14134
+ noteCreditFundingIncomplete(
14135
+ buildCreditFundingIncomplete({
14136
+ code,
14137
+ dvm: noticeDvm(args),
14138
+ endpoint: args.ref.endpoint,
14139
+ reason: ctx.reason,
14140
+ amountMicro: ctx.fundMicro,
14141
+ currency: ctx.currency,
14142
+ outcome,
14143
+ ...adoptedDrain ? { adoptedDrain } : {}
14144
+ }),
14145
+ args.human
14146
+ );
14147
+ };
14148
+ switch (outcome.status) {
14149
+ case "funded": {
14150
+ if (outcome.reconciled || !outcome.rail) {
14151
+ info(`${what} at ${args.ref.endpoint} \u2014 ${outcome.display}${hint}`);
14152
+ if (outcome.reconciled) incomplete("credit_funding_reconciled");
14153
+ return;
14154
+ }
14155
+ noteCreditFunding(
14156
+ buildCreditFundingReport({
14157
+ dvm: noticeDvm(args),
14158
+ endpoint: args.ref.endpoint,
14159
+ reason: ctx.reason,
14160
+ amountMicro: outcome.fundedMicro ?? ctx.fundMicro,
14161
+ currency: ctx.currency,
14162
+ route: outcome.rail,
14163
+ // Every funding this module makes is a `/v1/credit` call of its own,
14164
+ // including the open — the job it followed paid per-call.
14165
+ ownRoundTrip: true,
14166
+ ...outcome.railReason ? { routeReason: outcome.railReason } : {},
14167
+ ...outcome.railSource ? { routeReasonSource: outcome.railSource } : {},
14168
+ ...outcome.x402Flavour ? { x402Flavour: outcome.x402Flavour } : {},
14169
+ ...outcome.tempoIntent ? { tempoIntent: outcome.tempoIntent } : {},
14170
+ outcome,
14171
+ ...ctx.menu.lightning_min_micro !== void 0 ? { lightningMinMicro: ctx.menu.lightning_min_micro } : {},
14172
+ ...outcome.credit ? { balanceMicro: outcome.credit.remaining_micro } : {}
14173
+ }),
14174
+ args.human
14175
+ );
14176
+ return;
14177
+ }
14178
+ case "settlement_pending":
14179
+ info(`${what} at ${args.ref.endpoint} \u2014 ${outcome.display}${hint}`);
14180
+ incomplete("credit_funding_settlement_pending");
14181
+ return;
14182
+ case "refused": {
14183
+ const adopted = outcome.error?.code === "settlement_pending" && args.signing ? adoptWedgedChannelDrain({
14184
+ endpoint: args.ref.endpoint,
14185
+ // The store identity, which is `providerInfo`'s and not the
14186
+ // typeable handle below — the same key `applyReceiptCredit` and
14187
+ // `markRefillRailUnavailable` write this credit under.
14188
+ ...settleIdentityArgs(args),
14189
+ handle: noticeDvm(args),
14190
+ callerPubkey: args.signing.pubkey,
14191
+ creditId: outcome.creditId,
14192
+ data: outcome.error.data
14193
+ }) : void 0;
14194
+ const reclaim = adopted ? ` ${adopted.advice}` : "";
14195
+ info(
14196
+ outcome.spentSats !== void 0 || outcome.principalSats !== void 0 ? `${what} paid but not credited \u2014 ${outcome.display}${hint}${reclaim}` : `${what} skipped \u2014 ${outcome.display}${hint}${reclaim}`
14197
+ );
14198
+ incomplete("credit_funding_refused", adopted);
14199
+ return;
14200
+ }
14201
+ case "unavailable": {
14202
+ const pendingIntent = outcome.error?.code === "x402_voucher_pending" || outcome.error?.code === "x402_exact_authorization_pending" || outcome.error?.code === "tempo_charge_pending";
14203
+ if (outcome.error?.code === "below_rail_minimum" || pendingIntent) {
14204
+ info(`${what} at ${args.ref.endpoint} deferred \u2014 ${outcome.display}${hint}`);
14205
+ if (pendingIntent) incomplete("credit_funding_deferred");
14206
+ return;
14207
+ }
14208
+ if (outcome.railReason === "forced" && outcome.railSource !== "credit_bound") {
14209
+ info(`${what} at ${args.ref.endpoint} skipped \u2014 ${outcome.display}${hint}`);
14210
+ return;
14211
+ }
14212
+ return;
14213
+ }
14214
+ }
14215
+ }
14216
+
14217
+ // src/lib/provider-currency.ts
14218
+ async function providerCurrency(args) {
14219
+ if (!args.receipt?.settlement) return void 0;
14220
+ const upfront = args.status?.upfrontPayment?.currency;
14221
+ if (upfront) return upfront;
14222
+ const ask = [...args.messages ?? []].sort((a, b) => a.seq - b.seq).findLast((message2) => message2.from === "provider" && message2.type === "payment-request" && message2.content.credit?.currency);
14223
+ if (ask?.type === "payment-request" && ask.content.credit) return ask.content.credit.currency;
14224
+ try {
14225
+ return (await args.transport.describe(args.ref, { timeoutMs: 5e3 })).credit?.currency;
14226
+ } catch {
14227
+ return void 0;
14228
+ }
14229
+ }
14230
+
14231
+ // src/lib/job-ending.ts
14232
+ var PAYMENT_IN_PROGRESS_ATTEMPTS = 5;
14233
+ var MAX_RETRY_DELAY_MS = 3e4;
14234
+ async function retryWhilePaymentInProgress(send, options = {}) {
14235
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms)));
14236
+ for (let attempt = 1; ; attempt++) {
14237
+ try {
14238
+ return await send();
14239
+ } catch (error) {
14240
+ if (!(error instanceof DvmError) || error.code !== "payment_in_progress" || attempt >= PAYMENT_IN_PROGRESS_ATTEMPTS) throw error;
14241
+ const requested = error.data?.retry_after_ms;
14242
+ const delay = typeof requested === "number" && Number.isFinite(requested) ? Math.min(Math.max(requested, 0), MAX_RETRY_DELAY_MS) : 2e3;
14243
+ progressNotice(`A payment for this job is being verified; retrying in ${Math.ceil(delay / 1e3)} s...`, options.human);
14244
+ await sleep(delay);
14245
+ }
14246
+ }
14247
+ }
14248
+ async function readEnding(args) {
14249
+ const status2 = await observeJobContent(args.jobId, args.transport, args.ref, { timeoutMs: 5e3, jobToken: args.jobToken });
14250
+ if (status2 && isTerminalJobStatus(status2.status)) args.onTerminal?.(status2);
14251
+ if (!status2 || !isTerminalJobStatus(status2.status) || !status2.receipt?.settlement) return { status: status2 };
14252
+ if (args.persistLocalState) {
14253
+ const capture = captureTransportReceipt(args.jobId, status2);
14254
+ const job = loadJob(args.jobId);
14255
+ if (job) await settleCreditAfterRead({ job, capture, transport: args.transport, human: args.human });
14256
+ }
14257
+ const currency = args.persistLocalState ? void 0 : await providerCurrency({ receipt: status2.receipt, status: status2, transport: args.transport, ref: args.ref });
14258
+ const { settlement } = terminalSettlementFields(args.jobId, {
14259
+ status: status2.status,
14260
+ receipt: status2.receipt,
14261
+ persistLocalState: args.persistLocalState,
14262
+ currency
14263
+ });
14264
+ return { status: status2, ...settlement?.charged_micro !== void 0 ? { settlement } : {} };
14265
+ }
14266
+ function cancelledDisplay(settlement) {
14267
+ const stopped = settlement.stopped_micro ?? 0;
14268
+ const lead = stopped > 0 ? `Stopped. The ${formatMicro(stopped, settlement.currency ?? null)} paid for the work in progress is not refunded.` : "Stopped. No work was in progress, so only finished work is charged.";
14269
+ return `${lead} ${settlement.display}`;
14270
+ }
14271
+
13749
14272
  // src/commands/dvm-identity.ts
13750
14273
  function dvmIdentity(dvmId, capability) {
13751
14274
  const out = {};
@@ -13765,27 +14288,104 @@ async function cancelWithAccess(jobId, opts, access) {
13765
14288
  const json3 = (data) => providerJobJson(data, !!stored);
13766
14289
  const transport = createDvmTransport();
13767
14290
  progressNotice("Cancelling job...", opts.human);
13768
- await transport.cancel(jobId, opts.reason, ref, { jobToken });
13769
- transport.close();
14291
+ await retryWhilePaymentInProgress(() => transport.cancel(jobId, opts.reason, ref, { jobToken }), { human: opts.human });
13770
14292
  if (!access.endpointOverridden) markJobTerminal(
13771
14293
  jobId,
13772
14294
  "cancelled",
13773
14295
  opts.reason !== void 0 ? { message: opts.reason } : {},
13774
14296
  { callerCancelled: true }
13775
14297
  );
14298
+ const { settlement, status: status2 } = await readEnding({
14299
+ jobId,
14300
+ transport,
14301
+ ref,
14302
+ jobToken,
14303
+ persistLocalState: !access.endpointOverridden,
14304
+ human: opts.human
14305
+ });
14306
+ transport.close();
13776
14307
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
14308
+ const receiptPending = !settlement && status2 !== void 0 && isTerminalJobStatus(status2.status) && !status2.receipt && !status2.receiptParseError && !access.endpointOverridden && expectsReceipt(jobId, stored);
14309
+ const display = settlement ? cancelledDisplay(settlement) : receiptPending ? `Stopped. Its receipt is not available yet; \`dvm status ${guidanceJobArg(jobId)}\` shows what was charged once it is.` : void 0;
13777
14310
  if (opts.human) {
13778
14311
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
14312
+ if (display) info(display);
13779
14313
  } else {
13780
14314
  json3({
13781
14315
  jobId,
13782
14316
  ...dvmIdentity(stored?.dvmId, stored?.capability),
13783
14317
  status: "cancelled",
13784
14318
  ...opts.reason ? { reason: opts.reason } : {},
14319
+ ...settlement ? { settlement } : {},
14320
+ ...display ? { display } : {},
13785
14321
  next_action: null
13786
14322
  });
13787
14323
  }
13788
14324
  }
14325
+ function expectsReceipt(jobId, stored) {
14326
+ return stored?.receiptsSupported === true || loadMessages(jobId).some((message2) => message2.from === "provider" && message2.type === "payment-request" && typeof message2.content.charged_if_declined_micro === "number");
14327
+ }
14328
+
14329
+ // src/commands/decline.ts
14330
+ async function decline(jobId, opts) {
14331
+ const access = resolveJobAccess(jobId, opts);
14332
+ return withJobTokenRedaction(access.jobToken, () => declineWithAccess(jobId, opts, access));
14333
+ }
14334
+ async function declineWithAccess(jobId, opts, access) {
14335
+ const { stored, ref, jobToken } = access;
14336
+ const json3 = (data) => providerJobJson(data, !!stored);
14337
+ const job = guidanceJobArg(jobId);
14338
+ const transport = createDvmTransport();
14339
+ progressNotice("Declining...", opts.human);
14340
+ const content = opts.reason !== void 0 ? { reason: opts.reason } : {};
14341
+ await retryWhilePaymentInProgress(
14342
+ () => transport.sendMessage(jobId, { type: "decline", content }, ref, { jobToken }),
14343
+ { human: opts.human }
14344
+ );
14345
+ const ending = await readEnding({
14346
+ jobId,
14347
+ transport,
14348
+ ref,
14349
+ jobToken,
14350
+ persistLocalState: !access.endpointOverridden,
14351
+ human: opts.human,
14352
+ onTerminal: (status2) => {
14353
+ if (!access.endpointOverridden && isTerminalJobStatus(status2.status)) markJobTerminal(
14354
+ jobId,
14355
+ status2.status,
14356
+ opts.reason !== void 0 ? { message: opts.reason } : {},
14357
+ { callerCancelled: true, callerDeclined: true }
14358
+ );
14359
+ }
14360
+ });
14361
+ transport.close();
14362
+ const observed = ending.status?.status;
14363
+ if (observed !== void 0 && !isTerminalJobStatus(observed)) {
14364
+ throw new DvmError(
14365
+ "decline_unsupported",
14366
+ `The provider accepted the decline, but the job is still ${observed}.`,
14367
+ `This DVM does not end a job at a decline. Pay with \`dvm pay ${job}\`, let the ask expire, or stop the work now with \`dvm cancel ${job}\`.`,
14368
+ { jobId, status: observed }
14369
+ );
14370
+ }
14371
+ const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
14372
+ const { settlement } = ending;
14373
+ const display = observed === void 0 ? `Decline sent, but the job's status could not be read. Check it with \`dvm status ${job}\`.` : settlement ? `Declined; the job has ended. ${settlement.display}` : `Declined; the job has ended. Its receipt is not available yet; \`dvm status ${job}\` shows the final charge once it is.`;
14374
+ if (opts.human) {
14375
+ info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""}: ${display}`);
14376
+ return;
14377
+ }
14378
+ json3({
14379
+ jobId,
14380
+ ...dvmIdentity(stored?.dvmId, stored?.capability),
14381
+ status: observed ?? "unknown",
14382
+ declined: true,
14383
+ ...opts.reason !== void 0 ? { reason: opts.reason } : {},
14384
+ ...settlement ? { settlement } : {},
14385
+ display,
14386
+ next_action: observed === void 0 ? pollNextAction(jobId, display) : null
14387
+ });
14388
+ }
13789
14389
 
13790
14390
  // src/commands/config.ts
13791
14391
  import { createInterface } from "readline";
@@ -13990,14 +14590,14 @@ async function confirmRollback(stored, preview, opts) {
13990
14590
  async function withStrandingChecked(removing, commit) {
13991
14591
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
13992
14592
  if (leaving.has("tempo")) {
13993
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-EOP5IHJT.js");
14593
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-FMBCHD2M.js");
13994
14594
  await assertTempoWalletIdle2("disconnect");
13995
14595
  }
13996
14596
  if (!leaving.has("x402")) return commit();
13997
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-KPPGYK5N.js");
13998
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-7YRNRLDQ.js");
13999
- const { ensureAddress: ensureAddress2 } = await import("./internal-KPPGYK5N.js");
14000
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-LASVQ72F.js");
14597
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-O7IQD6EQ.js");
14598
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-MIJH3JE4.js");
14599
+ const { ensureAddress: ensureAddress2 } = await import("./internal-O7IQD6EQ.js");
14600
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
14001
14601
  return withX402ChannelLock2(async () => {
14002
14602
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
14003
14603
  if (unsettled.length > 0) {
@@ -14367,63 +14967,6 @@ function routeDisplay(h) {
14367
14967
  return out;
14368
14968
  }
14369
14969
 
14370
- // src/lib/credit-reclaim.ts
14371
- function adoptWedgedChannelDrain(args) {
14372
- const drainId = args.data?.settlement_drain_id;
14373
- if (typeof drainId !== "string" || drainId === "") return void 0;
14374
- const identityArg = args.identity ? [args.identity] : [];
14375
- const stored = loadCredit(args.endpoint, args.callerPubkey, args.identity);
14376
- if (!stored) {
14377
- ensureProvisionalCredit({
14378
- endpoint: args.endpoint,
14379
- ...args.identity ? { identity: args.identity } : {},
14380
- callerPubkey: args.callerPubkey,
14381
- creditId: args.creditId,
14382
- currency: "usd",
14383
- targetMicro: 0
14384
- });
14385
- }
14386
- const recorded = pendingDrainFor(stored, args.creditId);
14387
- if (recorded && recorded.drainId !== drainId) {
14388
- clearPendingDrain(args.endpoint, args.callerPubkey, recorded, ...identityArg);
14389
- }
14390
- recordPendingDrain(
14391
- args.endpoint,
14392
- args.callerPubkey,
14393
- {
14394
- drainId,
14395
- creditId: args.creditId,
14396
- method: "x402",
14397
- payout: {},
14398
- requestedAt: Date.now()
14399
- },
14400
- ...identityArg
14401
- );
14402
- recordCreditX402Instrument(
14403
- args.endpoint,
14404
- args.callerPubkey,
14405
- args.creditId,
14406
- "x402_channel",
14407
- args.identity
14408
- );
14409
- const command = reclaimCommand(args.handle ?? args.endpoint, stored, args.creditId);
14410
- return {
14411
- drainId,
14412
- command,
14413
- // Written to be appended to the server's own refusal, never to replace it:
14414
- // that copy is the one saying nothing was charged and that paying per call
14415
- // still works, which is what a human needs to hear. What it cannot know is
14416
- // that this CLI just recorded the id, so the reclaim no longer carries it.
14417
- advice: `Drain ${drainId} is now this credit's recorded reclaim here, so '${command}' posts it \u2014 no --drain-id needed.`
14418
- };
14419
- }
14420
- function reclaimCommand(handle, tracked, creditId) {
14421
- return !tracked || tracked.creditId === creditId ? `dvm credit drain ${shellQuoteArg(handle)}` : creditDrainCommand(handle, creditId);
14422
- }
14423
- function creditDrainCommand(handle, creditId) {
14424
- return `dvm credit drain ${shellQuoteArg(handle)} --credit-id ${shellQuoteArg(creditId)}`;
14425
- }
14426
-
14427
14970
  // src/lib/credit-guidance.ts
14428
14971
  function repeatUseCreditHint(dvm) {
14429
14972
  return `First paid use settles per-call; ordinary repeat jobs use eligible credit automatically. For 2+ calls, returning later, or a batch, inspect signed balance and funding headroom with 'dvm credit balance ${dvm}'; manually fund only user-authorized prepay/batches or a degraded mint.`;
@@ -20658,8 +21201,8 @@ async function probeX402(x402, timeoutMs) {
20658
21201
  let network;
20659
21202
  let address;
20660
21203
  try {
20661
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-LASVQ72F.js");
20662
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-KPPGYK5N.js");
21204
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
21205
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-O7IQD6EQ.js");
20663
21206
  const wallet = loadX402Wallet2();
20664
21207
  if (!wallet) {
20665
21208
  const storedKey = x402.privateKey;
@@ -20711,8 +21254,8 @@ async function probeMpp(mpp, timeoutMs) {
20711
21254
  if (!mpp) return null;
20712
21255
  if (mpp.method === "tempo") {
20713
21256
  try {
20714
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-4A5M3FVO.js");
20715
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-KPPGYK5N.js");
21257
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-U3WBWIIH.js");
21258
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-O7IQD6EQ.js");
20716
21259
  const account = await connectedTempoAccount2();
20717
21260
  if (!account) {
20718
21261
  return {
@@ -23184,14 +23727,14 @@ function buildFeedbackHint(jobId) {
23184
23727
  }
23185
23728
  function noteFeedbackNudge(nudge, human) {
23186
23729
  info(`${nudge.display} ${nudge.hint}`);
23187
- if (!human) pending2.feedback_nudge = nudge;
23730
+ if (!human) pending3.feedback_nudge = nudge;
23188
23731
  }
23189
23732
  function noteFeedbackHint(hint, human) {
23190
- if (!human) pending2.feedback_hint = hint;
23733
+ if (!human) pending3.feedback_hint = hint;
23191
23734
  }
23192
23735
  function takeFeedbackNoticeFields() {
23193
- const taken = { ...pending2 };
23194
- pending2 = {};
23736
+ const taken = { ...pending3 };
23737
+ pending3 = {};
23195
23738
  return taken;
23196
23739
  }
23197
23740
  function feedbackCommand(jobId, verdict) {
@@ -23201,7 +23744,7 @@ function buildFeedbackIntro(approval) {
23201
23744
  const options = "Feedback nudges like this one are on by default. 'dvm feedback --posture ask' keeps the ask-first default, '--posture auto' sends without asking, and '--posture off' turns nudges off.";
23202
23745
  return approval === "ask" ? `${options} Relay these options to your user as part of this first approval request.` : options;
23203
23746
  }
23204
- var pending2 = {};
23747
+ var pending3 = {};
23205
23748
 
23206
23749
  // src/lib/feedback-nudges.ts
23207
23750
  var DEFAULT_FEEDBACK_POSTURE = "ask";
@@ -24026,12 +24569,16 @@ function persistStreamOutcome(outcome) {
24026
24569
  const { jobId, messages: messages2, cursor, afterSeq, extra, providerStatus } = outcome;
24027
24570
  const stored = loadJob(jobId);
24028
24571
  const callerCancelled = outcome.callerCancelled ?? stored?.callerCancelled;
24029
- const terminal = streamTerminalStatus(messages2, { providerStatus, callerCancelled });
24572
+ const terminal = streamTerminalStatus(messages2, {
24573
+ providerStatus,
24574
+ callerCancelled,
24575
+ callerDeclined: outcome.callerDeclined ?? stored?.callerDeclined
24576
+ });
24030
24577
  const log = terminal ? fullMessageLog(jobId, messages2, afterSeq) : void 0;
24031
24578
  const providerTerminal = providerStatus?.status && isTerminalJobStatus(providerStatus.status);
24032
24579
  if (terminal && (log || providerTerminal)) {
24033
24580
  const saved = stored?.status === terminal ? stored.completion : void 0;
24034
- const fromLog = log?.some((m) => m.type === "complete" || m.type === "cancel") ? completionFromMessages(log) : void 0;
24581
+ const fromLog = log?.some((m) => m.type === "complete" || m.type === "cancel" || m.type === "decline") ? completionFromMessages(log) : void 0;
24035
24582
  const retained = saved ?? fromLog;
24036
24583
  const completion = providerStatus?.content_available === false && retained ? retained : {
24037
24584
  ...saved,
@@ -24051,9 +24598,10 @@ function persistStreamOutcome(outcome) {
24051
24598
  function streamTerminalStatus(messages2, context = {}) {
24052
24599
  const providerStatus = context.providerStatus?.status;
24053
24600
  if (providerStatus && isTerminalJobStatus(providerStatus)) return providerStatus;
24054
- const last = messages2.findLast((m) => m.type === "complete" || m.type === "cancel");
24601
+ const last = messages2.findLast((m) => m.type === "complete" || m.type === "cancel" || m.type === "decline" && context.callerDeclined === true);
24055
24602
  if (!last) return void 0;
24056
24603
  if (last.type === "complete") return "completed";
24604
+ if (last.type === "decline") return "cancelled";
24057
24605
  return context.callerCancelled ? "cancelled" : "failed";
24058
24606
  }
24059
24607
  function fullMessageLog(jobId, messages2, afterSeq) {
@@ -24140,6 +24688,9 @@ function formatMessageHuman(msg, jobId, artifactSession) {
24140
24688
  case "cancel":
24141
24689
  info(`[${msg.seq}] Job ended${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
24142
24690
  break;
24691
+ case "decline":
24692
+ info(`[${msg.seq}] ${prefix} declined; the job ended${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
24693
+ break;
24143
24694
  default:
24144
24695
  info(`[${seq}] ${prefix} sent a message of type "${type}".`);
24145
24696
  }
@@ -24152,14 +24703,15 @@ function nextActionHuman(action) {
24152
24703
  case "respond":
24153
24704
  case "pay": {
24154
24705
  const display = action.display.replace(/`dvm status '<job_id>'`/g, () => `\`dvm status ${shellQuoteArg(action.job_id)}\``);
24155
- const template = action.hint.match(/`(dvm[\s\S]*)`/)?.[1]?.replace(/^(dvm (?:message|pay|status)) '<job_id>'/, (_, prefix) => `${prefix} ${shellQuoteArg(action.job_id)}`);
24706
+ const template = action.hint.match(/`(dvm[^`]*)`/)?.[1]?.replace(/^(dvm (?:message|pay|status)) '<job_id>'/, (_, prefix) => `${prefix} ${shellQuoteArg(action.job_id)}`);
24156
24707
  const command = action.type === "respond" ? template?.replace("--prompt-id '<prompt_id>'", () => `--prompt-id ${shellQuoteArg(action.prompt_id)}`) : template;
24157
24708
  if (command?.startsWith("dvm status ")) return `Next: ${action.type === "pay" ? "the provider's charge of " : ""}${display}`;
24158
24709
  if (action.type === "respond") {
24159
24710
  return `Next: ${display} Provider is waiting for your input. ${command ? `Run \`${command}\`.` : action.hint}`;
24160
24711
  }
24161
24712
  const thresholdHint = action.hint.match(/ For the next run, use --auto-pay-below .+$/)?.[0] ?? "";
24162
- return `Next: Payment required to continue: ${display}${display.endsWith(".") ? "" : "."} Run \`${command ?? `dvm pay ${shellQuoteArg(action.job_id)}`}\`.${thresholdHint}`;
24713
+ const decline2 = action.charged_if_declined_micro !== void 0 && command?.startsWith("dvm pay ") ? ` To stop instead, run \`dvm decline ${shellQuoteArg(action.job_id)}\`.` : "";
24714
+ return `Next: Payment required to continue: ${display}${display.endsWith(".") ? "" : "."} Run \`${command ?? `dvm pay ${shellQuoteArg(action.job_id)}`}\`.${decline2}${thresholdHint}`;
24163
24715
  }
24164
24716
  case "poll": {
24165
24717
  const hint = typeof action.hint === "string" ? action.hint : action.hint.text;
@@ -24397,7 +24949,8 @@ async function messagesWithAccess(jobId, opts, access) {
24397
24949
  const nextAction = withRefundNextAction(jobId, actionFromMessages(msgs) ?? (streamTerminalStatus(msgs, { providerStatus: providerStatus2 }) || isTerminal ? null : pollNextAction(jobId)), refunds);
24398
24950
  const content2 = jobContentFields(jobId, providerStatus2, opts.human);
24399
24951
  const resolvedAction2 = await resolveNextAction2(nextAction, msgs, providerStatus2?.status);
24400
- const settlement2 = observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden);
24952
+ const currency2 = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus2?.receipt, status: providerStatus2, messages: msgs, transport, ref }) : void 0;
24953
+ const settlement2 = observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden, currency2);
24401
24954
  transport.close();
24402
24955
  if (opts.human) {
24403
24956
  if (settlement2.settlement) info(settlement2.settlement.display);
@@ -24464,7 +25017,9 @@ async function messagesWithAccess(jobId, opts, access) {
24464
25017
  }
24465
25018
  const content = jobContentFields(jobId, providerStatus, opts.human);
24466
25019
  const resolvedAction = await resolveNextAction2(result.nextAction, result.messages, providerStatus?.status ?? result.providerStatus?.status);
24467
- const settlement = observedSettlementFields(jobId, providerStatus ?? result.providerStatus, !access.endpointOverridden);
25020
+ const observed = providerStatus ?? result.providerStatus;
25021
+ const currency = access.endpointOverridden ? await providerCurrency({ receipt: observed?.receipt, status: observed, messages: result.messages, transport, ref }) : void 0;
25022
+ const settlement = observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
24468
25023
  transport.close();
24469
25024
  if (opts.human) {
24470
25025
  if (settlement.settlement) info(settlement.settlement.display);
@@ -24646,7 +25201,8 @@ async function messageWithAccess(jobId, text, opts, access) {
24646
25201
  });
24647
25202
  }
24648
25203
  const content = jobContentFields(jobId, providerStatus, opts.human);
24649
- const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden);
25204
+ const currency = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus?.receipt, status: providerStatus, messages: result.messages, transport, ref }) : void 0;
25205
+ const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
24650
25206
  transport.close();
24651
25207
  if (opts.human) {
24652
25208
  if (settlement.settlement) info(settlement.settlement.display);
@@ -24862,7 +25418,8 @@ async function payWithAccess(jobId, opts, access) {
24862
25418
  human: opts.human
24863
25419
  });
24864
25420
  }
24865
- const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden);
25421
+ const currency = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus?.receipt, status: providerStatus, messages: streamResult.messages, transport, ref }) : void 0;
25422
+ const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
24866
25423
  transport.close();
24867
25424
  const identifier = stored.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
24868
25425
  if (opts.human) {
@@ -25815,374 +26372,6 @@ function artifactContent(msg) {
25815
26372
  // src/commands/request.ts
25816
26373
  import { createHash as createHash4, randomUUID as randomUUID4 } from "crypto";
25817
26374
 
25818
- // src/lib/credit-defer.ts
25819
- function noteDeferredFunding(funding) {
25820
- pending3 = funding;
25821
- }
25822
- function takeDeferredFunding() {
25823
- const taken = pending3;
25824
- pending3 = void 0;
25825
- return taken;
25826
- }
25827
- var pending3;
25828
-
25829
- // src/lib/credit-topup.ts
25830
- async function settleCreditAfterJob(args) {
25831
- const deferred = args.deferred ?? takeDeferredFunding();
25832
- try {
25833
- await settle(args);
25834
- } catch (err) {
25835
- info(
25836
- `Credit bookkeeping failed (job outcome unaffected): ${err instanceof Error ? err.message : String(err)}`
25837
- );
25838
- }
25839
- if (deferred) {
25840
- try {
25841
- await fundDeferred(args, deferred);
25842
- } catch (err) {
25843
- info(
25844
- `Credit funding failed (job outcome unaffected): ${err instanceof Error ? err.message : String(err)}`
25845
- );
25846
- }
25847
- }
25848
- if (args.allowTopup !== false) {
25849
- const refill = args.refillPocket ?? (await import("./pocket-refill-E2QVQDME.js")).refillPocketIfLow;
25850
- await refill({ human: args.human }).catch(() => void 0);
25851
- }
25852
- }
25853
- async function settleCreditAfterRead(args) {
25854
- const { job, capture } = args;
25855
- const binding = job.creditBinding;
25856
- const receipt = capture.receipt;
25857
- if (job.strictPerCall || !binding || "unbound" in binding || !receipt?.credit || receipt.job_id !== job.id || receipt.requester_pubkey !== binding.callerPubkey || receipt.credit.credit_id !== binding.creditId || receipt.credit.draw_id !== binding.drawId || receipt.credit.credit_id.startsWith("imp:")) return;
25858
- const builder = loadJob(job.id)?.builderAnchor ?? job.builderAnchor;
25859
- await settleCreditAfterJob({
25860
- capture,
25861
- transport: args.transport,
25862
- ref: { endpoint: job.endpoint },
25863
- dvmId: job.dvmId,
25864
- providerInfo: builder ? { builder } : void 0,
25865
- callerPubkey: binding.callerPubkey,
25866
- allowTopup: false,
25867
- human: args.human
25868
- });
25869
- }
25870
- function settleIdentity(args) {
25871
- return providerDvmIdentity(args.providerInfo);
25872
- }
25873
- function settleIdentityArgs(args) {
25874
- const identity = settleIdentity(args);
25875
- return identity ? { identity } : {};
25876
- }
25877
- function settleIdentityArg(args) {
25878
- const identity = settleIdentity(args);
25879
- return identity ? [identity] : [];
25880
- }
25881
- function noticeDvm(args) {
25882
- return args.dvmId ?? args.ref.endpoint;
25883
- }
25884
- async function settle(args) {
25885
- const receipt = args.capture?.receipt;
25886
- const credit = receipt?.credit;
25887
- const callerPubkey = args.signing?.pubkey ?? args.callerPubkey;
25888
- if (!receipt || !credit || !callerPubkey || args.capture?.status !== "verified" && args.capture?.status !== "verified_unattested" || receipt.requester_pubkey !== callerPubkey) return;
25889
- if (credit.credit_id.startsWith("imp:")) {
25890
- const applied2 = applyImplicitReceiptCredit({
25891
- endpoint: args.ref.endpoint,
25892
- ...settleIdentityArgs(args),
25893
- callerPubkey,
25894
- jobId: receipt.job_id,
25895
- outcome: receipt.outcome,
25896
- credit,
25897
- currency: args.providerInfo?.pricing?.max?.currency ?? args.providerInfo?.credit?.currency ?? "usd",
25898
- issuedAtMs: receipt.issued_at * 1e3
25899
- });
25900
- if (applied2.mismatch) renderBalanceMismatch(args.ref.endpoint, applied2.mismatch);
25901
- return;
25902
- }
25903
- const applied = applyReceiptCredit({
25904
- endpoint: args.ref.endpoint,
25905
- ...settleIdentityArgs(args),
25906
- callerPubkey,
25907
- jobId: receipt.job_id,
25908
- outcome: receipt.outcome,
25909
- credit,
25910
- drawFundings: jobDrawFundings(receipt.job_id, args.ref.endpoint, callerPubkey, credit)
25911
- });
25912
- if (!applied.credit) return;
25913
- if (applied.mismatch) {
25914
- renderBalanceMismatch(args.ref.endpoint, applied.mismatch);
25915
- }
25916
- if (args.allowTopup === false || !args.signing) return;
25917
- if (receipt.outcome !== "completed") return;
25918
- const record2 = applied.credit;
25919
- if (record2.status !== "active") return;
25920
- if (record2.reconciliationPending) return;
25921
- if (!needsTopup(record2.remainingMicro, record2.targetMicro)) return;
25922
- const posture = effectiveCreditPosture(
25923
- args.config ?? loadConfig()?.credit,
25924
- args.ref.endpoint,
25925
- providerDvmIdentity(args.providerInfo)
25926
- );
25927
- if (posture.posture === "off") return;
25928
- const held = pendingDrainFor(record2, record2.creditId);
25929
- if (held) {
25930
- reportRefillHeldByDrain(args, record2, held, args.signing.pubkey);
25931
- return;
25932
- }
25933
- await fundTopup(args, record2, posture);
25934
- }
25935
- function renderBalanceMismatch(endpoint, mismatch) {
25936
- const prior = mismatch.priorJobId ? `the previous countersigned receipt (job ${mismatch.priorJobId})` : "the recorded balance projection";
25937
- info(
25938
- `Warning: credit balance mismatch at ${endpoint}. The DVM-signed receipt for job ${mismatch.jobId} (draw ${mismatch.drawId}, ledger seq ${String(mismatch.ledgerSeq)}) reports $${formatUsd(mismatch.reportedMicro / 1e6)} remaining, but ${prior} implies $${formatUsd(mismatch.expectedMicro / 1e6)}. Both signed artifacts are stored \u2014 inspect them with 'dvm receipts show <job-id>' and re-read the server with 'dvm credit balance'.`
25939
- );
25940
- }
25941
- function reportRefillHeldByDrain(args, record2, held, callerPubkey) {
25942
- const identityArg = settleIdentityArg(args);
25943
- if (!markRefillDrainNoticed(
25944
- args.ref.endpoint,
25945
- callerPubkey,
25946
- record2.creditId,
25947
- held.drainId,
25948
- ...identityArg
25949
- )) {
25950
- return;
25951
- }
25952
- noteCreditRefillUnavailable(
25953
- buildCreditRefillDrainPending({
25954
- dvm: noticeDvm(args),
25955
- endpoint: args.ref.endpoint,
25956
- creditId: record2.creditId,
25957
- drainId: held.drainId,
25958
- // The reclaim as the doors that record one spell it ,
25959
- // rather than a third spelling of the same command.
25960
- drainCommand: reclaimCommand(noticeDvm(args), record2, record2.creditId),
25961
- balanceMicro: record2.remainingMicro,
25962
- currency: record2.currency
25963
- }),
25964
- args.human
25965
- );
25966
- }
25967
- async function fundTopup(args, record2, posture) {
25968
- const menu = record2.menu;
25969
- if (!menu) return;
25970
- if (!args.transport.credit) return;
25971
- const signing = args.signing;
25972
- if (!signing) return;
25973
- const identityArg = settleIdentityArg(args);
25974
- const boundRail = isCreditFundRail(record2.rail) ? record2.rail : void 0;
25975
- const boundRailAvailable = boundRail ? availableRails({
25976
- menu,
25977
- ...args.providerInfo ? { providerInfo: args.providerInfo } : {}
25978
- }).includes(boundRail) : void 0;
25979
- if (boundRail && !boundRailAvailable) {
25980
- if (!markRefillRailUnavailable(
25981
- args.ref.endpoint,
25982
- signing.pubkey,
25983
- record2.creditId,
25984
- boundRail,
25985
- ...identityArg
25986
- )) {
25987
- return;
25988
- }
25989
- noteCreditRefillUnavailable(
25990
- buildCreditRefillUnavailable({
25991
- dvm: noticeDvm(args),
25992
- endpoint: args.ref.endpoint,
25993
- creditId: record2.creditId,
25994
- boundRail,
25995
- balanceMicro: record2.remainingMicro,
25996
- currency: record2.currency
25997
- }),
25998
- args.human
25999
- );
26000
- return;
26001
- }
26002
- if (boundRail) {
26003
- clearRefillRailUnavailable(args.ref.endpoint, signing.pubkey, record2.creditId, ...identityArg);
26004
- }
26005
- const forced = forcedRefillRail(args, record2);
26006
- const railFloorMicro = forced.rail === "lightning" && menu.lightning_min_micro !== void 0 ? Math.max(menu.min_micro, menu.lightning_min_micro) : menu.min_micro;
26007
- let fundMicro = Math.max(record2.targetMicro - record2.remainingMicro, railFloorMicro);
26008
- fundMicro = Math.min(fundMicro, menu.max_micro - record2.remainingMicro);
26009
- if (fundMicro < railFloorMicro) {
26010
- if (railFloorMicro > menu.min_micro) {
26011
- info(
26012
- `Credit top-up at ${args.ref.endpoint} deferred: this credit refills over Lightning, which needs at least $${formatUsd(railFloorMicro / 1e6)} per funding, but only $${formatUsd(Math.max(0, menu.max_micro - record2.remainingMicro) / 1e6)} of headroom remains under the DVM's balance ceiling. It retries after a later job.`
26013
- );
26014
- }
26015
- return;
26016
- }
26017
- if (posture.posture === "suggest") {
26018
- noteCreditSuggestion(
26019
- buildCreditSuggestion({
26020
- dvm: noticeDvm(args),
26021
- endpoint: args.ref.endpoint,
26022
- posture: posture.posture,
26023
- postureSource: posture.source,
26024
- suppressed: {
26025
- reason: "refill",
26026
- fundMicro,
26027
- targetMicro: record2.targetMicro,
26028
- currency: record2.currency
26029
- }
26030
- }),
26031
- args.human
26032
- );
26033
- return;
26034
- }
26035
- const outcome = await fundCredit({
26036
- transport: args.transport,
26037
- ref: args.ref,
26038
- signing,
26039
- creditId: record2.creditId,
26040
- amountMicro: fundMicro,
26041
- menu,
26042
- targetMicro: record2.targetMicro,
26043
- maxDepositMicro: fundMicro,
26044
- human: args.human,
26045
- ...forced.rail ? { rail: forced.rail, railSource: forced.source } : {},
26046
- ...args.providerInfo ? { providerInfo: args.providerInfo } : {},
26047
- ...args.signBody ? { signBody: args.signBody } : {}
26048
- });
26049
- reportFunding(args, outcome, {
26050
- reason: "below_refill_target",
26051
- fundMicro,
26052
- currency: record2.currency,
26053
- menu
26054
- });
26055
- }
26056
- async function fundDeferred(args, deferred) {
26057
- if (args.allowTopup === false) return;
26058
- if (args.capture?.receipt?.outcome !== "completed") return;
26059
- if (!args.transport.credit) return;
26060
- const signing = args.signing;
26061
- if (!signing) return;
26062
- const posture = effectiveCreditPosture(
26063
- args.config ?? loadConfig()?.credit,
26064
- args.ref.endpoint,
26065
- providerDvmIdentity(args.providerInfo)
26066
- );
26067
- if (posture.posture !== "auto") return;
26068
- const outcome = await fundCredit({
26069
- transport: args.transport,
26070
- ref: args.ref,
26071
- signing,
26072
- creditId: deferred.creditId,
26073
- amountMicro: deferred.fundMicro,
26074
- menu: deferred.menu,
26075
- targetMicro: deferred.targetMicro,
26076
- maxDepositMicro: deferred.maxDepositMicro ?? deferred.fundMicro,
26077
- human: args.human,
26078
- ...deferred.pinnedRail ? { rail: deferred.pinnedRail, railSource: deferred.pinnedRailSource } : {},
26079
- ...args.providerInfo ? { providerInfo: args.providerInfo } : {},
26080
- ...args.signBody ? { signBody: args.signBody } : {}
26081
- });
26082
- reportFunding(args, outcome, {
26083
- reason: deferred.reason === "open" ? "no_credit_open" : "below_refill_target",
26084
- fundMicro: deferred.fundMicro,
26085
- currency: deferred.currency,
26086
- menu: deferred.menu,
26087
- label: deferred.reason === "open" ? "Credit opening" : "Credit top-up"
26088
- });
26089
- }
26090
- function forcedRefillRail(args, record2) {
26091
- if (isCreditFundRail(record2.rail)) return { rail: record2.rail, source: "credit_bound" };
26092
- const pin = effectiveFundingRail(
26093
- args.config ?? loadConfig()?.credit,
26094
- args.ref.endpoint,
26095
- providerDvmIdentity(args.providerInfo)
26096
- );
26097
- return pin.rail && pin.source !== "default" ? { rail: pin.rail, source: pin.source } : {};
26098
- }
26099
- function reportFunding(args, outcome, ctx) {
26100
- const what = ctx.label ?? "Credit top-up";
26101
- const hint = outcome.hint ? ` ${outcome.hint}` : "";
26102
- const incomplete = (code, adoptedDrain) => {
26103
- noteCreditFundingIncomplete(
26104
- buildCreditFundingIncomplete({
26105
- code,
26106
- dvm: noticeDvm(args),
26107
- endpoint: args.ref.endpoint,
26108
- reason: ctx.reason,
26109
- amountMicro: ctx.fundMicro,
26110
- currency: ctx.currency,
26111
- outcome,
26112
- ...adoptedDrain ? { adoptedDrain } : {}
26113
- }),
26114
- args.human
26115
- );
26116
- };
26117
- switch (outcome.status) {
26118
- case "funded": {
26119
- if (outcome.reconciled || !outcome.rail) {
26120
- info(`${what} at ${args.ref.endpoint} \u2014 ${outcome.display}${hint}`);
26121
- if (outcome.reconciled) incomplete("credit_funding_reconciled");
26122
- return;
26123
- }
26124
- noteCreditFunding(
26125
- buildCreditFundingReport({
26126
- dvm: noticeDvm(args),
26127
- endpoint: args.ref.endpoint,
26128
- reason: ctx.reason,
26129
- amountMicro: outcome.fundedMicro ?? ctx.fundMicro,
26130
- currency: ctx.currency,
26131
- route: outcome.rail,
26132
- // Every funding this module makes is a `/v1/credit` call of its own,
26133
- // including the open — the job it followed paid per-call.
26134
- ownRoundTrip: true,
26135
- ...outcome.railReason ? { routeReason: outcome.railReason } : {},
26136
- ...outcome.railSource ? { routeReasonSource: outcome.railSource } : {},
26137
- ...outcome.x402Flavour ? { x402Flavour: outcome.x402Flavour } : {},
26138
- ...outcome.tempoIntent ? { tempoIntent: outcome.tempoIntent } : {},
26139
- outcome,
26140
- ...ctx.menu.lightning_min_micro !== void 0 ? { lightningMinMicro: ctx.menu.lightning_min_micro } : {},
26141
- ...outcome.credit ? { balanceMicro: outcome.credit.remaining_micro } : {}
26142
- }),
26143
- args.human
26144
- );
26145
- return;
26146
- }
26147
- case "settlement_pending":
26148
- info(`${what} at ${args.ref.endpoint} \u2014 ${outcome.display}${hint}`);
26149
- incomplete("credit_funding_settlement_pending");
26150
- return;
26151
- case "refused": {
26152
- const adopted = outcome.error?.code === "settlement_pending" && args.signing ? adoptWedgedChannelDrain({
26153
- endpoint: args.ref.endpoint,
26154
- // The store identity, which is `providerInfo`'s and not the
26155
- // typeable handle below — the same key `applyReceiptCredit` and
26156
- // `markRefillRailUnavailable` write this credit under.
26157
- ...settleIdentityArgs(args),
26158
- handle: noticeDvm(args),
26159
- callerPubkey: args.signing.pubkey,
26160
- creditId: outcome.creditId,
26161
- data: outcome.error.data
26162
- }) : void 0;
26163
- const reclaim = adopted ? ` ${adopted.advice}` : "";
26164
- info(
26165
- outcome.spentSats !== void 0 || outcome.principalSats !== void 0 ? `${what} paid but not credited \u2014 ${outcome.display}${hint}${reclaim}` : `${what} skipped \u2014 ${outcome.display}${hint}${reclaim}`
26166
- );
26167
- incomplete("credit_funding_refused", adopted);
26168
- return;
26169
- }
26170
- case "unavailable": {
26171
- const pendingIntent = outcome.error?.code === "x402_voucher_pending" || outcome.error?.code === "x402_exact_authorization_pending" || outcome.error?.code === "tempo_charge_pending";
26172
- if (outcome.error?.code === "below_rail_minimum" || pendingIntent) {
26173
- info(`${what} at ${args.ref.endpoint} deferred \u2014 ${outcome.display}${hint}`);
26174
- if (pendingIntent) incomplete("credit_funding_deferred");
26175
- return;
26176
- }
26177
- if (outcome.railReason === "forced" && outcome.railSource !== "credit_bound") {
26178
- info(`${what} at ${args.ref.endpoint} skipped \u2014 ${outcome.display}${hint}`);
26179
- return;
26180
- }
26181
- return;
26182
- }
26183
- }
26184
- }
26185
-
26186
26375
  // src/lib/local-correlation.ts
26187
26376
  var UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
26188
26377
  function prepareLocalCorrelationId(raw2) {
@@ -29875,7 +30064,8 @@ function jobSpend(job, receipt) {
29875
30064
  const receiptTotalDisplay = receipt ? formatPaymentAmount(receipt.paid.msats, void 0, { anchor: false }) + valuationLabel : void 0;
29876
30065
  const settled = settlement.status === "settled" || settlement.status === "free";
29877
30066
  const receiptHeadline = settled && settlement.evidence === "receipt" && (settlement.settled_msats !== total || job.paymentMethod === "credit" && !knownCredit);
29878
- let display = receiptHeadline ? `${settlement.display.replace(/\.$/, "")}; recorded payments: ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}` : !settled && isTerminalJobStatus(job.status) ? settlement.display.replace(/\.$/, "") : job.paymentMethod === "credit" && !knownCredit ? "Drawn from prepaid credit; the upfront amount is not recorded locally" + (total > 0 ? `; recorded conversation payments: ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}` : "") : total === 0 && charges.length === 0 ? job.status === "completed" ? "This job was free" : "No charges yet" : `${settled ? "Settled" : "Sent or held"} ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}`;
30067
+ const pieces = settlement.charged_micro !== void 0 ? settlement.display : void 0;
30068
+ let display = pieces !== void 0 ? `Recorded payments: ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}` : receiptHeadline ? `${settlement.display.replace(/\.$/, "")}; recorded payments: ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}` : !settled && isTerminalJobStatus(job.status) ? settlement.display.replace(/\.$/, "") : job.paymentMethod === "credit" && !knownCredit ? "Drawn from prepaid credit; the upfront amount is not recorded locally" + (total > 0 ? `; recorded conversation payments: ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}` : "") : total === 0 && charges.length === 0 ? job.status === "completed" ? "This job was free" : "No charges yet" : `${settled ? "Settled" : "Sent or held"} ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}`;
29879
30069
  if (job.paymentMethod === "credit" && !knownCredit && settlement.status === "unknown")
29880
30070
  display = `Drawn from prepaid credit; the upfront amount is not recorded locally. ${display}`;
29881
30071
  else if (job.paymentMethod === "credit" && !knownCredit && receiptHeadline)
@@ -29883,6 +30073,7 @@ function jobSpend(job, receipt) {
29883
30073
  if (budgetDisplay) display += `, budget ${budgetDisplay}`;
29884
30074
  if (refunds.length > 0) display += `, ${refunds.length} refund${refunds.length === 1 ? "" : "s"}`;
29885
30075
  display += ".";
30076
+ if (pieces !== void 0) display += ` ${pieces}`;
29886
30077
  if (logMismatch) display += " Local payment log disagrees with the job record.";
29887
30078
  if (receipt && job.paymentMethod === "credit" && !knownCredit) display += " The receipt total includes the unrecorded credit draw.";
29888
30079
  if (receipt && converted) display += " Receipt comparison is unknown: local records lack comparable native settlement amounts for Tempo/x402 payments. Converted BTC totals can differ with exchange rates and do not establish a difference in token principal or fees.";
@@ -29980,11 +30171,12 @@ async function statusWithAccess(jobId, opts, access) {
29980
30171
  const reasonUnavailable = completion.message === void 0 || result.content_available === false && completion.message === "";
29981
30172
  if (reasonUnavailable && (result.status === "failed" || result.status === "cancelled")) {
29982
30173
  const savedReason = !access.endpointOverridden && stored?.status === result.status ? stored.completion?.message : void 0;
29983
- const terminal = msgs.findLast((message2) => message2.type === "complete" || message2.type === "cancel");
29984
- const reason = savedReason ?? (terminal?.type === "cancel" ? terminal.content.reason : void 0);
30174
+ const terminal = msgs.findLast((message2) => message2.type === "complete" || message2.type === "cancel" || message2.type === "decline");
30175
+ const reason = savedReason ?? (terminal?.type === "cancel" || terminal?.type === "decline" ? terminal.content.reason : void 0);
29985
30176
  if (reason !== void 0) completion.message = reason;
29986
30177
  }
29987
30178
  let receipt;
30179
+ let currency;
29988
30180
  if (isTerminalJobStatus(result.status)) {
29989
30181
  if (stored && !access.endpointOverridden) {
29990
30182
  const savedCompletion = result.content_available === false && stored.status === result.status && stored.completion ? stored.completion : completion;
@@ -29995,7 +30187,8 @@ async function statusWithAccess(jobId, opts, access) {
29995
30187
  if (stored && result.receipt && !stored.builderAnchor && !access.endpointOverridden) {
29996
30188
  await backfillTrustAnchor(jobId, transport, ref);
29997
30189
  }
29998
- receipt = stored && !access.endpointOverridden ? captureTransportReceipt(jobId, result) : transientReceiptCapture(jobId, result);
30190
+ currency = stored && !access.endpointOverridden ? void 0 : await providerCurrency({ receipt: result.receipt, status: result, messages: msgs, transport, ref });
30191
+ receipt = stored && !access.endpointOverridden ? captureTransportReceipt(jobId, result) : transientReceiptCapture(jobId, result, currency);
29999
30192
  if (stored && !access.endpointOverridden) {
30000
30193
  await settleCreditAfterRead({ job: stored, capture: receipt, transport, human: opts.human });
30001
30194
  }
@@ -30019,10 +30212,11 @@ async function statusWithAccess(jobId, opts, access) {
30019
30212
  msgs,
30020
30213
  cursor: newCursor,
30021
30214
  receipt,
30022
- content: result
30215
+ content: result,
30216
+ currency
30023
30217
  });
30024
30218
  }
30025
- function transientReceiptCapture(jobId, response) {
30219
+ function transientReceiptCapture(jobId, response, currency) {
30026
30220
  if (response.receiptParseError) {
30027
30221
  return {
30028
30222
  status: "unparseable",
@@ -30040,7 +30234,8 @@ function transientReceiptCapture(jobId, response) {
30040
30234
  display: receiptDisplay(
30041
30235
  response.receipt,
30042
30236
  result.status,
30043
- getLastKnownBtcRate()?.rate ?? 0
30237
+ getLastKnownBtcRate()?.rate ?? 0,
30238
+ currency
30044
30239
  )
30045
30240
  };
30046
30241
  }
@@ -30057,7 +30252,8 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
30057
30252
  const settlement = terminalSettlementFields(jobId, {
30058
30253
  status: jobStatus,
30059
30254
  receipt: receipt?.receipt,
30060
- persistLocalState: !!stored
30255
+ persistLocalState: !!stored,
30256
+ currency: fetched?.currency
30061
30257
  });
30062
30258
  if (opts.human) {
30063
30259
  if (jobStatus === "completed" && completion.summary) {
@@ -30180,7 +30376,7 @@ async function streamUpload(opts) {
30180
30376
  const compatibilityError = clientCompatibilityError(res.status, res.body);
30181
30377
  if (compatibilityError) throw compatibilityError;
30182
30378
  if (res.status === 429 && attempt < maxAttempts) {
30183
- const wait = retryAfterMs(res.headers["retry-after"], capMs);
30379
+ const wait = retryAfterMs2(res.headers["retry-after"], capMs);
30184
30380
  opts.log?.(
30185
30381
  `429 backpressure; retry ${attempt.toString()}/${(maxAttempts - 1).toString()} in ${wait.toString()}ms`
30186
30382
  );
@@ -30257,7 +30453,7 @@ function firstValueHeaders(headers) {
30257
30453
  }
30258
30454
  return out;
30259
30455
  }
30260
- function retryAfterMs(retryAfter, capMs) {
30456
+ function retryAfterMs2(retryAfter, capMs) {
30261
30457
  const seconds = retryAfter !== void 0 ? Number.parseInt(retryAfter, 10) : NaN;
30262
30458
  const ms = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : 2e3;
30263
30459
  return Math.min(ms, capMs);
@@ -32920,8 +33116,8 @@ function fundInterruptedError(err, fund) {
32920
33116
  const cause = classifyMintError(err);
32921
33117
  const reason = describeCause(cause, minting);
32922
33118
  const command = "dvm wallet show";
32923
- const retryAfterMs2 = suggestedRetryAfterMs(cause, err);
32924
- const wait = retryAfterMs2 !== void 0 ? ` Wait ${formatWait(retryAfterMs2)} first.` : "";
33119
+ const retryAfterMs3 = suggestedRetryAfterMs(cause, err);
33120
+ const wait = retryAfterMs3 !== void 0 ? ` Wait ${formatWait(retryAfterMs3)} first.` : "";
32925
33121
  const hint = `The invoice is still recorded as pending.${wait} Once it is paid (or if it already was), run \`${command}\` to mint the sats \u2014 don't start a new fund for the same money.`;
32926
33122
  const diagnostic = err instanceof DvmError && err.code === "mint_quote_poll_unavailable" ? { name: mintErrorName(cause), label: mintErrorName(cause) } : unknownErrorDiagnostic(err);
32927
33123
  return new DvmError(
@@ -32935,14 +33131,14 @@ function fundInterruptedError(err, fund) {
32935
33131
  quote_id: quoteId,
32936
33132
  amount_sats: amountSats,
32937
33133
  pending: true,
32938
- ...retryAfterMs2 !== void 0 ? { retry_after_ms: retryAfterMs2 } : {},
33134
+ ...retryAfterMs3 !== void 0 ? { retry_after_ms: retryAfterMs3 } : {},
32939
33135
  error_name: diagnostic.name,
32940
33136
  ...diagnostic.code ? { error_code: diagnostic.code } : {},
32941
33137
  display: minting ? `Funding ${amountSats} sats was paid but not collected (${reason}). The invoice is still recorded, so 'dvm wallet show' collects the sats.` : `Funding ${amountSats} sats stopped before the payment was seen (${reason}). The invoice is still recorded, so a payment made before it expires is collected by 'dvm wallet show'.`,
32942
33138
  next_action: {
32943
33139
  type: "run_command",
32944
33140
  command,
32945
- ...retryAfterMs2 !== void 0 ? { retry_after_ms: retryAfterMs2 } : {},
33141
+ ...retryAfterMs3 !== void 0 ? { retry_after_ms: retryAfterMs3 } : {},
32946
33142
  hint
32947
33143
  }
32948
33144
  }
@@ -33115,11 +33311,11 @@ var RATE_LIMIT_TEXT = /\b429\b|rate[ -]?limit|too many requests/i;
33115
33311
  function uncheckedMint(entry, quoteId, thrown, message2, subject = "mint") {
33116
33312
  const cause = thrown !== void 0 ? classifyMintError(thrown) : RATE_LIMIT_TEXT.test(message2) ? "rate_limited" : "unexpected";
33117
33313
  const retryable = cause !== "unexpected";
33118
- const retryAfterMs2 = suggestedRetryAfterMs(cause, thrown);
33314
+ const retryAfterMs3 = suggestedRetryAfterMs(cause, thrown);
33119
33315
  const diagnostic = thrown !== void 0 ? unknownErrorDiagnostic(thrown) : void 0;
33120
33316
  const amountSats = entry?.amount_sats ?? 0;
33121
33317
  const reason = describeCause2(cause);
33122
- const wait = retryAfterMs2 !== void 0 ? ` Wait ${formatWait(retryAfterMs2)} and try again.` : "";
33318
+ const wait = retryAfterMs3 !== void 0 ? ` Wait ${formatWait(retryAfterMs3)} and try again.` : "";
33123
33319
  const copy = uncheckedCopy(subject, amountSats, quoteId, reason, wait, retryable);
33124
33320
  return {
33125
33321
  quote_id: quoteId,
@@ -33129,7 +33325,7 @@ function uncheckedMint(entry, quoteId, thrown, message2, subject = "mint") {
33129
33325
  retryable,
33130
33326
  reason,
33131
33327
  pending: true,
33132
- ...retryAfterMs2 !== void 0 ? { retry_after_ms: retryAfterMs2 } : {},
33328
+ ...retryAfterMs3 !== void 0 ? { retry_after_ms: retryAfterMs3 } : {},
33133
33329
  ...diagnostic ? { error_name: diagnostic.name } : {},
33134
33330
  ...diagnostic?.code ? { error_code: diagnostic.code } : {},
33135
33331
  display: copy.display,
@@ -33137,7 +33333,7 @@ function uncheckedMint(entry, quoteId, thrown, message2, subject = "mint") {
33137
33333
  next_action: {
33138
33334
  type: "run_command",
33139
33335
  command: RECONCILE_COMMAND,
33140
- ...retryAfterMs2 !== void 0 ? { retry_after_ms: retryAfterMs2 } : {},
33336
+ ...retryAfterMs3 !== void 0 ? { retry_after_ms: retryAfterMs3 } : {},
33141
33337
  hint: copy.hint
33142
33338
  }
33143
33339
  };
@@ -38616,7 +38812,14 @@ function buildProgram() {
38616
38812
  ).action((jobId, opts) => {
38617
38813
  return catchErrors(() => pay(jobId, opts), opts.human);
38618
38814
  });
38619
- program2.command("cancel <job-id>").description("Cancel a running job").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--reason <text>", "Reason for cancellation").option("--human", "Human-readable output instead of JSON").action((jobId, opts) => {
38815
+ program2.command("decline <job-id>").description(
38816
+ "Decline a job's open payment request or prompt. The job ends; finished work is charged, and nothing was in progress at the ask. Use this to stop a job and keep the finished pieces' results."
38817
+ ).option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--reason <text>", "Reason for declining").option("--human", "Human-readable output instead of JSON").action((jobId, opts) => {
38818
+ return catchErrors(() => decline(jobId, opts), opts.human);
38819
+ });
38820
+ program2.command("cancel <job-id>").description(
38821
+ "Stop a running job now. The work in progress is charged on a DVM that charges by the piece; to stop and keep only finished work, decline at the next ask instead."
38822
+ ).option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--reason <text>", "Reason for cancellation").option("--human", "Human-readable output instead of JSON").action((jobId, opts) => {
38620
38823
  return catchErrors(() => cancel(jobId, opts), opts.human);
38621
38824
  });
38622
38825
  program2.command("feedback [body...]").description(