@dvmkit/dvm-cli 0.17.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
@@ -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,
@@ -194,6 +204,8 @@ import {
194
204
  unresendablePaymentHint,
195
205
  updateJob,
196
206
  updateObservedJob,
207
+ upfrontRailPayment,
208
+ usdMicro,
197
209
  walletHistory,
198
210
  walletInvoiceFundingAdvice,
199
211
  warnInvalidJobIdentityHeader,
@@ -201,7 +213,7 @@ import {
201
213
  withIdentityRecovery,
202
214
  withJobTokenRedaction,
203
215
  withRequestResultRecovery
204
- } from "./chunk-DE7TEOUR.js";
216
+ } from "./chunk-VSOIBYBF.js";
205
217
  import {
206
218
  connectedTempoAccount,
207
219
  generateTempoKey,
@@ -245,6 +257,7 @@ import {
245
257
  hasUnsavedJobState,
246
258
  info,
247
259
  json,
260
+ jsonEvent,
248
261
  monetaryJson,
249
262
  parseBudget,
250
263
  raw,
@@ -254,7 +267,7 @@ import {
254
267
  tryResolveBtcUsdRate,
255
268
  tryX402Payment,
256
269
  withOutputWarnings
257
- } from "./chunk-R6FZT6S2.js";
270
+ } from "./chunk-RYFCHR6Z.js";
258
271
  import {
259
272
  assertX402WalletIdle
260
273
  } from "./chunk-REIUNZQX.js";
@@ -9195,6 +9208,52 @@ async function readBoundedBody(response, limit) {
9195
9208
  }
9196
9209
  var MAX_COMPATIBILITY_BODY_BYTES = 16384;
9197
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
+
9198
9257
  // src/lib/credit-notice.ts
9199
9258
  function buildCreditFundingSkipped(args) {
9200
9259
  return {
@@ -9213,7 +9272,7 @@ function noteCreditFundingSkipped(skipped, human) {
9213
9272
  function buildCreditSuggestion(args) {
9214
9273
  const { dvm, suppressed } = args;
9215
9274
  const amount = `$${formatUsd(suppressed.fundMicro / 1e6)}`;
9216
- const fundCommand = `dvm credit fund ${shellQuoteArg(dvm)}`;
9275
+ const fundCommand = `dvm credit fund ${shellQuoteArg(dvm)}${suppressed.reason === "open" ? ` --amount ${shellQuoteArg(`$${exactUsd(suppressed.fundMicro)}`)}` : ""}`;
9217
9276
  const optIn = `dvm credit posture auto --dvm ${shellQuoteArg(dvm)}`;
9218
9277
  const covers = args.coversJobs !== void 0 && args.coversJobs > 1 ? ` about ${String(args.coversJobs)} jobs` : " a run of jobs";
9219
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.`;
@@ -9230,7 +9289,7 @@ function buildCreditSuggestion(args) {
9230
9289
  opt_in_command: optIn,
9231
9290
  opt_in_command_global: "dvm credit posture auto",
9232
9291
  display,
9233
- 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.`
9234
9293
  };
9235
9294
  }
9236
9295
  function buildCreditFundingReport(args) {
@@ -9388,8 +9447,18 @@ function buildCreditRefillDrainPending(args) {
9388
9447
  };
9389
9448
  }
9390
9449
  function noteCreditSuggestion(suggestion, human) {
9391
- info(`${suggestion.display} ${suggestion.hint}`);
9392
- 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);
9393
9462
  }
9394
9463
  function noteCreditFunding(report, human, stage = "settled") {
9395
9464
  info(stage === "in_flight" ? inFlightLine(report) : report.display);
@@ -9507,6 +9576,7 @@ function noteCreditRefillUnavailable(unavailable, human) {
9507
9576
  function takeCreditNoticeFields() {
9508
9577
  const taken = { ...pending };
9509
9578
  pending = {};
9579
+ staged = void 0;
9510
9580
  return taken;
9511
9581
  }
9512
9582
  function creditFundingSpendDisplay(outcome) {
@@ -9649,7 +9719,12 @@ function inFlightLine(report) {
9649
9719
  const route = inFlightRouteDisplay(report.route, report.x402_flavour, report.tempo_intent);
9650
9720
  return `Funding ${amount} of prepaid credit at ${report.dvm} \u2014 ${route}, because ${whyFunded(report.reason)}. It lands when the job does. ${POSTURE_FOOTER}`;
9651
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
+ }
9652
9726
  var pending = {};
9727
+ var staged;
9653
9728
 
9654
9729
  // src/lib/credit-per-dvm.ts
9655
9730
  function providerDvmIdentity(providerInfo) {
@@ -9855,7 +9930,10 @@ async function tryCreditPayment(args) {
9855
9930
  );
9856
9931
  const amountMsats = Math.max(1, usdToMsats(ask.amount_micro / 1e6, rate));
9857
9932
  if (!Number.isSafeInteger(amountMsats)) return false;
9858
- 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)
9859
9937
  throw new DvmError("over_budget", "The exact balance charge would exceed this job's budget.");
9860
9938
  if (amountMsats > args.policy.autoPayBelowMsats) return false;
9861
9939
  const selectedBinding = binding;
@@ -9884,7 +9962,7 @@ async function tryCreditPayment(args) {
9884
9962
  if (booked) return booked;
9885
9963
  if ((current.paymentsHonoured ?? 0) >= args.policy.maxPayments)
9886
9964
  throw new DvmError("payment_cap_exceeded", "Job has reached its maximum payment count.");
9887
- if ((current.totalPaidMsats ?? 0) + amountMsats > args.policy.maxTotalMsats)
9965
+ if (!budgetVerdict(args.policy, current, budgetAsk).fits)
9888
9966
  throw new DvmError("over_budget", "The exact balance charge would exceed this job's budget.");
9889
9967
  current.creditBinding = selectedBinding;
9890
9968
  current.pendingCreditPayment = {
@@ -11072,6 +11150,76 @@ function publicRequestIdField(entry) {
11072
11150
  return publicRequestId ? { publicRequestId } : {};
11073
11151
  }
11074
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
+
11075
11223
  // src/lib/agent-wallet-retry.ts
11076
11224
  var TRANSIENT_PAYMENT_BACKOFF_MS = [250, 500, 1e3, 2e3, 4e3];
11077
11225
  var TRANSIENT_PAYMENT_CODES = /* @__PURE__ */ new Set(["proof_pending", "mint_unreachable"]);
@@ -11256,15 +11404,15 @@ function parseTempoNetwork(value, source) {
11256
11404
  var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
11257
11405
  import {
11258
11406
  closeSync,
11259
- existsSync as existsSync2,
11407
+ existsSync as existsSync3,
11260
11408
  fsyncSync,
11261
11409
  mkdirSync,
11262
11410
  openSync,
11263
- readFileSync as readFileSync2,
11264
- renameSync,
11265
- writeFileSync
11411
+ readFileSync as readFileSync3,
11412
+ renameSync as renameSync2,
11413
+ writeFileSync as writeFileSync2
11266
11414
  } from "fs";
11267
- import { join as join2 } from "path";
11415
+ import { join as join3 } from "path";
11268
11416
  function saveRequestIntent(intent) {
11269
11417
  assertRequestId(intent.requestId);
11270
11418
  assertNoPaymentOrAuthSecrets(intent.body);
@@ -11277,26 +11425,26 @@ function saveRequestIntent(intent) {
11277
11425
  throw error;
11278
11426
  }
11279
11427
  fsyncDirectory(REQUEST_INTENTS_DIR);
11280
- const temp = join2(dir, `intent.${String(process.pid)}.tmp`);
11281
- const target = join2(dir, "intent.json");
11428
+ const temp = join3(dir, `intent.${String(process.pid)}.tmp`);
11429
+ const target = join3(dir, "intent.json");
11282
11430
  const fd = openSync(temp, "wx", 384);
11283
11431
  try {
11284
- writeFileSync(fd, JSON.stringify(intent, null, 2) + "\n");
11432
+ writeFileSync2(fd, JSON.stringify(intent, null, 2) + "\n");
11285
11433
  fsyncSync(fd);
11286
11434
  } finally {
11287
11435
  closeSync(fd);
11288
11436
  }
11289
- renameSync(temp, target);
11437
+ renameSync2(temp, target);
11290
11438
  fsyncDirectory(dir);
11291
11439
  return true;
11292
11440
  }
11293
11441
  function loadRequestIntent(requestId) {
11294
11442
  assertRequestId(requestId);
11295
11443
  const dir = intentDirectory(requestId);
11296
- if (!existsSync2(dir)) return null;
11297
- const path = join2(dir, "intent.json");
11444
+ if (!existsSync3(dir)) return null;
11445
+ const path = join3(dir, "intent.json");
11298
11446
  try {
11299
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
11447
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
11300
11448
  if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
11301
11449
  throw new Error("invalid shape");
11302
11450
  return parsed;
@@ -11313,22 +11461,22 @@ function recordRequestRailPayment(requestId, payment) {
11313
11461
  assertRequestId(requestId);
11314
11462
  if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
11315
11463
  const dir = intentDirectory(requestId);
11316
- const target = join2(dir, "intent.json");
11464
+ const target = join3(dir, "intent.json");
11317
11465
  const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
11318
11466
  try {
11319
11467
  const intent = loadRequestIntent(requestId);
11320
11468
  if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
11321
11469
  if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
11322
11470
  throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
11323
- const temp = join2(dir, `rail.${String(process.pid)}.tmp`);
11471
+ const temp = join3(dir, `rail.${String(process.pid)}.tmp`);
11324
11472
  const fd = openSync(temp, "w", 384);
11325
11473
  try {
11326
- writeFileSync(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
11474
+ writeFileSync2(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
11327
11475
  fsyncSync(fd);
11328
11476
  } finally {
11329
11477
  closeSync(fd);
11330
11478
  }
11331
- renameSync(temp, target);
11479
+ renameSync2(temp, target);
11332
11480
  fsyncDirectory(dir);
11333
11481
  } finally {
11334
11482
  release();
@@ -11371,7 +11519,7 @@ function assertRequestId(requestId) {
11371
11519
  );
11372
11520
  }
11373
11521
  function intentDirectory(requestId) {
11374
- return join2(REQUEST_INTENTS_DIR, requestId);
11522
+ return join3(REQUEST_INTENTS_DIR, requestId);
11375
11523
  }
11376
11524
  function fsyncDirectory(path) {
11377
11525
  if (process.platform === "win32") return;
@@ -11398,21 +11546,89 @@ function isSignedRequestAudience(value) {
11398
11546
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11399
11547
  const seq = opts?.requestSeq;
11400
11548
  let replacing = false;
11401
- 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 };
11402
11589
  replacing = opts?.approval === "explicit" && seq !== void 0 && loadJob(jobId)?.askPaymentBlocks?.[seq] !== void 0;
11590
+ let newPayment = false;
11403
11591
  const guardedTransport = new Proxy(transport, {
11404
11592
  get(target, key) {
11405
11593
  if (key === "sendMessage") return async (...args) => {
11406
11594
  assertOwned();
11595
+ if (newPayment && approvedPolicy && !budgetSaved) {
11596
+ assertBudgetNotBelowSpend(approvedPolicy, loadJob(jobId));
11597
+ updateJob(jobId, { policy: approvedPolicy, budgetRefusals: {} });
11598
+ budgetSaved = true;
11599
+ }
11407
11600
  return target.sendMessage(...args);
11408
11601
  };
11409
11602
  const value = Reflect.get(target, key, target);
11410
11603
  return typeof value === "function" ? value.bind(target) : value;
11411
11604
  }
11412
11605
  });
11413
- 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;
11414
11620
  }).catch((error) => {
11621
+ if (budgetSaved && !(error instanceof DvmError)) error = new DvmError("payment_failed", "The payment was not completed.");
11415
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
+ }
11416
11632
  const job = loadJob(jobId);
11417
11633
  if (!job || !provider.endpoint || !sameEndpoint(job.endpoint, provider.endpoint)) throw error;
11418
11634
  let requestId;
@@ -11436,6 +11652,7 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11436
11652
  }, ["job_id"]);
11437
11653
  throw error;
11438
11654
  }
11655
+ if (budgetSaved) throw error;
11439
11656
  const command = requestId ? `dvm request-result ${shellQuoteArg(requestId)}` : `dvm status ${guidanceJobArg(jobId)}`;
11440
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.`;
11441
11658
  error.data = providerFields({
@@ -11446,9 +11663,37 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11446
11663
  next_step: [typeof error.data?.next_step === "string" ? error.data.next_step : void 0, recovery].filter(Boolean).join(" ")
11447
11664
  }, ["job_id"]);
11448
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;
11449
11680
  });
11450
11681
  }
11451
- 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) {
11452
11697
  if (hasPendingAcceptedJobAccess(jobId, provider.endpoint)) throw new DvmError(
11453
11698
  "local_job_state_unsaved",
11454
11699
  "Private recovery state must be folded before another payment can be sent.",
@@ -11526,17 +11771,36 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11526
11771
  throw unconfirmedPaymentError(jobId, "An earlier payment for this request is unconfirmed and this CLI holds no copy to re-send.");
11527
11772
  }
11528
11773
  const latest = loadJob(jobId);
11529
- const spent = latest?.totalPaidMsats ?? 0;
11530
11774
  const paymentsHonoured = latest?.paymentsHonoured ?? 0;
11531
- 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);
11532
11790
  return "over-budget";
11533
- }
11534
- 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
+ );
11535
11800
  return "over-budget";
11536
11801
  }
11537
- if (paymentsHonoured >= policy.maxPayments) {
11538
- return "payment-cap-exceeded";
11539
- }
11802
+ let signedRefusal;
11803
+ if (paymentsHonoured >= policy.maxPayments) return "payment-cap-exceeded";
11540
11804
  if (strictPerCall)
11541
11805
  throw new DvmError(
11542
11806
  "strict_per_call_mid_job_payment",
@@ -11565,6 +11829,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11565
11829
  }
11566
11830
  if (opts?.requestSeq !== void 0 && loadJob(jobId)?.askPaymentBlocks?.[opts.requestSeq] && opts.approval !== "explicit")
11567
11831
  return "needs-approval";
11832
+ beforeNewPayment?.();
11568
11833
  if (matchingEndpoint && !balanceRefused && opts?.rail === void 0) {
11569
11834
  const creditPaid = await tryCreditPayment({
11570
11835
  jobId,
@@ -11603,6 +11868,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11603
11868
  transport,
11604
11869
  provider,
11605
11870
  btcRate,
11871
+ usdMicro: dollarBoundUsdMicro(budgetAsk),
11606
11872
  pinnedMint,
11607
11873
  maxCashuFeeSats,
11608
11874
  strictPerCall,
@@ -11616,7 +11882,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11616
11882
  }
11617
11883
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11618
11884
  const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
11619
- const { tryX402Payment: tryX402Payment2 } = await import("./client-3JOMNAIQ.js");
11885
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-PVRLAMI3.js");
11620
11886
  const wallet = loadX402Wallet2();
11621
11887
  if (wallet) {
11622
11888
  let proof;
@@ -11643,6 +11909,18 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11643
11909
  if (!(err instanceof DvmError) || err.code !== "x402_build_failed") throw err;
11644
11910
  proof = null;
11645
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
+ }
11646
11924
  if (proof) {
11647
11925
  await enforceGlobalBudget({ plannedMsats: proof.amountMsats, btcRate: proof.btcRate });
11648
11926
  return deliverSignedRailPayment({
@@ -11658,6 +11936,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11658
11936
  content: { x402_payment: proof.paymentHeader, amount_msats: proof.amountMsats },
11659
11937
  requestAmountMsats: request2.amount_msats,
11660
11938
  amountMsats: proof.amountMsats,
11939
+ // Book the dollars the signed authorization moves, not the ask's figure.
11940
+ ...usdMicroField(signedUsd),
11661
11941
  btcRate: proof.btcRate,
11662
11942
  amountUsdcMicro: proof.amountUsdcMicro,
11663
11943
  approval: approval?.approval,
@@ -11671,7 +11951,15 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11671
11951
  const tempoRate = btcRate > 0 ? btcRate : (await tryResolveBtcUsdRate())?.rate ?? 0;
11672
11952
  const cred = await tryMppCredential(request2.tempo.challenges, request2.amount_msats, tempoRate);
11673
11953
  if (cred) {
11674
- 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);
11675
11963
  await enforceGlobalBudget({ plannedMsats: paidMsats, btcRate: tempoRate });
11676
11964
  return deliverSignedRailPayment({
11677
11965
  jobId,
@@ -11686,6 +11974,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11686
11974
  content: { tempo_credential: cred, amount_msats: paidMsats },
11687
11975
  requestAmountMsats: request2.amount_msats,
11688
11976
  amountMsats: paidMsats,
11977
+ ...usdMicroField(signedUsd),
11689
11978
  btcRate: tempoRate,
11690
11979
  approval: approval?.approval,
11691
11980
  reason: request2.reason
@@ -11693,7 +11982,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11693
11982
  });
11694
11983
  }
11695
11984
  }
11696
- return "needs-approval";
11985
+ return signedRefusal ? refuse(signedRefusal) : "needs-approval";
11697
11986
  }
11698
11987
  function unconfirmedPaymentError(jobId, message2, hint = unresendablePaymentHint(jobId)) {
11699
11988
  return new DvmError("payment_unconfirmed", `${message2} No new payment was signed.`, hint);
@@ -11755,7 +12044,7 @@ async function deliverSignedRailPayment(args) {
11755
12044
  args.redelivery
11756
12045
  );
11757
12046
  if (!sent.tracked) {
11758
- addPayment(jobId, submission.amountMsats, args.approval);
12047
+ addPayment(jobId, submission.amountMsats, args.approval, submission.usdMicro);
11759
12048
  recordSpend({
11760
12049
  msats: submission.amountMsats,
11761
12050
  btcRate: submission.btcRate,
@@ -11844,6 +12133,7 @@ async function tryAgentWalletMidJobPayment(args) {
11844
12133
  ...prepared.fromReserve ? { reserve: true } : {},
11845
12134
  requestAmountMsats: request2.amount_msats,
11846
12135
  amountMsats: request2.amount_msats,
12136
+ ...usdMicroField(args.usdMicro),
11847
12137
  btcRate,
11848
12138
  approval: approval?.approval,
11849
12139
  reason: request2.reason
@@ -11890,7 +12180,7 @@ async function deliverAgentWalletPayment(args) {
11890
12180
  signed_at_ms: Date.now()
11891
12181
  }
11892
12182
  });
11893
- addPayment(jobId, request2.amount_msats, approval);
12183
+ addPayment(jobId, request2.amount_msats, approval, submission.usdMicro);
11894
12184
  recordSpend({
11895
12185
  msats: request2.amount_msats,
11896
12186
  btcRate: submission.btcRate,
@@ -12027,6 +12317,9 @@ async function tryMppCredential(challenges, amountMsats, btcRate) {
12027
12317
  onError: "null"
12028
12318
  });
12029
12319
  }
12320
+ function usdMicroField(value) {
12321
+ return value !== void 0 ? { usdMicro: value } : {};
12322
+ }
12030
12323
 
12031
12324
  // src/lib/refund-claim.ts
12032
12325
  async function claimInboundPayments(jobId, messages2) {
@@ -12167,16 +12460,18 @@ async function streamLoop(opts) {
12167
12460
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
12168
12461
  const declined = () => persistLocalState && loadJob(jobId)?.callerDeclined === true;
12169
12462
  async function recordAutoPayment(result, request2, seq) {
12170
- autoPayments.push({
12463
+ const payment = {
12171
12464
  amount_msats: result.amountMsats,
12172
12465
  rail: result.rail,
12173
12466
  reason: asProviderText(request2.reason),
12174
12467
  ...result.amountUsdcMicro !== void 0 && { amount_usdc_microunits: result.amountUsdcMicro },
12175
12468
  display: paidConfirmationDisplay(result, request2.fiat_amount)
12176
- });
12469
+ };
12470
+ autoPayments.push(payment);
12177
12471
  if (persistLocalState) markPaymentRequestAnswered(jobId, seq);
12178
12472
  answeredSeqs.add(seq);
12179
12473
  justAutoPaid = true;
12474
+ opts.onAutoPayment?.(payment, seq);
12180
12475
  }
12181
12476
  let pendingAction = null;
12182
12477
  const pending4 = persistLocalState ? loadJob(jobId)?.pendingCreditPayment : void 0;
@@ -12185,11 +12480,19 @@ async function streamLoop(opts) {
12185
12480
  try {
12186
12481
  result = await handlePaymentRequest(jobId, pending4.request, policy, transport, provider, {
12187
12482
  jobToken,
12188
- requestSeq: pending4.authorization.request_seq
12483
+ requestSeq: pending4.authorization.request_seq,
12484
+ useStoredPolicy: true
12189
12485
  });
12190
12486
  } catch (error) {
12191
12487
  if (error instanceof DvmError && error.code === "payment_settling")
12192
- 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
+ };
12193
12496
  throw error;
12194
12497
  }
12195
12498
  if (typeof result === "object") await recordAutoPayment(result, pending4.request, pending4.authorization.request_seq);
@@ -12199,7 +12502,7 @@ async function streamLoop(opts) {
12199
12502
  timestamp: 0,
12200
12503
  type: "payment-request",
12201
12504
  content: pending4.request
12202
- }], void 0, policy ? { policy, totalPaidMsats: loadJob(jobId)?.totalPaidMsats } : void 0);
12505
+ }], void 0, policy ? budgetContext(policy, loadJob(jobId)) : void 0);
12203
12506
  }
12204
12507
  const deadline = opts.timeoutMs === void 0 ? void 0 : Date.now() + Math.max(0, opts.timeoutMs);
12205
12508
  const nextPollOptions = () => {
@@ -12291,12 +12594,14 @@ async function streamLoop(opts) {
12291
12594
  }
12292
12595
  if (lastYield2?.type === "payment-request" && lastYield2.seq === pendingPayment?.seq && policy && !declined()) {
12293
12596
  const req = lastYield2.content;
12294
- 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)) {
12295
12599
  let result;
12296
12600
  try {
12297
12601
  result = await handlePaymentRequest(jobId, req, policy, transport, provider, {
12298
12602
  jobToken,
12299
- requestSeq: lastYield2.seq
12603
+ requestSeq: lastYield2.seq,
12604
+ useStoredPolicy: true
12300
12605
  });
12301
12606
  } catch (error) {
12302
12607
  if (error instanceof DvmError && ["payment_settling", "payment_unconfirmed"].includes(error.code)) {
@@ -12320,7 +12625,7 @@ async function streamLoop(opts) {
12320
12625
  throw new DvmError(
12321
12626
  "payment_cap_exceeded",
12322
12627
  "Job has reached its maximum payment count.",
12323
- `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),
12324
12629
  {
12325
12630
  anchor: "max_payments_exceeded",
12326
12631
  display: `Payment cap reached (${cap2} payment${cap2 === 1 ? "" : "s"})`,
@@ -12362,7 +12667,7 @@ async function streamLoop(opts) {
12362
12667
  if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
12363
12668
  for (const seq of answeredYieldSeqs(allMessages)) answeredSeqs.add(seq);
12364
12669
  const terminal = allMessages.some((msg) => msg.type === "complete" || msg.type === "cancel") || declined();
12365
- 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);
12366
12671
  let nextAction = withRefundNextAction(jobId, yieldAction ?? (terminal ? null : pollNextAction(jobId)), refunds);
12367
12672
  const lastYield = findLastYield(allMessages);
12368
12673
  const heldJob = persistLocalState ? loadJob(jobId) : null;
@@ -12384,7 +12689,7 @@ async function streamLoop(opts) {
12384
12689
  ));
12385
12690
  if (hasUnsavedJobState() && !terminal)
12386
12691
  nextAction = pollNextAction(jobId, "Local state may lag; refresh this job before another payment.");
12387
- return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
12692
+ return { messages: allMessages, autoPayments, refunds, nextAction, cursor, ...paymentUnresolved && { paymentInFlight: true } };
12388
12693
  }
12389
12694
  function isMessagePollTimeout(err) {
12390
12695
  return isAbortError(err) || err instanceof DvmError && err.code === "timeout";
@@ -12396,6 +12701,16 @@ function findLastYield(messages2) {
12396
12701
  }
12397
12702
  return void 0;
12398
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
+ }
12399
12714
 
12400
12715
  // src/lib/schema-defaults.ts
12401
12716
  function applyJsonSchemaDefaults(schema, data) {
@@ -14394,7 +14709,7 @@ async function settleCreditAfterJob(args) {
14394
14709
  }
14395
14710
  }
14396
14711
  if (args.allowTopup !== false) {
14397
- const refill = args.refillPocket ?? (await import("./pocket-refill-5BEM22UM.js")).refillPocketIfLow;
14712
+ const refill = args.refillPocket ?? (await import("./pocket-refill-6UL6CHD5.js")).refillPocketIfLow;
14398
14713
  await refill({ human: args.human }).catch(() => void 0);
14399
14714
  }
14400
14715
  }
@@ -19696,7 +20011,7 @@ import {
19696
20011
  } from "crypto";
19697
20012
 
19698
20013
  // src/lib/secret-input.ts
19699
- import { fstatSync, readFileSync as readFileSync3, realpathSync } from "fs";
20014
+ import { fstatSync, readFileSync as readFileSync4, realpathSync } from "fs";
19700
20015
  import { homedir } from "os";
19701
20016
  import { resolve, sep } from "path";
19702
20017
  var BLOCKED_SECRET_PATHS = [
@@ -19776,7 +20091,7 @@ function readSecretFile(path, config2) {
19776
20091
  throw err;
19777
20092
  }
19778
20093
  assertSafeFilePath(real);
19779
- return readFileSync3(real, "utf-8").trim();
20094
+ return readFileSync4(real, "utf-8").trim();
19780
20095
  }
19781
20096
  function readSecretStdin(config2) {
19782
20097
  return new Promise((resolveStdin, reject) => {
@@ -22037,8 +22352,8 @@ function x402WrongAssetHint(asset) {
22037
22352
  }
22038
22353
 
22039
22354
  // src/lib/build-freshness.ts
22040
- import { existsSync as existsSync3, readdirSync, statSync } from "fs";
22041
- 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";
22042
22357
  import { fileURLToPath as fileURLToPath2 } from "url";
22043
22358
  var EXTRA_SOURCES = ["package.json", "tsup.config.ts"];
22044
22359
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "__snapshots__"]);
@@ -22057,12 +22372,12 @@ function checkBuildFreshness(opts) {
22057
22372
  skipReason
22058
22373
  });
22059
22374
  if (root === null) return skipped("running_from_source");
22060
- const bundlePath = join3(root, "dist", "dvm.js");
22061
- if (dirname2(moduleDir) !== root || !existsSync3(bundlePath)) {
22375
+ const bundlePath = join4(root, "dist", "dvm.js");
22376
+ if (dirname2(moduleDir) !== root || !existsSync4(bundlePath)) {
22062
22377
  return skipped("running_from_source");
22063
22378
  }
22064
- const srcDir = join3(root, "src");
22065
- if (!existsSync3(srcDir)) return skipped("no_source_tree");
22379
+ const srcDir = join4(root, "src");
22380
+ if (!existsSync4(srcDir)) return skipped("no_source_tree");
22066
22381
  const builtAtMs = statSync(bundlePath).mtimeMs;
22067
22382
  const newer = [];
22068
22383
  let newestMs = 0;
@@ -22071,7 +22386,7 @@ function checkBuildFreshness(opts) {
22071
22386
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
22072
22387
  if (budget2.left-- <= 0) return;
22073
22388
  if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
22074
- const abs = join3(dir, entry.name);
22389
+ const abs = join4(dir, entry.name);
22075
22390
  const relPath = rel ? `${rel}/${entry.name}` : entry.name;
22076
22391
  if (entry.isDirectory()) {
22077
22392
  visit(abs, relPath, budget2);
@@ -22086,8 +22401,8 @@ function checkBuildFreshness(opts) {
22086
22401
  const budget = { left: MAX_ENTRIES };
22087
22402
  visit(srcDir, "src", budget);
22088
22403
  for (const name of EXTRA_SOURCES) {
22089
- const abs = join3(root, name);
22090
- if (!existsSync3(abs)) continue;
22404
+ const abs = join4(root, name);
22405
+ if (!existsSync4(abs)) continue;
22091
22406
  const mtimeMs = statSync(abs).mtimeMs;
22092
22407
  if (mtimeMs > newestMs) newestMs = mtimeMs;
22093
22408
  if (mtimeMs > builtAtMs) newer.push({ path: name, mtimeMs });
@@ -22105,7 +22420,7 @@ function checkBuildFreshness(opts) {
22105
22420
  function findPackageRoot(start) {
22106
22421
  let dir = start;
22107
22422
  for (; ; ) {
22108
- if (existsSync3(join3(dir, "package.json"))) return dir;
22423
+ if (existsSync4(join4(dir, "package.json"))) return dir;
22109
22424
  const parent = dirname2(dir);
22110
22425
  if (parent === dir) return null;
22111
22426
  dir = parent;
@@ -22113,25 +22428,25 @@ function findPackageRoot(start) {
22113
22428
  }
22114
22429
 
22115
22430
  // src/lib/caller-state.ts
22116
- import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
22117
- 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";
22118
22433
 
22119
22434
  // src/lib/request-refusal-store.ts
22120
22435
  import {
22121
22436
  closeSync as closeSync2,
22122
- existsSync as existsSync4,
22437
+ existsSync as existsSync5,
22123
22438
  fsyncSync as fsyncSync2,
22124
22439
  openSync as openSync2,
22125
- readFileSync as readFileSync4,
22126
- renameSync as renameSync2,
22440
+ readFileSync as readFileSync5,
22441
+ renameSync as renameSync3,
22127
22442
  rmSync,
22128
- writeFileSync as writeFileSync2
22443
+ writeFileSync as writeFileSync3
22129
22444
  } from "fs";
22130
- import { join as join4 } from "path";
22131
- 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");
22132
22447
  var SAFE_TOKEN = /^[a-z0-9_.:-]{1,64}$/;
22133
22448
  function requestIntentMayExist(requestId) {
22134
- return existsSync4(join4(REQUEST_INTENTS_DIR, requestId));
22449
+ return existsSync5(join5(REQUEST_INTENTS_DIR, requestId));
22135
22450
  }
22136
22451
  function recordRequestRefusal(requestId, refusal) {
22137
22452
  if (!isPublicRequestId(requestId) || requestIntentMayExist(requestId)) return false;
@@ -22148,12 +22463,12 @@ function recordRequestRefusal(requestId, refusal) {
22148
22463
  const temp = `${target}.${String(process.pid)}.tmp`;
22149
22464
  const fd = openSync2(temp, "w", 384);
22150
22465
  try {
22151
- writeFileSync2(fd, JSON.stringify(record2, null, 2) + "\n");
22466
+ writeFileSync3(fd, JSON.stringify(record2, null, 2) + "\n");
22152
22467
  fsyncSync2(fd);
22153
22468
  } finally {
22154
22469
  closeSync2(fd);
22155
22470
  }
22156
- renameSync2(temp, target);
22471
+ renameSync3(temp, target);
22157
22472
  } catch {
22158
22473
  }
22159
22474
  return true;
@@ -22168,7 +22483,7 @@ function clearRequestRefusal(requestId) {
22168
22483
  function loadRequestRefusal(requestId) {
22169
22484
  if (!isPublicRequestId(requestId)) return null;
22170
22485
  try {
22171
- const parsed = JSON.parse(readFileSync4(refusalPath(requestId), "utf8"));
22486
+ const parsed = JSON.parse(readFileSync5(refusalPath(requestId), "utf8"));
22172
22487
  if (parsed.v !== 1 || parsed.requestId !== requestId || typeof parsed.code !== "string" || typeof parsed.refusedAt !== "number" || parsed.reason !== void 0 && typeof parsed.reason !== "string") {
22173
22488
  return null;
22174
22489
  }
@@ -22178,20 +22493,20 @@ function loadRequestRefusal(requestId) {
22178
22493
  }
22179
22494
  }
22180
22495
  function refusalPath(requestId) {
22181
- return join4(REQUEST_REFUSALS_DIR, `${requestId}.json`);
22496
+ return join5(REQUEST_REFUSALS_DIR, `${requestId}.json`);
22182
22497
  }
22183
22498
 
22184
22499
  // src/lib/caller-state.ts
22185
22500
  function detectSetupState() {
22186
22501
  return {
22187
22502
  existingState: {
22188
- jobs: existsSync5(JOBS_FILE),
22189
- messages: existsSync5(MESSAGES_DIR)
22503
+ jobs: existsSync6(JOBS_FILE),
22504
+ messages: existsSync6(MESSAGES_DIR)
22190
22505
  },
22191
22506
  missing: {
22192
- config: !existsSync5(CONFIG_FILE),
22193
- identity: !existsSync5(IDENTITIES_FILE),
22194
- wallet: !existsSync5(WALLET_FILE)
22507
+ config: !existsSync6(CONFIG_FILE),
22508
+ identity: !existsSync6(IDENTITIES_FILE),
22509
+ wallet: !existsSync6(WALLET_FILE)
22195
22510
  }
22196
22511
  };
22197
22512
  }
@@ -22261,6 +22576,16 @@ var FILE_SPECS = [
22261
22576
  // A store written by an older dvm keeps its old mode until the next write
22262
22577
  // replaces it — doctor warns, and the write repairs it.
22263
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
+ },
22264
22589
  {
22265
22590
  name: "x402_channels",
22266
22591
  path: X402_CHANNELS_FILE,
@@ -22321,17 +22646,17 @@ function findQuarantinedCreditStores() {
22321
22646
  } catch {
22322
22647
  return [];
22323
22648
  }
22324
- 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 }));
22325
22650
  }
22326
22651
  function checkOne(spec) {
22327
- const exists = existsSync5(spec.path);
22652
+ const exists = existsSync6(spec.path);
22328
22653
  if (!exists) {
22329
22654
  return { name: spec.name, path: spec.path, exists: false };
22330
22655
  }
22331
22656
  const row = { name: spec.name, path: spec.path, exists: true };
22332
22657
  if (spec.json) {
22333
22658
  try {
22334
- JSON.parse(readFileSync5(spec.path, "utf-8"));
22659
+ JSON.parse(readFileSync6(spec.path, "utf-8"));
22335
22660
  row.parseable = true;
22336
22661
  } catch (err) {
22337
22662
  row.parseable = false;
@@ -22360,7 +22685,7 @@ function checkSecretDirectory(dir, row) {
22360
22685
  try {
22361
22686
  const offenders = [];
22362
22687
  for (const name of readdirSync2(dir)) {
22363
- const path = join5(dir, name);
22688
+ const path = join6(dir, name);
22364
22689
  const stat2 = statSync2(path);
22365
22690
  if (!stat2.isFile()) continue;
22366
22691
  const mode = stat2.mode & 511;
@@ -22381,9 +22706,9 @@ function octalMode(mode) {
22381
22706
  return "0" + mode.toString(8).padStart(3, "0");
22382
22707
  }
22383
22708
  function readBtcRateCacheAge(now = Date.now()) {
22384
- if (!existsSync5(BTC_RATE_FILE)) return null;
22709
+ if (!existsSync6(BTC_RATE_FILE)) return null;
22385
22710
  try {
22386
- const data = JSON.parse(readFileSync5(BTC_RATE_FILE, "utf-8"));
22711
+ const data = JSON.parse(readFileSync6(BTC_RATE_FILE, "utf-8"));
22387
22712
  if (typeof data.timestamp !== "number") return null;
22388
22713
  return { ageMs: now - data.timestamp };
22389
22714
  } catch {
@@ -22393,7 +22718,7 @@ function readBtcRateCacheAge(now = Date.now()) {
22393
22718
 
22394
22719
  // src/lib/mnemonic-backups.ts
22395
22720
  import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
22396
- 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";
22397
22722
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
22398
22723
  const dir = dirname3(mnemonicFile);
22399
22724
  const prefix = `${basename2(mnemonicFile)}.`;
@@ -22405,7 +22730,7 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
22405
22730
  throw err;
22406
22731
  }
22407
22732
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
22408
- const path = join6(dir, name);
22733
+ const path = join7(dir, name);
22409
22734
  const stat2 = statSync3(path);
22410
22735
  if (!stat2.isFile()) return null;
22411
22736
  const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
@@ -24301,11 +24626,11 @@ async function favRm(name, opts) {
24301
24626
  }
24302
24627
 
24303
24628
  // src/lib/byte-source.ts
24304
- import { readFileSync as readFileSync6 } from "fs";
24629
+ import { readFileSync as readFileSync7 } from "fs";
24305
24630
  import { resolve as resolve2 } from "path";
24306
24631
  var STDIN_TIMEOUT_MS2 = 1e4;
24307
24632
  function readFileText(path) {
24308
- return readFileSync6(resolve2(path), "utf-8");
24633
+ return readFileSync7(resolve2(path), "utf-8");
24309
24634
  }
24310
24635
  var StdinTimeoutError = class extends Error {
24311
24636
  constructor(timeoutMs) {
@@ -24469,7 +24794,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
24469
24794
  }
24470
24795
 
24471
24796
  // src/lib/feedback-nudges.ts
24472
- 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";
24473
24798
 
24474
24799
  // src/lib/feedback-notice.ts
24475
24800
  function buildFeedbackNudge(args) {
@@ -24521,10 +24846,10 @@ function effectiveFeedbackPosture(config2) {
24521
24846
  return { posture: DEFAULT_FEEDBACK_POSTURE, source: "default" };
24522
24847
  }
24523
24848
  function loadFeedbackNudgeState() {
24524
- if (!existsSync6(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
24849
+ if (!existsSync7(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
24525
24850
  try {
24526
24851
  const parsed = JSON.parse(
24527
- readFileSync7(FEEDBACK_NUDGES_FILE, "utf-8")
24852
+ readFileSync8(FEEDBACK_NUDGES_FILE, "utf-8")
24528
24853
  );
24529
24854
  return {
24530
24855
  ...typeof parsed.introShownAt === "string" ? { introShownAt: parsed.introShownAt } : {},
@@ -24541,7 +24866,7 @@ function recordFeedbackSent(dvmId, now = Date.now()) {
24541
24866
  ...state.perDvm[dvmId] ?? {},
24542
24867
  lastSentAt: new Date(now).toISOString()
24543
24868
  };
24544
- saveState(state);
24869
+ saveState2(state);
24545
24870
  } catch {
24546
24871
  }
24547
24872
  }
@@ -24574,7 +24899,7 @@ function noteFeedbackAfterTerminal(moment) {
24574
24899
  ...code === "feedback_first_success" ? { firstSuccessNudgedAt: stamp } : {}
24575
24900
  };
24576
24901
  if (intro) state.introShownAt = stamp;
24577
- saveState(state);
24902
+ saveState2(state);
24578
24903
  return;
24579
24904
  }
24580
24905
  if (moment.status === "completed") {
@@ -24610,15 +24935,15 @@ function coercePerDvm(perDvm) {
24610
24935
  )
24611
24936
  );
24612
24937
  }
24613
- function saveState(state) {
24938
+ function saveState2(state) {
24614
24939
  ensureConfigDir();
24615
24940
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
24616
- writeFileSync3(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
24941
+ writeFileSync4(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
24617
24942
  try {
24618
- renameSync3(tmp, FEEDBACK_NUDGES_FILE);
24943
+ renameSync4(tmp, FEEDBACK_NUDGES_FILE);
24619
24944
  } catch (err) {
24620
24945
  try {
24621
- unlinkSync(tmp);
24946
+ unlinkSync2(tmp);
24622
24947
  } catch {
24623
24948
  }
24624
24949
  throw err;
@@ -24627,9 +24952,9 @@ function saveState(state) {
24627
24952
  var nudgedThisInvocation = false;
24628
24953
 
24629
24954
  // src/lib/platform.ts
24630
- 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";
24631
24956
  import { homedir as homedir2 } from "os";
24632
- import { join as join7 } from "path";
24957
+ import { join as join8 } from "path";
24633
24958
  function getPlatformUrl() {
24634
24959
  return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
24635
24960
  }
@@ -25203,11 +25528,11 @@ import {
25203
25528
  openSync as openSync3,
25204
25529
  readdirSync as readdirSync4,
25205
25530
  rmdirSync,
25206
- unlinkSync as unlinkSync2,
25207
- writeFileSync as writeFileSync5
25531
+ unlinkSync as unlinkSync3,
25532
+ writeFileSync as writeFileSync6
25208
25533
  } from "fs";
25209
25534
  import { tmpdir } from "os";
25210
- import { join as join8 } from "path";
25535
+ import { join as join9 } from "path";
25211
25536
 
25212
25537
  // src/lib/mime-ext.ts
25213
25538
  var MIME_TO_EXT = {
@@ -25263,10 +25588,10 @@ var ArtifactSaveSession = class {
25263
25588
  let created = false;
25264
25589
  try {
25265
25590
  const directory = this.ensureDirectory();
25266
- path = join8(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
25591
+ path = join9(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
25267
25592
  fd = openSync3(path, "wx", FILE_MODE);
25268
25593
  created = true;
25269
- writeFileSync5(fd, buf);
25594
+ writeFileSync6(fd, buf);
25270
25595
  closeSync3(fd);
25271
25596
  fd = void 0;
25272
25597
  chmodSync(path, FILE_MODE);
@@ -25281,7 +25606,7 @@ var ArtifactSaveSession = class {
25281
25606
  }
25282
25607
  if (created && path) {
25283
25608
  try {
25284
- unlinkSync2(path);
25609
+ unlinkSync3(path);
25285
25610
  } catch {
25286
25611
  }
25287
25612
  }
@@ -25292,7 +25617,7 @@ var ArtifactSaveSession = class {
25292
25617
  }
25293
25618
  ensureDirectory() {
25294
25619
  if (this.directory) return this.directory;
25295
- const directory = mkdtempSync(join8(tmpdir(), "dvm-artifacts-"));
25620
+ const directory = mkdtempSync(join9(tmpdir(), "dvm-artifacts-"));
25296
25621
  try {
25297
25622
  chmodSync(directory, DIRECTORY_MODE);
25298
25623
  } catch (err) {
@@ -25428,9 +25753,12 @@ function nextActionHuman(action) {
25428
25753
  if (action.type === "respond") {
25429
25754
  return `Next: ${display} Provider is waiting for your input. ${command ? `Run \`${command}\`.` : action.hint}`;
25430
25755
  }
25756
+ if (command?.startsWith("dvm decline ")) return `Next: ${display} ${action.hint}`;
25431
25757
  const thresholdHint = action.hint.match(/ For the next run, use --auto-pay-below .+$/)?.[0] ?? "";
25432
- const decline2 = action.charged_if_declined_micro !== void 0 && command?.startsWith("dvm pay ") ? ` To stop instead, run \`dvm decline ${shellQuoteArg(action.job_id)}\`.` : "";
25433
- 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}`;
25434
25762
  }
25435
25763
  case "poll": {
25436
25764
  const hint = typeof action.hint === "string" ? action.hint : action.hint.text;
@@ -25465,8 +25793,68 @@ function readNextAction(jobId, messages2, options = {}) {
25465
25793
  return action;
25466
25794
  }
25467
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
+
25468
25847
  // src/lib/wait-for-job.ts
25469
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) {
25470
25858
  const deadline = now() + durationMs;
25471
25859
  const result = {
25472
25860
  messages: [],
@@ -25491,6 +25879,8 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25491
25879
  const messageAppendSession = opts.persistLocalState === false ? void 0 : opts.messageAppendSession ?? createMessageAppendSession(opts.jobId);
25492
25880
  let backoffMs = 1e3;
25493
25881
  let firstRead = true;
25882
+ let paymentInFlight = false;
25883
+ let seenRunning = false;
25494
25884
  const idleTimeoutMs = opts.timeoutMs ?? JOB_READ_TIMEOUT_MS;
25495
25885
  async function readWithRetry(read) {
25496
25886
  while (now() < deadline) {
@@ -25508,6 +25898,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25508
25898
  const readOptions = () => ({ jobToken: opts.jobToken, timeoutMs: Math.max(1, Math.min(idleTimeoutMs, deadline - now())) });
25509
25899
  const snapshot = await readWithRetry(() => opts.transport.status(opts.jobId, opts.provider, readOptions()));
25510
25900
  if (!snapshot) break;
25901
+ seenRunning = !isTerminalJobStatus(snapshot.status);
25511
25902
  if (isTerminalJobStatus(snapshot.status)) {
25512
25903
  result.providerStatus = snapshot;
25513
25904
  result.nextAction = null;
@@ -25574,6 +25965,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25574
25965
  }
25575
25966
  if (unresolved && !newerYield) {
25576
25967
  result.nextAction = pollNextAction(opts.jobId);
25968
+ paymentInFlight = true;
25577
25969
  await new Promise((resolve3) => setTimeout(resolve3, Math.min(retryDelayMs, Math.max(0, deadline - now()))));
25578
25970
  backoffMs = Math.min(backoffMs * 2, 3e4);
25579
25971
  continue;
@@ -25598,6 +25990,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25598
25990
  const progressed = next.cursor > result.cursor;
25599
25991
  result.cursor = Math.min(next.cursor, cursorLimit);
25600
25992
  result.nextAction = next.nextAction;
25993
+ paymentInFlight = next.paymentInFlight === true;
25601
25994
  if (hasUnsavedJobState() || next.nextAction?.type !== "poll") break;
25602
25995
  if (progressed) backoffMs = 1e3;
25603
25996
  const delay = Math.min(backoffMs, Math.max(0, deadline - now()));
@@ -25609,8 +26002,27 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25609
26002
  result.cursor = Math.min(result.cursor, ...remaining.map((seq) => seq - 1));
25610
26003
  }
25611
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 });
25612
26007
  return result;
25613
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
+ }
25614
26026
 
25615
26027
  // src/commands/messages.ts
25616
26028
  async function messages(jobId, opts) {
@@ -25708,6 +26120,13 @@ async function messagesWithAccess(jobId, opts, access) {
25708
26120
  return;
25709
26121
  }
25710
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;
25711
26130
  const streamOptions = {
25712
26131
  jobId,
25713
26132
  transport,
@@ -25722,6 +26141,18 @@ async function messagesWithAccess(jobId, opts, access) {
25722
26141
  onMessage: (msg) => {
25723
26142
  if (msg.type === "progress") formatMessageHuman(msg);
25724
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
+ }
25725
26156
  }
25726
26157
  };
25727
26158
  const waitDeadline = waitDuration === void 0 ? void 0 : Date.now() + waitDuration;
@@ -25731,6 +26162,13 @@ async function messagesWithAccess(jobId, opts, access) {
25731
26162
  } catch (err) {
25732
26163
  transport.close();
25733
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
+ }
25734
26172
  }
25735
26173
  const providerStatus = waitDeadline !== void 0 && Date.now() >= waitDeadline ? void 0 : await observeJobContent(jobId, transport, ref, {
25736
26174
  timeoutMs: waitDeadline === void 0 ? opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now())),
@@ -25764,6 +26202,18 @@ async function messagesWithAccess(jobId, opts, access) {
25764
26202
  finalizeProgressLine();
25765
26203
  }
25766
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
+ });
25767
26217
  } else {
25768
26218
  json3({
25769
26219
  jobId,
@@ -26091,11 +26541,20 @@ async function payWithAccess(jobId, opts, access) {
26091
26541
  maxCashuPrincipalSats,
26092
26542
  requestSeq,
26093
26543
  approval: "explicit",
26094
- creditRecoveryOnly: pending4 !== void 0
26544
+ creditRecoveryOnly: pending4 !== void 0,
26545
+ budget: opts.budget,
26546
+ useStoredPolicy: true
26095
26547
  });
26096
26548
  if (result === "over-budget") {
26097
26549
  transport.close();
26098
- 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
+ );
26099
26558
  }
26100
26559
  if (result === "payment-cap-exceeded") {
26101
26560
  transport.close();
@@ -26103,7 +26562,7 @@ async function payWithAccess(jobId, opts, access) {
26103
26562
  throw new DvmError(
26104
26563
  "payment_cap_exceeded",
26105
26564
  "Job has reached its maximum payment count.",
26106
- `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),
26107
26566
  {
26108
26567
  anchor: "max_payments_exceeded",
26109
26568
  display: `Payment cap reached (${cap2} payment${cap2 === 1 ? "" : "s"})`,
@@ -26124,7 +26583,7 @@ async function payWithAccess(jobId, opts, access) {
26124
26583
  jobId,
26125
26584
  transport,
26126
26585
  provider: ref,
26127
- policy: stored.policy,
26586
+ policy: loadJob(jobId)?.policy ?? stored.policy,
26128
26587
  afterSeq,
26129
26588
  timeoutMs,
26130
26589
  jobToken,
@@ -26226,28 +26685,6 @@ function parsePositiveCashuSats(raw2) {
26226
26685
  return value;
26227
26686
  }
26228
26687
 
26229
- // src/lib/policy.ts
26230
- function buildPolicy(opts, btcRate) {
26231
- if (opts.maxPayments === void 0) {
26232
- throw new DvmError(
26233
- "missing_max_payments",
26234
- "Cannot build a spending policy without a payment count cap.",
26235
- "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."
26236
- );
26237
- }
26238
- if (!Number.isInteger(opts.maxPayments) || opts.maxPayments < 0) {
26239
- throw new DvmError(
26240
- "invalid_max_payments",
26241
- "Invalid value for --max-payments.",
26242
- "Pass a non-negative integer (e.g. --max-payments 1)."
26243
- );
26244
- }
26245
- const maxTotalMsats = opts.budget ? parseBudget(opts.budget, btcRate) : 0;
26246
- const autoPayBelowMsats = opts.autoPayBelow ? parseBudget(opts.autoPayBelow, btcRate) : Math.floor(maxTotalMsats * 0.2);
26247
- const maxIncrementMsats = opts.maxIncrement ? parseBudget(opts.maxIncrement, btcRate) : maxTotalMsats;
26248
- return { maxTotalMsats, autoPayBelowMsats, maxIncrementMsats, maxPayments: opts.maxPayments };
26249
- }
26250
-
26251
26688
  // src/lib/auto-pay-warning.ts
26252
26689
  function positive(value) {
26253
26690
  return typeof value === "number" && Number.isFinite(value) && value > 0;
@@ -27245,46 +27682,6 @@ function hintForUnconfigured(flag, _hasOther) {
27245
27682
  }
27246
27683
  }
27247
27684
 
27248
- // src/lib/quote-limit.ts
27249
- function quoteWithinDeclaredLimit(quote2, limitMsats, declaredLimit, rail) {
27250
- const native = quoteWithinNativeDollarLimit(quote2, declaredLimit, rail);
27251
- return native ?? quote2.priceMsats <= limitMsats;
27252
- }
27253
- function quoteWithinNativeDollarLimit(quote2, declaredLimit, rail) {
27254
- const normalizedRail = rail?.trim().toLowerCase();
27255
- if (normalizedRail === "x402") {
27256
- const native = x402QuoteWithinDollarLimit(quote2, declaredLimit);
27257
- if (native !== void 0) return native;
27258
- }
27259
- const upfront = upfrontQuoteWithinDollarLimit(quote2, declaredLimit);
27260
- if (normalizedRail === "tempo" && declaredLimit?.trim().startsWith("$")) {
27261
- return upfront ?? false;
27262
- }
27263
- return upfront;
27264
- }
27265
- function x402QuoteWithinDollarLimit(quote2, declaredLimit) {
27266
- if (!declaredLimit || !quote2.requiredUsdcMicro) return void 0;
27267
- const limitMicro = dollarLimitMicro(declaredLimit);
27268
- if (limitMicro === void 0 || !/^\d+$/.test(quote2.requiredUsdcMicro)) return void 0;
27269
- return BigInt(quote2.requiredUsdcMicro) <= limitMicro;
27270
- }
27271
- function upfrontQuoteWithinDollarLimit(quote2, declaredLimit) {
27272
- if (!declaredLimit?.trim().startsWith("$")) return void 0;
27273
- const limitMicro = dollarLimitMicro(declaredLimit);
27274
- const amountMicro = quote2.upfront?.amount_micro;
27275
- if (limitMicro === void 0 || quote2.upfront?.currency !== "usd" || amountMicro === void 0 || !Number.isSafeInteger(amountMicro) || amountMicro <= 0) {
27276
- return void 0;
27277
- }
27278
- return BigInt(amountMicro) <= limitMicro;
27279
- }
27280
- function dollarLimitMicro(declaredLimit) {
27281
- const amount = /^\$(\d+)(?:\.(\d{1,6}))?$/.exec(declaredLimit.trim());
27282
- if (!amount) return void 0;
27283
- const whole = BigInt(amount[1]);
27284
- const fraction = BigInt((amount[2] || "").padEnd(6, "0"));
27285
- return whole * 1000000n + fraction;
27286
- }
27287
-
27288
27685
  // src/lib/wallet-agent/balance.ts
27289
27686
  function groupProofsByMint(proofs) {
27290
27687
  const out = /* @__PURE__ */ new Map();
@@ -28650,7 +29047,7 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
28650
29047
  if (plan.mode === "none" && plan.suppressed) {
28651
29048
  const posture = effectiveCreditPosture(loadConfig()?.credit, ref.endpoint, attestedIdentity);
28652
29049
  const priceMicro = planRate > 0 ? msatsToMicro(chosen.priceMsats, planRate) : 0;
28653
- noteCreditSuggestion(
29050
+ stageCreditSuggestion(
28654
29051
  buildCreditSuggestion({
28655
29052
  dvm: identity.dvmId ?? ref.endpoint,
28656
29053
  endpoint: ref.endpoint,
@@ -28871,6 +29268,13 @@ function floatUsable() {
28871
29268
  return false;
28872
29269
  }
28873
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
+ }
28874
29278
  function buildSpendLabel(capability, input) {
28875
29279
  return input.length > 0 ? `${capability} \xB7 ${input.length.toLocaleString("en-US")} chars` : capability;
28876
29280
  }
@@ -28986,7 +29390,8 @@ async function payWithTempo(args, credential) {
28986
29390
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
28987
29391
  const usdcMicroUnits = Number(tempoCredentialAmountMicro(credential));
28988
29392
  const paidMsats = usdcToMsats(usdcMicroUnits / 1e6, btcRate);
28989
- 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);
28990
29395
  const usd2 = usdcMicroUnits / 1e6;
28991
29396
  const priceLabel = `$${formatUsd(usd2)} USDC`;
28992
29397
  const accountShort = `${account.address.slice(0, 6)}\u2026${account.address.slice(-4)}`;
@@ -29081,7 +29486,7 @@ async function payWithTempo(args, credential) {
29081
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)}` : ""}`
29082
29487
  );
29083
29488
  }
29084
- recordUpfrontRailPayment(effectiveJobId, { method: "tempo", amountMsats: paidMsats }, true);
29489
+ recordUpfrontRailPayment(effectiveJobId, railPayment, true);
29085
29490
  recordSpend({
29086
29491
  msats: paidMsats,
29087
29492
  btcRate: args.btcRate,
@@ -29090,6 +29495,7 @@ async function payWithTempo(args, credential) {
29090
29495
  label: buildSpendLabel(identity.capability, envelope.input)
29091
29496
  });
29092
29497
  if (receipt.status === "completed" && receipt.summary) {
29498
+ commitCreditSuggestion();
29093
29499
  markJobTerminal(effectiveJobId, "completed", completionSnapshot(receipt), {
29094
29500
  costMsats: paidMsats,
29095
29501
  paymentMethod: "tempo"
@@ -29340,7 +29746,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
29340
29746
  const priceSats = Math.ceil(chosen.priceMsats / 1e3);
29341
29747
  const maxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
29342
29748
  const baseContext = {
29343
- upfront_rail_payment: { method: "cashu", amountMsats: chosen.priceMsats },
29749
+ upfront_rail_payment: cashuUpfrontPayment(chosen, btcRate),
29344
29750
  dvm_id: identity.dvmId,
29345
29751
  capability: identity.capability,
29346
29752
  pinned_mint: opts.mint,
@@ -29469,7 +29875,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
29469
29875
  });
29470
29876
  }
29471
29877
  const pricedRequestId = opts.requestId ?? generatedRequestId;
29472
- if (pricedRequestId) recordRequestRailPayment(pricedRequestId, { method: "cashu", amountMsats: chosen.priceMsats });
29878
+ if (pricedRequestId) recordRequestRailPayment(pricedRequestId, cashuUpfrontPayment(chosen, btcRate));
29473
29879
  if (fundPlan && signing) {
29474
29880
  ensureProvisionalCredit({
29475
29881
  endpoint: ref.endpoint,
@@ -29738,7 +30144,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29738
30144
  });
29739
30145
  }
29740
30146
  await collectCashuChange(effectiveJobId, receipt.cashuChange);
29741
- recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
30147
+ recordUpfrontRailPayment(effectiveJobId, cashuUpfrontPayment(chosen, btcRate), true);
29742
30148
  if (!hasUnsavedJobState()) await commitAgentSpend({
29743
30149
  requestId: prepared.requestId,
29744
30150
  recentSpend: {
@@ -29768,6 +30174,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29768
30174
  });
29769
30175
  }
29770
30176
  if (receipt.status === "completed" && receipt.summary) {
30177
+ commitCreditSuggestion();
29771
30178
  markJobTerminal(effectiveJobId, "completed", completionSnapshot(receipt), {
29772
30179
  costMsats: chosen.priceMsats,
29773
30180
  paymentMethod: "cashu"
@@ -29876,7 +30283,8 @@ async function tryX402UpfrontPayment(args) {
29876
30283
  }
29877
30284
  async function payWithX402(args, proof) {
29878
30285
  const { transport, ref, envelope, chosen, opts, identity, policy, wallet } = args;
29879
- 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);
29880
30288
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
29881
30289
  const usdcMicroUnits = Number(proof.amountUsdcMicro);
29882
30290
  const usd2 = usdcMicroUnits / 1e6;
@@ -29961,7 +30369,7 @@ async function payWithX402(args, proof) {
29961
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."
29962
30370
  );
29963
30371
  }
29964
- recordUpfrontRailPayment(effectiveJobId, { method: "x402", amountMsats: proof.amountMsats }, true);
30372
+ recordUpfrontRailPayment(effectiveJobId, railPayment, true);
29965
30373
  recordSpend({
29966
30374
  msats: proof.amountMsats,
29967
30375
  btcRate: proof.btcRate,
@@ -29970,6 +30378,7 @@ async function payWithX402(args, proof) {
29970
30378
  label: buildSpendLabel(identity.capability, envelope.input)
29971
30379
  });
29972
30380
  if (receipt.status === "completed" && receipt.summary) {
30381
+ commitCreditSuggestion();
29973
30382
  markJobTerminal(effectiveJobId, "completed", completionSnapshot(receipt), {
29974
30383
  costMsats: proof.amountMsats,
29975
30384
  paymentMethod: "x402"
@@ -30178,6 +30587,7 @@ async function streamAfterPayment(args) {
30178
30587
  }
30179
30588
  throw new DvmError("timeout", paidTimeoutMessage);
30180
30589
  }
30590
+ if (streamedTerminal !== "failed" && streamedTerminal !== "cancelled") commitCreditSuggestion();
30181
30591
  if (human) {
30182
30592
  if (streamedTerminal === "failed" || streamedTerminal === "cancelled")
30183
30593
  info(`Status: ${streamedTerminal}${completion?.message ? `: ${completion.message}` : ""}`);
@@ -30233,6 +30643,7 @@ async function recoverViaStatusPoll(args) {
30233
30643
  costMsats: chosen.priceMsats,
30234
30644
  paymentMethod: paymentMethod2
30235
30645
  });
30646
+ commitCreditSuggestion();
30236
30647
  await collectCashuChange(jobId, status2.cashuChange);
30237
30648
  const captured = captureTransportReceipt(jobId, status2);
30238
30649
  if (!args.strictPerCall)
@@ -30869,7 +31280,7 @@ function jobSpend(job, receipt) {
30869
31280
  const totalDisplay = formatPaymentAmount(total, fiat, { anchor: false }) + valuationLabel;
30870
31281
  const budgetDisplay = job.policy ? formatPaymentAmount(
30871
31282
  job.policy.maxTotalMsats,
30872
- 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,
30873
31284
  { anchor: false }
30874
31285
  ) : void 0;
30875
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));
@@ -32550,14 +32961,14 @@ function tempoChannelDisplay(chain, endpoint, amounts) {
32550
32961
  }
32551
32962
  function x402ChannelDisplay(chain, channel) {
32552
32963
  const where = x402NetworkLabel(channel.network);
32553
- const amount = usdMicro(chain.depositMicro);
32964
+ const amount = usdMicro2(chain.depositMicro);
32554
32965
  switch (chain.status) {
32555
32966
  case "open":
32556
- 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.`;
32557
32968
  case "closing":
32558
- 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.`;
32559
32970
  case "closed":
32560
- 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.`;
32561
32972
  case "unconfirmed":
32562
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.`;
32563
32974
  case "unreadable":
@@ -32594,7 +33005,7 @@ function foreignX402ChannelClause(payer, connected) {
32594
33005
  function foreignX402ChannelHint() {
32595
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.";
32596
33007
  }
32597
- function usdMicro(micro) {
33008
+ function usdMicro2(micro) {
32598
33009
  return micro === void 0 ? void 0 : `$${(micro / 1e6).toFixed(2)}`;
32599
33010
  }
32600
33011
  var UNKNOWN_AMOUNT = "an unknown amount";
@@ -33223,7 +33634,7 @@ function mnemonicValidationError(result) {
33223
33634
  var import_qrcode = __toESM(require_lib(), 1);
33224
33635
  import { randomBytes as randomBytes3 } from "crypto";
33225
33636
  import { tmpdir as tmpdir2 } from "os";
33226
- import { join as join9 } from "path";
33637
+ import { join as join10 } from "path";
33227
33638
  async function renderQrTerminal(payload) {
33228
33639
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
33229
33640
  }
@@ -33236,7 +33647,7 @@ async function renderQrPng(payload, outPath) {
33236
33647
  });
33237
33648
  }
33238
33649
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
33239
- return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
33650
+ return join10(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
33240
33651
  }
33241
33652
 
33242
33653
  // src/lib/funding-handoff.ts
@@ -33681,18 +34092,18 @@ function examples(fetcher) {
33681
34092
  }
33682
34093
 
33683
34094
  // src/lib/error-handler.ts
33684
- async function catchErrors(fn, human) {
34095
+ async function catchErrors(fn, human, jsonFields) {
33685
34096
  const lifetimeHold = setInterval(() => void 0, 60 * 60 * 1e3);
33686
34097
  try {
33687
34098
  await fn();
33688
34099
  } catch (err) {
33689
- handleError(err, human);
34100
+ handleError(err, human, jsonFields);
33690
34101
  } finally {
33691
34102
  clearInterval(lifetimeHold);
33692
34103
  }
33693
34104
  process.exit(process.exitCode ?? 0);
33694
34105
  }
33695
- function handleError(err, human) {
34106
+ function handleError(err, human, jsonFields) {
33696
34107
  if (err instanceof DvmError) {
33697
34108
  if (human) {
33698
34109
  if (err.code === "client_upgrade_required") {
@@ -33720,6 +34131,7 @@ function handleError(err, human) {
33720
34131
  }
33721
34132
  }
33722
34133
  json({
34134
+ ...jsonFields,
33723
34135
  error,
33724
34136
  ...takeCreditNoticeFields(),
33725
34137
  ...takeFeedbackNoticeFields()
@@ -33733,6 +34145,7 @@ function handleError(err, human) {
33733
34145
  info(`Error: ${message2}`);
33734
34146
  } else {
33735
34147
  json({
34148
+ ...jsonFields,
33736
34149
  error: {
33737
34150
  code: "internal",
33738
34151
  message: message2,
@@ -35163,14 +35576,14 @@ import { randomUUID as randomUUID5 } from "crypto";
35163
35576
  // src/lib/wallet-agent/release-intents.ts
35164
35577
  var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
35165
35578
  import { createHash as createHash6 } from "crypto";
35166
- import { dirname as dirname4, join as join10 } from "path";
35579
+ import { dirname as dirname4, join as join11 } from "path";
35167
35580
  var intents = journalFile("release-intents.json");
35168
35581
  async function withReleaseLock(walletPubkey, builderHandle, mint, operation) {
35169
35582
  ensureConfigDir();
35170
35583
  const key = createHash6("sha256").update(JSON.stringify([walletPubkey, builderHandle, mint])).digest("hex");
35171
35584
  let unlock;
35172
35585
  try {
35173
- 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}`), {
35174
35587
  realpath: false,
35175
35588
  stale: 2 * 6e4,
35176
35589
  retries: 0
@@ -38060,14 +38473,14 @@ function hexToBytes2(hex2) {
38060
38473
  var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
38061
38474
  import {
38062
38475
  chmodSync as chmodSync2,
38063
- existsSync as existsSync8,
38476
+ existsSync as existsSync9,
38064
38477
  readdirSync as readdirSync5,
38065
- readFileSync as readFileSync9,
38066
- renameSync as renameSync4,
38067
- unlinkSync as unlinkSync3,
38068
- writeFileSync as writeFileSync6
38478
+ readFileSync as readFileSync10,
38479
+ renameSync as renameSync5,
38480
+ unlinkSync as unlinkSync4,
38481
+ writeFileSync as writeFileSync7
38069
38482
  } from "fs";
38070
- import { join as join11 } from "path";
38483
+ import { join as join12 } from "path";
38071
38484
  var pairingIdPattern = /^[0-9a-f]{64}$/;
38072
38485
  var stateSchema = external_exports.object({
38073
38486
  version: external_exports.literal(1),
@@ -38089,12 +38502,12 @@ var stateSchema = external_exports.object({
38089
38502
  function createWalletPairingState(state) {
38090
38503
  ensurePairingsDirectory();
38091
38504
  const path = pairingPath(state.pairing_id);
38092
- 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" });
38093
38506
  chmodSync2(path, 384);
38094
38507
  }
38095
38508
  function loadWalletPairingState(pairingId) {
38096
38509
  const path = pairingPath(pairingId);
38097
- if (!existsSync8(path)) {
38510
+ if (!existsSync9(path)) {
38098
38511
  throw new DvmError(
38099
38512
  "wallet_pairing_not_found",
38100
38513
  "No local state exists for that wallet pairing.",
@@ -38102,7 +38515,7 @@ function loadWalletPairingState(pairingId) {
38102
38515
  );
38103
38516
  }
38104
38517
  try {
38105
- return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
38518
+ return stateSchema.parse(JSON.parse(readFileSync10(path, "utf8")));
38106
38519
  } catch {
38107
38520
  throw new DvmError(
38108
38521
  "wallet_pairing_state_invalid",
@@ -38116,13 +38529,13 @@ function saveWalletPairingState(state) {
38116
38529
  ensurePairingsDirectory();
38117
38530
  const path = pairingPath(state.pairing_id);
38118
38531
  const tmp = `${path}.tmp`;
38119
- writeFileSync6(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
38532
+ writeFileSync7(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
38120
38533
  try {
38121
- renameSync4(tmp, path);
38534
+ renameSync5(tmp, path);
38122
38535
  chmodSync2(path, 384);
38123
38536
  } catch (err) {
38124
38537
  try {
38125
- unlinkSync3(tmp);
38538
+ unlinkSync4(tmp);
38126
38539
  } catch {
38127
38540
  }
38128
38541
  throw err;
@@ -38131,21 +38544,21 @@ function saveWalletPairingState(state) {
38131
38544
  function deleteWalletPairingState(pairingId) {
38132
38545
  const path = pairingPath(pairingId);
38133
38546
  try {
38134
- unlinkSync3(path);
38547
+ unlinkSync4(path);
38135
38548
  } catch (err) {
38136
38549
  if (err.code !== "ENOENT") throw err;
38137
38550
  }
38138
38551
  }
38139
38552
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
38140
- if (!existsSync8(PAIRINGS_DIR)) return 0;
38553
+ if (!existsSync9(PAIRINGS_DIR)) return 0;
38141
38554
  let removed = 0;
38142
38555
  for (const name of readdirSync5(PAIRINGS_DIR)) {
38143
38556
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
38144
- const path = join11(PAIRINGS_DIR, name);
38557
+ const path = join12(PAIRINGS_DIR, name);
38145
38558
  try {
38146
- const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
38559
+ const state = stateSchema.parse(JSON.parse(readFileSync10(path, "utf8")));
38147
38560
  if (state.manifest.expires_at <= nowSeconds) {
38148
- unlinkSync3(path);
38561
+ unlinkSync4(path);
38149
38562
  removed += 1;
38150
38563
  }
38151
38564
  } catch {
@@ -38155,7 +38568,7 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
38155
38568
  }
38156
38569
  async function withWalletPairingLock(pairingId, fn) {
38157
38570
  const path = pairingPath(pairingId);
38158
- if (!existsSync8(path)) return fn();
38571
+ if (!existsSync9(path)) return fn();
38159
38572
  let release;
38160
38573
  try {
38161
38574
  release = await import_proper_lockfile4.default.lock(path, {
@@ -38185,7 +38598,7 @@ function pairingPath(pairingId) {
38185
38598
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
38186
38599
  );
38187
38600
  }
38188
- return join11(PAIRINGS_DIR, `${pairingId}.json`);
38601
+ return join12(PAIRINGS_DIR, `${pairingId}.json`);
38189
38602
  }
38190
38603
  function ensurePairingsDirectory() {
38191
38604
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -40009,8 +40422,17 @@ function buildProgram() {
40009
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) => {
40010
40423
  return catchErrors(() => creditReceipts(dvm, opts), opts.human);
40011
40424
  });
40012
- 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) => {
40013
- 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);
40014
40436
  });
40015
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(
40016
40438
  "--type <type>",
@@ -40020,7 +40442,7 @@ function buildProgram() {
40020
40442
  });
40021
40443
  program2.command("pay <job-id>").description(
40022
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."
40023
- ).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(
40024
40446
  "--mint <url>",
40025
40447
  "Pin the Cashu spend mint for this payment (must be one the DVM accepts). Overrides any mint pinned at request time."
40026
40448
  ).option("--rail <rail>", "Force this payment onto cashu, tempo, or x402 without fallback").option(