@dvmkit/dvm-cli 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dvm.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-CEBEPXQ7.js";
8
+ } from "./chunk-ZGBCVQF2.js";
9
9
  import {
10
10
  CARD_MIN_MICRO,
11
11
  DEFAULT_CREDIT_POSTURE,
@@ -19,12 +19,14 @@ import {
19
19
  answeredYieldSeqs,
20
20
  appendMessages,
21
21
  applySubmissionVerdicts,
22
+ askUsdMicro,
22
23
  assertFloatBudget,
23
24
  automaticCreditBoundRail,
24
25
  availableRails,
25
26
  backfillTrustAnchor,
26
27
  blockHeldPayment,
27
28
  bookCreditPayment,
29
+ budgetVerdict,
28
30
  buildCompletionHintFields,
29
31
  buildTempoCredential,
30
32
  captureDrawFundingReceipts,
@@ -46,7 +48,9 @@ import {
46
48
  createPendingMintQuote,
47
49
  declinedAskSeqs,
48
50
  deriveAlias,
51
+ describeBudgetOverrun,
49
52
  describeMintBounds,
53
+ dollarBoundUsdMicro,
50
54
  drainReceiptsDisplay,
51
55
  drainReceiptsHint,
52
56
  dvmLabelFromEndpoint,
@@ -62,8 +66,10 @@ import {
62
66
  floatBudgetJson,
63
67
  floatPaymentDisplay,
64
68
  floatPaymentJson,
69
+ formatDurationMs,
65
70
  formatLocktime,
66
71
  formatMicro,
72
+ formatUsdMicro,
67
73
  fundAgentWallet,
68
74
  fundCredit,
69
75
  fundTimeoutMs,
@@ -112,7 +118,9 @@ import {
112
118
  nextStepHint,
113
119
  normalizeProviderEndpoint,
114
120
  observeJobContent,
121
+ observePaymentBookings,
115
122
  observedSettlementFields,
123
+ overBudgetHint,
116
124
  parseDurationMs,
117
125
  parseJobContent,
118
126
  parseLocktime,
@@ -120,6 +128,7 @@ import {
120
128
  parseUpfrontPayment,
121
129
  parseUpfrontRailPayment,
122
130
  payViaFloat,
131
+ paymentCountHint,
123
132
  paymentInFlightHint,
124
133
  pendingPaymentRequest,
125
134
  pickCreditFundRail,
@@ -145,6 +154,7 @@ import {
145
154
  reclaimIntentIds,
146
155
  reconcileInFlightPaymentRequest,
147
156
  reconcilePaymentRequestHistory,
157
+ recordBudgetRefusal,
148
158
  recordCallerMessageHash,
149
159
  recordFloatSpend,
150
160
  recordIdentityFailure,
@@ -182,6 +192,7 @@ import {
182
192
  sweepPendingMints,
183
193
  sweepStaleInFlight,
184
194
  terminalSettlementFields,
195
+ terminalSettlementReport,
185
196
  tierCapOverrides,
186
197
  toCapture,
187
198
  toFloatError,
@@ -193,6 +204,8 @@ import {
193
204
  unresendablePaymentHint,
194
205
  updateJob,
195
206
  updateObservedJob,
207
+ upfrontRailPayment,
208
+ usdMicro,
196
209
  walletHistory,
197
210
  walletInvoiceFundingAdvice,
198
211
  warnInvalidJobIdentityHeader,
@@ -200,34 +213,13 @@ import {
200
213
  withIdentityRecovery,
201
214
  withJobTokenRedaction,
202
215
  withRequestResultRecovery
203
- } from "./chunk-LDYMUQZE.js";
216
+ } from "./chunk-VSOIBYBF.js";
204
217
  import {
205
218
  connectedTempoAccount,
206
219
  generateTempoKey,
207
220
  tempoBalanceCheckHint,
208
221
  tempoWrongAssetHint
209
- } from "./chunk-WSLZBJ52.js";
210
- import {
211
- addOutputWarnings,
212
- assertValidBudget,
213
- costAnchor,
214
- formatAmount,
215
- formatAmountBestEffort,
216
- formatPaymentAmount,
217
- getOutputTraceId,
218
- hasUnsavedJobState,
219
- info,
220
- json,
221
- monetaryJson,
222
- parseBudget,
223
- raw,
224
- resolveBtcUsdRate,
225
- setOutputTraceId,
226
- staleRateNotice,
227
- tryResolveBtcUsdRate,
228
- tryX402Payment,
229
- withOutputWarnings
230
- } from "./chunk-NSA2RJ2T.js";
222
+ } from "./chunk-OEWENVJ7.js";
231
223
  import {
232
224
  assertSupportedX402Network,
233
225
  connectedX402Payer,
@@ -236,7 +228,7 @@ import {
236
228
  repinX402WalletNetwork,
237
229
  saveX402Wallet,
238
230
  x402NetworkLabel
239
- } from "./chunk-H6WQ4S6K.js";
231
+ } from "./chunk-VLD7OKSH.js";
240
232
  import {
241
233
  CREDIT_POSTURES,
242
234
  FEEDBACK_POSTURES,
@@ -253,10 +245,32 @@ import {
253
245
  retireConfigBackup,
254
246
  rollbackConfig,
255
247
  updateConfig
256
- } from "./chunk-WRIXUSMR.js";
248
+ } from "./chunk-ESQ6DCS3.js";
249
+ import {
250
+ addOutputWarnings,
251
+ assertValidBudget,
252
+ costAnchor,
253
+ formatAmount,
254
+ formatAmountBestEffort,
255
+ formatPaymentAmount,
256
+ getOutputTraceId,
257
+ hasUnsavedJobState,
258
+ info,
259
+ json,
260
+ jsonEvent,
261
+ monetaryJson,
262
+ parseBudget,
263
+ raw,
264
+ resolveBtcUsdRate,
265
+ setOutputTraceId,
266
+ staleRateNotice,
267
+ tryResolveBtcUsdRate,
268
+ tryX402Payment,
269
+ withOutputWarnings
270
+ } from "./chunk-RYFCHR6Z.js";
257
271
  import {
258
272
  assertX402WalletIdle
259
- } from "./chunk-2TNH4ME5.js";
273
+ } from "./chunk-REIUNZQX.js";
260
274
  import {
261
275
  A,
262
276
  AGENT_MNEMONIC_FILE,
@@ -316,6 +330,7 @@ import {
316
330
  attestedDvmIdentity,
317
331
  authenticatedBuilderPubkey,
318
332
  base64,
333
+ bech32,
319
334
  bindCashuTokenToSubmissionContext,
320
335
  canonicalRequestPath,
321
336
  cashuSubmissionBindingFingerprint,
@@ -495,7 +510,7 @@ import {
495
510
  x402PendingUnsettled,
496
511
  x402RequiredFromError,
497
512
  x402ReservationRelease
498
- } from "./chunk-U2PODYIS.js";
513
+ } from "./chunk-THTPKBZX.js";
499
514
  import "./chunk-JBU7RKQ3.js";
500
515
  import "./chunk-KDNFUDOG.js";
501
516
  import "./chunk-IUTVV6N5.js";
@@ -9193,6 +9208,52 @@ async function readBoundedBody(response, limit) {
9193
9208
  }
9194
9209
  var MAX_COMPATIBILITY_BODY_BYTES = 16384;
9195
9210
 
9211
+ // src/lib/credit-suggestion-cooldown.ts
9212
+ import { existsSync as existsSync2, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync } from "fs";
9213
+ import { join as join2 } from "path";
9214
+ var CREDIT_SUGGESTIONS_FILE = join2(CONFIG_DIR, "credit-suggestions.json");
9215
+ var CREDIT_SUGGESTION_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1e3;
9216
+ function creditSuggestionDue(endpoint, now = Date.now()) {
9217
+ const shownAt = loadState()[normalizeCreditEndpoint(endpoint)];
9218
+ if (shownAt === void 0) return true;
9219
+ const at = Date.parse(shownAt);
9220
+ return !Number.isFinite(at) || at > now || now - at >= CREDIT_SUGGESTION_COOLDOWN_MS;
9221
+ }
9222
+ function recordCreditSuggestionShown(endpoint, now = Date.now()) {
9223
+ try {
9224
+ const state = loadState();
9225
+ state[normalizeCreditEndpoint(endpoint)] = new Date(now).toISOString();
9226
+ saveState(state);
9227
+ } catch {
9228
+ }
9229
+ }
9230
+ function loadState() {
9231
+ if (!existsSync2(CREDIT_SUGGESTIONS_FILE)) return {};
9232
+ try {
9233
+ const parsed = JSON.parse(readFileSync2(CREDIT_SUGGESTIONS_FILE, "utf-8"));
9234
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
9235
+ return Object.fromEntries(
9236
+ Object.entries(parsed).filter((entry) => typeof entry[1] === "string")
9237
+ );
9238
+ } catch {
9239
+ return {};
9240
+ }
9241
+ }
9242
+ function saveState(state) {
9243
+ ensureConfigDir();
9244
+ const tmp = `${CREDIT_SUGGESTIONS_FILE}.${process.pid}.tmp`;
9245
+ writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
9246
+ try {
9247
+ renameSync(tmp, CREDIT_SUGGESTIONS_FILE);
9248
+ } catch (err) {
9249
+ try {
9250
+ unlinkSync(tmp);
9251
+ } catch {
9252
+ }
9253
+ throw err;
9254
+ }
9255
+ }
9256
+
9196
9257
  // src/lib/credit-notice.ts
9197
9258
  function buildCreditFundingSkipped(args) {
9198
9259
  return {
@@ -9211,7 +9272,7 @@ function noteCreditFundingSkipped(skipped, human) {
9211
9272
  function buildCreditSuggestion(args) {
9212
9273
  const { dvm, suppressed } = args;
9213
9274
  const amount = `$${formatUsd(suppressed.fundMicro / 1e6)}`;
9214
- const fundCommand = `dvm credit fund ${shellQuoteArg(dvm)}`;
9275
+ const fundCommand = `dvm credit fund ${shellQuoteArg(dvm)}${suppressed.reason === "open" ? ` --amount ${shellQuoteArg(`$${exactUsd(suppressed.fundMicro)}`)}` : ""}`;
9215
9276
  const optIn = `dvm credit posture auto --dvm ${shellQuoteArg(dvm)}`;
9216
9277
  const covers = args.coversJobs !== void 0 && args.coversJobs > 1 ? ` about ${String(args.coversJobs)} jobs` : " a run of jobs";
9217
9278
  const display = suppressed.reason === "open" ? `Prepaid credit is available at ${dvm}. Funding ${amount} once would cover${covers} in a single payment and reduce per-job fees. Nothing was funded \u2014 this job paid per-call.` : `The prepaid credit at ${dvm} is running low. Adding ${amount} would keep${covers} on one payment and reduce per-job fees. Nothing was funded \u2014 jobs keep drawing on what is left, then go back to paying per-call.`;
@@ -9228,7 +9289,7 @@ function buildCreditSuggestion(args) {
9228
9289
  opt_in_command: optIn,
9229
9290
  opt_in_command_global: "dvm credit posture auto",
9230
9291
  display,
9231
- hint: `Fund it once with '${fundCommand}', or run '${optIn}' (drop --dvm for every DVM) and funding is handled automatically.`
9292
+ hint: `Fund it once with \`${fundCommand}\`, or run \`${optIn}\` (drop --dvm for every DVM) and funding is handled automatically.`
9232
9293
  };
9233
9294
  }
9234
9295
  function buildCreditFundingReport(args) {
@@ -9386,8 +9447,18 @@ function buildCreditRefillDrainPending(args) {
9386
9447
  };
9387
9448
  }
9388
9449
  function noteCreditSuggestion(suggestion, human) {
9389
- info(`${suggestion.display} ${suggestion.hint}`);
9390
- if (!human) pending.credit_suggestion = suggestion;
9450
+ if (!creditSuggestionDue(suggestion.endpoint)) return;
9451
+ if (human) info(`${suggestion.display} ${suggestion.hint}`);
9452
+ else pending.credit_suggestion = suggestion;
9453
+ recordCreditSuggestionShown(suggestion.endpoint);
9454
+ }
9455
+ function stageCreditSuggestion(suggestion, human) {
9456
+ staged = { suggestion, human };
9457
+ }
9458
+ function commitCreditSuggestion() {
9459
+ const held = staged;
9460
+ staged = void 0;
9461
+ if (held) noteCreditSuggestion(held.suggestion, held.human);
9391
9462
  }
9392
9463
  function noteCreditFunding(report, human, stage = "settled") {
9393
9464
  info(stage === "in_flight" ? inFlightLine(report) : report.display);
@@ -9505,6 +9576,7 @@ function noteCreditRefillUnavailable(unavailable, human) {
9505
9576
  function takeCreditNoticeFields() {
9506
9577
  const taken = { ...pending };
9507
9578
  pending = {};
9579
+ staged = void 0;
9508
9580
  return taken;
9509
9581
  }
9510
9582
  function creditFundingSpendDisplay(outcome) {
@@ -9647,7 +9719,12 @@ function inFlightLine(report) {
9647
9719
  const route = inFlightRouteDisplay(report.route, report.x402_flavour, report.tempo_intent);
9648
9720
  return `Funding ${amount} of prepaid credit at ${report.dvm} \u2014 ${route}, because ${whyFunded(report.reason)}. It lands when the job does. ${POSTURE_FOOTER}`;
9649
9721
  }
9722
+ function exactUsd(micro) {
9723
+ const fraction = String(micro % 1e6).padStart(6, "0").replace(/0+$/, "").padEnd(2, "0");
9724
+ return `${Math.floor(micro / 1e6)}.${fraction}`;
9725
+ }
9650
9726
  var pending = {};
9727
+ var staged;
9651
9728
 
9652
9729
  // src/lib/credit-per-dvm.ts
9653
9730
  function providerDvmIdentity(providerInfo) {
@@ -9853,7 +9930,10 @@ async function tryCreditPayment(args) {
9853
9930
  );
9854
9931
  const amountMsats = Math.max(1, usdToMsats(ask.amount_micro / 1e6, rate));
9855
9932
  if (!Number.isSafeInteger(amountMsats)) return false;
9856
- if (args.policy.maxIncrementMsats > 0 && amountMsats > args.policy.maxIncrementMsats || (job.totalPaidMsats ?? 0) + amountMsats > args.policy.maxTotalMsats)
9933
+ const budgetAsk = { msats: amountMsats, usdMicro: usdMicro(ask.amount_micro, ask.currency), rate };
9934
+ const budget = budgetVerdict(args.policy, job, budgetAsk);
9935
+ const explicitIncrement = args.policy.maxIncrementExplicit ?? args.policy.maxIncrementMsats !== args.policy.maxTotalMsats;
9936
+ if (args.policy.maxIncrementMsats > 0 && amountMsats > args.policy.maxIncrementMsats && (explicitIncrement || budget.unit !== "usd") || !budget.fits)
9857
9937
  throw new DvmError("over_budget", "The exact balance charge would exceed this job's budget.");
9858
9938
  if (amountMsats > args.policy.autoPayBelowMsats) return false;
9859
9939
  const selectedBinding = binding;
@@ -9882,7 +9962,7 @@ async function tryCreditPayment(args) {
9882
9962
  if (booked) return booked;
9883
9963
  if ((current.paymentsHonoured ?? 0) >= args.policy.maxPayments)
9884
9964
  throw new DvmError("payment_cap_exceeded", "Job has reached its maximum payment count.");
9885
- if ((current.totalPaidMsats ?? 0) + amountMsats > args.policy.maxTotalMsats)
9965
+ if (!budgetVerdict(args.policy, current, budgetAsk).fits)
9886
9966
  throw new DvmError("over_budget", "The exact balance charge would exceed this job's budget.");
9887
9967
  current.creditBinding = selectedBinding;
9888
9968
  current.pendingCreditPayment = {
@@ -11070,6 +11150,76 @@ function publicRequestIdField(entry) {
11070
11150
  return publicRequestId ? { publicRequestId } : {};
11071
11151
  }
11072
11152
 
11153
+ // src/lib/quote-limit.ts
11154
+ function quoteWithinDeclaredLimit(quote2, limitMsats, declaredLimit, rail) {
11155
+ const native = quoteWithinNativeDollarLimit(quote2, declaredLimit, rail);
11156
+ return native ?? quote2.priceMsats <= limitMsats;
11157
+ }
11158
+ function dollarLimitMicro(declaredLimit) {
11159
+ const amount = /^\$(\d+)(?:\.(\d{1,6}))?$/.exec(declaredLimit.trim().replace(/^\$\./, "$0."));
11160
+ if (!amount) return void 0;
11161
+ const whole = BigInt(amount[1]);
11162
+ const fraction = BigInt((amount[2] || "").padEnd(6, "0"));
11163
+ return whole * 1000000n + fraction;
11164
+ }
11165
+ function quoteWithinNativeDollarLimit(quote2, declaredLimit, rail) {
11166
+ const normalizedRail = rail?.trim().toLowerCase();
11167
+ if (normalizedRail === "x402") {
11168
+ const native = x402QuoteWithinDollarLimit(quote2, declaredLimit);
11169
+ if (native !== void 0) return native;
11170
+ }
11171
+ const upfront = upfrontQuoteWithinDollarLimit(quote2, declaredLimit);
11172
+ if (normalizedRail === "tempo" && declaredLimit?.trim().startsWith("$")) {
11173
+ return upfront ?? false;
11174
+ }
11175
+ return upfront;
11176
+ }
11177
+ function x402QuoteWithinDollarLimit(quote2, declaredLimit) {
11178
+ if (!declaredLimit || !quote2.requiredUsdcMicro) return void 0;
11179
+ const limitMicro = dollarLimitMicro(declaredLimit);
11180
+ if (limitMicro === void 0 || !/^\d+$/.test(quote2.requiredUsdcMicro)) return void 0;
11181
+ return BigInt(quote2.requiredUsdcMicro) <= limitMicro;
11182
+ }
11183
+ function upfrontQuoteWithinDollarLimit(quote2, declaredLimit) {
11184
+ if (!declaredLimit?.trim().startsWith("$")) return void 0;
11185
+ const limitMicro = dollarLimitMicro(declaredLimit);
11186
+ const amountMicro = quote2.upfront?.amount_micro;
11187
+ if (limitMicro === void 0 || quote2.upfront?.currency !== "usd" || amountMicro === void 0 || !Number.isSafeInteger(amountMicro) || amountMicro <= 0) {
11188
+ return void 0;
11189
+ }
11190
+ return BigInt(amountMicro) <= limitMicro;
11191
+ }
11192
+
11193
+ // src/lib/policy.ts
11194
+ function buildPolicy(opts, btcRate) {
11195
+ if (opts.maxPayments === void 0) {
11196
+ throw new DvmError(
11197
+ "missing_max_payments",
11198
+ "Cannot build a spending policy without a payment count cap.",
11199
+ "Pass --max-payments <n> on dvm request. Use 0 for free jobs, 1 for typical paid jobs, or higher for multi-turn flows that may require progressive payments."
11200
+ );
11201
+ }
11202
+ if (!Number.isInteger(opts.maxPayments) || opts.maxPayments < 0) {
11203
+ throw new DvmError(
11204
+ "invalid_max_payments",
11205
+ "Invalid value for --max-payments.",
11206
+ "Pass a non-negative integer (e.g. --max-payments 1)."
11207
+ );
11208
+ }
11209
+ const maxTotalMsats = opts.budget ? parseBudget(opts.budget, btcRate) : 0;
11210
+ const autoPayBelowMsats = opts.autoPayBelow ? parseBudget(opts.autoPayBelow, btcRate) : Math.floor(maxTotalMsats * 0.2);
11211
+ const maxIncrementMsats = opts.maxIncrement ? parseBudget(opts.maxIncrement, btcRate) : maxTotalMsats;
11212
+ const maxTotalUsdMicro = opts.budget?.trim().startsWith("$") ? dollarLimitMicro(opts.budget) : void 0;
11213
+ return {
11214
+ maxTotalMsats,
11215
+ autoPayBelowMsats,
11216
+ maxIncrementMsats,
11217
+ maxPayments: opts.maxPayments,
11218
+ maxIncrementExplicit: opts.maxIncrement !== void 0,
11219
+ ...maxTotalUsdMicro !== void 0 && Number.isSafeInteger(Number(maxTotalUsdMicro)) ? { maxTotalUsdMicro: Number(maxTotalUsdMicro) } : {}
11220
+ };
11221
+ }
11222
+
11073
11223
  // src/lib/agent-wallet-retry.ts
11074
11224
  var TRANSIENT_PAYMENT_BACKOFF_MS = [250, 500, 1e3, 2e3, 4e3];
11075
11225
  var TRANSIENT_PAYMENT_CODES = /* @__PURE__ */ new Set(["proof_pending", "mint_unreachable"]);
@@ -11254,15 +11404,15 @@ function parseTempoNetwork(value, source) {
11254
11404
  var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
11255
11405
  import {
11256
11406
  closeSync,
11257
- existsSync as existsSync2,
11407
+ existsSync as existsSync3,
11258
11408
  fsyncSync,
11259
11409
  mkdirSync,
11260
11410
  openSync,
11261
- readFileSync as readFileSync2,
11262
- renameSync,
11263
- writeFileSync
11411
+ readFileSync as readFileSync3,
11412
+ renameSync as renameSync2,
11413
+ writeFileSync as writeFileSync2
11264
11414
  } from "fs";
11265
- import { join as join2 } from "path";
11415
+ import { join as join3 } from "path";
11266
11416
  function saveRequestIntent(intent) {
11267
11417
  assertRequestId(intent.requestId);
11268
11418
  assertNoPaymentOrAuthSecrets(intent.body);
@@ -11275,26 +11425,26 @@ function saveRequestIntent(intent) {
11275
11425
  throw error;
11276
11426
  }
11277
11427
  fsyncDirectory(REQUEST_INTENTS_DIR);
11278
- const temp = join2(dir, `intent.${String(process.pid)}.tmp`);
11279
- const target = join2(dir, "intent.json");
11428
+ const temp = join3(dir, `intent.${String(process.pid)}.tmp`);
11429
+ const target = join3(dir, "intent.json");
11280
11430
  const fd = openSync(temp, "wx", 384);
11281
11431
  try {
11282
- writeFileSync(fd, JSON.stringify(intent, null, 2) + "\n");
11432
+ writeFileSync2(fd, JSON.stringify(intent, null, 2) + "\n");
11283
11433
  fsyncSync(fd);
11284
11434
  } finally {
11285
11435
  closeSync(fd);
11286
11436
  }
11287
- renameSync(temp, target);
11437
+ renameSync2(temp, target);
11288
11438
  fsyncDirectory(dir);
11289
11439
  return true;
11290
11440
  }
11291
11441
  function loadRequestIntent(requestId) {
11292
11442
  assertRequestId(requestId);
11293
11443
  const dir = intentDirectory(requestId);
11294
- if (!existsSync2(dir)) return null;
11295
- const path = join2(dir, "intent.json");
11444
+ if (!existsSync3(dir)) return null;
11445
+ const path = join3(dir, "intent.json");
11296
11446
  try {
11297
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
11447
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
11298
11448
  if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
11299
11449
  throw new Error("invalid shape");
11300
11450
  return parsed;
@@ -11311,22 +11461,22 @@ function recordRequestRailPayment(requestId, payment) {
11311
11461
  assertRequestId(requestId);
11312
11462
  if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
11313
11463
  const dir = intentDirectory(requestId);
11314
- const target = join2(dir, "intent.json");
11464
+ const target = join3(dir, "intent.json");
11315
11465
  const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
11316
11466
  try {
11317
11467
  const intent = loadRequestIntent(requestId);
11318
11468
  if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
11319
11469
  if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
11320
11470
  throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
11321
- const temp = join2(dir, `rail.${String(process.pid)}.tmp`);
11471
+ const temp = join3(dir, `rail.${String(process.pid)}.tmp`);
11322
11472
  const fd = openSync(temp, "w", 384);
11323
11473
  try {
11324
- writeFileSync(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
11474
+ writeFileSync2(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
11325
11475
  fsyncSync(fd);
11326
11476
  } finally {
11327
11477
  closeSync(fd);
11328
11478
  }
11329
- renameSync(temp, target);
11479
+ renameSync2(temp, target);
11330
11480
  fsyncDirectory(dir);
11331
11481
  } finally {
11332
11482
  release();
@@ -11369,7 +11519,7 @@ function assertRequestId(requestId) {
11369
11519
  );
11370
11520
  }
11371
11521
  function intentDirectory(requestId) {
11372
- return join2(REQUEST_INTENTS_DIR, requestId);
11522
+ return join3(REQUEST_INTENTS_DIR, requestId);
11373
11523
  }
11374
11524
  function fsyncDirectory(path) {
11375
11525
  if (process.platform === "win32") return;
@@ -11396,21 +11546,89 @@ function isSignedRequestAudience(value) {
11396
11546
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11397
11547
  const seq = opts?.requestSeq;
11398
11548
  let replacing = false;
11399
- return withJobPaymentLock(jobId, (assertOwned) => {
11549
+ let budgetSaved = false;
11550
+ let approvedPolicy;
11551
+ return withJobPaymentLock(jobId, async (assertOwned) => {
11552
+ const current = loadJob(jobId);
11553
+ const localEndpoint = current && provider.endpoint && sameEndpoint(current.endpoint, provider.endpoint);
11554
+ if (opts?.useStoredPolicy && localEndpoint && current.policy) policy = current.policy;
11555
+ if (opts?.budget !== void 0) {
11556
+ if (opts.approval !== "explicit" || !localEndpoint || !current.policy) {
11557
+ throw new DvmError(
11558
+ "invalid_budget",
11559
+ "Cannot change this job's budget here.",
11560
+ "Use dvm pay --budget on the saved job at its original endpoint after your human approves the new total."
11561
+ );
11562
+ }
11563
+ const raw2 = opts.budget;
11564
+ if (!/^(?:\$(?:\d+(?:\.\d{1,6})?|\.\d{1,6})|\d+)$/.test(raw2)) {
11565
+ throw new DvmError(
11566
+ "invalid_budget",
11567
+ "Invalid --budget total.",
11568
+ 'Use a dollar amount such as "$1.00" or an integer number of millisats, as on dvm request.'
11569
+ );
11570
+ }
11571
+ const rate = raw2.startsWith("$") ? (await resolveBtcUsdRate("payment")).rate : 0;
11572
+ const parsed = buildPolicy({ budget: raw2, maxPayments: current.policy.maxPayments }, rate);
11573
+ if (!Number.isSafeInteger(parsed.maxTotalMsats) || parsed.maxTotalMsats < 0 || raw2.startsWith("$") && parsed.maxTotalUsdMicro === void 0) {
11574
+ throw new DvmError("invalid_budget", "Invalid --budget total.", "Pass a non-negative total within the supported integer range.");
11575
+ }
11576
+ assertBudgetNotBelowSpend(parsed, current);
11577
+ const { maxTotalUsdMicro: _oldDollars, ...preserved } = current.policy;
11578
+ const explicitIncrement = current.policy.maxIncrementExplicit ?? current.policy.maxIncrementMsats !== current.policy.maxTotalMsats;
11579
+ approvedPolicy = {
11580
+ ...preserved,
11581
+ maxTotalMsats: parsed.maxTotalMsats,
11582
+ maxIncrementExplicit: explicitIncrement,
11583
+ maxIncrementMsats: explicitIncrement ? current.policy.maxIncrementMsats : parsed.maxTotalMsats,
11584
+ ...parsed.maxTotalUsdMicro !== void 0 ? { maxTotalUsdMicro: parsed.maxTotalUsdMicro } : {}
11585
+ };
11586
+ policy = approvedPolicy;
11587
+ }
11588
+ if (opts?.approval === "explicit") policy = { ...policy, autoPayBelowMsats: Number.MAX_SAFE_INTEGER };
11400
11589
  replacing = opts?.approval === "explicit" && seq !== void 0 && loadJob(jobId)?.askPaymentBlocks?.[seq] !== void 0;
11590
+ let newPayment = false;
11401
11591
  const guardedTransport = new Proxy(transport, {
11402
11592
  get(target, key) {
11403
11593
  if (key === "sendMessage") return async (...args) => {
11404
11594
  assertOwned();
11595
+ if (newPayment && approvedPolicy && !budgetSaved) {
11596
+ assertBudgetNotBelowSpend(approvedPolicy, loadJob(jobId));
11597
+ updateJob(jobId, { policy: approvedPolicy, budgetRefusals: {} });
11598
+ budgetSaved = true;
11599
+ }
11405
11600
  return target.sendMessage(...args);
11406
11601
  };
11407
11602
  const value = Reflect.get(target, key, target);
11408
11603
  return typeof value === "function" ? value.bind(target) : value;
11409
11604
  }
11410
11605
  });
11411
- return handleLockedPaymentRequest(jobId, request2, policy, guardedTransport, provider, opts);
11606
+ const result = await handleLockedPaymentRequest(
11607
+ jobId,
11608
+ request2,
11609
+ policy,
11610
+ guardedTransport,
11611
+ provider,
11612
+ opts,
11613
+ () => {
11614
+ newPayment = true;
11615
+ }
11616
+ );
11617
+ if (budgetSaved && typeof result === "string")
11618
+ throw new DvmError(result === "over-budget" ? "over_budget" : "payment_failed", "The payment was not completed.");
11619
+ return result;
11412
11620
  }).catch((error) => {
11621
+ if (budgetSaved && !(error instanceof DvmError)) error = new DvmError("payment_failed", "The payment was not completed.");
11413
11622
  if (!(error instanceof DvmError)) throw error;
11623
+ if (error.code === "budget_below_spend" || error.code === "invalid_budget" || error.code === "over_budget" && opts?.budget !== void 0 && !budgetSaved) {
11624
+ error.data = providerFields({
11625
+ ...error.data,
11626
+ job_id: jobId,
11627
+ next_step: error.hint,
11628
+ next_action: providerFields({ type: "pay", job_id: jobId, amount_msats: request2.amount_msats, display: error.message, hint: error.hint }, ["job_id"])
11629
+ }, ["job_id"]);
11630
+ throw error;
11631
+ }
11414
11632
  const job = loadJob(jobId);
11415
11633
  if (!job || !provider.endpoint || !sameEndpoint(job.endpoint, provider.endpoint)) throw error;
11416
11634
  let requestId;
@@ -11434,6 +11652,7 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11434
11652
  }, ["job_id"]);
11435
11653
  throw error;
11436
11654
  }
11655
+ if (budgetSaved) throw error;
11437
11656
  const command = requestId ? `dvm request-result ${shellQuoteArg(requestId)}` : `dvm status ${guidanceJobArg(jobId)}`;
11438
11657
  const recovery = `The job was already accepted. Inspect it with \`${command}\` before submitting a replacement. This read cannot submit a job or send payment.`;
11439
11658
  error.data = providerFields({
@@ -11444,9 +11663,37 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11444
11663
  next_step: [typeof error.data?.next_step === "string" ? error.data.next_step : void 0, recovery].filter(Boolean).join(" ")
11445
11664
  }, ["job_id"]);
11446
11665
  throw error;
11666
+ }).catch((error) => {
11667
+ if (!budgetSaved || !(error instanceof DvmError)) throw error;
11668
+ const total = approvedPolicy?.maxTotalUsdMicro !== void 0 ? formatUsdMicro(approvedPolicy.maxTotalUsdMicro) : `${approvedPolicy?.maxTotalMsats} msats`;
11669
+ const action = error.data?.next_action;
11670
+ const saved = action?.type === "poll" ? `The new total budget of ${total} was saved.` : `The new total budget of ${total} was saved. Retry with \`dvm pay ${guidanceJobArg(jobId)}\`; it resolves any earlier send before paying again.`;
11671
+ error.hint = [error.hint, saved].filter(Boolean).join(" ");
11672
+ error.data = providerFields({
11673
+ ...error.data,
11674
+ job_id: jobId,
11675
+ budget_saved: true,
11676
+ next_step: [error.data?.next_step, saved].filter(Boolean).join(" "),
11677
+ next_action: providerFields(action ? { ...action, hint: [action.hint, saved].filter(Boolean).join(" ") } : { type: "pay", job_id: jobId, amount_msats: request2.amount_msats, display: error.message, hint: error.hint }, ["job_id"])
11678
+ }, ["job_id"]);
11679
+ throw error;
11447
11680
  });
11448
11681
  }
11449
- async function handleLockedPaymentRequest(jobId, request2, policy, transport, provider, opts) {
11682
+ function assertBudgetNotBelowSpend(policy, job) {
11683
+ const dollars = policy.maxTotalUsdMicro !== void 0 && (job?.paidUsdMsats ?? 0) === (job?.totalPaidMsats ?? 0);
11684
+ const spent = dollars ? job?.paidUsdMicro ?? 0 : job?.totalPaidMsats ?? 0;
11685
+ const proposed = dollars ? policy.maxTotalUsdMicro : policy.maxTotalMsats;
11686
+ if (proposed >= spent) return;
11687
+ const format = dollars ? formatUsdMicro : (value) => `${value.toLocaleString("en-US")} msats`;
11688
+ const display = `The new total ${format(proposed)} is below the amount already spent: ${format(spent)}.`;
11689
+ throw new DvmError(
11690
+ "budget_below_spend",
11691
+ display,
11692
+ `Ask your human to approve a higher total of at least ${format(spent)}, then retry dvm pay --budget with that approved total.`,
11693
+ { display, spent, proposed, unit: dollars ? "usd" : "msats" }
11694
+ );
11695
+ }
11696
+ async function handleLockedPaymentRequest(jobId, request2, policy, transport, provider, opts, beforeNewPayment) {
11450
11697
  if (hasPendingAcceptedJobAccess(jobId, provider.endpoint)) throw new DvmError(
11451
11698
  "local_job_state_unsaved",
11452
11699
  "Private recovery state must be folded before another payment can be sent.",
@@ -11524,17 +11771,36 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11524
11771
  throw unconfirmedPaymentError(jobId, "An earlier payment for this request is unconfirmed and this CLI holds no copy to re-send.");
11525
11772
  }
11526
11773
  const latest = loadJob(jobId);
11527
- const spent = latest?.totalPaidMsats ?? 0;
11528
11774
  const paymentsHonoured = latest?.paymentsHonoured ?? 0;
11529
- if (policy.maxIncrementMsats > 0 && request2.amount_msats > policy.maxIncrementMsats) {
11775
+ if (opts?.budget !== void 0 && paymentsHonoured >= policy.maxPayments) return "payment-cap-exceeded";
11776
+ const askUsd = askUsdMicro(request2);
11777
+ const budgetAsk = {
11778
+ msats: request2.amount_msats,
11779
+ usdMicro: askUsd,
11780
+ rate: policy.maxTotalUsdMicro !== void 0 && askUsd !== void 0 ? (await tryResolveBtcUsdRate())?.rate : void 0
11781
+ };
11782
+ const budget = budgetVerdict(policy, latest ?? void 0, budgetAsk);
11783
+ const refuse = (overrun) => {
11784
+ if (opts?.budget !== void 0) {
11785
+ const total = policy.maxTotalUsdMicro !== void 0 ? formatUsdMicro(policy.maxTotalUsdMicro) : `${policy.maxTotalMsats} msats`;
11786
+ const display = `Proposed total ${total}: ${describeBudgetOverrun(overrun, policy)}`;
11787
+ throw new DvmError("over_budget", display, overBudgetHint(jobId, display), { display, proposed_total: overrun.cap, unit: overrun.unit });
11788
+ }
11789
+ if (matchingEndpoint && opts?.requestSeq !== void 0) recordBudgetRefusal(jobId, opts.requestSeq, overrun);
11530
11790
  return "over-budget";
11531
- }
11532
- if (spent + request2.amount_msats > policy.maxTotalMsats) {
11791
+ };
11792
+ if (!budget.fits) return refuse(budget);
11793
+ const explicitIncrement = policy.maxIncrementExplicit ?? policy.maxIncrementMsats !== policy.maxTotalMsats;
11794
+ if (policy.maxIncrementMsats > 0 && request2.amount_msats > policy.maxIncrementMsats && (explicitIncrement || budget.unit !== "usd")) {
11795
+ if (opts?.budget !== void 0) throw new DvmError(
11796
+ "over_budget",
11797
+ "The proposed budget does not change the explicit per-ask limit.",
11798
+ `This ask exceeds --max-increment. To stop, run \`dvm decline ${guidanceJobArg(jobId)}\`; further work needs a new request with approved limits.`
11799
+ );
11533
11800
  return "over-budget";
11534
11801
  }
11535
- if (paymentsHonoured >= policy.maxPayments) {
11536
- return "payment-cap-exceeded";
11537
- }
11802
+ let signedRefusal;
11803
+ if (paymentsHonoured >= policy.maxPayments) return "payment-cap-exceeded";
11538
11804
  if (strictPerCall)
11539
11805
  throw new DvmError(
11540
11806
  "strict_per_call_mid_job_payment",
@@ -11563,6 +11829,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11563
11829
  }
11564
11830
  if (opts?.requestSeq !== void 0 && loadJob(jobId)?.askPaymentBlocks?.[opts.requestSeq] && opts.approval !== "explicit")
11565
11831
  return "needs-approval";
11832
+ beforeNewPayment?.();
11566
11833
  if (matchingEndpoint && !balanceRefused && opts?.rail === void 0) {
11567
11834
  const creditPaid = await tryCreditPayment({
11568
11835
  jobId,
@@ -11601,6 +11868,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11601
11868
  transport,
11602
11869
  provider,
11603
11870
  btcRate,
11871
+ usdMicro: dollarBoundUsdMicro(budgetAsk),
11604
11872
  pinnedMint,
11605
11873
  maxCashuFeeSats,
11606
11874
  strictPerCall,
@@ -11613,8 +11881,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11613
11881
  }
11614
11882
  }
11615
11883
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11616
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-QKAKRLPI.js");
11617
- const { tryX402Payment: tryX402Payment2 } = await import("./client-S5PTHG25.js");
11884
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
11885
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-PVRLAMI3.js");
11618
11886
  const wallet = loadX402Wallet2();
11619
11887
  if (wallet) {
11620
11888
  let proof;
@@ -11641,6 +11909,18 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11641
11909
  if (!(err instanceof DvmError) || err.code !== "x402_build_failed") throw err;
11642
11910
  proof = null;
11643
11911
  }
11912
+ const signedUsd = proof ? usdMicro(Number(proof.amountUsdcMicro), "usd") : void 0;
11913
+ if (proof) {
11914
+ const signed = budgetVerdict(
11915
+ policy,
11916
+ loadJob(jobId) ?? void 0,
11917
+ { msats: proof.amountMsats, usdMicro: signedUsd, rate: proof.btcRate }
11918
+ );
11919
+ if (!signed.fits) {
11920
+ signedRefusal = signed;
11921
+ proof = null;
11922
+ }
11923
+ }
11644
11924
  if (proof) {
11645
11925
  await enforceGlobalBudget({ plannedMsats: proof.amountMsats, btcRate: proof.btcRate });
11646
11926
  return deliverSignedRailPayment({
@@ -11656,6 +11936,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11656
11936
  content: { x402_payment: proof.paymentHeader, amount_msats: proof.amountMsats },
11657
11937
  requestAmountMsats: request2.amount_msats,
11658
11938
  amountMsats: proof.amountMsats,
11939
+ // Book the dollars the signed authorization moves, not the ask's figure.
11940
+ ...usdMicroField(signedUsd),
11659
11941
  btcRate: proof.btcRate,
11660
11942
  amountUsdcMicro: proof.amountUsdcMicro,
11661
11943
  approval: approval?.approval,
@@ -11669,7 +11951,15 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11669
11951
  const tempoRate = btcRate > 0 ? btcRate : (await tryResolveBtcUsdRate())?.rate ?? 0;
11670
11952
  const cred = await tryMppCredential(request2.tempo.challenges, request2.amount_msats, tempoRate);
11671
11953
  if (cred) {
11672
- const paidMsats = usdcToMsats(Number(tempoCredentialAmountMicro(cred)) / 1e6, tempoRate);
11954
+ const signedMicro = Number(tempoCredentialAmountMicro(cred));
11955
+ const paidMsats = usdcToMsats(signedMicro / 1e6, tempoRate);
11956
+ const signedUsd = usdMicro(signedMicro, "usd");
11957
+ const signed = budgetVerdict(
11958
+ policy,
11959
+ loadJob(jobId) ?? void 0,
11960
+ { msats: paidMsats, usdMicro: signedUsd, rate: tempoRate }
11961
+ );
11962
+ if (!signed.fits) return refuse(signed);
11673
11963
  await enforceGlobalBudget({ plannedMsats: paidMsats, btcRate: tempoRate });
11674
11964
  return deliverSignedRailPayment({
11675
11965
  jobId,
@@ -11684,6 +11974,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11684
11974
  content: { tempo_credential: cred, amount_msats: paidMsats },
11685
11975
  requestAmountMsats: request2.amount_msats,
11686
11976
  amountMsats: paidMsats,
11977
+ ...usdMicroField(signedUsd),
11687
11978
  btcRate: tempoRate,
11688
11979
  approval: approval?.approval,
11689
11980
  reason: request2.reason
@@ -11691,7 +11982,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11691
11982
  });
11692
11983
  }
11693
11984
  }
11694
- return "needs-approval";
11985
+ return signedRefusal ? refuse(signedRefusal) : "needs-approval";
11695
11986
  }
11696
11987
  function unconfirmedPaymentError(jobId, message2, hint = unresendablePaymentHint(jobId)) {
11697
11988
  return new DvmError("payment_unconfirmed", `${message2} No new payment was signed.`, hint);
@@ -11753,7 +12044,7 @@ async function deliverSignedRailPayment(args) {
11753
12044
  args.redelivery
11754
12045
  );
11755
12046
  if (!sent.tracked) {
11756
- addPayment(jobId, submission.amountMsats, args.approval);
12047
+ addPayment(jobId, submission.amountMsats, args.approval, submission.usdMicro);
11757
12048
  recordSpend({
11758
12049
  msats: submission.amountMsats,
11759
12050
  btcRate: submission.btcRate,
@@ -11842,6 +12133,7 @@ async function tryAgentWalletMidJobPayment(args) {
11842
12133
  ...prepared.fromReserve ? { reserve: true } : {},
11843
12134
  requestAmountMsats: request2.amount_msats,
11844
12135
  amountMsats: request2.amount_msats,
12136
+ ...usdMicroField(args.usdMicro),
11845
12137
  btcRate,
11846
12138
  approval: approval?.approval,
11847
12139
  reason: request2.reason
@@ -11888,7 +12180,7 @@ async function deliverAgentWalletPayment(args) {
11888
12180
  signed_at_ms: Date.now()
11889
12181
  }
11890
12182
  });
11891
- addPayment(jobId, request2.amount_msats, approval);
12183
+ addPayment(jobId, request2.amount_msats, approval, submission.usdMicro);
11892
12184
  recordSpend({
11893
12185
  msats: request2.amount_msats,
11894
12186
  btcRate: submission.btcRate,
@@ -12025,6 +12317,9 @@ async function tryMppCredential(challenges, amountMsats, btcRate) {
12025
12317
  onError: "null"
12026
12318
  });
12027
12319
  }
12320
+ function usdMicroField(value) {
12321
+ return value !== void 0 ? { usdMicro: value } : {};
12322
+ }
12028
12323
 
12029
12324
  // src/lib/refund-claim.ts
12030
12325
  async function claimInboundPayments(jobId, messages2) {
@@ -12165,16 +12460,18 @@ async function streamLoop(opts) {
12165
12460
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
12166
12461
  const declined = () => persistLocalState && loadJob(jobId)?.callerDeclined === true;
12167
12462
  async function recordAutoPayment(result, request2, seq) {
12168
- autoPayments.push({
12463
+ const payment = {
12169
12464
  amount_msats: result.amountMsats,
12170
12465
  rail: result.rail,
12171
12466
  reason: asProviderText(request2.reason),
12172
12467
  ...result.amountUsdcMicro !== void 0 && { amount_usdc_microunits: result.amountUsdcMicro },
12173
12468
  display: paidConfirmationDisplay(result, request2.fiat_amount)
12174
- });
12469
+ };
12470
+ autoPayments.push(payment);
12175
12471
  if (persistLocalState) markPaymentRequestAnswered(jobId, seq);
12176
12472
  answeredSeqs.add(seq);
12177
12473
  justAutoPaid = true;
12474
+ opts.onAutoPayment?.(payment, seq);
12178
12475
  }
12179
12476
  let pendingAction = null;
12180
12477
  const pending4 = persistLocalState ? loadJob(jobId)?.pendingCreditPayment : void 0;
@@ -12183,11 +12480,19 @@ async function streamLoop(opts) {
12183
12480
  try {
12184
12481
  result = await handlePaymentRequest(jobId, pending4.request, policy, transport, provider, {
12185
12482
  jobToken,
12186
- requestSeq: pending4.authorization.request_seq
12483
+ requestSeq: pending4.authorization.request_seq,
12484
+ useStoredPolicy: true
12187
12485
  });
12188
12486
  } catch (error) {
12189
12487
  if (error instanceof DvmError && error.code === "payment_settling")
12190
- return { messages: [], autoPayments, refunds, cursor, nextAction: pollNextAction(jobId, paymentInFlightHint(jobId, loadJob(jobId), pending4.authorization.request_seq)) };
12488
+ return {
12489
+ messages: [],
12490
+ autoPayments,
12491
+ refunds,
12492
+ cursor,
12493
+ paymentInFlight: true,
12494
+ nextAction: pollNextAction(jobId, paymentInFlightHint(jobId, loadJob(jobId), pending4.authorization.request_seq))
12495
+ };
12191
12496
  throw error;
12192
12497
  }
12193
12498
  if (typeof result === "object") await recordAutoPayment(result, pending4.request, pending4.authorization.request_seq);
@@ -12197,7 +12502,7 @@ async function streamLoop(opts) {
12197
12502
  timestamp: 0,
12198
12503
  type: "payment-request",
12199
12504
  content: pending4.request
12200
- }], void 0, policy ? { policy, totalPaidMsats: loadJob(jobId)?.totalPaidMsats } : void 0);
12505
+ }], void 0, policy ? budgetContext(policy, loadJob(jobId)) : void 0);
12201
12506
  }
12202
12507
  const deadline = opts.timeoutMs === void 0 ? void 0 : Date.now() + Math.max(0, opts.timeoutMs);
12203
12508
  const nextPollOptions = () => {
@@ -12289,12 +12594,14 @@ async function streamLoop(opts) {
12289
12594
  }
12290
12595
  if (lastYield2?.type === "payment-request" && lastYield2.seq === pendingPayment?.seq && policy && !declined()) {
12291
12596
  const req = lastYield2.content;
12292
- if (req.amount_msats <= policy.autoPayBelowMsats && (policy.maxIncrementMsats === 0 || req.amount_msats <= policy.maxIncrementMsats)) {
12597
+ const activePolicy = persistLocalState ? loadJob(jobId)?.policy ?? policy : policy;
12598
+ if (req.amount_msats <= activePolicy.autoPayBelowMsats && (activePolicy.maxIncrementMsats === 0 || req.amount_msats <= activePolicy.maxIncrementMsats)) {
12293
12599
  let result;
12294
12600
  try {
12295
12601
  result = await handlePaymentRequest(jobId, req, policy, transport, provider, {
12296
12602
  jobToken,
12297
- requestSeq: lastYield2.seq
12603
+ requestSeq: lastYield2.seq,
12604
+ useStoredPolicy: true
12298
12605
  });
12299
12606
  } catch (error) {
12300
12607
  if (error instanceof DvmError && ["payment_settling", "payment_unconfirmed"].includes(error.code)) {
@@ -12318,7 +12625,7 @@ async function streamLoop(opts) {
12318
12625
  throw new DvmError(
12319
12626
  "payment_cap_exceeded",
12320
12627
  "Job has reached its maximum payment count.",
12321
- `The provider has sent more payment-requests than --max-payments allows. Inspect with 'dvm messages ${jobId}' and 'dvm cancel ${jobId}' if unintended. Raise with '--max-payments ${cap2 + 1}' or investigate why this provider is asking for many small payments.`,
12628
+ paymentCountHint(jobId, cap2),
12322
12629
  {
12323
12630
  anchor: "max_payments_exceeded",
12324
12631
  display: `Payment cap reached (${cap2} payment${cap2 === 1 ? "" : "s"})`,
@@ -12360,7 +12667,7 @@ async function streamLoop(opts) {
12360
12667
  if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
12361
12668
  for (const seq of answeredYieldSeqs(allMessages)) answeredSeqs.add(seq);
12362
12669
  const terminal = allMessages.some((msg) => msg.type === "complete" || msg.type === "cancel") || declined();
12363
- const yieldAction = computeNextAction(jobId, allMessages.filter((message2) => !answeredSeqs.has(message2.seq)), void 0, policy ? { policy, totalPaidMsats: loadJob(jobId)?.totalPaidMsats } : void 0) ?? (terminal ? null : pendingAction);
12670
+ const yieldAction = computeNextAction(jobId, allMessages.filter((message2) => !answeredSeqs.has(message2.seq)), void 0, policy ? budgetContext(policy, loadJob(jobId)) : void 0) ?? (terminal ? null : pendingAction);
12364
12671
  let nextAction = withRefundNextAction(jobId, yieldAction ?? (terminal ? null : pollNextAction(jobId)), refunds);
12365
12672
  const lastYield = findLastYield(allMessages);
12366
12673
  const heldJob = persistLocalState ? loadJob(jobId) : null;
@@ -12382,7 +12689,7 @@ async function streamLoop(opts) {
12382
12689
  ));
12383
12690
  if (hasUnsavedJobState() && !terminal)
12384
12691
  nextAction = pollNextAction(jobId, "Local state may lag; refresh this job before another payment.");
12385
- return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
12692
+ return { messages: allMessages, autoPayments, refunds, nextAction, cursor, ...paymentUnresolved && { paymentInFlight: true } };
12386
12693
  }
12387
12694
  function isMessagePollTimeout(err) {
12388
12695
  return isAbortError(err) || err instanceof DvmError && err.code === "timeout";
@@ -12394,6 +12701,16 @@ function findLastYield(messages2) {
12394
12701
  }
12395
12702
  return void 0;
12396
12703
  }
12704
+ function budgetContext(policy, job) {
12705
+ return {
12706
+ policy: job?.policy ?? policy,
12707
+ paymentsHonoured: job?.paymentsHonoured,
12708
+ totalPaidMsats: job?.totalPaidMsats,
12709
+ paidUsdMicro: job?.paidUsdMicro,
12710
+ paidUsdMsats: job?.paidUsdMsats,
12711
+ budgetRefusals: job?.budgetRefusals
12712
+ };
12713
+ }
12397
12714
 
12398
12715
  // src/lib/schema-defaults.ts
12399
12716
  function applyJsonSchemaDefaults(schema, data) {
@@ -14392,7 +14709,7 @@ async function settleCreditAfterJob(args) {
14392
14709
  }
14393
14710
  }
14394
14711
  if (args.allowTopup !== false) {
14395
- const refill = args.refillPocket ?? (await import("./pocket-refill-3CA4PFXG.js")).refillPocketIfLow;
14712
+ const refill = args.refillPocket ?? (await import("./pocket-refill-6UL6CHD5.js")).refillPocketIfLow;
14396
14713
  await refill({ human: args.human }).catch(() => void 0);
14397
14714
  }
14398
14715
  }
@@ -14850,8 +15167,10 @@ async function cancelWithAccess(jobId, opts, access) {
14850
15167
  const endingDisplay = settlement ? cancelledDisplay(settlement) : receiptPending ? `Stopped. Its receipt is not available yet; \`dvm status ${guidanceJobArg(jobId)}\` shows what was charged once it is.` : void 0;
14851
15168
  const display = [endingDisplay, artifacts.display].filter(Boolean).join(" ") || void 0;
14852
15169
  const hint = settlementCurrencyHint(settlement, ref.endpoint);
15170
+ const { wallet_remaining } = await terminalSettlementReport(jobId, { status: "cancelled", persistLocalState: !access.endpointOverridden });
14853
15171
  if (opts.human) {
14854
15172
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
15173
+ if (wallet_remaining) info(wallet_remaining.display);
14855
15174
  if (display) info(display);
14856
15175
  if (hint) info(` ${hint}`);
14857
15176
  } else {
@@ -14861,6 +15180,7 @@ async function cancelWithAccess(jobId, opts, access) {
14861
15180
  status: "cancelled",
14862
15181
  ...opts.reason ? { reason: opts.reason } : {},
14863
15182
  ...settlement ? { settlement } : {},
15183
+ ...wallet_remaining ? { wallet_remaining } : {},
14864
15184
  ...display ? { display } : {},
14865
15185
  ...artifacts.fields,
14866
15186
  ...hint ? { hint } : {},
@@ -14945,8 +15265,10 @@ async function declineWithAccess(jobId, opts, access) {
14945
15265
  const endingDisplay = observed === void 0 ? `Decline sent, but the job's status could not be read. Check it with \`dvm status ${job}\`.` : settlement ? `Declined; the job has ended. ${settlement.display}` : `Declined; the job has ended. Its receipt is not available yet; \`dvm status ${job}\` shows the final charge once it is.`;
14946
15266
  const display = [endingDisplay, artifacts.display].filter(Boolean).join(" ");
14947
15267
  const hint = settlementCurrencyHint(settlement, ref.endpoint);
15268
+ const { wallet_remaining } = await terminalSettlementReport(jobId, { status: observed, persistLocalState: !access.endpointOverridden });
14948
15269
  if (opts.human) {
14949
15270
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""}: ${display}`);
15271
+ if (wallet_remaining) info(wallet_remaining.display);
14950
15272
  if (hint) info(` ${hint}`);
14951
15273
  return;
14952
15274
  }
@@ -14957,6 +15279,7 @@ async function declineWithAccess(jobId, opts, access) {
14957
15279
  declined: true,
14958
15280
  ...opts.reason !== void 0 ? { reason: opts.reason } : {},
14959
15281
  ...settlement ? { settlement } : {},
15282
+ ...wallet_remaining ? { wallet_remaining } : {},
14960
15283
  display,
14961
15284
  ...artifacts.fields,
14962
15285
  ...hint ? { hint } : {},
@@ -15167,14 +15490,14 @@ async function confirmRollback(stored, preview, opts) {
15167
15490
  async function withStrandingChecked(removing, commit) {
15168
15491
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
15169
15492
  if (leaving.has("tempo")) {
15170
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-GAM3DJ63.js");
15493
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-WGTX6MJR.js");
15171
15494
  await assertTempoWalletIdle2("disconnect");
15172
15495
  }
15173
15496
  if (!leaving.has("x402")) return commit();
15174
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-3SIUYRWP.js");
15175
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-7NHL5ATK.js");
15176
- const { ensureAddress: ensureAddress2 } = await import("./internal-3SIUYRWP.js");
15177
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-QKAKRLPI.js");
15497
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-L362ZUWL.js");
15498
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-BH4OA5I3.js");
15499
+ const { ensureAddress: ensureAddress2 } = await import("./internal-L362ZUWL.js");
15500
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
15178
15501
  return withX402ChannelLock2(async () => {
15179
15502
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
15180
15503
  if (unsettled.length > 0) {
@@ -19688,7 +20011,7 @@ import {
19688
20011
  } from "crypto";
19689
20012
 
19690
20013
  // src/lib/secret-input.ts
19691
- import { fstatSync, readFileSync as readFileSync3, realpathSync } from "fs";
20014
+ import { fstatSync, readFileSync as readFileSync4, realpathSync } from "fs";
19692
20015
  import { homedir } from "os";
19693
20016
  import { resolve, sep } from "path";
19694
20017
  var BLOCKED_SECRET_PATHS = [
@@ -19768,7 +20091,7 @@ function readSecretFile(path, config2) {
19768
20091
  throw err;
19769
20092
  }
19770
20093
  assertSafeFilePath(real);
19771
- return readFileSync3(real, "utf-8").trim();
20094
+ return readFileSync4(real, "utf-8").trim();
19772
20095
  }
19773
20096
  function readSecretStdin(config2) {
19774
20097
  return new Promise((resolveStdin, reject) => {
@@ -21881,8 +22204,8 @@ async function probeX402(x402, timeoutMs) {
21881
22204
  let network;
21882
22205
  let address;
21883
22206
  try {
21884
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-QKAKRLPI.js");
21885
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-3SIUYRWP.js");
22207
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
22208
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-L362ZUWL.js");
21886
22209
  const wallet = loadX402Wallet2();
21887
22210
  if (!wallet) {
21888
22211
  const storedKey = x402.privateKey;
@@ -21934,8 +22257,8 @@ async function probeMpp(mpp, timeoutMs) {
21934
22257
  if (!mpp) return null;
21935
22258
  if (mpp.method === "tempo") {
21936
22259
  try {
21937
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-JTARPYLN.js");
21938
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-3SIUYRWP.js");
22260
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-OTB2YSWE.js");
22261
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-L362ZUWL.js");
21939
22262
  const account = await connectedTempoAccount2();
21940
22263
  if (!account) {
21941
22264
  return {
@@ -22029,8 +22352,8 @@ function x402WrongAssetHint(asset) {
22029
22352
  }
22030
22353
 
22031
22354
  // src/lib/build-freshness.ts
22032
- import { existsSync as existsSync3, readdirSync, statSync } from "fs";
22033
- import { dirname as dirname2, join as join3 } from "path";
22355
+ import { existsSync as existsSync4, readdirSync, statSync } from "fs";
22356
+ import { dirname as dirname2, join as join4 } from "path";
22034
22357
  import { fileURLToPath as fileURLToPath2 } from "url";
22035
22358
  var EXTRA_SOURCES = ["package.json", "tsup.config.ts"];
22036
22359
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "__snapshots__"]);
@@ -22049,12 +22372,12 @@ function checkBuildFreshness(opts) {
22049
22372
  skipReason
22050
22373
  });
22051
22374
  if (root === null) return skipped("running_from_source");
22052
- const bundlePath = join3(root, "dist", "dvm.js");
22053
- if (dirname2(moduleDir) !== root || !existsSync3(bundlePath)) {
22375
+ const bundlePath = join4(root, "dist", "dvm.js");
22376
+ if (dirname2(moduleDir) !== root || !existsSync4(bundlePath)) {
22054
22377
  return skipped("running_from_source");
22055
22378
  }
22056
- const srcDir = join3(root, "src");
22057
- if (!existsSync3(srcDir)) return skipped("no_source_tree");
22379
+ const srcDir = join4(root, "src");
22380
+ if (!existsSync4(srcDir)) return skipped("no_source_tree");
22058
22381
  const builtAtMs = statSync(bundlePath).mtimeMs;
22059
22382
  const newer = [];
22060
22383
  let newestMs = 0;
@@ -22063,7 +22386,7 @@ function checkBuildFreshness(opts) {
22063
22386
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
22064
22387
  if (budget2.left-- <= 0) return;
22065
22388
  if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
22066
- const abs = join3(dir, entry.name);
22389
+ const abs = join4(dir, entry.name);
22067
22390
  const relPath = rel ? `${rel}/${entry.name}` : entry.name;
22068
22391
  if (entry.isDirectory()) {
22069
22392
  visit(abs, relPath, budget2);
@@ -22078,8 +22401,8 @@ function checkBuildFreshness(opts) {
22078
22401
  const budget = { left: MAX_ENTRIES };
22079
22402
  visit(srcDir, "src", budget);
22080
22403
  for (const name of EXTRA_SOURCES) {
22081
- const abs = join3(root, name);
22082
- if (!existsSync3(abs)) continue;
22404
+ const abs = join4(root, name);
22405
+ if (!existsSync4(abs)) continue;
22083
22406
  const mtimeMs = statSync(abs).mtimeMs;
22084
22407
  if (mtimeMs > newestMs) newestMs = mtimeMs;
22085
22408
  if (mtimeMs > builtAtMs) newer.push({ path: name, mtimeMs });
@@ -22097,7 +22420,7 @@ function checkBuildFreshness(opts) {
22097
22420
  function findPackageRoot(start) {
22098
22421
  let dir = start;
22099
22422
  for (; ; ) {
22100
- if (existsSync3(join3(dir, "package.json"))) return dir;
22423
+ if (existsSync4(join4(dir, "package.json"))) return dir;
22101
22424
  const parent = dirname2(dir);
22102
22425
  if (parent === dir) return null;
22103
22426
  dir = parent;
@@ -22105,25 +22428,25 @@ function findPackageRoot(start) {
22105
22428
  }
22106
22429
 
22107
22430
  // src/lib/caller-state.ts
22108
- import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
22109
- import { basename, join as join5 } from "path";
22431
+ import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync6, statSync as statSync2 } from "fs";
22432
+ import { basename, join as join6 } from "path";
22110
22433
 
22111
22434
  // src/lib/request-refusal-store.ts
22112
22435
  import {
22113
22436
  closeSync as closeSync2,
22114
- existsSync as existsSync4,
22437
+ existsSync as existsSync5,
22115
22438
  fsyncSync as fsyncSync2,
22116
22439
  openSync as openSync2,
22117
- readFileSync as readFileSync4,
22118
- renameSync as renameSync2,
22440
+ readFileSync as readFileSync5,
22441
+ renameSync as renameSync3,
22119
22442
  rmSync,
22120
- writeFileSync as writeFileSync2
22443
+ writeFileSync as writeFileSync3
22121
22444
  } from "fs";
22122
- import { join as join4 } from "path";
22123
- var REQUEST_REFUSALS_DIR = join4(CONFIG_DIR, "request-refusals");
22445
+ import { join as join5 } from "path";
22446
+ var REQUEST_REFUSALS_DIR = join5(CONFIG_DIR, "request-refusals");
22124
22447
  var SAFE_TOKEN = /^[a-z0-9_.:-]{1,64}$/;
22125
22448
  function requestIntentMayExist(requestId) {
22126
- return existsSync4(join4(REQUEST_INTENTS_DIR, requestId));
22449
+ return existsSync5(join5(REQUEST_INTENTS_DIR, requestId));
22127
22450
  }
22128
22451
  function recordRequestRefusal(requestId, refusal) {
22129
22452
  if (!isPublicRequestId(requestId) || requestIntentMayExist(requestId)) return false;
@@ -22140,12 +22463,12 @@ function recordRequestRefusal(requestId, refusal) {
22140
22463
  const temp = `${target}.${String(process.pid)}.tmp`;
22141
22464
  const fd = openSync2(temp, "w", 384);
22142
22465
  try {
22143
- writeFileSync2(fd, JSON.stringify(record2, null, 2) + "\n");
22466
+ writeFileSync3(fd, JSON.stringify(record2, null, 2) + "\n");
22144
22467
  fsyncSync2(fd);
22145
22468
  } finally {
22146
22469
  closeSync2(fd);
22147
22470
  }
22148
- renameSync2(temp, target);
22471
+ renameSync3(temp, target);
22149
22472
  } catch {
22150
22473
  }
22151
22474
  return true;
@@ -22160,7 +22483,7 @@ function clearRequestRefusal(requestId) {
22160
22483
  function loadRequestRefusal(requestId) {
22161
22484
  if (!isPublicRequestId(requestId)) return null;
22162
22485
  try {
22163
- const parsed = JSON.parse(readFileSync4(refusalPath(requestId), "utf8"));
22486
+ const parsed = JSON.parse(readFileSync5(refusalPath(requestId), "utf8"));
22164
22487
  if (parsed.v !== 1 || parsed.requestId !== requestId || typeof parsed.code !== "string" || typeof parsed.refusedAt !== "number" || parsed.reason !== void 0 && typeof parsed.reason !== "string") {
22165
22488
  return null;
22166
22489
  }
@@ -22170,20 +22493,20 @@ function loadRequestRefusal(requestId) {
22170
22493
  }
22171
22494
  }
22172
22495
  function refusalPath(requestId) {
22173
- return join4(REQUEST_REFUSALS_DIR, `${requestId}.json`);
22496
+ return join5(REQUEST_REFUSALS_DIR, `${requestId}.json`);
22174
22497
  }
22175
22498
 
22176
22499
  // src/lib/caller-state.ts
22177
22500
  function detectSetupState() {
22178
22501
  return {
22179
22502
  existingState: {
22180
- jobs: existsSync5(JOBS_FILE),
22181
- messages: existsSync5(MESSAGES_DIR)
22503
+ jobs: existsSync6(JOBS_FILE),
22504
+ messages: existsSync6(MESSAGES_DIR)
22182
22505
  },
22183
22506
  missing: {
22184
- config: !existsSync5(CONFIG_FILE),
22185
- identity: !existsSync5(IDENTITIES_FILE),
22186
- wallet: !existsSync5(WALLET_FILE)
22507
+ config: !existsSync6(CONFIG_FILE),
22508
+ identity: !existsSync6(IDENTITIES_FILE),
22509
+ wallet: !existsSync6(WALLET_FILE)
22187
22510
  }
22188
22511
  };
22189
22512
  }
@@ -22253,6 +22576,16 @@ var FILE_SPECS = [
22253
22576
  // A store written by an older dvm keeps its old mode until the next write
22254
22577
  // replaces it — doctor warns, and the write repairs it.
22255
22578
  { name: "credits", path: CREDITS_FILE, json: true, secret: true, directory: false },
22579
+ // When the prepaid-credit suggestion was last shown at each DVM. 0600 for
22580
+ // the reason the feedback cooldowns are: it records which DVMs this caller
22581
+ // pays and when.
22582
+ {
22583
+ name: "credit_suggestions",
22584
+ path: CREDIT_SUGGESTIONS_FILE,
22585
+ json: true,
22586
+ secret: true,
22587
+ directory: false
22588
+ },
22256
22589
  {
22257
22590
  name: "x402_channels",
22258
22591
  path: X402_CHANNELS_FILE,
@@ -22313,17 +22646,17 @@ function findQuarantinedCreditStores() {
22313
22646
  } catch {
22314
22647
  return [];
22315
22648
  }
22316
- 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 }));
22649
+ return entries.filter((name) => name.startsWith(prefix)).sort((a, b) => a < b ? 1 : a > b ? -1 : 0).map((name) => ({ path: join6(CONFIG_DIR, name), name }));
22317
22650
  }
22318
22651
  function checkOne(spec) {
22319
- const exists = existsSync5(spec.path);
22652
+ const exists = existsSync6(spec.path);
22320
22653
  if (!exists) {
22321
22654
  return { name: spec.name, path: spec.path, exists: false };
22322
22655
  }
22323
22656
  const row = { name: spec.name, path: spec.path, exists: true };
22324
22657
  if (spec.json) {
22325
22658
  try {
22326
- JSON.parse(readFileSync5(spec.path, "utf-8"));
22659
+ JSON.parse(readFileSync6(spec.path, "utf-8"));
22327
22660
  row.parseable = true;
22328
22661
  } catch (err) {
22329
22662
  row.parseable = false;
@@ -22352,7 +22685,7 @@ function checkSecretDirectory(dir, row) {
22352
22685
  try {
22353
22686
  const offenders = [];
22354
22687
  for (const name of readdirSync2(dir)) {
22355
- const path = join5(dir, name);
22688
+ const path = join6(dir, name);
22356
22689
  const stat2 = statSync2(path);
22357
22690
  if (!stat2.isFile()) continue;
22358
22691
  const mode = stat2.mode & 511;
@@ -22373,9 +22706,9 @@ function octalMode(mode) {
22373
22706
  return "0" + mode.toString(8).padStart(3, "0");
22374
22707
  }
22375
22708
  function readBtcRateCacheAge(now = Date.now()) {
22376
- if (!existsSync5(BTC_RATE_FILE)) return null;
22709
+ if (!existsSync6(BTC_RATE_FILE)) return null;
22377
22710
  try {
22378
- const data = JSON.parse(readFileSync5(BTC_RATE_FILE, "utf-8"));
22711
+ const data = JSON.parse(readFileSync6(BTC_RATE_FILE, "utf-8"));
22379
22712
  if (typeof data.timestamp !== "number") return null;
22380
22713
  return { ageMs: now - data.timestamp };
22381
22714
  } catch {
@@ -22385,7 +22718,7 @@ function readBtcRateCacheAge(now = Date.now()) {
22385
22718
 
22386
22719
  // src/lib/mnemonic-backups.ts
22387
22720
  import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
22388
- import { basename as basename2, dirname as dirname3, join as join6 } from "path";
22721
+ import { basename as basename2, dirname as dirname3, join as join7 } from "path";
22389
22722
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
22390
22723
  const dir = dirname3(mnemonicFile);
22391
22724
  const prefix = `${basename2(mnemonicFile)}.`;
@@ -22397,7 +22730,7 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
22397
22730
  throw err;
22398
22731
  }
22399
22732
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
22400
- const path = join6(dir, name);
22733
+ const path = join7(dir, name);
22401
22734
  const stat2 = statSync3(path);
22402
22735
  if (!stat2.isFile()) return null;
22403
22736
  const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
@@ -24293,11 +24626,11 @@ async function favRm(name, opts) {
24293
24626
  }
24294
24627
 
24295
24628
  // src/lib/byte-source.ts
24296
- import { readFileSync as readFileSync6 } from "fs";
24629
+ import { readFileSync as readFileSync7 } from "fs";
24297
24630
  import { resolve as resolve2 } from "path";
24298
24631
  var STDIN_TIMEOUT_MS2 = 1e4;
24299
24632
  function readFileText(path) {
24300
- return readFileSync6(resolve2(path), "utf-8");
24633
+ return readFileSync7(resolve2(path), "utf-8");
24301
24634
  }
24302
24635
  var StdinTimeoutError = class extends Error {
24303
24636
  constructor(timeoutMs) {
@@ -24461,7 +24794,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
24461
24794
  }
24462
24795
 
24463
24796
  // src/lib/feedback-nudges.ts
24464
- import { existsSync as existsSync6, readFileSync as readFileSync7, renameSync as renameSync3, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
24797
+ import { existsSync as existsSync7, readFileSync as readFileSync8, renameSync as renameSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs";
24465
24798
 
24466
24799
  // src/lib/feedback-notice.ts
24467
24800
  function buildFeedbackNudge(args) {
@@ -24513,10 +24846,10 @@ function effectiveFeedbackPosture(config2) {
24513
24846
  return { posture: DEFAULT_FEEDBACK_POSTURE, source: "default" };
24514
24847
  }
24515
24848
  function loadFeedbackNudgeState() {
24516
- if (!existsSync6(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
24849
+ if (!existsSync7(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
24517
24850
  try {
24518
24851
  const parsed = JSON.parse(
24519
- readFileSync7(FEEDBACK_NUDGES_FILE, "utf-8")
24852
+ readFileSync8(FEEDBACK_NUDGES_FILE, "utf-8")
24520
24853
  );
24521
24854
  return {
24522
24855
  ...typeof parsed.introShownAt === "string" ? { introShownAt: parsed.introShownAt } : {},
@@ -24533,7 +24866,7 @@ function recordFeedbackSent(dvmId, now = Date.now()) {
24533
24866
  ...state.perDvm[dvmId] ?? {},
24534
24867
  lastSentAt: new Date(now).toISOString()
24535
24868
  };
24536
- saveState(state);
24869
+ saveState2(state);
24537
24870
  } catch {
24538
24871
  }
24539
24872
  }
@@ -24566,7 +24899,7 @@ function noteFeedbackAfterTerminal(moment) {
24566
24899
  ...code === "feedback_first_success" ? { firstSuccessNudgedAt: stamp } : {}
24567
24900
  };
24568
24901
  if (intro) state.introShownAt = stamp;
24569
- saveState(state);
24902
+ saveState2(state);
24570
24903
  return;
24571
24904
  }
24572
24905
  if (moment.status === "completed") {
@@ -24602,15 +24935,15 @@ function coercePerDvm(perDvm) {
24602
24935
  )
24603
24936
  );
24604
24937
  }
24605
- function saveState(state) {
24938
+ function saveState2(state) {
24606
24939
  ensureConfigDir();
24607
24940
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
24608
- writeFileSync3(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
24941
+ writeFileSync4(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
24609
24942
  try {
24610
- renameSync3(tmp, FEEDBACK_NUDGES_FILE);
24943
+ renameSync4(tmp, FEEDBACK_NUDGES_FILE);
24611
24944
  } catch (err) {
24612
24945
  try {
24613
- unlinkSync(tmp);
24946
+ unlinkSync2(tmp);
24614
24947
  } catch {
24615
24948
  }
24616
24949
  throw err;
@@ -24619,9 +24952,9 @@ function saveState(state) {
24619
24952
  var nudgedThisInvocation = false;
24620
24953
 
24621
24954
  // src/lib/platform.ts
24622
- import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
24955
+ import { existsSync as existsSync8, mkdirSync as mkdirSync2, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
24623
24956
  import { homedir as homedir2 } from "os";
24624
- import { join as join7 } from "path";
24957
+ import { join as join8 } from "path";
24625
24958
  function getPlatformUrl() {
24626
24959
  return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
24627
24960
  }
@@ -25195,11 +25528,11 @@ import {
25195
25528
  openSync as openSync3,
25196
25529
  readdirSync as readdirSync4,
25197
25530
  rmdirSync,
25198
- unlinkSync as unlinkSync2,
25199
- writeFileSync as writeFileSync5
25531
+ unlinkSync as unlinkSync3,
25532
+ writeFileSync as writeFileSync6
25200
25533
  } from "fs";
25201
25534
  import { tmpdir } from "os";
25202
- import { join as join8 } from "path";
25535
+ import { join as join9 } from "path";
25203
25536
 
25204
25537
  // src/lib/mime-ext.ts
25205
25538
  var MIME_TO_EXT = {
@@ -25255,10 +25588,10 @@ var ArtifactSaveSession = class {
25255
25588
  let created = false;
25256
25589
  try {
25257
25590
  const directory = this.ensureDirectory();
25258
- path = join8(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
25591
+ path = join9(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
25259
25592
  fd = openSync3(path, "wx", FILE_MODE);
25260
25593
  created = true;
25261
- writeFileSync5(fd, buf);
25594
+ writeFileSync6(fd, buf);
25262
25595
  closeSync3(fd);
25263
25596
  fd = void 0;
25264
25597
  chmodSync(path, FILE_MODE);
@@ -25273,7 +25606,7 @@ var ArtifactSaveSession = class {
25273
25606
  }
25274
25607
  if (created && path) {
25275
25608
  try {
25276
- unlinkSync2(path);
25609
+ unlinkSync3(path);
25277
25610
  } catch {
25278
25611
  }
25279
25612
  }
@@ -25284,7 +25617,7 @@ var ArtifactSaveSession = class {
25284
25617
  }
25285
25618
  ensureDirectory() {
25286
25619
  if (this.directory) return this.directory;
25287
- const directory = mkdtempSync(join8(tmpdir(), "dvm-artifacts-"));
25620
+ const directory = mkdtempSync(join9(tmpdir(), "dvm-artifacts-"));
25288
25621
  try {
25289
25622
  chmodSync(directory, DIRECTORY_MODE);
25290
25623
  } catch (err) {
@@ -25420,9 +25753,12 @@ function nextActionHuman(action) {
25420
25753
  if (action.type === "respond") {
25421
25754
  return `Next: ${display} Provider is waiting for your input. ${command ? `Run \`${command}\`.` : action.hint}`;
25422
25755
  }
25756
+ if (command?.startsWith("dvm decline ")) return `Next: ${display} ${action.hint}`;
25423
25757
  const thresholdHint = action.hint.match(/ For the next run, use --auto-pay-below .+$/)?.[0] ?? "";
25424
- const decline2 = action.charged_if_declined_micro !== void 0 && command?.startsWith("dvm pay ") ? ` To stop instead, run \`dvm decline ${shellQuoteArg(action.job_id)}\`.` : "";
25425
- return `Next: Payment required to continue: ${display}${display.endsWith(".") ? "" : "."} Run \`${command ?? `dvm pay ${shellQuoteArg(action.job_id)}`}\`.${decline2}${thresholdHint}`;
25758
+ const budgetChange = command?.includes(" --budget ");
25759
+ const approval = budgetChange ? "Ask your human to approve the new total first, then run" : "Run";
25760
+ const decline2 = (action.charged_if_declined_micro !== void 0 || budgetChange) && command?.startsWith("dvm pay ") ? ` To stop instead, run \`dvm decline ${shellQuoteArg(action.job_id)}\`.` : "";
25761
+ return `Next: Payment required to continue: ${display}${display.endsWith(".") ? "" : "."} ${approval} \`${command ?? `dvm pay ${shellQuoteArg(action.job_id)}`}\`.${decline2}${thresholdHint}`;
25426
25762
  }
25427
25763
  case "poll": {
25428
25764
  const hint = typeof action.hint === "string" ? action.hint : action.hint.text;
@@ -25457,8 +25793,68 @@ function readNextAction(jobId, messages2, options = {}) {
25457
25793
  return action;
25458
25794
  }
25459
25795
 
25796
+ // src/lib/wait-payment-lines.ts
25797
+ function createWaitPaymentLines(opts) {
25798
+ const report = opts.onAutoPayment;
25799
+ const emitted = /* @__PURE__ */ new Set();
25800
+ const reported = /* @__PURE__ */ new Set();
25801
+ const waiting = /* @__PURE__ */ new Map();
25802
+ function write(payment, seq, force = false) {
25803
+ if (reported.has(seq)) return;
25804
+ if (!force && seq > opts.afterSeq && !emitted.has(seq)) {
25805
+ waiting.set(seq, payment);
25806
+ return;
25807
+ }
25808
+ waiting.delete(seq);
25809
+ reported.add(seq);
25810
+ report?.(payment, seq);
25811
+ }
25812
+ const stop = report ? observePaymentBookings((booking) => {
25813
+ if (booking.jobId === opts.jobId && booking.approval === "auto") write(bookedPayment(booking), booking.requestSeq);
25814
+ }) : () => void 0;
25815
+ return {
25816
+ onMessage(message2) {
25817
+ opts.onMessage?.(message2);
25818
+ emitted.add(message2.seq);
25819
+ const pending4 = waiting.get(message2.seq);
25820
+ if (pending4) write(pending4, message2.seq);
25821
+ },
25822
+ onAutoPayment: write,
25823
+ finish() {
25824
+ stop();
25825
+ for (const seq of [...waiting.keys()].sort((a, b) => a - b)) write(waiting.get(seq), seq, true);
25826
+ }
25827
+ };
25828
+ }
25829
+ function bookedPayment(booking) {
25830
+ const ask = loadMessages(booking.jobId).find((message2) => message2.seq === booking.requestSeq && message2.type === "payment-request");
25831
+ const content = ask?.type === "payment-request" ? ask.content : void 0;
25832
+ const paid = {
25833
+ status: "paid",
25834
+ rail: booking.rail,
25835
+ amountMsats: booking.amountMsats,
25836
+ ...booking.amountUsdcMicro !== void 0 ? { amountUsdcMicro: booking.amountUsdcMicro } : {}
25837
+ };
25838
+ return {
25839
+ amount_msats: booking.amountMsats,
25840
+ rail: booking.rail,
25841
+ reason: asProviderText(booking.reason ?? content?.reason ?? ""),
25842
+ ...booking.amountUsdcMicro !== void 0 ? { amount_usdc_microunits: booking.amountUsdcMicro } : {},
25843
+ display: paidConfirmationDisplay(paid, content?.fiat_amount)
25844
+ };
25845
+ }
25846
+
25460
25847
  // src/lib/wait-for-job.ts
25461
25848
  async function waitForJob(opts, durationMs, now = Date.now) {
25849
+ if (!opts.onAutoPayment) return waitAttached(opts, durationMs, now);
25850
+ const payments = createWaitPaymentLines(opts);
25851
+ try {
25852
+ return await waitAttached({ ...opts, onMessage: payments.onMessage, onAutoPayment: payments.onAutoPayment }, durationMs, now);
25853
+ } finally {
25854
+ payments.finish();
25855
+ }
25856
+ }
25857
+ async function waitAttached(opts, durationMs, now) {
25462
25858
  const deadline = now() + durationMs;
25463
25859
  const result = {
25464
25860
  messages: [],
@@ -25483,6 +25879,8 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25483
25879
  const messageAppendSession = opts.persistLocalState === false ? void 0 : opts.messageAppendSession ?? createMessageAppendSession(opts.jobId);
25484
25880
  let backoffMs = 1e3;
25485
25881
  let firstRead = true;
25882
+ let paymentInFlight = false;
25883
+ let seenRunning = false;
25486
25884
  const idleTimeoutMs = opts.timeoutMs ?? JOB_READ_TIMEOUT_MS;
25487
25885
  async function readWithRetry(read) {
25488
25886
  while (now() < deadline) {
@@ -25500,6 +25898,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25500
25898
  const readOptions = () => ({ jobToken: opts.jobToken, timeoutMs: Math.max(1, Math.min(idleTimeoutMs, deadline - now())) });
25501
25899
  const snapshot = await readWithRetry(() => opts.transport.status(opts.jobId, opts.provider, readOptions()));
25502
25900
  if (!snapshot) break;
25901
+ seenRunning = !isTerminalJobStatus(snapshot.status);
25503
25902
  if (isTerminalJobStatus(snapshot.status)) {
25504
25903
  result.providerStatus = snapshot;
25505
25904
  result.nextAction = null;
@@ -25566,6 +25965,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25566
25965
  }
25567
25966
  if (unresolved && !newerYield) {
25568
25967
  result.nextAction = pollNextAction(opts.jobId);
25968
+ paymentInFlight = true;
25569
25969
  await new Promise((resolve3) => setTimeout(resolve3, Math.min(retryDelayMs, Math.max(0, deadline - now()))));
25570
25970
  backoffMs = Math.min(backoffMs * 2, 3e4);
25571
25971
  continue;
@@ -25590,6 +25990,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25590
25990
  const progressed = next.cursor > result.cursor;
25591
25991
  result.cursor = Math.min(next.cursor, cursorLimit);
25592
25992
  result.nextAction = next.nextAction;
25993
+ paymentInFlight = next.paymentInFlight === true;
25593
25994
  if (hasUnsavedJobState() || next.nextAction?.type !== "poll") break;
25594
25995
  if (progressed) backoffMs = 1e3;
25595
25996
  const delay = Math.min(backoffMs, Math.max(0, deadline - now()));
@@ -25601,8 +26002,27 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25601
26002
  result.cursor = Math.min(result.cursor, ...remaining.map((seq) => seq - 1));
25602
26003
  }
25603
26004
  result.messages.sort((a, b) => a.seq - b.seq);
26005
+ if (now() >= deadline && result.nextAction?.type === "poll" && !hasUnsavedJobState())
26006
+ result.nextAction = waitLimitAction(opts, durationMs, result.nextAction, { paymentInFlight, seenRunning });
25604
26007
  return result;
25605
26008
  }
26009
+ function waitLimitAction(opts, durationMs, current, state) {
26010
+ const { jobId } = opts;
26011
+ const limit = formatDurationMs(durationMs);
26012
+ const job = opts.persistLocalState === false ? void 0 : loadJob(jobId);
26013
+ const answered = job ? loadAnsweredYieldSeqs(jobId) : /* @__PURE__ */ new Set();
26014
+ const heldSeq = job?.inFlightPaymentRequestSeqs?.[0] ?? Object.keys(job?.unconfirmedPaymentSubmissions ?? {}).map(Number).find((seq) => !answered.has(seq));
26015
+ if (heldSeq !== void 0)
26016
+ return pollNextAction(jobId, `The wait limit (${limit}) was reached while an earlier payment for this job is unconfirmed. ` + paymentInFlightHint(jobId, job, heldSeq));
26017
+ if (state.paymentInFlight) return current;
26018
+ const arg = guidanceJobArg(jobId);
26019
+ if (!state.seenRunning)
26020
+ return pollNextAction(jobId, `The wait limit (${limit}) passed before this job could be read, so its state is unknown. Check it with \`dvm status ${arg}\`, or keep watching with \`dvm messages ${arg} --wait\`.`);
26021
+ return {
26022
+ ...pollNextAction(jobId, `The wait limit (${limit}) was reached and the job was still running when last read. Keep watching with \`dvm messages ${arg} --wait --until ${limit}\`.`),
26023
+ ...current.estimate_seconds !== void 0 ? { estimate_seconds: current.estimate_seconds } : {}
26024
+ };
26025
+ }
25606
26026
 
25607
26027
  // src/commands/messages.ts
25608
26028
  async function messages(jobId, opts) {
@@ -25672,7 +26092,7 @@ async function messagesWithAccess(jobId, opts, access) {
25672
26092
  const content2 = jobContentFields(jobId, providerStatus2, opts.human);
25673
26093
  const resolvedAction2 = await resolveNextAction2(nextAction, msgs, providerStatus2?.status);
25674
26094
  const currency2 = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus2?.receipt, status: providerStatus2, messages: msgs, transport, ref }) : void 0;
25675
- const settlement2 = observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden, currency2);
26095
+ const settlement2 = await observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden, currency2);
25676
26096
  transport.close();
25677
26097
  if (opts.human) {
25678
26098
  renderSettlementHuman(settlement2);
@@ -25700,6 +26120,13 @@ async function messagesWithAccess(jobId, opts, access) {
25700
26120
  return;
25701
26121
  }
25702
26122
  progressNotice("Streaming messages...", opts.human);
26123
+ const streamEvents = opts.wait === true && !opts.human;
26124
+ const recordDelivery = streamEvents && !access.endpointOverridden;
26125
+ const delivered = recordDelivery ? stored?.waitDeliveredSeq ?? 0 : 0;
26126
+ const skipThrough = opts.after === void 0 ? delivered : 0;
26127
+ let lastDelivered = delivered;
26128
+ let messageLines = 0;
26129
+ let paymentLines = 0;
25703
26130
  const streamOptions = {
25704
26131
  jobId,
25705
26132
  transport,
@@ -25714,6 +26141,18 @@ async function messagesWithAccess(jobId, opts, access) {
25714
26141
  onMessage: (msg) => {
25715
26142
  if (msg.type === "progress") formatMessageHuman(msg);
25716
26143
  }
26144
+ },
26145
+ ...streamEvents && {
26146
+ onMessage: (msg) => {
26147
+ if (msg.seq <= skipThrough && !((msg.type === "payment-request" || msg.type === "prompt") && !loadAnsweredYieldSeqs(jobId).has(msg.seq))) return;
26148
+ jsonEvent({ event: "message", ...serialize(msg) });
26149
+ messageLines++;
26150
+ lastDelivered = Math.max(lastDelivered, msg.seq);
26151
+ },
26152
+ onAutoPayment: (payment) => {
26153
+ jsonEvent({ event: "payment", ...payment });
26154
+ paymentLines++;
26155
+ }
25717
26156
  }
25718
26157
  };
25719
26158
  const waitDeadline = waitDuration === void 0 ? void 0 : Date.now() + waitDuration;
@@ -25723,6 +26162,13 @@ async function messagesWithAccess(jobId, opts, access) {
25723
26162
  } catch (err) {
25724
26163
  transport.close();
25725
26164
  throw err;
26165
+ } finally {
26166
+ if (recordDelivery && lastDelivered > delivered) {
26167
+ try {
26168
+ if (lastDelivered > (loadJob(jobId)?.waitDeliveredSeq ?? 0)) updateObservedJob(jobId, { waitDeliveredSeq: lastDelivered });
26169
+ } catch {
26170
+ }
26171
+ }
25726
26172
  }
25727
26173
  const providerStatus = waitDeadline !== void 0 && Date.now() >= waitDeadline ? void 0 : await observeJobContent(jobId, transport, ref, {
25728
26174
  timeoutMs: waitDeadline === void 0 ? opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now())),
@@ -25741,7 +26187,7 @@ async function messagesWithAccess(jobId, opts, access) {
25741
26187
  const resolvedAction = await resolveNextAction2(result.nextAction, result.messages, providerStatus?.status ?? result.providerStatus?.status);
25742
26188
  const observed = providerStatus ?? result.providerStatus;
25743
26189
  const currency = access.endpointOverridden ? await providerCurrency({ receipt: observed?.receipt, status: observed, messages: result.messages, transport, ref }) : void 0;
25744
- const settlement = observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
26190
+ const settlement = await observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
25745
26191
  transport.close();
25746
26192
  if (opts.human) {
25747
26193
  renderSettlementHuman(settlement);
@@ -25756,6 +26202,18 @@ async function messagesWithAccess(jobId, opts, access) {
25756
26202
  finalizeProgressLine();
25757
26203
  }
25758
26204
  printNextActionHuman(resolvedAction, { refunds: result.refunds });
26205
+ } else if (streamEvents) {
26206
+ json3({
26207
+ event: "result",
26208
+ jobId,
26209
+ ...content,
26210
+ ...settlement,
26211
+ message_count: messageLines,
26212
+ auto_payment_count: paymentLines,
26213
+ cursor: result.cursor,
26214
+ next_action: resolvedAction,
26215
+ ...await refundJsonField(result.refunds)
26216
+ });
25759
26217
  } else {
25760
26218
  json3({
25761
26219
  jobId,
@@ -25924,7 +26382,7 @@ async function messageWithAccess(jobId, text, opts, access) {
25924
26382
  }
25925
26383
  const content = jobContentFields(jobId, providerStatus, opts.human);
25926
26384
  const currency = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus?.receipt, status: providerStatus, messages: result.messages, transport, ref }) : void 0;
25927
- const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
26385
+ const settlement = await observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
25928
26386
  transport.close();
25929
26387
  if (opts.human) {
25930
26388
  renderSettlementHuman(settlement);
@@ -26083,11 +26541,20 @@ async function payWithAccess(jobId, opts, access) {
26083
26541
  maxCashuPrincipalSats,
26084
26542
  requestSeq,
26085
26543
  approval: "explicit",
26086
- creditRecoveryOnly: pending4 !== void 0
26544
+ creditRecoveryOnly: pending4 !== void 0,
26545
+ budget: opts.budget,
26546
+ useStoredPolicy: true
26087
26547
  });
26088
26548
  if (result === "over-budget") {
26089
26549
  transport.close();
26090
- throw new DvmError("over_budget", "Payment would exceed the job's budget.");
26550
+ const refusal = requestSeq === void 0 ? void 0 : loadJob(jobId)?.budgetRefusals?.[String(requestSeq)];
26551
+ const current = loadJob(jobId);
26552
+ const countHint = current?.policy && (current.paymentsHonoured ?? 0) >= current.policy.maxPayments ? paymentCountHint(jobId, current.policy.maxPayments) : void 0;
26553
+ throw new DvmError(
26554
+ "over_budget",
26555
+ "Payment would exceed the job's budget.",
26556
+ countHint ?? (refusal ? overBudgetHint(jobId, describeBudgetOverrun(refusal, loadJob(jobId)?.policy)) : void 0)
26557
+ );
26091
26558
  }
26092
26559
  if (result === "payment-cap-exceeded") {
26093
26560
  transport.close();
@@ -26095,7 +26562,7 @@ async function payWithAccess(jobId, opts, access) {
26095
26562
  throw new DvmError(
26096
26563
  "payment_cap_exceeded",
26097
26564
  "Job has reached its maximum payment count.",
26098
- `The provider has sent more payment-requests than --max-payments allows. Inspect with 'dvm messages ${jobId}' and 'dvm cancel ${jobId}' if unintended. Raise with '--max-payments ${cap2 + 1}' or investigate why this provider is asking for many small payments.`,
26565
+ paymentCountHint(jobId, cap2),
26099
26566
  {
26100
26567
  anchor: "max_payments_exceeded",
26101
26568
  display: `Payment cap reached (${cap2} payment${cap2 === 1 ? "" : "s"})`,
@@ -26116,7 +26583,7 @@ async function payWithAccess(jobId, opts, access) {
26116
26583
  jobId,
26117
26584
  transport,
26118
26585
  provider: ref,
26119
- policy: stored.policy,
26586
+ policy: loadJob(jobId)?.policy ?? stored.policy,
26120
26587
  afterSeq,
26121
26588
  timeoutMs,
26122
26589
  jobToken,
@@ -26141,7 +26608,7 @@ async function payWithAccess(jobId, opts, access) {
26141
26608
  });
26142
26609
  }
26143
26610
  const currency = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus?.receipt, status: providerStatus, messages: streamResult.messages, transport, ref }) : void 0;
26144
- const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
26611
+ const settlement = await observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
26145
26612
  transport.close();
26146
26613
  const identifier = stored.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
26147
26614
  if (opts.human) {
@@ -26218,28 +26685,6 @@ function parsePositiveCashuSats(raw2) {
26218
26685
  return value;
26219
26686
  }
26220
26687
 
26221
- // src/lib/policy.ts
26222
- function buildPolicy(opts, btcRate) {
26223
- if (opts.maxPayments === void 0) {
26224
- throw new DvmError(
26225
- "missing_max_payments",
26226
- "Cannot build a spending policy without a payment count cap.",
26227
- "Pass --max-payments <n> on dvm request. Use 0 for free jobs, 1 for typical paid jobs, or higher for multi-turn flows that may require progressive payments."
26228
- );
26229
- }
26230
- if (!Number.isInteger(opts.maxPayments) || opts.maxPayments < 0) {
26231
- throw new DvmError(
26232
- "invalid_max_payments",
26233
- "Invalid value for --max-payments.",
26234
- "Pass a non-negative integer (e.g. --max-payments 1)."
26235
- );
26236
- }
26237
- const maxTotalMsats = opts.budget ? parseBudget(opts.budget, btcRate) : 0;
26238
- const autoPayBelowMsats = opts.autoPayBelow ? parseBudget(opts.autoPayBelow, btcRate) : Math.floor(maxTotalMsats * 0.2);
26239
- const maxIncrementMsats = opts.maxIncrement ? parseBudget(opts.maxIncrement, btcRate) : maxTotalMsats;
26240
- return { maxTotalMsats, autoPayBelowMsats, maxIncrementMsats, maxPayments: opts.maxPayments };
26241
- }
26242
-
26243
26688
  // src/lib/auto-pay-warning.ts
26244
26689
  function positive(value) {
26245
26690
  return typeof value === "number" && Number.isFinite(value) && value > 0;
@@ -27237,46 +27682,6 @@ function hintForUnconfigured(flag, _hasOther) {
27237
27682
  }
27238
27683
  }
27239
27684
 
27240
- // src/lib/quote-limit.ts
27241
- function quoteWithinDeclaredLimit(quote2, limitMsats, declaredLimit, rail) {
27242
- const native = quoteWithinNativeDollarLimit(quote2, declaredLimit, rail);
27243
- return native ?? quote2.priceMsats <= limitMsats;
27244
- }
27245
- function quoteWithinNativeDollarLimit(quote2, declaredLimit, rail) {
27246
- const normalizedRail = rail?.trim().toLowerCase();
27247
- if (normalizedRail === "x402") {
27248
- const native = x402QuoteWithinDollarLimit(quote2, declaredLimit);
27249
- if (native !== void 0) return native;
27250
- }
27251
- const upfront = upfrontQuoteWithinDollarLimit(quote2, declaredLimit);
27252
- if (normalizedRail === "tempo" && declaredLimit?.trim().startsWith("$")) {
27253
- return upfront ?? false;
27254
- }
27255
- return upfront;
27256
- }
27257
- function x402QuoteWithinDollarLimit(quote2, declaredLimit) {
27258
- if (!declaredLimit || !quote2.requiredUsdcMicro) return void 0;
27259
- const limitMicro = dollarLimitMicro(declaredLimit);
27260
- if (limitMicro === void 0 || !/^\d+$/.test(quote2.requiredUsdcMicro)) return void 0;
27261
- return BigInt(quote2.requiredUsdcMicro) <= limitMicro;
27262
- }
27263
- function upfrontQuoteWithinDollarLimit(quote2, declaredLimit) {
27264
- if (!declaredLimit?.trim().startsWith("$")) return void 0;
27265
- const limitMicro = dollarLimitMicro(declaredLimit);
27266
- const amountMicro = quote2.upfront?.amount_micro;
27267
- if (limitMicro === void 0 || quote2.upfront?.currency !== "usd" || amountMicro === void 0 || !Number.isSafeInteger(amountMicro) || amountMicro <= 0) {
27268
- return void 0;
27269
- }
27270
- return BigInt(amountMicro) <= limitMicro;
27271
- }
27272
- function dollarLimitMicro(declaredLimit) {
27273
- const amount = /^\$(\d+)(?:\.(\d{1,6}))?$/.exec(declaredLimit.trim());
27274
- if (!amount) return void 0;
27275
- const whole = BigInt(amount[1]);
27276
- const fraction = BigInt((amount[2] || "").padEnd(6, "0"));
27277
- return whole * 1000000n + fraction;
27278
- }
27279
-
27280
27685
  // src/lib/wallet-agent/balance.ts
27281
27686
  function groupProofsByMint(proofs) {
27282
27687
  const out = /* @__PURE__ */ new Map();
@@ -28102,7 +28507,7 @@ async function requestWithWarnings(opts, stage) {
28102
28507
  console.log(receipt.summary);
28103
28508
  const hint = nextStepHint(receipt.jobId, receipt.payloadIn, receipt.artifactCount, true);
28104
28509
  if (hint) info(`\u{1F4CE} ${hint}`);
28105
- renderReceiptHuman(captured, receipt.jobId);
28510
+ await renderReceiptHuman(captured, receipt.jobId);
28106
28511
  echoTraceIdHuman();
28107
28512
  } else {
28108
28513
  providerJobJson({
@@ -28113,7 +28518,7 @@ async function requestWithWarnings(opts, stage) {
28113
28518
  summary: receipt.summary,
28114
28519
  _provider_fields: ["summary"],
28115
28520
  ...buildCompletionHintFields(receipt.jobId, receipt),
28116
- ...receiptJsonFields(captured, receipt.jobId),
28521
+ ...await receiptJsonFields(captured, receipt.jobId),
28117
28522
  ...takeCreditNoticeFields(),
28118
28523
  ...takeFeedbackNoticeFields(),
28119
28524
  next_action: null
@@ -28182,8 +28587,8 @@ async function requestWithWarnings(opts, stage) {
28182
28587
  const hint = nextStepHint(receipt.jobId, completion.payloadIn, completion.artifactCount, true);
28183
28588
  if (hint) info(`\u{1F4CE} ${hint}`);
28184
28589
  }
28185
- if (captured) renderReceiptHuman(captured, receipt.jobId);
28186
- else renderSettlementHuman(terminalSettlementFields(receipt.jobId));
28590
+ if (captured) await renderReceiptHuman(captured, receipt.jobId);
28591
+ else renderSettlementHuman(await terminalSettlementReport(receipt.jobId));
28187
28592
  finalizeProgressLine();
28188
28593
  echoTraceIdHuman();
28189
28594
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: isTerminalJobStatus(receipt.status) || !!streamTerminalStatus(result.messages) });
@@ -28207,7 +28612,7 @@ async function requestWithWarnings(opts, stage) {
28207
28612
  ...completion?.message !== void 0 ? ["message"] : []
28208
28613
  ],
28209
28614
  ...completion ? buildCompletionHintFields(receipt.jobId, completion) : {},
28210
- ...captured ? receiptJsonFields(captured, receipt.jobId) : terminalSettlementFields(receipt.jobId),
28615
+ ...captured ? await receiptJsonFields(captured, receipt.jobId) : await terminalSettlementReport(receipt.jobId),
28211
28616
  ...takeCreditNoticeFields(),
28212
28617
  ...takeFeedbackNoticeFields(),
28213
28618
  next_action: result.nextAction,
@@ -28249,15 +28654,16 @@ async function requestWithWarnings(opts, stage) {
28249
28654
  human: opts.human
28250
28655
  });
28251
28656
  transport.close();
28657
+ const report = await terminalSettlementReport(receipt.jobId, { receipt: captured.receipt });
28252
28658
  if (opts.human) {
28253
28659
  for (const msg of failureMessages) {
28254
28660
  formatMessageHuman(msg, receipt.jobId, artifactSession);
28255
28661
  }
28256
- renderReceiptHuman(captured, receipt.jobId);
28662
+ await renderReceiptHuman(captured, receipt.jobId, report);
28257
28663
  }
28258
28664
  throw new DvmError(terminalStatus === "failed" ? "job_failed" : "cancelled", completion?.message ?? `Job ${terminalStatus}.`, void 0, {
28259
28665
  status: terminalStatus,
28260
- ...receiptJsonFields(captured, receipt.jobId),
28666
+ ...await receiptJsonFields(captured, receipt.jobId, report),
28261
28667
  ...failureMessages.length > 0 ? { messages: failureMessages.map(serializeMessageForOutput) } : {}
28262
28668
  }, void 0, completion?.message !== void 0 ? { message: "provider" } : void 0);
28263
28669
  }
@@ -28641,7 +29047,7 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
28641
29047
  if (plan.mode === "none" && plan.suppressed) {
28642
29048
  const posture = effectiveCreditPosture(loadConfig()?.credit, ref.endpoint, attestedIdentity);
28643
29049
  const priceMicro = planRate > 0 ? msatsToMicro(chosen.priceMsats, planRate) : 0;
28644
- noteCreditSuggestion(
29050
+ stageCreditSuggestion(
28645
29051
  buildCreditSuggestion({
28646
29052
  dvm: identity.dvmId ?? ref.endpoint,
28647
29053
  endpoint: ref.endpoint,
@@ -28862,6 +29268,13 @@ function floatUsable() {
28862
29268
  return false;
28863
29269
  }
28864
29270
  }
29271
+ function cashuUpfrontPayment(chosen, btcRate) {
29272
+ return upfrontRailPayment("cashu", chosen.priceMsats, dollarBoundUsdMicro({
29273
+ msats: chosen.priceMsats,
29274
+ usdMicro: usdMicro(chosen.upfront?.amount_micro, chosen.upfront?.currency),
29275
+ rate: btcRate
29276
+ }));
29277
+ }
28865
29278
  function buildSpendLabel(capability, input) {
28866
29279
  return input.length > 0 ? `${capability} \xB7 ${input.length.toLocaleString("en-US")} chars` : capability;
28867
29280
  }
@@ -28977,7 +29390,8 @@ async function payWithTempo(args, credential) {
28977
29390
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
28978
29391
  const usdcMicroUnits = Number(tempoCredentialAmountMicro(credential));
28979
29392
  const paidMsats = usdcToMsats(usdcMicroUnits / 1e6, btcRate);
28980
- if (opts.requestId) recordRequestRailPayment(opts.requestId, { method: "tempo", amountMsats: paidMsats });
29393
+ const railPayment = upfrontRailPayment("tempo", paidMsats, usdMicro(usdcMicroUnits, "usd"));
29394
+ if (opts.requestId) recordRequestRailPayment(opts.requestId, railPayment);
28981
29395
  const usd2 = usdcMicroUnits / 1e6;
28982
29396
  const priceLabel = `$${formatUsd(usd2)} USDC`;
28983
29397
  const accountShort = `${account.address.slice(0, 6)}\u2026${account.address.slice(-4)}`;
@@ -29072,7 +29486,7 @@ async function payWithTempo(args, credential) {
29072
29486
  `Verify the Tempo account has at least the quoted amount in ${asset?.label ?? "the rail's settlement token"} on ${tempoNetworkLabel(network)} (chain ${String(chain.chainId)}).${asset ? ` ${tempoWrongAssetHint(asset)}` : ""}`
29073
29487
  );
29074
29488
  }
29075
- recordUpfrontRailPayment(effectiveJobId, { method: "tempo", amountMsats: paidMsats }, true);
29489
+ recordUpfrontRailPayment(effectiveJobId, railPayment, true);
29076
29490
  recordSpend({
29077
29491
  msats: paidMsats,
29078
29492
  btcRate: args.btcRate,
@@ -29081,6 +29495,7 @@ async function payWithTempo(args, credential) {
29081
29495
  label: buildSpendLabel(identity.capability, envelope.input)
29082
29496
  });
29083
29497
  if (receipt.status === "completed" && receipt.summary) {
29498
+ commitCreditSuggestion();
29084
29499
  markJobTerminal(effectiveJobId, "completed", completionSnapshot(receipt), {
29085
29500
  costMsats: paidMsats,
29086
29501
  paymentMethod: "tempo"
@@ -29107,7 +29522,7 @@ async function payWithTempo(args, credential) {
29107
29522
  console.log(receipt.summary);
29108
29523
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
29109
29524
  if (hint) info(`\u{1F4CE} ${hint}`);
29110
- renderReceiptHuman(captured, effectiveJobId);
29525
+ await renderReceiptHuman(captured, effectiveJobId);
29111
29526
  } else {
29112
29527
  providerJobJson({
29113
29528
  jobId: effectiveJobId,
@@ -29117,7 +29532,7 @@ async function payWithTempo(args, credential) {
29117
29532
  summary: receipt.summary,
29118
29533
  _provider_fields: ["summary"],
29119
29534
  ...buildCompletionHintFields(effectiveJobId, receipt),
29120
- ...receiptJsonFields(captured, effectiveJobId),
29535
+ ...await receiptJsonFields(captured, effectiveJobId),
29121
29536
  paidWith: "tempo",
29122
29537
  account: account.address,
29123
29538
  ...takeCreditNoticeFields(),
@@ -29331,7 +29746,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
29331
29746
  const priceSats = Math.ceil(chosen.priceMsats / 1e3);
29332
29747
  const maxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
29333
29748
  const baseContext = {
29334
- upfront_rail_payment: { method: "cashu", amountMsats: chosen.priceMsats },
29749
+ upfront_rail_payment: cashuUpfrontPayment(chosen, btcRate),
29335
29750
  dvm_id: identity.dvmId,
29336
29751
  capability: identity.capability,
29337
29752
  pinned_mint: opts.mint,
@@ -29460,7 +29875,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
29460
29875
  });
29461
29876
  }
29462
29877
  const pricedRequestId = opts.requestId ?? generatedRequestId;
29463
- if (pricedRequestId) recordRequestRailPayment(pricedRequestId, { method: "cashu", amountMsats: chosen.priceMsats });
29878
+ if (pricedRequestId) recordRequestRailPayment(pricedRequestId, cashuUpfrontPayment(chosen, btcRate));
29464
29879
  if (fundPlan && signing) {
29465
29880
  ensureProvisionalCredit({
29466
29881
  endpoint: ref.endpoint,
@@ -29729,7 +30144,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29729
30144
  });
29730
30145
  }
29731
30146
  await collectCashuChange(effectiveJobId, receipt.cashuChange);
29732
- recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
30147
+ recordUpfrontRailPayment(effectiveJobId, cashuUpfrontPayment(chosen, btcRate), true);
29733
30148
  if (!hasUnsavedJobState()) await commitAgentSpend({
29734
30149
  requestId: prepared.requestId,
29735
30150
  recentSpend: {
@@ -29759,6 +30174,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29759
30174
  });
29760
30175
  }
29761
30176
  if (receipt.status === "completed" && receipt.summary) {
30177
+ commitCreditSuggestion();
29762
30178
  markJobTerminal(effectiveJobId, "completed", completionSnapshot(receipt), {
29763
30179
  costMsats: chosen.priceMsats,
29764
30180
  paymentMethod: "cashu"
@@ -29786,7 +30202,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29786
30202
  console.log(receipt.summary);
29787
30203
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
29788
30204
  if (hint) info(`\u{1F4CE} ${hint}`);
29789
- renderReceiptHuman(captured, effectiveJobId);
30205
+ await renderReceiptHuman(captured, effectiveJobId);
29790
30206
  } else {
29791
30207
  providerJobJson({
29792
30208
  jobId: effectiveJobId,
@@ -29794,7 +30210,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29794
30210
  summary: receipt.summary,
29795
30211
  _provider_fields: ["summary"],
29796
30212
  ...buildCompletionHintFields(effectiveJobId, receipt),
29797
- ...receiptJsonFields(captured, effectiveJobId),
30213
+ ...await receiptJsonFields(captured, effectiveJobId),
29798
30214
  paidWith: "cashu_p2pk",
29799
30215
  mint: prepared.mint,
29800
30216
  amountSats: prepared.totalSats,
@@ -29867,7 +30283,8 @@ async function tryX402UpfrontPayment(args) {
29867
30283
  }
29868
30284
  async function payWithX402(args, proof) {
29869
30285
  const { transport, ref, envelope, chosen, opts, identity, policy, wallet } = args;
29870
- if (opts.requestId) recordRequestRailPayment(opts.requestId, { method: "x402", amountMsats: proof.amountMsats });
30286
+ const railPayment = upfrontRailPayment("x402", proof.amountMsats, usdMicro(Number(proof.amountUsdcMicro), "usd"));
30287
+ if (opts.requestId) recordRequestRailPayment(opts.requestId, railPayment);
29871
30288
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
29872
30289
  const usdcMicroUnits = Number(proof.amountUsdcMicro);
29873
30290
  const usd2 = usdcMicroUnits / 1e6;
@@ -29952,7 +30369,7 @@ async function payWithX402(args, proof) {
29952
30369
  asset ? `Verify the account ${addressShort} holds at least the quoted amount in ${asset.label} (${asset.address}) on ${asset.networkLabel} \u2014 the chain this DVM advertises, which is not necessarily the one 'dvm wallet balance' reads. A different dollar${asset.confusable ? ` such as ${asset.confusable}` : ""}, or the right one on another chain, cannot settle this payment.` : "Verify the x402 account holds the quoted USDC amount on the advertised network."
29953
30370
  );
29954
30371
  }
29955
- recordUpfrontRailPayment(effectiveJobId, { method: "x402", amountMsats: proof.amountMsats }, true);
30372
+ recordUpfrontRailPayment(effectiveJobId, railPayment, true);
29956
30373
  recordSpend({
29957
30374
  msats: proof.amountMsats,
29958
30375
  btcRate: proof.btcRate,
@@ -29961,6 +30378,7 @@ async function payWithX402(args, proof) {
29961
30378
  label: buildSpendLabel(identity.capability, envelope.input)
29962
30379
  });
29963
30380
  if (receipt.status === "completed" && receipt.summary) {
30381
+ commitCreditSuggestion();
29964
30382
  markJobTerminal(effectiveJobId, "completed", completionSnapshot(receipt), {
29965
30383
  costMsats: proof.amountMsats,
29966
30384
  paymentMethod: "x402"
@@ -29987,7 +30405,7 @@ async function payWithX402(args, proof) {
29987
30405
  console.log(receipt.summary);
29988
30406
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
29989
30407
  if (hint) info(`\u{1F4CE} ${hint}`);
29990
- renderReceiptHuman(captured, effectiveJobId);
30408
+ await renderReceiptHuman(captured, effectiveJobId);
29991
30409
  } else {
29992
30410
  providerJobJson({
29993
30411
  jobId: effectiveJobId,
@@ -29997,7 +30415,7 @@ async function payWithX402(args, proof) {
29997
30415
  summary: receipt.summary,
29998
30416
  _provider_fields: ["summary"],
29999
30417
  ...buildCompletionHintFields(effectiveJobId, receipt),
30000
- ...receiptJsonFields(captured, effectiveJobId),
30418
+ ...await receiptJsonFields(captured, effectiveJobId),
30001
30419
  paidWith: "x402",
30002
30420
  account: wallet.address,
30003
30421
  ...takeCreditNoticeFields(),
@@ -30169,6 +30587,7 @@ async function streamAfterPayment(args) {
30169
30587
  }
30170
30588
  throw new DvmError("timeout", paidTimeoutMessage);
30171
30589
  }
30590
+ if (streamedTerminal !== "failed" && streamedTerminal !== "cancelled") commitCreditSuggestion();
30172
30591
  if (human) {
30173
30592
  if (streamedTerminal === "failed" || streamedTerminal === "cancelled")
30174
30593
  info(`Status: ${streamedTerminal}${completion?.message ? `: ${completion.message}` : ""}`);
@@ -30180,8 +30599,8 @@ async function streamAfterPayment(args) {
30180
30599
  const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, true);
30181
30600
  if (hint) info(`\u{1F4CE} ${hint}`);
30182
30601
  }
30183
- if (captured) renderReceiptHuman(captured, jobId);
30184
- else renderSettlementHuman(terminalSettlementFields(jobId));
30602
+ if (captured) await renderReceiptHuman(captured, jobId);
30603
+ else renderSettlementHuman(await terminalSettlementReport(jobId));
30185
30604
  finalizeProgressLine();
30186
30605
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: !!streamTerminalStatus(result.messages) });
30187
30606
  } else {
@@ -30200,7 +30619,7 @@ async function streamAfterPayment(args) {
30200
30619
  ...completion?.message !== void 0 ? ["message"] : []
30201
30620
  ],
30202
30621
  ...completion ? buildCompletionHintFields(jobId, completion) : {},
30203
- ...captured ? receiptJsonFields(captured, jobId) : terminalSettlementFields(jobId),
30622
+ ...captured ? await receiptJsonFields(captured, jobId) : await terminalSettlementReport(jobId),
30204
30623
  ...takeCreditNoticeFields(),
30205
30624
  ...takeFeedbackNoticeFields(),
30206
30625
  next_action: result.nextAction,
@@ -30224,6 +30643,7 @@ async function recoverViaStatusPoll(args) {
30224
30643
  costMsats: chosen.priceMsats,
30225
30644
  paymentMethod: paymentMethod2
30226
30645
  });
30646
+ commitCreditSuggestion();
30227
30647
  await collectCashuChange(jobId, status2.cashuChange);
30228
30648
  const captured = captureTransportReceipt(jobId, status2);
30229
30649
  if (!args.strictPerCall)
@@ -30246,7 +30666,7 @@ async function recoverViaStatusPoll(args) {
30246
30666
  });
30247
30667
  if (human) {
30248
30668
  info(status2.summary ?? "Job completed (recovered via status check).");
30249
- renderReceiptHuman(captured, jobId);
30669
+ await renderReceiptHuman(captured, jobId);
30250
30670
  } else {
30251
30671
  providerJobJson({
30252
30672
  jobId,
@@ -30256,7 +30676,7 @@ async function recoverViaStatusPoll(args) {
30256
30676
  _provider_fields: ["summary"],
30257
30677
  recovered: true,
30258
30678
  ...paymentFields,
30259
- ...receiptJsonFields(captured, jobId),
30679
+ ...await receiptJsonFields(captured, jobId),
30260
30680
  ...takeCreditNoticeFields(),
30261
30681
  ...takeFeedbackNoticeFields(),
30262
30682
  next_action: null
@@ -30278,7 +30698,7 @@ async function recoverViaStatusPoll(args) {
30278
30698
  const errorMsg = status2.message ?? `Job ${status2.status}.`;
30279
30699
  if (human) {
30280
30700
  info(errorMsg);
30281
- renderReceiptHuman(captured, jobId);
30701
+ await renderReceiptHuman(captured, jobId);
30282
30702
  } else {
30283
30703
  providerJobJson({
30284
30704
  jobId,
@@ -30287,7 +30707,7 @@ async function recoverViaStatusPoll(args) {
30287
30707
  message: errorMsg,
30288
30708
  ...status2.message !== void 0 ? { _provider_fields: ["message"] } : {},
30289
30709
  ...paymentFields,
30290
- ...receiptJsonFields(captured, jobId),
30710
+ ...await receiptJsonFields(captured, jobId),
30291
30711
  ...takeCreditNoticeFields(),
30292
30712
  ...takeFeedbackNoticeFields(),
30293
30713
  next_action: null
@@ -30475,12 +30895,14 @@ async function requestResultWithWarnings(requestId, opts) {
30475
30895
  endpoint: intent.endpoint,
30476
30896
  jobId: receipt.jobId
30477
30897
  });
30898
+ const { wallet_remaining } = await terminalSettlementReport(receipt.jobId);
30478
30899
  if (opts.human) {
30479
30900
  info(`Recovered request ${requestId} as job ${receipt.jobId} (${receipt.status}).`);
30901
+ if (wallet_remaining) info(wallet_remaining.display);
30480
30902
  if (confirmed.length > 0) {
30481
30903
  info(`The wallet payment held for this request is now confirmed as spent on that job.`);
30482
30904
  }
30483
- renderReceiptHuman(captured);
30905
+ await renderReceiptHuman(captured);
30484
30906
  return;
30485
30907
  }
30486
30908
  json({
@@ -30491,7 +30913,8 @@ async function requestResultWithWarnings(requestId, opts) {
30491
30913
  ...dvmIdentity(intent.dvmId, intent.capability),
30492
30914
  ...receipt.summary !== void 0 ? { summary: receipt.summary } : {},
30493
30915
  ...confirmed.length > 0 ? { confirmed_pending_submissions: confirmed } : {},
30494
- ...receiptJsonFields(captured),
30916
+ ...await receiptJsonFields(captured),
30917
+ ...wallet_remaining ? { wallet_remaining } : {},
30495
30918
  next_action: receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled" ? null : {
30496
30919
  type: "poll",
30497
30920
  job_id: receipt.jobId,
@@ -30857,7 +31280,7 @@ function jobSpend(job, receipt) {
30857
31280
  const totalDisplay = formatPaymentAmount(total, fiat, { anchor: false }) + valuationLabel;
30858
31281
  const budgetDisplay = job.policy ? formatPaymentAmount(
30859
31282
  job.policy.maxTotalMsats,
30860
- fiat && total > 0 ? { currency: fiat.currency, amount: fiat.amount * job.policy.maxTotalMsats / total } : void 0,
31283
+ job.policy.maxTotalUsdMicro !== void 0 ? { currency: "usd", amount: job.policy.maxTotalUsdMicro / 1e6 } : fiat && total > 0 ? { currency: fiat.currency, amount: fiat.amount * job.policy.maxTotalMsats / total } : void 0,
30861
31284
  { anchor: false }
30862
31285
  ) : void 0;
30863
31286
  const logMismatch = isTerminalJobStatus(job.status) && (chargeTotal > total || payments !== charges.length + (upfront > 0 ? 1 : 0) || (knownCredit ? total !== chargeTotal + upfront : job.costMsats !== void 0 && total - chargeTotal !== job.costMsats));
@@ -30957,7 +31380,7 @@ async function statusWithAccess(jobId, opts, access) {
30957
31380
  }
30958
31381
  await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
30959
31382
  transport2.close();
30960
- renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
31383
+ await renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
30961
31384
  receipt: receipt2,
30962
31385
  content
30963
31386
  });
@@ -31037,7 +31460,7 @@ async function statusWithAccess(jobId, opts, access) {
31037
31460
  if (Object.keys(updates).length > 0) updateObservedJob(jobId, updates);
31038
31461
  }
31039
31462
  transport.close();
31040
- renderStatus(jobId, stored, result.status, completion, "provider", nextAction, opts, {
31463
+ await renderStatus(jobId, stored, result.status, completion, "provider", nextAction, opts, {
31041
31464
  msgs,
31042
31465
  cursor: newCursor,
31043
31466
  receipt,
@@ -31057,7 +31480,7 @@ function transientReceiptCapture(jobId, response, endpoint, currency) {
31057
31480
  const result = verifyJobReceipt({ receipt: response.receipt, expectedJobId: jobId });
31058
31481
  return toCapture(response.receipt, result, { currency }, endpoint);
31059
31482
  }
31060
- function renderStatus(jobId, stored, jobStatus, completion, source, nextAction, opts, fetched) {
31483
+ async function renderStatus(jobId, stored, jobStatus, completion, source, nextAction, opts, fetched) {
31061
31484
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
31062
31485
  const artifacts = terminalCompletionOutput(jobId, jobStatus, completion, {
31063
31486
  human: opts.human,
@@ -31070,7 +31493,7 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
31070
31493
  ...loadJob(jobId) ?? stored,
31071
31494
  status: jobStatus
31072
31495
  }, receipt?.receipt) : void 0;
31073
- const settlement = terminalSettlementFields(jobId, {
31496
+ const settlement = await terminalSettlementReport(jobId, {
31074
31497
  status: jobStatus,
31075
31498
  receipt: receipt?.receipt,
31076
31499
  persistLocalState: !!stored,
@@ -31097,7 +31520,8 @@ ${msgs.length} new message(s):`);
31097
31520
  if (traceId) info(`Trace: ${traceId}`);
31098
31521
  if (spend) renderSpendHuman(spend, info);
31099
31522
  else if (settlement.settlement) info(settlement.settlement.display);
31100
- if (receipt) renderReceiptHuman(receipt);
31523
+ if (settlement.wallet_remaining) info(settlement.wallet_remaining.display);
31524
+ if (receipt) await renderReceiptHuman(receipt);
31101
31525
  if (settlement.settlement_hint && !receipt?.currencyHint) info(` ${settlement.settlement_hint}`);
31102
31526
  printNextActionHuman(nextAction);
31103
31527
  return;
@@ -31119,7 +31543,7 @@ ${msgs.length} new message(s):`);
31119
31543
  ...completion.message ? { message: completion.message } : {},
31120
31544
  // terminal responses only. On a still-running job "absent" would
31121
31545
  // read as "this DVM doesn't issue receipts" rather than "not yet".
31122
- ...receipt ? receiptJsonFields(receipt) : {},
31546
+ ...receipt ? await receiptJsonFields(receipt) : {},
31123
31547
  ...settlement,
31124
31548
  ...receipt?.currencyHint ? { settlement_hint: void 0 } : {},
31125
31549
  // `dvm status` is a job-terminal emission for `--no-stream`
@@ -32537,14 +32961,14 @@ function tempoChannelDisplay(chain, endpoint, amounts) {
32537
32961
  }
32538
32962
  function x402ChannelDisplay(chain, channel) {
32539
32963
  const where = x402NetworkLabel(channel.network);
32540
- const amount = usdMicro(chain.depositMicro);
32964
+ const amount = usdMicro2(chain.depositMicro);
32541
32965
  switch (chain.status) {
32542
32966
  case "open":
32543
- return `x402 channel deposit at ${channel.endpoint}: ${amount ?? UNKNOWN_AMOUNT} locked on-chain on ${where}, of which ${usdMicro(chain.settledMicro) ?? UNKNOWN_AMOUNT} has already been claimed by the DVM.`;
32967
+ return `x402 channel deposit at ${channel.endpoint}: ${amount ?? UNKNOWN_AMOUNT} locked on-chain on ${where}, of which ${usdMicro2(chain.settledMicro) ?? UNKNOWN_AMOUNT} has already been claimed by the DVM.`;
32544
32968
  case "closing":
32545
- return `x402 channel at ${channel.endpoint}: a timed exit for ${usdMicro(chain.pendingWithdrawalMicro) ?? UNKNOWN_AMOUNT} is in flight on ${where} and is inside its delay window.`;
32969
+ return `x402 channel at ${channel.endpoint}: a timed exit for ${usdMicro2(chain.pendingWithdrawalMicro) ?? UNKNOWN_AMOUNT} is in flight on ${where} and is inside its delay window.`;
32546
32970
  case "closed":
32547
- return `x402 channel at ${channel.endpoint} holds nothing on ${where}: the contract has paid out everything it held, ${usdMicro(chain.settledMicro) ?? UNKNOWN_AMOUNT} of it to the DVM.`;
32971
+ return `x402 channel at ${channel.endpoint} holds nothing on ${where}: the contract has paid out everything it held, ${usdMicro2(chain.settledMicro) ?? UNKNOWN_AMOUNT} of it to the DVM.`;
32548
32972
  case "unconfirmed":
32549
32973
  return `x402 channel at ${channel.endpoint}: the settlement contract on ${where} holds nothing for this channel and has no record of ever having held anything${chain.depositMicro !== void 0 && chain.depositMicro > 0 ? `, though this wallet's own record still shows ${amount}` : ""}. A deposit that has not landed yet and a channel already emptied through its timed exit look identical from the chain, so this row cannot say which happened.`;
32550
32974
  case "unreadable":
@@ -32581,7 +33005,7 @@ function foreignX402ChannelClause(payer, connected) {
32581
33005
  function foreignX402ChannelHint() {
32582
33006
  return "Reconnect that exact key ('dvm wallet x402-connect --key-file <path>', or DVM_X402_KEY=<key> dvm wallet x402-connect) to recover this collateral: the contract only ever pays a withdrawal back to the payer that opened the channel. This row blocks neither 'dvm wallet x402-disconnect' nor a replacement, because the key guard judges only the channels the connected key opened.";
32583
33007
  }
32584
- function usdMicro(micro) {
33008
+ function usdMicro2(micro) {
32585
33009
  return micro === void 0 ? void 0 : `$${(micro / 1e6).toFixed(2)}`;
32586
33010
  }
32587
33011
  var UNKNOWN_AMOUNT = "an unknown amount";
@@ -33210,7 +33634,7 @@ function mnemonicValidationError(result) {
33210
33634
  var import_qrcode = __toESM(require_lib(), 1);
33211
33635
  import { randomBytes as randomBytes3 } from "crypto";
33212
33636
  import { tmpdir as tmpdir2 } from "os";
33213
- import { join as join9 } from "path";
33637
+ import { join as join10 } from "path";
33214
33638
  async function renderQrTerminal(payload) {
33215
33639
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
33216
33640
  }
@@ -33223,7 +33647,7 @@ async function renderQrPng(payload, outPath) {
33223
33647
  });
33224
33648
  }
33225
33649
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
33226
- return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
33650
+ return join10(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
33227
33651
  }
33228
33652
 
33229
33653
  // src/lib/funding-handoff.ts
@@ -33668,18 +34092,18 @@ function examples(fetcher) {
33668
34092
  }
33669
34093
 
33670
34094
  // src/lib/error-handler.ts
33671
- async function catchErrors(fn, human) {
34095
+ async function catchErrors(fn, human, jsonFields) {
33672
34096
  const lifetimeHold = setInterval(() => void 0, 60 * 60 * 1e3);
33673
34097
  try {
33674
34098
  await fn();
33675
34099
  } catch (err) {
33676
- handleError(err, human);
34100
+ handleError(err, human, jsonFields);
33677
34101
  } finally {
33678
34102
  clearInterval(lifetimeHold);
33679
34103
  }
33680
34104
  process.exit(process.exitCode ?? 0);
33681
34105
  }
33682
- function handleError(err, human) {
34106
+ function handleError(err, human, jsonFields) {
33683
34107
  if (err instanceof DvmError) {
33684
34108
  if (human) {
33685
34109
  if (err.code === "client_upgrade_required") {
@@ -33707,6 +34131,7 @@ function handleError(err, human) {
33707
34131
  }
33708
34132
  }
33709
34133
  json({
34134
+ ...jsonFields,
33710
34135
  error,
33711
34136
  ...takeCreditNoticeFields(),
33712
34137
  ...takeFeedbackNoticeFields()
@@ -33720,6 +34145,7 @@ function handleError(err, human) {
33720
34145
  info(`Error: ${message2}`);
33721
34146
  } else {
33722
34147
  json({
34148
+ ...jsonFields,
33723
34149
  error: {
33724
34150
  code: "internal",
33725
34151
  message: message2,
@@ -34839,7 +35265,7 @@ async function fundX402Rail(amount, opts) {
34839
35265
  const { connected, isNew } = await withX402ChannelLock(async () => {
34840
35266
  const existing = loadX402Wallet();
34841
35267
  return existing ? { connected: await ensureAddress(existing), isNew: false } : {
34842
- connected: await saveX402Wallet(await generateX402PrivateKey(), X402_DEFAULT_NETWORK),
35268
+ connected: await saveX402Wallet(await generateX402PrivateKey(), X402_DEFAULT_NETWORK, true),
34843
35269
  isNew: true
34844
35270
  };
34845
35271
  });
@@ -35150,14 +35576,14 @@ import { randomUUID as randomUUID5 } from "crypto";
35150
35576
  // src/lib/wallet-agent/release-intents.ts
35151
35577
  var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
35152
35578
  import { createHash as createHash6 } from "crypto";
35153
- import { dirname as dirname4, join as join10 } from "path";
35579
+ import { dirname as dirname4, join as join11 } from "path";
35154
35580
  var intents = journalFile("release-intents.json");
35155
35581
  async function withReleaseLock(walletPubkey, builderHandle, mint, operation) {
35156
35582
  ensureConfigDir();
35157
35583
  const key = createHash6("sha256").update(JSON.stringify([walletPubkey, builderHandle, mint])).digest("hex");
35158
35584
  let unlock;
35159
35585
  try {
35160
- unlock = await import_proper_lockfile3.default.lock(join10(dirname4(JOBS_FILE), `release-${key}`), {
35586
+ unlock = await import_proper_lockfile3.default.lock(join11(dirname4(JOBS_FILE), `release-${key}`), {
35161
35587
  realpath: false,
35162
35588
  stale: 2 * 6e4,
35163
35589
  retries: 0
@@ -36071,35 +36497,132 @@ function mnemonicValidationError2(result) {
36071
36497
  );
36072
36498
  }
36073
36499
 
36074
- // src/lib/wallet-agent/cash-out.ts
36075
- async function cashOutFromMint(opts) {
36076
- const mintUrl = opts.mintUrl;
36077
- const now = opts.now ?? (() => Date.now());
36078
- const getWalletForMint = opts.getWalletForMint ?? getWallet;
36079
- const fetchInvoice = opts.fetchInvoice ?? fetchLnurlPayInvoice;
36080
- const initial = loadAgentWallet();
36081
- if (!initial) {
36500
+ // src/lib/wallet-agent/invoice.ts
36501
+ function invoiceDestination(destination) {
36502
+ const invoice = destination.replace(/^lightning:/i, "").toLowerCase();
36503
+ return !invoice.includes("@") && /^ln(bcrt|tbs|tb|bc)([0-9]+[munp]?)?1[02-9ac-hj-np-z]+$/.test(invoice) ? invoice : void 0;
36504
+ }
36505
+ function invalidInvoice(message2) {
36506
+ throw new DvmError(
36507
+ "invalid_invoice",
36508
+ `${message2} No money moved.`,
36509
+ "Ask for a valid mainnet invoice with an amount, then run `dvm wallet cash-out <invoice>`."
36510
+ );
36511
+ }
36512
+ function invoiceAmountSats(invoice, now = Date.now()) {
36513
+ let decoded;
36514
+ try {
36515
+ decoded = bech32.decode(invoice, false);
36516
+ } catch {
36517
+ return invalidInvoice("The invoice has invalid Bech32 encoding or checksum.");
36518
+ }
36519
+ const header = /^ln(bcrt|tbs|tb|bc)([0-9]+)?([munp]?)$/.exec(decoded.prefix);
36520
+ if (!header || header[1] !== "bc") return invalidInvoice("The invoice is on the wrong network; this wallet pays Bitcoin mainnet invoices.");
36521
+ if (!header[2]) return invalidInvoice("An amountless invoice cannot be cashed out.");
36522
+ const scale = { "": 1000000000000n, m: 1000000000n, u: 1000000n, n: 1000n, p: 1n };
36523
+ const picoBtc = BigInt(header[2]) * scale[header[3]];
36524
+ if (picoBtc <= 0n || picoBtc % 10n !== 0n) return invalidInvoice("The invoice amount must be positive and represent whole millisatoshis.");
36525
+ const sats = Number((picoBtc + 9999n) / 10000n);
36526
+ const words = decoded.words;
36527
+ const end = words.length - 104;
36528
+ if (end < 7 || !Number.isSafeInteger(sats)) return invalidInvoice("The invoice has invalid payment data or amount.");
36529
+ const integer = (data) => data.reduce((value, word) => value * 32 + word, 0);
36530
+ const timestamp = integer(words.slice(0, 7));
36531
+ let expiry = 3600;
36532
+ let hasExpiry = false;
36533
+ for (let pos = 7; pos < end; ) {
36534
+ if (pos + 3 > end) return invalidInvoice("The invoice has a truncated tagged field.");
36535
+ const tag = words[pos], length = words[pos + 1] * 32 + words[pos + 2];
36536
+ pos += 3;
36537
+ if (pos + length > end) return invalidInvoice("The invoice has a truncated tagged field.");
36538
+ if (tag === 6) {
36539
+ if (hasExpiry || length === 0) return invalidInvoice("The invoice has an invalid expiry field.");
36540
+ expiry = integer(words.slice(pos, pos + length));
36541
+ hasExpiry = true;
36542
+ }
36543
+ pos += length;
36544
+ }
36545
+ if (!Number.isSafeInteger(timestamp + expiry)) return invalidInvoice("The invoice expiry is out of range.");
36546
+ const remainingMs = (timestamp + expiry) * 1e3 - now;
36547
+ if (remainingMs <= 0) return invalidInvoice("The invoice has expired.");
36548
+ if (remainingMs < 6e4) return invalidInvoice("The invoice expires in less than 60 seconds.");
36549
+ return sats;
36550
+ }
36551
+ function assertInvoiceNotPending(wallet, invoice) {
36552
+ const normalized = invoiceDestination(invoice);
36553
+ if (normalized && wallet.pending_melts.some((entry) => invoiceDestination(entry.bolt11) === normalized)) {
36082
36554
  throw new DvmError(
36083
- "wallet_missing",
36084
- "No agent wallet found.",
36085
- "Run `dvm wallet init` first to generate a lock keypair."
36555
+ "cash_out_pending",
36556
+ "This invoice already has a cash-out in flight. No money moved.",
36557
+ "Run `dvm wallet show` to reconcile it before retrying."
36086
36558
  );
36087
36559
  }
36088
- const candidates = spendableAt(initial.proofs, mintUrl);
36089
- if (candidates.length === 0) {
36090
- return {
36091
- kind: "skipped",
36092
- mint: mintUrl,
36093
- reason: "no_balance",
36094
- message: `No spendable proofs at ${mintUrl}.`
36095
- };
36096
- }
36097
- let cashuWallet;
36560
+ }
36561
+
36562
+ // src/lib/wallet-agent/cash-out-invoice.ts
36563
+ async function prepareInvoice(opts, candidates, bounds) {
36564
+ const mint = opts.mintUrl;
36565
+ const refuse = (reason, message2) => ({
36566
+ kind: "skipped",
36567
+ mint,
36568
+ reason,
36569
+ message: `${message2} No money moved. Run \`dvm wallet mint-health\`, then retry \`dvm wallet cash-out <invoice>\`.`
36570
+ });
36571
+ const invoice = opts.bolt11;
36572
+ const amount = invoiceAmountSats(invoice, (opts.now ?? Date.now)());
36098
36573
  try {
36099
- cashuWallet = await getWalletForMint(mintUrl);
36574
+ const quote2 = await fetchMeltQuote(mint, invoice);
36575
+ if (quote2.amountSats !== amount) {
36576
+ return refuse("quote_amount_mismatch", `The mint quoted ${quote2.amountSats} sats for a ${amount} sat invoice.`);
36577
+ }
36578
+ if (typeof quote2.rawQuote.expiry === "number" && quote2.rawQuote.expiry * 1e3 <= (opts.now ?? Date.now)()) {
36579
+ return refuse("quote_expired", "The invoice's melt quote has expired.");
36580
+ }
36581
+ const inBounds = (bounds.minSats === null || amount >= bounds.minSats) && (bounds.maxSats === null || amount <= bounds.maxSats);
36582
+ const selected = [];
36583
+ let selectedTotal = 0;
36584
+ let inputFees = 0;
36585
+ for (const proof of candidates) {
36586
+ selected.push(proof);
36587
+ selectedTotal += proof.amount;
36588
+ inputFees = await getInputFeesForProofs(mint, toCashuProofs(selected));
36589
+ if (inBounds && selectedTotal >= quote2.amountSats + quote2.feeReserveSats + inputFees) break;
36590
+ }
36591
+ let largest = Math.max(0, Math.min(selectedTotal - quote2.feeReserveSats - inputFees, bounds.maxSats ?? Infinity));
36592
+ if (largest < (bounds.minSats ?? 1)) largest = 0;
36593
+ const fits = largest > 0 ? `The largest invoice amount that fits at the quoted fees is ${largest} sats. No money moved. Ask for an invoice of at most ${largest} sats, then run \`dvm wallet cash-out <invoice>\`.` : "No invoice can be paid from this balance at the quoted fees and mint limits. No money moved. Run `dvm wallet show` to check your balance, or `dvm wallet fund` to add funds.";
36594
+ if (selectedTotal < quote2.amountSats + quote2.feeReserveSats + inputFees) {
36595
+ return {
36596
+ kind: "skipped",
36597
+ mint,
36598
+ reason: "fees_exceed_balance",
36599
+ message: `The ${quote2.amountSats} sat invoice plus fees exceeds the ${selectedTotal} sat balance at ${mint}. ${fits}`
36600
+ };
36601
+ }
36602
+ if (bounds.minSats !== null && amount < bounds.minSats || bounds.maxSats !== null && amount > bounds.maxSats) {
36603
+ return {
36604
+ kind: "skipped",
36605
+ mint,
36606
+ reason: "amount_out_of_range",
36607
+ message: `The ${amount} sat invoice is outside this mint's payout limits. ${fits}`
36608
+ };
36609
+ }
36610
+ return { invoice, quote: quote2, selected, selectedTotal, inputFees };
36100
36611
  } catch (err) {
36101
- return { kind: "failed", mint: mintUrl, message: errorMessage2(err), settlement: "reverted" };
36612
+ return {
36613
+ kind: "failed",
36614
+ mint,
36615
+ settlement: "reverted",
36616
+ message: `Could not obtain a cash-out quote or input fees at ${mint}: ${err instanceof Error ? err.message : String(err)}. No money moved. Run \`dvm wallet mint-health\`, then retry \`dvm wallet cash-out <invoice>\`.`
36617
+ };
36102
36618
  }
36619
+ }
36620
+
36621
+ // src/lib/wallet-agent/cash-out-prepare.ts
36622
+ async function prepareCashOut(opts, candidates, cashuWallet) {
36623
+ const mintUrl = opts.mintUrl;
36624
+ const fetchInvoice = opts.fetchInvoice ?? fetchLnurlPayInvoice;
36625
+ if (opts.bolt11 !== void 0) return prepareInvoice(opts, candidates, meltBoundsOf(cashuWallet));
36103
36626
  const meltBounds = meltBoundsOf(cashuWallet);
36104
36627
  let target = opts.target;
36105
36628
  let cappedByMintMax;
@@ -36215,6 +36738,92 @@ async function cashOutFromMint(opts) {
36215
36738
  }
36216
36739
  }
36217
36740
  }
36741
+ return { invoice, quote: quote2, selected, selectedTotal, inputFees, cappedByMintMax };
36742
+ }
36743
+ function meltBoundsOf(wallet) {
36744
+ const reader = wallet;
36745
+ try {
36746
+ const nuts = reader.getMintInfo?.().cache?.nuts;
36747
+ if (nuts === void 0 || nuts === null) return { minSats: null, maxSats: null };
36748
+ return meltAmountBounds(nuts);
36749
+ } catch {
36750
+ return { minSats: null, maxSats: null };
36751
+ }
36752
+ }
36753
+ function selectInputs(candidates, target) {
36754
+ if (target.kind === "all") return [...candidates];
36755
+ const selected = [];
36756
+ let total = 0;
36757
+ for (const p of candidates) {
36758
+ selected.push(p);
36759
+ total += p.amount;
36760
+ if (total >= target.sats) return selected;
36761
+ }
36762
+ return selected;
36763
+ }
36764
+ function widenSelection(candidates, selected, needed, currentInputFees) {
36765
+ const chosen = new Set(selected.map((p) => proofKey(p)));
36766
+ const rest = candidates.filter((p) => !chosen.has(proofKey(p)));
36767
+ if (rest.length === 0) return null;
36768
+ const next = [...selected];
36769
+ let total = sumSats2(next);
36770
+ for (const p of rest) {
36771
+ if (total >= needed + currentInputFees) break;
36772
+ next.push(p);
36773
+ total += p.amount;
36774
+ }
36775
+ return next.length === selected.length ? null : { selected: next };
36776
+ }
36777
+ function classifyPreCommitError(mintUrl, err) {
36778
+ if (err instanceof DvmError && err.code === "lnurl_amount_out_of_range") {
36779
+ return {
36780
+ kind: "skipped",
36781
+ mint: mintUrl,
36782
+ reason: "amount_out_of_range",
36783
+ message: err.message
36784
+ };
36785
+ }
36786
+ return { kind: "failed", mint: mintUrl, message: errorMessage2(err), settlement: "reverted" };
36787
+ }
36788
+ function sumSats2(proofs) {
36789
+ return proofs.reduce((sum, p) => sum + p.amount, 0);
36790
+ }
36791
+ function errorMessage2(err) {
36792
+ return err instanceof Error ? err.message : String(err);
36793
+ }
36794
+
36795
+ // src/lib/wallet-agent/cash-out.ts
36796
+ async function cashOutFromMint(opts) {
36797
+ const mintUrl = opts.mintUrl;
36798
+ const now = opts.now ?? (() => Date.now());
36799
+ const getWalletForMint = opts.getWalletForMint ?? getWallet;
36800
+ const initial = loadAgentWallet();
36801
+ if (!initial) {
36802
+ throw new DvmError(
36803
+ "wallet_missing",
36804
+ "No agent wallet found.",
36805
+ "Run `dvm wallet init` first to generate a lock keypair."
36806
+ );
36807
+ }
36808
+ if (opts.bolt11) assertInvoiceNotPending(initial, opts.bolt11);
36809
+ const candidates = spendableAt(initial.proofs, mintUrl);
36810
+ if (candidates.length === 0) {
36811
+ return {
36812
+ kind: "skipped",
36813
+ mint: mintUrl,
36814
+ reason: "no_balance",
36815
+ message: `No spendable proofs at ${mintUrl}.`
36816
+ };
36817
+ }
36818
+ let cashuWallet;
36819
+ try {
36820
+ cashuWallet = await getWalletForMint(mintUrl);
36821
+ } catch (err) {
36822
+ return { kind: "failed", mint: mintUrl, message: errorMessage3(err), settlement: "reverted" };
36823
+ }
36824
+ const prepared = await prepareCashOut(opts, candidates, cashuWallet);
36825
+ if ("kind" in prepared) return prepared;
36826
+ const { invoice, quote: quote2, selected, selectedTotal, inputFees, cappedByMintMax } = prepared;
36218
36827
  const quoteView = {
36219
36828
  mint: mintUrl,
36220
36829
  quote_id: quote2.rawQuote.quote,
@@ -36230,7 +36839,7 @@ async function cashOutFromMint(opts) {
36230
36839
  kind: "skipped",
36231
36840
  mint: mintUrl,
36232
36841
  reason: "fee_cap_exceeded",
36233
- message: `Fees at ${mintUrl} would be up to ${totalFees} sats, over the ${opts.maxFeeSats} sat cap.`,
36842
+ message: `Fees at ${mintUrl} would be up to ${totalFees} sats, over the ${opts.maxFeeSats} sat cap.${opts.bolt11 ? " No money moved. Run `dvm wallet cash-out <invoice> --max-fee <sats>` with a sufficient cap if you accept these fees." : ""}`,
36234
36843
  quote: quoteView
36235
36844
  };
36236
36845
  }
@@ -36250,7 +36859,7 @@ async function cashOutFromMint(opts) {
36250
36859
  return {
36251
36860
  kind: "failed",
36252
36861
  mint: mintUrl,
36253
- message: errorMessage2(err),
36862
+ message: errorMessage3(err),
36254
36863
  settlement: "reverted",
36255
36864
  quote: quoteView
36256
36865
  };
@@ -36276,6 +36885,10 @@ async function cashOutFromMint(opts) {
36276
36885
  const committed = await withWalletLock(() => {
36277
36886
  const fresh = loadAgentWallet();
36278
36887
  if (!fresh) return false;
36888
+ if (opts.bolt11) {
36889
+ assertInvoiceNotPending(fresh, opts.bolt11);
36890
+ invoiceAmountSats(opts.bolt11, now());
36891
+ }
36279
36892
  const swept = sweepStaleInFlight(fresh, now());
36280
36893
  const available = new Set(spendableAt(swept.wallet.proofs, mintUrl).map((p) => proofKey(p)));
36281
36894
  if (![...selectedKeys].every((k) => available.has(k))) {
@@ -36319,20 +36932,10 @@ async function cashOutFromMint(opts) {
36319
36932
  mint: mintUrl,
36320
36933
  quote: quoteView,
36321
36934
  preimage,
36322
- change_sats: sumSats2(changeProofs),
36935
+ change_sats: sumSats3(changeProofs),
36323
36936
  ...cappedByMintMax !== void 0 ? { mint_max_sats: cappedByMintMax } : {}
36324
36937
  };
36325
36938
  }
36326
- function meltBoundsOf(wallet) {
36327
- const reader = wallet;
36328
- try {
36329
- const nuts = reader.getMintInfo?.().cache?.nuts;
36330
- if (nuts === void 0 || nuts === null) return { minSats: null, maxSats: null };
36331
- return meltAmountBounds(nuts);
36332
- } catch {
36333
- return { minSats: null, maxSats: null };
36334
- }
36335
- }
36336
36939
  function spendableAt(proofs, mintUrl) {
36337
36940
  return proofs.filter((p) => p.mint === mintUrl && p.status === "valid" && p.reserved_for === void 0).slice().sort((a, b) => b.amount - a.amount);
36338
36941
  }
@@ -36348,7 +36951,7 @@ async function resolveFailedMelt(cashuWallet, mintUrl, entry, selectedKeys, quot
36348
36951
  return {
36349
36952
  kind: "failed",
36350
36953
  mint: mintUrl,
36351
- message: `${errorMessage2(err)} \u2014 ${entry.amount_sats} sats may still be in flight at ${mintUrl}. Run \`dvm wallet show\` to reconcile before retrying.`,
36954
+ message: `${errorMessage3(err)} \u2014 ${entry.amount_sats} sats may still be in flight at ${mintUrl}. Run \`dvm wallet show\` to reconcile before retrying.`,
36352
36955
  settlement: "unresolved",
36353
36956
  quote: quoteView
36354
36957
  };
@@ -36365,63 +36968,37 @@ async function resolveFailedMelt(cashuWallet, mintUrl, entry, selectedKeys, quot
36365
36968
  return {
36366
36969
  kind: "failed",
36367
36970
  mint: mintUrl,
36368
- message: `${errorMessage2(err)} \u2014 the mint confirms the invoice is unpaid, so the ${quoteView.debit_sats} sats are back in the wallet.`,
36971
+ message: `${errorMessage3(err)} \u2014 the mint confirms the invoice is unpaid, so the ${quoteView.debit_sats} sats are back in the wallet.`,
36369
36972
  settlement: "reverted",
36370
36973
  quote: quoteView
36371
36974
  };
36372
36975
  }
36373
- function selectInputs(candidates, target) {
36374
- if (target.kind === "all") return [...candidates];
36375
- const selected = [];
36376
- let total = 0;
36377
- for (const p of candidates) {
36378
- selected.push(p);
36379
- total += p.amount;
36380
- if (total >= target.sats) return selected;
36381
- }
36382
- return selected;
36383
- }
36384
- function widenSelection(candidates, selected, needed, currentInputFees) {
36385
- const chosen = new Set(selected.map((p) => proofKey(p)));
36386
- const rest = candidates.filter((p) => !chosen.has(proofKey(p)));
36387
- if (rest.length === 0) return null;
36388
- const next = [...selected];
36389
- let total = sumSats2(next);
36390
- for (const p of rest) {
36391
- if (total >= needed + currentInputFees) break;
36392
- next.push(p);
36393
- total += p.amount;
36394
- }
36395
- return next.length === selected.length ? null : { selected: next };
36396
- }
36397
- function classifyPreCommitError(mintUrl, err) {
36398
- if (err instanceof DvmError && err.code === "lnurl_amount_out_of_range") {
36399
- return {
36400
- kind: "skipped",
36401
- mint: mintUrl,
36402
- reason: "amount_out_of_range",
36403
- message: err.message
36404
- };
36405
- }
36406
- return { kind: "failed", mint: mintUrl, message: errorMessage2(err), settlement: "reverted" };
36407
- }
36408
- function sumSats2(proofs) {
36976
+ function sumSats3(proofs) {
36409
36977
  return proofs.reduce((sum, p) => sum + p.amount, 0);
36410
36978
  }
36411
- function errorMessage2(err) {
36979
+ function errorMessage3(err) {
36412
36980
  return err instanceof Error ? err.message : String(err);
36413
36981
  }
36414
36982
 
36415
36983
  // src/commands/wallet-cash-out.ts
36416
36984
  async function walletCashOut(destination, opts) {
36417
36985
  const human = opts.human ?? false;
36418
- if (opts.amount === void 0 === (opts.all !== true)) {
36986
+ const bolt11 = invoiceDestination(destination);
36987
+ if (bolt11 && (opts.amount !== void 0 || opts.all === true || opts.sats === true)) {
36988
+ throw new DvmError(
36989
+ "invalid_flags",
36990
+ "The invoice fixes the amount; --amount, --all, and --sats cannot be used with it. No money moved.",
36991
+ "Run `dvm wallet cash-out <invoice>` without --amount, --all, or --sats."
36992
+ );
36993
+ }
36994
+ if (!bolt11 && opts.amount === void 0 === (opts.all !== true)) {
36419
36995
  throw new DvmError(
36420
36996
  "invalid_flags",
36421
36997
  "Pass exactly one of --amount <amount> or --all.",
36422
36998
  "`--amount 1000` sends 1000 sats and draws the fees on top; `--all` empties the wallet, with fees coming out of the balance."
36423
36999
  );
36424
37000
  }
37001
+ const invoiceSats = bolt11 ? invoiceAmountSats(bolt11) : void 0;
36425
37002
  await loadConfiguredMints();
36426
37003
  const wallet = loadAgentWallet();
36427
37004
  if (!wallet) {
@@ -36434,9 +37011,10 @@ async function walletCashOut(destination, opts) {
36434
37011
  await sweepPendingMints().catch(() => void 0);
36435
37012
  await sweepPendingMelts().catch(() => void 0);
36436
37013
  const fresh = loadAgentWallet() ?? wallet;
37014
+ if (bolt11) assertInvoiceNotPending(fresh, bolt11);
36437
37015
  const requested = opts.amount ? await resolveFundingAmountSats(opts.amount, opts.sats) : null;
36438
37016
  const maxFeeSats = parseMaxFee(opts.maxFee);
36439
- await validateLnAddress(destination);
37017
+ if (!bolt11) await validateLnAddress(destination);
36440
37018
  const mints = resolveMints(fresh, opts.mint);
36441
37019
  if (mints.length === 0) {
36442
37020
  throw new DvmError(
@@ -36446,9 +37024,9 @@ async function walletCashOut(destination, opts) {
36446
37024
  );
36447
37025
  }
36448
37026
  if (human) {
36449
- const what = requested ? describeAmount(requested) : "everything";
37027
+ const what = bolt11 ? "the invoice amount" : requested ? describeAmount(requested) : "everything";
36450
37028
  info(
36451
- `Cashing out ${what} to ${destination} across ${mints.length} mint(s)${opts.dryRun ? " (dry run \u2014 nothing will be paid)" : ""}\u2026`
37029
+ `Cashing out ${what} to ${destination}${bolt11 ? " from one mint" : ` across ${mints.length} mint(s)`}${opts.dryRun ? " (dry run \u2014 nothing will be paid)" : ""}\u2026`
36452
37030
  );
36453
37031
  }
36454
37032
  const outcomes = [];
@@ -36459,6 +37037,7 @@ async function walletCashOut(destination, opts) {
36459
37037
  mintUrl,
36460
37038
  target: requested ? { kind: "exact", sats: remaining } : { kind: "all" },
36461
37039
  destination,
37040
+ bolt11,
36462
37041
  maxFeeSats,
36463
37042
  dryRun: opts.dryRun,
36464
37043
  onQuote: (quote2) => {
@@ -36466,6 +37045,7 @@ async function walletCashOut(destination, opts) {
36466
37045
  }
36467
37046
  });
36468
37047
  outcomes.push(outcome);
37048
+ if (bolt11 && (outcome.kind !== "skipped" && !(outcome.kind === "failed" && !outcome.quote))) break;
36469
37049
  if (requested && (outcome.kind === "sent" || outcome.kind === "quoted")) {
36470
37050
  remaining -= outcome.quote.amount_sats;
36471
37051
  }
@@ -36485,7 +37065,7 @@ async function walletCashOut(destination, opts) {
36485
37065
  const moreToSend = opts.all === true || shortfall > 0;
36486
37066
  const rows = outcomes.map((o) => toRow(o, moreToSend));
36487
37067
  const status2 = opts.dryRun ? "quoted" : sentSats > 0 ? "cashed_out" : "nothing_sent";
36488
- const display = opts.dryRun ? `Quoted ${quotedSats} sats to ${destination} across ${rows.length} mint(s). Nothing was paid.` : sentSats > 0 ? `Sent ${sentSats} sats to ${destination}${feeSats > 0 ? `, plus ${feeSats} sats in fees` : ""}${shortfall > 0 ? ` \u2014 ${shortfall} sats short of what you asked for` : ""}.` : `Nothing was sent to ${destination}.`;
37068
+ const display = opts.dryRun ? `Quoted ${quotedSats} sats to ${destination}${bolt11 ? " from one mint" : ` across ${rows.length} mint(s)`}. Nothing was paid.` : sentSats > 0 ? `Sent ${sentSats} sats to ${destination}${feeSats > 0 ? `, plus ${feeSats} sats in fees` : ""}${shortfall > 0 ? ` \u2014 ${shortfall} sats short of what you asked for` : ""}.` : `Nothing was sent to ${destination}.`;
36489
37069
  const cappedCount = moreToSend ? rows.filter((r) => r.mint_max_sats !== void 0).length : 0;
36490
37070
  const hint = buildHint({
36491
37071
  unresolvedCount: unresolved.length,
@@ -36506,7 +37086,7 @@ async function walletCashOut(destination, opts) {
36506
37086
  status: status2,
36507
37087
  destination,
36508
37088
  ...requested ? amountSourceFields(requested) : { source_currency: "sats" },
36509
- requested_sats: requested?.sats ?? null,
37089
+ requested_sats: requested?.sats ?? invoiceSats ?? null,
36510
37090
  sats_sent: sentSats,
36511
37091
  fee_sats: feeSats,
36512
37092
  change_sats: changeSats,
@@ -36519,7 +37099,7 @@ async function walletCashOut(destination, opts) {
36519
37099
  if (!opts.dryRun && sentSats === 0) {
36520
37100
  throw new DvmError(
36521
37101
  "cash_out_failed",
36522
- `No mint could pay ${destination}.`,
37102
+ bolt11 && outcomes.every((o) => o.kind === "skipped" && o.reason === "fees_exceed_balance") ? "No single mint could cover this invoice and its fees. No money moved; invoice payments cannot be split across mints." : bolt11 && unresolved.length === 0 ? outcomes.map((o) => "message" in o ? o.message : "").filter(Boolean).join(" ") : `No mint could pay ${destination}.`,
36523
37103
  unresolved.length > 0 ? "At least one melt's outcome is unknown \u2014 run `dvm wallet show` to reconcile it against the mint before retrying." : "See the per-mint reasons above. `dvm wallet mint-health` reports whether a mint is currently able to melt."
36524
37104
  );
36525
37105
  }
@@ -36611,7 +37191,7 @@ function resolveMints(wallet, explicit) {
36611
37191
  return spendableAt(wallet.proofs, explicit).length > 0 ? [explicit] : [];
36612
37192
  }
36613
37193
  const candidates = /* @__PURE__ */ new Set([...effectiveMints(wallet), ...wallet.proofs.map((p) => p.mint)]);
36614
- return [...candidates].map((url2) => ({ url: url2, sats: sumSats3(spendableAt(wallet.proofs, url2)) })).filter((m) => m.sats > 0).sort((a, b) => b.sats - a.sats || a.url.localeCompare(b.url)).map((m) => m.url);
37194
+ return [...candidates].map((url2) => ({ url: url2, sats: sumSats4(spendableAt(wallet.proofs, url2)) })).filter((m) => m.sats > 0).sort((a, b) => b.sats - a.sats || a.url.localeCompare(b.url)).map((m) => m.url);
36615
37195
  }
36616
37196
  function buildHint(args) {
36617
37197
  if (args.unresolvedCount > 0) {
@@ -36640,7 +37220,7 @@ function parseMaxFee(raw2) {
36640
37220
  }
36641
37221
  return Math.floor(n);
36642
37222
  }
36643
- function sumSats3(proofs) {
37223
+ function sumSats4(proofs) {
36644
37224
  return proofs.reduce((sum, p) => sum + p.amount, 0);
36645
37225
  }
36646
37226
 
@@ -37893,14 +38473,14 @@ function hexToBytes2(hex2) {
37893
38473
  var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
37894
38474
  import {
37895
38475
  chmodSync as chmodSync2,
37896
- existsSync as existsSync8,
38476
+ existsSync as existsSync9,
37897
38477
  readdirSync as readdirSync5,
37898
- readFileSync as readFileSync9,
37899
- renameSync as renameSync4,
37900
- unlinkSync as unlinkSync3,
37901
- writeFileSync as writeFileSync6
38478
+ readFileSync as readFileSync10,
38479
+ renameSync as renameSync5,
38480
+ unlinkSync as unlinkSync4,
38481
+ writeFileSync as writeFileSync7
37902
38482
  } from "fs";
37903
- import { join as join11 } from "path";
38483
+ import { join as join12 } from "path";
37904
38484
  var pairingIdPattern = /^[0-9a-f]{64}$/;
37905
38485
  var stateSchema = external_exports.object({
37906
38486
  version: external_exports.literal(1),
@@ -37922,12 +38502,12 @@ var stateSchema = external_exports.object({
37922
38502
  function createWalletPairingState(state) {
37923
38503
  ensurePairingsDirectory();
37924
38504
  const path = pairingPath(state.pairing_id);
37925
- writeFileSync6(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
38505
+ writeFileSync7(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
37926
38506
  chmodSync2(path, 384);
37927
38507
  }
37928
38508
  function loadWalletPairingState(pairingId) {
37929
38509
  const path = pairingPath(pairingId);
37930
- if (!existsSync8(path)) {
38510
+ if (!existsSync9(path)) {
37931
38511
  throw new DvmError(
37932
38512
  "wallet_pairing_not_found",
37933
38513
  "No local state exists for that wallet pairing.",
@@ -37935,7 +38515,7 @@ function loadWalletPairingState(pairingId) {
37935
38515
  );
37936
38516
  }
37937
38517
  try {
37938
- return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
38518
+ return stateSchema.parse(JSON.parse(readFileSync10(path, "utf8")));
37939
38519
  } catch {
37940
38520
  throw new DvmError(
37941
38521
  "wallet_pairing_state_invalid",
@@ -37949,13 +38529,13 @@ function saveWalletPairingState(state) {
37949
38529
  ensurePairingsDirectory();
37950
38530
  const path = pairingPath(state.pairing_id);
37951
38531
  const tmp = `${path}.tmp`;
37952
- writeFileSync6(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
38532
+ writeFileSync7(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
37953
38533
  try {
37954
- renameSync4(tmp, path);
38534
+ renameSync5(tmp, path);
37955
38535
  chmodSync2(path, 384);
37956
38536
  } catch (err) {
37957
38537
  try {
37958
- unlinkSync3(tmp);
38538
+ unlinkSync4(tmp);
37959
38539
  } catch {
37960
38540
  }
37961
38541
  throw err;
@@ -37964,21 +38544,21 @@ function saveWalletPairingState(state) {
37964
38544
  function deleteWalletPairingState(pairingId) {
37965
38545
  const path = pairingPath(pairingId);
37966
38546
  try {
37967
- unlinkSync3(path);
38547
+ unlinkSync4(path);
37968
38548
  } catch (err) {
37969
38549
  if (err.code !== "ENOENT") throw err;
37970
38550
  }
37971
38551
  }
37972
38552
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
37973
- if (!existsSync8(PAIRINGS_DIR)) return 0;
38553
+ if (!existsSync9(PAIRINGS_DIR)) return 0;
37974
38554
  let removed = 0;
37975
38555
  for (const name of readdirSync5(PAIRINGS_DIR)) {
37976
38556
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
37977
- const path = join11(PAIRINGS_DIR, name);
38557
+ const path = join12(PAIRINGS_DIR, name);
37978
38558
  try {
37979
- const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
38559
+ const state = stateSchema.parse(JSON.parse(readFileSync10(path, "utf8")));
37980
38560
  if (state.manifest.expires_at <= nowSeconds) {
37981
- unlinkSync3(path);
38561
+ unlinkSync4(path);
37982
38562
  removed += 1;
37983
38563
  }
37984
38564
  } catch {
@@ -37988,7 +38568,7 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
37988
38568
  }
37989
38569
  async function withWalletPairingLock(pairingId, fn) {
37990
38570
  const path = pairingPath(pairingId);
37991
- if (!existsSync8(path)) return fn();
38571
+ if (!existsSync9(path)) return fn();
37992
38572
  let release;
37993
38573
  try {
37994
38574
  release = await import_proper_lockfile4.default.lock(path, {
@@ -38018,7 +38598,7 @@ function pairingPath(pairingId) {
38018
38598
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
38019
38599
  );
38020
38600
  }
38021
- return join11(PAIRINGS_DIR, `${pairingId}.json`);
38601
+ return join12(PAIRINGS_DIR, `${pairingId}.json`);
38022
38602
  }
38023
38603
  function ensurePairingsDirectory() {
38024
38604
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -38824,7 +39404,7 @@ async function walletX402Connect(keyArg, opts) {
38824
39404
  qrImagePath: opts.qrImage
38825
39405
  });
38826
39406
  return {
38827
- connected: { ...await saveX402Wallet(privateKey, network), generated: true },
39407
+ connected: { ...await saveX402Wallet(privateKey, network, true), generated: true },
38828
39408
  handoff: handoff2
38829
39409
  };
38830
39410
  });
@@ -39842,8 +40422,17 @@ function buildProgram() {
39842
40422
  ).option("--drain-id <id>", "Only the evidence for this drain").option("--export", "Write the raw bundles to stdout as JSONL, un-enveloped").option("--refetch", "Grade against the DVM's live /v1/info instead of the pinned anchor").option("--as <name>", "Caller signing identity whose evidence to read").option("--human", "Human-readable output instead of JSON").action((dvm, opts) => {
39843
40423
  return catchErrors(() => creditReceipts(dvm, opts), opts.human);
39844
40424
  });
39845
- program2.command("messages <job-id>").description("Fetch messages from a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--after <seq>", "Only show messages with seq > N").option("--no-stream", "Non-blocking snapshot instead of streaming until yield").option("--human", "Human-readable output instead of JSON").option("--wait", "Stay attached until the job needs input or ends").option("--until <duration>", "Wait limit with --wait (default: 12h; e.g. 30s, 5m, 12h)").option("--timeout <sec>", "Read timeout (default: 5s, or 60s with --wait)").action((jobId, opts) => {
39846
- return catchErrors(() => messages(jobId, opts), opts.human);
40425
+ const jsonWait = () => {
40426
+ const args = program2.args.slice(1);
40427
+ return args.includes("--wait") && !args.includes("--human");
40428
+ };
40429
+ program2.command("messages <job-id>").configureOutput({ outputError: (text, write) => {
40430
+ if (!jsonWait()) write(text);
40431
+ } }).exitOverride((error) => {
40432
+ if (error.exitCode === 0 || !jsonWait()) process.exit(error.exitCode);
40433
+ handleError(new DvmError("invalid_arguments", error.message.replace(/^error: /, "")), false, { event: "error" });
40434
+ }).description("Fetch messages from a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--after <seq>", "Only show messages with seq > N").option("--no-stream", "Non-blocking snapshot instead of streaming until yield").option("--human", "Human-readable output instead of JSON").option("--wait", "Stay attached until the job needs input or ends; JSON output is one line per event").option("--until <duration>", "Wait limit with --wait (default: 12h; e.g. 30s, 5m, 12h)").option("--timeout <sec>", "Read timeout (default: 5s, or 60s with --wait)").action((jobId, opts) => {
40435
+ return catchErrors(() => messages(jobId, opts), opts.human, opts.wait && !opts.human ? { event: "error" } : void 0);
39847
40436
  });
39848
40437
  program2.command("message <job-id> [text]").description("Send a message in a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option(
39849
40438
  "--type <type>",
@@ -39853,7 +40442,7 @@ function buildProgram() {
39853
40442
  });
39854
40443
  program2.command("pay <job-id>").description(
39855
40444
  "Approve a pending payment request. The job's stored --max-increment still applies \u2014 a payment that exceeds it returns an over-budget error even when explicitly approved here."
39856
- ).option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--human", "Human-readable output instead of JSON").option("--timeout <sec>", "Override default timeout for streaming").option(
40445
+ ).option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--budget <amount>", "Approve a new total job budget and pay the open ask (dollars or millisats)").option("--human", "Human-readable output instead of JSON").option("--timeout <sec>", "Override default timeout for streaming").option(
39857
40446
  "--mint <url>",
39858
40447
  "Pin the Cashu spend mint for this payment (must be one the DVM accepts). Overrides any mint pinned at request time."
39859
40448
  ).option("--rail <rail>", "Force this payment onto cashu, tempo, or x402 without fallback").option(
@@ -40031,16 +40620,16 @@ Docs:
40031
40620
  ).option("--human", "Human-readable output instead of JSON").action((amount, opts) => {
40032
40621
  return catchErrors(() => walletFund(amount, opts), opts.human);
40033
40622
  });
40034
- wallet.command("cash-out <ln-address>").description(
40035
- "Move value out of the agent wallet to a Lightning address (or lnurl1\u2026 string). Fees are drawn from the wallet on top of --amount, so the stated amount is what arrives"
40623
+ wallet.command("cash-out <destination>").description(
40624
+ "Move value out of the agent wallet to a Lightning address, lnurl1\u2026 string, or BOLT11 invoice (optionally lightning:). An invoice fixes the amount; otherwise pass --amount or --all. Fees are drawn on top of --amount"
40036
40625
  ).option(
40037
40626
  "--amount <amount>",
40038
40627
  "How much should arrive. Accepts sats (1000), USD ($5), GBP (\xA35 / 5gbp), EUR (\u20AC5 / 5eur), or JPY"
40039
40628
  ).option(
40040
40629
  "--sats",
40041
40630
  "Treat numeric input as sats (default: fiat if a currency symbol/code is present \u2014 $5, \xA35, 5eur \u2014 else sats)"
40042
- ).option("--all", "Empty the wallet (or the --mint mint) \u2014 fees come out of the balance").option("--mint <url>", "Cash out from this mint only (default: every mint, richest first)").option("--max-fee <sats>", "Refuse a mint whose routing reserve + input fee exceeds this").option("--dry-run", "Quote the melt and report the fee without paying anything").option("--human", "Human-readable output instead of JSON").action((lnAddress, opts) => {
40043
- return catchErrors(() => walletCashOut(lnAddress, opts), opts.human);
40631
+ ).option("--all", "Empty the wallet (or the --mint mint) \u2014 fees come out of the balance").option("--mint <url>", "Cash out from this mint only (default: every mint, richest first)").option("--max-fee <sats>", "Refuse a mint whose routing reserve + input fee exceeds this").option("--dry-run", "Quote the melt and report the fee without paying anything").option("--human", "Human-readable output instead of JSON").action((destination, opts) => {
40632
+ return catchErrors(() => walletCashOut(destination, opts), opts.human);
40044
40633
  });
40045
40634
  wallet.command("receive-token <token>").description("Claim an external Cashu token into the agent wallet as spendable balance").option("--human", "Human-readable output instead of JSON").action((token, opts) => {
40046
40635
  return catchErrors(() => walletReceiveToken(token, opts), opts.human);