@dvmkit/dvm-cli 0.14.0 → 0.15.1

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
@@ -7,6 +7,7 @@ import {
7
7
  resolveSigningIdentity
8
8
  } from "./chunk-EZL4IVCU.js";
9
9
  import {
10
+ CARD_MIN_MICRO,
10
11
  DEFAULT_CREDIT_POSTURE,
11
12
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
12
13
  JOB_READ_TIMEOUT_MS,
@@ -17,16 +18,19 @@ import {
17
18
  addPayment,
18
19
  answeredYieldSeqs,
19
20
  appendMessages,
21
+ applySubmissionVerdicts,
20
22
  assertFloatBudget,
21
23
  automaticCreditBoundRail,
22
24
  availableRails,
23
25
  backfillTrustAnchor,
26
+ blockHeldPayment,
24
27
  bookCreditPayment,
25
28
  buildCompletionHintFields,
26
29
  buildTempoCredential,
27
30
  captureDrawFundingReceipts,
28
31
  captureFundingReceipt,
29
32
  captureTransportReceipt,
33
+ clearAskPaymentBlocks,
30
34
  clearPaymentRequestInFlight,
31
35
  commitAgentSpend,
32
36
  completedCreditHistory,
@@ -38,6 +42,7 @@ import {
38
42
  computeNextAction,
39
43
  correctPendingFundAmount,
40
44
  createMessageAppendSession,
45
+ declinedAskSeqs,
41
46
  deriveAlias,
42
47
  describeMintBounds,
43
48
  drainReceiptsDisplay,
@@ -50,6 +55,7 @@ import {
50
55
  extractBuilderHandle,
51
56
  fetchMissingJobReceipt,
52
57
  fetchTrustAnchor,
58
+ finishBookedSubmission,
53
59
  floatBudgetJson,
54
60
  floatPaymentDisplay,
55
61
  floatPaymentJson,
@@ -61,10 +67,13 @@ import {
61
67
  guidanceJobArg,
62
68
  hasUnknownUpfrontCredit,
63
69
  hasUnknownUpfrontRail,
70
+ heldCashuSubmissionAsks,
71
+ heldPaymentResendable,
64
72
  identityDataFields,
65
73
  identityError,
66
74
  inFlightTimeoutSeconds,
67
75
  isIdentityFailure,
76
+ isImplicitCreditId,
68
77
  isOpaqueJobToken,
69
78
  isParseableBodyJobId,
70
79
  isTerminalJobStatus,
@@ -84,12 +93,14 @@ import {
84
93
  loadMessages,
85
94
  loadSubmissionEvidence,
86
95
  markJobTerminal,
96
+ markPaymentRequestAnswered,
87
97
  markPaymentRequestInFlight,
88
98
  markPaymentRequestPaid,
89
99
  markPendingSubmissionUnresolved,
90
100
  markProofsInFlight,
91
101
  maxSeq,
92
102
  meltInFlightTimeoutSeconds,
103
+ midJobSpendLabel,
93
104
  mutateCreditPayment,
94
105
  needsTopup,
95
106
  nextStepHint,
@@ -116,11 +127,13 @@ import {
116
127
  proofKey,
117
128
  providerFields,
118
129
  providerJobJson,
130
+ receiptCurrencyHint,
119
131
  receiptDisplay,
120
132
  receiptFailureDetail,
121
133
  receiptHint,
122
134
  receiptIssuedAtIso,
123
135
  receiptJsonFields,
136
+ receiptPieceContext,
124
137
  receiptSettlement,
125
138
  receiptTrustFields,
126
139
  reconcileInFlightPaymentRequest,
@@ -132,10 +145,13 @@ import {
132
145
  recordSpend,
133
146
  recordSpendOnce,
134
147
  recordSubmissionEvidence,
148
+ recordSubmissionVerdicts,
135
149
  recordUpfrontCreditPayment,
136
150
  recordUpfrontRailPayment,
151
+ redactJobTokenFromError,
137
152
  removeFavorite,
138
153
  renderReceiptHuman,
154
+ renderSettlementHuman,
139
155
  replayStoredReceipt,
140
156
  reservedForMarker,
141
157
  resolveEndpoint,
@@ -149,17 +165,23 @@ import {
149
165
  saveJob,
150
166
  saveLedger,
151
167
  saveSubmittedJob,
168
+ settleAnsweredAsk,
152
169
  settleJobIdentity,
170
+ settleRecordedPayments,
171
+ settlementCurrencyHint,
153
172
  statusSnapshot,
154
173
  sweepPendingMints,
155
174
  sweepStaleInFlight,
156
175
  terminalSettlementFields,
157
176
  tierCapOverrides,
177
+ toCapture,
158
178
  toFloatError,
159
179
  trustLadderFor,
160
180
  trustOverrideCapMicro,
181
+ unknownCurrencyHint,
161
182
  unknownUpfrontPrice,
162
183
  unrecordedFloatBudgetWarning,
184
+ unresendablePaymentHint,
163
185
  updateJob,
164
186
  walletHistory,
165
187
  warnInvalidJobIdentityHeader,
@@ -167,7 +189,7 @@ import {
167
189
  withIdentityRecovery,
168
190
  withJobTokenRedaction,
169
191
  withRequestResultRecovery
170
- } from "./chunk-DU7YCGCQ.js";
192
+ } from "./chunk-BFYZO3BV.js";
171
193
  import {
172
194
  connectedTempoAccount,
173
195
  generateTempoKey,
@@ -193,7 +215,7 @@ import {
193
215
  tryResolveBtcUsdRate,
194
216
  tryX402Payment,
195
217
  withOutputWarnings
196
- } from "./chunk-CO2TD5RO.js";
218
+ } from "./chunk-5SHB3MZ7.js";
197
219
  import {
198
220
  assertSupportedX402Network,
199
221
  connectedX402Payer,
@@ -718,8 +740,10 @@ import {
718
740
  bytesToHex,
719
741
  chainIdFromCaip2,
720
742
  concatBytes,
743
+ decodePayment,
721
744
  decodePaymentRequiredHeader,
722
745
  ensureAddress,
746
+ exactEvmAuthorization,
723
747
  generateX402PrivateKey,
724
748
  hexToBytes,
725
749
  hmac,
@@ -9890,6 +9914,10 @@ async function sweepPendingSubmissions(opts = {}) {
9890
9914
  outcomes.push(await resolveEntry(entry, deps, now(), unreadable.has(entry.request_id)));
9891
9915
  }
9892
9916
  if (outcomes.some(mutatesWallet)) {
9917
+ try {
9918
+ recordSubmissionVerdicts(outcomes.flatMap(verdictFor));
9919
+ } catch {
9920
+ }
9893
9921
  await withWalletLock(() => {
9894
9922
  const fresh = loadAgentWallet() ?? wallet;
9895
9923
  const next = outcomes.reduce(
@@ -9898,9 +9926,16 @@ async function sweepPendingSubmissions(opts = {}) {
9898
9926
  );
9899
9927
  saveAgentWallet(next);
9900
9928
  });
9929
+ await applySubmissionVerdicts().catch(() => void 0);
9901
9930
  }
9902
9931
  return { outcomes };
9903
9932
  }
9933
+ function verdictFor(outcome) {
9934
+ const reserve = outcome.entry.output_proofs.some((proof) => proof.reserved_for !== void 0) ? { reserve: true } : {};
9935
+ if (outcome.kind === "already_accepted") return [{ requestId: outcome.entry.request_id, verdict: "spent", ...reserve }];
9936
+ if (outcome.kind !== "reclaimed") return [];
9937
+ return [outcome.spent_sats > 0 ? { requestId: outcome.entry.request_id, verdict: "partly_spent", spentSats: outcome.spent_sats, amountSats: outcome.entry.amount_sats } : { requestId: outcome.entry.request_id, verdict: "reclaimed" }];
9938
+ }
9904
9939
  async function recoverPendingSubmission(opts) {
9905
9940
  if (!UUID_V4_RE.test(opts.requestId))
9906
9941
  throw new DvmError("invalid_request_id", "The pending-submission request id must be a UUIDv4.");
@@ -11213,7 +11248,10 @@ function isSignedRequestAudience(value) {
11213
11248
 
11214
11249
  // src/lib/payment-responder.ts
11215
11250
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11251
+ const seq = opts?.requestSeq;
11252
+ let replacing = false;
11216
11253
  return withJobPaymentLock(jobId, (assertOwned) => {
11254
+ replacing = opts?.approval === "explicit" && seq !== void 0 && loadJob(jobId)?.askPaymentBlocks?.[seq] !== void 0;
11217
11255
  const guardedTransport = new Proxy(transport, {
11218
11256
  get(target, key) {
11219
11257
  if (key === "sendMessage") return async (...args) => {
@@ -11237,6 +11275,19 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11237
11275
  } catch {
11238
11276
  }
11239
11277
  }
11278
+ const heldUnsendable = !replacing && seq !== void 0 && holdsPayment(job, seq) && !heldPaymentResendable(job, seq);
11279
+ if (error.code !== "payment_unconfirmed" && heldUnsendable) {
11280
+ error.hint = paymentInFlightHint(jobId, job, seq);
11281
+ if (error.proseSources?.hint) error.proseSources = { ...error.proseSources, hint: void 0 };
11282
+ }
11283
+ if (error.code === "payment_unconfirmed" || heldUnsendable) {
11284
+ error.data = providerFields({
11285
+ ...error.data,
11286
+ job_id: jobId,
11287
+ next_action: providerFields({ ...pollNextAction(jobId, error.hint) }, ["job_id"])
11288
+ }, ["job_id"]);
11289
+ throw error;
11290
+ }
11240
11291
  const command = requestId ? `dvm request-result ${shellQuoteArg(requestId)}` : `dvm status ${guidanceJobArg(jobId)}`;
11241
11292
  const recovery = `The job was already accepted. Inspect it with \`${command}\` before submitting a replacement. This read cannot submit a job or send payment.`;
11242
11293
  error.data = providerFields({
@@ -11267,8 +11318,6 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11267
11318
  "The original upfront credit debit is unknown or conflicting.",
11268
11319
  "Recover the accepted upfront amount with 'dvm request-result' before authorizing more payments."
11269
11320
  );
11270
- const spent = job?.totalPaidMsats ?? 0;
11271
- const paymentsHonoured = job?.paymentsHonoured ?? 0;
11272
11321
  const pinnedMint = job?.pinnedMint;
11273
11322
  const strictPerCall = job?.strictPerCall === true;
11274
11323
  const maxCashuFeeSats = job?.maxCashuFeeSats;
@@ -11301,16 +11350,31 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11301
11350
  "The saved balance payment was not recovered; no replacement payment was sent.",
11302
11351
  `Run \`dvm status ${shellQuoteArg(jobId)}\` to refresh the job, then run \`dvm pay ${shellQuoteArg(jobId)}\` only if payment is still requested.`
11303
11352
  );
11353
+ if (!matchingEndpoint && job && opts?.requestSeq !== void 0 && holdsPayment(job, opts.requestSeq))
11354
+ throw unconfirmedPaymentError(
11355
+ jobId,
11356
+ "An earlier payment for this request was sent to this job's stored endpoint and is unconfirmed.",
11357
+ `Re-send it with \`dvm pay ${guidanceJobArg(jobId)}\` without --endpoint; it re-delivers that same payment.`
11358
+ );
11359
+ let unconfirmed;
11304
11360
  if (matchingEndpoint && opts?.requestSeq !== void 0) {
11305
11361
  if (job.inFlightPaymentRequestSeqs?.includes(opts.requestSeq))
11306
11362
  await reconcileInFlightPaymentRequest(jobId, opts.requestSeq, transport, provider, { jobToken });
11363
+ await settleRecordedPayments(jobId);
11307
11364
  if (loadAnsweredYieldSeqs(jobId).has(opts.requestSeq))
11308
11365
  throw new DvmError(
11309
11366
  "payment_already_sent",
11310
11367
  "Payment already sent for this request.",
11311
11368
  `Keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
11312
11369
  );
11313
- }
11370
+ const current = loadJob(jobId);
11371
+ unconfirmed = current?.unconfirmedPaymentSubmissions?.[opts.requestSeq];
11372
+ if (!unconfirmed && current?.inFlightPaymentRequestSeqs?.includes(opts.requestSeq))
11373
+ throw unconfirmedPaymentError(jobId, "An earlier payment for this request is unconfirmed and this CLI holds no copy to re-send.");
11374
+ }
11375
+ const latest = loadJob(jobId);
11376
+ const spent = latest?.totalPaidMsats ?? 0;
11377
+ const paymentsHonoured = latest?.paymentsHonoured ?? 0;
11314
11378
  if (policy.maxIncrementMsats > 0 && request2.amount_msats > policy.maxIncrementMsats) {
11315
11379
  return "over-budget";
11316
11380
  }
@@ -11327,6 +11391,27 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11327
11391
  "Verify the original one-payment quote; do not authorize a fallback or replacement payment."
11328
11392
  );
11329
11393
  if (request2.amount_msats > policy.autoPayBelowMsats) return "needs-approval";
11394
+ if (unconfirmed && opts?.requestSeq !== void 0) {
11395
+ if (!unconfirmed.blocked)
11396
+ return redeliverUnconfirmedPayment({
11397
+ jobId,
11398
+ request: request2,
11399
+ requestSeq: opts.requestSeq,
11400
+ submission: unconfirmed,
11401
+ transport,
11402
+ provider,
11403
+ jobToken,
11404
+ rail: opts.rail
11405
+ });
11406
+ if (unconfirmed.blocked.reason === "not_resendable")
11407
+ throw unconfirmedPaymentError(
11408
+ jobId,
11409
+ "Sending the earlier payment for this request again cannot settle it.",
11410
+ paymentInFlightHint(jobId, loadJob(jobId), opts.requestSeq)
11411
+ );
11412
+ }
11413
+ if (opts?.requestSeq !== void 0 && loadJob(jobId)?.askPaymentBlocks?.[opts.requestSeq] && opts.approval !== "explicit")
11414
+ return "needs-approval";
11330
11415
  if (matchingEndpoint && !balanceRefused && opts?.rail === void 0) {
11331
11416
  const creditPaid = await tryCreditPayment({
11332
11417
  jobId,
@@ -11378,7 +11463,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11378
11463
  }
11379
11464
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11380
11465
  const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
11381
- const { tryX402Payment: tryX402Payment2 } = await import("./client-DC7TVYNU.js");
11466
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-YIHI4AIC.js");
11382
11467
  const wallet = loadX402Wallet2();
11383
11468
  if (wallet) {
11384
11469
  let proof;
@@ -11407,34 +11492,25 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11407
11492
  }
11408
11493
  if (proof) {
11409
11494
  await enforceGlobalBudget({ plannedMsats: proof.amountMsats, btcRate: proof.btcRate });
11410
- await sendRailPayment(
11411
- transport,
11495
+ return deliverSignedRailPayment({
11412
11496
  jobId,
11413
- {
11414
- type: "payment",
11415
- content: {
11416
- x402_payment: proof.paymentHeader,
11417
- amount_msats: proof.amountMsats
11418
- }
11419
- },
11497
+ request: request2,
11498
+ transport,
11420
11499
  provider,
11421
- { jobToken },
11422
- matchingEndpoint ? opts?.requestSeq : void 0
11423
- );
11424
- addPayment(jobId, proof.amountMsats, approval);
11425
- recordSpend({
11426
- msats: proof.amountMsats,
11427
- btcRate: proof.btcRate,
11428
- jobId,
11429
- providerEndpoint: provider.endpoint,
11430
- ...midJobSpendLabel(request2.reason)
11500
+ jobToken,
11501
+ approval,
11502
+ requestSeq: matchingEndpoint ? opts?.requestSeq : void 0,
11503
+ submission: {
11504
+ rail: "x402",
11505
+ content: { x402_payment: proof.paymentHeader, amount_msats: proof.amountMsats },
11506
+ requestAmountMsats: request2.amount_msats,
11507
+ amountMsats: proof.amountMsats,
11508
+ btcRate: proof.btcRate,
11509
+ amountUsdcMicro: proof.amountUsdcMicro,
11510
+ approval: approval?.approval,
11511
+ reason: request2.reason
11512
+ }
11431
11513
  });
11432
- return {
11433
- status: "paid",
11434
- rail: "x402",
11435
- amountMsats: proof.amountMsats,
11436
- amountUsdcMicro: proof.amountUsdcMicro
11437
- };
11438
11514
  }
11439
11515
  }
11440
11516
  }
@@ -11444,36 +11520,103 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11444
11520
  if (cred) {
11445
11521
  const paidMsats = usdcToMsats(Number(tempoCredentialAmountMicro(cred)) / 1e6, tempoRate);
11446
11522
  await enforceGlobalBudget({ plannedMsats: paidMsats, btcRate: tempoRate });
11447
- await sendRailPayment(
11448
- transport,
11523
+ return deliverSignedRailPayment({
11449
11524
  jobId,
11450
- {
11451
- type: "payment",
11452
- content: {
11453
- tempo_credential: cred,
11454
- amount_msats: paidMsats
11455
- }
11456
- },
11525
+ request: request2,
11526
+ transport,
11457
11527
  provider,
11458
- { jobToken },
11459
- matchingEndpoint ? opts?.requestSeq : void 0
11460
- );
11461
- addPayment(jobId, paidMsats, approval);
11462
- recordSpend({
11463
- msats: paidMsats,
11464
- btcRate: tempoRate,
11465
- jobId,
11466
- providerEndpoint: provider.endpoint,
11467
- ...midJobSpendLabel(request2.reason)
11528
+ jobToken,
11529
+ approval,
11530
+ requestSeq: matchingEndpoint ? opts?.requestSeq : void 0,
11531
+ submission: {
11532
+ rail: "tempo",
11533
+ content: { tempo_credential: cred, amount_msats: paidMsats },
11534
+ requestAmountMsats: request2.amount_msats,
11535
+ amountMsats: paidMsats,
11536
+ btcRate: tempoRate,
11537
+ approval: approval?.approval,
11538
+ reason: request2.reason
11539
+ }
11468
11540
  });
11469
- return { status: "paid", rail: "tempo", amountMsats: paidMsats };
11470
11541
  }
11471
11542
  }
11472
11543
  return "needs-approval";
11473
11544
  }
11474
- function midJobSpendLabel(reason) {
11475
- const text = reason.trim();
11476
- return text ? { label: text, labelSource: "provider" } : {};
11545
+ function unconfirmedPaymentError(jobId, message2, hint = unresendablePaymentHint(jobId)) {
11546
+ return new DvmError("payment_unconfirmed", `${message2} No new payment was signed.`, hint);
11547
+ }
11548
+ function holdsPayment(job, requestSeq) {
11549
+ return job.inFlightPaymentRequestSeqs?.includes(requestSeq) === true || job.unconfirmedPaymentSubmissions?.[requestSeq] !== void 0;
11550
+ }
11551
+ async function redeliverUnconfirmedPayment(args) {
11552
+ const { jobId, request: request2, submission, provider } = args;
11553
+ const sentRail = submission.rail === "cashu_p2pk" ? "cashu" : submission.rail;
11554
+ if (submission.requestAmountMsats !== request2.amount_msats)
11555
+ throw unconfirmedPaymentError(jobId, "The unconfirmed payment held for this request answered a different amount.");
11556
+ if (args.rail !== void 0 && args.rail !== sentRail)
11557
+ throw unconfirmedPaymentError(
11558
+ jobId,
11559
+ `An unconfirmed ${sentRail} payment was already sent for this request.`,
11560
+ `Re-send it with \`dvm pay ${guidanceJobArg(jobId)}\` without --rail; it re-delivers that same payment.`
11561
+ );
11562
+ if (submission.rail !== "cashu_p2pk")
11563
+ return deliverSignedRailPayment({ ...args, submission, redelivery: true });
11564
+ const wallet = loadAgentWallet();
11565
+ if (!wallet)
11566
+ throw unconfirmedPaymentError(
11567
+ jobId,
11568
+ "The agent wallet holding the unconfirmed Cashu payment for this request is unavailable.",
11569
+ `Restore the agent wallet, then run \`dvm pay ${guidanceJobArg(jobId)}\` to re-send that same payment. ${unresendablePaymentHint(jobId)}`
11570
+ );
11571
+ const held = wallet.pending_submissions.find((entry) => entry.request_id === submission.cashuRequestId);
11572
+ if (!held)
11573
+ throw unconfirmedPaymentError(jobId, "The wallet no longer holds the unconfirmed Cashu payment for this request and recorded no verdict on it.");
11574
+ const cashuToken = held.cashu_token ?? (held.output_proofs.length ? ki({ mint: held.mint, proofs: toCashuProofs(held.output_proofs) }) : void 0);
11575
+ if (!cashuToken || !sameEndpoint(held.endpoint, provider.endpoint))
11576
+ throw unconfirmedPaymentError(jobId, "The unconfirmed Cashu payment for this request cannot be re-delivered.");
11577
+ await deliverAgentWalletPayment({
11578
+ ...args,
11579
+ submission: held.output_proofs.some((proof) => proof.reserved_for !== void 0) ? { ...submission, reserve: true } : submission,
11580
+ redelivery: true,
11581
+ prepared: {
11582
+ cashuToken,
11583
+ requestId: held.request_id,
11584
+ mint: held.mint,
11585
+ totalSats: held.amount_sats,
11586
+ endpoint: held.endpoint,
11587
+ intendedLockPubkey: held.intended_lock_pubkey
11588
+ }
11589
+ });
11590
+ return { status: "paid", rail: "cashu_p2pk", amountMsats: request2.amount_msats };
11591
+ }
11592
+ async function deliverSignedRailPayment(args) {
11593
+ const { jobId, submission, provider } = args;
11594
+ const sent = await sendRailPayment(
11595
+ args.transport,
11596
+ jobId,
11597
+ { type: "payment", content: submission.content },
11598
+ provider,
11599
+ { jobToken: args.jobToken },
11600
+ args.requestSeq,
11601
+ submission,
11602
+ args.redelivery
11603
+ );
11604
+ if (!sent.tracked) {
11605
+ addPayment(jobId, submission.amountMsats, args.approval);
11606
+ recordSpend({
11607
+ msats: submission.amountMsats,
11608
+ btcRate: submission.btcRate,
11609
+ jobId,
11610
+ providerEndpoint: provider.endpoint,
11611
+ ...midJobSpendLabel(args.request.reason)
11612
+ });
11613
+ } else if (sent.booked) await finishBookedSubmission(jobId, sent.booked, provider.endpoint);
11614
+ return {
11615
+ status: "paid",
11616
+ rail: submission.rail,
11617
+ amountMsats: submission.amountMsats,
11618
+ ...submission.amountUsdcMicro !== void 0 ? { amountUsdcMicro: submission.amountUsdcMicro } : {}
11619
+ };
11477
11620
  }
11478
11621
  async function tryAgentWalletMidJobPayment(args) {
11479
11622
  const {
@@ -11533,22 +11676,57 @@ async function tryAgentWalletMidJobPayment(args) {
11533
11676
  prepared.error.attempts ? { mint_attempts: prepared.error.attempts } : void 0
11534
11677
  );
11535
11678
  }
11679
+ await deliverAgentWalletPayment({
11680
+ jobId,
11681
+ request: request2,
11682
+ prepared,
11683
+ transport,
11684
+ provider,
11685
+ approval,
11686
+ jobToken,
11687
+ requestSeq: args.requestSeq,
11688
+ submission: {
11689
+ rail: "cashu_p2pk",
11690
+ cashuRequestId: prepared.requestId,
11691
+ ...prepared.fromReserve ? { reserve: true } : {},
11692
+ requestAmountMsats: request2.amount_msats,
11693
+ amountMsats: request2.amount_msats,
11694
+ btcRate,
11695
+ approval: approval?.approval,
11696
+ reason: request2.reason
11697
+ }
11698
+ });
11699
+ return true;
11700
+ }
11701
+ async function deliverAgentWalletPayment(args) {
11702
+ const { jobId, request: request2, prepared, submission, transport, provider, approval, jobToken } = args;
11703
+ let sent;
11536
11704
  try {
11537
- await sendMidJobPaymentWithRetry({
11705
+ sent = await sendMidJobPaymentWithRetry({
11538
11706
  jobId,
11539
11707
  amountMsats: request2.amount_msats,
11540
11708
  prepared,
11541
11709
  transport,
11542
11710
  provider,
11543
11711
  jobToken,
11544
- requestSeq: args.requestSeq
11712
+ requestSeq: args.requestSeq,
11713
+ submission,
11714
+ redelivery: args.redelivery
11545
11715
  });
11546
11716
  } catch (err) {
11547
- if (err instanceof DvmError && err.code === "payment_invalid") {
11717
+ if (err instanceof DvmError && err.code === "payment_invalid" && sendOutcome(err, submission, args.redelivery).kind === "refused") {
11548
11718
  await abandonPendingSubmission({ requestId: prepared.requestId, preserveRecovery: true });
11549
11719
  }
11720
+ if (args.requestSeq !== void 0 && err instanceof DvmError && (err.code === "payment_lock_pubkey_stale" || err.code === "wrong_lock_pubkey")) {
11721
+ const reclaimAt = loadAgentWallet()?.pending_submissions.find((entry) => entry.request_id === prepared.requestId)?.t_expire;
11722
+ blockHeldPayment(jobId, args.requestSeq, { reason: "not_resendable", detail: "The provider no longer accepts the lock key this Cashu token was made for, though it may still redeem it." + (reclaimAt ? ` The wallet can take the token back after ${new Date(reclaimAt).toISOString()} if it does not.` : "") });
11723
+ }
11550
11724
  throw err;
11551
11725
  }
11726
+ if (sent.tracked) {
11727
+ if (sent.booked) await finishBookedSubmission(jobId, sent.booked, provider.endpoint);
11728
+ return;
11729
+ }
11552
11730
  await commitAgentSpend({
11553
11731
  requestId: prepared.requestId,
11554
11732
  recentSpend: {
@@ -11562,16 +11740,15 @@ async function tryAgentWalletMidJobPayment(args) {
11562
11740
  addPayment(jobId, request2.amount_msats, approval);
11563
11741
  recordSpend({
11564
11742
  msats: request2.amount_msats,
11565
- btcRate,
11743
+ btcRate: submission.btcRate,
11566
11744
  jobId,
11567
11745
  providerEndpoint: provider.endpoint,
11568
11746
  ...midJobSpendLabel(request2.reason)
11569
11747
  });
11570
- return true;
11571
11748
  }
11572
11749
  async function sendMidJobPaymentWithRetry(args) {
11573
11750
  const { jobId, amountMsats, prepared, transport, provider, jobToken } = args;
11574
- await withAgentWalletPaymentRetry({
11751
+ return withAgentWalletPaymentRetry({
11575
11752
  attempt: () => sendRailPayment(
11576
11753
  transport,
11577
11754
  jobId,
@@ -11586,14 +11763,16 @@ async function sendMidJobPaymentWithRetry(args) {
11586
11763
  },
11587
11764
  provider,
11588
11765
  { jobToken },
11589
- args.requestSeq
11766
+ args.requestSeq,
11767
+ args.submission,
11768
+ args.redelivery
11590
11769
  ),
11591
11770
  intendedLockPubkey: prepared.intendedLockPubkey,
11592
11771
  refetchInfo: () => transport.describe(provider),
11593
11772
  sleep: args.sleep
11594
11773
  });
11595
11774
  }
11596
- async function sendRailPayment(transport, jobId, message2, provider, options, requestSeq) {
11775
+ async function sendRailPayment(transport, jobId, message2, provider, options, requestSeq, submission, redelivery) {
11597
11776
  const capture = (evidence) => {
11598
11777
  if (evidence.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
11599
11778
  if (evidence.drawFundingReceipt) captureDrawFundingReceipts(jobId, [evidence.drawFundingReceipt], {
@@ -11601,31 +11780,81 @@ async function sendRailPayment(transport, jobId, message2, provider, options, re
11601
11780
  ...typeof message2.content.cashu_request_id === "string" ? { fundId: message2.content.cashu_request_id } : {}
11602
11781
  });
11603
11782
  };
11604
- if (requestSeq !== void 0) markPaymentRequestInFlight(jobId, requestSeq);
11783
+ if (requestSeq !== void 0) markPaymentRequestInFlight(jobId, requestSeq, submission);
11784
+ let result;
11605
11785
  try {
11606
- const result = await transport.sendMessage(jobId, message2, provider, options);
11607
- if (requestSeq !== void 0) markPaymentRequestPaid(jobId, requestSeq);
11608
- if (result) capture(result);
11786
+ result = await transport.sendMessage(jobId, message2, provider, options);
11609
11787
  } catch (error) {
11610
- if (requestSeq !== void 0) {
11611
- if (error instanceof DvmError && error.code === "replay_rejected") markPaymentRequestPaid(jobId, requestSeq);
11612
- else if (definitelyNotAccepted(error)) clearPaymentRequestInFlight(jobId, requestSeq);
11613
- else markPaymentRequestInFlight(jobId, requestSeq);
11614
- }
11615
11788
  if (error instanceof DvmError && error.data) capture(error.data);
11616
- if (error instanceof DvmError && error.code === "replay_rejected") return;
11789
+ const outcome = sendOutcome(error, submission, redelivery);
11790
+ if (requestSeq === void 0) {
11791
+ if (outcome.kind === "taken" && error instanceof DvmError && error.code === "replay_rejected") return { tracked: false };
11792
+ throw error;
11793
+ }
11794
+ if (outcome.kind === "taken") return { tracked: true, booked: markPaymentRequestPaid(jobId, requestSeq) };
11795
+ if (outcome.kind === "blocked") blockHeldPayment(jobId, requestSeq, outcome.blocked);
11796
+ else if (outcome.kind === "refused") clearPaymentRequestInFlight(jobId, requestSeq);
11797
+ else if (outcome.kind === "not_sent") clearPaymentRequestInFlight(jobId, requestSeq, { keepSubmission: true });
11798
+ else markPaymentRequestInFlight(jobId, requestSeq);
11617
11799
  throw error;
11618
11800
  }
11619
- }
11620
- function definitelyNotAccepted(error) {
11621
- if (error instanceof DvmError) {
11622
- const status2 = error.data?.http_status;
11623
- return typeof status2 === "number" && status2 >= 400 && status2 < 500;
11801
+ const sent = requestSeq === void 0 ? { tracked: false } : { tracked: true, booked: markPaymentRequestPaid(jobId, requestSeq) };
11802
+ if (result) capture(result);
11803
+ return sent;
11804
+ }
11805
+ var DEFINITE_REFUSALS = /* @__PURE__ */ new Set([
11806
+ "payment_invalid",
11807
+ "lock_not_exclusive",
11808
+ "not_p2pk_locked",
11809
+ "cashu_not_p2pk_locked",
11810
+ "invalid_token",
11811
+ "invalid_message",
11812
+ "invalid_input",
11813
+ "invalid_request"
11814
+ ]);
11815
+ function sendOutcome(error, submission, redelivery) {
11816
+ if (!(error instanceof DvmError)) return { kind: requestNeverSent(error) ? "not_sent" : "unknown" };
11817
+ if (error.code === "replay_rejected") return { kind: "taken" };
11818
+ const status2 = error.data?.http_status;
11819
+ if (typeof status2 !== "number" || status2 < 400 || status2 >= 500) return { kind: "unknown" };
11820
+ if (error.data?.code_source === "inferred") return { kind: "unknown" };
11821
+ const cashu = submission?.rail === "cashu_p2pk" ? submission : void 0;
11822
+ if (cashu && error.code === "proof_not_unspent") {
11823
+ if (!cashu.reserve) return { kind: "taken" };
11824
+ return { kind: "blocked", blocked: {
11825
+ reason: "proofs_spent",
11826
+ detail: "The reserve proofs the earlier Cashu payment used are already spent at the mint and the provider recorded no payment for this charge, but it may already have redeemed this token for this charge, so paying again may pay twice."
11827
+ } };
11828
+ }
11829
+ if (error.code === "payment_insufficient")
11830
+ return { kind: "blocked", blocked: {
11831
+ reason: "credit_held",
11832
+ ...typeof error.data?.credit_id === "string" ? { creditId: error.data.credit_id } : {}
11833
+ } };
11834
+ if (error.code === "request_id_reused")
11835
+ return { kind: "blocked", blocked: {
11836
+ reason: "not_resendable",
11837
+ detail: "The provider did not take this payment, because its request id already carries a different payment there."
11838
+ } };
11839
+ if (!DEFINITE_REFUSALS.has(error.code)) return { kind: "unknown" };
11840
+ if (redelivery && submission && submission.rail !== "cashu_p2pk" && error.code === "payment_invalid")
11841
+ return { kind: "blocked", blocked: { reason: "not_resendable", detail: submission.rail === "tempo" ? "The provider refused the earlier Tempo credential, which it also does for one it already used." : `${x402RefusalNote(submission.content.x402_payment)} It also answers that way for an authorization it already settled.` } };
11842
+ return { kind: "refused" };
11843
+ }
11844
+ function x402RefusalNote(header) {
11845
+ try {
11846
+ const validBefore = Number(exactEvmAuthorization(decodePayment(String(header))).validBefore) * 1e3;
11847
+ if (Number.isFinite(validBefore))
11848
+ return validBefore <= Date.now() ? `The provider refused the earlier x402 authorization, which expired at ${new Date(validBefore).toISOString()}.` : "The provider refused the earlier x402 authorization before it expired.";
11849
+ } catch {
11624
11850
  }
11625
- if (!(error instanceof Error)) return false;
11851
+ return "The provider refused the earlier x402 authorization.";
11852
+ }
11853
+ function requestNeverSent(error) {
11854
+ if (!(error instanceof Error) || error instanceof DvmError) return false;
11626
11855
  if ("code" in error && ["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH"].includes(String(error.code))) return true;
11627
- if (error instanceof AggregateError) return error.errors.length > 0 && error.errors.every(definitelyNotAccepted);
11628
- return definitelyNotAccepted(error.cause);
11856
+ if (error instanceof AggregateError) return error.errors.length > 0 && error.errors.every(requestNeverSent);
11857
+ return requestNeverSent(error.cause);
11629
11858
  }
11630
11859
  async function tryMppCredential(challenges, amountMsats, btcRate) {
11631
11860
  const wallet = loadConfig()?.tempo;
@@ -11777,7 +12006,7 @@ async function streamLoop(opts) {
11777
12006
  let messageAppendSession = opts.messageAppendSession;
11778
12007
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
11779
12008
  const declined = () => persistLocalState && loadJob(jobId)?.callerDeclined === true;
11780
- function recordAutoPayment(result, request2, seq) {
12009
+ async function recordAutoPayment(result, request2, seq) {
11781
12010
  autoPayments.push({
11782
12011
  amount_msats: result.amountMsats,
11783
12012
  rail: result.rail,
@@ -11785,7 +12014,7 @@ async function streamLoop(opts) {
11785
12014
  ...result.amountUsdcMicro !== void 0 && { amount_usdc_microunits: result.amountUsdcMicro },
11786
12015
  display: paidConfirmationDisplay(result, request2.fiat_amount)
11787
12016
  });
11788
- if (persistLocalState) markPaymentRequestPaid(jobId, seq);
12017
+ if (persistLocalState) markPaymentRequestAnswered(jobId, seq);
11789
12018
  answeredSeqs.add(seq);
11790
12019
  justAutoPaid = true;
11791
12020
  }
@@ -11800,10 +12029,10 @@ async function streamLoop(opts) {
11800
12029
  });
11801
12030
  } catch (error) {
11802
12031
  if (error instanceof DvmError && error.code === "payment_settling")
11803
- return { messages: [], autoPayments, refunds, cursor, nextAction: pollNextAction(jobId, paymentInFlightHint(jobId)) };
12032
+ return { messages: [], autoPayments, refunds, cursor, nextAction: pollNextAction(jobId, paymentInFlightHint(jobId, loadJob(jobId), pending4.authorization.request_seq)) };
11804
12033
  throw error;
11805
12034
  }
11806
- if (typeof result === "object") recordAutoPayment(result, pending4.request, pending4.authorization.request_seq);
12035
+ if (typeof result === "object") await recordAutoPayment(result, pending4.request, pending4.authorization.request_seq);
11807
12036
  else pendingAction = computeNextAction(jobId, [{
11808
12037
  seq: pending4.authorization.request_seq,
11809
12038
  from: "provider",
@@ -11866,6 +12095,7 @@ async function streamLoop(opts) {
11866
12095
  if (persistLocalState) {
11867
12096
  messageAppendSession ??= createMessageAppendSession(jobId);
11868
12097
  messageAppendSession.append(batchMessages);
12098
+ await settleRecordedPayments(jobId);
11869
12099
  }
11870
12100
  if (persistLocalState) {
11871
12101
  refunds.push(...await claimInboundPayments(jobId, batchMessages));
@@ -11876,7 +12106,8 @@ async function streamLoop(opts) {
11876
12106
  const pendingPayment = pendingPaymentRequest(batchMessages, answeredSeqs);
11877
12107
  const lastYield2 = findLastYield(batchMessages.filter((message2) => !answeredSeqs.has(message2.seq) && (message2.type !== "payment-request" || message2.seq === pendingPayment?.seq))) ?? findLastYield(batchMessages);
11878
12108
  if (lastYield2?.type === "payment-request" && answeredSeqs.has(lastYield2.seq)) {
11879
- if (persistLocalState) markPaymentRequestPaid(jobId, lastYield2.seq);
12109
+ if (persistLocalState && !declinedAskSeqs(jobId).has(lastYield2.seq))
12110
+ await settleAnsweredAsk(jobId, lastYield2.seq, loadMessages(jobId));
11880
12111
  break;
11881
12112
  }
11882
12113
  if (lastYield2?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield2.seq)) {
@@ -11906,8 +12137,9 @@ async function streamLoop(opts) {
11906
12137
  requestSeq: lastYield2.seq
11907
12138
  });
11908
12139
  } catch (error) {
11909
- if (error instanceof DvmError && error.code === "payment_settling") {
12140
+ if (error instanceof DvmError && ["payment_settling", "payment_unconfirmed"].includes(error.code)) {
11910
12141
  paymentUnresolved = true;
12142
+ if (error.code === "payment_unconfirmed") cursor = Math.min(cursor, lastYield2.seq - 1);
11911
12143
  break;
11912
12144
  }
11913
12145
  if (error instanceof DvmError && error.code === "payment_already_sent") {
@@ -11917,7 +12149,7 @@ async function streamLoop(opts) {
11917
12149
  throw error;
11918
12150
  }
11919
12151
  if (typeof result === "object") {
11920
- recordAutoPayment(result, req, lastYield2.seq);
12152
+ await recordAutoPayment(result, req, lastYield2.seq);
11921
12153
  continue;
11922
12154
  }
11923
12155
  if (result === "payment-cap-exceeded") {
@@ -11960,6 +12192,7 @@ async function streamLoop(opts) {
11960
12192
  if (persistLocalState) {
11961
12193
  messageAppendSession ??= createMessageAppendSession(jobId);
11962
12194
  messageAppendSession.append(recheck);
12195
+ await settleRecordedPayments(jobId);
11963
12196
  refunds.push(...await claimInboundPayments(jobId, recheck));
11964
12197
  }
11965
12198
  }
@@ -11970,8 +12203,9 @@ async function streamLoop(opts) {
11970
12203
  const yieldAction = computeNextAction(jobId, allMessages.filter((message2) => !answeredSeqs.has(message2.seq)), void 0, policy ? { policy, totalPaidMsats: loadJob(jobId)?.totalPaidMsats } : void 0) ?? (terminal ? null : pendingAction);
11971
12204
  let nextAction = withRefundNextAction(jobId, yieldAction ?? (terminal ? null : pollNextAction(jobId)), refunds);
11972
12205
  const lastYield = findLastYield(allMessages);
11973
- if (nextAction?.type === "pay" && lastYield?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield.seq))
11974
- nextAction = { ...nextAction, hint: paymentInFlightHint(jobId) };
12206
+ const heldJob = persistLocalState ? loadJob(jobId) : null;
12207
+ if (nextAction?.type === "pay" && lastYield?.type === "payment-request" && heldJob && (heldJob.inFlightPaymentRequestSeqs?.includes(lastYield.seq) || heldJob.unconfirmedPaymentSubmissions?.[lastYield.seq] || heldJob.askPaymentBlocks?.[lastYield.seq]))
12208
+ nextAction = { ...nextAction, hint: paymentInFlightHint(jobId, heldJob, lastYield.seq) };
11975
12209
  if (nextAction?.type === "pay" || nextAction?.type === "poll" && !terminal) {
11976
12210
  if (lastYield?.type === "payment-request" && answeredSeqs.has(lastYield.seq)) {
11977
12211
  nextAction = {
@@ -11981,7 +12215,11 @@ async function streamLoop(opts) {
11981
12215
  };
11982
12216
  }
11983
12217
  }
11984
- if (paymentUnresolved) nextAction = pollNextAction(jobId, paymentInFlightHint(jobId));
12218
+ if (paymentUnresolved) nextAction = pollNextAction(jobId, paymentInFlightHint(
12219
+ jobId,
12220
+ heldJob,
12221
+ lastYield?.type === "payment-request" ? lastYield.seq : void 0
12222
+ ));
11985
12223
  return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
11986
12224
  }
11987
12225
  function isMessagePollTimeout(err) {
@@ -12016,6 +12254,54 @@ function formatAppliedDefaults(applied) {
12016
12254
  return Object.entries(applied).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(", ");
12017
12255
  }
12018
12256
 
12257
+ // src/lib/stream-outcome.ts
12258
+ function persistStreamOutcome(outcome) {
12259
+ const { jobId, messages: messages2, cursor, afterSeq, extra, providerStatus } = outcome;
12260
+ const stored = loadJob(jobId);
12261
+ const callerCancelled = outcome.callerCancelled ?? stored?.callerCancelled;
12262
+ const terminal = streamTerminalStatus(messages2, {
12263
+ providerStatus,
12264
+ callerCancelled,
12265
+ callerDeclined: outcome.callerDeclined ?? stored?.callerDeclined
12266
+ });
12267
+ const log = terminal ? fullMessageLog(jobId, messages2, afterSeq) : void 0;
12268
+ const providerTerminal = providerStatus?.status && isTerminalJobStatus(providerStatus.status);
12269
+ if (terminal && (log || providerTerminal)) {
12270
+ const saved = stored?.status === terminal ? stored.completion : void 0;
12271
+ const fromLog = log?.some((m) => m.type === "complete" || m.type === "cancel" || m.type === "decline") ? completionFromMessages(log) : void 0;
12272
+ const retained = saved ?? fromLog;
12273
+ const completion = providerStatus?.content_available === false && retained ? retained : {
12274
+ ...saved,
12275
+ ...fromLog,
12276
+ ...terminal === "cancelled" && callerCancelled && stored?.completion?.message !== void 0 ? { message: stored.completion.message } : {},
12277
+ ...providerTerminal ? completionSnapshot(providerStatus) : {}
12278
+ };
12279
+ markJobTerminal(jobId, terminal, completion, {
12280
+ messageCursor: cursor,
12281
+ ...extra
12282
+ });
12283
+ return completion;
12284
+ }
12285
+ updateJob(jobId, { messageCursor: cursor });
12286
+ return void 0;
12287
+ }
12288
+ function streamTerminalStatus(messages2, context = {}) {
12289
+ const providerStatus = context.providerStatus?.status;
12290
+ if (providerStatus && isTerminalJobStatus(providerStatus)) return providerStatus;
12291
+ const last = messages2.findLast((m) => m.type === "complete" || m.type === "cancel" || m.type === "decline" && context.callerDeclined === true);
12292
+ if (!last) return void 0;
12293
+ if (last.type === "complete") return "completed";
12294
+ if (last.type === "decline") return "cancelled";
12295
+ return context.callerCancelled ? "cancelled" : "failed";
12296
+ }
12297
+ function fullMessageLog(jobId, messages2, afterSeq) {
12298
+ if (afterSeq === 0) return messages2;
12299
+ const local = [...loadMessages(jobId)].sort((a, b) => a.seq - b.seq);
12300
+ if (local.length === 0 || local[0].seq > 1) return void 0;
12301
+ const contiguous = local.every((m, i2) => i2 === 0 || m.seq === local[i2 - 1].seq + 1);
12302
+ return contiguous ? local : void 0;
12303
+ }
12304
+
12019
12305
  // src/lib/discovery-lifecycle.ts
12020
12306
  async function runDiscoveryLifecycle(options) {
12021
12307
  const { transport, provider, capability, input, timeoutMs } = options;
@@ -12041,42 +12327,54 @@ async function runDiscoveryLifecycle(options) {
12041
12327
  if (receipt.status === "completed" && receipt.summary) {
12042
12328
  return { summary: receipt.summary, messages: [], nextAction: null };
12043
12329
  }
12044
- const deadline = Date.now() + timeoutMs;
12045
- const messageAppendSession = createMessageAppendSession(receipt.jobId);
12046
- const messages2 = [];
12047
- let result = await streamLoop({
12048
- jobId: receipt.jobId,
12049
- transport,
12050
- provider,
12051
- afterSeq: 0,
12052
- timeoutMs: Math.max(1, deadline - Date.now()),
12053
- messageAppendSession,
12054
- jobToken: receipt.jobToken
12055
- });
12056
- messages2.push(...result.messages);
12057
- while (result.nextAction?.type === "poll" && Date.now() < deadline) {
12058
- const waitMs = Math.min(
12059
- Math.max((result.nextAction.estimate_seconds ?? 0) * 1e3, 500),
12060
- deadline - Date.now()
12061
- );
12062
- if (waitMs > 0) await new Promise((resolve3) => setTimeout(resolve3, waitMs));
12063
- if (Date.now() >= deadline) break;
12064
- const next = await streamLoop({
12330
+ return withJobTokenRedaction(receipt.jobToken, async () => {
12331
+ if (receipt.jobId) saveSubmittedJob({
12332
+ id: receipt.jobId,
12333
+ endpoint: provider.endpoint,
12334
+ capability,
12335
+ status: "submitted",
12336
+ submittedAt: Date.now(),
12337
+ jobToken: receipt.jobToken
12338
+ });
12339
+ const deadline = Date.now() + timeoutMs;
12340
+ const messageAppendSession = createMessageAppendSession(receipt.jobId);
12341
+ const messages2 = [];
12342
+ let result = await streamLoop({
12065
12343
  jobId: receipt.jobId,
12066
12344
  transport,
12067
12345
  provider,
12068
- afterSeq: result.cursor,
12346
+ afterSeq: 0,
12069
12347
  timeoutMs: Math.max(1, deadline - Date.now()),
12070
12348
  messageAppendSession,
12071
12349
  jobToken: receipt.jobToken
12072
12350
  });
12073
- if (next.messages.length === 0) break;
12074
- messages2.push(...next.messages);
12075
- result = next;
12076
- }
12077
- const complete = messages2.find((message2) => message2.type === "complete");
12078
- const summary = complete?.content.summary;
12079
- return { ...summary ? { summary } : {}, messages: messages2, nextAction: result.nextAction };
12351
+ messages2.push(...result.messages);
12352
+ persistStreamOutcome({ jobId: receipt.jobId, messages: messages2, cursor: result.cursor, afterSeq: 0 });
12353
+ while (result.nextAction?.type === "poll" && Date.now() < deadline) {
12354
+ const waitMs = Math.min(
12355
+ Math.max((result.nextAction.estimate_seconds ?? 0) * 1e3, 500),
12356
+ deadline - Date.now()
12357
+ );
12358
+ if (waitMs > 0) await new Promise((resolve3) => setTimeout(resolve3, waitMs));
12359
+ if (Date.now() >= deadline) break;
12360
+ const next = await streamLoop({
12361
+ jobId: receipt.jobId,
12362
+ transport,
12363
+ provider,
12364
+ afterSeq: result.cursor,
12365
+ timeoutMs: Math.max(1, deadline - Date.now()),
12366
+ messageAppendSession,
12367
+ jobToken: receipt.jobToken
12368
+ });
12369
+ messages2.push(...next.messages);
12370
+ persistStreamOutcome({ jobId: receipt.jobId, messages: messages2, cursor: next.cursor, afterSeq: 0 });
12371
+ if (next.messages.length === 0) break;
12372
+ result = next;
12373
+ }
12374
+ const complete = messages2.find((message2) => message2.type === "complete");
12375
+ const summary = complete?.content.summary;
12376
+ return { ...summary ? { summary } : {}, messages: messages2, nextAction: result.nextAction, jobToken: receipt.jobToken };
12377
+ });
12080
12378
  }
12081
12379
 
12082
12380
  // src/lib/discovery-options.ts
@@ -12799,7 +13097,7 @@ var HttpsTransport = class {
12799
13097
  }
12800
13098
  if (res.status === 409) {
12801
13099
  const body2 = parseJsonObject(await res.text());
12802
- if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string")) {
13100
+ if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && body2.error === "request_id_reused" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string")) {
12803
13101
  const error = withDrawFunding(withCreditErrorContext(buildPaymentError(body2), body2), body2);
12804
13102
  error.data = { ...error.data, http_status: res.status };
12805
13103
  throw error;
@@ -13202,8 +13500,12 @@ function isReceipt402(code) {
13202
13500
  return code === void 0 || code === "payment_required" || code === "payment_insufficient";
13203
13501
  }
13204
13502
  function buildPaymentError(errorBody) {
13205
- const code = typeof errorBody.error === "string" ? errorBody.error : "payment_insufficient";
13206
- return buildStructuredError(code, errorBody);
13503
+ if (typeof errorBody.error === "string") return buildStructuredError(errorBody.error, errorBody);
13504
+ const nested = errorBody.error && typeof errorBody.error === "object" && !Array.isArray(errorBody.error) ? errorBody.error : void 0;
13505
+ if (typeof nested?.code === "string") return buildStructuredError(nested.code, nested);
13506
+ const error = buildStructuredError("payment_insufficient", errorBody);
13507
+ error.data = { ...error.data, code_source: "inferred" };
13508
+ return error;
13207
13509
  }
13208
13510
  async function paymentHeaders(payment) {
13209
13511
  const headers = {};
@@ -13381,6 +13683,7 @@ async function browse(opts) {
13381
13683
  const transport = createDvmTransport();
13382
13684
  const ref = { endpoint };
13383
13685
  progressNotice("Browsing catalog...", opts.human);
13686
+ let jobToken;
13384
13687
  try {
13385
13688
  const result = await runDiscoveryLifecycle({
13386
13689
  transport,
@@ -13389,6 +13692,7 @@ async function browse(opts) {
13389
13692
  input,
13390
13693
  timeoutMs: timeout
13391
13694
  });
13695
+ jobToken = result.jobToken;
13392
13696
  if (result.summary) {
13393
13697
  outputResults(result.summary, opts.human, result.nextAction);
13394
13698
  return;
@@ -13411,6 +13715,8 @@ async function browse(opts) {
13411
13715
  "Browse did not complete in time.",
13412
13716
  "Try again or increase --timeout."
13413
13717
  );
13718
+ } catch (error) {
13719
+ throw redactJobTokenFromError(error, jobToken);
13414
13720
  } finally {
13415
13721
  transport.close();
13416
13722
  }
@@ -13874,7 +14180,7 @@ async function settleCreditAfterJob(args) {
13874
14180
  }
13875
14181
  }
13876
14182
  if (args.allowTopup !== false) {
13877
- const refill = args.refillPocket ?? (await import("./pocket-refill-HEVLAMKN.js")).refillPocketIfLow;
14183
+ const refill = args.refillPocket ?? (await import("./pocket-refill-KA37CF4N.js")).refillPocketIfLow;
13878
14184
  await refill({ human: args.human }).catch(() => void 0);
13879
14185
  }
13880
14186
  }
@@ -13882,7 +14188,7 @@ async function settleCreditAfterRead(args) {
13882
14188
  const { job, capture } = args;
13883
14189
  const binding = job.creditBinding;
13884
14190
  const receipt = capture.receipt;
13885
- if (job.strictPerCall || !binding || "unbound" in binding || !receipt?.credit || receipt.job_id !== job.id || receipt.requester_pubkey !== binding.callerPubkey || receipt.credit.credit_id !== binding.creditId || receipt.credit.draw_id !== binding.drawId || receipt.credit.credit_id.startsWith("imp:")) return;
14191
+ if (job.strictPerCall || !binding || "unbound" in binding || !receipt?.credit || receipt.job_id !== job.id || receipt.requester_pubkey !== binding.callerPubkey || receipt.credit.credit_id !== binding.creditId || receipt.credit.draw_id !== binding.drawId || isImplicitCreditId(receipt.credit.credit_id)) return;
13886
14192
  const builder = loadJob(job.id)?.builderAnchor ?? job.builderAnchor;
13887
14193
  await settleCreditAfterJob({
13888
14194
  capture,
@@ -13914,7 +14220,7 @@ async function settle(args) {
13914
14220
  const credit = receipt?.credit;
13915
14221
  const callerPubkey = args.signing?.pubkey ?? args.callerPubkey;
13916
14222
  if (!receipt || !credit || !callerPubkey || args.capture?.status !== "verified" && args.capture?.status !== "verified_unattested" || receipt.requester_pubkey !== callerPubkey) return;
13917
- if (credit.credit_id.startsWith("imp:")) {
14223
+ if (isImplicitCreditId(credit.credit_id)) {
13918
14224
  const applied2 = applyImplicitReceiptCredit({
13919
14225
  endpoint: args.ref.endpoint,
13920
14226
  ...settleIdentityArgs(args),
@@ -14281,7 +14587,7 @@ function dvmIdentity(dvmId, capability) {
14281
14587
  // src/commands/cancel.ts
14282
14588
  async function cancel(jobId, opts) {
14283
14589
  const access = resolveJobAccess(jobId, opts);
14284
- return withJobTokenRedaction(access.jobToken, () => cancelWithAccess(jobId, opts, access));
14590
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => cancelWithAccess(jobId, opts, access)));
14285
14591
  }
14286
14592
  async function cancelWithAccess(jobId, opts, access) {
14287
14593
  const { stored, ref, jobToken } = access;
@@ -14301,15 +14607,20 @@ async function cancelWithAccess(jobId, opts, access) {
14301
14607
  ref,
14302
14608
  jobToken,
14303
14609
  persistLocalState: !access.endpointOverridden,
14304
- human: opts.human
14610
+ human: opts.human,
14611
+ onTerminal: () => {
14612
+ if (!access.endpointOverridden) clearAskPaymentBlocks(jobId);
14613
+ }
14305
14614
  });
14306
14615
  transport.close();
14307
14616
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
14308
14617
  const receiptPending = !settlement && status2 !== void 0 && isTerminalJobStatus(status2.status) && !status2.receipt && !status2.receiptParseError && !access.endpointOverridden && expectsReceipt(jobId, stored);
14309
14618
  const display = settlement ? cancelledDisplay(settlement) : receiptPending ? `Stopped. Its receipt is not available yet; \`dvm status ${guidanceJobArg(jobId)}\` shows what was charged once it is.` : void 0;
14619
+ const hint = settlementCurrencyHint(settlement, ref.endpoint);
14310
14620
  if (opts.human) {
14311
14621
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
14312
14622
  if (display) info(display);
14623
+ if (hint) info(` ${hint}`);
14313
14624
  } else {
14314
14625
  json3({
14315
14626
  jobId,
@@ -14318,6 +14629,7 @@ async function cancelWithAccess(jobId, opts, access) {
14318
14629
  ...opts.reason ? { reason: opts.reason } : {},
14319
14630
  ...settlement ? { settlement } : {},
14320
14631
  ...display ? { display } : {},
14632
+ ...hint ? { hint } : {},
14321
14633
  next_action: null
14322
14634
  });
14323
14635
  }
@@ -14329,7 +14641,7 @@ function expectsReceipt(jobId, stored) {
14329
14641
  // src/commands/decline.ts
14330
14642
  async function decline(jobId, opts) {
14331
14643
  const access = resolveJobAccess(jobId, opts);
14332
- return withJobTokenRedaction(access.jobToken, () => declineWithAccess(jobId, opts, access));
14644
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => declineWithAccess(jobId, opts, access)));
14333
14645
  }
14334
14646
  async function declineWithAccess(jobId, opts, access) {
14335
14647
  const { stored, ref, jobToken } = access;
@@ -14350,12 +14662,15 @@ async function declineWithAccess(jobId, opts, access) {
14350
14662
  persistLocalState: !access.endpointOverridden,
14351
14663
  human: opts.human,
14352
14664
  onTerminal: (status2) => {
14353
- if (!access.endpointOverridden && isTerminalJobStatus(status2.status)) markJobTerminal(
14354
- jobId,
14355
- status2.status,
14356
- opts.reason !== void 0 ? { message: opts.reason } : {},
14357
- { callerCancelled: true, callerDeclined: true }
14358
- );
14665
+ if (!access.endpointOverridden && isTerminalJobStatus(status2.status)) {
14666
+ markJobTerminal(
14667
+ jobId,
14668
+ status2.status,
14669
+ opts.reason !== void 0 ? { message: opts.reason } : {},
14670
+ { callerCancelled: true, callerDeclined: true }
14671
+ );
14672
+ clearAskPaymentBlocks(jobId);
14673
+ }
14359
14674
  }
14360
14675
  });
14361
14676
  transport.close();
@@ -14371,8 +14686,10 @@ async function declineWithAccess(jobId, opts, access) {
14371
14686
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
14372
14687
  const { settlement } = ending;
14373
14688
  const display = observed === void 0 ? `Decline sent, but the job's status could not be read. Check it with \`dvm status ${job}\`.` : settlement ? `Declined; the job has ended. ${settlement.display}` : `Declined; the job has ended. Its receipt is not available yet; \`dvm status ${job}\` shows the final charge once it is.`;
14689
+ const hint = settlementCurrencyHint(settlement, ref.endpoint);
14374
14690
  if (opts.human) {
14375
14691
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""}: ${display}`);
14692
+ if (hint) info(` ${hint}`);
14376
14693
  return;
14377
14694
  }
14378
14695
  json3({
@@ -14383,6 +14700,7 @@ async function declineWithAccess(jobId, opts, access) {
14383
14700
  ...opts.reason !== void 0 ? { reason: opts.reason } : {},
14384
14701
  ...settlement ? { settlement } : {},
14385
14702
  display,
14703
+ ...hint ? { hint } : {},
14386
14704
  next_action: observed === void 0 ? pollNextAction(jobId, display) : null
14387
14705
  });
14388
14706
  }
@@ -14729,6 +15047,7 @@ function computeHeadroom(args) {
14729
15047
  menu,
14730
15048
  routeAmountMicro,
14731
15049
  fundableNowMicro,
15050
+ menuRoomMicro: menu ? Math.max(menu.max_micro - Math.max(args.balanceMicro ?? 0, 0), 0) : void 0,
14732
15051
  availability: args.routeAvailability
14733
15052
  });
14734
15053
  const pin = effectiveFundingRail(args.config, args.endpoint, args.identity);
@@ -14883,19 +15202,27 @@ function fundableNow(capMicro, balanceMicro, menu) {
14883
15202
  return Math.max(room, 0);
14884
15203
  }
14885
15204
  function railMinimums(menu) {
14886
- if (!menu?.lightning_min_micro) return [];
14887
- return [{ rail: "lightning", minMicro: menu.lightning_min_micro }];
15205
+ const minimums = [];
15206
+ if (menu?.lightning_min_micro) {
15207
+ minimums.push({ rail: "lightning", minMicro: menu.lightning_min_micro });
15208
+ }
15209
+ if (menu?.funding.includes("stripe")) {
15210
+ minimums.push({ rail: "stripe", minMicro: CARD_MIN_MICRO });
15211
+ }
15212
+ return minimums;
14888
15213
  }
14889
15214
  function compatibilityFor(args) {
14890
15215
  if (!args.menu || args.routeAmountMicro === void 0) return [];
14891
15216
  const menu = args.menu;
14892
15217
  const routeAmountMicro = args.routeAmountMicro;
14893
15218
  const availability = new Map(args.availability?.map((entry) => [entry.rail, entry]));
15219
+ const minimums = new Map(railMinimums(menu).map((entry) => [entry.rail, entry.minMicro]));
14894
15220
  return menu.funding.filter(isCreditFundRail).map((rail) => {
14895
- const minimum = rail === "lightning" && menu.lightning_min_micro !== void 0 ? Math.max(menu.min_micro, menu.lightning_min_micro) : menu.min_micro;
15221
+ const minimum = Math.max(menu.min_micro, minimums.get(rail) ?? 0);
14896
15222
  const local = availability.get(rail);
14897
15223
  let status2;
14898
- if (args.fundableNowMicro !== void 0 && (routeAmountMicro > args.fundableNowMicro || minimum > args.fundableNowMicro)) {
15224
+ const bound = rail === "stripe" ? args.menuRoomMicro : args.fundableNowMicro;
15225
+ if (bound !== void 0 && (routeAmountMicro > bound || rail !== "stripe" && minimum > bound)) {
14899
15226
  status2 = "blocked_by_trust_cap";
14900
15227
  } else if (routeAmountMicro < minimum) {
14901
15228
  status2 = "blocked_by_rail_minimum";
@@ -14963,6 +15290,14 @@ function routeDisplay(h) {
14963
15290
  out.push(
14964
15291
  "No automatic funding route is available locally: the ecash pocket cannot cover this amount and no connected funding wallet can replenish or carry it."
14965
15292
  );
15293
+ const card = h.routeCompatibility.find((route) => route.rail === "stripe");
15294
+ if (card) {
15295
+ const separateCredit = h.boundRail !== void 0 && h.boundRail !== "stripe";
15296
+ const command = `dvm credit fund ${shellQuoteArg(h.endpoint)} --rail stripe${separateCredit ? " --credit-id <new id>" : ""} --amount '$X'`;
15297
+ out.push(
15298
+ `${separateCredit ? `This credit is bound to ${h.boundRail}; open a separate card-funded credit` : "This DVM accepts card top-ups"} with '${command}': replace $X with a whole-cent amount of at least ${usd(card.minMicro)}. Your human must approve the top-up in Stripe Link.`
15299
+ );
15300
+ }
14966
15301
  }
14967
15302
  return out;
14968
15303
  }
@@ -19334,7 +19669,7 @@ async function runCreditFund(dvm, opts) {
19334
19669
  amountMicro = sizing.amountMicro;
19335
19670
  }
19336
19671
  const fundMicro = amountMicro;
19337
- if (!pending4 && !signedPending && (explicitMicro !== void 0 || targetJobs !== void 0)) {
19672
+ if (rail !== "stripe" && !pending4 && !signedPending && (explicitMicro !== void 0 || targetJobs !== void 0)) {
19338
19673
  await enforceTrustTier({
19339
19674
  endpoint,
19340
19675
  amountMicro: fundMicro,
@@ -24564,54 +24899,6 @@ function formatBytes(bytes) {
24564
24899
  return `${bytes.toLocaleString("en-US")} bytes`;
24565
24900
  }
24566
24901
 
24567
- // src/lib/stream-outcome.ts
24568
- function persistStreamOutcome(outcome) {
24569
- const { jobId, messages: messages2, cursor, afterSeq, extra, providerStatus } = outcome;
24570
- const stored = loadJob(jobId);
24571
- const callerCancelled = outcome.callerCancelled ?? stored?.callerCancelled;
24572
- const terminal = streamTerminalStatus(messages2, {
24573
- providerStatus,
24574
- callerCancelled,
24575
- callerDeclined: outcome.callerDeclined ?? stored?.callerDeclined
24576
- });
24577
- const log = terminal ? fullMessageLog(jobId, messages2, afterSeq) : void 0;
24578
- const providerTerminal = providerStatus?.status && isTerminalJobStatus(providerStatus.status);
24579
- if (terminal && (log || providerTerminal)) {
24580
- const saved = stored?.status === terminal ? stored.completion : void 0;
24581
- const fromLog = log?.some((m) => m.type === "complete" || m.type === "cancel" || m.type === "decline") ? completionFromMessages(log) : void 0;
24582
- const retained = saved ?? fromLog;
24583
- const completion = providerStatus?.content_available === false && retained ? retained : {
24584
- ...saved,
24585
- ...fromLog,
24586
- ...terminal === "cancelled" && callerCancelled && stored?.completion?.message !== void 0 ? { message: stored.completion.message } : {},
24587
- ...providerTerminal ? completionSnapshot(providerStatus) : {}
24588
- };
24589
- markJobTerminal(jobId, terminal, completion, {
24590
- messageCursor: cursor,
24591
- ...extra
24592
- });
24593
- return completion;
24594
- }
24595
- updateJob(jobId, { messageCursor: cursor });
24596
- return void 0;
24597
- }
24598
- function streamTerminalStatus(messages2, context = {}) {
24599
- const providerStatus = context.providerStatus?.status;
24600
- if (providerStatus && isTerminalJobStatus(providerStatus)) return providerStatus;
24601
- const last = messages2.findLast((m) => m.type === "complete" || m.type === "cancel" || m.type === "decline" && context.callerDeclined === true);
24602
- if (!last) return void 0;
24603
- if (last.type === "complete") return "completed";
24604
- if (last.type === "decline") return "cancelled";
24605
- return context.callerCancelled ? "cancelled" : "failed";
24606
- }
24607
- function fullMessageLog(jobId, messages2, afterSeq) {
24608
- if (afterSeq === 0) return messages2;
24609
- const local = [...loadMessages(jobId)].sort((a, b) => a.seq - b.seq);
24610
- if (local.length === 0 || local[0].seq > 1) return void 0;
24611
- const contiguous = local.every((m, i2) => i2 === 0 || m.seq === local[i2 - 1].seq + 1);
24612
- return contiguous ? local : void 0;
24613
- }
24614
-
24615
24902
  // src/lib/message-human.ts
24616
24903
  function paymentAmount(msg) {
24617
24904
  if (msg.from === "requester" && msg.content.credit) {
@@ -24721,8 +25008,6 @@ function nextActionHuman(action) {
24721
25008
  }
24722
25009
  case "refund":
24723
25010
  return action.claimed ? null : `Next: ${refundSummaryHuman(action)}`;
24724
- case "approve":
24725
- return `Next: ${action.hint}`;
24726
25011
  }
24727
25012
  }
24728
25013
  function printNextActionHuman(action, options = {}) {
@@ -24789,6 +25074,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
24789
25074
  for (const message2 of tail) onMessage(message2);
24790
25075
  if (opts.persistLocalState !== false) {
24791
25076
  messageAppendSession?.append(tail);
25077
+ await settleRecordedPayments(opts.jobId);
24792
25078
  result.refunds.push(...await claimInboundPayments(opts.jobId, tail));
24793
25079
  }
24794
25080
  result.nextAction = withRefundNextAction(opts.jobId, null, result.refunds);
@@ -24807,7 +25093,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
24807
25093
  assertOwned();
24808
25094
  for (const seq of loadJob(opts.jobId)?.inFlightPaymentRequestSeqs ?? []) {
24809
25095
  try {
24810
- reconcilePaymentRequestHistory(opts.jobId, seq, messages2, snapshot.status, now);
25096
+ await reconcilePaymentRequestHistory(opts.jobId, seq, messages2, snapshot.status, now);
24811
25097
  } catch (error) {
24812
25098
  if (!(error instanceof DvmError) || !["payment_settling", "payment_request_not_pending"].includes(error.code)) throw error;
24813
25099
  if (!loadJob(opts.jobId)?.inFlightPaymentRequestSeqs?.includes(seq)) continue;
@@ -24827,6 +25113,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
24827
25113
  }
24828
25114
  if (!history) break;
24829
25115
  messageAppendSession?.append(history);
25116
+ if (opts.persistLocalState !== false) await settleRecordedPayments(opts.jobId);
24830
25117
  const answered = opts.persistLocalState === false ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(opts.jobId);
24831
25118
  for (const seq of answeredYieldSeqs(history)) answered.add(seq);
24832
25119
  const pending4 = history.findLast((msg) => msg.from === "provider" && ["prompt", "payment-request", "working", "complete", "cancel"].includes(msg.type) && !answered.has(msg.seq));
@@ -24886,7 +25173,7 @@ async function messages(jobId, opts) {
24886
25173
  throw new DvmError("invalid_arguments", "Use --until with --wait, and --wait with streaming enabled.");
24887
25174
  }
24888
25175
  const access = resolveJobAccess(jobId, opts);
24889
- return withJobTokenRedaction(access.jobToken, () => messagesWithAccess(jobId, opts, access));
25176
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => messagesWithAccess(jobId, opts, access)));
24890
25177
  }
24891
25178
  async function messagesWithAccess(jobId, opts, access) {
24892
25179
  const waitDuration = opts.wait ? parseDurationMs(opts.until ?? "12h") : void 0;
@@ -24897,8 +25184,9 @@ async function messagesWithAccess(jobId, opts, access) {
24897
25184
  const answered = access.endpointOverridden ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(jobId);
24898
25185
  const action = computeNextAction(jobId, batch.filter((message2) => !answered.has(message2.seq)), void 0, access.endpointOverridden ? void 0 : stored ?? void 0);
24899
25186
  const request2 = batch.findLast((message2) => message2.type === "payment-request");
24900
- if (action?.type === "pay" && request2 && !access.endpointOverridden && stored?.inFlightPaymentRequestSeqs?.includes(request2.seq))
24901
- return { ...action, hint: paymentInFlightHint(jobId) };
25187
+ const current = access.endpointOverridden ? null : loadJob(jobId);
25188
+ if (action?.type === "pay" && request2 && current && (current.inFlightPaymentRequestSeqs?.includes(request2.seq) || current.unconfirmedPaymentSubmissions?.[request2.seq] || current.askPaymentBlocks?.[request2.seq]))
25189
+ return { ...action, hint: paymentInFlightHint(jobId, current, request2.seq) };
24902
25190
  return action;
24903
25191
  }
24904
25192
  async function resolveNextAction2(action, messages2, observedStatus) {
@@ -24939,7 +25227,10 @@ async function messagesWithAccess(jobId, opts, access) {
24939
25227
  }
24940
25228
  throw err;
24941
25229
  }
24942
- if (!access.endpointOverridden) appendMessages(jobId, msgs);
25230
+ if (!access.endpointOverridden) {
25231
+ appendMessages(jobId, msgs);
25232
+ await settleRecordedPayments(jobId);
25233
+ }
24943
25234
  const newCursor = maxSeq(msgs, after);
24944
25235
  const providerStatus2 = await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken });
24945
25236
  if (!access.endpointOverridden) {
@@ -24953,7 +25244,7 @@ async function messagesWithAccess(jobId, opts, access) {
24953
25244
  const settlement2 = observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden, currency2);
24954
25245
  transport.close();
24955
25246
  if (opts.human) {
24956
- if (settlement2.settlement) info(settlement2.settlement.display);
25247
+ renderSettlementHuman(settlement2);
24957
25248
  info(String(content2.content_hint));
24958
25249
  if (msgs.length === 0) {
24959
25250
  info("No new messages.");
@@ -25022,7 +25313,7 @@ async function messagesWithAccess(jobId, opts, access) {
25022
25313
  const settlement = observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
25023
25314
  transport.close();
25024
25315
  if (opts.human) {
25025
- if (settlement.settlement) info(settlement.settlement.display);
25316
+ renderSettlementHuman(settlement);
25026
25317
  info(String(content.content_hint));
25027
25318
  if (result.messages.length === 0) {
25028
25319
  info("No new messages.");
@@ -25148,7 +25439,7 @@ async function message(jobId, text, opts) {
25148
25439
  const access = resolveJobAccess(jobId, opts);
25149
25440
  return withJobTokenRedaction(
25150
25441
  access.jobToken,
25151
- () => messageWithAccess(jobId, text, opts, access)
25442
+ () => withOutputWarnings(() => messageWithAccess(jobId, text, opts, access))
25152
25443
  );
25153
25444
  }
25154
25445
  async function messageWithAccess(jobId, text, opts, access) {
@@ -25205,7 +25496,7 @@ async function messageWithAccess(jobId, text, opts, access) {
25205
25496
  const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden, currency);
25206
25497
  transport.close();
25207
25498
  if (opts.human) {
25208
- if (settlement.settlement) info(settlement.settlement.display);
25499
+ renderSettlementHuman(settlement);
25209
25500
  info(String(content.content_hint));
25210
25501
  info(`Message sent (type: ${msgType}).`);
25211
25502
  for (const msg of result.messages) {
@@ -25286,7 +25577,7 @@ function parseForcedRail(raw2) {
25286
25577
  // src/commands/pay.ts
25287
25578
  async function pay(jobId, opts) {
25288
25579
  const access = resolveStoredJobAccess(jobId, opts);
25289
- return withJobTokenRedaction(access.jobToken, () => payWithAccess(jobId, opts, access));
25580
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => payWithAccess(jobId, opts, access)));
25290
25581
  }
25291
25582
  async function payWithAccess(jobId, opts, access) {
25292
25583
  const rail = parseForcedRail(opts.rail);
@@ -25423,7 +25714,7 @@ async function payWithAccess(jobId, opts, access) {
25423
25714
  transport.close();
25424
25715
  const identifier = stored.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
25425
25716
  if (opts.human) {
25426
- if (settlement.settlement) info(settlement.settlement.display);
25717
+ renderSettlementHuman(settlement);
25427
25718
  info(`${paid.display}${identifier ? ` [${identifier}]` : ""}`);
25428
25719
  for (const msg of streamResult.messages) {
25429
25720
  formatMessageHuman(msg, jobId, artifactSession);
@@ -26099,11 +26390,18 @@ function receiptsList(opts) {
26099
26390
  info(emptyMessage(opts));
26100
26391
  return;
26101
26392
  }
26393
+ const unnamed = /* @__PURE__ */ new Set();
26102
26394
  for (const { entry, status: status2 } of shown) {
26103
- info(`${entry.receipt.job_id} ${receiptDisplay(entry.receipt, status2, rate)}`);
26395
+ const context = receiptPieceContext(entry.receipt);
26396
+ info(`${entry.receipt.job_id} ${receiptDisplay(entry.receipt, status2, rate, context)}`);
26397
+ if (receiptCurrencyHint(entry.receipt, status2, context)) unnamed.add(entry.endpoint);
26104
26398
  }
26105
26399
  info(`
26106
26400
  ${shown.length} of ${matched.length} receipt(s).`);
26401
+ if (unnamed.size > 0) {
26402
+ const [only] = unnamed;
26403
+ info(unknownCurrencyHint(unnamed.size === 1 && only ? only : void 0));
26404
+ }
26107
26405
  return;
26108
26406
  }
26109
26407
  json({
@@ -26129,7 +26427,7 @@ Endpoint: ${entry.endpoint || "(unknown)"}`);
26129
26427
  }
26130
26428
  json({
26131
26429
  ...storedReceiptJson(entry, result, rate),
26132
- hint: receiptHint(result.status, jobId)
26430
+ hint: verdictHint(entry, result, jobId)
26133
26431
  });
26134
26432
  }
26135
26433
  async function receiptsVerify(jobId, opts) {
@@ -26165,7 +26463,7 @@ Signature: ${result.checks.signature ? "valid" : "INVALID"}`);
26165
26463
  ...storedReceiptJson(entry, result, rate),
26166
26464
  ...opts.file?.length ? { files } : {},
26167
26465
  anchor_source: opts.endpoint ? "refetched" : "stored",
26168
- hint: receiptHint(result.status, jobId)
26466
+ hint: verdictHint(entry, result, jobId)
26169
26467
  });
26170
26468
  }
26171
26469
  async function verifyFiles(jobId, opts, delivered, result) {
@@ -26286,6 +26584,8 @@ function resolveLimit(limit) {
26286
26584
  return n;
26287
26585
  }
26288
26586
  function listEntryJson(entry, status2, rate) {
26587
+ const context = receiptPieceContext(entry.receipt);
26588
+ const currencyHint = receiptCurrencyHint(entry.receipt, status2, context, entry.endpoint || void 0);
26289
26589
  return {
26290
26590
  job_id: entry.receipt.job_id,
26291
26591
  dvm_id: entry.receipt.dvm_id,
@@ -26296,19 +26596,21 @@ function listEntryJson(entry, status2, rate) {
26296
26596
  // see `receiptIssuedAtIso`. The raw number stays intact under `receipt`.
26297
26597
  issued_at: receiptIssuedAtIso(entry.receipt),
26298
26598
  paid_msats: entry.receipt.paid.msats,
26299
- settlement: receiptSettlement(entry.receipt, status2),
26599
+ settlement: receiptSettlement(entry.receipt, status2, void 0, context),
26300
26600
  receipt_verified: status2,
26301
- display: receiptDisplay(entry.receipt, status2, rate)
26601
+ display: receiptDisplay(entry.receipt, status2, rate, context),
26602
+ ...currencyHint ? { hint: currencyHint } : {}
26302
26603
  };
26303
26604
  }
26304
26605
  function storedReceiptJson(entry, result, rate) {
26606
+ const context = receiptPieceContext(entry.receipt);
26305
26607
  return {
26306
26608
  job_id: entry.receipt.job_id,
26307
26609
  endpoint: entry.endpoint,
26308
26610
  receipt: entry.receipt,
26309
26611
  receipt_verified: result.status,
26310
26612
  receipt_checks: result.checks,
26311
- settlement: receiptSettlement(entry.receipt, result.status),
26613
+ settlement: receiptSettlement(entry.receipt, result.status, void 0, context),
26312
26614
  ...result.reason ? { receipt_error: result.reason, receipt_error_detail: receiptFailureDetail(result.reason) } : {},
26313
26615
  // The DVM's terminal reason is provider free text — an agent relaying it
26314
26616
  // must be able to see that it is untrusted (docs/cli.md).
@@ -26319,11 +26621,18 @@ function storedReceiptJson(entry, result, rate) {
26319
26621
  // caller the proof it is attached to.
26320
26622
  collected_at: epochMsToIso(entry.verified_at),
26321
26623
  ...entry.builder ? { builder: entry.builder } : {},
26322
- display: receiptDisplay(entry.receipt, result.status, rate)
26624
+ display: receiptDisplay(entry.receipt, result.status, rate, context)
26323
26625
  };
26324
26626
  }
26627
+ function verdictHint(entry, result, jobId) {
26628
+ const currency = receiptCurrencyHint(entry.receipt, result.status, receiptPieceContext(entry.receipt), entry.endpoint || void 0);
26629
+ return [currency, receiptHint(result.status, jobId)].filter(Boolean).join(" ");
26630
+ }
26325
26631
  function renderVerdictHuman(entry, result, rate) {
26326
- info(receiptDisplay(entry.receipt, result.status, rate));
26632
+ const context = receiptPieceContext(entry.receipt);
26633
+ info(receiptDisplay(entry.receipt, result.status, rate, context));
26634
+ const currencyHint = receiptCurrencyHint(entry.receipt, result.status, context, entry.endpoint || void 0);
26635
+ if (currencyHint) info(` ${currencyHint}`);
26327
26636
  if (result.reason) info(` ${receiptFailureDetail(result.reason)}`);
26328
26637
  if (entry.receipt.reason) info(` Provider reason: ${entry.receipt.reason}`);
26329
26638
  }
@@ -27421,10 +27730,7 @@ async function requestWithWarnings(opts) {
27421
27730
  if (hint) info(`\u{1F4CE} ${hint}`);
27422
27731
  }
27423
27732
  if (captured) renderReceiptHuman(captured, receipt.jobId);
27424
- else {
27425
- const { settlement } = terminalSettlementFields(receipt.jobId);
27426
- if (settlement) info(settlement.display);
27427
- }
27733
+ else renderSettlementHuman(terminalSettlementFields(receipt.jobId));
27428
27734
  finalizeProgressLine();
27429
27735
  echoTraceIdHuman();
27430
27736
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: isTerminalJobStatus(receipt.status) || !!streamTerminalStatus(result.messages) });
@@ -29407,10 +29713,7 @@ async function streamAfterPayment(args) {
29407
29713
  if (hint) info(`\u{1F4CE} ${hint}`);
29408
29714
  }
29409
29715
  if (captured) renderReceiptHuman(captured, jobId);
29410
- else {
29411
- const { settlement } = terminalSettlementFields(jobId);
29412
- if (settlement) info(settlement.display);
29413
- }
29716
+ else renderSettlementHuman(terminalSettlementFields(jobId));
29414
29717
  finalizeProgressLine();
29415
29718
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: !!streamTerminalStatus(result.messages) });
29416
29719
  } else {
@@ -29770,6 +30073,9 @@ function paymentMethod(receipt) {
29770
30073
 
29771
30074
  // src/commands/request-resume.ts
29772
30075
  async function requestResume(requestId, opts = {}) {
30076
+ return withOutputWarnings(() => resumeRequest(requestId, opts));
30077
+ }
30078
+ async function resumeRequest(requestId, opts) {
29773
30079
  if (!isPublicRequestId(requestId)) {
29774
30080
  throw new DvmError(
29775
30081
  "invalid_request_id",
@@ -29880,6 +30186,7 @@ async function search(opts) {
29880
30186
  const transport = createDvmTransport();
29881
30187
  const ref = { endpoint };
29882
30188
  progressNotice("Searching for providers...", opts.human);
30189
+ let jobToken;
29883
30190
  try {
29884
30191
  const result = await runDiscoveryLifecycle({
29885
30192
  transport,
@@ -29888,6 +30195,7 @@ async function search(opts) {
29888
30195
  input,
29889
30196
  timeoutMs: timeout
29890
30197
  });
30198
+ jobToken = result.jobToken;
29891
30199
  if (result.summary) {
29892
30200
  outputResults2(result.summary, opts.human, result.nextAction);
29893
30201
  return;
@@ -29917,6 +30225,8 @@ async function search(opts) {
29917
30225
  "Search did not complete in time.",
29918
30226
  "Try again or increase --timeout."
29919
30227
  );
30228
+ } catch (error) {
30229
+ throw redactJobTokenFromError(error, jobToken);
29920
30230
  } finally {
29921
30231
  transport.close();
29922
30232
  }
@@ -30118,7 +30428,7 @@ function renderSpendHuman(spend, print) {
30118
30428
  // src/commands/status.ts
30119
30429
  async function status(jobId, opts) {
30120
30430
  const access = resolveJobAccess(jobId, opts);
30121
- return withJobTokenRedaction(access.jobToken, () => statusWithAccess(jobId, opts, access));
30431
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => statusWithAccess(jobId, opts, access)));
30122
30432
  }
30123
30433
  async function statusWithAccess(jobId, opts, access) {
30124
30434
  const { stored, ref, jobToken } = access;
@@ -30159,13 +30469,17 @@ async function statusWithAccess(jobId, opts, access) {
30159
30469
  if (opts.messages) {
30160
30470
  const after = access.endpointOverridden ? 0 : stored?.messageCursor ?? 0;
30161
30471
  msgs = await transport.getMessages(jobId, after, ref, { timeoutMs: timeout, jobToken });
30162
- if (!access.endpointOverridden) appendMessages(jobId, msgs);
30472
+ if (!access.endpointOverridden) {
30473
+ appendMessages(jobId, msgs);
30474
+ await settleRecordedPayments(jobId);
30475
+ }
30163
30476
  newCursor = maxSeq(msgs, after);
30164
30477
  }
30165
30478
  const nextAction = await resolveNextAction(jobId, result.status, msgs, transport, ref, {
30166
30479
  timeoutMs: timeout,
30167
30480
  jobToken,
30168
- context: access.endpointOverridden ? void 0 : stored ?? void 0
30481
+ context: access.endpointOverridden ? void 0 : stored ?? void 0,
30482
+ held: access.endpointOverridden ? void 0 : loadJob(jobId)
30169
30483
  });
30170
30484
  const completion = completionSnapshot(result);
30171
30485
  const reasonUnavailable = completion.message === void 0 || result.content_available === false && completion.message === "";
@@ -30188,7 +30502,7 @@ async function statusWithAccess(jobId, opts, access) {
30188
30502
  await backfillTrustAnchor(jobId, transport, ref);
30189
30503
  }
30190
30504
  currency = stored && !access.endpointOverridden ? void 0 : await providerCurrency({ receipt: result.receipt, status: result, messages: msgs, transport, ref });
30191
- receipt = stored && !access.endpointOverridden ? captureTransportReceipt(jobId, result) : transientReceiptCapture(jobId, result, currency);
30505
+ receipt = stored && !access.endpointOverridden ? captureTransportReceipt(jobId, result) : transientReceiptCapture(jobId, result, ref.endpoint, currency);
30192
30506
  if (stored && !access.endpointOverridden) {
30193
30507
  await settleCreditAfterRead({ job: stored, capture: receipt, transport, human: opts.human });
30194
30508
  }
@@ -30216,7 +30530,7 @@ async function statusWithAccess(jobId, opts, access) {
30216
30530
  currency
30217
30531
  });
30218
30532
  }
30219
- function transientReceiptCapture(jobId, response, currency) {
30533
+ function transientReceiptCapture(jobId, response, endpoint, currency) {
30220
30534
  if (response.receiptParseError) {
30221
30535
  return {
30222
30536
  status: "unparseable",
@@ -30226,18 +30540,7 @@ function transientReceiptCapture(jobId, response, currency) {
30226
30540
  }
30227
30541
  if (!response.receipt) return { status: "absent", display: receiptHint("absent") };
30228
30542
  const result = verifyJobReceipt({ receipt: response.receipt, expectedJobId: jobId });
30229
- return {
30230
- status: result.status,
30231
- receipt: response.receipt,
30232
- checks: result.checks,
30233
- ...result.reason ? { reason: result.reason } : {},
30234
- display: receiptDisplay(
30235
- response.receipt,
30236
- result.status,
30237
- getLastKnownBtcRate()?.rate ?? 0,
30238
- currency
30239
- )
30240
- };
30543
+ return toCapture(response.receipt, result, { currency }, endpoint);
30241
30544
  }
30242
30545
  function renderStatus(jobId, stored, jobStatus, completion, source, nextAction, opts, fetched) {
30243
30546
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
@@ -30277,6 +30580,7 @@ ${msgs.length} new message(s):`);
30277
30580
  if (spend) renderSpendHuman(spend, info);
30278
30581
  else if (settlement.settlement) info(settlement.settlement.display);
30279
30582
  if (receipt) renderReceiptHuman(receipt);
30583
+ if (settlement.settlement_hint && !receipt?.currencyHint) info(` ${settlement.settlement_hint}`);
30280
30584
  printNextActionHuman(nextAction);
30281
30585
  return;
30282
30586
  }
@@ -30298,6 +30602,7 @@ ${msgs.length} new message(s):`);
30298
30602
  // read as "this DVM doesn't issue receipts" rather than "not yet".
30299
30603
  ...receipt ? receiptJsonFields(receipt) : {},
30300
30604
  ...settlement,
30605
+ ...receipt?.currencyHint ? { settlement_hint: void 0 } : {},
30301
30606
  // `dvm status` is a job-terminal emission for `--no-stream`
30302
30607
  // jobs, so it drains the deferred-notice sinks like the request terminals
30303
30608
  // do. Both spread blind and are absent when nothing was stashed.
@@ -30316,12 +30621,19 @@ async function resolveNextAction(jobId, status2, fetched, transport, ref, opts)
30316
30621
  if (isTerminalJobStatus(status2)) return null;
30317
30622
  if (status2 === "awaiting-input") {
30318
30623
  const fromBatch = computeNextAction(jobId, fetched, void 0, opts.context);
30319
- if (fromBatch) return fromBatch;
30624
+ if (fromBatch) return withHeldPaymentHint(jobId, fromBatch, fetched, opts.held);
30320
30625
  const history = await transport.getMessages(jobId, 0, ref, opts);
30321
- return computeNextAction(jobId, history, void 0, opts.context) ?? pollNextAction(jobId);
30626
+ return withHeldPaymentHint(jobId, computeNextAction(jobId, history, void 0, opts.context), history, opts.held) ?? pollNextAction(jobId);
30322
30627
  }
30323
30628
  return pollNextAction(jobId);
30324
30629
  }
30630
+ function withHeldPaymentHint(jobId, action, messages2, held) {
30631
+ if (action?.type !== "pay" || !held) return action;
30632
+ const ask = pendingPaymentRequest(messages2);
30633
+ if (!ask || !(held.inFlightPaymentRequestSeqs?.includes(ask.seq) || held.unconfirmedPaymentSubmissions?.[ask.seq] || held.askPaymentBlocks?.[ask.seq]))
30634
+ return action;
30635
+ return { ...action, hint: paymentInFlightHint(jobId, held, ask.seq) };
30636
+ }
30325
30637
 
30326
30638
  // src/commands/upload.ts
30327
30639
  import { statSync as statSync4 } from "fs";
@@ -37625,10 +37937,13 @@ async function forgetSubmission(requestId, opts) {
37625
37937
  await confirmForget(view, opts);
37626
37938
  await abandonPendingSubmission({ requestId });
37627
37939
  const abandoned = view.at_risk ? view.amount_sats : 0;
37940
+ const heldFor = heldCashuSubmissionAsks(/* @__PURE__ */ new Set([requestId]));
37941
+ const warning = heldFor.length === 0 ? void 0 : `This token is the unconfirmed payment for an open charge on ${heldFor.map((ask) => `job ${ask.jobId}`).join(", ")}. That charge stays held, but if the provider asks for it again it can become payable again, and the provider can still redeem the forgotten token.`;
37628
37942
  if (opts.human) {
37629
37943
  info(
37630
37944
  view.at_risk ? `Forgot request ${requestId} \u2014 abandoned ${abandoned} sats paid to ${view.endpoint}.` : `Forgot request ${requestId} \u2014 no sats were spent (nothing to abandon).`
37631
37945
  );
37946
+ if (warning) info(`Warning: ${warning}`);
37632
37947
  return;
37633
37948
  }
37634
37949
  json({
@@ -37637,7 +37952,8 @@ async function forgetSubmission(requestId, opts) {
37637
37952
  endpoint: view.endpoint,
37638
37953
  abandoned_sats: abandoned,
37639
37954
  display: !view.at_risk ? `Forgot request ${requestId}. No sats were spent, so nothing was abandoned.` : view.state === "reclaimable" || view.state === "reclaim_failed" ? `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 and this one was still recoverable: the wallet would have returned it to your balance by itself${view.reclaim_at ? ` after ${view.reclaim_at}` : ""}.` : view.state === "accepted_unresolved" ? `Forgot the journal entry for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are no longer tracked; the provider accepted that call, and its evidence stays under submission_evidence.` : view.state === "unreclaimable" ? `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 nothing was given up by forgetting it, since ${view.reclaim_error ?? "the mint's fee exceeds the value"}.` : `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 the proofs were locked to the provider with no refund.`,
37640
- hint: "The entry is gone from the journal. This cannot be undone."
37955
+ hint: "The entry is gone from the journal. This cannot be undone.",
37956
+ ...warning ? { warning, held_for: heldFor.map((ask) => ({ job_id: ask.jobId, request_seq: ask.requestSeq })) } : {}
37641
37957
  });
37642
37958
  }
37643
37959
  function refuseIfSelfHealing(view, opts) {
@@ -38757,7 +39073,7 @@ function buildProgram() {
38757
39073
  "Size the funding to a workload instead of a figure: N jobs' worth at this DVM's price"
38758
39074
  ).option(
38759
39075
  "--over-trust",
38760
- "Fund past the trust-tier cap deliberately \u2014 required for an amount above what receipts here have earned"
39076
+ "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"
38761
39077
  ).option("--rail <rail>", `Force a funding rail: ${creditFundRails}`).option("--cashu-mint <mint>", "Pin Cashu funding to one DVM-accepted mint").option(
38762
39078
  "--max-cashu-principal-sats <sats>",
38763
39079
  "Refuse Cashu funding above this token-principal ceiling"