@dvmkit/dvm-cli 0.17.0 → 0.19.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.
Files changed (29) hide show
  1. package/README.md +1 -1
  2. package/dist/{chunk-ESQ6DCS3.js → chunk-3NXAIRFF.js} +2 -2
  3. package/dist/{chunk-REIUNZQX.js → chunk-B5KW2TPR.js} +2 -2
  4. package/dist/{chunk-DGA5EFKU.js → chunk-DF2OWCRY.js} +6 -6
  5. package/dist/{chunk-R6FZT6S2.js → chunk-DJDONOMG.js} +9 -5
  6. package/dist/{chunk-DE7TEOUR.js → chunk-J3HYNDMI.js} +424 -51
  7. package/dist/{chunk-OEWENVJ7.js → chunk-MM646MFM.js} +4 -4
  8. package/dist/{chunk-VLD7OKSH.js → chunk-NKD4NEUF.js} +3 -3
  9. package/dist/{chunk-ZGBCVQF2.js → chunk-OCVRCWBL.js} +3 -3
  10. package/dist/{chunk-IK7RI645.js → chunk-W4ADV3HW.js} +449 -5
  11. package/dist/{chunk-UFMAHF6T.js → chunk-WCX4PNEF.js} +127 -40
  12. package/dist/{chunk-THTPKBZX.js → chunk-X6BETQ7V.js} +1252 -737
  13. package/dist/{chunk-A2B7QDMS.js → chunk-ZZCYSYXR.js} +2 -2
  14. package/dist/{client-3JOMNAIQ.js → client-S3FEXAWD.js} +6 -6
  15. package/dist/dvm.js +687 -249
  16. package/dist/{internal-L362ZUWL.js → internal-WAQ3LZN4.js} +10 -8
  17. package/dist/{lifecycle-BH4OA5I3.js → lifecycle-NOK3MKL4.js} +6 -6
  18. package/dist/{payout-reporter-F5LFV5W4-EJ7E5ALO.js → payout-reporter-5PH53T44-7IA4NGIN.js} +2 -2
  19. package/dist/{pocket-refill-5BEM22UM.js → pocket-refill-KUBHM7MR.js} +10 -10
  20. package/dist/{revenue-reporter-2U55YH2I-EUB6PBRN.js → revenue-reporter-4XV3OO5O-RYHS3M34.js} +2 -2
  21. package/dist/{tempo-lifecycle-WGTX6MJR.js → tempo-lifecycle-QGJ4JEHN.js} +8 -8
  22. package/dist/{tempo-wallet-OTB2YSWE.js → tempo-wallet-GDDZZP5S.js} +7 -7
  23. package/dist/{wallet-73EJBUSO.js → wallet-2M3H75UP.js} +7 -7
  24. package/dist/{x402-G6C4N2BN-TAJEBQGU.js → x402-FHHB3V4V-CM6OMLHE.js} +2 -2
  25. package/package.json +2 -2
  26. package/skills/dvm/calling.md +13 -2
  27. package/skills/dvm/credit.md +5 -1
  28. package/skills/dvm/recovery.md +2 -0
  29. package/skills/dvm/wallets.md +2 -0
package/dist/dvm.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-ZGBCVQF2.js";
8
+ } from "./chunk-OCVRCWBL.js";
9
9
  import {
10
10
  CARD_MIN_MICRO,
11
11
  DEFAULT_CREDIT_POSTURE,
@@ -19,12 +19,14 @@ import {
19
19
  answeredYieldSeqs,
20
20
  appendMessages,
21
21
  applySubmissionVerdicts,
22
+ askUsdMicro,
22
23
  assertFloatBudget,
23
24
  automaticCreditBoundRail,
24
25
  availableRails,
25
26
  backfillTrustAnchor,
26
27
  blockHeldPayment,
27
28
  bookCreditPayment,
29
+ budgetVerdict,
28
30
  buildCompletionHintFields,
29
31
  buildTempoCredential,
30
32
  captureDrawFundingReceipts,
@@ -46,7 +48,9 @@ import {
46
48
  createPendingMintQuote,
47
49
  declinedAskSeqs,
48
50
  deriveAlias,
51
+ describeBudgetOverrun,
49
52
  describeMintBounds,
53
+ dollarBoundUsdMicro,
50
54
  drainReceiptsDisplay,
51
55
  drainReceiptsHint,
52
56
  dvmLabelFromEndpoint,
@@ -62,8 +66,10 @@ import {
62
66
  floatBudgetJson,
63
67
  floatPaymentDisplay,
64
68
  floatPaymentJson,
69
+ formatDurationMs,
65
70
  formatLocktime,
66
71
  formatMicro,
72
+ formatUsdMicro,
67
73
  fundAgentWallet,
68
74
  fundCredit,
69
75
  fundTimeoutMs,
@@ -112,7 +118,9 @@ import {
112
118
  nextStepHint,
113
119
  normalizeProviderEndpoint,
114
120
  observeJobContent,
121
+ observePaymentBookings,
115
122
  observedSettlementFields,
123
+ overBudgetHint,
116
124
  parseDurationMs,
117
125
  parseJobContent,
118
126
  parseLocktime,
@@ -120,6 +128,7 @@ import {
120
128
  parseUpfrontPayment,
121
129
  parseUpfrontRailPayment,
122
130
  payViaFloat,
131
+ paymentCountHint,
123
132
  paymentInFlightHint,
124
133
  pendingPaymentRequest,
125
134
  pickCreditFundRail,
@@ -145,6 +154,7 @@ import {
145
154
  reclaimIntentIds,
146
155
  reconcileInFlightPaymentRequest,
147
156
  reconcilePaymentRequestHistory,
157
+ recordBudgetRefusal,
148
158
  recordCallerMessageHash,
149
159
  recordFloatSpend,
150
160
  recordIdentityFailure,
@@ -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,13 +213,13 @@ import {
201
213
  withIdentityRecovery,
202
214
  withJobTokenRedaction,
203
215
  withRequestResultRecovery
204
- } from "./chunk-DE7TEOUR.js";
216
+ } from "./chunk-J3HYNDMI.js";
205
217
  import {
206
218
  connectedTempoAccount,
207
219
  generateTempoKey,
208
220
  tempoBalanceCheckHint,
209
221
  tempoWrongAssetHint
210
- } from "./chunk-OEWENVJ7.js";
222
+ } from "./chunk-MM646MFM.js";
211
223
  import {
212
224
  assertSupportedX402Network,
213
225
  connectedX402Payer,
@@ -216,7 +228,7 @@ import {
216
228
  repinX402WalletNetwork,
217
229
  saveX402Wallet,
218
230
  x402NetworkLabel
219
- } from "./chunk-VLD7OKSH.js";
231
+ } from "./chunk-NKD4NEUF.js";
220
232
  import {
221
233
  CREDIT_POSTURES,
222
234
  FEEDBACK_POSTURES,
@@ -233,7 +245,7 @@ import {
233
245
  retireConfigBackup,
234
246
  rollbackConfig,
235
247
  updateConfig
236
- } from "./chunk-ESQ6DCS3.js";
248
+ } from "./chunk-3NXAIRFF.js";
237
249
  import {
238
250
  addOutputWarnings,
239
251
  assertValidBudget,
@@ -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,10 +267,10 @@ import {
254
267
  tryResolveBtcUsdRate,
255
268
  tryX402Payment,
256
269
  withOutputWarnings
257
- } from "./chunk-R6FZT6S2.js";
270
+ } from "./chunk-DJDONOMG.js";
258
271
  import {
259
272
  assertX402WalletIdle
260
- } from "./chunk-REIUNZQX.js";
273
+ } from "./chunk-B5KW2TPR.js";
261
274
  import {
262
275
  A,
263
276
  AGENT_MNEMONIC_FILE,
@@ -497,7 +510,7 @@ import {
497
510
  x402PendingUnsettled,
498
511
  x402RequiredFromError,
499
512
  x402ReservationRelease
500
- } from "./chunk-THTPKBZX.js";
513
+ } from "./chunk-X6BETQ7V.js";
501
514
  import "./chunk-JBU7RKQ3.js";
502
515
  import "./chunk-KDNFUDOG.js";
503
516
  import "./chunk-IUTVV6N5.js";
@@ -783,11 +796,11 @@ import {
783
796
  usdToMsats,
784
797
  usdcToMsats,
785
798
  x402NetworkByCaip2
786
- } from "./chunk-DGA5EFKU.js";
787
- import "./chunk-A2B7QDMS.js";
788
- import "./chunk-IK7RI645.js";
799
+ } from "./chunk-DF2OWCRY.js";
800
+ import "./chunk-ZZCYSYXR.js";
801
+ import "./chunk-W4ADV3HW.js";
789
802
  import "./chunk-R2DSAZBO.js";
790
- import "./chunk-UFMAHF6T.js";
803
+ import "./chunk-WCX4PNEF.js";
791
804
  import {
792
805
  privateKeyToAccount
793
806
  } from "./chunk-EVQERRCP.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,
@@ -11615,8 +11881,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11615
11881
  }
11616
11882
  }
11617
11883
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11618
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
11619
- const { tryX402Payment: tryX402Payment2 } = await import("./client-3JOMNAIQ.js");
11884
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
11885
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-S3FEXAWD.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) {
@@ -13713,10 +14028,12 @@ function withCreditErrorContext(err, body) {
13713
14028
  }
13714
14029
  const menu = parseCreditMenu(body.credit);
13715
14030
  if (menu) extra.credit = menu;
14031
+ if (Number.isSafeInteger(body.stripe_status)) extra.stripe_status = body.stripe_status;
13716
14032
  const lightning = parseLightningOffer(body.lightning);
13717
14033
  if (lightning) extra.lightning = lightning;
13718
14034
  for (const key of [
13719
14035
  "reason",
14036
+ "cause",
13720
14037
  "stripe_error_code",
13721
14038
  "decline_code",
13722
14039
  "blocking_drain_id",
@@ -14394,7 +14711,7 @@ async function settleCreditAfterJob(args) {
14394
14711
  }
14395
14712
  }
14396
14713
  if (args.allowTopup !== false) {
14397
- const refill = args.refillPocket ?? (await import("./pocket-refill-5BEM22UM.js")).refillPocketIfLow;
14714
+ const refill = args.refillPocket ?? (await import("./pocket-refill-KUBHM7MR.js")).refillPocketIfLow;
14398
14715
  await refill({ human: args.human }).catch(() => void 0);
14399
14716
  }
14400
14717
  }
@@ -15175,14 +15492,14 @@ async function confirmRollback(stored, preview, opts) {
15175
15492
  async function withStrandingChecked(removing, commit) {
15176
15493
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
15177
15494
  if (leaving.has("tempo")) {
15178
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-WGTX6MJR.js");
15495
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-QGJ4JEHN.js");
15179
15496
  await assertTempoWalletIdle2("disconnect");
15180
15497
  }
15181
15498
  if (!leaving.has("x402")) return commit();
15182
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-L362ZUWL.js");
15183
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-BH4OA5I3.js");
15184
- const { ensureAddress: ensureAddress2 } = await import("./internal-L362ZUWL.js");
15185
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
15499
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-WAQ3LZN4.js");
15500
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-NOK3MKL4.js");
15501
+ const { ensureAddress: ensureAddress2 } = await import("./internal-WAQ3LZN4.js");
15502
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
15186
15503
  return withX402ChannelLock2(async () => {
15187
15504
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
15188
15505
  if (unsettled.length > 0) {
@@ -19696,7 +20013,7 @@ import {
19696
20013
  } from "crypto";
19697
20014
 
19698
20015
  // src/lib/secret-input.ts
19699
- import { fstatSync, readFileSync as readFileSync3, realpathSync } from "fs";
20016
+ import { fstatSync, readFileSync as readFileSync4, realpathSync } from "fs";
19700
20017
  import { homedir } from "os";
19701
20018
  import { resolve, sep } from "path";
19702
20019
  var BLOCKED_SECRET_PATHS = [
@@ -19776,7 +20093,7 @@ function readSecretFile(path, config2) {
19776
20093
  throw err;
19777
20094
  }
19778
20095
  assertSafeFilePath(real);
19779
- return readFileSync3(real, "utf-8").trim();
20096
+ return readFileSync4(real, "utf-8").trim();
19780
20097
  }
19781
20098
  function readSecretStdin(config2) {
19782
20099
  return new Promise((resolveStdin, reject) => {
@@ -19896,6 +20213,7 @@ function capitalise(s) {
19896
20213
 
19897
20214
  // src/lib/credit/funding.ts
19898
20215
  async function runCreditFund(dvm, opts) {
20216
+ const invocationStartedAt = Date.now();
19899
20217
  const endpoint = resolveCreditEndpoint(dvm);
19900
20218
  const config2 = loadConfig();
19901
20219
  const signer = resolveSigningIdentity({ as: opts.as, config: config2 });
@@ -19994,7 +20312,7 @@ async function runCreditFund(dvm, opts) {
19994
20312
  }
19995
20313
  const transport = createDvmTransport();
19996
20314
  try {
19997
- const menu = stored?.menu ?? (pending4 ?? signedPending ? void 0 : await discoverCreditMenu(transport, endpoint, signer));
20315
+ const menu = (stored?.menu && rail === "stripe" && cardSpt === void 0 && !pending4 && !signedPending ? await discoverCreditMenu(transport, endpoint, signer) : void 0) ?? stored?.menu ?? (pending4 ?? signedPending ? void 0 : await discoverCreditMenu(transport, endpoint, signer));
19998
20316
  let sizing;
19999
20317
  if (targetJobs !== void 0 && !pending4 && !signedPending) {
20000
20318
  sizing = await sizeForTargetJobs({ endpoint, targetJobs, stored, menu, providerInfo });
@@ -20018,7 +20336,7 @@ async function runCreditFund(dvm, opts) {
20018
20336
  transport,
20019
20337
  ref: { endpoint },
20020
20338
  signing: signer,
20021
- creditId: pending4?.creditId ?? opts.creditId ?? (canRefillStoredCredit(stored) ? stored.creditId : signedPending?.creditId ?? randomUUID3()),
20339
+ creditId: pending4?.creditId ?? opts.creditId ?? signedPending?.creditId ?? (canRefillStoredCredit(stored) ? stored.creditId : randomUUID3()),
20022
20340
  amountMicro: fundMicro,
20023
20341
  human: opts.human,
20024
20342
  providerInfo,
@@ -20031,7 +20349,15 @@ async function runCreditFund(dvm, opts) {
20031
20349
  ...maxCashuPrincipalSats !== void 0 ? { maxCashuPrincipalSats } : {},
20032
20350
  ...maxCashuFeeSats !== void 0 ? { maxCashuFeeSats } : {},
20033
20351
  ...cardSpt !== void 0 ? { cardSpt } : {},
20034
- cardApprovalSteps: true
20352
+ cardApprovalSteps: true,
20353
+ cardWait: opts.wait !== false,
20354
+ cardCreditIdExplicit: opts.creditId !== void 0,
20355
+ cardInvocationStartedAt: invocationStartedAt,
20356
+ ...signer.source.kind !== "env" ? { cardIdentity: signer.source.name } : {},
20357
+ cardCheckoutProgress: (handoff) => {
20358
+ if (opts.human) info(String(handoff.display));
20359
+ else json({ op: "fund", endpoint, ...handoff });
20360
+ }
20035
20361
  });
20036
20362
  if (outcome.status === "refused" || outcome.status === "unavailable") {
20037
20363
  const err = outcome.error;
@@ -20092,6 +20418,7 @@ async function runCreditFund(dvm, opts) {
20092
20418
  op: "fund",
20093
20419
  endpoint,
20094
20420
  status: outcome.status,
20421
+ ...outcome.checkoutHandoff ?? {},
20095
20422
  credit_id: outcome.creditId,
20096
20423
  fund_id: outcome.fundId,
20097
20424
  ...resumedNote ? { resumed: resumedNote } : {},
@@ -20137,7 +20464,10 @@ async function runCreditFund(dvm, opts) {
20137
20464
  }
20138
20465
  }
20139
20466
  function pendingSignedResume(args) {
20140
- if (args.opts.creditId || args.journalled || canRefillStoredCredit(args.stored)) return void 0;
20467
+ if (args.journalled) return void 0;
20468
+ const card = listPendingCardFundings({ endpoint: args.endpoint, callerPubkey: args.signer.pubkey }).find((entry) => !args.opts.creditId || entry.creditId === args.opts.creditId);
20469
+ if (card?.v === 2) return card;
20470
+ if (args.opts.creditId || canRefillStoredCredit(args.stored)) return void 0;
20141
20471
  const scope = { endpoint: args.endpoint, callerPubkey: args.signer.pubkey };
20142
20472
  return [
20143
20473
  ...listResumableX402Fundings(scope),
@@ -20397,14 +20727,15 @@ async function enforceTrustTier(args) {
20397
20727
  ...walletInvoiceFundingAdvice(args.amountMicro),
20398
20728
  minimumUsd: `$${formatUsd(lightningMinimum / 1e6)}`
20399
20729
  } : void 0;
20400
- const walletGuidance = walletFunding ? `Lightning top-ups here start at ${walletFunding.minimumUsd}, above the ${capUsd} this caller can load at the current trust tier. ${walletFunding.text} ` : "";
20730
+ const cardGuidance = args.menu?.stripe?.checkout ? `Pay by card: dvm credit fund ${shellQuoteArg(args.endpoint)} --rail stripe --amount ${shellQuoteArg(`$${formatUsd(args.amountMicro / 1e6)}`)}. ` : "";
20731
+ const walletGuidance = walletFunding ? `${cardGuidance}Lightning top-ups here start at ${walletFunding.minimumUsd}, above the ${capUsd} this caller can load at the current trust tier. ${walletFunding.text} ` : "";
20401
20732
  throw withHeadroom(
20402
20733
  new DvmError(
20403
20734
  "amount_exceeds_trust_tier",
20404
20735
  `Funding ${amountUsd} at ${args.endpoint} would exceed this DVM's ${capUsd} trust-tier cap.`,
20405
- walletFunding ? `No money moved. ${walletGuidance}Re-run with --over-trust to fund credit over Lightning anyway, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'.` : `Nothing moved. Re-run with --over-trust to fund it anyway, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'. Or fund ${capUsd} or less.`,
20736
+ walletFunding ? `No money moved. ${walletGuidance}Re-run with --over-trust to fund credit over Lightning anyway, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'.` : `Nothing moved. ${cardGuidance}Re-run with --over-trust to fund it anyway, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'. Or fund ${capUsd} or less.`,
20406
20737
  {
20407
- display: `This agent has only earned ${capUsd} of credit at ${args.endpoint} so far, and ${amountUsd} was asked for.${heldClause} No money moved. ` + walletGuidance + `Loading more than the earned amount is allowed, but it has to be asked for explicitly \u2014 re-run with --over-trust, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'.`,
20738
+ display: `This agent has only earned ${capUsd} of credit at ${args.endpoint} so far, and ${amountUsd} was asked for.${heldClause} No money moved. ` + (walletGuidance || cardGuidance) + `Loading more than the earned amount is allowed, but it has to be asked for explicitly \u2014 re-run with --over-trust, or pre-grant every DVM signed by this builder with 'dvm credit trust ${args.endpoint} <builder-max|$amount>'.`,
20408
20739
  endpoint: args.endpoint,
20409
20740
  amount_micro: args.amountMicro,
20410
20741
  exposure_micro: exposureMicro,
@@ -21889,8 +22220,8 @@ async function probeX402(x402, timeoutMs) {
21889
22220
  let network;
21890
22221
  let address;
21891
22222
  try {
21892
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-73EJBUSO.js");
21893
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-L362ZUWL.js");
22223
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
22224
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-WAQ3LZN4.js");
21894
22225
  const wallet = loadX402Wallet2();
21895
22226
  if (!wallet) {
21896
22227
  const storedKey = x402.privateKey;
@@ -21942,8 +22273,8 @@ async function probeMpp(mpp, timeoutMs) {
21942
22273
  if (!mpp) return null;
21943
22274
  if (mpp.method === "tempo") {
21944
22275
  try {
21945
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-OTB2YSWE.js");
21946
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-L362ZUWL.js");
22276
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-GDDZZP5S.js");
22277
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-WAQ3LZN4.js");
21947
22278
  const account = await connectedTempoAccount2();
21948
22279
  if (!account) {
21949
22280
  return {
@@ -22037,8 +22368,8 @@ function x402WrongAssetHint(asset) {
22037
22368
  }
22038
22369
 
22039
22370
  // src/lib/build-freshness.ts
22040
- import { existsSync as existsSync3, readdirSync, statSync } from "fs";
22041
- import { dirname as dirname2, join as join3 } from "path";
22371
+ import { existsSync as existsSync4, readdirSync, statSync } from "fs";
22372
+ import { dirname as dirname2, join as join4 } from "path";
22042
22373
  import { fileURLToPath as fileURLToPath2 } from "url";
22043
22374
  var EXTRA_SOURCES = ["package.json", "tsup.config.ts"];
22044
22375
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "__snapshots__"]);
@@ -22057,12 +22388,12 @@ function checkBuildFreshness(opts) {
22057
22388
  skipReason
22058
22389
  });
22059
22390
  if (root === null) return skipped("running_from_source");
22060
- const bundlePath = join3(root, "dist", "dvm.js");
22061
- if (dirname2(moduleDir) !== root || !existsSync3(bundlePath)) {
22391
+ const bundlePath = join4(root, "dist", "dvm.js");
22392
+ if (dirname2(moduleDir) !== root || !existsSync4(bundlePath)) {
22062
22393
  return skipped("running_from_source");
22063
22394
  }
22064
- const srcDir = join3(root, "src");
22065
- if (!existsSync3(srcDir)) return skipped("no_source_tree");
22395
+ const srcDir = join4(root, "src");
22396
+ if (!existsSync4(srcDir)) return skipped("no_source_tree");
22066
22397
  const builtAtMs = statSync(bundlePath).mtimeMs;
22067
22398
  const newer = [];
22068
22399
  let newestMs = 0;
@@ -22071,7 +22402,7 @@ function checkBuildFreshness(opts) {
22071
22402
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
22072
22403
  if (budget2.left-- <= 0) return;
22073
22404
  if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
22074
- const abs = join3(dir, entry.name);
22405
+ const abs = join4(dir, entry.name);
22075
22406
  const relPath = rel ? `${rel}/${entry.name}` : entry.name;
22076
22407
  if (entry.isDirectory()) {
22077
22408
  visit(abs, relPath, budget2);
@@ -22086,8 +22417,8 @@ function checkBuildFreshness(opts) {
22086
22417
  const budget = { left: MAX_ENTRIES };
22087
22418
  visit(srcDir, "src", budget);
22088
22419
  for (const name of EXTRA_SOURCES) {
22089
- const abs = join3(root, name);
22090
- if (!existsSync3(abs)) continue;
22420
+ const abs = join4(root, name);
22421
+ if (!existsSync4(abs)) continue;
22091
22422
  const mtimeMs = statSync(abs).mtimeMs;
22092
22423
  if (mtimeMs > newestMs) newestMs = mtimeMs;
22093
22424
  if (mtimeMs > builtAtMs) newer.push({ path: name, mtimeMs });
@@ -22105,7 +22436,7 @@ function checkBuildFreshness(opts) {
22105
22436
  function findPackageRoot(start) {
22106
22437
  let dir = start;
22107
22438
  for (; ; ) {
22108
- if (existsSync3(join3(dir, "package.json"))) return dir;
22439
+ if (existsSync4(join4(dir, "package.json"))) return dir;
22109
22440
  const parent = dirname2(dir);
22110
22441
  if (parent === dir) return null;
22111
22442
  dir = parent;
@@ -22113,25 +22444,25 @@ function findPackageRoot(start) {
22113
22444
  }
22114
22445
 
22115
22446
  // 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";
22447
+ import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync6, statSync as statSync2 } from "fs";
22448
+ import { basename, join as join6 } from "path";
22118
22449
 
22119
22450
  // src/lib/request-refusal-store.ts
22120
22451
  import {
22121
22452
  closeSync as closeSync2,
22122
- existsSync as existsSync4,
22453
+ existsSync as existsSync5,
22123
22454
  fsyncSync as fsyncSync2,
22124
22455
  openSync as openSync2,
22125
- readFileSync as readFileSync4,
22126
- renameSync as renameSync2,
22456
+ readFileSync as readFileSync5,
22457
+ renameSync as renameSync3,
22127
22458
  rmSync,
22128
- writeFileSync as writeFileSync2
22459
+ writeFileSync as writeFileSync3
22129
22460
  } from "fs";
22130
- import { join as join4 } from "path";
22131
- var REQUEST_REFUSALS_DIR = join4(CONFIG_DIR, "request-refusals");
22461
+ import { join as join5 } from "path";
22462
+ var REQUEST_REFUSALS_DIR = join5(CONFIG_DIR, "request-refusals");
22132
22463
  var SAFE_TOKEN = /^[a-z0-9_.:-]{1,64}$/;
22133
22464
  function requestIntentMayExist(requestId) {
22134
- return existsSync4(join4(REQUEST_INTENTS_DIR, requestId));
22465
+ return existsSync5(join5(REQUEST_INTENTS_DIR, requestId));
22135
22466
  }
22136
22467
  function recordRequestRefusal(requestId, refusal) {
22137
22468
  if (!isPublicRequestId(requestId) || requestIntentMayExist(requestId)) return false;
@@ -22148,12 +22479,12 @@ function recordRequestRefusal(requestId, refusal) {
22148
22479
  const temp = `${target}.${String(process.pid)}.tmp`;
22149
22480
  const fd = openSync2(temp, "w", 384);
22150
22481
  try {
22151
- writeFileSync2(fd, JSON.stringify(record2, null, 2) + "\n");
22482
+ writeFileSync3(fd, JSON.stringify(record2, null, 2) + "\n");
22152
22483
  fsyncSync2(fd);
22153
22484
  } finally {
22154
22485
  closeSync2(fd);
22155
22486
  }
22156
- renameSync2(temp, target);
22487
+ renameSync3(temp, target);
22157
22488
  } catch {
22158
22489
  }
22159
22490
  return true;
@@ -22168,7 +22499,7 @@ function clearRequestRefusal(requestId) {
22168
22499
  function loadRequestRefusal(requestId) {
22169
22500
  if (!isPublicRequestId(requestId)) return null;
22170
22501
  try {
22171
- const parsed = JSON.parse(readFileSync4(refusalPath(requestId), "utf8"));
22502
+ const parsed = JSON.parse(readFileSync5(refusalPath(requestId), "utf8"));
22172
22503
  if (parsed.v !== 1 || parsed.requestId !== requestId || typeof parsed.code !== "string" || typeof parsed.refusedAt !== "number" || parsed.reason !== void 0 && typeof parsed.reason !== "string") {
22173
22504
  return null;
22174
22505
  }
@@ -22178,20 +22509,20 @@ function loadRequestRefusal(requestId) {
22178
22509
  }
22179
22510
  }
22180
22511
  function refusalPath(requestId) {
22181
- return join4(REQUEST_REFUSALS_DIR, `${requestId}.json`);
22512
+ return join5(REQUEST_REFUSALS_DIR, `${requestId}.json`);
22182
22513
  }
22183
22514
 
22184
22515
  // src/lib/caller-state.ts
22185
22516
  function detectSetupState() {
22186
22517
  return {
22187
22518
  existingState: {
22188
- jobs: existsSync5(JOBS_FILE),
22189
- messages: existsSync5(MESSAGES_DIR)
22519
+ jobs: existsSync6(JOBS_FILE),
22520
+ messages: existsSync6(MESSAGES_DIR)
22190
22521
  },
22191
22522
  missing: {
22192
- config: !existsSync5(CONFIG_FILE),
22193
- identity: !existsSync5(IDENTITIES_FILE),
22194
- wallet: !existsSync5(WALLET_FILE)
22523
+ config: !existsSync6(CONFIG_FILE),
22524
+ identity: !existsSync6(IDENTITIES_FILE),
22525
+ wallet: !existsSync6(WALLET_FILE)
22195
22526
  }
22196
22527
  };
22197
22528
  }
@@ -22261,6 +22592,16 @@ var FILE_SPECS = [
22261
22592
  // A store written by an older dvm keeps its old mode until the next write
22262
22593
  // replaces it — doctor warns, and the write repairs it.
22263
22594
  { name: "credits", path: CREDITS_FILE, json: true, secret: true, directory: false },
22595
+ // When the prepaid-credit suggestion was last shown at each DVM. 0600 for
22596
+ // the reason the feedback cooldowns are: it records which DVMs this caller
22597
+ // pays and when.
22598
+ {
22599
+ name: "credit_suggestions",
22600
+ path: CREDIT_SUGGESTIONS_FILE,
22601
+ json: true,
22602
+ secret: true,
22603
+ directory: false
22604
+ },
22264
22605
  {
22265
22606
  name: "x402_channels",
22266
22607
  path: X402_CHANNELS_FILE,
@@ -22321,17 +22662,17 @@ function findQuarantinedCreditStores() {
22321
22662
  } catch {
22322
22663
  return [];
22323
22664
  }
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 }));
22665
+ 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
22666
  }
22326
22667
  function checkOne(spec) {
22327
- const exists = existsSync5(spec.path);
22668
+ const exists = existsSync6(spec.path);
22328
22669
  if (!exists) {
22329
22670
  return { name: spec.name, path: spec.path, exists: false };
22330
22671
  }
22331
22672
  const row = { name: spec.name, path: spec.path, exists: true };
22332
22673
  if (spec.json) {
22333
22674
  try {
22334
- JSON.parse(readFileSync5(spec.path, "utf-8"));
22675
+ JSON.parse(readFileSync6(spec.path, "utf-8"));
22335
22676
  row.parseable = true;
22336
22677
  } catch (err) {
22337
22678
  row.parseable = false;
@@ -22360,7 +22701,7 @@ function checkSecretDirectory(dir, row) {
22360
22701
  try {
22361
22702
  const offenders = [];
22362
22703
  for (const name of readdirSync2(dir)) {
22363
- const path = join5(dir, name);
22704
+ const path = join6(dir, name);
22364
22705
  const stat2 = statSync2(path);
22365
22706
  if (!stat2.isFile()) continue;
22366
22707
  const mode = stat2.mode & 511;
@@ -22381,9 +22722,9 @@ function octalMode(mode) {
22381
22722
  return "0" + mode.toString(8).padStart(3, "0");
22382
22723
  }
22383
22724
  function readBtcRateCacheAge(now = Date.now()) {
22384
- if (!existsSync5(BTC_RATE_FILE)) return null;
22725
+ if (!existsSync6(BTC_RATE_FILE)) return null;
22385
22726
  try {
22386
- const data = JSON.parse(readFileSync5(BTC_RATE_FILE, "utf-8"));
22727
+ const data = JSON.parse(readFileSync6(BTC_RATE_FILE, "utf-8"));
22387
22728
  if (typeof data.timestamp !== "number") return null;
22388
22729
  return { ageMs: now - data.timestamp };
22389
22730
  } catch {
@@ -22393,7 +22734,7 @@ function readBtcRateCacheAge(now = Date.now()) {
22393
22734
 
22394
22735
  // src/lib/mnemonic-backups.ts
22395
22736
  import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
22396
- import { basename as basename2, dirname as dirname3, join as join6 } from "path";
22737
+ import { basename as basename2, dirname as dirname3, join as join7 } from "path";
22397
22738
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
22398
22739
  const dir = dirname3(mnemonicFile);
22399
22740
  const prefix = `${basename2(mnemonicFile)}.`;
@@ -22405,7 +22746,7 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
22405
22746
  throw err;
22406
22747
  }
22407
22748
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
22408
- const path = join6(dir, name);
22749
+ const path = join7(dir, name);
22409
22750
  const stat2 = statSync3(path);
22410
22751
  if (!stat2.isFile()) return null;
22411
22752
  const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
@@ -24301,11 +24642,11 @@ async function favRm(name, opts) {
24301
24642
  }
24302
24643
 
24303
24644
  // src/lib/byte-source.ts
24304
- import { readFileSync as readFileSync6 } from "fs";
24645
+ import { readFileSync as readFileSync7 } from "fs";
24305
24646
  import { resolve as resolve2 } from "path";
24306
24647
  var STDIN_TIMEOUT_MS2 = 1e4;
24307
24648
  function readFileText(path) {
24308
- return readFileSync6(resolve2(path), "utf-8");
24649
+ return readFileSync7(resolve2(path), "utf-8");
24309
24650
  }
24310
24651
  var StdinTimeoutError = class extends Error {
24311
24652
  constructor(timeoutMs) {
@@ -24469,7 +24810,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
24469
24810
  }
24470
24811
 
24471
24812
  // src/lib/feedback-nudges.ts
24472
- import { existsSync as existsSync6, readFileSync as readFileSync7, renameSync as renameSync3, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
24813
+ import { existsSync as existsSync7, readFileSync as readFileSync8, renameSync as renameSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs";
24473
24814
 
24474
24815
  // src/lib/feedback-notice.ts
24475
24816
  function buildFeedbackNudge(args) {
@@ -24521,10 +24862,10 @@ function effectiveFeedbackPosture(config2) {
24521
24862
  return { posture: DEFAULT_FEEDBACK_POSTURE, source: "default" };
24522
24863
  }
24523
24864
  function loadFeedbackNudgeState() {
24524
- if (!existsSync6(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
24865
+ if (!existsSync7(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
24525
24866
  try {
24526
24867
  const parsed = JSON.parse(
24527
- readFileSync7(FEEDBACK_NUDGES_FILE, "utf-8")
24868
+ readFileSync8(FEEDBACK_NUDGES_FILE, "utf-8")
24528
24869
  );
24529
24870
  return {
24530
24871
  ...typeof parsed.introShownAt === "string" ? { introShownAt: parsed.introShownAt } : {},
@@ -24541,7 +24882,7 @@ function recordFeedbackSent(dvmId, now = Date.now()) {
24541
24882
  ...state.perDvm[dvmId] ?? {},
24542
24883
  lastSentAt: new Date(now).toISOString()
24543
24884
  };
24544
- saveState(state);
24885
+ saveState2(state);
24545
24886
  } catch {
24546
24887
  }
24547
24888
  }
@@ -24574,7 +24915,7 @@ function noteFeedbackAfterTerminal(moment) {
24574
24915
  ...code === "feedback_first_success" ? { firstSuccessNudgedAt: stamp } : {}
24575
24916
  };
24576
24917
  if (intro) state.introShownAt = stamp;
24577
- saveState(state);
24918
+ saveState2(state);
24578
24919
  return;
24579
24920
  }
24580
24921
  if (moment.status === "completed") {
@@ -24610,15 +24951,15 @@ function coercePerDvm(perDvm) {
24610
24951
  )
24611
24952
  );
24612
24953
  }
24613
- function saveState(state) {
24954
+ function saveState2(state) {
24614
24955
  ensureConfigDir();
24615
24956
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
24616
- writeFileSync3(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
24957
+ writeFileSync4(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
24617
24958
  try {
24618
- renameSync3(tmp, FEEDBACK_NUDGES_FILE);
24959
+ renameSync4(tmp, FEEDBACK_NUDGES_FILE);
24619
24960
  } catch (err) {
24620
24961
  try {
24621
- unlinkSync(tmp);
24962
+ unlinkSync2(tmp);
24622
24963
  } catch {
24623
24964
  }
24624
24965
  throw err;
@@ -24627,9 +24968,9 @@ function saveState(state) {
24627
24968
  var nudgedThisInvocation = false;
24628
24969
 
24629
24970
  // src/lib/platform.ts
24630
- import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
24971
+ import { existsSync as existsSync8, mkdirSync as mkdirSync2, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
24631
24972
  import { homedir as homedir2 } from "os";
24632
- import { join as join7 } from "path";
24973
+ import { join as join8 } from "path";
24633
24974
  function getPlatformUrl() {
24634
24975
  return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
24635
24976
  }
@@ -25203,11 +25544,11 @@ import {
25203
25544
  openSync as openSync3,
25204
25545
  readdirSync as readdirSync4,
25205
25546
  rmdirSync,
25206
- unlinkSync as unlinkSync2,
25207
- writeFileSync as writeFileSync5
25547
+ unlinkSync as unlinkSync3,
25548
+ writeFileSync as writeFileSync6
25208
25549
  } from "fs";
25209
25550
  import { tmpdir } from "os";
25210
- import { join as join8 } from "path";
25551
+ import { join as join9 } from "path";
25211
25552
 
25212
25553
  // src/lib/mime-ext.ts
25213
25554
  var MIME_TO_EXT = {
@@ -25263,10 +25604,10 @@ var ArtifactSaveSession = class {
25263
25604
  let created = false;
25264
25605
  try {
25265
25606
  const directory = this.ensureDirectory();
25266
- path = join8(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
25607
+ path = join9(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
25267
25608
  fd = openSync3(path, "wx", FILE_MODE);
25268
25609
  created = true;
25269
- writeFileSync5(fd, buf);
25610
+ writeFileSync6(fd, buf);
25270
25611
  closeSync3(fd);
25271
25612
  fd = void 0;
25272
25613
  chmodSync(path, FILE_MODE);
@@ -25281,7 +25622,7 @@ var ArtifactSaveSession = class {
25281
25622
  }
25282
25623
  if (created && path) {
25283
25624
  try {
25284
- unlinkSync2(path);
25625
+ unlinkSync3(path);
25285
25626
  } catch {
25286
25627
  }
25287
25628
  }
@@ -25292,7 +25633,7 @@ var ArtifactSaveSession = class {
25292
25633
  }
25293
25634
  ensureDirectory() {
25294
25635
  if (this.directory) return this.directory;
25295
- const directory = mkdtempSync(join8(tmpdir(), "dvm-artifacts-"));
25636
+ const directory = mkdtempSync(join9(tmpdir(), "dvm-artifacts-"));
25296
25637
  try {
25297
25638
  chmodSync(directory, DIRECTORY_MODE);
25298
25639
  } catch (err) {
@@ -25428,9 +25769,12 @@ function nextActionHuman(action) {
25428
25769
  if (action.type === "respond") {
25429
25770
  return `Next: ${display} Provider is waiting for your input. ${command ? `Run \`${command}\`.` : action.hint}`;
25430
25771
  }
25772
+ if (command?.startsWith("dvm decline ")) return `Next: ${display} ${action.hint}`;
25431
25773
  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}`;
25774
+ const budgetChange = command?.includes(" --budget ");
25775
+ const approval = budgetChange ? "Ask your human to approve the new total first, then run" : "Run";
25776
+ const decline2 = (action.charged_if_declined_micro !== void 0 || budgetChange) && command?.startsWith("dvm pay ") ? ` To stop instead, run \`dvm decline ${shellQuoteArg(action.job_id)}\`.` : "";
25777
+ return `Next: Payment required to continue: ${display}${display.endsWith(".") ? "" : "."} ${approval} \`${command ?? `dvm pay ${shellQuoteArg(action.job_id)}`}\`.${decline2}${thresholdHint}`;
25434
25778
  }
25435
25779
  case "poll": {
25436
25780
  const hint = typeof action.hint === "string" ? action.hint : action.hint.text;
@@ -25465,8 +25809,68 @@ function readNextAction(jobId, messages2, options = {}) {
25465
25809
  return action;
25466
25810
  }
25467
25811
 
25812
+ // src/lib/wait-payment-lines.ts
25813
+ function createWaitPaymentLines(opts) {
25814
+ const report = opts.onAutoPayment;
25815
+ const emitted = /* @__PURE__ */ new Set();
25816
+ const reported = /* @__PURE__ */ new Set();
25817
+ const waiting = /* @__PURE__ */ new Map();
25818
+ function write(payment, seq, force = false) {
25819
+ if (reported.has(seq)) return;
25820
+ if (!force && seq > opts.afterSeq && !emitted.has(seq)) {
25821
+ waiting.set(seq, payment);
25822
+ return;
25823
+ }
25824
+ waiting.delete(seq);
25825
+ reported.add(seq);
25826
+ report?.(payment, seq);
25827
+ }
25828
+ const stop = report ? observePaymentBookings((booking) => {
25829
+ if (booking.jobId === opts.jobId && booking.approval === "auto") write(bookedPayment(booking), booking.requestSeq);
25830
+ }) : () => void 0;
25831
+ return {
25832
+ onMessage(message2) {
25833
+ opts.onMessage?.(message2);
25834
+ emitted.add(message2.seq);
25835
+ const pending4 = waiting.get(message2.seq);
25836
+ if (pending4) write(pending4, message2.seq);
25837
+ },
25838
+ onAutoPayment: write,
25839
+ finish() {
25840
+ stop();
25841
+ for (const seq of [...waiting.keys()].sort((a, b) => a - b)) write(waiting.get(seq), seq, true);
25842
+ }
25843
+ };
25844
+ }
25845
+ function bookedPayment(booking) {
25846
+ const ask = loadMessages(booking.jobId).find((message2) => message2.seq === booking.requestSeq && message2.type === "payment-request");
25847
+ const content = ask?.type === "payment-request" ? ask.content : void 0;
25848
+ const paid = {
25849
+ status: "paid",
25850
+ rail: booking.rail,
25851
+ amountMsats: booking.amountMsats,
25852
+ ...booking.amountUsdcMicro !== void 0 ? { amountUsdcMicro: booking.amountUsdcMicro } : {}
25853
+ };
25854
+ return {
25855
+ amount_msats: booking.amountMsats,
25856
+ rail: booking.rail,
25857
+ reason: asProviderText(booking.reason ?? content?.reason ?? ""),
25858
+ ...booking.amountUsdcMicro !== void 0 ? { amount_usdc_microunits: booking.amountUsdcMicro } : {},
25859
+ display: paidConfirmationDisplay(paid, content?.fiat_amount)
25860
+ };
25861
+ }
25862
+
25468
25863
  // src/lib/wait-for-job.ts
25469
25864
  async function waitForJob(opts, durationMs, now = Date.now) {
25865
+ if (!opts.onAutoPayment) return waitAttached(opts, durationMs, now);
25866
+ const payments = createWaitPaymentLines(opts);
25867
+ try {
25868
+ return await waitAttached({ ...opts, onMessage: payments.onMessage, onAutoPayment: payments.onAutoPayment }, durationMs, now);
25869
+ } finally {
25870
+ payments.finish();
25871
+ }
25872
+ }
25873
+ async function waitAttached(opts, durationMs, now) {
25470
25874
  const deadline = now() + durationMs;
25471
25875
  const result = {
25472
25876
  messages: [],
@@ -25491,6 +25895,8 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25491
25895
  const messageAppendSession = opts.persistLocalState === false ? void 0 : opts.messageAppendSession ?? createMessageAppendSession(opts.jobId);
25492
25896
  let backoffMs = 1e3;
25493
25897
  let firstRead = true;
25898
+ let paymentInFlight = false;
25899
+ let seenRunning = false;
25494
25900
  const idleTimeoutMs = opts.timeoutMs ?? JOB_READ_TIMEOUT_MS;
25495
25901
  async function readWithRetry(read) {
25496
25902
  while (now() < deadline) {
@@ -25508,6 +25914,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25508
25914
  const readOptions = () => ({ jobToken: opts.jobToken, timeoutMs: Math.max(1, Math.min(idleTimeoutMs, deadline - now())) });
25509
25915
  const snapshot = await readWithRetry(() => opts.transport.status(opts.jobId, opts.provider, readOptions()));
25510
25916
  if (!snapshot) break;
25917
+ seenRunning = !isTerminalJobStatus(snapshot.status);
25511
25918
  if (isTerminalJobStatus(snapshot.status)) {
25512
25919
  result.providerStatus = snapshot;
25513
25920
  result.nextAction = null;
@@ -25574,6 +25981,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25574
25981
  }
25575
25982
  if (unresolved && !newerYield) {
25576
25983
  result.nextAction = pollNextAction(opts.jobId);
25984
+ paymentInFlight = true;
25577
25985
  await new Promise((resolve3) => setTimeout(resolve3, Math.min(retryDelayMs, Math.max(0, deadline - now()))));
25578
25986
  backoffMs = Math.min(backoffMs * 2, 3e4);
25579
25987
  continue;
@@ -25598,6 +26006,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25598
26006
  const progressed = next.cursor > result.cursor;
25599
26007
  result.cursor = Math.min(next.cursor, cursorLimit);
25600
26008
  result.nextAction = next.nextAction;
26009
+ paymentInFlight = next.paymentInFlight === true;
25601
26010
  if (hasUnsavedJobState() || next.nextAction?.type !== "poll") break;
25602
26011
  if (progressed) backoffMs = 1e3;
25603
26012
  const delay = Math.min(backoffMs, Math.max(0, deadline - now()));
@@ -25609,8 +26018,27 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25609
26018
  result.cursor = Math.min(result.cursor, ...remaining.map((seq) => seq - 1));
25610
26019
  }
25611
26020
  result.messages.sort((a, b) => a.seq - b.seq);
26021
+ if (now() >= deadline && result.nextAction?.type === "poll" && !hasUnsavedJobState())
26022
+ result.nextAction = waitLimitAction(opts, durationMs, result.nextAction, { paymentInFlight, seenRunning });
25612
26023
  return result;
25613
26024
  }
26025
+ function waitLimitAction(opts, durationMs, current, state) {
26026
+ const { jobId } = opts;
26027
+ const limit = formatDurationMs(durationMs);
26028
+ const job = opts.persistLocalState === false ? void 0 : loadJob(jobId);
26029
+ const answered = job ? loadAnsweredYieldSeqs(jobId) : /* @__PURE__ */ new Set();
26030
+ const heldSeq = job?.inFlightPaymentRequestSeqs?.[0] ?? Object.keys(job?.unconfirmedPaymentSubmissions ?? {}).map(Number).find((seq) => !answered.has(seq));
26031
+ if (heldSeq !== void 0)
26032
+ return pollNextAction(jobId, `The wait limit (${limit}) was reached while an earlier payment for this job is unconfirmed. ` + paymentInFlightHint(jobId, job, heldSeq));
26033
+ if (state.paymentInFlight) return current;
26034
+ const arg = guidanceJobArg(jobId);
26035
+ if (!state.seenRunning)
26036
+ 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\`.`);
26037
+ return {
26038
+ ...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}\`.`),
26039
+ ...current.estimate_seconds !== void 0 ? { estimate_seconds: current.estimate_seconds } : {}
26040
+ };
26041
+ }
25614
26042
 
25615
26043
  // src/commands/messages.ts
25616
26044
  async function messages(jobId, opts) {
@@ -25708,6 +26136,13 @@ async function messagesWithAccess(jobId, opts, access) {
25708
26136
  return;
25709
26137
  }
25710
26138
  progressNotice("Streaming messages...", opts.human);
26139
+ const streamEvents = opts.wait === true && !opts.human;
26140
+ const recordDelivery = streamEvents && !access.endpointOverridden;
26141
+ const delivered = recordDelivery ? stored?.waitDeliveredSeq ?? 0 : 0;
26142
+ const skipThrough = opts.after === void 0 ? delivered : 0;
26143
+ let lastDelivered = delivered;
26144
+ let messageLines = 0;
26145
+ let paymentLines = 0;
25711
26146
  const streamOptions = {
25712
26147
  jobId,
25713
26148
  transport,
@@ -25722,6 +26157,18 @@ async function messagesWithAccess(jobId, opts, access) {
25722
26157
  onMessage: (msg) => {
25723
26158
  if (msg.type === "progress") formatMessageHuman(msg);
25724
26159
  }
26160
+ },
26161
+ ...streamEvents && {
26162
+ onMessage: (msg) => {
26163
+ if (msg.seq <= skipThrough && !((msg.type === "payment-request" || msg.type === "prompt") && !loadAnsweredYieldSeqs(jobId).has(msg.seq))) return;
26164
+ jsonEvent({ event: "message", ...serialize(msg) });
26165
+ messageLines++;
26166
+ lastDelivered = Math.max(lastDelivered, msg.seq);
26167
+ },
26168
+ onAutoPayment: (payment) => {
26169
+ jsonEvent({ event: "payment", ...payment });
26170
+ paymentLines++;
26171
+ }
25725
26172
  }
25726
26173
  };
25727
26174
  const waitDeadline = waitDuration === void 0 ? void 0 : Date.now() + waitDuration;
@@ -25731,6 +26178,13 @@ async function messagesWithAccess(jobId, opts, access) {
25731
26178
  } catch (err) {
25732
26179
  transport.close();
25733
26180
  throw err;
26181
+ } finally {
26182
+ if (recordDelivery && lastDelivered > delivered) {
26183
+ try {
26184
+ if (lastDelivered > (loadJob(jobId)?.waitDeliveredSeq ?? 0)) updateObservedJob(jobId, { waitDeliveredSeq: lastDelivered });
26185
+ } catch {
26186
+ }
26187
+ }
25734
26188
  }
25735
26189
  const providerStatus = waitDeadline !== void 0 && Date.now() >= waitDeadline ? void 0 : await observeJobContent(jobId, transport, ref, {
25736
26190
  timeoutMs: waitDeadline === void 0 ? opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now())),
@@ -25764,6 +26218,18 @@ async function messagesWithAccess(jobId, opts, access) {
25764
26218
  finalizeProgressLine();
25765
26219
  }
25766
26220
  printNextActionHuman(resolvedAction, { refunds: result.refunds });
26221
+ } else if (streamEvents) {
26222
+ json3({
26223
+ event: "result",
26224
+ jobId,
26225
+ ...content,
26226
+ ...settlement,
26227
+ message_count: messageLines,
26228
+ auto_payment_count: paymentLines,
26229
+ cursor: result.cursor,
26230
+ next_action: resolvedAction,
26231
+ ...await refundJsonField(result.refunds)
26232
+ });
25767
26233
  } else {
25768
26234
  json3({
25769
26235
  jobId,
@@ -26091,11 +26557,20 @@ async function payWithAccess(jobId, opts, access) {
26091
26557
  maxCashuPrincipalSats,
26092
26558
  requestSeq,
26093
26559
  approval: "explicit",
26094
- creditRecoveryOnly: pending4 !== void 0
26560
+ creditRecoveryOnly: pending4 !== void 0,
26561
+ budget: opts.budget,
26562
+ useStoredPolicy: true
26095
26563
  });
26096
26564
  if (result === "over-budget") {
26097
26565
  transport.close();
26098
- throw new DvmError("over_budget", "Payment would exceed the job's budget.");
26566
+ const refusal = requestSeq === void 0 ? void 0 : loadJob(jobId)?.budgetRefusals?.[String(requestSeq)];
26567
+ const current = loadJob(jobId);
26568
+ const countHint = current?.policy && (current.paymentsHonoured ?? 0) >= current.policy.maxPayments ? paymentCountHint(jobId, current.policy.maxPayments) : void 0;
26569
+ throw new DvmError(
26570
+ "over_budget",
26571
+ "Payment would exceed the job's budget.",
26572
+ countHint ?? (refusal ? overBudgetHint(jobId, describeBudgetOverrun(refusal, loadJob(jobId)?.policy)) : void 0)
26573
+ );
26099
26574
  }
26100
26575
  if (result === "payment-cap-exceeded") {
26101
26576
  transport.close();
@@ -26103,7 +26578,7 @@ async function payWithAccess(jobId, opts, access) {
26103
26578
  throw new DvmError(
26104
26579
  "payment_cap_exceeded",
26105
26580
  "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.`,
26581
+ paymentCountHint(jobId, cap2),
26107
26582
  {
26108
26583
  anchor: "max_payments_exceeded",
26109
26584
  display: `Payment cap reached (${cap2} payment${cap2 === 1 ? "" : "s"})`,
@@ -26124,7 +26599,7 @@ async function payWithAccess(jobId, opts, access) {
26124
26599
  jobId,
26125
26600
  transport,
26126
26601
  provider: ref,
26127
- policy: stored.policy,
26602
+ policy: loadJob(jobId)?.policy ?? stored.policy,
26128
26603
  afterSeq,
26129
26604
  timeoutMs,
26130
26605
  jobToken,
@@ -26226,28 +26701,6 @@ function parsePositiveCashuSats(raw2) {
26226
26701
  return value;
26227
26702
  }
26228
26703
 
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
26704
  // src/lib/auto-pay-warning.ts
26252
26705
  function positive(value) {
26253
26706
  return typeof value === "number" && Number.isFinite(value) && value > 0;
@@ -27245,46 +27698,6 @@ function hintForUnconfigured(flag, _hasOther) {
27245
27698
  }
27246
27699
  }
27247
27700
 
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
27701
  // src/lib/wallet-agent/balance.ts
27289
27702
  function groupProofsByMint(proofs) {
27290
27703
  const out = /* @__PURE__ */ new Map();
@@ -28650,7 +29063,7 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
28650
29063
  if (plan.mode === "none" && plan.suppressed) {
28651
29064
  const posture = effectiveCreditPosture(loadConfig()?.credit, ref.endpoint, attestedIdentity);
28652
29065
  const priceMicro = planRate > 0 ? msatsToMicro(chosen.priceMsats, planRate) : 0;
28653
- noteCreditSuggestion(
29066
+ stageCreditSuggestion(
28654
29067
  buildCreditSuggestion({
28655
29068
  dvm: identity.dvmId ?? ref.endpoint,
28656
29069
  endpoint: ref.endpoint,
@@ -28871,6 +29284,13 @@ function floatUsable() {
28871
29284
  return false;
28872
29285
  }
28873
29286
  }
29287
+ function cashuUpfrontPayment(chosen, btcRate) {
29288
+ return upfrontRailPayment("cashu", chosen.priceMsats, dollarBoundUsdMicro({
29289
+ msats: chosen.priceMsats,
29290
+ usdMicro: usdMicro(chosen.upfront?.amount_micro, chosen.upfront?.currency),
29291
+ rate: btcRate
29292
+ }));
29293
+ }
28874
29294
  function buildSpendLabel(capability, input) {
28875
29295
  return input.length > 0 ? `${capability} \xB7 ${input.length.toLocaleString("en-US")} chars` : capability;
28876
29296
  }
@@ -28986,7 +29406,8 @@ async function payWithTempo(args, credential) {
28986
29406
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
28987
29407
  const usdcMicroUnits = Number(tempoCredentialAmountMicro(credential));
28988
29408
  const paidMsats = usdcToMsats(usdcMicroUnits / 1e6, btcRate);
28989
- if (opts.requestId) recordRequestRailPayment(opts.requestId, { method: "tempo", amountMsats: paidMsats });
29409
+ const railPayment = upfrontRailPayment("tempo", paidMsats, usdMicro(usdcMicroUnits, "usd"));
29410
+ if (opts.requestId) recordRequestRailPayment(opts.requestId, railPayment);
28990
29411
  const usd2 = usdcMicroUnits / 1e6;
28991
29412
  const priceLabel = `$${formatUsd(usd2)} USDC`;
28992
29413
  const accountShort = `${account.address.slice(0, 6)}\u2026${account.address.slice(-4)}`;
@@ -29081,7 +29502,7 @@ async function payWithTempo(args, credential) {
29081
29502
  `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
29503
  );
29083
29504
  }
29084
- recordUpfrontRailPayment(effectiveJobId, { method: "tempo", amountMsats: paidMsats }, true);
29505
+ recordUpfrontRailPayment(effectiveJobId, railPayment, true);
29085
29506
  recordSpend({
29086
29507
  msats: paidMsats,
29087
29508
  btcRate: args.btcRate,
@@ -29090,6 +29511,7 @@ async function payWithTempo(args, credential) {
29090
29511
  label: buildSpendLabel(identity.capability, envelope.input)
29091
29512
  });
29092
29513
  if (receipt.status === "completed" && receipt.summary) {
29514
+ commitCreditSuggestion();
29093
29515
  markJobTerminal(effectiveJobId, "completed", completionSnapshot(receipt), {
29094
29516
  costMsats: paidMsats,
29095
29517
  paymentMethod: "tempo"
@@ -29340,7 +29762,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
29340
29762
  const priceSats = Math.ceil(chosen.priceMsats / 1e3);
29341
29763
  const maxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
29342
29764
  const baseContext = {
29343
- upfront_rail_payment: { method: "cashu", amountMsats: chosen.priceMsats },
29765
+ upfront_rail_payment: cashuUpfrontPayment(chosen, btcRate),
29344
29766
  dvm_id: identity.dvmId,
29345
29767
  capability: identity.capability,
29346
29768
  pinned_mint: opts.mint,
@@ -29469,7 +29891,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
29469
29891
  });
29470
29892
  }
29471
29893
  const pricedRequestId = opts.requestId ?? generatedRequestId;
29472
- if (pricedRequestId) recordRequestRailPayment(pricedRequestId, { method: "cashu", amountMsats: chosen.priceMsats });
29894
+ if (pricedRequestId) recordRequestRailPayment(pricedRequestId, cashuUpfrontPayment(chosen, btcRate));
29473
29895
  if (fundPlan && signing) {
29474
29896
  ensureProvisionalCredit({
29475
29897
  endpoint: ref.endpoint,
@@ -29738,7 +30160,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29738
30160
  });
29739
30161
  }
29740
30162
  await collectCashuChange(effectiveJobId, receipt.cashuChange);
29741
- recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
30163
+ recordUpfrontRailPayment(effectiveJobId, cashuUpfrontPayment(chosen, btcRate), true);
29742
30164
  if (!hasUnsavedJobState()) await commitAgentSpend({
29743
30165
  requestId: prepared.requestId,
29744
30166
  recentSpend: {
@@ -29768,6 +30190,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29768
30190
  });
29769
30191
  }
29770
30192
  if (receipt.status === "completed" && receipt.summary) {
30193
+ commitCreditSuggestion();
29771
30194
  markJobTerminal(effectiveJobId, "completed", completionSnapshot(receipt), {
29772
30195
  costMsats: chosen.priceMsats,
29773
30196
  paymentMethod: "cashu"
@@ -29876,7 +30299,8 @@ async function tryX402UpfrontPayment(args) {
29876
30299
  }
29877
30300
  async function payWithX402(args, proof) {
29878
30301
  const { transport, ref, envelope, chosen, opts, identity, policy, wallet } = args;
29879
- if (opts.requestId) recordRequestRailPayment(opts.requestId, { method: "x402", amountMsats: proof.amountMsats });
30302
+ const railPayment = upfrontRailPayment("x402", proof.amountMsats, usdMicro(Number(proof.amountUsdcMicro), "usd"));
30303
+ if (opts.requestId) recordRequestRailPayment(opts.requestId, railPayment);
29880
30304
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
29881
30305
  const usdcMicroUnits = Number(proof.amountUsdcMicro);
29882
30306
  const usd2 = usdcMicroUnits / 1e6;
@@ -29961,7 +30385,7 @@ async function payWithX402(args, proof) {
29961
30385
  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
30386
  );
29963
30387
  }
29964
- recordUpfrontRailPayment(effectiveJobId, { method: "x402", amountMsats: proof.amountMsats }, true);
30388
+ recordUpfrontRailPayment(effectiveJobId, railPayment, true);
29965
30389
  recordSpend({
29966
30390
  msats: proof.amountMsats,
29967
30391
  btcRate: proof.btcRate,
@@ -29970,6 +30394,7 @@ async function payWithX402(args, proof) {
29970
30394
  label: buildSpendLabel(identity.capability, envelope.input)
29971
30395
  });
29972
30396
  if (receipt.status === "completed" && receipt.summary) {
30397
+ commitCreditSuggestion();
29973
30398
  markJobTerminal(effectiveJobId, "completed", completionSnapshot(receipt), {
29974
30399
  costMsats: proof.amountMsats,
29975
30400
  paymentMethod: "x402"
@@ -30178,6 +30603,7 @@ async function streamAfterPayment(args) {
30178
30603
  }
30179
30604
  throw new DvmError("timeout", paidTimeoutMessage);
30180
30605
  }
30606
+ if (streamedTerminal !== "failed" && streamedTerminal !== "cancelled") commitCreditSuggestion();
30181
30607
  if (human) {
30182
30608
  if (streamedTerminal === "failed" || streamedTerminal === "cancelled")
30183
30609
  info(`Status: ${streamedTerminal}${completion?.message ? `: ${completion.message}` : ""}`);
@@ -30233,6 +30659,7 @@ async function recoverViaStatusPoll(args) {
30233
30659
  costMsats: chosen.priceMsats,
30234
30660
  paymentMethod: paymentMethod2
30235
30661
  });
30662
+ commitCreditSuggestion();
30236
30663
  await collectCashuChange(jobId, status2.cashuChange);
30237
30664
  const captured = captureTransportReceipt(jobId, status2);
30238
30665
  if (!args.strictPerCall)
@@ -30869,7 +31296,7 @@ function jobSpend(job, receipt) {
30869
31296
  const totalDisplay = formatPaymentAmount(total, fiat, { anchor: false }) + valuationLabel;
30870
31297
  const budgetDisplay = job.policy ? formatPaymentAmount(
30871
31298
  job.policy.maxTotalMsats,
30872
- fiat && total > 0 ? { currency: fiat.currency, amount: fiat.amount * job.policy.maxTotalMsats / total } : void 0,
31299
+ 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
31300
  { anchor: false }
30874
31301
  ) : void 0;
30875
31302
  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 +32977,14 @@ function tempoChannelDisplay(chain, endpoint, amounts) {
32550
32977
  }
32551
32978
  function x402ChannelDisplay(chain, channel) {
32552
32979
  const where = x402NetworkLabel(channel.network);
32553
- const amount = usdMicro(chain.depositMicro);
32980
+ const amount = usdMicro2(chain.depositMicro);
32554
32981
  switch (chain.status) {
32555
32982
  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.`;
32983
+ 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
32984
  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.`;
32985
+ 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
32986
  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.`;
32987
+ 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
32988
  case "unconfirmed":
32562
32989
  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
32990
  case "unreadable":
@@ -32594,7 +33021,7 @@ function foreignX402ChannelClause(payer, connected) {
32594
33021
  function foreignX402ChannelHint() {
32595
33022
  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
33023
  }
32597
- function usdMicro(micro) {
33024
+ function usdMicro2(micro) {
32598
33025
  return micro === void 0 ? void 0 : `$${(micro / 1e6).toFixed(2)}`;
32599
33026
  }
32600
33027
  var UNKNOWN_AMOUNT = "an unknown amount";
@@ -33223,7 +33650,7 @@ function mnemonicValidationError(result) {
33223
33650
  var import_qrcode = __toESM(require_lib(), 1);
33224
33651
  import { randomBytes as randomBytes3 } from "crypto";
33225
33652
  import { tmpdir as tmpdir2 } from "os";
33226
- import { join as join9 } from "path";
33653
+ import { join as join10 } from "path";
33227
33654
  async function renderQrTerminal(payload) {
33228
33655
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
33229
33656
  }
@@ -33236,7 +33663,7 @@ async function renderQrPng(payload, outPath) {
33236
33663
  });
33237
33664
  }
33238
33665
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
33239
- return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
33666
+ return join10(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
33240
33667
  }
33241
33668
 
33242
33669
  // src/lib/funding-handoff.ts
@@ -33681,18 +34108,18 @@ function examples(fetcher) {
33681
34108
  }
33682
34109
 
33683
34110
  // src/lib/error-handler.ts
33684
- async function catchErrors(fn, human) {
34111
+ async function catchErrors(fn, human, jsonFields) {
33685
34112
  const lifetimeHold = setInterval(() => void 0, 60 * 60 * 1e3);
33686
34113
  try {
33687
34114
  await fn();
33688
34115
  } catch (err) {
33689
- handleError(err, human);
34116
+ handleError(err, human, jsonFields);
33690
34117
  } finally {
33691
34118
  clearInterval(lifetimeHold);
33692
34119
  }
33693
34120
  process.exit(process.exitCode ?? 0);
33694
34121
  }
33695
- function handleError(err, human) {
34122
+ function handleError(err, human, jsonFields) {
33696
34123
  if (err instanceof DvmError) {
33697
34124
  if (human) {
33698
34125
  if (err.code === "client_upgrade_required") {
@@ -33720,6 +34147,7 @@ function handleError(err, human) {
33720
34147
  }
33721
34148
  }
33722
34149
  json({
34150
+ ...jsonFields,
33723
34151
  error,
33724
34152
  ...takeCreditNoticeFields(),
33725
34153
  ...takeFeedbackNoticeFields()
@@ -33733,6 +34161,7 @@ function handleError(err, human) {
33733
34161
  info(`Error: ${message2}`);
33734
34162
  } else {
33735
34163
  json({
34164
+ ...jsonFields,
33736
34165
  error: {
33737
34166
  code: "internal",
33738
34167
  message: message2,
@@ -35163,14 +35592,14 @@ import { randomUUID as randomUUID5 } from "crypto";
35163
35592
  // src/lib/wallet-agent/release-intents.ts
35164
35593
  var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
35165
35594
  import { createHash as createHash6 } from "crypto";
35166
- import { dirname as dirname4, join as join10 } from "path";
35595
+ import { dirname as dirname4, join as join11 } from "path";
35167
35596
  var intents = journalFile("release-intents.json");
35168
35597
  async function withReleaseLock(walletPubkey, builderHandle, mint, operation) {
35169
35598
  ensureConfigDir();
35170
35599
  const key = createHash6("sha256").update(JSON.stringify([walletPubkey, builderHandle, mint])).digest("hex");
35171
35600
  let unlock;
35172
35601
  try {
35173
- unlock = await import_proper_lockfile3.default.lock(join10(dirname4(JOBS_FILE), `release-${key}`), {
35602
+ unlock = await import_proper_lockfile3.default.lock(join11(dirname4(JOBS_FILE), `release-${key}`), {
35174
35603
  realpath: false,
35175
35604
  stale: 2 * 6e4,
35176
35605
  retries: 0
@@ -38060,14 +38489,14 @@ function hexToBytes2(hex2) {
38060
38489
  var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
38061
38490
  import {
38062
38491
  chmodSync as chmodSync2,
38063
- existsSync as existsSync8,
38492
+ existsSync as existsSync9,
38064
38493
  readdirSync as readdirSync5,
38065
- readFileSync as readFileSync9,
38066
- renameSync as renameSync4,
38067
- unlinkSync as unlinkSync3,
38068
- writeFileSync as writeFileSync6
38494
+ readFileSync as readFileSync10,
38495
+ renameSync as renameSync5,
38496
+ unlinkSync as unlinkSync4,
38497
+ writeFileSync as writeFileSync7
38069
38498
  } from "fs";
38070
- import { join as join11 } from "path";
38499
+ import { join as join12 } from "path";
38071
38500
  var pairingIdPattern = /^[0-9a-f]{64}$/;
38072
38501
  var stateSchema = external_exports.object({
38073
38502
  version: external_exports.literal(1),
@@ -38089,12 +38518,12 @@ var stateSchema = external_exports.object({
38089
38518
  function createWalletPairingState(state) {
38090
38519
  ensurePairingsDirectory();
38091
38520
  const path = pairingPath(state.pairing_id);
38092
- writeFileSync6(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
38521
+ writeFileSync7(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
38093
38522
  chmodSync2(path, 384);
38094
38523
  }
38095
38524
  function loadWalletPairingState(pairingId) {
38096
38525
  const path = pairingPath(pairingId);
38097
- if (!existsSync8(path)) {
38526
+ if (!existsSync9(path)) {
38098
38527
  throw new DvmError(
38099
38528
  "wallet_pairing_not_found",
38100
38529
  "No local state exists for that wallet pairing.",
@@ -38102,7 +38531,7 @@ function loadWalletPairingState(pairingId) {
38102
38531
  );
38103
38532
  }
38104
38533
  try {
38105
- return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
38534
+ return stateSchema.parse(JSON.parse(readFileSync10(path, "utf8")));
38106
38535
  } catch {
38107
38536
  throw new DvmError(
38108
38537
  "wallet_pairing_state_invalid",
@@ -38116,13 +38545,13 @@ function saveWalletPairingState(state) {
38116
38545
  ensurePairingsDirectory();
38117
38546
  const path = pairingPath(state.pairing_id);
38118
38547
  const tmp = `${path}.tmp`;
38119
- writeFileSync6(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
38548
+ writeFileSync7(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
38120
38549
  try {
38121
- renameSync4(tmp, path);
38550
+ renameSync5(tmp, path);
38122
38551
  chmodSync2(path, 384);
38123
38552
  } catch (err) {
38124
38553
  try {
38125
- unlinkSync3(tmp);
38554
+ unlinkSync4(tmp);
38126
38555
  } catch {
38127
38556
  }
38128
38557
  throw err;
@@ -38131,21 +38560,21 @@ function saveWalletPairingState(state) {
38131
38560
  function deleteWalletPairingState(pairingId) {
38132
38561
  const path = pairingPath(pairingId);
38133
38562
  try {
38134
- unlinkSync3(path);
38563
+ unlinkSync4(path);
38135
38564
  } catch (err) {
38136
38565
  if (err.code !== "ENOENT") throw err;
38137
38566
  }
38138
38567
  }
38139
38568
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
38140
- if (!existsSync8(PAIRINGS_DIR)) return 0;
38569
+ if (!existsSync9(PAIRINGS_DIR)) return 0;
38141
38570
  let removed = 0;
38142
38571
  for (const name of readdirSync5(PAIRINGS_DIR)) {
38143
38572
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
38144
- const path = join11(PAIRINGS_DIR, name);
38573
+ const path = join12(PAIRINGS_DIR, name);
38145
38574
  try {
38146
- const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
38575
+ const state = stateSchema.parse(JSON.parse(readFileSync10(path, "utf8")));
38147
38576
  if (state.manifest.expires_at <= nowSeconds) {
38148
- unlinkSync3(path);
38577
+ unlinkSync4(path);
38149
38578
  removed += 1;
38150
38579
  }
38151
38580
  } catch {
@@ -38155,7 +38584,7 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
38155
38584
  }
38156
38585
  async function withWalletPairingLock(pairingId, fn) {
38157
38586
  const path = pairingPath(pairingId);
38158
- if (!existsSync8(path)) return fn();
38587
+ if (!existsSync9(path)) return fn();
38159
38588
  let release;
38160
38589
  try {
38161
38590
  release = await import_proper_lockfile4.default.lock(path, {
@@ -38185,7 +38614,7 @@ function pairingPath(pairingId) {
38185
38614
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
38186
38615
  );
38187
38616
  }
38188
- return join11(PAIRINGS_DIR, `${pairingId}.json`);
38617
+ return join12(PAIRINGS_DIR, `${pairingId}.json`);
38189
38618
  }
38190
38619
  function ensurePairingsDirectory() {
38191
38620
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -39983,8 +40412,8 @@ function buildProgram() {
39983
40412
  `Choose reusable channel collateral or, only when the DVM explicitly allows its manual refund obligation, a one-shot stablecoin payment: ${creditFundingModes}. Stablecoin rails only`
39984
40413
  ).option(
39985
40414
  "--spt <token>",
39986
- "Pay by card: the shared payment token (spt_\u2026) your human approved in Stripe Link, or '-' to read it from stdin. Implies --rail stripe; without it, --rail stripe prints the link-cli approval steps"
39987
- ).option("--credit-id <id>", "Fund a specific credit id instead of the tracked one").option("--as <name>", "Caller signing identity to sign the funding as").option("--human", "Human-readable output instead of JSON").action((dvm, opts) => {
40415
+ "Pay by card: the shared payment token (spt_\u2026) your human approved in Stripe Link, or '-' to read it from stdin. Implies --rail stripe; without it, --rail stripe offers a card checkout link when supported, otherwise the link-cli approval steps"
40416
+ ).option("--no-wait", "Print the card checkout link and exit; re-run to resume and confirm payment").option("--credit-id <id>", "Fund a specific credit id instead of the tracked one").option("--as <name>", "Caller signing identity to sign the funding as").option("--human", "Human-readable output instead of JSON").action((dvm, opts) => {
39988
40417
  return catchErrors(() => creditFund(dvm, opts), opts.human);
39989
40418
  });
39990
40419
  credit.command("drain <dvm>").description(
@@ -40009,8 +40438,17 @@ function buildProgram() {
40009
40438
  ).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
40439
  return catchErrors(() => creditReceipts(dvm, opts), opts.human);
40011
40440
  });
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);
40441
+ const jsonWait = () => {
40442
+ const args = program2.args.slice(1);
40443
+ return args.includes("--wait") && !args.includes("--human");
40444
+ };
40445
+ program2.command("messages <job-id>").configureOutput({ outputError: (text, write) => {
40446
+ if (!jsonWait()) write(text);
40447
+ } }).exitOverride((error) => {
40448
+ if (error.exitCode === 0 || !jsonWait()) process.exit(error.exitCode);
40449
+ handleError(new DvmError("invalid_arguments", error.message.replace(/^error: /, "")), false, { event: "error" });
40450
+ }).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) => {
40451
+ return catchErrors(() => messages(jobId, opts), opts.human, opts.wait && !opts.human ? { event: "error" } : void 0);
40014
40452
  });
40015
40453
  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
40454
  "--type <type>",
@@ -40020,7 +40458,7 @@ function buildProgram() {
40020
40458
  });
40021
40459
  program2.command("pay <job-id>").description(
40022
40460
  "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(
40461
+ ).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
40462
  "--mint <url>",
40025
40463
  "Pin the Cashu spend mint for this payment (must be one the DVM accepts). Overrides any mint pinned at request time."
40026
40464
  ).option("--rail <rail>", "Force this payment onto cashu, tempo, or x402 without fallback").option(