@dvmkit/dvm-cli 0.15.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
@@ -18,16 +18,19 @@ import {
18
18
  addPayment,
19
19
  answeredYieldSeqs,
20
20
  appendMessages,
21
+ applySubmissionVerdicts,
21
22
  assertFloatBudget,
22
23
  automaticCreditBoundRail,
23
24
  availableRails,
24
25
  backfillTrustAnchor,
26
+ blockHeldPayment,
25
27
  bookCreditPayment,
26
28
  buildCompletionHintFields,
27
29
  buildTempoCredential,
28
30
  captureDrawFundingReceipts,
29
31
  captureFundingReceipt,
30
32
  captureTransportReceipt,
33
+ clearAskPaymentBlocks,
31
34
  clearPaymentRequestInFlight,
32
35
  commitAgentSpend,
33
36
  completedCreditHistory,
@@ -39,6 +42,7 @@ import {
39
42
  computeNextAction,
40
43
  correctPendingFundAmount,
41
44
  createMessageAppendSession,
45
+ declinedAskSeqs,
42
46
  deriveAlias,
43
47
  describeMintBounds,
44
48
  drainReceiptsDisplay,
@@ -51,6 +55,7 @@ import {
51
55
  extractBuilderHandle,
52
56
  fetchMissingJobReceipt,
53
57
  fetchTrustAnchor,
58
+ finishBookedSubmission,
54
59
  floatBudgetJson,
55
60
  floatPaymentDisplay,
56
61
  floatPaymentJson,
@@ -62,6 +67,8 @@ import {
62
67
  guidanceJobArg,
63
68
  hasUnknownUpfrontCredit,
64
69
  hasUnknownUpfrontRail,
70
+ heldCashuSubmissionAsks,
71
+ heldPaymentResendable,
65
72
  identityDataFields,
66
73
  identityError,
67
74
  inFlightTimeoutSeconds,
@@ -86,12 +93,14 @@ import {
86
93
  loadMessages,
87
94
  loadSubmissionEvidence,
88
95
  markJobTerminal,
96
+ markPaymentRequestAnswered,
89
97
  markPaymentRequestInFlight,
90
98
  markPaymentRequestPaid,
91
99
  markPendingSubmissionUnresolved,
92
100
  markProofsInFlight,
93
101
  maxSeq,
94
102
  meltInFlightTimeoutSeconds,
103
+ midJobSpendLabel,
95
104
  mutateCreditPayment,
96
105
  needsTopup,
97
106
  nextStepHint,
@@ -136,6 +145,7 @@ import {
136
145
  recordSpend,
137
146
  recordSpendOnce,
138
147
  recordSubmissionEvidence,
148
+ recordSubmissionVerdicts,
139
149
  recordUpfrontCreditPayment,
140
150
  recordUpfrontRailPayment,
141
151
  redactJobTokenFromError,
@@ -155,7 +165,9 @@ import {
155
165
  saveJob,
156
166
  saveLedger,
157
167
  saveSubmittedJob,
168
+ settleAnsweredAsk,
158
169
  settleJobIdentity,
170
+ settleRecordedPayments,
159
171
  settlementCurrencyHint,
160
172
  statusSnapshot,
161
173
  sweepPendingMints,
@@ -169,6 +181,7 @@ import {
169
181
  unknownCurrencyHint,
170
182
  unknownUpfrontPrice,
171
183
  unrecordedFloatBudgetWarning,
184
+ unresendablePaymentHint,
172
185
  updateJob,
173
186
  walletHistory,
174
187
  warnInvalidJobIdentityHeader,
@@ -176,7 +189,7 @@ import {
176
189
  withIdentityRecovery,
177
190
  withJobTokenRedaction,
178
191
  withRequestResultRecovery
179
- } from "./chunk-ZKC6KN36.js";
192
+ } from "./chunk-BFYZO3BV.js";
180
193
  import {
181
194
  connectedTempoAccount,
182
195
  generateTempoKey,
@@ -202,7 +215,7 @@ import {
202
215
  tryResolveBtcUsdRate,
203
216
  tryX402Payment,
204
217
  withOutputWarnings
205
- } from "./chunk-LPILVPFG.js";
218
+ } from "./chunk-5SHB3MZ7.js";
206
219
  import {
207
220
  assertSupportedX402Network,
208
221
  connectedX402Payer,
@@ -727,8 +740,10 @@ import {
727
740
  bytesToHex,
728
741
  chainIdFromCaip2,
729
742
  concatBytes,
743
+ decodePayment,
730
744
  decodePaymentRequiredHeader,
731
745
  ensureAddress,
746
+ exactEvmAuthorization,
732
747
  generateX402PrivateKey,
733
748
  hexToBytes,
734
749
  hmac,
@@ -9899,6 +9914,10 @@ async function sweepPendingSubmissions(opts = {}) {
9899
9914
  outcomes.push(await resolveEntry(entry, deps, now(), unreadable.has(entry.request_id)));
9900
9915
  }
9901
9916
  if (outcomes.some(mutatesWallet)) {
9917
+ try {
9918
+ recordSubmissionVerdicts(outcomes.flatMap(verdictFor));
9919
+ } catch {
9920
+ }
9902
9921
  await withWalletLock(() => {
9903
9922
  const fresh = loadAgentWallet() ?? wallet;
9904
9923
  const next = outcomes.reduce(
@@ -9907,9 +9926,16 @@ async function sweepPendingSubmissions(opts = {}) {
9907
9926
  );
9908
9927
  saveAgentWallet(next);
9909
9928
  });
9929
+ await applySubmissionVerdicts().catch(() => void 0);
9910
9930
  }
9911
9931
  return { outcomes };
9912
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
+ }
9913
9939
  async function recoverPendingSubmission(opts) {
9914
9940
  if (!UUID_V4_RE.test(opts.requestId))
9915
9941
  throw new DvmError("invalid_request_id", "The pending-submission request id must be a UUIDv4.");
@@ -11222,7 +11248,10 @@ function isSignedRequestAudience(value) {
11222
11248
 
11223
11249
  // src/lib/payment-responder.ts
11224
11250
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11251
+ const seq = opts?.requestSeq;
11252
+ let replacing = false;
11225
11253
  return withJobPaymentLock(jobId, (assertOwned) => {
11254
+ replacing = opts?.approval === "explicit" && seq !== void 0 && loadJob(jobId)?.askPaymentBlocks?.[seq] !== void 0;
11226
11255
  const guardedTransport = new Proxy(transport, {
11227
11256
  get(target, key) {
11228
11257
  if (key === "sendMessage") return async (...args) => {
@@ -11246,6 +11275,19 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11246
11275
  } catch {
11247
11276
  }
11248
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
+ }
11249
11291
  const command = requestId ? `dvm request-result ${shellQuoteArg(requestId)}` : `dvm status ${guidanceJobArg(jobId)}`;
11250
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.`;
11251
11293
  error.data = providerFields({
@@ -11276,8 +11318,6 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11276
11318
  "The original upfront credit debit is unknown or conflicting.",
11277
11319
  "Recover the accepted upfront amount with 'dvm request-result' before authorizing more payments."
11278
11320
  );
11279
- const spent = job?.totalPaidMsats ?? 0;
11280
- const paymentsHonoured = job?.paymentsHonoured ?? 0;
11281
11321
  const pinnedMint = job?.pinnedMint;
11282
11322
  const strictPerCall = job?.strictPerCall === true;
11283
11323
  const maxCashuFeeSats = job?.maxCashuFeeSats;
@@ -11310,16 +11350,31 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11310
11350
  "The saved balance payment was not recovered; no replacement payment was sent.",
11311
11351
  `Run \`dvm status ${shellQuoteArg(jobId)}\` to refresh the job, then run \`dvm pay ${shellQuoteArg(jobId)}\` only if payment is still requested.`
11312
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;
11313
11360
  if (matchingEndpoint && opts?.requestSeq !== void 0) {
11314
11361
  if (job.inFlightPaymentRequestSeqs?.includes(opts.requestSeq))
11315
11362
  await reconcileInFlightPaymentRequest(jobId, opts.requestSeq, transport, provider, { jobToken });
11363
+ await settleRecordedPayments(jobId);
11316
11364
  if (loadAnsweredYieldSeqs(jobId).has(opts.requestSeq))
11317
11365
  throw new DvmError(
11318
11366
  "payment_already_sent",
11319
11367
  "Payment already sent for this request.",
11320
11368
  `Keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
11321
11369
  );
11322
- }
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;
11323
11378
  if (policy.maxIncrementMsats > 0 && request2.amount_msats > policy.maxIncrementMsats) {
11324
11379
  return "over-budget";
11325
11380
  }
@@ -11336,6 +11391,27 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11336
11391
  "Verify the original one-payment quote; do not authorize a fallback or replacement payment."
11337
11392
  );
11338
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";
11339
11415
  if (matchingEndpoint && !balanceRefused && opts?.rail === void 0) {
11340
11416
  const creditPaid = await tryCreditPayment({
11341
11417
  jobId,
@@ -11387,7 +11463,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11387
11463
  }
11388
11464
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11389
11465
  const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
11390
- const { tryX402Payment: tryX402Payment2 } = await import("./client-RSHQFXCA.js");
11466
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-YIHI4AIC.js");
11391
11467
  const wallet = loadX402Wallet2();
11392
11468
  if (wallet) {
11393
11469
  let proof;
@@ -11416,34 +11492,25 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11416
11492
  }
11417
11493
  if (proof) {
11418
11494
  await enforceGlobalBudget({ plannedMsats: proof.amountMsats, btcRate: proof.btcRate });
11419
- await sendRailPayment(
11420
- transport,
11495
+ return deliverSignedRailPayment({
11421
11496
  jobId,
11422
- {
11423
- type: "payment",
11424
- content: {
11425
- x402_payment: proof.paymentHeader,
11426
- amount_msats: proof.amountMsats
11427
- }
11428
- },
11497
+ request: request2,
11498
+ transport,
11429
11499
  provider,
11430
- { jobToken },
11431
- matchingEndpoint ? opts?.requestSeq : void 0
11432
- );
11433
- addPayment(jobId, proof.amountMsats, approval);
11434
- recordSpend({
11435
- msats: proof.amountMsats,
11436
- btcRate: proof.btcRate,
11437
- jobId,
11438
- providerEndpoint: provider.endpoint,
11439
- ...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
+ }
11440
11513
  });
11441
- return {
11442
- status: "paid",
11443
- rail: "x402",
11444
- amountMsats: proof.amountMsats,
11445
- amountUsdcMicro: proof.amountUsdcMicro
11446
- };
11447
11514
  }
11448
11515
  }
11449
11516
  }
@@ -11453,36 +11520,103 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11453
11520
  if (cred) {
11454
11521
  const paidMsats = usdcToMsats(Number(tempoCredentialAmountMicro(cred)) / 1e6, tempoRate);
11455
11522
  await enforceGlobalBudget({ plannedMsats: paidMsats, btcRate: tempoRate });
11456
- await sendRailPayment(
11457
- transport,
11523
+ return deliverSignedRailPayment({
11458
11524
  jobId,
11459
- {
11460
- type: "payment",
11461
- content: {
11462
- tempo_credential: cred,
11463
- amount_msats: paidMsats
11464
- }
11465
- },
11525
+ request: request2,
11526
+ transport,
11466
11527
  provider,
11467
- { jobToken },
11468
- matchingEndpoint ? opts?.requestSeq : void 0
11469
- );
11470
- addPayment(jobId, paidMsats, approval);
11471
- recordSpend({
11472
- msats: paidMsats,
11473
- btcRate: tempoRate,
11474
- jobId,
11475
- providerEndpoint: provider.endpoint,
11476
- ...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
+ }
11477
11540
  });
11478
- return { status: "paid", rail: "tempo", amountMsats: paidMsats };
11479
11541
  }
11480
11542
  }
11481
11543
  return "needs-approval";
11482
11544
  }
11483
- function midJobSpendLabel(reason) {
11484
- const text = reason.trim();
11485
- 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
+ };
11486
11620
  }
11487
11621
  async function tryAgentWalletMidJobPayment(args) {
11488
11622
  const {
@@ -11542,22 +11676,57 @@ async function tryAgentWalletMidJobPayment(args) {
11542
11676
  prepared.error.attempts ? { mint_attempts: prepared.error.attempts } : void 0
11543
11677
  );
11544
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;
11545
11704
  try {
11546
- await sendMidJobPaymentWithRetry({
11705
+ sent = await sendMidJobPaymentWithRetry({
11547
11706
  jobId,
11548
11707
  amountMsats: request2.amount_msats,
11549
11708
  prepared,
11550
11709
  transport,
11551
11710
  provider,
11552
11711
  jobToken,
11553
- requestSeq: args.requestSeq
11712
+ requestSeq: args.requestSeq,
11713
+ submission,
11714
+ redelivery: args.redelivery
11554
11715
  });
11555
11716
  } catch (err) {
11556
- if (err instanceof DvmError && err.code === "payment_invalid") {
11717
+ if (err instanceof DvmError && err.code === "payment_invalid" && sendOutcome(err, submission, args.redelivery).kind === "refused") {
11557
11718
  await abandonPendingSubmission({ requestId: prepared.requestId, preserveRecovery: true });
11558
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
+ }
11559
11724
  throw err;
11560
11725
  }
11726
+ if (sent.tracked) {
11727
+ if (sent.booked) await finishBookedSubmission(jobId, sent.booked, provider.endpoint);
11728
+ return;
11729
+ }
11561
11730
  await commitAgentSpend({
11562
11731
  requestId: prepared.requestId,
11563
11732
  recentSpend: {
@@ -11571,16 +11740,15 @@ async function tryAgentWalletMidJobPayment(args) {
11571
11740
  addPayment(jobId, request2.amount_msats, approval);
11572
11741
  recordSpend({
11573
11742
  msats: request2.amount_msats,
11574
- btcRate,
11743
+ btcRate: submission.btcRate,
11575
11744
  jobId,
11576
11745
  providerEndpoint: provider.endpoint,
11577
11746
  ...midJobSpendLabel(request2.reason)
11578
11747
  });
11579
- return true;
11580
11748
  }
11581
11749
  async function sendMidJobPaymentWithRetry(args) {
11582
11750
  const { jobId, amountMsats, prepared, transport, provider, jobToken } = args;
11583
- await withAgentWalletPaymentRetry({
11751
+ return withAgentWalletPaymentRetry({
11584
11752
  attempt: () => sendRailPayment(
11585
11753
  transport,
11586
11754
  jobId,
@@ -11595,14 +11763,16 @@ async function sendMidJobPaymentWithRetry(args) {
11595
11763
  },
11596
11764
  provider,
11597
11765
  { jobToken },
11598
- args.requestSeq
11766
+ args.requestSeq,
11767
+ args.submission,
11768
+ args.redelivery
11599
11769
  ),
11600
11770
  intendedLockPubkey: prepared.intendedLockPubkey,
11601
11771
  refetchInfo: () => transport.describe(provider),
11602
11772
  sleep: args.sleep
11603
11773
  });
11604
11774
  }
11605
- async function sendRailPayment(transport, jobId, message2, provider, options, requestSeq) {
11775
+ async function sendRailPayment(transport, jobId, message2, provider, options, requestSeq, submission, redelivery) {
11606
11776
  const capture = (evidence) => {
11607
11777
  if (evidence.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
11608
11778
  if (evidence.drawFundingReceipt) captureDrawFundingReceipts(jobId, [evidence.drawFundingReceipt], {
@@ -11610,31 +11780,81 @@ async function sendRailPayment(transport, jobId, message2, provider, options, re
11610
11780
  ...typeof message2.content.cashu_request_id === "string" ? { fundId: message2.content.cashu_request_id } : {}
11611
11781
  });
11612
11782
  };
11613
- if (requestSeq !== void 0) markPaymentRequestInFlight(jobId, requestSeq);
11783
+ if (requestSeq !== void 0) markPaymentRequestInFlight(jobId, requestSeq, submission);
11784
+ let result;
11614
11785
  try {
11615
- const result = await transport.sendMessage(jobId, message2, provider, options);
11616
- if (requestSeq !== void 0) markPaymentRequestPaid(jobId, requestSeq);
11617
- if (result) capture(result);
11786
+ result = await transport.sendMessage(jobId, message2, provider, options);
11618
11787
  } catch (error) {
11619
- if (requestSeq !== void 0) {
11620
- if (error instanceof DvmError && error.code === "replay_rejected") markPaymentRequestPaid(jobId, requestSeq);
11621
- else if (definitelyNotAccepted(error)) clearPaymentRequestInFlight(jobId, requestSeq);
11622
- else markPaymentRequestInFlight(jobId, requestSeq);
11623
- }
11624
11788
  if (error instanceof DvmError && error.data) capture(error.data);
11625
- 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);
11626
11799
  throw error;
11627
11800
  }
11628
- }
11629
- function definitelyNotAccepted(error) {
11630
- if (error instanceof DvmError) {
11631
- const status2 = error.data?.http_status;
11632
- 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 {
11633
11850
  }
11634
- 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;
11635
11855
  if ("code" in error && ["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH"].includes(String(error.code))) return true;
11636
- if (error instanceof AggregateError) return error.errors.length > 0 && error.errors.every(definitelyNotAccepted);
11637
- return definitelyNotAccepted(error.cause);
11856
+ if (error instanceof AggregateError) return error.errors.length > 0 && error.errors.every(requestNeverSent);
11857
+ return requestNeverSent(error.cause);
11638
11858
  }
11639
11859
  async function tryMppCredential(challenges, amountMsats, btcRate) {
11640
11860
  const wallet = loadConfig()?.tempo;
@@ -11786,7 +12006,7 @@ async function streamLoop(opts) {
11786
12006
  let messageAppendSession = opts.messageAppendSession;
11787
12007
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
11788
12008
  const declined = () => persistLocalState && loadJob(jobId)?.callerDeclined === true;
11789
- function recordAutoPayment(result, request2, seq) {
12009
+ async function recordAutoPayment(result, request2, seq) {
11790
12010
  autoPayments.push({
11791
12011
  amount_msats: result.amountMsats,
11792
12012
  rail: result.rail,
@@ -11794,7 +12014,7 @@ async function streamLoop(opts) {
11794
12014
  ...result.amountUsdcMicro !== void 0 && { amount_usdc_microunits: result.amountUsdcMicro },
11795
12015
  display: paidConfirmationDisplay(result, request2.fiat_amount)
11796
12016
  });
11797
- if (persistLocalState) markPaymentRequestPaid(jobId, seq);
12017
+ if (persistLocalState) markPaymentRequestAnswered(jobId, seq);
11798
12018
  answeredSeqs.add(seq);
11799
12019
  justAutoPaid = true;
11800
12020
  }
@@ -11809,10 +12029,10 @@ async function streamLoop(opts) {
11809
12029
  });
11810
12030
  } catch (error) {
11811
12031
  if (error instanceof DvmError && error.code === "payment_settling")
11812
- 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)) };
11813
12033
  throw error;
11814
12034
  }
11815
- 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);
11816
12036
  else pendingAction = computeNextAction(jobId, [{
11817
12037
  seq: pending4.authorization.request_seq,
11818
12038
  from: "provider",
@@ -11875,6 +12095,7 @@ async function streamLoop(opts) {
11875
12095
  if (persistLocalState) {
11876
12096
  messageAppendSession ??= createMessageAppendSession(jobId);
11877
12097
  messageAppendSession.append(batchMessages);
12098
+ await settleRecordedPayments(jobId);
11878
12099
  }
11879
12100
  if (persistLocalState) {
11880
12101
  refunds.push(...await claimInboundPayments(jobId, batchMessages));
@@ -11885,7 +12106,8 @@ async function streamLoop(opts) {
11885
12106
  const pendingPayment = pendingPaymentRequest(batchMessages, answeredSeqs);
11886
12107
  const lastYield2 = findLastYield(batchMessages.filter((message2) => !answeredSeqs.has(message2.seq) && (message2.type !== "payment-request" || message2.seq === pendingPayment?.seq))) ?? findLastYield(batchMessages);
11887
12108
  if (lastYield2?.type === "payment-request" && answeredSeqs.has(lastYield2.seq)) {
11888
- if (persistLocalState) markPaymentRequestPaid(jobId, lastYield2.seq);
12109
+ if (persistLocalState && !declinedAskSeqs(jobId).has(lastYield2.seq))
12110
+ await settleAnsweredAsk(jobId, lastYield2.seq, loadMessages(jobId));
11889
12111
  break;
11890
12112
  }
11891
12113
  if (lastYield2?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield2.seq)) {
@@ -11915,8 +12137,9 @@ async function streamLoop(opts) {
11915
12137
  requestSeq: lastYield2.seq
11916
12138
  });
11917
12139
  } catch (error) {
11918
- if (error instanceof DvmError && error.code === "payment_settling") {
12140
+ if (error instanceof DvmError && ["payment_settling", "payment_unconfirmed"].includes(error.code)) {
11919
12141
  paymentUnresolved = true;
12142
+ if (error.code === "payment_unconfirmed") cursor = Math.min(cursor, lastYield2.seq - 1);
11920
12143
  break;
11921
12144
  }
11922
12145
  if (error instanceof DvmError && error.code === "payment_already_sent") {
@@ -11926,7 +12149,7 @@ async function streamLoop(opts) {
11926
12149
  throw error;
11927
12150
  }
11928
12151
  if (typeof result === "object") {
11929
- recordAutoPayment(result, req, lastYield2.seq);
12152
+ await recordAutoPayment(result, req, lastYield2.seq);
11930
12153
  continue;
11931
12154
  }
11932
12155
  if (result === "payment-cap-exceeded") {
@@ -11969,6 +12192,7 @@ async function streamLoop(opts) {
11969
12192
  if (persistLocalState) {
11970
12193
  messageAppendSession ??= createMessageAppendSession(jobId);
11971
12194
  messageAppendSession.append(recheck);
12195
+ await settleRecordedPayments(jobId);
11972
12196
  refunds.push(...await claimInboundPayments(jobId, recheck));
11973
12197
  }
11974
12198
  }
@@ -11979,8 +12203,9 @@ async function streamLoop(opts) {
11979
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);
11980
12204
  let nextAction = withRefundNextAction(jobId, yieldAction ?? (terminal ? null : pollNextAction(jobId)), refunds);
11981
12205
  const lastYield = findLastYield(allMessages);
11982
- if (nextAction?.type === "pay" && lastYield?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield.seq))
11983
- 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) };
11984
12209
  if (nextAction?.type === "pay" || nextAction?.type === "poll" && !terminal) {
11985
12210
  if (lastYield?.type === "payment-request" && answeredSeqs.has(lastYield.seq)) {
11986
12211
  nextAction = {
@@ -11990,7 +12215,11 @@ async function streamLoop(opts) {
11990
12215
  };
11991
12216
  }
11992
12217
  }
11993
- 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
+ ));
11994
12223
  return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
11995
12224
  }
11996
12225
  function isMessagePollTimeout(err) {
@@ -12868,7 +13097,7 @@ var HttpsTransport = class {
12868
13097
  }
12869
13098
  if (res.status === 409) {
12870
13099
  const body2 = parseJsonObject(await res.text());
12871
- 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")) {
12872
13101
  const error = withDrawFunding(withCreditErrorContext(buildPaymentError(body2), body2), body2);
12873
13102
  error.data = { ...error.data, http_status: res.status };
12874
13103
  throw error;
@@ -13271,8 +13500,12 @@ function isReceipt402(code) {
13271
13500
  return code === void 0 || code === "payment_required" || code === "payment_insufficient";
13272
13501
  }
13273
13502
  function buildPaymentError(errorBody) {
13274
- const code = typeof errorBody.error === "string" ? errorBody.error : "payment_insufficient";
13275
- 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;
13276
13509
  }
13277
13510
  async function paymentHeaders(payment) {
13278
13511
  const headers = {};
@@ -13947,7 +14180,7 @@ async function settleCreditAfterJob(args) {
13947
14180
  }
13948
14181
  }
13949
14182
  if (args.allowTopup !== false) {
13950
- const refill = args.refillPocket ?? (await import("./pocket-refill-7Q6CR6I4.js")).refillPocketIfLow;
14183
+ const refill = args.refillPocket ?? (await import("./pocket-refill-KA37CF4N.js")).refillPocketIfLow;
13951
14184
  await refill({ human: args.human }).catch(() => void 0);
13952
14185
  }
13953
14186
  }
@@ -14374,7 +14607,10 @@ async function cancelWithAccess(jobId, opts, access) {
14374
14607
  ref,
14375
14608
  jobToken,
14376
14609
  persistLocalState: !access.endpointOverridden,
14377
- human: opts.human
14610
+ human: opts.human,
14611
+ onTerminal: () => {
14612
+ if (!access.endpointOverridden) clearAskPaymentBlocks(jobId);
14613
+ }
14378
14614
  });
14379
14615
  transport.close();
14380
14616
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
@@ -14426,12 +14662,15 @@ async function declineWithAccess(jobId, opts, access) {
14426
14662
  persistLocalState: !access.endpointOverridden,
14427
14663
  human: opts.human,
14428
14664
  onTerminal: (status2) => {
14429
- if (!access.endpointOverridden && isTerminalJobStatus(status2.status)) markJobTerminal(
14430
- jobId,
14431
- status2.status,
14432
- opts.reason !== void 0 ? { message: opts.reason } : {},
14433
- { callerCancelled: true, callerDeclined: true }
14434
- );
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
+ }
14435
14674
  }
14436
14675
  });
14437
14676
  transport.close();
@@ -24835,6 +25074,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
24835
25074
  for (const message2 of tail) onMessage(message2);
24836
25075
  if (opts.persistLocalState !== false) {
24837
25076
  messageAppendSession?.append(tail);
25077
+ await settleRecordedPayments(opts.jobId);
24838
25078
  result.refunds.push(...await claimInboundPayments(opts.jobId, tail));
24839
25079
  }
24840
25080
  result.nextAction = withRefundNextAction(opts.jobId, null, result.refunds);
@@ -24853,7 +25093,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
24853
25093
  assertOwned();
24854
25094
  for (const seq of loadJob(opts.jobId)?.inFlightPaymentRequestSeqs ?? []) {
24855
25095
  try {
24856
- reconcilePaymentRequestHistory(opts.jobId, seq, messages2, snapshot.status, now);
25096
+ await reconcilePaymentRequestHistory(opts.jobId, seq, messages2, snapshot.status, now);
24857
25097
  } catch (error) {
24858
25098
  if (!(error instanceof DvmError) || !["payment_settling", "payment_request_not_pending"].includes(error.code)) throw error;
24859
25099
  if (!loadJob(opts.jobId)?.inFlightPaymentRequestSeqs?.includes(seq)) continue;
@@ -24873,6 +25113,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
24873
25113
  }
24874
25114
  if (!history) break;
24875
25115
  messageAppendSession?.append(history);
25116
+ if (opts.persistLocalState !== false) await settleRecordedPayments(opts.jobId);
24876
25117
  const answered = opts.persistLocalState === false ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(opts.jobId);
24877
25118
  for (const seq of answeredYieldSeqs(history)) answered.add(seq);
24878
25119
  const pending4 = history.findLast((msg) => msg.from === "provider" && ["prompt", "payment-request", "working", "complete", "cancel"].includes(msg.type) && !answered.has(msg.seq));
@@ -24943,8 +25184,9 @@ async function messagesWithAccess(jobId, opts, access) {
24943
25184
  const answered = access.endpointOverridden ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(jobId);
24944
25185
  const action = computeNextAction(jobId, batch.filter((message2) => !answered.has(message2.seq)), void 0, access.endpointOverridden ? void 0 : stored ?? void 0);
24945
25186
  const request2 = batch.findLast((message2) => message2.type === "payment-request");
24946
- if (action?.type === "pay" && request2 && !access.endpointOverridden && stored?.inFlightPaymentRequestSeqs?.includes(request2.seq))
24947
- 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) };
24948
25190
  return action;
24949
25191
  }
24950
25192
  async function resolveNextAction2(action, messages2, observedStatus) {
@@ -24985,7 +25227,10 @@ async function messagesWithAccess(jobId, opts, access) {
24985
25227
  }
24986
25228
  throw err;
24987
25229
  }
24988
- if (!access.endpointOverridden) appendMessages(jobId, msgs);
25230
+ if (!access.endpointOverridden) {
25231
+ appendMessages(jobId, msgs);
25232
+ await settleRecordedPayments(jobId);
25233
+ }
24989
25234
  const newCursor = maxSeq(msgs, after);
24990
25235
  const providerStatus2 = await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken });
24991
25236
  if (!access.endpointOverridden) {
@@ -30224,13 +30469,17 @@ async function statusWithAccess(jobId, opts, access) {
30224
30469
  if (opts.messages) {
30225
30470
  const after = access.endpointOverridden ? 0 : stored?.messageCursor ?? 0;
30226
30471
  msgs = await transport.getMessages(jobId, after, ref, { timeoutMs: timeout, jobToken });
30227
- if (!access.endpointOverridden) appendMessages(jobId, msgs);
30472
+ if (!access.endpointOverridden) {
30473
+ appendMessages(jobId, msgs);
30474
+ await settleRecordedPayments(jobId);
30475
+ }
30228
30476
  newCursor = maxSeq(msgs, after);
30229
30477
  }
30230
30478
  const nextAction = await resolveNextAction(jobId, result.status, msgs, transport, ref, {
30231
30479
  timeoutMs: timeout,
30232
30480
  jobToken,
30233
- 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)
30234
30483
  });
30235
30484
  const completion = completionSnapshot(result);
30236
30485
  const reasonUnavailable = completion.message === void 0 || result.content_available === false && completion.message === "";
@@ -30372,12 +30621,19 @@ async function resolveNextAction(jobId, status2, fetched, transport, ref, opts)
30372
30621
  if (isTerminalJobStatus(status2)) return null;
30373
30622
  if (status2 === "awaiting-input") {
30374
30623
  const fromBatch = computeNextAction(jobId, fetched, void 0, opts.context);
30375
- if (fromBatch) return fromBatch;
30624
+ if (fromBatch) return withHeldPaymentHint(jobId, fromBatch, fetched, opts.held);
30376
30625
  const history = await transport.getMessages(jobId, 0, ref, opts);
30377
- 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);
30378
30627
  }
30379
30628
  return pollNextAction(jobId);
30380
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
+ }
30381
30637
 
30382
30638
  // src/commands/upload.ts
30383
30639
  import { statSync as statSync4 } from "fs";
@@ -37681,10 +37937,13 @@ async function forgetSubmission(requestId, opts) {
37681
37937
  await confirmForget(view, opts);
37682
37938
  await abandonPendingSubmission({ requestId });
37683
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.`;
37684
37942
  if (opts.human) {
37685
37943
  info(
37686
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).`
37687
37945
  );
37946
+ if (warning) info(`Warning: ${warning}`);
37688
37947
  return;
37689
37948
  }
37690
37949
  json({
@@ -37693,7 +37952,8 @@ async function forgetSubmission(requestId, opts) {
37693
37952
  endpoint: view.endpoint,
37694
37953
  abandoned_sats: abandoned,
37695
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.`,
37696
- 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 })) } : {}
37697
37957
  });
37698
37958
  }
37699
37959
  function refuseIfSelfHealing(view, opts) {