@dvmkit/dvm-cli 0.15.1 → 0.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dvm.js CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  captureTransportReceipt,
33
33
  clearAskPaymentBlocks,
34
34
  clearPaymentRequestInFlight,
35
+ clearReclaimIntent,
35
36
  commitAgentSpend,
36
37
  completedCreditHistory,
37
38
  completedDrainMatches,
@@ -55,6 +56,7 @@ import {
55
56
  extractBuilderHandle,
56
57
  fetchMissingJobReceipt,
57
58
  fetchTrustAnchor,
59
+ finalizeLandedReclaims,
58
60
  finishBookedSubmission,
59
61
  floatBudgetJson,
60
62
  floatPaymentDisplay,
@@ -81,6 +83,7 @@ import {
81
83
  jobDrawFundings,
82
84
  jobIdentityHeaderValue,
83
85
  jobSettlement,
86
+ journalFile,
84
87
  journalMarkerFor,
85
88
  listPendingCardFundings,
86
89
  listSubmissionEvidence,
@@ -91,6 +94,7 @@ import {
91
94
  loadJob,
92
95
  loadLedger,
93
96
  loadMessages,
97
+ loadReclaimIntent,
94
98
  loadSubmissionEvidence,
95
99
  markJobTerminal,
96
100
  markPaymentRequestAnswered,
@@ -136,12 +140,14 @@ import {
136
140
  receiptPieceContext,
137
141
  receiptSettlement,
138
142
  receiptTrustFields,
143
+ reclaimIntentIds,
139
144
  reconcileInFlightPaymentRequest,
140
145
  reconcilePaymentRequestHistory,
141
146
  recordCallerMessageHash,
142
147
  recordFloatSpend,
143
148
  recordIdentityFailure,
144
149
  recordLocalJobCollision,
150
+ recordReclaimIntent,
145
151
  recordSpend,
146
152
  recordSpendOnce,
147
153
  recordSubmissionEvidence,
@@ -161,6 +167,7 @@ import {
161
167
  revertInFlight,
162
168
  routerConflictObservation,
163
169
  sameEndpoint,
170
+ saveAcceptedJob,
164
171
  saveFavorite,
165
172
  saveJob,
166
173
  saveLedger,
@@ -183,13 +190,14 @@ import {
183
190
  unrecordedFloatBudgetWarning,
184
191
  unresendablePaymentHint,
185
192
  updateJob,
193
+ updateObservedJob,
186
194
  walletHistory,
187
195
  warnInvalidJobIdentityHeader,
188
196
  withAcceptedUnresolved,
189
197
  withIdentityRecovery,
190
198
  withJobTokenRedaction,
191
199
  withRequestResultRecovery
192
- } from "./chunk-BFYZO3BV.js";
200
+ } from "./chunk-DZHEYRS2.js";
193
201
  import {
194
202
  connectedTempoAccount,
195
203
  generateTempoKey,
@@ -204,6 +212,7 @@ import {
204
212
  formatAmountBestEffort,
205
213
  formatPaymentAmount,
206
214
  getOutputTraceId,
215
+ hasUnsavedJobState,
207
216
  info,
208
217
  json,
209
218
  monetaryJson,
@@ -215,7 +224,7 @@ import {
215
224
  tryResolveBtcUsdRate,
216
225
  tryX402Payment,
217
226
  withOutputWarnings
218
- } from "./chunk-5SHB3MZ7.js";
227
+ } from "./chunk-F45ETHDP.js";
219
228
  import {
220
229
  assertSupportedX402Network,
221
230
  connectedX402Payer,
@@ -432,6 +441,7 @@ import {
432
441
  resolveTempoAsset,
433
442
  resolveTempoNetwork,
434
443
  resolveX402ChannelRpc,
444
+ restoreProofsFromOutputs,
435
445
  retryMintQuoteOperation,
436
446
  sa,
437
447
  saveAgentWallet,
@@ -444,6 +454,7 @@ import {
444
454
  signedRequestDomain,
445
455
  sn,
446
456
  swapFeeForProofs,
457
+ te,
447
458
  tempoChannelControlledBy,
448
459
  tempoCredentialAmountMicro,
449
460
  tempoSessionChallenge,
@@ -9891,10 +9902,20 @@ function requestRecoveryPath(route, requestId) {
9891
9902
  // src/lib/wallet-agent/recovery-submissions.ts
9892
9903
  var RESUME_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
9893
9904
  var RESUME_MAX_ATTEMPTS = 5;
9905
+ var RECLAIM_IN_FLIGHT_MS = 2 * 6e4;
9906
+ var RECLAIM_UNSAVED_REASON = "the reclaim swap may have gone through at the mint but its result is not saved to the wallet yet; run `dvm wallet show` to recover it";
9894
9907
  async function sweepPendingSubmissions(opts = {}) {
9908
+ const writeFailures = [];
9909
+ const result = (outcomes2) => writeFailures.length > 0 ? { outcomes: outcomes2, writeFailures } : { outcomes: outcomes2 };
9910
+ const failed = (requestId, stage, error) => writeFailures.push({ requestId, stage, message: errorText(error) });
9911
+ try {
9912
+ finalizeLandedReclaims();
9913
+ } catch (error) {
9914
+ failed("", "verdict_journal", error);
9915
+ }
9895
9916
  const wallet = loadAgentWallet();
9896
9917
  if (!wallet || wallet.pending_submissions.length === 0) {
9897
- return { outcomes: [] };
9918
+ return result([]);
9898
9919
  }
9899
9920
  const deps = {
9900
9921
  httpPost: opts.httpPost ?? createDefaultHttpPost(opts.fetchImpl ?? dvmFetch),
@@ -9910,31 +9931,79 @@ async function sweepPendingSubmissions(opts = {}) {
9910
9931
  const now = opts.now ?? (() => Date.now());
9911
9932
  const { entries, unreadable } = await reconcileEvidenceMarkers(wallet);
9912
9933
  const outcomes = [];
9934
+ const handled = /* @__PURE__ */ new Set();
9913
9935
  for (const entry of entries) {
9914
- outcomes.push(await resolveEntry(entry, deps, now(), unreadable.has(entry.request_id)));
9936
+ const outcome = await resolveEntry(entry, deps, now(), unreadable.has(entry.request_id));
9937
+ if (outcome.kind !== "reclaimed") {
9938
+ outcomes.push(outcome);
9939
+ continue;
9940
+ }
9941
+ const unsaved = await commitReclaim(outcome, wallet, now, failed);
9942
+ const reported = unsaved ?? outcome;
9943
+ handled.add(reported);
9944
+ outcomes.push(reported);
9915
9945
  }
9916
- if (outcomes.some(mutatesWallet)) {
9946
+ const rest = outcomes.filter((outcome) => !handled.has(outcome) && mutatesWallet(outcome));
9947
+ if (rest.length > 0) {
9917
9948
  try {
9918
- recordSubmissionVerdicts(outcomes.flatMap(verdictFor));
9919
- } catch {
9949
+ recordSubmissionVerdicts(rest.flatMap(verdictFor));
9950
+ } catch (error) {
9951
+ for (const outcome of rest) failed(outcome.entry.request_id, "verdict_journal", error);
9952
+ }
9953
+ try {
9954
+ await withWalletLock(() => {
9955
+ const fresh = loadAgentWallet() ?? wallet;
9956
+ const next = rest.reduce((acc, outcome) => applyOutcome(acc, outcome, now), fresh);
9957
+ saveAgentWallet(next);
9958
+ });
9959
+ await applySubmissionVerdicts().catch((error) => failed("", "verdict_apply", error));
9960
+ } catch (error) {
9961
+ for (const outcome of rest) failed(outcome.entry.request_id, "wallet_save", error);
9920
9962
  }
9963
+ }
9964
+ return result(outcomes);
9965
+ }
9966
+ async function commitReclaim(outcome, wallet, now, failed) {
9967
+ const requestId = outcome.entry.request_id;
9968
+ let alreadySaved = false;
9969
+ try {
9921
9970
  await withWalletLock(() => {
9922
9971
  const fresh = loadAgentWallet() ?? wallet;
9923
- const next = outcomes.reduce(
9924
- (acc, outcome) => applyOutcome(acc, outcome, now),
9925
- fresh
9926
- );
9927
- saveAgentWallet(next);
9972
+ if (!fresh.pending_submissions.some((s) => s.request_id === requestId)) {
9973
+ alreadySaved = true;
9974
+ return;
9975
+ }
9976
+ saveAgentWallet(applyOutcome(fresh, outcome, now));
9928
9977
  });
9929
- await applySubmissionVerdicts().catch(() => void 0);
9978
+ } catch (error) {
9979
+ failed(requestId, "wallet_save", error);
9980
+ return { kind: "reclaim_skipped", entry: outcome.entry, reason: RECLAIM_UNSAVED_REASON, terminal: false };
9930
9981
  }
9931
- return { outcomes };
9982
+ if (alreadySaved) {
9983
+ return {
9984
+ kind: "reclaim_skipped",
9985
+ entry: outcome.entry,
9986
+ reason: "another sweep already saved this reclaim",
9987
+ terminal: false
9988
+ };
9989
+ }
9990
+ try {
9991
+ finalizeLandedReclaims();
9992
+ } catch (error) {
9993
+ failed(requestId, "verdict_journal", error);
9994
+ return null;
9995
+ }
9996
+ await applySubmissionVerdicts().catch((error) => failed(requestId, "verdict_apply", error));
9997
+ return null;
9932
9998
  }
9933
9999
  function verdictFor(outcome) {
9934
10000
  const reserve = outcome.entry.output_proofs.some((proof) => proof.reserved_for !== void 0) ? { reserve: true } : {};
9935
10001
  if (outcome.kind === "already_accepted") return [{ requestId: outcome.entry.request_id, verdict: "spent", ...reserve }];
9936
10002
  if (outcome.kind !== "reclaimed") return [];
9937
- return [outcome.spent_sats > 0 ? { requestId: outcome.entry.request_id, verdict: "partly_spent", spentSats: outcome.spent_sats, amountSats: outcome.entry.amount_sats } : { requestId: outcome.entry.request_id, verdict: "reclaimed" }];
10003
+ return [reclaimVerdict(outcome.entry, outcome.spent_sats)];
10004
+ }
10005
+ function reclaimVerdict(entry, spentSats) {
10006
+ return spentSats > 0 ? { requestId: entry.request_id, verdict: "partly_spent", spentSats, amountSats: entry.amount_sats } : { requestId: entry.request_id, verdict: "reclaimed" };
9938
10007
  }
9939
10008
  async function recoverPendingSubmission(opts) {
9940
10009
  if (!UUID_V4_RE.test(opts.requestId))
@@ -10205,6 +10274,11 @@ async function reclaimEntry(entry, deps) {
10205
10274
  } catch (err) {
10206
10275
  return skipped(errorText(err));
10207
10276
  }
10277
+ const intent = loadReclaimIntent(entry.request_id);
10278
+ if (intent) {
10279
+ const recovered = await recoverReclaimIntent(entry, intent, cashuWallet, deps.lockPubkey);
10280
+ if (recovered) return recovered;
10281
+ }
10208
10282
  let grouped;
10209
10283
  try {
10210
10284
  grouped = await cashuWallet.groupProofsByState(toCashuProofs(entry.output_proofs));
@@ -10225,8 +10299,9 @@ async function reclaimEntry(entry, deps) {
10225
10299
  return skipped("the mint still reports some of these proofs in flight");
10226
10300
  }
10227
10301
  const totalSats = unspent.reduce((sum, p) => sum + p.amount, 0);
10302
+ const spentSats = spent.reduce((sum, p) => sum + p.amount, 0);
10228
10303
  const inputs = toCashuProofs(unspent);
10229
- let outputs;
10304
+ let preview;
10230
10305
  try {
10231
10306
  const swapFeeSats = swapFeeForProofs(cashuWallet, inputs);
10232
10307
  const allowance = reclaimFeeAllowance(entry);
@@ -10246,20 +10321,88 @@ async function reclaimEntry(entry, deps) {
10246
10321
  true
10247
10322
  );
10248
10323
  }
10249
- const result = await cashuWallet.ops.send(reclaimSats, inputs).privkey(refundPrivkey).asP2PK({ pubkey: deps.lockPubkey }).run();
10250
- outputs = result.send;
10324
+ preview = await cashuWallet.ops.send(reclaimSats, inputs).privkey(refundPrivkey).asP2PK({ pubkey: deps.lockPubkey }).prepare();
10325
+ } catch (err) {
10326
+ const diagnostic = missingDleqRecoveryDiagnostic(inputs, err);
10327
+ return skipped(diagnostic ?? errorText(err), diagnostic !== null);
10328
+ }
10329
+ const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10330
+ try {
10331
+ recordReclaimIntent({
10332
+ requestId: entry.request_id,
10333
+ mint: entry.mint,
10334
+ keysetId: preview.keysetId,
10335
+ lockPubkey: deps.lockPubkey,
10336
+ outputs: serializeOutputData(preview.sendOutputs ?? []),
10337
+ inputSecrets: unspent.map((p) => p.secret),
10338
+ spentSats,
10339
+ verdict: reclaimVerdict(entry, spentSats),
10340
+ createdAt
10341
+ });
10342
+ } catch (err) {
10343
+ return skipped(`could not record the reclaim before sending it to the mint, so nothing was swapped: ${errorText(err)}`);
10344
+ }
10345
+ let outputs;
10346
+ try {
10347
+ outputs = (await cashuWallet.completeSwap(preview, refundPrivkey)).send;
10251
10348
  } catch (err) {
10252
10349
  const diagnostic = missingDleqRecoveryDiagnostic(inputs, err);
10350
+ if (err instanceof te || diagnostic !== null) discardReclaimIntent(entry.request_id, createdAt);
10253
10351
  return skipped(diagnostic ?? errorText(err), diagnostic !== null);
10254
10352
  }
10353
+ return reclaimedOutcome(entry, outputs, deps.lockPubkey, spentSats);
10354
+ }
10355
+ function reclaimedOutcome(entry, outputs, lockPubkey, spentSats) {
10255
10356
  return {
10256
10357
  kind: "reclaimed",
10257
10358
  entry,
10258
- outputs: outputs.map((p) => toAgentProof(p, entry.mint, deps.lockPubkey)),
10359
+ outputs: outputs.map((p) => toAgentProof(p, entry.mint, lockPubkey)),
10259
10360
  reclaimed_sats: outputs.reduce((sum, p) => sum + A.from(p.amount).toNumber(), 0),
10260
- spent_sats: spent.reduce((sum, p) => sum + p.amount, 0)
10361
+ spent_sats: spentSats
10261
10362
  };
10262
10363
  }
10364
+ function discardReclaimIntent(requestId, createdAt) {
10365
+ try {
10366
+ clearReclaimIntent(requestId, createdAt);
10367
+ } catch {
10368
+ }
10369
+ }
10370
+ async function recoverReclaimIntent(entry, intent, cashuWallet, lockPubkey) {
10371
+ const skipped = (reason) => ({
10372
+ kind: "reclaim_skipped",
10373
+ entry,
10374
+ reason,
10375
+ terminal: false
10376
+ });
10377
+ let restored = [];
10378
+ let restoreError;
10379
+ try {
10380
+ restored = await restoreProofsFromOutputs(cashuWallet, intent.keysetId, intent.outputs);
10381
+ } catch (err) {
10382
+ restoreError = errorText(err);
10383
+ }
10384
+ if (restored.length > 0) {
10385
+ return restored.length === intent.outputs.length ? reclaimedOutcome(entry, restored, lockPubkey, intent.spentSats) : skipped("the mint restored only part of the reclaim swap's outputs");
10386
+ }
10387
+ const secrets = new Set(intent.inputSecrets);
10388
+ try {
10389
+ const states = await cashuWallet.groupProofsByState(
10390
+ toCashuProofs(entry.output_proofs.filter((proof) => secrets.has(proof.secret)))
10391
+ );
10392
+ if (states.pending.length === 0 && (states.spent.length === 0 || restoreError === void 0)) {
10393
+ if (states.spent.length === 0 && Date.now() - Date.parse(intent.createdAt) < RECLAIM_IN_FLIGHT_MS) {
10394
+ return skipped("another reclaim of this payment may still be in flight; the next sweep checks again");
10395
+ }
10396
+ clearReclaimIntent(entry.request_id, intent.createdAt);
10397
+ return null;
10398
+ }
10399
+ } catch (err) {
10400
+ return skipped(errorText(err));
10401
+ }
10402
+ return skipped(
10403
+ `the reclaim swap spent these proofs at the mint but its outputs cannot be restored yet${restoreError ? ` (${restoreError})` : ""}; the next sweep tries again`
10404
+ );
10405
+ }
10263
10406
  function reclaimFeeAllowance(entry) {
10264
10407
  const maxSats = entry.max_cashu_fee_sats;
10265
10408
  const contextMaxSats = entry.context?.max_cashu_fee_sats;
@@ -11040,9 +11183,9 @@ function configuredTempoNetwork() {
11040
11183
  if (tempo?.method !== "tempo") return null;
11041
11184
  return parseTempoNetwork(tempo.network, "config.tempo.network") ?? "mainnet";
11042
11185
  }
11043
- function assertTempoChallengeNetwork(challenges, network, intents) {
11186
+ function assertTempoChallengeNetwork(challenges, network, intents2) {
11044
11187
  const expected = resolveTempoNetwork(network);
11045
- const acceptedIntents = intents ? new Set(intents) : null;
11188
+ const acceptedIntents = intents2 ? new Set(intents2) : null;
11046
11189
  for (const challenge of challenges) {
11047
11190
  if (challenge.method !== "tempo" || acceptedIntents && !acceptedIntents.has(challenge.intent))
11048
11191
  continue;
@@ -11062,9 +11205,9 @@ function assertTempoChallengeNetwork(challenges, network, intents) {
11062
11205
  );
11063
11206
  }
11064
11207
  }
11065
- function assertConfiguredTempoChallengeNetwork(challenges, intents) {
11208
+ function assertConfiguredTempoChallengeNetwork(challenges, intents2) {
11066
11209
  const network = configuredTempoNetwork();
11067
- if (network) assertTempoChallengeNetwork(challenges, network, intents);
11210
+ if (network) assertTempoChallengeNetwork(challenges, network, intents2);
11068
11211
  }
11069
11212
  function assertTempoChannelNetwork(association, account) {
11070
11213
  const network = tempoAccountNetwork(account);
@@ -11463,7 +11606,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11463
11606
  }
11464
11607
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11465
11608
  const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
11466
- const { tryX402Payment: tryX402Payment2 } = await import("./client-YIHI4AIC.js");
11609
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-NBC2IDA2.js");
11467
11610
  const wallet = loadX402Wallet2();
11468
11611
  if (wallet) {
11469
11612
  let proof;
@@ -11910,7 +12053,7 @@ async function claimInboundPayments(jobId, messages2) {
11910
12053
  if (claimedMsats > 0) {
11911
12054
  claimedSeqs.add(msg.seq);
11912
12055
  claimedAmounts[msg.seq] = claimedMsats;
11913
- updateJob(jobId, { claimedPaymentSeqs: [...claimedSeqs], claimedPaymentAmountsMsats: claimedAmounts });
12056
+ updateObservedJob(jobId, { claimedPaymentSeqs: [...claimedSeqs], claimedPaymentAmountsMsats: claimedAmounts });
11914
12057
  results.push({
11915
12058
  seq: msg.seq,
11916
12059
  amount_msats: claimedMsats,
@@ -11994,6 +12137,13 @@ function withRefundNextAction(jobId, action, claims) {
11994
12137
  // src/lib/stream-loop.ts
11995
12138
  async function streamLoop(opts) {
11996
12139
  const { jobId, transport, provider } = opts;
12140
+ if (hasUnsavedJobState()) return {
12141
+ messages: [],
12142
+ autoPayments: [],
12143
+ refunds: [],
12144
+ cursor: opts.afterSeq,
12145
+ nextAction: pollNextAction(jobId, "Local state may lag; refresh this job before another payment.")
12146
+ };
11997
12147
  const persistLocalState = opts.persistLocalState !== false;
11998
12148
  const policy = persistLocalState ? opts.policy : void 0;
11999
12149
  const allMessages = [];
@@ -12057,7 +12207,7 @@ async function streamLoop(opts) {
12057
12207
  }
12058
12208
  try {
12059
12209
  for (; ; ) {
12060
- if (deadline !== void 0 && Date.now() >= deadline) break;
12210
+ if (hasUnsavedJobState() || deadline !== void 0 && Date.now() >= deadline) break;
12061
12211
  const streamFn = transport.stream?.bind(transport);
12062
12212
  let batchMessages;
12063
12213
  if (streamFn) {
@@ -12096,9 +12246,11 @@ async function streamLoop(opts) {
12096
12246
  messageAppendSession ??= createMessageAppendSession(jobId);
12097
12247
  messageAppendSession.append(batchMessages);
12098
12248
  await settleRecordedPayments(jobId);
12249
+ if (hasUnsavedJobState()) break;
12099
12250
  }
12100
12251
  if (persistLocalState) {
12101
12252
  refunds.push(...await claimInboundPayments(jobId, batchMessages));
12253
+ if (hasUnsavedJobState()) break;
12102
12254
  }
12103
12255
  justAutoPaid = false;
12104
12256
  if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
@@ -12175,7 +12327,7 @@ async function streamLoop(opts) {
12175
12327
  } finally {
12176
12328
  if (timer) clearTimeout(timer);
12177
12329
  }
12178
- if (justAutoPaid) {
12330
+ if (justAutoPaid && !hasUnsavedJobState()) {
12179
12331
  const pollOptions = nextPollOptions();
12180
12332
  let recheck = [];
12181
12333
  try {
@@ -12220,6 +12372,8 @@ async function streamLoop(opts) {
12220
12372
  heldJob,
12221
12373
  lastYield?.type === "payment-request" ? lastYield.seq : void 0
12222
12374
  ));
12375
+ if (hasUnsavedJobState() && !terminal)
12376
+ nextAction = pollNextAction(jobId, "Local state may lag; refresh this job before another payment.");
12223
12377
  return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
12224
12378
  }
12225
12379
  function isMessagePollTimeout(err) {
@@ -12282,7 +12436,7 @@ function persistStreamOutcome(outcome) {
12282
12436
  });
12283
12437
  return completion;
12284
12438
  }
12285
- updateJob(jobId, { messageCursor: cursor });
12439
+ updateObservedJob(jobId, { messageCursor: cursor });
12286
12440
  return void 0;
12287
12441
  }
12288
12442
  function streamTerminalStatus(messages2, context = {}) {
@@ -13409,7 +13563,7 @@ function parseStructuredError(body) {
13409
13563
  if (err && typeof err === "object" && !Array.isArray(err)) {
13410
13564
  const e = err;
13411
13565
  if (typeof e.code !== "string") return null;
13412
- return buildStructuredError(e.code, e);
13566
+ return buildStructuredError(e.code, e, parsed);
13413
13567
  }
13414
13568
  if (typeof err !== "string") return null;
13415
13569
  if (err === "invalid_input" || err === "invalid_quote_data") {
@@ -13425,7 +13579,7 @@ function jobCredentialError(status2, body) {
13425
13579
  if (status2 !== 401) return null;
13426
13580
  return parseStructuredError(body);
13427
13581
  }
13428
- function buildStructuredError(code, fields) {
13582
+ function buildStructuredError(code, fields, envelope = fields) {
13429
13583
  const display = typeof fields.display === "string" ? fields.display : void 0;
13430
13584
  const providerMessage = typeof fields.message === "string" ? fields.message : void 0;
13431
13585
  const message2 = providerMessage ?? display ?? "The provider returned an error without explanatory prose.";
@@ -13433,10 +13587,10 @@ function buildStructuredError(code, fields) {
13433
13587
  const data = {};
13434
13588
  if (display !== void 0) data.display = display;
13435
13589
  if (typeof fields.retryable === "boolean") data.retryable = fields.retryable;
13436
- if (fields.status === "unknown") data.status = fields.status;
13590
+ if (fields.status === "unknown" || envelope.status === "unknown") data.status = "unknown";
13437
13591
  if (typeof fields.request_id === "string") data.request_id = fields.request_id;
13438
13592
  if (fields.server_acceptance === "absent") data.server_acceptance = fields.server_acceptance;
13439
- if (fields.payment_state === "unknown") data.payment_state = fields.payment_state;
13593
+ if (fields.payment_state === "unknown" || envelope.payment_state === "unknown") data.payment_state = "unknown";
13440
13594
  const detectedSources = providerProseSources(fields, data);
13441
13595
  const proseSources = display !== void 0 && providerMessage === void 0 ? { ...detectedSources, message: "provider" } : detectedSources;
13442
13596
  return new DvmError(
@@ -13502,7 +13656,7 @@ function isReceipt402(code) {
13502
13656
  function buildPaymentError(errorBody) {
13503
13657
  if (typeof errorBody.error === "string") return buildStructuredError(errorBody.error, errorBody);
13504
13658
  const nested = errorBody.error && typeof errorBody.error === "object" && !Array.isArray(errorBody.error) ? errorBody.error : void 0;
13505
- if (typeof nested?.code === "string") return buildStructuredError(nested.code, nested);
13659
+ if (typeof nested?.code === "string") return buildStructuredError(nested.code, nested, errorBody);
13506
13660
  const error = buildStructuredError("payment_insufficient", errorBody);
13507
13661
  error.data = { ...error.data, code_source: "inferred" };
13508
13662
  return error;
@@ -13932,6 +14086,55 @@ function round2(n) {
13932
14086
  return Math.round(n * 100) / 100;
13933
14087
  }
13934
14088
 
14089
+ // src/lib/terminal-completion.ts
14090
+ async function readTerminalCompletion(args) {
14091
+ const { jobId, status: status2, saved, transport, ref, jobToken } = args;
14092
+ let completion = completionSnapshot(status2);
14093
+ if (!isTerminalJobStatus(status2.status) || status2.content_available === false) return completion;
14094
+ if (completion.hasArtifacts === void 0) {
14095
+ delete completion.artifactCount;
14096
+ delete completion.payloadIn;
14097
+ try {
14098
+ const messages2 = await transport.getMessages(jobId, 0, ref, {
14099
+ jobToken,
14100
+ timeoutMs: args.timeoutMs ?? 5e3
14101
+ });
14102
+ const derived = messages2.length === 0 && saved?.hasArtifacts !== void 0 ? saved : completionFromMessages(messages2);
14103
+ completion = { ...derived, ...completion };
14104
+ } catch {
14105
+ completion = { ...saved, ...completion };
14106
+ }
14107
+ }
14108
+ return completionForStatus(status2.status, completion);
14109
+ }
14110
+ function completionForStatus(status2, input) {
14111
+ const completion = { ...input };
14112
+ if (status2 !== "completed") {
14113
+ if (completion.hasArtifacts === true) completion.payloadIn = "messages";
14114
+ else delete completion.payloadIn;
14115
+ }
14116
+ return completion;
14117
+ }
14118
+ function terminalCompletionOutput(jobId, status2, input, options = {}) {
14119
+ if (!isTerminalJobStatus(status2)) return { fields: {} };
14120
+ const completion = completionForStatus(status2, input);
14121
+ const fields = buildCompletionHintFields(jobId, completion);
14122
+ if (options.contentAvailable === false) {
14123
+ delete fields.next_step_hint;
14124
+ if (fields.payload_in === "messages") delete fields.payload_in;
14125
+ return { fields };
14126
+ }
14127
+ let hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, options.human);
14128
+ if (completion.hasArtifacts === void 0 && status2 !== "completed") {
14129
+ const job = options.human ? shellQuoteArg(jobId) : guidanceJobArg(jobId);
14130
+ hint = `Any output from finished pieces can be read with 'dvm messages ${job} --no-stream'.`;
14131
+ }
14132
+ if (hint) fields.next_step_hint = hint;
14133
+ const count = typeof completion.artifactCount === "number" && Number.isSafeInteger(completion.artifactCount) && completion.artifactCount >= 0 ? completion.artifactCount : void 0;
14134
+ const display = completion.hasArtifacts === true && hint ? `The job holds ${count === void 0 ? "artifacts" : `${count} artifact${count === 1 ? "" : "s"}`}. ${hint}` : hint;
14135
+ return { fields, hint, display };
14136
+ }
14137
+
13935
14138
  // src/lib/dvm-identifier.ts
13936
14139
  var TAG_NAME_RE = CAPABILITY_NAME_RE;
13937
14140
  var HANDLE_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
@@ -14163,6 +14366,7 @@ function creditDrainCommand(handle, creditId) {
14163
14366
  // src/lib/credit-topup.ts
14164
14367
  async function settleCreditAfterJob(args) {
14165
14368
  const deferred = args.deferred ?? takeDeferredFunding();
14369
+ if (hasUnsavedJobState()) return;
14166
14370
  try {
14167
14371
  await settle(args);
14168
14372
  } catch (err) {
@@ -14180,7 +14384,7 @@ async function settleCreditAfterJob(args) {
14180
14384
  }
14181
14385
  }
14182
14386
  if (args.allowTopup !== false) {
14183
- const refill = args.refillPocket ?? (await import("./pocket-refill-KA37CF4N.js")).refillPocketIfLow;
14387
+ const refill = args.refillPocket ?? (await import("./pocket-refill-LCDXSC74.js")).refillPocketIfLow;
14184
14388
  await refill({ human: args.human }).catch(() => void 0);
14185
14389
  }
14186
14390
  }
@@ -14587,7 +14791,7 @@ function dvmIdentity(dvmId, capability) {
14587
14791
  // src/commands/cancel.ts
14588
14792
  async function cancel(jobId, opts) {
14589
14793
  const access = resolveJobAccess(jobId, opts);
14590
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => cancelWithAccess(jobId, opts, access)));
14794
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => cancelWithAccess(jobId, opts, access), opts.human));
14591
14795
  }
14592
14796
  async function cancelWithAccess(jobId, opts, access) {
14593
14797
  const { stored, ref, jobToken } = access;
@@ -14598,7 +14802,10 @@ async function cancelWithAccess(jobId, opts, access) {
14598
14802
  if (!access.endpointOverridden) markJobTerminal(
14599
14803
  jobId,
14600
14804
  "cancelled",
14601
- opts.reason !== void 0 ? { message: opts.reason } : {},
14805
+ {
14806
+ ...stored?.status === "cancelled" ? stored.completion : {},
14807
+ ...opts.reason !== void 0 ? { message: opts.reason } : {}
14808
+ },
14602
14809
  { callerCancelled: true }
14603
14810
  );
14604
14811
  const { settlement, status: status2 } = await readEnding({
@@ -14612,10 +14819,28 @@ async function cancelWithAccess(jobId, opts, access) {
14612
14819
  if (!access.endpointOverridden) clearAskPaymentBlocks(jobId);
14613
14820
  }
14614
14821
  });
14822
+ const saved = stored?.status === "cancelled" ? stored.completion : void 0;
14823
+ const completion = await readTerminalCompletion({
14824
+ jobId,
14825
+ status: status2 ?? { status: "cancelled" },
14826
+ saved,
14827
+ transport,
14828
+ ref,
14829
+ jobToken
14830
+ });
14831
+ if (!access.endpointOverridden) markJobTerminal(jobId, "cancelled", {
14832
+ ...status2?.content_available === false && saved ? saved : completion,
14833
+ ...opts.reason !== void 0 ? { message: opts.reason } : {}
14834
+ });
14835
+ const artifacts = terminalCompletionOutput(jobId, "cancelled", completion, {
14836
+ human: opts.human,
14837
+ contentAvailable: status2?.content_available
14838
+ });
14615
14839
  transport.close();
14616
14840
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
14617
14841
  const receiptPending = !settlement && status2 !== void 0 && isTerminalJobStatus(status2.status) && !status2.receipt && !status2.receiptParseError && !access.endpointOverridden && expectsReceipt(jobId, stored);
14618
- const display = settlement ? cancelledDisplay(settlement) : receiptPending ? `Stopped. Its receipt is not available yet; \`dvm status ${guidanceJobArg(jobId)}\` shows what was charged once it is.` : void 0;
14842
+ const endingDisplay = settlement ? cancelledDisplay(settlement) : receiptPending ? `Stopped. Its receipt is not available yet; \`dvm status ${guidanceJobArg(jobId)}\` shows what was charged once it is.` : void 0;
14843
+ const display = [endingDisplay, artifacts.display].filter(Boolean).join(" ") || void 0;
14619
14844
  const hint = settlementCurrencyHint(settlement, ref.endpoint);
14620
14845
  if (opts.human) {
14621
14846
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
@@ -14629,6 +14854,7 @@ async function cancelWithAccess(jobId, opts, access) {
14629
14854
  ...opts.reason ? { reason: opts.reason } : {},
14630
14855
  ...settlement ? { settlement } : {},
14631
14856
  ...display ? { display } : {},
14857
+ ...artifacts.fields,
14632
14858
  ...hint ? { hint } : {},
14633
14859
  next_action: null
14634
14860
  });
@@ -14641,7 +14867,7 @@ function expectsReceipt(jobId, stored) {
14641
14867
  // src/commands/decline.ts
14642
14868
  async function decline(jobId, opts) {
14643
14869
  const access = resolveJobAccess(jobId, opts);
14644
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => declineWithAccess(jobId, opts, access)));
14870
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => declineWithAccess(jobId, opts, access), opts.human));
14645
14871
  }
14646
14872
  async function declineWithAccess(jobId, opts, access) {
14647
14873
  const { stored, ref, jobToken } = access;
@@ -14666,16 +14892,19 @@ async function declineWithAccess(jobId, opts, access) {
14666
14892
  markJobTerminal(
14667
14893
  jobId,
14668
14894
  status2.status,
14669
- opts.reason !== void 0 ? { message: opts.reason } : {},
14895
+ {
14896
+ ...stored?.status === status2.status ? stored.completion : {},
14897
+ ...opts.reason !== void 0 ? { message: opts.reason } : {}
14898
+ },
14670
14899
  { callerCancelled: true, callerDeclined: true }
14671
14900
  );
14672
14901
  clearAskPaymentBlocks(jobId);
14673
14902
  }
14674
14903
  }
14675
14904
  });
14676
- transport.close();
14677
14905
  const observed = ending.status?.status;
14678
14906
  if (observed !== void 0 && !isTerminalJobStatus(observed)) {
14907
+ transport.close();
14679
14908
  throw new DvmError(
14680
14909
  "decline_unsupported",
14681
14910
  `The provider accepted the decline, but the job is still ${observed}.`,
@@ -14683,9 +14912,30 @@ async function declineWithAccess(jobId, opts, access) {
14683
14912
  { jobId, status: observed }
14684
14913
  );
14685
14914
  }
14915
+ const completion = ending.status ? await readTerminalCompletion({
14916
+ jobId,
14917
+ status: ending.status,
14918
+ transport,
14919
+ ref,
14920
+ jobToken,
14921
+ saved: stored && stored.status === observed ? stored.completion : void 0
14922
+ }) : {};
14923
+ if (observed && isTerminalJobStatus(observed) && !access.endpointOverridden) {
14924
+ const saved = stored?.status === observed ? stored.completion : void 0;
14925
+ markJobTerminal(jobId, observed, {
14926
+ ...ending.status?.content_available === false && saved ? saved : completion,
14927
+ ...opts.reason !== void 0 ? { message: opts.reason } : {}
14928
+ });
14929
+ }
14930
+ const artifacts = terminalCompletionOutput(jobId, observed ?? "unknown", completion, {
14931
+ human: opts.human,
14932
+ contentAvailable: ending.status?.content_available
14933
+ });
14934
+ transport.close();
14686
14935
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
14687
14936
  const { settlement } = ending;
14688
- const display = observed === void 0 ? `Decline sent, but the job's status could not be read. Check it with \`dvm status ${job}\`.` : settlement ? `Declined; the job has ended. ${settlement.display}` : `Declined; the job has ended. Its receipt is not available yet; \`dvm status ${job}\` shows the final charge once it is.`;
14937
+ const endingDisplay = observed === void 0 ? `Decline sent, but the job's status could not be read. Check it with \`dvm status ${job}\`.` : settlement ? `Declined; the job has ended. ${settlement.display}` : `Declined; the job has ended. Its receipt is not available yet; \`dvm status ${job}\` shows the final charge once it is.`;
14938
+ const display = [endingDisplay, artifacts.display].filter(Boolean).join(" ");
14689
14939
  const hint = settlementCurrencyHint(settlement, ref.endpoint);
14690
14940
  if (opts.human) {
14691
14941
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""}: ${display}`);
@@ -14700,6 +14950,7 @@ async function declineWithAccess(jobId, opts, access) {
14700
14950
  ...opts.reason !== void 0 ? { reason: opts.reason } : {},
14701
14951
  ...settlement ? { settlement } : {},
14702
14952
  display,
14953
+ ...artifacts.fields,
14703
14954
  ...hint ? { hint } : {},
14704
14955
  next_action: observed === void 0 ? pollNextAction(jobId, display) : null
14705
14956
  });
@@ -15456,8 +15707,9 @@ async function creditOp(transport, endpoint, body, payment) {
15456
15707
  function advisoryBtcRate() {
15457
15708
  return tryResolveBtcUsdRate().then((resolved) => resolved?.rate).catch(() => void 0);
15458
15709
  }
15459
- function implicitCreditJson(credit) {
15710
+ function implicitCreditJson(credit, postureOff) {
15460
15711
  const active2 = credit.status === "active";
15712
+ const blocked = active2 && postureOff;
15461
15713
  const amount = formatFiat(Math.max(credit.remainingMicro, 0) / 1e6, credit.currency);
15462
15714
  const label = dvmLabelFromEndpoint(credit.endpoint);
15463
15715
  return {
@@ -15471,7 +15723,8 @@ function implicitCreditJson(credit) {
15471
15723
  expiry_ms: credit.expiryMs,
15472
15724
  status: credit.status,
15473
15725
  tracked: true,
15474
- drawable: active2,
15726
+ drawable: active2 && !postureOff,
15727
+ ...blocked ? { draw_blocked_reason: "posture_off" } : {},
15475
15728
  drainable: false,
15476
15729
  released_by_job_id: credit.releasedByJobId,
15477
15730
  released_at_ms: credit.releasedAt,
@@ -15486,7 +15739,7 @@ function implicitCreditJson(credit) {
15486
15739
  job_id: credit.discrepancy.jobId
15487
15740
  }
15488
15741
  } : {},
15489
- display: active2 ? `${amount} released by an unsuccessful per-call job at ${label}; the next eligible request spends it automatically before prepaid credit.` : `${amount} released per-call balance at ${label} is lost; implicit credits have no drain path after expiry or server retirement.`,
15742
+ display: blocked ? `${amount} released per-call balance is held at ${label}, but spending it is switched off by credit posture; no drain path is available.` : active2 ? `${amount} released by an unsuccessful per-call job at ${label}; the next eligible request spends it automatically before prepaid credit.` : `${amount} released per-call balance at ${label} is lost; implicit credits have no drain path after expiry or server retirement.`,
15490
15743
  hint: active2 ? `Use it promptly. ${new Date(credit.expiryMs).toISOString()} is the latest possible expiry inferred from the receipt; the server may retire it earlier. No funding menu or new payment is needed.` : "No reclaim action is available. A provider must offer prepaid credit for unused value to have a drain path."
15491
15744
  };
15492
15745
  }
@@ -15498,6 +15751,7 @@ function currencyTotal(totals, currency) {
15498
15751
  trackedCount: 0,
15499
15752
  siblingCount: 0,
15500
15753
  drawableMicro: 0,
15754
+ postureBlockedMicro: 0,
15501
15755
  siblingSpendableMicro: 0
15502
15756
  };
15503
15757
  totals.set(currency, created);
@@ -15512,8 +15766,9 @@ function creditCurrencyTotalsJson(total, source) {
15512
15766
  tracked_count: total.trackedCount,
15513
15767
  sibling_count: total.siblingCount,
15514
15768
  drawable_micro: total.drawableMicro,
15769
+ ...total.postureBlockedMicro > 0 ? { posture_blocked_micro: total.postureBlockedMicro } : {},
15515
15770
  sibling_spendable_micro: total.siblingSpendableMicro,
15516
- spendable_micro: total.drawableMicro + total.siblingSpendableMicro,
15771
+ spendable_micro: total.drawableMicro + total.postureBlockedMicro + total.siblingSpendableMicro,
15517
15772
  display: creditCurrencyTotalDisplay(total, source)
15518
15773
  };
15519
15774
  }
@@ -15525,10 +15780,14 @@ function creditCurrencyTotalDisplay(total, source) {
15525
15780
  const drawable = formatFiat(total.drawableMicro / 1e6, total.currency);
15526
15781
  const sibling = formatFiat(total.siblingSpendableMicro / 1e6, total.currency);
15527
15782
  const spendable = formatFiat(
15528
- (total.drawableMicro + total.siblingSpendableMicro) / 1e6,
15783
+ (total.drawableMicro + total.postureBlockedMicro + total.siblingSpendableMicro) / 1e6,
15529
15784
  total.currency
15530
15785
  );
15531
15786
  const certainty = source === "local" ? "believed" : "server-confirmed";
15787
+ if (total.postureBlockedMicro > 0) {
15788
+ const blocked = formatFiat(total.postureBlockedMicro / 1e6, total.currency);
15789
+ return `${spendable} ${certainty} spendable: ${drawable} drawable from tracked credits, ${blocked} held but spending switched off by credit posture, and ${sibling} held on sibling credits that draws do not use.`;
15790
+ }
15532
15791
  return total.siblingSpendableMicro > 0 ? `${spendable} ${certainty} spendable: ${drawable} drawable from tracked credits, and ${sibling} held on sibling credits that draws do not use.` : `${drawable} ${certainty} spendable, all drawable from tracked credits; no sibling spendable balance is recorded in ${total.currency.toUpperCase()}.`;
15533
15792
  }
15534
15793
  function headroomReader() {
@@ -15708,9 +15967,11 @@ async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate,
15708
15967
  }
15709
15968
  const providerInfo = await transport.describe({ endpoint }).catch(() => void 0);
15710
15969
  const identity = providerDvmIdentity(providerInfo);
15970
+ const postureOff = effectiveCreditPosture(loadConfig()?.credit, endpoint, identity).posture === "off";
15711
15971
  if (!providerInfo)
15712
15972
  throw new DvmError("provider_unavailable", "Could not read provider metadata.");
15713
- const implicitCredits = loadImplicitCredits(endpoint, signer.pubkey, identity).filter(
15973
+ const localImplicitCredits = loadImplicitCredits(endpoint, signer.pubkey, identity);
15974
+ const implicitCredits = localImplicitCredits.filter(
15714
15975
  (credit) => !creditId || credit.creditId === creditId
15715
15976
  );
15716
15977
  const signCredit = (body) => signDvmRequestData(
@@ -15747,7 +16008,7 @@ async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate,
15747
16008
  }
15748
16009
  } catch (err) {
15749
16010
  if (err instanceof DvmError && err.code === "credit_not_supported") {
15750
- const rows = implicitCredits.map(implicitCreditJson);
16011
+ const rows = implicitCredits.map((credit) => implicitCreditJson(credit, postureOff));
15751
16012
  return {
15752
16013
  rows: rows.length > 0 ? rows : [
15753
16014
  {
@@ -15804,16 +16065,18 @@ async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate,
15804
16065
  ...btcRate !== void 0 ? { btcRate } : {}
15805
16066
  });
15806
16067
  const liveIds = new Set(credits.map((credit) => credit.credit_id));
16068
+ const implicitById = new Map(localImplicitCredits.map((credit) => [credit.creditId, credit]));
15807
16069
  return {
15808
16070
  rows: [
15809
16071
  ...credits.map(
15810
- (credit) => wireCreditJson(
16072
+ (credit) => credit.credit_id.startsWith("imp:") ? wireImplicitCreditJson(endpoint, credit, implicitById.get(credit.credit_id), postureOff) : wireCreditJson(
15811
16073
  endpoint,
15812
16074
  credit,
15813
- credit.credit_id === currentStored?.creditId && currentStored.selectionCleared !== true
16075
+ credit.credit_id === currentStored?.creditId && currentStored.selectionCleared !== true,
16076
+ postureOff
15814
16077
  )
15815
16078
  ),
15816
- ...implicitCredits.filter((credit) => !liveIds.has(credit.creditId)).map(implicitCreditJson)
16079
+ ...implicitCredits.filter((credit) => !liveIds.has(credit.creditId)).map((credit) => implicitCreditJson(credit, postureOff))
15817
16080
  ],
15818
16081
  // Emitted even when `credits` is empty: the server just stated its menu, so
15819
16082
  // this read answers "what could I open here" without a second round trip.
@@ -15829,7 +16092,25 @@ function advisoryBtcRateOnce() {
15829
16092
  let pending4;
15830
16093
  return () => pending4 ??= advisoryBtcRate();
15831
16094
  }
15832
- function wireCreditJson(endpoint, credit, tracked) {
16095
+ function wireImplicitCreditJson(endpoint, credit, local, postureOff) {
16096
+ const label = dvmLabelFromEndpoint(endpoint);
16097
+ const amount = formatFiat(Math.max(credit.remaining_micro, 0) / 1e6, credit.currency);
16098
+ const unavailable = credit.status === "unbacked" ? "backing finalized before collection" : credit.reconciliation_pending ? "backing reconciliation pending" : credit.expired ? "expired" : !local ? "no receipt-backed release is tracked for this caller at this DVM" : local.status !== "active" || local.expiryMs <= Date.now() ? "the local release is lost" : local.remainingMicro <= 0 || credit.remaining_micro <= 0 ? "no released value is available for draws" : void 0;
16099
+ const blocked = unavailable === void 0 && postureOff;
16100
+ return {
16101
+ endpoint,
16102
+ dvm: label,
16103
+ ...credit,
16104
+ kind: "implicit",
16105
+ tracked: local !== void 0,
16106
+ drawable: unavailable === void 0 && !postureOff,
16107
+ ...blocked ? { draw_blocked_reason: "posture_off" } : {},
16108
+ drainable: false,
16109
+ ...local ? { released_by_job_id: local.releasedByJobId, released_at_ms: local.releasedAt } : {},
16110
+ display: blocked ? `${amount} released per-call balance is held at ${label}, but spending it is switched off by credit posture; no drain path is available.` : unavailable !== void 0 ? `${amount} released per-call balance at ${label} (${unavailable}; not drawable). No drain path is available.` : `${amount} released by an unsuccessful per-call job at ${label}; the next eligible request spends it automatically before prepaid credit.`
16111
+ };
16112
+ }
16113
+ function wireCreditJson(endpoint, credit, tracked, postureOff) {
15833
16114
  const label = dvmLabelFromEndpoint(endpoint);
15834
16115
  const unbacked = credit.status === "unbacked";
15835
16116
  const amount = formatFiat(
@@ -15838,14 +16119,18 @@ function wireCreditJson(endpoint, credit, tracked) {
15838
16119
  );
15839
16120
  const state = unbacked ? "closed \u2014 backing finalized before collection" : credit.reconciliation_pending ? "backing reconciliation pending" : credit.expired ? "expired \u2014 balance reclaimable" : "spendable";
15840
16121
  const command = creditDrainCommand(endpoint, credit.credit_id);
16122
+ const active2 = !credit.expired && !unbacked && !credit.reconciliation_pending;
16123
+ const eligible = tracked && active2;
16124
+ const blocked = postureOff && eligible;
15841
16125
  return {
15842
16126
  endpoint,
15843
16127
  dvm: label,
15844
16128
  ...credit,
15845
16129
  tracked,
15846
- drawable: tracked && !credit.expired && !unbacked && !credit.reconciliation_pending,
16130
+ drawable: eligible && !postureOff,
16131
+ ...blocked ? { draw_blocked_reason: "posture_off" } : {},
15847
16132
  ...!tracked && credit.drainable ? { drain_command: command } : {},
15848
- display: tracked ? unbacked ? `${amount} of former credit at ${label} (${state}; no action is available).` : credit.reconciliation_pending ? `${amount} of credit at ${label} (${state}, tracked locally but not drawable).` : credit.expired ? `${amount} of credit at ${label} (${state}, tracked locally but not drawable).` : `${amount} of credit at ${label} (${state}, tracked for draws).` : `${amount} on sibling credit ${credit.credit_id} at ${label} (${state}, not used for draws).`,
16133
+ display: blocked ? `${amount} of credit is held at ${label}, but spending it is switched off by credit posture${credit.drainable ? "; balance remains reclaimable" : ""}.` : tracked ? unbacked ? `${amount} of former credit at ${label} (${state}; no action is available).` : credit.reconciliation_pending ? `${amount} of credit at ${label} (${state}, tracked locally but not drawable).` : credit.expired ? `${amount} of credit at ${label} (${state}, tracked locally but not drawable).` : `${amount} of credit at ${label} (${state}, tracked for draws).` : `${amount} on sibling credit ${credit.credit_id} at ${label} (${state}, not used for draws).`,
15849
16134
  ...!tracked && credit.drainable ? { hint: `Reclaim it with this command: ${command}` } : {}
15850
16135
  };
15851
16136
  }
@@ -15860,7 +16145,9 @@ function wireCreditCurrencyTotals(rows) {
15860
16145
  else total.siblingCount += 1;
15861
16146
  if (row.expired === true) continue;
15862
16147
  if (row.drawable === true) total.drawableMicro += Math.max(row.remaining_micro, 0);
15863
- else if (!row.tracked && row.drainable === true) {
16148
+ else if (row.draw_blocked_reason === "posture_off") {
16149
+ total.postureBlockedMicro += Math.max(row.remaining_micro, 0);
16150
+ } else if (!row.tracked && row.drainable === true) {
15864
16151
  total.siblingSpendableMicro += Math.max(row.remaining_micro, 0);
15865
16152
  }
15866
16153
  }
@@ -18381,6 +18668,10 @@ async function runCreditDrain(dvm, opts) {
18381
18668
  });
18382
18669
  return;
18383
18670
  }
18671
+ if (method === "tempo" && isKnownEmptyTempoCredit(stored, creditId) && !opts.drainId && !pendingDrainFor(stored, creditId) && !tempoSession) {
18672
+ renderAlreadyDrained({ human: opts.human === true, endpoint, creditId });
18673
+ return;
18674
+ }
18384
18675
  const canPersist = !stored || stored.creditId === creditId;
18385
18676
  const named = opts.drainId ? pendingDrainById(stored, opts.drainId) : void 0;
18386
18677
  if (named?.creditId !== void 0 && named.creditId !== creditId) {
@@ -18702,6 +18993,10 @@ async function runCreditDrain(dvm, opts) {
18702
18993
  if (!stored) forgetCredit(endpoint, signer.pubkey, ...identityArg);
18703
18994
  else if (mintedThisRun) clearPendingDrain(endpoint, signer.pubkey, drain, ...identityArg);
18704
18995
  }
18996
+ if (err instanceof DvmError && err.code === "tempo_channel_exit_required" && err.data?.drain_registered === false && isKnownEmptyTempoCredit(stored, creditId)) {
18997
+ renderAlreadyDrained({ human: opts.human === true, endpoint, creditId });
18998
+ return;
18999
+ }
18705
19000
  if (err instanceof DvmError && err.code === "tempo_channel_exit_required") {
18706
19001
  const local2 = tempoExitRequiredCopy(exitRecovery, err.data?.channel_id, err.data?.status);
18707
19002
  const display2 = retirement ? `${local2.display} ${retirement}` : local2.display;
@@ -19158,6 +19453,27 @@ function localDrainCopy(wire, requested, exitRecovery) {
19158
19453
  );
19159
19454
  }
19160
19455
  }
19456
+ function isKnownEmptyTempoCredit(stored, creditId) {
19457
+ return stored?.creditId === creditId && stored.status === "drained" && stored.remainingMicro <= 0 && !stored.provisional && !stored.discrepancy;
19458
+ }
19459
+ function renderAlreadyDrained(args) {
19460
+ const display = "This credit is already drained: its earlier drain was sent, so nothing is owed and no refund is pending.";
19461
+ 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.";
19462
+ if (args.human) {
19463
+ info(display);
19464
+ info(hint);
19465
+ return;
19466
+ }
19467
+ json({
19468
+ op: "drain",
19469
+ endpoint: args.endpoint,
19470
+ credit_id: args.creditId,
19471
+ already_drained: true,
19472
+ balance_micro: 0,
19473
+ display,
19474
+ hint
19475
+ });
19476
+ }
19161
19477
  function tempoExitRequiredCopy(recovery, channelId, status2) {
19162
19478
  const channel = typeof channelId === "string" ? ` Channel ID: ${channelId}.` : "";
19163
19479
  const pending4 = status2 === "pending";
@@ -20315,16 +20631,17 @@ function creditList(opts) {
20315
20631
  const creditConfig = loadConfig()?.credit;
20316
20632
  const headroomOf = headroomReader();
20317
20633
  const identityOf = (endpoint) => offlineDvmIdentity(creditConfig, endpoint, headroomOf);
20318
- const postureOf = (endpoint) => effectiveCreditPosture(creditConfig, endpoint, identityOf(endpoint));
20634
+ const postureOf = (row) => effectiveCreditPosture(creditConfig, row.endpoint, dvmLocationIdentity(row) ?? identityOf(row.endpoint));
20635
+ const postureOff = (row) => postureOf(row).posture === "off";
20319
20636
  const fundingRailOf = (endpoint) => effectiveFundingRail(creditConfig, endpoint, identityOf(endpoint));
20320
20637
  const globalPosture = isCreditPosture(creditConfig?.posture) ? { posture: creditConfig.posture, source: "global" } : { posture: DEFAULT_CREDIT_POSTURE, source: "default" };
20321
20638
  const globalRail = effectiveFundingRail(creditConfig);
20322
20639
  const siblingCredits = credits.flatMap((credit) => credit.siblingCredits ?? []);
20323
- const totals = localCreditCurrencyTotals(credits, implicitCredits);
20640
+ const totals = localCreditCurrencyTotals(credits, implicitCredits, postureOff);
20324
20641
  if (opts.human) {
20325
20642
  info(humanPostureLine(globalPosture));
20326
20643
  for (const [endpoint, per] of postureOverrides(creditConfig)) {
20327
- info(` At ${dvmLabelFromEndpoint(endpoint)}: ${per} (overrides the global setting).`);
20644
+ info(` At ${dvmLabelFromEndpoint(endpoint)}: ${per} (overrides the global setting).${per === "off" ? " Spending held credit is also switched off." : ""}`);
20328
20645
  }
20329
20646
  info(humanFundingRailLine(globalRail));
20330
20647
  for (const [endpoint, rail] of fundingRailOverrides(creditConfig)) {
@@ -20338,13 +20655,13 @@ function creditList(opts) {
20338
20655
  return;
20339
20656
  }
20340
20657
  for (const c of credits) {
20341
- info(` ${humanCreditRow(c)}`);
20658
+ info(` ${humanCreditRow(c, postureOff(c))}`);
20342
20659
  for (const sibling of c.siblingCredits ?? []) {
20343
20660
  info(` ${humanSiblingCreditRow(c, sibling)}`);
20344
20661
  }
20345
20662
  info(` ${headroomDisplay(headroomOf.of(headroomInputsFor(c, identityOf(c.endpoint))))}`);
20346
20663
  }
20347
- for (const row of humanImplicitCreditRows(implicitCredits)) info(` ${row}`);
20664
+ for (const row of humanImplicitCreditRows(implicitCredits, postureOff)) info(` ${row}`);
20348
20665
  for (const snapshot of snapshots) {
20349
20666
  const machine = cachedDvmJson(snapshot, credits, headroomOf, identityOf(snapshot.endpoint));
20350
20667
  info(` ${String(machine.display)}`);
@@ -20378,19 +20695,19 @@ function creditList(opts) {
20378
20695
  hint: `Pin it with 'dvm credit rail <${CREDIT_FUND_RAILS.join("|")}>' or return to the amount rule with 'dvm credit rail --clear'; add --dvm <dvm> to scope either operation.`
20379
20696
  },
20380
20697
  credits: credits.map((c) => ({
20381
- ...storedCreditJson(c, headroomOf.of(headroomInputsFor(c, identityOf(c.endpoint)))),
20382
- ...postureFields(postureOf(c.endpoint)),
20698
+ ...storedCreditJson(c, headroomOf.of(headroomInputsFor(c, identityOf(c.endpoint))), postureOff(c)),
20699
+ ...postureFields(postureOf(c)),
20383
20700
  ...fundingRailFields(fundingRailOf(c.endpoint))
20384
20701
  })),
20385
20702
  count: credits.length,
20386
- implicit_credits: implicitCredits.map(implicitCreditJson),
20703
+ implicit_credits: implicitCredits.map((c) => implicitCreditJson(c, postureOff(c))),
20387
20704
  implicit_count: implicitCredits.length,
20388
20705
  credit_count: credits.length + siblingCredits.length + implicitCredits.length,
20389
20706
  sibling_count: siblingCredits.length,
20390
20707
  totals_by_currency: totals.map((total) => creditCurrencyTotalsJson(total, "local")),
20391
20708
  dvms: snapshots.map((snapshot) => ({
20392
20709
  ...cachedDvmJson(snapshot, credits, headroomOf, identityOf(snapshot.endpoint)),
20393
- ...postureFields(postureOf(snapshot.endpoint)),
20710
+ ...postureFields(postureOf(snapshot)),
20394
20711
  ...fundingRailFields(fundingRailOf(snapshot.endpoint))
20395
20712
  })),
20396
20713
  dvm_count: snapshots.length,
@@ -20437,14 +20754,15 @@ function postureSentence(posture) {
20437
20754
  case "auto":
20438
20755
  return "credit is bought within the trust-tier caps without asking, and every purchase reports its amount, route and reason.";
20439
20756
  case "off":
20440
- return "no multi-job credit is opened, refilled, or drawn on; every job pays per-call.";
20757
+ return "no multi-job credit is opened or refilled, and spending held credit is switched off; every job pays per-call.";
20441
20758
  case "suggest":
20442
20759
  return "nothing is ever bought automatically; where a credit would have helped, the job output says so and names how to fund it.";
20443
20760
  }
20444
20761
  }
20445
20762
  function humanPostureLine(effective) {
20446
20763
  const provenance = effective.source === "global" ? "set in config" : "the default";
20447
- return `Automatic credit purchases: ${effective.posture} (${provenance}) \u2014 ${postureSentence(effective.posture)}`;
20764
+ const subject = effective.posture === "off" ? "Credit purchases and spending" : "Automatic credit purchases";
20765
+ return `${subject}: ${effective.posture} (${provenance}) \u2014 ${postureSentence(effective.posture)}`;
20448
20766
  }
20449
20767
  function postureAdoptionSentence(posture) {
20450
20768
  switch (posture) {
@@ -20483,8 +20801,9 @@ function fundingRailFields(effective) {
20483
20801
  funding_rail_source: effective.source
20484
20802
  };
20485
20803
  }
20486
- function storedCreditJson(c, headroom) {
20804
+ function storedCreditJson(c, headroom, postureOff) {
20487
20805
  const channelId = storedCreditChannelId(c);
20806
+ const eligible = c.selectionCleared !== true && c.status === "active" && !c.reconciliationPending;
20488
20807
  return {
20489
20808
  endpoint: c.endpoint,
20490
20809
  dvm: dvmLabelFromEndpoint(c.endpoint),
@@ -20498,7 +20817,8 @@ function storedCreditJson(c, headroom) {
20498
20817
  ...channelId ? { channel_id: channelId } : {},
20499
20818
  ...c.reconciliationPending ? { reconciliation_pending: true } : {},
20500
20819
  tracked: c.selectionCleared !== true,
20501
- drawable: c.selectionCleared !== true && c.status === "active" && !c.reconciliationPending,
20820
+ drawable: eligible && !postureOff,
20821
+ ...eligible && postureOff ? { draw_blocked_reason: "posture_off" } : {},
20502
20822
  ...c.siblingCredits ? { sibling_credits: c.siblingCredits.map((sibling) => siblingCreditJson(c, sibling)) } : {},
20503
20823
  ...c.provisional ? { provisional: true } : {},
20504
20824
  ...c.pendingDrains?.length ? { pending_drains: c.pendingDrains.map(pendingDrainJson) } : {},
@@ -20514,7 +20834,7 @@ function storedCreditJson(c, headroom) {
20514
20834
  }
20515
20835
  } : {},
20516
20836
  headroom: headroomJson(headroom),
20517
- display: humanCreditRow(c)
20837
+ display: humanCreditRow(c, postureOff)
20518
20838
  };
20519
20839
  }
20520
20840
  function storedCreditChannelId(credit) {
@@ -20548,13 +20868,14 @@ function siblingCreditJson(record2, sibling) {
20548
20868
  ...sibling.drainable ? { hint: `Reclaim it with this command: ${command}` } : {}
20549
20869
  };
20550
20870
  }
20551
- function localCreditCurrencyTotals(credits, implicitCredits = []) {
20871
+ function localCreditCurrencyTotals(credits, implicitCredits, postureOff) {
20552
20872
  const totals = /* @__PURE__ */ new Map();
20553
20873
  for (const credit of credits) {
20554
20874
  const tracked = currencyTotal(totals, credit.currency);
20555
20875
  tracked.trackedCount += 1;
20556
20876
  if (credit.status === "active" && !credit.reconciliationPending) {
20557
- tracked.drawableMicro += Math.max(credit.remainingMicro, 0);
20877
+ if (postureOff(credit)) tracked.postureBlockedMicro += Math.max(credit.remainingMicro, 0);
20878
+ else tracked.drawableMicro += Math.max(credit.remainingMicro, 0);
20558
20879
  }
20559
20880
  for (const sibling of credit.siblingCredits ?? []) {
20560
20881
  const siblingTotal = currencyTotal(totals, sibling.currency);
@@ -20567,7 +20888,10 @@ function localCreditCurrencyTotals(credits, implicitCredits = []) {
20567
20888
  for (const credit of implicitCredits) {
20568
20889
  const total = currencyTotal(totals, credit.currency);
20569
20890
  total.trackedCount += 1;
20570
- if (credit.status === "active") total.drawableMicro += Math.max(credit.remainingMicro, 0);
20891
+ if (credit.status === "active") {
20892
+ if (postureOff(credit)) total.postureBlockedMicro += Math.max(credit.remainingMicro, 0);
20893
+ else total.drawableMicro += Math.max(credit.remainingMicro, 0);
20894
+ }
20571
20895
  }
20572
20896
  return sortedCurrencyTotals(totals);
20573
20897
  }
@@ -20734,7 +21058,7 @@ function pendingFundingsDisplay(pending4) {
20734
21058
  function drainReceiptCount(c) {
20735
21059
  return (c.drainEvidence ?? []).reduce((sum, e) => sum + e.receipts.length, 0);
20736
21060
  }
20737
- function humanCreditRow(c) {
21061
+ function humanCreditRow(c, postureOff) {
20738
21062
  const label = dvmLabelFromEndpoint(c.endpoint).padEnd(12);
20739
21063
  const amount = formatFiat(
20740
21064
  Math.max(c.status === "unbacked" ? c.balanceMicro : c.remainingMicro, 0) / 1e6,
@@ -20744,6 +21068,7 @@ function humanCreditRow(c) {
20744
21068
  const stranded = others.filter((d) => d.creditId !== void 0).length;
20745
21069
  const unattributed = others.length - stranded;
20746
21070
  const flags = [
21071
+ postureOff && c.status === "active" && !c.reconciliationPending ? "held but spending switched off by credit posture; balance remains reclaimable" : void 0,
20747
21072
  c.status !== "active" ? c.status : void 0,
20748
21073
  c.reconciliationPending ? "backing reconciliation pending" : void 0,
20749
21074
  c.provisional ? "syncing" : void 0,
@@ -20756,10 +21081,10 @@ function humanCreditRow(c) {
20756
21081
  const expiry = c.expiryMs > 0 ? ` \xB7 expires ${new Date(c.expiryMs).toISOString().slice(0, 10)}` : "";
20757
21082
  return `${label} ${amount}${expiry}${flags ? ` \xB7 ${flags}` : ""}`;
20758
21083
  }
20759
- function humanImplicitCreditRows(credits) {
21084
+ function humanImplicitCreditRows(credits, postureOff) {
20760
21085
  const groups = /* @__PURE__ */ new Map();
20761
21086
  for (const credit of credits) {
20762
- const key = `${credit.endpoint}\0${credit.currency}\0${credit.status}`;
21087
+ const key = `${credit.endpoint}\0${credit.currency}\0${credit.status}\0${postureOff(credit)}`;
20763
21088
  const group = groups.get(key) ?? [];
20764
21089
  group.push(credit);
20765
21090
  groups.set(key, group);
@@ -20775,6 +21100,9 @@ function humanImplicitCreditRows(credits) {
20775
21100
  if (first.status === "lost") {
20776
21101
  return `${label} ${amount} across ${count} \xB7 lost; no drain path is available`;
20777
21102
  }
21103
+ if (postureOff(first)) {
21104
+ return `${label} ${amount} across ${count} \xB7 held but spending switched off by credit posture; no drain path is available`;
21105
+ }
20778
21106
  const expiry = Math.min(...group.map((credit) => credit.expiryMs));
20779
21107
  return `${label} ${amount} across ${count} \xB7 next request uses the earliest expiry first \xB7 expires by ${new Date(expiry).toISOString().slice(0, 10)}`;
20780
21108
  });
@@ -21760,18 +22088,85 @@ function findPackageRoot(start) {
21760
22088
  }
21761
22089
 
21762
22090
  // src/lib/caller-state.ts
21763
- import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
21764
- import { basename, join as join4 } from "path";
22091
+ import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
22092
+ import { basename, join as join5 } from "path";
22093
+
22094
+ // src/lib/request-refusal-store.ts
22095
+ import {
22096
+ closeSync as closeSync2,
22097
+ existsSync as existsSync4,
22098
+ fsyncSync as fsyncSync2,
22099
+ openSync as openSync2,
22100
+ readFileSync as readFileSync4,
22101
+ renameSync as renameSync2,
22102
+ rmSync,
22103
+ writeFileSync as writeFileSync2
22104
+ } from "fs";
22105
+ import { join as join4 } from "path";
22106
+ var REQUEST_REFUSALS_DIR = join4(CONFIG_DIR, "request-refusals");
22107
+ var SAFE_TOKEN = /^[a-z0-9_.:-]{1,64}$/;
22108
+ function requestIntentMayExist(requestId) {
22109
+ return existsSync4(join4(REQUEST_INTENTS_DIR, requestId));
22110
+ }
22111
+ function recordRequestRefusal(requestId, refusal) {
22112
+ if (!isPublicRequestId(requestId) || requestIntentMayExist(requestId)) return false;
22113
+ const record2 = {
22114
+ v: 1,
22115
+ requestId,
22116
+ code: SAFE_TOKEN.test(refusal.code) ? refusal.code : "refused",
22117
+ ...typeof refusal.reason === "string" && SAFE_TOKEN.test(refusal.reason) ? { reason: refusal.reason } : {},
22118
+ refusedAt: Date.now()
22119
+ };
22120
+ try {
22121
+ ensureConfigSubdir(REQUEST_REFUSALS_DIR);
22122
+ const target = refusalPath(requestId);
22123
+ const temp = `${target}.${String(process.pid)}.tmp`;
22124
+ const fd = openSync2(temp, "w", 384);
22125
+ try {
22126
+ writeFileSync2(fd, JSON.stringify(record2, null, 2) + "\n");
22127
+ fsyncSync2(fd);
22128
+ } finally {
22129
+ closeSync2(fd);
22130
+ }
22131
+ renameSync2(temp, target);
22132
+ } catch {
22133
+ }
22134
+ return true;
22135
+ }
22136
+ function clearRequestRefusal(requestId) {
22137
+ if (!isPublicRequestId(requestId)) return;
22138
+ try {
22139
+ rmSync(refusalPath(requestId), { force: true });
22140
+ } catch {
22141
+ }
22142
+ }
22143
+ function loadRequestRefusal(requestId) {
22144
+ if (!isPublicRequestId(requestId)) return null;
22145
+ try {
22146
+ const parsed = JSON.parse(readFileSync4(refusalPath(requestId), "utf8"));
22147
+ if (parsed.v !== 1 || parsed.requestId !== requestId || typeof parsed.code !== "string" || typeof parsed.refusedAt !== "number" || parsed.reason !== void 0 && typeof parsed.reason !== "string") {
22148
+ return null;
22149
+ }
22150
+ return parsed;
22151
+ } catch {
22152
+ return null;
22153
+ }
22154
+ }
22155
+ function refusalPath(requestId) {
22156
+ return join4(REQUEST_REFUSALS_DIR, `${requestId}.json`);
22157
+ }
22158
+
22159
+ // src/lib/caller-state.ts
21765
22160
  function detectSetupState() {
21766
22161
  return {
21767
22162
  existingState: {
21768
- jobs: existsSync4(JOBS_FILE),
21769
- messages: existsSync4(MESSAGES_DIR)
22163
+ jobs: existsSync5(JOBS_FILE),
22164
+ messages: existsSync5(MESSAGES_DIR)
21770
22165
  },
21771
22166
  missing: {
21772
- config: !existsSync4(CONFIG_FILE),
21773
- identity: !existsSync4(IDENTITIES_FILE),
21774
- wallet: !existsSync4(WALLET_FILE)
22167
+ config: !existsSync5(CONFIG_FILE),
22168
+ identity: !existsSync5(IDENTITIES_FILE),
22169
+ wallet: !existsSync5(WALLET_FILE)
21775
22170
  }
21776
22171
  };
21777
22172
  }
@@ -21866,6 +22261,13 @@ var FILE_SPECS = [
21866
22261
  secret: false,
21867
22262
  directory: true
21868
22263
  },
22264
+ {
22265
+ name: "request_refusals",
22266
+ path: REQUEST_REFUSALS_DIR,
22267
+ json: false,
22268
+ secret: false,
22269
+ directory: true
22270
+ },
21869
22271
  { name: "messages", path: MESSAGES_DIR, json: false, secret: false, directory: true },
21870
22272
  // Evidence of paid calls accepted without a settled job identity. Each file
21871
22273
  // is 0600 because a record can hold an anonymous job's access token, so
@@ -21894,17 +22296,17 @@ function findQuarantinedCreditStores() {
21894
22296
  } catch {
21895
22297
  return [];
21896
22298
  }
21897
- return entries.filter((name) => name.startsWith(prefix)).sort((a, b) => a < b ? 1 : a > b ? -1 : 0).map((name) => ({ path: join4(CONFIG_DIR, name), name }));
22299
+ return entries.filter((name) => name.startsWith(prefix)).sort((a, b) => a < b ? 1 : a > b ? -1 : 0).map((name) => ({ path: join5(CONFIG_DIR, name), name }));
21898
22300
  }
21899
22301
  function checkOne(spec) {
21900
- const exists = existsSync4(spec.path);
22302
+ const exists = existsSync5(spec.path);
21901
22303
  if (!exists) {
21902
22304
  return { name: spec.name, path: spec.path, exists: false };
21903
22305
  }
21904
22306
  const row = { name: spec.name, path: spec.path, exists: true };
21905
22307
  if (spec.json) {
21906
22308
  try {
21907
- JSON.parse(readFileSync4(spec.path, "utf-8"));
22309
+ JSON.parse(readFileSync5(spec.path, "utf-8"));
21908
22310
  row.parseable = true;
21909
22311
  } catch (err) {
21910
22312
  row.parseable = false;
@@ -21933,7 +22335,7 @@ function checkSecretDirectory(dir, row) {
21933
22335
  try {
21934
22336
  const offenders = [];
21935
22337
  for (const name of readdirSync2(dir)) {
21936
- const path = join4(dir, name);
22338
+ const path = join5(dir, name);
21937
22339
  const stat2 = statSync2(path);
21938
22340
  if (!stat2.isFile()) continue;
21939
22341
  const mode = stat2.mode & 511;
@@ -21954,9 +22356,9 @@ function octalMode(mode) {
21954
22356
  return "0" + mode.toString(8).padStart(3, "0");
21955
22357
  }
21956
22358
  function readBtcRateCacheAge(now = Date.now()) {
21957
- if (!existsSync4(BTC_RATE_FILE)) return null;
22359
+ if (!existsSync5(BTC_RATE_FILE)) return null;
21958
22360
  try {
21959
- const data = JSON.parse(readFileSync4(BTC_RATE_FILE, "utf-8"));
22361
+ const data = JSON.parse(readFileSync5(BTC_RATE_FILE, "utf-8"));
21960
22362
  if (typeof data.timestamp !== "number") return null;
21961
22363
  return { ageMs: now - data.timestamp };
21962
22364
  } catch {
@@ -21966,7 +22368,7 @@ function readBtcRateCacheAge(now = Date.now()) {
21966
22368
 
21967
22369
  // src/lib/mnemonic-backups.ts
21968
22370
  import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
21969
- import { basename as basename2, dirname as dirname3, join as join5 } from "path";
22371
+ import { basename as basename2, dirname as dirname3, join as join6 } from "path";
21970
22372
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
21971
22373
  const dir = dirname3(mnemonicFile);
21972
22374
  const prefix = `${basename2(mnemonicFile)}.`;
@@ -21978,7 +22380,7 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
21978
22380
  throw err;
21979
22381
  }
21980
22382
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
21981
- const path = join5(dir, name);
22383
+ const path = join6(dir, name);
21982
22384
  const stat2 = statSync3(path);
21983
22385
  if (!stat2.isFile()) return null;
21984
22386
  const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
@@ -22018,8 +22420,8 @@ function formatMnemonicBackupAge(ageMs2) {
22018
22420
  }
22019
22421
 
22020
22422
  // src/lib/wallet-agent/submissions-view.ts
22021
- function describePendingSubmissions(wallet, nowMs = Date.now()) {
22022
- const entries = wallet.pending_submissions.map((entry) => toView(entry, nowMs));
22423
+ function describePendingSubmissions(wallet, nowMs = Date.now(), reclaimUnsaved = reclaimIntentIds()) {
22424
+ const entries = wallet.pending_submissions.map((entry) => toView(entry, nowMs, reclaimUnsaved.has(entry.request_id)));
22023
22425
  return {
22024
22426
  entries,
22025
22427
  at_risk_sats: entries.filter((e) => e.at_risk).reduce((sum, e) => sum + e.amount_sats, 0),
@@ -22162,12 +22564,12 @@ function describeSubmissionEvidence(records) {
22162
22564
  };
22163
22565
  });
22164
22566
  }
22165
- function toView(entry, nowMs) {
22567
+ function toView(entry, nowMs, reclaimUnsaved) {
22166
22568
  const createdMs = Date.parse(entry.created_at);
22167
22569
  const ageMs2 = Number.isNaN(createdMs) ? Number.POSITIVE_INFINITY : nowMs - createdMs;
22168
22570
  const attempts = entry.attempts ?? 0;
22169
22571
  const reclaimAt = reclaimAtMs(entry);
22170
- const state = deriveState(entry, ageMs2, attempts, reclaimAt);
22572
+ const state = reclaimUnsaved ? "reclaim_failed" : deriveState(entry, ageMs2, attempts, reclaimAt);
22171
22573
  return {
22172
22574
  request_id: entry.request_id,
22173
22575
  endpoint: entry.endpoint,
@@ -22178,10 +22580,15 @@ function toView(entry, nowMs) {
22178
22580
  state,
22179
22581
  at_risk: state !== "awaiting_swap",
22180
22582
  reclaim_at: reclaimAt === null ? null : new Date(reclaimAt).toISOString(),
22181
- reclaim_error: state === "reclaim_failed" || state === "unreclaimable" ? entry.reclaim_error ?? null : null,
22583
+ reclaim_error: reclaimUnsaved ? RECLAIM_UNSAVED_REASON : state === "reclaim_failed" || state === "unreclaimable" ? entry.reclaim_error ?? null : null,
22182
22584
  ...entry.accepted_unresolved ? { accepted_unresolved: entry.accepted_unresolved } : {},
22183
22585
  ...publicRequestIdOf(entry) ? { public_request_id: publicRequestIdOf(entry) } : {},
22184
- display: describe4(entry, state, reclaimAt, nowMs)
22586
+ display: describe4(
22587
+ reclaimUnsaved ? { ...entry, reclaim_error: RECLAIM_UNSAVED_REASON } : entry,
22588
+ state,
22589
+ reclaimAt,
22590
+ nowMs
22591
+ )
22185
22592
  };
22186
22593
  }
22187
22594
  function locateAdvice(entry, publicRequestId = publicRequestIdOf(entry)) {
@@ -23869,11 +24276,11 @@ async function favRm(name, opts) {
23869
24276
  }
23870
24277
 
23871
24278
  // src/lib/byte-source.ts
23872
- import { readFileSync as readFileSync5 } from "fs";
24279
+ import { readFileSync as readFileSync6 } from "fs";
23873
24280
  import { resolve as resolve2 } from "path";
23874
24281
  var STDIN_TIMEOUT_MS2 = 1e4;
23875
24282
  function readFileText(path) {
23876
- return readFileSync5(resolve2(path), "utf-8");
24283
+ return readFileSync6(resolve2(path), "utf-8");
23877
24284
  }
23878
24285
  var StdinTimeoutError = class extends Error {
23879
24286
  constructor(timeoutMs) {
@@ -24037,7 +24444,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
24037
24444
  }
24038
24445
 
24039
24446
  // src/lib/feedback-nudges.ts
24040
- import { existsSync as existsSync5, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
24447
+ import { existsSync as existsSync6, readFileSync as readFileSync7, renameSync as renameSync3, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
24041
24448
 
24042
24449
  // src/lib/feedback-notice.ts
24043
24450
  function buildFeedbackNudge(args) {
@@ -24089,10 +24496,10 @@ function effectiveFeedbackPosture(config2) {
24089
24496
  return { posture: DEFAULT_FEEDBACK_POSTURE, source: "default" };
24090
24497
  }
24091
24498
  function loadFeedbackNudgeState() {
24092
- if (!existsSync5(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
24499
+ if (!existsSync6(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
24093
24500
  try {
24094
24501
  const parsed = JSON.parse(
24095
- readFileSync6(FEEDBACK_NUDGES_FILE, "utf-8")
24502
+ readFileSync7(FEEDBACK_NUDGES_FILE, "utf-8")
24096
24503
  );
24097
24504
  return {
24098
24505
  ...typeof parsed.introShownAt === "string" ? { introShownAt: parsed.introShownAt } : {},
@@ -24181,9 +24588,9 @@ function coercePerDvm(perDvm) {
24181
24588
  function saveState(state) {
24182
24589
  ensureConfigDir();
24183
24590
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
24184
- writeFileSync2(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
24591
+ writeFileSync3(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
24185
24592
  try {
24186
- renameSync2(tmp, FEEDBACK_NUDGES_FILE);
24593
+ renameSync3(tmp, FEEDBACK_NUDGES_FILE);
24187
24594
  } catch (err) {
24188
24595
  try {
24189
24596
  unlinkSync(tmp);
@@ -24195,9 +24602,9 @@ function saveState(state) {
24195
24602
  var nudgedThisInvocation = false;
24196
24603
 
24197
24604
  // src/lib/platform.ts
24198
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
24605
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
24199
24606
  import { homedir as homedir2 } from "os";
24200
- import { join as join6 } from "path";
24607
+ import { join as join7 } from "path";
24201
24608
  function getPlatformUrl() {
24202
24609
  return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
24203
24610
  }
@@ -24766,16 +25173,16 @@ function finalizeProgressLine() {
24766
25173
  import { randomBytes as randomBytes2 } from "crypto";
24767
25174
  import {
24768
25175
  chmodSync,
24769
- closeSync as closeSync2,
25176
+ closeSync as closeSync3,
24770
25177
  mkdtempSync,
24771
- openSync as openSync2,
25178
+ openSync as openSync3,
24772
25179
  readdirSync as readdirSync4,
24773
25180
  rmdirSync,
24774
25181
  unlinkSync as unlinkSync2,
24775
- writeFileSync as writeFileSync4
25182
+ writeFileSync as writeFileSync5
24776
25183
  } from "fs";
24777
25184
  import { tmpdir } from "os";
24778
- import { join as join7 } from "path";
25185
+ import { join as join8 } from "path";
24779
25186
 
24780
25187
  // src/lib/mime-ext.ts
24781
25188
  var MIME_TO_EXT = {
@@ -24831,11 +25238,11 @@ var ArtifactSaveSession = class {
24831
25238
  let created = false;
24832
25239
  try {
24833
25240
  const directory = this.ensureDirectory();
24834
- path = join7(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
24835
- fd = openSync2(path, "wx", FILE_MODE);
25241
+ path = join8(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
25242
+ fd = openSync3(path, "wx", FILE_MODE);
24836
25243
  created = true;
24837
- writeFileSync4(fd, buf);
24838
- closeSync2(fd);
25244
+ writeFileSync5(fd, buf);
25245
+ closeSync3(fd);
24839
25246
  fd = void 0;
24840
25247
  chmodSync(path, FILE_MODE);
24841
25248
  this.successfulWrites += 1;
@@ -24843,7 +25250,7 @@ var ArtifactSaveSession = class {
24843
25250
  } catch (err) {
24844
25251
  if (fd !== void 0) {
24845
25252
  try {
24846
- closeSync2(fd);
25253
+ closeSync3(fd);
24847
25254
  } catch {
24848
25255
  }
24849
25256
  }
@@ -24860,7 +25267,7 @@ var ArtifactSaveSession = class {
24860
25267
  }
24861
25268
  ensureDirectory() {
24862
25269
  if (this.directory) return this.directory;
24863
- const directory = mkdtempSync(join7(tmpdir(), "dvm-artifacts-"));
25270
+ const directory = mkdtempSync(join8(tmpdir(), "dvm-artifacts-"));
24864
25271
  try {
24865
25272
  chmodSync(directory, DIRECTORY_MODE);
24866
25273
  } catch (err) {
@@ -25020,6 +25427,19 @@ function printNextActionHuman(action, options = {}) {
25020
25427
  if (line) info(line);
25021
25428
  }
25022
25429
 
25430
+ // src/lib/read-next-action.ts
25431
+ function readNextAction(jobId, messages2, options = {}) {
25432
+ const answered = options.ignoreLocalState ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(jobId);
25433
+ const pending4 = messages2.filter((message2) => !answered.has(message2.seq));
25434
+ const action = computeNextAction(jobId, pending4, void 0, options.ignoreLocalState ? void 0 : options.context);
25435
+ if (action?.type !== "pay" || options.ignoreLocalState) return action;
25436
+ const request2 = pendingPaymentRequest(pending4);
25437
+ const held = loadJob(jobId);
25438
+ if (request2 && held && (held.inFlightPaymentRequestSeqs?.includes(request2.seq) || held.unconfirmedPaymentSubmissions?.[request2.seq] || held.askPaymentBlocks?.[request2.seq]))
25439
+ return { ...action, hint: paymentInFlightHint(jobId, held, request2.seq) };
25440
+ return action;
25441
+ }
25442
+
25023
25443
  // src/lib/wait-for-job.ts
25024
25444
  async function waitForJob(opts, durationMs, now = Date.now) {
25025
25445
  const deadline = now() + durationMs;
@@ -25059,7 +25479,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25059
25479
  }
25060
25480
  return void 0;
25061
25481
  }
25062
- while (now() < deadline) {
25482
+ while (now() < deadline && !hasUnsavedJobState()) {
25063
25483
  const readOptions = () => ({ jobToken: opts.jobToken, timeoutMs: Math.max(1, Math.min(idleTimeoutMs, deadline - now())) });
25064
25484
  const snapshot = await readWithRetry(() => opts.transport.status(opts.jobId, opts.provider, readOptions()));
25065
25485
  if (!snapshot) break;
@@ -25153,7 +25573,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25153
25573
  const progressed = next.cursor > result.cursor;
25154
25574
  result.cursor = Math.min(next.cursor, cursorLimit);
25155
25575
  result.nextAction = next.nextAction;
25156
- if (next.nextAction?.type !== "poll") break;
25576
+ if (hasUnsavedJobState() || next.nextAction?.type !== "poll") break;
25157
25577
  if (progressed) backoffMs = 1e3;
25158
25578
  const delay = Math.min(backoffMs, Math.max(0, deadline - now()));
25159
25579
  if (delay > 0) await new Promise((resolve3) => setTimeout(resolve3, delay));
@@ -25173,7 +25593,7 @@ async function messages(jobId, opts) {
25173
25593
  throw new DvmError("invalid_arguments", "Use --until with --wait, and --wait with streaming enabled.");
25174
25594
  }
25175
25595
  const access = resolveJobAccess(jobId, opts);
25176
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => messagesWithAccess(jobId, opts, access)));
25596
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => messagesWithAccess(jobId, opts, access), opts.human));
25177
25597
  }
25178
25598
  async function messagesWithAccess(jobId, opts, access) {
25179
25599
  const waitDuration = opts.wait ? parseDurationMs(opts.until ?? "12h") : void 0;
@@ -25181,13 +25601,7 @@ async function messagesWithAccess(jobId, opts, access) {
25181
25601
  const { stored, ref, jobToken } = access;
25182
25602
  const json3 = (data) => providerJobJson(data, !!stored);
25183
25603
  function actionFromMessages(batch) {
25184
- const answered = access.endpointOverridden ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(jobId);
25185
- const action = computeNextAction(jobId, batch.filter((message2) => !answered.has(message2.seq)), void 0, access.endpointOverridden ? void 0 : stored ?? void 0);
25186
- const request2 = batch.findLast((message2) => message2.type === "payment-request");
25187
- const current = access.endpointOverridden ? null : loadJob(jobId);
25188
- if (action?.type === "pay" && request2 && current && (current.inFlightPaymentRequestSeqs?.includes(request2.seq) || current.unconfirmedPaymentSubmissions?.[request2.seq] || current.askPaymentBlocks?.[request2.seq]))
25189
- return { ...action, hint: paymentInFlightHint(jobId, current, request2.seq) };
25190
- return action;
25604
+ return readNextAction(jobId, batch, { ignoreLocalState: access.endpointOverridden, context: stored ?? void 0 });
25191
25605
  }
25192
25606
  async function resolveNextAction2(action, messages2, observedStatus) {
25193
25607
  if (action?.type === "refund") return action;
@@ -25439,7 +25853,7 @@ async function message(jobId, text, opts) {
25439
25853
  const access = resolveJobAccess(jobId, opts);
25440
25854
  return withJobTokenRedaction(
25441
25855
  access.jobToken,
25442
- () => withOutputWarnings(() => messageWithAccess(jobId, text, opts, access))
25856
+ () => withOutputWarnings(() => messageWithAccess(jobId, text, opts, access), opts.human)
25443
25857
  );
25444
25858
  }
25445
25859
  async function messageWithAccess(jobId, text, opts, access) {
@@ -25577,7 +25991,7 @@ function parseForcedRail(raw2) {
25577
25991
  // src/commands/pay.ts
25578
25992
  async function pay(jobId, opts) {
25579
25993
  const access = resolveStoredJobAccess(jobId, opts);
25580
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => payWithAccess(jobId, opts, access)));
25994
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => payWithAccess(jobId, opts, access), opts.human));
25581
25995
  }
25582
25996
  async function payWithAccess(jobId, opts, access) {
25583
25997
  const rail = parseForcedRail(opts.rail);
@@ -26100,7 +26514,7 @@ function isPlainObject2(value) {
26100
26514
 
26101
26515
  // src/commands/quote.ts
26102
26516
  async function quote(opts) {
26103
- return withOutputWarnings(() => quoteWithWarnings(opts));
26517
+ return withOutputWarnings(() => quoteWithWarnings(opts), opts.human);
26104
26518
  }
26105
26519
  async function quoteWithWarnings(opts) {
26106
26520
  if (!opts.dvm && !opts.endpoint) {
@@ -26663,8 +27077,9 @@ async function refetchAnchor(endpointOrAlias) {
26663
27077
  function deliveredFromMessages(jobId, receipt) {
26664
27078
  const messages2 = loadMessages(jobId);
26665
27079
  if (messages2.length === 0) return void 0;
26666
- if (!messages2.some((m) => isCompleteMessage(m) || isCancelMessage(m))) return void 0;
26667
- const completion = loadJob(jobId)?.completion;
27080
+ const job = loadJob(jobId);
27081
+ if (!messages2.some((m) => isCompleteMessage(m) || isCancelMessage(m) || m.type === "decline" && job?.callerDeclined === true && isTerminalJobStatus(job.status))) return void 0;
27082
+ const completion = job?.completion;
26668
27083
  if (completion?.hasArtifacts === void 0) return void 0;
26669
27084
  const artifacts = messages2.filter(isArtifactMessage);
26670
27085
  if (artifacts.length !== (completion.artifactCount ?? 0)) return void 0;
@@ -27125,9 +27540,23 @@ function resolveBudget(current, minimumMsats) {
27125
27540
 
27126
27541
  // src/commands/request.ts
27127
27542
  async function request(opts) {
27128
- return withOutputWarnings(() => requestWithWarnings(opts));
27543
+ const stage = { intentReached: false };
27544
+ return withOutputWarnings(async () => {
27545
+ try {
27546
+ await requestWithWarnings(opts, stage);
27547
+ } catch (error) {
27548
+ throw stage.intentReached ? error : markRefusedBeforeSend(opts.requestId, error);
27549
+ }
27550
+ }, opts.human);
27551
+ }
27552
+ function markRefusedBeforeSend(requestId, error) {
27553
+ if (!requestId || !(error instanceof DvmError)) return error;
27554
+ const reason = error.data?.reason;
27555
+ if (!recordRequestRefusal(requestId, { code: error.code, reason })) return error;
27556
+ error.data = { ...error.data, submitted: false };
27557
+ return error;
27129
27558
  }
27130
- async function requestWithWarnings(opts) {
27559
+ async function requestWithWarnings(opts, stage) {
27131
27560
  const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
27132
27561
  const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 3e4;
27133
27562
  const requestedMaxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
@@ -27380,7 +27809,7 @@ async function requestWithWarnings(opts) {
27380
27809
  throw new DvmError(
27381
27810
  "credit_only_unavailable",
27382
27811
  `Prepaid credit ${opts.creditOnly} is not drawable under the current caller state.`,
27383
- "Reconcile that exact credit with 'dvm credit balance <dvm> --credit-id <id>'; this request did not fall back to a wallet payment.",
27812
+ probePlan.mode === "none" && probePlan.drawSkipped?.reason === "posture_off" ? buildCreditDrawSkipped({ dvm: identity.dvmId ?? endpoint, endpoint, skip: probePlan.drawSkipped }).hint : "Reconcile that exact credit with 'dvm credit balance <dvm> --credit-id <id>'; this request did not fall back to a wallet payment.",
27384
27813
  {
27385
27814
  credit_id: opts.creditOnly,
27386
27815
  ...probePlan.mode === "none" && probePlan.drawSkipped ? { reason: probePlan.drawSkipped.reason } : {}
@@ -27419,6 +27848,7 @@ async function requestWithWarnings(opts) {
27419
27848
  }
27420
27849
  let envelope = { ...envelopeBase, data };
27421
27850
  let jobRequestId = opts.requestId ?? drawRequestId;
27851
+ stage.intentReached = true;
27422
27852
  if (jobRequestId) {
27423
27853
  persistRequestIntent({
27424
27854
  requestId: jobRequestId,
@@ -27670,7 +28100,7 @@ async function requestWithWarnings(opts) {
27670
28100
  }
27671
28101
  case "awaiting-input":
27672
28102
  case "processing": {
27673
- updateJob(receipt.jobId, {
28103
+ updateObservedJob(receipt.jobId, {
27674
28104
  status: receipt.status === "awaiting-input" ? "awaiting-input" : "processing"
27675
28105
  });
27676
28106
  const result = await streamToCompletion(
@@ -28582,7 +29012,7 @@ async function payWithTempo(args, credential) {
28582
29012
  }
28583
29013
  const effectiveJobId = args.jobId || receipt.jobId;
28584
29014
  if (!args.jobId && receipt.jobId) {
28585
- saveJob({
29015
+ saveAcceptedJob({
28586
29016
  id: effectiveJobId,
28587
29017
  ...transactionRecordFields(receipt),
28588
29018
  endpoint: ref.endpoint,
@@ -28674,7 +29104,7 @@ async function payWithTempo(args, credential) {
28674
29104
  }
28675
29105
  return;
28676
29106
  }
28677
- updateJob(effectiveJobId, {
29107
+ updateObservedJob(effectiveJobId, {
28678
29108
  status: "processing",
28679
29109
  paymentMethod: "tempo"
28680
29110
  });
@@ -28750,6 +29180,7 @@ function persistRequestIntent(args) {
28750
29180
  { request_id: requestId, status: "unknown" }
28751
29181
  );
28752
29182
  }
29183
+ clearRequestRefusal(requestId);
28753
29184
  }
28754
29185
  function submitCanCarryGeneratedRequestId(args) {
28755
29186
  return args.opts.requestId === void 0 && args.opts.creditOnly === void 0 && args.providerInfo.requestRecovery === true && args.providerInfo.auth?.includes(SIGNED_REQUEST_AUTH_ID) === true && args.signing !== void 0;
@@ -28801,7 +29232,21 @@ function requestIdOutputFields(requestId) {
28801
29232
  function normalizedLocalCorrelationId(opts) {
28802
29233
  return opts.localCorrelationId === void 0 ? void 0 : normalizeLocalCorrelationId(opts.localCorrelationId);
28803
29234
  }
29235
+ var PREACCEPT_REFUSAL_CODES = /* @__PURE__ */ new Set([
29236
+ "invalid_input",
29237
+ "budget_exceeded",
29238
+ "cashu_fee_cap_exceeded",
29239
+ "insufficient_balance",
29240
+ "no_eligible_mint",
29241
+ "mint_not_allowed",
29242
+ "mint_pin_unsatisfiable",
29243
+ "rail_unsatisfiable",
29244
+ "tempo_network_mismatch"
29245
+ ]);
28804
29246
  function requestOutcomeUnknown(requestId, cause) {
29247
+ if (cause instanceof DvmError && PREACCEPT_REFUSAL_CODES.has(cause.code) && !postPaymentErrors.has(cause) && cause.data?.spend_committed !== true && cause.data?.status !== "unknown" && cause.data?.payment_state !== "unknown") {
29248
+ return cause;
29249
+ }
28805
29250
  if (cause instanceof DvmError && typeof cause.data?.job_id === "string" && loadJob(cause.data.job_id)?.requestId === requestId) {
28806
29251
  return cause;
28807
29252
  }
@@ -29228,7 +29673,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29228
29673
  }
29229
29674
  const effectiveJobId = jobId || receipt.jobId;
29230
29675
  if (!jobId && receipt.jobId) {
29231
- saveJob({
29676
+ saveAcceptedJob({
29232
29677
  id: effectiveJobId,
29233
29678
  ...transactionRecordFields(receipt),
29234
29679
  endpoint: ref.endpoint,
@@ -29260,7 +29705,9 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29260
29705
  ...localCorrelationJobFields(normalizedLocalCorrelationId(opts))
29261
29706
  });
29262
29707
  }
29263
- await commitAgentSpend({
29708
+ await collectCashuChange(effectiveJobId, receipt.cashuChange);
29709
+ recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
29710
+ if (!hasUnsavedJobState()) await commitAgentSpend({
29264
29711
  requestId: prepared.requestId,
29265
29712
  recentSpend: {
29266
29713
  request_id: prepared.requestId,
@@ -29270,9 +29717,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29270
29717
  signed_at_ms: Date.now()
29271
29718
  }
29272
29719
  });
29273
- await collectCashuChange(effectiveJobId, receipt.cashuChange);
29274
- recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
29275
- if (fundPlan) {
29720
+ if (!hasUnsavedJobState() && fundPlan) {
29276
29721
  recordSpend({
29277
29722
  msats: fundPlan.fundMsats,
29278
29723
  btcRate,
@@ -29281,7 +29726,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29281
29726
  providerEndpoint: ref.endpoint,
29282
29727
  label: `credit fund \xB7 ${identity.dvmId ?? identity.capability}`
29283
29728
  });
29284
- } else {
29729
+ } else if (!hasUnsavedJobState()) {
29285
29730
  recordSpend({
29286
29731
  msats: chosen.priceMsats,
29287
29732
  btcRate,
@@ -29340,7 +29785,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29340
29785
  }
29341
29786
  return;
29342
29787
  }
29343
- updateJob(effectiveJobId, {
29788
+ updateObservedJob(effectiveJobId, {
29344
29789
  status: "processing",
29345
29790
  paymentMethod: "cashu"
29346
29791
  });
@@ -29458,7 +29903,7 @@ async function payWithX402(args, proof) {
29458
29903
  }
29459
29904
  const effectiveJobId = args.jobId || receipt.jobId;
29460
29905
  if (!args.jobId && receipt.jobId) {
29461
- saveJob({
29906
+ saveAcceptedJob({
29462
29907
  id: effectiveJobId,
29463
29908
  ...transactionRecordFields(receipt),
29464
29909
  endpoint: ref.endpoint,
@@ -29539,7 +29984,7 @@ async function payWithX402(args, proof) {
29539
29984
  }
29540
29985
  return;
29541
29986
  }
29542
- updateJob(effectiveJobId, {
29987
+ updateObservedJob(effectiveJobId, {
29543
29988
  status: "processing",
29544
29989
  paymentMethod: "x402"
29545
29990
  });
@@ -29574,7 +30019,7 @@ async function streamToCompletion(baseOpts, deadlineMs) {
29574
30019
  const allMessages = [...result.messages];
29575
30020
  const allAutoPayments = [...result.autoPayments];
29576
30021
  const allRefunds = [...result.refunds];
29577
- while (result.nextAction?.type === "poll") {
30022
+ while (result.nextAction?.type === "poll" && !hasUnsavedJobState()) {
29578
30023
  if (Date.now() >= deadlineMs) break;
29579
30024
  const waitMs = Math.min(
29580
30025
  Math.max((result.nextAction.estimate_seconds ?? 0) * 1e3, MIN_POLL_WAIT_MS),
@@ -29662,7 +30107,7 @@ async function streamAfterPayment(args) {
29662
30107
  });
29663
30108
  }
29664
30109
  transport.close?.();
29665
- if (result.messages.length === 0) {
30110
+ if (result.messages.length === 0 && !hasUnsavedJobState()) {
29666
30111
  const recovered = await recoverViaStatusPoll({
29667
30112
  jobId,
29668
30113
  transport,
@@ -29721,7 +30166,7 @@ async function streamAfterPayment(args) {
29721
30166
  jobId,
29722
30167
  ...dvmFields,
29723
30168
  messages: result.messages.map(serializeMessageForOutput),
29724
- ...streamedTerminal ? { status: streamedTerminal } : {},
30169
+ ...streamedTerminal ? { status: streamedTerminal } : hasUnsavedJobState() ? { status: "processing" } : {},
29725
30170
  ...completion?.message !== void 0 ? { message: completion.message } : {},
29726
30171
  // Same as the unpaid arc above: the outcome is only knowable from the
29727
30172
  // streamed log here, so render it rather than leaving the agent to dig
@@ -29846,7 +30291,7 @@ async function collectCashuChange(jobId, cashuChange) {
29846
30291
  } catch {
29847
30292
  }
29848
30293
  if (sats > 0) {
29849
- updateJob(jobId, { changeProcessed: true });
30294
+ updateObservedJob(jobId, { changeProcessed: true });
29850
30295
  info(`Received ${sats} sats change.`);
29851
30296
  }
29852
30297
  }
@@ -29867,6 +30312,9 @@ async function readStdin() {
29867
30312
 
29868
30313
  // src/commands/request-result.ts
29869
30314
  async function requestResult(requestId, opts = {}) {
30315
+ return withOutputWarnings(() => requestResultWithWarnings(requestId, opts), opts.human);
30316
+ }
30317
+ async function requestResultWithWarnings(requestId, opts) {
29870
30318
  if (!isPublicRequestId(requestId)) {
29871
30319
  throw new DvmError(
29872
30320
  "invalid_request_id",
@@ -29876,11 +30324,9 @@ async function requestResult(requestId, opts = {}) {
29876
30324
  }
29877
30325
  const intent = loadRequestIntent(requestId);
29878
30326
  if (!intent) {
29879
- throw new DvmError(
29880
- "request_not_found",
29881
- `No local intent exists for request ${requestId}.`,
29882
- "The outcome is unknown. Do not submit or pay for a replacement; restore the original caller state and retry.",
29883
- { request_id: requestId, status: "unknown" }
30327
+ throw requestNotFound(
30328
+ requestId,
30329
+ "The outcome is unknown. Do not submit or pay for a replacement; restore the original caller state and retry."
29884
30330
  );
29885
30331
  }
29886
30332
  const signer = findSigningIdentityByPubkey(intent.callerPubkey);
@@ -29961,9 +30407,9 @@ async function requestResult(requestId, opts = {}) {
29961
30407
  "Do not overwrite the local record."
29962
30408
  );
29963
30409
  }
29964
- updateJob(receipt.jobId, restored);
30410
+ updateObservedJob(receipt.jobId, restored);
29965
30411
  } else {
29966
- saveJob({
30412
+ saveAcceptedJob({
29967
30413
  id: receipt.jobId,
29968
30414
  endpoint: intent.endpoint,
29969
30415
  dvmId: intent.dvmId,
@@ -29991,7 +30437,7 @@ async function requestResult(requestId, opts = {}) {
29991
30437
  if (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled") {
29992
30438
  markJobTerminal(receipt.jobId, receipt.status, completionSnapshot(receipt), restored);
29993
30439
  } else {
29994
- updateJob(receipt.jobId, {
30440
+ updateObservedJob(receipt.jobId, {
29995
30441
  status: receipt.status === "awaiting-input" ? "awaiting-input" : "processing",
29996
30442
  ...restored
29997
30443
  });
@@ -30001,7 +30447,7 @@ async function requestResult(requestId, opts = {}) {
30001
30447
  if (recovered && (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled")) {
30002
30448
  await settleCreditAfterRead({ job: recovered, capture: captured, transport, human: opts.human });
30003
30449
  }
30004
- const confirmed = await bookRecoveredSubmissions({
30450
+ const confirmed = hasUnsavedJobState() ? [] : await bookRecoveredSubmissions({
30005
30451
  publicRequestId: requestId,
30006
30452
  endpoint: intent.endpoint,
30007
30453
  jobId: receipt.jobId
@@ -30030,6 +30476,30 @@ async function requestResult(requestId, opts = {}) {
30030
30476
  }
30031
30477
  });
30032
30478
  }
30479
+ function requestNotFound(requestId, unknownHint) {
30480
+ const refusal = loadRequestRefusal(requestId);
30481
+ if (!refusal) {
30482
+ return new DvmError(
30483
+ "request_not_found",
30484
+ `No local intent exists for request ${requestId}.`,
30485
+ unknownHint,
30486
+ { request_id: requestId, status: "unknown" }
30487
+ );
30488
+ }
30489
+ return new DvmError(
30490
+ "request_not_submitted",
30491
+ `Request ${requestId} was refused locally before it was sent.`,
30492
+ "No job or payment was sent for this request id. Retrying the same approved request is safe.",
30493
+ {
30494
+ request_id: requestId,
30495
+ status: "not_submitted",
30496
+ submitted: false,
30497
+ refusal_code: refusal.code,
30498
+ ...refusal.reason ? { refusal_reason: refusal.reason } : {},
30499
+ refused_at: new Date(refusal.refusedAt).toISOString()
30500
+ }
30501
+ );
30502
+ }
30033
30503
  function signedIntentEnvelope(intent, privkey, route) {
30034
30504
  const body = intent.body;
30035
30505
  const data = body.data;
@@ -30073,7 +30543,7 @@ function paymentMethod(receipt) {
30073
30543
 
30074
30544
  // src/commands/request-resume.ts
30075
30545
  async function requestResume(requestId, opts = {}) {
30076
- return withOutputWarnings(() => resumeRequest(requestId, opts));
30546
+ return withOutputWarnings(() => resumeRequest(requestId, opts), opts.human);
30077
30547
  }
30078
30548
  async function resumeRequest(requestId, opts) {
30079
30549
  if (!isPublicRequestId(requestId)) {
@@ -30091,11 +30561,9 @@ async function resumeRequest(requestId, opts) {
30091
30561
  }
30092
30562
  const intent = loadRequestIntent(requestId);
30093
30563
  if (!intent) {
30094
- throw new DvmError(
30095
- "request_not_found",
30096
- `No local intent exists for request ${requestId}.`,
30097
- "The outcome is unknown. Restore the original caller state; never submit or pay for a replacement.",
30098
- { request_id: requestId, status: "unknown" }
30564
+ throw requestNotFound(
30565
+ requestId,
30566
+ "The outcome is unknown. Restore the original caller state; never submit or pay for a replacement."
30099
30567
  );
30100
30568
  }
30101
30569
  const signer = findSigningIdentityByPubkey(intent.callerPubkey);
@@ -30428,18 +30896,20 @@ function renderSpendHuman(spend, print) {
30428
30896
  // src/commands/status.ts
30429
30897
  async function status(jobId, opts) {
30430
30898
  const access = resolveJobAccess(jobId, opts);
30431
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => statusWithAccess(jobId, opts, access)));
30899
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => statusWithAccess(jobId, opts, access), opts.human));
30432
30900
  }
30433
30901
  async function statusWithAccess(jobId, opts, access) {
30434
30902
  const { stored, ref, jobToken } = access;
30435
- if (stored && !access.overridden && isTerminalJobStatus(stored.status) && stored.completion && !opts.messages) {
30903
+ if (stored && !access.overridden && isTerminalJobStatus(stored.status) && (stored.completion || stored.status !== "completed") && !opts.messages) {
30436
30904
  let receipt2 = replayStoredReceipt(stored);
30437
30905
  let terminalStatus = stored.status;
30438
- let completion2 = stored.completion;
30906
+ let completion2 = stored.completion ?? {};
30907
+ let content;
30439
30908
  const transport2 = createDvmTransport();
30440
30909
  if (stored.receiptsSupported && receipt2.status === "absent") {
30441
30910
  const fetched = await fetchMissingJobReceipt(jobId, transport2, ref);
30442
30911
  if (fetched.status && isTerminalJobStatus(fetched.status)) {
30912
+ content = fetched;
30443
30913
  const saved = stored.status === fetched.status ? completion2 : void 0;
30444
30914
  terminalStatus = fetched.status;
30445
30915
  completion2 = fetched.content_available === false && saved ? saved : { ...saved, ...completionSnapshot(fetched) };
@@ -30452,10 +30922,21 @@ async function statusWithAccess(jobId, opts, access) {
30452
30922
  receipt2 = captureTransportReceipt(jobId, fetched);
30453
30923
  }
30454
30924
  }
30925
+ if (terminalStatus !== "completed" && completion2.hasArtifacts === void 0 && content?.content_available !== false) {
30926
+ completion2 = await readTerminalCompletion({
30927
+ jobId,
30928
+ status: { ...completion2, ...content, status: terminalStatus },
30929
+ transport: transport2,
30930
+ ref,
30931
+ jobToken
30932
+ });
30933
+ markJobTerminal(jobId, terminalStatus, completion2);
30934
+ }
30455
30935
  await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
30456
30936
  transport2.close();
30457
30937
  renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
30458
- receipt: receipt2
30938
+ receipt: receipt2,
30939
+ content
30459
30940
  });
30460
30941
  return;
30461
30942
  }
@@ -30479,9 +30960,9 @@ async function statusWithAccess(jobId, opts, access) {
30479
30960
  timeoutMs: timeout,
30480
30961
  jobToken,
30481
30962
  context: access.endpointOverridden ? void 0 : stored ?? void 0,
30482
- held: access.endpointOverridden ? void 0 : loadJob(jobId)
30963
+ ignoreLocalState: access.endpointOverridden
30483
30964
  });
30484
- const completion = completionSnapshot(result);
30965
+ let completion = completionSnapshot(result);
30485
30966
  const reasonUnavailable = completion.message === void 0 || result.content_available === false && completion.message === "";
30486
30967
  if (reasonUnavailable && (result.status === "failed" || result.status === "cancelled")) {
30487
30968
  const savedReason = !access.endpointOverridden && stored?.status === result.status ? stored.completion?.message : void 0;
@@ -30489,6 +30970,17 @@ async function statusWithAccess(jobId, opts, access) {
30489
30970
  const reason = savedReason ?? (terminal?.type === "cancel" || terminal?.type === "decline" ? terminal.content.reason : void 0);
30490
30971
  if (reason !== void 0) completion.message = reason;
30491
30972
  }
30973
+ if (isTerminalJobStatus(result.status)) {
30974
+ completion = await readTerminalCompletion({
30975
+ jobId,
30976
+ status: { ...result, ...completion },
30977
+ transport,
30978
+ ref,
30979
+ jobToken,
30980
+ timeoutMs: timeout,
30981
+ saved: !access.endpointOverridden && stored?.status === result.status ? stored.completion : void 0
30982
+ });
30983
+ }
30492
30984
  let receipt;
30493
30985
  let currency;
30494
30986
  if (isTerminalJobStatus(result.status)) {
@@ -30519,7 +31011,7 @@ async function statusWithAccess(jobId, opts, access) {
30519
31011
  const updates = {};
30520
31012
  if (result.status === "processing") updates.status = "processing";
30521
31013
  if (newCursor !== void 0) updates.messageCursor = newCursor;
30522
- if (Object.keys(updates).length > 0) updateJob(jobId, updates);
31014
+ if (Object.keys(updates).length > 0) updateObservedJob(jobId, updates);
30523
31015
  }
30524
31016
  transport.close();
30525
31017
  renderStatus(jobId, stored, result.status, completion, "provider", nextAction, opts, {
@@ -30544,7 +31036,10 @@ function transientReceiptCapture(jobId, response, endpoint, currency) {
30544
31036
  }
30545
31037
  function renderStatus(jobId, stored, jobStatus, completion, source, nextAction, opts, fetched) {
30546
31038
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
30547
- const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, opts.human);
31039
+ const artifacts = terminalCompletionOutput(jobId, jobStatus, completion, {
31040
+ human: opts.human,
31041
+ contentAvailable: fetched?.content?.content_available
31042
+ });
30548
31043
  const msgs = fetched?.msgs ?? [];
30549
31044
  const receipt = fetched?.receipt;
30550
31045
  const content = jobContentFields(jobId, fetched?.content, opts.human);
@@ -30566,7 +31061,7 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
30566
31061
  info(`Status: ${jobStatus}${identifier ? ` [${identifier}]` : ""}`);
30567
31062
  if (completion.message) info(` ${completion.message}`);
30568
31063
  }
30569
- if (jobStatus === "completed" && hint) info(`\u{1F4CE} ${hint}`);
31064
+ if (artifacts.hint) info(`\u{1F4CE} ${artifacts.hint}`);
30570
31065
  info(String(content.content_hint));
30571
31066
  if (msgs.length > 0) {
30572
31067
  info(`
@@ -30596,7 +31091,8 @@ ${msgs.length} new message(s):`);
30596
31091
  ],
30597
31092
  ...content,
30598
31093
  ...completion.summary ? { summary: completion.summary } : {},
30599
- ...jobStatus === "completed" ? buildCompletionHintFields(jobId, completion) : {},
31094
+ ...artifacts.fields,
31095
+ ...artifacts.display ? { display: artifacts.display } : {},
30600
31096
  ...completion.message ? { message: completion.message } : {},
30601
31097
  // terminal responses only. On a still-running job "absent" would
30602
31098
  // read as "this DVM doesn't issue receipts" rather than "not yet".
@@ -30620,20 +31116,13 @@ ${msgs.length} new message(s):`);
30620
31116
  async function resolveNextAction(jobId, status2, fetched, transport, ref, opts) {
30621
31117
  if (isTerminalJobStatus(status2)) return null;
30622
31118
  if (status2 === "awaiting-input") {
30623
- const fromBatch = computeNextAction(jobId, fetched, void 0, opts.context);
30624
- if (fromBatch) return withHeldPaymentHint(jobId, fromBatch, fetched, opts.held);
31119
+ const fromBatch = readNextAction(jobId, fetched, opts);
31120
+ if (fromBatch) return fromBatch;
30625
31121
  const history = await transport.getMessages(jobId, 0, ref, opts);
30626
- return withHeldPaymentHint(jobId, computeNextAction(jobId, history, void 0, opts.context), history, opts.held) ?? pollNextAction(jobId);
31122
+ return readNextAction(jobId, history, opts) ?? pollNextAction(jobId);
30627
31123
  }
30628
31124
  return pollNextAction(jobId);
30629
31125
  }
30630
- function withHeldPaymentHint(jobId, action, messages2, held) {
30631
- if (action?.type !== "pay" || !held) return action;
30632
- const ask = pendingPaymentRequest(messages2);
30633
- if (!ask || !(held.inFlightPaymentRequestSeqs?.includes(ask.seq) || held.unconfirmedPaymentSubmissions?.[ask.seq] || held.askPaymentBlocks?.[ask.seq]))
30634
- return action;
30635
- return { ...action, hint: paymentInFlightHint(jobId, held, ask.seq) };
30636
- }
30637
31126
 
30638
31127
  // src/commands/upload.ts
30639
31128
  import { statSync as statSync4 } from "fs";
@@ -32698,7 +33187,7 @@ function mnemonicValidationError(result) {
32698
33187
  var import_qrcode = __toESM(require_lib(), 1);
32699
33188
  import { randomBytes as randomBytes3 } from "crypto";
32700
33189
  import { tmpdir as tmpdir2 } from "os";
32701
- import { join as join8 } from "path";
33190
+ import { join as join9 } from "path";
32702
33191
  async function renderQrTerminal(payload) {
32703
33192
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
32704
33193
  }
@@ -32711,7 +33200,7 @@ async function renderQrPng(payload, outPath) {
32711
33200
  });
32712
33201
  }
32713
33202
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
32714
- return join8(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
33203
+ return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
32715
33204
  }
32716
33205
 
32717
33206
  // src/lib/funding-handoff.ts
@@ -34575,6 +35064,57 @@ async function writeInvoicePng(invoice, outPath) {
34575
35064
  }
34576
35065
 
34577
35066
  // src/lib/wallet-agent/release.ts
35067
+ import { randomUUID as randomUUID5 } from "crypto";
35068
+
35069
+ // src/lib/wallet-agent/release-intents.ts
35070
+ var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
35071
+ import { createHash as createHash6 } from "crypto";
35072
+ import { dirname as dirname4, join as join10 } from "path";
35073
+ var intents = journalFile("release-intents.json");
35074
+ async function withReleaseLock(walletPubkey, builderHandle, mint, operation) {
35075
+ ensureConfigDir();
35076
+ const key = createHash6("sha256").update(JSON.stringify([walletPubkey, builderHandle, mint])).digest("hex");
35077
+ let unlock;
35078
+ try {
35079
+ unlock = await import_proper_lockfile3.default.lock(join10(dirname4(JOBS_FILE), `release-${key}`), {
35080
+ realpath: false,
35081
+ stale: 2 * 6e4,
35082
+ retries: 0
35083
+ });
35084
+ } catch {
35085
+ throw new Error("Could not acquire the release lock; another release may be running for this builder and mint. Retry `dvm wallet release` shortly.");
35086
+ }
35087
+ try {
35088
+ return await operation();
35089
+ } finally {
35090
+ try {
35091
+ await unlock();
35092
+ } catch {
35093
+ }
35094
+ }
35095
+ }
35096
+ function allReleaseIntents() {
35097
+ return intents.read();
35098
+ }
35099
+ function loadReleaseIntent(walletPubkey, builderHandle, mint) {
35100
+ return intents.read().find(
35101
+ (intent) => intent.walletPubkey === walletPubkey && intent.builderHandle === builderHandle && intent.mint === mint
35102
+ );
35103
+ }
35104
+ function recordReleaseIntent(intent) {
35105
+ intents.withLock(() => {
35106
+ if (loadReleaseIntent(intent.walletPubkey, intent.builderHandle, intent.mint)) {
35107
+ throw new Error("Another release is awaiting recovery; retry `dvm wallet release`.");
35108
+ }
35109
+ intents.write([...intents.read(), intent]);
35110
+ });
35111
+ }
35112
+ function clearReleaseIntent(intent) {
35113
+ intents.withLock(() => intents.write(intents.read().filter((held) => held.id !== intent.id)));
35114
+ }
35115
+
35116
+ // src/lib/wallet-agent/release.ts
35117
+ var RELEASE_IN_FLIGHT_MS = 2 * 6e4;
34578
35118
  async function releaseAgentReserve(opts) {
34579
35119
  const cashu = opts.providerInfo.cashu;
34580
35120
  if (!cashu?.canonical_id) {
@@ -34604,9 +35144,6 @@ async function releaseAgentReserve(opts) {
34604
35144
  const candidates = initial.proofs.filter(
34605
35145
  (p) => p.reserved_for === marker && p.status === "valid" && typeof p.t_expire === "number" && p.t_expire < now
34606
35146
  );
34607
- if (candidates.length === 0) {
34608
- return { builder_handle: opts.builderHandle, output_mode: outputMode, mints: [] };
34609
- }
34610
35147
  const getWalletForMint = opts.getWalletForMint ?? getWallet;
34611
35148
  const byMint = /* @__PURE__ */ new Map();
34612
35149
  for (const p of candidates) {
@@ -34614,47 +35151,60 @@ async function releaseAgentReserve(opts) {
34614
35151
  bucket.push(p);
34615
35152
  byMint.set(p.mint, bucket);
34616
35153
  }
35154
+ for (const intent of allReleaseIntents()) {
35155
+ if (intent.walletPubkey === initial.lock_pubkey && intent.builderHandle === opts.builderHandle && !byMint.has(intent.mint)) {
35156
+ byMint.set(intent.mint, []);
35157
+ }
35158
+ }
34617
35159
  const outcomes = [];
34618
35160
  for (const [mintUrl, mintProofs] of byMint) {
34619
- outcomes.push(
34620
- await releaseAtMint(
35161
+ try {
35162
+ outcomes.push(await withReleaseLock(
35163
+ initial.lock_pubkey,
35164
+ opts.builderHandle,
34621
35165
  mintUrl,
34622
- mintProofs,
34623
- refund.privkey,
34624
- initial,
34625
- outputMode,
34626
- getWalletForMint
34627
- )
34628
- );
35166
+ () => releaseAtMint(mintUrl, mintProofs, refund.privkey, initial, outputMode, getWalletForMint, opts.builderHandle, now)
35167
+ ));
35168
+ } catch (err) {
35169
+ outcomes.push({ mint: mintUrl, output_mode: null, alreadySpent: [], pending: [], reclaimedInputs: [], reclaimedOutputs: [], error: errorText2(err) });
35170
+ }
34629
35171
  }
34630
- return { builder_handle: opts.builderHandle, output_mode: outputMode, mints: outcomes };
35172
+ const modes = new Set(outcomes.flatMap((outcome) => outcome.output_mode === null ? [] : [outcome.output_mode]));
35173
+ return {
35174
+ builder_handle: opts.builderHandle,
35175
+ output_mode: modes.size > 1 ? "mixed" : modes.values().next().value ?? outputMode,
35176
+ mints: outcomes
35177
+ };
34631
35178
  }
34632
- async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, outputMode, getWalletForMint) {
35179
+ async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, outputMode, getWalletForMint, builderHandle, now) {
35180
+ const outcome = {
35181
+ mint: mintUrl,
35182
+ output_mode: null,
35183
+ alreadySpent: [],
35184
+ pending: [],
35185
+ reclaimedInputs: [],
35186
+ reclaimedOutputs: [],
35187
+ error: null
35188
+ };
34633
35189
  let cashuWallet;
34634
35190
  try {
34635
35191
  cashuWallet = await getWalletForMint(mintUrl);
35192
+ const intent2 = loadReleaseIntent(initial.lock_pubkey, builderHandle, mintUrl);
35193
+ if (intent2) {
35194
+ const recovered = await recoverRelease(intent2, cashuWallet, outcome, now);
35195
+ if (recovered) return recovered;
35196
+ }
35197
+ const available = new Set(currentWallet(initial.lock_pubkey).proofs.filter((p) => p.mint === mintUrl && p.status === "valid").map(proofIdKey));
35198
+ mintProofs = mintProofs.filter((p) => available.has(proofIdKey(p)));
34636
35199
  } catch (err) {
34637
- return {
34638
- mint: mintUrl,
34639
- alreadySpent: [],
34640
- pending: [],
34641
- reclaimedInputs: [],
34642
- reclaimedOutputs: [],
34643
- error: err instanceof Error ? err.message : String(err)
34644
- };
35200
+ return { ...outcome, error: errorText2(err) };
34645
35201
  }
35202
+ if (mintProofs.length === 0) return outcome;
34646
35203
  let grouped;
34647
35204
  try {
34648
35205
  grouped = await cashuWallet.groupProofsByState(toCashuProofs(mintProofs));
34649
35206
  } catch (err) {
34650
- return {
34651
- mint: mintUrl,
34652
- alreadySpent: [],
34653
- pending: [],
34654
- reclaimedInputs: [],
34655
- reclaimedOutputs: [],
34656
- error: err instanceof Error ? err.message : String(err)
34657
- };
35207
+ return { ...outcome, error: errorText2(err) };
34658
35208
  }
34659
35209
  const spentSecrets = new Set(grouped.spent.map((p) => p.secret));
34660
35210
  const pendingSecrets = new Set(grouped.pending.map((p) => p.secret));
@@ -34663,29 +35213,24 @@ async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, output
34663
35213
  const unspent = mintProofs.filter(
34664
35214
  (p) => !spentSecrets.has(p.secret) && !pendingSecrets.has(p.secret)
34665
35215
  );
34666
- if (alreadySpent.length > 0) {
35216
+ outcome.pending = pending4;
35217
+ try {
34667
35218
  await withWalletLock(() => {
34668
- const fresh = loadAgentWallet() ?? initial;
34669
- const spentKeys = new Set(alreadySpent.map((p) => proofIdKey(p)));
34670
- saveAgentWallet({
34671
- ...fresh,
34672
- proofs: fresh.proofs.filter((p) => !spentKeys.has(proofIdKey(p)))
34673
- });
35219
+ assertNoRelease(initial.lock_pubkey, builderHandle, mintUrl);
35220
+ const fresh = currentWallet(initial.lock_pubkey);
35221
+ if (alreadySpent.length > 0) {
35222
+ const spentKeys = new Set(alreadySpent.map(proofIdKey));
35223
+ saveAgentWallet({ ...fresh, proofs: fresh.proofs.filter((p) => p.mint !== mintUrl || !spentKeys.has(proofIdKey(p))) });
35224
+ }
34674
35225
  });
35226
+ outcome.alreadySpent = alreadySpent;
35227
+ } catch (err) {
35228
+ return { ...outcome, error: errorText2(err) };
34675
35229
  }
34676
- if (unspent.length === 0) {
34677
- return {
34678
- mint: mintUrl,
34679
- alreadySpent,
34680
- pending: pending4,
34681
- reclaimedInputs: [],
34682
- reclaimedOutputs: [],
34683
- error: null
34684
- };
34685
- }
35230
+ if (unspent.length === 0) return outcome;
34686
35231
  const totalSats = unspent.reduce((sum, p) => sum + p.amount, 0);
34687
35232
  const inputs = toCashuProofs(unspent);
34688
- let outputs;
35233
+ let preview;
34689
35234
  try {
34690
35235
  const swapFeeSats = swapFeeForProofs(cashuWallet, inputs);
34691
35236
  const reclaimSats = totalSats - swapFeeSats;
@@ -34695,38 +35240,134 @@ async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, output
34695
35240
  );
34696
35241
  }
34697
35242
  const builder = cashuWallet.ops.send(reclaimSats, inputs).privkey(refundPrivkey);
34698
- const result = outputMode === "locked" ? await builder.asP2PK({ pubkey: initial.lock_pubkey }).run() : await builder.asRandom().run();
34699
- outputs = result.send;
35243
+ preview = outputMode === "locked" ? await builder.asP2PK({ pubkey: initial.lock_pubkey }).keepAsP2PK({ pubkey: initial.lock_pubkey }).prepare() : await builder.asRandom().keepAsRandom().prepare();
34700
35244
  } catch (err) {
34701
- return {
34702
- mint: mintUrl,
34703
- alreadySpent,
34704
- pending: pending4,
34705
- reclaimedInputs: [],
34706
- reclaimedOutputs: [],
34707
- error: err instanceof Error ? err.message : String(err)
34708
- };
35245
+ return { ...outcome, error: errorText2(err) };
34709
35246
  }
34710
- const reclaimedOutputs = outputs.map(
34711
- (p) => toAgentProof(p, mintUrl, outputMode === "locked" ? initial.lock_pubkey : null)
34712
- );
34713
- await withWalletLock(() => {
34714
- const fresh = loadAgentWallet() ?? initial;
34715
- const inputKeys = new Set(unspent.map((p) => proofIdKey(p)));
34716
- saveAgentWallet({
34717
- ...fresh,
34718
- proofs: [...fresh.proofs.filter((p) => !inputKeys.has(proofIdKey(p))), ...reclaimedOutputs]
35247
+ const selected = new Set(preview.inputs.map(proofIdKey));
35248
+ const intent = {
35249
+ id: randomUUID5(),
35250
+ builderHandle,
35251
+ mint: mintUrl,
35252
+ walletPubkey: initial.lock_pubkey,
35253
+ lockPubkey: outputMode === "locked" ? initial.lock_pubkey : null,
35254
+ keysetId: preview.keysetId,
35255
+ inputs: unspent.filter((p) => selected.has(proofIdKey(p))),
35256
+ outputs: serializeOutputData([...preview.sendOutputs ?? [], ...preview.keepOutputs ?? []]),
35257
+ createdAt: now
35258
+ };
35259
+ try {
35260
+ await withWalletLock(() => {
35261
+ const fresh = currentWallet(initial.lock_pubkey);
35262
+ const available = new Set(fresh.proofs.filter((p) => p.mint === mintUrl && p.status === "valid").map(proofIdKey));
35263
+ if (intent.inputs.length === 0 || !intent.inputs.every((p) => available.has(proofIdKey(p)))) {
35264
+ throw new Error("Reserve proofs changed during release; retry `dvm wallet release`.");
35265
+ }
35266
+ recordReleaseIntent(intent);
34719
35267
  });
34720
- });
35268
+ } catch (err) {
35269
+ return { ...outcome, error: `Could not record the release, so nothing was swapped: ${errorText2(err)}` };
35270
+ }
35271
+ let outputs;
35272
+ try {
35273
+ const result = await cashuWallet.completeSwap(preview, refundPrivkey);
35274
+ const inputKeys = new Set(inputs.map(proofIdKey));
35275
+ outputs = [...result.send, ...result.keep.filter((p) => !inputKeys.has(proofIdKey(p)))];
35276
+ } catch (err) {
35277
+ if (err instanceof te) {
35278
+ try {
35279
+ clearReleaseIntent(intent);
35280
+ } catch {
35281
+ }
35282
+ }
35283
+ return { ...outcome, error: errorText2(err) };
35284
+ }
35285
+ return commitRelease(intent, outputs, outcome);
35286
+ }
35287
+ async function commitRelease(intent, outputs, outcome) {
35288
+ const reclaimedOutputs = outputs.map((p) => toAgentProof(p, intent.mint, intent.lockPubkey));
35289
+ let saved = false;
35290
+ let cleanupError;
35291
+ try {
35292
+ await withWalletLock(() => {
35293
+ const fresh = currentWallet(intent.walletPubkey);
35294
+ const active2 = loadReleaseIntent(intent.walletPubkey, intent.builderHandle, intent.mint);
35295
+ if (active2?.id !== intent.id) return;
35296
+ const inputKeys = new Set(intent.inputs.map(proofIdKey));
35297
+ if (fresh.proofs.some((p) => p.mint === intent.mint && inputKeys.has(proofIdKey(p)))) {
35298
+ const existing = new Set(fresh.proofs.filter((p) => p.mint === intent.mint).map(proofIdKey));
35299
+ saveAgentWallet({
35300
+ ...fresh,
35301
+ proofs: [
35302
+ ...fresh.proofs.filter((p) => p.mint !== intent.mint || !inputKeys.has(proofIdKey(p))),
35303
+ ...reclaimedOutputs.filter((p) => !existing.has(proofIdKey(p)))
35304
+ ]
35305
+ });
35306
+ saved = true;
35307
+ }
35308
+ try {
35309
+ clearReleaseIntent(intent);
35310
+ } catch (err) {
35311
+ cleanupError = err;
35312
+ }
35313
+ });
35314
+ } catch (err) {
35315
+ return { ...outcome, error: `Release result is not saved to the wallet: ${errorText2(err)}. Retry \`dvm wallet release\` to recover it.` };
35316
+ }
34721
35317
  return {
34722
- mint: mintUrl,
34723
- alreadySpent,
34724
- pending: pending4,
34725
- reclaimedInputs: unspent,
34726
- reclaimedOutputs,
34727
- error: null
35318
+ ...outcome,
35319
+ output_mode: saved && reclaimedOutputs.length > 0 ? intent.lockPubkey === null ? "unlocked" : "locked" : null,
35320
+ reclaimedInputs: saved ? intent.inputs : [],
35321
+ reclaimedOutputs: saved ? reclaimedOutputs : [],
35322
+ error: cleanupError ? `Release saved, but recovery journal cleanup failed: ${errorText2(cleanupError)}. Retry \`dvm wallet release\`.` : null
35323
+ };
35324
+ }
35325
+ async function recoverRelease(intent, cashuWallet, outcome, now) {
35326
+ const fresh = currentWallet(intent.walletPubkey);
35327
+ const inputKeys = new Set(intent.inputs.map(proofIdKey));
35328
+ if (!fresh.proofs.some((p) => p.mint === intent.mint && inputKeys.has(proofIdKey(p)))) {
35329
+ return commitRelease(intent, [], outcome);
35330
+ }
35331
+ let restored = [];
35332
+ let restoreError;
35333
+ try {
35334
+ restored = await restoreProofsFromOutputs(cashuWallet, intent.keysetId, intent.outputs);
35335
+ } catch (err) {
35336
+ restoreError = err;
35337
+ }
35338
+ if (restored.length === intent.outputs.length && restored.length > 0) {
35339
+ return commitRelease(intent, restored, outcome);
35340
+ }
35341
+ if (restored.length > 0) {
35342
+ return { ...outcome, error: "The mint restored only part of the release outputs; retry `dvm wallet release`." };
35343
+ }
35344
+ const states = await cashuWallet.groupProofsByState(toCashuProofs(intent.inputs));
35345
+ if (now - intent.createdAt < RELEASE_IN_FLIGHT_MS) {
35346
+ return { ...outcome, error: "Another release may still be in flight; retry `dvm wallet release` shortly." };
35347
+ }
35348
+ const unspent = new Set(states.unspent.map((p) => proofIdKey(p)));
35349
+ if (states.pending.length === 0 && (intent.inputs.every((p) => unspent.has(proofIdKey(p))) || restoreError === void 0)) {
35350
+ await withWalletLock(() => clearReleaseIntent(intent));
35351
+ return null;
35352
+ }
35353
+ return {
35354
+ ...outcome,
35355
+ error: `Release recovery is pending${restoreError ? `: ${errorText2(restoreError)}` : ": the mint still reports inputs pending"}. Retry \`dvm wallet release\`.`
34728
35356
  };
34729
35357
  }
35358
+ function currentWallet(pubkey) {
35359
+ const wallet = loadAgentWallet();
35360
+ if (!wallet || wallet.lock_pubkey !== pubkey) throw new Error("The agent wallet changed during release.");
35361
+ return wallet;
35362
+ }
35363
+ function assertNoRelease(walletPubkey, builderHandle, mint) {
35364
+ if (loadReleaseIntent(walletPubkey, builderHandle, mint)) {
35365
+ throw new Error("Another release is awaiting recovery; retry `dvm wallet release`.");
35366
+ }
35367
+ }
35368
+ function errorText2(err) {
35369
+ return err instanceof Error ? err.message : String(err);
35370
+ }
34730
35371
  function proofIdKey(p) {
34731
35372
  return `${p.secret}:${p.C}`;
34732
35373
  }
@@ -35046,7 +35687,8 @@ async function walletRelease(opts) {
35046
35687
  `Released ${totals.reclaimedSats} sats at ${builderHandle} (output mode: ${result.output_mode}).`
35047
35688
  );
35048
35689
  for (const mintOutcome of result.mints) {
35049
- info(` ${mintOutcome.mint}:`);
35690
+ const policy = mintOutcome.output_mode === null ? "" : ` (output mode: ${mintOutcome.output_mode})`;
35691
+ info(` ${mintOutcome.mint}${policy}:`);
35050
35692
  info(
35051
35693
  ` reclaimed: ${sumSats(mintOutcome.reclaimedOutputs)} sats from ${mintOutcome.reclaimedInputs.length} proof(s)`
35052
35694
  );
@@ -35072,6 +35714,7 @@ async function walletRelease(opts) {
35072
35714
  pending_sats: totals.pendingSats,
35073
35715
  mints: result.mints.map((m) => ({
35074
35716
  mint: m.mint,
35717
+ output_mode: m.output_mode,
35075
35718
  reclaimed_sats: sumSats(m.reclaimedOutputs),
35076
35719
  reclaimed_input_count: m.reclaimedInputs.length,
35077
35720
  already_spent_sats: sumSats(m.alreadySpent),
@@ -36268,7 +36911,7 @@ function resolveMppEndpoint(identifier) {
36268
36911
  }
36269
36912
 
36270
36913
  // src/commands/wallet-pair.ts
36271
- import { createHash as createHash6, randomBytes as randomBytes5 } from "crypto";
36914
+ import { createHash as createHash7, randomBytes as randomBytes5 } from "crypto";
36272
36915
  import { hostname as hostname2 } from "os";
36273
36916
 
36274
36917
  // node_modules/nostr-tools/lib/esm/pure.js
@@ -37166,17 +37809,17 @@ function hexToBytes2(hex2) {
37166
37809
  }
37167
37810
 
37168
37811
  // src/lib/wallet-pairing-store.ts
37169
- var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
37812
+ var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
37170
37813
  import {
37171
37814
  chmodSync as chmodSync2,
37172
- existsSync as existsSync7,
37815
+ existsSync as existsSync8,
37173
37816
  readdirSync as readdirSync5,
37174
- readFileSync as readFileSync8,
37175
- renameSync as renameSync3,
37817
+ readFileSync as readFileSync9,
37818
+ renameSync as renameSync4,
37176
37819
  unlinkSync as unlinkSync3,
37177
- writeFileSync as writeFileSync5
37820
+ writeFileSync as writeFileSync6
37178
37821
  } from "fs";
37179
- import { join as join9 } from "path";
37822
+ import { join as join11 } from "path";
37180
37823
  var pairingIdPattern = /^[0-9a-f]{64}$/;
37181
37824
  var stateSchema = external_exports.object({
37182
37825
  version: external_exports.literal(1),
@@ -37198,12 +37841,12 @@ var stateSchema = external_exports.object({
37198
37841
  function createWalletPairingState(state) {
37199
37842
  ensurePairingsDirectory();
37200
37843
  const path = pairingPath(state.pairing_id);
37201
- writeFileSync5(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
37844
+ writeFileSync6(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
37202
37845
  chmodSync2(path, 384);
37203
37846
  }
37204
37847
  function loadWalletPairingState(pairingId) {
37205
37848
  const path = pairingPath(pairingId);
37206
- if (!existsSync7(path)) {
37849
+ if (!existsSync8(path)) {
37207
37850
  throw new DvmError(
37208
37851
  "wallet_pairing_not_found",
37209
37852
  "No local state exists for that wallet pairing.",
@@ -37211,7 +37854,7 @@ function loadWalletPairingState(pairingId) {
37211
37854
  );
37212
37855
  }
37213
37856
  try {
37214
- return stateSchema.parse(JSON.parse(readFileSync8(path, "utf8")));
37857
+ return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
37215
37858
  } catch {
37216
37859
  throw new DvmError(
37217
37860
  "wallet_pairing_state_invalid",
@@ -37225,9 +37868,9 @@ function saveWalletPairingState(state) {
37225
37868
  ensurePairingsDirectory();
37226
37869
  const path = pairingPath(state.pairing_id);
37227
37870
  const tmp = `${path}.tmp`;
37228
- writeFileSync5(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
37871
+ writeFileSync6(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
37229
37872
  try {
37230
- renameSync3(tmp, path);
37873
+ renameSync4(tmp, path);
37231
37874
  chmodSync2(path, 384);
37232
37875
  } catch (err) {
37233
37876
  try {
@@ -37246,13 +37889,13 @@ function deleteWalletPairingState(pairingId) {
37246
37889
  }
37247
37890
  }
37248
37891
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
37249
- if (!existsSync7(PAIRINGS_DIR)) return 0;
37892
+ if (!existsSync8(PAIRINGS_DIR)) return 0;
37250
37893
  let removed = 0;
37251
37894
  for (const name of readdirSync5(PAIRINGS_DIR)) {
37252
37895
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
37253
- const path = join9(PAIRINGS_DIR, name);
37896
+ const path = join11(PAIRINGS_DIR, name);
37254
37897
  try {
37255
- const state = stateSchema.parse(JSON.parse(readFileSync8(path, "utf8")));
37898
+ const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
37256
37899
  if (state.manifest.expires_at <= nowSeconds) {
37257
37900
  unlinkSync3(path);
37258
37901
  removed += 1;
@@ -37264,10 +37907,10 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
37264
37907
  }
37265
37908
  async function withWalletPairingLock(pairingId, fn) {
37266
37909
  const path = pairingPath(pairingId);
37267
- if (!existsSync7(path)) return fn();
37910
+ if (!existsSync8(path)) return fn();
37268
37911
  let release;
37269
37912
  try {
37270
- release = await import_proper_lockfile3.default.lock(path, {
37913
+ release = await import_proper_lockfile4.default.lock(path, {
37271
37914
  lockfilePath: `${path}.lock`,
37272
37915
  realpath: false,
37273
37916
  stale: 12 * 60 * 1e3,
@@ -37294,7 +37937,7 @@ function pairingPath(pairingId) {
37294
37937
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
37295
37938
  );
37296
37939
  }
37297
- return join9(PAIRINGS_DIR, `${pairingId}.json`);
37940
+ return join11(PAIRINGS_DIR, `${pairingId}.json`);
37298
37941
  }
37299
37942
  function ensurePairingsDirectory() {
37300
37943
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -37719,7 +38362,7 @@ function walletFingerprint(uri) {
37719
38362
  return uri ? sha2562(uri) : null;
37720
38363
  }
37721
38364
  function sha2562(value) {
37722
- return createHash6("sha256").update(value).digest("hex");
38365
+ return createHash7("sha256").update(value).digest("hex");
37723
38366
  }
37724
38367
  function relayHost2(relay) {
37725
38368
  try {
@@ -37933,9 +38576,11 @@ async function forgetSubmission(requestId, opts) {
37933
38576
  "List them with: dvm wallet submissions"
37934
38577
  );
37935
38578
  }
38579
+ refuseIfReclaimUnsaved(view, opts);
37936
38580
  refuseIfSelfHealing(view, opts);
37937
38581
  await confirmForget(view, opts);
37938
38582
  await abandonPendingSubmission({ requestId });
38583
+ clearReclaimIntent(requestId);
37939
38584
  const abandoned = view.at_risk ? view.amount_sats : 0;
37940
38585
  const heldFor = heldCashuSubmissionAsks(/* @__PURE__ */ new Set([requestId]));
37941
38586
  const warning = heldFor.length === 0 ? void 0 : `This token is the unconfirmed payment for an open charge on ${heldFor.map((ask) => `job ${ask.jobId}`).join(", ")}. That charge stays held, but if the provider asks for it again it can become payable again, and the provider can still redeem the forgotten token.`;
@@ -37956,6 +38601,14 @@ async function forgetSubmission(requestId, opts) {
37956
38601
  ...warning ? { warning, held_for: heldFor.map((ask) => ({ job_id: ask.jobId, request_seq: ask.requestSeq })) } : {}
37957
38602
  });
37958
38603
  }
38604
+ function refuseIfReclaimUnsaved(view, opts) {
38605
+ if (opts.force || !reclaimIntentIds().has(view.request_id)) return;
38606
+ throw new DvmError(
38607
+ "reclaim_unsaved",
38608
+ `Request ${view.request_id}: the reclaim swap for ${view.amount_sats} sats may already have gone through at the mint, and the new proofs have not been saved to the wallet yet.`,
38609
+ `Run \`dvm wallet show\` to recover them. Forgetting this entry first can lose them; if the recovery keeps failing and you accept that, add --force: dvm wallet submissions --forget ${view.request_id} --yes --force`
38610
+ );
38611
+ }
37959
38612
  function refuseIfSelfHealing(view, opts) {
37960
38613
  if (opts.force) return;
37961
38614
  if (view.state !== "reclaimable" && view.state !== "reclaim_failed") return;