@dvmkit/dvm-cli 0.19.0 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dvm.js CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  DEFAULT_CREDIT_POSTURE,
12
12
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
13
13
  JOB_READ_TIMEOUT_MS,
14
+ MINT_QUOTE_EXPIRY_GRACE_MS,
14
15
  NWC_FUNDING_FLOAT_ROLE,
15
16
  SUBMISSION_EVIDENCE_DIR,
16
17
  abandonPendingSubmission,
@@ -113,6 +114,7 @@ import {
113
114
  maxSeq,
114
115
  meltInFlightTimeoutSeconds,
115
116
  midJobSpendLabel,
117
+ mintQuoteRefusal,
116
118
  mutateCreditPayment,
117
119
  needsTopup,
118
120
  nextStepHint,
@@ -151,6 +153,7 @@ import {
151
153
  receiptPieceContext,
152
154
  receiptSettlement,
153
155
  receiptTrustFields,
156
+ receiptUpfrontFault,
154
157
  reclaimIntentIds,
155
158
  reconcileInFlightPaymentRequest,
156
159
  reconcilePaymentRequestHistory,
@@ -205,6 +208,7 @@ import {
205
208
  updateJob,
206
209
  updateObservedJob,
207
210
  upfrontRailPayment,
211
+ upfrontReceiptFields,
208
212
  usdMicro,
209
213
  walletHistory,
210
214
  walletInvoiceFundingAdvice,
@@ -212,8 +216,9 @@ import {
212
216
  withAcceptedUnresolved,
213
217
  withIdentityRecovery,
214
218
  withJobTokenRedaction,
215
- withRequestResultRecovery
216
- } from "./chunk-J3HYNDMI.js";
219
+ withRequestResultRecovery,
220
+ withoutPendingMint
221
+ } from "./chunk-5ZY5IKS2.js";
217
222
  import {
218
223
  connectedTempoAccount,
219
224
  generateTempoKey,
@@ -266,8 +271,9 @@ import {
266
271
  staleRateNotice,
267
272
  tryResolveBtcUsdRate,
268
273
  tryX402Payment,
274
+ withOutputWarningContext,
269
275
  withOutputWarnings
270
- } from "./chunk-DJDONOMG.js";
276
+ } from "./chunk-7HJ5ZR3D.js";
271
277
  import {
272
278
  assertX402WalletIdle
273
279
  } from "./chunk-B5KW2TPR.js";
@@ -9008,19 +9014,180 @@ function formatPaidAmount(result, fiat) {
9008
9014
  return formatPaymentAmount(result.amountMsats, fiat, { anchor: false });
9009
9015
  }
9010
9016
 
9017
+ // src/lib/request-intent-store.ts
9018
+ var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
9019
+ import {
9020
+ closeSync,
9021
+ existsSync,
9022
+ fsyncSync,
9023
+ mkdirSync,
9024
+ openSync,
9025
+ readFileSync,
9026
+ renameSync,
9027
+ writeFileSync
9028
+ } from "fs";
9029
+ import { join } from "path";
9030
+ function saveRequestIntent(intent) {
9031
+ assertRequestId(intent.requestId);
9032
+ assertNoPaymentOrAuthSecrets(intent.body);
9033
+ ensureConfigSubdir(REQUEST_INTENTS_DIR);
9034
+ const dir = intentDirectory(intent.requestId);
9035
+ try {
9036
+ mkdirSync(dir, { mode: 448 });
9037
+ } catch (error) {
9038
+ if (error.code === "EEXIST") return false;
9039
+ throw error;
9040
+ }
9041
+ fsyncDirectory(REQUEST_INTENTS_DIR);
9042
+ const temp = join(dir, `intent.${String(process.pid)}.tmp`);
9043
+ const target = join(dir, "intent.json");
9044
+ const fd = openSync(temp, "wx", 384);
9045
+ try {
9046
+ writeFileSync(fd, JSON.stringify(intent, null, 2) + "\n");
9047
+ fsyncSync(fd);
9048
+ } finally {
9049
+ closeSync(fd);
9050
+ }
9051
+ renameSync(temp, target);
9052
+ fsyncDirectory(dir);
9053
+ return true;
9054
+ }
9055
+ function loadRequestIntent(requestId) {
9056
+ assertRequestId(requestId);
9057
+ const dir = intentDirectory(requestId);
9058
+ if (!existsSync(dir)) return null;
9059
+ const path = join(dir, "intent.json");
9060
+ try {
9061
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
9062
+ if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
9063
+ throw new Error("invalid shape");
9064
+ return parsed;
9065
+ } catch (error) {
9066
+ throw new DvmError(
9067
+ "request_intent_unreadable",
9068
+ `The saved request intent for ${requestId} is incomplete or unreadable.`,
9069
+ "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.",
9070
+ { request_id: requestId, cause: error instanceof Error ? error.message : String(error) }
9071
+ );
9072
+ }
9073
+ }
9074
+ function recordRequestRailPayment(requestId, payment) {
9075
+ assertRequestId(requestId);
9076
+ if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
9077
+ const dir = intentDirectory(requestId);
9078
+ const target = join(dir, "intent.json");
9079
+ const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
9080
+ try {
9081
+ const intent = loadRequestIntent(requestId);
9082
+ if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
9083
+ if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
9084
+ throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
9085
+ const temp = join(dir, `rail.${String(process.pid)}.tmp`);
9086
+ const fd = openSync(temp, "w", 384);
9087
+ try {
9088
+ writeFileSync(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
9089
+ fsyncSync(fd);
9090
+ } finally {
9091
+ closeSync(fd);
9092
+ }
9093
+ renameSync(temp, target);
9094
+ fsyncDirectory(dir);
9095
+ } finally {
9096
+ release();
9097
+ }
9098
+ }
9099
+ function assertNoPaymentOrAuthSecrets(body) {
9100
+ if (!containsForbiddenSecret(body)) return;
9101
+ throw new DvmError(
9102
+ "request_intent_contains_secret",
9103
+ "Request recovery cannot persist a payment credential, bearer token, or request auth signature.",
9104
+ "No payment was attempted. Remove the secret-bearing input or omit --request-id."
9105
+ );
9106
+ }
9107
+ function containsForbiddenSecret(value) {
9108
+ if (typeof value === "string") return /^Bearer\s/i.test(value);
9109
+ if (!value || typeof value !== "object") return false;
9110
+ if (Array.isArray(value)) return value.some(containsForbiddenSecret);
9111
+ const record2 = value;
9112
+ if (["pubkey", "timestamp", "nonce", "signature"].every((key) => Object.hasOwn(record2, key))) {
9113
+ return true;
9114
+ }
9115
+ const forbidden = /* @__PURE__ */ new Set([
9116
+ "authorization",
9117
+ "bearer_token",
9118
+ "access_token",
9119
+ "cashu_token",
9120
+ "x402_payment",
9121
+ "tempo_credential"
9122
+ ]);
9123
+ return Object.entries(record2).some(
9124
+ ([key, child]) => forbidden.has(key.toLowerCase()) || containsForbiddenSecret(child)
9125
+ );
9126
+ }
9127
+ function assertRequestId(requestId) {
9128
+ if (isPublicRequestId(requestId)) return;
9129
+ throw new DvmError(
9130
+ "invalid_request_id",
9131
+ "Invalid request id.",
9132
+ "Use 1\u2013128 characters: letters, digits, dot, underscore, colon, or hyphen."
9133
+ );
9134
+ }
9135
+ function intentDirectory(requestId) {
9136
+ return join(REQUEST_INTENTS_DIR, requestId);
9137
+ }
9138
+ function fsyncDirectory(path) {
9139
+ if (process.platform === "win32") return;
9140
+ let fd;
9141
+ try {
9142
+ fd = openSync(path, "r");
9143
+ fsyncSync(fd);
9144
+ } finally {
9145
+ if (fd !== void 0) closeSync(fd);
9146
+ }
9147
+ }
9148
+ function isRequestIntent(value) {
9149
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
9150
+ const candidate = value;
9151
+ 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;
9152
+ }
9153
+ function isSignedRequestAudience(value) {
9154
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
9155
+ const candidate = value;
9156
+ return typeof candidate.dvm_id === "string" && typeof candidate.builder_pubkey === "string";
9157
+ }
9158
+
9159
+ // src/lib/upfront-credit-error.ts
9160
+ function unknownUpfrontCreditError(job, message2) {
9161
+ const reason = job.upfrontCreditConflictReason;
9162
+ const requestId = job.requestId;
9163
+ let recovery;
9164
+ if (requestId && loadRequestIntent(requestId))
9165
+ recovery = `Run \`dvm request-result ${shellQuoteArg(requestId)}\` to recover the accepted upfront amount; it reads only and sends no payment.`;
9166
+ else if (requestId)
9167
+ recovery = `Request ${requestId} has no stored intent on this machine, so \`dvm request-result\` cannot recover it. Restore the caller state that submitted it.`;
9168
+ else
9169
+ recovery = "This job has no stored request id, so `dvm request-result` cannot recover it. Restore the caller state that submitted it.";
9170
+ return new DvmError(
9171
+ "upfront_credit_unknown",
9172
+ `${message2}${reason ? ` Cause: ${reason}.` : ""}`,
9173
+ `${recovery} Do not edit the local job store.`,
9174
+ { ...reason ? { reason } : {}, ...requestId ? { request_id: requestId } : {} }
9175
+ );
9176
+ }
9177
+
9011
9178
  // src/lib/credit-payment.ts
9012
9179
  import { randomUUID } from "crypto";
9013
9180
 
9014
9181
  // src/lib/caller-version.ts
9015
- import { existsSync, readFileSync } from "fs";
9016
- import { dirname, join } from "path";
9182
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
9183
+ import { dirname, join as join2 } from "path";
9017
9184
  import { fileURLToPath } from "url";
9018
9185
  var CALLER_VERSION = readCallerVersion();
9019
9186
  function readCallerVersion() {
9020
9187
  let dir = dirname(fileURLToPath(import.meta.url));
9021
9188
  for (; ; ) {
9022
- const manifestPath = join(dir, "package.json");
9023
- if (existsSync(manifestPath)) {
9189
+ const manifestPath = join2(dir, "package.json");
9190
+ if (existsSync2(manifestPath)) {
9024
9191
  const manifest = readManifest(manifestPath);
9025
9192
  if (manifest.name === "@dvmkit/dvm-cli") return manifest.version;
9026
9193
  }
@@ -9032,7 +9199,7 @@ function readCallerVersion() {
9032
9199
  }
9033
9200
  }
9034
9201
  function readManifest(path) {
9035
- return JSON.parse(readFileSync(path, "utf8"));
9202
+ return JSON.parse(readFileSync2(path, "utf8"));
9036
9203
  }
9037
9204
 
9038
9205
  // src/lib/client-compatibility.ts
@@ -9209,9 +9376,9 @@ async function readBoundedBody(response, limit) {
9209
9376
  var MAX_COMPATIBILITY_BODY_BYTES = 16384;
9210
9377
 
9211
9378
  // src/lib/credit-suggestion-cooldown.ts
9212
- import { existsSync as existsSync2, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync } from "fs";
9213
- import { join as join2 } from "path";
9214
- var CREDIT_SUGGESTIONS_FILE = join2(CONFIG_DIR, "credit-suggestions.json");
9379
+ import { existsSync as existsSync3, readFileSync as readFileSync3, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
9380
+ import { join as join3 } from "path";
9381
+ var CREDIT_SUGGESTIONS_FILE = join3(CONFIG_DIR, "credit-suggestions.json");
9215
9382
  var CREDIT_SUGGESTION_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1e3;
9216
9383
  function creditSuggestionDue(endpoint, now = Date.now()) {
9217
9384
  const shownAt = loadState()[normalizeCreditEndpoint(endpoint)];
@@ -9228,9 +9395,9 @@ function recordCreditSuggestionShown(endpoint, now = Date.now()) {
9228
9395
  }
9229
9396
  }
9230
9397
  function loadState() {
9231
- if (!existsSync2(CREDIT_SUGGESTIONS_FILE)) return {};
9398
+ if (!existsSync3(CREDIT_SUGGESTIONS_FILE)) return {};
9232
9399
  try {
9233
- const parsed = JSON.parse(readFileSync2(CREDIT_SUGGESTIONS_FILE, "utf-8"));
9400
+ const parsed = JSON.parse(readFileSync3(CREDIT_SUGGESTIONS_FILE, "utf-8"));
9234
9401
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
9235
9402
  return Object.fromEntries(
9236
9403
  Object.entries(parsed).filter((entry) => typeof entry[1] === "string")
@@ -9242,9 +9409,9 @@ function loadState() {
9242
9409
  function saveState(state) {
9243
9410
  ensureConfigDir();
9244
9411
  const tmp = `${CREDIT_SUGGESTIONS_FILE}.${process.pid}.tmp`;
9245
- writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
9412
+ writeFileSync2(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
9246
9413
  try {
9247
- renameSync(tmp, CREDIT_SUGGESTIONS_FILE);
9414
+ renameSync2(tmp, CREDIT_SUGGESTIONS_FILE);
9248
9415
  } catch (err) {
9249
9416
  try {
9250
9417
  unlinkSync(tmp);
@@ -9894,7 +10061,7 @@ async function tryCreditPayment(args) {
9894
10061
  throw new DvmError("upfront_rail_unknown", "Recover the original upfront rail charge before another balance payment.");
9895
10062
  const ask = request2.credit;
9896
10063
  if (job && hasUnknownUpfrontCredit(job))
9897
- throw new DvmError("upfront_credit_unknown", "The original upfront credit debit must be recovered before another balance payment.");
10064
+ throw unknownUpfrontCreditError(job, "The original upfront credit debit must be recovered before another balance payment.");
9898
10065
  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;
9899
10066
  const signer = findSigningIdentityByPubkey(job.creditBinding.callerPubkey);
9900
10067
  if (!signer) return false;
@@ -11400,148 +11567,6 @@ function parseTempoNetwork(value, source) {
11400
11567
  );
11401
11568
  }
11402
11569
 
11403
- // src/lib/request-intent-store.ts
11404
- var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
11405
- import {
11406
- closeSync,
11407
- existsSync as existsSync3,
11408
- fsyncSync,
11409
- mkdirSync,
11410
- openSync,
11411
- readFileSync as readFileSync3,
11412
- renameSync as renameSync2,
11413
- writeFileSync as writeFileSync2
11414
- } from "fs";
11415
- import { join as join3 } from "path";
11416
- function saveRequestIntent(intent) {
11417
- assertRequestId(intent.requestId);
11418
- assertNoPaymentOrAuthSecrets(intent.body);
11419
- ensureConfigSubdir(REQUEST_INTENTS_DIR);
11420
- const dir = intentDirectory(intent.requestId);
11421
- try {
11422
- mkdirSync(dir, { mode: 448 });
11423
- } catch (error) {
11424
- if (error.code === "EEXIST") return false;
11425
- throw error;
11426
- }
11427
- fsyncDirectory(REQUEST_INTENTS_DIR);
11428
- const temp = join3(dir, `intent.${String(process.pid)}.tmp`);
11429
- const target = join3(dir, "intent.json");
11430
- const fd = openSync(temp, "wx", 384);
11431
- try {
11432
- writeFileSync2(fd, JSON.stringify(intent, null, 2) + "\n");
11433
- fsyncSync(fd);
11434
- } finally {
11435
- closeSync(fd);
11436
- }
11437
- renameSync2(temp, target);
11438
- fsyncDirectory(dir);
11439
- return true;
11440
- }
11441
- function loadRequestIntent(requestId) {
11442
- assertRequestId(requestId);
11443
- const dir = intentDirectory(requestId);
11444
- if (!existsSync3(dir)) return null;
11445
- const path = join3(dir, "intent.json");
11446
- try {
11447
- const parsed = JSON.parse(readFileSync3(path, "utf8"));
11448
- if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
11449
- throw new Error("invalid shape");
11450
- return parsed;
11451
- } catch (error) {
11452
- throw new DvmError(
11453
- "request_intent_unreadable",
11454
- `The saved request intent for ${requestId} is incomplete or unreadable.`,
11455
- "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.",
11456
- { request_id: requestId, cause: error instanceof Error ? error.message : String(error) }
11457
- );
11458
- }
11459
- }
11460
- function recordRequestRailPayment(requestId, payment) {
11461
- assertRequestId(requestId);
11462
- if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
11463
- const dir = intentDirectory(requestId);
11464
- const target = join3(dir, "intent.json");
11465
- const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
11466
- try {
11467
- const intent = loadRequestIntent(requestId);
11468
- if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
11469
- if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
11470
- throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
11471
- const temp = join3(dir, `rail.${String(process.pid)}.tmp`);
11472
- const fd = openSync(temp, "w", 384);
11473
- try {
11474
- writeFileSync2(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
11475
- fsyncSync(fd);
11476
- } finally {
11477
- closeSync(fd);
11478
- }
11479
- renameSync2(temp, target);
11480
- fsyncDirectory(dir);
11481
- } finally {
11482
- release();
11483
- }
11484
- }
11485
- function assertNoPaymentOrAuthSecrets(body) {
11486
- if (!containsForbiddenSecret(body)) return;
11487
- throw new DvmError(
11488
- "request_intent_contains_secret",
11489
- "Request recovery cannot persist a payment credential, bearer token, or request auth signature.",
11490
- "No payment was attempted. Remove the secret-bearing input or omit --request-id."
11491
- );
11492
- }
11493
- function containsForbiddenSecret(value) {
11494
- if (typeof value === "string") return /^Bearer\s/i.test(value);
11495
- if (!value || typeof value !== "object") return false;
11496
- if (Array.isArray(value)) return value.some(containsForbiddenSecret);
11497
- const record2 = value;
11498
- if (["pubkey", "timestamp", "nonce", "signature"].every((key) => Object.hasOwn(record2, key))) {
11499
- return true;
11500
- }
11501
- const forbidden = /* @__PURE__ */ new Set([
11502
- "authorization",
11503
- "bearer_token",
11504
- "access_token",
11505
- "cashu_token",
11506
- "x402_payment",
11507
- "tempo_credential"
11508
- ]);
11509
- return Object.entries(record2).some(
11510
- ([key, child]) => forbidden.has(key.toLowerCase()) || containsForbiddenSecret(child)
11511
- );
11512
- }
11513
- function assertRequestId(requestId) {
11514
- if (isPublicRequestId(requestId)) return;
11515
- throw new DvmError(
11516
- "invalid_request_id",
11517
- "Invalid request id.",
11518
- "Use 1\u2013128 characters: letters, digits, dot, underscore, colon, or hyphen."
11519
- );
11520
- }
11521
- function intentDirectory(requestId) {
11522
- return join3(REQUEST_INTENTS_DIR, requestId);
11523
- }
11524
- function fsyncDirectory(path) {
11525
- if (process.platform === "win32") return;
11526
- let fd;
11527
- try {
11528
- fd = openSync(path, "r");
11529
- fsyncSync(fd);
11530
- } finally {
11531
- if (fd !== void 0) closeSync(fd);
11532
- }
11533
- }
11534
- function isRequestIntent(value) {
11535
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
11536
- const candidate = value;
11537
- 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;
11538
- }
11539
- function isSignedRequestAudience(value) {
11540
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
11541
- const candidate = value;
11542
- return typeof candidate.dvm_id === "string" && typeof candidate.builder_pubkey === "string";
11543
- }
11544
-
11545
11570
  // src/lib/payment-responder.ts
11546
11571
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11547
11572
  const seq = opts?.requestSeq;
@@ -11711,11 +11736,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11711
11736
  "Recover the original job price before authorizing more payments."
11712
11737
  );
11713
11738
  if (job && hasUnknownUpfrontCredit(job))
11714
- throw new DvmError(
11715
- "upfront_credit_unknown",
11716
- "The original upfront credit debit is unknown or conflicting.",
11717
- "Recover the accepted upfront amount with 'dvm request-result' before authorizing more payments."
11718
- );
11739
+ throw unknownUpfrontCreditError(job, "The original upfront credit debit is unknown or conflicting.");
11719
11740
  const pinnedMint = job?.pinnedMint;
11720
11741
  const strictPerCall = job?.strictPerCall === true;
11721
11742
  const maxCashuFeeSats = job?.maxCashuFeeSats;
@@ -11882,7 +11903,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11882
11903
  }
11883
11904
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11884
11905
  const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-2M3H75UP.js");
11885
- const { tryX402Payment: tryX402Payment2 } = await import("./client-S3FEXAWD.js");
11906
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-PY4T2DOA.js");
11886
11907
  const wallet = loadX402Wallet2();
11887
11908
  if (wallet) {
11888
11909
  let proof;
@@ -12393,7 +12414,7 @@ function refundNextAction(jobId, claims) {
12393
12414
  reason: claim.reason,
12394
12415
  claimed: false,
12395
12416
  cashu_token: claim.cashu_token,
12396
- 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).`
12417
+ 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).`
12397
12418
  }, ["amount_msats", "reason", "cashu_token"]);
12398
12419
  }
12399
12420
  return providerFields({
@@ -12427,7 +12448,7 @@ function refundSummaryHuman(claim) {
12427
12448
  if (claim.claimed) {
12428
12449
  return `Claimed ${noun} of ${formatAmountBestEffort(claim.amount_msats)} into your wallet.`;
12429
12450
  }
12430
- 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}`;
12451
+ 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.`;
12431
12452
  }
12432
12453
  function cap(s) {
12433
12454
  return s.charAt(0).toUpperCase() + s.slice(1);
@@ -13266,7 +13287,7 @@ var HttpsTransport = class {
13266
13287
  ...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {},
13267
13288
  ...feedbackClaim ? { feedbackClaim } : {},
13268
13289
  ...parseFundingResponse(data),
13269
- upfrontPayment: parseUpfrontPayment(data.upfront_payment)
13290
+ ...upfrontReceiptFields(data.upfront_payment)
13270
13291
  };
13271
13292
  }
13272
13293
  return {
@@ -13282,7 +13303,7 @@ var HttpsTransport = class {
13282
13303
  ...feedbackClaim ? { feedbackClaim } : {},
13283
13304
  ...parseSignedReceipt(data.receipt),
13284
13305
  ...parseFundingResponse(data),
13285
- upfrontPayment: parseUpfrontPayment(data.upfront_payment)
13306
+ ...upfrontReceiptFields(data.upfront_payment)
13286
13307
  };
13287
13308
  }
13288
13309
  async requestResult(provider, requestId, signedJob) {
@@ -13793,7 +13814,7 @@ function parseRequestResultResponse(value, requestId, httpStatus) {
13793
13814
  ...typeof data.job_token === "string" ? { jobToken: data.job_token } : {},
13794
13815
  ...receipt ? { receipt } : {},
13795
13816
  ...parseFundingResponse(data),
13796
- upfrontPayment: parseUpfrontPayment(data.upfront_payment)
13817
+ ...upfrontReceiptFields(data.upfront_payment)
13797
13818
  };
13798
13819
  }
13799
13820
  function malformedRequestResult(requestId, reason) {
@@ -14711,7 +14732,7 @@ async function settleCreditAfterJob(args) {
14711
14732
  }
14712
14733
  }
14713
14734
  if (args.allowTopup !== false) {
14714
- const refill = args.refillPocket ?? (await import("./pocket-refill-KUBHM7MR.js")).refillPocketIfLow;
14735
+ const refill = args.refillPocket ?? (await import("./pocket-refill-ETV6QWO6.js")).refillPocketIfLow;
14715
14736
  await refill({ human: args.human }).catch(() => void 0);
14716
14737
  }
14717
14738
  }
@@ -22016,9 +22037,9 @@ function cashuOptions(mints, hasLightningBackend) {
22016
22037
  const receiveTokenOption = {
22017
22038
  method: "cashu-receive-token",
22018
22039
  display: "Receive an existing Cashu token",
22019
- command: "dvm wallet receive-token <cashu-token>",
22040
+ command: "dvm wallet receive-token",
22020
22041
  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.",
22021
- hint: "Tokens are single-use; a token locked to a third party can't be claimed.",
22042
+ 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.",
22022
22043
  ...hasMints ? { mints } : {}
22023
22044
  };
22024
22045
  const options = [];
@@ -25672,6 +25693,61 @@ function formatBytes(bytes) {
25672
25693
  return `${bytes.toLocaleString("en-US")} bytes`;
25673
25694
  }
25674
25695
 
25696
+ // src/lib/unanswered-payment.ts
25697
+ import { isDeepStrictEqual } from "util";
25698
+ async function readUnansweredPaymentRequest(jobId, status2, access, transport, options = {}) {
25699
+ if (status2 !== "cancelled") return void 0;
25700
+ const job = access.endpointOverridden ? void 0 : loadJob(jobId);
25701
+ if (job?.callerCancelled) return void 0;
25702
+ const retained = job?.unansweredPaymentEvidence;
25703
+ const local = job ? loadMessages(jobId) : [];
25704
+ let history = options.messages ?? [];
25705
+ const hasPaymentContext = (job?.policy?.maxPayments ?? 0) > 0 || retained !== void 0 || [...local, ...history].some((message2) => message2.from === "provider" && message2.type === "payment-request");
25706
+ if (hasPaymentContext && !options.localOnly && !options.fullHistory) {
25707
+ try {
25708
+ history = await transport.getMessages(jobId, 0, access.ref, {
25709
+ jobToken: access.jobToken,
25710
+ timeoutMs: options.timeoutMs ?? 5e3
25711
+ });
25712
+ } catch {
25713
+ }
25714
+ }
25715
+ const log = [...new Map([
25716
+ ...retained ? [retained.request, retained.cancellation] : [],
25717
+ ...local,
25718
+ ...history
25719
+ ].map((message2) => [message2.seq, message2])).values()].sort((a, b) => a.seq - b.seq);
25720
+ const answered = answeredYieldSeqs(log);
25721
+ if (job) for (const seq of loadAnsweredYieldSeqs(jobId)) answered.add(seq);
25722
+ const evidence = unansweredPaymentEvidence(log, answered, job);
25723
+ if (job && !isDeepStrictEqual(retained, evidence)) updateObservedJob(jobId, { unansweredPaymentEvidence: evidence });
25724
+ if (!evidence) return void 0;
25725
+ const ask = evidence.request;
25726
+ const expiresAtMs = ask.content.expires_at_ms;
25727
+ const amount = formatPaymentAmount(ask.content.amount_msats, ask.content.fiat_amount, { anchor: false });
25728
+ return providerFields({
25729
+ seq: ask.seq,
25730
+ amount_msats: ask.content.amount_msats,
25731
+ ...ask.content.fiat_amount ? { fiat_amount: ask.content.fiat_amount } : {},
25732
+ ...ask.content.credit ? { credit: ask.content.credit } : {},
25733
+ reason: asProviderText(ask.content.reason),
25734
+ expires_at_ms: expiresAtMs,
25735
+ display: `The job appears to have stopped because payment ask #${ask.seq} went unanswered by its deadline (${new Date(expiresAtMs).toISOString()}). The provider asked for ${amount}, reason: ${JSON.stringify(ask.content.reason)}. Only charges paid before this ask were taken. Cancellation timestamps have one-second precision and do not establish when useful work stopped.`
25736
+ }, ["seq", "amount_msats", "fiat_amount", "credit", "expires_at_ms"]);
25737
+ }
25738
+ function unansweredPaymentEvidence(log, answered, job) {
25739
+ const ask = log.findLast((message2) => message2.from === "provider" && message2.type === "payment-request");
25740
+ if (ask?.type !== "payment-request" || ask.content.amount_msats <= 0) return void 0;
25741
+ if (answered.has(ask.seq)) return void 0;
25742
+ if (job?.inFlightPaymentRequestSeqs?.includes(ask.seq) || job?.unconfirmedPaymentSubmissions?.[ask.seq] || job?.askPaymentBlocks?.[ask.seq] || job?.pendingCreditPayment?.authorization.request_seq === ask.seq) return void 0;
25743
+ const expiresAtMs = ask.content.expires_at_ms;
25744
+ if (typeof expiresAtMs !== "number" || !Number.isSafeInteger(expiresAtMs) || expiresAtMs < 0 || expiresAtMs > 864e13) return void 0;
25745
+ const ending = log.findLast((message2) => message2.type === "cancel" || message2.type === "complete");
25746
+ if (ending?.type !== "cancel" || ending.from !== "provider" || ending.seq <= ask.seq || !Number.isFinite(ending.timestamp) || ending.timestamp < Math.floor(expiresAtMs / 1e3)) return void 0;
25747
+ if (log.some((message2) => message2.seq > ask.seq && message2.seq < ending.seq && (message2.from === "provider" && message2.type === "working" || message2.from === "requester" && (message2.type === "decline" || message2.type === "cancel")))) return void 0;
25748
+ return { request: ask, cancellation: ending };
25749
+ }
25750
+
25675
25751
  // src/lib/message-human.ts
25676
25752
  function paymentAmount(msg) {
25677
25753
  if (msg.from === "requester" && msg.content.credit) {
@@ -26109,9 +26185,16 @@ async function messagesWithAccess(jobId, opts, access) {
26109
26185
  const resolvedAction2 = await resolveNextAction2(nextAction, msgs, providerStatus2?.status);
26110
26186
  const currency2 = access.endpointOverridden ? await providerCurrency({ receipt: providerStatus2?.receipt, status: providerStatus2, messages: msgs, transport, ref }) : void 0;
26111
26187
  const settlement2 = await observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden, currency2);
26188
+ const unanswered2 = await readUnansweredPaymentRequest(jobId, providerStatus2?.status ?? (access.endpointOverridden ? void 0 : loadJob(jobId)?.status), access, transport, {
26189
+ messages: msgs,
26190
+ fullHistory: after === 0,
26191
+ localOnly: isTerminal || providerStatus2?.content_available === false,
26192
+ timeoutMs: timeout
26193
+ });
26112
26194
  transport.close();
26113
26195
  if (opts.human) {
26114
26196
  renderSettlementHuman(settlement2);
26197
+ if (unanswered2) info(unanswered2.display);
26115
26198
  info(String(content2.content_hint));
26116
26199
  if (msgs.length === 0) {
26117
26200
  info("No new messages.");
@@ -26127,6 +26210,7 @@ async function messagesWithAccess(jobId, opts, access) {
26127
26210
  jobId,
26128
26211
  ...content2,
26129
26212
  ...settlement2,
26213
+ ...unanswered2 ? { unanswered_payment_request: unanswered2 } : {},
26130
26214
  messages: msgs.map(serialize),
26131
26215
  cursor: newCursor,
26132
26216
  next_action: resolvedAction2,
@@ -26204,9 +26288,16 @@ async function messagesWithAccess(jobId, opts, access) {
26204
26288
  const observed = providerStatus ?? result.providerStatus;
26205
26289
  const currency = access.endpointOverridden ? await providerCurrency({ receipt: observed?.receipt, status: observed, messages: result.messages, transport, ref }) : void 0;
26206
26290
  const settlement = await observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
26291
+ const unanswered = await readUnansweredPaymentRequest(jobId, observed?.status ?? (access.endpointOverridden ? void 0 : loadJob(jobId)?.status), access, transport, {
26292
+ messages: result.messages,
26293
+ fullHistory: after === 0 && result.messages.some((message2) => message2.type === "cancel" || message2.type === "complete"),
26294
+ localOnly: isTerminal || observed?.content_available === false || waitDeadline !== void 0 && Date.now() >= waitDeadline,
26295
+ timeoutMs: waitDeadline === void 0 ? streamOptions.timeoutMs : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now()))
26296
+ });
26207
26297
  transport.close();
26208
26298
  if (opts.human) {
26209
26299
  renderSettlementHuman(settlement);
26300
+ if (unanswered) info(unanswered.display);
26210
26301
  info(String(content.content_hint));
26211
26302
  if (result.messages.length === 0) {
26212
26303
  info("No new messages.");
@@ -26224,6 +26315,7 @@ async function messagesWithAccess(jobId, opts, access) {
26224
26315
  jobId,
26225
26316
  ...content,
26226
26317
  ...settlement,
26318
+ ...unanswered ? { unanswered_payment_request: unanswered } : {},
26227
26319
  message_count: messageLines,
26228
26320
  auto_payment_count: paymentLines,
26229
26321
  cursor: result.cursor,
@@ -26235,6 +26327,7 @@ async function messagesWithAccess(jobId, opts, access) {
26235
26327
  jobId,
26236
26328
  ...content,
26237
26329
  ...settlement,
26330
+ ...unanswered ? { unanswered_payment_request: unanswered } : {},
26238
26331
  messages: result.messages.map(serialize),
26239
26332
  cursor: result.cursor,
26240
26333
  next_action: resolvedAction,
@@ -26705,15 +26798,19 @@ function parsePositiveCashuSats(raw2) {
26705
26798
  function positive(value) {
26706
26799
  return typeof value === "number" && Number.isFinite(value) && value > 0;
26707
26800
  }
26708
- function autoPayWarnings(quotes, limits, ceiling, btcRate = getLastKnownBtcRate()?.rate ?? 0) {
26801
+ function autoPayWarnings(quotes, limits, ceiling, btcRate = getLastKnownBtcRate()?.rate ?? 0, { upfrontCoveredByCredit = false } = {}) {
26709
26802
  if (!limits.budget && !limits.autoPayBelow) return [];
26710
26803
  if (!positive(btcRate)) {
26711
26804
  const quoted = quotes.find((quote2) => quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount) && positive(quote2.priceMsats));
26712
26805
  btcRate = getLastKnownBtcRate()?.rate ?? (quoted ? quoted.upfront.amount * 1e11 / quoted.priceMsats : 0);
26713
26806
  }
26714
26807
  const amounts = [];
26808
+ let excludedUpfront = false;
26715
26809
  for (const quote2 of quotes) {
26716
- if (quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount)) amounts.push(quote2.upfront.amount);
26810
+ if (quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount)) {
26811
+ if (upfrontCoveredByCredit) excludedUpfront = true;
26812
+ else amounts.push(quote2.upfront.amount);
26813
+ }
26717
26814
  const rate = quote2.rate;
26718
26815
  if (rate?.per_unit?.currency === "usd" && positive(rate.per_unit.amount) && positive(rate.max_units)) {
26719
26816
  const maximum2 = Number((rate.per_unit.amount * rate.max_units).toPrecision(15));
@@ -26721,7 +26818,7 @@ function autoPayWarnings(quotes, limits, ceiling, btcRate = getLastKnownBtcRate(
26721
26818
  }
26722
26819
  }
26723
26820
  let source = "quote";
26724
- if (!amounts.length && ceiling && typeof ceiling === "object") {
26821
+ if (!amounts.length && !excludedUpfront && ceiling && typeof ceiling === "object") {
26725
26822
  const max = ceiling;
26726
26823
  if (max.currency === "usd" && positive(max.amount)) {
26727
26824
  amounts.push(max.amount);
@@ -28210,8 +28307,6 @@ async function requestWithWarnings(opts, stage) {
28210
28307
  }
28211
28308
  const pricing = providerInfo.capabilities?.[capability]?.pricing;
28212
28309
  const warningLimits = { budget: effectiveBudget, autoPayBelow: effectiveAutoPayBelow };
28213
- const previewWarnings = autoPayWarnings(previewQuotes, warningLimits, pricing?.max ?? providerInfo.pricing?.max, btcRate);
28214
- addOutputWarnings(previewWarnings, opts.human);
28215
28310
  if (signing) {
28216
28311
  const signer = signing;
28217
28312
  const unsignedData = signing.unsignedData;
@@ -28290,6 +28385,15 @@ async function requestWithWarnings(opts, stage) {
28290
28385
  );
28291
28386
  }
28292
28387
  }
28388
+ const previewUpfrontCoveredByCredit = probePlan.mode === "draw";
28389
+ const previewWarnings = autoPayWarnings(
28390
+ previewQuotes,
28391
+ warningLimits,
28392
+ pricing?.max ?? providerInfo.pricing?.max,
28393
+ btcRate,
28394
+ { upfrontCoveredByCredit: previewUpfrontCoveredByCredit }
28395
+ );
28396
+ addOutputWarnings(previewWarnings, opts.human);
28293
28397
  let envelope = { ...envelopeBase, data };
28294
28398
  let jobRequestId = opts.requestId ?? drawRequestId;
28295
28399
  stage.intentReached = true;
@@ -28384,7 +28488,9 @@ async function requestWithWarnings(opts, stage) {
28384
28488
  transport.close();
28385
28489
  throw new DvmError("credit_only_unavailable", "The selected prepaid credit did not cover this submission; no fresh payment was attempted.");
28386
28490
  }
28387
- if (!previewWarnings.length) addOutputWarnings(autoPayWarnings(quotes, warningLimits, void 0, btcRate), opts.human);
28491
+ if (!previewWarnings.length || previewUpfrontCoveredByCredit) {
28492
+ addOutputWarnings(autoPayWarnings(quotes, warningLimits, void 0, btcRate), opts.human);
28493
+ }
28388
28494
  if (autoPayConsent && quotes.length > 0) {
28389
28495
  const pay2 = () => handleAutoPayQuotes(
28390
28496
  transport,
@@ -28461,14 +28567,19 @@ async function requestWithWarnings(opts, stage) {
28461
28567
  ...receiptTrustFields(providerInfo),
28462
28568
  ...localCorrelationJobFields(localCorrelationId)
28463
28569
  });
28464
- recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment);
28570
+ recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, false, receiptUpfrontFault(receipt));
28465
28571
  if (noStream && !isTerminalJobStatus(receipt.status)) {
28466
28572
  transport.close();
28573
+ const nextAction = pollNextAction(receipt.jobId);
28574
+ if (policy.maxPayments > 1) {
28575
+ const job = guidanceJobArg(receipt.jobId);
28576
+ nextAction.hint += ` Later payment asks are paid only while \`dvm messages ${job} --wait\` stays attached within the saved spending policy, or by running \`dvm pay ${job}\` for each ask. An unanswered payment ask ends the job. Neither \`dvm status ${job}\` nor \`dvm messages ${job} --no-stream\` pays later asks.`;
28577
+ }
28467
28578
  if (opts.human) {
28468
28579
  info(`Job published: ${receipt.jobId}`);
28469
28580
  echoTraceIdHuman();
28470
28581
  if (!isTerminalJobStatus(receipt.status)) {
28471
- printNextActionHuman(pollNextAction(receipt.jobId, "Job submitted, check back for updates"));
28582
+ printNextActionHuman(nextAction);
28472
28583
  }
28473
28584
  } else {
28474
28585
  providerJobJson({
@@ -28487,11 +28598,7 @@ async function requestWithWarnings(opts, stage) {
28487
28598
  // NOT drain here: nothing may stash a feedback notice before a
28488
28599
  // terminal, so there is nothing to carry.
28489
28600
  ...takeCreditNoticeFields(),
28490
- next_action: {
28491
- type: "poll",
28492
- job_id: receipt.jobId,
28493
- hint: "Job submitted, check back for updates"
28494
- }
28601
+ next_action: nextAction
28495
28602
  });
28496
28603
  }
28497
28604
  return;
@@ -30773,7 +30880,12 @@ async function readStdin() {
30773
30880
  async function requestResult(requestId, opts = {}) {
30774
30881
  return withOutputWarnings(() => requestResultWithWarnings(requestId, opts), opts.human);
30775
30882
  }
30776
- async function requestResultWithWarnings(requestId, opts) {
30883
+ function resolveRequestId(arg) {
30884
+ if (isPublicRequestId(arg) && loadRequestIntent(arg)) return arg;
30885
+ return loadJob(arg)?.requestId ?? arg;
30886
+ }
30887
+ async function requestResultWithWarnings(argument, opts) {
30888
+ const requestId = resolveRequestId(argument);
30777
30889
  if (!isPublicRequestId(requestId)) {
30778
30890
  throw new DvmError(
30779
30891
  "invalid_request_id",
@@ -30892,7 +31004,7 @@ async function requestResultWithWarnings(requestId, opts) {
30892
31004
  const free = existing?.upfrontRailPayment === "free" || accepted?.amount_msats === 0 && !method;
30893
31005
  recordUpfrontRailPayment(receipt.jobId, localPayment ?? (free ? "free" : accepted && method ? { method, amountMsats: accepted.amount_msats } : void 0));
30894
31006
  }
30895
- recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, originalData?.fund !== void 0);
31007
+ recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, originalData?.fund !== void 0, receiptUpfrontFault(receipt));
30896
31008
  if (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled") {
30897
31009
  markJobTerminal(receipt.jobId, receipt.status, completionSnapshot(receipt), restored);
30898
31010
  } else {
@@ -31395,10 +31507,12 @@ async function statusWithAccess(jobId, opts, access) {
31395
31507
  markJobTerminal(jobId, terminalStatus, completion2);
31396
31508
  }
31397
31509
  await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
31510
+ const unanswered2 = await readUnansweredPaymentRequest(jobId, terminalStatus, access, transport2, { localOnly: true });
31398
31511
  transport2.close();
31399
31512
  await renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
31400
31513
  receipt: receipt2,
31401
- content
31514
+ content,
31515
+ unanswered: unanswered2
31402
31516
  });
31403
31517
  return;
31404
31518
  }
@@ -31475,13 +31589,19 @@ async function statusWithAccess(jobId, opts, access) {
31475
31589
  if (newCursor !== void 0) updates.messageCursor = newCursor;
31476
31590
  if (Object.keys(updates).length > 0) updateObservedJob(jobId, updates);
31477
31591
  }
31592
+ const unanswered = await readUnansweredPaymentRequest(jobId, result.status, access, transport, {
31593
+ messages: msgs,
31594
+ timeoutMs: timeout,
31595
+ localOnly: result.content_available === false
31596
+ });
31478
31597
  transport.close();
31479
31598
  await renderStatus(jobId, stored, result.status, completion, "provider", nextAction, opts, {
31480
31599
  msgs,
31481
31600
  cursor: newCursor,
31482
31601
  receipt,
31483
31602
  content: result,
31484
- currency
31603
+ currency,
31604
+ unanswered
31485
31605
  });
31486
31606
  }
31487
31607
  function transientReceiptCapture(jobId, response, endpoint, currency) {
@@ -31523,6 +31643,7 @@ async function renderStatus(jobId, stored, jobStatus, completion, source, nextAc
31523
31643
  info(`Status: ${jobStatus}${identifier ? ` [${identifier}]` : ""}`);
31524
31644
  if (completion.message) info(` ${completion.message}`);
31525
31645
  }
31646
+ if (fetched?.unanswered) info(fetched.unanswered.display);
31526
31647
  if (artifacts.hint) info(`\u{1F4CE} ${artifacts.hint}`);
31527
31648
  info(String(content.content_hint));
31528
31649
  if (msgs.length > 0) {
@@ -31557,6 +31678,7 @@ ${msgs.length} new message(s):`);
31557
31678
  ...artifacts.fields,
31558
31679
  ...artifacts.display ? { display: artifacts.display } : {},
31559
31680
  ...completion.message ? { message: completion.message } : {},
31681
+ ...fetched?.unanswered ? { unanswered_payment_request: fetched.unanswered } : {},
31560
31682
  // terminal responses only. On a still-running job "absent" would
31561
31683
  // read as "this DVM doesn't issue receipts" rather than "not yet".
31562
31684
  ...receipt ? await receiptJsonFields(receipt) : {},
@@ -34111,9 +34233,13 @@ function examples(fetcher) {
34111
34233
  async function catchErrors(fn, human, jsonFields) {
34112
34234
  const lifetimeHold = setInterval(() => void 0, 60 * 60 * 1e3);
34113
34235
  try {
34114
- await fn();
34115
- } catch (err) {
34116
- handleError(err, human, jsonFields);
34236
+ await withOutputWarningContext(async () => {
34237
+ try {
34238
+ await fn();
34239
+ } catch (err) {
34240
+ handleError(err, human, jsonFields);
34241
+ }
34242
+ });
34117
34243
  } finally {
34118
34244
  clearInterval(lifetimeHold);
34119
34245
  }
@@ -34801,6 +34927,7 @@ async function walletFund(amount, opts) {
34801
34927
  info(`Quote ID: ${quote2.quote}`);
34802
34928
  if (expiresAt) info(`Invoice expires: ${expiresAt}`);
34803
34929
  info("After payment, run `dvm wallet show` to collect the sats and check the new balance.");
34930
+ info(` \u21B3 ${collectDeadlineHint(expiresAt)}`);
34804
34931
  } else {
34805
34932
  info(
34806
34933
  "Polling for payment every 2s; press Ctrl-C to bail (the quote will be recoverable on next run)."
@@ -34821,6 +34948,7 @@ async function walletFund(amount, opts) {
34821
34948
  qr_image_path: qrImagePath,
34822
34949
  relay: { copy_text: invoice, standalone: true },
34823
34950
  expires_at: expiresAt,
34951
+ ...opts.wait === false ? { collect_before: expiresAt } : {},
34824
34952
  lock_pubkey: wallet.lock_pubkey,
34825
34953
  display: `Pay ${sats} sats to the Lightning invoice to fund ${amountPhrase} into the agent wallet at ${mintUrl} (${selectionPhrase}). Scannable QR at ${qrImagePath}.`,
34826
34954
  ...opts.wait === false ? {
@@ -34829,7 +34957,7 @@ async function walletFund(amount, opts) {
34829
34957
  sweep: summarizeSweep(sweep),
34830
34958
  melt_sweep: summarizeMeltSweep(meltSweep)
34831
34959
  } : {},
34832
- hint: opts.wait === false ? "Forward the QR PNG (or raw invoice) to a human. After payment, run `dvm wallet show` to collect the sats and check the new balance. Funding is still pending." : "Forward the QR PNG (or raw invoice) to a human; the CLI will mint P2PK-locked Cashu proofs into ~/.dvm/wallet.json once paid."
34960
+ hint: opts.wait === false ? `Forward the QR PNG (or raw invoice) to a human. After payment, run \`dvm wallet show\` to collect the sats and check the new balance. ${collectDeadlineHint(expiresAt)} Funding is still pending.` : "Forward the QR PNG (or raw invoice) to a human; the CLI will mint P2PK-locked Cashu proofs into ~/.dvm/wallet.json once paid."
34833
34961
  });
34834
34962
  }
34835
34963
  };
@@ -34937,6 +35065,25 @@ function describeFloatOutcome(outcome) {
34937
35065
  }
34938
35066
  }
34939
35067
  async function walletReceiveToken(token, opts) {
35068
+ 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.";
35069
+ if (token === void 0 || token === "-") {
35070
+ if (process.stdin.isTTY) {
35071
+ throw new DvmError("no_input", "No Cashu token provided.", stdinHint);
35072
+ }
35073
+ try {
35074
+ token = (await drainStdin()).trim();
35075
+ } catch (err) {
35076
+ if (err instanceof StdinTimeoutError) {
35077
+ throw new DvmError("no_input", "No Cashu token provided (stdin timed out).", stdinHint);
35078
+ }
35079
+ throw err;
35080
+ }
35081
+ } else {
35082
+ 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.");
35083
+ }
35084
+ if (!token) {
35085
+ throw new DvmError("no_input", "No Cashu token provided.", stdinHint);
35086
+ }
34940
35087
  const result = await receiveToAgentWallet(token);
34941
35088
  if (opts.human) {
34942
35089
  info("");
@@ -34965,7 +35112,8 @@ async function walletShow(opts) {
34965
35112
  }
34966
35113
  await loadConfiguredMints();
34967
35114
  const sweep = await reconcilePendingMints();
34968
- const expiredMints = describeExpiredMints(sweep);
35115
+ const sweepSummary = summarizeSweep(sweep);
35116
+ const expiredMints = sweepSummary.expired;
34969
35117
  const meltSweep = await reconcilePendingMelts().catch(emptyMeltSweep);
34970
35118
  const inFlightSweepReverted = await sweepStaleInFlightUnderLock();
34971
35119
  const submissionSweep = await sweepPendingSubmissions({ fetchImpl: dvmFetch }).catch(() => ({
@@ -34987,6 +35135,11 @@ async function walletShow(opts) {
34987
35135
  (entry) => entry.state === "unreclaimable"
34988
35136
  );
34989
35137
  const unchecked = new Map(sweep.unchecked.map((u) => [u.quote_id, u]));
35138
+ const pendingNotes = new Map([
35139
+ ...sweepSummary.pending.map((p) => [p.quote_id, p.display]),
35140
+ ...sweepSummary.kept_past_expiry.map((p) => [p.quote_id, p.display]),
35141
+ ...sweepSummary.paid_uncollected.map((p) => [p.quote_id, p.display])
35142
+ ]);
34990
35143
  const inventory = buildDisplayMintInventory(post);
34991
35144
  const mintsToProbe = inventory.map((e) => e.url);
34992
35145
  const sources = new Map(inventory.map((e) => [e.url, e.source]));
@@ -35016,14 +35169,18 @@ async function walletShow(opts) {
35016
35169
  const recovered = sweep.recovered_proofs.reduce((sum, p) => sum + p.amount, 0);
35017
35170
  info(`Recovered ${recovered} sats from ${sweep.recovered_proofs.length} pending mint(s).`);
35018
35171
  }
35019
- for (const collected of summarizeSweep(sweep).collected) {
35172
+ for (const collected of sweepSummary.collected) {
35020
35173
  info(`${collected.display} Added ${collected.sats_collected} sats at ${collected.mint}.`);
35021
35174
  }
35022
35175
  for (const expired of expiredMints) {
35023
35176
  info(
35024
- `Unpaid mint quote expired: ${expired.amount_sats} sats at ${expired.mint} (quote ID ${expired.quote_id}) \u2014 local recovery entry removed.`
35177
+ `Unpaid mint quote expired: ${expired.amount_sats} sats at ${expired.mint} (quote ID ${expired.quote_id}) \u2014 ${describeDropReason(expired.reason)}; local recovery entry removed.`
35025
35178
  );
35026
35179
  }
35180
+ for (const refused of sweepSummary.paid_uncollected) {
35181
+ info(refused.display);
35182
+ info(` \u21B3 ${refused.hint}`);
35183
+ }
35027
35184
  reportUncheckedMints(sweep.unchecked);
35028
35185
  reportUncheckedMints(meltSweep.unchecked);
35029
35186
  if (inFlightSweepReverted > 0) {
@@ -35086,7 +35243,7 @@ async function walletShow(opts) {
35086
35243
  info("");
35087
35244
  info(`Pending mints: ${post.pending_mints.length}`);
35088
35245
  for (const p of post.pending_mints) {
35089
- info(` ${formatPending(p, unchecked.get(p.quote_id))}`);
35246
+ info(` ${formatPending(p, unchecked.get(p.quote_id), pendingNotes.get(p.quote_id))}`);
35090
35247
  }
35091
35248
  }
35092
35249
  if (pendingMelts.length > 0) {
@@ -35144,6 +35301,8 @@ async function walletShow(opts) {
35144
35301
  const totalUsd = railsSnapshot.reduce((sum, r) => sum + (r.json.balance_usd ?? 0), 0);
35145
35302
  const baseHint = pendingMeltSats > 0 ? `${pendingMeltSats} sats are committed to a cash-out the mint hasn't confirmed \u2014 see pending_melts. They stay unspendable until it resolves.` : submissions.at_risk_sats > 0 ? `${submissions.at_risk_sats} sats were paid to a DVM that never confirmed \u2014 see pending_submissions.` : railsSnapshot.length === 0 ? "Fund with: dvm wallet fund <amount> [--rail cashu|tempo]" : cashuSplit ? `${NON_FUNGIBLE_MINT_NOTE} Fund more with: dvm wallet fund <amount> [--rail cashu|tempo]` : "Fund more with: dvm wallet fund <amount> [--rail cashu|tempo]";
35146
35303
  const uncheckedHint = sweep.unchecked.length > 0 ? `${sweep.unchecked.length} pending mint(s) could not be checked against their mint on this call \u2014 see sweep.unchecked for the cause and how long to wait. They keep their pending state; don't fund the same invoice again.` : null;
35304
+ const refusedHint = sweepSummary.paid_uncollected.length > 0 ? `${sweepSummary.paid_uncollected.length} paid invoice(s) could not be collected because the mint refuses to issue after the quote expired \u2014 see sweep.paid_uncollected. Don't pay them again.` : null;
35305
+ const keptHint = sweepSummary.kept_past_expiry.length > 0 ? `${sweepSummary.kept_past_expiry.length} unpaid invoice(s) are past their expiry and still checked for a late payment \u2014 see sweep.kept_past_expiry for when each is removed.` : null;
35147
35306
  const stuckReclaims = skippedReclaimViews.filter((v) => !v.terminal);
35148
35307
  const deadReclaims = skippedReclaimViews.filter((v) => v.terminal);
35149
35308
  const unresolvedHint = unresolvedViews.length > 0 ? `${unresolvedViews.length} paid call(s) need attention: the provider accepted them without a clear job ID \u2014 see accepted_unresolved. Do not pay for them again.` : null;
@@ -35183,10 +35342,10 @@ async function walletShow(opts) {
35183
35342
  // paid calls the provider accepted without a settled job identity,
35184
35343
  // detected on this call or missing their evidence record.
35185
35344
  accepted_unresolved: unresolvedViews,
35186
- sweep: summarizeSweep(sweep),
35345
+ sweep: sweepSummary,
35187
35346
  melt_sweep: summarizeMeltSweep(meltSweep),
35188
35347
  display: railsSnapshot.length === 0 ? "Agent wallet is empty." : `${railsSnapshot.map((r) => r.json.display).join(" \u2014 ")} (~$${totalUsd.toFixed(2)} total)`,
35189
- hint: [uncheckedHint, unresolvedHint, resumedHint, baseHint].filter(Boolean).join(" ")
35348
+ hint: [refusedHint, uncheckedHint, keptHint, unresolvedHint, resumedHint, baseHint].filter(Boolean).join(" ")
35190
35349
  });
35191
35350
  }
35192
35351
  }
@@ -35493,10 +35652,25 @@ function formatFeePpk(fee) {
35493
35652
  if (fee === null) return "- (mint unreachable)";
35494
35653
  return `${fee} ppk`;
35495
35654
  }
35496
- function formatPending(p, unchecked) {
35655
+ function formatPending(p, unchecked, note) {
35497
35656
  const row = `${p.amount_sats} sats at ${p.mint} (quote ${p.quote_id}, requested ${p.requested_at})`;
35498
- return unchecked ? `${row}
35499
- \u21B3 ${uncheckedPendingNote(unchecked)}` : `${row} \u2014 not paid yet; awaiting payment`;
35657
+ if (unchecked) return `${row}
35658
+ \u21B3 ${uncheckedPendingNote(unchecked)}`;
35659
+ return note ? `${row}
35660
+ \u21B3 ${note}` : `${row} \u2014 not paid yet; awaiting payment`;
35661
+ }
35662
+ function collectDeadlineHint(expiresAt) {
35663
+ return expiresAt ? `Collect before ${expiresAt}: a mint can refuse to issue for a paid invoice once its quote has expired.` : "The mint named no expiry for this invoice; collect soon after payment.";
35664
+ }
35665
+ function describeDropReason(reason) {
35666
+ switch (reason) {
35667
+ case "mint_unknown":
35668
+ return "the mint no longer knows this quote";
35669
+ case "mint_expired":
35670
+ return "the mint reports it expired";
35671
+ case "grace_elapsed":
35672
+ return `the mint still reported it unpaid ${GRACE_HOURS} hours after it expired`;
35673
+ }
35500
35674
  }
35501
35675
  function reportUncheckedMints(unchecked) {
35502
35676
  for (const entry of unchecked) {
@@ -35541,13 +35715,45 @@ function summarizeMeltSweep(sweep) {
35541
35715
  unchecked: sweep.unchecked
35542
35716
  };
35543
35717
  }
35544
- function summarizeSweep(sweep) {
35718
+ function summarizeSweep(sweep, nowMs = Date.now()) {
35719
+ const waiting = sweep.outcomes.filter((o) => o.kind === "still_pending");
35545
35720
  return {
35546
- pending: sweep.still_pending.map((entry) => ({
35721
+ pending: waiting.filter((o) => o.past_expiry === void 0).map(({ entry }) => {
35722
+ const requestedAtMs = Date.parse(entry.requested_at);
35723
+ const forget = `dvm wallet forget-quote ${shellQuoteArg(entry.quote_id)}`;
35724
+ return {
35725
+ quote_id: entry.quote_id,
35726
+ mint: entry.mint,
35727
+ amount_sats: entry.amount_sats,
35728
+ requested_at: entry.requested_at,
35729
+ age_seconds: Number.isFinite(requestedAtMs) ? Math.max(0, Math.floor((nowMs - requestedAtMs) / 1e3)) : null,
35730
+ expires_at: entry.expires_at === void 0 ? null : new Date(entry.expires_at * 1e3).toISOString(),
35731
+ display: entry.expires_at === void 0 ? `Mint quote ${entry.quote_id} is not paid yet. The mint named no expiry, so it stays pending until it is paid or you forget it with \`${forget}\`.` : `Mint quote ${entry.quote_id} is not paid yet.`
35732
+ };
35733
+ }),
35734
+ // Unpaid quotes past their expiry. A late payment is still collected while
35735
+ // they are listed here.
35736
+ kept_past_expiry: waiting.flatMap(({ entry, past_expiry }) => {
35737
+ if (past_expiry === void 0) return [];
35738
+ const dropAfter = new Date(past_expiry.drop_after_ms).toISOString();
35739
+ return [{
35740
+ quote_id: entry.quote_id,
35741
+ mint: entry.mint,
35742
+ amount_sats: entry.amount_sats,
35743
+ expired_at: new Date(past_expiry.expired_at_ms).toISOString(),
35744
+ drop_after: dropAfter,
35745
+ display: `Mint quote ${entry.quote_id} expired unpaid. It is kept and checked for a late payment until ${dropAfter}.`,
35746
+ hint: `A payment that arrives late is collected by \`dvm wallet show\` if the mint credits it. Ask for a new invoice instead of paying this one; to stop tracking it now, run \`dvm wallet forget-quote ${shellQuoteArg(entry.quote_id)}\`.`
35747
+ }];
35748
+ }),
35749
+ // Paid, but the mint will not issue ecash for it. Never dropped by a sweep.
35750
+ paid_uncollected: sweep.refused.map((entry) => ({
35547
35751
  quote_id: entry.quote_id,
35548
35752
  mint: entry.mint,
35549
35753
  amount_sats: entry.amount_sats,
35550
- display: `Mint quote ${entry.quote_id} is not paid yet.`
35754
+ reason: "quote_expired",
35755
+ display: `Mint quote ${entry.quote_id} was paid (${entry.amount_sats} sats at ${entry.mint}), but the mint refuses to issue the sats because the quote expired before they were collected.`,
35756
+ hint: `The payment is recorded and \`dvm wallet show\` asks the mint again on every run. Don't pay it again. If the mint keeps refusing, its operator is the one who can release the payment: give them the quote ID. To stop tracking it, run \`dvm wallet forget-quote ${shellQuoteArg(entry.quote_id)} --force --yes\`.`
35551
35757
  })),
35552
35758
  collected: sweep.outcomes.flatMap(
35553
35759
  (outcome) => outcome.kind === "minted" || outcome.kind === "restored" ? [{
@@ -35566,12 +35772,17 @@ function summarizeSweep(sweep) {
35566
35772
  unchecked: sweep.unchecked
35567
35773
  };
35568
35774
  }
35775
+ var GRACE_HOURS = MINT_QUOTE_EXPIRY_GRACE_MS / 36e5;
35569
35776
  function describeExpiredMints(sweep) {
35570
- return sweep.outcomes.filter((outcome) => outcome.kind === "expired").map(({ entry }) => ({
35571
- quote_id: entry.quote_id,
35572
- mint: entry.mint,
35573
- amount_sats: entry.amount_sats
35574
- }));
35777
+ return sweep.outcomes.flatMap(
35778
+ (outcome) => outcome.kind === "expired" ? [{
35779
+ quote_id: outcome.entry.quote_id,
35780
+ mint: outcome.entry.mint,
35781
+ amount_sats: outcome.entry.amount_sats,
35782
+ reason: outcome.reason,
35783
+ display: `Unpaid mint quote ${outcome.entry.quote_id} was removed: ${describeDropReason(outcome.reason)}. A payment made to it now cannot be collected.`
35784
+ }] : []
35785
+ );
35575
35786
  }
35576
35787
  async function writeInvoicePng(invoice, outPath) {
35577
35788
  try {
@@ -39155,8 +39366,136 @@ async function walletSetDefaultRail(rail, opts) {
39155
39366
  }
39156
39367
  }
39157
39368
 
39158
- // src/commands/wallet-submissions.ts
39369
+ // src/commands/wallet-forget-quote.ts
39159
39370
  import { createInterface as createInterface4 } from "readline";
39371
+ async function walletForgetQuote(quoteId, opts) {
39372
+ const wallet = loadAgentWallet();
39373
+ if (!wallet) {
39374
+ throw new DvmError(
39375
+ "wallet_missing",
39376
+ "No agent wallet found.",
39377
+ "Run `dvm wallet init` first to generate a lock keypair."
39378
+ );
39379
+ }
39380
+ const entry = wallet.pending_mints.find((p) => p.quote_id === quoteId);
39381
+ if (!entry) {
39382
+ throw new DvmError(
39383
+ "mint_quote_not_found",
39384
+ `No pending mint quote with ID "${quoteId}".`,
39385
+ "List pending quotes with: dvm wallet show"
39386
+ );
39387
+ }
39388
+ const standing = await quoteStanding(entry);
39389
+ refuseIfCollectable(entry, standing, opts);
39390
+ await confirmForget(entry, standing, opts);
39391
+ await withWalletLock(() => {
39392
+ const fresh = loadAgentWallet() ?? wallet;
39393
+ saveAgentWallet(withoutPendingMint(fresh, quoteId));
39394
+ });
39395
+ const display = `Forgot mint quote ${quoteId} (${entry.amount_sats} sats at ${entry.mint}). ${forgottenConsequence(standing)}`;
39396
+ if (opts.human) {
39397
+ info(display);
39398
+ return;
39399
+ }
39400
+ json({
39401
+ status: "forgotten",
39402
+ quote_id: quoteId,
39403
+ mint: entry.mint,
39404
+ amount_sats: entry.amount_sats,
39405
+ mint_state: standing.state,
39406
+ display,
39407
+ hint: "The quote is gone from the wallet. This cannot be undone."
39408
+ });
39409
+ }
39410
+ async function quoteStanding(entry) {
39411
+ try {
39412
+ const cashuWallet = await getWallet(entry.mint);
39413
+ const quote2 = await cashuWallet.checkMintQuoteBolt11(entry.quote_id);
39414
+ if (quote2.state === sa.PAID) return { state: "paid" };
39415
+ if (quote2.state === sa.ISSUED) return { state: "issued" };
39416
+ if (quote2.state === sa.UNPAID) return { state: "unpaid" };
39417
+ if (quote2.state === "EXPIRED") return { state: "gone" };
39418
+ return { state: "unchecked", cause: "unexpected" };
39419
+ } catch (err) {
39420
+ if (mintQuoteRefusal(err) !== void 0) return { state: "gone" };
39421
+ return { state: "unchecked", cause: classifyMintError(err) };
39422
+ }
39423
+ }
39424
+ function refuseIfCollectable(entry, standing, opts) {
39425
+ if (opts.force) return;
39426
+ const forced = `dvm wallet forget-quote ${shellQuoteArg(entry.quote_id)} --yes --force`;
39427
+ const collectable = standing.state === "paid" || standing.state === "issued" && entry.minting !== void 0;
39428
+ if (collectable) {
39429
+ throw new DvmError(
39430
+ "mint_quote_collectable",
39431
+ `Mint quote ${entry.quote_id} is paid: ${entry.amount_sats} sats at ${entry.mint} are waiting to be collected.`,
39432
+ `Run \`dvm wallet show\` to collect them. Forgetting the quote gives up the only record that can; if the mint keeps refusing to issue and you accept that, add --force: ${forced}`
39433
+ );
39434
+ }
39435
+ if (standing.state === "unchecked") {
39436
+ throw new DvmError(
39437
+ "mint_quote_unchecked",
39438
+ `The mint did not say whether mint quote ${entry.quote_id} has been paid, so forgetting it could lose a payment.`,
39439
+ `Try again once the mint answers. To forget it without knowing, add --force: ${forced}`,
39440
+ { cause: standing.cause, retryable: standing.cause !== "unexpected" }
39441
+ );
39442
+ }
39443
+ }
39444
+ async function confirmForget(entry, standing, opts) {
39445
+ if (opts.yes) return;
39446
+ const consequence = forgetConsequence(standing);
39447
+ if (opts.human && process.stdin.isTTY) {
39448
+ const rl = createInterface4({ input: process.stdin, output: process.stderr });
39449
+ const answer = await new Promise((resolve3) => {
39450
+ rl.question(
39451
+ `Forgetting mint quote ${entry.quote_id} ${consequence}. Type the quote ID to confirm: `,
39452
+ (a) => {
39453
+ rl.close();
39454
+ resolve3(a.trim());
39455
+ }
39456
+ );
39457
+ });
39458
+ if (answer !== entry.quote_id) {
39459
+ throw new DvmError("cancelled", "Forget cancelled.");
39460
+ }
39461
+ return;
39462
+ }
39463
+ throw new DvmError(
39464
+ "confirmation_required",
39465
+ "Pass --yes to forget in non-interactive mode.",
39466
+ `This ${consequence}. Use: dvm wallet forget-quote ${shellQuoteArg(entry.quote_id)} --yes${opts.force ? " --force" : ""}`
39467
+ );
39468
+ }
39469
+ function forgetConsequence(standing) {
39470
+ switch (standing.state) {
39471
+ case "paid":
39472
+ case "issued":
39473
+ return "gives up the only record that can collect a payment the mint has already taken, so this cannot be undone";
39474
+ case "unchecked":
39475
+ return "removes the only record that can collect its payment, without knowing whether it was paid, so this cannot be undone";
39476
+ case "gone":
39477
+ return "clears a quote the mint no longer honors, so nothing collectable is lost, but this cannot be undone";
39478
+ case "unpaid":
39479
+ return "means a payment made to its invoice afterwards cannot be collected, so this cannot be undone";
39480
+ }
39481
+ }
39482
+ function forgottenConsequence(standing) {
39483
+ switch (standing.state) {
39484
+ case "paid":
39485
+ return "The mint reported it as paid; that payment can no longer be collected by this wallet.";
39486
+ case "issued":
39487
+ return "The mint reported it as already issued.";
39488
+ case "unchecked":
39489
+ return "The mint did not say whether it was paid; a payment for it can no longer be collected by this wallet.";
39490
+ case "gone":
39491
+ return "The mint no longer honors it, so nothing collectable was given up.";
39492
+ case "unpaid":
39493
+ return "It was unpaid. Do not pay its invoice now: that payment could not be collected.";
39494
+ }
39495
+ }
39496
+
39497
+ // src/commands/wallet-submissions.ts
39498
+ import { createInterface as createInterface5 } from "readline";
39160
39499
  async function walletSubmissions(opts) {
39161
39500
  if (opts.forget !== void 0) {
39162
39501
  await forgetSubmission(opts.forget, opts);
@@ -39255,7 +39594,7 @@ async function forgetSubmission(requestId, opts) {
39255
39594
  }
39256
39595
  refuseIfReclaimUnsaved(view, opts);
39257
39596
  refuseIfSelfHealing(view, opts);
39258
- await confirmForget(view, opts);
39597
+ await confirmForget2(view, opts);
39259
39598
  await abandonPendingSubmission({ requestId });
39260
39599
  clearReclaimIntent(requestId);
39261
39600
  const abandoned = view.at_risk ? view.amount_sats : 0;
@@ -39296,7 +39635,7 @@ function refuseIfSelfHealing(view, opts) {
39296
39635
  `Forgetting it throws those sats away for good. Leave it alone and it resolves on its own; if you really want it gone, add --force: dvm wallet submissions --forget ${view.request_id} --yes --force`
39297
39636
  );
39298
39637
  }
39299
- async function confirmForget(view, opts) {
39638
+ async function confirmForget2(view, opts) {
39300
39639
  if (opts.yes) return;
39301
39640
  const consequence = !view.at_risk ? `clears the journal entry for ${view.endpoint} (nothing was spent)` : view.state === "reclaimable" || view.state === "reclaim_failed" ? (
39302
39641
  // Worth spelling out: this is the one case where forgetting *costs* the
@@ -39305,7 +39644,7 @@ async function confirmForget(view, opts) {
39305
39644
  `throws away ${view.amount_sats} sats paid to ${view.endpoint} that the wallet can still reclaim by itself, so this cannot be undone`
39306
39645
  ) : view.state === "accepted_unresolved" ? `stops tracking ${view.amount_sats} sats paid to ${view.endpoint} for a call the provider accepted without a clear job ID${view.reclaim_at ? `, including the wallet's claim to take them back after ${view.reclaim_at} if the provider never redeems them` : ""}; the recorded evidence is kept, but this cannot be undone` : view.state === "unreclaimable" ? `clears ${view.amount_sats} sats paid to ${view.endpoint} that are too small to be worth taking back, so nothing recoverable is lost \u2014 but this cannot be undone` : `abandons ${view.amount_sats} sats paid to ${view.endpoint} \u2014 the proofs are locked to the provider with no refund, so this cannot be undone`;
39307
39646
  if (opts.human && process.stdin.isTTY) {
39308
- const rl = createInterface4({ input: process.stdin, output: process.stderr });
39647
+ const rl = createInterface5({ input: process.stdin, output: process.stderr });
39309
39648
  const answer = await new Promise((resolve3) => {
39310
39649
  rl.question(
39311
39650
  `Forgetting request ${view.request_id} ${consequence}. Type the request id to confirm: `,
@@ -40294,7 +40633,7 @@ function buildProgram() {
40294
40633
  ).option("--max-increment <amount>", "Max single payment (millisats or $USD)").option(
40295
40634
  "--max-payments <n>",
40296
40635
  "Max payments to honour per job (default: 5); 0 = free, 1 = typical, 3+ = multi-turn"
40297
- ).option("--output-type <mime>", "Desired output MIME type").option("--no-stream", "Submit and return immediately without streaming").option(
40636
+ ).option("--output-type <mime>", "Desired output MIME type").option("--no-stream", "Submit and return immediately; later asks need dvm messages <job> --wait or dvm pay <job>").option(
40298
40637
  "--auto-pay",
40299
40638
  "Pay without prompting, bounded by --auto-pay-below (else config autoPayThreshold, else 20% of --budget). Unnecessary when --auto-pay-below is set."
40300
40639
  ).option(
@@ -40321,7 +40660,7 @@ function buildProgram() {
40321
40660
  ).option("--human", "Human-readable output instead of JSON").option("--timeout <sec>", "Override default timeout").action((opts) => {
40322
40661
  return catchErrors(() => request(opts), opts.human);
40323
40662
  });
40324
- 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) => {
40663
+ 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) => {
40325
40664
  return catchErrors(() => requestResult(requestId, opts), opts.human);
40326
40665
  });
40327
40666
  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) => {
@@ -40647,7 +40986,7 @@ Docs:
40647
40986
  ).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) => {
40648
40987
  return catchErrors(() => walletCashOut(destination, opts), opts.human);
40649
40988
  });
40650
- 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) => {
40989
+ 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) => {
40651
40990
  return catchErrors(() => walletReceiveToken(token, opts), opts.human);
40652
40991
  });
40653
40992
  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) => {
@@ -40669,6 +41008,14 @@ Docs:
40669
41008
  ).option("--human", "Human-readable output instead of JSON").action((opts) => {
40670
41009
  return catchErrors(() => walletSubmissions(opts), opts.human);
40671
41010
  });
41011
+ wallet.command("forget-quote <quote-id>").description(
41012
+ "Stop tracking one pending funding invoice, named by its mint quote ID. Asks the mint first and refuses while the invoice is paid or its state is unknown. A payment made after forgetting cannot be collected"
41013
+ ).option("--yes", "Skip the confirmation prompt (required to forget non-interactively)").option(
41014
+ "--force",
41015
+ "Forget a quote the mint reports as paid, or whose state could not be checked. This gives up the only record that can collect that payment"
41016
+ ).option("--human", "Human-readable output instead of JSON").action((quoteId, opts) => {
41017
+ return catchErrors(() => walletForgetQuote(quoteId, opts), opts.human);
41018
+ });
40672
41019
  wallet.command("recover-submission <request-id>").description(
40673
41020
  "Recover one strict Cashu request by exact UUID and request-binding fingerprint. Holds the wallet lock and never sweeps unrelated pending state"
40674
41021
  ).requiredOption(