@dvmkit/dvm-cli 0.19.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dvm.js CHANGED
@@ -5,17 +5,18 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-OCVRCWBL.js";
8
+ } from "./chunk-MSQJWCPT.js";
9
9
  import {
10
- CARD_MIN_MICRO,
11
10
  DEFAULT_CREDIT_POSTURE,
12
11
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
13
12
  JOB_READ_TIMEOUT_MS,
13
+ MINT_FEE_EXPLAINER,
14
14
  MINT_QUOTE_EXPIRY_GRACE_MS,
15
15
  NWC_FUNDING_FLOAT_ROLE,
16
16
  SUBMISSION_EVIDENCE_DIR,
17
17
  abandonPendingSubmission,
18
18
  abandonSubmissionInWallet,
19
+ addCashuSwapFee,
19
20
  addPayment,
20
21
  answeredYieldSeqs,
21
22
  appendMessages,
@@ -33,6 +34,8 @@ import {
33
34
  captureDrawFundingReceipts,
34
35
  captureFundingReceipt,
35
36
  captureTransportReceipt,
37
+ cardMinimumMicro,
38
+ cashuPaymentFeeFields,
36
39
  clearAskPaymentBlocks,
37
40
  clearPaymentRequestInFlight,
38
41
  clearReclaimIntent,
@@ -50,6 +53,7 @@ import {
50
53
  declinedAskSeqs,
51
54
  deriveAlias,
52
55
  describeBudgetOverrun,
56
+ describeCashuPayment,
53
57
  describeMintBounds,
54
58
  dollarBoundUsdMicro,
55
59
  drainReceiptsDisplay,
@@ -153,6 +157,7 @@ import {
153
157
  receiptPieceContext,
154
158
  receiptSettlement,
155
159
  receiptTrustFields,
160
+ receiptUpfrontFault,
156
161
  reclaimIntentIds,
157
162
  reconcileInFlightPaymentRequest,
158
163
  reconcilePaymentRequestHistory,
@@ -191,6 +196,7 @@ import {
191
196
  settleRecordedPayments,
192
197
  settlementCurrencyHint,
193
198
  statusSnapshot,
199
+ submissionSwapFeeSats,
194
200
  sweepPendingMints,
195
201
  sweepStaleInFlight,
196
202
  terminalSettlementFields,
@@ -207,6 +213,7 @@ import {
207
213
  updateJob,
208
214
  updateObservedJob,
209
215
  upfrontRailPayment,
216
+ upfrontReceiptFields,
210
217
  usdMicro,
211
218
  walletHistory,
212
219
  walletInvoiceFundingAdvice,
@@ -216,13 +223,13 @@ import {
216
223
  withJobTokenRedaction,
217
224
  withRequestResultRecovery,
218
225
  withoutPendingMint
219
- } from "./chunk-NCX4JVLU.js";
226
+ } from "./chunk-4S6TNP4N.js";
220
227
  import {
221
228
  connectedTempoAccount,
222
229
  generateTempoKey,
223
230
  tempoBalanceCheckHint,
224
231
  tempoWrongAssetHint
225
- } from "./chunk-MM646MFM.js";
232
+ } from "./chunk-2B2MCZ2I.js";
226
233
  import {
227
234
  assertSupportedX402Network,
228
235
  connectedX402Payer,
@@ -231,7 +238,7 @@ import {
231
238
  repinX402WalletNetwork,
232
239
  saveX402Wallet,
233
240
  x402NetworkLabel
234
- } from "./chunk-NKD4NEUF.js";
241
+ } from "./chunk-2YPUKPJN.js";
235
242
  import {
236
243
  CREDIT_POSTURES,
237
244
  FEEDBACK_POSTURES,
@@ -248,7 +255,7 @@ import {
248
255
  retireConfigBackup,
249
256
  rollbackConfig,
250
257
  updateConfig
251
- } from "./chunk-3NXAIRFF.js";
258
+ } from "./chunk-EEQPFGPM.js";
252
259
  import {
253
260
  addOutputWarnings,
254
261
  assertValidBudget,
@@ -271,10 +278,10 @@ import {
271
278
  tryX402Payment,
272
279
  withOutputWarningContext,
273
280
  withOutputWarnings
274
- } from "./chunk-7HJ5ZR3D.js";
281
+ } from "./chunk-QXXPXQLM.js";
275
282
  import {
276
283
  assertX402WalletIdle
277
- } from "./chunk-B5KW2TPR.js";
284
+ } from "./chunk-DOAMK5C6.js";
278
285
  import {
279
286
  A,
280
287
  AGENT_MNEMONIC_FILE,
@@ -344,6 +351,7 @@ import {
344
351
  clean,
345
352
  clearCreditSelection,
346
353
  clearPendingDrain,
354
+ clearPendingFunding,
347
355
  clearPendingX402Funding,
348
356
  clearRefillRailUnavailable,
349
357
  computeSmartDenominations,
@@ -501,6 +509,7 @@ import {
501
509
  withinAdvertisedTolerance,
502
510
  wrapCipher,
503
511
  writeAgentMnemonic,
512
+ x,
504
513
  x402ChannelControlledBy,
505
514
  x402ChannelReservation,
506
515
  x402CreditChannelNetworks,
@@ -514,7 +523,7 @@ import {
514
523
  x402PendingUnsettled,
515
524
  x402RequiredFromError,
516
525
  x402ReservationRelease
517
- } from "./chunk-X6BETQ7V.js";
526
+ } from "./chunk-4RINUKY4.js";
518
527
  import "./chunk-JBU7RKQ3.js";
519
528
  import "./chunk-KDNFUDOG.js";
520
529
  import "./chunk-IUTVV6N5.js";
@@ -5041,13 +5050,13 @@ var require_galois_field = __commonJS({
5041
5050
  var EXP_TABLE = new Uint8Array(512);
5042
5051
  var LOG_TABLE = new Uint8Array(256);
5043
5052
  (function initTables() {
5044
- let x = 1;
5053
+ let x2 = 1;
5045
5054
  for (let i2 = 0; i2 < 255; i2++) {
5046
- EXP_TABLE[i2] = x;
5047
- LOG_TABLE[x] = i2;
5048
- x <<= 1;
5049
- if (x & 256) {
5050
- x ^= 285;
5055
+ EXP_TABLE[i2] = x2;
5056
+ LOG_TABLE[x2] = i2;
5057
+ x2 <<= 1;
5058
+ if (x2 & 256) {
5059
+ x2 ^= 285;
5051
5060
  }
5052
5061
  }
5053
5062
  for (let i2 = 255; i2 < 512; i2++) {
@@ -5061,9 +5070,9 @@ var require_galois_field = __commonJS({
5061
5070
  exports.exp = function exp(n) {
5062
5071
  return EXP_TABLE[n];
5063
5072
  };
5064
- exports.mul = function mul(x, y) {
5065
- if (x === 0 || y === 0) return 0;
5066
- return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]];
5073
+ exports.mul = function mul(x2, y) {
5074
+ if (x2 === 0 || y === 0) return 0;
5075
+ return EXP_TABLE[LOG_TABLE[x2] + LOG_TABLE[y]];
5067
5076
  };
5068
5077
  }
5069
5078
  });
@@ -6321,9 +6330,9 @@ var require_interlace = __commonJS({
6321
6330
  return images;
6322
6331
  };
6323
6332
  exports.getInterlaceIterator = function(width) {
6324
- return function(x, y, pass) {
6325
- let outerXLeftOver = x % imagePasses[pass].x.length;
6326
- let outerX = (x - outerXLeftOver) / imagePasses[pass].x.length * 8 + imagePasses[pass].x[outerXLeftOver];
6333
+ return function(x2, y, pass) {
6334
+ let outerXLeftOver = x2 % imagePasses[pass].x.length;
6335
+ let outerX = (x2 - outerXLeftOver) / imagePasses[pass].x.length * 8 + imagePasses[pass].x[outerXLeftOver];
6327
6336
  let outerYLeftOver = y % imagePasses[pass].y.length;
6328
6337
  let outerY = (y - outerYLeftOver) / imagePasses[pass].y.length * 8 + imagePasses[pass].y[outerYLeftOver];
6329
6338
  return outerX * 4 + outerY * width * 4;
@@ -6409,43 +6418,43 @@ var require_filter_parse = __commonJS({
6409
6418
  Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
6410
6419
  let xComparison = this._xComparison;
6411
6420
  let xBiggerThan = xComparison - 1;
6412
- for (let x = 0; x < byteWidth; x++) {
6413
- let rawByte = rawData[1 + x];
6414
- let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
6415
- unfilteredLine[x] = rawByte + f1Left;
6421
+ for (let x2 = 0; x2 < byteWidth; x2++) {
6422
+ let rawByte = rawData[1 + x2];
6423
+ let f1Left = x2 > xBiggerThan ? unfilteredLine[x2 - xComparison] : 0;
6424
+ unfilteredLine[x2] = rawByte + f1Left;
6416
6425
  }
6417
6426
  };
6418
6427
  Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
6419
6428
  let lastLine = this._lastLine;
6420
- for (let x = 0; x < byteWidth; x++) {
6421
- let rawByte = rawData[1 + x];
6422
- let f2Up = lastLine ? lastLine[x] : 0;
6423
- unfilteredLine[x] = rawByte + f2Up;
6429
+ for (let x2 = 0; x2 < byteWidth; x2++) {
6430
+ let rawByte = rawData[1 + x2];
6431
+ let f2Up = lastLine ? lastLine[x2] : 0;
6432
+ unfilteredLine[x2] = rawByte + f2Up;
6424
6433
  }
6425
6434
  };
6426
6435
  Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
6427
6436
  let xComparison = this._xComparison;
6428
6437
  let xBiggerThan = xComparison - 1;
6429
6438
  let lastLine = this._lastLine;
6430
- for (let x = 0; x < byteWidth; x++) {
6431
- let rawByte = rawData[1 + x];
6432
- let f3Up = lastLine ? lastLine[x] : 0;
6433
- let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
6439
+ for (let x2 = 0; x2 < byteWidth; x2++) {
6440
+ let rawByte = rawData[1 + x2];
6441
+ let f3Up = lastLine ? lastLine[x2] : 0;
6442
+ let f3Left = x2 > xBiggerThan ? unfilteredLine[x2 - xComparison] : 0;
6434
6443
  let f3Add = Math.floor((f3Left + f3Up) / 2);
6435
- unfilteredLine[x] = rawByte + f3Add;
6444
+ unfilteredLine[x2] = rawByte + f3Add;
6436
6445
  }
6437
6446
  };
6438
6447
  Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
6439
6448
  let xComparison = this._xComparison;
6440
6449
  let xBiggerThan = xComparison - 1;
6441
6450
  let lastLine = this._lastLine;
6442
- for (let x = 0; x < byteWidth; x++) {
6443
- let rawByte = rawData[1 + x];
6444
- let f4Up = lastLine ? lastLine[x] : 0;
6445
- let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
6446
- let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
6451
+ for (let x2 = 0; x2 < byteWidth; x2++) {
6452
+ let rawByte = rawData[1 + x2];
6453
+ let f4Up = lastLine ? lastLine[x2] : 0;
6454
+ let f4Left = x2 > xBiggerThan ? unfilteredLine[x2 - xComparison] : 0;
6455
+ let f4UpLeft = x2 > xBiggerThan && lastLine ? lastLine[x2 - xComparison] : 0;
6447
6456
  let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
6448
- unfilteredLine[x] = rawByte + f4Add;
6457
+ unfilteredLine[x2] = rawByte + f4Add;
6449
6458
  }
6450
6459
  };
6451
6460
  Filter.prototype._reverseFilterLine = function(rawData) {
@@ -6598,7 +6607,7 @@ var require_crc = __commonJS({
6598
6607
  var require_parser = __commonJS({
6599
6608
  "node_modules/pngjs/lib/parser.js"(exports, module) {
6600
6609
  "use strict";
6601
- var constants = require_constants();
6610
+ var constants2 = require_constants();
6602
6611
  var CrcCalculator = require_crc();
6603
6612
  var Parser = module.exports = function(options, dependencies) {
6604
6613
  this._options = options;
@@ -6609,12 +6618,12 @@ var require_parser = __commonJS({
6609
6618
  this._palette = [];
6610
6619
  this._colorType = 0;
6611
6620
  this._chunks = {};
6612
- this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
6613
- this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
6614
- this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
6615
- this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
6616
- this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
6617
- this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
6621
+ this._chunks[constants2.TYPE_IHDR] = this._handleIHDR.bind(this);
6622
+ this._chunks[constants2.TYPE_IEND] = this._handleIEND.bind(this);
6623
+ this._chunks[constants2.TYPE_IDAT] = this._handleIDAT.bind(this);
6624
+ this._chunks[constants2.TYPE_PLTE] = this._handlePLTE.bind(this);
6625
+ this._chunks[constants2.TYPE_tRNS] = this._handleTRNS.bind(this);
6626
+ this._chunks[constants2.TYPE_gAMA] = this._handleGAMA.bind(this);
6618
6627
  this.read = dependencies.read;
6619
6628
  this.error = dependencies.error;
6620
6629
  this.metadata = dependencies.metadata;
@@ -6629,10 +6638,10 @@ var require_parser = __commonJS({
6629
6638
  };
6630
6639
  };
6631
6640
  Parser.prototype.start = function() {
6632
- this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this));
6641
+ this.read(constants2.PNG_SIGNATURE.length, this._parseSignature.bind(this));
6633
6642
  };
6634
6643
  Parser.prototype._parseSignature = function(data) {
6635
- let signature = constants.PNG_SIGNATURE;
6644
+ let signature = constants2.PNG_SIGNATURE;
6636
6645
  for (let i2 = 0; i2 < signature.length; i2++) {
6637
6646
  if (data[i2] !== signature[i2]) {
6638
6647
  this.error(new Error("Invalid file signature"));
@@ -6649,7 +6658,7 @@ var require_parser = __commonJS({
6649
6658
  name += String.fromCharCode(data[i2]);
6650
6659
  }
6651
6660
  let ancillary = Boolean(data[4] & 32);
6652
- if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
6661
+ if (!this._hasIHDR && type !== constants2.TYPE_IHDR) {
6653
6662
  this.error(new Error("Expected IHDR on beggining"));
6654
6663
  return;
6655
6664
  }
@@ -6697,7 +6706,7 @@ var require_parser = __commonJS({
6697
6706
  this.error(new Error("Unsupported bit depth " + depth));
6698
6707
  return;
6699
6708
  }
6700
- if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
6709
+ if (!(colorType in constants2.COLORTYPE_TO_BPP_MAP)) {
6701
6710
  this.error(new Error("Unsupported color type"));
6702
6711
  return;
6703
6712
  }
@@ -6714,16 +6723,16 @@ var require_parser = __commonJS({
6714
6723
  return;
6715
6724
  }
6716
6725
  this._colorType = colorType;
6717
- let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
6726
+ let bpp = constants2.COLORTYPE_TO_BPP_MAP[this._colorType];
6718
6727
  this._hasIHDR = true;
6719
6728
  this.metadata({
6720
6729
  width,
6721
6730
  height,
6722
6731
  depth,
6723
6732
  interlace: Boolean(interlace),
6724
- palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
6725
- color: Boolean(colorType & constants.COLORTYPE_COLOR),
6726
- alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
6733
+ palette: Boolean(colorType & constants2.COLORTYPE_PALETTE),
6734
+ color: Boolean(colorType & constants2.COLORTYPE_COLOR),
6735
+ alpha: Boolean(colorType & constants2.COLORTYPE_ALPHA),
6727
6736
  bpp,
6728
6737
  colorType
6729
6738
  });
@@ -6747,7 +6756,7 @@ var require_parser = __commonJS({
6747
6756
  };
6748
6757
  Parser.prototype._parseTRNS = function(data) {
6749
6758
  this._crc.write(data);
6750
- if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
6759
+ if (this._colorType === constants2.COLORTYPE_PALETTE_COLOR) {
6751
6760
  if (this._palette.length === 0) {
6752
6761
  this.error(new Error("Transparency chunk must be after palette"));
6753
6762
  return;
@@ -6761,10 +6770,10 @@ var require_parser = __commonJS({
6761
6770
  }
6762
6771
  this.palette(this._palette);
6763
6772
  }
6764
- if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
6773
+ if (this._colorType === constants2.COLORTYPE_GRAYSCALE) {
6765
6774
  this.transColor([data.readUInt16BE(0)]);
6766
6775
  }
6767
- if (this._colorType === constants.COLORTYPE_COLOR) {
6776
+ if (this._colorType === constants2.COLORTYPE_COLOR) {
6768
6777
  this.transColor([
6769
6778
  data.readUInt16BE(0),
6770
6779
  data.readUInt16BE(2),
@@ -6778,7 +6787,7 @@ var require_parser = __commonJS({
6778
6787
  };
6779
6788
  Parser.prototype._parseGAMA = function(data) {
6780
6789
  this._crc.write(data);
6781
- this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
6790
+ this.gamma(data.readUInt32BE(0) / constants2.GAMMA_DIVISION);
6782
6791
  this._handleChunkEnd();
6783
6792
  };
6784
6793
  Parser.prototype._handleIDAT = function(length) {
@@ -6790,7 +6799,7 @@ var require_parser = __commonJS({
6790
6799
  };
6791
6800
  Parser.prototype._parseIDAT = function(length, data) {
6792
6801
  this._crc.write(data);
6793
- if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
6802
+ if (this._colorType === constants2.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
6794
6803
  throw new Error("Expected palette not found");
6795
6804
  }
6796
6805
  this.inflateData(data);
@@ -6977,8 +6986,8 @@ var require_bitmapper = __commonJS({
6977
6986
  let imageHeight = image.height;
6978
6987
  let imagePass = image.index;
6979
6988
  for (let y = 0; y < imageHeight; y++) {
6980
- for (let x = 0; x < imageWidth; x++) {
6981
- let pxPos = getPxPos(x, y, imagePass);
6989
+ for (let x2 = 0; x2 < imageWidth; x2++) {
6990
+ let pxPos = getPxPos(x2, y, imagePass);
6982
6991
  pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
6983
6992
  rawPos += bpp;
6984
6993
  }
@@ -6990,9 +6999,9 @@ var require_bitmapper = __commonJS({
6990
6999
  let imageHeight = image.height;
6991
7000
  let imagePass = image.index;
6992
7001
  for (let y = 0; y < imageHeight; y++) {
6993
- for (let x = 0; x < imageWidth; x++) {
7002
+ for (let x2 = 0; x2 < imageWidth; x2++) {
6994
7003
  let pixelData = bits.get(bpp);
6995
- let pxPos = getPxPos(x, y, imagePass);
7004
+ let pxPos = getPxPos(x2, y, imagePass);
6996
7005
  pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
6997
7006
  }
6998
7007
  bits.resetAfterLine();
@@ -7070,7 +7079,7 @@ var require_format_normaliser = __commonJS({
7070
7079
  function dePalette(indata, outdata, width, height, palette) {
7071
7080
  let pxPos = 0;
7072
7081
  for (let y = 0; y < height; y++) {
7073
- for (let x = 0; x < width; x++) {
7082
+ for (let x2 = 0; x2 < width; x2++) {
7074
7083
  let color = palette[indata[pxPos]];
7075
7084
  if (!color) {
7076
7085
  throw new Error("index " + indata[pxPos] + " not in palette");
@@ -7085,7 +7094,7 @@ var require_format_normaliser = __commonJS({
7085
7094
  function replaceTransparentColor(indata, outdata, width, height, transColor) {
7086
7095
  let pxPos = 0;
7087
7096
  for (let y = 0; y < height; y++) {
7088
- for (let x = 0; x < width; x++) {
7097
+ for (let x2 = 0; x2 < width; x2++) {
7089
7098
  let makeTrans = false;
7090
7099
  if (transColor.length === 1) {
7091
7100
  if (transColor[0] === indata[pxPos]) {
@@ -7108,7 +7117,7 @@ var require_format_normaliser = __commonJS({
7108
7117
  let maxInSample = Math.pow(2, depth) - 1;
7109
7118
  let pxPos = 0;
7110
7119
  for (let y = 0; y < height; y++) {
7111
- for (let x = 0; x < width; x++) {
7120
+ for (let x2 = 0; x2 < width; x2++) {
7112
7121
  for (let i2 = 0; i2 < 4; i2++) {
7113
7122
  outdata[pxPos + i2] = Math.floor(
7114
7123
  indata[pxPos + i2] * maxOutSample / maxInSample + 0.5
@@ -7274,9 +7283,9 @@ var require_parser_async = __commonJS({
7274
7283
  var require_bitpacker = __commonJS({
7275
7284
  "node_modules/pngjs/lib/bitpacker.js"(exports, module) {
7276
7285
  "use strict";
7277
- var constants = require_constants();
7286
+ var constants2 = require_constants();
7278
7287
  module.exports = function(dataIn, width, height, options) {
7279
- let outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(
7288
+ let outHasAlpha = [constants2.COLORTYPE_COLOR_ALPHA, constants2.COLORTYPE_ALPHA].indexOf(
7280
7289
  options.colorType
7281
7290
  ) !== -1;
7282
7291
  if (options.colorType === options.inputColorType) {
@@ -7296,11 +7305,11 @@ var require_bitpacker = __commonJS({
7296
7305
  }
7297
7306
  let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
7298
7307
  let maxValue = 255;
7299
- let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
7308
+ let inBpp = constants2.COLORTYPE_TO_BPP_MAP[options.inputColorType];
7300
7309
  if (inBpp === 4 && !options.inputHasAlpha) {
7301
7310
  inBpp = 3;
7302
7311
  }
7303
- let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
7312
+ let outBpp = constants2.COLORTYPE_TO_BPP_MAP[options.colorType];
7304
7313
  if (options.bitDepth === 16) {
7305
7314
  maxValue = 65535;
7306
7315
  outBpp *= 2;
@@ -7324,24 +7333,24 @@ var require_bitpacker = __commonJS({
7324
7333
  let blue;
7325
7334
  let alpha = maxValue;
7326
7335
  switch (options.inputColorType) {
7327
- case constants.COLORTYPE_COLOR_ALPHA:
7336
+ case constants2.COLORTYPE_COLOR_ALPHA:
7328
7337
  alpha = data[inIndex + 3];
7329
7338
  red = data[inIndex];
7330
7339
  green = data[inIndex + 1];
7331
7340
  blue = data[inIndex + 2];
7332
7341
  break;
7333
- case constants.COLORTYPE_COLOR:
7342
+ case constants2.COLORTYPE_COLOR:
7334
7343
  red = data[inIndex];
7335
7344
  green = data[inIndex + 1];
7336
7345
  blue = data[inIndex + 2];
7337
7346
  break;
7338
- case constants.COLORTYPE_ALPHA:
7347
+ case constants2.COLORTYPE_ALPHA:
7339
7348
  alpha = data[inIndex + 1];
7340
7349
  red = data[inIndex];
7341
7350
  green = red;
7342
7351
  blue = red;
7343
7352
  break;
7344
- case constants.COLORTYPE_GRAYSCALE:
7353
+ case constants2.COLORTYPE_GRAYSCALE:
7345
7354
  red = data[inIndex];
7346
7355
  green = red;
7347
7356
  blue = red;
@@ -7371,11 +7380,11 @@ var require_bitpacker = __commonJS({
7371
7380
  return { red, green, blue, alpha };
7372
7381
  }
7373
7382
  for (let y = 0; y < height; y++) {
7374
- for (let x = 0; x < width; x++) {
7383
+ for (let x2 = 0; x2 < width; x2++) {
7375
7384
  let rgba = getRGBA(data, inIndex);
7376
7385
  switch (options.colorType) {
7377
- case constants.COLORTYPE_COLOR_ALPHA:
7378
- case constants.COLORTYPE_COLOR:
7386
+ case constants2.COLORTYPE_COLOR_ALPHA:
7387
+ case constants2.COLORTYPE_COLOR:
7379
7388
  if (options.bitDepth === 8) {
7380
7389
  outData[outIndex] = rgba.red;
7381
7390
  outData[outIndex + 1] = rgba.green;
@@ -7392,8 +7401,8 @@ var require_bitpacker = __commonJS({
7392
7401
  }
7393
7402
  }
7394
7403
  break;
7395
- case constants.COLORTYPE_ALPHA:
7396
- case constants.COLORTYPE_GRAYSCALE: {
7404
+ case constants2.COLORTYPE_ALPHA:
7405
+ case constants2.COLORTYPE_GRAYSCALE: {
7397
7406
  let grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
7398
7407
  if (options.bitDepth === 8) {
7399
7408
  outData[outIndex] = grayscale;
@@ -7426,8 +7435,8 @@ var require_filter_pack = __commonJS({
7426
7435
  "use strict";
7427
7436
  var paethPredictor = require_paeth_predictor();
7428
7437
  function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
7429
- for (let x = 0; x < byteWidth; x++) {
7430
- rawData[rawPos + x] = pxData[pxPos + x];
7438
+ for (let x2 = 0; x2 < byteWidth; x2++) {
7439
+ rawData[rawPos + x2] = pxData[pxPos + x2];
7431
7440
  }
7432
7441
  }
7433
7442
  function filterSumNone(pxData, pxPos, byteWidth) {
@@ -7439,72 +7448,72 @@ var require_filter_pack = __commonJS({
7439
7448
  return sum;
7440
7449
  }
7441
7450
  function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
7442
- for (let x = 0; x < byteWidth; x++) {
7443
- let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
7444
- let val = pxData[pxPos + x] - left;
7445
- rawData[rawPos + x] = val;
7451
+ for (let x2 = 0; x2 < byteWidth; x2++) {
7452
+ let left = x2 >= bpp ? pxData[pxPos + x2 - bpp] : 0;
7453
+ let val = pxData[pxPos + x2] - left;
7454
+ rawData[rawPos + x2] = val;
7446
7455
  }
7447
7456
  }
7448
7457
  function filterSumSub(pxData, pxPos, byteWidth, bpp) {
7449
7458
  let sum = 0;
7450
- for (let x = 0; x < byteWidth; x++) {
7451
- let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
7452
- let val = pxData[pxPos + x] - left;
7459
+ for (let x2 = 0; x2 < byteWidth; x2++) {
7460
+ let left = x2 >= bpp ? pxData[pxPos + x2 - bpp] : 0;
7461
+ let val = pxData[pxPos + x2] - left;
7453
7462
  sum += Math.abs(val);
7454
7463
  }
7455
7464
  return sum;
7456
7465
  }
7457
7466
  function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
7458
- for (let x = 0; x < byteWidth; x++) {
7459
- let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
7460
- let val = pxData[pxPos + x] - up;
7461
- rawData[rawPos + x] = val;
7467
+ for (let x2 = 0; x2 < byteWidth; x2++) {
7468
+ let up = pxPos > 0 ? pxData[pxPos + x2 - byteWidth] : 0;
7469
+ let val = pxData[pxPos + x2] - up;
7470
+ rawData[rawPos + x2] = val;
7462
7471
  }
7463
7472
  }
7464
7473
  function filterSumUp(pxData, pxPos, byteWidth) {
7465
7474
  let sum = 0;
7466
7475
  let length = pxPos + byteWidth;
7467
- for (let x = pxPos; x < length; x++) {
7468
- let up = pxPos > 0 ? pxData[x - byteWidth] : 0;
7469
- let val = pxData[x] - up;
7476
+ for (let x2 = pxPos; x2 < length; x2++) {
7477
+ let up = pxPos > 0 ? pxData[x2 - byteWidth] : 0;
7478
+ let val = pxData[x2] - up;
7470
7479
  sum += Math.abs(val);
7471
7480
  }
7472
7481
  return sum;
7473
7482
  }
7474
7483
  function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
7475
- for (let x = 0; x < byteWidth; x++) {
7476
- let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
7477
- let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
7478
- let val = pxData[pxPos + x] - (left + up >> 1);
7479
- rawData[rawPos + x] = val;
7484
+ for (let x2 = 0; x2 < byteWidth; x2++) {
7485
+ let left = x2 >= bpp ? pxData[pxPos + x2 - bpp] : 0;
7486
+ let up = pxPos > 0 ? pxData[pxPos + x2 - byteWidth] : 0;
7487
+ let val = pxData[pxPos + x2] - (left + up >> 1);
7488
+ rawData[rawPos + x2] = val;
7480
7489
  }
7481
7490
  }
7482
7491
  function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
7483
7492
  let sum = 0;
7484
- for (let x = 0; x < byteWidth; x++) {
7485
- let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
7486
- let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
7487
- let val = pxData[pxPos + x] - (left + up >> 1);
7493
+ for (let x2 = 0; x2 < byteWidth; x2++) {
7494
+ let left = x2 >= bpp ? pxData[pxPos + x2 - bpp] : 0;
7495
+ let up = pxPos > 0 ? pxData[pxPos + x2 - byteWidth] : 0;
7496
+ let val = pxData[pxPos + x2] - (left + up >> 1);
7488
7497
  sum += Math.abs(val);
7489
7498
  }
7490
7499
  return sum;
7491
7500
  }
7492
7501
  function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
7493
- for (let x = 0; x < byteWidth; x++) {
7494
- let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
7495
- let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
7496
- let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
7497
- let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
7498
- rawData[rawPos + x] = val;
7502
+ for (let x2 = 0; x2 < byteWidth; x2++) {
7503
+ let left = x2 >= bpp ? pxData[pxPos + x2 - bpp] : 0;
7504
+ let up = pxPos > 0 ? pxData[pxPos + x2 - byteWidth] : 0;
7505
+ let upleft = pxPos > 0 && x2 >= bpp ? pxData[pxPos + x2 - (byteWidth + bpp)] : 0;
7506
+ let val = pxData[pxPos + x2] - paethPredictor(left, up, upleft);
7507
+ rawData[rawPos + x2] = val;
7499
7508
  }
7500
7509
  }
7501
7510
  function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
7502
7511
  let sum = 0;
7503
- for (let x = 0; x < byteWidth; x++) {
7504
- let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
7505
- let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
7506
- let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
7507
- let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
7512
+ for (let x2 = 0; x2 < byteWidth; x2++) {
7513
+ let left = x2 >= bpp ? pxData[pxPos + x2 - bpp] : 0;
7514
+ let up = pxPos > 0 ? pxData[pxPos + x2 - byteWidth] : 0;
7515
+ let upleft = pxPos > 0 && x2 >= bpp ? pxData[pxPos + x2 - (byteWidth + bpp)] : 0;
7516
+ let val = pxData[pxPos + x2] - paethPredictor(left, up, upleft);
7508
7517
  sum += Math.abs(val);
7509
7518
  }
7510
7519
  return sum;
@@ -7566,7 +7575,7 @@ var require_filter_pack = __commonJS({
7566
7575
  var require_packer = __commonJS({
7567
7576
  "node_modules/pngjs/lib/packer.js"(exports, module) {
7568
7577
  "use strict";
7569
- var constants = require_constants();
7578
+ var constants2 = require_constants();
7570
7579
  var CrcStream = require_crc();
7571
7580
  var bitPacker = require_bitpacker();
7572
7581
  var filter = require_filter_pack();
@@ -7579,23 +7588,23 @@ var require_packer = __commonJS({
7579
7588
  options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
7580
7589
  options.deflateFactory = options.deflateFactory || zlib.createDeflate;
7581
7590
  options.bitDepth = options.bitDepth || 8;
7582
- options.colorType = typeof options.colorType === "number" ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
7583
- options.inputColorType = typeof options.inputColorType === "number" ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
7591
+ options.colorType = typeof options.colorType === "number" ? options.colorType : constants2.COLORTYPE_COLOR_ALPHA;
7592
+ options.inputColorType = typeof options.inputColorType === "number" ? options.inputColorType : constants2.COLORTYPE_COLOR_ALPHA;
7584
7593
  if ([
7585
- constants.COLORTYPE_GRAYSCALE,
7586
- constants.COLORTYPE_COLOR,
7587
- constants.COLORTYPE_COLOR_ALPHA,
7588
- constants.COLORTYPE_ALPHA
7594
+ constants2.COLORTYPE_GRAYSCALE,
7595
+ constants2.COLORTYPE_COLOR,
7596
+ constants2.COLORTYPE_COLOR_ALPHA,
7597
+ constants2.COLORTYPE_ALPHA
7589
7598
  ].indexOf(options.colorType) === -1) {
7590
7599
  throw new Error(
7591
7600
  "option color type:" + options.colorType + " is not supported at present"
7592
7601
  );
7593
7602
  }
7594
7603
  if ([
7595
- constants.COLORTYPE_GRAYSCALE,
7596
- constants.COLORTYPE_COLOR,
7597
- constants.COLORTYPE_COLOR_ALPHA,
7598
- constants.COLORTYPE_ALPHA
7604
+ constants2.COLORTYPE_GRAYSCALE,
7605
+ constants2.COLORTYPE_COLOR,
7606
+ constants2.COLORTYPE_COLOR_ALPHA,
7607
+ constants2.COLORTYPE_ALPHA
7599
7608
  ].indexOf(options.inputColorType) === -1) {
7600
7609
  throw new Error(
7601
7610
  "option input color type:" + options.inputColorType + " is not supported at present"
@@ -7619,7 +7628,7 @@ var require_packer = __commonJS({
7619
7628
  };
7620
7629
  Packer.prototype.filterData = function(data, width, height) {
7621
7630
  let packedData = bitPacker(data, width, height, this._options);
7622
- let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
7631
+ let bpp = constants2.COLORTYPE_TO_BPP_MAP[this._options.colorType];
7623
7632
  let filteredData = filter(packedData, width, height, this._options, bpp);
7624
7633
  return filteredData;
7625
7634
  };
@@ -7639,8 +7648,8 @@ var require_packer = __commonJS({
7639
7648
  };
7640
7649
  Packer.prototype.packGAMA = function(gamma) {
7641
7650
  let buf = Buffer.alloc(4);
7642
- buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
7643
- return this._packChunk(constants.TYPE_gAMA, buf);
7651
+ buf.writeUInt32BE(Math.floor(gamma * constants2.GAMMA_DIVISION), 0);
7652
+ return this._packChunk(constants2.TYPE_gAMA, buf);
7644
7653
  };
7645
7654
  Packer.prototype.packIHDR = function(width, height) {
7646
7655
  let buf = Buffer.alloc(13);
@@ -7651,13 +7660,13 @@ var require_packer = __commonJS({
7651
7660
  buf[10] = 0;
7652
7661
  buf[11] = 0;
7653
7662
  buf[12] = 0;
7654
- return this._packChunk(constants.TYPE_IHDR, buf);
7663
+ return this._packChunk(constants2.TYPE_IHDR, buf);
7655
7664
  };
7656
7665
  Packer.prototype.packIDAT = function(data) {
7657
- return this._packChunk(constants.TYPE_IDAT, data);
7666
+ return this._packChunk(constants2.TYPE_IDAT, data);
7658
7667
  };
7659
7668
  Packer.prototype.packIEND = function() {
7660
- return this._packChunk(constants.TYPE_IEND, null);
7669
+ return this._packChunk(constants2.TYPE_IEND, null);
7661
7670
  };
7662
7671
  }
7663
7672
  });
@@ -7668,7 +7677,7 @@ var require_packer_async = __commonJS({
7668
7677
  "use strict";
7669
7678
  var util = __require("util");
7670
7679
  var Stream = __require("stream");
7671
- var constants = require_constants();
7680
+ var constants2 = require_constants();
7672
7681
  var Packer = require_packer();
7673
7682
  var PackerAsync = module.exports = function(opt) {
7674
7683
  Stream.call(this);
@@ -7679,7 +7688,7 @@ var require_packer_async = __commonJS({
7679
7688
  };
7680
7689
  util.inherits(PackerAsync, Stream);
7681
7690
  PackerAsync.prototype.pack = function(data, width, height, gamma) {
7682
- this.emit("data", Buffer.from(constants.PNG_SIGNATURE));
7691
+ this.emit("data", Buffer.from(constants2.PNG_SIGNATURE));
7683
7692
  this.emit("data", this._packer.packIHDR(width, height));
7684
7693
  if (gamma) {
7685
7694
  this.emit("data", this._packer.packGAMA(gamma));
@@ -8003,7 +8012,7 @@ var require_packer_sync = __commonJS({
8003
8012
  if (!zlib.deflateSync) {
8004
8013
  hasSyncZlib = false;
8005
8014
  }
8006
- var constants = require_constants();
8015
+ var constants2 = require_constants();
8007
8016
  var Packer = require_packer();
8008
8017
  module.exports = function(metaData, opt) {
8009
8018
  if (!hasSyncZlib) {
@@ -8014,7 +8023,7 @@ var require_packer_sync = __commonJS({
8014
8023
  let options = opt || {};
8015
8024
  let packer = new Packer(options);
8016
8025
  let chunks = [];
8017
- chunks.push(Buffer.from(constants.PNG_SIGNATURE));
8026
+ chunks.push(Buffer.from(constants2.PNG_SIGNATURE));
8018
8027
  chunks.push(packer.packIHDR(metaData.width, metaData.height));
8019
8028
  if (metaData.gamma) {
8020
8029
  chunks.push(packer.packGAMA(metaData.gamma));
@@ -8173,8 +8182,8 @@ var require_png = __commonJS({
8173
8182
  PNG.adjustGamma = function(src) {
8174
8183
  if (src.gamma) {
8175
8184
  for (let y = 0; y < src.height; y++) {
8176
- for (let x = 0; x < src.width; x++) {
8177
- let idx = src.width * y + x << 2;
8185
+ for (let x2 = 0; x2 < src.width; x2++) {
8186
+ let idx = src.width * y + x2 << 2;
8178
8187
  for (let i2 = 0; i2 < 3; i2++) {
8179
8188
  let sample = src.data[idx + i2] / 255;
8180
8189
  sample = Math.pow(sample, 1 / 2.2 / src.gamma);
@@ -8457,15 +8466,15 @@ var require_terminal_small = __commonJS({
8457
8466
  22: "\u2588"
8458
8467
  };
8459
8468
  };
8460
- var mkCodePixel = function(modules, size, x, y) {
8469
+ var mkCodePixel = function(modules, size, x2, y) {
8461
8470
  const sizePlus = size + 1;
8462
- if (x >= sizePlus || y >= sizePlus || y < -1 || x < -1) return "0";
8463
- if (x >= size || y >= size || y < 0 || x < 0) return "1";
8464
- const idx = y * size + x;
8471
+ if (x2 >= sizePlus || y >= sizePlus || y < -1 || x2 < -1) return "0";
8472
+ if (x2 >= size || y >= size || y < 0 || x2 < 0) return "1";
8473
+ const idx = y * size + x2;
8465
8474
  return modules[idx] ? "2" : "1";
8466
8475
  };
8467
- var mkCode = function(modules, size, x, y) {
8468
- return mkCodePixel(modules, size, x, y) + mkCodePixel(modules, size, x, y + 1);
8476
+ var mkCode = function(modules, size, x2, y) {
8477
+ return mkCodePixel(modules, size, x2, y) + mkCodePixel(modules, size, x2, y + 1);
8469
8478
  };
8470
8479
  exports.render = function(qrData, options, cb) {
8471
8480
  const size = qrData.modules.size;
@@ -8478,8 +8487,8 @@ var require_terminal_small = __commonJS({
8478
8487
  const newLine = reset + "\n" + lineSetup;
8479
8488
  let output = lineSetup;
8480
8489
  for (let y = -1; y < size + 1; y += 2) {
8481
- for (let x = -1; x < size; x++) {
8482
- output += palette[mkCode(data, size, x, y)];
8490
+ for (let x2 = -1; x2 < size; x2++) {
8491
+ output += palette[mkCode(data, size, x2, y)];
8483
8492
  }
8484
8493
  output += palette[mkCode(data, size, size, y)] + newLine;
8485
8494
  }
@@ -8517,8 +8526,8 @@ var require_svg_tag = __commonJS({
8517
8526
  const str = attrib + '="' + color.hex + '"';
8518
8527
  return alpha < 1 ? str + " " + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"' : str;
8519
8528
  }
8520
- function svgCmd(cmd, x, y) {
8521
- let str = cmd + x;
8529
+ function svgCmd(cmd, x2, y) {
8530
+ let str = cmd + x2;
8522
8531
  if (typeof y !== "undefined") str += " " + y;
8523
8532
  return str;
8524
8533
  }
@@ -8841,7 +8850,7 @@ var require_lib = __commonJS({
8841
8850
 
8842
8851
  // src/cli/dvm.ts
8843
8852
  import { realpathSync as realpathSync2 } from "fs";
8844
- import { fileURLToPath as fileURLToPath3 } from "url";
8853
+ import { fileURLToPath as fileURLToPath4 } from "url";
8845
8854
 
8846
8855
  // node_modules/commander/esm.mjs
8847
8856
  var import_index = __toESM(require_commander(), 1);
@@ -8923,6 +8932,11 @@ function renderDiscoveryDisplay(row, indent) {
8923
8932
  }
8924
8933
  }
8925
8934
 
8935
+ // src/lib/job-read-error.ts
8936
+ function isTransientJobReadError(error) {
8937
+ return isAbortError(error) || error instanceof DvmError && ["timeout", "provider_unreachable"].includes(error.code);
8938
+ }
8939
+
8926
8940
  // src/lib/payment-lock.ts
8927
8941
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
8928
8942
  import { createHash } from "crypto";
@@ -9012,19 +9026,180 @@ function formatPaidAmount(result, fiat) {
9012
9026
  return formatPaymentAmount(result.amountMsats, fiat, { anchor: false });
9013
9027
  }
9014
9028
 
9029
+ // src/lib/request-intent-store.ts
9030
+ var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
9031
+ import {
9032
+ closeSync,
9033
+ existsSync,
9034
+ fsyncSync,
9035
+ mkdirSync,
9036
+ openSync,
9037
+ readFileSync,
9038
+ renameSync,
9039
+ writeFileSync
9040
+ } from "fs";
9041
+ import { join } from "path";
9042
+ function saveRequestIntent(intent) {
9043
+ assertRequestId(intent.requestId);
9044
+ assertNoPaymentOrAuthSecrets(intent.body);
9045
+ ensureConfigSubdir(REQUEST_INTENTS_DIR);
9046
+ const dir = intentDirectory(intent.requestId);
9047
+ try {
9048
+ mkdirSync(dir, { mode: 448 });
9049
+ } catch (error) {
9050
+ if (error.code === "EEXIST") return false;
9051
+ throw error;
9052
+ }
9053
+ fsyncDirectory(REQUEST_INTENTS_DIR);
9054
+ const temp = join(dir, `intent.${String(process.pid)}.tmp`);
9055
+ const target = join(dir, "intent.json");
9056
+ const fd = openSync(temp, "wx", 384);
9057
+ try {
9058
+ writeFileSync(fd, JSON.stringify(intent, null, 2) + "\n");
9059
+ fsyncSync(fd);
9060
+ } finally {
9061
+ closeSync(fd);
9062
+ }
9063
+ renameSync(temp, target);
9064
+ fsyncDirectory(dir);
9065
+ return true;
9066
+ }
9067
+ function loadRequestIntent(requestId) {
9068
+ assertRequestId(requestId);
9069
+ const dir = intentDirectory(requestId);
9070
+ if (!existsSync(dir)) return null;
9071
+ const path = join(dir, "intent.json");
9072
+ try {
9073
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
9074
+ if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
9075
+ throw new Error("invalid shape");
9076
+ return parsed;
9077
+ } catch (error) {
9078
+ throw new DvmError(
9079
+ "request_intent_unreadable",
9080
+ `The saved request intent for ${requestId} is incomplete or unreadable.`,
9081
+ "Do not submit a replacement request. The provider may already have accepted and charged the original; restore this intent from backup before using request-result.",
9082
+ { request_id: requestId, cause: error instanceof Error ? error.message : String(error) }
9083
+ );
9084
+ }
9085
+ }
9086
+ function recordRequestRailPayment(requestId, payment) {
9087
+ assertRequestId(requestId);
9088
+ if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
9089
+ const dir = intentDirectory(requestId);
9090
+ const target = join(dir, "intent.json");
9091
+ const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
9092
+ try {
9093
+ const intent = loadRequestIntent(requestId);
9094
+ if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
9095
+ if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
9096
+ throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
9097
+ const temp = join(dir, `rail.${String(process.pid)}.tmp`);
9098
+ const fd = openSync(temp, "w", 384);
9099
+ try {
9100
+ writeFileSync(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
9101
+ fsyncSync(fd);
9102
+ } finally {
9103
+ closeSync(fd);
9104
+ }
9105
+ renameSync(temp, target);
9106
+ fsyncDirectory(dir);
9107
+ } finally {
9108
+ release();
9109
+ }
9110
+ }
9111
+ function assertNoPaymentOrAuthSecrets(body) {
9112
+ if (!containsForbiddenSecret(body)) return;
9113
+ throw new DvmError(
9114
+ "request_intent_contains_secret",
9115
+ "Request recovery cannot persist a payment credential, bearer token, or request auth signature.",
9116
+ "No payment was attempted. Remove the secret-bearing input or omit --request-id."
9117
+ );
9118
+ }
9119
+ function containsForbiddenSecret(value) {
9120
+ if (typeof value === "string") return /^Bearer\s/i.test(value);
9121
+ if (!value || typeof value !== "object") return false;
9122
+ if (Array.isArray(value)) return value.some(containsForbiddenSecret);
9123
+ const record2 = value;
9124
+ if (["pubkey", "timestamp", "nonce", "signature"].every((key) => Object.hasOwn(record2, key))) {
9125
+ return true;
9126
+ }
9127
+ const forbidden = /* @__PURE__ */ new Set([
9128
+ "authorization",
9129
+ "bearer_token",
9130
+ "access_token",
9131
+ "cashu_token",
9132
+ "x402_payment",
9133
+ "tempo_credential"
9134
+ ]);
9135
+ return Object.entries(record2).some(
9136
+ ([key, child]) => forbidden.has(key.toLowerCase()) || containsForbiddenSecret(child)
9137
+ );
9138
+ }
9139
+ function assertRequestId(requestId) {
9140
+ if (isPublicRequestId(requestId)) return;
9141
+ throw new DvmError(
9142
+ "invalid_request_id",
9143
+ "Invalid request id.",
9144
+ "Use 1\u2013128 characters: letters, digits, dot, underscore, colon, or hyphen."
9145
+ );
9146
+ }
9147
+ function intentDirectory(requestId) {
9148
+ return join(REQUEST_INTENTS_DIR, requestId);
9149
+ }
9150
+ function fsyncDirectory(path) {
9151
+ if (process.platform === "win32") return;
9152
+ let fd;
9153
+ try {
9154
+ fd = openSync(path, "r");
9155
+ fsyncSync(fd);
9156
+ } finally {
9157
+ if (fd !== void 0) closeSync(fd);
9158
+ }
9159
+ }
9160
+ function isRequestIntent(value) {
9161
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
9162
+ const candidate = value;
9163
+ return candidate.v === 2 && isPublicRequestId(candidate.requestId) && typeof candidate.endpoint === "string" && typeof candidate.capability === "string" && typeof candidate.callerPubkey === "string" && isSignedRequestAudience(candidate.authAudience) && typeof candidate.createdAt === "number" && typeof candidate.body === "object" && candidate.body !== null && !Array.isArray(candidate.body) && typeof candidate.policy === "object" && candidate.policy !== null;
9164
+ }
9165
+ function isSignedRequestAudience(value) {
9166
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
9167
+ const candidate = value;
9168
+ return typeof candidate.dvm_id === "string" && typeof candidate.builder_pubkey === "string";
9169
+ }
9170
+
9171
+ // src/lib/upfront-credit-error.ts
9172
+ function unknownUpfrontCreditError(job, message2) {
9173
+ const reason = job.upfrontCreditConflictReason;
9174
+ const requestId = job.requestId;
9175
+ let recovery;
9176
+ if (requestId && loadRequestIntent(requestId))
9177
+ recovery = `Run \`dvm request-result ${shellQuoteArg(requestId)}\` to recover the accepted upfront amount; it reads only and sends no payment.`;
9178
+ else if (requestId)
9179
+ recovery = `Request ${requestId} has no stored intent on this machine, so \`dvm request-result\` cannot recover it. Restore the caller state that submitted it.`;
9180
+ else
9181
+ recovery = "This job has no stored request id, so `dvm request-result` cannot recover it. Restore the caller state that submitted it.";
9182
+ return new DvmError(
9183
+ "upfront_credit_unknown",
9184
+ `${message2}${reason ? ` Cause: ${reason}.` : ""}`,
9185
+ `${recovery} Do not edit the local job store.`,
9186
+ { ...reason ? { reason } : {}, ...requestId ? { request_id: requestId } : {} }
9187
+ );
9188
+ }
9189
+
9015
9190
  // src/lib/credit-payment.ts
9016
9191
  import { randomUUID } from "crypto";
9017
9192
 
9018
9193
  // src/lib/caller-version.ts
9019
- import { existsSync, readFileSync } from "fs";
9020
- import { dirname, join } from "path";
9194
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
9195
+ import { dirname, join as join2 } from "path";
9021
9196
  import { fileURLToPath } from "url";
9022
9197
  var CALLER_VERSION = readCallerVersion();
9023
9198
  function readCallerVersion() {
9024
9199
  let dir = dirname(fileURLToPath(import.meta.url));
9025
9200
  for (; ; ) {
9026
- const manifestPath = join(dir, "package.json");
9027
- if (existsSync(manifestPath)) {
9201
+ const manifestPath = join2(dir, "package.json");
9202
+ if (existsSync2(manifestPath)) {
9028
9203
  const manifest = readManifest(manifestPath);
9029
9204
  if (manifest.name === "@dvmkit/dvm-cli") return manifest.version;
9030
9205
  }
@@ -9036,7 +9211,7 @@ function readCallerVersion() {
9036
9211
  }
9037
9212
  }
9038
9213
  function readManifest(path) {
9039
- return JSON.parse(readFileSync(path, "utf8"));
9214
+ return JSON.parse(readFileSync2(path, "utf8"));
9040
9215
  }
9041
9216
 
9042
9217
  // src/lib/client-compatibility.ts
@@ -9213,9 +9388,9 @@ async function readBoundedBody(response, limit) {
9213
9388
  var MAX_COMPATIBILITY_BODY_BYTES = 16384;
9214
9389
 
9215
9390
  // src/lib/credit-suggestion-cooldown.ts
9216
- import { existsSync as existsSync2, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync } from "fs";
9217
- import { join as join2 } from "path";
9218
- var CREDIT_SUGGESTIONS_FILE = join2(CONFIG_DIR, "credit-suggestions.json");
9391
+ import { existsSync as existsSync3, readFileSync as readFileSync3, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
9392
+ import { join as join3 } from "path";
9393
+ var CREDIT_SUGGESTIONS_FILE = join3(CONFIG_DIR, "credit-suggestions.json");
9219
9394
  var CREDIT_SUGGESTION_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1e3;
9220
9395
  function creditSuggestionDue(endpoint, now = Date.now()) {
9221
9396
  const shownAt = loadState()[normalizeCreditEndpoint(endpoint)];
@@ -9232,9 +9407,9 @@ function recordCreditSuggestionShown(endpoint, now = Date.now()) {
9232
9407
  }
9233
9408
  }
9234
9409
  function loadState() {
9235
- if (!existsSync2(CREDIT_SUGGESTIONS_FILE)) return {};
9410
+ if (!existsSync3(CREDIT_SUGGESTIONS_FILE)) return {};
9236
9411
  try {
9237
- const parsed = JSON.parse(readFileSync2(CREDIT_SUGGESTIONS_FILE, "utf-8"));
9412
+ const parsed = JSON.parse(readFileSync3(CREDIT_SUGGESTIONS_FILE, "utf-8"));
9238
9413
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
9239
9414
  return Object.fromEntries(
9240
9415
  Object.entries(parsed).filter((entry) => typeof entry[1] === "string")
@@ -9246,9 +9421,9 @@ function loadState() {
9246
9421
  function saveState(state) {
9247
9422
  ensureConfigDir();
9248
9423
  const tmp = `${CREDIT_SUGGESTIONS_FILE}.${process.pid}.tmp`;
9249
- writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
9424
+ writeFileSync2(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
9250
9425
  try {
9251
- renameSync(tmp, CREDIT_SUGGESTIONS_FILE);
9426
+ renameSync2(tmp, CREDIT_SUGGESTIONS_FILE);
9252
9427
  } catch (err) {
9253
9428
  try {
9254
9429
  unlinkSync(tmp);
@@ -9259,6 +9434,29 @@ function saveState(state) {
9259
9434
  }
9260
9435
 
9261
9436
  // src/lib/credit-notice.ts
9437
+ function refusedFundingReport(endpoint, outcome) {
9438
+ return {
9439
+ endpoint,
9440
+ status: outcome.status,
9441
+ credit_id: outcome.creditId,
9442
+ fund_id: outcome.fundId,
9443
+ rail: outcome.rail,
9444
+ ...outcome.spentSats !== void 0 ? { spent_sats: outcome.spentSats } : {},
9445
+ ...outcome.principalSats !== void 0 ? { principal_sats: outcome.principalSats } : {},
9446
+ ...outcome.routingFeeSats !== void 0 ? { routing_fee_sats: outcome.routingFeeSats } : {},
9447
+ ...outcome.totalWalletFeeSats !== void 0 ? { total_wallet_fee_sats: outcome.totalWalletFeeSats } : {},
9448
+ ...outcome.unitemizedWalletFeeSats !== void 0 ? { unitemized_wallet_fee_sats: outcome.unitemizedWalletFeeSats } : {},
9449
+ ...outcome.walletDebitSats !== void 0 ? { wallet_debit_sats: outcome.walletDebitSats } : {},
9450
+ ...outcome.paymentOutcome ? { payment_outcome: outcome.paymentOutcome } : {},
9451
+ ...outcome.error ? { error_code: outcome.error.code } : {},
9452
+ display: outcome.display,
9453
+ hint: outcome.hint
9454
+ };
9455
+ }
9456
+ function noteRefusedCreditFunding(endpoint, outcome, human) {
9457
+ if (human) info([outcome.display, outcome.hint].filter(Boolean).join(" "));
9458
+ else (pending.refused_fundings ??= []).push(refusedFundingReport(endpoint, outcome));
9459
+ }
9262
9460
  function buildCreditFundingSkipped(args) {
9263
9461
  return {
9264
9462
  code: "credit_funding_skipped",
@@ -9898,7 +10096,7 @@ async function tryCreditPayment(args) {
9898
10096
  throw new DvmError("upfront_rail_unknown", "Recover the original upfront rail charge before another balance payment.");
9899
10097
  const ask = request2.credit;
9900
10098
  if (job && hasUnknownUpfrontCredit(job))
9901
- throw new DvmError("upfront_credit_unknown", "The original upfront credit debit must be recovered before another balance payment.");
10099
+ throw unknownUpfrontCreditError(job, "The original upfront credit debit must be recovered before another balance payment.");
9902
10100
  if (!job?.creditBinding || !ask || !Number.isSafeInteger(requestSeq) || requestSeq < 0 || !Number.isSafeInteger(ask.amount_micro) || ask.amount_micro <= 0 || !/^[a-z]{3}$/.test(ask.currency)) return false;
9903
10101
  const signer = findSigningIdentityByPubkey(job.creditBinding.callerPubkey);
9904
10102
  if (!signer) return false;
@@ -11404,148 +11602,6 @@ function parseTempoNetwork(value, source) {
11404
11602
  );
11405
11603
  }
11406
11604
 
11407
- // src/lib/request-intent-store.ts
11408
- var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
11409
- import {
11410
- closeSync,
11411
- existsSync as existsSync3,
11412
- fsyncSync,
11413
- mkdirSync,
11414
- openSync,
11415
- readFileSync as readFileSync3,
11416
- renameSync as renameSync2,
11417
- writeFileSync as writeFileSync2
11418
- } from "fs";
11419
- import { join as join3 } from "path";
11420
- function saveRequestIntent(intent) {
11421
- assertRequestId(intent.requestId);
11422
- assertNoPaymentOrAuthSecrets(intent.body);
11423
- ensureConfigSubdir(REQUEST_INTENTS_DIR);
11424
- const dir = intentDirectory(intent.requestId);
11425
- try {
11426
- mkdirSync(dir, { mode: 448 });
11427
- } catch (error) {
11428
- if (error.code === "EEXIST") return false;
11429
- throw error;
11430
- }
11431
- fsyncDirectory(REQUEST_INTENTS_DIR);
11432
- const temp = join3(dir, `intent.${String(process.pid)}.tmp`);
11433
- const target = join3(dir, "intent.json");
11434
- const fd = openSync(temp, "wx", 384);
11435
- try {
11436
- writeFileSync2(fd, JSON.stringify(intent, null, 2) + "\n");
11437
- fsyncSync(fd);
11438
- } finally {
11439
- closeSync(fd);
11440
- }
11441
- renameSync2(temp, target);
11442
- fsyncDirectory(dir);
11443
- return true;
11444
- }
11445
- function loadRequestIntent(requestId) {
11446
- assertRequestId(requestId);
11447
- const dir = intentDirectory(requestId);
11448
- if (!existsSync3(dir)) return null;
11449
- const path = join3(dir, "intent.json");
11450
- try {
11451
- const parsed = JSON.parse(readFileSync3(path, "utf8"));
11452
- if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
11453
- throw new Error("invalid shape");
11454
- return parsed;
11455
- } catch (error) {
11456
- throw new DvmError(
11457
- "request_intent_unreadable",
11458
- `The saved request intent for ${requestId} is incomplete or unreadable.`,
11459
- "Do not submit a replacement request. The provider may already have accepted and charged the original; restore this intent from backup before using request-result.",
11460
- { request_id: requestId, cause: error instanceof Error ? error.message : String(error) }
11461
- );
11462
- }
11463
- }
11464
- function recordRequestRailPayment(requestId, payment) {
11465
- assertRequestId(requestId);
11466
- if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
11467
- const dir = intentDirectory(requestId);
11468
- const target = join3(dir, "intent.json");
11469
- const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
11470
- try {
11471
- const intent = loadRequestIntent(requestId);
11472
- if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
11473
- if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
11474
- throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
11475
- const temp = join3(dir, `rail.${String(process.pid)}.tmp`);
11476
- const fd = openSync(temp, "w", 384);
11477
- try {
11478
- writeFileSync2(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
11479
- fsyncSync(fd);
11480
- } finally {
11481
- closeSync(fd);
11482
- }
11483
- renameSync2(temp, target);
11484
- fsyncDirectory(dir);
11485
- } finally {
11486
- release();
11487
- }
11488
- }
11489
- function assertNoPaymentOrAuthSecrets(body) {
11490
- if (!containsForbiddenSecret(body)) return;
11491
- throw new DvmError(
11492
- "request_intent_contains_secret",
11493
- "Request recovery cannot persist a payment credential, bearer token, or request auth signature.",
11494
- "No payment was attempted. Remove the secret-bearing input or omit --request-id."
11495
- );
11496
- }
11497
- function containsForbiddenSecret(value) {
11498
- if (typeof value === "string") return /^Bearer\s/i.test(value);
11499
- if (!value || typeof value !== "object") return false;
11500
- if (Array.isArray(value)) return value.some(containsForbiddenSecret);
11501
- const record2 = value;
11502
- if (["pubkey", "timestamp", "nonce", "signature"].every((key) => Object.hasOwn(record2, key))) {
11503
- return true;
11504
- }
11505
- const forbidden = /* @__PURE__ */ new Set([
11506
- "authorization",
11507
- "bearer_token",
11508
- "access_token",
11509
- "cashu_token",
11510
- "x402_payment",
11511
- "tempo_credential"
11512
- ]);
11513
- return Object.entries(record2).some(
11514
- ([key, child]) => forbidden.has(key.toLowerCase()) || containsForbiddenSecret(child)
11515
- );
11516
- }
11517
- function assertRequestId(requestId) {
11518
- if (isPublicRequestId(requestId)) return;
11519
- throw new DvmError(
11520
- "invalid_request_id",
11521
- "Invalid request id.",
11522
- "Use 1\u2013128 characters: letters, digits, dot, underscore, colon, or hyphen."
11523
- );
11524
- }
11525
- function intentDirectory(requestId) {
11526
- return join3(REQUEST_INTENTS_DIR, requestId);
11527
- }
11528
- function fsyncDirectory(path) {
11529
- if (process.platform === "win32") return;
11530
- let fd;
11531
- try {
11532
- fd = openSync(path, "r");
11533
- fsyncSync(fd);
11534
- } finally {
11535
- if (fd !== void 0) closeSync(fd);
11536
- }
11537
- }
11538
- function isRequestIntent(value) {
11539
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
11540
- const candidate = value;
11541
- return candidate.v === 2 && isPublicRequestId(candidate.requestId) && typeof candidate.endpoint === "string" && typeof candidate.capability === "string" && typeof candidate.callerPubkey === "string" && isSignedRequestAudience(candidate.authAudience) && typeof candidate.createdAt === "number" && typeof candidate.body === "object" && candidate.body !== null && !Array.isArray(candidate.body) && typeof candidate.policy === "object" && candidate.policy !== null;
11542
- }
11543
- function isSignedRequestAudience(value) {
11544
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
11545
- const candidate = value;
11546
- return typeof candidate.dvm_id === "string" && typeof candidate.builder_pubkey === "string";
11547
- }
11548
-
11549
11605
  // src/lib/payment-responder.ts
11550
11606
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11551
11607
  const seq = opts?.requestSeq;
@@ -11715,11 +11771,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11715
11771
  "Recover the original job price before authorizing more payments."
11716
11772
  );
11717
11773
  if (job && hasUnknownUpfrontCredit(job))
11718
- throw new DvmError(
11719
- "upfront_credit_unknown",
11720
- "The original upfront credit debit is unknown or conflicting.",
11721
- "Recover the accepted upfront amount with 'dvm request-result' before authorizing more payments."
11722
- );
11774
+ throw unknownUpfrontCreditError(job, "The original upfront credit debit is unknown or conflicting.");
11723
11775
  const pinnedMint = job?.pinnedMint;
11724
11776
  const strictPerCall = job?.strictPerCall === true;
11725
11777
  const maxCashuFeeSats = job?.maxCashuFeeSats;
@@ -11885,8 +11937,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11885
11937
  }
11886
11938
  }
11887
11939
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11888
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
11889
- const { tryX402Payment: tryX402Payment2 } = await import("./client-PY4T2DOA.js");
11940
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-J7JCMFZ2.js");
11941
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-FKYQXFBN.js");
11890
11942
  const wallet = loadX402Wallet2();
11891
11943
  if (wallet) {
11892
11944
  let proof;
@@ -12029,6 +12081,7 @@ async function redeliverUnconfirmedPayment(args) {
12029
12081
  requestId: held.request_id,
12030
12082
  mint: held.mint,
12031
12083
  totalSats: held.amount_sats,
12084
+ swapFeeSats: submissionSwapFeeSats(held),
12032
12085
  endpoint: held.endpoint,
12033
12086
  intendedLockPubkey: held.intended_lock_pubkey
12034
12087
  }
@@ -12181,10 +12234,12 @@ async function deliverAgentWalletPayment(args) {
12181
12234
  dvm_endpoint: provider.endpoint,
12182
12235
  mint: prepared.mint,
12183
12236
  amount_sats: prepared.totalSats,
12237
+ ...prepared.swapFeeSats > 0 ? { fee_sats: prepared.swapFeeSats } : {},
12184
12238
  signed_at_ms: Date.now()
12185
12239
  }
12186
12240
  });
12187
12241
  addPayment(jobId, request2.amount_msats, approval, submission.usdMicro);
12242
+ addCashuSwapFee(jobId, prepared.swapFeeSats);
12188
12243
  recordSpend({
12189
12244
  msats: request2.amount_msats,
12190
12245
  btcRate: submission.btcRate,
@@ -12397,7 +12452,7 @@ function refundNextAction(jobId, claims) {
12397
12452
  reason: claim.reason,
12398
12453
  claimed: false,
12399
12454
  cashu_token: claim.cashu_token,
12400
- hint: `The provider sent a ${noun} but the auto-claim into your wallet failed (the mint may be unreachable). Claim it manually with 'dvm wallet receive-token <cashu_token>' \u2014 the token is in this action's 'cashu_token' field, don't lose it. Or retry the auto-claim with 'dvm messages ${guidanceJobArg(jobId)} --no-stream' (re-running plain 'dvm messages' won't retry \u2014 its cursor has already advanced past this message).`
12455
+ hint: `The provider sent a ${noun} but the auto-claim into your wallet failed (the mint may be unreachable). Pipe this action's 'cashu_token' field into 'dvm wallet receive-token' via stdin; do not put the token in command arguments. Or retry the auto-claim with 'dvm messages ${guidanceJobArg(jobId)} --no-stream' (re-running plain 'dvm messages' won't retry \u2014 its cursor has already advanced past this message).`
12401
12456
  }, ["amount_msats", "reason", "cashu_token"]);
12402
12457
  }
12403
12458
  return providerFields({
@@ -12431,7 +12486,7 @@ function refundSummaryHuman(claim) {
12431
12486
  if (claim.claimed) {
12432
12487
  return `Claimed ${noun} of ${formatAmountBestEffort(claim.amount_msats)} into your wallet.`;
12433
12488
  }
12434
- return `${cap(noun)} of ${formatAmountBestEffort(claim.amount_msats)} could not be auto-claimed (the mint may be down). Recover with: dvm wallet receive-token ${claim.cashu_token}`;
12489
+ return `${cap(noun)} of ${formatAmountBestEffort(claim.amount_msats)} could not be auto-claimed (the mint may be down). Pipe the cashu_token field from JSON messages output into dvm wallet receive-token via stdin; do not put the token in command arguments. Use dvm messages <job-id> --no-stream to retry the auto-claim or recover the token.`;
12435
12490
  }
12436
12491
  function cap(s) {
12437
12492
  return s.charAt(0).toUpperCase() + s.slice(1);
@@ -12444,6 +12499,7 @@ function withRefundNextAction(jobId, action, claims) {
12444
12499
  // src/lib/stream-loop.ts
12445
12500
  async function streamLoop(opts) {
12446
12501
  const { jobId, transport, provider } = opts;
12502
+ const recoverableRead = (error) => opts.retryUnreachableReads ? isTransientJobReadError(error) : isMessagePollTimeout(error);
12447
12503
  if (hasUnsavedJobState()) return {
12448
12504
  messages: [],
12449
12505
  autoPayments: [],
@@ -12539,7 +12595,7 @@ async function streamLoop(opts) {
12539
12595
  try {
12540
12596
  result = await streamFn(jobId, cursor, provider, streamOpts);
12541
12597
  } catch (err) {
12542
- if (isAbortError(err) || deadline !== void 0 && isMessagePollTimeout(err)) break;
12598
+ if (isAbortError(err) || deadline !== void 0 && recoverableRead(err)) break;
12543
12599
  throw err;
12544
12600
  }
12545
12601
  batchMessages = result.messages.filter((message2) => message2.seq > cursor);
@@ -12549,7 +12605,7 @@ async function streamLoop(opts) {
12549
12605
  try {
12550
12606
  batchMessages = (await transport.getMessages(jobId, cursor, provider, pollOptions)).filter((message2) => message2.seq > cursor);
12551
12607
  } catch (err) {
12552
- if (deadline !== void 0 && isMessagePollTimeout(err)) break;
12608
+ if (deadline !== void 0 && recoverableRead(err)) break;
12553
12609
  throw err;
12554
12610
  }
12555
12611
  for (const msg of batchMessages) {
@@ -12588,7 +12644,7 @@ async function streamLoop(opts) {
12588
12644
  break;
12589
12645
  }
12590
12646
  } catch (error) {
12591
- if (!isMessagePollTimeout(error) && !(error instanceof DvmError && ["payment_settling", "payment_request_not_pending"].includes(error.code))) throw error;
12647
+ if (!recoverableRead(error) && !(error instanceof DvmError && ["payment_settling", "payment_request_not_pending"].includes(error.code))) throw error;
12592
12648
  paymentUnresolved = true;
12593
12649
  }
12594
12650
  if (paymentUnresolved) {
@@ -12654,7 +12710,7 @@ async function streamLoop(opts) {
12654
12710
  recheck = (await transport.getMessages(jobId, cursor, provider, pollOptions)).filter((message2) => message2.seq > cursor);
12655
12711
  }
12656
12712
  } catch (err) {
12657
- if (deadline === void 0 || !isMessagePollTimeout(err)) throw err;
12713
+ if (deadline === void 0 || !recoverableRead(err)) throw err;
12658
12714
  }
12659
12715
  if (recheck.length > 0) {
12660
12716
  for (const msg of recheck) opts.onMessage?.(msg);
@@ -13004,18 +13060,18 @@ function paramsToData(params) {
13004
13060
  function jobTokenHeader(jobToken) {
13005
13061
  return jobToken ? { "X-Job-Token": jobToken } : {};
13006
13062
  }
13007
- function messagePollUnreachable(jobId) {
13063
+ function messagePollUnreachable(jobId, operation = "fetch messages") {
13008
13064
  return new DvmError(
13009
13065
  "provider_unreachable",
13010
- `Could not reach the provider to fetch messages for job ${jobId}.`,
13011
- "The provider may be down or unreachable from this network. Retry once it is back."
13066
+ `Could not reach the provider to ${operation} for job ${jobId}.`,
13067
+ `The provider may be down or unreachable from this network. Continue watching this job with \`dvm messages ${shellQuoteArg(jobId)} --wait\` once it is back.`
13012
13068
  );
13013
13069
  }
13014
- async function readMessagePollBody(read, jobId) {
13070
+ async function readMessagePollBody(read, jobId, operation) {
13015
13071
  try {
13016
13072
  return await read();
13017
13073
  } catch (err) {
13018
- if (err instanceof TypeError && !isAbortError(err)) throw messagePollUnreachable(jobId);
13074
+ if (err instanceof TypeError && !isAbortError(err)) throw messagePollUnreachable(jobId, operation);
13019
13075
  throw err;
13020
13076
  }
13021
13077
  }
@@ -13270,7 +13326,7 @@ var HttpsTransport = class {
13270
13326
  ...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {},
13271
13327
  ...feedbackClaim ? { feedbackClaim } : {},
13272
13328
  ...parseFundingResponse(data),
13273
- upfrontPayment: parseUpfrontPayment(data.upfront_payment)
13329
+ ...upfrontReceiptFields(data.upfront_payment)
13274
13330
  };
13275
13331
  }
13276
13332
  return {
@@ -13286,7 +13342,7 @@ var HttpsTransport = class {
13286
13342
  ...feedbackClaim ? { feedbackClaim } : {},
13287
13343
  ...parseSignedReceipt(data.receipt),
13288
13344
  ...parseFundingResponse(data),
13289
- upfrontPayment: parseUpfrontPayment(data.upfront_payment)
13345
+ ...upfrontReceiptFields(data.upfront_payment)
13290
13346
  };
13291
13347
  }
13292
13348
  async requestResult(provider, requestId, signedJob) {
@@ -13454,7 +13510,7 @@ var HttpsTransport = class {
13454
13510
  const url2 = `${endpoint}/v1/job/${jobId}`;
13455
13511
  const signal = options?.timeoutMs && options.timeoutMs > 0 ? AbortSignal.timeout(options.timeoutMs) : void 0;
13456
13512
  try {
13457
- const res = await dvmFetch(url2, { headers: jobTokenHeader(options?.jobToken), signal });
13513
+ const res = await readMessagePollBody(() => dvmFetch(url2, { headers: jobTokenHeader(options?.jobToken), signal }), jobId, "read status");
13458
13514
  captureTraceId(res);
13459
13515
  if (res.status === 404) {
13460
13516
  const storedEndpoint = loadJob(jobId)?.endpoint;
@@ -13464,11 +13520,11 @@ var HttpsTransport = class {
13464
13520
  ));
13465
13521
  }
13466
13522
  if (!res.ok) {
13467
- const credentialErr = jobCredentialError(res.status, await res.text());
13523
+ const credentialErr = jobCredentialError(res.status, await readMessagePollBody(() => res.text(), jobId, "read status"));
13468
13524
  if (credentialErr) throw credentialErr;
13469
13525
  throw new DvmError("provider_error", `Status check failed (${res.status})`);
13470
13526
  }
13471
- const data = await res.json();
13527
+ const data = await readMessagePollBody(() => res.json(), jobId, "read status");
13472
13528
  return {
13473
13529
  jobId,
13474
13530
  status: data.status,
@@ -13621,12 +13677,12 @@ var HttpsTransport = class {
13621
13677
  throw new DvmError("not_supported", "HTTPS stream requires a provider with an endpoint.");
13622
13678
  }
13623
13679
  const url2 = `${endpoint}/v1/job/${jobId}/messages?after=${afterSeq}`;
13624
- const res = await dvmFetch(url2, {
13680
+ const res = await readMessagePollBody(() => dvmFetch(url2, {
13625
13681
  headers: { Accept: "text/event-stream", ...jobTokenHeader(options?.jobToken) },
13626
13682
  signal: options?.signal
13627
- });
13683
+ }), jobId);
13628
13684
  if (!res.ok) {
13629
- const text = await res.text();
13685
+ const text = await readMessagePollBody(() => res.text(), jobId);
13630
13686
  const credentialErr = jobCredentialError(res.status, text);
13631
13687
  if (credentialErr) throw credentialErr;
13632
13688
  throw providerResponseError("provider_error", `stream failed (${res.status}): ${text}`);
@@ -13634,7 +13690,7 @@ var HttpsTransport = class {
13634
13690
  const contentType = res.headers.get("content-type") ?? "";
13635
13691
  const recognize = callerMessageRecognizer(jobId, endpoint);
13636
13692
  if (contentType.includes("application/json")) {
13637
- const body = await res.json();
13693
+ const body = await readMessagePollBody(() => res.json(), jobId);
13638
13694
  const messages2 = (body.messages ?? []).map(recognize);
13639
13695
  const last = messages2.at(-1);
13640
13696
  const reason = last?.type === "complete" ? "complete" : last?.type === "cancel" ? "cancel" : "yield";
@@ -13797,7 +13853,7 @@ function parseRequestResultResponse(value, requestId, httpStatus) {
13797
13853
  ...typeof data.job_token === "string" ? { jobToken: data.job_token } : {},
13798
13854
  ...receipt ? { receipt } : {},
13799
13855
  ...parseFundingResponse(data),
13800
- upfrontPayment: parseUpfrontPayment(data.upfront_payment)
13856
+ ...upfrontReceiptFields(data.upfront_payment)
13801
13857
  };
13802
13858
  }
13803
13859
  function malformedRequestResult(requestId, reason) {
@@ -14715,7 +14771,7 @@ async function settleCreditAfterJob(args) {
14715
14771
  }
14716
14772
  }
14717
14773
  if (args.allowTopup !== false) {
14718
- const refill = args.refillPocket ?? (await import("./pocket-refill-U4VK5WGO.js")).refillPocketIfLow;
14774
+ const refill = args.refillPocket ?? (await import("./pocket-refill-M65PPCN3.js")).refillPocketIfLow;
14719
14775
  await refill({ human: args.human }).catch(() => void 0);
14720
14776
  }
14721
14777
  }
@@ -15016,6 +15072,10 @@ function reportFunding(args, outcome, ctx) {
15016
15072
  );
15017
15073
  return;
15018
15074
  }
15075
+ case "invoice_pending":
15076
+ info(`${what} at ${args.ref.endpoint} deferred \u2014 ${outcome.display}${hint}`);
15077
+ incomplete("credit_funding_deferred");
15078
+ return;
15019
15079
  case "settlement_pending":
15020
15080
  info(`${what} at ${args.ref.endpoint} \u2014 ${outcome.display}${hint}`);
15021
15081
  incomplete("credit_funding_settlement_pending");
@@ -15496,14 +15556,14 @@ async function confirmRollback(stored, preview, opts) {
15496
15556
  async function withStrandingChecked(removing, commit) {
15497
15557
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
15498
15558
  if (leaving.has("tempo")) {
15499
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-QGJ4JEHN.js");
15559
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-Q3N5GGIQ.js");
15500
15560
  await assertTempoWalletIdle2("disconnect");
15501
15561
  }
15502
15562
  if (!leaving.has("x402")) return commit();
15503
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-WAQ3LZN4.js");
15504
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-NOK3MKL4.js");
15505
- const { ensureAddress: ensureAddress2 } = await import("./internal-WAQ3LZN4.js");
15506
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
15563
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-EQJXMIR2.js");
15564
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-3IBVUCTB.js");
15565
+ const { ensureAddress: ensureAddress2 } = await import("./internal-EQJXMIR2.js");
15566
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-J7JCMFZ2.js");
15507
15567
  return withX402ChannelLock2(async () => {
15508
15568
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
15509
15569
  if (unsettled.length > 0) {
@@ -15795,7 +15855,7 @@ function railMinimums(menu) {
15795
15855
  minimums.push({ rail: "lightning", minMicro: menu.lightning_min_micro });
15796
15856
  }
15797
15857
  if (menu?.funding.includes("stripe")) {
15798
- minimums.push({ rail: "stripe", minMicro: CARD_MIN_MICRO });
15858
+ minimums.push({ rail: "stripe", minMicro: cardMinimumMicro(menu) });
15799
15859
  }
15800
15860
  return minimums;
15801
15861
  }
@@ -16233,6 +16293,17 @@ async function runCreditBalance(dvm, opts) {
16233
16293
  try {
16234
16294
  for (const endpoint of endpoints) {
16235
16295
  try {
16296
+ if (!opts.observeOnly && !opts.selectionOnly) {
16297
+ const refused = await pollPendingCreditFundings({
16298
+ transport,
16299
+ ref: { endpoint },
16300
+ signing: signer
16301
+ }).catch(() => []);
16302
+ for (const outcome of refused) {
16303
+ noteRefusedCreditFunding(endpoint, outcome, opts.human);
16304
+ clearPendingFunding(endpoint, signer.pubkey, outcome.creditId, outcome.fundId);
16305
+ }
16306
+ }
16236
16307
  reads.push(
16237
16308
  await balanceAt(
16238
16309
  transport,
@@ -16241,8 +16312,7 @@ async function runCreditBalance(dvm, opts) {
16241
16312
  headroomOf,
16242
16313
  advisoryRate,
16243
16314
  opts.creditId,
16244
- opts.observeOnly,
16245
- opts.selectionOnly
16315
+ opts.observeOnly
16246
16316
  )
16247
16317
  );
16248
16318
  } catch (err) {
@@ -16290,18 +16360,12 @@ async function runCreditBalance(dvm, opts) {
16290
16360
  dvms: machines,
16291
16361
  display,
16292
16362
  hint: "Balances come from signed server reads or countersigned job receipts. `drawable: true` identifies value job draws can use; every untracked prepaid sibling carries the exact `drain_command` that reclaims it, while `kind: implicit` rows have no drain path. Each entry in `dvms` says what may be funded at that machine now. Expired prepaid credit remains reclaimable; a lost implicit balance does not.",
16293
- ...creditHint ? { credit_hint: creditHint } : {}
16363
+ ...creditHint ? { credit_hint: creditHint } : {},
16364
+ ...takeCreditNoticeFields()
16294
16365
  }
16295
16366
  });
16296
16367
  }
16297
- async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate, creditId, observeOnly = false, selectionOnly = false) {
16298
- if (!observeOnly && !selectionOnly) {
16299
- await pollPendingCreditFundings({
16300
- transport,
16301
- ref: { endpoint },
16302
- signing: signer
16303
- }).catch(() => void 0);
16304
- }
16368
+ async function balanceAt(transport, endpoint, signer, headroomOf, advisoryRate, creditId, observeOnly = false) {
16305
16369
  const providerInfo = await transport.describe({ endpoint }).catch(() => void 0);
16306
16370
  const identity = providerDvmIdentity(providerInfo);
16307
16371
  const postureOff = effectiveCreditPosture(loadConfig()?.credit, endpoint, identity).posture === "off";
@@ -20215,6 +20279,26 @@ function capitalise(s) {
20215
20279
  return s.length === 0 ? s : s[0].toUpperCase() + s.slice(1);
20216
20280
  }
20217
20281
 
20282
+ // src/lib/qr.ts
20283
+ var import_qrcode = __toESM(require_lib(), 1);
20284
+ import { randomBytes as randomBytes2 } from "crypto";
20285
+ import { tmpdir } from "os";
20286
+ import { join as join4 } from "path";
20287
+ async function renderQrTerminal(payload) {
20288
+ return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
20289
+ }
20290
+ async function renderQrPng(payload, outPath) {
20291
+ await (0, import_qrcode.toFile)(outPath, payload, {
20292
+ type: "png",
20293
+ errorCorrectionLevel: "M",
20294
+ margin: 2,
20295
+ scale: 8
20296
+ });
20297
+ }
20298
+ function defaultQrImagePath(prefix = "dvm-wallet-fund") {
20299
+ return join4(tmpdir(), `${prefix}-${randomBytes2(8).toString("hex")}.png`);
20300
+ }
20301
+
20218
20302
  // src/lib/credit/funding.ts
20219
20303
  async function runCreditFund(dvm, opts) {
20220
20304
  const invocationStartedAt = Date.now();
@@ -20232,8 +20316,15 @@ async function runCreditFund(dvm, opts) {
20232
20316
  );
20233
20317
  }
20234
20318
  const fundingMode = parseFundingMode(opts.fundingMode);
20235
- const cardSpt = await resolveCardSpt(opts.spt);
20236
20319
  const namedRail = parseFundRail(opts.rail);
20320
+ if (opts.invoice && (namedRail && namedRail !== "lightning" || opts.spt !== void 0 || fundingMode || opts.cashuMint !== void 0 || opts.maxCashuPrincipalSats !== void 0 || opts.maxCashuFeeSats !== void 0)) {
20321
+ throw new DvmError(
20322
+ "invalid_argument",
20323
+ "--invoice only applies to Lightning credit funding.",
20324
+ "Use --rail lightning --invoice without card, stablecoin, or Cashu funding options."
20325
+ );
20326
+ }
20327
+ const cardSpt = await resolveCardSpt(opts.spt);
20237
20328
  if (cardSpt !== void 0 && namedRail && namedRail !== "stripe") {
20238
20329
  throw new DvmError(
20239
20330
  "invalid_argument",
@@ -20244,7 +20335,7 @@ async function runCreditFund(dvm, opts) {
20244
20335
  }
20245
20336
  );
20246
20337
  }
20247
- const flagRail = cardSpt !== void 0 ? "stripe" : namedRail;
20338
+ const flagRail = opts.invoice ? "lightning" : cardSpt !== void 0 ? "stripe" : namedRail;
20248
20339
  if (fundingMode && flagRail && !isStablecoinFundRail(flagRail)) {
20249
20340
  throw new DvmError(
20250
20341
  "invalid_argument",
@@ -20291,6 +20382,13 @@ async function runCreditFund(dvm, opts) {
20291
20382
  stored,
20292
20383
  journalled: pending4
20293
20384
  });
20385
+ if (opts.invoice && (pending4 && pending4.rail !== "lightning" || signedPending)) {
20386
+ throw new DvmError(
20387
+ "invalid_argument",
20388
+ "Another funding for this credit is unresolved on a different rail.",
20389
+ "Resume that funding without --invoice before starting a Lightning funding."
20390
+ );
20391
+ }
20294
20392
  const configPin = effectiveFundingRail(config2?.credit, endpoint, attestedIdentity);
20295
20393
  const boundRail = pinnedRail(stored, opts.creditId);
20296
20394
  if (!pending4 && !signedPending && flagRail && boundRail && flagRail !== boundRail) {
@@ -20343,6 +20441,17 @@ async function runCreditFund(dvm, opts) {
20343
20441
  creditId: pending4?.creditId ?? opts.creditId ?? signedPending?.creditId ?? (canRefillStoredCredit(stored) ? stored.creditId : randomUUID3()),
20344
20442
  amountMicro: fundMicro,
20345
20443
  human: opts.human,
20444
+ invoice: opts.invoice,
20445
+ invoiceWait: opts.wait !== false,
20446
+ ...signer.source.kind !== "env" ? { invoiceIdentity: signer.source.name } : {},
20447
+ invoiceProgress: async (handoff) => {
20448
+ if (opts.human) {
20449
+ info(String(handoff.display));
20450
+ info(String(handoff.bolt11));
20451
+ info(await renderQrTerminal(String(handoff.bolt11).toUpperCase()));
20452
+ info(`Resume with: ${String(handoff.next_step)}`);
20453
+ } else json({ op: "fund", endpoint, ...handoff });
20454
+ },
20346
20455
  providerInfo,
20347
20456
  ...menu ? { menu } : {},
20348
20457
  ...stored ? { targetMicro: Math.max(stored.targetMicro, fundMicro) } : {},
@@ -20413,7 +20522,12 @@ async function runCreditFund(dvm, opts) {
20413
20522
  outcome.display,
20414
20523
  providerDisplay || providerHint ? `The DVM says: ${[providerDisplay?.text, providerHint?.text].filter(Boolean).join(" ")}` : void 0,
20415
20524
  modeSentence,
20416
- outcome.hint
20525
+ outcome.hint,
20526
+ ...outcome.invoiceHandoff && opts.human ? [
20527
+ String(outcome.invoiceHandoff.bolt11),
20528
+ await renderQrTerminal(String(outcome.invoiceHandoff.bolt11).toUpperCase()),
20529
+ `Resume with: ${String(outcome.invoiceHandoff.next_step)}`
20530
+ ] : []
20417
20531
  ].filter((line) => line !== void 0);
20418
20532
  renderCreditFunding({
20419
20533
  human: opts.human === true,
@@ -20423,6 +20537,7 @@ async function runCreditFund(dvm, opts) {
20423
20537
  endpoint,
20424
20538
  status: outcome.status,
20425
20539
  ...outcome.checkoutHandoff ?? {},
20540
+ ...outcome.invoiceHandoff ?? {},
20426
20541
  credit_id: outcome.creditId,
20427
20542
  fund_id: outcome.fundId,
20428
20543
  ...resumedNote ? { resumed: resumedNote } : {},
@@ -22020,9 +22135,9 @@ function cashuOptions(mints, hasLightningBackend) {
22020
22135
  const receiveTokenOption = {
22021
22136
  method: "cashu-receive-token",
22022
22137
  display: "Receive an existing Cashu token",
22023
- command: "dvm wallet receive-token <cashu-token>",
22138
+ command: "dvm wallet receive-token",
22024
22139
  description: "Claim a pre-minted Cashu token (e.g. from a friend or a faucet) into the agent wallet. The token is re-locked to your wallet's key so it's spendable.",
22025
- hint: "Tokens are single-use; a token locked to a third party can't be claimed.",
22140
+ hint: "Pipe the token into stdin or redirect a token file; do not pass it as a command argument. Tokens are single-use; a token locked to a third party can't be claimed.",
22026
22141
  ...hasMints ? { mints } : {}
22027
22142
  };
22028
22143
  const options = [];
@@ -22224,8 +22339,8 @@ async function probeX402(x402, timeoutMs) {
22224
22339
  let network;
22225
22340
  let address;
22226
22341
  try {
22227
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
22228
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-WAQ3LZN4.js");
22342
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-J7JCMFZ2.js");
22343
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-EQJXMIR2.js");
22229
22344
  const wallet = loadX402Wallet2();
22230
22345
  if (!wallet) {
22231
22346
  const storedKey = x402.privateKey;
@@ -22277,8 +22392,8 @@ async function probeMpp(mpp, timeoutMs) {
22277
22392
  if (!mpp) return null;
22278
22393
  if (mpp.method === "tempo") {
22279
22394
  try {
22280
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-GDDZZP5S.js");
22281
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-WAQ3LZN4.js");
22395
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-AY6R3E4Z.js");
22396
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-EQJXMIR2.js");
22282
22397
  const account = await connectedTempoAccount2();
22283
22398
  if (!account) {
22284
22399
  return {
@@ -22373,7 +22488,7 @@ function x402WrongAssetHint(asset) {
22373
22488
 
22374
22489
  // src/lib/build-freshness.ts
22375
22490
  import { existsSync as existsSync4, readdirSync, statSync } from "fs";
22376
- import { dirname as dirname2, join as join4 } from "path";
22491
+ import { dirname as dirname2, join as join5 } from "path";
22377
22492
  import { fileURLToPath as fileURLToPath2 } from "url";
22378
22493
  var EXTRA_SOURCES = ["package.json", "tsup.config.ts"];
22379
22494
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "__snapshots__"]);
@@ -22392,11 +22507,11 @@ function checkBuildFreshness(opts) {
22392
22507
  skipReason
22393
22508
  });
22394
22509
  if (root === null) return skipped("running_from_source");
22395
- const bundlePath = join4(root, "dist", "dvm.js");
22510
+ const bundlePath = join5(root, "dist", "dvm.js");
22396
22511
  if (dirname2(moduleDir) !== root || !existsSync4(bundlePath)) {
22397
22512
  return skipped("running_from_source");
22398
22513
  }
22399
- const srcDir = join4(root, "src");
22514
+ const srcDir = join5(root, "src");
22400
22515
  if (!existsSync4(srcDir)) return skipped("no_source_tree");
22401
22516
  const builtAtMs = statSync(bundlePath).mtimeMs;
22402
22517
  const newer = [];
@@ -22406,7 +22521,7 @@ function checkBuildFreshness(opts) {
22406
22521
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
22407
22522
  if (budget2.left-- <= 0) return;
22408
22523
  if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
22409
- const abs = join4(dir, entry.name);
22524
+ const abs = join5(dir, entry.name);
22410
22525
  const relPath = rel ? `${rel}/${entry.name}` : entry.name;
22411
22526
  if (entry.isDirectory()) {
22412
22527
  visit(abs, relPath, budget2);
@@ -22421,7 +22536,7 @@ function checkBuildFreshness(opts) {
22421
22536
  const budget = { left: MAX_ENTRIES };
22422
22537
  visit(srcDir, "src", budget);
22423
22538
  for (const name of EXTRA_SOURCES) {
22424
- const abs = join4(root, name);
22539
+ const abs = join5(root, name);
22425
22540
  if (!existsSync4(abs)) continue;
22426
22541
  const mtimeMs = statSync(abs).mtimeMs;
22427
22542
  if (mtimeMs > newestMs) newestMs = mtimeMs;
@@ -22440,7 +22555,7 @@ function checkBuildFreshness(opts) {
22440
22555
  function findPackageRoot(start) {
22441
22556
  let dir = start;
22442
22557
  for (; ; ) {
22443
- if (existsSync4(join4(dir, "package.json"))) return dir;
22558
+ if (existsSync4(join5(dir, "package.json"))) return dir;
22444
22559
  const parent = dirname2(dir);
22445
22560
  if (parent === dir) return null;
22446
22561
  dir = parent;
@@ -22449,7 +22564,7 @@ function findPackageRoot(start) {
22449
22564
 
22450
22565
  // src/lib/caller-state.ts
22451
22566
  import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync6, statSync as statSync2 } from "fs";
22452
- import { basename, join as join6 } from "path";
22567
+ import { basename, join as join7 } from "path";
22453
22568
 
22454
22569
  // src/lib/request-refusal-store.ts
22455
22570
  import {
@@ -22462,11 +22577,11 @@ import {
22462
22577
  rmSync,
22463
22578
  writeFileSync as writeFileSync3
22464
22579
  } from "fs";
22465
- import { join as join5 } from "path";
22466
- var REQUEST_REFUSALS_DIR = join5(CONFIG_DIR, "request-refusals");
22580
+ import { join as join6 } from "path";
22581
+ var REQUEST_REFUSALS_DIR = join6(CONFIG_DIR, "request-refusals");
22467
22582
  var SAFE_TOKEN = /^[a-z0-9_.:-]{1,64}$/;
22468
22583
  function requestIntentMayExist(requestId) {
22469
- return existsSync5(join5(REQUEST_INTENTS_DIR, requestId));
22584
+ return existsSync5(join6(REQUEST_INTENTS_DIR, requestId));
22470
22585
  }
22471
22586
  function recordRequestRefusal(requestId, refusal) {
22472
22587
  if (!isPublicRequestId(requestId) || requestIntentMayExist(requestId)) return false;
@@ -22513,7 +22628,7 @@ function loadRequestRefusal(requestId) {
22513
22628
  }
22514
22629
  }
22515
22630
  function refusalPath(requestId) {
22516
- return join5(REQUEST_REFUSALS_DIR, `${requestId}.json`);
22631
+ return join6(REQUEST_REFUSALS_DIR, `${requestId}.json`);
22517
22632
  }
22518
22633
 
22519
22634
  // src/lib/caller-state.ts
@@ -22532,9 +22647,15 @@ function detectSetupState() {
22532
22647
  }
22533
22648
  function isPartialSetup(state) {
22534
22649
  const hasExisting = state.existingState.jobs || state.existingState.messages;
22535
- const hasMissing = state.missing.config || state.missing.identity || state.missing.wallet;
22650
+ const hasMissing = state.missing.config || state.missing.identity;
22536
22651
  return hasExisting && hasMissing;
22537
22652
  }
22653
+ function describeMissingSetup(state) {
22654
+ const files = [];
22655
+ if (state.missing.config) files.push("config.json");
22656
+ if (state.missing.identity) files.push("identities.json");
22657
+ return files.join(" and ");
22658
+ }
22538
22659
  function describeExisting(state) {
22539
22660
  const { jobs, messages: messages2 } = state.existingState;
22540
22661
  if (jobs && messages2) return "job and message history";
@@ -22666,7 +22787,7 @@ function findQuarantinedCreditStores() {
22666
22787
  } catch {
22667
22788
  return [];
22668
22789
  }
22669
- 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 }));
22790
+ return entries.filter((name) => name.startsWith(prefix)).sort((a, b) => a < b ? 1 : a > b ? -1 : 0).map((name) => ({ path: join7(CONFIG_DIR, name), name }));
22670
22791
  }
22671
22792
  function checkOne(spec) {
22672
22793
  const exists = existsSync6(spec.path);
@@ -22705,7 +22826,7 @@ function checkSecretDirectory(dir, row) {
22705
22826
  try {
22706
22827
  const offenders = [];
22707
22828
  for (const name of readdirSync2(dir)) {
22708
- const path = join6(dir, name);
22829
+ const path = join7(dir, name);
22709
22830
  const stat2 = statSync2(path);
22710
22831
  if (!stat2.isFile()) continue;
22711
22832
  const mode = stat2.mode & 511;
@@ -22738,7 +22859,7 @@ function readBtcRateCacheAge(now = Date.now()) {
22738
22859
 
22739
22860
  // src/lib/mnemonic-backups.ts
22740
22861
  import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
22741
- import { basename as basename2, dirname as dirname3, join as join7 } from "path";
22862
+ import { basename as basename2, dirname as dirname3, join as join8 } from "path";
22742
22863
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
22743
22864
  const dir = dirname3(mnemonicFile);
22744
22865
  const prefix = `${basename2(mnemonicFile)}.`;
@@ -22750,7 +22871,7 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
22750
22871
  throw err;
22751
22872
  }
22752
22873
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
22753
- const path = join7(dir, name);
22874
+ const path = join8(dir, name);
22754
22875
  const stat2 = statSync3(path);
22755
22876
  if (!stat2.isFile()) return null;
22756
22877
  const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
@@ -23232,12 +23353,13 @@ function buildFileChecks() {
23232
23353
  try {
23233
23354
  const state = detectSetupState();
23234
23355
  if (isPartialSetup(state)) {
23356
+ const missing = describeMissingSetup(state);
23235
23357
  checks.push({
23236
23358
  name: "partial_setup_state",
23237
23359
  group: "files",
23238
23360
  status: "warn",
23239
- display: "Caller history (jobs / messages) is present but core setup files are missing.",
23240
- hint: "Run 'dvm init' to recreate the missing config, identity, and wallet without touching existing history.",
23361
+ display: `Caller history (jobs / messages) is present. Missing setup: ${missing}.`,
23362
+ hint: `Run 'dvm init' to recreate ${missing} without touching existing history.`,
23241
23363
  details: { existingState: state.existingState, missing: state.missing }
23242
23364
  });
23243
23365
  }
@@ -24974,7 +25096,7 @@ var nudgedThisInvocation = false;
24974
25096
  // src/lib/platform.ts
24975
25097
  import { existsSync as existsSync8, mkdirSync as mkdirSync2, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
24976
25098
  import { homedir as homedir2 } from "os";
24977
- import { join as join8 } from "path";
25099
+ import { join as join9 } from "path";
24978
25100
  function getPlatformUrl() {
24979
25101
  return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
24980
25102
  }
@@ -25451,11 +25573,11 @@ async function init(opts) {
25451
25573
  const creditPosture2 = existing.credit?.posture ?? posture ?? DEFAULT_CREDIT_POSTURE;
25452
25574
  const feedbackPosture2 = existing.feedback?.posture ?? DEFAULT_FEEDBACK_POSTURE;
25453
25575
  if (opts.human) {
25454
- if (created && isPartialSetup(setupState)) {
25576
+ if (isPartialSetup(setupState)) {
25455
25577
  info(
25456
- `Found existing ${describeExisting(setupState)} in ${CONFIG_DIR}, but no config, identity, or wallet.`
25578
+ `Found existing ${describeExisting(setupState)} in ${CONFIG_DIR}. Missing setup: ${describeMissingSetup(setupState)}.`
25457
25579
  );
25458
- info("Creating the missing setup files and preserving existing history.");
25580
+ info("Preserved existing history.");
25459
25581
  }
25460
25582
  info(created ? `Config written to ${CONFIG_FILE}` : `Config already exists at ${CONFIG_FILE}`);
25461
25583
  if (!created) info("Nothing already configured was changed.");
@@ -25540,7 +25662,7 @@ function finalizeProgressLine() {
25540
25662
  }
25541
25663
 
25542
25664
  // src/lib/save-artifact.ts
25543
- import { randomBytes as randomBytes2 } from "crypto";
25665
+ import { randomBytes as randomBytes3 } from "crypto";
25544
25666
  import {
25545
25667
  chmodSync,
25546
25668
  closeSync as closeSync3,
@@ -25551,8 +25673,8 @@ import {
25551
25673
  unlinkSync as unlinkSync3,
25552
25674
  writeFileSync as writeFileSync6
25553
25675
  } from "fs";
25554
- import { tmpdir } from "os";
25555
- import { join as join9 } from "path";
25676
+ import { tmpdir as tmpdir2 } from "os";
25677
+ import { join as join10 } from "path";
25556
25678
 
25557
25679
  // src/lib/mime-ext.ts
25558
25680
  var MIME_TO_EXT = {
@@ -25608,7 +25730,7 @@ var ArtifactSaveSession = class {
25608
25730
  let created = false;
25609
25731
  try {
25610
25732
  const directory = this.ensureDirectory();
25611
- path = join9(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
25733
+ path = join10(directory, `artifact-${randomBytes3(16).toString("hex")}.${ext}`);
25612
25734
  fd = openSync3(path, "wx", FILE_MODE);
25613
25735
  created = true;
25614
25736
  writeFileSync6(fd, buf);
@@ -25637,7 +25759,7 @@ var ArtifactSaveSession = class {
25637
25759
  }
25638
25760
  ensureDirectory() {
25639
25761
  if (this.directory) return this.directory;
25640
- const directory = mkdtempSync(join9(tmpdir(), "dvm-artifacts-"));
25762
+ const directory = mkdtempSync(join10(tmpdir2(), "dvm-artifacts-"));
25641
25763
  try {
25642
25764
  chmodSync(directory, DIRECTORY_MODE);
25643
25765
  } catch (err) {
@@ -25962,7 +26084,7 @@ async function waitAttached(opts, durationMs, now) {
25962
26084
  try {
25963
26085
  return await read();
25964
26086
  } catch (error) {
25965
- if (!isAbortError(error) && !(error instanceof DvmError && error.code === "timeout")) throw error;
26087
+ if (!isTransientJobReadError(error)) throw error;
25966
26088
  await new Promise((resolve3) => setTimeout(resolve3, Math.min(backoffMs, Math.max(0, deadline - now()))));
25967
26089
  backoffMs = Math.min(backoffMs * 2, 3e4);
25968
26090
  }
@@ -26057,6 +26179,7 @@ async function waitAttached(opts, durationMs, now) {
26057
26179
  onMessage,
26058
26180
  messageAppendSession,
26059
26181
  afterSeq: streamAfter,
26182
+ retryUnreachableReads: true,
26060
26183
  timeoutMs: readOptions().timeoutMs
26061
26184
  });
26062
26185
  collectMessages(next.messages);
@@ -26104,11 +26227,11 @@ async function messages(jobId, opts) {
26104
26227
  if (opts.until !== void 0 && !opts.wait || opts.wait && opts.stream === false) {
26105
26228
  throw new DvmError("invalid_arguments", "Use --until with --wait, and --wait with streaming enabled.");
26106
26229
  }
26230
+ const waitDuration = opts.wait ? parseDurationMs(opts.until ?? "12h") : void 0;
26107
26231
  const access = resolveJobAccess(jobId, opts);
26108
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => messagesWithAccess(jobId, opts, access), opts.human));
26232
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => messagesWithAccess(jobId, opts, access, waitDuration), opts.human));
26109
26233
  }
26110
- async function messagesWithAccess(jobId, opts, access) {
26111
- const waitDuration = opts.wait ? parseDurationMs(opts.until ?? "12h") : void 0;
26234
+ async function messagesWithAccess(jobId, opts, access, waitDuration) {
26112
26235
  const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
26113
26236
  const { stored, ref, jobToken } = access;
26114
26237
  const json3 = (data) => providerJobJson(data, !!stored);
@@ -26781,15 +26904,15 @@ function parsePositiveCashuSats(raw2) {
26781
26904
  function positive(value) {
26782
26905
  return typeof value === "number" && Number.isFinite(value) && value > 0;
26783
26906
  }
26784
- function autoPayWarnings(quotes, limits, ceiling, btcRate = getLastKnownBtcRate()?.rate ?? 0, { upfrontCoveredByCredit = false } = {}) {
26907
+ function autoPayWarnings(quotes2, limits, ceiling, btcRate = getLastKnownBtcRate()?.rate ?? 0, { upfrontCoveredByCredit = false } = {}) {
26785
26908
  if (!limits.budget && !limits.autoPayBelow) return [];
26786
26909
  if (!positive(btcRate)) {
26787
- const quoted = quotes.find((quote2) => quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount) && positive(quote2.priceMsats));
26910
+ const quoted = quotes2.find((quote2) => quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount) && positive(quote2.priceMsats));
26788
26911
  btcRate = getLastKnownBtcRate()?.rate ?? (quoted ? quoted.upfront.amount * 1e11 / quoted.priceMsats : 0);
26789
26912
  }
26790
26913
  const amounts = [];
26791
26914
  let excludedUpfront = false;
26792
- for (const quote2 of quotes) {
26915
+ for (const quote2 of quotes2) {
26793
26916
  if (quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount)) {
26794
26917
  if (upfrontCoveredByCredit) excludedUpfront = true;
26795
26918
  else amounts.push(quote2.upfront.amount);
@@ -26935,7 +27058,7 @@ function jsonParseErrorLine(jsonText, err) {
26935
27058
  function expectedFieldsFromSchema(schema) {
26936
27059
  const props = schema.properties;
26937
27060
  if (!isPlainObject(props)) return [];
26938
- const requiredList = Array.isArray(schema.required) ? schema.required.filter((x) => typeof x === "string") : [];
27061
+ const requiredList = Array.isArray(schema.required) ? schema.required.filter((x2) => typeof x2 === "string") : [];
26939
27062
  const required = new Set(requiredList);
26940
27063
  const out = [];
26941
27064
  for (const [name, raw2] of Object.entries(props)) {
@@ -26982,7 +27105,7 @@ function jsonSchemaType(node) {
26982
27105
  if (!isPlainObject(node)) return "unknown";
26983
27106
  const t = node.type;
26984
27107
  if (typeof t === "string") return t;
26985
- if (Array.isArray(t)) return t.filter((x) => typeof x === "string").join("|") || "unknown";
27108
+ if (Array.isArray(t)) return t.filter((x2) => typeof x2 === "string").join("|") || "unknown";
26986
27109
  if (Array.isArray(node.anyOf) || Array.isArray(node.oneOf)) return "union";
26987
27110
  if (Array.isArray(node.enum)) return "enum";
26988
27111
  return "unknown";
@@ -27180,7 +27303,7 @@ async function quoteWithWarnings(opts) {
27180
27303
  });
27181
27304
  progressNotice("Requesting quote...", opts.human);
27182
27305
  const usedPrimitiveInput = !!opts.input && !opts.data && !(opts.param && opts.param.length > 0);
27183
- const quotes = await withInputSchemaHint(
27306
+ const quotes2 = await withInputSchemaHint(
27184
27307
  transport,
27185
27308
  ref,
27186
27309
  {
@@ -27194,10 +27317,10 @@ async function quoteWithWarnings(opts) {
27194
27317
  },
27195
27318
  () => transport.quote(ref, envelope)
27196
27319
  );
27197
- if (quotes.length === 0) {
27320
+ if (quotes2.length === 0) {
27198
27321
  throw new DvmError("no_quotes", "No quotes received from provider.");
27199
27322
  }
27200
- const q = quotes[0];
27323
+ const q = quotes2[0];
27201
27324
  const pricing = providerInfo.capabilities?.[capability]?.pricing;
27202
27325
  addOutputWarnings(autoPayWarnings([q], {
27203
27326
  budget: opts.budget ?? config2?.defaultBudget,
@@ -27832,13 +27955,13 @@ function buildRow(url2, list, fee, source) {
27832
27955
  }
27833
27956
 
27834
27957
  // src/commands/request-output.ts
27835
- function outputCollectedQuotes(jobId, quotes, opts, identity, hint, nextAction) {
27958
+ function outputCollectedQuotes(jobId, quotes2, opts, identity, hint, nextAction) {
27836
27959
  const defaultHint = jobId ? "Use --auto-pay or --budget to pay automatically." : "Upfront payment required. Re-submit with --auto-pay to pay automatically.";
27837
27960
  const effectiveHint = nextAction?.hint ?? hint ?? defaultHint;
27838
27961
  if (opts.human) {
27839
- info(`${quotes.length} quote(s) received:`);
27840
- for (let i2 = 0; i2 < quotes.length; i2++) {
27841
- const q = quotes[i2];
27962
+ info(`${quotes2.length} quote(s) received:`);
27963
+ for (let i2 = 0; i2 < quotes2.length; i2++) {
27964
+ const q = quotes2[i2];
27842
27965
  info(` ${i2 + 1}. ${quoteAmountLabel(q)}`);
27843
27966
  }
27844
27967
  info(`
@@ -27852,14 +27975,14 @@ ${effectiveHint}`);
27852
27975
  ...requestIdFields(opts),
27853
27976
  ...dvmIdentity(identity?.dvmId, identity?.capability),
27854
27977
  status: "quotes-collected",
27855
- quotes: formatQuotes(quotes),
27978
+ quotes: formatQuotes(quotes2),
27856
27979
  hint: effectiveHint,
27857
27980
  ...takeCreditNoticeFields(),
27858
27981
  next_action: nextAction ?? null
27859
27982
  });
27860
27983
  }
27861
27984
  }
27862
- function outputQuotesNoWallet(jobId, quotes, opts, identity) {
27985
+ function outputQuotesNoWallet(jobId, quotes2, opts, identity) {
27863
27986
  const nextAction = {
27864
27987
  type: "setup_wallet",
27865
27988
  command: "dvm wallet setup",
@@ -27868,7 +27991,7 @@ function outputQuotesNoWallet(jobId, quotes, opts, identity) {
27868
27991
  };
27869
27992
  if (opts.human) {
27870
27993
  info("No wallet connected. Quotes received:");
27871
- for (const q of quotes) {
27994
+ for (const q of quotes2) {
27872
27995
  info(` ${quoteAmountLabel(q)}`);
27873
27996
  }
27874
27997
  info(`
@@ -27880,7 +28003,7 @@ ${nextAction.hint}`);
27880
28003
  ...requestIdFields(opts),
27881
28004
  ...dvmIdentity(identity?.dvmId, identity?.capability),
27882
28005
  status: "quotes-collected",
27883
- quotes: formatQuotes(quotes),
28006
+ quotes: formatQuotes(quotes2),
27884
28007
  message: "No wallet connected.",
27885
28008
  hint: nextAction.hint,
27886
28009
  ...takeCreditNoticeFields(),
@@ -27888,7 +28011,7 @@ ${nextAction.hint}`);
27888
28011
  });
27889
28012
  }
27890
28013
  }
27891
- function outputQuotesNoEligibleMint(jobId, quotes, opts, identity, detail) {
28014
+ function outputQuotesNoEligibleMint(jobId, quotes2, opts, identity, detail) {
27892
28015
  const acceptedList = detail.acceptedMints.join(", ") || "(none advertised)";
27893
28016
  const heldList = detail.heldMints.map((m) => `${m.mint}: ${m.sats} sats`).join(", ");
27894
28017
  const message2 = detail.code === "no_eligible_mint" ? "Wallet connected, but it holds no balance at any Cashu mint this service accepts." : "Wallet connected, but its balance at this service's accepted mint is too low to cover the quote.";
@@ -27901,7 +28024,7 @@ function outputQuotesNoEligibleMint(jobId, quotes, opts, identity, detail) {
27901
28024
  };
27902
28025
  if (opts.human) {
27903
28026
  info(message2);
27904
- for (const q of quotes) {
28027
+ for (const q of quotes2) {
27905
28028
  info(` ${quoteAmountLabel(q)}`);
27906
28029
  }
27907
28030
  info(`
@@ -27913,7 +28036,7 @@ ${hint}`);
27913
28036
  ...requestIdFields(opts),
27914
28037
  ...dvmIdentity(identity?.dvmId, identity?.capability),
27915
28038
  status: "quotes-collected",
27916
- quotes: formatQuotes(quotes),
28039
+ quotes: formatQuotes(quotes2),
27917
28040
  message: message2,
27918
28041
  hint,
27919
28042
  ...takeCreditNoticeFields(),
@@ -27924,11 +28047,11 @@ ${hint}`);
27924
28047
  });
27925
28048
  }
27926
28049
  }
27927
- function outputOverBudget(jobId, quotes, opts, identity, nextAction) {
27928
- const effectiveHint = nextAction?.hint ?? `Every quote is above your budget${quotes.length > 0 ? ` \u2014 the cheapest is ${quoteAmountLabel(cheapestQuote(quotes))}` : ""}. Re-run with --budget at or above the quote price to approve it.`;
28050
+ function outputOverBudget(jobId, quotes2, opts, identity, nextAction) {
28051
+ const effectiveHint = nextAction?.hint ?? `Every quote is above your budget${quotes2.length > 0 ? ` \u2014 the cheapest is ${quoteAmountLabel(cheapestQuote(quotes2))}` : ""}. Re-run with --budget at or above the quote price to approve it.`;
27929
28052
  if (opts.human) {
27930
28053
  info("No quotes within budget.");
27931
- for (const q of quotes) {
28054
+ for (const q of quotes2) {
27932
28055
  info(` ${quoteAmountLabel(q)}`);
27933
28056
  }
27934
28057
  info(`
@@ -27942,18 +28065,18 @@ ${effectiveHint}`);
27942
28065
  ...requestIdFields(opts),
27943
28066
  ...dvmIdentity(identity?.dvmId, identity?.capability),
27944
28067
  status: "over-budget",
27945
- quotes: formatQuotes(quotes),
28068
+ quotes: formatQuotes(quotes2),
27946
28069
  hint: effectiveHint,
27947
28070
  ...takeCreditNoticeFields(),
27948
28071
  next_action: nextAction ?? null
27949
28072
  });
27950
28073
  }
27951
28074
  }
27952
- function cheapestQuote(quotes) {
27953
- return quotes.reduce((min, q) => q.priceMsats < min.priceMsats ? q : min);
28075
+ function cheapestQuote(quotes2) {
28076
+ return quotes2.reduce((min, q) => q.priceMsats < min.priceMsats ? q : min);
27954
28077
  }
27955
- function formatQuotes(quotes) {
27956
- return quotes.map((q) => ({
28078
+ function formatQuotes(quotes2) {
28079
+ return quotes2.map((q) => ({
27957
28080
  upfront: q.upfront,
27958
28081
  msats: q.priceMsats,
27959
28082
  ...q.description ? { description: asProviderText(q.description) } : {},
@@ -28466,22 +28589,22 @@ async function requestWithWarnings(opts, stage) {
28466
28589
  jobRequestId = recovered.requestId;
28467
28590
  }
28468
28591
  if (receipt.status === "payment-required") {
28469
- const quotes = receipt.quotes ?? [];
28592
+ const quotes2 = receipt.quotes ?? [];
28470
28593
  if (opts.creditOnly) {
28471
28594
  transport.close();
28472
28595
  throw new DvmError("credit_only_unavailable", "The selected prepaid credit did not cover this submission; no fresh payment was attempted.");
28473
28596
  }
28474
28597
  if (!previewWarnings.length || previewUpfrontCoveredByCredit) {
28475
- addOutputWarnings(autoPayWarnings(quotes, warningLimits, void 0, btcRate), opts.human);
28598
+ addOutputWarnings(autoPayWarnings(quotes2, warningLimits, void 0, btcRate), opts.human);
28476
28599
  }
28477
- if (autoPayConsent && quotes.length > 0) {
28600
+ if (autoPayConsent && quotes2.length > 0) {
28478
28601
  const pay2 = () => handleAutoPayQuotes(
28479
28602
  transport,
28480
28603
  ref,
28481
28604
  envelope,
28482
28605
  receipt.jobId,
28483
28606
  deadlineMs,
28484
- quotes,
28607
+ quotes2,
28485
28608
  budgetMsats,
28486
28609
  opts,
28487
28610
  identity,
@@ -28508,8 +28631,8 @@ async function requestWithWarnings(opts, stage) {
28508
28631
  transport.close();
28509
28632
  const minMaxPayments = opts.maxPayments === "0" ? 1 : void 0;
28510
28633
  let action;
28511
- if (quotes.length > 0) {
28512
- const cheapest = cheapestQuote(quotes);
28634
+ if (quotes2.length > 0) {
28635
+ const cheapest = cheapestQuote(quotes2);
28513
28636
  const adjustmentNote = minMaxPayments ? " Bumps --max-payments from 0 to 1." : "";
28514
28637
  action = buildResubmitAction(
28515
28638
  opts,
@@ -28517,7 +28640,7 @@ async function requestWithWarnings(opts, stage) {
28517
28640
  `Upfront payment required: ${quoteAmountLabel(cheapest)}. Re-run with --auto-pay to approve.${adjustmentNote}`
28518
28641
  );
28519
28642
  }
28520
- outputCollectedQuotes(receipt.jobId || null, quotes, opts, identity, void 0, action);
28643
+ outputCollectedQuotes(receipt.jobId || null, quotes2, opts, identity, void 0, action);
28521
28644
  return;
28522
28645
  }
28523
28646
  saveSubmittedJob({
@@ -28550,7 +28673,7 @@ async function requestWithWarnings(opts, stage) {
28550
28673
  ...receiptTrustFields(providerInfo),
28551
28674
  ...localCorrelationJobFields(localCorrelationId)
28552
28675
  });
28553
- recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment);
28676
+ recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, false, receiptUpfrontFault(receipt));
28554
28677
  if (noStream && !isTerminalJobStatus(receipt.status)) {
28555
28678
  transport.close();
28556
28679
  const nextAction = pollNextAction(receipt.jobId);
@@ -28790,8 +28913,8 @@ function sha256Hex(value) {
28790
28913
  }
28791
28914
  async function fetchServerPriceMicro(transport, ref, envelope) {
28792
28915
  try {
28793
- const quotes = await transport.quote(ref, envelope);
28794
- return quotePriceMicro(quotes[0]);
28916
+ const quotes2 = await transport.quote(ref, envelope);
28917
+ return quotePriceMicro(quotes2[0]);
28795
28918
  } catch {
28796
28919
  return void 0;
28797
28920
  }
@@ -29034,22 +29157,22 @@ async function recoverDrawProbe(err, args) {
29034
29157
  }
29035
29158
  throw err;
29036
29159
  }
29037
- async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs, quotes, budgetMsats, opts, identity, policy, providerInfo, creditCtx) {
29160
+ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs, quotes2, budgetMsats, opts, identity, policy, providerInfo, creditCtx) {
29038
29161
  const configuredLimits = loadConfig();
29039
29162
  const declaredBudget = opts.budget ?? configuredLimits?.defaultBudget;
29040
29163
  const declaredAutoPayBelow = opts.autoPayBelow ?? configuredLimits?.autoPayThreshold;
29041
- const chosen = budgetMsats ? quotes.find(
29164
+ const chosen = budgetMsats ? quotes2.find(
29042
29165
  (quote2) => quoteWithinDeclaredLimit(quote2, budgetMsats, declaredBudget, opts.rail)
29043
- ) : quotes[0];
29166
+ ) : quotes2[0];
29044
29167
  if (!chosen) {
29045
29168
  transport.close?.();
29046
- const cheapest = cheapestQuote(quotes);
29169
+ const cheapest = cheapestQuote(quotes2);
29047
29170
  const action = buildResubmitAction(
29048
29171
  opts,
29049
29172
  { minBudgetMsats: cheapest.priceMsats, minAutoPayBelowMsats: cheapest.priceMsats },
29050
29173
  `Cheapest quote (${quoteAmountLabel(cheapest)}) exceeds your --budget. Re-run with --budget at or above the quote price.`
29051
29174
  );
29052
- outputOverBudget(jobId || null, quotes, opts, identity, action);
29175
+ outputOverBudget(jobId || null, quotes2, opts, identity, action);
29053
29176
  return;
29054
29177
  }
29055
29178
  if (!quoteWithinDeclaredLimit(chosen, policy.autoPayBelowMsats, declaredAutoPayBelow, opts.rail)) {
@@ -29061,7 +29184,7 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
29061
29184
  );
29062
29185
  outputCollectedQuotes(
29063
29186
  jobId || null,
29064
- quotes,
29187
+ quotes2,
29065
29188
  opts,
29066
29189
  identity,
29067
29190
  "Price exceeds your --auto-pay-below threshold. Increase it or pass a higher --budget.",
@@ -29078,7 +29201,7 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
29078
29201
  );
29079
29202
  outputCollectedQuotes(
29080
29203
  jobId || null,
29081
- quotes,
29204
+ quotes2,
29082
29205
  opts,
29083
29206
  identity,
29084
29207
  "--max-payments is 0 but a payment is required to proceed. Resubmit with --max-payments 1 (or higher) and --auto-pay if you wish to authorise it.",
@@ -29229,7 +29352,7 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
29229
29352
  }
29230
29353
  if (selection.rails.length === 0) {
29231
29354
  transport.close?.();
29232
- outputQuotesNoWallet(jobId, quotes, opts, identity);
29355
+ outputQuotesNoWallet(jobId, quotes2, opts, identity);
29233
29356
  return;
29234
29357
  }
29235
29358
  if (opts.mint && !selection.rails.some((r) => r === "cashu_p2pk")) {
@@ -29306,7 +29429,7 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
29306
29429
  jobId,
29307
29430
  deadlineMs,
29308
29431
  chosen,
29309
- quotes,
29432
+ quotes: quotes2,
29310
29433
  opts: railOpts,
29311
29434
  identity,
29312
29435
  policy,
@@ -29345,14 +29468,14 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
29345
29468
  if (cashuFellThroughCode && agentWallet) {
29346
29469
  outputQuotesNoEligibleMint(
29347
29470
  jobId,
29348
- quotes,
29471
+ quotes2,
29349
29472
  opts,
29350
29473
  identity,
29351
29474
  buildNoEligibleMintDetail(cashuFellThroughCode, providerInfo, agentWallet, chosen)
29352
29475
  );
29353
29476
  return;
29354
29477
  }
29355
- outputQuotesNoWallet(jobId, quotes, opts, identity);
29478
+ outputQuotesNoWallet(jobId, quotes2, opts, identity);
29356
29479
  }
29357
29480
  function buildNoEligibleMintDetail(code, providerInfo, agentWallet, chosen) {
29358
29481
  const acceptedMints = providerInfo.cashu?.mints ?? [];
@@ -30251,6 +30374,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
30251
30374
  }
30252
30375
  await collectCashuChange(effectiveJobId, receipt.cashuChange);
30253
30376
  recordUpfrontRailPayment(effectiveJobId, cashuUpfrontPayment(chosen, btcRate), true);
30377
+ addCashuSwapFee(effectiveJobId, prepared.swapFeeSats);
30254
30378
  if (!hasUnsavedJobState()) await commitAgentSpend({
30255
30379
  requestId: prepared.requestId,
30256
30380
  recentSpend: {
@@ -30258,6 +30382,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
30258
30382
  dvm_endpoint: ref.endpoint,
30259
30383
  mint: prepared.mint,
30260
30384
  amount_sats: prepared.totalSats,
30385
+ ...prepared.swapFeeSats > 0 ? { fee_sats: prepared.swapFeeSats } : {},
30261
30386
  signed_at_ms: Date.now()
30262
30387
  }
30263
30388
  });
@@ -30306,6 +30431,8 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
30306
30431
  transport.close?.();
30307
30432
  if (opts.human) {
30308
30433
  console.log(receipt.summary);
30434
+ const feeLine = describeCashuPayment(prepared.totalSats, prepared.swapFeeSats);
30435
+ if (feeLine) info(feeLine);
30309
30436
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
30310
30437
  if (hint) info(`\u{1F4CE} ${hint}`);
30311
30438
  await renderReceiptHuman(captured, effectiveJobId);
@@ -30320,6 +30447,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
30320
30447
  paidWith: "cashu_p2pk",
30321
30448
  mint: prepared.mint,
30322
30449
  amountSats: prepared.totalSats,
30450
+ ...cashuPaymentFeeFields(prepared.totalSats, prepared.swapFeeSats),
30323
30451
  requestId: prepared.requestId,
30324
30452
  ...prepared.attempts?.length ? { mint_attempts: prepared.attempts } : {},
30325
30453
  ...prepared.submissionBindingFingerprint ? { submissionBindingFingerprint: prepared.submissionBindingFingerprint } : {},
@@ -30346,6 +30474,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
30346
30474
  paidWith: "cashu_p2pk",
30347
30475
  mint: prepared.mint,
30348
30476
  amountSats: prepared.totalSats,
30477
+ ...cashuPaymentFeeFields(prepared.totalSats, prepared.swapFeeSats),
30349
30478
  requestId: prepared.requestId,
30350
30479
  ...prepared.attempts?.length ? { mint_attempts: prepared.attempts } : {},
30351
30480
  ...prepared.submissionBindingFingerprint ? { submissionBindingFingerprint: prepared.submissionBindingFingerprint } : {}
@@ -30863,7 +30992,12 @@ async function readStdin() {
30863
30992
  async function requestResult(requestId, opts = {}) {
30864
30993
  return withOutputWarnings(() => requestResultWithWarnings(requestId, opts), opts.human);
30865
30994
  }
30866
- async function requestResultWithWarnings(requestId, opts) {
30995
+ function resolveRequestId(arg) {
30996
+ if (isPublicRequestId(arg) && loadRequestIntent(arg)) return arg;
30997
+ return loadJob(arg)?.requestId ?? arg;
30998
+ }
30999
+ async function requestResultWithWarnings(argument, opts) {
31000
+ const requestId = resolveRequestId(argument);
30867
31001
  if (!isPublicRequestId(requestId)) {
30868
31002
  throw new DvmError(
30869
31003
  "invalid_request_id",
@@ -30982,7 +31116,7 @@ async function requestResultWithWarnings(requestId, opts) {
30982
31116
  const free = existing?.upfrontRailPayment === "free" || accepted?.amount_msats === 0 && !method;
30983
31117
  recordUpfrontRailPayment(receipt.jobId, localPayment ?? (free ? "free" : accepted && method ? { method, amountMsats: accepted.amount_msats } : void 0));
30984
31118
  }
30985
- recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, originalData?.fund !== void 0);
31119
+ recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, originalData?.fund !== void 0, receiptUpfrontFault(receipt));
30986
31120
  if (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled") {
30987
31121
  markJobTerminal(receipt.jobId, receipt.status, completionSnapshot(receipt), restored);
30988
31122
  } else {
@@ -31408,6 +31542,9 @@ function jobSpend(job, receipt) {
31408
31542
  if (receipt && job.paymentMethod === "credit" && !knownCredit) display += " The receipt total includes the unrecorded credit draw.";
31409
31543
  if (receipt && converted) display += " Receipt comparison is unknown: local records lack comparable native settlement amounts for Tempo/x402 payments. Converted BTC totals can differ with exchange rates and do not establish a difference in token principal or fees.";
31410
31544
  const [receiptLabel, localLabel] = receiptTotalDisplay === totalDisplay ? [`${receipt.paid.msats} msats`, `${total} msats`] : [receiptTotalDisplay, totalDisplay];
31545
+ const swapFeeSats = job.cashuSwapFeeSats ?? 0;
31546
+ const swapFeeDisplay = swapFeeSats > 0 ? `Mint fee: ${formatPaymentAmount(swapFeeSats * 1e3, void 0, { anchor: false })} left your wallet on top of the payments above. ${MINT_FEE_EXPLAINER}` : void 0;
31547
+ if (swapFeeDisplay) display += ` ${swapFeeDisplay}`;
31411
31548
  if (receiptMismatch) display += ` Receipt total ${receiptLabel} differs from local total ${localLabel}; mint fees, returned change, or a payment not recorded locally can explain the difference.`;
31412
31549
  return {
31413
31550
  charges,
@@ -31423,6 +31560,7 @@ function jobSpend(job, receipt) {
31423
31560
  )
31424
31561
  } : {},
31425
31562
  ...budgetDisplay ? { budget_display: budgetDisplay } : {},
31563
+ ...swapFeeDisplay ? { swap_fee_sats: swapFeeSats, swap_fee_display: swapFeeDisplay } : {},
31426
31564
  payments,
31427
31565
  max_payments: job.policy?.maxPayments ?? null,
31428
31566
  log_mismatch: logMismatch,
@@ -33746,26 +33884,6 @@ function mnemonicValidationError(result) {
33746
33884
  );
33747
33885
  }
33748
33886
 
33749
- // src/lib/qr.ts
33750
- var import_qrcode = __toESM(require_lib(), 1);
33751
- import { randomBytes as randomBytes3 } from "crypto";
33752
- import { tmpdir as tmpdir2 } from "os";
33753
- import { join as join10 } from "path";
33754
- async function renderQrTerminal(payload) {
33755
- return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
33756
- }
33757
- async function renderQrPng(payload, outPath) {
33758
- await (0, import_qrcode.toFile)(outPath, payload, {
33759
- type: "png",
33760
- errorCorrectionLevel: "M",
33761
- margin: 2,
33762
- scale: 8
33763
- });
33764
- }
33765
- function defaultQrImagePath(prefix = "dvm-wallet-fund") {
33766
- return join10(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
33767
- }
33768
-
33769
33887
  // src/lib/funding-handoff.ts
33770
33888
  var EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
33771
33889
  async function prepareStablecoinFundingHandoff(opts) {
@@ -34207,6 +34325,105 @@ function examples(fetcher) {
34207
34325
  return parts.join(", ");
34208
34326
  }
34209
34327
 
34328
+ // src/lib/error-handler.ts
34329
+ import { readFileSync as readFileSync11 } from "fs";
34330
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join12, relative as relative2, sep as sep3 } from "path";
34331
+ import { fileURLToPath as fileURLToPath3 } from "url";
34332
+
34333
+ // src/lib/internal-error-log.ts
34334
+ import { closeSync as closeSync4, constants, fchmodSync, fstatSync as fstatSync2, openSync as openSync4, renameSync as renameSync5, rmSync as rmSync2, writeSync, chmodSync as chmodSync2, readFileSync as readFileSync10, lstatSync } from "fs";
34335
+ import { homedir as homedir3 } from "os";
34336
+ import { isAbsolute, join as join11, relative, sep as sep2 } from "path";
34337
+ var MAX_LOG_BYTES = 256 * 1024;
34338
+ function appendInternalErrorLog(err, diagnostic) {
34339
+ let fd;
34340
+ try {
34341
+ const record2 = JSON.stringify({
34342
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
34343
+ version: localVersion(),
34344
+ command: process.argv[2],
34345
+ code: "internal",
34346
+ error_name: diagnostic.name,
34347
+ ...diagnostic.code ? { error_code: diagnostic.code } : {},
34348
+ ...errorDetail(err, 0)
34349
+ }) + "\n";
34350
+ if (Buffer.byteLength(record2) > MAX_LOG_BYTES) return void 0;
34351
+ const dir = join11(CONFIG_DIR, "logs");
34352
+ const file2 = join11(dir, "internal-errors.jsonl");
34353
+ try {
34354
+ if (!lstatSync(dir).isDirectory()) return void 0;
34355
+ } catch (err2) {
34356
+ if (err2.code !== "ENOENT") throw err2;
34357
+ ensureConfigSubdir(dir);
34358
+ }
34359
+ if (!lstatSync(dir).isDirectory()) return void 0;
34360
+ chmodSync2(dir, 448);
34361
+ const open2 = () => {
34362
+ const descriptor = openSync4(file2, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 384);
34363
+ try {
34364
+ fchmodSync(descriptor, 384);
34365
+ return descriptor;
34366
+ } catch (err2) {
34367
+ closeSync4(descriptor);
34368
+ throw err2;
34369
+ }
34370
+ };
34371
+ fd = open2();
34372
+ const size = fstatSync2(fd).size;
34373
+ if (size + Buffer.byteLength(record2) > MAX_LOG_BYTES) {
34374
+ closeSync4(fd);
34375
+ fd = void 0;
34376
+ rmSync2(file2 + ".1", { force: true });
34377
+ if (size <= MAX_LOG_BYTES) renameSync5(file2, file2 + ".1");
34378
+ else rmSync2(file2);
34379
+ fd = open2();
34380
+ }
34381
+ const bytes = Buffer.from(record2);
34382
+ let offset = 0;
34383
+ while (offset < bytes.length) offset += writeSync(fd, bytes, offset, bytes.length - offset);
34384
+ closeSync4(fd);
34385
+ fd = void 0;
34386
+ const fromHome = relative(homedir3(), file2);
34387
+ return fromHome !== ".." && !fromHome.startsWith(".." + sep2) && !isAbsolute(fromHome) ? join11("~", fromHome) : file2;
34388
+ } catch {
34389
+ return void 0;
34390
+ } finally {
34391
+ if (fd !== void 0) {
34392
+ try {
34393
+ closeSync4(fd);
34394
+ } catch {
34395
+ }
34396
+ }
34397
+ }
34398
+ }
34399
+ function errorDetail(err, depth) {
34400
+ const message2 = readProperty(err, "message");
34401
+ const stack = readProperty(err, "stack");
34402
+ const cause = readProperty(err, "cause");
34403
+ return {
34404
+ ...typeof message2 === "string" ? { message: message2 } : typeof err === "string" ? { message: err } : {},
34405
+ ...typeof stack === "string" ? { stack } : {},
34406
+ ...cause !== void 0 && depth < 5 ? { cause: errorDetail(cause, depth + 1) } : {}
34407
+ };
34408
+ }
34409
+ function readProperty(value, key) {
34410
+ try {
34411
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value[key] : void 0;
34412
+ } catch {
34413
+ return void 0;
34414
+ }
34415
+ }
34416
+ function localVersion() {
34417
+ for (const parent of ["..", "../.."]) {
34418
+ try {
34419
+ const manifest = JSON.parse(readFileSync10(join11(import.meta.dirname, parent, "package.json"), "utf8"));
34420
+ if (manifest.name === "@dvmkit/dvm-cli") return manifest.version;
34421
+ } catch {
34422
+ }
34423
+ }
34424
+ return void 0;
34425
+ }
34426
+
34210
34427
  // src/lib/error-handler.ts
34211
34428
  async function catchErrors(fn, human, jsonFields) {
34212
34429
  const lifetimeHold = setInterval(() => void 0, 60 * 60 * 1e3);
@@ -34260,9 +34477,13 @@ function handleError(err, human, jsonFields) {
34260
34477
  process.exit(1);
34261
34478
  }
34262
34479
  const diagnostic = unknownErrorDiagnostic(err);
34263
- const message2 = `An unexpected internal error occurred (${diagnostic.label}).`;
34480
+ const site = unknownErrorSite(err);
34481
+ const log = appendInternalErrorLog(err, diagnostic);
34482
+ const label = site.length ? `${diagnostic.label} at ${site.join(" < ")}` : diagnostic.label;
34483
+ const message2 = `An unexpected internal error occurred (${label}).`;
34264
34484
  if (human) {
34265
34485
  info(`Error: ${message2}`);
34486
+ if (log) info(`Details saved to ${log}`);
34266
34487
  } else {
34267
34488
  json({
34268
34489
  ...jsonFields,
@@ -34270,6 +34491,8 @@ function handleError(err, human, jsonFields) {
34270
34491
  code: "internal",
34271
34492
  message: message2,
34272
34493
  error_name: diagnostic.name,
34494
+ ...site.length ? { error_site: site } : {},
34495
+ ...log ? { error_log: log } : {},
34273
34496
  ...diagnostic.code ? { error_code: diagnostic.code } : {}
34274
34497
  },
34275
34498
  ...takeCreditNoticeFields(),
@@ -34283,6 +34506,7 @@ function unknownErrorDiagnostic(err) {
34283
34506
  const code = unknownErrorCode(err);
34284
34507
  return { name, ...code ? { code } : {}, label: code ? `${name}:${code}` : name };
34285
34508
  }
34509
+ var CLI_PACKAGE_ROOT = findCliPackageRoot();
34286
34510
  var ERROR_NAME_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/;
34287
34511
  function unknownErrorName(err) {
34288
34512
  if (!(err instanceof Error)) return `thrown_${typeof err}`;
@@ -34306,6 +34530,46 @@ function unknownErrorCode(err) {
34306
34530
  return void 0;
34307
34531
  }
34308
34532
  }
34533
+ function unknownErrorSite(err) {
34534
+ try {
34535
+ if (!CLI_PACKAGE_ROOT || !(err instanceof Error) || typeof err.stack !== "string" || typeof err.message !== "string") return [];
34536
+ const lines = err.stack.split("\n");
34537
+ const headerLines = err.message.split("\n").length;
34538
+ if (!lines.slice(0, headerLines).join("\n").endsWith(err.message)) return [];
34539
+ const names = [];
34540
+ for (const frame of lines.slice(headerLines)) {
34541
+ if (frame.includes("node:")) continue;
34542
+ const match = /^\s+at (?:async )?([^()]+) \((.*):\d+:\d+\)$/.exec(frame);
34543
+ if (!match) continue;
34544
+ const name = match[1].replace(/^new /, "").replace(/ \[as [^\]]+\]$/, "");
34545
+ const segments = name.split(".");
34546
+ if (name.length > 128 || !segments.every((segment) => ERROR_NAME_PATTERN.test(segment) && !/^(?:[a-f0-9]{64}|nsec1[a-z0-9]{58})$/i.test(segment))) continue;
34547
+ let location = match[2];
34548
+ if (location.startsWith("file:")) location = fileURLToPath3(location);
34549
+ if (!isAbsolute2(location)) continue;
34550
+ const fromPackage = relative2(CLI_PACKAGE_ROOT, location);
34551
+ if (isAbsolute2(fromPackage) || fromPackage === ".." || fromPackage.startsWith(".." + sep3)) continue;
34552
+ names.push(name);
34553
+ if (names.length === 5) break;
34554
+ }
34555
+ return names;
34556
+ } catch {
34557
+ return [];
34558
+ }
34559
+ }
34560
+ function findCliPackageRoot() {
34561
+ let dir = import.meta.dirname;
34562
+ for (; ; ) {
34563
+ try {
34564
+ const manifest = JSON.parse(readFileSync11(join12(dir, "package.json"), "utf8"));
34565
+ if (manifest.name === "@dvmkit/dvm-cli") return dir;
34566
+ } catch {
34567
+ }
34568
+ const parent = dirname4(dir);
34569
+ if (parent === dir) return void 0;
34570
+ dir = parent;
34571
+ }
34572
+ }
34309
34573
 
34310
34574
  // src/lib/wallet-agent/mint-failure-observer.ts
34311
34575
  var MintFailureLog = class {
@@ -35043,6 +35307,25 @@ function describeFloatOutcome(outcome) {
35043
35307
  }
35044
35308
  }
35045
35309
  async function walletReceiveToken(token, opts) {
35310
+ const stdinHint = "Pipe the Cashu token into `dvm wallet receive-token` or redirect a token file into stdin. Do not put the token in command arguments.";
35311
+ if (token === void 0 || token === "-") {
35312
+ if (process.stdin.isTTY) {
35313
+ throw new DvmError("no_input", "No Cashu token provided.", stdinHint);
35314
+ }
35315
+ try {
35316
+ token = (await drainStdin()).trim();
35317
+ } catch (err) {
35318
+ if (err instanceof StdinTimeoutError) {
35319
+ throw new DvmError("no_input", "No Cashu token provided (stdin timed out).", stdinHint);
35320
+ }
35321
+ throw err;
35322
+ }
35323
+ } else {
35324
+ info("WARNING: passing a Cashu token on the command line exposes it in shell history and process listings, where anyone who reads it can spend it first. Pipe it into `dvm wallet receive-token` instead.");
35325
+ }
35326
+ if (!token) {
35327
+ throw new DvmError("no_input", "No Cashu token provided.", stdinHint);
35328
+ }
35046
35329
  const result = await receiveToAgentWallet(token);
35047
35330
  if (opts.human) {
35048
35331
  info("");
@@ -35255,6 +35538,7 @@ async function walletShow(opts) {
35255
35538
  for (const spend of recentSpends) {
35256
35539
  info(` ${formatRecentSpend(spend)}`);
35257
35540
  }
35541
+ if (recentSpends.some((spend) => spend.fee_sats)) info(MINT_FEE_EXPLAINER);
35258
35542
  }
35259
35543
  } else {
35260
35544
  const totalUsd = railsSnapshot.reduce((sum, r) => sum + (r.json.balance_usd ?? 0), 0);
@@ -35640,7 +35924,8 @@ function reportUncheckedMints(unchecked) {
35640
35924
  function formatRecentSpend(spend) {
35641
35925
  const when = new Date(spend.signed_at_ms).toISOString();
35642
35926
  const reqShort = `${spend.request_id.slice(0, 8)}\u2026${spend.request_id.slice(-4)}`;
35643
- return `${when} ${spend.amount_sats} sats ${spend.dvm_endpoint} (req ${reqShort})`;
35927
+ const fee = spend.fee_sats !== void 0 && spend.fee_sats > 0 ? ` + ${spend.fee_sats} sats mint fee` : "";
35928
+ return `${when} ${spend.amount_sats} sats${fee} ${spend.dvm_endpoint} (req ${reqShort})`;
35644
35929
  }
35645
35930
  function formatMintSourceTag(source) {
35646
35931
  switch (source) {
@@ -35762,14 +36047,14 @@ import { randomUUID as randomUUID5 } from "crypto";
35762
36047
  // src/lib/wallet-agent/release-intents.ts
35763
36048
  var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
35764
36049
  import { createHash as createHash6 } from "crypto";
35765
- import { dirname as dirname4, join as join11 } from "path";
36050
+ import { dirname as dirname5, join as join13 } from "path";
35766
36051
  var intents = journalFile("release-intents.json");
35767
36052
  async function withReleaseLock(walletPubkey, builderHandle, mint, operation) {
35768
36053
  ensureConfigDir();
35769
36054
  const key = createHash6("sha256").update(JSON.stringify([walletPubkey, builderHandle, mint])).digest("hex");
35770
36055
  let unlock;
35771
36056
  try {
35772
- unlock = await import_proper_lockfile3.default.lock(join11(dirname4(JOBS_FILE), `release-${key}`), {
36057
+ unlock = await import_proper_lockfile3.default.lock(join13(dirname5(JOBS_FILE), `release-${key}`), {
35773
36058
  realpath: false,
35774
36059
  stale: 2 * 6e4,
35775
36060
  retries: 0
@@ -36745,8 +37030,129 @@ function assertInvoiceNotPending(wallet, invoice) {
36745
37030
  }
36746
37031
  }
36747
37032
 
37033
+ // src/lib/wallet-agent/melt-quotes.ts
37034
+ var quotes = journalFile("melt-quotes.json");
37035
+ var UNDATED_QUOTE_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
37036
+ function normalise(bolt11) {
37037
+ return invoiceDestination(bolt11) ?? bolt11.toLowerCase();
37038
+ }
37039
+ function isStale(entry, nowMs) {
37040
+ if (typeof entry.expires_at === "number") return entry.expires_at * 1e3 <= nowMs;
37041
+ const created = Date.parse(entry.created_at);
37042
+ return !Number.isFinite(created) || created + UNDATED_QUOTE_TTL_MS <= nowMs;
37043
+ }
37044
+ function isEntry(value) {
37045
+ if (typeof value !== "object" || value === null) return false;
37046
+ const entry = value;
37047
+ return typeof entry.mint === "string" && typeof entry.quote_id === "string" && entry.quote_id.length > 0 && typeof entry.bolt11 === "string" && typeof entry.created_at === "string";
37048
+ }
37049
+ function storedMeltQuote(mint, bolt11, nowMs) {
37050
+ const invoice = normalise(bolt11);
37051
+ return quotes.read().filter(isEntry).find((entry) => entry.mint === mint && entry.bolt11 === invoice && !isStale(entry, nowMs));
37052
+ }
37053
+ function rememberMeltQuote(entry, nowMs) {
37054
+ const invoice = normalise(entry.bolt11);
37055
+ quotes.withLock(() => {
37056
+ const kept = quotes.read().filter(isEntry).filter((held) => !isStale(held, nowMs) && !(held.mint === entry.mint && held.bolt11 === invoice));
37057
+ quotes.write([...kept, { ...entry, bolt11: invoice, created_at: new Date(nowMs).toISOString() }]);
37058
+ });
37059
+ }
37060
+ function forgetMeltQuote(mint, bolt11, quoteId) {
37061
+ const invoice = normalise(bolt11);
37062
+ const matches = (held) => held.mint === mint && held.bolt11 === invoice && (quoteId === void 0 || held.quote_id === quoteId);
37063
+ if (!quotes.read().filter(isEntry).some(matches)) return;
37064
+ quotes.withLock(() => quotes.write(quotes.read().filter(isEntry).filter((held) => !matches(held))));
37065
+ }
37066
+
36748
37067
  // src/lib/wallet-agent/cash-out-invoice.ts
36749
- async function prepareInvoice(opts, candidates, bounds) {
37068
+ function isDuplicateQuoteRefusal(err) {
37069
+ return /already has a (melt )?quote/i.test(err instanceof Error ? err.message : String(err));
37070
+ }
37071
+ function isMintRejection(err) {
37072
+ if (err instanceof te) return true;
37073
+ return err instanceof x && err.status >= 400 && err.status < 500 && err.status !== 408 && err.status !== 429;
37074
+ }
37075
+ async function resolveInvoiceQuote(mint, invoice, nowMs, cashuWallet) {
37076
+ const held = storedMeltQuote(mint, invoice, nowMs);
37077
+ if (held) {
37078
+ let current;
37079
+ try {
37080
+ current = await cashuWallet.checkMeltQuoteBolt11(held.quote_id);
37081
+ } catch (err) {
37082
+ if (!isMintRejection(err)) {
37083
+ return {
37084
+ kind: "failed",
37085
+ mint,
37086
+ settlement: "reverted",
37087
+ reason: "quote_state_unknown",
37088
+ message: `Could not check this wallet's saved melt quote for the invoice at ${mint}: ${err instanceof Error ? err.message : String(err)}. No money moved and the quote is still saved. Run \`dvm wallet mint-health\`, then retry \`dvm wallet cash-out <invoice>\`; do not pay this invoice from another mint until the quote's state is known.`
37089
+ };
37090
+ }
37091
+ forgetStored(mint, invoice, held.quote_id);
37092
+ current = void 0;
37093
+ }
37094
+ if (current && current.state === "PAID") {
37095
+ return {
37096
+ kind: "failed",
37097
+ mint,
37098
+ settlement: "reverted",
37099
+ reason: "quote_already_in_progress",
37100
+ message: `${mint} reports this invoice as already paid with this wallet's saved quote. No money moved in this run and nothing is left to pay; do not pay this invoice again. \`dvm wallet show\` shows the current balance.`
37101
+ };
37102
+ }
37103
+ if (current && current.state === "PENDING") {
37104
+ return {
37105
+ kind: "failed",
37106
+ mint,
37107
+ settlement: "reverted",
37108
+ reason: "quote_already_in_progress",
37109
+ message: `${mint} reports this invoice's melt quote as being paid. No money moved in this run. Run \`dvm wallet show\` to reconcile it; do not pay this invoice again.`
37110
+ };
37111
+ }
37112
+ const sameInvoice = current !== void 0 && (typeof current.request !== "string" || invoiceDestination(current.request) === invoiceDestination(invoice));
37113
+ const live = current !== void 0 && current.state === "UNPAID" && sameInvoice && !(typeof current.expiry === "number" && current.expiry * 1e3 <= nowMs);
37114
+ if (current && live) {
37115
+ return {
37116
+ amountSats: A.from(current.amount).toNumber(),
37117
+ feeReserveSats: A.from(current.fee_reserve).toNumber(),
37118
+ rawQuote: current
37119
+ };
37120
+ }
37121
+ if (current) forgetStored(mint, invoice, held.quote_id);
37122
+ }
37123
+ let quote2;
37124
+ try {
37125
+ quote2 = await fetchMeltQuote(mint, invoice);
37126
+ } catch (err) {
37127
+ if (!isDuplicateQuoteRefusal(err)) throw err;
37128
+ return {
37129
+ kind: "failed",
37130
+ mint,
37131
+ settlement: "reverted",
37132
+ reason: "quote_already_exists",
37133
+ message: `${mint} already holds a melt quote for this invoice and will not issue another, and this wallet has no usable record of that quote. No money moved. Ask for a new invoice, or run \`dvm wallet cash-out <invoice> --mint <url>\` to pay this one from a different mint.`
37134
+ };
37135
+ }
37136
+ try {
37137
+ rememberMeltQuote({
37138
+ mint,
37139
+ bolt11: invoice,
37140
+ quote_id: quote2.rawQuote.quote,
37141
+ amount_sats: quote2.amountSats,
37142
+ fee_reserve_sats: quote2.feeReserveSats,
37143
+ expires_at: typeof quote2.rawQuote.expiry === "number" ? quote2.rawQuote.expiry : null
37144
+ }, nowMs);
37145
+ } catch {
37146
+ }
37147
+ return quote2;
37148
+ }
37149
+ function forgetStored(mint, invoice, quoteId) {
37150
+ try {
37151
+ forgetMeltQuote(mint, invoice, quoteId);
37152
+ } catch {
37153
+ }
37154
+ }
37155
+ async function prepareInvoice(opts, candidates, bounds, cashuWallet) {
36750
37156
  const mint = opts.mintUrl;
36751
37157
  const refuse = (reason, message2) => ({
36752
37158
  kind: "skipped",
@@ -36757,7 +37163,8 @@ async function prepareInvoice(opts, candidates, bounds) {
36757
37163
  const invoice = opts.bolt11;
36758
37164
  const amount = invoiceAmountSats(invoice, (opts.now ?? Date.now)());
36759
37165
  try {
36760
- const quote2 = await fetchMeltQuote(mint, invoice);
37166
+ const quote2 = await resolveInvoiceQuote(mint, invoice, (opts.now ?? Date.now)(), cashuWallet);
37167
+ if ("kind" in quote2) return quote2;
36761
37168
  if (quote2.amountSats !== amount) {
36762
37169
  return refuse("quote_amount_mismatch", `The mint quoted ${quote2.amountSats} sats for a ${amount} sat invoice.`);
36763
37170
  }
@@ -36808,7 +37215,7 @@ async function prepareInvoice(opts, candidates, bounds) {
36808
37215
  async function prepareCashOut(opts, candidates, cashuWallet) {
36809
37216
  const mintUrl = opts.mintUrl;
36810
37217
  const fetchInvoice = opts.fetchInvoice ?? fetchLnurlPayInvoice;
36811
- if (opts.bolt11 !== void 0) return prepareInvoice(opts, candidates, meltBoundsOf(cashuWallet));
37218
+ if (opts.bolt11 !== void 0) return prepareInvoice(opts, candidates, meltBoundsOf(cashuWallet), cashuWallet);
36812
37219
  const meltBounds = meltBoundsOf(cashuWallet);
36813
37220
  let target = opts.target;
36814
37221
  let cappedByMintMax;
@@ -37025,7 +37432,7 @@ async function cashOutFromMint(opts) {
37025
37432
  kind: "skipped",
37026
37433
  mint: mintUrl,
37027
37434
  reason: "fee_cap_exceeded",
37028
- message: `Fees at ${mintUrl} would be up to ${totalFees} sats, over the ${opts.maxFeeSats} sat cap.${opts.bolt11 ? " No money moved. Run `dvm wallet cash-out <invoice> --max-fee <sats>` with a sufficient cap if you accept these fees." : ""}`,
37435
+ message: `Fees at ${mintUrl} would be up to ${totalFees} sats, over the ${opts.maxFeeSats} sat cap.${opts.bolt11 ? " No money moved. The quote is saved: run `dvm wallet cash-out <invoice> --max-fee <sats>` with a sufficient cap to pay with it if you accept these fees." : ""}`,
37029
37436
  quote: quoteView
37030
37437
  };
37031
37438
  }
@@ -37113,6 +37520,12 @@ async function cashOutFromMint(opts) {
37113
37520
  pending_melts: fresh.pending_melts.filter((m) => m.quote_id !== entry.quote_id)
37114
37521
  });
37115
37522
  });
37523
+ if (opts.bolt11) {
37524
+ try {
37525
+ forgetMeltQuote(mintUrl, opts.bolt11, entry.quote_id);
37526
+ } catch {
37527
+ }
37528
+ }
37116
37529
  return {
37117
37530
  kind: "sent",
37118
37531
  mint: mintUrl,
@@ -37166,6 +37579,27 @@ function errorMessage3(err) {
37166
37579
  return err instanceof Error ? err.message : String(err);
37167
37580
  }
37168
37581
 
37582
+ // src/lib/wallet-agent/cash-out-fees.ts
37583
+ var LARGE_FEE_SHARE_PERCENT = 2;
37584
+ function feeSharePercent(feeSats, payoutSats) {
37585
+ if (payoutSats <= 0) return null;
37586
+ return Math.round(feeSats / payoutSats * 1e3) / 10;
37587
+ }
37588
+ function isLargeFeeShare(feeSats, payoutSats) {
37589
+ return payoutSats > 0 && feeSats * 100 > payoutSats * LARGE_FEE_SHARE_PERCENT;
37590
+ }
37591
+ function settledFeeBreakdown(quote2, changeSats) {
37592
+ const feeSats = quote2.debit_sats - quote2.amount_sats - changeSats;
37593
+ const routingFeeSats = Math.max(0, feeSats - quote2.input_fee_sats);
37594
+ return {
37595
+ feeSats,
37596
+ inputFeeSats: quote2.input_fee_sats,
37597
+ routingFeeSats,
37598
+ routingReserveReturnedSats: Math.max(0, quote2.fee_reserve_sats - routingFeeSats)
37599
+ };
37600
+ }
37601
+ var LARGE_FEE_ADVICE = "That is a large share of the payout. Run with --dry-run to see the fee before anything is paid, and pass --max-fee <sats> to refuse a mint whose fees exceed your limit.";
37602
+
37169
37603
  // src/commands/wallet-cash-out.ts
37170
37604
  async function walletCashOut(destination, opts) {
37171
37605
  const human = opts.human ?? false;
@@ -37231,7 +37665,8 @@ async function walletCashOut(destination, opts) {
37231
37665
  }
37232
37666
  });
37233
37667
  outcomes.push(outcome);
37234
- if (bolt11 && (outcome.kind !== "skipped" && !(outcome.kind === "failed" && !outcome.quote))) break;
37668
+ const routable = outcome.kind === "skipped" || outcome.kind === "failed" && !outcome.quote && !outcome.reason;
37669
+ if (bolt11 && !routable) break;
37235
37670
  if (requested && (outcome.kind === "sent" || outcome.kind === "quoted")) {
37236
37671
  remaining -= outcome.quote.amount_sats;
37237
37672
  }
@@ -37241,6 +37676,19 @@ async function walletCashOut(destination, opts) {
37241
37676
  0
37242
37677
  );
37243
37678
  const feeSats = outcomes.reduce((sum, o) => sum + (o.kind === "sent" ? netFeeSats(o) : 0), 0);
37679
+ const sentBreakdowns = outcomes.flatMap(
37680
+ (o) => o.kind === "sent" ? [settledFeeBreakdown(o.quote, o.change_sats)] : []
37681
+ );
37682
+ const inputFeeSats = sentBreakdowns.reduce((sum, b) => sum + b.inputFeeSats, 0);
37683
+ const routingFeeSats = sentBreakdowns.reduce((sum, b) => sum + b.routingFeeSats, 0);
37684
+ const routingReserveReturnedSats = sentBreakdowns.reduce(
37685
+ (sum, b) => sum + b.routingReserveReturnedSats,
37686
+ 0
37687
+ );
37688
+ const quotedFeeSats = outcomes.reduce(
37689
+ (sum, o) => sum + (o.kind === "quoted" ? quotedFeeCeiling(o.quote) : 0),
37690
+ 0
37691
+ );
37244
37692
  const changeSats = outcomes.reduce((sum, o) => sum + (o.kind === "sent" ? o.change_sats : 0), 0);
37245
37693
  const quotedSats = outcomes.reduce(
37246
37694
  (sum, o) => sum + (o.kind === "quoted" ? o.quote.amount_sats : 0),
@@ -37251,13 +37699,21 @@ async function walletCashOut(destination, opts) {
37251
37699
  const moreToSend = opts.all === true || shortfall > 0;
37252
37700
  const rows = outcomes.map((o) => toRow(o, moreToSend));
37253
37701
  const status2 = opts.dryRun ? "quoted" : sentSats > 0 ? "cashed_out" : "nothing_sent";
37254
- const display = opts.dryRun ? `Quoted ${quotedSats} sats to ${destination}${bolt11 ? " from one mint" : ` across ${rows.length} mint(s)`}. Nothing was paid.` : sentSats > 0 ? `Sent ${sentSats} sats to ${destination}${feeSats > 0 ? `, plus ${feeSats} sats in fees` : ""}${shortfall > 0 ? ` \u2014 ${shortfall} sats short of what you asked for` : ""}.` : `Nothing was sent to ${destination}.`;
37702
+ const headlineFeeSats = opts.dryRun ? quotedFeeSats : feeSats;
37703
+ const headlinePayoutSats = opts.dryRun ? quotedSats : sentSats;
37704
+ const feeSharePct = feeSharePercent(headlineFeeSats, headlinePayoutSats);
37705
+ const feeWarning = rows.some((r) => r.fee_warning) || isLargeFeeShare(headlineFeeSats, headlinePayoutSats);
37706
+ const anyInputFee = rows.some((r) => (r.input_fee_sats ?? 0) > 0);
37707
+ const display = opts.dryRun ? `Quoted ${quotedSats} sats to ${destination}${bolt11 ? " from one mint" : ` across ${rows.length} mint(s)`}${quotedFeeSats > 0 ? `, with fees of up to ${feeAmount(quotedFeeSats)}${shareClause(feeSharePct)}` : ""}. Nothing was paid.${feeWarning ? ` ${LARGE_FEE_ADVICE}` : ""}${anyInputFee ? ` ${MINT_FEE_EXPLAINER}` : ""}` : sentSats > 0 ? `Sent ${sentSats} sats to ${destination}${feeSats > 0 ? `, plus ${feeAmount(feeSats)} in fees (${inputFeeSats} mint input fee + ${routingFeeSats} routing${shareClause(feeSharePct, true)}${routingReserveReturnedSats > 0 ? `; ${routingReserveReturnedSats} sats of unused routing reserve came back` : ""})` : ""}${shortfall > 0 ? ` \u2014 ${shortfall} sats short of what you asked for` : ""}.${feeSats > 0 && inputFeeSats > 0 ? ` ${MINT_FEE_EXPLAINER}` : ""}` : `Nothing was sent to ${destination}.`;
37255
37708
  const cappedCount = moreToSend ? rows.filter((r) => r.mint_max_sats !== void 0).length : 0;
37709
+ const savedQuote = bolt11 ? outcomes.find((o) => o.kind === "quoted")?.quote : void 0;
37256
37710
  const hint = buildHint({
37257
37711
  unresolvedCount: unresolved.length,
37258
37712
  shortfall,
37259
37713
  cappedCount,
37260
- dryRun: opts.dryRun
37714
+ dryRun: opts.dryRun,
37715
+ savedQuote,
37716
+ invoiceOutcomes: bolt11 ? outcomes : void 0
37261
37717
  });
37262
37718
  if (human) {
37263
37719
  info("");
@@ -37275,6 +37731,12 @@ async function walletCashOut(destination, opts) {
37275
37731
  requested_sats: requested?.sats ?? invoiceSats ?? null,
37276
37732
  sats_sent: sentSats,
37277
37733
  fee_sats: feeSats,
37734
+ input_fee_sats: inputFeeSats,
37735
+ routing_fee_sats: routingFeeSats,
37736
+ routing_reserve_returned_sats: routingReserveReturnedSats,
37737
+ quoted_fee_sats: quotedFeeSats,
37738
+ fee_share_pct: feeSharePct,
37739
+ fee_warning: feeWarning,
37278
37740
  change_sats: changeSats,
37279
37741
  shortfall_sats: shortfall,
37280
37742
  mints: rows,
@@ -37290,6 +37752,16 @@ async function walletCashOut(destination, opts) {
37290
37752
  );
37291
37753
  }
37292
37754
  }
37755
+ function quotedFeeCeiling(quote2) {
37756
+ return quote2.fee_reserve_sats + quote2.input_fee_sats;
37757
+ }
37758
+ function shareClause(share, inline = false) {
37759
+ if (share === null) return "";
37760
+ return inline ? `, about ${share}% of the payout` : ` (about ${share}% of the payout)`;
37761
+ }
37762
+ function feeAmount(sats) {
37763
+ return formatAmountBestEffort(sats * 1e3, { anchor: false });
37764
+ }
37293
37765
  function netFeeSats(outcome) {
37294
37766
  return outcome.quote.debit_sats - outcome.quote.amount_sats - outcome.change_sats;
37295
37767
  }
@@ -37307,13 +37779,25 @@ function toRow(outcome, moreToSend) {
37307
37779
  input_fee_sats: null,
37308
37780
  debit_sats: null,
37309
37781
  change_sats: null,
37782
+ fee_sats: null,
37783
+ routing_fee_sats: null,
37784
+ routing_reserve_returned_sats: null,
37785
+ fee_share_pct: null,
37786
+ fee_warning: false,
37310
37787
  preimage: null,
37311
37788
  error: null
37312
37789
  };
37313
37790
  switch (outcome.kind) {
37314
- case "sent":
37791
+ case "sent": {
37792
+ const breakdown = settledFeeBreakdown(outcome.quote, outcome.change_sats);
37793
+ const share = feeSharePercent(breakdown.feeSats, outcome.quote.amount_sats);
37315
37794
  return {
37316
37795
  ...base,
37796
+ fee_sats: breakdown.feeSats,
37797
+ routing_fee_sats: breakdown.routingFeeSats,
37798
+ routing_reserve_returned_sats: breakdown.routingReserveReturnedSats,
37799
+ fee_share_pct: share,
37800
+ fee_warning: isLargeFeeShare(breakdown.feeSats, outcome.quote.amount_sats),
37317
37801
  sats_sent: outcome.quote.amount_sats,
37318
37802
  fee_reserve_sats: outcome.quote.fee_reserve_sats,
37319
37803
  input_fee_sats: outcome.quote.input_fee_sats,
@@ -37321,11 +37805,18 @@ function toRow(outcome, moreToSend) {
37321
37805
  change_sats: outcome.change_sats,
37322
37806
  preimage: outcome.preimage,
37323
37807
  ...outcome.mint_max_sats !== void 0 ? { mint_max_sats: outcome.mint_max_sats } : {},
37324
- display: `${outcome.mint}: sent ${outcome.quote.amount_sats} sats (${netFeeSats(outcome)} sats in fees).${capNote(outcome.mint_max_sats, moreToSend)}`
37808
+ display: `${outcome.mint}: sent ${outcome.quote.amount_sats} sats. Fees ${breakdown.feeSats} sats${shareClause(share, true)}: ${breakdown.inputFeeSats} mint input fee + ${breakdown.routingFeeSats} routing${breakdown.routingReserveReturnedSats > 0 ? `; ${breakdown.routingReserveReturnedSats} sats of unused routing reserve came back` : ""}.${capNote(outcome.mint_max_sats, moreToSend)}`
37325
37809
  };
37326
- case "quoted":
37810
+ }
37811
+ case "quoted": {
37812
+ const ceiling = quotedFeeCeiling(outcome.quote);
37813
+ const share = feeSharePercent(ceiling, outcome.quote.amount_sats);
37814
+ const large = isLargeFeeShare(ceiling, outcome.quote.amount_sats);
37327
37815
  return {
37328
37816
  ...base,
37817
+ fee_sats: ceiling,
37818
+ fee_share_pct: share,
37819
+ fee_warning: large,
37329
37820
  fee_reserve_sats: outcome.quote.fee_reserve_sats,
37330
37821
  input_fee_sats: outcome.quote.input_fee_sats,
37331
37822
  debit_sats: outcome.quote.debit_sats,
@@ -37333,8 +37824,9 @@ function toRow(outcome, moreToSend) {
37333
37824
  // A dry run sent nothing, so "run it again" would be the wrong advice
37334
37825
  // whatever the mode — the cap is reported as fact and the summary hint
37335
37826
  // already says to re-run without --dry-run.
37336
- display: `${outcome.mint}: would send ${outcome.quote.amount_sats} sats for up to ${outcome.quote.fee_reserve_sats + outcome.quote.input_fee_sats} sats in fees.${capNote(outcome.mint_max_sats, false)}`
37827
+ display: `${outcome.mint}: would send ${outcome.quote.amount_sats} sats for up to ${ceiling} sats in fees (${outcome.quote.fee_reserve_sats} routing reserve + ${outcome.quote.input_fee_sats} mint input fee${shareClause(share, true)}).${large ? ` ${LARGE_FEE_ADVICE}` : ""}${capNote(outcome.mint_max_sats, false)}`
37337
37828
  };
37829
+ }
37338
37830
  case "skipped":
37339
37831
  return {
37340
37832
  ...base,
@@ -37347,14 +37839,17 @@ function toRow(outcome, moreToSend) {
37347
37839
  return {
37348
37840
  ...base,
37349
37841
  settlement: outcome.settlement,
37842
+ ...outcome.reason !== void 0 ? { reason: outcome.reason } : {},
37350
37843
  error: outcome.message,
37351
37844
  display: `${outcome.mint}: failed \u2014 ${outcome.message}`
37352
37845
  };
37353
37846
  }
37354
37847
  }
37355
37848
  function emitQuote(quote2, destination, human) {
37356
- const fees = quote2.fee_reserve_sats + quote2.input_fee_sats;
37357
- const display = `${quote2.mint}: sending ${quote2.amount_sats} sats to ${destination} costs up to ${fees} sats in fees (${quote2.fee_reserve_sats} routing reserve + ${quote2.input_fee_sats} mint input fee), debiting up to ${quote2.debit_sats} sats. Unused routing reserve comes back.`;
37849
+ const fees = quotedFeeCeiling(quote2);
37850
+ const share = feeSharePercent(fees, quote2.amount_sats);
37851
+ const large = isLargeFeeShare(fees, quote2.amount_sats);
37852
+ const display = `${quote2.mint}: sending ${quote2.amount_sats} sats to ${destination} costs up to ${fees} sats in fees (${quote2.fee_reserve_sats} routing reserve + ${quote2.input_fee_sats} mint input fee${shareClause(share, true)}), debiting up to ${quote2.debit_sats} sats. Unused routing reserve comes back.${large ? ` ${LARGE_FEE_ADVICE}` : ""}`;
37358
37853
  if (human) {
37359
37854
  info(display);
37360
37855
  } else {
@@ -37366,6 +37861,9 @@ function emitQuote(quote2, destination, human) {
37366
37861
  amount_sats: quote2.amount_sats,
37367
37862
  fee_reserve_sats: quote2.fee_reserve_sats,
37368
37863
  input_fee_sats: quote2.input_fee_sats,
37864
+ fee_sats: fees,
37865
+ fee_share_pct: share,
37866
+ fee_warning: large,
37369
37867
  debit_sats: quote2.debit_sats,
37370
37868
  expires_at: quote2.expires_at,
37371
37869
  display
@@ -37384,6 +37882,11 @@ function buildHint(args) {
37384
37882
  return "At least one melt's outcome is unknown \u2014 those sats stay committed until `dvm wallet show` reconciles them against the mint. Don't retry that mint until it does.";
37385
37883
  }
37386
37884
  if (args.dryRun) {
37885
+ if (args.savedQuote) {
37886
+ const until = args.savedQuote.expires_at !== null ? ` until it expires at ${new Date(args.savedQuote.expires_at * 1e3).toISOString()}` : " while the mint still holds it unpaid";
37887
+ return `Re-run without --dry-run to send. This quote is saved and the real run pays with it${until}, at the fees shown.`;
37888
+ }
37889
+ if (args.invoiceOutcomes) return unquotedInvoiceHint(args.invoiceOutcomes);
37387
37890
  return "Re-run without --dry-run to send. Quotes expire, so the fee is re-quoted at that point.";
37388
37891
  }
37389
37892
  if (args.cappedCount > 0) {
@@ -37394,6 +37897,22 @@ function buildHint(args) {
37394
37897
  }
37395
37898
  return "Confirm the remaining balance with `dvm wallet show`.";
37396
37899
  }
37900
+ function unquotedInvoiceHint(outcomes) {
37901
+ const reason = outcomes.find((o) => o.kind === "failed" && o.reason !== void 0);
37902
+ if (reason?.kind === "failed" && reason.reason === "quote_already_in_progress") {
37903
+ return "Do not re-run to send: the mint reports this invoice's quote as paid or being paid. `dvm wallet show` reconciles any payment still in flight.";
37904
+ }
37905
+ if (reason?.kind === "failed" && reason.reason === "quote_already_exists") {
37906
+ return "Re-running will not send this invoice from that mint: it will not issue another quote. Ask for a new invoice, or pass --mint to pay from a different mint.";
37907
+ }
37908
+ if (reason?.kind === "failed" && reason.reason === "quote_state_unknown") {
37909
+ return "Nothing was quoted because the saved quote could not be checked. It is still saved: retry once `dvm wallet mint-health` shows the mint reachable.";
37910
+ }
37911
+ if (outcomes.some((o) => o.kind === "skipped" && o.reason === "fee_cap_exceeded")) {
37912
+ return "Nothing would be sent at this fee cap. The quote is saved, so a re-run meets the same fees: raise --max-fee to accept them.";
37913
+ }
37914
+ return "Nothing would be sent: see the per-mint reasons above.";
37915
+ }
37397
37916
  function parseMaxFee(raw2) {
37398
37917
  if (raw2 === void 0) return void 0;
37399
37918
  const n = Number(raw2);
@@ -38658,15 +39177,15 @@ function hexToBytes2(hex2) {
38658
39177
  // src/lib/wallet-pairing-store.ts
38659
39178
  var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
38660
39179
  import {
38661
- chmodSync as chmodSync2,
39180
+ chmodSync as chmodSync3,
38662
39181
  existsSync as existsSync9,
38663
39182
  readdirSync as readdirSync5,
38664
- readFileSync as readFileSync10,
38665
- renameSync as renameSync5,
39183
+ readFileSync as readFileSync12,
39184
+ renameSync as renameSync6,
38666
39185
  unlinkSync as unlinkSync4,
38667
39186
  writeFileSync as writeFileSync7
38668
39187
  } from "fs";
38669
- import { join as join12 } from "path";
39188
+ import { join as join14 } from "path";
38670
39189
  var pairingIdPattern = /^[0-9a-f]{64}$/;
38671
39190
  var stateSchema = external_exports.object({
38672
39191
  version: external_exports.literal(1),
@@ -38689,7 +39208,7 @@ function createWalletPairingState(state) {
38689
39208
  ensurePairingsDirectory();
38690
39209
  const path = pairingPath(state.pairing_id);
38691
39210
  writeFileSync7(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
38692
- chmodSync2(path, 384);
39211
+ chmodSync3(path, 384);
38693
39212
  }
38694
39213
  function loadWalletPairingState(pairingId) {
38695
39214
  const path = pairingPath(pairingId);
@@ -38701,7 +39220,7 @@ function loadWalletPairingState(pairingId) {
38701
39220
  );
38702
39221
  }
38703
39222
  try {
38704
- return stateSchema.parse(JSON.parse(readFileSync10(path, "utf8")));
39223
+ return stateSchema.parse(JSON.parse(readFileSync12(path, "utf8")));
38705
39224
  } catch {
38706
39225
  throw new DvmError(
38707
39226
  "wallet_pairing_state_invalid",
@@ -38717,8 +39236,8 @@ function saveWalletPairingState(state) {
38717
39236
  const tmp = `${path}.tmp`;
38718
39237
  writeFileSync7(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
38719
39238
  try {
38720
- renameSync5(tmp, path);
38721
- chmodSync2(path, 384);
39239
+ renameSync6(tmp, path);
39240
+ chmodSync3(path, 384);
38722
39241
  } catch (err) {
38723
39242
  try {
38724
39243
  unlinkSync4(tmp);
@@ -38740,9 +39259,9 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
38740
39259
  let removed = 0;
38741
39260
  for (const name of readdirSync5(PAIRINGS_DIR)) {
38742
39261
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
38743
- const path = join12(PAIRINGS_DIR, name);
39262
+ const path = join14(PAIRINGS_DIR, name);
38744
39263
  try {
38745
- const state = stateSchema.parse(JSON.parse(readFileSync10(path, "utf8")));
39264
+ const state = stateSchema.parse(JSON.parse(readFileSync12(path, "utf8")));
38746
39265
  if (state.manifest.expires_at <= nowSeconds) {
38747
39266
  unlinkSync4(path);
38748
39267
  removed += 1;
@@ -38784,11 +39303,11 @@ function pairingPath(pairingId) {
38784
39303
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
38785
39304
  );
38786
39305
  }
38787
- return join12(PAIRINGS_DIR, `${pairingId}.json`);
39306
+ return join14(PAIRINGS_DIR, `${pairingId}.json`);
38788
39307
  }
38789
39308
  function ensurePairingsDirectory() {
38790
39309
  ensureConfigSubdir(PAIRINGS_DIR);
38791
- chmodSync2(PAIRINGS_DIR, 448);
39310
+ chmodSync3(PAIRINGS_DIR, 448);
38792
39311
  }
38793
39312
 
38794
39313
  // src/commands/wallet-pair.ts
@@ -40619,7 +41138,7 @@ function buildProgram() {
40619
41138
  ).option("--human", "Human-readable output instead of JSON").option("--timeout <sec>", "Override default timeout").action((opts) => {
40620
41139
  return catchErrors(() => request(opts), opts.human);
40621
41140
  });
40622
- program2.command("request-result <request-id>").description("Read the exact accepted job for a caller-generated request id without mutation").option("--human", "Human-readable output instead of JSON").action((requestId, opts) => {
41141
+ program2.command("request-result <request-id>").description("Read the exact accepted job for a caller-generated request id (or a local job id) without mutation").option("--human", "Human-readable output instead of JSON").action((requestId, opts) => {
40623
41142
  return catchErrors(() => requestResult(requestId, opts), opts.human);
40624
41143
  });
40625
41144
  program2.command("request-resume <request-id>").description("Explicitly finish a durably accepted request without sending payment").option("--human", "Human-readable output instead of JSON").option("--timeout <sec>", "Override default timeout").action((requestId, opts) => {
@@ -40702,7 +41221,7 @@ function buildProgram() {
40702
41221
  ).option(
40703
41222
  "--over-trust",
40704
41223
  "Fund past the trust-tier cap deliberately \u2014 required for an amount above what receipts here have earned, on every rail except card (stripe), which the cap never applies to"
40705
- ).option("--rail <rail>", `Force a funding rail: ${creditFundRails}`).option("--cashu-mint <mint>", "Pin Cashu funding to one DVM-accepted mint").option(
41224
+ ).option("--rail <rail>", `Force a funding rail: ${creditFundRails}`).option("--invoice", "Print a Lightning funding invoice for payment from any wallet; implies --rail lightning").option("--cashu-mint <mint>", "Pin Cashu funding to one DVM-accepted mint").option(
40706
41225
  "--max-cashu-principal-sats <sats>",
40707
41226
  "Refuse Cashu funding above this token-principal ceiling"
40708
41227
  ).option("--max-cashu-fee-sats <sats>", "Refuse Cashu funding above this swap-fee ceiling").option(
@@ -40711,7 +41230,7 @@ function buildProgram() {
40711
41230
  ).option(
40712
41231
  "--spt <token>",
40713
41232
  "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"
40714
- ).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) => {
41233
+ ).option("--no-wait", "Print the card checkout link or Lightning --invoice 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) => {
40715
41234
  return catchErrors(() => creditFund(dvm, opts), opts.human);
40716
41235
  });
40717
41236
  credit.command("drain <dvm>").description(
@@ -40745,7 +41264,7 @@ function buildProgram() {
40745
41264
  } }).exitOverride((error) => {
40746
41265
  if (error.exitCode === 0 || !jsonWait()) process.exit(error.exitCode);
40747
41266
  handleError(new DvmError("invalid_arguments", error.message.replace(/^error: /, "")), false, { event: "error" });
40748
- }).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) => {
41267
+ }).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, 1h30m)").option("--timeout <sec>", "Read timeout (default: 5s, or 60s with --wait)").action((jobId, opts) => {
40749
41268
  return catchErrors(() => messages(jobId, opts), opts.human, opts.wait && !opts.human ? { event: "error" } : void 0);
40750
41269
  });
40751
41270
  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(
@@ -40867,7 +41386,7 @@ Docs:
40867
41386
  "Local budget charges, credit draws, completed refunds/losses, and active recovery, newest first. Confirmed spend history has no automatic expiry; budget limits still use rolling windows."
40868
41387
  ).option("--today", "Only spends since UTC start of today").option(
40869
41388
  "--since <iso-or-duration>",
40870
- "Only spends since an ISO date (2026-07-01) or a duration (7d, 24h, 30m)"
41389
+ "Only spends since an ISO date (2026-07-01) or a duration (7d, 24h, 30m, 1h30m)"
40871
41390
  ).option("--limit <n>", "Max rows to show, newest first (default 50)").option("--offset <n>", "Skip rows in unchanged newest-first history (default 0)").option("--cursor <token>", "Continue history with the same filters; refuses changed local records").option("--endpoint <url>", "Only history at this endpoint origin").option("--kind <kind>", "Only job, float_fund, credit_fund, credit_draw, completed_refund, expired_credit_loss, or active_recovery rows").option("--human", "Human-readable table instead of JSON").action((opts) => {
40872
41391
  return catchErrors(() => {
40873
41392
  walletHistory(opts);
@@ -40945,7 +41464,7 @@ Docs:
40945
41464
  ).option("--all", "Empty the wallet (or the --mint mint) \u2014 fees come out of the balance").option("--mint <url>", "Cash out from this mint only (default: every mint, richest first)").option("--max-fee <sats>", "Refuse a mint whose routing reserve + input fee exceeds this").option("--dry-run", "Quote the melt and report the fee without paying anything").option("--human", "Human-readable output instead of JSON").action((destination, opts) => {
40946
41465
  return catchErrors(() => walletCashOut(destination, opts), opts.human);
40947
41466
  });
40948
- wallet.command("receive-token <token>").description("Claim an external Cashu token into the agent wallet as spendable balance").option("--human", "Human-readable output instead of JSON").action((token, opts) => {
41467
+ wallet.command("receive-token [token]").description("Claim an external Cashu token into the agent wallet. Omit token or use - to read stdin (recommended); positional tokens expose funds in shell history and process listings").option("--human", "Human-readable output instead of JSON").action((token, opts) => {
40949
41468
  return catchErrors(() => walletReceiveToken(token, opts), opts.human);
40950
41469
  });
40951
41470
  wallet.command("set-default-rail [rail]").description("Set the preferred rail for `dvm request` upfront payments (cashu, tempo, x402)").option("--clear", "Clear the persisted default rail").option("--human", "Human-readable output instead of JSON").action((rail, opts) => {
@@ -41111,7 +41630,7 @@ function collectOption(val, acc) {
41111
41630
  acc.push(val);
41112
41631
  return acc;
41113
41632
  }
41114
- if (process.argv[1] && realpathSync2(process.argv[1]) === fileURLToPath3(import.meta.url)) {
41633
+ if (process.argv[1] && realpathSync2(process.argv[1]) === fileURLToPath4(import.meta.url)) {
41115
41634
  installGlobalAcceptEncoding();
41116
41635
  await buildProgram().parseAsync();
41117
41636
  }