@dvmkit/dvm-cli 0.16.0 → 0.17.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.
package/dist/dvm.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-CEBEPXQ7.js";
8
+ } from "./chunk-ZGBCVQF2.js";
9
9
  import {
10
10
  CARD_MIN_MICRO,
11
11
  DEFAULT_CREDIT_POSTURE,
@@ -182,6 +182,7 @@ import {
182
182
  sweepPendingMints,
183
183
  sweepStaleInFlight,
184
184
  terminalSettlementFields,
185
+ terminalSettlementReport,
185
186
  tierCapOverrides,
186
187
  toCapture,
187
188
  toFloatError,
@@ -200,34 +201,13 @@ import {
200
201
  withIdentityRecovery,
201
202
  withJobTokenRedaction,
202
203
  withRequestResultRecovery
203
- } from "./chunk-LDYMUQZE.js";
204
+ } from "./chunk-DE7TEOUR.js";
204
205
  import {
205
206
  connectedTempoAccount,
206
207
  generateTempoKey,
207
208
  tempoBalanceCheckHint,
208
209
  tempoWrongAssetHint
209
- } from "./chunk-WSLZBJ52.js";
210
- import {
211
- addOutputWarnings,
212
- assertValidBudget,
213
- costAnchor,
214
- formatAmount,
215
- formatAmountBestEffort,
216
- formatPaymentAmount,
217
- getOutputTraceId,
218
- hasUnsavedJobState,
219
- info,
220
- json,
221
- monetaryJson,
222
- parseBudget,
223
- raw,
224
- resolveBtcUsdRate,
225
- setOutputTraceId,
226
- staleRateNotice,
227
- tryResolveBtcUsdRate,
228
- tryX402Payment,
229
- withOutputWarnings
230
- } from "./chunk-NSA2RJ2T.js";
210
+ } from "./chunk-OEWENVJ7.js";
231
211
  import {
232
212
  assertSupportedX402Network,
233
213
  connectedX402Payer,
@@ -236,7 +216,7 @@ import {
236
216
  repinX402WalletNetwork,
237
217
  saveX402Wallet,
238
218
  x402NetworkLabel
239
- } from "./chunk-H6WQ4S6K.js";
219
+ } from "./chunk-VLD7OKSH.js";
240
220
  import {
241
221
  CREDIT_POSTURES,
242
222
  FEEDBACK_POSTURES,
@@ -253,10 +233,31 @@ import {
253
233
  retireConfigBackup,
254
234
  rollbackConfig,
255
235
  updateConfig
256
- } from "./chunk-WRIXUSMR.js";
236
+ } from "./chunk-ESQ6DCS3.js";
237
+ import {
238
+ addOutputWarnings,
239
+ assertValidBudget,
240
+ costAnchor,
241
+ formatAmount,
242
+ formatAmountBestEffort,
243
+ formatPaymentAmount,
244
+ getOutputTraceId,
245
+ hasUnsavedJobState,
246
+ info,
247
+ json,
248
+ monetaryJson,
249
+ parseBudget,
250
+ raw,
251
+ resolveBtcUsdRate,
252
+ setOutputTraceId,
253
+ staleRateNotice,
254
+ tryResolveBtcUsdRate,
255
+ tryX402Payment,
256
+ withOutputWarnings
257
+ } from "./chunk-R6FZT6S2.js";
257
258
  import {
258
259
  assertX402WalletIdle
259
- } from "./chunk-2TNH4ME5.js";
260
+ } from "./chunk-REIUNZQX.js";
260
261
  import {
261
262
  A,
262
263
  AGENT_MNEMONIC_FILE,
@@ -316,6 +317,7 @@ import {
316
317
  attestedDvmIdentity,
317
318
  authenticatedBuilderPubkey,
318
319
  base64,
320
+ bech32,
319
321
  bindCashuTokenToSubmissionContext,
320
322
  canonicalRequestPath,
321
323
  cashuSubmissionBindingFingerprint,
@@ -495,7 +497,7 @@ import {
495
497
  x402PendingUnsettled,
496
498
  x402RequiredFromError,
497
499
  x402ReservationRelease
498
- } from "./chunk-U2PODYIS.js";
500
+ } from "./chunk-THTPKBZX.js";
499
501
  import "./chunk-JBU7RKQ3.js";
500
502
  import "./chunk-KDNFUDOG.js";
501
503
  import "./chunk-IUTVV6N5.js";
@@ -11613,8 +11615,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11613
11615
  }
11614
11616
  }
11615
11617
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11616
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-QKAKRLPI.js");
11617
- const { tryX402Payment: tryX402Payment2 } = await import("./client-S5PTHG25.js");
11618
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
11619
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-3JOMNAIQ.js");
11618
11620
  const wallet = loadX402Wallet2();
11619
11621
  if (wallet) {
11620
11622
  let proof;
@@ -14392,7 +14394,7 @@ async function settleCreditAfterJob(args) {
14392
14394
  }
14393
14395
  }
14394
14396
  if (args.allowTopup !== false) {
14395
- const refill = args.refillPocket ?? (await import("./pocket-refill-3CA4PFXG.js")).refillPocketIfLow;
14397
+ const refill = args.refillPocket ?? (await import("./pocket-refill-5BEM22UM.js")).refillPocketIfLow;
14396
14398
  await refill({ human: args.human }).catch(() => void 0);
14397
14399
  }
14398
14400
  }
@@ -14850,8 +14852,10 @@ async function cancelWithAccess(jobId, opts, access) {
14850
14852
  const endingDisplay = settlement ? cancelledDisplay(settlement) : receiptPending ? `Stopped. Its receipt is not available yet; \`dvm status ${guidanceJobArg(jobId)}\` shows what was charged once it is.` : void 0;
14851
14853
  const display = [endingDisplay, artifacts.display].filter(Boolean).join(" ") || void 0;
14852
14854
  const hint = settlementCurrencyHint(settlement, ref.endpoint);
14855
+ const { wallet_remaining } = await terminalSettlementReport(jobId, { status: "cancelled", persistLocalState: !access.endpointOverridden });
14853
14856
  if (opts.human) {
14854
14857
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
14858
+ if (wallet_remaining) info(wallet_remaining.display);
14855
14859
  if (display) info(display);
14856
14860
  if (hint) info(` ${hint}`);
14857
14861
  } else {
@@ -14861,6 +14865,7 @@ async function cancelWithAccess(jobId, opts, access) {
14861
14865
  status: "cancelled",
14862
14866
  ...opts.reason ? { reason: opts.reason } : {},
14863
14867
  ...settlement ? { settlement } : {},
14868
+ ...wallet_remaining ? { wallet_remaining } : {},
14864
14869
  ...display ? { display } : {},
14865
14870
  ...artifacts.fields,
14866
14871
  ...hint ? { hint } : {},
@@ -14945,8 +14950,10 @@ async function declineWithAccess(jobId, opts, access) {
14945
14950
  const endingDisplay = 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.`;
14946
14951
  const display = [endingDisplay, artifacts.display].filter(Boolean).join(" ");
14947
14952
  const hint = settlementCurrencyHint(settlement, ref.endpoint);
14953
+ const { wallet_remaining } = await terminalSettlementReport(jobId, { status: observed, persistLocalState: !access.endpointOverridden });
14948
14954
  if (opts.human) {
14949
14955
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""}: ${display}`);
14956
+ if (wallet_remaining) info(wallet_remaining.display);
14950
14957
  if (hint) info(` ${hint}`);
14951
14958
  return;
14952
14959
  }
@@ -14957,6 +14964,7 @@ async function declineWithAccess(jobId, opts, access) {
14957
14964
  declined: true,
14958
14965
  ...opts.reason !== void 0 ? { reason: opts.reason } : {},
14959
14966
  ...settlement ? { settlement } : {},
14967
+ ...wallet_remaining ? { wallet_remaining } : {},
14960
14968
  display,
14961
14969
  ...artifacts.fields,
14962
14970
  ...hint ? { hint } : {},
@@ -15167,14 +15175,14 @@ async function confirmRollback(stored, preview, opts) {
15167
15175
  async function withStrandingChecked(removing, commit) {
15168
15176
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
15169
15177
  if (leaving.has("tempo")) {
15170
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-GAM3DJ63.js");
15178
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-WGTX6MJR.js");
15171
15179
  await assertTempoWalletIdle2("disconnect");
15172
15180
  }
15173
15181
  if (!leaving.has("x402")) return commit();
15174
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-3SIUYRWP.js");
15175
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-7NHL5ATK.js");
15176
- const { ensureAddress: ensureAddress2 } = await import("./internal-3SIUYRWP.js");
15177
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-QKAKRLPI.js");
15182
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-L362ZUWL.js");
15183
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-BH4OA5I3.js");
15184
+ const { ensureAddress: ensureAddress2 } = await import("./internal-L362ZUWL.js");
15185
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
15178
15186
  return withX402ChannelLock2(async () => {
15179
15187
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
15180
15188
  if (unsettled.length > 0) {
@@ -21881,8 +21889,8 @@ async function probeX402(x402, timeoutMs) {
21881
21889
  let network;
21882
21890
  let address;
21883
21891
  try {
21884
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-QKAKRLPI.js");
21885
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-3SIUYRWP.js");
21892
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
21893
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-L362ZUWL.js");
21886
21894
  const wallet = loadX402Wallet2();
21887
21895
  if (!wallet) {
21888
21896
  const storedKey = x402.privateKey;
@@ -21934,8 +21942,8 @@ async function probeMpp(mpp, timeoutMs) {
21934
21942
  if (!mpp) return null;
21935
21943
  if (mpp.method === "tempo") {
21936
21944
  try {
21937
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-JTARPYLN.js");
21938
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-3SIUYRWP.js");
21945
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-OTB2YSWE.js");
21946
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-L362ZUWL.js");
21939
21947
  const account = await connectedTempoAccount2();
21940
21948
  if (!account) {
21941
21949
  return {
@@ -25672,7 +25680,7 @@ async function messagesWithAccess(jobId, opts, access) {
25672
25680
  const content2 = jobContentFields(jobId, providerStatus2, opts.human);
25673
25681
  const resolvedAction2 = await resolveNextAction2(nextAction, msgs, providerStatus2?.status);
25674
25682
  const currency2 = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus2?.receipt, status: providerStatus2, messages: msgs, transport, ref }) : void 0;
25675
- const settlement2 = observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden, currency2);
25683
+ const settlement2 = await observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden, currency2);
25676
25684
  transport.close();
25677
25685
  if (opts.human) {
25678
25686
  renderSettlementHuman(settlement2);
@@ -25741,7 +25749,7 @@ async function messagesWithAccess(jobId, opts, access) {
25741
25749
  const resolvedAction = await resolveNextAction2(result.nextAction, result.messages, providerStatus?.status ?? result.providerStatus?.status);
25742
25750
  const observed = providerStatus ?? result.providerStatus;
25743
25751
  const currency = access.endpointOverridden ? await providerCurrency({ receipt: observed?.receipt, status: observed, messages: result.messages, transport, ref }) : void 0;
25744
- const settlement = observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
25752
+ const settlement = await observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
25745
25753
  transport.close();
25746
25754
  if (opts.human) {
25747
25755
  renderSettlementHuman(settlement);
@@ -25924,7 +25932,7 @@ async function messageWithAccess(jobId, text, opts, access) {
25924
25932
  }
25925
25933
  const content = jobContentFields(jobId, providerStatus, opts.human);
25926
25934
  const currency = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus?.receipt, status: providerStatus, messages: result.messages, transport, ref }) : void 0;
25927
- const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
25935
+ const settlement = await observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
25928
25936
  transport.close();
25929
25937
  if (opts.human) {
25930
25938
  renderSettlementHuman(settlement);
@@ -26141,7 +26149,7 @@ async function payWithAccess(jobId, opts, access) {
26141
26149
  });
26142
26150
  }
26143
26151
  const currency = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus?.receipt, status: providerStatus, messages: streamResult.messages, transport, ref }) : void 0;
26144
- const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
26152
+ const settlement = await observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
26145
26153
  transport.close();
26146
26154
  const identifier = stored.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
26147
26155
  if (opts.human) {
@@ -28102,7 +28110,7 @@ async function requestWithWarnings(opts, stage) {
28102
28110
  console.log(receipt.summary);
28103
28111
  const hint = nextStepHint(receipt.jobId, receipt.payloadIn, receipt.artifactCount, true);
28104
28112
  if (hint) info(`\u{1F4CE} ${hint}`);
28105
- renderReceiptHuman(captured, receipt.jobId);
28113
+ await renderReceiptHuman(captured, receipt.jobId);
28106
28114
  echoTraceIdHuman();
28107
28115
  } else {
28108
28116
  providerJobJson({
@@ -28113,7 +28121,7 @@ async function requestWithWarnings(opts, stage) {
28113
28121
  summary: receipt.summary,
28114
28122
  _provider_fields: ["summary"],
28115
28123
  ...buildCompletionHintFields(receipt.jobId, receipt),
28116
- ...receiptJsonFields(captured, receipt.jobId),
28124
+ ...await receiptJsonFields(captured, receipt.jobId),
28117
28125
  ...takeCreditNoticeFields(),
28118
28126
  ...takeFeedbackNoticeFields(),
28119
28127
  next_action: null
@@ -28182,8 +28190,8 @@ async function requestWithWarnings(opts, stage) {
28182
28190
  const hint = nextStepHint(receipt.jobId, completion.payloadIn, completion.artifactCount, true);
28183
28191
  if (hint) info(`\u{1F4CE} ${hint}`);
28184
28192
  }
28185
- if (captured) renderReceiptHuman(captured, receipt.jobId);
28186
- else renderSettlementHuman(terminalSettlementFields(receipt.jobId));
28193
+ if (captured) await renderReceiptHuman(captured, receipt.jobId);
28194
+ else renderSettlementHuman(await terminalSettlementReport(receipt.jobId));
28187
28195
  finalizeProgressLine();
28188
28196
  echoTraceIdHuman();
28189
28197
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: isTerminalJobStatus(receipt.status) || !!streamTerminalStatus(result.messages) });
@@ -28207,7 +28215,7 @@ async function requestWithWarnings(opts, stage) {
28207
28215
  ...completion?.message !== void 0 ? ["message"] : []
28208
28216
  ],
28209
28217
  ...completion ? buildCompletionHintFields(receipt.jobId, completion) : {},
28210
- ...captured ? receiptJsonFields(captured, receipt.jobId) : terminalSettlementFields(receipt.jobId),
28218
+ ...captured ? await receiptJsonFields(captured, receipt.jobId) : await terminalSettlementReport(receipt.jobId),
28211
28219
  ...takeCreditNoticeFields(),
28212
28220
  ...takeFeedbackNoticeFields(),
28213
28221
  next_action: result.nextAction,
@@ -28249,15 +28257,16 @@ async function requestWithWarnings(opts, stage) {
28249
28257
  human: opts.human
28250
28258
  });
28251
28259
  transport.close();
28260
+ const report = await terminalSettlementReport(receipt.jobId, { receipt: captured.receipt });
28252
28261
  if (opts.human) {
28253
28262
  for (const msg of failureMessages) {
28254
28263
  formatMessageHuman(msg, receipt.jobId, artifactSession);
28255
28264
  }
28256
- renderReceiptHuman(captured, receipt.jobId);
28265
+ await renderReceiptHuman(captured, receipt.jobId, report);
28257
28266
  }
28258
28267
  throw new DvmError(terminalStatus === "failed" ? "job_failed" : "cancelled", completion?.message ?? `Job ${terminalStatus}.`, void 0, {
28259
28268
  status: terminalStatus,
28260
- ...receiptJsonFields(captured, receipt.jobId),
28269
+ ...await receiptJsonFields(captured, receipt.jobId, report),
28261
28270
  ...failureMessages.length > 0 ? { messages: failureMessages.map(serializeMessageForOutput) } : {}
28262
28271
  }, void 0, completion?.message !== void 0 ? { message: "provider" } : void 0);
28263
28272
  }
@@ -29107,7 +29116,7 @@ async function payWithTempo(args, credential) {
29107
29116
  console.log(receipt.summary);
29108
29117
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
29109
29118
  if (hint) info(`\u{1F4CE} ${hint}`);
29110
- renderReceiptHuman(captured, effectiveJobId);
29119
+ await renderReceiptHuman(captured, effectiveJobId);
29111
29120
  } else {
29112
29121
  providerJobJson({
29113
29122
  jobId: effectiveJobId,
@@ -29117,7 +29126,7 @@ async function payWithTempo(args, credential) {
29117
29126
  summary: receipt.summary,
29118
29127
  _provider_fields: ["summary"],
29119
29128
  ...buildCompletionHintFields(effectiveJobId, receipt),
29120
- ...receiptJsonFields(captured, effectiveJobId),
29129
+ ...await receiptJsonFields(captured, effectiveJobId),
29121
29130
  paidWith: "tempo",
29122
29131
  account: account.address,
29123
29132
  ...takeCreditNoticeFields(),
@@ -29786,7 +29795,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29786
29795
  console.log(receipt.summary);
29787
29796
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
29788
29797
  if (hint) info(`\u{1F4CE} ${hint}`);
29789
- renderReceiptHuman(captured, effectiveJobId);
29798
+ await renderReceiptHuman(captured, effectiveJobId);
29790
29799
  } else {
29791
29800
  providerJobJson({
29792
29801
  jobId: effectiveJobId,
@@ -29794,7 +29803,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29794
29803
  summary: receipt.summary,
29795
29804
  _provider_fields: ["summary"],
29796
29805
  ...buildCompletionHintFields(effectiveJobId, receipt),
29797
- ...receiptJsonFields(captured, effectiveJobId),
29806
+ ...await receiptJsonFields(captured, effectiveJobId),
29798
29807
  paidWith: "cashu_p2pk",
29799
29808
  mint: prepared.mint,
29800
29809
  amountSats: prepared.totalSats,
@@ -29987,7 +29996,7 @@ async function payWithX402(args, proof) {
29987
29996
  console.log(receipt.summary);
29988
29997
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
29989
29998
  if (hint) info(`\u{1F4CE} ${hint}`);
29990
- renderReceiptHuman(captured, effectiveJobId);
29999
+ await renderReceiptHuman(captured, effectiveJobId);
29991
30000
  } else {
29992
30001
  providerJobJson({
29993
30002
  jobId: effectiveJobId,
@@ -29997,7 +30006,7 @@ async function payWithX402(args, proof) {
29997
30006
  summary: receipt.summary,
29998
30007
  _provider_fields: ["summary"],
29999
30008
  ...buildCompletionHintFields(effectiveJobId, receipt),
30000
- ...receiptJsonFields(captured, effectiveJobId),
30009
+ ...await receiptJsonFields(captured, effectiveJobId),
30001
30010
  paidWith: "x402",
30002
30011
  account: wallet.address,
30003
30012
  ...takeCreditNoticeFields(),
@@ -30180,8 +30189,8 @@ async function streamAfterPayment(args) {
30180
30189
  const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, true);
30181
30190
  if (hint) info(`\u{1F4CE} ${hint}`);
30182
30191
  }
30183
- if (captured) renderReceiptHuman(captured, jobId);
30184
- else renderSettlementHuman(terminalSettlementFields(jobId));
30192
+ if (captured) await renderReceiptHuman(captured, jobId);
30193
+ else renderSettlementHuman(await terminalSettlementReport(jobId));
30185
30194
  finalizeProgressLine();
30186
30195
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: !!streamTerminalStatus(result.messages) });
30187
30196
  } else {
@@ -30200,7 +30209,7 @@ async function streamAfterPayment(args) {
30200
30209
  ...completion?.message !== void 0 ? ["message"] : []
30201
30210
  ],
30202
30211
  ...completion ? buildCompletionHintFields(jobId, completion) : {},
30203
- ...captured ? receiptJsonFields(captured, jobId) : terminalSettlementFields(jobId),
30212
+ ...captured ? await receiptJsonFields(captured, jobId) : await terminalSettlementReport(jobId),
30204
30213
  ...takeCreditNoticeFields(),
30205
30214
  ...takeFeedbackNoticeFields(),
30206
30215
  next_action: result.nextAction,
@@ -30246,7 +30255,7 @@ async function recoverViaStatusPoll(args) {
30246
30255
  });
30247
30256
  if (human) {
30248
30257
  info(status2.summary ?? "Job completed (recovered via status check).");
30249
- renderReceiptHuman(captured, jobId);
30258
+ await renderReceiptHuman(captured, jobId);
30250
30259
  } else {
30251
30260
  providerJobJson({
30252
30261
  jobId,
@@ -30256,7 +30265,7 @@ async function recoverViaStatusPoll(args) {
30256
30265
  _provider_fields: ["summary"],
30257
30266
  recovered: true,
30258
30267
  ...paymentFields,
30259
- ...receiptJsonFields(captured, jobId),
30268
+ ...await receiptJsonFields(captured, jobId),
30260
30269
  ...takeCreditNoticeFields(),
30261
30270
  ...takeFeedbackNoticeFields(),
30262
30271
  next_action: null
@@ -30278,7 +30287,7 @@ async function recoverViaStatusPoll(args) {
30278
30287
  const errorMsg = status2.message ?? `Job ${status2.status}.`;
30279
30288
  if (human) {
30280
30289
  info(errorMsg);
30281
- renderReceiptHuman(captured, jobId);
30290
+ await renderReceiptHuman(captured, jobId);
30282
30291
  } else {
30283
30292
  providerJobJson({
30284
30293
  jobId,
@@ -30287,7 +30296,7 @@ async function recoverViaStatusPoll(args) {
30287
30296
  message: errorMsg,
30288
30297
  ...status2.message !== void 0 ? { _provider_fields: ["message"] } : {},
30289
30298
  ...paymentFields,
30290
- ...receiptJsonFields(captured, jobId),
30299
+ ...await receiptJsonFields(captured, jobId),
30291
30300
  ...takeCreditNoticeFields(),
30292
30301
  ...takeFeedbackNoticeFields(),
30293
30302
  next_action: null
@@ -30475,12 +30484,14 @@ async function requestResultWithWarnings(requestId, opts) {
30475
30484
  endpoint: intent.endpoint,
30476
30485
  jobId: receipt.jobId
30477
30486
  });
30487
+ const { wallet_remaining } = await terminalSettlementReport(receipt.jobId);
30478
30488
  if (opts.human) {
30479
30489
  info(`Recovered request ${requestId} as job ${receipt.jobId} (${receipt.status}).`);
30490
+ if (wallet_remaining) info(wallet_remaining.display);
30480
30491
  if (confirmed.length > 0) {
30481
30492
  info(`The wallet payment held for this request is now confirmed as spent on that job.`);
30482
30493
  }
30483
- renderReceiptHuman(captured);
30494
+ await renderReceiptHuman(captured);
30484
30495
  return;
30485
30496
  }
30486
30497
  json({
@@ -30491,7 +30502,8 @@ async function requestResultWithWarnings(requestId, opts) {
30491
30502
  ...dvmIdentity(intent.dvmId, intent.capability),
30492
30503
  ...receipt.summary !== void 0 ? { summary: receipt.summary } : {},
30493
30504
  ...confirmed.length > 0 ? { confirmed_pending_submissions: confirmed } : {},
30494
- ...receiptJsonFields(captured),
30505
+ ...await receiptJsonFields(captured),
30506
+ ...wallet_remaining ? { wallet_remaining } : {},
30495
30507
  next_action: receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled" ? null : {
30496
30508
  type: "poll",
30497
30509
  job_id: receipt.jobId,
@@ -30957,7 +30969,7 @@ async function statusWithAccess(jobId, opts, access) {
30957
30969
  }
30958
30970
  await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
30959
30971
  transport2.close();
30960
- renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
30972
+ await renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
30961
30973
  receipt: receipt2,
30962
30974
  content
30963
30975
  });
@@ -31037,7 +31049,7 @@ async function statusWithAccess(jobId, opts, access) {
31037
31049
  if (Object.keys(updates).length > 0) updateObservedJob(jobId, updates);
31038
31050
  }
31039
31051
  transport.close();
31040
- renderStatus(jobId, stored, result.status, completion, "provider", nextAction, opts, {
31052
+ await renderStatus(jobId, stored, result.status, completion, "provider", nextAction, opts, {
31041
31053
  msgs,
31042
31054
  cursor: newCursor,
31043
31055
  receipt,
@@ -31057,7 +31069,7 @@ function transientReceiptCapture(jobId, response, endpoint, currency) {
31057
31069
  const result = verifyJobReceipt({ receipt: response.receipt, expectedJobId: jobId });
31058
31070
  return toCapture(response.receipt, result, { currency }, endpoint);
31059
31071
  }
31060
- function renderStatus(jobId, stored, jobStatus, completion, source, nextAction, opts, fetched) {
31072
+ async function renderStatus(jobId, stored, jobStatus, completion, source, nextAction, opts, fetched) {
31061
31073
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
31062
31074
  const artifacts = terminalCompletionOutput(jobId, jobStatus, completion, {
31063
31075
  human: opts.human,
@@ -31070,7 +31082,7 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
31070
31082
  ...loadJob(jobId) ?? stored,
31071
31083
  status: jobStatus
31072
31084
  }, receipt?.receipt) : void 0;
31073
- const settlement = terminalSettlementFields(jobId, {
31085
+ const settlement = await terminalSettlementReport(jobId, {
31074
31086
  status: jobStatus,
31075
31087
  receipt: receipt?.receipt,
31076
31088
  persistLocalState: !!stored,
@@ -31097,7 +31109,8 @@ ${msgs.length} new message(s):`);
31097
31109
  if (traceId) info(`Trace: ${traceId}`);
31098
31110
  if (spend) renderSpendHuman(spend, info);
31099
31111
  else if (settlement.settlement) info(settlement.settlement.display);
31100
- if (receipt) renderReceiptHuman(receipt);
31112
+ if (settlement.wallet_remaining) info(settlement.wallet_remaining.display);
31113
+ if (receipt) await renderReceiptHuman(receipt);
31101
31114
  if (settlement.settlement_hint && !receipt?.currencyHint) info(` ${settlement.settlement_hint}`);
31102
31115
  printNextActionHuman(nextAction);
31103
31116
  return;
@@ -31119,7 +31132,7 @@ ${msgs.length} new message(s):`);
31119
31132
  ...completion.message ? { message: completion.message } : {},
31120
31133
  // terminal responses only. On a still-running job "absent" would
31121
31134
  // read as "this DVM doesn't issue receipts" rather than "not yet".
31122
- ...receipt ? receiptJsonFields(receipt) : {},
31135
+ ...receipt ? await receiptJsonFields(receipt) : {},
31123
31136
  ...settlement,
31124
31137
  ...receipt?.currencyHint ? { settlement_hint: void 0 } : {},
31125
31138
  // `dvm status` is a job-terminal emission for `--no-stream`
@@ -34839,7 +34852,7 @@ async function fundX402Rail(amount, opts) {
34839
34852
  const { connected, isNew } = await withX402ChannelLock(async () => {
34840
34853
  const existing = loadX402Wallet();
34841
34854
  return existing ? { connected: await ensureAddress(existing), isNew: false } : {
34842
- connected: await saveX402Wallet(await generateX402PrivateKey(), X402_DEFAULT_NETWORK),
34855
+ connected: await saveX402Wallet(await generateX402PrivateKey(), X402_DEFAULT_NETWORK, true),
34843
34856
  isNew: true
34844
34857
  };
34845
34858
  });
@@ -36071,35 +36084,132 @@ function mnemonicValidationError2(result) {
36071
36084
  );
36072
36085
  }
36073
36086
 
36074
- // src/lib/wallet-agent/cash-out.ts
36075
- async function cashOutFromMint(opts) {
36076
- const mintUrl = opts.mintUrl;
36077
- const now = opts.now ?? (() => Date.now());
36078
- const getWalletForMint = opts.getWalletForMint ?? getWallet;
36079
- const fetchInvoice = opts.fetchInvoice ?? fetchLnurlPayInvoice;
36080
- const initial = loadAgentWallet();
36081
- if (!initial) {
36087
+ // src/lib/wallet-agent/invoice.ts
36088
+ function invoiceDestination(destination) {
36089
+ const invoice = destination.replace(/^lightning:/i, "").toLowerCase();
36090
+ return !invoice.includes("@") && /^ln(bcrt|tbs|tb|bc)([0-9]+[munp]?)?1[02-9ac-hj-np-z]+$/.test(invoice) ? invoice : void 0;
36091
+ }
36092
+ function invalidInvoice(message2) {
36093
+ throw new DvmError(
36094
+ "invalid_invoice",
36095
+ `${message2} No money moved.`,
36096
+ "Ask for a valid mainnet invoice with an amount, then run `dvm wallet cash-out <invoice>`."
36097
+ );
36098
+ }
36099
+ function invoiceAmountSats(invoice, now = Date.now()) {
36100
+ let decoded;
36101
+ try {
36102
+ decoded = bech32.decode(invoice, false);
36103
+ } catch {
36104
+ return invalidInvoice("The invoice has invalid Bech32 encoding or checksum.");
36105
+ }
36106
+ const header = /^ln(bcrt|tbs|tb|bc)([0-9]+)?([munp]?)$/.exec(decoded.prefix);
36107
+ if (!header || header[1] !== "bc") return invalidInvoice("The invoice is on the wrong network; this wallet pays Bitcoin mainnet invoices.");
36108
+ if (!header[2]) return invalidInvoice("An amountless invoice cannot be cashed out.");
36109
+ const scale = { "": 1000000000000n, m: 1000000000n, u: 1000000n, n: 1000n, p: 1n };
36110
+ const picoBtc = BigInt(header[2]) * scale[header[3]];
36111
+ if (picoBtc <= 0n || picoBtc % 10n !== 0n) return invalidInvoice("The invoice amount must be positive and represent whole millisatoshis.");
36112
+ const sats = Number((picoBtc + 9999n) / 10000n);
36113
+ const words = decoded.words;
36114
+ const end = words.length - 104;
36115
+ if (end < 7 || !Number.isSafeInteger(sats)) return invalidInvoice("The invoice has invalid payment data or amount.");
36116
+ const integer = (data) => data.reduce((value, word) => value * 32 + word, 0);
36117
+ const timestamp = integer(words.slice(0, 7));
36118
+ let expiry = 3600;
36119
+ let hasExpiry = false;
36120
+ for (let pos = 7; pos < end; ) {
36121
+ if (pos + 3 > end) return invalidInvoice("The invoice has a truncated tagged field.");
36122
+ const tag = words[pos], length = words[pos + 1] * 32 + words[pos + 2];
36123
+ pos += 3;
36124
+ if (pos + length > end) return invalidInvoice("The invoice has a truncated tagged field.");
36125
+ if (tag === 6) {
36126
+ if (hasExpiry || length === 0) return invalidInvoice("The invoice has an invalid expiry field.");
36127
+ expiry = integer(words.slice(pos, pos + length));
36128
+ hasExpiry = true;
36129
+ }
36130
+ pos += length;
36131
+ }
36132
+ if (!Number.isSafeInteger(timestamp + expiry)) return invalidInvoice("The invoice expiry is out of range.");
36133
+ const remainingMs = (timestamp + expiry) * 1e3 - now;
36134
+ if (remainingMs <= 0) return invalidInvoice("The invoice has expired.");
36135
+ if (remainingMs < 6e4) return invalidInvoice("The invoice expires in less than 60 seconds.");
36136
+ return sats;
36137
+ }
36138
+ function assertInvoiceNotPending(wallet, invoice) {
36139
+ const normalized = invoiceDestination(invoice);
36140
+ if (normalized && wallet.pending_melts.some((entry) => invoiceDestination(entry.bolt11) === normalized)) {
36082
36141
  throw new DvmError(
36083
- "wallet_missing",
36084
- "No agent wallet found.",
36085
- "Run `dvm wallet init` first to generate a lock keypair."
36142
+ "cash_out_pending",
36143
+ "This invoice already has a cash-out in flight. No money moved.",
36144
+ "Run `dvm wallet show` to reconcile it before retrying."
36086
36145
  );
36087
36146
  }
36088
- const candidates = spendableAt(initial.proofs, mintUrl);
36089
- if (candidates.length === 0) {
36090
- return {
36091
- kind: "skipped",
36092
- mint: mintUrl,
36093
- reason: "no_balance",
36094
- message: `No spendable proofs at ${mintUrl}.`
36095
- };
36096
- }
36097
- let cashuWallet;
36147
+ }
36148
+
36149
+ // src/lib/wallet-agent/cash-out-invoice.ts
36150
+ async function prepareInvoice(opts, candidates, bounds) {
36151
+ const mint = opts.mintUrl;
36152
+ const refuse = (reason, message2) => ({
36153
+ kind: "skipped",
36154
+ mint,
36155
+ reason,
36156
+ message: `${message2} No money moved. Run \`dvm wallet mint-health\`, then retry \`dvm wallet cash-out <invoice>\`.`
36157
+ });
36158
+ const invoice = opts.bolt11;
36159
+ const amount = invoiceAmountSats(invoice, (opts.now ?? Date.now)());
36098
36160
  try {
36099
- cashuWallet = await getWalletForMint(mintUrl);
36161
+ const quote2 = await fetchMeltQuote(mint, invoice);
36162
+ if (quote2.amountSats !== amount) {
36163
+ return refuse("quote_amount_mismatch", `The mint quoted ${quote2.amountSats} sats for a ${amount} sat invoice.`);
36164
+ }
36165
+ if (typeof quote2.rawQuote.expiry === "number" && quote2.rawQuote.expiry * 1e3 <= (opts.now ?? Date.now)()) {
36166
+ return refuse("quote_expired", "The invoice's melt quote has expired.");
36167
+ }
36168
+ const inBounds = (bounds.minSats === null || amount >= bounds.minSats) && (bounds.maxSats === null || amount <= bounds.maxSats);
36169
+ const selected = [];
36170
+ let selectedTotal = 0;
36171
+ let inputFees = 0;
36172
+ for (const proof of candidates) {
36173
+ selected.push(proof);
36174
+ selectedTotal += proof.amount;
36175
+ inputFees = await getInputFeesForProofs(mint, toCashuProofs(selected));
36176
+ if (inBounds && selectedTotal >= quote2.amountSats + quote2.feeReserveSats + inputFees) break;
36177
+ }
36178
+ let largest = Math.max(0, Math.min(selectedTotal - quote2.feeReserveSats - inputFees, bounds.maxSats ?? Infinity));
36179
+ if (largest < (bounds.minSats ?? 1)) largest = 0;
36180
+ const fits = largest > 0 ? `The largest invoice amount that fits at the quoted fees is ${largest} sats. No money moved. Ask for an invoice of at most ${largest} sats, then run \`dvm wallet cash-out <invoice>\`.` : "No invoice can be paid from this balance at the quoted fees and mint limits. No money moved. Run `dvm wallet show` to check your balance, or `dvm wallet fund` to add funds.";
36181
+ if (selectedTotal < quote2.amountSats + quote2.feeReserveSats + inputFees) {
36182
+ return {
36183
+ kind: "skipped",
36184
+ mint,
36185
+ reason: "fees_exceed_balance",
36186
+ message: `The ${quote2.amountSats} sat invoice plus fees exceeds the ${selectedTotal} sat balance at ${mint}. ${fits}`
36187
+ };
36188
+ }
36189
+ if (bounds.minSats !== null && amount < bounds.minSats || bounds.maxSats !== null && amount > bounds.maxSats) {
36190
+ return {
36191
+ kind: "skipped",
36192
+ mint,
36193
+ reason: "amount_out_of_range",
36194
+ message: `The ${amount} sat invoice is outside this mint's payout limits. ${fits}`
36195
+ };
36196
+ }
36197
+ return { invoice, quote: quote2, selected, selectedTotal, inputFees };
36100
36198
  } catch (err) {
36101
- return { kind: "failed", mint: mintUrl, message: errorMessage2(err), settlement: "reverted" };
36199
+ return {
36200
+ kind: "failed",
36201
+ mint,
36202
+ settlement: "reverted",
36203
+ message: `Could not obtain a cash-out quote or input fees at ${mint}: ${err instanceof Error ? err.message : String(err)}. No money moved. Run \`dvm wallet mint-health\`, then retry \`dvm wallet cash-out <invoice>\`.`
36204
+ };
36102
36205
  }
36206
+ }
36207
+
36208
+ // src/lib/wallet-agent/cash-out-prepare.ts
36209
+ async function prepareCashOut(opts, candidates, cashuWallet) {
36210
+ const mintUrl = opts.mintUrl;
36211
+ const fetchInvoice = opts.fetchInvoice ?? fetchLnurlPayInvoice;
36212
+ if (opts.bolt11 !== void 0) return prepareInvoice(opts, candidates, meltBoundsOf(cashuWallet));
36103
36213
  const meltBounds = meltBoundsOf(cashuWallet);
36104
36214
  let target = opts.target;
36105
36215
  let cappedByMintMax;
@@ -36215,6 +36325,92 @@ async function cashOutFromMint(opts) {
36215
36325
  }
36216
36326
  }
36217
36327
  }
36328
+ return { invoice, quote: quote2, selected, selectedTotal, inputFees, cappedByMintMax };
36329
+ }
36330
+ function meltBoundsOf(wallet) {
36331
+ const reader = wallet;
36332
+ try {
36333
+ const nuts = reader.getMintInfo?.().cache?.nuts;
36334
+ if (nuts === void 0 || nuts === null) return { minSats: null, maxSats: null };
36335
+ return meltAmountBounds(nuts);
36336
+ } catch {
36337
+ return { minSats: null, maxSats: null };
36338
+ }
36339
+ }
36340
+ function selectInputs(candidates, target) {
36341
+ if (target.kind === "all") return [...candidates];
36342
+ const selected = [];
36343
+ let total = 0;
36344
+ for (const p of candidates) {
36345
+ selected.push(p);
36346
+ total += p.amount;
36347
+ if (total >= target.sats) return selected;
36348
+ }
36349
+ return selected;
36350
+ }
36351
+ function widenSelection(candidates, selected, needed, currentInputFees) {
36352
+ const chosen = new Set(selected.map((p) => proofKey(p)));
36353
+ const rest = candidates.filter((p) => !chosen.has(proofKey(p)));
36354
+ if (rest.length === 0) return null;
36355
+ const next = [...selected];
36356
+ let total = sumSats2(next);
36357
+ for (const p of rest) {
36358
+ if (total >= needed + currentInputFees) break;
36359
+ next.push(p);
36360
+ total += p.amount;
36361
+ }
36362
+ return next.length === selected.length ? null : { selected: next };
36363
+ }
36364
+ function classifyPreCommitError(mintUrl, err) {
36365
+ if (err instanceof DvmError && err.code === "lnurl_amount_out_of_range") {
36366
+ return {
36367
+ kind: "skipped",
36368
+ mint: mintUrl,
36369
+ reason: "amount_out_of_range",
36370
+ message: err.message
36371
+ };
36372
+ }
36373
+ return { kind: "failed", mint: mintUrl, message: errorMessage2(err), settlement: "reverted" };
36374
+ }
36375
+ function sumSats2(proofs) {
36376
+ return proofs.reduce((sum, p) => sum + p.amount, 0);
36377
+ }
36378
+ function errorMessage2(err) {
36379
+ return err instanceof Error ? err.message : String(err);
36380
+ }
36381
+
36382
+ // src/lib/wallet-agent/cash-out.ts
36383
+ async function cashOutFromMint(opts) {
36384
+ const mintUrl = opts.mintUrl;
36385
+ const now = opts.now ?? (() => Date.now());
36386
+ const getWalletForMint = opts.getWalletForMint ?? getWallet;
36387
+ const initial = loadAgentWallet();
36388
+ if (!initial) {
36389
+ throw new DvmError(
36390
+ "wallet_missing",
36391
+ "No agent wallet found.",
36392
+ "Run `dvm wallet init` first to generate a lock keypair."
36393
+ );
36394
+ }
36395
+ if (opts.bolt11) assertInvoiceNotPending(initial, opts.bolt11);
36396
+ const candidates = spendableAt(initial.proofs, mintUrl);
36397
+ if (candidates.length === 0) {
36398
+ return {
36399
+ kind: "skipped",
36400
+ mint: mintUrl,
36401
+ reason: "no_balance",
36402
+ message: `No spendable proofs at ${mintUrl}.`
36403
+ };
36404
+ }
36405
+ let cashuWallet;
36406
+ try {
36407
+ cashuWallet = await getWalletForMint(mintUrl);
36408
+ } catch (err) {
36409
+ return { kind: "failed", mint: mintUrl, message: errorMessage3(err), settlement: "reverted" };
36410
+ }
36411
+ const prepared = await prepareCashOut(opts, candidates, cashuWallet);
36412
+ if ("kind" in prepared) return prepared;
36413
+ const { invoice, quote: quote2, selected, selectedTotal, inputFees, cappedByMintMax } = prepared;
36218
36414
  const quoteView = {
36219
36415
  mint: mintUrl,
36220
36416
  quote_id: quote2.rawQuote.quote,
@@ -36230,7 +36426,7 @@ async function cashOutFromMint(opts) {
36230
36426
  kind: "skipped",
36231
36427
  mint: mintUrl,
36232
36428
  reason: "fee_cap_exceeded",
36233
- message: `Fees at ${mintUrl} would be up to ${totalFees} sats, over the ${opts.maxFeeSats} sat cap.`,
36429
+ message: `Fees at ${mintUrl} would be up to ${totalFees} sats, over the ${opts.maxFeeSats} sat cap.${opts.bolt11 ? " No money moved. Run `dvm wallet cash-out <invoice> --max-fee <sats>` with a sufficient cap if you accept these fees." : ""}`,
36234
36430
  quote: quoteView
36235
36431
  };
36236
36432
  }
@@ -36250,7 +36446,7 @@ async function cashOutFromMint(opts) {
36250
36446
  return {
36251
36447
  kind: "failed",
36252
36448
  mint: mintUrl,
36253
- message: errorMessage2(err),
36449
+ message: errorMessage3(err),
36254
36450
  settlement: "reverted",
36255
36451
  quote: quoteView
36256
36452
  };
@@ -36276,6 +36472,10 @@ async function cashOutFromMint(opts) {
36276
36472
  const committed = await withWalletLock(() => {
36277
36473
  const fresh = loadAgentWallet();
36278
36474
  if (!fresh) return false;
36475
+ if (opts.bolt11) {
36476
+ assertInvoiceNotPending(fresh, opts.bolt11);
36477
+ invoiceAmountSats(opts.bolt11, now());
36478
+ }
36279
36479
  const swept = sweepStaleInFlight(fresh, now());
36280
36480
  const available = new Set(spendableAt(swept.wallet.proofs, mintUrl).map((p) => proofKey(p)));
36281
36481
  if (![...selectedKeys].every((k) => available.has(k))) {
@@ -36319,20 +36519,10 @@ async function cashOutFromMint(opts) {
36319
36519
  mint: mintUrl,
36320
36520
  quote: quoteView,
36321
36521
  preimage,
36322
- change_sats: sumSats2(changeProofs),
36522
+ change_sats: sumSats3(changeProofs),
36323
36523
  ...cappedByMintMax !== void 0 ? { mint_max_sats: cappedByMintMax } : {}
36324
36524
  };
36325
36525
  }
36326
- function meltBoundsOf(wallet) {
36327
- const reader = wallet;
36328
- try {
36329
- const nuts = reader.getMintInfo?.().cache?.nuts;
36330
- if (nuts === void 0 || nuts === null) return { minSats: null, maxSats: null };
36331
- return meltAmountBounds(nuts);
36332
- } catch {
36333
- return { minSats: null, maxSats: null };
36334
- }
36335
- }
36336
36526
  function spendableAt(proofs, mintUrl) {
36337
36527
  return proofs.filter((p) => p.mint === mintUrl && p.status === "valid" && p.reserved_for === void 0).slice().sort((a, b) => b.amount - a.amount);
36338
36528
  }
@@ -36348,7 +36538,7 @@ async function resolveFailedMelt(cashuWallet, mintUrl, entry, selectedKeys, quot
36348
36538
  return {
36349
36539
  kind: "failed",
36350
36540
  mint: mintUrl,
36351
- message: `${errorMessage2(err)} \u2014 ${entry.amount_sats} sats may still be in flight at ${mintUrl}. Run \`dvm wallet show\` to reconcile before retrying.`,
36541
+ message: `${errorMessage3(err)} \u2014 ${entry.amount_sats} sats may still be in flight at ${mintUrl}. Run \`dvm wallet show\` to reconcile before retrying.`,
36352
36542
  settlement: "unresolved",
36353
36543
  quote: quoteView
36354
36544
  };
@@ -36365,63 +36555,37 @@ async function resolveFailedMelt(cashuWallet, mintUrl, entry, selectedKeys, quot
36365
36555
  return {
36366
36556
  kind: "failed",
36367
36557
  mint: mintUrl,
36368
- message: `${errorMessage2(err)} \u2014 the mint confirms the invoice is unpaid, so the ${quoteView.debit_sats} sats are back in the wallet.`,
36558
+ message: `${errorMessage3(err)} \u2014 the mint confirms the invoice is unpaid, so the ${quoteView.debit_sats} sats are back in the wallet.`,
36369
36559
  settlement: "reverted",
36370
36560
  quote: quoteView
36371
36561
  };
36372
36562
  }
36373
- function selectInputs(candidates, target) {
36374
- if (target.kind === "all") return [...candidates];
36375
- const selected = [];
36376
- let total = 0;
36377
- for (const p of candidates) {
36378
- selected.push(p);
36379
- total += p.amount;
36380
- if (total >= target.sats) return selected;
36381
- }
36382
- return selected;
36383
- }
36384
- function widenSelection(candidates, selected, needed, currentInputFees) {
36385
- const chosen = new Set(selected.map((p) => proofKey(p)));
36386
- const rest = candidates.filter((p) => !chosen.has(proofKey(p)));
36387
- if (rest.length === 0) return null;
36388
- const next = [...selected];
36389
- let total = sumSats2(next);
36390
- for (const p of rest) {
36391
- if (total >= needed + currentInputFees) break;
36392
- next.push(p);
36393
- total += p.amount;
36394
- }
36395
- return next.length === selected.length ? null : { selected: next };
36396
- }
36397
- function classifyPreCommitError(mintUrl, err) {
36398
- if (err instanceof DvmError && err.code === "lnurl_amount_out_of_range") {
36399
- return {
36400
- kind: "skipped",
36401
- mint: mintUrl,
36402
- reason: "amount_out_of_range",
36403
- message: err.message
36404
- };
36405
- }
36406
- return { kind: "failed", mint: mintUrl, message: errorMessage2(err), settlement: "reverted" };
36407
- }
36408
- function sumSats2(proofs) {
36563
+ function sumSats3(proofs) {
36409
36564
  return proofs.reduce((sum, p) => sum + p.amount, 0);
36410
36565
  }
36411
- function errorMessage2(err) {
36566
+ function errorMessage3(err) {
36412
36567
  return err instanceof Error ? err.message : String(err);
36413
36568
  }
36414
36569
 
36415
36570
  // src/commands/wallet-cash-out.ts
36416
36571
  async function walletCashOut(destination, opts) {
36417
36572
  const human = opts.human ?? false;
36418
- if (opts.amount === void 0 === (opts.all !== true)) {
36573
+ const bolt11 = invoiceDestination(destination);
36574
+ if (bolt11 && (opts.amount !== void 0 || opts.all === true || opts.sats === true)) {
36575
+ throw new DvmError(
36576
+ "invalid_flags",
36577
+ "The invoice fixes the amount; --amount, --all, and --sats cannot be used with it. No money moved.",
36578
+ "Run `dvm wallet cash-out <invoice>` without --amount, --all, or --sats."
36579
+ );
36580
+ }
36581
+ if (!bolt11 && opts.amount === void 0 === (opts.all !== true)) {
36419
36582
  throw new DvmError(
36420
36583
  "invalid_flags",
36421
36584
  "Pass exactly one of --amount <amount> or --all.",
36422
36585
  "`--amount 1000` sends 1000 sats and draws the fees on top; `--all` empties the wallet, with fees coming out of the balance."
36423
36586
  );
36424
36587
  }
36588
+ const invoiceSats = bolt11 ? invoiceAmountSats(bolt11) : void 0;
36425
36589
  await loadConfiguredMints();
36426
36590
  const wallet = loadAgentWallet();
36427
36591
  if (!wallet) {
@@ -36434,9 +36598,10 @@ async function walletCashOut(destination, opts) {
36434
36598
  await sweepPendingMints().catch(() => void 0);
36435
36599
  await sweepPendingMelts().catch(() => void 0);
36436
36600
  const fresh = loadAgentWallet() ?? wallet;
36601
+ if (bolt11) assertInvoiceNotPending(fresh, bolt11);
36437
36602
  const requested = opts.amount ? await resolveFundingAmountSats(opts.amount, opts.sats) : null;
36438
36603
  const maxFeeSats = parseMaxFee(opts.maxFee);
36439
- await validateLnAddress(destination);
36604
+ if (!bolt11) await validateLnAddress(destination);
36440
36605
  const mints = resolveMints(fresh, opts.mint);
36441
36606
  if (mints.length === 0) {
36442
36607
  throw new DvmError(
@@ -36446,9 +36611,9 @@ async function walletCashOut(destination, opts) {
36446
36611
  );
36447
36612
  }
36448
36613
  if (human) {
36449
- const what = requested ? describeAmount(requested) : "everything";
36614
+ const what = bolt11 ? "the invoice amount" : requested ? describeAmount(requested) : "everything";
36450
36615
  info(
36451
- `Cashing out ${what} to ${destination} across ${mints.length} mint(s)${opts.dryRun ? " (dry run \u2014 nothing will be paid)" : ""}\u2026`
36616
+ `Cashing out ${what} to ${destination}${bolt11 ? " from one mint" : ` across ${mints.length} mint(s)`}${opts.dryRun ? " (dry run \u2014 nothing will be paid)" : ""}\u2026`
36452
36617
  );
36453
36618
  }
36454
36619
  const outcomes = [];
@@ -36459,6 +36624,7 @@ async function walletCashOut(destination, opts) {
36459
36624
  mintUrl,
36460
36625
  target: requested ? { kind: "exact", sats: remaining } : { kind: "all" },
36461
36626
  destination,
36627
+ bolt11,
36462
36628
  maxFeeSats,
36463
36629
  dryRun: opts.dryRun,
36464
36630
  onQuote: (quote2) => {
@@ -36466,6 +36632,7 @@ async function walletCashOut(destination, opts) {
36466
36632
  }
36467
36633
  });
36468
36634
  outcomes.push(outcome);
36635
+ if (bolt11 && (outcome.kind !== "skipped" && !(outcome.kind === "failed" && !outcome.quote))) break;
36469
36636
  if (requested && (outcome.kind === "sent" || outcome.kind === "quoted")) {
36470
36637
  remaining -= outcome.quote.amount_sats;
36471
36638
  }
@@ -36485,7 +36652,7 @@ async function walletCashOut(destination, opts) {
36485
36652
  const moreToSend = opts.all === true || shortfall > 0;
36486
36653
  const rows = outcomes.map((o) => toRow(o, moreToSend));
36487
36654
  const status2 = opts.dryRun ? "quoted" : sentSats > 0 ? "cashed_out" : "nothing_sent";
36488
- const display = opts.dryRun ? `Quoted ${quotedSats} sats to ${destination} across ${rows.length} mint(s). Nothing was paid.` : sentSats > 0 ? `Sent ${sentSats} sats to ${destination}${feeSats > 0 ? `, plus ${feeSats} sats in fees` : ""}${shortfall > 0 ? ` \u2014 ${shortfall} sats short of what you asked for` : ""}.` : `Nothing was sent to ${destination}.`;
36655
+ const display = opts.dryRun ? `Quoted ${quotedSats} sats to ${destination}${bolt11 ? " from one mint" : ` across ${rows.length} mint(s)`}. Nothing was paid.` : sentSats > 0 ? `Sent ${sentSats} sats to ${destination}${feeSats > 0 ? `, plus ${feeSats} sats in fees` : ""}${shortfall > 0 ? ` \u2014 ${shortfall} sats short of what you asked for` : ""}.` : `Nothing was sent to ${destination}.`;
36489
36656
  const cappedCount = moreToSend ? rows.filter((r) => r.mint_max_sats !== void 0).length : 0;
36490
36657
  const hint = buildHint({
36491
36658
  unresolvedCount: unresolved.length,
@@ -36506,7 +36673,7 @@ async function walletCashOut(destination, opts) {
36506
36673
  status: status2,
36507
36674
  destination,
36508
36675
  ...requested ? amountSourceFields(requested) : { source_currency: "sats" },
36509
- requested_sats: requested?.sats ?? null,
36676
+ requested_sats: requested?.sats ?? invoiceSats ?? null,
36510
36677
  sats_sent: sentSats,
36511
36678
  fee_sats: feeSats,
36512
36679
  change_sats: changeSats,
@@ -36519,7 +36686,7 @@ async function walletCashOut(destination, opts) {
36519
36686
  if (!opts.dryRun && sentSats === 0) {
36520
36687
  throw new DvmError(
36521
36688
  "cash_out_failed",
36522
- `No mint could pay ${destination}.`,
36689
+ bolt11 && outcomes.every((o) => o.kind === "skipped" && o.reason === "fees_exceed_balance") ? "No single mint could cover this invoice and its fees. No money moved; invoice payments cannot be split across mints." : bolt11 && unresolved.length === 0 ? outcomes.map((o) => "message" in o ? o.message : "").filter(Boolean).join(" ") : `No mint could pay ${destination}.`,
36523
36690
  unresolved.length > 0 ? "At least one melt's outcome is unknown \u2014 run `dvm wallet show` to reconcile it against the mint before retrying." : "See the per-mint reasons above. `dvm wallet mint-health` reports whether a mint is currently able to melt."
36524
36691
  );
36525
36692
  }
@@ -36611,7 +36778,7 @@ function resolveMints(wallet, explicit) {
36611
36778
  return spendableAt(wallet.proofs, explicit).length > 0 ? [explicit] : [];
36612
36779
  }
36613
36780
  const candidates = /* @__PURE__ */ new Set([...effectiveMints(wallet), ...wallet.proofs.map((p) => p.mint)]);
36614
- return [...candidates].map((url2) => ({ url: url2, sats: sumSats3(spendableAt(wallet.proofs, url2)) })).filter((m) => m.sats > 0).sort((a, b) => b.sats - a.sats || a.url.localeCompare(b.url)).map((m) => m.url);
36781
+ return [...candidates].map((url2) => ({ url: url2, sats: sumSats4(spendableAt(wallet.proofs, url2)) })).filter((m) => m.sats > 0).sort((a, b) => b.sats - a.sats || a.url.localeCompare(b.url)).map((m) => m.url);
36615
36782
  }
36616
36783
  function buildHint(args) {
36617
36784
  if (args.unresolvedCount > 0) {
@@ -36640,7 +36807,7 @@ function parseMaxFee(raw2) {
36640
36807
  }
36641
36808
  return Math.floor(n);
36642
36809
  }
36643
- function sumSats3(proofs) {
36810
+ function sumSats4(proofs) {
36644
36811
  return proofs.reduce((sum, p) => sum + p.amount, 0);
36645
36812
  }
36646
36813
 
@@ -38824,7 +38991,7 @@ async function walletX402Connect(keyArg, opts) {
38824
38991
  qrImagePath: opts.qrImage
38825
38992
  });
38826
38993
  return {
38827
- connected: { ...await saveX402Wallet(privateKey, network), generated: true },
38994
+ connected: { ...await saveX402Wallet(privateKey, network, true), generated: true },
38828
38995
  handoff: handoff2
38829
38996
  };
38830
38997
  });
@@ -40031,16 +40198,16 @@ Docs:
40031
40198
  ).option("--human", "Human-readable output instead of JSON").action((amount, opts) => {
40032
40199
  return catchErrors(() => walletFund(amount, opts), opts.human);
40033
40200
  });
40034
- wallet.command("cash-out <ln-address>").description(
40035
- "Move value out of the agent wallet to a Lightning address (or lnurl1\u2026 string). Fees are drawn from the wallet on top of --amount, so the stated amount is what arrives"
40201
+ wallet.command("cash-out <destination>").description(
40202
+ "Move value out of the agent wallet to a Lightning address, lnurl1\u2026 string, or BOLT11 invoice (optionally lightning:). An invoice fixes the amount; otherwise pass --amount or --all. Fees are drawn on top of --amount"
40036
40203
  ).option(
40037
40204
  "--amount <amount>",
40038
40205
  "How much should arrive. Accepts sats (1000), USD ($5), GBP (\xA35 / 5gbp), EUR (\u20AC5 / 5eur), or JPY"
40039
40206
  ).option(
40040
40207
  "--sats",
40041
40208
  "Treat numeric input as sats (default: fiat if a currency symbol/code is present \u2014 $5, \xA35, 5eur \u2014 else sats)"
40042
- ).option("--all", "Empty the wallet (or the --mint mint) \u2014 fees come out of the balance").option("--mint <url>", "Cash out from this mint only (default: every mint, richest first)").option("--max-fee <sats>", "Refuse a mint whose routing reserve + input fee exceeds this").option("--dry-run", "Quote the melt and report the fee without paying anything").option("--human", "Human-readable output instead of JSON").action((lnAddress, opts) => {
40043
- return catchErrors(() => walletCashOut(lnAddress, opts), opts.human);
40209
+ ).option("--all", "Empty the wallet (or the --mint mint) \u2014 fees come out of the balance").option("--mint <url>", "Cash out from this mint only (default: every mint, richest first)").option("--max-fee <sats>", "Refuse a mint whose routing reserve + input fee exceeds this").option("--dry-run", "Quote the melt and report the fee without paying anything").option("--human", "Human-readable output instead of JSON").action((destination, opts) => {
40210
+ return catchErrors(() => walletCashOut(destination, opts), opts.human);
40044
40211
  });
40045
40212
  wallet.command("receive-token <token>").description("Claim an external Cashu token into the agent wallet as spendable balance").option("--human", "Human-readable output instead of JSON").action((token, opts) => {
40046
40213
  return catchErrors(() => walletReceiveToken(token, opts), opts.human);