@dvmkit/dvm-cli 0.19.0 → 0.19.1

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/README.md CHANGED
@@ -10,9 +10,17 @@ Requires Node.js 22 or later.
10
10
 
11
11
  ```sh
12
12
  npm install --global @dvmkit/dvm-cli
13
+ ```
14
+
15
+ ## Try it
16
+
17
+ ```sh
13
18
  dvm init
19
+ dvm request -d dvmkit--stakeout/peek --data '{"cameras":["kiruna"]}'
14
20
  ```
15
21
 
22
+ Get a one-time grade of the live Kiruna aurora camera for free, with no wallet or payment; see [Stakeout](https://dvmkit.com/dvmkit/stakeout) for more capabilities.
23
+
16
24
  `dvm init` returns JSON with `status: "created"` on first setup and the message "Local setup is ready. Nothing has been funded yet, so nothing can be spent yet." It also reports the configuration path and wallet setup steps.
17
25
 
18
26
  ## For agents
@@ -52,15 +52,19 @@ function withJobPersistence(run, warn) {
52
52
 
53
53
  // src/lib/output.ts
54
54
  var warnings = new AsyncLocalStorage2();
55
+ function withOutputWarningContext(run) {
56
+ return warnings.run([], run);
57
+ }
55
58
  function withOutputWarnings(run, human) {
56
- return warnings.run([], () => withJobPersistence(run, ({ accessPreserved, accessUnpreserved }) => {
59
+ const collect = () => withJobPersistence(run, ({ accessPreserved, accessUnpreserved }) => {
57
60
  const hint = accessUnpreserved ? "Job access was not preserved. Supply --endpoint <url> and --job-token <hex>, or DVM_JOB_ENDPOINT and DVM_JOB_TOKEN, to read this job; do not submit or pay again." : "Refresh the job with dvm status <job_id> --messages before paying or submitting a replacement.";
58
61
  addOutputWarnings([{
59
62
  code: "local_job_state_unsaved",
60
63
  display: "The provider's outcome is unchanged, but local job state could not be saved and may lag. Automatic payments are paused for this command." + (accessUnpreserved ? ` ${hint}` : accessPreserved ? ` Job access is preserved privately. ${hint}` : ""),
61
64
  hint
62
65
  }], human);
63
- }));
66
+ });
67
+ return warnings.getStore() ? collect() : withOutputWarningContext(collect);
64
68
  }
65
69
  function sameWarning(prior, entry) {
66
70
  if (prior.code === "local_job_state_unsaved" && entry.code === "local_job_state_unsaved") return true;
@@ -452,6 +456,7 @@ async function priceableRate(btcRate) {
452
456
  export {
453
457
  jobPersistence,
454
458
  hasUnsavedJobState,
459
+ withOutputWarningContext,
455
460
  withOutputWarnings,
456
461
  addOutputWarnings,
457
462
  setOutputTraceId,
@@ -26,7 +26,7 @@ import {
26
26
  resolveBtcUsdRate,
27
27
  tryResolveBtcUsdRate,
28
28
  tryX402Payment
29
- } from "./chunk-DJDONOMG.js";
29
+ } from "./chunk-7HJ5ZR3D.js";
30
30
  import {
31
31
  BUDGET_FILE,
32
32
  CONFIG_DIR,
@@ -9205,6 +9205,9 @@ function fundTimeoutMs() {
9205
9205
  if (!Number.isFinite(n) || n <= 0) return DEFAULT_TIMEOUT_SEC * 1e3;
9206
9206
  return Math.floor(n) * 1e3;
9207
9207
  }
9208
+ function withoutPendingMint(wallet, quoteId) {
9209
+ return { ...wallet, pending_mints: wallet.pending_mints.filter((p) => p.quote_id !== quoteId) };
9210
+ }
9208
9211
  function upsertPending(wallet, entry) {
9209
9212
  const others = wallet.pending_mints.filter((p) => p.quote_id !== entry.quote_id);
9210
9213
  return { ...wallet, pending_mints: [...others, entry] };
@@ -9366,18 +9369,19 @@ async function findFundableAlternatives(configured, skip, sats) {
9366
9369
 
9367
9370
  // src/lib/wallet-agent/recovery.ts
9368
9371
  var DEFAULT_SWEEP_QUOTE_RETRY_TIMEOUT_MS = 1e4;
9372
+ var MINT_QUOTE_EXPIRY_GRACE_MS = 24 * 60 * 60 * 1e3;
9369
9373
  async function sweepPendingMints(opts = {}) {
9370
9374
  const wallet = loadAgentWallet();
9371
9375
  if (!wallet || wallet.pending_mints.length === 0) {
9372
- return { outcomes: [], recovered_proofs: [], still_pending: [], errors: [] };
9376
+ return { outcomes: [], recovered_proofs: [], still_pending: [], refused: [], errors: [] };
9373
9377
  }
9374
9378
  const now = opts.now ?? (() => Date.now());
9375
- const expirationMs = opts.expirationMs ?? fundTimeoutMs();
9379
+ const expiryGraceMs = opts.expiryGraceMs ?? MINT_QUOTE_EXPIRY_GRACE_MS;
9376
9380
  const getWalletForMint = opts.getWalletForMint ?? getWallet;
9377
9381
  const quoteRetryTimeoutMs = opts.quoteRetryTimeoutMs ?? DEFAULT_SWEEP_QUOTE_RETRY_TIMEOUT_MS;
9378
9382
  const outcomes = [];
9379
9383
  for (const entry of wallet.pending_mints) {
9380
- const outcome = await processEntry(wallet, entry, now(), expirationMs, getWalletForMint, {
9384
+ const outcome = await processEntry(wallet, entry, now(), expiryGraceMs, getWalletForMint, {
9381
9385
  now,
9382
9386
  sleep: opts.sleep,
9383
9387
  timeoutMs: quoteRetryTimeoutMs
@@ -9401,10 +9405,11 @@ async function sweepPendingMints(opts = {}) {
9401
9405
  still_pending: outcomes.filter(
9402
9406
  (o) => o.kind === "still_pending"
9403
9407
  ).map((o) => o.entry),
9408
+ refused: outcomes.filter((o) => o.kind === "paid_refused").map((o) => o.entry),
9404
9409
  errors: outcomes.filter((o) => o.kind === "error").map((o) => ({ quote_id: o.entry.quote_id, error: o.error }))
9405
9410
  };
9406
9411
  }
9407
- async function processEntry(wallet, entry, nowMs, expirationMs, getWalletForMint, retry) {
9412
+ async function processEntry(wallet, entry, nowMs, expiryGraceMs, getWalletForMint, retry) {
9408
9413
  let cashuWallet;
9409
9414
  let quoteResponse;
9410
9415
  try {
@@ -9422,6 +9427,15 @@ async function processEntry(wallet, entry, nowMs, expirationMs, getWalletForMint
9422
9427
  }
9423
9428
  ));
9424
9429
  } catch (err) {
9430
+ const refusal = mintQuoteRefusal(err);
9431
+ if (refusal !== void 0) {
9432
+ return finalAnswer(
9433
+ wallet,
9434
+ entry,
9435
+ refusal === "unknown" ? "mint_unknown" : "mint_expired",
9436
+ () => getWalletForMint(entry.mint)
9437
+ );
9438
+ }
9425
9439
  return { kind: "error", entry, error: errorMessage(err) };
9426
9440
  }
9427
9441
  const state = quoteResponse.state;
@@ -9475,29 +9489,72 @@ async function processEntry(wallet, entry, nowMs, expirationMs, getWalletForMint
9475
9489
  const agentProofs = proofs.map((p) => toAgentProof(p, entry.mint, wallet.lock_pubkey));
9476
9490
  return { kind: "minted", entry, proofs: agentProofs };
9477
9491
  } catch (err) {
9492
+ if (mintQuoteRefusal(err) === "expired") {
9493
+ return { kind: "paid_refused", entry, reason: "quote_expired" };
9494
+ }
9478
9495
  return { kind: "error", entry, error: errorMessage(err) };
9479
9496
  }
9480
9497
  }
9498
+ if (state === "EXPIRED") {
9499
+ return finalAnswer(wallet, entry, "mint_expired", async () => cashuWallet);
9500
+ }
9481
9501
  const quoteExpiry = entry.expires_at;
9482
- if (quoteExpiry !== void 0 && Number.isFinite(quoteExpiry)) {
9483
- if (nowMs > quoteExpiry * 1e3) {
9484
- return { kind: "expired", entry };
9485
- }
9502
+ if (quoteExpiry === void 0 || !Number.isFinite(quoteExpiry)) {
9503
+ return { kind: "still_pending", entry };
9504
+ }
9505
+ const expiredAtMs = quoteExpiry * 1e3;
9506
+ if (nowMs <= expiredAtMs) {
9486
9507
  return { kind: "still_pending", entry };
9487
9508
  }
9488
- const requestedAtMs = Date.parse(entry.requested_at);
9489
- const ageMs = Number.isFinite(requestedAtMs) ? nowMs - requestedAtMs : Infinity;
9490
- if (ageMs > expirationMs) {
9491
- return { kind: "expired", entry };
9509
+ const dropAfterMs = expiredAtMs + expiryGraceMs;
9510
+ if (nowMs > dropAfterMs) {
9511
+ return finalAnswer(wallet, entry, "grace_elapsed", async () => cashuWallet);
9492
9512
  }
9493
- return { kind: "still_pending", entry };
9513
+ return {
9514
+ kind: "still_pending",
9515
+ entry,
9516
+ past_expiry: { expired_at_ms: expiredAtMs, drop_after_ms: dropAfterMs }
9517
+ };
9518
+ }
9519
+ async function finalAnswer(wallet, entry, reason, getCashuWallet) {
9520
+ if (!entry.minting) return { kind: "expired", entry, reason };
9521
+ try {
9522
+ const restored = await restoreFromMintingState(
9523
+ await getCashuWallet(),
9524
+ entry.minting,
9525
+ wallet.lock_pubkey,
9526
+ entry.mint
9527
+ );
9528
+ if (restored.length > 0) return { kind: "restored", entry, proofs: restored };
9529
+ } catch (err) {
9530
+ return { kind: "error", entry, error: errorMessage(err) };
9531
+ }
9532
+ if (reason === "mint_expired") return { kind: "paid_refused", entry, reason: "quote_expired" };
9533
+ return {
9534
+ kind: "error",
9535
+ entry,
9536
+ error: reason === "mint_unknown" ? "The mint reported this quote paid earlier and no longer knows it; nothing could be restored, so the quote is kept." : "The mint reported this quote paid earlier and now reports it unpaid; nothing could be restored, so the quote is kept."
9537
+ };
9538
+ }
9539
+ var MINT_QUOTE_EXPIRED_CODE = 20007;
9540
+ var QUOTE_UNKNOWN_TEXT = /\bquote\b[^.]*\b(not found|unknown|does not exist)\b|\b(unknown|no such) quote\b/i;
9541
+ var QUOTE_EXPIRED_TEXT = /\bquote\b[^.]*\bexpired\b|\bexpired quote\b/i;
9542
+ function mintQuoteRefusal(err) {
9543
+ if (typeof err !== "object" || err === null) return void 0;
9544
+ const { name, status, code, message } = err;
9545
+ const answered = name === "MintOperationError" && status === 400 && typeof code === "number";
9546
+ if (!answered) return void 0;
9547
+ const text = typeof message === "string" ? message : "";
9548
+ if (code === MINT_QUOTE_EXPIRED_CODE || QUOTE_EXPIRED_TEXT.test(text)) return "expired";
9549
+ if (QUOTE_UNKNOWN_TEXT.test(text)) return "unknown";
9550
+ return void 0;
9494
9551
  }
9495
9552
  async function restoreFromMintingState(cashuWallet, minting, lockPubkey, mintUrl) {
9496
9553
  const proofs = await restoreProofsFromOutputs(cashuWallet, minting.keyset_id, minting.outputs);
9497
9554
  return proofs.map((proof) => toAgentProof(proof, mintUrl, lockPubkey));
9498
9555
  }
9499
9556
  function applyOutcome(wallet, outcome) {
9500
- if (outcome.kind === "still_pending" || outcome.kind === "error") {
9557
+ if (outcome.kind === "still_pending" || outcome.kind === "paid_refused" || outcome.kind === "error") {
9501
9558
  return wallet;
9502
9559
  }
9503
9560
  const next = {
@@ -9719,8 +9776,11 @@ export {
9719
9776
  createPendingMintQuote,
9720
9777
  fundAgentWallet,
9721
9778
  fundTimeoutMs,
9779
+ withoutPendingMint,
9722
9780
  pollUntilPaidOrTimeout,
9723
9781
  resolveFundMint,
9724
9782
  describeMintBounds,
9725
- sweepPendingMints
9783
+ MINT_QUOTE_EXPIRY_GRACE_MS,
9784
+ sweepPendingMints,
9785
+ mintQuoteRefusal
9726
9786
  };
@@ -3,7 +3,7 @@ import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
5
  tryX402Payment
6
- } from "./chunk-DJDONOMG.js";
6
+ } from "./chunk-7HJ5ZR3D.js";
7
7
  import "./chunk-X6BETQ7V.js";
8
8
  import "./chunk-JBU7RKQ3.js";
9
9
  import "./chunk-KDNFUDOG.js";
package/dist/dvm.js CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  DEFAULT_CREDIT_POSTURE,
12
12
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
13
13
  JOB_READ_TIMEOUT_MS,
14
+ MINT_QUOTE_EXPIRY_GRACE_MS,
14
15
  NWC_FUNDING_FLOAT_ROLE,
15
16
  SUBMISSION_EVIDENCE_DIR,
16
17
  abandonPendingSubmission,
@@ -113,6 +114,7 @@ import {
113
114
  maxSeq,
114
115
  meltInFlightTimeoutSeconds,
115
116
  midJobSpendLabel,
117
+ mintQuoteRefusal,
116
118
  mutateCreditPayment,
117
119
  needsTopup,
118
120
  nextStepHint,
@@ -212,8 +214,9 @@ import {
212
214
  withAcceptedUnresolved,
213
215
  withIdentityRecovery,
214
216
  withJobTokenRedaction,
215
- withRequestResultRecovery
216
- } from "./chunk-J3HYNDMI.js";
217
+ withRequestResultRecovery,
218
+ withoutPendingMint
219
+ } from "./chunk-NCX4JVLU.js";
217
220
  import {
218
221
  connectedTempoAccount,
219
222
  generateTempoKey,
@@ -266,8 +269,9 @@ import {
266
269
  staleRateNotice,
267
270
  tryResolveBtcUsdRate,
268
271
  tryX402Payment,
272
+ withOutputWarningContext,
269
273
  withOutputWarnings
270
- } from "./chunk-DJDONOMG.js";
274
+ } from "./chunk-7HJ5ZR3D.js";
271
275
  import {
272
276
  assertX402WalletIdle
273
277
  } from "./chunk-B5KW2TPR.js";
@@ -11882,7 +11886,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11882
11886
  }
11883
11887
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11884
11888
  const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
11885
- const { tryX402Payment: tryX402Payment2 } = await import("./client-S3FEXAWD.js");
11889
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-PY4T2DOA.js");
11886
11890
  const wallet = loadX402Wallet2();
11887
11891
  if (wallet) {
11888
11892
  let proof;
@@ -14711,7 +14715,7 @@ async function settleCreditAfterJob(args) {
14711
14715
  }
14712
14716
  }
14713
14717
  if (args.allowTopup !== false) {
14714
- const refill = args.refillPocket ?? (await import("./pocket-refill-KUBHM7MR.js")).refillPocketIfLow;
14718
+ const refill = args.refillPocket ?? (await import("./pocket-refill-U4VK5WGO.js")).refillPocketIfLow;
14715
14719
  await refill({ human: args.human }).catch(() => void 0);
14716
14720
  }
14717
14721
  }
@@ -25672,6 +25676,61 @@ function formatBytes(bytes) {
25672
25676
  return `${bytes.toLocaleString("en-US")} bytes`;
25673
25677
  }
25674
25678
 
25679
+ // src/lib/unanswered-payment.ts
25680
+ import { isDeepStrictEqual } from "util";
25681
+ async function readUnansweredPaymentRequest(jobId, status2, access, transport, options = {}) {
25682
+ if (status2 !== "cancelled") return void 0;
25683
+ const job = access.endpointOverridden ? void 0 : loadJob(jobId);
25684
+ if (job?.callerCancelled) return void 0;
25685
+ const retained = job?.unansweredPaymentEvidence;
25686
+ const local = job ? loadMessages(jobId) : [];
25687
+ let history = options.messages ?? [];
25688
+ const hasPaymentContext = (job?.policy?.maxPayments ?? 0) > 0 || retained !== void 0 || [...local, ...history].some((message2) => message2.from === "provider" && message2.type === "payment-request");
25689
+ if (hasPaymentContext && !options.localOnly && !options.fullHistory) {
25690
+ try {
25691
+ history = await transport.getMessages(jobId, 0, access.ref, {
25692
+ jobToken: access.jobToken,
25693
+ timeoutMs: options.timeoutMs ?? 5e3
25694
+ });
25695
+ } catch {
25696
+ }
25697
+ }
25698
+ const log = [...new Map([
25699
+ ...retained ? [retained.request, retained.cancellation] : [],
25700
+ ...local,
25701
+ ...history
25702
+ ].map((message2) => [message2.seq, message2])).values()].sort((a, b) => a.seq - b.seq);
25703
+ const answered = answeredYieldSeqs(log);
25704
+ if (job) for (const seq of loadAnsweredYieldSeqs(jobId)) answered.add(seq);
25705
+ const evidence = unansweredPaymentEvidence(log, answered, job);
25706
+ if (job && !isDeepStrictEqual(retained, evidence)) updateObservedJob(jobId, { unansweredPaymentEvidence: evidence });
25707
+ if (!evidence) return void 0;
25708
+ const ask = evidence.request;
25709
+ const expiresAtMs = ask.content.expires_at_ms;
25710
+ const amount = formatPaymentAmount(ask.content.amount_msats, ask.content.fiat_amount, { anchor: false });
25711
+ return providerFields({
25712
+ seq: ask.seq,
25713
+ amount_msats: ask.content.amount_msats,
25714
+ ...ask.content.fiat_amount ? { fiat_amount: ask.content.fiat_amount } : {},
25715
+ ...ask.content.credit ? { credit: ask.content.credit } : {},
25716
+ reason: asProviderText(ask.content.reason),
25717
+ expires_at_ms: expiresAtMs,
25718
+ display: `The job appears to have stopped because payment ask #${ask.seq} went unanswered by its deadline (${new Date(expiresAtMs).toISOString()}). The provider asked for ${amount}, reason: ${JSON.stringify(ask.content.reason)}. Only charges paid before this ask were taken. Cancellation timestamps have one-second precision and do not establish when useful work stopped.`
25719
+ }, ["seq", "amount_msats", "fiat_amount", "credit", "expires_at_ms"]);
25720
+ }
25721
+ function unansweredPaymentEvidence(log, answered, job) {
25722
+ const ask = log.findLast((message2) => message2.from === "provider" && message2.type === "payment-request");
25723
+ if (ask?.type !== "payment-request" || ask.content.amount_msats <= 0) return void 0;
25724
+ if (answered.has(ask.seq)) return void 0;
25725
+ if (job?.inFlightPaymentRequestSeqs?.includes(ask.seq) || job?.unconfirmedPaymentSubmissions?.[ask.seq] || job?.askPaymentBlocks?.[ask.seq] || job?.pendingCreditPayment?.authorization.request_seq === ask.seq) return void 0;
25726
+ const expiresAtMs = ask.content.expires_at_ms;
25727
+ if (typeof expiresAtMs !== "number" || !Number.isSafeInteger(expiresAtMs) || expiresAtMs < 0 || expiresAtMs > 864e13) return void 0;
25728
+ const ending = log.findLast((message2) => message2.type === "cancel" || message2.type === "complete");
25729
+ if (ending?.type !== "cancel" || ending.from !== "provider" || ending.seq <= ask.seq || !Number.isFinite(ending.timestamp) || ending.timestamp < Math.floor(expiresAtMs / 1e3)) return void 0;
25730
+ if (log.some((message2) => message2.seq > ask.seq && message2.seq < ending.seq && (message2.from === "provider" && message2.type === "working" || message2.from === "requester" && (message2.type === "decline" || message2.type === "cancel")))) return void 0;
25731
+ return { request: ask, cancellation: ending };
25732
+ }
25733
+
25675
25734
  // src/lib/message-human.ts
25676
25735
  function paymentAmount(msg) {
25677
25736
  if (msg.from === "requester" && msg.content.credit) {
@@ -26109,9 +26168,16 @@ async function messagesWithAccess(jobId, opts, access) {
26109
26168
  const resolvedAction2 = await resolveNextAction2(nextAction, msgs, providerStatus2?.status);
26110
26169
  const currency2 = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus2?.receipt, status: providerStatus2, messages: msgs, transport, ref }) : void 0;
26111
26170
  const settlement2 = await observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden, currency2);
26171
+ const unanswered2 = await readUnansweredPaymentRequest(jobId, providerStatus2?.status ?? (access.endpointOverridden ? void 0 : loadJob(jobId)?.status), access, transport, {
26172
+ messages: msgs,
26173
+ fullHistory: after === 0,
26174
+ localOnly: isTerminal || providerStatus2?.content_available === false,
26175
+ timeoutMs: timeout
26176
+ });
26112
26177
  transport.close();
26113
26178
  if (opts.human) {
26114
26179
  renderSettlementHuman(settlement2);
26180
+ if (unanswered2) info(unanswered2.display);
26115
26181
  info(String(content2.content_hint));
26116
26182
  if (msgs.length === 0) {
26117
26183
  info("No new messages.");
@@ -26127,6 +26193,7 @@ async function messagesWithAccess(jobId, opts, access) {
26127
26193
  jobId,
26128
26194
  ...content2,
26129
26195
  ...settlement2,
26196
+ ...unanswered2 ? { unanswered_payment_request: unanswered2 } : {},
26130
26197
  messages: msgs.map(serialize),
26131
26198
  cursor: newCursor,
26132
26199
  next_action: resolvedAction2,
@@ -26204,9 +26271,16 @@ async function messagesWithAccess(jobId, opts, access) {
26204
26271
  const observed = providerStatus ?? result.providerStatus;
26205
26272
  const currency = access.endpointOverridden ? await providerCurrency({ receipt: observed?.receipt, status: observed, messages: result.messages, transport, ref }) : void 0;
26206
26273
  const settlement = await observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
26274
+ const unanswered = await readUnansweredPaymentRequest(jobId, observed?.status ?? (access.endpointOverridden ? void 0 : loadJob(jobId)?.status), access, transport, {
26275
+ messages: result.messages,
26276
+ fullHistory: after === 0 && result.messages.some((message2) => message2.type === "cancel" || message2.type === "complete"),
26277
+ localOnly: isTerminal || observed?.content_available === false || waitDeadline !== void 0 && Date.now() >= waitDeadline,
26278
+ timeoutMs: waitDeadline === void 0 ? streamOptions.timeoutMs : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now()))
26279
+ });
26207
26280
  transport.close();
26208
26281
  if (opts.human) {
26209
26282
  renderSettlementHuman(settlement);
26283
+ if (unanswered) info(unanswered.display);
26210
26284
  info(String(content.content_hint));
26211
26285
  if (result.messages.length === 0) {
26212
26286
  info("No new messages.");
@@ -26224,6 +26298,7 @@ async function messagesWithAccess(jobId, opts, access) {
26224
26298
  jobId,
26225
26299
  ...content,
26226
26300
  ...settlement,
26301
+ ...unanswered ? { unanswered_payment_request: unanswered } : {},
26227
26302
  message_count: messageLines,
26228
26303
  auto_payment_count: paymentLines,
26229
26304
  cursor: result.cursor,
@@ -26235,6 +26310,7 @@ async function messagesWithAccess(jobId, opts, access) {
26235
26310
  jobId,
26236
26311
  ...content,
26237
26312
  ...settlement,
26313
+ ...unanswered ? { unanswered_payment_request: unanswered } : {},
26238
26314
  messages: result.messages.map(serialize),
26239
26315
  cursor: result.cursor,
26240
26316
  next_action: resolvedAction,
@@ -26705,15 +26781,19 @@ function parsePositiveCashuSats(raw2) {
26705
26781
  function positive(value) {
26706
26782
  return typeof value === "number" && Number.isFinite(value) && value > 0;
26707
26783
  }
26708
- function autoPayWarnings(quotes, limits, ceiling, btcRate = getLastKnownBtcRate()?.rate ?? 0) {
26784
+ function autoPayWarnings(quotes, limits, ceiling, btcRate = getLastKnownBtcRate()?.rate ?? 0, { upfrontCoveredByCredit = false } = {}) {
26709
26785
  if (!limits.budget && !limits.autoPayBelow) return [];
26710
26786
  if (!positive(btcRate)) {
26711
26787
  const quoted = quotes.find((quote2) => quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount) && positive(quote2.priceMsats));
26712
26788
  btcRate = getLastKnownBtcRate()?.rate ?? (quoted ? quoted.upfront.amount * 1e11 / quoted.priceMsats : 0);
26713
26789
  }
26714
26790
  const amounts = [];
26791
+ let excludedUpfront = false;
26715
26792
  for (const quote2 of quotes) {
26716
- if (quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount)) amounts.push(quote2.upfront.amount);
26793
+ if (quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount)) {
26794
+ if (upfrontCoveredByCredit) excludedUpfront = true;
26795
+ else amounts.push(quote2.upfront.amount);
26796
+ }
26717
26797
  const rate = quote2.rate;
26718
26798
  if (rate?.per_unit?.currency === "usd" && positive(rate.per_unit.amount) && positive(rate.max_units)) {
26719
26799
  const maximum2 = Number((rate.per_unit.amount * rate.max_units).toPrecision(15));
@@ -26721,7 +26801,7 @@ function autoPayWarnings(quotes, limits, ceiling, btcRate = getLastKnownBtcRate(
26721
26801
  }
26722
26802
  }
26723
26803
  let source = "quote";
26724
- if (!amounts.length && ceiling && typeof ceiling === "object") {
26804
+ if (!amounts.length && !excludedUpfront && ceiling && typeof ceiling === "object") {
26725
26805
  const max = ceiling;
26726
26806
  if (max.currency === "usd" && positive(max.amount)) {
26727
26807
  amounts.push(max.amount);
@@ -28210,8 +28290,6 @@ async function requestWithWarnings(opts, stage) {
28210
28290
  }
28211
28291
  const pricing = providerInfo.capabilities?.[capability]?.pricing;
28212
28292
  const warningLimits = { budget: effectiveBudget, autoPayBelow: effectiveAutoPayBelow };
28213
- const previewWarnings = autoPayWarnings(previewQuotes, warningLimits, pricing?.max ?? providerInfo.pricing?.max, btcRate);
28214
- addOutputWarnings(previewWarnings, opts.human);
28215
28293
  if (signing) {
28216
28294
  const signer = signing;
28217
28295
  const unsignedData = signing.unsignedData;
@@ -28290,6 +28368,15 @@ async function requestWithWarnings(opts, stage) {
28290
28368
  );
28291
28369
  }
28292
28370
  }
28371
+ const previewUpfrontCoveredByCredit = probePlan.mode === "draw";
28372
+ const previewWarnings = autoPayWarnings(
28373
+ previewQuotes,
28374
+ warningLimits,
28375
+ pricing?.max ?? providerInfo.pricing?.max,
28376
+ btcRate,
28377
+ { upfrontCoveredByCredit: previewUpfrontCoveredByCredit }
28378
+ );
28379
+ addOutputWarnings(previewWarnings, opts.human);
28293
28380
  let envelope = { ...envelopeBase, data };
28294
28381
  let jobRequestId = opts.requestId ?? drawRequestId;
28295
28382
  stage.intentReached = true;
@@ -28384,7 +28471,9 @@ async function requestWithWarnings(opts, stage) {
28384
28471
  transport.close();
28385
28472
  throw new DvmError("credit_only_unavailable", "The selected prepaid credit did not cover this submission; no fresh payment was attempted.");
28386
28473
  }
28387
- if (!previewWarnings.length) addOutputWarnings(autoPayWarnings(quotes, warningLimits, void 0, btcRate), opts.human);
28474
+ if (!previewWarnings.length || previewUpfrontCoveredByCredit) {
28475
+ addOutputWarnings(autoPayWarnings(quotes, warningLimits, void 0, btcRate), opts.human);
28476
+ }
28388
28477
  if (autoPayConsent && quotes.length > 0) {
28389
28478
  const pay2 = () => handleAutoPayQuotes(
28390
28479
  transport,
@@ -28464,11 +28553,16 @@ async function requestWithWarnings(opts, stage) {
28464
28553
  recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment);
28465
28554
  if (noStream && !isTerminalJobStatus(receipt.status)) {
28466
28555
  transport.close();
28556
+ const nextAction = pollNextAction(receipt.jobId);
28557
+ if (policy.maxPayments > 1) {
28558
+ const job = guidanceJobArg(receipt.jobId);
28559
+ nextAction.hint += ` Later payment asks are paid only while \`dvm messages ${job} --wait\` stays attached within the saved spending policy, or by running \`dvm pay ${job}\` for each ask. An unanswered payment ask ends the job. Neither \`dvm status ${job}\` nor \`dvm messages ${job} --no-stream\` pays later asks.`;
28560
+ }
28467
28561
  if (opts.human) {
28468
28562
  info(`Job published: ${receipt.jobId}`);
28469
28563
  echoTraceIdHuman();
28470
28564
  if (!isTerminalJobStatus(receipt.status)) {
28471
- printNextActionHuman(pollNextAction(receipt.jobId, "Job submitted, check back for updates"));
28565
+ printNextActionHuman(nextAction);
28472
28566
  }
28473
28567
  } else {
28474
28568
  providerJobJson({
@@ -28487,11 +28581,7 @@ async function requestWithWarnings(opts, stage) {
28487
28581
  // NOT drain here: nothing may stash a feedback notice before a
28488
28582
  // terminal, so there is nothing to carry.
28489
28583
  ...takeCreditNoticeFields(),
28490
- next_action: {
28491
- type: "poll",
28492
- job_id: receipt.jobId,
28493
- hint: "Job submitted, check back for updates"
28494
- }
28584
+ next_action: nextAction
28495
28585
  });
28496
28586
  }
28497
28587
  return;
@@ -31395,10 +31485,12 @@ async function statusWithAccess(jobId, opts, access) {
31395
31485
  markJobTerminal(jobId, terminalStatus, completion2);
31396
31486
  }
31397
31487
  await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
31488
+ const unanswered2 = await readUnansweredPaymentRequest(jobId, terminalStatus, access, transport2, { localOnly: true });
31398
31489
  transport2.close();
31399
31490
  await renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
31400
31491
  receipt: receipt2,
31401
- content
31492
+ content,
31493
+ unanswered: unanswered2
31402
31494
  });
31403
31495
  return;
31404
31496
  }
@@ -31475,13 +31567,19 @@ async function statusWithAccess(jobId, opts, access) {
31475
31567
  if (newCursor !== void 0) updates.messageCursor = newCursor;
31476
31568
  if (Object.keys(updates).length > 0) updateObservedJob(jobId, updates);
31477
31569
  }
31570
+ const unanswered = await readUnansweredPaymentRequest(jobId, result.status, access, transport, {
31571
+ messages: msgs,
31572
+ timeoutMs: timeout,
31573
+ localOnly: result.content_available === false
31574
+ });
31478
31575
  transport.close();
31479
31576
  await renderStatus(jobId, stored, result.status, completion, "provider", nextAction, opts, {
31480
31577
  msgs,
31481
31578
  cursor: newCursor,
31482
31579
  receipt,
31483
31580
  content: result,
31484
- currency
31581
+ currency,
31582
+ unanswered
31485
31583
  });
31486
31584
  }
31487
31585
  function transientReceiptCapture(jobId, response, endpoint, currency) {
@@ -31523,6 +31621,7 @@ async function renderStatus(jobId, stored, jobStatus, completion, source, nextAc
31523
31621
  info(`Status: ${jobStatus}${identifier ? ` [${identifier}]` : ""}`);
31524
31622
  if (completion.message) info(` ${completion.message}`);
31525
31623
  }
31624
+ if (fetched?.unanswered) info(fetched.unanswered.display);
31526
31625
  if (artifacts.hint) info(`\u{1F4CE} ${artifacts.hint}`);
31527
31626
  info(String(content.content_hint));
31528
31627
  if (msgs.length > 0) {
@@ -31557,6 +31656,7 @@ ${msgs.length} new message(s):`);
31557
31656
  ...artifacts.fields,
31558
31657
  ...artifacts.display ? { display: artifacts.display } : {},
31559
31658
  ...completion.message ? { message: completion.message } : {},
31659
+ ...fetched?.unanswered ? { unanswered_payment_request: fetched.unanswered } : {},
31560
31660
  // terminal responses only. On a still-running job "absent" would
31561
31661
  // read as "this DVM doesn't issue receipts" rather than "not yet".
31562
31662
  ...receipt ? await receiptJsonFields(receipt) : {},
@@ -34111,9 +34211,13 @@ function examples(fetcher) {
34111
34211
  async function catchErrors(fn, human, jsonFields) {
34112
34212
  const lifetimeHold = setInterval(() => void 0, 60 * 60 * 1e3);
34113
34213
  try {
34114
- await fn();
34115
- } catch (err) {
34116
- handleError(err, human, jsonFields);
34214
+ await withOutputWarningContext(async () => {
34215
+ try {
34216
+ await fn();
34217
+ } catch (err) {
34218
+ handleError(err, human, jsonFields);
34219
+ }
34220
+ });
34117
34221
  } finally {
34118
34222
  clearInterval(lifetimeHold);
34119
34223
  }
@@ -34801,6 +34905,7 @@ async function walletFund(amount, opts) {
34801
34905
  info(`Quote ID: ${quote2.quote}`);
34802
34906
  if (expiresAt) info(`Invoice expires: ${expiresAt}`);
34803
34907
  info("After payment, run `dvm wallet show` to collect the sats and check the new balance.");
34908
+ info(` \u21B3 ${collectDeadlineHint(expiresAt)}`);
34804
34909
  } else {
34805
34910
  info(
34806
34911
  "Polling for payment every 2s; press Ctrl-C to bail (the quote will be recoverable on next run)."
@@ -34821,6 +34926,7 @@ async function walletFund(amount, opts) {
34821
34926
  qr_image_path: qrImagePath,
34822
34927
  relay: { copy_text: invoice, standalone: true },
34823
34928
  expires_at: expiresAt,
34929
+ ...opts.wait === false ? { collect_before: expiresAt } : {},
34824
34930
  lock_pubkey: wallet.lock_pubkey,
34825
34931
  display: `Pay ${sats} sats to the Lightning invoice to fund ${amountPhrase} into the agent wallet at ${mintUrl} (${selectionPhrase}). Scannable QR at ${qrImagePath}.`,
34826
34932
  ...opts.wait === false ? {
@@ -34829,7 +34935,7 @@ async function walletFund(amount, opts) {
34829
34935
  sweep: summarizeSweep(sweep),
34830
34936
  melt_sweep: summarizeMeltSweep(meltSweep)
34831
34937
  } : {},
34832
- 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."
34938
+ 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. ${collectDeadlineHint(expiresAt)} 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."
34833
34939
  });
34834
34940
  }
34835
34941
  };
@@ -34965,7 +35071,8 @@ async function walletShow(opts) {
34965
35071
  }
34966
35072
  await loadConfiguredMints();
34967
35073
  const sweep = await reconcilePendingMints();
34968
- const expiredMints = describeExpiredMints(sweep);
35074
+ const sweepSummary = summarizeSweep(sweep);
35075
+ const expiredMints = sweepSummary.expired;
34969
35076
  const meltSweep = await reconcilePendingMelts().catch(emptyMeltSweep);
34970
35077
  const inFlightSweepReverted = await sweepStaleInFlightUnderLock();
34971
35078
  const submissionSweep = await sweepPendingSubmissions({ fetchImpl: dvmFetch }).catch(() => ({
@@ -34987,6 +35094,11 @@ async function walletShow(opts) {
34987
35094
  (entry) => entry.state === "unreclaimable"
34988
35095
  );
34989
35096
  const unchecked = new Map(sweep.unchecked.map((u) => [u.quote_id, u]));
35097
+ const pendingNotes = new Map([
35098
+ ...sweepSummary.pending.map((p) => [p.quote_id, p.display]),
35099
+ ...sweepSummary.kept_past_expiry.map((p) => [p.quote_id, p.display]),
35100
+ ...sweepSummary.paid_uncollected.map((p) => [p.quote_id, p.display])
35101
+ ]);
34990
35102
  const inventory = buildDisplayMintInventory(post);
34991
35103
  const mintsToProbe = inventory.map((e) => e.url);
34992
35104
  const sources = new Map(inventory.map((e) => [e.url, e.source]));
@@ -35016,14 +35128,18 @@ async function walletShow(opts) {
35016
35128
  const recovered = sweep.recovered_proofs.reduce((sum, p) => sum + p.amount, 0);
35017
35129
  info(`Recovered ${recovered} sats from ${sweep.recovered_proofs.length} pending mint(s).`);
35018
35130
  }
35019
- for (const collected of summarizeSweep(sweep).collected) {
35131
+ for (const collected of sweepSummary.collected) {
35020
35132
  info(`${collected.display} Added ${collected.sats_collected} sats at ${collected.mint}.`);
35021
35133
  }
35022
35134
  for (const expired of expiredMints) {
35023
35135
  info(
35024
- `Unpaid mint quote expired: ${expired.amount_sats} sats at ${expired.mint} (quote ID ${expired.quote_id}) \u2014 local recovery entry removed.`
35136
+ `Unpaid mint quote expired: ${expired.amount_sats} sats at ${expired.mint} (quote ID ${expired.quote_id}) \u2014 ${describeDropReason(expired.reason)}; local recovery entry removed.`
35025
35137
  );
35026
35138
  }
35139
+ for (const refused of sweepSummary.paid_uncollected) {
35140
+ info(refused.display);
35141
+ info(` \u21B3 ${refused.hint}`);
35142
+ }
35027
35143
  reportUncheckedMints(sweep.unchecked);
35028
35144
  reportUncheckedMints(meltSweep.unchecked);
35029
35145
  if (inFlightSweepReverted > 0) {
@@ -35086,7 +35202,7 @@ async function walletShow(opts) {
35086
35202
  info("");
35087
35203
  info(`Pending mints: ${post.pending_mints.length}`);
35088
35204
  for (const p of post.pending_mints) {
35089
- info(` ${formatPending(p, unchecked.get(p.quote_id))}`);
35205
+ info(` ${formatPending(p, unchecked.get(p.quote_id), pendingNotes.get(p.quote_id))}`);
35090
35206
  }
35091
35207
  }
35092
35208
  if (pendingMelts.length > 0) {
@@ -35144,6 +35260,8 @@ async function walletShow(opts) {
35144
35260
  const totalUsd = railsSnapshot.reduce((sum, r) => sum + (r.json.balance_usd ?? 0), 0);
35145
35261
  const baseHint = pendingMeltSats > 0 ? `${pendingMeltSats} sats are committed to a cash-out the mint hasn't confirmed \u2014 see pending_melts. They stay unspendable until it resolves.` : submissions.at_risk_sats > 0 ? `${submissions.at_risk_sats} sats were paid to a DVM that never confirmed \u2014 see pending_submissions.` : railsSnapshot.length === 0 ? "Fund with: dvm wallet fund <amount> [--rail cashu|tempo]" : cashuSplit ? `${NON_FUNGIBLE_MINT_NOTE} Fund more with: dvm wallet fund <amount> [--rail cashu|tempo]` : "Fund more with: dvm wallet fund <amount> [--rail cashu|tempo]";
35146
35262
  const uncheckedHint = sweep.unchecked.length > 0 ? `${sweep.unchecked.length} pending mint(s) could not be checked against their mint on this call \u2014 see sweep.unchecked for the cause and how long to wait. They keep their pending state; don't fund the same invoice again.` : null;
35263
+ const refusedHint = sweepSummary.paid_uncollected.length > 0 ? `${sweepSummary.paid_uncollected.length} paid invoice(s) could not be collected because the mint refuses to issue after the quote expired \u2014 see sweep.paid_uncollected. Don't pay them again.` : null;
35264
+ const keptHint = sweepSummary.kept_past_expiry.length > 0 ? `${sweepSummary.kept_past_expiry.length} unpaid invoice(s) are past their expiry and still checked for a late payment \u2014 see sweep.kept_past_expiry for when each is removed.` : null;
35147
35265
  const stuckReclaims = skippedReclaimViews.filter((v) => !v.terminal);
35148
35266
  const deadReclaims = skippedReclaimViews.filter((v) => v.terminal);
35149
35267
  const unresolvedHint = unresolvedViews.length > 0 ? `${unresolvedViews.length} paid call(s) need attention: the provider accepted them without a clear job ID \u2014 see accepted_unresolved. Do not pay for them again.` : null;
@@ -35183,10 +35301,10 @@ async function walletShow(opts) {
35183
35301
  // paid calls the provider accepted without a settled job identity,
35184
35302
  // detected on this call or missing their evidence record.
35185
35303
  accepted_unresolved: unresolvedViews,
35186
- sweep: summarizeSweep(sweep),
35304
+ sweep: sweepSummary,
35187
35305
  melt_sweep: summarizeMeltSweep(meltSweep),
35188
35306
  display: railsSnapshot.length === 0 ? "Agent wallet is empty." : `${railsSnapshot.map((r) => r.json.display).join(" \u2014 ")} (~$${totalUsd.toFixed(2)} total)`,
35189
- hint: [uncheckedHint, unresolvedHint, resumedHint, baseHint].filter(Boolean).join(" ")
35307
+ hint: [refusedHint, uncheckedHint, keptHint, unresolvedHint, resumedHint, baseHint].filter(Boolean).join(" ")
35190
35308
  });
35191
35309
  }
35192
35310
  }
@@ -35493,10 +35611,25 @@ function formatFeePpk(fee) {
35493
35611
  if (fee === null) return "- (mint unreachable)";
35494
35612
  return `${fee} ppk`;
35495
35613
  }
35496
- function formatPending(p, unchecked) {
35614
+ function formatPending(p, unchecked, note) {
35497
35615
  const row = `${p.amount_sats} sats at ${p.mint} (quote ${p.quote_id}, requested ${p.requested_at})`;
35498
- return unchecked ? `${row}
35499
- \u21B3 ${uncheckedPendingNote(unchecked)}` : `${row} \u2014 not paid yet; awaiting payment`;
35616
+ if (unchecked) return `${row}
35617
+ \u21B3 ${uncheckedPendingNote(unchecked)}`;
35618
+ return note ? `${row}
35619
+ \u21B3 ${note}` : `${row} \u2014 not paid yet; awaiting payment`;
35620
+ }
35621
+ function collectDeadlineHint(expiresAt) {
35622
+ return expiresAt ? `Collect before ${expiresAt}: a mint can refuse to issue for a paid invoice once its quote has expired.` : "The mint named no expiry for this invoice; collect soon after payment.";
35623
+ }
35624
+ function describeDropReason(reason) {
35625
+ switch (reason) {
35626
+ case "mint_unknown":
35627
+ return "the mint no longer knows this quote";
35628
+ case "mint_expired":
35629
+ return "the mint reports it expired";
35630
+ case "grace_elapsed":
35631
+ return `the mint still reported it unpaid ${GRACE_HOURS} hours after it expired`;
35632
+ }
35500
35633
  }
35501
35634
  function reportUncheckedMints(unchecked) {
35502
35635
  for (const entry of unchecked) {
@@ -35541,13 +35674,45 @@ function summarizeMeltSweep(sweep) {
35541
35674
  unchecked: sweep.unchecked
35542
35675
  };
35543
35676
  }
35544
- function summarizeSweep(sweep) {
35677
+ function summarizeSweep(sweep, nowMs = Date.now()) {
35678
+ const waiting = sweep.outcomes.filter((o) => o.kind === "still_pending");
35545
35679
  return {
35546
- pending: sweep.still_pending.map((entry) => ({
35680
+ pending: waiting.filter((o) => o.past_expiry === void 0).map(({ entry }) => {
35681
+ const requestedAtMs = Date.parse(entry.requested_at);
35682
+ const forget = `dvm wallet forget-quote ${shellQuoteArg(entry.quote_id)}`;
35683
+ return {
35684
+ quote_id: entry.quote_id,
35685
+ mint: entry.mint,
35686
+ amount_sats: entry.amount_sats,
35687
+ requested_at: entry.requested_at,
35688
+ age_seconds: Number.isFinite(requestedAtMs) ? Math.max(0, Math.floor((nowMs - requestedAtMs) / 1e3)) : null,
35689
+ expires_at: entry.expires_at === void 0 ? null : new Date(entry.expires_at * 1e3).toISOString(),
35690
+ display: entry.expires_at === void 0 ? `Mint quote ${entry.quote_id} is not paid yet. The mint named no expiry, so it stays pending until it is paid or you forget it with \`${forget}\`.` : `Mint quote ${entry.quote_id} is not paid yet.`
35691
+ };
35692
+ }),
35693
+ // Unpaid quotes past their expiry. A late payment is still collected while
35694
+ // they are listed here.
35695
+ kept_past_expiry: waiting.flatMap(({ entry, past_expiry }) => {
35696
+ if (past_expiry === void 0) return [];
35697
+ const dropAfter = new Date(past_expiry.drop_after_ms).toISOString();
35698
+ return [{
35699
+ quote_id: entry.quote_id,
35700
+ mint: entry.mint,
35701
+ amount_sats: entry.amount_sats,
35702
+ expired_at: new Date(past_expiry.expired_at_ms).toISOString(),
35703
+ drop_after: dropAfter,
35704
+ display: `Mint quote ${entry.quote_id} expired unpaid. It is kept and checked for a late payment until ${dropAfter}.`,
35705
+ hint: `A payment that arrives late is collected by \`dvm wallet show\` if the mint credits it. Ask for a new invoice instead of paying this one; to stop tracking it now, run \`dvm wallet forget-quote ${shellQuoteArg(entry.quote_id)}\`.`
35706
+ }];
35707
+ }),
35708
+ // Paid, but the mint will not issue ecash for it. Never dropped by a sweep.
35709
+ paid_uncollected: sweep.refused.map((entry) => ({
35547
35710
  quote_id: entry.quote_id,
35548
35711
  mint: entry.mint,
35549
35712
  amount_sats: entry.amount_sats,
35550
- display: `Mint quote ${entry.quote_id} is not paid yet.`
35713
+ reason: "quote_expired",
35714
+ display: `Mint quote ${entry.quote_id} was paid (${entry.amount_sats} sats at ${entry.mint}), but the mint refuses to issue the sats because the quote expired before they were collected.`,
35715
+ hint: `The payment is recorded and \`dvm wallet show\` asks the mint again on every run. Don't pay it again. If the mint keeps refusing, its operator is the one who can release the payment: give them the quote ID. To stop tracking it, run \`dvm wallet forget-quote ${shellQuoteArg(entry.quote_id)} --force --yes\`.`
35551
35716
  })),
35552
35717
  collected: sweep.outcomes.flatMap(
35553
35718
  (outcome) => outcome.kind === "minted" || outcome.kind === "restored" ? [{
@@ -35566,12 +35731,17 @@ function summarizeSweep(sweep) {
35566
35731
  unchecked: sweep.unchecked
35567
35732
  };
35568
35733
  }
35734
+ var GRACE_HOURS = MINT_QUOTE_EXPIRY_GRACE_MS / 36e5;
35569
35735
  function describeExpiredMints(sweep) {
35570
- return sweep.outcomes.filter((outcome) => outcome.kind === "expired").map(({ entry }) => ({
35571
- quote_id: entry.quote_id,
35572
- mint: entry.mint,
35573
- amount_sats: entry.amount_sats
35574
- }));
35736
+ return sweep.outcomes.flatMap(
35737
+ (outcome) => outcome.kind === "expired" ? [{
35738
+ quote_id: outcome.entry.quote_id,
35739
+ mint: outcome.entry.mint,
35740
+ amount_sats: outcome.entry.amount_sats,
35741
+ reason: outcome.reason,
35742
+ display: `Unpaid mint quote ${outcome.entry.quote_id} was removed: ${describeDropReason(outcome.reason)}. A payment made to it now cannot be collected.`
35743
+ }] : []
35744
+ );
35575
35745
  }
35576
35746
  async function writeInvoicePng(invoice, outPath) {
35577
35747
  try {
@@ -39155,8 +39325,136 @@ async function walletSetDefaultRail(rail, opts) {
39155
39325
  }
39156
39326
  }
39157
39327
 
39158
- // src/commands/wallet-submissions.ts
39328
+ // src/commands/wallet-forget-quote.ts
39159
39329
  import { createInterface as createInterface4 } from "readline";
39330
+ async function walletForgetQuote(quoteId, opts) {
39331
+ const wallet = loadAgentWallet();
39332
+ if (!wallet) {
39333
+ throw new DvmError(
39334
+ "wallet_missing",
39335
+ "No agent wallet found.",
39336
+ "Run `dvm wallet init` first to generate a lock keypair."
39337
+ );
39338
+ }
39339
+ const entry = wallet.pending_mints.find((p) => p.quote_id === quoteId);
39340
+ if (!entry) {
39341
+ throw new DvmError(
39342
+ "mint_quote_not_found",
39343
+ `No pending mint quote with ID "${quoteId}".`,
39344
+ "List pending quotes with: dvm wallet show"
39345
+ );
39346
+ }
39347
+ const standing = await quoteStanding(entry);
39348
+ refuseIfCollectable(entry, standing, opts);
39349
+ await confirmForget(entry, standing, opts);
39350
+ await withWalletLock(() => {
39351
+ const fresh = loadAgentWallet() ?? wallet;
39352
+ saveAgentWallet(withoutPendingMint(fresh, quoteId));
39353
+ });
39354
+ const display = `Forgot mint quote ${quoteId} (${entry.amount_sats} sats at ${entry.mint}). ${forgottenConsequence(standing)}`;
39355
+ if (opts.human) {
39356
+ info(display);
39357
+ return;
39358
+ }
39359
+ json({
39360
+ status: "forgotten",
39361
+ quote_id: quoteId,
39362
+ mint: entry.mint,
39363
+ amount_sats: entry.amount_sats,
39364
+ mint_state: standing.state,
39365
+ display,
39366
+ hint: "The quote is gone from the wallet. This cannot be undone."
39367
+ });
39368
+ }
39369
+ async function quoteStanding(entry) {
39370
+ try {
39371
+ const cashuWallet = await getWallet(entry.mint);
39372
+ const quote2 = await cashuWallet.checkMintQuoteBolt11(entry.quote_id);
39373
+ if (quote2.state === sa.PAID) return { state: "paid" };
39374
+ if (quote2.state === sa.ISSUED) return { state: "issued" };
39375
+ if (quote2.state === sa.UNPAID) return { state: "unpaid" };
39376
+ if (quote2.state === "EXPIRED") return { state: "gone" };
39377
+ return { state: "unchecked", cause: "unexpected" };
39378
+ } catch (err) {
39379
+ if (mintQuoteRefusal(err) !== void 0) return { state: "gone" };
39380
+ return { state: "unchecked", cause: classifyMintError(err) };
39381
+ }
39382
+ }
39383
+ function refuseIfCollectable(entry, standing, opts) {
39384
+ if (opts.force) return;
39385
+ const forced = `dvm wallet forget-quote ${shellQuoteArg(entry.quote_id)} --yes --force`;
39386
+ const collectable = standing.state === "paid" || standing.state === "issued" && entry.minting !== void 0;
39387
+ if (collectable) {
39388
+ throw new DvmError(
39389
+ "mint_quote_collectable",
39390
+ `Mint quote ${entry.quote_id} is paid: ${entry.amount_sats} sats at ${entry.mint} are waiting to be collected.`,
39391
+ `Run \`dvm wallet show\` to collect them. Forgetting the quote gives up the only record that can; if the mint keeps refusing to issue and you accept that, add --force: ${forced}`
39392
+ );
39393
+ }
39394
+ if (standing.state === "unchecked") {
39395
+ throw new DvmError(
39396
+ "mint_quote_unchecked",
39397
+ `The mint did not say whether mint quote ${entry.quote_id} has been paid, so forgetting it could lose a payment.`,
39398
+ `Try again once the mint answers. To forget it without knowing, add --force: ${forced}`,
39399
+ { cause: standing.cause, retryable: standing.cause !== "unexpected" }
39400
+ );
39401
+ }
39402
+ }
39403
+ async function confirmForget(entry, standing, opts) {
39404
+ if (opts.yes) return;
39405
+ const consequence = forgetConsequence(standing);
39406
+ if (opts.human && process.stdin.isTTY) {
39407
+ const rl = createInterface4({ input: process.stdin, output: process.stderr });
39408
+ const answer = await new Promise((resolve3) => {
39409
+ rl.question(
39410
+ `Forgetting mint quote ${entry.quote_id} ${consequence}. Type the quote ID to confirm: `,
39411
+ (a) => {
39412
+ rl.close();
39413
+ resolve3(a.trim());
39414
+ }
39415
+ );
39416
+ });
39417
+ if (answer !== entry.quote_id) {
39418
+ throw new DvmError("cancelled", "Forget cancelled.");
39419
+ }
39420
+ return;
39421
+ }
39422
+ throw new DvmError(
39423
+ "confirmation_required",
39424
+ "Pass --yes to forget in non-interactive mode.",
39425
+ `This ${consequence}. Use: dvm wallet forget-quote ${shellQuoteArg(entry.quote_id)} --yes${opts.force ? " --force" : ""}`
39426
+ );
39427
+ }
39428
+ function forgetConsequence(standing) {
39429
+ switch (standing.state) {
39430
+ case "paid":
39431
+ case "issued":
39432
+ return "gives up the only record that can collect a payment the mint has already taken, so this cannot be undone";
39433
+ case "unchecked":
39434
+ return "removes the only record that can collect its payment, without knowing whether it was paid, so this cannot be undone";
39435
+ case "gone":
39436
+ return "clears a quote the mint no longer honors, so nothing collectable is lost, but this cannot be undone";
39437
+ case "unpaid":
39438
+ return "means a payment made to its invoice afterwards cannot be collected, so this cannot be undone";
39439
+ }
39440
+ }
39441
+ function forgottenConsequence(standing) {
39442
+ switch (standing.state) {
39443
+ case "paid":
39444
+ return "The mint reported it as paid; that payment can no longer be collected by this wallet.";
39445
+ case "issued":
39446
+ return "The mint reported it as already issued.";
39447
+ case "unchecked":
39448
+ return "The mint did not say whether it was paid; a payment for it can no longer be collected by this wallet.";
39449
+ case "gone":
39450
+ return "The mint no longer honors it, so nothing collectable was given up.";
39451
+ case "unpaid":
39452
+ return "It was unpaid. Do not pay its invoice now: that payment could not be collected.";
39453
+ }
39454
+ }
39455
+
39456
+ // src/commands/wallet-submissions.ts
39457
+ import { createInterface as createInterface5 } from "readline";
39160
39458
  async function walletSubmissions(opts) {
39161
39459
  if (opts.forget !== void 0) {
39162
39460
  await forgetSubmission(opts.forget, opts);
@@ -39255,7 +39553,7 @@ async function forgetSubmission(requestId, opts) {
39255
39553
  }
39256
39554
  refuseIfReclaimUnsaved(view, opts);
39257
39555
  refuseIfSelfHealing(view, opts);
39258
- await confirmForget(view, opts);
39556
+ await confirmForget2(view, opts);
39259
39557
  await abandonPendingSubmission({ requestId });
39260
39558
  clearReclaimIntent(requestId);
39261
39559
  const abandoned = view.at_risk ? view.amount_sats : 0;
@@ -39296,7 +39594,7 @@ function refuseIfSelfHealing(view, opts) {
39296
39594
  `Forgetting it throws those sats away for good. Leave it alone and it resolves on its own; if you really want it gone, add --force: dvm wallet submissions --forget ${view.request_id} --yes --force`
39297
39595
  );
39298
39596
  }
39299
- async function confirmForget(view, opts) {
39597
+ async function confirmForget2(view, opts) {
39300
39598
  if (opts.yes) return;
39301
39599
  const consequence = !view.at_risk ? `clears the journal entry for ${view.endpoint} (nothing was spent)` : view.state === "reclaimable" || view.state === "reclaim_failed" ? (
39302
39600
  // Worth spelling out: this is the one case where forgetting *costs* the
@@ -39305,7 +39603,7 @@ async function confirmForget(view, opts) {
39305
39603
  `throws away ${view.amount_sats} sats paid to ${view.endpoint} that the wallet can still reclaim by itself, so this cannot be undone`
39306
39604
  ) : view.state === "accepted_unresolved" ? `stops tracking ${view.amount_sats} sats paid to ${view.endpoint} for a call the provider accepted without a clear job ID${view.reclaim_at ? `, including the wallet's claim to take them back after ${view.reclaim_at} if the provider never redeems them` : ""}; the recorded evidence is kept, but this cannot be undone` : view.state === "unreclaimable" ? `clears ${view.amount_sats} sats paid to ${view.endpoint} that are too small to be worth taking back, so nothing recoverable is lost \u2014 but this cannot be undone` : `abandons ${view.amount_sats} sats paid to ${view.endpoint} \u2014 the proofs are locked to the provider with no refund, so this cannot be undone`;
39307
39605
  if (opts.human && process.stdin.isTTY) {
39308
- const rl = createInterface4({ input: process.stdin, output: process.stderr });
39606
+ const rl = createInterface5({ input: process.stdin, output: process.stderr });
39309
39607
  const answer = await new Promise((resolve3) => {
39310
39608
  rl.question(
39311
39609
  `Forgetting request ${view.request_id} ${consequence}. Type the request id to confirm: `,
@@ -40294,7 +40592,7 @@ function buildProgram() {
40294
40592
  ).option("--max-increment <amount>", "Max single payment (millisats or $USD)").option(
40295
40593
  "--max-payments <n>",
40296
40594
  "Max payments to honour per job (default: 5); 0 = free, 1 = typical, 3+ = multi-turn"
40297
- ).option("--output-type <mime>", "Desired output MIME type").option("--no-stream", "Submit and return immediately without streaming").option(
40595
+ ).option("--output-type <mime>", "Desired output MIME type").option("--no-stream", "Submit and return immediately; later asks need dvm messages <job> --wait or dvm pay <job>").option(
40298
40596
  "--auto-pay",
40299
40597
  "Pay without prompting, bounded by --auto-pay-below (else config autoPayThreshold, else 20% of --budget). Unnecessary when --auto-pay-below is set."
40300
40598
  ).option(
@@ -40669,6 +40967,14 @@ Docs:
40669
40967
  ).option("--human", "Human-readable output instead of JSON").action((opts) => {
40670
40968
  return catchErrors(() => walletSubmissions(opts), opts.human);
40671
40969
  });
40970
+ wallet.command("forget-quote <quote-id>").description(
40971
+ "Stop tracking one pending funding invoice, named by its mint quote ID. Asks the mint first and refuses while the invoice is paid or its state is unknown. A payment made after forgetting cannot be collected"
40972
+ ).option("--yes", "Skip the confirmation prompt (required to forget non-interactively)").option(
40973
+ "--force",
40974
+ "Forget a quote the mint reports as paid, or whose state could not be checked. This gives up the only record that can collect that payment"
40975
+ ).option("--human", "Human-readable output instead of JSON").action((quoteId, opts) => {
40976
+ return catchErrors(() => walletForgetQuote(quoteId, opts), opts.human);
40977
+ });
40672
40978
  wallet.command("recover-submission <request-id>").description(
40673
40979
  "Recover one strict Cashu request by exact UUID and request-binding fingerprint. Holds the wallet lock and never sweeps unrelated pending state"
40674
40980
  ).requiredOption(
@@ -13,7 +13,7 @@ import {
13
13
  recordFloatSpend,
14
14
  resolveFundMint,
15
15
  sweepPendingMints
16
- } from "./chunk-J3HYNDMI.js";
16
+ } from "./chunk-NCX4JVLU.js";
17
17
  import "./chunk-MM646MFM.js";
18
18
  import "./chunk-NKD4NEUF.js";
19
19
  import {
@@ -22,7 +22,7 @@ import {
22
22
  import {
23
23
  info,
24
24
  tryResolveBtcUsdRate
25
- } from "./chunk-DJDONOMG.js";
25
+ } from "./chunk-7HJ5ZR3D.js";
26
26
  import {
27
27
  effectiveFundingMint,
28
28
  effectiveMints,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dvmkit/dvm-cli",
3
- "version": "0.19.0",
3
+ "version": "0.19.1",
4
4
  "description": "Command-line client and agent skill for Digital Vending Machines: pay-per-use HTTPS services AI agents can find, pay, and call with no account or API key",
5
5
  "author": "DVM Technologies Ltd",
6
6
  "keywords": [
@@ -29,7 +29,7 @@ For metered DVMs, size `--auto-pay-below` for the largest authorized charge (the
29
29
 
30
30
  ## Run and deliver
31
31
 
32
- Submit once with `dvm request`, preserving the approved input and spending limits. Save the returned request and job identifiers. A long job can use `--no-stream` and be followed through its recorded job.
32
+ Submit once with `dvm request`, preserving the approved input and spending limits. Save the returned request and job identifiers. `--no-stream` returns immediately; it leaves no process attached to pay later asks, even with prepaid credit, a budget, and `--max-payments` greater than one. Keep `dvm messages <job-id> --wait` running to pay within the saved policy, or run `dvm pay <job-id>` for each ask. An unanswered ask ends the job; `dvm status` and `dvm messages --no-stream` pay nothing. Do not promise the full planned duration merely because submission succeeded.
33
33
 
34
34
  Successful upfront Cashu fallback includes optional `mint_attempts`: an array of `{ mint, reason, message }` for earlier failed candidates in the order tried. Reasons are `unreachable`, `keys_unavailable`, `swap_disabled`, `fee_cap_exceeded`, `insufficient_balance`, `no_eligible_mint`, or `swap_rejected`. Messages are bounded CLI-authored explanations, never raw dependency errors; mint URLs are redacted and limited to 2,048 characters. These observations explain why the selected `mint` was used; they do not mark the request failed or represent extra payments. The field is omitted when no candidate failed, including reserve-direct success. Attempts are temporary diagnostics and are not persisted for later status or recovery commands. Existing failure diagnostics remain unchanged.
35
35
 
@@ -48,6 +48,8 @@ Answer with `dvm message <job-id> "<answer>" --type response --prompt-id <prompt
48
48
 
49
49
  When a respond or pay action includes `expires_at_ms` (Unix milliseconds), relay the deadline in its `display` to the human: the provider cancels the job if they do not answer or pay by then.
50
50
 
51
+ Terminal status and messages may include `unanswered_payment_request` when retained evidence indicates the last charge expired unanswered around provider cancellation. Relay its qualified `display`, which names the unpaid ask and explains that only earlier paid charges were taken. Its `seq`, `reason`, amount and `expires_at_ms` identify the ask; the provider's message remains separate evidence. Cancellation timestamps have one-second precision, so an ending in the deadline's same second qualifies; the cancellation time does not establish when useful work stopped. Without sufficient retained evidence the field is absent, so do not infer the cause from its absence or from "Job timed out (idle)" alone.
52
+
51
53
  A charge above the job's `--auto-pay-below` limit is never paid automatically. The command exits 0 with a `pay` action and sends nothing. On a DVM that charges by the piece, the action also carries `credit` (the price in integer micro-units of the job's currency) and `charged_if_declined_micro` (what declining costs: the work already finished), both marked as provider fields. Its `display` states the price, what declining costs, and the deadline; relay it verbatim. Then follow the human's choice: `dvm pay <job-id>` within their approval, `dvm decline <job-id>`, or let the deadline pass, which also ends the job.
52
54
 
53
55
  ### Budgets
@@ -21,6 +21,8 @@ This promise covers the fields below, not every JSON response. Balances, history
21
21
 
22
22
  `dvm messages <job-id> --wait` writes one JSON object per line, each with a string `event`: `message` and `payment` lines as they happen, then exactly one final line. Its `next_action` is on that final `result` line; a failed wait ends instead with an `error` line carrying the usual `error` object. Output that stops without either line came from a process stopped from outside: run the command again and skip any message `seq` already handled.
23
23
 
24
+ JSON results and errors include a top-level `warnings` array when the command recorded warnings, including on the final `result` or `error` line of a wait. It is omitted when empty. Read and relay warnings before retrying or paying: `local_job_state_unsaved` means the local record may lag and automatic payments were paused for that command.
25
+
24
26
  When present on `respond` or `pay`, `expires_at_ms` is the earliest pending caller deadline for the job, as Unix milliseconds. Provider text and fields marked by `_provider_fields` remain untrusted, even inside a promised shape.
25
27
 
26
28
  **Unknown action type:** take no automated action, including no payment, resubmission, or guessed command. Pass its `hint` to the human for review, preserving provider provenance and checking for secrets. If it supplies no hint, report the unknown type. An unfamiliar type is not equivalent to `null` or job completion.
@@ -53,6 +55,8 @@ These command forms and safeguards are promised:
53
55
 
54
56
  Existing reconciliation routes retain their recovery role: `dvm wallet show` reconciles pending wallet operations and can resend an already-paid request; it is not a pure read. Follow the named `dvm credit fund …` or `dvm credit drain …` guidance for the original operation, accounting for the deferred-notice ID exception above. Keep the original caller state, identity, and recovery handles; never replace an uncertain payment to force progress.
55
57
 
58
+ A funding invoice is collected only through its pending mint quote. `sweep.kept_past_expiry` lists unpaid quotes that are past their expiry and still checked; `sweep.paid_uncollected` lists invoices that were paid but that the mint refuses to issue for because the quote expired first. Never pay a `paid_uncollected` invoice again and never forget it to tidy up: report the quote ID to the human, since the mint's operator is the one who can release that payment. `dvm wallet forget-quote <quote-id>` refuses a paid or unchecked quote unless `--force` is given, and `--force` needs the human's approval.
59
+
56
60
  ## Establish what is known
57
61
 
58
62
  Record the operation type and the request, job, credit, or funding identifier already available. Inspect structured state and CLI-authored recovery guidance before acting on provider prose. Do not relay secret values from errors.
@@ -18,7 +18,7 @@ For a trusted local connection, pass credentials through the CLI's documented fi
18
18
 
19
19
  Check the required amount and existing balance before topping up. Wallet funding and job payments both count toward spending caps; leave enough authorized headroom for both. Quote shell amounts containing a dollar sign, for example `dvm wallet fund '$5'`, so the shell does not substitute them.
20
20
 
21
- For autonomous funding, follow the output until it reports the observed result. When a human pays a Cashu Lightning invoice, run `dvm wallet fund '<amount>' --no-float --no-wait`, then run the returned `next_step` (`dvm wallet show`) after payment to collect it. An existing unpaid-quote warning names an earlier invoice: avoid asking the human to pay both for the same top-up.
21
+ For autonomous funding, follow the output until it reports the observed result. When a human pays a Cashu Lightning invoice, run `dvm wallet fund '<amount>' --no-float --no-wait`, then run the returned `next_step` (`dvm wallet show`) after payment to collect it. An existing unpaid-quote warning names an earlier invoice: avoid asking the human to pay both for the same top-up. Collect before the returned `collect_before` time: a mint can refuse to issue for a paid invoice once its quote has expired. `dvm wallet show` keeps an unpaid invoice past its expiry and keeps checking it for a late payment for 24 hours (`sweep.kept_past_expiry`); it removes one only when the mint no longer honors it (`sweep.expired`). An invoice whose mint named no expiry stays pending until it is paid or you run `dvm wallet forget-quote <quote-id> --yes`. Forget a quote only when you are sure its invoice will not be paid: a payment made afterwards cannot be collected.
22
22
 
23
23
  For human-assisted funding, show the invoice as soon as the CLI prints it; never wait for the funding command to finish. Send:
24
24