@dvmkit/dvm-cli 0.15.0 → 0.15.2

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
@@ -18,17 +18,21 @@ import {
18
18
  addPayment,
19
19
  answeredYieldSeqs,
20
20
  appendMessages,
21
+ applySubmissionVerdicts,
21
22
  assertFloatBudget,
22
23
  automaticCreditBoundRail,
23
24
  availableRails,
24
25
  backfillTrustAnchor,
26
+ blockHeldPayment,
25
27
  bookCreditPayment,
26
28
  buildCompletionHintFields,
27
29
  buildTempoCredential,
28
30
  captureDrawFundingReceipts,
29
31
  captureFundingReceipt,
30
32
  captureTransportReceipt,
33
+ clearAskPaymentBlocks,
31
34
  clearPaymentRequestInFlight,
35
+ clearReclaimIntent,
32
36
  commitAgentSpend,
33
37
  completedCreditHistory,
34
38
  completedDrainMatches,
@@ -39,6 +43,7 @@ import {
39
43
  computeNextAction,
40
44
  correctPendingFundAmount,
41
45
  createMessageAppendSession,
46
+ declinedAskSeqs,
42
47
  deriveAlias,
43
48
  describeMintBounds,
44
49
  drainReceiptsDisplay,
@@ -51,6 +56,8 @@ import {
51
56
  extractBuilderHandle,
52
57
  fetchMissingJobReceipt,
53
58
  fetchTrustAnchor,
59
+ finalizeLandedReclaims,
60
+ finishBookedSubmission,
54
61
  floatBudgetJson,
55
62
  floatPaymentDisplay,
56
63
  floatPaymentJson,
@@ -62,6 +69,8 @@ import {
62
69
  guidanceJobArg,
63
70
  hasUnknownUpfrontCredit,
64
71
  hasUnknownUpfrontRail,
72
+ heldCashuSubmissionAsks,
73
+ heldPaymentResendable,
65
74
  identityDataFields,
66
75
  identityError,
67
76
  inFlightTimeoutSeconds,
@@ -84,14 +93,17 @@ import {
84
93
  loadJob,
85
94
  loadLedger,
86
95
  loadMessages,
96
+ loadReclaimIntent,
87
97
  loadSubmissionEvidence,
88
98
  markJobTerminal,
99
+ markPaymentRequestAnswered,
89
100
  markPaymentRequestInFlight,
90
101
  markPaymentRequestPaid,
91
102
  markPendingSubmissionUnresolved,
92
103
  markProofsInFlight,
93
104
  maxSeq,
94
105
  meltInFlightTimeoutSeconds,
106
+ midJobSpendLabel,
95
107
  mutateCreditPayment,
96
108
  needsTopup,
97
109
  nextStepHint,
@@ -127,15 +139,18 @@ import {
127
139
  receiptPieceContext,
128
140
  receiptSettlement,
129
141
  receiptTrustFields,
142
+ reclaimIntentIds,
130
143
  reconcileInFlightPaymentRequest,
131
144
  reconcilePaymentRequestHistory,
132
145
  recordCallerMessageHash,
133
146
  recordFloatSpend,
134
147
  recordIdentityFailure,
135
148
  recordLocalJobCollision,
149
+ recordReclaimIntent,
136
150
  recordSpend,
137
151
  recordSpendOnce,
138
152
  recordSubmissionEvidence,
153
+ recordSubmissionVerdicts,
139
154
  recordUpfrontCreditPayment,
140
155
  recordUpfrontRailPayment,
141
156
  redactJobTokenFromError,
@@ -155,7 +170,9 @@ import {
155
170
  saveJob,
156
171
  saveLedger,
157
172
  saveSubmittedJob,
173
+ settleAnsweredAsk,
158
174
  settleJobIdentity,
175
+ settleRecordedPayments,
159
176
  settlementCurrencyHint,
160
177
  statusSnapshot,
161
178
  sweepPendingMints,
@@ -169,6 +186,7 @@ import {
169
186
  unknownCurrencyHint,
170
187
  unknownUpfrontPrice,
171
188
  unrecordedFloatBudgetWarning,
189
+ unresendablePaymentHint,
172
190
  updateJob,
173
191
  walletHistory,
174
192
  warnInvalidJobIdentityHeader,
@@ -176,7 +194,7 @@ import {
176
194
  withIdentityRecovery,
177
195
  withJobTokenRedaction,
178
196
  withRequestResultRecovery
179
- } from "./chunk-ZKC6KN36.js";
197
+ } from "./chunk-ECJO73RZ.js";
180
198
  import {
181
199
  connectedTempoAccount,
182
200
  generateTempoKey,
@@ -202,7 +220,7 @@ import {
202
220
  tryResolveBtcUsdRate,
203
221
  tryX402Payment,
204
222
  withOutputWarnings
205
- } from "./chunk-LPILVPFG.js";
223
+ } from "./chunk-5SHB3MZ7.js";
206
224
  import {
207
225
  assertSupportedX402Network,
208
226
  connectedX402Payer,
@@ -419,6 +437,7 @@ import {
419
437
  resolveTempoAsset,
420
438
  resolveTempoNetwork,
421
439
  resolveX402ChannelRpc,
440
+ restoreProofsFromOutputs,
422
441
  retryMintQuoteOperation,
423
442
  sa,
424
443
  saveAgentWallet,
@@ -431,6 +450,7 @@ import {
431
450
  signedRequestDomain,
432
451
  sn,
433
452
  swapFeeForProofs,
453
+ te,
434
454
  tempoChannelControlledBy,
435
455
  tempoCredentialAmountMicro,
436
456
  tempoSessionChallenge,
@@ -727,8 +747,10 @@ import {
727
747
  bytesToHex,
728
748
  chainIdFromCaip2,
729
749
  concatBytes,
750
+ decodePayment,
730
751
  decodePaymentRequiredHeader,
731
752
  ensureAddress,
753
+ exactEvmAuthorization,
732
754
  generateX402PrivateKey,
733
755
  hexToBytes,
734
756
  hmac,
@@ -9876,10 +9898,20 @@ function requestRecoveryPath(route, requestId) {
9876
9898
  // src/lib/wallet-agent/recovery-submissions.ts
9877
9899
  var RESUME_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
9878
9900
  var RESUME_MAX_ATTEMPTS = 5;
9901
+ var RECLAIM_IN_FLIGHT_MS = 2 * 6e4;
9902
+ 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";
9879
9903
  async function sweepPendingSubmissions(opts = {}) {
9904
+ const writeFailures = [];
9905
+ const result = (outcomes2) => writeFailures.length > 0 ? { outcomes: outcomes2, writeFailures } : { outcomes: outcomes2 };
9906
+ const failed = (requestId, stage, error) => writeFailures.push({ requestId, stage, message: errorText(error) });
9907
+ try {
9908
+ finalizeLandedReclaims();
9909
+ } catch (error) {
9910
+ failed("", "verdict_journal", error);
9911
+ }
9880
9912
  const wallet = loadAgentWallet();
9881
9913
  if (!wallet || wallet.pending_submissions.length === 0) {
9882
- return { outcomes: [] };
9914
+ return result([]);
9883
9915
  }
9884
9916
  const deps = {
9885
9917
  httpPost: opts.httpPost ?? createDefaultHttpPost(opts.fetchImpl ?? dvmFetch),
@@ -9895,20 +9927,79 @@ async function sweepPendingSubmissions(opts = {}) {
9895
9927
  const now = opts.now ?? (() => Date.now());
9896
9928
  const { entries, unreadable } = await reconcileEvidenceMarkers(wallet);
9897
9929
  const outcomes = [];
9930
+ const handled = /* @__PURE__ */ new Set();
9898
9931
  for (const entry of entries) {
9899
- outcomes.push(await resolveEntry(entry, deps, now(), unreadable.has(entry.request_id)));
9932
+ const outcome = await resolveEntry(entry, deps, now(), unreadable.has(entry.request_id));
9933
+ if (outcome.kind !== "reclaimed") {
9934
+ outcomes.push(outcome);
9935
+ continue;
9936
+ }
9937
+ const unsaved = await commitReclaim(outcome, wallet, now, failed);
9938
+ const reported = unsaved ?? outcome;
9939
+ handled.add(reported);
9940
+ outcomes.push(reported);
9941
+ }
9942
+ const rest = outcomes.filter((outcome) => !handled.has(outcome) && mutatesWallet(outcome));
9943
+ if (rest.length > 0) {
9944
+ try {
9945
+ recordSubmissionVerdicts(rest.flatMap(verdictFor));
9946
+ } catch (error) {
9947
+ for (const outcome of rest) failed(outcome.entry.request_id, "verdict_journal", error);
9948
+ }
9949
+ try {
9950
+ await withWalletLock(() => {
9951
+ const fresh = loadAgentWallet() ?? wallet;
9952
+ const next = rest.reduce((acc, outcome) => applyOutcome(acc, outcome, now), fresh);
9953
+ saveAgentWallet(next);
9954
+ });
9955
+ await applySubmissionVerdicts().catch((error) => failed("", "verdict_apply", error));
9956
+ } catch (error) {
9957
+ for (const outcome of rest) failed(outcome.entry.request_id, "wallet_save", error);
9958
+ }
9900
9959
  }
9901
- if (outcomes.some(mutatesWallet)) {
9960
+ return result(outcomes);
9961
+ }
9962
+ async function commitReclaim(outcome, wallet, now, failed) {
9963
+ const requestId = outcome.entry.request_id;
9964
+ let alreadySaved = false;
9965
+ try {
9902
9966
  await withWalletLock(() => {
9903
9967
  const fresh = loadAgentWallet() ?? wallet;
9904
- const next = outcomes.reduce(
9905
- (acc, outcome) => applyOutcome(acc, outcome, now),
9906
- fresh
9907
- );
9908
- saveAgentWallet(next);
9968
+ if (!fresh.pending_submissions.some((s) => s.request_id === requestId)) {
9969
+ alreadySaved = true;
9970
+ return;
9971
+ }
9972
+ saveAgentWallet(applyOutcome(fresh, outcome, now));
9909
9973
  });
9974
+ } catch (error) {
9975
+ failed(requestId, "wallet_save", error);
9976
+ return { kind: "reclaim_skipped", entry: outcome.entry, reason: RECLAIM_UNSAVED_REASON, terminal: false };
9910
9977
  }
9911
- return { outcomes };
9978
+ if (alreadySaved) {
9979
+ return {
9980
+ kind: "reclaim_skipped",
9981
+ entry: outcome.entry,
9982
+ reason: "another sweep already saved this reclaim",
9983
+ terminal: false
9984
+ };
9985
+ }
9986
+ try {
9987
+ finalizeLandedReclaims();
9988
+ } catch (error) {
9989
+ failed(requestId, "verdict_journal", error);
9990
+ return null;
9991
+ }
9992
+ await applySubmissionVerdicts().catch((error) => failed(requestId, "verdict_apply", error));
9993
+ return null;
9994
+ }
9995
+ function verdictFor(outcome) {
9996
+ const reserve = outcome.entry.output_proofs.some((proof) => proof.reserved_for !== void 0) ? { reserve: true } : {};
9997
+ if (outcome.kind === "already_accepted") return [{ requestId: outcome.entry.request_id, verdict: "spent", ...reserve }];
9998
+ if (outcome.kind !== "reclaimed") return [];
9999
+ return [reclaimVerdict(outcome.entry, outcome.spent_sats)];
10000
+ }
10001
+ function reclaimVerdict(entry, spentSats) {
10002
+ return spentSats > 0 ? { requestId: entry.request_id, verdict: "partly_spent", spentSats, amountSats: entry.amount_sats } : { requestId: entry.request_id, verdict: "reclaimed" };
9912
10003
  }
9913
10004
  async function recoverPendingSubmission(opts) {
9914
10005
  if (!UUID_V4_RE.test(opts.requestId))
@@ -10179,6 +10270,11 @@ async function reclaimEntry(entry, deps) {
10179
10270
  } catch (err) {
10180
10271
  return skipped(errorText(err));
10181
10272
  }
10273
+ const intent = loadReclaimIntent(entry.request_id);
10274
+ if (intent) {
10275
+ const recovered = await recoverReclaimIntent(entry, intent, cashuWallet, deps.lockPubkey);
10276
+ if (recovered) return recovered;
10277
+ }
10182
10278
  let grouped;
10183
10279
  try {
10184
10280
  grouped = await cashuWallet.groupProofsByState(toCashuProofs(entry.output_proofs));
@@ -10199,8 +10295,9 @@ async function reclaimEntry(entry, deps) {
10199
10295
  return skipped("the mint still reports some of these proofs in flight");
10200
10296
  }
10201
10297
  const totalSats = unspent.reduce((sum, p) => sum + p.amount, 0);
10298
+ const spentSats = spent.reduce((sum, p) => sum + p.amount, 0);
10202
10299
  const inputs = toCashuProofs(unspent);
10203
- let outputs;
10300
+ let preview;
10204
10301
  try {
10205
10302
  const swapFeeSats = swapFeeForProofs(cashuWallet, inputs);
10206
10303
  const allowance = reclaimFeeAllowance(entry);
@@ -10220,20 +10317,88 @@ async function reclaimEntry(entry, deps) {
10220
10317
  true
10221
10318
  );
10222
10319
  }
10223
- const result = await cashuWallet.ops.send(reclaimSats, inputs).privkey(refundPrivkey).asP2PK({ pubkey: deps.lockPubkey }).run();
10224
- outputs = result.send;
10320
+ preview = await cashuWallet.ops.send(reclaimSats, inputs).privkey(refundPrivkey).asP2PK({ pubkey: deps.lockPubkey }).prepare();
10225
10321
  } catch (err) {
10226
10322
  const diagnostic = missingDleqRecoveryDiagnostic(inputs, err);
10227
10323
  return skipped(diagnostic ?? errorText(err), diagnostic !== null);
10228
10324
  }
10325
+ const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10326
+ try {
10327
+ recordReclaimIntent({
10328
+ requestId: entry.request_id,
10329
+ mint: entry.mint,
10330
+ keysetId: preview.keysetId,
10331
+ lockPubkey: deps.lockPubkey,
10332
+ outputs: serializeOutputData(preview.sendOutputs ?? []),
10333
+ inputSecrets: unspent.map((p) => p.secret),
10334
+ spentSats,
10335
+ verdict: reclaimVerdict(entry, spentSats),
10336
+ createdAt
10337
+ });
10338
+ } catch (err) {
10339
+ return skipped(`could not record the reclaim before sending it to the mint, so nothing was swapped: ${errorText(err)}`);
10340
+ }
10341
+ let outputs;
10342
+ try {
10343
+ outputs = (await cashuWallet.completeSwap(preview, refundPrivkey)).send;
10344
+ } catch (err) {
10345
+ const diagnostic = missingDleqRecoveryDiagnostic(inputs, err);
10346
+ if (err instanceof te || diagnostic !== null) discardReclaimIntent(entry.request_id, createdAt);
10347
+ return skipped(diagnostic ?? errorText(err), diagnostic !== null);
10348
+ }
10349
+ return reclaimedOutcome(entry, outputs, deps.lockPubkey, spentSats);
10350
+ }
10351
+ function reclaimedOutcome(entry, outputs, lockPubkey, spentSats) {
10229
10352
  return {
10230
10353
  kind: "reclaimed",
10231
10354
  entry,
10232
- outputs: outputs.map((p) => toAgentProof(p, entry.mint, deps.lockPubkey)),
10355
+ outputs: outputs.map((p) => toAgentProof(p, entry.mint, lockPubkey)),
10233
10356
  reclaimed_sats: outputs.reduce((sum, p) => sum + A.from(p.amount).toNumber(), 0),
10234
- spent_sats: spent.reduce((sum, p) => sum + p.amount, 0)
10357
+ spent_sats: spentSats
10235
10358
  };
10236
10359
  }
10360
+ function discardReclaimIntent(requestId, createdAt) {
10361
+ try {
10362
+ clearReclaimIntent(requestId, createdAt);
10363
+ } catch {
10364
+ }
10365
+ }
10366
+ async function recoverReclaimIntent(entry, intent, cashuWallet, lockPubkey) {
10367
+ const skipped = (reason) => ({
10368
+ kind: "reclaim_skipped",
10369
+ entry,
10370
+ reason,
10371
+ terminal: false
10372
+ });
10373
+ let restored = [];
10374
+ let restoreError;
10375
+ try {
10376
+ restored = await restoreProofsFromOutputs(cashuWallet, intent.keysetId, intent.outputs);
10377
+ } catch (err) {
10378
+ restoreError = errorText(err);
10379
+ }
10380
+ if (restored.length > 0) {
10381
+ return restored.length === intent.outputs.length ? reclaimedOutcome(entry, restored, lockPubkey, intent.spentSats) : skipped("the mint restored only part of the reclaim swap's outputs");
10382
+ }
10383
+ const secrets = new Set(intent.inputSecrets);
10384
+ try {
10385
+ const states = await cashuWallet.groupProofsByState(
10386
+ toCashuProofs(entry.output_proofs.filter((proof) => secrets.has(proof.secret)))
10387
+ );
10388
+ if (states.pending.length === 0 && (states.spent.length === 0 || restoreError === void 0)) {
10389
+ if (states.spent.length === 0 && Date.now() - Date.parse(intent.createdAt) < RECLAIM_IN_FLIGHT_MS) {
10390
+ return skipped("another reclaim of this payment may still be in flight; the next sweep checks again");
10391
+ }
10392
+ clearReclaimIntent(entry.request_id, intent.createdAt);
10393
+ return null;
10394
+ }
10395
+ } catch (err) {
10396
+ return skipped(errorText(err));
10397
+ }
10398
+ return skipped(
10399
+ `the reclaim swap spent these proofs at the mint but its outputs cannot be restored yet${restoreError ? ` (${restoreError})` : ""}; the next sweep tries again`
10400
+ );
10401
+ }
10237
10402
  function reclaimFeeAllowance(entry) {
10238
10403
  const maxSats = entry.max_cashu_fee_sats;
10239
10404
  const contextMaxSats = entry.context?.max_cashu_fee_sats;
@@ -11222,7 +11387,10 @@ function isSignedRequestAudience(value) {
11222
11387
 
11223
11388
  // src/lib/payment-responder.ts
11224
11389
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11390
+ const seq = opts?.requestSeq;
11391
+ let replacing = false;
11225
11392
  return withJobPaymentLock(jobId, (assertOwned) => {
11393
+ replacing = opts?.approval === "explicit" && seq !== void 0 && loadJob(jobId)?.askPaymentBlocks?.[seq] !== void 0;
11226
11394
  const guardedTransport = new Proxy(transport, {
11227
11395
  get(target, key) {
11228
11396
  if (key === "sendMessage") return async (...args) => {
@@ -11246,6 +11414,19 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11246
11414
  } catch {
11247
11415
  }
11248
11416
  }
11417
+ const heldUnsendable = !replacing && seq !== void 0 && holdsPayment(job, seq) && !heldPaymentResendable(job, seq);
11418
+ if (error.code !== "payment_unconfirmed" && heldUnsendable) {
11419
+ error.hint = paymentInFlightHint(jobId, job, seq);
11420
+ if (error.proseSources?.hint) error.proseSources = { ...error.proseSources, hint: void 0 };
11421
+ }
11422
+ if (error.code === "payment_unconfirmed" || heldUnsendable) {
11423
+ error.data = providerFields({
11424
+ ...error.data,
11425
+ job_id: jobId,
11426
+ next_action: providerFields({ ...pollNextAction(jobId, error.hint) }, ["job_id"])
11427
+ }, ["job_id"]);
11428
+ throw error;
11429
+ }
11249
11430
  const command = requestId ? `dvm request-result ${shellQuoteArg(requestId)}` : `dvm status ${guidanceJobArg(jobId)}`;
11250
11431
  const recovery = `The job was already accepted. Inspect it with \`${command}\` before submitting a replacement. This read cannot submit a job or send payment.`;
11251
11432
  error.data = providerFields({
@@ -11276,8 +11457,6 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11276
11457
  "The original upfront credit debit is unknown or conflicting.",
11277
11458
  "Recover the accepted upfront amount with 'dvm request-result' before authorizing more payments."
11278
11459
  );
11279
- const spent = job?.totalPaidMsats ?? 0;
11280
- const paymentsHonoured = job?.paymentsHonoured ?? 0;
11281
11460
  const pinnedMint = job?.pinnedMint;
11282
11461
  const strictPerCall = job?.strictPerCall === true;
11283
11462
  const maxCashuFeeSats = job?.maxCashuFeeSats;
@@ -11310,16 +11489,31 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11310
11489
  "The saved balance payment was not recovered; no replacement payment was sent.",
11311
11490
  `Run \`dvm status ${shellQuoteArg(jobId)}\` to refresh the job, then run \`dvm pay ${shellQuoteArg(jobId)}\` only if payment is still requested.`
11312
11491
  );
11492
+ if (!matchingEndpoint && job && opts?.requestSeq !== void 0 && holdsPayment(job, opts.requestSeq))
11493
+ throw unconfirmedPaymentError(
11494
+ jobId,
11495
+ "An earlier payment for this request was sent to this job's stored endpoint and is unconfirmed.",
11496
+ `Re-send it with \`dvm pay ${guidanceJobArg(jobId)}\` without --endpoint; it re-delivers that same payment.`
11497
+ );
11498
+ let unconfirmed;
11313
11499
  if (matchingEndpoint && opts?.requestSeq !== void 0) {
11314
11500
  if (job.inFlightPaymentRequestSeqs?.includes(opts.requestSeq))
11315
11501
  await reconcileInFlightPaymentRequest(jobId, opts.requestSeq, transport, provider, { jobToken });
11502
+ await settleRecordedPayments(jobId);
11316
11503
  if (loadAnsweredYieldSeqs(jobId).has(opts.requestSeq))
11317
11504
  throw new DvmError(
11318
11505
  "payment_already_sent",
11319
11506
  "Payment already sent for this request.",
11320
11507
  `Keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
11321
11508
  );
11322
- }
11509
+ const current = loadJob(jobId);
11510
+ unconfirmed = current?.unconfirmedPaymentSubmissions?.[opts.requestSeq];
11511
+ if (!unconfirmed && current?.inFlightPaymentRequestSeqs?.includes(opts.requestSeq))
11512
+ throw unconfirmedPaymentError(jobId, "An earlier payment for this request is unconfirmed and this CLI holds no copy to re-send.");
11513
+ }
11514
+ const latest = loadJob(jobId);
11515
+ const spent = latest?.totalPaidMsats ?? 0;
11516
+ const paymentsHonoured = latest?.paymentsHonoured ?? 0;
11323
11517
  if (policy.maxIncrementMsats > 0 && request2.amount_msats > policy.maxIncrementMsats) {
11324
11518
  return "over-budget";
11325
11519
  }
@@ -11336,6 +11530,27 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11336
11530
  "Verify the original one-payment quote; do not authorize a fallback or replacement payment."
11337
11531
  );
11338
11532
  if (request2.amount_msats > policy.autoPayBelowMsats) return "needs-approval";
11533
+ if (unconfirmed && opts?.requestSeq !== void 0) {
11534
+ if (!unconfirmed.blocked)
11535
+ return redeliverUnconfirmedPayment({
11536
+ jobId,
11537
+ request: request2,
11538
+ requestSeq: opts.requestSeq,
11539
+ submission: unconfirmed,
11540
+ transport,
11541
+ provider,
11542
+ jobToken,
11543
+ rail: opts.rail
11544
+ });
11545
+ if (unconfirmed.blocked.reason === "not_resendable")
11546
+ throw unconfirmedPaymentError(
11547
+ jobId,
11548
+ "Sending the earlier payment for this request again cannot settle it.",
11549
+ paymentInFlightHint(jobId, loadJob(jobId), opts.requestSeq)
11550
+ );
11551
+ }
11552
+ if (opts?.requestSeq !== void 0 && loadJob(jobId)?.askPaymentBlocks?.[opts.requestSeq] && opts.approval !== "explicit")
11553
+ return "needs-approval";
11339
11554
  if (matchingEndpoint && !balanceRefused && opts?.rail === void 0) {
11340
11555
  const creditPaid = await tryCreditPayment({
11341
11556
  jobId,
@@ -11387,7 +11602,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11387
11602
  }
11388
11603
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11389
11604
  const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
11390
- const { tryX402Payment: tryX402Payment2 } = await import("./client-RSHQFXCA.js");
11605
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-YIHI4AIC.js");
11391
11606
  const wallet = loadX402Wallet2();
11392
11607
  if (wallet) {
11393
11608
  let proof;
@@ -11416,34 +11631,25 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11416
11631
  }
11417
11632
  if (proof) {
11418
11633
  await enforceGlobalBudget({ plannedMsats: proof.amountMsats, btcRate: proof.btcRate });
11419
- await sendRailPayment(
11420
- transport,
11634
+ return deliverSignedRailPayment({
11421
11635
  jobId,
11422
- {
11423
- type: "payment",
11424
- content: {
11425
- x402_payment: proof.paymentHeader,
11426
- amount_msats: proof.amountMsats
11427
- }
11428
- },
11636
+ request: request2,
11637
+ transport,
11429
11638
  provider,
11430
- { jobToken },
11431
- matchingEndpoint ? opts?.requestSeq : void 0
11432
- );
11433
- addPayment(jobId, proof.amountMsats, approval);
11434
- recordSpend({
11435
- msats: proof.amountMsats,
11436
- btcRate: proof.btcRate,
11437
- jobId,
11438
- providerEndpoint: provider.endpoint,
11439
- ...midJobSpendLabel(request2.reason)
11639
+ jobToken,
11640
+ approval,
11641
+ requestSeq: matchingEndpoint ? opts?.requestSeq : void 0,
11642
+ submission: {
11643
+ rail: "x402",
11644
+ content: { x402_payment: proof.paymentHeader, amount_msats: proof.amountMsats },
11645
+ requestAmountMsats: request2.amount_msats,
11646
+ amountMsats: proof.amountMsats,
11647
+ btcRate: proof.btcRate,
11648
+ amountUsdcMicro: proof.amountUsdcMicro,
11649
+ approval: approval?.approval,
11650
+ reason: request2.reason
11651
+ }
11440
11652
  });
11441
- return {
11442
- status: "paid",
11443
- rail: "x402",
11444
- amountMsats: proof.amountMsats,
11445
- amountUsdcMicro: proof.amountUsdcMicro
11446
- };
11447
11653
  }
11448
11654
  }
11449
11655
  }
@@ -11453,36 +11659,103 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11453
11659
  if (cred) {
11454
11660
  const paidMsats = usdcToMsats(Number(tempoCredentialAmountMicro(cred)) / 1e6, tempoRate);
11455
11661
  await enforceGlobalBudget({ plannedMsats: paidMsats, btcRate: tempoRate });
11456
- await sendRailPayment(
11457
- transport,
11662
+ return deliverSignedRailPayment({
11458
11663
  jobId,
11459
- {
11460
- type: "payment",
11461
- content: {
11462
- tempo_credential: cred,
11463
- amount_msats: paidMsats
11464
- }
11465
- },
11664
+ request: request2,
11665
+ transport,
11466
11666
  provider,
11467
- { jobToken },
11468
- matchingEndpoint ? opts?.requestSeq : void 0
11469
- );
11470
- addPayment(jobId, paidMsats, approval);
11471
- recordSpend({
11472
- msats: paidMsats,
11473
- btcRate: tempoRate,
11474
- jobId,
11475
- providerEndpoint: provider.endpoint,
11476
- ...midJobSpendLabel(request2.reason)
11667
+ jobToken,
11668
+ approval,
11669
+ requestSeq: matchingEndpoint ? opts?.requestSeq : void 0,
11670
+ submission: {
11671
+ rail: "tempo",
11672
+ content: { tempo_credential: cred, amount_msats: paidMsats },
11673
+ requestAmountMsats: request2.amount_msats,
11674
+ amountMsats: paidMsats,
11675
+ btcRate: tempoRate,
11676
+ approval: approval?.approval,
11677
+ reason: request2.reason
11678
+ }
11477
11679
  });
11478
- return { status: "paid", rail: "tempo", amountMsats: paidMsats };
11479
11680
  }
11480
11681
  }
11481
11682
  return "needs-approval";
11482
11683
  }
11483
- function midJobSpendLabel(reason) {
11484
- const text = reason.trim();
11485
- return text ? { label: text, labelSource: "provider" } : {};
11684
+ function unconfirmedPaymentError(jobId, message2, hint = unresendablePaymentHint(jobId)) {
11685
+ return new DvmError("payment_unconfirmed", `${message2} No new payment was signed.`, hint);
11686
+ }
11687
+ function holdsPayment(job, requestSeq) {
11688
+ return job.inFlightPaymentRequestSeqs?.includes(requestSeq) === true || job.unconfirmedPaymentSubmissions?.[requestSeq] !== void 0;
11689
+ }
11690
+ async function redeliverUnconfirmedPayment(args) {
11691
+ const { jobId, request: request2, submission, provider } = args;
11692
+ const sentRail = submission.rail === "cashu_p2pk" ? "cashu" : submission.rail;
11693
+ if (submission.requestAmountMsats !== request2.amount_msats)
11694
+ throw unconfirmedPaymentError(jobId, "The unconfirmed payment held for this request answered a different amount.");
11695
+ if (args.rail !== void 0 && args.rail !== sentRail)
11696
+ throw unconfirmedPaymentError(
11697
+ jobId,
11698
+ `An unconfirmed ${sentRail} payment was already sent for this request.`,
11699
+ `Re-send it with \`dvm pay ${guidanceJobArg(jobId)}\` without --rail; it re-delivers that same payment.`
11700
+ );
11701
+ if (submission.rail !== "cashu_p2pk")
11702
+ return deliverSignedRailPayment({ ...args, submission, redelivery: true });
11703
+ const wallet = loadAgentWallet();
11704
+ if (!wallet)
11705
+ throw unconfirmedPaymentError(
11706
+ jobId,
11707
+ "The agent wallet holding the unconfirmed Cashu payment for this request is unavailable.",
11708
+ `Restore the agent wallet, then run \`dvm pay ${guidanceJobArg(jobId)}\` to re-send that same payment. ${unresendablePaymentHint(jobId)}`
11709
+ );
11710
+ const held = wallet.pending_submissions.find((entry) => entry.request_id === submission.cashuRequestId);
11711
+ if (!held)
11712
+ throw unconfirmedPaymentError(jobId, "The wallet no longer holds the unconfirmed Cashu payment for this request and recorded no verdict on it.");
11713
+ const cashuToken = held.cashu_token ?? (held.output_proofs.length ? ki({ mint: held.mint, proofs: toCashuProofs(held.output_proofs) }) : void 0);
11714
+ if (!cashuToken || !sameEndpoint(held.endpoint, provider.endpoint))
11715
+ throw unconfirmedPaymentError(jobId, "The unconfirmed Cashu payment for this request cannot be re-delivered.");
11716
+ await deliverAgentWalletPayment({
11717
+ ...args,
11718
+ submission: held.output_proofs.some((proof) => proof.reserved_for !== void 0) ? { ...submission, reserve: true } : submission,
11719
+ redelivery: true,
11720
+ prepared: {
11721
+ cashuToken,
11722
+ requestId: held.request_id,
11723
+ mint: held.mint,
11724
+ totalSats: held.amount_sats,
11725
+ endpoint: held.endpoint,
11726
+ intendedLockPubkey: held.intended_lock_pubkey
11727
+ }
11728
+ });
11729
+ return { status: "paid", rail: "cashu_p2pk", amountMsats: request2.amount_msats };
11730
+ }
11731
+ async function deliverSignedRailPayment(args) {
11732
+ const { jobId, submission, provider } = args;
11733
+ const sent = await sendRailPayment(
11734
+ args.transport,
11735
+ jobId,
11736
+ { type: "payment", content: submission.content },
11737
+ provider,
11738
+ { jobToken: args.jobToken },
11739
+ args.requestSeq,
11740
+ submission,
11741
+ args.redelivery
11742
+ );
11743
+ if (!sent.tracked) {
11744
+ addPayment(jobId, submission.amountMsats, args.approval);
11745
+ recordSpend({
11746
+ msats: submission.amountMsats,
11747
+ btcRate: submission.btcRate,
11748
+ jobId,
11749
+ providerEndpoint: provider.endpoint,
11750
+ ...midJobSpendLabel(args.request.reason)
11751
+ });
11752
+ } else if (sent.booked) await finishBookedSubmission(jobId, sent.booked, provider.endpoint);
11753
+ return {
11754
+ status: "paid",
11755
+ rail: submission.rail,
11756
+ amountMsats: submission.amountMsats,
11757
+ ...submission.amountUsdcMicro !== void 0 ? { amountUsdcMicro: submission.amountUsdcMicro } : {}
11758
+ };
11486
11759
  }
11487
11760
  async function tryAgentWalletMidJobPayment(args) {
11488
11761
  const {
@@ -11542,22 +11815,57 @@ async function tryAgentWalletMidJobPayment(args) {
11542
11815
  prepared.error.attempts ? { mint_attempts: prepared.error.attempts } : void 0
11543
11816
  );
11544
11817
  }
11818
+ await deliverAgentWalletPayment({
11819
+ jobId,
11820
+ request: request2,
11821
+ prepared,
11822
+ transport,
11823
+ provider,
11824
+ approval,
11825
+ jobToken,
11826
+ requestSeq: args.requestSeq,
11827
+ submission: {
11828
+ rail: "cashu_p2pk",
11829
+ cashuRequestId: prepared.requestId,
11830
+ ...prepared.fromReserve ? { reserve: true } : {},
11831
+ requestAmountMsats: request2.amount_msats,
11832
+ amountMsats: request2.amount_msats,
11833
+ btcRate,
11834
+ approval: approval?.approval,
11835
+ reason: request2.reason
11836
+ }
11837
+ });
11838
+ return true;
11839
+ }
11840
+ async function deliverAgentWalletPayment(args) {
11841
+ const { jobId, request: request2, prepared, submission, transport, provider, approval, jobToken } = args;
11842
+ let sent;
11545
11843
  try {
11546
- await sendMidJobPaymentWithRetry({
11844
+ sent = await sendMidJobPaymentWithRetry({
11547
11845
  jobId,
11548
11846
  amountMsats: request2.amount_msats,
11549
11847
  prepared,
11550
11848
  transport,
11551
11849
  provider,
11552
11850
  jobToken,
11553
- requestSeq: args.requestSeq
11851
+ requestSeq: args.requestSeq,
11852
+ submission,
11853
+ redelivery: args.redelivery
11554
11854
  });
11555
11855
  } catch (err) {
11556
- if (err instanceof DvmError && err.code === "payment_invalid") {
11856
+ if (err instanceof DvmError && err.code === "payment_invalid" && sendOutcome(err, submission, args.redelivery).kind === "refused") {
11557
11857
  await abandonPendingSubmission({ requestId: prepared.requestId, preserveRecovery: true });
11558
11858
  }
11859
+ if (args.requestSeq !== void 0 && err instanceof DvmError && (err.code === "payment_lock_pubkey_stale" || err.code === "wrong_lock_pubkey")) {
11860
+ const reclaimAt = loadAgentWallet()?.pending_submissions.find((entry) => entry.request_id === prepared.requestId)?.t_expire;
11861
+ blockHeldPayment(jobId, args.requestSeq, { reason: "not_resendable", detail: "The provider no longer accepts the lock key this Cashu token was made for, though it may still redeem it." + (reclaimAt ? ` The wallet can take the token back after ${new Date(reclaimAt).toISOString()} if it does not.` : "") });
11862
+ }
11559
11863
  throw err;
11560
11864
  }
11865
+ if (sent.tracked) {
11866
+ if (sent.booked) await finishBookedSubmission(jobId, sent.booked, provider.endpoint);
11867
+ return;
11868
+ }
11561
11869
  await commitAgentSpend({
11562
11870
  requestId: prepared.requestId,
11563
11871
  recentSpend: {
@@ -11571,16 +11879,15 @@ async function tryAgentWalletMidJobPayment(args) {
11571
11879
  addPayment(jobId, request2.amount_msats, approval);
11572
11880
  recordSpend({
11573
11881
  msats: request2.amount_msats,
11574
- btcRate,
11882
+ btcRate: submission.btcRate,
11575
11883
  jobId,
11576
11884
  providerEndpoint: provider.endpoint,
11577
11885
  ...midJobSpendLabel(request2.reason)
11578
11886
  });
11579
- return true;
11580
11887
  }
11581
11888
  async function sendMidJobPaymentWithRetry(args) {
11582
11889
  const { jobId, amountMsats, prepared, transport, provider, jobToken } = args;
11583
- await withAgentWalletPaymentRetry({
11890
+ return withAgentWalletPaymentRetry({
11584
11891
  attempt: () => sendRailPayment(
11585
11892
  transport,
11586
11893
  jobId,
@@ -11595,14 +11902,16 @@ async function sendMidJobPaymentWithRetry(args) {
11595
11902
  },
11596
11903
  provider,
11597
11904
  { jobToken },
11598
- args.requestSeq
11905
+ args.requestSeq,
11906
+ args.submission,
11907
+ args.redelivery
11599
11908
  ),
11600
11909
  intendedLockPubkey: prepared.intendedLockPubkey,
11601
11910
  refetchInfo: () => transport.describe(provider),
11602
11911
  sleep: args.sleep
11603
11912
  });
11604
11913
  }
11605
- async function sendRailPayment(transport, jobId, message2, provider, options, requestSeq) {
11914
+ async function sendRailPayment(transport, jobId, message2, provider, options, requestSeq, submission, redelivery) {
11606
11915
  const capture = (evidence) => {
11607
11916
  if (evidence.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
11608
11917
  if (evidence.drawFundingReceipt) captureDrawFundingReceipts(jobId, [evidence.drawFundingReceipt], {
@@ -11610,31 +11919,81 @@ async function sendRailPayment(transport, jobId, message2, provider, options, re
11610
11919
  ...typeof message2.content.cashu_request_id === "string" ? { fundId: message2.content.cashu_request_id } : {}
11611
11920
  });
11612
11921
  };
11613
- if (requestSeq !== void 0) markPaymentRequestInFlight(jobId, requestSeq);
11922
+ if (requestSeq !== void 0) markPaymentRequestInFlight(jobId, requestSeq, submission);
11923
+ let result;
11614
11924
  try {
11615
- const result = await transport.sendMessage(jobId, message2, provider, options);
11616
- if (requestSeq !== void 0) markPaymentRequestPaid(jobId, requestSeq);
11617
- if (result) capture(result);
11925
+ result = await transport.sendMessage(jobId, message2, provider, options);
11618
11926
  } catch (error) {
11619
- if (requestSeq !== void 0) {
11620
- if (error instanceof DvmError && error.code === "replay_rejected") markPaymentRequestPaid(jobId, requestSeq);
11621
- else if (definitelyNotAccepted(error)) clearPaymentRequestInFlight(jobId, requestSeq);
11622
- else markPaymentRequestInFlight(jobId, requestSeq);
11623
- }
11624
11927
  if (error instanceof DvmError && error.data) capture(error.data);
11625
- if (error instanceof DvmError && error.code === "replay_rejected") return;
11928
+ const outcome = sendOutcome(error, submission, redelivery);
11929
+ if (requestSeq === void 0) {
11930
+ if (outcome.kind === "taken" && error instanceof DvmError && error.code === "replay_rejected") return { tracked: false };
11931
+ throw error;
11932
+ }
11933
+ if (outcome.kind === "taken") return { tracked: true, booked: markPaymentRequestPaid(jobId, requestSeq) };
11934
+ if (outcome.kind === "blocked") blockHeldPayment(jobId, requestSeq, outcome.blocked);
11935
+ else if (outcome.kind === "refused") clearPaymentRequestInFlight(jobId, requestSeq);
11936
+ else if (outcome.kind === "not_sent") clearPaymentRequestInFlight(jobId, requestSeq, { keepSubmission: true });
11937
+ else markPaymentRequestInFlight(jobId, requestSeq);
11626
11938
  throw error;
11627
11939
  }
11628
- }
11629
- function definitelyNotAccepted(error) {
11630
- if (error instanceof DvmError) {
11631
- const status2 = error.data?.http_status;
11632
- return typeof status2 === "number" && status2 >= 400 && status2 < 500;
11940
+ const sent = requestSeq === void 0 ? { tracked: false } : { tracked: true, booked: markPaymentRequestPaid(jobId, requestSeq) };
11941
+ if (result) capture(result);
11942
+ return sent;
11943
+ }
11944
+ var DEFINITE_REFUSALS = /* @__PURE__ */ new Set([
11945
+ "payment_invalid",
11946
+ "lock_not_exclusive",
11947
+ "not_p2pk_locked",
11948
+ "cashu_not_p2pk_locked",
11949
+ "invalid_token",
11950
+ "invalid_message",
11951
+ "invalid_input",
11952
+ "invalid_request"
11953
+ ]);
11954
+ function sendOutcome(error, submission, redelivery) {
11955
+ if (!(error instanceof DvmError)) return { kind: requestNeverSent(error) ? "not_sent" : "unknown" };
11956
+ if (error.code === "replay_rejected") return { kind: "taken" };
11957
+ const status2 = error.data?.http_status;
11958
+ if (typeof status2 !== "number" || status2 < 400 || status2 >= 500) return { kind: "unknown" };
11959
+ if (error.data?.code_source === "inferred") return { kind: "unknown" };
11960
+ const cashu = submission?.rail === "cashu_p2pk" ? submission : void 0;
11961
+ if (cashu && error.code === "proof_not_unspent") {
11962
+ if (!cashu.reserve) return { kind: "taken" };
11963
+ return { kind: "blocked", blocked: {
11964
+ reason: "proofs_spent",
11965
+ detail: "The reserve proofs the earlier Cashu payment used are already spent at the mint and the provider recorded no payment for this charge, but it may already have redeemed this token for this charge, so paying again may pay twice."
11966
+ } };
11967
+ }
11968
+ if (error.code === "payment_insufficient")
11969
+ return { kind: "blocked", blocked: {
11970
+ reason: "credit_held",
11971
+ ...typeof error.data?.credit_id === "string" ? { creditId: error.data.credit_id } : {}
11972
+ } };
11973
+ if (error.code === "request_id_reused")
11974
+ return { kind: "blocked", blocked: {
11975
+ reason: "not_resendable",
11976
+ detail: "The provider did not take this payment, because its request id already carries a different payment there."
11977
+ } };
11978
+ if (!DEFINITE_REFUSALS.has(error.code)) return { kind: "unknown" };
11979
+ if (redelivery && submission && submission.rail !== "cashu_p2pk" && error.code === "payment_invalid")
11980
+ return { kind: "blocked", blocked: { reason: "not_resendable", detail: submission.rail === "tempo" ? "The provider refused the earlier Tempo credential, which it also does for one it already used." : `${x402RefusalNote(submission.content.x402_payment)} It also answers that way for an authorization it already settled.` } };
11981
+ return { kind: "refused" };
11982
+ }
11983
+ function x402RefusalNote(header) {
11984
+ try {
11985
+ const validBefore = Number(exactEvmAuthorization(decodePayment(String(header))).validBefore) * 1e3;
11986
+ if (Number.isFinite(validBefore))
11987
+ return validBefore <= Date.now() ? `The provider refused the earlier x402 authorization, which expired at ${new Date(validBefore).toISOString()}.` : "The provider refused the earlier x402 authorization before it expired.";
11988
+ } catch {
11633
11989
  }
11634
- if (!(error instanceof Error)) return false;
11990
+ return "The provider refused the earlier x402 authorization.";
11991
+ }
11992
+ function requestNeverSent(error) {
11993
+ if (!(error instanceof Error) || error instanceof DvmError) return false;
11635
11994
  if ("code" in error && ["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH"].includes(String(error.code))) return true;
11636
- if (error instanceof AggregateError) return error.errors.length > 0 && error.errors.every(definitelyNotAccepted);
11637
- return definitelyNotAccepted(error.cause);
11995
+ if (error instanceof AggregateError) return error.errors.length > 0 && error.errors.every(requestNeverSent);
11996
+ return requestNeverSent(error.cause);
11638
11997
  }
11639
11998
  async function tryMppCredential(challenges, amountMsats, btcRate) {
11640
11999
  const wallet = loadConfig()?.tempo;
@@ -11786,7 +12145,7 @@ async function streamLoop(opts) {
11786
12145
  let messageAppendSession = opts.messageAppendSession;
11787
12146
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
11788
12147
  const declined = () => persistLocalState && loadJob(jobId)?.callerDeclined === true;
11789
- function recordAutoPayment(result, request2, seq) {
12148
+ async function recordAutoPayment(result, request2, seq) {
11790
12149
  autoPayments.push({
11791
12150
  amount_msats: result.amountMsats,
11792
12151
  rail: result.rail,
@@ -11794,7 +12153,7 @@ async function streamLoop(opts) {
11794
12153
  ...result.amountUsdcMicro !== void 0 && { amount_usdc_microunits: result.amountUsdcMicro },
11795
12154
  display: paidConfirmationDisplay(result, request2.fiat_amount)
11796
12155
  });
11797
- if (persistLocalState) markPaymentRequestPaid(jobId, seq);
12156
+ if (persistLocalState) markPaymentRequestAnswered(jobId, seq);
11798
12157
  answeredSeqs.add(seq);
11799
12158
  justAutoPaid = true;
11800
12159
  }
@@ -11809,10 +12168,10 @@ async function streamLoop(opts) {
11809
12168
  });
11810
12169
  } catch (error) {
11811
12170
  if (error instanceof DvmError && error.code === "payment_settling")
11812
- return { messages: [], autoPayments, refunds, cursor, nextAction: pollNextAction(jobId, paymentInFlightHint(jobId)) };
12171
+ return { messages: [], autoPayments, refunds, cursor, nextAction: pollNextAction(jobId, paymentInFlightHint(jobId, loadJob(jobId), pending4.authorization.request_seq)) };
11813
12172
  throw error;
11814
12173
  }
11815
- if (typeof result === "object") recordAutoPayment(result, pending4.request, pending4.authorization.request_seq);
12174
+ if (typeof result === "object") await recordAutoPayment(result, pending4.request, pending4.authorization.request_seq);
11816
12175
  else pendingAction = computeNextAction(jobId, [{
11817
12176
  seq: pending4.authorization.request_seq,
11818
12177
  from: "provider",
@@ -11875,6 +12234,7 @@ async function streamLoop(opts) {
11875
12234
  if (persistLocalState) {
11876
12235
  messageAppendSession ??= createMessageAppendSession(jobId);
11877
12236
  messageAppendSession.append(batchMessages);
12237
+ await settleRecordedPayments(jobId);
11878
12238
  }
11879
12239
  if (persistLocalState) {
11880
12240
  refunds.push(...await claimInboundPayments(jobId, batchMessages));
@@ -11885,7 +12245,8 @@ async function streamLoop(opts) {
11885
12245
  const pendingPayment = pendingPaymentRequest(batchMessages, answeredSeqs);
11886
12246
  const lastYield2 = findLastYield(batchMessages.filter((message2) => !answeredSeqs.has(message2.seq) && (message2.type !== "payment-request" || message2.seq === pendingPayment?.seq))) ?? findLastYield(batchMessages);
11887
12247
  if (lastYield2?.type === "payment-request" && answeredSeqs.has(lastYield2.seq)) {
11888
- if (persistLocalState) markPaymentRequestPaid(jobId, lastYield2.seq);
12248
+ if (persistLocalState && !declinedAskSeqs(jobId).has(lastYield2.seq))
12249
+ await settleAnsweredAsk(jobId, lastYield2.seq, loadMessages(jobId));
11889
12250
  break;
11890
12251
  }
11891
12252
  if (lastYield2?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield2.seq)) {
@@ -11915,8 +12276,9 @@ async function streamLoop(opts) {
11915
12276
  requestSeq: lastYield2.seq
11916
12277
  });
11917
12278
  } catch (error) {
11918
- if (error instanceof DvmError && error.code === "payment_settling") {
12279
+ if (error instanceof DvmError && ["payment_settling", "payment_unconfirmed"].includes(error.code)) {
11919
12280
  paymentUnresolved = true;
12281
+ if (error.code === "payment_unconfirmed") cursor = Math.min(cursor, lastYield2.seq - 1);
11920
12282
  break;
11921
12283
  }
11922
12284
  if (error instanceof DvmError && error.code === "payment_already_sent") {
@@ -11926,7 +12288,7 @@ async function streamLoop(opts) {
11926
12288
  throw error;
11927
12289
  }
11928
12290
  if (typeof result === "object") {
11929
- recordAutoPayment(result, req, lastYield2.seq);
12291
+ await recordAutoPayment(result, req, lastYield2.seq);
11930
12292
  continue;
11931
12293
  }
11932
12294
  if (result === "payment-cap-exceeded") {
@@ -11969,6 +12331,7 @@ async function streamLoop(opts) {
11969
12331
  if (persistLocalState) {
11970
12332
  messageAppendSession ??= createMessageAppendSession(jobId);
11971
12333
  messageAppendSession.append(recheck);
12334
+ await settleRecordedPayments(jobId);
11972
12335
  refunds.push(...await claimInboundPayments(jobId, recheck));
11973
12336
  }
11974
12337
  }
@@ -11979,8 +12342,9 @@ async function streamLoop(opts) {
11979
12342
  const yieldAction = computeNextAction(jobId, allMessages.filter((message2) => !answeredSeqs.has(message2.seq)), void 0, policy ? { policy, totalPaidMsats: loadJob(jobId)?.totalPaidMsats } : void 0) ?? (terminal ? null : pendingAction);
11980
12343
  let nextAction = withRefundNextAction(jobId, yieldAction ?? (terminal ? null : pollNextAction(jobId)), refunds);
11981
12344
  const lastYield = findLastYield(allMessages);
11982
- if (nextAction?.type === "pay" && lastYield?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield.seq))
11983
- nextAction = { ...nextAction, hint: paymentInFlightHint(jobId) };
12345
+ const heldJob = persistLocalState ? loadJob(jobId) : null;
12346
+ if (nextAction?.type === "pay" && lastYield?.type === "payment-request" && heldJob && (heldJob.inFlightPaymentRequestSeqs?.includes(lastYield.seq) || heldJob.unconfirmedPaymentSubmissions?.[lastYield.seq] || heldJob.askPaymentBlocks?.[lastYield.seq]))
12347
+ nextAction = { ...nextAction, hint: paymentInFlightHint(jobId, heldJob, lastYield.seq) };
11984
12348
  if (nextAction?.type === "pay" || nextAction?.type === "poll" && !terminal) {
11985
12349
  if (lastYield?.type === "payment-request" && answeredSeqs.has(lastYield.seq)) {
11986
12350
  nextAction = {
@@ -11990,7 +12354,11 @@ async function streamLoop(opts) {
11990
12354
  };
11991
12355
  }
11992
12356
  }
11993
- if (paymentUnresolved) nextAction = pollNextAction(jobId, paymentInFlightHint(jobId));
12357
+ if (paymentUnresolved) nextAction = pollNextAction(jobId, paymentInFlightHint(
12358
+ jobId,
12359
+ heldJob,
12360
+ lastYield?.type === "payment-request" ? lastYield.seq : void 0
12361
+ ));
11994
12362
  return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
11995
12363
  }
11996
12364
  function isMessagePollTimeout(err) {
@@ -12868,7 +13236,7 @@ var HttpsTransport = class {
12868
13236
  }
12869
13237
  if (res.status === 409) {
12870
13238
  const body2 = parseJsonObject(await res.text());
12871
- if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string")) {
13239
+ if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && body2.error === "request_id_reused" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string")) {
12872
13240
  const error = withDrawFunding(withCreditErrorContext(buildPaymentError(body2), body2), body2);
12873
13241
  error.data = { ...error.data, http_status: res.status };
12874
13242
  throw error;
@@ -13180,7 +13548,7 @@ function parseStructuredError(body) {
13180
13548
  if (err && typeof err === "object" && !Array.isArray(err)) {
13181
13549
  const e = err;
13182
13550
  if (typeof e.code !== "string") return null;
13183
- return buildStructuredError(e.code, e);
13551
+ return buildStructuredError(e.code, e, parsed);
13184
13552
  }
13185
13553
  if (typeof err !== "string") return null;
13186
13554
  if (err === "invalid_input" || err === "invalid_quote_data") {
@@ -13196,7 +13564,7 @@ function jobCredentialError(status2, body) {
13196
13564
  if (status2 !== 401) return null;
13197
13565
  return parseStructuredError(body);
13198
13566
  }
13199
- function buildStructuredError(code, fields) {
13567
+ function buildStructuredError(code, fields, envelope = fields) {
13200
13568
  const display = typeof fields.display === "string" ? fields.display : void 0;
13201
13569
  const providerMessage = typeof fields.message === "string" ? fields.message : void 0;
13202
13570
  const message2 = providerMessage ?? display ?? "The provider returned an error without explanatory prose.";
@@ -13204,10 +13572,10 @@ function buildStructuredError(code, fields) {
13204
13572
  const data = {};
13205
13573
  if (display !== void 0) data.display = display;
13206
13574
  if (typeof fields.retryable === "boolean") data.retryable = fields.retryable;
13207
- if (fields.status === "unknown") data.status = fields.status;
13575
+ if (fields.status === "unknown" || envelope.status === "unknown") data.status = "unknown";
13208
13576
  if (typeof fields.request_id === "string") data.request_id = fields.request_id;
13209
13577
  if (fields.server_acceptance === "absent") data.server_acceptance = fields.server_acceptance;
13210
- if (fields.payment_state === "unknown") data.payment_state = fields.payment_state;
13578
+ if (fields.payment_state === "unknown" || envelope.payment_state === "unknown") data.payment_state = "unknown";
13211
13579
  const detectedSources = providerProseSources(fields, data);
13212
13580
  const proseSources = display !== void 0 && providerMessage === void 0 ? { ...detectedSources, message: "provider" } : detectedSources;
13213
13581
  return new DvmError(
@@ -13271,8 +13639,12 @@ function isReceipt402(code) {
13271
13639
  return code === void 0 || code === "payment_required" || code === "payment_insufficient";
13272
13640
  }
13273
13641
  function buildPaymentError(errorBody) {
13274
- const code = typeof errorBody.error === "string" ? errorBody.error : "payment_insufficient";
13275
- return buildStructuredError(code, errorBody);
13642
+ if (typeof errorBody.error === "string") return buildStructuredError(errorBody.error, errorBody);
13643
+ const nested = errorBody.error && typeof errorBody.error === "object" && !Array.isArray(errorBody.error) ? errorBody.error : void 0;
13644
+ if (typeof nested?.code === "string") return buildStructuredError(nested.code, nested, errorBody);
13645
+ const error = buildStructuredError("payment_insufficient", errorBody);
13646
+ error.data = { ...error.data, code_source: "inferred" };
13647
+ return error;
13276
13648
  }
13277
13649
  async function paymentHeaders(payment) {
13278
13650
  const headers = {};
@@ -13699,6 +14071,55 @@ function round2(n) {
13699
14071
  return Math.round(n * 100) / 100;
13700
14072
  }
13701
14073
 
14074
+ // src/lib/terminal-completion.ts
14075
+ async function readTerminalCompletion(args) {
14076
+ const { jobId, status: status2, saved, transport, ref, jobToken } = args;
14077
+ let completion = completionSnapshot(status2);
14078
+ if (!isTerminalJobStatus(status2.status) || status2.content_available === false) return completion;
14079
+ if (completion.hasArtifacts === void 0) {
14080
+ delete completion.artifactCount;
14081
+ delete completion.payloadIn;
14082
+ try {
14083
+ const messages2 = await transport.getMessages(jobId, 0, ref, {
14084
+ jobToken,
14085
+ timeoutMs: args.timeoutMs ?? 5e3
14086
+ });
14087
+ const derived = messages2.length === 0 && saved?.hasArtifacts !== void 0 ? saved : completionFromMessages(messages2);
14088
+ completion = { ...derived, ...completion };
14089
+ } catch {
14090
+ completion = { ...saved, ...completion };
14091
+ }
14092
+ }
14093
+ return completionForStatus(status2.status, completion);
14094
+ }
14095
+ function completionForStatus(status2, input) {
14096
+ const completion = { ...input };
14097
+ if (status2 !== "completed") {
14098
+ if (completion.hasArtifacts === true) completion.payloadIn = "messages";
14099
+ else delete completion.payloadIn;
14100
+ }
14101
+ return completion;
14102
+ }
14103
+ function terminalCompletionOutput(jobId, status2, input, options = {}) {
14104
+ if (!isTerminalJobStatus(status2)) return { fields: {} };
14105
+ const completion = completionForStatus(status2, input);
14106
+ const fields = buildCompletionHintFields(jobId, completion);
14107
+ if (options.contentAvailable === false) {
14108
+ delete fields.next_step_hint;
14109
+ if (fields.payload_in === "messages") delete fields.payload_in;
14110
+ return { fields };
14111
+ }
14112
+ let hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, options.human);
14113
+ if (completion.hasArtifacts === void 0 && status2 !== "completed") {
14114
+ const job = options.human ? shellQuoteArg(jobId) : guidanceJobArg(jobId);
14115
+ hint = `Any output from finished pieces can be read with 'dvm messages ${job} --no-stream'.`;
14116
+ }
14117
+ if (hint) fields.next_step_hint = hint;
14118
+ const count = typeof completion.artifactCount === "number" && Number.isSafeInteger(completion.artifactCount) && completion.artifactCount >= 0 ? completion.artifactCount : void 0;
14119
+ const display = completion.hasArtifacts === true && hint ? `The job holds ${count === void 0 ? "artifacts" : `${count} artifact${count === 1 ? "" : "s"}`}. ${hint}` : hint;
14120
+ return { fields, hint, display };
14121
+ }
14122
+
13702
14123
  // src/lib/dvm-identifier.ts
13703
14124
  var TAG_NAME_RE = CAPABILITY_NAME_RE;
13704
14125
  var HANDLE_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
@@ -13947,7 +14368,7 @@ async function settleCreditAfterJob(args) {
13947
14368
  }
13948
14369
  }
13949
14370
  if (args.allowTopup !== false) {
13950
- const refill = args.refillPocket ?? (await import("./pocket-refill-7Q6CR6I4.js")).refillPocketIfLow;
14371
+ const refill = args.refillPocket ?? (await import("./pocket-refill-XZTMPTP6.js")).refillPocketIfLow;
13951
14372
  await refill({ human: args.human }).catch(() => void 0);
13952
14373
  }
13953
14374
  }
@@ -14365,7 +14786,10 @@ async function cancelWithAccess(jobId, opts, access) {
14365
14786
  if (!access.endpointOverridden) markJobTerminal(
14366
14787
  jobId,
14367
14788
  "cancelled",
14368
- opts.reason !== void 0 ? { message: opts.reason } : {},
14789
+ {
14790
+ ...stored?.status === "cancelled" ? stored.completion : {},
14791
+ ...opts.reason !== void 0 ? { message: opts.reason } : {}
14792
+ },
14369
14793
  { callerCancelled: true }
14370
14794
  );
14371
14795
  const { settlement, status: status2 } = await readEnding({
@@ -14374,12 +14798,33 @@ async function cancelWithAccess(jobId, opts, access) {
14374
14798
  ref,
14375
14799
  jobToken,
14376
14800
  persistLocalState: !access.endpointOverridden,
14377
- human: opts.human
14801
+ human: opts.human,
14802
+ onTerminal: () => {
14803
+ if (!access.endpointOverridden) clearAskPaymentBlocks(jobId);
14804
+ }
14805
+ });
14806
+ const saved = stored?.status === "cancelled" ? stored.completion : void 0;
14807
+ const completion = await readTerminalCompletion({
14808
+ jobId,
14809
+ status: status2 ?? { status: "cancelled" },
14810
+ saved,
14811
+ transport,
14812
+ ref,
14813
+ jobToken
14814
+ });
14815
+ if (!access.endpointOverridden) markJobTerminal(jobId, "cancelled", {
14816
+ ...status2?.content_available === false && saved ? saved : completion,
14817
+ ...opts.reason !== void 0 ? { message: opts.reason } : {}
14818
+ });
14819
+ const artifacts = terminalCompletionOutput(jobId, "cancelled", completion, {
14820
+ human: opts.human,
14821
+ contentAvailable: status2?.content_available
14378
14822
  });
14379
14823
  transport.close();
14380
14824
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
14381
14825
  const receiptPending = !settlement && status2 !== void 0 && isTerminalJobStatus(status2.status) && !status2.receipt && !status2.receiptParseError && !access.endpointOverridden && expectsReceipt(jobId, stored);
14382
- const display = settlement ? cancelledDisplay(settlement) : receiptPending ? `Stopped. Its receipt is not available yet; \`dvm status ${guidanceJobArg(jobId)}\` shows what was charged once it is.` : void 0;
14826
+ 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;
14827
+ const display = [endingDisplay, artifacts.display].filter(Boolean).join(" ") || void 0;
14383
14828
  const hint = settlementCurrencyHint(settlement, ref.endpoint);
14384
14829
  if (opts.human) {
14385
14830
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
@@ -14393,6 +14838,7 @@ async function cancelWithAccess(jobId, opts, access) {
14393
14838
  ...opts.reason ? { reason: opts.reason } : {},
14394
14839
  ...settlement ? { settlement } : {},
14395
14840
  ...display ? { display } : {},
14841
+ ...artifacts.fields,
14396
14842
  ...hint ? { hint } : {},
14397
14843
  next_action: null
14398
14844
  });
@@ -14426,17 +14872,23 @@ async function declineWithAccess(jobId, opts, access) {
14426
14872
  persistLocalState: !access.endpointOverridden,
14427
14873
  human: opts.human,
14428
14874
  onTerminal: (status2) => {
14429
- if (!access.endpointOverridden && isTerminalJobStatus(status2.status)) markJobTerminal(
14430
- jobId,
14431
- status2.status,
14432
- opts.reason !== void 0 ? { message: opts.reason } : {},
14433
- { callerCancelled: true, callerDeclined: true }
14434
- );
14875
+ if (!access.endpointOverridden && isTerminalJobStatus(status2.status)) {
14876
+ markJobTerminal(
14877
+ jobId,
14878
+ status2.status,
14879
+ {
14880
+ ...stored?.status === status2.status ? stored.completion : {},
14881
+ ...opts.reason !== void 0 ? { message: opts.reason } : {}
14882
+ },
14883
+ { callerCancelled: true, callerDeclined: true }
14884
+ );
14885
+ clearAskPaymentBlocks(jobId);
14886
+ }
14435
14887
  }
14436
14888
  });
14437
- transport.close();
14438
14889
  const observed = ending.status?.status;
14439
14890
  if (observed !== void 0 && !isTerminalJobStatus(observed)) {
14891
+ transport.close();
14440
14892
  throw new DvmError(
14441
14893
  "decline_unsupported",
14442
14894
  `The provider accepted the decline, but the job is still ${observed}.`,
@@ -14444,9 +14896,30 @@ async function declineWithAccess(jobId, opts, access) {
14444
14896
  { jobId, status: observed }
14445
14897
  );
14446
14898
  }
14899
+ const completion = ending.status ? await readTerminalCompletion({
14900
+ jobId,
14901
+ status: ending.status,
14902
+ transport,
14903
+ ref,
14904
+ jobToken,
14905
+ saved: stored && stored.status === observed ? stored.completion : void 0
14906
+ }) : {};
14907
+ if (observed && isTerminalJobStatus(observed) && !access.endpointOverridden) {
14908
+ const saved = stored?.status === observed ? stored.completion : void 0;
14909
+ markJobTerminal(jobId, observed, {
14910
+ ...ending.status?.content_available === false && saved ? saved : completion,
14911
+ ...opts.reason !== void 0 ? { message: opts.reason } : {}
14912
+ });
14913
+ }
14914
+ const artifacts = terminalCompletionOutput(jobId, observed ?? "unknown", completion, {
14915
+ human: opts.human,
14916
+ contentAvailable: ending.status?.content_available
14917
+ });
14918
+ transport.close();
14447
14919
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
14448
14920
  const { settlement } = ending;
14449
- const display = observed === void 0 ? `Decline sent, but the job's status could not be read. Check it with \`dvm status ${job}\`.` : settlement ? `Declined; the job has ended. ${settlement.display}` : `Declined; the job has ended. Its receipt is not available yet; \`dvm status ${job}\` shows the final charge once it is.`;
14921
+ 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.`;
14922
+ const display = [endingDisplay, artifacts.display].filter(Boolean).join(" ");
14450
14923
  const hint = settlementCurrencyHint(settlement, ref.endpoint);
14451
14924
  if (opts.human) {
14452
14925
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""}: ${display}`);
@@ -14461,6 +14934,7 @@ async function declineWithAccess(jobId, opts, access) {
14461
14934
  ...opts.reason !== void 0 ? { reason: opts.reason } : {},
14462
14935
  ...settlement ? { settlement } : {},
14463
14936
  display,
14937
+ ...artifacts.fields,
14464
14938
  ...hint ? { hint } : {},
14465
14939
  next_action: observed === void 0 ? pollNextAction(jobId, display) : null
14466
14940
  });
@@ -15217,8 +15691,9 @@ async function creditOp(transport, endpoint, body, payment) {
15217
15691
  function advisoryBtcRate() {
15218
15692
  return tryResolveBtcUsdRate().then((resolved) => resolved?.rate).catch(() => void 0);
15219
15693
  }
15220
- function implicitCreditJson(credit) {
15694
+ function implicitCreditJson(credit, postureOff) {
15221
15695
  const active2 = credit.status === "active";
15696
+ const blocked = active2 && postureOff;
15222
15697
  const amount = formatFiat(Math.max(credit.remainingMicro, 0) / 1e6, credit.currency);
15223
15698
  const label = dvmLabelFromEndpoint(credit.endpoint);
15224
15699
  return {
@@ -15232,7 +15707,8 @@ function implicitCreditJson(credit) {
15232
15707
  expiry_ms: credit.expiryMs,
15233
15708
  status: credit.status,
15234
15709
  tracked: true,
15235
- drawable: active2,
15710
+ drawable: active2 && !postureOff,
15711
+ ...blocked ? { draw_blocked_reason: "posture_off" } : {},
15236
15712
  drainable: false,
15237
15713
  released_by_job_id: credit.releasedByJobId,
15238
15714
  released_at_ms: credit.releasedAt,
@@ -15247,7 +15723,7 @@ function implicitCreditJson(credit) {
15247
15723
  job_id: credit.discrepancy.jobId
15248
15724
  }
15249
15725
  } : {},
15250
- 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.`,
15726
+ 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.`,
15251
15727
  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."
15252
15728
  };
15253
15729
  }
@@ -15259,6 +15735,7 @@ function currencyTotal(totals, currency) {
15259
15735
  trackedCount: 0,
15260
15736
  siblingCount: 0,
15261
15737
  drawableMicro: 0,
15738
+ postureBlockedMicro: 0,
15262
15739
  siblingSpendableMicro: 0
15263
15740
  };
15264
15741
  totals.set(currency, created);
@@ -15273,8 +15750,9 @@ function creditCurrencyTotalsJson(total, source) {
15273
15750
  tracked_count: total.trackedCount,
15274
15751
  sibling_count: total.siblingCount,
15275
15752
  drawable_micro: total.drawableMicro,
15753
+ ...total.postureBlockedMicro > 0 ? { posture_blocked_micro: total.postureBlockedMicro } : {},
15276
15754
  sibling_spendable_micro: total.siblingSpendableMicro,
15277
- spendable_micro: total.drawableMicro + total.siblingSpendableMicro,
15755
+ spendable_micro: total.drawableMicro + total.postureBlockedMicro + total.siblingSpendableMicro,
15278
15756
  display: creditCurrencyTotalDisplay(total, source)
15279
15757
  };
15280
15758
  }
@@ -15286,10 +15764,14 @@ function creditCurrencyTotalDisplay(total, source) {
15286
15764
  const drawable = formatFiat(total.drawableMicro / 1e6, total.currency);
15287
15765
  const sibling = formatFiat(total.siblingSpendableMicro / 1e6, total.currency);
15288
15766
  const spendable = formatFiat(
15289
- (total.drawableMicro + total.siblingSpendableMicro) / 1e6,
15767
+ (total.drawableMicro + total.postureBlockedMicro + total.siblingSpendableMicro) / 1e6,
15290
15768
  total.currency
15291
15769
  );
15292
15770
  const certainty = source === "local" ? "believed" : "server-confirmed";
15771
+ if (total.postureBlockedMicro > 0) {
15772
+ const blocked = formatFiat(total.postureBlockedMicro / 1e6, total.currency);
15773
+ 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.`;
15774
+ }
15293
15775
  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()}.`;
15294
15776
  }
15295
15777
  function headroomReader() {
@@ -15469,9 +15951,11 @@ async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate,
15469
15951
  }
15470
15952
  const providerInfo = await transport.describe({ endpoint }).catch(() => void 0);
15471
15953
  const identity = providerDvmIdentity(providerInfo);
15954
+ const postureOff = effectiveCreditPosture(loadConfig()?.credit, endpoint, identity).posture === "off";
15472
15955
  if (!providerInfo)
15473
15956
  throw new DvmError("provider_unavailable", "Could not read provider metadata.");
15474
- const implicitCredits = loadImplicitCredits(endpoint, signer.pubkey, identity).filter(
15957
+ const localImplicitCredits = loadImplicitCredits(endpoint, signer.pubkey, identity);
15958
+ const implicitCredits = localImplicitCredits.filter(
15475
15959
  (credit) => !creditId || credit.creditId === creditId
15476
15960
  );
15477
15961
  const signCredit = (body) => signDvmRequestData(
@@ -15508,7 +15992,7 @@ async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate,
15508
15992
  }
15509
15993
  } catch (err) {
15510
15994
  if (err instanceof DvmError && err.code === "credit_not_supported") {
15511
- const rows = implicitCredits.map(implicitCreditJson);
15995
+ const rows = implicitCredits.map((credit) => implicitCreditJson(credit, postureOff));
15512
15996
  return {
15513
15997
  rows: rows.length > 0 ? rows : [
15514
15998
  {
@@ -15565,16 +16049,18 @@ async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate,
15565
16049
  ...btcRate !== void 0 ? { btcRate } : {}
15566
16050
  });
15567
16051
  const liveIds = new Set(credits.map((credit) => credit.credit_id));
16052
+ const implicitById = new Map(localImplicitCredits.map((credit) => [credit.creditId, credit]));
15568
16053
  return {
15569
16054
  rows: [
15570
16055
  ...credits.map(
15571
- (credit) => wireCreditJson(
16056
+ (credit) => credit.credit_id.startsWith("imp:") ? wireImplicitCreditJson(endpoint, credit, implicitById.get(credit.credit_id), postureOff) : wireCreditJson(
15572
16057
  endpoint,
15573
16058
  credit,
15574
- credit.credit_id === currentStored?.creditId && currentStored.selectionCleared !== true
16059
+ credit.credit_id === currentStored?.creditId && currentStored.selectionCleared !== true,
16060
+ postureOff
15575
16061
  )
15576
16062
  ),
15577
- ...implicitCredits.filter((credit) => !liveIds.has(credit.creditId)).map(implicitCreditJson)
16063
+ ...implicitCredits.filter((credit) => !liveIds.has(credit.creditId)).map((credit) => implicitCreditJson(credit, postureOff))
15578
16064
  ],
15579
16065
  // Emitted even when `credits` is empty: the server just stated its menu, so
15580
16066
  // this read answers "what could I open here" without a second round trip.
@@ -15590,7 +16076,25 @@ function advisoryBtcRateOnce() {
15590
16076
  let pending4;
15591
16077
  return () => pending4 ??= advisoryBtcRate();
15592
16078
  }
15593
- function wireCreditJson(endpoint, credit, tracked) {
16079
+ function wireImplicitCreditJson(endpoint, credit, local, postureOff) {
16080
+ const label = dvmLabelFromEndpoint(endpoint);
16081
+ const amount = formatFiat(Math.max(credit.remaining_micro, 0) / 1e6, credit.currency);
16082
+ 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;
16083
+ const blocked = unavailable === void 0 && postureOff;
16084
+ return {
16085
+ endpoint,
16086
+ dvm: label,
16087
+ ...credit,
16088
+ kind: "implicit",
16089
+ tracked: local !== void 0,
16090
+ drawable: unavailable === void 0 && !postureOff,
16091
+ ...blocked ? { draw_blocked_reason: "posture_off" } : {},
16092
+ drainable: false,
16093
+ ...local ? { released_by_job_id: local.releasedByJobId, released_at_ms: local.releasedAt } : {},
16094
+ 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.`
16095
+ };
16096
+ }
16097
+ function wireCreditJson(endpoint, credit, tracked, postureOff) {
15594
16098
  const label = dvmLabelFromEndpoint(endpoint);
15595
16099
  const unbacked = credit.status === "unbacked";
15596
16100
  const amount = formatFiat(
@@ -15599,14 +16103,18 @@ function wireCreditJson(endpoint, credit, tracked) {
15599
16103
  );
15600
16104
  const state = unbacked ? "closed \u2014 backing finalized before collection" : credit.reconciliation_pending ? "backing reconciliation pending" : credit.expired ? "expired \u2014 balance reclaimable" : "spendable";
15601
16105
  const command = creditDrainCommand(endpoint, credit.credit_id);
16106
+ const active2 = !credit.expired && !unbacked && !credit.reconciliation_pending;
16107
+ const eligible = tracked && active2;
16108
+ const blocked = postureOff && eligible;
15602
16109
  return {
15603
16110
  endpoint,
15604
16111
  dvm: label,
15605
16112
  ...credit,
15606
16113
  tracked,
15607
- drawable: tracked && !credit.expired && !unbacked && !credit.reconciliation_pending,
16114
+ drawable: eligible && !postureOff,
16115
+ ...blocked ? { draw_blocked_reason: "posture_off" } : {},
15608
16116
  ...!tracked && credit.drainable ? { drain_command: command } : {},
15609
- 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).`,
16117
+ 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).`,
15610
16118
  ...!tracked && credit.drainable ? { hint: `Reclaim it with this command: ${command}` } : {}
15611
16119
  };
15612
16120
  }
@@ -15621,7 +16129,9 @@ function wireCreditCurrencyTotals(rows) {
15621
16129
  else total.siblingCount += 1;
15622
16130
  if (row.expired === true) continue;
15623
16131
  if (row.drawable === true) total.drawableMicro += Math.max(row.remaining_micro, 0);
15624
- else if (!row.tracked && row.drainable === true) {
16132
+ else if (row.draw_blocked_reason === "posture_off") {
16133
+ total.postureBlockedMicro += Math.max(row.remaining_micro, 0);
16134
+ } else if (!row.tracked && row.drainable === true) {
15625
16135
  total.siblingSpendableMicro += Math.max(row.remaining_micro, 0);
15626
16136
  }
15627
16137
  }
@@ -20076,16 +20586,17 @@ function creditList(opts) {
20076
20586
  const creditConfig = loadConfig()?.credit;
20077
20587
  const headroomOf = headroomReader();
20078
20588
  const identityOf = (endpoint) => offlineDvmIdentity(creditConfig, endpoint, headroomOf);
20079
- const postureOf = (endpoint) => effectiveCreditPosture(creditConfig, endpoint, identityOf(endpoint));
20589
+ const postureOf = (row) => effectiveCreditPosture(creditConfig, row.endpoint, dvmLocationIdentity(row) ?? identityOf(row.endpoint));
20590
+ const postureOff = (row) => postureOf(row).posture === "off";
20080
20591
  const fundingRailOf = (endpoint) => effectiveFundingRail(creditConfig, endpoint, identityOf(endpoint));
20081
20592
  const globalPosture = isCreditPosture(creditConfig?.posture) ? { posture: creditConfig.posture, source: "global" } : { posture: DEFAULT_CREDIT_POSTURE, source: "default" };
20082
20593
  const globalRail = effectiveFundingRail(creditConfig);
20083
20594
  const siblingCredits = credits.flatMap((credit) => credit.siblingCredits ?? []);
20084
- const totals = localCreditCurrencyTotals(credits, implicitCredits);
20595
+ const totals = localCreditCurrencyTotals(credits, implicitCredits, postureOff);
20085
20596
  if (opts.human) {
20086
20597
  info(humanPostureLine(globalPosture));
20087
20598
  for (const [endpoint, per] of postureOverrides(creditConfig)) {
20088
- info(` At ${dvmLabelFromEndpoint(endpoint)}: ${per} (overrides the global setting).`);
20599
+ info(` At ${dvmLabelFromEndpoint(endpoint)}: ${per} (overrides the global setting).${per === "off" ? " Spending held credit is also switched off." : ""}`);
20089
20600
  }
20090
20601
  info(humanFundingRailLine(globalRail));
20091
20602
  for (const [endpoint, rail] of fundingRailOverrides(creditConfig)) {
@@ -20099,13 +20610,13 @@ function creditList(opts) {
20099
20610
  return;
20100
20611
  }
20101
20612
  for (const c of credits) {
20102
- info(` ${humanCreditRow(c)}`);
20613
+ info(` ${humanCreditRow(c, postureOff(c))}`);
20103
20614
  for (const sibling of c.siblingCredits ?? []) {
20104
20615
  info(` ${humanSiblingCreditRow(c, sibling)}`);
20105
20616
  }
20106
20617
  info(` ${headroomDisplay(headroomOf.of(headroomInputsFor(c, identityOf(c.endpoint))))}`);
20107
20618
  }
20108
- for (const row of humanImplicitCreditRows(implicitCredits)) info(` ${row}`);
20619
+ for (const row of humanImplicitCreditRows(implicitCredits, postureOff)) info(` ${row}`);
20109
20620
  for (const snapshot of snapshots) {
20110
20621
  const machine = cachedDvmJson(snapshot, credits, headroomOf, identityOf(snapshot.endpoint));
20111
20622
  info(` ${String(machine.display)}`);
@@ -20139,19 +20650,19 @@ function creditList(opts) {
20139
20650
  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.`
20140
20651
  },
20141
20652
  credits: credits.map((c) => ({
20142
- ...storedCreditJson(c, headroomOf.of(headroomInputsFor(c, identityOf(c.endpoint)))),
20143
- ...postureFields(postureOf(c.endpoint)),
20653
+ ...storedCreditJson(c, headroomOf.of(headroomInputsFor(c, identityOf(c.endpoint))), postureOff(c)),
20654
+ ...postureFields(postureOf(c)),
20144
20655
  ...fundingRailFields(fundingRailOf(c.endpoint))
20145
20656
  })),
20146
20657
  count: credits.length,
20147
- implicit_credits: implicitCredits.map(implicitCreditJson),
20658
+ implicit_credits: implicitCredits.map((c) => implicitCreditJson(c, postureOff(c))),
20148
20659
  implicit_count: implicitCredits.length,
20149
20660
  credit_count: credits.length + siblingCredits.length + implicitCredits.length,
20150
20661
  sibling_count: siblingCredits.length,
20151
20662
  totals_by_currency: totals.map((total) => creditCurrencyTotalsJson(total, "local")),
20152
20663
  dvms: snapshots.map((snapshot) => ({
20153
20664
  ...cachedDvmJson(snapshot, credits, headroomOf, identityOf(snapshot.endpoint)),
20154
- ...postureFields(postureOf(snapshot.endpoint)),
20665
+ ...postureFields(postureOf(snapshot)),
20155
20666
  ...fundingRailFields(fundingRailOf(snapshot.endpoint))
20156
20667
  })),
20157
20668
  dvm_count: snapshots.length,
@@ -20198,14 +20709,15 @@ function postureSentence(posture) {
20198
20709
  case "auto":
20199
20710
  return "credit is bought within the trust-tier caps without asking, and every purchase reports its amount, route and reason.";
20200
20711
  case "off":
20201
- return "no multi-job credit is opened, refilled, or drawn on; every job pays per-call.";
20712
+ return "no multi-job credit is opened or refilled, and spending held credit is switched off; every job pays per-call.";
20202
20713
  case "suggest":
20203
20714
  return "nothing is ever bought automatically; where a credit would have helped, the job output says so and names how to fund it.";
20204
20715
  }
20205
20716
  }
20206
20717
  function humanPostureLine(effective) {
20207
20718
  const provenance = effective.source === "global" ? "set in config" : "the default";
20208
- return `Automatic credit purchases: ${effective.posture} (${provenance}) \u2014 ${postureSentence(effective.posture)}`;
20719
+ const subject = effective.posture === "off" ? "Credit purchases and spending" : "Automatic credit purchases";
20720
+ return `${subject}: ${effective.posture} (${provenance}) \u2014 ${postureSentence(effective.posture)}`;
20209
20721
  }
20210
20722
  function postureAdoptionSentence(posture) {
20211
20723
  switch (posture) {
@@ -20244,8 +20756,9 @@ function fundingRailFields(effective) {
20244
20756
  funding_rail_source: effective.source
20245
20757
  };
20246
20758
  }
20247
- function storedCreditJson(c, headroom) {
20759
+ function storedCreditJson(c, headroom, postureOff) {
20248
20760
  const channelId = storedCreditChannelId(c);
20761
+ const eligible = c.selectionCleared !== true && c.status === "active" && !c.reconciliationPending;
20249
20762
  return {
20250
20763
  endpoint: c.endpoint,
20251
20764
  dvm: dvmLabelFromEndpoint(c.endpoint),
@@ -20259,7 +20772,8 @@ function storedCreditJson(c, headroom) {
20259
20772
  ...channelId ? { channel_id: channelId } : {},
20260
20773
  ...c.reconciliationPending ? { reconciliation_pending: true } : {},
20261
20774
  tracked: c.selectionCleared !== true,
20262
- drawable: c.selectionCleared !== true && c.status === "active" && !c.reconciliationPending,
20775
+ drawable: eligible && !postureOff,
20776
+ ...eligible && postureOff ? { draw_blocked_reason: "posture_off" } : {},
20263
20777
  ...c.siblingCredits ? { sibling_credits: c.siblingCredits.map((sibling) => siblingCreditJson(c, sibling)) } : {},
20264
20778
  ...c.provisional ? { provisional: true } : {},
20265
20779
  ...c.pendingDrains?.length ? { pending_drains: c.pendingDrains.map(pendingDrainJson) } : {},
@@ -20275,7 +20789,7 @@ function storedCreditJson(c, headroom) {
20275
20789
  }
20276
20790
  } : {},
20277
20791
  headroom: headroomJson(headroom),
20278
- display: humanCreditRow(c)
20792
+ display: humanCreditRow(c, postureOff)
20279
20793
  };
20280
20794
  }
20281
20795
  function storedCreditChannelId(credit) {
@@ -20309,13 +20823,14 @@ function siblingCreditJson(record2, sibling) {
20309
20823
  ...sibling.drainable ? { hint: `Reclaim it with this command: ${command}` } : {}
20310
20824
  };
20311
20825
  }
20312
- function localCreditCurrencyTotals(credits, implicitCredits = []) {
20826
+ function localCreditCurrencyTotals(credits, implicitCredits, postureOff) {
20313
20827
  const totals = /* @__PURE__ */ new Map();
20314
20828
  for (const credit of credits) {
20315
20829
  const tracked = currencyTotal(totals, credit.currency);
20316
20830
  tracked.trackedCount += 1;
20317
20831
  if (credit.status === "active" && !credit.reconciliationPending) {
20318
- tracked.drawableMicro += Math.max(credit.remainingMicro, 0);
20832
+ if (postureOff(credit)) tracked.postureBlockedMicro += Math.max(credit.remainingMicro, 0);
20833
+ else tracked.drawableMicro += Math.max(credit.remainingMicro, 0);
20319
20834
  }
20320
20835
  for (const sibling of credit.siblingCredits ?? []) {
20321
20836
  const siblingTotal = currencyTotal(totals, sibling.currency);
@@ -20328,7 +20843,10 @@ function localCreditCurrencyTotals(credits, implicitCredits = []) {
20328
20843
  for (const credit of implicitCredits) {
20329
20844
  const total = currencyTotal(totals, credit.currency);
20330
20845
  total.trackedCount += 1;
20331
- if (credit.status === "active") total.drawableMicro += Math.max(credit.remainingMicro, 0);
20846
+ if (credit.status === "active") {
20847
+ if (postureOff(credit)) total.postureBlockedMicro += Math.max(credit.remainingMicro, 0);
20848
+ else total.drawableMicro += Math.max(credit.remainingMicro, 0);
20849
+ }
20332
20850
  }
20333
20851
  return sortedCurrencyTotals(totals);
20334
20852
  }
@@ -20495,7 +21013,7 @@ function pendingFundingsDisplay(pending4) {
20495
21013
  function drainReceiptCount(c) {
20496
21014
  return (c.drainEvidence ?? []).reduce((sum, e) => sum + e.receipts.length, 0);
20497
21015
  }
20498
- function humanCreditRow(c) {
21016
+ function humanCreditRow(c, postureOff) {
20499
21017
  const label = dvmLabelFromEndpoint(c.endpoint).padEnd(12);
20500
21018
  const amount = formatFiat(
20501
21019
  Math.max(c.status === "unbacked" ? c.balanceMicro : c.remainingMicro, 0) / 1e6,
@@ -20505,6 +21023,7 @@ function humanCreditRow(c) {
20505
21023
  const stranded = others.filter((d) => d.creditId !== void 0).length;
20506
21024
  const unattributed = others.length - stranded;
20507
21025
  const flags = [
21026
+ postureOff && c.status === "active" && !c.reconciliationPending ? "held but spending switched off by credit posture; balance remains reclaimable" : void 0,
20508
21027
  c.status !== "active" ? c.status : void 0,
20509
21028
  c.reconciliationPending ? "backing reconciliation pending" : void 0,
20510
21029
  c.provisional ? "syncing" : void 0,
@@ -20517,10 +21036,10 @@ function humanCreditRow(c) {
20517
21036
  const expiry = c.expiryMs > 0 ? ` \xB7 expires ${new Date(c.expiryMs).toISOString().slice(0, 10)}` : "";
20518
21037
  return `${label} ${amount}${expiry}${flags ? ` \xB7 ${flags}` : ""}`;
20519
21038
  }
20520
- function humanImplicitCreditRows(credits) {
21039
+ function humanImplicitCreditRows(credits, postureOff) {
20521
21040
  const groups = /* @__PURE__ */ new Map();
20522
21041
  for (const credit of credits) {
20523
- const key = `${credit.endpoint}\0${credit.currency}\0${credit.status}`;
21042
+ const key = `${credit.endpoint}\0${credit.currency}\0${credit.status}\0${postureOff(credit)}`;
20524
21043
  const group = groups.get(key) ?? [];
20525
21044
  group.push(credit);
20526
21045
  groups.set(key, group);
@@ -20536,6 +21055,9 @@ function humanImplicitCreditRows(credits) {
20536
21055
  if (first.status === "lost") {
20537
21056
  return `${label} ${amount} across ${count} \xB7 lost; no drain path is available`;
20538
21057
  }
21058
+ if (postureOff(first)) {
21059
+ return `${label} ${amount} across ${count} \xB7 held but spending switched off by credit posture; no drain path is available`;
21060
+ }
20539
21061
  const expiry = Math.min(...group.map((credit) => credit.expiryMs));
20540
21062
  return `${label} ${amount} across ${count} \xB7 next request uses the earliest expiry first \xB7 expires by ${new Date(expiry).toISOString().slice(0, 10)}`;
20541
21063
  });
@@ -21521,18 +22043,85 @@ function findPackageRoot(start) {
21521
22043
  }
21522
22044
 
21523
22045
  // src/lib/caller-state.ts
21524
- import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
21525
- import { basename, join as join4 } from "path";
22046
+ import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
22047
+ import { basename, join as join5 } from "path";
22048
+
22049
+ // src/lib/request-refusal-store.ts
22050
+ import {
22051
+ closeSync as closeSync2,
22052
+ existsSync as existsSync4,
22053
+ fsyncSync as fsyncSync2,
22054
+ openSync as openSync2,
22055
+ readFileSync as readFileSync4,
22056
+ renameSync as renameSync2,
22057
+ rmSync,
22058
+ writeFileSync as writeFileSync2
22059
+ } from "fs";
22060
+ import { join as join4 } from "path";
22061
+ var REQUEST_REFUSALS_DIR = join4(CONFIG_DIR, "request-refusals");
22062
+ var SAFE_TOKEN = /^[a-z0-9_.:-]{1,64}$/;
22063
+ function requestIntentMayExist(requestId) {
22064
+ return existsSync4(join4(REQUEST_INTENTS_DIR, requestId));
22065
+ }
22066
+ function recordRequestRefusal(requestId, refusal) {
22067
+ if (!isPublicRequestId(requestId) || requestIntentMayExist(requestId)) return false;
22068
+ const record2 = {
22069
+ v: 1,
22070
+ requestId,
22071
+ code: SAFE_TOKEN.test(refusal.code) ? refusal.code : "refused",
22072
+ ...typeof refusal.reason === "string" && SAFE_TOKEN.test(refusal.reason) ? { reason: refusal.reason } : {},
22073
+ refusedAt: Date.now()
22074
+ };
22075
+ try {
22076
+ ensureConfigSubdir(REQUEST_REFUSALS_DIR);
22077
+ const target = refusalPath(requestId);
22078
+ const temp = `${target}.${String(process.pid)}.tmp`;
22079
+ const fd = openSync2(temp, "w", 384);
22080
+ try {
22081
+ writeFileSync2(fd, JSON.stringify(record2, null, 2) + "\n");
22082
+ fsyncSync2(fd);
22083
+ } finally {
22084
+ closeSync2(fd);
22085
+ }
22086
+ renameSync2(temp, target);
22087
+ } catch {
22088
+ }
22089
+ return true;
22090
+ }
22091
+ function clearRequestRefusal(requestId) {
22092
+ if (!isPublicRequestId(requestId)) return;
22093
+ try {
22094
+ rmSync(refusalPath(requestId), { force: true });
22095
+ } catch {
22096
+ }
22097
+ }
22098
+ function loadRequestRefusal(requestId) {
22099
+ if (!isPublicRequestId(requestId)) return null;
22100
+ try {
22101
+ const parsed = JSON.parse(readFileSync4(refusalPath(requestId), "utf8"));
22102
+ if (parsed.v !== 1 || parsed.requestId !== requestId || typeof parsed.code !== "string" || typeof parsed.refusedAt !== "number" || parsed.reason !== void 0 && typeof parsed.reason !== "string") {
22103
+ return null;
22104
+ }
22105
+ return parsed;
22106
+ } catch {
22107
+ return null;
22108
+ }
22109
+ }
22110
+ function refusalPath(requestId) {
22111
+ return join4(REQUEST_REFUSALS_DIR, `${requestId}.json`);
22112
+ }
22113
+
22114
+ // src/lib/caller-state.ts
21526
22115
  function detectSetupState() {
21527
22116
  return {
21528
22117
  existingState: {
21529
- jobs: existsSync4(JOBS_FILE),
21530
- messages: existsSync4(MESSAGES_DIR)
22118
+ jobs: existsSync5(JOBS_FILE),
22119
+ messages: existsSync5(MESSAGES_DIR)
21531
22120
  },
21532
22121
  missing: {
21533
- config: !existsSync4(CONFIG_FILE),
21534
- identity: !existsSync4(IDENTITIES_FILE),
21535
- wallet: !existsSync4(WALLET_FILE)
22122
+ config: !existsSync5(CONFIG_FILE),
22123
+ identity: !existsSync5(IDENTITIES_FILE),
22124
+ wallet: !existsSync5(WALLET_FILE)
21536
22125
  }
21537
22126
  };
21538
22127
  }
@@ -21627,6 +22216,13 @@ var FILE_SPECS = [
21627
22216
  secret: false,
21628
22217
  directory: true
21629
22218
  },
22219
+ {
22220
+ name: "request_refusals",
22221
+ path: REQUEST_REFUSALS_DIR,
22222
+ json: false,
22223
+ secret: false,
22224
+ directory: true
22225
+ },
21630
22226
  { name: "messages", path: MESSAGES_DIR, json: false, secret: false, directory: true },
21631
22227
  // Evidence of paid calls accepted without a settled job identity. Each file
21632
22228
  // is 0600 because a record can hold an anonymous job's access token, so
@@ -21655,17 +22251,17 @@ function findQuarantinedCreditStores() {
21655
22251
  } catch {
21656
22252
  return [];
21657
22253
  }
21658
- 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 }));
22254
+ 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 }));
21659
22255
  }
21660
22256
  function checkOne(spec) {
21661
- const exists = existsSync4(spec.path);
22257
+ const exists = existsSync5(spec.path);
21662
22258
  if (!exists) {
21663
22259
  return { name: spec.name, path: spec.path, exists: false };
21664
22260
  }
21665
22261
  const row = { name: spec.name, path: spec.path, exists: true };
21666
22262
  if (spec.json) {
21667
22263
  try {
21668
- JSON.parse(readFileSync4(spec.path, "utf-8"));
22264
+ JSON.parse(readFileSync5(spec.path, "utf-8"));
21669
22265
  row.parseable = true;
21670
22266
  } catch (err) {
21671
22267
  row.parseable = false;
@@ -21694,7 +22290,7 @@ function checkSecretDirectory(dir, row) {
21694
22290
  try {
21695
22291
  const offenders = [];
21696
22292
  for (const name of readdirSync2(dir)) {
21697
- const path = join4(dir, name);
22293
+ const path = join5(dir, name);
21698
22294
  const stat2 = statSync2(path);
21699
22295
  if (!stat2.isFile()) continue;
21700
22296
  const mode = stat2.mode & 511;
@@ -21715,9 +22311,9 @@ function octalMode(mode) {
21715
22311
  return "0" + mode.toString(8).padStart(3, "0");
21716
22312
  }
21717
22313
  function readBtcRateCacheAge(now = Date.now()) {
21718
- if (!existsSync4(BTC_RATE_FILE)) return null;
22314
+ if (!existsSync5(BTC_RATE_FILE)) return null;
21719
22315
  try {
21720
- const data = JSON.parse(readFileSync4(BTC_RATE_FILE, "utf-8"));
22316
+ const data = JSON.parse(readFileSync5(BTC_RATE_FILE, "utf-8"));
21721
22317
  if (typeof data.timestamp !== "number") return null;
21722
22318
  return { ageMs: now - data.timestamp };
21723
22319
  } catch {
@@ -21727,7 +22323,7 @@ function readBtcRateCacheAge(now = Date.now()) {
21727
22323
 
21728
22324
  // src/lib/mnemonic-backups.ts
21729
22325
  import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
21730
- import { basename as basename2, dirname as dirname3, join as join5 } from "path";
22326
+ import { basename as basename2, dirname as dirname3, join as join6 } from "path";
21731
22327
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
21732
22328
  const dir = dirname3(mnemonicFile);
21733
22329
  const prefix = `${basename2(mnemonicFile)}.`;
@@ -21739,7 +22335,7 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
21739
22335
  throw err;
21740
22336
  }
21741
22337
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
21742
- const path = join5(dir, name);
22338
+ const path = join6(dir, name);
21743
22339
  const stat2 = statSync3(path);
21744
22340
  if (!stat2.isFile()) return null;
21745
22341
  const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
@@ -21779,8 +22375,8 @@ function formatMnemonicBackupAge(ageMs2) {
21779
22375
  }
21780
22376
 
21781
22377
  // src/lib/wallet-agent/submissions-view.ts
21782
- function describePendingSubmissions(wallet, nowMs = Date.now()) {
21783
- const entries = wallet.pending_submissions.map((entry) => toView(entry, nowMs));
22378
+ function describePendingSubmissions(wallet, nowMs = Date.now(), reclaimUnsaved = reclaimIntentIds()) {
22379
+ const entries = wallet.pending_submissions.map((entry) => toView(entry, nowMs, reclaimUnsaved.has(entry.request_id)));
21784
22380
  return {
21785
22381
  entries,
21786
22382
  at_risk_sats: entries.filter((e) => e.at_risk).reduce((sum, e) => sum + e.amount_sats, 0),
@@ -21923,12 +22519,12 @@ function describeSubmissionEvidence(records) {
21923
22519
  };
21924
22520
  });
21925
22521
  }
21926
- function toView(entry, nowMs) {
22522
+ function toView(entry, nowMs, reclaimUnsaved) {
21927
22523
  const createdMs = Date.parse(entry.created_at);
21928
22524
  const ageMs2 = Number.isNaN(createdMs) ? Number.POSITIVE_INFINITY : nowMs - createdMs;
21929
22525
  const attempts = entry.attempts ?? 0;
21930
22526
  const reclaimAt = reclaimAtMs(entry);
21931
- const state = deriveState(entry, ageMs2, attempts, reclaimAt);
22527
+ const state = reclaimUnsaved ? "reclaim_failed" : deriveState(entry, ageMs2, attempts, reclaimAt);
21932
22528
  return {
21933
22529
  request_id: entry.request_id,
21934
22530
  endpoint: entry.endpoint,
@@ -21939,10 +22535,15 @@ function toView(entry, nowMs) {
21939
22535
  state,
21940
22536
  at_risk: state !== "awaiting_swap",
21941
22537
  reclaim_at: reclaimAt === null ? null : new Date(reclaimAt).toISOString(),
21942
- reclaim_error: state === "reclaim_failed" || state === "unreclaimable" ? entry.reclaim_error ?? null : null,
22538
+ reclaim_error: reclaimUnsaved ? RECLAIM_UNSAVED_REASON : state === "reclaim_failed" || state === "unreclaimable" ? entry.reclaim_error ?? null : null,
21943
22539
  ...entry.accepted_unresolved ? { accepted_unresolved: entry.accepted_unresolved } : {},
21944
22540
  ...publicRequestIdOf(entry) ? { public_request_id: publicRequestIdOf(entry) } : {},
21945
- display: describe4(entry, state, reclaimAt, nowMs)
22541
+ display: describe4(
22542
+ reclaimUnsaved ? { ...entry, reclaim_error: RECLAIM_UNSAVED_REASON } : entry,
22543
+ state,
22544
+ reclaimAt,
22545
+ nowMs
22546
+ )
21946
22547
  };
21947
22548
  }
21948
22549
  function locateAdvice(entry, publicRequestId = publicRequestIdOf(entry)) {
@@ -23630,11 +24231,11 @@ async function favRm(name, opts) {
23630
24231
  }
23631
24232
 
23632
24233
  // src/lib/byte-source.ts
23633
- import { readFileSync as readFileSync5 } from "fs";
24234
+ import { readFileSync as readFileSync6 } from "fs";
23634
24235
  import { resolve as resolve2 } from "path";
23635
24236
  var STDIN_TIMEOUT_MS2 = 1e4;
23636
24237
  function readFileText(path) {
23637
- return readFileSync5(resolve2(path), "utf-8");
24238
+ return readFileSync6(resolve2(path), "utf-8");
23638
24239
  }
23639
24240
  var StdinTimeoutError = class extends Error {
23640
24241
  constructor(timeoutMs) {
@@ -23798,7 +24399,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
23798
24399
  }
23799
24400
 
23800
24401
  // src/lib/feedback-nudges.ts
23801
- import { existsSync as existsSync5, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
24402
+ import { existsSync as existsSync6, readFileSync as readFileSync7, renameSync as renameSync3, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
23802
24403
 
23803
24404
  // src/lib/feedback-notice.ts
23804
24405
  function buildFeedbackNudge(args) {
@@ -23850,10 +24451,10 @@ function effectiveFeedbackPosture(config2) {
23850
24451
  return { posture: DEFAULT_FEEDBACK_POSTURE, source: "default" };
23851
24452
  }
23852
24453
  function loadFeedbackNudgeState() {
23853
- if (!existsSync5(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
24454
+ if (!existsSync6(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
23854
24455
  try {
23855
24456
  const parsed = JSON.parse(
23856
- readFileSync6(FEEDBACK_NUDGES_FILE, "utf-8")
24457
+ readFileSync7(FEEDBACK_NUDGES_FILE, "utf-8")
23857
24458
  );
23858
24459
  return {
23859
24460
  ...typeof parsed.introShownAt === "string" ? { introShownAt: parsed.introShownAt } : {},
@@ -23942,9 +24543,9 @@ function coercePerDvm(perDvm) {
23942
24543
  function saveState(state) {
23943
24544
  ensureConfigDir();
23944
24545
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
23945
- writeFileSync2(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
24546
+ writeFileSync3(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
23946
24547
  try {
23947
- renameSync2(tmp, FEEDBACK_NUDGES_FILE);
24548
+ renameSync3(tmp, FEEDBACK_NUDGES_FILE);
23948
24549
  } catch (err) {
23949
24550
  try {
23950
24551
  unlinkSync(tmp);
@@ -23956,9 +24557,9 @@ function saveState(state) {
23956
24557
  var nudgedThisInvocation = false;
23957
24558
 
23958
24559
  // src/lib/platform.ts
23959
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
24560
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
23960
24561
  import { homedir as homedir2 } from "os";
23961
- import { join as join6 } from "path";
24562
+ import { join as join7 } from "path";
23962
24563
  function getPlatformUrl() {
23963
24564
  return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
23964
24565
  }
@@ -24527,16 +25128,16 @@ function finalizeProgressLine() {
24527
25128
  import { randomBytes as randomBytes2 } from "crypto";
24528
25129
  import {
24529
25130
  chmodSync,
24530
- closeSync as closeSync2,
25131
+ closeSync as closeSync3,
24531
25132
  mkdtempSync,
24532
- openSync as openSync2,
25133
+ openSync as openSync3,
24533
25134
  readdirSync as readdirSync4,
24534
25135
  rmdirSync,
24535
25136
  unlinkSync as unlinkSync2,
24536
- writeFileSync as writeFileSync4
25137
+ writeFileSync as writeFileSync5
24537
25138
  } from "fs";
24538
25139
  import { tmpdir } from "os";
24539
- import { join as join7 } from "path";
25140
+ import { join as join8 } from "path";
24540
25141
 
24541
25142
  // src/lib/mime-ext.ts
24542
25143
  var MIME_TO_EXT = {
@@ -24592,11 +25193,11 @@ var ArtifactSaveSession = class {
24592
25193
  let created = false;
24593
25194
  try {
24594
25195
  const directory = this.ensureDirectory();
24595
- path = join7(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
24596
- fd = openSync2(path, "wx", FILE_MODE);
25196
+ path = join8(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
25197
+ fd = openSync3(path, "wx", FILE_MODE);
24597
25198
  created = true;
24598
- writeFileSync4(fd, buf);
24599
- closeSync2(fd);
25199
+ writeFileSync5(fd, buf);
25200
+ closeSync3(fd);
24600
25201
  fd = void 0;
24601
25202
  chmodSync(path, FILE_MODE);
24602
25203
  this.successfulWrites += 1;
@@ -24604,7 +25205,7 @@ var ArtifactSaveSession = class {
24604
25205
  } catch (err) {
24605
25206
  if (fd !== void 0) {
24606
25207
  try {
24607
- closeSync2(fd);
25208
+ closeSync3(fd);
24608
25209
  } catch {
24609
25210
  }
24610
25211
  }
@@ -24621,7 +25222,7 @@ var ArtifactSaveSession = class {
24621
25222
  }
24622
25223
  ensureDirectory() {
24623
25224
  if (this.directory) return this.directory;
24624
- const directory = mkdtempSync(join7(tmpdir(), "dvm-artifacts-"));
25225
+ const directory = mkdtempSync(join8(tmpdir(), "dvm-artifacts-"));
24625
25226
  try {
24626
25227
  chmodSync(directory, DIRECTORY_MODE);
24627
25228
  } catch (err) {
@@ -24781,6 +25382,19 @@ function printNextActionHuman(action, options = {}) {
24781
25382
  if (line) info(line);
24782
25383
  }
24783
25384
 
25385
+ // src/lib/read-next-action.ts
25386
+ function readNextAction(jobId, messages2, options = {}) {
25387
+ const answered = options.ignoreLocalState ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(jobId);
25388
+ const pending4 = messages2.filter((message2) => !answered.has(message2.seq));
25389
+ const action = computeNextAction(jobId, pending4, void 0, options.ignoreLocalState ? void 0 : options.context);
25390
+ if (action?.type !== "pay" || options.ignoreLocalState) return action;
25391
+ const request2 = pendingPaymentRequest(pending4);
25392
+ const held = loadJob(jobId);
25393
+ if (request2 && held && (held.inFlightPaymentRequestSeqs?.includes(request2.seq) || held.unconfirmedPaymentSubmissions?.[request2.seq] || held.askPaymentBlocks?.[request2.seq]))
25394
+ return { ...action, hint: paymentInFlightHint(jobId, held, request2.seq) };
25395
+ return action;
25396
+ }
25397
+
24784
25398
  // src/lib/wait-for-job.ts
24785
25399
  async function waitForJob(opts, durationMs, now = Date.now) {
24786
25400
  const deadline = now() + durationMs;
@@ -24835,6 +25449,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
24835
25449
  for (const message2 of tail) onMessage(message2);
24836
25450
  if (opts.persistLocalState !== false) {
24837
25451
  messageAppendSession?.append(tail);
25452
+ await settleRecordedPayments(opts.jobId);
24838
25453
  result.refunds.push(...await claimInboundPayments(opts.jobId, tail));
24839
25454
  }
24840
25455
  result.nextAction = withRefundNextAction(opts.jobId, null, result.refunds);
@@ -24853,7 +25468,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
24853
25468
  assertOwned();
24854
25469
  for (const seq of loadJob(opts.jobId)?.inFlightPaymentRequestSeqs ?? []) {
24855
25470
  try {
24856
- reconcilePaymentRequestHistory(opts.jobId, seq, messages2, snapshot.status, now);
25471
+ await reconcilePaymentRequestHistory(opts.jobId, seq, messages2, snapshot.status, now);
24857
25472
  } catch (error) {
24858
25473
  if (!(error instanceof DvmError) || !["payment_settling", "payment_request_not_pending"].includes(error.code)) throw error;
24859
25474
  if (!loadJob(opts.jobId)?.inFlightPaymentRequestSeqs?.includes(seq)) continue;
@@ -24873,6 +25488,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
24873
25488
  }
24874
25489
  if (!history) break;
24875
25490
  messageAppendSession?.append(history);
25491
+ if (opts.persistLocalState !== false) await settleRecordedPayments(opts.jobId);
24876
25492
  const answered = opts.persistLocalState === false ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(opts.jobId);
24877
25493
  for (const seq of answeredYieldSeqs(history)) answered.add(seq);
24878
25494
  const pending4 = history.findLast((msg) => msg.from === "provider" && ["prompt", "payment-request", "working", "complete", "cancel"].includes(msg.type) && !answered.has(msg.seq));
@@ -24940,12 +25556,7 @@ async function messagesWithAccess(jobId, opts, access) {
24940
25556
  const { stored, ref, jobToken } = access;
24941
25557
  const json3 = (data) => providerJobJson(data, !!stored);
24942
25558
  function actionFromMessages(batch) {
24943
- const answered = access.endpointOverridden ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(jobId);
24944
- const action = computeNextAction(jobId, batch.filter((message2) => !answered.has(message2.seq)), void 0, access.endpointOverridden ? void 0 : stored ?? void 0);
24945
- const request2 = batch.findLast((message2) => message2.type === "payment-request");
24946
- if (action?.type === "pay" && request2 && !access.endpointOverridden && stored?.inFlightPaymentRequestSeqs?.includes(request2.seq))
24947
- return { ...action, hint: paymentInFlightHint(jobId) };
24948
- return action;
25559
+ return readNextAction(jobId, batch, { ignoreLocalState: access.endpointOverridden, context: stored ?? void 0 });
24949
25560
  }
24950
25561
  async function resolveNextAction2(action, messages2, observedStatus) {
24951
25562
  if (action?.type === "refund") return action;
@@ -24985,7 +25596,10 @@ async function messagesWithAccess(jobId, opts, access) {
24985
25596
  }
24986
25597
  throw err;
24987
25598
  }
24988
- if (!access.endpointOverridden) appendMessages(jobId, msgs);
25599
+ if (!access.endpointOverridden) {
25600
+ appendMessages(jobId, msgs);
25601
+ await settleRecordedPayments(jobId);
25602
+ }
24989
25603
  const newCursor = maxSeq(msgs, after);
24990
25604
  const providerStatus2 = await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken });
24991
25605
  if (!access.endpointOverridden) {
@@ -26418,8 +27032,9 @@ async function refetchAnchor(endpointOrAlias) {
26418
27032
  function deliveredFromMessages(jobId, receipt) {
26419
27033
  const messages2 = loadMessages(jobId);
26420
27034
  if (messages2.length === 0) return void 0;
26421
- if (!messages2.some((m) => isCompleteMessage(m) || isCancelMessage(m))) return void 0;
26422
- const completion = loadJob(jobId)?.completion;
27035
+ const job = loadJob(jobId);
27036
+ if (!messages2.some((m) => isCompleteMessage(m) || isCancelMessage(m) || m.type === "decline" && job?.callerDeclined === true && isTerminalJobStatus(job.status))) return void 0;
27037
+ const completion = job?.completion;
26423
27038
  if (completion?.hasArtifacts === void 0) return void 0;
26424
27039
  const artifacts = messages2.filter(isArtifactMessage);
26425
27040
  if (artifacts.length !== (completion.artifactCount ?? 0)) return void 0;
@@ -26880,9 +27495,23 @@ function resolveBudget(current, minimumMsats) {
26880
27495
 
26881
27496
  // src/commands/request.ts
26882
27497
  async function request(opts) {
26883
- return withOutputWarnings(() => requestWithWarnings(opts));
27498
+ const stage = { intentReached: false };
27499
+ return withOutputWarnings(async () => {
27500
+ try {
27501
+ await requestWithWarnings(opts, stage);
27502
+ } catch (error) {
27503
+ throw stage.intentReached ? error : markRefusedBeforeSend(opts.requestId, error);
27504
+ }
27505
+ });
27506
+ }
27507
+ function markRefusedBeforeSend(requestId, error) {
27508
+ if (!requestId || !(error instanceof DvmError)) return error;
27509
+ const reason = error.data?.reason;
27510
+ if (!recordRequestRefusal(requestId, { code: error.code, reason })) return error;
27511
+ error.data = { ...error.data, submitted: false };
27512
+ return error;
26884
27513
  }
26885
- async function requestWithWarnings(opts) {
27514
+ async function requestWithWarnings(opts, stage) {
26886
27515
  const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
26887
27516
  const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 3e4;
26888
27517
  const requestedMaxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
@@ -27135,7 +27764,7 @@ async function requestWithWarnings(opts) {
27135
27764
  throw new DvmError(
27136
27765
  "credit_only_unavailable",
27137
27766
  `Prepaid credit ${opts.creditOnly} is not drawable under the current caller state.`,
27138
- "Reconcile that exact credit with 'dvm credit balance <dvm> --credit-id <id>'; this request did not fall back to a wallet payment.",
27767
+ 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.",
27139
27768
  {
27140
27769
  credit_id: opts.creditOnly,
27141
27770
  ...probePlan.mode === "none" && probePlan.drawSkipped ? { reason: probePlan.drawSkipped.reason } : {}
@@ -27174,6 +27803,7 @@ async function requestWithWarnings(opts) {
27174
27803
  }
27175
27804
  let envelope = { ...envelopeBase, data };
27176
27805
  let jobRequestId = opts.requestId ?? drawRequestId;
27806
+ stage.intentReached = true;
27177
27807
  if (jobRequestId) {
27178
27808
  persistRequestIntent({
27179
27809
  requestId: jobRequestId,
@@ -28505,6 +29135,7 @@ function persistRequestIntent(args) {
28505
29135
  { request_id: requestId, status: "unknown" }
28506
29136
  );
28507
29137
  }
29138
+ clearRequestRefusal(requestId);
28508
29139
  }
28509
29140
  function submitCanCarryGeneratedRequestId(args) {
28510
29141
  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;
@@ -28556,7 +29187,21 @@ function requestIdOutputFields(requestId) {
28556
29187
  function normalizedLocalCorrelationId(opts) {
28557
29188
  return opts.localCorrelationId === void 0 ? void 0 : normalizeLocalCorrelationId(opts.localCorrelationId);
28558
29189
  }
29190
+ var PREACCEPT_REFUSAL_CODES = /* @__PURE__ */ new Set([
29191
+ "invalid_input",
29192
+ "budget_exceeded",
29193
+ "cashu_fee_cap_exceeded",
29194
+ "insufficient_balance",
29195
+ "no_eligible_mint",
29196
+ "mint_not_allowed",
29197
+ "mint_pin_unsatisfiable",
29198
+ "rail_unsatisfiable",
29199
+ "tempo_network_mismatch"
29200
+ ]);
28559
29201
  function requestOutcomeUnknown(requestId, cause) {
29202
+ 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") {
29203
+ return cause;
29204
+ }
28560
29205
  if (cause instanceof DvmError && typeof cause.data?.job_id === "string" && loadJob(cause.data.job_id)?.requestId === requestId) {
28561
29206
  return cause;
28562
29207
  }
@@ -29631,11 +30276,9 @@ async function requestResult(requestId, opts = {}) {
29631
30276
  }
29632
30277
  const intent = loadRequestIntent(requestId);
29633
30278
  if (!intent) {
29634
- throw new DvmError(
29635
- "request_not_found",
29636
- `No local intent exists for request ${requestId}.`,
29637
- "The outcome is unknown. Do not submit or pay for a replacement; restore the original caller state and retry.",
29638
- { request_id: requestId, status: "unknown" }
30279
+ throw requestNotFound(
30280
+ requestId,
30281
+ "The outcome is unknown. Do not submit or pay for a replacement; restore the original caller state and retry."
29639
30282
  );
29640
30283
  }
29641
30284
  const signer = findSigningIdentityByPubkey(intent.callerPubkey);
@@ -29785,6 +30428,30 @@ async function requestResult(requestId, opts = {}) {
29785
30428
  }
29786
30429
  });
29787
30430
  }
30431
+ function requestNotFound(requestId, unknownHint) {
30432
+ const refusal = loadRequestRefusal(requestId);
30433
+ if (!refusal) {
30434
+ return new DvmError(
30435
+ "request_not_found",
30436
+ `No local intent exists for request ${requestId}.`,
30437
+ unknownHint,
30438
+ { request_id: requestId, status: "unknown" }
30439
+ );
30440
+ }
30441
+ return new DvmError(
30442
+ "request_not_submitted",
30443
+ `Request ${requestId} was refused locally before it was sent.`,
30444
+ "No job or payment was sent for this request id. Retrying the same approved request is safe.",
30445
+ {
30446
+ request_id: requestId,
30447
+ status: "not_submitted",
30448
+ submitted: false,
30449
+ refusal_code: refusal.code,
30450
+ ...refusal.reason ? { refusal_reason: refusal.reason } : {},
30451
+ refused_at: new Date(refusal.refusedAt).toISOString()
30452
+ }
30453
+ );
30454
+ }
29788
30455
  function signedIntentEnvelope(intent, privkey, route) {
29789
30456
  const body = intent.body;
29790
30457
  const data = body.data;
@@ -29846,11 +30513,9 @@ async function resumeRequest(requestId, opts) {
29846
30513
  }
29847
30514
  const intent = loadRequestIntent(requestId);
29848
30515
  if (!intent) {
29849
- throw new DvmError(
29850
- "request_not_found",
29851
- `No local intent exists for request ${requestId}.`,
29852
- "The outcome is unknown. Restore the original caller state; never submit or pay for a replacement.",
29853
- { request_id: requestId, status: "unknown" }
30516
+ throw requestNotFound(
30517
+ requestId,
30518
+ "The outcome is unknown. Restore the original caller state; never submit or pay for a replacement."
29854
30519
  );
29855
30520
  }
29856
30521
  const signer = findSigningIdentityByPubkey(intent.callerPubkey);
@@ -30187,14 +30852,16 @@ async function status(jobId, opts) {
30187
30852
  }
30188
30853
  async function statusWithAccess(jobId, opts, access) {
30189
30854
  const { stored, ref, jobToken } = access;
30190
- if (stored && !access.overridden && isTerminalJobStatus(stored.status) && stored.completion && !opts.messages) {
30855
+ if (stored && !access.overridden && isTerminalJobStatus(stored.status) && (stored.completion || stored.status !== "completed") && !opts.messages) {
30191
30856
  let receipt2 = replayStoredReceipt(stored);
30192
30857
  let terminalStatus = stored.status;
30193
- let completion2 = stored.completion;
30858
+ let completion2 = stored.completion ?? {};
30859
+ let content;
30194
30860
  const transport2 = createDvmTransport();
30195
30861
  if (stored.receiptsSupported && receipt2.status === "absent") {
30196
30862
  const fetched = await fetchMissingJobReceipt(jobId, transport2, ref);
30197
30863
  if (fetched.status && isTerminalJobStatus(fetched.status)) {
30864
+ content = fetched;
30198
30865
  const saved = stored.status === fetched.status ? completion2 : void 0;
30199
30866
  terminalStatus = fetched.status;
30200
30867
  completion2 = fetched.content_available === false && saved ? saved : { ...saved, ...completionSnapshot(fetched) };
@@ -30207,10 +30874,21 @@ async function statusWithAccess(jobId, opts, access) {
30207
30874
  receipt2 = captureTransportReceipt(jobId, fetched);
30208
30875
  }
30209
30876
  }
30877
+ if (terminalStatus !== "completed" && completion2.hasArtifacts === void 0 && content?.content_available !== false) {
30878
+ completion2 = await readTerminalCompletion({
30879
+ jobId,
30880
+ status: { ...completion2, ...content, status: terminalStatus },
30881
+ transport: transport2,
30882
+ ref,
30883
+ jobToken
30884
+ });
30885
+ markJobTerminal(jobId, terminalStatus, completion2);
30886
+ }
30210
30887
  await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
30211
30888
  transport2.close();
30212
30889
  renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
30213
- receipt: receipt2
30890
+ receipt: receipt2,
30891
+ content
30214
30892
  });
30215
30893
  return;
30216
30894
  }
@@ -30224,15 +30902,19 @@ async function statusWithAccess(jobId, opts, access) {
30224
30902
  if (opts.messages) {
30225
30903
  const after = access.endpointOverridden ? 0 : stored?.messageCursor ?? 0;
30226
30904
  msgs = await transport.getMessages(jobId, after, ref, { timeoutMs: timeout, jobToken });
30227
- if (!access.endpointOverridden) appendMessages(jobId, msgs);
30905
+ if (!access.endpointOverridden) {
30906
+ appendMessages(jobId, msgs);
30907
+ await settleRecordedPayments(jobId);
30908
+ }
30228
30909
  newCursor = maxSeq(msgs, after);
30229
30910
  }
30230
30911
  const nextAction = await resolveNextAction(jobId, result.status, msgs, transport, ref, {
30231
30912
  timeoutMs: timeout,
30232
30913
  jobToken,
30233
- context: access.endpointOverridden ? void 0 : stored ?? void 0
30914
+ context: access.endpointOverridden ? void 0 : stored ?? void 0,
30915
+ ignoreLocalState: access.endpointOverridden
30234
30916
  });
30235
- const completion = completionSnapshot(result);
30917
+ let completion = completionSnapshot(result);
30236
30918
  const reasonUnavailable = completion.message === void 0 || result.content_available === false && completion.message === "";
30237
30919
  if (reasonUnavailable && (result.status === "failed" || result.status === "cancelled")) {
30238
30920
  const savedReason = !access.endpointOverridden && stored?.status === result.status ? stored.completion?.message : void 0;
@@ -30240,6 +30922,17 @@ async function statusWithAccess(jobId, opts, access) {
30240
30922
  const reason = savedReason ?? (terminal?.type === "cancel" || terminal?.type === "decline" ? terminal.content.reason : void 0);
30241
30923
  if (reason !== void 0) completion.message = reason;
30242
30924
  }
30925
+ if (isTerminalJobStatus(result.status)) {
30926
+ completion = await readTerminalCompletion({
30927
+ jobId,
30928
+ status: { ...result, ...completion },
30929
+ transport,
30930
+ ref,
30931
+ jobToken,
30932
+ timeoutMs: timeout,
30933
+ saved: !access.endpointOverridden && stored?.status === result.status ? stored.completion : void 0
30934
+ });
30935
+ }
30243
30936
  let receipt;
30244
30937
  let currency;
30245
30938
  if (isTerminalJobStatus(result.status)) {
@@ -30295,7 +30988,10 @@ function transientReceiptCapture(jobId, response, endpoint, currency) {
30295
30988
  }
30296
30989
  function renderStatus(jobId, stored, jobStatus, completion, source, nextAction, opts, fetched) {
30297
30990
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
30298
- const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, opts.human);
30991
+ const artifacts = terminalCompletionOutput(jobId, jobStatus, completion, {
30992
+ human: opts.human,
30993
+ contentAvailable: fetched?.content?.content_available
30994
+ });
30299
30995
  const msgs = fetched?.msgs ?? [];
30300
30996
  const receipt = fetched?.receipt;
30301
30997
  const content = jobContentFields(jobId, fetched?.content, opts.human);
@@ -30317,7 +31013,7 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
30317
31013
  info(`Status: ${jobStatus}${identifier ? ` [${identifier}]` : ""}`);
30318
31014
  if (completion.message) info(` ${completion.message}`);
30319
31015
  }
30320
- if (jobStatus === "completed" && hint) info(`\u{1F4CE} ${hint}`);
31016
+ if (artifacts.hint) info(`\u{1F4CE} ${artifacts.hint}`);
30321
31017
  info(String(content.content_hint));
30322
31018
  if (msgs.length > 0) {
30323
31019
  info(`
@@ -30347,7 +31043,8 @@ ${msgs.length} new message(s):`);
30347
31043
  ],
30348
31044
  ...content,
30349
31045
  ...completion.summary ? { summary: completion.summary } : {},
30350
- ...jobStatus === "completed" ? buildCompletionHintFields(jobId, completion) : {},
31046
+ ...artifacts.fields,
31047
+ ...artifacts.display ? { display: artifacts.display } : {},
30351
31048
  ...completion.message ? { message: completion.message } : {},
30352
31049
  // terminal responses only. On a still-running job "absent" would
30353
31050
  // read as "this DVM doesn't issue receipts" rather than "not yet".
@@ -30371,10 +31068,10 @@ ${msgs.length} new message(s):`);
30371
31068
  async function resolveNextAction(jobId, status2, fetched, transport, ref, opts) {
30372
31069
  if (isTerminalJobStatus(status2)) return null;
30373
31070
  if (status2 === "awaiting-input") {
30374
- const fromBatch = computeNextAction(jobId, fetched, void 0, opts.context);
31071
+ const fromBatch = readNextAction(jobId, fetched, opts);
30375
31072
  if (fromBatch) return fromBatch;
30376
31073
  const history = await transport.getMessages(jobId, 0, ref, opts);
30377
- return computeNextAction(jobId, history, void 0, opts.context) ?? pollNextAction(jobId);
31074
+ return readNextAction(jobId, history, opts) ?? pollNextAction(jobId);
30378
31075
  }
30379
31076
  return pollNextAction(jobId);
30380
31077
  }
@@ -32442,7 +33139,7 @@ function mnemonicValidationError(result) {
32442
33139
  var import_qrcode = __toESM(require_lib(), 1);
32443
33140
  import { randomBytes as randomBytes3 } from "crypto";
32444
33141
  import { tmpdir as tmpdir2 } from "os";
32445
- import { join as join8 } from "path";
33142
+ import { join as join9 } from "path";
32446
33143
  async function renderQrTerminal(payload) {
32447
33144
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
32448
33145
  }
@@ -32455,7 +33152,7 @@ async function renderQrPng(payload, outPath) {
32455
33152
  });
32456
33153
  }
32457
33154
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
32458
- return join8(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
33155
+ return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
32459
33156
  }
32460
33157
 
32461
33158
  // src/lib/funding-handoff.ts
@@ -36913,14 +37610,14 @@ function hexToBytes2(hex2) {
36913
37610
  var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
36914
37611
  import {
36915
37612
  chmodSync as chmodSync2,
36916
- existsSync as existsSync7,
37613
+ existsSync as existsSync8,
36917
37614
  readdirSync as readdirSync5,
36918
- readFileSync as readFileSync8,
36919
- renameSync as renameSync3,
37615
+ readFileSync as readFileSync9,
37616
+ renameSync as renameSync4,
36920
37617
  unlinkSync as unlinkSync3,
36921
- writeFileSync as writeFileSync5
37618
+ writeFileSync as writeFileSync6
36922
37619
  } from "fs";
36923
- import { join as join9 } from "path";
37620
+ import { join as join10 } from "path";
36924
37621
  var pairingIdPattern = /^[0-9a-f]{64}$/;
36925
37622
  var stateSchema = external_exports.object({
36926
37623
  version: external_exports.literal(1),
@@ -36942,12 +37639,12 @@ var stateSchema = external_exports.object({
36942
37639
  function createWalletPairingState(state) {
36943
37640
  ensurePairingsDirectory();
36944
37641
  const path = pairingPath(state.pairing_id);
36945
- writeFileSync5(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
37642
+ writeFileSync6(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
36946
37643
  chmodSync2(path, 384);
36947
37644
  }
36948
37645
  function loadWalletPairingState(pairingId) {
36949
37646
  const path = pairingPath(pairingId);
36950
- if (!existsSync7(path)) {
37647
+ if (!existsSync8(path)) {
36951
37648
  throw new DvmError(
36952
37649
  "wallet_pairing_not_found",
36953
37650
  "No local state exists for that wallet pairing.",
@@ -36955,7 +37652,7 @@ function loadWalletPairingState(pairingId) {
36955
37652
  );
36956
37653
  }
36957
37654
  try {
36958
- return stateSchema.parse(JSON.parse(readFileSync8(path, "utf8")));
37655
+ return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
36959
37656
  } catch {
36960
37657
  throw new DvmError(
36961
37658
  "wallet_pairing_state_invalid",
@@ -36969,9 +37666,9 @@ function saveWalletPairingState(state) {
36969
37666
  ensurePairingsDirectory();
36970
37667
  const path = pairingPath(state.pairing_id);
36971
37668
  const tmp = `${path}.tmp`;
36972
- writeFileSync5(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
37669
+ writeFileSync6(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
36973
37670
  try {
36974
- renameSync3(tmp, path);
37671
+ renameSync4(tmp, path);
36975
37672
  chmodSync2(path, 384);
36976
37673
  } catch (err) {
36977
37674
  try {
@@ -36990,13 +37687,13 @@ function deleteWalletPairingState(pairingId) {
36990
37687
  }
36991
37688
  }
36992
37689
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
36993
- if (!existsSync7(PAIRINGS_DIR)) return 0;
37690
+ if (!existsSync8(PAIRINGS_DIR)) return 0;
36994
37691
  let removed = 0;
36995
37692
  for (const name of readdirSync5(PAIRINGS_DIR)) {
36996
37693
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
36997
- const path = join9(PAIRINGS_DIR, name);
37694
+ const path = join10(PAIRINGS_DIR, name);
36998
37695
  try {
36999
- const state = stateSchema.parse(JSON.parse(readFileSync8(path, "utf8")));
37696
+ const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
37000
37697
  if (state.manifest.expires_at <= nowSeconds) {
37001
37698
  unlinkSync3(path);
37002
37699
  removed += 1;
@@ -37008,7 +37705,7 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
37008
37705
  }
37009
37706
  async function withWalletPairingLock(pairingId, fn) {
37010
37707
  const path = pairingPath(pairingId);
37011
- if (!existsSync7(path)) return fn();
37708
+ if (!existsSync8(path)) return fn();
37012
37709
  let release;
37013
37710
  try {
37014
37711
  release = await import_proper_lockfile3.default.lock(path, {
@@ -37038,7 +37735,7 @@ function pairingPath(pairingId) {
37038
37735
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
37039
37736
  );
37040
37737
  }
37041
- return join9(PAIRINGS_DIR, `${pairingId}.json`);
37738
+ return join10(PAIRINGS_DIR, `${pairingId}.json`);
37042
37739
  }
37043
37740
  function ensurePairingsDirectory() {
37044
37741
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -37677,14 +38374,19 @@ async function forgetSubmission(requestId, opts) {
37677
38374
  "List them with: dvm wallet submissions"
37678
38375
  );
37679
38376
  }
38377
+ refuseIfReclaimUnsaved(view, opts);
37680
38378
  refuseIfSelfHealing(view, opts);
37681
38379
  await confirmForget(view, opts);
37682
38380
  await abandonPendingSubmission({ requestId });
38381
+ clearReclaimIntent(requestId);
37683
38382
  const abandoned = view.at_risk ? view.amount_sats : 0;
38383
+ const heldFor = heldCashuSubmissionAsks(/* @__PURE__ */ new Set([requestId]));
38384
+ 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.`;
37684
38385
  if (opts.human) {
37685
38386
  info(
37686
38387
  view.at_risk ? `Forgot request ${requestId} \u2014 abandoned ${abandoned} sats paid to ${view.endpoint}.` : `Forgot request ${requestId} \u2014 no sats were spent (nothing to abandon).`
37687
38388
  );
38389
+ if (warning) info(`Warning: ${warning}`);
37688
38390
  return;
37689
38391
  }
37690
38392
  json({
@@ -37693,9 +38395,18 @@ async function forgetSubmission(requestId, opts) {
37693
38395
  endpoint: view.endpoint,
37694
38396
  abandoned_sats: abandoned,
37695
38397
  display: !view.at_risk ? `Forgot request ${requestId}. No sats were spent, so nothing was abandoned.` : view.state === "reclaimable" || view.state === "reclaim_failed" ? `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 and this one was still recoverable: the wallet would have returned it to your balance by itself${view.reclaim_at ? ` after ${view.reclaim_at}` : ""}.` : view.state === "accepted_unresolved" ? `Forgot the journal entry for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are no longer tracked; the provider accepted that call, and its evidence stays under submission_evidence.` : view.state === "unreclaimable" ? `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 nothing was given up by forgetting it, since ${view.reclaim_error ?? "the mint's fee exceeds the value"}.` : `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 the proofs were locked to the provider with no refund.`,
37696
- hint: "The entry is gone from the journal. This cannot be undone."
38398
+ hint: "The entry is gone from the journal. This cannot be undone.",
38399
+ ...warning ? { warning, held_for: heldFor.map((ask) => ({ job_id: ask.jobId, request_seq: ask.requestSeq })) } : {}
37697
38400
  });
37698
38401
  }
38402
+ function refuseIfReclaimUnsaved(view, opts) {
38403
+ if (opts.force || !reclaimIntentIds().has(view.request_id)) return;
38404
+ throw new DvmError(
38405
+ "reclaim_unsaved",
38406
+ `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.`,
38407
+ `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`
38408
+ );
38409
+ }
37699
38410
  function refuseIfSelfHealing(view, opts) {
37700
38411
  if (opts.force) return;
37701
38412
  if (view.state !== "reclaimable" && view.state !== "reclaim_failed") return;