@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
package/dist/dvm.js CHANGED
@@ -5,11 +5,9 @@ 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 {
10
+ CARD_MIN_MICRO,
13
11
  DEFAULT_CREDIT_POSTURE,
14
12
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
15
13
  JOB_READ_TIMEOUT_MS,
@@ -57,6 +55,7 @@ import {
57
55
  floatPaymentDisplay,
58
56
  floatPaymentJson,
59
57
  formatLocktime,
58
+ formatMicro,
60
59
  fundAgentWallet,
61
60
  fundCredit,
62
61
  fundTimeoutMs,
@@ -67,6 +66,7 @@ import {
67
66
  identityError,
68
67
  inFlightTimeoutSeconds,
69
68
  isIdentityFailure,
69
+ isImplicitCreditId,
70
70
  isOpaqueJobToken,
71
71
  isParseableBodyJobId,
72
72
  isTerminalJobStatus,
@@ -118,11 +118,13 @@ import {
118
118
  proofKey,
119
119
  providerFields,
120
120
  providerJobJson,
121
+ receiptCurrencyHint,
121
122
  receiptDisplay,
122
123
  receiptFailureDetail,
123
124
  receiptHint,
124
125
  receiptIssuedAtIso,
125
126
  receiptJsonFields,
127
+ receiptPieceContext,
126
128
  receiptSettlement,
127
129
  receiptTrustFields,
128
130
  reconcileInFlightPaymentRequest,
@@ -136,8 +138,10 @@ import {
136
138
  recordSubmissionEvidence,
137
139
  recordUpfrontCreditPayment,
138
140
  recordUpfrontRailPayment,
141
+ redactJobTokenFromError,
139
142
  removeFavorite,
140
143
  renderReceiptHuman,
144
+ renderSettlementHuman,
141
145
  replayStoredReceipt,
142
146
  reservedForMarker,
143
147
  resolveEndpoint,
@@ -152,14 +156,17 @@ import {
152
156
  saveLedger,
153
157
  saveSubmittedJob,
154
158
  settleJobIdentity,
159
+ settlementCurrencyHint,
155
160
  statusSnapshot,
156
161
  sweepPendingMints,
157
162
  sweepStaleInFlight,
158
163
  terminalSettlementFields,
159
164
  tierCapOverrides,
165
+ toCapture,
160
166
  toFloatError,
161
167
  trustLadderFor,
162
168
  trustOverrideCapMicro,
169
+ unknownCurrencyHint,
163
170
  unknownUpfrontPrice,
164
171
  unrecordedFloatBudgetWarning,
165
172
  updateJob,
@@ -169,13 +176,13 @@ import {
169
176
  withIdentityRecovery,
170
177
  withJobTokenRedaction,
171
178
  withRequestResultRecovery
172
- } from "./chunk-NLUOHCX2.js";
179
+ } from "./chunk-ZKC6KN36.js";
173
180
  import {
174
181
  connectedTempoAccount,
175
182
  generateTempoKey,
176
183
  tempoBalanceCheckHint,
177
184
  tempoWrongAssetHint
178
- } from "./chunk-I2C3YEUN.js";
185
+ } from "./chunk-HJ2JYBTT.js";
179
186
  import {
180
187
  addOutputWarnings,
181
188
  assertValidBudget,
@@ -195,7 +202,7 @@ import {
195
202
  tryResolveBtcUsdRate,
196
203
  tryX402Payment,
197
204
  withOutputWarnings
198
- } from "./chunk-RPM5XEVS.js";
205
+ } from "./chunk-LPILVPFG.js";
199
206
  import {
200
207
  assertSupportedX402Network,
201
208
  connectedX402Payer,
@@ -204,7 +211,7 @@ import {
204
211
  repinX402WalletNetwork,
205
212
  saveX402Wallet,
206
213
  x402NetworkLabel
207
- } from "./chunk-KQQALLOL.js";
214
+ } from "./chunk-UWVMG4VG.js";
208
215
  import {
209
216
  CREDIT_POSTURES,
210
217
  FEEDBACK_POSTURES,
@@ -221,7 +228,10 @@ import {
221
228
  retireConfigBackup,
222
229
  rollbackConfig,
223
230
  updateConfig
224
- } from "./chunk-GWLOO5XD.js";
231
+ } from "./chunk-2MCZ4QOK.js";
232
+ import {
233
+ assertX402WalletIdle
234
+ } from "./chunk-I7ZBID4L.js";
225
235
  import {
226
236
  A,
227
237
  AGENT_MNEMONIC_FILE,
@@ -458,7 +468,7 @@ import {
458
468
  x402PendingUnsettled,
459
469
  x402RequiredFromError,
460
470
  x402ReservationRelease
461
- } from "./chunk-SEJWBDGY.js";
471
+ } from "./chunk-YQJRKWNT.js";
462
472
  import "./chunk-JBU7RKQ3.js";
463
473
  import "./chunk-KDNFUDOG.js";
464
474
  import "./chunk-IUTVV6N5.js";
@@ -742,11 +752,11 @@ import {
742
752
  usdToMsats,
743
753
  usdcToMsats,
744
754
  x402NetworkByCaip2
745
- } from "./chunk-C2BJETRG.js";
746
- import "./chunk-CCF4QONY.js";
747
- import "./chunk-PS4AUWK3.js";
755
+ } from "./chunk-57PXJ56K.js";
756
+ import "./chunk-HXTASGHL.js";
757
+ import "./chunk-D5CGDS3V.js";
748
758
  import "./chunk-R2DSAZBO.js";
749
- import "./chunk-ZV57FFIL.js";
759
+ import "./chunk-UCCT5IKU.js";
750
760
  import {
751
761
  privateKeyToAccount
752
762
  } from "./chunk-EVQERRCP.js";
@@ -11376,8 +11386,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11376
11386
  }
11377
11387
  }
11378
11388
  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");
11389
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
11390
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-RSHQFXCA.js");
11381
11391
  const wallet = loadX402Wallet2();
11382
11392
  if (wallet) {
11383
11393
  let proof;
@@ -11775,6 +11785,7 @@ async function streamLoop(opts) {
11775
11785
  let cursor = opts.afterSeq;
11776
11786
  let messageAppendSession = opts.messageAppendSession;
11777
11787
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
11788
+ const declined = () => persistLocalState && loadJob(jobId)?.callerDeclined === true;
11778
11789
  function recordAutoPayment(result, request2, seq) {
11779
11790
  autoPayments.push({
11780
11791
  amount_msats: result.amountMsats,
@@ -11894,7 +11905,7 @@ async function streamLoop(opts) {
11894
11905
  break;
11895
11906
  }
11896
11907
  }
11897
- if (lastYield2?.type === "payment-request" && lastYield2.seq === pendingPayment?.seq && policy) {
11908
+ if (lastYield2?.type === "payment-request" && lastYield2.seq === pendingPayment?.seq && policy && !declined()) {
11898
11909
  const req = lastYield2.content;
11899
11910
  if (req.amount_msats <= policy.autoPayBelowMsats && (policy.maxIncrementMsats === 0 || req.amount_msats <= policy.maxIncrementMsats)) {
11900
11911
  let result;
@@ -11964,7 +11975,7 @@ async function streamLoop(opts) {
11964
11975
  }
11965
11976
  if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
11966
11977
  for (const seq of answeredYieldSeqs(allMessages)) answeredSeqs.add(seq);
11967
- const terminal = allMessages.some((msg) => msg.type === "complete" || msg.type === "cancel");
11978
+ const terminal = allMessages.some((msg) => msg.type === "complete" || msg.type === "cancel") || declined();
11968
11979
  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
11980
  let nextAction = withRefundNextAction(jobId, yieldAction ?? (terminal ? null : pollNextAction(jobId)), refunds);
11970
11981
  const lastYield = findLastYield(allMessages);
@@ -12014,6 +12025,54 @@ function formatAppliedDefaults(applied) {
12014
12025
  return Object.entries(applied).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(", ");
12015
12026
  }
12016
12027
 
12028
+ // src/lib/stream-outcome.ts
12029
+ function persistStreamOutcome(outcome) {
12030
+ const { jobId, messages: messages2, cursor, afterSeq, extra, providerStatus } = outcome;
12031
+ const stored = loadJob(jobId);
12032
+ const callerCancelled = outcome.callerCancelled ?? stored?.callerCancelled;
12033
+ const terminal = streamTerminalStatus(messages2, {
12034
+ providerStatus,
12035
+ callerCancelled,
12036
+ callerDeclined: outcome.callerDeclined ?? stored?.callerDeclined
12037
+ });
12038
+ const log = terminal ? fullMessageLog(jobId, messages2, afterSeq) : void 0;
12039
+ const providerTerminal = providerStatus?.status && isTerminalJobStatus(providerStatus.status);
12040
+ if (terminal && (log || providerTerminal)) {
12041
+ const saved = stored?.status === terminal ? stored.completion : void 0;
12042
+ const fromLog = log?.some((m) => m.type === "complete" || m.type === "cancel" || m.type === "decline") ? completionFromMessages(log) : void 0;
12043
+ const retained = saved ?? fromLog;
12044
+ const completion = providerStatus?.content_available === false && retained ? retained : {
12045
+ ...saved,
12046
+ ...fromLog,
12047
+ ...terminal === "cancelled" && callerCancelled && stored?.completion?.message !== void 0 ? { message: stored.completion.message } : {},
12048
+ ...providerTerminal ? completionSnapshot(providerStatus) : {}
12049
+ };
12050
+ markJobTerminal(jobId, terminal, completion, {
12051
+ messageCursor: cursor,
12052
+ ...extra
12053
+ });
12054
+ return completion;
12055
+ }
12056
+ updateJob(jobId, { messageCursor: cursor });
12057
+ return void 0;
12058
+ }
12059
+ function streamTerminalStatus(messages2, context = {}) {
12060
+ const providerStatus = context.providerStatus?.status;
12061
+ if (providerStatus && isTerminalJobStatus(providerStatus)) return providerStatus;
12062
+ const last = messages2.findLast((m) => m.type === "complete" || m.type === "cancel" || m.type === "decline" && context.callerDeclined === true);
12063
+ if (!last) return void 0;
12064
+ if (last.type === "complete") return "completed";
12065
+ if (last.type === "decline") return "cancelled";
12066
+ return context.callerCancelled ? "cancelled" : "failed";
12067
+ }
12068
+ function fullMessageLog(jobId, messages2, afterSeq) {
12069
+ if (afterSeq === 0) return messages2;
12070
+ const local = [...loadMessages(jobId)].sort((a, b) => a.seq - b.seq);
12071
+ if (local.length === 0 || local[0].seq > 1) return void 0;
12072
+ const contiguous = local.every((m, i2) => i2 === 0 || m.seq === local[i2 - 1].seq + 1);
12073
+ return contiguous ? local : void 0;
12074
+ }
12075
+
12017
12076
  // src/lib/discovery-lifecycle.ts
12018
12077
  async function runDiscoveryLifecycle(options) {
12019
12078
  const { transport, provider, capability, input, timeoutMs } = options;
@@ -12039,42 +12098,54 @@ async function runDiscoveryLifecycle(options) {
12039
12098
  if (receipt.status === "completed" && receipt.summary) {
12040
12099
  return { summary: receipt.summary, messages: [], nextAction: null };
12041
12100
  }
12042
- const deadline = Date.now() + timeoutMs;
12043
- const messageAppendSession = createMessageAppendSession(receipt.jobId);
12044
- const messages2 = [];
12045
- let result = await streamLoop({
12046
- jobId: receipt.jobId,
12047
- transport,
12048
- provider,
12049
- afterSeq: 0,
12050
- timeoutMs: Math.max(1, deadline - Date.now()),
12051
- messageAppendSession,
12052
- jobToken: receipt.jobToken
12053
- });
12054
- messages2.push(...result.messages);
12055
- while (result.nextAction?.type === "poll" && Date.now() < deadline) {
12056
- const waitMs = Math.min(
12057
- Math.max((result.nextAction.estimate_seconds ?? 0) * 1e3, 500),
12058
- deadline - Date.now()
12059
- );
12060
- if (waitMs > 0) await new Promise((resolve3) => setTimeout(resolve3, waitMs));
12061
- if (Date.now() >= deadline) break;
12062
- const next = await streamLoop({
12101
+ return withJobTokenRedaction(receipt.jobToken, async () => {
12102
+ if (receipt.jobId) saveSubmittedJob({
12103
+ id: receipt.jobId,
12104
+ endpoint: provider.endpoint,
12105
+ capability,
12106
+ status: "submitted",
12107
+ submittedAt: Date.now(),
12108
+ jobToken: receipt.jobToken
12109
+ });
12110
+ const deadline = Date.now() + timeoutMs;
12111
+ const messageAppendSession = createMessageAppendSession(receipt.jobId);
12112
+ const messages2 = [];
12113
+ let result = await streamLoop({
12063
12114
  jobId: receipt.jobId,
12064
12115
  transport,
12065
12116
  provider,
12066
- afterSeq: result.cursor,
12117
+ afterSeq: 0,
12067
12118
  timeoutMs: Math.max(1, deadline - Date.now()),
12068
12119
  messageAppendSession,
12069
12120
  jobToken: receipt.jobToken
12070
12121
  });
12071
- if (next.messages.length === 0) break;
12072
- messages2.push(...next.messages);
12073
- result = next;
12074
- }
12075
- const complete = messages2.find((message2) => message2.type === "complete");
12076
- const summary = complete?.content.summary;
12077
- return { ...summary ? { summary } : {}, messages: messages2, nextAction: result.nextAction };
12122
+ messages2.push(...result.messages);
12123
+ persistStreamOutcome({ jobId: receipt.jobId, messages: messages2, cursor: result.cursor, afterSeq: 0 });
12124
+ while (result.nextAction?.type === "poll" && Date.now() < deadline) {
12125
+ const waitMs = Math.min(
12126
+ Math.max((result.nextAction.estimate_seconds ?? 0) * 1e3, 500),
12127
+ deadline - Date.now()
12128
+ );
12129
+ if (waitMs > 0) await new Promise((resolve3) => setTimeout(resolve3, waitMs));
12130
+ if (Date.now() >= deadline) break;
12131
+ const next = await streamLoop({
12132
+ jobId: receipt.jobId,
12133
+ transport,
12134
+ provider,
12135
+ afterSeq: result.cursor,
12136
+ timeoutMs: Math.max(1, deadline - Date.now()),
12137
+ messageAppendSession,
12138
+ jobToken: receipt.jobToken
12139
+ });
12140
+ messages2.push(...next.messages);
12141
+ persistStreamOutcome({ jobId: receipt.jobId, messages: messages2, cursor: next.cursor, afterSeq: 0 });
12142
+ if (next.messages.length === 0) break;
12143
+ result = next;
12144
+ }
12145
+ const complete = messages2.find((message2) => message2.type === "complete");
12146
+ const summary = complete?.content.summary;
12147
+ return { ...summary ? { summary } : {}, messages: messages2, nextAction: result.nextAction, jobToken: receipt.jobToken };
12148
+ });
12078
12149
  }
12079
12150
 
12080
12151
  // src/lib/discovery-options.ts
@@ -12802,6 +12873,8 @@ var HttpsTransport = class {
12802
12873
  error.data = { ...error.data, http_status: res.status };
12803
12874
  throw error;
12804
12875
  }
12876
+ const conflict = jobEndingConflict(jobId, body2, res.headers.get("retry-after"));
12877
+ if (conflict) throw conflict;
12805
12878
  throw new DvmError(
12806
12879
  "job_terminal",
12807
12880
  "Job is no longer active.",
@@ -12870,6 +12943,10 @@ var HttpsTransport = class {
12870
12943
  const res = await dvmFetch(url2, { method: "DELETE", headers, body });
12871
12944
  if (!res.ok) {
12872
12945
  const text = await res.text();
12946
+ if (res.status === 409) {
12947
+ const conflict = jobEndingConflict(jobId, parseJsonObject(text), res.headers.get("retry-after"));
12948
+ if (conflict) throw conflict;
12949
+ }
12873
12950
  const credentialErr = jobCredentialError(res.status, text);
12874
12951
  if (credentialErr) throw credentialErr;
12875
12952
  throw providerResponseError("provider_error", `Cancel failed (${res.status}): ${text}`);
@@ -13149,6 +13226,38 @@ function routerProse(structured) {
13149
13226
  const display = typeof structured.data?.display === "string" ? structured.data.display : void 0;
13150
13227
  return display !== void 0 ? { display, proseSources: { display: "provider" } } : {};
13151
13228
  }
13229
+ function jobEndingConflict(jobId, body, retryAfter) {
13230
+ const job = shellQuoteArg(jobId);
13231
+ if (body?.error === "payment_in_progress") {
13232
+ return new DvmError(
13233
+ "payment_in_progress",
13234
+ "A payment for this job is still being verified, so the job cannot end yet.",
13235
+ `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}\`.`,
13236
+ { retryable: true, retry_after_ms: retryAfterMs(retryAfter) }
13237
+ );
13238
+ }
13239
+ if (body?.error === "no_open_ask") {
13240
+ return new DvmError(
13241
+ "no_open_ask",
13242
+ "The job has no open payment request or prompt to decline.",
13243
+ `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.`
13244
+ );
13245
+ }
13246
+ if (body?.error === "decline_unavailable") {
13247
+ return new DvmError(
13248
+ "decline_unavailable",
13249
+ "This DVM cannot end this job at a decline; the job is still running.",
13250
+ `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.`
13251
+ );
13252
+ }
13253
+ return void 0;
13254
+ }
13255
+ function retryAfterMs(header, nowMs = Date.now()) {
13256
+ const value = header?.trim();
13257
+ if (value && /^\d+$/.test(value)) return Number(value) * 1e3;
13258
+ const date4 = value ? Date.parse(value) : Number.NaN;
13259
+ return Number.isFinite(date4) ? Math.max(0, date4 - nowMs) : 2e3;
13260
+ }
13152
13261
  function parseJsonObject(body) {
13153
13262
  try {
13154
13263
  const parsed = JSON.parse(body);
@@ -13341,6 +13450,7 @@ async function browse(opts) {
13341
13450
  const transport = createDvmTransport();
13342
13451
  const ref = { endpoint };
13343
13452
  progressNotice("Browsing catalog...", opts.human);
13453
+ let jobToken;
13344
13454
  try {
13345
13455
  const result = await runDiscoveryLifecycle({
13346
13456
  transport,
@@ -13349,6 +13459,7 @@ async function browse(opts) {
13349
13459
  input,
13350
13460
  timeoutMs: timeout
13351
13461
  });
13462
+ jobToken = result.jobToken;
13352
13463
  if (result.summary) {
13353
13464
  outputResults(result.summary, opts.human, result.nextAction);
13354
13465
  return;
@@ -13371,6 +13482,8 @@ async function browse(opts) {
13371
13482
  "Browse did not complete in time.",
13372
13483
  "Try again or increase --timeout."
13373
13484
  );
13485
+ } catch (error) {
13486
+ throw redactJobTokenFromError(error, jobToken);
13374
13487
  } finally {
13375
13488
  transport.close();
13376
13489
  }
@@ -13746,6 +13859,489 @@ function capabilityRetryHint(caps, dvmId, endpoint) {
13746
13859
  return `Try \`${command} --data '{}'\` using a name from available_capabilities. Replace --data '{}' with the input for that capability.${alternate}`;
13747
13860
  }
13748
13861
 
13862
+ // src/lib/credit-defer.ts
13863
+ function noteDeferredFunding(funding) {
13864
+ pending2 = funding;
13865
+ }
13866
+ function takeDeferredFunding() {
13867
+ const taken = pending2;
13868
+ pending2 = void 0;
13869
+ return taken;
13870
+ }
13871
+ var pending2;
13872
+
13873
+ // src/lib/credit-reclaim.ts
13874
+ function adoptWedgedChannelDrain(args) {
13875
+ const drainId = args.data?.settlement_drain_id;
13876
+ if (typeof drainId !== "string" || drainId === "") return void 0;
13877
+ const identityArg = args.identity ? [args.identity] : [];
13878
+ const stored = loadCredit(args.endpoint, args.callerPubkey, args.identity);
13879
+ if (!stored) {
13880
+ ensureProvisionalCredit({
13881
+ endpoint: args.endpoint,
13882
+ ...args.identity ? { identity: args.identity } : {},
13883
+ callerPubkey: args.callerPubkey,
13884
+ creditId: args.creditId,
13885
+ currency: "usd",
13886
+ targetMicro: 0
13887
+ });
13888
+ }
13889
+ const recorded = pendingDrainFor(stored, args.creditId);
13890
+ if (recorded && recorded.drainId !== drainId) {
13891
+ clearPendingDrain(args.endpoint, args.callerPubkey, recorded, ...identityArg);
13892
+ }
13893
+ recordPendingDrain(
13894
+ args.endpoint,
13895
+ args.callerPubkey,
13896
+ {
13897
+ drainId,
13898
+ creditId: args.creditId,
13899
+ method: "x402",
13900
+ payout: {},
13901
+ requestedAt: Date.now()
13902
+ },
13903
+ ...identityArg
13904
+ );
13905
+ recordCreditX402Instrument(
13906
+ args.endpoint,
13907
+ args.callerPubkey,
13908
+ args.creditId,
13909
+ "x402_channel",
13910
+ args.identity
13911
+ );
13912
+ const command = reclaimCommand(args.handle ?? args.endpoint, stored, args.creditId);
13913
+ return {
13914
+ drainId,
13915
+ command,
13916
+ // Written to be appended to the server's own refusal, never to replace it:
13917
+ // that copy is the one saying nothing was charged and that paying per call
13918
+ // still works, which is what a human needs to hear. What it cannot know is
13919
+ // that this CLI just recorded the id, so the reclaim no longer carries it.
13920
+ advice: `Drain ${drainId} is now this credit's recorded reclaim here, so '${command}' posts it \u2014 no --drain-id needed.`
13921
+ };
13922
+ }
13923
+ function reclaimCommand(handle, tracked, creditId) {
13924
+ return !tracked || tracked.creditId === creditId ? `dvm credit drain ${shellQuoteArg(handle)}` : creditDrainCommand(handle, creditId);
13925
+ }
13926
+ function creditDrainCommand(handle, creditId) {
13927
+ return `dvm credit drain ${shellQuoteArg(handle)} --credit-id ${shellQuoteArg(creditId)}`;
13928
+ }
13929
+
13930
+ // src/lib/credit-topup.ts
13931
+ async function settleCreditAfterJob(args) {
13932
+ const deferred = args.deferred ?? takeDeferredFunding();
13933
+ try {
13934
+ await settle(args);
13935
+ } catch (err) {
13936
+ info(
13937
+ `Credit bookkeeping failed (job outcome unaffected): ${err instanceof Error ? err.message : String(err)}`
13938
+ );
13939
+ }
13940
+ if (deferred) {
13941
+ try {
13942
+ await fundDeferred(args, deferred);
13943
+ } catch (err) {
13944
+ info(
13945
+ `Credit funding failed (job outcome unaffected): ${err instanceof Error ? err.message : String(err)}`
13946
+ );
13947
+ }
13948
+ }
13949
+ if (args.allowTopup !== false) {
13950
+ const refill = args.refillPocket ?? (await import("./pocket-refill-7Q6CR6I4.js")).refillPocketIfLow;
13951
+ await refill({ human: args.human }).catch(() => void 0);
13952
+ }
13953
+ }
13954
+ async function settleCreditAfterRead(args) {
13955
+ const { job, capture } = args;
13956
+ const binding = job.creditBinding;
13957
+ const receipt = capture.receipt;
13958
+ 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 || isImplicitCreditId(receipt.credit.credit_id)) return;
13959
+ const builder = loadJob(job.id)?.builderAnchor ?? job.builderAnchor;
13960
+ await settleCreditAfterJob({
13961
+ capture,
13962
+ transport: args.transport,
13963
+ ref: { endpoint: job.endpoint },
13964
+ dvmId: job.dvmId,
13965
+ providerInfo: builder ? { builder } : void 0,
13966
+ callerPubkey: binding.callerPubkey,
13967
+ allowTopup: false,
13968
+ human: args.human
13969
+ });
13970
+ }
13971
+ function settleIdentity(args) {
13972
+ return providerDvmIdentity(args.providerInfo);
13973
+ }
13974
+ function settleIdentityArgs(args) {
13975
+ const identity = settleIdentity(args);
13976
+ return identity ? { identity } : {};
13977
+ }
13978
+ function settleIdentityArg(args) {
13979
+ const identity = settleIdentity(args);
13980
+ return identity ? [identity] : [];
13981
+ }
13982
+ function noticeDvm(args) {
13983
+ return args.dvmId ?? args.ref.endpoint;
13984
+ }
13985
+ async function settle(args) {
13986
+ const receipt = args.capture?.receipt;
13987
+ const credit = receipt?.credit;
13988
+ const callerPubkey = args.signing?.pubkey ?? args.callerPubkey;
13989
+ if (!receipt || !credit || !callerPubkey || args.capture?.status !== "verified" && args.capture?.status !== "verified_unattested" || receipt.requester_pubkey !== callerPubkey) return;
13990
+ if (isImplicitCreditId(credit.credit_id)) {
13991
+ const applied2 = applyImplicitReceiptCredit({
13992
+ endpoint: args.ref.endpoint,
13993
+ ...settleIdentityArgs(args),
13994
+ callerPubkey,
13995
+ jobId: receipt.job_id,
13996
+ outcome: receipt.outcome,
13997
+ credit,
13998
+ currency: args.providerInfo?.pricing?.max?.currency ?? args.providerInfo?.credit?.currency ?? "usd",
13999
+ issuedAtMs: receipt.issued_at * 1e3
14000
+ });
14001
+ if (applied2.mismatch) renderBalanceMismatch(args.ref.endpoint, applied2.mismatch);
14002
+ return;
14003
+ }
14004
+ const applied = applyReceiptCredit({
14005
+ endpoint: args.ref.endpoint,
14006
+ ...settleIdentityArgs(args),
14007
+ callerPubkey,
14008
+ jobId: receipt.job_id,
14009
+ outcome: receipt.outcome,
14010
+ credit,
14011
+ // A piece-settled draw can charge on a failed or cancelled job too; the
14012
+ // SDK checks every ending whose settlement charged anything.
14013
+ ...receipt.settlement ? { settlement: { charged: receipt.settlement.charged } } : {},
14014
+ drawFundings: jobDrawFundings(receipt.job_id, args.ref.endpoint, callerPubkey, credit)
14015
+ });
14016
+ if (!applied.credit) return;
14017
+ if (applied.mismatch) {
14018
+ renderBalanceMismatch(args.ref.endpoint, applied.mismatch);
14019
+ }
14020
+ if (args.allowTopup === false || !args.signing) return;
14021
+ if (receipt.outcome !== "completed") return;
14022
+ const record2 = applied.credit;
14023
+ if (record2.status !== "active") return;
14024
+ if (record2.reconciliationPending) return;
14025
+ if (!needsTopup(record2.remainingMicro, record2.targetMicro)) return;
14026
+ const posture = effectiveCreditPosture(
14027
+ args.config ?? loadConfig()?.credit,
14028
+ args.ref.endpoint,
14029
+ providerDvmIdentity(args.providerInfo)
14030
+ );
14031
+ if (posture.posture === "off") return;
14032
+ const held = pendingDrainFor(record2, record2.creditId);
14033
+ if (held) {
14034
+ reportRefillHeldByDrain(args, record2, held, args.signing.pubkey);
14035
+ return;
14036
+ }
14037
+ await fundTopup(args, record2, posture);
14038
+ }
14039
+ function renderBalanceMismatch(endpoint, mismatch) {
14040
+ const prior = mismatch.priorJobId ? `the previous countersigned receipt (job ${mismatch.priorJobId})` : "the recorded balance projection";
14041
+ info(
14042
+ `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'.`
14043
+ );
14044
+ }
14045
+ function reportRefillHeldByDrain(args, record2, held, callerPubkey) {
14046
+ const identityArg = settleIdentityArg(args);
14047
+ if (!markRefillDrainNoticed(
14048
+ args.ref.endpoint,
14049
+ callerPubkey,
14050
+ record2.creditId,
14051
+ held.drainId,
14052
+ ...identityArg
14053
+ )) {
14054
+ return;
14055
+ }
14056
+ noteCreditRefillUnavailable(
14057
+ buildCreditRefillDrainPending({
14058
+ dvm: noticeDvm(args),
14059
+ endpoint: args.ref.endpoint,
14060
+ creditId: record2.creditId,
14061
+ drainId: held.drainId,
14062
+ // The reclaim as the doors that record one spell it ,
14063
+ // rather than a third spelling of the same command.
14064
+ drainCommand: reclaimCommand(noticeDvm(args), record2, record2.creditId),
14065
+ balanceMicro: record2.remainingMicro,
14066
+ currency: record2.currency
14067
+ }),
14068
+ args.human
14069
+ );
14070
+ }
14071
+ async function fundTopup(args, record2, posture) {
14072
+ const menu = record2.menu;
14073
+ if (!menu) return;
14074
+ if (!args.transport.credit) return;
14075
+ const signing = args.signing;
14076
+ if (!signing) return;
14077
+ const identityArg = settleIdentityArg(args);
14078
+ const boundRail = isCreditFundRail(record2.rail) ? record2.rail : void 0;
14079
+ const boundRailAvailable = boundRail ? availableRails({
14080
+ menu,
14081
+ ...args.providerInfo ? { providerInfo: args.providerInfo } : {}
14082
+ }).includes(boundRail) : void 0;
14083
+ if (boundRail && !boundRailAvailable) {
14084
+ if (!markRefillRailUnavailable(
14085
+ args.ref.endpoint,
14086
+ signing.pubkey,
14087
+ record2.creditId,
14088
+ boundRail,
14089
+ ...identityArg
14090
+ )) {
14091
+ return;
14092
+ }
14093
+ noteCreditRefillUnavailable(
14094
+ buildCreditRefillUnavailable({
14095
+ dvm: noticeDvm(args),
14096
+ endpoint: args.ref.endpoint,
14097
+ creditId: record2.creditId,
14098
+ boundRail,
14099
+ balanceMicro: record2.remainingMicro,
14100
+ currency: record2.currency
14101
+ }),
14102
+ args.human
14103
+ );
14104
+ return;
14105
+ }
14106
+ if (boundRail) {
14107
+ clearRefillRailUnavailable(args.ref.endpoint, signing.pubkey, record2.creditId, ...identityArg);
14108
+ }
14109
+ const forced = forcedRefillRail(args, record2);
14110
+ const railFloorMicro = forced.rail === "lightning" && menu.lightning_min_micro !== void 0 ? Math.max(menu.min_micro, menu.lightning_min_micro) : menu.min_micro;
14111
+ let fundMicro = Math.max(record2.targetMicro - record2.remainingMicro, railFloorMicro);
14112
+ fundMicro = Math.min(fundMicro, menu.max_micro - record2.remainingMicro);
14113
+ if (fundMicro < railFloorMicro) {
14114
+ if (railFloorMicro > menu.min_micro) {
14115
+ info(
14116
+ `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.`
14117
+ );
14118
+ }
14119
+ return;
14120
+ }
14121
+ if (posture.posture === "suggest") {
14122
+ noteCreditSuggestion(
14123
+ buildCreditSuggestion({
14124
+ dvm: noticeDvm(args),
14125
+ endpoint: args.ref.endpoint,
14126
+ posture: posture.posture,
14127
+ postureSource: posture.source,
14128
+ suppressed: {
14129
+ reason: "refill",
14130
+ fundMicro,
14131
+ targetMicro: record2.targetMicro,
14132
+ currency: record2.currency
14133
+ }
14134
+ }),
14135
+ args.human
14136
+ );
14137
+ return;
14138
+ }
14139
+ const outcome = await fundCredit({
14140
+ transport: args.transport,
14141
+ ref: args.ref,
14142
+ signing,
14143
+ creditId: record2.creditId,
14144
+ amountMicro: fundMicro,
14145
+ menu,
14146
+ targetMicro: record2.targetMicro,
14147
+ maxDepositMicro: fundMicro,
14148
+ human: args.human,
14149
+ ...forced.rail ? { rail: forced.rail, railSource: forced.source } : {},
14150
+ ...args.providerInfo ? { providerInfo: args.providerInfo } : {},
14151
+ ...args.signBody ? { signBody: args.signBody } : {}
14152
+ });
14153
+ reportFunding(args, outcome, {
14154
+ reason: "below_refill_target",
14155
+ fundMicro,
14156
+ currency: record2.currency,
14157
+ menu
14158
+ });
14159
+ }
14160
+ async function fundDeferred(args, deferred) {
14161
+ if (args.allowTopup === false) return;
14162
+ if (args.capture?.receipt?.outcome !== "completed") return;
14163
+ if (!args.transport.credit) return;
14164
+ const signing = args.signing;
14165
+ if (!signing) return;
14166
+ const posture = effectiveCreditPosture(
14167
+ args.config ?? loadConfig()?.credit,
14168
+ args.ref.endpoint,
14169
+ providerDvmIdentity(args.providerInfo)
14170
+ );
14171
+ if (posture.posture !== "auto") return;
14172
+ const outcome = await fundCredit({
14173
+ transport: args.transport,
14174
+ ref: args.ref,
14175
+ signing,
14176
+ creditId: deferred.creditId,
14177
+ amountMicro: deferred.fundMicro,
14178
+ menu: deferred.menu,
14179
+ targetMicro: deferred.targetMicro,
14180
+ maxDepositMicro: deferred.maxDepositMicro ?? deferred.fundMicro,
14181
+ human: args.human,
14182
+ ...deferred.pinnedRail ? { rail: deferred.pinnedRail, railSource: deferred.pinnedRailSource } : {},
14183
+ ...args.providerInfo ? { providerInfo: args.providerInfo } : {},
14184
+ ...args.signBody ? { signBody: args.signBody } : {}
14185
+ });
14186
+ reportFunding(args, outcome, {
14187
+ reason: deferred.reason === "open" ? "no_credit_open" : "below_refill_target",
14188
+ fundMicro: deferred.fundMicro,
14189
+ currency: deferred.currency,
14190
+ menu: deferred.menu,
14191
+ label: deferred.reason === "open" ? "Credit opening" : "Credit top-up"
14192
+ });
14193
+ }
14194
+ function forcedRefillRail(args, record2) {
14195
+ if (isCreditFundRail(record2.rail)) return { rail: record2.rail, source: "credit_bound" };
14196
+ const pin = effectiveFundingRail(
14197
+ args.config ?? loadConfig()?.credit,
14198
+ args.ref.endpoint,
14199
+ providerDvmIdentity(args.providerInfo)
14200
+ );
14201
+ return pin.rail && pin.source !== "default" ? { rail: pin.rail, source: pin.source } : {};
14202
+ }
14203
+ function reportFunding(args, outcome, ctx) {
14204
+ const what = ctx.label ?? "Credit top-up";
14205
+ const hint = outcome.hint ? ` ${outcome.hint}` : "";
14206
+ const incomplete = (code, adoptedDrain) => {
14207
+ noteCreditFundingIncomplete(
14208
+ buildCreditFundingIncomplete({
14209
+ code,
14210
+ dvm: noticeDvm(args),
14211
+ endpoint: args.ref.endpoint,
14212
+ reason: ctx.reason,
14213
+ amountMicro: ctx.fundMicro,
14214
+ currency: ctx.currency,
14215
+ outcome,
14216
+ ...adoptedDrain ? { adoptedDrain } : {}
14217
+ }),
14218
+ args.human
14219
+ );
14220
+ };
14221
+ switch (outcome.status) {
14222
+ case "funded": {
14223
+ if (outcome.reconciled || !outcome.rail) {
14224
+ info(`${what} at ${args.ref.endpoint} \u2014 ${outcome.display}${hint}`);
14225
+ if (outcome.reconciled) incomplete("credit_funding_reconciled");
14226
+ return;
14227
+ }
14228
+ noteCreditFunding(
14229
+ buildCreditFundingReport({
14230
+ dvm: noticeDvm(args),
14231
+ endpoint: args.ref.endpoint,
14232
+ reason: ctx.reason,
14233
+ amountMicro: outcome.fundedMicro ?? ctx.fundMicro,
14234
+ currency: ctx.currency,
14235
+ route: outcome.rail,
14236
+ // Every funding this module makes is a `/v1/credit` call of its own,
14237
+ // including the open — the job it followed paid per-call.
14238
+ ownRoundTrip: true,
14239
+ ...outcome.railReason ? { routeReason: outcome.railReason } : {},
14240
+ ...outcome.railSource ? { routeReasonSource: outcome.railSource } : {},
14241
+ ...outcome.x402Flavour ? { x402Flavour: outcome.x402Flavour } : {},
14242
+ ...outcome.tempoIntent ? { tempoIntent: outcome.tempoIntent } : {},
14243
+ outcome,
14244
+ ...ctx.menu.lightning_min_micro !== void 0 ? { lightningMinMicro: ctx.menu.lightning_min_micro } : {},
14245
+ ...outcome.credit ? { balanceMicro: outcome.credit.remaining_micro } : {}
14246
+ }),
14247
+ args.human
14248
+ );
14249
+ return;
14250
+ }
14251
+ case "settlement_pending":
14252
+ info(`${what} at ${args.ref.endpoint} \u2014 ${outcome.display}${hint}`);
14253
+ incomplete("credit_funding_settlement_pending");
14254
+ return;
14255
+ case "refused": {
14256
+ const adopted = outcome.error?.code === "settlement_pending" && args.signing ? adoptWedgedChannelDrain({
14257
+ endpoint: args.ref.endpoint,
14258
+ // The store identity, which is `providerInfo`'s and not the
14259
+ // typeable handle below — the same key `applyReceiptCredit` and
14260
+ // `markRefillRailUnavailable` write this credit under.
14261
+ ...settleIdentityArgs(args),
14262
+ handle: noticeDvm(args),
14263
+ callerPubkey: args.signing.pubkey,
14264
+ creditId: outcome.creditId,
14265
+ data: outcome.error.data
14266
+ }) : void 0;
14267
+ const reclaim = adopted ? ` ${adopted.advice}` : "";
14268
+ info(
14269
+ 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}`
14270
+ );
14271
+ incomplete("credit_funding_refused", adopted);
14272
+ return;
14273
+ }
14274
+ case "unavailable": {
14275
+ const pendingIntent = outcome.error?.code === "x402_voucher_pending" || outcome.error?.code === "x402_exact_authorization_pending" || outcome.error?.code === "tempo_charge_pending";
14276
+ if (outcome.error?.code === "below_rail_minimum" || pendingIntent) {
14277
+ info(`${what} at ${args.ref.endpoint} deferred \u2014 ${outcome.display}${hint}`);
14278
+ if (pendingIntent) incomplete("credit_funding_deferred");
14279
+ return;
14280
+ }
14281
+ if (outcome.railReason === "forced" && outcome.railSource !== "credit_bound") {
14282
+ info(`${what} at ${args.ref.endpoint} skipped \u2014 ${outcome.display}${hint}`);
14283
+ return;
14284
+ }
14285
+ return;
14286
+ }
14287
+ }
14288
+ }
14289
+
14290
+ // src/lib/provider-currency.ts
14291
+ async function providerCurrency(args) {
14292
+ if (!args.receipt?.settlement) return void 0;
14293
+ const upfront = args.status?.upfrontPayment?.currency;
14294
+ if (upfront) return upfront;
14295
+ const ask = [...args.messages ?? []].sort((a, b) => a.seq - b.seq).findLast((message2) => message2.from === "provider" && message2.type === "payment-request" && message2.content.credit?.currency);
14296
+ if (ask?.type === "payment-request" && ask.content.credit) return ask.content.credit.currency;
14297
+ try {
14298
+ return (await args.transport.describe(args.ref, { timeoutMs: 5e3 })).credit?.currency;
14299
+ } catch {
14300
+ return void 0;
14301
+ }
14302
+ }
14303
+
14304
+ // src/lib/job-ending.ts
14305
+ var PAYMENT_IN_PROGRESS_ATTEMPTS = 5;
14306
+ var MAX_RETRY_DELAY_MS = 3e4;
14307
+ async function retryWhilePaymentInProgress(send, options = {}) {
14308
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms)));
14309
+ for (let attempt = 1; ; attempt++) {
14310
+ try {
14311
+ return await send();
14312
+ } catch (error) {
14313
+ if (!(error instanceof DvmError) || error.code !== "payment_in_progress" || attempt >= PAYMENT_IN_PROGRESS_ATTEMPTS) throw error;
14314
+ const requested = error.data?.retry_after_ms;
14315
+ const delay = typeof requested === "number" && Number.isFinite(requested) ? Math.min(Math.max(requested, 0), MAX_RETRY_DELAY_MS) : 2e3;
14316
+ progressNotice(`A payment for this job is being verified; retrying in ${Math.ceil(delay / 1e3)} s...`, options.human);
14317
+ await sleep(delay);
14318
+ }
14319
+ }
14320
+ }
14321
+ async function readEnding(args) {
14322
+ const status2 = await observeJobContent(args.jobId, args.transport, args.ref, { timeoutMs: 5e3, jobToken: args.jobToken });
14323
+ if (status2 && isTerminalJobStatus(status2.status)) args.onTerminal?.(status2);
14324
+ if (!status2 || !isTerminalJobStatus(status2.status) || !status2.receipt?.settlement) return { status: status2 };
14325
+ if (args.persistLocalState) {
14326
+ const capture = captureTransportReceipt(args.jobId, status2);
14327
+ const job = loadJob(args.jobId);
14328
+ if (job) await settleCreditAfterRead({ job, capture, transport: args.transport, human: args.human });
14329
+ }
14330
+ const currency = args.persistLocalState ? void 0 : await providerCurrency({ receipt: status2.receipt, status: status2, transport: args.transport, ref: args.ref });
14331
+ const { settlement } = terminalSettlementFields(args.jobId, {
14332
+ status: status2.status,
14333
+ receipt: status2.receipt,
14334
+ persistLocalState: args.persistLocalState,
14335
+ currency
14336
+ });
14337
+ return { status: status2, ...settlement?.charged_micro !== void 0 ? { settlement } : {} };
14338
+ }
14339
+ function cancelledDisplay(settlement) {
14340
+ const stopped = settlement.stopped_micro ?? 0;
14341
+ 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.";
14342
+ return `${lead} ${settlement.display}`;
14343
+ }
14344
+
13749
14345
  // src/commands/dvm-identity.ts
13750
14346
  function dvmIdentity(dvmId, capability) {
13751
14347
  const out = {};
@@ -13758,34 +14354,117 @@ function dvmIdentity(dvmId, capability) {
13758
14354
  // src/commands/cancel.ts
13759
14355
  async function cancel(jobId, opts) {
13760
14356
  const access = resolveJobAccess(jobId, opts);
13761
- return withJobTokenRedaction(access.jobToken, () => cancelWithAccess(jobId, opts, access));
14357
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => cancelWithAccess(jobId, opts, access)));
13762
14358
  }
13763
14359
  async function cancelWithAccess(jobId, opts, access) {
13764
14360
  const { stored, ref, jobToken } = access;
13765
14361
  const json3 = (data) => providerJobJson(data, !!stored);
13766
14362
  const transport = createDvmTransport();
13767
14363
  progressNotice("Cancelling job...", opts.human);
13768
- await transport.cancel(jobId, opts.reason, ref, { jobToken });
13769
- transport.close();
14364
+ await retryWhilePaymentInProgress(() => transport.cancel(jobId, opts.reason, ref, { jobToken }), { human: opts.human });
13770
14365
  if (!access.endpointOverridden) markJobTerminal(
13771
14366
  jobId,
13772
14367
  "cancelled",
13773
14368
  opts.reason !== void 0 ? { message: opts.reason } : {},
13774
14369
  { callerCancelled: true }
13775
14370
  );
14371
+ const { settlement, status: status2 } = await readEnding({
14372
+ jobId,
14373
+ transport,
14374
+ ref,
14375
+ jobToken,
14376
+ persistLocalState: !access.endpointOverridden,
14377
+ human: opts.human
14378
+ });
14379
+ transport.close();
13776
14380
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
14381
+ const receiptPending = !settlement && status2 !== void 0 && isTerminalJobStatus(status2.status) && !status2.receipt && !status2.receiptParseError && !access.endpointOverridden && expectsReceipt(jobId, stored);
14382
+ 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;
14383
+ const hint = settlementCurrencyHint(settlement, ref.endpoint);
13777
14384
  if (opts.human) {
13778
14385
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
14386
+ if (display) info(display);
14387
+ if (hint) info(` ${hint}`);
13779
14388
  } else {
13780
14389
  json3({
13781
14390
  jobId,
13782
14391
  ...dvmIdentity(stored?.dvmId, stored?.capability),
13783
14392
  status: "cancelled",
13784
14393
  ...opts.reason ? { reason: opts.reason } : {},
14394
+ ...settlement ? { settlement } : {},
14395
+ ...display ? { display } : {},
14396
+ ...hint ? { hint } : {},
13785
14397
  next_action: null
13786
14398
  });
13787
14399
  }
13788
14400
  }
14401
+ function expectsReceipt(jobId, stored) {
14402
+ return stored?.receiptsSupported === true || loadMessages(jobId).some((message2) => message2.from === "provider" && message2.type === "payment-request" && typeof message2.content.charged_if_declined_micro === "number");
14403
+ }
14404
+
14405
+ // src/commands/decline.ts
14406
+ async function decline(jobId, opts) {
14407
+ const access = resolveJobAccess(jobId, opts);
14408
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => declineWithAccess(jobId, opts, access)));
14409
+ }
14410
+ async function declineWithAccess(jobId, opts, access) {
14411
+ const { stored, ref, jobToken } = access;
14412
+ const json3 = (data) => providerJobJson(data, !!stored);
14413
+ const job = guidanceJobArg(jobId);
14414
+ const transport = createDvmTransport();
14415
+ progressNotice("Declining...", opts.human);
14416
+ const content = opts.reason !== void 0 ? { reason: opts.reason } : {};
14417
+ await retryWhilePaymentInProgress(
14418
+ () => transport.sendMessage(jobId, { type: "decline", content }, ref, { jobToken }),
14419
+ { human: opts.human }
14420
+ );
14421
+ const ending = await readEnding({
14422
+ jobId,
14423
+ transport,
14424
+ ref,
14425
+ jobToken,
14426
+ persistLocalState: !access.endpointOverridden,
14427
+ human: opts.human,
14428
+ onTerminal: (status2) => {
14429
+ if (!access.endpointOverridden && isTerminalJobStatus(status2.status)) markJobTerminal(
14430
+ jobId,
14431
+ status2.status,
14432
+ opts.reason !== void 0 ? { message: opts.reason } : {},
14433
+ { callerCancelled: true, callerDeclined: true }
14434
+ );
14435
+ }
14436
+ });
14437
+ transport.close();
14438
+ const observed = ending.status?.status;
14439
+ if (observed !== void 0 && !isTerminalJobStatus(observed)) {
14440
+ throw new DvmError(
14441
+ "decline_unsupported",
14442
+ `The provider accepted the decline, but the job is still ${observed}.`,
14443
+ `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}\`.`,
14444
+ { jobId, status: observed }
14445
+ );
14446
+ }
14447
+ const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
14448
+ const { settlement } = ending;
14449
+ 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.`;
14450
+ const hint = settlementCurrencyHint(settlement, ref.endpoint);
14451
+ if (opts.human) {
14452
+ info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""}: ${display}`);
14453
+ if (hint) info(` ${hint}`);
14454
+ return;
14455
+ }
14456
+ json3({
14457
+ jobId,
14458
+ ...dvmIdentity(stored?.dvmId, stored?.capability),
14459
+ status: observed ?? "unknown",
14460
+ declined: true,
14461
+ ...opts.reason !== void 0 ? { reason: opts.reason } : {},
14462
+ ...settlement ? { settlement } : {},
14463
+ display,
14464
+ ...hint ? { hint } : {},
14465
+ next_action: observed === void 0 ? pollNextAction(jobId, display) : null
14466
+ });
14467
+ }
13789
14468
 
13790
14469
  // src/commands/config.ts
13791
14470
  import { createInterface } from "readline";
@@ -13990,14 +14669,14 @@ async function confirmRollback(stored, preview, opts) {
13990
14669
  async function withStrandingChecked(removing, commit) {
13991
14670
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
13992
14671
  if (leaving.has("tempo")) {
13993
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-EOP5IHJT.js");
14672
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-FMBCHD2M.js");
13994
14673
  await assertTempoWalletIdle2("disconnect");
13995
14674
  }
13996
14675
  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");
14676
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-O7IQD6EQ.js");
14677
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-MIJH3JE4.js");
14678
+ const { ensureAddress: ensureAddress2 } = await import("./internal-O7IQD6EQ.js");
14679
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
14001
14680
  return withX402ChannelLock2(async () => {
14002
14681
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
14003
14682
  if (unsettled.length > 0) {
@@ -14129,6 +14808,7 @@ function computeHeadroom(args) {
14129
14808
  menu,
14130
14809
  routeAmountMicro,
14131
14810
  fundableNowMicro,
14811
+ menuRoomMicro: menu ? Math.max(menu.max_micro - Math.max(args.balanceMicro ?? 0, 0), 0) : void 0,
14132
14812
  availability: args.routeAvailability
14133
14813
  });
14134
14814
  const pin = effectiveFundingRail(args.config, args.endpoint, args.identity);
@@ -14283,19 +14963,27 @@ function fundableNow(capMicro, balanceMicro, menu) {
14283
14963
  return Math.max(room, 0);
14284
14964
  }
14285
14965
  function railMinimums(menu) {
14286
- if (!menu?.lightning_min_micro) return [];
14287
- return [{ rail: "lightning", minMicro: menu.lightning_min_micro }];
14966
+ const minimums = [];
14967
+ if (menu?.lightning_min_micro) {
14968
+ minimums.push({ rail: "lightning", minMicro: menu.lightning_min_micro });
14969
+ }
14970
+ if (menu?.funding.includes("stripe")) {
14971
+ minimums.push({ rail: "stripe", minMicro: CARD_MIN_MICRO });
14972
+ }
14973
+ return minimums;
14288
14974
  }
14289
14975
  function compatibilityFor(args) {
14290
14976
  if (!args.menu || args.routeAmountMicro === void 0) return [];
14291
14977
  const menu = args.menu;
14292
14978
  const routeAmountMicro = args.routeAmountMicro;
14293
14979
  const availability = new Map(args.availability?.map((entry) => [entry.rail, entry]));
14980
+ const minimums = new Map(railMinimums(menu).map((entry) => [entry.rail, entry.minMicro]));
14294
14981
  return menu.funding.filter(isCreditFundRail).map((rail) => {
14295
- const minimum = rail === "lightning" && menu.lightning_min_micro !== void 0 ? Math.max(menu.min_micro, menu.lightning_min_micro) : menu.min_micro;
14982
+ const minimum = Math.max(menu.min_micro, minimums.get(rail) ?? 0);
14296
14983
  const local = availability.get(rail);
14297
14984
  let status2;
14298
- if (args.fundableNowMicro !== void 0 && (routeAmountMicro > args.fundableNowMicro || minimum > args.fundableNowMicro)) {
14985
+ const bound = rail === "stripe" ? args.menuRoomMicro : args.fundableNowMicro;
14986
+ if (bound !== void 0 && (routeAmountMicro > bound || rail !== "stripe" && minimum > bound)) {
14299
14987
  status2 = "blocked_by_trust_cap";
14300
14988
  } else if (routeAmountMicro < minimum) {
14301
14989
  status2 = "blocked_by_rail_minimum";
@@ -14363,67 +15051,18 @@ function routeDisplay(h) {
14363
15051
  out.push(
14364
15052
  "No automatic funding route is available locally: the ecash pocket cannot cover this amount and no connected funding wallet can replenish or carry it."
14365
15053
  );
15054
+ const card = h.routeCompatibility.find((route) => route.rail === "stripe");
15055
+ if (card) {
15056
+ const separateCredit = h.boundRail !== void 0 && h.boundRail !== "stripe";
15057
+ const command = `dvm credit fund ${shellQuoteArg(h.endpoint)} --rail stripe${separateCredit ? " --credit-id <new id>" : ""} --amount '$X'`;
15058
+ out.push(
15059
+ `${separateCredit ? `This credit is bound to ${h.boundRail}; open a separate card-funded credit` : "This DVM accepts card top-ups"} with '${command}': replace $X with a whole-cent amount of at least ${usd(card.minMicro)}. Your human must approve the top-up in Stripe Link.`
15060
+ );
15061
+ }
14366
15062
  }
14367
15063
  return out;
14368
15064
  }
14369
15065
 
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
15066
  // src/lib/credit-guidance.ts
14428
15067
  function repeatUseCreditHint(dvm) {
14429
15068
  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.`;
@@ -18791,7 +19430,7 @@ async function runCreditFund(dvm, opts) {
18791
19430
  amountMicro = sizing.amountMicro;
18792
19431
  }
18793
19432
  const fundMicro = amountMicro;
18794
- if (!pending4 && !signedPending && (explicitMicro !== void 0 || targetJobs !== void 0)) {
19433
+ if (rail !== "stripe" && !pending4 && !signedPending && (explicitMicro !== void 0 || targetJobs !== void 0)) {
18795
19434
  await enforceTrustTier({
18796
19435
  endpoint,
18797
19436
  amountMicro: fundMicro,
@@ -20658,8 +21297,8 @@ async function probeX402(x402, timeoutMs) {
20658
21297
  let network;
20659
21298
  let address;
20660
21299
  try {
20661
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-LASVQ72F.js");
20662
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-KPPGYK5N.js");
21300
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
21301
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-O7IQD6EQ.js");
20663
21302
  const wallet = loadX402Wallet2();
20664
21303
  if (!wallet) {
20665
21304
  const storedKey = x402.privateKey;
@@ -20711,8 +21350,8 @@ async function probeMpp(mpp, timeoutMs) {
20711
21350
  if (!mpp) return null;
20712
21351
  if (mpp.method === "tempo") {
20713
21352
  try {
20714
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-4A5M3FVO.js");
20715
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-KPPGYK5N.js");
21353
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-U3WBWIIH.js");
21354
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-O7IQD6EQ.js");
20716
21355
  const account = await connectedTempoAccount2();
20717
21356
  if (!account) {
20718
21357
  return {
@@ -23184,14 +23823,14 @@ function buildFeedbackHint(jobId) {
23184
23823
  }
23185
23824
  function noteFeedbackNudge(nudge, human) {
23186
23825
  info(`${nudge.display} ${nudge.hint}`);
23187
- if (!human) pending2.feedback_nudge = nudge;
23826
+ if (!human) pending3.feedback_nudge = nudge;
23188
23827
  }
23189
23828
  function noteFeedbackHint(hint, human) {
23190
- if (!human) pending2.feedback_hint = hint;
23829
+ if (!human) pending3.feedback_hint = hint;
23191
23830
  }
23192
23831
  function takeFeedbackNoticeFields() {
23193
- const taken = { ...pending2 };
23194
- pending2 = {};
23832
+ const taken = { ...pending3 };
23833
+ pending3 = {};
23195
23834
  return taken;
23196
23835
  }
23197
23836
  function feedbackCommand(jobId, verdict) {
@@ -23201,7 +23840,7 @@ function buildFeedbackIntro(approval) {
23201
23840
  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
23841
  return approval === "ask" ? `${options} Relay these options to your user as part of this first approval request.` : options;
23203
23842
  }
23204
- var pending2 = {};
23843
+ var pending3 = {};
23205
23844
 
23206
23845
  // src/lib/feedback-nudges.ts
23207
23846
  var DEFAULT_FEEDBACK_POSTURE = "ask";
@@ -24021,49 +24660,6 @@ function formatBytes(bytes) {
24021
24660
  return `${bytes.toLocaleString("en-US")} bytes`;
24022
24661
  }
24023
24662
 
24024
- // src/lib/stream-outcome.ts
24025
- function persistStreamOutcome(outcome) {
24026
- const { jobId, messages: messages2, cursor, afterSeq, extra, providerStatus } = outcome;
24027
- const stored = loadJob(jobId);
24028
- const callerCancelled = outcome.callerCancelled ?? stored?.callerCancelled;
24029
- const terminal = streamTerminalStatus(messages2, { providerStatus, callerCancelled });
24030
- const log = terminal ? fullMessageLog(jobId, messages2, afterSeq) : void 0;
24031
- const providerTerminal = providerStatus?.status && isTerminalJobStatus(providerStatus.status);
24032
- if (terminal && (log || providerTerminal)) {
24033
- 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;
24035
- const retained = saved ?? fromLog;
24036
- const completion = providerStatus?.content_available === false && retained ? retained : {
24037
- ...saved,
24038
- ...fromLog,
24039
- ...terminal === "cancelled" && callerCancelled && stored?.completion?.message !== void 0 ? { message: stored.completion.message } : {},
24040
- ...providerTerminal ? completionSnapshot(providerStatus) : {}
24041
- };
24042
- markJobTerminal(jobId, terminal, completion, {
24043
- messageCursor: cursor,
24044
- ...extra
24045
- });
24046
- return completion;
24047
- }
24048
- updateJob(jobId, { messageCursor: cursor });
24049
- return void 0;
24050
- }
24051
- function streamTerminalStatus(messages2, context = {}) {
24052
- const providerStatus = context.providerStatus?.status;
24053
- if (providerStatus && isTerminalJobStatus(providerStatus)) return providerStatus;
24054
- const last = messages2.findLast((m) => m.type === "complete" || m.type === "cancel");
24055
- if (!last) return void 0;
24056
- if (last.type === "complete") return "completed";
24057
- return context.callerCancelled ? "cancelled" : "failed";
24058
- }
24059
- function fullMessageLog(jobId, messages2, afterSeq) {
24060
- if (afterSeq === 0) return messages2;
24061
- const local = [...loadMessages(jobId)].sort((a, b) => a.seq - b.seq);
24062
- if (local.length === 0 || local[0].seq > 1) return void 0;
24063
- const contiguous = local.every((m, i2) => i2 === 0 || m.seq === local[i2 - 1].seq + 1);
24064
- return contiguous ? local : void 0;
24065
- }
24066
-
24067
24663
  // src/lib/message-human.ts
24068
24664
  function paymentAmount(msg) {
24069
24665
  if (msg.from === "requester" && msg.content.credit) {
@@ -24140,6 +24736,9 @@ function formatMessageHuman(msg, jobId, artifactSession) {
24140
24736
  case "cancel":
24141
24737
  info(`[${msg.seq}] Job ended${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
24142
24738
  break;
24739
+ case "decline":
24740
+ info(`[${msg.seq}] ${prefix} declined; the job ended${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
24741
+ break;
24143
24742
  default:
24144
24743
  info(`[${seq}] ${prefix} sent a message of type "${type}".`);
24145
24744
  }
@@ -24152,14 +24751,15 @@ function nextActionHuman(action) {
24152
24751
  case "respond":
24153
24752
  case "pay": {
24154
24753
  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)}`);
24754
+ const template = action.hint.match(/`(dvm[^`]*)`/)?.[1]?.replace(/^(dvm (?:message|pay|status)) '<job_id>'/, (_, prefix) => `${prefix} ${shellQuoteArg(action.job_id)}`);
24156
24755
  const command = action.type === "respond" ? template?.replace("--prompt-id '<prompt_id>'", () => `--prompt-id ${shellQuoteArg(action.prompt_id)}`) : template;
24157
24756
  if (command?.startsWith("dvm status ")) return `Next: ${action.type === "pay" ? "the provider's charge of " : ""}${display}`;
24158
24757
  if (action.type === "respond") {
24159
24758
  return `Next: ${display} Provider is waiting for your input. ${command ? `Run \`${command}\`.` : action.hint}`;
24160
24759
  }
24161
24760
  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}`;
24761
+ const decline2 = action.charged_if_declined_micro !== void 0 && command?.startsWith("dvm pay ") ? ` To stop instead, run \`dvm decline ${shellQuoteArg(action.job_id)}\`.` : "";
24762
+ return `Next: Payment required to continue: ${display}${display.endsWith(".") ? "" : "."} Run \`${command ?? `dvm pay ${shellQuoteArg(action.job_id)}`}\`.${decline2}${thresholdHint}`;
24163
24763
  }
24164
24764
  case "poll": {
24165
24765
  const hint = typeof action.hint === "string" ? action.hint : action.hint.text;
@@ -24169,8 +24769,6 @@ function nextActionHuman(action) {
24169
24769
  }
24170
24770
  case "refund":
24171
24771
  return action.claimed ? null : `Next: ${refundSummaryHuman(action)}`;
24172
- case "approve":
24173
- return `Next: ${action.hint}`;
24174
24772
  }
24175
24773
  }
24176
24774
  function printNextActionHuman(action, options = {}) {
@@ -24334,7 +24932,7 @@ async function messages(jobId, opts) {
24334
24932
  throw new DvmError("invalid_arguments", "Use --until with --wait, and --wait with streaming enabled.");
24335
24933
  }
24336
24934
  const access = resolveJobAccess(jobId, opts);
24337
- return withJobTokenRedaction(access.jobToken, () => messagesWithAccess(jobId, opts, access));
24935
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => messagesWithAccess(jobId, opts, access)));
24338
24936
  }
24339
24937
  async function messagesWithAccess(jobId, opts, access) {
24340
24938
  const waitDuration = opts.wait ? parseDurationMs(opts.until ?? "12h") : void 0;
@@ -24397,10 +24995,11 @@ async function messagesWithAccess(jobId, opts, access) {
24397
24995
  const nextAction = withRefundNextAction(jobId, actionFromMessages(msgs) ?? (streamTerminalStatus(msgs, { providerStatus: providerStatus2 }) || isTerminal ? null : pollNextAction(jobId)), refunds);
24398
24996
  const content2 = jobContentFields(jobId, providerStatus2, opts.human);
24399
24997
  const resolvedAction2 = await resolveNextAction2(nextAction, msgs, providerStatus2?.status);
24400
- const settlement2 = observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden);
24998
+ const currency2 = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus2?.receipt, status: providerStatus2, messages: msgs, transport, ref }) : void 0;
24999
+ const settlement2 = observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden, currency2);
24401
25000
  transport.close();
24402
25001
  if (opts.human) {
24403
- if (settlement2.settlement) info(settlement2.settlement.display);
25002
+ renderSettlementHuman(settlement2);
24404
25003
  info(String(content2.content_hint));
24405
25004
  if (msgs.length === 0) {
24406
25005
  info("No new messages.");
@@ -24464,10 +25063,12 @@ async function messagesWithAccess(jobId, opts, access) {
24464
25063
  }
24465
25064
  const content = jobContentFields(jobId, providerStatus, opts.human);
24466
25065
  const resolvedAction = await resolveNextAction2(result.nextAction, result.messages, providerStatus?.status ?? result.providerStatus?.status);
24467
- const settlement = observedSettlementFields(jobId, providerStatus ?? result.providerStatus, !access.endpointOverridden);
25066
+ const observed = providerStatus ?? result.providerStatus;
25067
+ const currency = access.endpointOverridden ? await providerCurrency({ receipt: observed?.receipt, status: observed, messages: result.messages, transport, ref }) : void 0;
25068
+ const settlement = observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
24468
25069
  transport.close();
24469
25070
  if (opts.human) {
24470
- if (settlement.settlement) info(settlement.settlement.display);
25071
+ renderSettlementHuman(settlement);
24471
25072
  info(String(content.content_hint));
24472
25073
  if (result.messages.length === 0) {
24473
25074
  info("No new messages.");
@@ -24593,7 +25194,7 @@ async function message(jobId, text, opts) {
24593
25194
  const access = resolveJobAccess(jobId, opts);
24594
25195
  return withJobTokenRedaction(
24595
25196
  access.jobToken,
24596
- () => messageWithAccess(jobId, text, opts, access)
25197
+ () => withOutputWarnings(() => messageWithAccess(jobId, text, opts, access))
24597
25198
  );
24598
25199
  }
24599
25200
  async function messageWithAccess(jobId, text, opts, access) {
@@ -24646,10 +25247,11 @@ async function messageWithAccess(jobId, text, opts, access) {
24646
25247
  });
24647
25248
  }
24648
25249
  const content = jobContentFields(jobId, providerStatus, opts.human);
24649
- const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden);
25250
+ const currency = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus?.receipt, status: providerStatus, messages: result.messages, transport, ref }) : void 0;
25251
+ const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
24650
25252
  transport.close();
24651
25253
  if (opts.human) {
24652
- if (settlement.settlement) info(settlement.settlement.display);
25254
+ renderSettlementHuman(settlement);
24653
25255
  info(String(content.content_hint));
24654
25256
  info(`Message sent (type: ${msgType}).`);
24655
25257
  for (const msg of result.messages) {
@@ -24730,7 +25332,7 @@ function parseForcedRail(raw2) {
24730
25332
  // src/commands/pay.ts
24731
25333
  async function pay(jobId, opts) {
24732
25334
  const access = resolveStoredJobAccess(jobId, opts);
24733
- return withJobTokenRedaction(access.jobToken, () => payWithAccess(jobId, opts, access));
25335
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => payWithAccess(jobId, opts, access)));
24734
25336
  }
24735
25337
  async function payWithAccess(jobId, opts, access) {
24736
25338
  const rail = parseForcedRail(opts.rail);
@@ -24862,11 +25464,12 @@ async function payWithAccess(jobId, opts, access) {
24862
25464
  human: opts.human
24863
25465
  });
24864
25466
  }
24865
- const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden);
25467
+ const currency = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus?.receipt, status: providerStatus, messages: streamResult.messages, transport, ref }) : void 0;
25468
+ const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
24866
25469
  transport.close();
24867
25470
  const identifier = stored.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
24868
25471
  if (opts.human) {
24869
- if (settlement.settlement) info(settlement.settlement.display);
25472
+ renderSettlementHuman(settlement);
24870
25473
  info(`${paid.display}${identifier ? ` [${identifier}]` : ""}`);
24871
25474
  for (const msg of streamResult.messages) {
24872
25475
  formatMessageHuman(msg, jobId, artifactSession);
@@ -25542,11 +26145,18 @@ function receiptsList(opts) {
25542
26145
  info(emptyMessage(opts));
25543
26146
  return;
25544
26147
  }
26148
+ const unnamed = /* @__PURE__ */ new Set();
25545
26149
  for (const { entry, status: status2 } of shown) {
25546
- info(`${entry.receipt.job_id} ${receiptDisplay(entry.receipt, status2, rate)}`);
26150
+ const context = receiptPieceContext(entry.receipt);
26151
+ info(`${entry.receipt.job_id} ${receiptDisplay(entry.receipt, status2, rate, context)}`);
26152
+ if (receiptCurrencyHint(entry.receipt, status2, context)) unnamed.add(entry.endpoint);
25547
26153
  }
25548
26154
  info(`
25549
26155
  ${shown.length} of ${matched.length} receipt(s).`);
26156
+ if (unnamed.size > 0) {
26157
+ const [only] = unnamed;
26158
+ info(unknownCurrencyHint(unnamed.size === 1 && only ? only : void 0));
26159
+ }
25550
26160
  return;
25551
26161
  }
25552
26162
  json({
@@ -25572,7 +26182,7 @@ Endpoint: ${entry.endpoint || "(unknown)"}`);
25572
26182
  }
25573
26183
  json({
25574
26184
  ...storedReceiptJson(entry, result, rate),
25575
- hint: receiptHint(result.status, jobId)
26185
+ hint: verdictHint(entry, result, jobId)
25576
26186
  });
25577
26187
  }
25578
26188
  async function receiptsVerify(jobId, opts) {
@@ -25608,7 +26218,7 @@ Signature: ${result.checks.signature ? "valid" : "INVALID"}`);
25608
26218
  ...storedReceiptJson(entry, result, rate),
25609
26219
  ...opts.file?.length ? { files } : {},
25610
26220
  anchor_source: opts.endpoint ? "refetched" : "stored",
25611
- hint: receiptHint(result.status, jobId)
26221
+ hint: verdictHint(entry, result, jobId)
25612
26222
  });
25613
26223
  }
25614
26224
  async function verifyFiles(jobId, opts, delivered, result) {
@@ -25729,6 +26339,8 @@ function resolveLimit(limit) {
25729
26339
  return n;
25730
26340
  }
25731
26341
  function listEntryJson(entry, status2, rate) {
26342
+ const context = receiptPieceContext(entry.receipt);
26343
+ const currencyHint = receiptCurrencyHint(entry.receipt, status2, context, entry.endpoint || void 0);
25732
26344
  return {
25733
26345
  job_id: entry.receipt.job_id,
25734
26346
  dvm_id: entry.receipt.dvm_id,
@@ -25739,19 +26351,21 @@ function listEntryJson(entry, status2, rate) {
25739
26351
  // see `receiptIssuedAtIso`. The raw number stays intact under `receipt`.
25740
26352
  issued_at: receiptIssuedAtIso(entry.receipt),
25741
26353
  paid_msats: entry.receipt.paid.msats,
25742
- settlement: receiptSettlement(entry.receipt, status2),
26354
+ settlement: receiptSettlement(entry.receipt, status2, void 0, context),
25743
26355
  receipt_verified: status2,
25744
- display: receiptDisplay(entry.receipt, status2, rate)
26356
+ display: receiptDisplay(entry.receipt, status2, rate, context),
26357
+ ...currencyHint ? { hint: currencyHint } : {}
25745
26358
  };
25746
26359
  }
25747
26360
  function storedReceiptJson(entry, result, rate) {
26361
+ const context = receiptPieceContext(entry.receipt);
25748
26362
  return {
25749
26363
  job_id: entry.receipt.job_id,
25750
26364
  endpoint: entry.endpoint,
25751
26365
  receipt: entry.receipt,
25752
26366
  receipt_verified: result.status,
25753
26367
  receipt_checks: result.checks,
25754
- settlement: receiptSettlement(entry.receipt, result.status),
26368
+ settlement: receiptSettlement(entry.receipt, result.status, void 0, context),
25755
26369
  ...result.reason ? { receipt_error: result.reason, receipt_error_detail: receiptFailureDetail(result.reason) } : {},
25756
26370
  // The DVM's terminal reason is provider free text — an agent relaying it
25757
26371
  // must be able to see that it is untrusted (docs/cli.md).
@@ -25762,11 +26376,18 @@ function storedReceiptJson(entry, result, rate) {
25762
26376
  // caller the proof it is attached to.
25763
26377
  collected_at: epochMsToIso(entry.verified_at),
25764
26378
  ...entry.builder ? { builder: entry.builder } : {},
25765
- display: receiptDisplay(entry.receipt, result.status, rate)
26379
+ display: receiptDisplay(entry.receipt, result.status, rate, context)
25766
26380
  };
25767
26381
  }
26382
+ function verdictHint(entry, result, jobId) {
26383
+ const currency = receiptCurrencyHint(entry.receipt, result.status, receiptPieceContext(entry.receipt), entry.endpoint || void 0);
26384
+ return [currency, receiptHint(result.status, jobId)].filter(Boolean).join(" ");
26385
+ }
25768
26386
  function renderVerdictHuman(entry, result, rate) {
25769
- info(receiptDisplay(entry.receipt, result.status, rate));
26387
+ const context = receiptPieceContext(entry.receipt);
26388
+ info(receiptDisplay(entry.receipt, result.status, rate, context));
26389
+ const currencyHint = receiptCurrencyHint(entry.receipt, result.status, context, entry.endpoint || void 0);
26390
+ if (currencyHint) info(` ${currencyHint}`);
25770
26391
  if (result.reason) info(` ${receiptFailureDetail(result.reason)}`);
25771
26392
  if (entry.receipt.reason) info(` Provider reason: ${entry.receipt.reason}`);
25772
26393
  }
@@ -25815,374 +26436,6 @@ function artifactContent(msg) {
25815
26436
  // src/commands/request.ts
25816
26437
  import { createHash as createHash4, randomUUID as randomUUID4 } from "crypto";
25817
26438
 
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
26439
  // src/lib/local-correlation.ts
26187
26440
  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
26441
  function prepareLocalCorrelationId(raw2) {
@@ -27232,10 +27485,7 @@ async function requestWithWarnings(opts) {
27232
27485
  if (hint) info(`\u{1F4CE} ${hint}`);
27233
27486
  }
27234
27487
  if (captured) renderReceiptHuman(captured, receipt.jobId);
27235
- else {
27236
- const { settlement } = terminalSettlementFields(receipt.jobId);
27237
- if (settlement) info(settlement.display);
27238
- }
27488
+ else renderSettlementHuman(terminalSettlementFields(receipt.jobId));
27239
27489
  finalizeProgressLine();
27240
27490
  echoTraceIdHuman();
27241
27491
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: isTerminalJobStatus(receipt.status) || !!streamTerminalStatus(result.messages) });
@@ -29218,10 +29468,7 @@ async function streamAfterPayment(args) {
29218
29468
  if (hint) info(`\u{1F4CE} ${hint}`);
29219
29469
  }
29220
29470
  if (captured) renderReceiptHuman(captured, jobId);
29221
- else {
29222
- const { settlement } = terminalSettlementFields(jobId);
29223
- if (settlement) info(settlement.display);
29224
- }
29471
+ else renderSettlementHuman(terminalSettlementFields(jobId));
29225
29472
  finalizeProgressLine();
29226
29473
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: !!streamTerminalStatus(result.messages) });
29227
29474
  } else {
@@ -29581,6 +29828,9 @@ function paymentMethod(receipt) {
29581
29828
 
29582
29829
  // src/commands/request-resume.ts
29583
29830
  async function requestResume(requestId, opts = {}) {
29831
+ return withOutputWarnings(() => resumeRequest(requestId, opts));
29832
+ }
29833
+ async function resumeRequest(requestId, opts) {
29584
29834
  if (!isPublicRequestId(requestId)) {
29585
29835
  throw new DvmError(
29586
29836
  "invalid_request_id",
@@ -29691,6 +29941,7 @@ async function search(opts) {
29691
29941
  const transport = createDvmTransport();
29692
29942
  const ref = { endpoint };
29693
29943
  progressNotice("Searching for providers...", opts.human);
29944
+ let jobToken;
29694
29945
  try {
29695
29946
  const result = await runDiscoveryLifecycle({
29696
29947
  transport,
@@ -29699,6 +29950,7 @@ async function search(opts) {
29699
29950
  input,
29700
29951
  timeoutMs: timeout
29701
29952
  });
29953
+ jobToken = result.jobToken;
29702
29954
  if (result.summary) {
29703
29955
  outputResults2(result.summary, opts.human, result.nextAction);
29704
29956
  return;
@@ -29728,6 +29980,8 @@ async function search(opts) {
29728
29980
  "Search did not complete in time.",
29729
29981
  "Try again or increase --timeout."
29730
29982
  );
29983
+ } catch (error) {
29984
+ throw redactJobTokenFromError(error, jobToken);
29731
29985
  } finally {
29732
29986
  transport.close();
29733
29987
  }
@@ -29875,7 +30129,8 @@ function jobSpend(job, receipt) {
29875
30129
  const receiptTotalDisplay = receipt ? formatPaymentAmount(receipt.paid.msats, void 0, { anchor: false }) + valuationLabel : void 0;
29876
30130
  const settled = settlement.status === "settled" || settlement.status === "free";
29877
30131
  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"}`;
30132
+ const pieces = settlement.charged_micro !== void 0 ? settlement.display : void 0;
30133
+ 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
30134
  if (job.paymentMethod === "credit" && !knownCredit && settlement.status === "unknown")
29880
30135
  display = `Drawn from prepaid credit; the upfront amount is not recorded locally. ${display}`;
29881
30136
  else if (job.paymentMethod === "credit" && !knownCredit && receiptHeadline)
@@ -29883,6 +30138,7 @@ function jobSpend(job, receipt) {
29883
30138
  if (budgetDisplay) display += `, budget ${budgetDisplay}`;
29884
30139
  if (refunds.length > 0) display += `, ${refunds.length} refund${refunds.length === 1 ? "" : "s"}`;
29885
30140
  display += ".";
30141
+ if (pieces !== void 0) display += ` ${pieces}`;
29886
30142
  if (logMismatch) display += " Local payment log disagrees with the job record.";
29887
30143
  if (receipt && job.paymentMethod === "credit" && !knownCredit) display += " The receipt total includes the unrecorded credit draw.";
29888
30144
  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.";
@@ -29927,7 +30183,7 @@ function renderSpendHuman(spend, print) {
29927
30183
  // src/commands/status.ts
29928
30184
  async function status(jobId, opts) {
29929
30185
  const access = resolveJobAccess(jobId, opts);
29930
- return withJobTokenRedaction(access.jobToken, () => statusWithAccess(jobId, opts, access));
30186
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => statusWithAccess(jobId, opts, access)));
29931
30187
  }
29932
30188
  async function statusWithAccess(jobId, opts, access) {
29933
30189
  const { stored, ref, jobToken } = access;
@@ -29980,11 +30236,12 @@ async function statusWithAccess(jobId, opts, access) {
29980
30236
  const reasonUnavailable = completion.message === void 0 || result.content_available === false && completion.message === "";
29981
30237
  if (reasonUnavailable && (result.status === "failed" || result.status === "cancelled")) {
29982
30238
  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);
30239
+ const terminal = msgs.findLast((message2) => message2.type === "complete" || message2.type === "cancel" || message2.type === "decline");
30240
+ const reason = savedReason ?? (terminal?.type === "cancel" || terminal?.type === "decline" ? terminal.content.reason : void 0);
29985
30241
  if (reason !== void 0) completion.message = reason;
29986
30242
  }
29987
30243
  let receipt;
30244
+ let currency;
29988
30245
  if (isTerminalJobStatus(result.status)) {
29989
30246
  if (stored && !access.endpointOverridden) {
29990
30247
  const savedCompletion = result.content_available === false && stored.status === result.status && stored.completion ? stored.completion : completion;
@@ -29995,7 +30252,8 @@ async function statusWithAccess(jobId, opts, access) {
29995
30252
  if (stored && result.receipt && !stored.builderAnchor && !access.endpointOverridden) {
29996
30253
  await backfillTrustAnchor(jobId, transport, ref);
29997
30254
  }
29998
- receipt = stored && !access.endpointOverridden ? captureTransportReceipt(jobId, result) : transientReceiptCapture(jobId, result);
30255
+ currency = stored && !access.endpointOverridden ? void 0 : await providerCurrency({ receipt: result.receipt, status: result, messages: msgs, transport, ref });
30256
+ receipt = stored && !access.endpointOverridden ? captureTransportReceipt(jobId, result) : transientReceiptCapture(jobId, result, ref.endpoint, currency);
29999
30257
  if (stored && !access.endpointOverridden) {
30000
30258
  await settleCreditAfterRead({ job: stored, capture: receipt, transport, human: opts.human });
30001
30259
  }
@@ -30019,10 +30277,11 @@ async function statusWithAccess(jobId, opts, access) {
30019
30277
  msgs,
30020
30278
  cursor: newCursor,
30021
30279
  receipt,
30022
- content: result
30280
+ content: result,
30281
+ currency
30023
30282
  });
30024
30283
  }
30025
- function transientReceiptCapture(jobId, response) {
30284
+ function transientReceiptCapture(jobId, response, endpoint, currency) {
30026
30285
  if (response.receiptParseError) {
30027
30286
  return {
30028
30287
  status: "unparseable",
@@ -30032,17 +30291,7 @@ function transientReceiptCapture(jobId, response) {
30032
30291
  }
30033
30292
  if (!response.receipt) return { status: "absent", display: receiptHint("absent") };
30034
30293
  const result = verifyJobReceipt({ receipt: response.receipt, expectedJobId: jobId });
30035
- return {
30036
- status: result.status,
30037
- receipt: response.receipt,
30038
- checks: result.checks,
30039
- ...result.reason ? { reason: result.reason } : {},
30040
- display: receiptDisplay(
30041
- response.receipt,
30042
- result.status,
30043
- getLastKnownBtcRate()?.rate ?? 0
30044
- )
30045
- };
30294
+ return toCapture(response.receipt, result, { currency }, endpoint);
30046
30295
  }
30047
30296
  function renderStatus(jobId, stored, jobStatus, completion, source, nextAction, opts, fetched) {
30048
30297
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
@@ -30057,7 +30306,8 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
30057
30306
  const settlement = terminalSettlementFields(jobId, {
30058
30307
  status: jobStatus,
30059
30308
  receipt: receipt?.receipt,
30060
- persistLocalState: !!stored
30309
+ persistLocalState: !!stored,
30310
+ currency: fetched?.currency
30061
30311
  });
30062
30312
  if (opts.human) {
30063
30313
  if (jobStatus === "completed" && completion.summary) {
@@ -30081,6 +30331,7 @@ ${msgs.length} new message(s):`);
30081
30331
  if (spend) renderSpendHuman(spend, info);
30082
30332
  else if (settlement.settlement) info(settlement.settlement.display);
30083
30333
  if (receipt) renderReceiptHuman(receipt);
30334
+ if (settlement.settlement_hint && !receipt?.currencyHint) info(` ${settlement.settlement_hint}`);
30084
30335
  printNextActionHuman(nextAction);
30085
30336
  return;
30086
30337
  }
@@ -30102,6 +30353,7 @@ ${msgs.length} new message(s):`);
30102
30353
  // read as "this DVM doesn't issue receipts" rather than "not yet".
30103
30354
  ...receipt ? receiptJsonFields(receipt) : {},
30104
30355
  ...settlement,
30356
+ ...receipt?.currencyHint ? { settlement_hint: void 0 } : {},
30105
30357
  // `dvm status` is a job-terminal emission for `--no-stream`
30106
30358
  // jobs, so it drains the deferred-notice sinks like the request terminals
30107
30359
  // do. Both spread blind and are absent when nothing was stashed.
@@ -30180,7 +30432,7 @@ async function streamUpload(opts) {
30180
30432
  const compatibilityError = clientCompatibilityError(res.status, res.body);
30181
30433
  if (compatibilityError) throw compatibilityError;
30182
30434
  if (res.status === 429 && attempt < maxAttempts) {
30183
- const wait = retryAfterMs(res.headers["retry-after"], capMs);
30435
+ const wait = retryAfterMs2(res.headers["retry-after"], capMs);
30184
30436
  opts.log?.(
30185
30437
  `429 backpressure; retry ${attempt.toString()}/${(maxAttempts - 1).toString()} in ${wait.toString()}ms`
30186
30438
  );
@@ -30257,7 +30509,7 @@ function firstValueHeaders(headers) {
30257
30509
  }
30258
30510
  return out;
30259
30511
  }
30260
- function retryAfterMs(retryAfter, capMs) {
30512
+ function retryAfterMs2(retryAfter, capMs) {
30261
30513
  const seconds = retryAfter !== void 0 ? Number.parseInt(retryAfter, 10) : NaN;
30262
30514
  const ms = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : 2e3;
30263
30515
  return Math.min(ms, capMs);
@@ -32920,8 +33172,8 @@ function fundInterruptedError(err, fund) {
32920
33172
  const cause = classifyMintError(err);
32921
33173
  const reason = describeCause(cause, minting);
32922
33174
  const command = "dvm wallet show";
32923
- const retryAfterMs2 = suggestedRetryAfterMs(cause, err);
32924
- const wait = retryAfterMs2 !== void 0 ? ` Wait ${formatWait(retryAfterMs2)} first.` : "";
33175
+ const retryAfterMs3 = suggestedRetryAfterMs(cause, err);
33176
+ const wait = retryAfterMs3 !== void 0 ? ` Wait ${formatWait(retryAfterMs3)} first.` : "";
32925
33177
  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
33178
  const diagnostic = err instanceof DvmError && err.code === "mint_quote_poll_unavailable" ? { name: mintErrorName(cause), label: mintErrorName(cause) } : unknownErrorDiagnostic(err);
32927
33179
  return new DvmError(
@@ -32935,14 +33187,14 @@ function fundInterruptedError(err, fund) {
32935
33187
  quote_id: quoteId,
32936
33188
  amount_sats: amountSats,
32937
33189
  pending: true,
32938
- ...retryAfterMs2 !== void 0 ? { retry_after_ms: retryAfterMs2 } : {},
33190
+ ...retryAfterMs3 !== void 0 ? { retry_after_ms: retryAfterMs3 } : {},
32939
33191
  error_name: diagnostic.name,
32940
33192
  ...diagnostic.code ? { error_code: diagnostic.code } : {},
32941
33193
  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
33194
  next_action: {
32943
33195
  type: "run_command",
32944
33196
  command,
32945
- ...retryAfterMs2 !== void 0 ? { retry_after_ms: retryAfterMs2 } : {},
33197
+ ...retryAfterMs3 !== void 0 ? { retry_after_ms: retryAfterMs3 } : {},
32946
33198
  hint
32947
33199
  }
32948
33200
  }
@@ -33115,11 +33367,11 @@ var RATE_LIMIT_TEXT = /\b429\b|rate[ -]?limit|too many requests/i;
33115
33367
  function uncheckedMint(entry, quoteId, thrown, message2, subject = "mint") {
33116
33368
  const cause = thrown !== void 0 ? classifyMintError(thrown) : RATE_LIMIT_TEXT.test(message2) ? "rate_limited" : "unexpected";
33117
33369
  const retryable = cause !== "unexpected";
33118
- const retryAfterMs2 = suggestedRetryAfterMs(cause, thrown);
33370
+ const retryAfterMs3 = suggestedRetryAfterMs(cause, thrown);
33119
33371
  const diagnostic = thrown !== void 0 ? unknownErrorDiagnostic(thrown) : void 0;
33120
33372
  const amountSats = entry?.amount_sats ?? 0;
33121
33373
  const reason = describeCause2(cause);
33122
- const wait = retryAfterMs2 !== void 0 ? ` Wait ${formatWait(retryAfterMs2)} and try again.` : "";
33374
+ const wait = retryAfterMs3 !== void 0 ? ` Wait ${formatWait(retryAfterMs3)} and try again.` : "";
33123
33375
  const copy = uncheckedCopy(subject, amountSats, quoteId, reason, wait, retryable);
33124
33376
  return {
33125
33377
  quote_id: quoteId,
@@ -33129,7 +33381,7 @@ function uncheckedMint(entry, quoteId, thrown, message2, subject = "mint") {
33129
33381
  retryable,
33130
33382
  reason,
33131
33383
  pending: true,
33132
- ...retryAfterMs2 !== void 0 ? { retry_after_ms: retryAfterMs2 } : {},
33384
+ ...retryAfterMs3 !== void 0 ? { retry_after_ms: retryAfterMs3 } : {},
33133
33385
  ...diagnostic ? { error_name: diagnostic.name } : {},
33134
33386
  ...diagnostic?.code ? { error_code: diagnostic.code } : {},
33135
33387
  display: copy.display,
@@ -33137,7 +33389,7 @@ function uncheckedMint(entry, quoteId, thrown, message2, subject = "mint") {
33137
33389
  next_action: {
33138
33390
  type: "run_command",
33139
33391
  command: RECONCILE_COMMAND,
33140
- ...retryAfterMs2 !== void 0 ? { retry_after_ms: retryAfterMs2 } : {},
33392
+ ...retryAfterMs3 !== void 0 ? { retry_after_ms: retryAfterMs3 } : {},
33141
33393
  hint: copy.hint
33142
33394
  }
33143
33395
  };
@@ -38561,7 +38813,7 @@ function buildProgram() {
38561
38813
  "Size the funding to a workload instead of a figure: N jobs' worth at this DVM's price"
38562
38814
  ).option(
38563
38815
  "--over-trust",
38564
- "Fund past the trust-tier cap deliberately \u2014 required for an amount above what receipts here have earned"
38816
+ "Fund past the trust-tier cap deliberately \u2014 required for an amount above what receipts here have earned, on every rail except card (stripe), which the cap never applies to"
38565
38817
  ).option("--rail <rail>", `Force a funding rail: ${creditFundRails}`).option("--cashu-mint <mint>", "Pin Cashu funding to one DVM-accepted mint").option(
38566
38818
  "--max-cashu-principal-sats <sats>",
38567
38819
  "Refuse Cashu funding above this token-principal ceiling"
@@ -38616,7 +38868,14 @@ function buildProgram() {
38616
38868
  ).action((jobId, opts) => {
38617
38869
  return catchErrors(() => pay(jobId, opts), opts.human);
38618
38870
  });
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) => {
38871
+ program2.command("decline <job-id>").description(
38872
+ "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."
38873
+ ).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) => {
38874
+ return catchErrors(() => decline(jobId, opts), opts.human);
38875
+ });
38876
+ program2.command("cancel <job-id>").description(
38877
+ "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."
38878
+ ).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
38879
  return catchErrors(() => cancel(jobId, opts), opts.human);
38621
38880
  });
38622
38881
  program2.command("feedback [body...]").description(