@dvmkit/dvm-cli 0.15.2 → 0.16.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 (26) hide show
  1. package/dist/{chunk-I7ZBID4L.js → chunk-2TNH4ME5.js} +2 -2
  2. package/dist/{chunk-HXTASGHL.js → chunk-A2B7QDMS.js} +2 -2
  3. package/dist/{chunk-EZL4IVCU.js → chunk-CEBEPXQ7.js} +3 -3
  4. package/dist/{chunk-57PXJ56K.js → chunk-DGA5EFKU.js} +354 -186
  5. package/dist/{chunk-UWVMG4VG.js → chunk-H6WQ4S6K.js} +3 -3
  6. package/dist/{chunk-D5CGDS3V.js → chunk-IK7RI645.js} +2 -2
  7. package/dist/{chunk-ECJO73RZ.js → chunk-LDYMUQZE.js} +2795 -2549
  8. package/dist/{chunk-5SHB3MZ7.js → chunk-NSA2RJ2T.js} +37 -7
  9. package/dist/{chunk-YQJRKWNT.js → chunk-U2PODYIS.js} +24487 -22833
  10. package/dist/{chunk-UCCT5IKU.js → chunk-UFMAHF6T.js} +63 -1
  11. package/dist/{chunk-2MCZ4QOK.js → chunk-WRIXUSMR.js} +2 -2
  12. package/dist/{chunk-HJ2JYBTT.js → chunk-WSLZBJ52.js} +4 -4
  13. package/dist/{client-YIHI4AIC.js → client-S5PTHG25.js} +6 -6
  14. package/dist/dvm.js +483 -197
  15. package/dist/{internal-O7IQD6EQ.js → internal-3SIUYRWP.js} +5 -5
  16. package/dist/{lifecycle-MIJH3JE4.js → lifecycle-7NHL5ATK.js} +6 -6
  17. package/dist/{payout-reporter-Y6OW3FYD-K6MRWQXK.js → payout-reporter-F5LFV5W4-EJ7E5ALO.js} +2 -2
  18. package/dist/{pocket-refill-XZTMPTP6.js → pocket-refill-3CA4PFXG.js} +10 -10
  19. package/dist/{revenue-reporter-CIG2MEDN-ZXMO6NWG.js → revenue-reporter-2U55YH2I-EUB6PBRN.js} +2 -2
  20. package/dist/{tempo-lifecycle-FMBCHD2M.js → tempo-lifecycle-GAM3DJ63.js} +8 -8
  21. package/dist/{tempo-wallet-U3WBWIIH.js → tempo-wallet-JTARPYLN.js} +7 -7
  22. package/dist/{wallet-Z3FDX43V.js → wallet-QKAKRLPI.js} +7 -7
  23. package/dist/{x402-ARXZQ5BD-H6PNJYYT.js → x402-G6C4N2BN-TAJEBQGU.js} +2 -2
  24. package/package.json +2 -2
  25. package/skills/dvm/calling.md +1 -1
  26. package/skills/dvm/wallets.md +9 -1
package/dist/dvm.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-EZL4IVCU.js";
8
+ } from "./chunk-CEBEPXQ7.js";
9
9
  import {
10
10
  CARD_MIN_MICRO,
11
11
  DEFAULT_CREDIT_POSTURE,
@@ -43,6 +43,7 @@ import {
43
43
  computeNextAction,
44
44
  correctPendingFundAmount,
45
45
  createMessageAppendSession,
46
+ createPendingMintQuote,
46
47
  declinedAskSeqs,
47
48
  deriveAlias,
48
49
  describeMintBounds,
@@ -67,6 +68,7 @@ import {
67
68
  fundCredit,
68
69
  fundTimeoutMs,
69
70
  guidanceJobArg,
71
+ hasPendingAcceptedJobAccess,
70
72
  hasUnknownUpfrontCredit,
71
73
  hasUnknownUpfrontRail,
72
74
  heldCashuSubmissionAsks,
@@ -83,6 +85,7 @@ import {
83
85
  jobDrawFundings,
84
86
  jobIdentityHeaderValue,
85
87
  jobSettlement,
88
+ journalFile,
86
89
  journalMarkerFor,
87
90
  listPendingCardFundings,
88
91
  listSubmissionEvidence,
@@ -166,6 +169,7 @@ import {
166
169
  revertInFlight,
167
170
  routerConflictObservation,
168
171
  sameEndpoint,
172
+ saveAcceptedJob,
169
173
  saveFavorite,
170
174
  saveJob,
171
175
  saveLedger,
@@ -188,19 +192,21 @@ import {
188
192
  unrecordedFloatBudgetWarning,
189
193
  unresendablePaymentHint,
190
194
  updateJob,
195
+ updateObservedJob,
191
196
  walletHistory,
197
+ walletInvoiceFundingAdvice,
192
198
  warnInvalidJobIdentityHeader,
193
199
  withAcceptedUnresolved,
194
200
  withIdentityRecovery,
195
201
  withJobTokenRedaction,
196
202
  withRequestResultRecovery
197
- } from "./chunk-ECJO73RZ.js";
203
+ } from "./chunk-LDYMUQZE.js";
198
204
  import {
199
205
  connectedTempoAccount,
200
206
  generateTempoKey,
201
207
  tempoBalanceCheckHint,
202
208
  tempoWrongAssetHint
203
- } from "./chunk-HJ2JYBTT.js";
209
+ } from "./chunk-WSLZBJ52.js";
204
210
  import {
205
211
  addOutputWarnings,
206
212
  assertValidBudget,
@@ -209,6 +215,7 @@ import {
209
215
  formatAmountBestEffort,
210
216
  formatPaymentAmount,
211
217
  getOutputTraceId,
218
+ hasUnsavedJobState,
212
219
  info,
213
220
  json,
214
221
  monetaryJson,
@@ -220,7 +227,7 @@ import {
220
227
  tryResolveBtcUsdRate,
221
228
  tryX402Payment,
222
229
  withOutputWarnings
223
- } from "./chunk-5SHB3MZ7.js";
230
+ } from "./chunk-NSA2RJ2T.js";
224
231
  import {
225
232
  assertSupportedX402Network,
226
233
  connectedX402Payer,
@@ -229,7 +236,7 @@ import {
229
236
  repinX402WalletNetwork,
230
237
  saveX402Wallet,
231
238
  x402NetworkLabel
232
- } from "./chunk-UWVMG4VG.js";
239
+ } from "./chunk-H6WQ4S6K.js";
233
240
  import {
234
241
  CREDIT_POSTURES,
235
242
  FEEDBACK_POSTURES,
@@ -246,10 +253,10 @@ import {
246
253
  retireConfigBackup,
247
254
  rollbackConfig,
248
255
  updateConfig
249
- } from "./chunk-2MCZ4QOK.js";
256
+ } from "./chunk-WRIXUSMR.js";
250
257
  import {
251
258
  assertX402WalletIdle
252
- } from "./chunk-I7ZBID4L.js";
259
+ } from "./chunk-2TNH4ME5.js";
253
260
  import {
254
261
  A,
255
262
  AGENT_MNEMONIC_FILE,
@@ -488,7 +495,7 @@ import {
488
495
  x402PendingUnsettled,
489
496
  x402RequiredFromError,
490
497
  x402ReservationRelease
491
- } from "./chunk-YQJRKWNT.js";
498
+ } from "./chunk-U2PODYIS.js";
492
499
  import "./chunk-JBU7RKQ3.js";
493
500
  import "./chunk-KDNFUDOG.js";
494
501
  import "./chunk-IUTVV6N5.js";
@@ -774,11 +781,11 @@ import {
774
781
  usdToMsats,
775
782
  usdcToMsats,
776
783
  x402NetworkByCaip2
777
- } from "./chunk-57PXJ56K.js";
778
- import "./chunk-HXTASGHL.js";
779
- import "./chunk-D5CGDS3V.js";
784
+ } from "./chunk-DGA5EFKU.js";
785
+ import "./chunk-A2B7QDMS.js";
786
+ import "./chunk-IK7RI645.js";
780
787
  import "./chunk-R2DSAZBO.js";
781
- import "./chunk-UCCT5IKU.js";
788
+ import "./chunk-UFMAHF6T.js";
782
789
  import {
783
790
  privateKeyToAccount
784
791
  } from "./chunk-EVQERRCP.js";
@@ -11179,9 +11186,9 @@ function configuredTempoNetwork() {
11179
11186
  if (tempo?.method !== "tempo") return null;
11180
11187
  return parseTempoNetwork(tempo.network, "config.tempo.network") ?? "mainnet";
11181
11188
  }
11182
- function assertTempoChallengeNetwork(challenges, network, intents) {
11189
+ function assertTempoChallengeNetwork(challenges, network, intents2) {
11183
11190
  const expected = resolveTempoNetwork(network);
11184
- const acceptedIntents = intents ? new Set(intents) : null;
11191
+ const acceptedIntents = intents2 ? new Set(intents2) : null;
11185
11192
  for (const challenge of challenges) {
11186
11193
  if (challenge.method !== "tempo" || acceptedIntents && !acceptedIntents.has(challenge.intent))
11187
11194
  continue;
@@ -11201,9 +11208,9 @@ function assertTempoChallengeNetwork(challenges, network, intents) {
11201
11208
  );
11202
11209
  }
11203
11210
  }
11204
- function assertConfiguredTempoChallengeNetwork(challenges, intents) {
11211
+ function assertConfiguredTempoChallengeNetwork(challenges, intents2) {
11205
11212
  const network = configuredTempoNetwork();
11206
- if (network) assertTempoChallengeNetwork(challenges, network, intents);
11213
+ if (network) assertTempoChallengeNetwork(challenges, network, intents2);
11207
11214
  }
11208
11215
  function assertTempoChannelNetwork(association, account) {
11209
11216
  const network = tempoAccountNetwork(account);
@@ -11440,6 +11447,11 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11440
11447
  });
11441
11448
  }
11442
11449
  async function handleLockedPaymentRequest(jobId, request2, policy, transport, provider, opts) {
11450
+ if (hasPendingAcceptedJobAccess(jobId, provider.endpoint)) throw new DvmError(
11451
+ "local_job_state_unsaved",
11452
+ "Private recovery state must be folded before another payment can be sent.",
11453
+ "Run dvm status <job_id> --messages before paying; unresolved recovery records remain preserved."
11454
+ );
11443
11455
  const approval = opts?.requestSeq === void 0 ? void 0 : {
11444
11456
  requestSeq: opts.requestSeq,
11445
11457
  approval: opts.approval ?? "auto"
@@ -11601,8 +11613,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11601
11613
  }
11602
11614
  }
11603
11615
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11604
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
11605
- const { tryX402Payment: tryX402Payment2 } = await import("./client-YIHI4AIC.js");
11616
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-QKAKRLPI.js");
11617
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-S5PTHG25.js");
11606
11618
  const wallet = loadX402Wallet2();
11607
11619
  if (wallet) {
11608
11620
  let proof;
@@ -12049,7 +12061,7 @@ async function claimInboundPayments(jobId, messages2) {
12049
12061
  if (claimedMsats > 0) {
12050
12062
  claimedSeqs.add(msg.seq);
12051
12063
  claimedAmounts[msg.seq] = claimedMsats;
12052
- updateJob(jobId, { claimedPaymentSeqs: [...claimedSeqs], claimedPaymentAmountsMsats: claimedAmounts });
12064
+ updateObservedJob(jobId, { claimedPaymentSeqs: [...claimedSeqs], claimedPaymentAmountsMsats: claimedAmounts });
12053
12065
  results.push({
12054
12066
  seq: msg.seq,
12055
12067
  amount_msats: claimedMsats,
@@ -12133,6 +12145,13 @@ function withRefundNextAction(jobId, action, claims) {
12133
12145
  // src/lib/stream-loop.ts
12134
12146
  async function streamLoop(opts) {
12135
12147
  const { jobId, transport, provider } = opts;
12148
+ if (hasUnsavedJobState()) return {
12149
+ messages: [],
12150
+ autoPayments: [],
12151
+ refunds: [],
12152
+ cursor: opts.afterSeq,
12153
+ nextAction: pollNextAction(jobId, "Local state may lag; refresh this job before another payment.")
12154
+ };
12136
12155
  const persistLocalState = opts.persistLocalState !== false;
12137
12156
  const policy = persistLocalState ? opts.policy : void 0;
12138
12157
  const allMessages = [];
@@ -12196,7 +12215,7 @@ async function streamLoop(opts) {
12196
12215
  }
12197
12216
  try {
12198
12217
  for (; ; ) {
12199
- if (deadline !== void 0 && Date.now() >= deadline) break;
12218
+ if (hasUnsavedJobState() || deadline !== void 0 && Date.now() >= deadline) break;
12200
12219
  const streamFn = transport.stream?.bind(transport);
12201
12220
  let batchMessages;
12202
12221
  if (streamFn) {
@@ -12235,9 +12254,11 @@ async function streamLoop(opts) {
12235
12254
  messageAppendSession ??= createMessageAppendSession(jobId);
12236
12255
  messageAppendSession.append(batchMessages);
12237
12256
  await settleRecordedPayments(jobId);
12257
+ if (hasUnsavedJobState()) break;
12238
12258
  }
12239
12259
  if (persistLocalState) {
12240
12260
  refunds.push(...await claimInboundPayments(jobId, batchMessages));
12261
+ if (hasUnsavedJobState()) break;
12241
12262
  }
12242
12263
  justAutoPaid = false;
12243
12264
  if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
@@ -12314,7 +12335,7 @@ async function streamLoop(opts) {
12314
12335
  } finally {
12315
12336
  if (timer) clearTimeout(timer);
12316
12337
  }
12317
- if (justAutoPaid) {
12338
+ if (justAutoPaid && !hasUnsavedJobState()) {
12318
12339
  const pollOptions = nextPollOptions();
12319
12340
  let recheck = [];
12320
12341
  try {
@@ -12359,6 +12380,8 @@ async function streamLoop(opts) {
12359
12380
  heldJob,
12360
12381
  lastYield?.type === "payment-request" ? lastYield.seq : void 0
12361
12382
  ));
12383
+ if (hasUnsavedJobState() && !terminal)
12384
+ nextAction = pollNextAction(jobId, "Local state may lag; refresh this job before another payment.");
12362
12385
  return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
12363
12386
  }
12364
12387
  function isMessagePollTimeout(err) {
@@ -12421,7 +12444,7 @@ function persistStreamOutcome(outcome) {
12421
12444
  });
12422
12445
  return completion;
12423
12446
  }
12424
- updateJob(jobId, { messageCursor: cursor });
12447
+ updateObservedJob(jobId, { messageCursor: cursor });
12425
12448
  return void 0;
12426
12449
  }
12427
12450
  function streamTerminalStatus(messages2, context = {}) {
@@ -14351,6 +14374,7 @@ function creditDrainCommand(handle, creditId) {
14351
14374
  // src/lib/credit-topup.ts
14352
14375
  async function settleCreditAfterJob(args) {
14353
14376
  const deferred = args.deferred ?? takeDeferredFunding();
14377
+ if (hasUnsavedJobState()) return;
14354
14378
  try {
14355
14379
  await settle(args);
14356
14380
  } catch (err) {
@@ -14368,7 +14392,7 @@ async function settleCreditAfterJob(args) {
14368
14392
  }
14369
14393
  }
14370
14394
  if (args.allowTopup !== false) {
14371
- const refill = args.refillPocket ?? (await import("./pocket-refill-XZTMPTP6.js")).refillPocketIfLow;
14395
+ const refill = args.refillPocket ?? (await import("./pocket-refill-3CA4PFXG.js")).refillPocketIfLow;
14372
14396
  await refill({ human: args.human }).catch(() => void 0);
14373
14397
  }
14374
14398
  }
@@ -14775,7 +14799,7 @@ function dvmIdentity(dvmId, capability) {
14775
14799
  // src/commands/cancel.ts
14776
14800
  async function cancel(jobId, opts) {
14777
14801
  const access = resolveJobAccess(jobId, opts);
14778
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => cancelWithAccess(jobId, opts, access)));
14802
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => cancelWithAccess(jobId, opts, access), opts.human));
14779
14803
  }
14780
14804
  async function cancelWithAccess(jobId, opts, access) {
14781
14805
  const { stored, ref, jobToken } = access;
@@ -14851,7 +14875,7 @@ function expectsReceipt(jobId, stored) {
14851
14875
  // src/commands/decline.ts
14852
14876
  async function decline(jobId, opts) {
14853
14877
  const access = resolveJobAccess(jobId, opts);
14854
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => declineWithAccess(jobId, opts, access)));
14878
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => declineWithAccess(jobId, opts, access), opts.human));
14855
14879
  }
14856
14880
  async function declineWithAccess(jobId, opts, access) {
14857
14881
  const { stored, ref, jobToken } = access;
@@ -15143,14 +15167,14 @@ async function confirmRollback(stored, preview, opts) {
15143
15167
  async function withStrandingChecked(removing, commit) {
15144
15168
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
15145
15169
  if (leaving.has("tempo")) {
15146
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-FMBCHD2M.js");
15170
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-GAM3DJ63.js");
15147
15171
  await assertTempoWalletIdle2("disconnect");
15148
15172
  }
15149
15173
  if (!leaving.has("x402")) return commit();
15150
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-O7IQD6EQ.js");
15151
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-MIJH3JE4.js");
15152
- const { ensureAddress: ensureAddress2 } = await import("./internal-O7IQD6EQ.js");
15153
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
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");
15154
15178
  return withX402ChannelLock2(async () => {
15155
15179
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
15156
15180
  if (unsettled.length > 0) {
@@ -18652,6 +18676,10 @@ async function runCreditDrain(dvm, opts) {
18652
18676
  });
18653
18677
  return;
18654
18678
  }
18679
+ if (method === "tempo" && isKnownEmptyTempoCredit(stored, creditId) && !opts.drainId && !pendingDrainFor(stored, creditId) && !tempoSession) {
18680
+ renderAlreadyDrained({ human: opts.human === true, endpoint, creditId });
18681
+ return;
18682
+ }
18655
18683
  const canPersist = !stored || stored.creditId === creditId;
18656
18684
  const named = opts.drainId ? pendingDrainById(stored, opts.drainId) : void 0;
18657
18685
  if (named?.creditId !== void 0 && named.creditId !== creditId) {
@@ -18973,6 +19001,10 @@ async function runCreditDrain(dvm, opts) {
18973
19001
  if (!stored) forgetCredit(endpoint, signer.pubkey, ...identityArg);
18974
19002
  else if (mintedThisRun) clearPendingDrain(endpoint, signer.pubkey, drain, ...identityArg);
18975
19003
  }
19004
+ if (err instanceof DvmError && err.code === "tempo_channel_exit_required" && err.data?.drain_registered === false && isKnownEmptyTempoCredit(stored, creditId)) {
19005
+ renderAlreadyDrained({ human: opts.human === true, endpoint, creditId });
19006
+ return;
19007
+ }
18976
19008
  if (err instanceof DvmError && err.code === "tempo_channel_exit_required") {
18977
19009
  const local2 = tempoExitRequiredCopy(exitRecovery, err.data?.channel_id, err.data?.status);
18978
19010
  const display2 = retirement ? `${local2.display} ${retirement}` : local2.display;
@@ -19429,6 +19461,27 @@ function localDrainCopy(wire, requested, exitRecovery) {
19429
19461
  );
19430
19462
  }
19431
19463
  }
19464
+ function isKnownEmptyTempoCredit(stored, creditId) {
19465
+ return stored?.creditId === creditId && stored.status === "drained" && stored.remainingMicro <= 0 && !stored.provisional && !stored.discrepancy;
19466
+ }
19467
+ function renderAlreadyDrained(args) {
19468
+ const display = "This credit is already drained: its earlier drain was sent, so nothing is owed and no refund is pending.";
19469
+ const hint = "Nothing remains to reclaim, so no further drain or on-chain action is needed. A fresh credit can open when you next need one.";
19470
+ if (args.human) {
19471
+ info(display);
19472
+ info(hint);
19473
+ return;
19474
+ }
19475
+ json({
19476
+ op: "drain",
19477
+ endpoint: args.endpoint,
19478
+ credit_id: args.creditId,
19479
+ already_drained: true,
19480
+ balance_micro: 0,
19481
+ display,
19482
+ hint
19483
+ });
19484
+ }
19432
19485
  function tempoExitRequiredCopy(recovery, channelId, status2) {
19433
19486
  const channel = typeof channelId === "string" ? ` Channel ID: ${channelId}.` : "";
19434
19487
  const pending4 = status2 === "pending";
@@ -19949,7 +20002,8 @@ async function runCreditFund(dvm, opts) {
19949
20002
  menu,
19950
20003
  providerInfo,
19951
20004
  opts,
19952
- config: config2
20005
+ config: config2,
20006
+ rail
19953
20007
  });
19954
20008
  }
19955
20009
  const outcome = await fundCredit({
@@ -19991,6 +20045,7 @@ async function runCreditFund(dvm, opts) {
19991
20045
  adopted ? `${baseHint ? `${baseHint} ` : ""}${adopted.advice}` : baseHint,
19992
20046
  {
19993
20047
  ...err?.data ?? {},
20048
+ ...outcome.walletFundCommand ? { wallet_fund_command: outcome.walletFundCommand } : {},
19994
20049
  display: outcome.display,
19995
20050
  endpoint,
19996
20051
  credit_id: outcome.creditId,
@@ -20329,17 +20384,24 @@ async function enforceTrustTier(args) {
20329
20384
  const capUsd = `$${formatUsd(cap2 / 1e6)}`;
20330
20385
  const held = fundsTracked ? Math.max(args.stored?.remainingMicro ?? 0, 0) : 0;
20331
20386
  const heldClause = held > 0 ? ` On top of the $${formatUsd(held / 1e6)} already on deposit, that would leave $${formatUsd(exposureMicro / 1e6)} here.` : "";
20387
+ const lightningMinimum = args.menu?.lightning_min_micro;
20388
+ const walletFunding = args.rail === "lightning" && lightningMinimum !== void 0 && lightningMinimum > cap2 ? {
20389
+ ...walletInvoiceFundingAdvice(args.amountMicro),
20390
+ minimumUsd: `$${formatUsd(lightningMinimum / 1e6)}`
20391
+ } : void 0;
20392
+ const walletGuidance = walletFunding ? `Lightning top-ups here start at ${walletFunding.minimumUsd}, above the ${capUsd} this caller can load at the current trust tier. ${walletFunding.text} ` : "";
20332
20393
  throw withHeadroom(
20333
20394
  new DvmError(
20334
20395
  "amount_exceeds_trust_tier",
20335
20396
  `Funding ${amountUsd} at ${args.endpoint} would exceed this DVM's ${capUsd} trust-tier cap.`,
20336
- `Nothing moved. Re-run with --over-trust to fund it anyway, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'. Or fund ${capUsd} or less.`,
20397
+ walletFunding ? `No money moved. ${walletGuidance}Re-run with --over-trust to fund credit over Lightning anyway, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'.` : `Nothing moved. Re-run with --over-trust to fund it anyway, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'. Or fund ${capUsd} or less.`,
20337
20398
  {
20338
- display: `This agent has only earned ${capUsd} of credit at ${args.endpoint} so far, and ${amountUsd} was asked for.${heldClause} No money moved. Loading more than the earned amount is allowed, but it has to be asked for explicitly \u2014 re-run with --over-trust, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'.`,
20399
+ display: `This agent has only earned ${capUsd} of credit at ${args.endpoint} so far, and ${amountUsd} was asked for.${heldClause} No money moved. ` + walletGuidance + `Loading more than the earned amount is allowed, but it has to be asked for explicitly \u2014 re-run with --over-trust, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'.`,
20339
20400
  endpoint: args.endpoint,
20340
20401
  amount_micro: args.amountMicro,
20341
20402
  exposure_micro: exposureMicro,
20342
- cap_micro: cap2
20403
+ cap_micro: cap2,
20404
+ ...walletFunding ? { wallet_fund_command: walletFunding.command } : {}
20343
20405
  }
20344
20406
  ),
20345
20407
  headroom
@@ -21819,8 +21881,8 @@ async function probeX402(x402, timeoutMs) {
21819
21881
  let network;
21820
21882
  let address;
21821
21883
  try {
21822
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
21823
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-O7IQD6EQ.js");
21884
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-QKAKRLPI.js");
21885
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-3SIUYRWP.js");
21824
21886
  const wallet = loadX402Wallet2();
21825
21887
  if (!wallet) {
21826
21888
  const storedKey = x402.privateKey;
@@ -21872,8 +21934,8 @@ async function probeMpp(mpp, timeoutMs) {
21872
21934
  if (!mpp) return null;
21873
21935
  if (mpp.method === "tempo") {
21874
21936
  try {
21875
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-U3WBWIIH.js");
21876
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-O7IQD6EQ.js");
21937
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-JTARPYLN.js");
21938
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-3SIUYRWP.js");
21877
21939
  const account = await connectedTempoAccount2();
21878
21940
  if (!account) {
21879
21941
  return {
@@ -25434,7 +25496,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25434
25496
  }
25435
25497
  return void 0;
25436
25498
  }
25437
- while (now() < deadline) {
25499
+ while (now() < deadline && !hasUnsavedJobState()) {
25438
25500
  const readOptions = () => ({ jobToken: opts.jobToken, timeoutMs: Math.max(1, Math.min(idleTimeoutMs, deadline - now())) });
25439
25501
  const snapshot = await readWithRetry(() => opts.transport.status(opts.jobId, opts.provider, readOptions()));
25440
25502
  if (!snapshot) break;
@@ -25528,7 +25590,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25528
25590
  const progressed = next.cursor > result.cursor;
25529
25591
  result.cursor = Math.min(next.cursor, cursorLimit);
25530
25592
  result.nextAction = next.nextAction;
25531
- if (next.nextAction?.type !== "poll") break;
25593
+ if (hasUnsavedJobState() || next.nextAction?.type !== "poll") break;
25532
25594
  if (progressed) backoffMs = 1e3;
25533
25595
  const delay = Math.min(backoffMs, Math.max(0, deadline - now()));
25534
25596
  if (delay > 0) await new Promise((resolve3) => setTimeout(resolve3, delay));
@@ -25548,7 +25610,7 @@ async function messages(jobId, opts) {
25548
25610
  throw new DvmError("invalid_arguments", "Use --until with --wait, and --wait with streaming enabled.");
25549
25611
  }
25550
25612
  const access = resolveJobAccess(jobId, opts);
25551
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => messagesWithAccess(jobId, opts, access)));
25613
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => messagesWithAccess(jobId, opts, access), opts.human));
25552
25614
  }
25553
25615
  async function messagesWithAccess(jobId, opts, access) {
25554
25616
  const waitDuration = opts.wait ? parseDurationMs(opts.until ?? "12h") : void 0;
@@ -25808,7 +25870,7 @@ async function message(jobId, text, opts) {
25808
25870
  const access = resolveJobAccess(jobId, opts);
25809
25871
  return withJobTokenRedaction(
25810
25872
  access.jobToken,
25811
- () => withOutputWarnings(() => messageWithAccess(jobId, text, opts, access))
25873
+ () => withOutputWarnings(() => messageWithAccess(jobId, text, opts, access), opts.human)
25812
25874
  );
25813
25875
  }
25814
25876
  async function messageWithAccess(jobId, text, opts, access) {
@@ -25946,7 +26008,7 @@ function parseForcedRail(raw2) {
25946
26008
  // src/commands/pay.ts
25947
26009
  async function pay(jobId, opts) {
25948
26010
  const access = resolveStoredJobAccess(jobId, opts);
25949
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => payWithAccess(jobId, opts, access)));
26011
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => payWithAccess(jobId, opts, access), opts.human));
25950
26012
  }
25951
26013
  async function payWithAccess(jobId, opts, access) {
25952
26014
  const rail = parseForcedRail(opts.rail);
@@ -26469,7 +26531,7 @@ function isPlainObject2(value) {
26469
26531
 
26470
26532
  // src/commands/quote.ts
26471
26533
  async function quote(opts) {
26472
- return withOutputWarnings(() => quoteWithWarnings(opts));
26534
+ return withOutputWarnings(() => quoteWithWarnings(opts), opts.human);
26473
26535
  }
26474
26536
  async function quoteWithWarnings(opts) {
26475
26537
  if (!opts.dvm && !opts.endpoint) {
@@ -27182,9 +27244,15 @@ function quoteWithinDeclaredLimit(quote2, limitMsats, declaredLimit, rail) {
27182
27244
  }
27183
27245
  function quoteWithinNativeDollarLimit(quote2, declaredLimit, rail) {
27184
27246
  const normalizedRail = rail?.trim().toLowerCase();
27185
- if (normalizedRail === "x402") return x402QuoteWithinDollarLimit(quote2, declaredLimit);
27186
- if (normalizedRail === "tempo") return tempoQuoteWithinDollarLimit(quote2, declaredLimit);
27187
- return void 0;
27247
+ if (normalizedRail === "x402") {
27248
+ const native = x402QuoteWithinDollarLimit(quote2, declaredLimit);
27249
+ if (native !== void 0) return native;
27250
+ }
27251
+ const upfront = upfrontQuoteWithinDollarLimit(quote2, declaredLimit);
27252
+ if (normalizedRail === "tempo" && declaredLimit?.trim().startsWith("$")) {
27253
+ return upfront ?? false;
27254
+ }
27255
+ return upfront;
27188
27256
  }
27189
27257
  function x402QuoteWithinDollarLimit(quote2, declaredLimit) {
27190
27258
  if (!declaredLimit || !quote2.requiredUsdcMicro) return void 0;
@@ -27192,12 +27260,12 @@ function x402QuoteWithinDollarLimit(quote2, declaredLimit) {
27192
27260
  if (limitMicro === void 0 || !/^\d+$/.test(quote2.requiredUsdcMicro)) return void 0;
27193
27261
  return BigInt(quote2.requiredUsdcMicro) <= limitMicro;
27194
27262
  }
27195
- function tempoQuoteWithinDollarLimit(quote2, declaredLimit) {
27263
+ function upfrontQuoteWithinDollarLimit(quote2, declaredLimit) {
27196
27264
  if (!declaredLimit?.trim().startsWith("$")) return void 0;
27197
27265
  const limitMicro = dollarLimitMicro(declaredLimit);
27198
- const amountMicro = quote2.upfront.amount_micro;
27199
- if (limitMicro === void 0 || quote2.upfront.currency !== "usd" || amountMicro === void 0 || !Number.isSafeInteger(amountMicro) || amountMicro <= 0) {
27200
- return false;
27266
+ const amountMicro = quote2.upfront?.amount_micro;
27267
+ if (limitMicro === void 0 || quote2.upfront?.currency !== "usd" || amountMicro === void 0 || !Number.isSafeInteger(amountMicro) || amountMicro <= 0) {
27268
+ return void 0;
27201
27269
  }
27202
27270
  return BigInt(amountMicro) <= limitMicro;
27203
27271
  }
@@ -27502,7 +27570,7 @@ async function request(opts) {
27502
27570
  } catch (error) {
27503
27571
  throw stage.intentReached ? error : markRefusedBeforeSend(opts.requestId, error);
27504
27572
  }
27505
- });
27573
+ }, opts.human);
27506
27574
  }
27507
27575
  function markRefusedBeforeSend(requestId, error) {
27508
27576
  if (!requestId || !(error instanceof DvmError)) return error;
@@ -28055,7 +28123,7 @@ async function requestWithWarnings(opts, stage) {
28055
28123
  }
28056
28124
  case "awaiting-input":
28057
28125
  case "processing": {
28058
- updateJob(receipt.jobId, {
28126
+ updateObservedJob(receipt.jobId, {
28059
28127
  status: receipt.status === "awaiting-input" ? "awaiting-input" : "processing"
28060
28128
  });
28061
28129
  const result = await streamToCompletion(
@@ -28967,7 +29035,7 @@ async function payWithTempo(args, credential) {
28967
29035
  }
28968
29036
  const effectiveJobId = args.jobId || receipt.jobId;
28969
29037
  if (!args.jobId && receipt.jobId) {
28970
- saveJob({
29038
+ saveAcceptedJob({
28971
29039
  id: effectiveJobId,
28972
29040
  ...transactionRecordFields(receipt),
28973
29041
  endpoint: ref.endpoint,
@@ -29059,7 +29127,7 @@ async function payWithTempo(args, credential) {
29059
29127
  }
29060
29128
  return;
29061
29129
  }
29062
- updateJob(effectiveJobId, {
29130
+ updateObservedJob(effectiveJobId, {
29063
29131
  status: "processing",
29064
29132
  paymentMethod: "tempo"
29065
29133
  });
@@ -29628,7 +29696,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29628
29696
  }
29629
29697
  const effectiveJobId = jobId || receipt.jobId;
29630
29698
  if (!jobId && receipt.jobId) {
29631
- saveJob({
29699
+ saveAcceptedJob({
29632
29700
  id: effectiveJobId,
29633
29701
  ...transactionRecordFields(receipt),
29634
29702
  endpoint: ref.endpoint,
@@ -29660,7 +29728,9 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29660
29728
  ...localCorrelationJobFields(normalizedLocalCorrelationId(opts))
29661
29729
  });
29662
29730
  }
29663
- await commitAgentSpend({
29731
+ await collectCashuChange(effectiveJobId, receipt.cashuChange);
29732
+ recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
29733
+ if (!hasUnsavedJobState()) await commitAgentSpend({
29664
29734
  requestId: prepared.requestId,
29665
29735
  recentSpend: {
29666
29736
  request_id: prepared.requestId,
@@ -29670,9 +29740,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29670
29740
  signed_at_ms: Date.now()
29671
29741
  }
29672
29742
  });
29673
- await collectCashuChange(effectiveJobId, receipt.cashuChange);
29674
- recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
29675
- if (fundPlan) {
29743
+ if (!hasUnsavedJobState() && fundPlan) {
29676
29744
  recordSpend({
29677
29745
  msats: fundPlan.fundMsats,
29678
29746
  btcRate,
@@ -29681,7 +29749,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29681
29749
  providerEndpoint: ref.endpoint,
29682
29750
  label: `credit fund \xB7 ${identity.dvmId ?? identity.capability}`
29683
29751
  });
29684
- } else {
29752
+ } else if (!hasUnsavedJobState()) {
29685
29753
  recordSpend({
29686
29754
  msats: chosen.priceMsats,
29687
29755
  btcRate,
@@ -29740,7 +29808,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29740
29808
  }
29741
29809
  return;
29742
29810
  }
29743
- updateJob(effectiveJobId, {
29811
+ updateObservedJob(effectiveJobId, {
29744
29812
  status: "processing",
29745
29813
  paymentMethod: "cashu"
29746
29814
  });
@@ -29858,7 +29926,7 @@ async function payWithX402(args, proof) {
29858
29926
  }
29859
29927
  const effectiveJobId = args.jobId || receipt.jobId;
29860
29928
  if (!args.jobId && receipt.jobId) {
29861
- saveJob({
29929
+ saveAcceptedJob({
29862
29930
  id: effectiveJobId,
29863
29931
  ...transactionRecordFields(receipt),
29864
29932
  endpoint: ref.endpoint,
@@ -29939,7 +30007,7 @@ async function payWithX402(args, proof) {
29939
30007
  }
29940
30008
  return;
29941
30009
  }
29942
- updateJob(effectiveJobId, {
30010
+ updateObservedJob(effectiveJobId, {
29943
30011
  status: "processing",
29944
30012
  paymentMethod: "x402"
29945
30013
  });
@@ -29974,7 +30042,7 @@ async function streamToCompletion(baseOpts, deadlineMs) {
29974
30042
  const allMessages = [...result.messages];
29975
30043
  const allAutoPayments = [...result.autoPayments];
29976
30044
  const allRefunds = [...result.refunds];
29977
- while (result.nextAction?.type === "poll") {
30045
+ while (result.nextAction?.type === "poll" && !hasUnsavedJobState()) {
29978
30046
  if (Date.now() >= deadlineMs) break;
29979
30047
  const waitMs = Math.min(
29980
30048
  Math.max((result.nextAction.estimate_seconds ?? 0) * 1e3, MIN_POLL_WAIT_MS),
@@ -30062,7 +30130,7 @@ async function streamAfterPayment(args) {
30062
30130
  });
30063
30131
  }
30064
30132
  transport.close?.();
30065
- if (result.messages.length === 0) {
30133
+ if (result.messages.length === 0 && !hasUnsavedJobState()) {
30066
30134
  const recovered = await recoverViaStatusPoll({
30067
30135
  jobId,
30068
30136
  transport,
@@ -30121,7 +30189,7 @@ async function streamAfterPayment(args) {
30121
30189
  jobId,
30122
30190
  ...dvmFields,
30123
30191
  messages: result.messages.map(serializeMessageForOutput),
30124
- ...streamedTerminal ? { status: streamedTerminal } : {},
30192
+ ...streamedTerminal ? { status: streamedTerminal } : hasUnsavedJobState() ? { status: "processing" } : {},
30125
30193
  ...completion?.message !== void 0 ? { message: completion.message } : {},
30126
30194
  // Same as the unpaid arc above: the outcome is only knowable from the
30127
30195
  // streamed log here, so render it rather than leaving the agent to dig
@@ -30246,7 +30314,7 @@ async function collectCashuChange(jobId, cashuChange) {
30246
30314
  } catch {
30247
30315
  }
30248
30316
  if (sats > 0) {
30249
- updateJob(jobId, { changeProcessed: true });
30317
+ updateObservedJob(jobId, { changeProcessed: true });
30250
30318
  info(`Received ${sats} sats change.`);
30251
30319
  }
30252
30320
  }
@@ -30267,6 +30335,9 @@ async function readStdin() {
30267
30335
 
30268
30336
  // src/commands/request-result.ts
30269
30337
  async function requestResult(requestId, opts = {}) {
30338
+ return withOutputWarnings(() => requestResultWithWarnings(requestId, opts), opts.human);
30339
+ }
30340
+ async function requestResultWithWarnings(requestId, opts) {
30270
30341
  if (!isPublicRequestId(requestId)) {
30271
30342
  throw new DvmError(
30272
30343
  "invalid_request_id",
@@ -30359,9 +30430,9 @@ async function requestResult(requestId, opts = {}) {
30359
30430
  "Do not overwrite the local record."
30360
30431
  );
30361
30432
  }
30362
- updateJob(receipt.jobId, restored);
30433
+ updateObservedJob(receipt.jobId, restored);
30363
30434
  } else {
30364
- saveJob({
30435
+ saveAcceptedJob({
30365
30436
  id: receipt.jobId,
30366
30437
  endpoint: intent.endpoint,
30367
30438
  dvmId: intent.dvmId,
@@ -30389,7 +30460,7 @@ async function requestResult(requestId, opts = {}) {
30389
30460
  if (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled") {
30390
30461
  markJobTerminal(receipt.jobId, receipt.status, completionSnapshot(receipt), restored);
30391
30462
  } else {
30392
- updateJob(receipt.jobId, {
30463
+ updateObservedJob(receipt.jobId, {
30393
30464
  status: receipt.status === "awaiting-input" ? "awaiting-input" : "processing",
30394
30465
  ...restored
30395
30466
  });
@@ -30399,7 +30470,7 @@ async function requestResult(requestId, opts = {}) {
30399
30470
  if (recovered && (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled")) {
30400
30471
  await settleCreditAfterRead({ job: recovered, capture: captured, transport, human: opts.human });
30401
30472
  }
30402
- const confirmed = await bookRecoveredSubmissions({
30473
+ const confirmed = hasUnsavedJobState() ? [] : await bookRecoveredSubmissions({
30403
30474
  publicRequestId: requestId,
30404
30475
  endpoint: intent.endpoint,
30405
30476
  jobId: receipt.jobId
@@ -30495,7 +30566,7 @@ function paymentMethod(receipt) {
30495
30566
 
30496
30567
  // src/commands/request-resume.ts
30497
30568
  async function requestResume(requestId, opts = {}) {
30498
- return withOutputWarnings(() => resumeRequest(requestId, opts));
30569
+ return withOutputWarnings(() => resumeRequest(requestId, opts), opts.human);
30499
30570
  }
30500
30571
  async function resumeRequest(requestId, opts) {
30501
30572
  if (!isPublicRequestId(requestId)) {
@@ -30848,7 +30919,7 @@ function renderSpendHuman(spend, print) {
30848
30919
  // src/commands/status.ts
30849
30920
  async function status(jobId, opts) {
30850
30921
  const access = resolveJobAccess(jobId, opts);
30851
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => statusWithAccess(jobId, opts, access)));
30922
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => statusWithAccess(jobId, opts, access), opts.human));
30852
30923
  }
30853
30924
  async function statusWithAccess(jobId, opts, access) {
30854
30925
  const { stored, ref, jobToken } = access;
@@ -30963,7 +31034,7 @@ async function statusWithAccess(jobId, opts, access) {
30963
31034
  const updates = {};
30964
31035
  if (result.status === "processing") updates.status = "processing";
30965
31036
  if (newCursor !== void 0) updates.messageCursor = newCursor;
30966
- if (Object.keys(updates).length > 0) updateJob(jobId, updates);
31037
+ if (Object.keys(updates).length > 0) updateObservedJob(jobId, updates);
30967
31038
  }
30968
31039
  transport.close();
30969
31040
  renderStatus(jobId, stored, result.status, completion, "provider", nextAction, opts, {
@@ -34158,10 +34229,10 @@ var NON_FUNGIBLE_MINT_NOTE = "Balances are per-mint: each mint is a separate cus
34158
34229
  async function walletFund(amount, opts) {
34159
34230
  const rail = (opts.rail ?? "cashu").toLowerCase();
34160
34231
  if (rail === "tempo" || rail === "x402") {
34161
- if (opts.mint !== void 0 || opts.timeout !== void 0 || opts.sats || opts.testSkipLightning || opts.float === false) {
34232
+ if (opts.mint !== void 0 || opts.timeout !== void 0 || opts.sats || opts.testSkipLightning || opts.float === false || opts.wait === false) {
34162
34233
  throw new DvmError(
34163
34234
  "invalid_flags_for_rail",
34164
- "--mint, --timeout, --sats, --test-skip-lightning, and --no-float only apply to --rail cashu.",
34235
+ "--mint, --timeout, --sats, --test-skip-lightning, --no-float, and --no-wait only apply to --rail cashu.",
34165
34236
  `Drop these flags when running \`dvm wallet fund --rail ${rail}\`.`
34166
34237
  );
34167
34238
  }
@@ -34176,6 +34247,21 @@ async function walletFund(amount, opts) {
34176
34247
  "Supported rails: cashu (default), tempo, x402."
34177
34248
  );
34178
34249
  }
34250
+ if (opts.wait === false && opts.testSkipLightning) {
34251
+ throw new DvmError(
34252
+ "invalid_fund_options",
34253
+ "--no-wait cannot be combined with --test-skip-lightning: there is no human-paid invoice to hand off.",
34254
+ "Drop --no-wait to wait for the test mint to settle."
34255
+ );
34256
+ }
34257
+ const float = opts.float === false || opts.testSkipLightning ? null : loadFloat();
34258
+ if (opts.wait === false && float) {
34259
+ throw new DvmError(
34260
+ "invalid_fund_options",
34261
+ "--no-wait cannot be used while the connected Lightning float pays the invoice.",
34262
+ "Add --no-float to hand the invoice to a human, or drop --no-wait for autonomous funding."
34263
+ );
34264
+ }
34179
34265
  await loadConfiguredMints();
34180
34266
  const wallet = loadAgentWallet();
34181
34267
  if (!wallet) {
@@ -34194,7 +34280,6 @@ async function walletFund(amount, opts) {
34194
34280
  const amountPhrase = describeAmount(amt);
34195
34281
  const timeoutMs = parseTimeout2(opts.timeout);
34196
34282
  const human = opts.human ?? false;
34197
- const float = opts.float === false || opts.testSkipLightning ? null : loadFloat();
34198
34283
  const btcRate = float ? await assertFloatBudget(sats * 1e3) : null;
34199
34284
  let fundedQuoteId;
34200
34285
  const selection = await resolveFundMint({
@@ -34249,6 +34334,68 @@ async function walletFund(amount, opts) {
34249
34334
  info(`Paying from your Lightning wallet${float.alias ? ` (${float.alias})` : ""}\u2026`);
34250
34335
  }
34251
34336
  }
34337
+ const onInvoice = async (invoice, quote2) => {
34338
+ const expiresAt = quote2.expiry !== null ? new Date(quote2.expiry * 1e3).toISOString() : null;
34339
+ const previousUnpaid = sweep.still_pending.map((entry) => ({
34340
+ quote_id: entry.quote_id,
34341
+ mint: entry.mint,
34342
+ amount_sats: entry.amount_sats
34343
+ }));
34344
+ const warning = opts.wait === false && previousUnpaid.length > 0 ? `An unpaid quote already exists: ${previousUnpaid.map((entry) => `${entry.quote_id} at ${entry.mint} (${entry.amount_sats} sats)`).join(", ")}. This is a new invoice; avoid asking a human to pay both for the same top-up.` : void 0;
34345
+ if (human) {
34346
+ if (warning) info(`Warning: ${warning}`);
34347
+ info("");
34348
+ info("Pay this Lightning invoice from any Lightning wallet:");
34349
+ info("");
34350
+ info(invoice);
34351
+ info("");
34352
+ const ascii = await renderQrTerminal(invoice.toUpperCase());
34353
+ info(ascii);
34354
+ if (opts.qrImage !== void 0) {
34355
+ await writeInvoicePng(invoice, opts.qrImage);
34356
+ info(`QR PNG written to ${opts.qrImage}`);
34357
+ }
34358
+ if (opts.wait === false) {
34359
+ info(`Quote ID: ${quote2.quote}`);
34360
+ if (expiresAt) info(`Invoice expires: ${expiresAt}`);
34361
+ info("After payment, run `dvm wallet show` to collect the sats and check the new balance.");
34362
+ } else {
34363
+ info(
34364
+ "Polling for payment every 2s; press Ctrl-C to bail (the quote will be recoverable on next run)."
34365
+ );
34366
+ }
34367
+ } else {
34368
+ const qrImagePath = opts.qrImage ?? defaultQrImagePath();
34369
+ await writeInvoicePng(invoice, qrImagePath);
34370
+ json({
34371
+ status: "awaiting_payment",
34372
+ mint: mintUrl,
34373
+ mint_selection: mintSelection,
34374
+ amount_sats: sats,
34375
+ ...amountSourceFields(amt),
34376
+ invoice,
34377
+ quote_id: quote2.quote,
34378
+ next_step: "dvm wallet show",
34379
+ qr_image_path: qrImagePath,
34380
+ relay: { copy_text: invoice, standalone: true },
34381
+ expires_at: expiresAt,
34382
+ lock_pubkey: wallet.lock_pubkey,
34383
+ display: `Pay ${sats} sats to the Lightning invoice to fund ${amountPhrase} into the agent wallet at ${mintUrl} (${selectionPhrase}). Scannable QR at ${qrImagePath}.`,
34384
+ ...opts.wait === false ? {
34385
+ existing_unpaid_quotes: previousUnpaid,
34386
+ ...warning ? { warning } : {},
34387
+ sweep: summarizeSweep(sweep),
34388
+ melt_sweep: summarizeMeltSweep(meltSweep)
34389
+ } : {},
34390
+ hint: opts.wait === false ? "Forward the QR PNG (or raw invoice) to a human. After payment, run `dvm wallet show` to collect the sats and check the new balance. Funding is still pending." : "Forward the QR PNG (or raw invoice) to a human; the CLI will mint P2PK-locked Cashu proofs into ~/.dvm/wallet.json once paid."
34391
+ });
34392
+ }
34393
+ };
34394
+ if (opts.wait === false) {
34395
+ const { quote: quote2 } = await createPendingMintQuote(sats, { mintUrl });
34396
+ await onInvoice(quote2.request, quote2);
34397
+ return;
34398
+ }
34252
34399
  const result = await fundWithRecoverableWait(sats, {
34253
34400
  mintUrl,
34254
34401
  timeoutMs,
@@ -34307,42 +34454,7 @@ async function walletFund(amount, opts) {
34307
34454
  });
34308
34455
  }
34309
34456
  },
34310
- onInvoice: async (invoice, quote2) => {
34311
- const expiresAt = quote2.expiry !== null ? new Date(quote2.expiry * 1e3).toISOString() : null;
34312
- if (human) {
34313
- info("");
34314
- info("Pay this Lightning invoice from any Lightning wallet:");
34315
- info("");
34316
- info(invoice);
34317
- info("");
34318
- const ascii = await renderQrTerminal(invoice.toUpperCase());
34319
- info(ascii);
34320
- if (opts.qrImage !== void 0) {
34321
- await writeInvoicePng(invoice, opts.qrImage);
34322
- info(`QR PNG written to ${opts.qrImage}`);
34323
- }
34324
- info(
34325
- "Polling for payment every 2s; press Ctrl-C to bail (the quote will be recoverable on next run)."
34326
- );
34327
- } else {
34328
- const qrImagePath = opts.qrImage ?? defaultQrImagePath();
34329
- await writeInvoicePng(invoice, qrImagePath);
34330
- json({
34331
- status: "awaiting_payment",
34332
- mint: mintUrl,
34333
- mint_selection: mintSelection,
34334
- amount_sats: sats,
34335
- ...amountSourceFields(amt),
34336
- invoice,
34337
- qr_image_path: qrImagePath,
34338
- relay: { copy_text: invoice, standalone: true },
34339
- expires_at: expiresAt,
34340
- lock_pubkey: wallet.lock_pubkey,
34341
- display: `Pay ${sats} sats to the Lightning invoice to fund ${amountPhrase} into the agent wallet at ${mintUrl} (${selectionPhrase}). Scannable QR at ${qrImagePath}.`,
34342
- hint: "Forward the QR PNG (or raw invoice) to a human; the CLI will mint P2PK-locked Cashu proofs into ~/.dvm/wallet.json once paid."
34343
- });
34344
- }
34345
- }
34457
+ onInvoice
34346
34458
  });
34347
34459
  const totalProofSats = result.proofs.reduce((sum, p) => sum + p.amount, 0);
34348
34460
  if (human) {
@@ -34462,6 +34574,9 @@ async function walletShow(opts) {
34462
34574
  const recovered = sweep.recovered_proofs.reduce((sum, p) => sum + p.amount, 0);
34463
34575
  info(`Recovered ${recovered} sats from ${sweep.recovered_proofs.length} pending mint(s).`);
34464
34576
  }
34577
+ for (const collected of summarizeSweep(sweep).collected) {
34578
+ info(`${collected.display} Added ${collected.sats_collected} sats at ${collected.mint}.`);
34579
+ }
34465
34580
  for (const expired of expiredMints) {
34466
34581
  info(
34467
34582
  `Unpaid mint quote expired: ${expired.amount_sats} sats at ${expired.mint} (quote ID ${expired.quote_id}) \u2014 local recovery entry removed.`
@@ -34939,7 +35054,7 @@ function formatFeePpk(fee) {
34939
35054
  function formatPending(p, unchecked) {
34940
35055
  const row = `${p.amount_sats} sats at ${p.mint} (quote ${p.quote_id}, requested ${p.requested_at})`;
34941
35056
  return unchecked ? `${row}
34942
- \u21B3 ${uncheckedPendingNote(unchecked)}` : `${row} \u2014 awaiting payment`;
35057
+ \u21B3 ${uncheckedPendingNote(unchecked)}` : `${row} \u2014 not paid yet; awaiting payment`;
34943
35058
  }
34944
35059
  function reportUncheckedMints(unchecked) {
34945
35060
  for (const entry of unchecked) {
@@ -34986,6 +35101,20 @@ function summarizeMeltSweep(sweep) {
34986
35101
  }
34987
35102
  function summarizeSweep(sweep) {
34988
35103
  return {
35104
+ pending: sweep.still_pending.map((entry) => ({
35105
+ quote_id: entry.quote_id,
35106
+ mint: entry.mint,
35107
+ amount_sats: entry.amount_sats,
35108
+ display: `Mint quote ${entry.quote_id} is not paid yet.`
35109
+ })),
35110
+ collected: sweep.outcomes.flatMap(
35111
+ (outcome) => outcome.kind === "minted" || outcome.kind === "restored" ? [{
35112
+ quote_id: outcome.entry.quote_id,
35113
+ mint: outcome.entry.mint,
35114
+ sats_collected: outcome.proofs.reduce((sum, proof) => sum + proof.amount, 0),
35115
+ display: `Mint quote ${outcome.entry.quote_id} was paid and collected.`
35116
+ }] : []
35117
+ ),
34989
35118
  recovered_count: sweep.recovered_proofs.length,
34990
35119
  recovered_sats: sweep.recovered_proofs.reduce((s, p) => s + p.amount, 0),
34991
35120
  // Additive to `dropped`, which remains the compatibility field for callers
@@ -35016,6 +35145,57 @@ async function writeInvoicePng(invoice, outPath) {
35016
35145
  }
35017
35146
 
35018
35147
  // src/lib/wallet-agent/release.ts
35148
+ import { randomUUID as randomUUID5 } from "crypto";
35149
+
35150
+ // src/lib/wallet-agent/release-intents.ts
35151
+ var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
35152
+ import { createHash as createHash6 } from "crypto";
35153
+ import { dirname as dirname4, join as join10 } from "path";
35154
+ var intents = journalFile("release-intents.json");
35155
+ async function withReleaseLock(walletPubkey, builderHandle, mint, operation) {
35156
+ ensureConfigDir();
35157
+ const key = createHash6("sha256").update(JSON.stringify([walletPubkey, builderHandle, mint])).digest("hex");
35158
+ let unlock;
35159
+ try {
35160
+ unlock = await import_proper_lockfile3.default.lock(join10(dirname4(JOBS_FILE), `release-${key}`), {
35161
+ realpath: false,
35162
+ stale: 2 * 6e4,
35163
+ retries: 0
35164
+ });
35165
+ } catch {
35166
+ throw new Error("Could not acquire the release lock; another release may be running for this builder and mint. Retry `dvm wallet release` shortly.");
35167
+ }
35168
+ try {
35169
+ return await operation();
35170
+ } finally {
35171
+ try {
35172
+ await unlock();
35173
+ } catch {
35174
+ }
35175
+ }
35176
+ }
35177
+ function allReleaseIntents() {
35178
+ return intents.read();
35179
+ }
35180
+ function loadReleaseIntent(walletPubkey, builderHandle, mint) {
35181
+ return intents.read().find(
35182
+ (intent) => intent.walletPubkey === walletPubkey && intent.builderHandle === builderHandle && intent.mint === mint
35183
+ );
35184
+ }
35185
+ function recordReleaseIntent(intent) {
35186
+ intents.withLock(() => {
35187
+ if (loadReleaseIntent(intent.walletPubkey, intent.builderHandle, intent.mint)) {
35188
+ throw new Error("Another release is awaiting recovery; retry `dvm wallet release`.");
35189
+ }
35190
+ intents.write([...intents.read(), intent]);
35191
+ });
35192
+ }
35193
+ function clearReleaseIntent(intent) {
35194
+ intents.withLock(() => intents.write(intents.read().filter((held) => held.id !== intent.id)));
35195
+ }
35196
+
35197
+ // src/lib/wallet-agent/release.ts
35198
+ var RELEASE_IN_FLIGHT_MS = 2 * 6e4;
35019
35199
  async function releaseAgentReserve(opts) {
35020
35200
  const cashu = opts.providerInfo.cashu;
35021
35201
  if (!cashu?.canonical_id) {
@@ -35045,9 +35225,6 @@ async function releaseAgentReserve(opts) {
35045
35225
  const candidates = initial.proofs.filter(
35046
35226
  (p) => p.reserved_for === marker && p.status === "valid" && typeof p.t_expire === "number" && p.t_expire < now
35047
35227
  );
35048
- if (candidates.length === 0) {
35049
- return { builder_handle: opts.builderHandle, output_mode: outputMode, mints: [] };
35050
- }
35051
35228
  const getWalletForMint = opts.getWalletForMint ?? getWallet;
35052
35229
  const byMint = /* @__PURE__ */ new Map();
35053
35230
  for (const p of candidates) {
@@ -35055,47 +35232,60 @@ async function releaseAgentReserve(opts) {
35055
35232
  bucket.push(p);
35056
35233
  byMint.set(p.mint, bucket);
35057
35234
  }
35235
+ for (const intent of allReleaseIntents()) {
35236
+ if (intent.walletPubkey === initial.lock_pubkey && intent.builderHandle === opts.builderHandle && !byMint.has(intent.mint)) {
35237
+ byMint.set(intent.mint, []);
35238
+ }
35239
+ }
35058
35240
  const outcomes = [];
35059
35241
  for (const [mintUrl, mintProofs] of byMint) {
35060
- outcomes.push(
35061
- await releaseAtMint(
35242
+ try {
35243
+ outcomes.push(await withReleaseLock(
35244
+ initial.lock_pubkey,
35245
+ opts.builderHandle,
35062
35246
  mintUrl,
35063
- mintProofs,
35064
- refund.privkey,
35065
- initial,
35066
- outputMode,
35067
- getWalletForMint
35068
- )
35069
- );
35247
+ () => releaseAtMint(mintUrl, mintProofs, refund.privkey, initial, outputMode, getWalletForMint, opts.builderHandle, now)
35248
+ ));
35249
+ } catch (err) {
35250
+ outcomes.push({ mint: mintUrl, output_mode: null, alreadySpent: [], pending: [], reclaimedInputs: [], reclaimedOutputs: [], error: errorText2(err) });
35251
+ }
35070
35252
  }
35071
- return { builder_handle: opts.builderHandle, output_mode: outputMode, mints: outcomes };
35253
+ const modes = new Set(outcomes.flatMap((outcome) => outcome.output_mode === null ? [] : [outcome.output_mode]));
35254
+ return {
35255
+ builder_handle: opts.builderHandle,
35256
+ output_mode: modes.size > 1 ? "mixed" : modes.values().next().value ?? outputMode,
35257
+ mints: outcomes
35258
+ };
35072
35259
  }
35073
- async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, outputMode, getWalletForMint) {
35260
+ async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, outputMode, getWalletForMint, builderHandle, now) {
35261
+ const outcome = {
35262
+ mint: mintUrl,
35263
+ output_mode: null,
35264
+ alreadySpent: [],
35265
+ pending: [],
35266
+ reclaimedInputs: [],
35267
+ reclaimedOutputs: [],
35268
+ error: null
35269
+ };
35074
35270
  let cashuWallet;
35075
35271
  try {
35076
35272
  cashuWallet = await getWalletForMint(mintUrl);
35273
+ const intent2 = loadReleaseIntent(initial.lock_pubkey, builderHandle, mintUrl);
35274
+ if (intent2) {
35275
+ const recovered = await recoverRelease(intent2, cashuWallet, outcome, now);
35276
+ if (recovered) return recovered;
35277
+ }
35278
+ const available = new Set(currentWallet(initial.lock_pubkey).proofs.filter((p) => p.mint === mintUrl && p.status === "valid").map(proofIdKey));
35279
+ mintProofs = mintProofs.filter((p) => available.has(proofIdKey(p)));
35077
35280
  } catch (err) {
35078
- return {
35079
- mint: mintUrl,
35080
- alreadySpent: [],
35081
- pending: [],
35082
- reclaimedInputs: [],
35083
- reclaimedOutputs: [],
35084
- error: err instanceof Error ? err.message : String(err)
35085
- };
35281
+ return { ...outcome, error: errorText2(err) };
35086
35282
  }
35283
+ if (mintProofs.length === 0) return outcome;
35087
35284
  let grouped;
35088
35285
  try {
35089
35286
  grouped = await cashuWallet.groupProofsByState(toCashuProofs(mintProofs));
35090
35287
  } catch (err) {
35091
- return {
35092
- mint: mintUrl,
35093
- alreadySpent: [],
35094
- pending: [],
35095
- reclaimedInputs: [],
35096
- reclaimedOutputs: [],
35097
- error: err instanceof Error ? err.message : String(err)
35098
- };
35288
+ return { ...outcome, error: errorText2(err) };
35099
35289
  }
35100
35290
  const spentSecrets = new Set(grouped.spent.map((p) => p.secret));
35101
35291
  const pendingSecrets = new Set(grouped.pending.map((p) => p.secret));
@@ -35104,29 +35294,24 @@ async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, output
35104
35294
  const unspent = mintProofs.filter(
35105
35295
  (p) => !spentSecrets.has(p.secret) && !pendingSecrets.has(p.secret)
35106
35296
  );
35107
- if (alreadySpent.length > 0) {
35297
+ outcome.pending = pending4;
35298
+ try {
35108
35299
  await withWalletLock(() => {
35109
- const fresh = loadAgentWallet() ?? initial;
35110
- const spentKeys = new Set(alreadySpent.map((p) => proofIdKey(p)));
35111
- saveAgentWallet({
35112
- ...fresh,
35113
- proofs: fresh.proofs.filter((p) => !spentKeys.has(proofIdKey(p)))
35114
- });
35300
+ assertNoRelease(initial.lock_pubkey, builderHandle, mintUrl);
35301
+ const fresh = currentWallet(initial.lock_pubkey);
35302
+ if (alreadySpent.length > 0) {
35303
+ const spentKeys = new Set(alreadySpent.map(proofIdKey));
35304
+ saveAgentWallet({ ...fresh, proofs: fresh.proofs.filter((p) => p.mint !== mintUrl || !spentKeys.has(proofIdKey(p))) });
35305
+ }
35115
35306
  });
35307
+ outcome.alreadySpent = alreadySpent;
35308
+ } catch (err) {
35309
+ return { ...outcome, error: errorText2(err) };
35116
35310
  }
35117
- if (unspent.length === 0) {
35118
- return {
35119
- mint: mintUrl,
35120
- alreadySpent,
35121
- pending: pending4,
35122
- reclaimedInputs: [],
35123
- reclaimedOutputs: [],
35124
- error: null
35125
- };
35126
- }
35311
+ if (unspent.length === 0) return outcome;
35127
35312
  const totalSats = unspent.reduce((sum, p) => sum + p.amount, 0);
35128
35313
  const inputs = toCashuProofs(unspent);
35129
- let outputs;
35314
+ let preview;
35130
35315
  try {
35131
35316
  const swapFeeSats = swapFeeForProofs(cashuWallet, inputs);
35132
35317
  const reclaimSats = totalSats - swapFeeSats;
@@ -35136,38 +35321,134 @@ async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, output
35136
35321
  );
35137
35322
  }
35138
35323
  const builder = cashuWallet.ops.send(reclaimSats, inputs).privkey(refundPrivkey);
35139
- const result = outputMode === "locked" ? await builder.asP2PK({ pubkey: initial.lock_pubkey }).run() : await builder.asRandom().run();
35140
- outputs = result.send;
35324
+ preview = outputMode === "locked" ? await builder.asP2PK({ pubkey: initial.lock_pubkey }).keepAsP2PK({ pubkey: initial.lock_pubkey }).prepare() : await builder.asRandom().keepAsRandom().prepare();
35141
35325
  } catch (err) {
35142
- return {
35143
- mint: mintUrl,
35144
- alreadySpent,
35145
- pending: pending4,
35146
- reclaimedInputs: [],
35147
- reclaimedOutputs: [],
35148
- error: err instanceof Error ? err.message : String(err)
35149
- };
35326
+ return { ...outcome, error: errorText2(err) };
35150
35327
  }
35151
- const reclaimedOutputs = outputs.map(
35152
- (p) => toAgentProof(p, mintUrl, outputMode === "locked" ? initial.lock_pubkey : null)
35153
- );
35154
- await withWalletLock(() => {
35155
- const fresh = loadAgentWallet() ?? initial;
35156
- const inputKeys = new Set(unspent.map((p) => proofIdKey(p)));
35157
- saveAgentWallet({
35158
- ...fresh,
35159
- proofs: [...fresh.proofs.filter((p) => !inputKeys.has(proofIdKey(p))), ...reclaimedOutputs]
35328
+ const selected = new Set(preview.inputs.map(proofIdKey));
35329
+ const intent = {
35330
+ id: randomUUID5(),
35331
+ builderHandle,
35332
+ mint: mintUrl,
35333
+ walletPubkey: initial.lock_pubkey,
35334
+ lockPubkey: outputMode === "locked" ? initial.lock_pubkey : null,
35335
+ keysetId: preview.keysetId,
35336
+ inputs: unspent.filter((p) => selected.has(proofIdKey(p))),
35337
+ outputs: serializeOutputData([...preview.sendOutputs ?? [], ...preview.keepOutputs ?? []]),
35338
+ createdAt: now
35339
+ };
35340
+ try {
35341
+ await withWalletLock(() => {
35342
+ const fresh = currentWallet(initial.lock_pubkey);
35343
+ const available = new Set(fresh.proofs.filter((p) => p.mint === mintUrl && p.status === "valid").map(proofIdKey));
35344
+ if (intent.inputs.length === 0 || !intent.inputs.every((p) => available.has(proofIdKey(p)))) {
35345
+ throw new Error("Reserve proofs changed during release; retry `dvm wallet release`.");
35346
+ }
35347
+ recordReleaseIntent(intent);
35160
35348
  });
35161
- });
35349
+ } catch (err) {
35350
+ return { ...outcome, error: `Could not record the release, so nothing was swapped: ${errorText2(err)}` };
35351
+ }
35352
+ let outputs;
35353
+ try {
35354
+ const result = await cashuWallet.completeSwap(preview, refundPrivkey);
35355
+ const inputKeys = new Set(inputs.map(proofIdKey));
35356
+ outputs = [...result.send, ...result.keep.filter((p) => !inputKeys.has(proofIdKey(p)))];
35357
+ } catch (err) {
35358
+ if (err instanceof te) {
35359
+ try {
35360
+ clearReleaseIntent(intent);
35361
+ } catch {
35362
+ }
35363
+ }
35364
+ return { ...outcome, error: errorText2(err) };
35365
+ }
35366
+ return commitRelease(intent, outputs, outcome);
35367
+ }
35368
+ async function commitRelease(intent, outputs, outcome) {
35369
+ const reclaimedOutputs = outputs.map((p) => toAgentProof(p, intent.mint, intent.lockPubkey));
35370
+ let saved = false;
35371
+ let cleanupError;
35372
+ try {
35373
+ await withWalletLock(() => {
35374
+ const fresh = currentWallet(intent.walletPubkey);
35375
+ const active2 = loadReleaseIntent(intent.walletPubkey, intent.builderHandle, intent.mint);
35376
+ if (active2?.id !== intent.id) return;
35377
+ const inputKeys = new Set(intent.inputs.map(proofIdKey));
35378
+ if (fresh.proofs.some((p) => p.mint === intent.mint && inputKeys.has(proofIdKey(p)))) {
35379
+ const existing = new Set(fresh.proofs.filter((p) => p.mint === intent.mint).map(proofIdKey));
35380
+ saveAgentWallet({
35381
+ ...fresh,
35382
+ proofs: [
35383
+ ...fresh.proofs.filter((p) => p.mint !== intent.mint || !inputKeys.has(proofIdKey(p))),
35384
+ ...reclaimedOutputs.filter((p) => !existing.has(proofIdKey(p)))
35385
+ ]
35386
+ });
35387
+ saved = true;
35388
+ }
35389
+ try {
35390
+ clearReleaseIntent(intent);
35391
+ } catch (err) {
35392
+ cleanupError = err;
35393
+ }
35394
+ });
35395
+ } catch (err) {
35396
+ return { ...outcome, error: `Release result is not saved to the wallet: ${errorText2(err)}. Retry \`dvm wallet release\` to recover it.` };
35397
+ }
35162
35398
  return {
35163
- mint: mintUrl,
35164
- alreadySpent,
35165
- pending: pending4,
35166
- reclaimedInputs: unspent,
35167
- reclaimedOutputs,
35168
- error: null
35399
+ ...outcome,
35400
+ output_mode: saved && reclaimedOutputs.length > 0 ? intent.lockPubkey === null ? "unlocked" : "locked" : null,
35401
+ reclaimedInputs: saved ? intent.inputs : [],
35402
+ reclaimedOutputs: saved ? reclaimedOutputs : [],
35403
+ error: cleanupError ? `Release saved, but recovery journal cleanup failed: ${errorText2(cleanupError)}. Retry \`dvm wallet release\`.` : null
35404
+ };
35405
+ }
35406
+ async function recoverRelease(intent, cashuWallet, outcome, now) {
35407
+ const fresh = currentWallet(intent.walletPubkey);
35408
+ const inputKeys = new Set(intent.inputs.map(proofIdKey));
35409
+ if (!fresh.proofs.some((p) => p.mint === intent.mint && inputKeys.has(proofIdKey(p)))) {
35410
+ return commitRelease(intent, [], outcome);
35411
+ }
35412
+ let restored = [];
35413
+ let restoreError;
35414
+ try {
35415
+ restored = await restoreProofsFromOutputs(cashuWallet, intent.keysetId, intent.outputs);
35416
+ } catch (err) {
35417
+ restoreError = err;
35418
+ }
35419
+ if (restored.length === intent.outputs.length && restored.length > 0) {
35420
+ return commitRelease(intent, restored, outcome);
35421
+ }
35422
+ if (restored.length > 0) {
35423
+ return { ...outcome, error: "The mint restored only part of the release outputs; retry `dvm wallet release`." };
35424
+ }
35425
+ const states = await cashuWallet.groupProofsByState(toCashuProofs(intent.inputs));
35426
+ if (now - intent.createdAt < RELEASE_IN_FLIGHT_MS) {
35427
+ return { ...outcome, error: "Another release may still be in flight; retry `dvm wallet release` shortly." };
35428
+ }
35429
+ const unspent = new Set(states.unspent.map((p) => proofIdKey(p)));
35430
+ if (states.pending.length === 0 && (intent.inputs.every((p) => unspent.has(proofIdKey(p))) || restoreError === void 0)) {
35431
+ await withWalletLock(() => clearReleaseIntent(intent));
35432
+ return null;
35433
+ }
35434
+ return {
35435
+ ...outcome,
35436
+ error: `Release recovery is pending${restoreError ? `: ${errorText2(restoreError)}` : ": the mint still reports inputs pending"}. Retry \`dvm wallet release\`.`
35169
35437
  };
35170
35438
  }
35439
+ function currentWallet(pubkey) {
35440
+ const wallet = loadAgentWallet();
35441
+ if (!wallet || wallet.lock_pubkey !== pubkey) throw new Error("The agent wallet changed during release.");
35442
+ return wallet;
35443
+ }
35444
+ function assertNoRelease(walletPubkey, builderHandle, mint) {
35445
+ if (loadReleaseIntent(walletPubkey, builderHandle, mint)) {
35446
+ throw new Error("Another release is awaiting recovery; retry `dvm wallet release`.");
35447
+ }
35448
+ }
35449
+ function errorText2(err) {
35450
+ return err instanceof Error ? err.message : String(err);
35451
+ }
35171
35452
  function proofIdKey(p) {
35172
35453
  return `${p.secret}:${p.C}`;
35173
35454
  }
@@ -35487,7 +35768,8 @@ async function walletRelease(opts) {
35487
35768
  `Released ${totals.reclaimedSats} sats at ${builderHandle} (output mode: ${result.output_mode}).`
35488
35769
  );
35489
35770
  for (const mintOutcome of result.mints) {
35490
- info(` ${mintOutcome.mint}:`);
35771
+ const policy = mintOutcome.output_mode === null ? "" : ` (output mode: ${mintOutcome.output_mode})`;
35772
+ info(` ${mintOutcome.mint}${policy}:`);
35491
35773
  info(
35492
35774
  ` reclaimed: ${sumSats(mintOutcome.reclaimedOutputs)} sats from ${mintOutcome.reclaimedInputs.length} proof(s)`
35493
35775
  );
@@ -35513,6 +35795,7 @@ async function walletRelease(opts) {
35513
35795
  pending_sats: totals.pendingSats,
35514
35796
  mints: result.mints.map((m) => ({
35515
35797
  mint: m.mint,
35798
+ output_mode: m.output_mode,
35516
35799
  reclaimed_sats: sumSats(m.reclaimedOutputs),
35517
35800
  reclaimed_input_count: m.reclaimedInputs.length,
35518
35801
  already_spent_sats: sumSats(m.alreadySpent),
@@ -36709,7 +36992,7 @@ function resolveMppEndpoint(identifier) {
36709
36992
  }
36710
36993
 
36711
36994
  // src/commands/wallet-pair.ts
36712
- import { createHash as createHash6, randomBytes as randomBytes5 } from "crypto";
36995
+ import { createHash as createHash7, randomBytes as randomBytes5 } from "crypto";
36713
36996
  import { hostname as hostname2 } from "os";
36714
36997
 
36715
36998
  // node_modules/nostr-tools/lib/esm/pure.js
@@ -37607,7 +37890,7 @@ function hexToBytes2(hex2) {
37607
37890
  }
37608
37891
 
37609
37892
  // src/lib/wallet-pairing-store.ts
37610
- var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
37893
+ var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
37611
37894
  import {
37612
37895
  chmodSync as chmodSync2,
37613
37896
  existsSync as existsSync8,
@@ -37617,7 +37900,7 @@ import {
37617
37900
  unlinkSync as unlinkSync3,
37618
37901
  writeFileSync as writeFileSync6
37619
37902
  } from "fs";
37620
- import { join as join10 } from "path";
37903
+ import { join as join11 } from "path";
37621
37904
  var pairingIdPattern = /^[0-9a-f]{64}$/;
37622
37905
  var stateSchema = external_exports.object({
37623
37906
  version: external_exports.literal(1),
@@ -37691,7 +37974,7 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
37691
37974
  let removed = 0;
37692
37975
  for (const name of readdirSync5(PAIRINGS_DIR)) {
37693
37976
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
37694
- const path = join10(PAIRINGS_DIR, name);
37977
+ const path = join11(PAIRINGS_DIR, name);
37695
37978
  try {
37696
37979
  const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
37697
37980
  if (state.manifest.expires_at <= nowSeconds) {
@@ -37708,7 +37991,7 @@ async function withWalletPairingLock(pairingId, fn) {
37708
37991
  if (!existsSync8(path)) return fn();
37709
37992
  let release;
37710
37993
  try {
37711
- release = await import_proper_lockfile3.default.lock(path, {
37994
+ release = await import_proper_lockfile4.default.lock(path, {
37712
37995
  lockfilePath: `${path}.lock`,
37713
37996
  realpath: false,
37714
37997
  stale: 12 * 60 * 1e3,
@@ -37735,7 +38018,7 @@ function pairingPath(pairingId) {
37735
38018
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
37736
38019
  );
37737
38020
  }
37738
- return join10(PAIRINGS_DIR, `${pairingId}.json`);
38021
+ return join11(PAIRINGS_DIR, `${pairingId}.json`);
37739
38022
  }
37740
38023
  function ensurePairingsDirectory() {
37741
38024
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -38160,7 +38443,7 @@ function walletFingerprint(uri) {
38160
38443
  return uri ? sha2562(uri) : null;
38161
38444
  }
38162
38445
  function sha2562(value) {
38163
- return createHash6("sha256").update(value).digest("hex");
38446
+ return createHash7("sha256").update(value).digest("hex");
38164
38447
  }
38165
38448
  function relayHost2(relay) {
38166
38449
  try {
@@ -39734,6 +40017,9 @@ Docs:
39734
40017
  "--sats",
39735
40018
  "Treat numeric input as sats (Cashu only; default: fiat if a currency symbol/code is present \u2014 $5, \xA35, 5eur \u2014 else sats)"
39736
40019
  ).option("--mint <url>", "Cashu mint URL (default: configured mint, or Coinos)").option("--timeout <sec>", "Override DVM_FUND_TIMEOUT_SEC (default 600s)").option(
40020
+ "--no-wait",
40021
+ "Print a human-paid Lightning invoice and exit; collect after payment with 'dvm wallet show'. Cashu only; use --no-float if a float is connected."
40022
+ ).option(
39737
40023
  "--test-skip-lightning",
39738
40024
  "Skip Lightning \u2014 for test mints that auto-pay invoices (FakeWallet). Cashu rail only."
39739
40025
  ).option(