@dvmkit/dvm-cli 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/{chunk-BHR7QHJG.js → chunk-3R2GM6AD.js} +2 -2
  2. package/dist/{chunk-TGRY23IF.js → chunk-6EYBCGGD.js} +2 -2
  3. package/dist/{chunk-NXXU3BSJ.js → chunk-7N3HQJKE.js} +4 -4
  4. package/dist/{chunk-C3HMFGYP.js → chunk-BPWZNIMS.js} +2 -2
  5. package/dist/{chunk-MTGQK7KA.js → chunk-GEZVSJDM.js} +3 -3
  6. package/dist/{chunk-GD25CUI4.js → chunk-GHNF2I5C.js} +4 -4
  7. package/dist/{chunk-3YU6KRCX.js → chunk-HWWW7JEM.js} +3 -3
  8. package/dist/{chunk-Q45TAYK2.js → chunk-JJBRTWWS.js} +160 -7
  9. package/dist/{chunk-HUBCGZJL.js → chunk-K562SFVD.js} +2 -2
  10. package/dist/{chunk-CWWZM4M6.js → chunk-MBSCP52L.js} +564 -204
  11. package/dist/{chunk-GMOKL4PQ.js → chunk-MMXHV3KC.js} +2 -2
  12. package/dist/{chunk-IEWV3CM2.js → chunk-UVFFMKU4.js} +3 -1
  13. package/dist/{client-MFSKFSV4.js → client-DS4QJ346.js} +6 -6
  14. package/dist/dvm.js +1075 -251
  15. package/dist/{internal-5EGKBZAE.js → internal-ZZHCUKOM.js} +5 -5
  16. package/dist/{lifecycle-7AVB36WP.js → lifecycle-XGNIMPTB.js} +6 -6
  17. package/dist/{payout-reporter-NXWQVKXW-KHVN6C4Z.js → payout-reporter-DDQ7FGRC-OKICJCC2.js} +2 -2
  18. package/dist/{pocket-refill-SKECWGA3.js → pocket-refill-3ZV36DOA.js} +10 -10
  19. package/dist/{revenue-reporter-HD4GMXGD-LAZU45ZA.js → revenue-reporter-RIEHBKRA-75BDPVVX.js} +2 -2
  20. package/dist/{tempo-lifecycle-SVPMTND2.js → tempo-lifecycle-LGGBDCKK.js} +8 -8
  21. package/dist/{tempo-wallet-5PKLSWFX.js → tempo-wallet-PLFC443A.js} +7 -7
  22. package/dist/{wallet-7BBWAZYJ.js → wallet-UJ7EJNQA.js} +7 -7
  23. package/dist/{x402-RUJ4LUKF-ZB7JM22B.js → x402-AY6P5KV4-SIZF7YNW.js} +2 -2
  24. package/package.json +2 -2
  25. package/skills/dvm/calling.md +15 -1
package/dist/dvm.js CHANGED
@@ -5,10 +5,10 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-3YU6KRCX.js";
8
+ } from "./chunk-HWWW7JEM.js";
9
9
  import {
10
10
  assertX402WalletIdle
11
- } from "./chunk-TGRY23IF.js";
11
+ } from "./chunk-6EYBCGGD.js";
12
12
  import {
13
13
  DEFAULT_CREDIT_POSTURE,
14
14
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
@@ -26,6 +26,7 @@ import {
26
26
  captureDrawFundingReceipts,
27
27
  captureFundingReceipt,
28
28
  captureTransportReceipt,
29
+ clearPaymentRequestInFlight,
29
30
  commitAgentSpend,
30
31
  correctPendingFundAmount,
31
32
  deriveAlias,
@@ -46,6 +47,8 @@ import {
46
47
  fundAgentWallet,
47
48
  fundCredit,
48
49
  fundTimeoutMs,
50
+ hasUnknownUpfrontCredit,
51
+ hasUnknownUpfrontRail,
49
52
  identityDataFields,
50
53
  identityError,
51
54
  inFlightTimeoutSeconds,
@@ -63,6 +66,8 @@ import {
63
66
  loadLedger,
64
67
  loadSubmissionEvidence,
65
68
  markJobTerminal,
69
+ markPaymentRequestInFlight,
70
+ markPaymentRequestPaid,
66
71
  markPendingSubmissionUnresolved,
67
72
  markProofsInFlight,
68
73
  meltInFlightTimeoutSeconds,
@@ -70,6 +75,8 @@ import {
70
75
  needsTopup,
71
76
  parseLocktime,
72
77
  parseStatedBudget,
78
+ parseUpfrontPayment,
79
+ parseUpfrontRailPayment,
73
80
  payViaFloat,
74
81
  pickCreditFundRail,
75
82
  planCreditForQuote,
@@ -91,6 +98,8 @@ import {
91
98
  recordSpend,
92
99
  recordSpendOnce,
93
100
  recordSubmissionEvidence,
101
+ recordUpfrontCreditPayment,
102
+ recordUpfrontRailPayment,
94
103
  removeFavorite,
95
104
  renderReceiptHuman,
96
105
  replayStoredReceipt,
@@ -105,6 +114,7 @@ import {
105
114
  saveFavorite,
106
115
  saveJob,
107
116
  saveLedger,
117
+ saveSubmittedJob,
108
118
  settleJobIdentity,
109
119
  statusSnapshot,
110
120
  sweepPendingMints,
@@ -120,13 +130,13 @@ import {
120
130
  withIdentityRecovery,
121
131
  withJobTokenRedaction,
122
132
  withRequestResultRecovery
123
- } from "./chunk-Q45TAYK2.js";
133
+ } from "./chunk-JJBRTWWS.js";
124
134
  import {
125
135
  connectedTempoAccount,
126
136
  generateTempoKey,
127
137
  tempoBalanceCheckHint,
128
138
  tempoWrongAssetHint
129
- } from "./chunk-NXXU3BSJ.js";
139
+ } from "./chunk-7N3HQJKE.js";
130
140
  import {
131
141
  assertValidBudget,
132
142
  costAnchor,
@@ -144,7 +154,7 @@ import {
144
154
  staleRateNotice,
145
155
  tryResolveBtcUsdRate,
146
156
  tryX402Payment
147
- } from "./chunk-C3HMFGYP.js";
157
+ } from "./chunk-BPWZNIMS.js";
148
158
  import {
149
159
  assertSupportedX402Network,
150
160
  connectedX402Payer,
@@ -153,7 +163,7 @@ import {
153
163
  repinX402WalletNetwork,
154
164
  saveX402Wallet,
155
165
  x402NetworkLabel
156
- } from "./chunk-MTGQK7KA.js";
166
+ } from "./chunk-GEZVSJDM.js";
157
167
  import {
158
168
  CREDIT_POSTURES,
159
169
  FEEDBACK_POSTURES,
@@ -170,7 +180,7 @@ import {
170
180
  retireConfigBackup,
171
181
  rollbackConfig,
172
182
  updateConfig
173
- } from "./chunk-GMOKL4PQ.js";
183
+ } from "./chunk-MMXHV3KC.js";
174
184
  import {
175
185
  A,
176
186
  AGENT_MNEMONIC_FILE,
@@ -414,7 +424,7 @@ import {
414
424
  x402PendingUnsettled,
415
425
  x402RequiredFromError,
416
426
  x402ReservationRelease
417
- } from "./chunk-CWWZM4M6.js";
427
+ } from "./chunk-MBSCP52L.js";
418
428
  import "./chunk-JBU7RKQ3.js";
419
429
  import "./chunk-KDNFUDOG.js";
420
430
  import "./chunk-IUTVV6N5.js";
@@ -455,11 +465,11 @@ import {
455
465
  usdToMsats,
456
466
  usdcToMsats,
457
467
  x402NetworkByCaip2
458
- } from "./chunk-GD25CUI4.js";
459
- import "./chunk-HUBCGZJL.js";
460
- import "./chunk-BHR7QHJG.js";
468
+ } from "./chunk-GHNF2I5C.js";
469
+ import "./chunk-K562SFVD.js";
470
+ import "./chunk-3R2GM6AD.js";
461
471
  import "./chunk-R2DSAZBO.js";
462
- import "./chunk-IEWV3CM2.js";
472
+ import "./chunk-UVFFMKU4.js";
463
473
  import {
464
474
  privateKeyToAccount
465
475
  } from "./chunk-EVQERRCP.js";
@@ -5224,11 +5234,11 @@ var require_dijkstra = __commonJS({
5224
5234
  var predecessors = {};
5225
5235
  var costs = {};
5226
5236
  costs[s] = 0;
5227
- var open = dijkstra.PriorityQueue.make();
5228
- open.push(s, 0);
5237
+ var open2 = dijkstra.PriorityQueue.make();
5238
+ open2.push(s, 0);
5229
5239
  var closest, u, v, cost_of_s_to_u, adjacent_nodes, cost_of_e, cost_of_s_to_u_plus_cost_of_e, cost_of_s_to_v, first_visit;
5230
- while (!open.empty()) {
5231
- closest = open.pop();
5240
+ while (!open2.empty()) {
5241
+ closest = open2.pop();
5232
5242
  u = closest.value;
5233
5243
  cost_of_s_to_u = closest.cost;
5234
5244
  adjacent_nodes = graph[u] || {};
@@ -5240,7 +5250,7 @@ var require_dijkstra = __commonJS({
5240
5250
  first_visit = typeof costs[v] === "undefined";
5241
5251
  if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
5242
5252
  costs[v] = cost_of_s_to_u_plus_cost_of_e;
5243
- open.push(v, cost_of_s_to_u_plus_cost_of_e);
5253
+ open2.push(v, cost_of_s_to_u_plus_cost_of_e);
5244
5254
  predecessors[v] = u;
5245
5255
  }
5246
5256
  }
@@ -8747,6 +8757,138 @@ function maxSeq(msgs, fallback) {
8747
8757
  return Math.max(...msgs.map((m) => m.seq));
8748
8758
  }
8749
8759
 
8760
+ // src/lib/payment-lock.ts
8761
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
8762
+ import { createHash } from "crypto";
8763
+ async function withJobPaymentLock(jobId, action) {
8764
+ ensureConfigDir();
8765
+ const key = createHash("sha256").update(jobId).digest("hex");
8766
+ let compromised = false;
8767
+ const assertOwned = () => {
8768
+ if (compromised) throw new DvmError(
8769
+ "payment_settling",
8770
+ "Payment lock ownership was lost.",
8771
+ `Retry shortly with \`dvm pay ${shellQuoteArg(jobId)}\`, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`
8772
+ );
8773
+ };
8774
+ let release;
8775
+ try {
8776
+ release = import_proper_lockfile.default.lockSync(`${JOBS_FILE}.payment-${key}`, {
8777
+ realpath: false,
8778
+ stale: 12e4,
8779
+ update: 1e4,
8780
+ onCompromised: () => {
8781
+ compromised = true;
8782
+ }
8783
+ });
8784
+ } catch (error) {
8785
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ELOCKED") throw error;
8786
+ throw new DvmError(
8787
+ "payment_settling",
8788
+ "Another dvm process is paying this job.",
8789
+ `Retry shortly with \`dvm pay ${shellQuoteArg(jobId)}\`, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`. If the lock is stale, it can take up to 2 minutes to clear.`
8790
+ );
8791
+ }
8792
+ try {
8793
+ return await action(assertOwned);
8794
+ } finally {
8795
+ if (!compromised) release();
8796
+ }
8797
+ }
8798
+
8799
+ // src/lib/yield-state.ts
8800
+ var JOB_READ_TIMEOUT_MS = 6e4;
8801
+ var PAYMENT_SETTLE_WINDOW_MS = 45e3;
8802
+ function answeredYieldSeqs(messages2) {
8803
+ const answered = /* @__PURE__ */ new Set();
8804
+ const prompts = /* @__PURE__ */ new Map();
8805
+ let paymentRequest;
8806
+ for (const message2 of [...messages2].sort((a, b) => a.seq - b.seq)) {
8807
+ if (message2.from === "provider") {
8808
+ if (message2.type === "payment-request") paymentRequest = message2.seq;
8809
+ if (message2.type === "prompt") prompts.set(message2.content.id, message2.seq);
8810
+ } else if (message2.type === "response") {
8811
+ const seq = prompts.get(message2.content.prompt_id);
8812
+ if (seq !== void 0) answered.add(seq);
8813
+ } else if (message2.type === "payment") {
8814
+ const seq = message2.content.credit?.request_seq ?? paymentRequest;
8815
+ if (seq !== void 0) answered.add(seq);
8816
+ }
8817
+ }
8818
+ return answered;
8819
+ }
8820
+ function latestProviderPaymentRequest(messages2) {
8821
+ return [...messages2].sort((a, b) => a.seq - b.seq).findLast((message2) => message2.from === "provider" && message2.type === "payment-request");
8822
+ }
8823
+ function pendingPaymentRequest(messages2, answered = answeredYieldSeqs(messages2)) {
8824
+ const latest = latestProviderPaymentRequest(messages2);
8825
+ if (!latest || answered.has(latest.seq)) return void 0;
8826
+ if (messages2.some((message2) => message2.from === "provider" && message2.seq > latest.seq && (message2.type === "complete" || message2.type === "cancel" || message2.type === "working"))) return void 0;
8827
+ return latest;
8828
+ }
8829
+ function loadAnsweredYieldSeqs(jobId) {
8830
+ const answered = answeredYieldSeqs(loadMessages(jobId));
8831
+ const job = loadJob(jobId);
8832
+ for (const seq of job?.paidPaymentRequestSeqs ?? []) answered.add(seq);
8833
+ for (const payment of job?.bookedCreditPayments ?? []) answered.add(payment.authorization.request_seq);
8834
+ return answered;
8835
+ }
8836
+ async function reconcileInFlightPaymentRequest(jobId, requestSeq, transport, provider, options) {
8837
+ const boundedOptions = { ...options, timeoutMs: options.timeoutMs ?? JOB_READ_TIMEOUT_MS };
8838
+ const history = await boundedPaymentRead(jobId, () => transport.getMessages(jobId, 0, provider, boundedOptions), boundedOptions.timeoutMs);
8839
+ const decisionTime = Date.now();
8840
+ const needsStatus = !answeredYieldSeqs(history).has(requestSeq) && decisionTime >= settleUntilMs(jobId, requestSeq, decisionTime);
8841
+ const status2 = needsStatus ? (await boundedPaymentRead(jobId, () => transport.status(jobId, provider, boundedOptions), boundedOptions.timeoutMs)).status : void 0;
8842
+ return reconcilePaymentRequestHistory(jobId, requestSeq, history, status2, () => decisionTime);
8843
+ }
8844
+ function reconcilePaymentRequestHistory(jobId, requestSeq, history, status2, now = Date.now) {
8845
+ if (answeredYieldSeqs(history).has(requestSeq)) {
8846
+ markPaymentRequestPaid(jobId, requestSeq);
8847
+ return true;
8848
+ }
8849
+ const superseded = (latestProviderPaymentRequest(history)?.seq ?? -1) > requestSeq;
8850
+ if (superseded) clearPaymentRequestInFlight(jobId, requestSeq);
8851
+ const decisionTime = now();
8852
+ const retryAt = settleUntilMs(jobId, requestSeq, decisionTime);
8853
+ const seconds = Math.ceil((retryAt - decisionTime) / 1e3);
8854
+ if (!superseded && decisionTime < retryAt)
8855
+ throw new DvmError(
8856
+ "payment_settling",
8857
+ "The previous payment may still be processing.",
8858
+ `Retry with \`dvm pay ${shellQuoteArg(jobId)}\` in about ${seconds} ${seconds === 1 ? "second" : "seconds"}, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`,
8859
+ { retry_at_ms: retryAt }
8860
+ );
8861
+ if (status2 !== "awaiting-input" || pendingPaymentRequest(history)?.seq !== requestSeq)
8862
+ throw new DvmError(
8863
+ "payment_request_not_pending",
8864
+ "The provider is no longer waiting on this payment request.",
8865
+ `Check the job with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
8866
+ );
8867
+ return false;
8868
+ }
8869
+ function settleUntilMs(jobId, requestSeq, now) {
8870
+ const startedAt = loadJob(jobId)?.inFlightPaymentRequestStartedAtMs?.[requestSeq];
8871
+ return startedAt === void 0 ? 0 : Math.min(startedAt + PAYMENT_SETTLE_WINDOW_MS, now + PAYMENT_SETTLE_WINDOW_MS);
8872
+ }
8873
+ async function boundedPaymentRead(jobId, read, timeoutMs) {
8874
+ let timer;
8875
+ try {
8876
+ return await Promise.race([read(), new Promise((_, reject) => {
8877
+ timer = setTimeout(() => reject(new DvmError("timeout", "Payment recovery read timed out. No new payment was sent.")), timeoutMs);
8878
+ })]);
8879
+ } catch (error) {
8880
+ if (isAbortError(error) || error instanceof DvmError && error.code === "timeout")
8881
+ throw new DvmError(
8882
+ "timeout",
8883
+ "Payment recovery read timed out. No new payment was sent.",
8884
+ `Retry with \`dvm pay ${shellQuoteArg(jobId)}\` or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`
8885
+ );
8886
+ throw error;
8887
+ } finally {
8888
+ if (timer) clearTimeout(timer);
8889
+ }
8890
+ }
8891
+
8750
8892
  // src/lib/next-action.ts
8751
8893
  function isTerminalJobStatus(status2) {
8752
8894
  return TERMINAL_STATUSES.has(status2);
@@ -8755,19 +8897,24 @@ function pollNextAction(jobId, hint) {
8755
8897
  return {
8756
8898
  type: "poll",
8757
8899
  job_id: jobId,
8758
- hint: hint ?? "Provider is working, check back later"
8900
+ hint: hint ?? `Provider is still working. Keep the job moving unattended with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`
8759
8901
  };
8760
8902
  }
8903
+ function paymentInFlightHint(jobId) {
8904
+ return `A payment may already have been sent for this request. Resolve it with \`dvm pay ${shellQuoteArg(jobId)}\`; it checks provider history before paying again.`;
8905
+ }
8761
8906
  var YIELD_TYPES = /* @__PURE__ */ new Set(["prompt", "payment-request", "working", "complete", "cancel"]);
8762
8907
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
8763
8908
  "completed",
8764
8909
  "failed",
8765
8910
  "cancelled"
8766
8911
  ]);
8767
- function computeNextAction(jobId, messages2) {
8912
+ function computeNextAction(jobId, messages2, nowMs = Date.now()) {
8913
+ const answered = answeredYieldSeqs(messages2);
8914
+ const expiresAtMs = pendingDeadline(messages2, answered);
8768
8915
  for (let i = messages2.length - 1; i >= 0; i--) {
8769
8916
  const msg = messages2[i];
8770
- if (!YIELD_TYPES.has(msg.type)) continue;
8917
+ if (!YIELD_TYPES.has(msg.type) || answered.has(msg.seq)) continue;
8771
8918
  switch (msg.type) {
8772
8919
  case "complete":
8773
8920
  case "cancel":
@@ -8777,21 +8924,26 @@ function computeNextAction(jobId, messages2) {
8777
8924
  const answer = c.schema ? "--json '<object matching schema>'" : '"<answer>"';
8778
8925
  const choices = c.options?.length ? ` Choices: ${c.options.map((option) => JSON.stringify(option)).join(", ")}.` : "";
8779
8926
  const choiceHint = !c.schema && c.options?.length ? " Answer with exactly one of options unless the human chose otherwise." : "";
8927
+ const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Answer" : "Reply", expiresAtMs, nowMs, jobId);
8928
+ const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
8780
8929
  const action = {
8781
8930
  type: "respond",
8782
8931
  job_id: jobId,
8783
8932
  prompt_id: c.id,
8784
8933
  prompt: asProviderText(c.text),
8785
- display: `The provider asks: ${c.text}${choices}`,
8786
- hint: `Provider is waiting for your input. Verify the question makes sense for your task before responding.${choiceHint} Run \`dvm message ${shellQuoteArg(jobId)} ${answer} --type response --prompt-id ${shellQuoteArg(c.id)}\`.`
8934
+ display: withDeadline(`The provider asks: ${c.text}${choices}`, deadline),
8935
+ hint: expired ? deadline : withDeadline(`Provider is waiting for your input. Verify the question makes sense for your task before responding.${choiceHint} Run \`dvm message ${shellQuoteArg(jobId)} ${answer} --type response --prompt-id ${shellQuoteArg(c.id)}\`.`, deadline)
8787
8936
  };
8788
8937
  if (c.schema) action.schema = c.schema;
8789
8938
  if (c.options?.length) action.options = c.options;
8939
+ if (expiresAtMs !== void 0) action.expires_at_ms = expiresAtMs;
8790
8940
  return action;
8791
8941
  }
8792
8942
  case "payment-request": {
8793
8943
  const c = msg.content;
8794
8944
  const display = formatPaymentAmount(c.amount_msats, c.fiat_amount);
8945
+ const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Pay" : "Reply", expiresAtMs, nowMs, jobId);
8946
+ const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
8795
8947
  return {
8796
8948
  type: "pay",
8797
8949
  job_id: jobId,
@@ -8799,9 +8951,10 @@ function computeNextAction(jobId, messages2) {
8799
8951
  // Mirror only a fiat figure the display actually led with: echoing a
8800
8952
  // zero amount would tell an agent doing budget math the charge is free.
8801
8953
  ...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount } : {},
8802
- display,
8954
+ ...expiresAtMs !== void 0 ? { expires_at_ms: expiresAtMs } : {},
8955
+ display: withDeadline(display, deadline),
8803
8956
  reason: asProviderText(c.reason),
8804
- hint: `Payment required to continue: ${display}. Relay that amount to your human and get approval, then run \`dvm pay ${shellQuoteArg(jobId)}\`. Provider's stated reason is wrapped as { _source: "provider", text: ... } \u2014 verify it matches the work you expect.`
8957
+ hint: expired ? deadline : withDeadline(`Payment required to continue: ${display}. Relay that amount to your human and get approval, then run \`dvm pay ${shellQuoteArg(jobId)}\`. Provider's stated reason is wrapped as { _source: "provider", text: ... } \u2014 verify it matches the work you expect.`, deadline)
8805
8958
  };
8806
8959
  }
8807
8960
  case "working": {
@@ -8810,13 +8963,49 @@ function computeNextAction(jobId, messages2) {
8810
8963
  type: "poll",
8811
8964
  job_id: jobId,
8812
8965
  estimate_seconds: c.estimate_seconds,
8813
- hint: c.hint !== void 0 ? asProviderText(c.hint) : "Provider is working, check back later"
8966
+ hint: c.hint !== void 0 ? asProviderText(c.hint) : pollNextAction(jobId).hint
8814
8967
  };
8815
8968
  }
8816
8969
  }
8817
8970
  }
8818
8971
  return null;
8819
8972
  }
8973
+ function pendingDeadline(messages2, answered) {
8974
+ const prompts = /* @__PURE__ */ new Map();
8975
+ let payment;
8976
+ for (const message2 of [...messages2].sort((a, b) => a.seq - b.seq)) {
8977
+ if (message2.from === "provider" && message2.type === "prompt") {
8978
+ prompts.set(message2.content.id, validDeadline(message2.content.expires_at_ms));
8979
+ } else if (message2.from === "requester" && message2.type === "response") {
8980
+ prompts.delete(message2.content.prompt_id);
8981
+ } else if (message2.from === "provider" && message2.type === "payment-request") {
8982
+ payment = !answered.has(message2.seq) && message2.content.amount_msats > 0 ? validDeadline(message2.content.expires_at_ms) : void 0;
8983
+ }
8984
+ }
8985
+ let earliest = payment;
8986
+ for (const deadline of prompts.values()) {
8987
+ if (deadline !== void 0 && (earliest === void 0 || deadline < earliest)) earliest = deadline;
8988
+ }
8989
+ return earliest;
8990
+ }
8991
+ function validDeadline(value) {
8992
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 864e13 ? value : void 0;
8993
+ }
8994
+ function withDeadline(display, deadline) {
8995
+ if (!deadline) return display;
8996
+ return `${display}${/[.!?]$/.test(display) ? "" : "."} ${deadline}`;
8997
+ }
8998
+ function deadlineClause(action, expiresAtMs, nowMs, jobId) {
8999
+ if (expiresAtMs === void 0) return "";
9000
+ const deadline = new Date(expiresAtMs).toISOString().slice(0, 16).replace("T", " ") + " UTC";
9001
+ if (expiresAtMs <= nowMs) {
9002
+ return `The deadline to ${action.toLowerCase()} (${deadline}) has passed. The provider will probably cancel the job. Check its status with \`dvm status ${shellQuoteArg(jobId)}\`.`;
9003
+ }
9004
+ const minutes = Math.floor((expiresAtMs - nowMs) / 6e4);
9005
+ const hours = Math.floor(minutes / 60);
9006
+ const remaining = expiresAtMs - nowMs > 48 * 36e5 ? `${Math.floor(hours / 24)} days${hours % 24 ? ` ${hours % 24} h` : ""}` : [hours ? `${hours} h` : "", minutes % 60 ? `${minutes % 60} min` : ""].filter(Boolean).join(" ") || "less than 1 min";
9007
+ return `${action} by ${deadline} (in ${remaining}), or the provider cancels the job.`;
9008
+ }
8820
9009
 
8821
9010
  // src/lib/rail-labels.ts
8822
9011
  var PAYMENT_RAIL_KEYS = ["cashu", "cashu_p2pk", "x402", "tempo"];
@@ -9665,7 +9854,11 @@ async function sendCreditPayment(jobId, intent, transport, provider, jobToken) {
9665
9854
  async function tryCreditPayment(args) {
9666
9855
  const { jobId, request: request2, requestSeq, transport, provider, jobToken } = args;
9667
9856
  const job = loadJob(jobId);
9857
+ if (job && hasUnknownUpfrontRail(job))
9858
+ throw new DvmError("upfront_rail_unknown", "Recover the original upfront rail charge before another balance payment.");
9668
9859
  const ask = request2.credit;
9860
+ if (job && hasUnknownUpfrontCredit(job))
9861
+ throw new DvmError("upfront_credit_unknown", "The original upfront credit debit must be recovered before another balance payment.");
9669
9862
  if (!job?.creditBinding || !ask || !Number.isSafeInteger(requestSeq) || requestSeq < 0 || !Number.isSafeInteger(ask.amount_micro) || ask.amount_micro <= 0 || !/^[a-z]{3}$/.test(ask.currency)) return false;
9670
9863
  const signer = findSigningIdentityByPubkey(job.creditBinding.callerPubkey);
9671
9864
  if (!signer) return false;
@@ -9737,6 +9930,7 @@ async function tryCreditPayment(args) {
9737
9930
  authorization,
9738
9931
  request: request2,
9739
9932
  amountMsats,
9933
+ approval: args.approval,
9740
9934
  ..."unbound" in job.creditBinding ? { selectedUnbound: true } : {}
9741
9935
  };
9742
9936
  return current.pendingCreditPayment;
@@ -9897,6 +10091,7 @@ async function bookRecoveredSubmissions(args) {
9897
10091
  const fresh = loadAgentWallet();
9898
10092
  const booked = matches(fresh);
9899
10093
  if (!fresh || booked.length === 0) return [];
10094
+ for (const entry of booked) restoreUpfrontRailPayment(entry, args.jobId, null);
9900
10095
  saveAgentWallet(
9901
10096
  booked.reduce(
9902
10097
  (acc, entry) => applyOutcome(acc, { kind: "shipped", entry, jobId: args.jobId }, now),
@@ -10231,6 +10426,8 @@ async function shipEntry(entry, httpPost, persistUnresolved) {
10231
10426
  ...record.jobToken && !existing.jobToken ? { jobToken: record.jobToken } : {}
10232
10427
  });
10233
10428
  } else saveJob(record);
10429
+ restoreUpfrontRailPayment(active2, identity.jobId, response.body);
10430
+ recordUpfrontCreditPayment(identity.jobId, response.body?.upfront_payment, true);
10234
10431
  }
10235
10432
  await reconcileResumedJobCredit(active2, response.body, httpPost);
10236
10433
  return { kind: "shipped", entry, jobId: identity.jobId };
@@ -10348,12 +10545,21 @@ function saveRecoveredJob(entry, jobId, body, requestId) {
10348
10545
  requestId,
10349
10546
  ...jobToken && !existing.jobToken ? { jobToken } : {}
10350
10547
  });
10548
+ recordUpfrontCreditPayment(jobId, body?.upfront_payment, true);
10549
+ restoreUpfrontRailPayment(entry, jobId, body);
10351
10550
  return "saved";
10352
10551
  }
10353
10552
  const { jobToken: _unchecked, ...record } = jobRecordFromEntry(entry, jobId, body, void 0);
10354
10553
  saveJob({ ...record, requestId, ...jobToken ? { jobToken } : {} });
10554
+ recordUpfrontCreditPayment(jobId, body?.upfront_payment, true);
10555
+ restoreUpfrontRailPayment(entry, jobId, body);
10355
10556
  return "saved";
10356
10557
  }
10558
+ function restoreUpfrontRailPayment(entry, jobId, body) {
10559
+ const context = entry.context;
10560
+ const accepted = parseUpfrontPayment(body?.upfront_payment);
10561
+ recordUpfrontRailPayment(jobId, context?.upfront_rail_payment ?? (accepted ? { method: "cashu", amountMsats: accepted.amount_msats } : void 0));
10562
+ }
10357
10563
  function errorCodeOf(body) {
10358
10564
  const error = body?.error;
10359
10565
  if (typeof error === "string") return error;
@@ -10571,6 +10777,7 @@ function applyOutcome(wallet, outcome, now) {
10571
10777
  signed_at_ms: now()
10572
10778
  };
10573
10779
  const dropped = drop();
10780
+ if (dropped.recent_spends.some((spend) => spend.request_id === recentSpend.request_id)) return dropped;
10574
10781
  return {
10575
10782
  ...dropped,
10576
10783
  recent_spends: [...dropped.recent_spends, recentSpend].slice(-RECENT_SPENDS_CAP)
@@ -10943,7 +11150,38 @@ function parseTempoNetwork(value, source) {
10943
11150
 
10944
11151
  // src/lib/payment-responder.ts
10945
11152
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11153
+ return withJobPaymentLock(jobId, (assertOwned) => {
11154
+ const guardedTransport = new Proxy(transport, {
11155
+ get(target, key) {
11156
+ if (key === "sendMessage") return async (...args) => {
11157
+ assertOwned();
11158
+ return target.sendMessage(...args);
11159
+ };
11160
+ const value = Reflect.get(target, key, target);
11161
+ return typeof value === "function" ? value.bind(target) : value;
11162
+ }
11163
+ });
11164
+ return handleLockedPaymentRequest(jobId, request2, policy, guardedTransport, provider, opts);
11165
+ });
11166
+ }
11167
+ async function handleLockedPaymentRequest(jobId, request2, policy, transport, provider, opts) {
11168
+ const approval = opts?.requestSeq === void 0 ? void 0 : {
11169
+ requestSeq: opts.requestSeq,
11170
+ approval: opts.approval ?? "auto"
11171
+ };
10946
11172
  const job = loadJob(jobId);
11173
+ if (job && hasUnknownUpfrontRail(job))
11174
+ throw new DvmError(
11175
+ "upfront_rail_unknown",
11176
+ "The original upfront rail charge is unknown or conflicting.",
11177
+ "Recover the original job price before authorizing more payments."
11178
+ );
11179
+ if (job && hasUnknownUpfrontCredit(job))
11180
+ throw new DvmError(
11181
+ "upfront_credit_unknown",
11182
+ "The original upfront credit debit is unknown or conflicting.",
11183
+ "Recover the accepted upfront amount with 'dvm request-result' before authorizing more payments."
11184
+ );
10947
11185
  const spent = job?.totalPaidMsats ?? 0;
10948
11186
  const paymentsHonoured = job?.paymentsHonoured ?? 0;
10949
11187
  const pinnedMint = job?.pinnedMint;
@@ -10970,6 +11208,22 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
10970
11208
  if (pending4.authorization.request_seq !== opts?.requestSeq)
10971
11209
  throw new DvmError("credit_payment_retry_required", "The prior balance payment was refused; reload this job's pending ask.");
10972
11210
  }
11211
+ if (opts?.creditRecoveryOnly)
11212
+ throw new DvmError(
11213
+ "credit_payment_retry_required",
11214
+ "The saved balance payment was not recovered; no replacement payment was sent.",
11215
+ `Run \`dvm status ${shellQuoteArg(jobId)}\` to refresh the job, then run \`dvm pay ${shellQuoteArg(jobId)}\` only if payment is still requested.`
11216
+ );
11217
+ if (matchingEndpoint && opts?.requestSeq !== void 0) {
11218
+ if (job.inFlightPaymentRequestSeqs?.includes(opts.requestSeq))
11219
+ await reconcileInFlightPaymentRequest(jobId, opts.requestSeq, transport, provider, { jobToken });
11220
+ if (loadAnsweredYieldSeqs(jobId).has(opts.requestSeq))
11221
+ throw new DvmError(
11222
+ "payment_already_sent",
11223
+ "Payment already sent for this request.",
11224
+ `Keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
11225
+ );
11226
+ }
10973
11227
  if (policy.maxIncrementMsats > 0 && request2.amount_msats > policy.maxIncrementMsats) {
10974
11228
  return "over-budget";
10975
11229
  }
@@ -10992,6 +11246,7 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
10992
11246
  request: request2,
10993
11247
  policy,
10994
11248
  requestSeq: opts?.requestSeq,
11249
+ approval: opts?.approval ?? "auto",
10995
11250
  transport,
10996
11251
  provider,
10997
11252
  jobToken
@@ -11024,15 +11279,17 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11024
11279
  pinnedMint,
11025
11280
  maxCashuFeeSats,
11026
11281
  strictPerCall,
11027
- jobToken
11282
+ approval,
11283
+ jobToken,
11284
+ requestSeq: matchingEndpoint ? opts?.requestSeq : void 0
11028
11285
  });
11029
11286
  if (paid) {
11030
11287
  return { status: "paid", rail: "cashu_p2pk", amountMsats: request2.amount_msats };
11031
11288
  }
11032
11289
  }
11033
11290
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11034
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-7BBWAZYJ.js");
11035
- const { tryX402Payment: tryX402Payment2 } = await import("./client-MFSKFSV4.js");
11291
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UJ7EJNQA.js");
11292
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-DS4QJ346.js");
11036
11293
  const wallet = loadX402Wallet2();
11037
11294
  if (wallet) {
11038
11295
  let proof;
@@ -11072,9 +11329,10 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11072
11329
  }
11073
11330
  },
11074
11331
  provider,
11075
- { jobToken }
11332
+ { jobToken },
11333
+ matchingEndpoint ? opts?.requestSeq : void 0
11076
11334
  );
11077
- addPayment(jobId, proof.amountMsats);
11335
+ addPayment(jobId, proof.amountMsats, approval);
11078
11336
  recordSpend({
11079
11337
  msats: proof.amountMsats,
11080
11338
  btcRate: proof.btcRate,
@@ -11108,9 +11366,10 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11108
11366
  }
11109
11367
  },
11110
11368
  provider,
11111
- { jobToken }
11369
+ { jobToken },
11370
+ matchingEndpoint ? opts?.requestSeq : void 0
11112
11371
  );
11113
- addPayment(jobId, paidMsats);
11372
+ addPayment(jobId, paidMsats, approval);
11114
11373
  recordSpend({
11115
11374
  msats: paidMsats,
11116
11375
  btcRate: tempoRate,
@@ -11137,6 +11396,7 @@ async function tryAgentWalletMidJobPayment(args) {
11137
11396
  pinnedMint,
11138
11397
  maxCashuFeeSats,
11139
11398
  strictPerCall,
11399
+ approval,
11140
11400
  jobToken
11141
11401
  } = args;
11142
11402
  if (!strictPerCall) await sweepPendingSubmissions({ fetchImpl: dvmFetch }).catch(() => void 0);
@@ -11191,7 +11451,8 @@ async function tryAgentWalletMidJobPayment(args) {
11191
11451
  prepared,
11192
11452
  transport,
11193
11453
  provider,
11194
- jobToken
11454
+ jobToken,
11455
+ requestSeq: args.requestSeq
11195
11456
  });
11196
11457
  } catch (err) {
11197
11458
  if (err instanceof DvmError && err.code === "payment_invalid") {
@@ -11209,7 +11470,7 @@ async function tryAgentWalletMidJobPayment(args) {
11209
11470
  signed_at_ms: Date.now()
11210
11471
  }
11211
11472
  });
11212
- addPayment(jobId, request2.amount_msats);
11473
+ addPayment(jobId, request2.amount_msats, approval);
11213
11474
  recordSpend({
11214
11475
  msats: request2.amount_msats,
11215
11476
  btcRate,
@@ -11235,14 +11496,15 @@ async function sendMidJobPaymentWithRetry(args) {
11235
11496
  }
11236
11497
  },
11237
11498
  provider,
11238
- { jobToken }
11499
+ { jobToken },
11500
+ args.requestSeq
11239
11501
  ),
11240
11502
  intendedLockPubkey: prepared.intendedLockPubkey,
11241
11503
  refetchInfo: () => transport.describe(provider),
11242
11504
  sleep: args.sleep
11243
11505
  });
11244
11506
  }
11245
- async function sendRailPayment(transport, jobId, message2, provider, options) {
11507
+ async function sendRailPayment(transport, jobId, message2, provider, options, requestSeq) {
11246
11508
  const capture = (evidence) => {
11247
11509
  if (evidence.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
11248
11510
  if (evidence.drawFundingReceipt) captureDrawFundingReceipts(jobId, [evidence.drawFundingReceipt], {
@@ -11250,14 +11512,32 @@ async function sendRailPayment(transport, jobId, message2, provider, options) {
11250
11512
  ...typeof message2.content.cashu_request_id === "string" ? { fundId: message2.content.cashu_request_id } : {}
11251
11513
  });
11252
11514
  };
11515
+ if (requestSeq !== void 0) markPaymentRequestInFlight(jobId, requestSeq);
11253
11516
  try {
11254
11517
  const result = await transport.sendMessage(jobId, message2, provider, options);
11518
+ if (requestSeq !== void 0) markPaymentRequestPaid(jobId, requestSeq);
11255
11519
  if (result) capture(result);
11256
11520
  } catch (error) {
11521
+ if (requestSeq !== void 0) {
11522
+ if (error instanceof DvmError && error.code === "replay_rejected") markPaymentRequestPaid(jobId, requestSeq);
11523
+ else if (definitelyNotAccepted(error)) clearPaymentRequestInFlight(jobId, requestSeq);
11524
+ else markPaymentRequestInFlight(jobId, requestSeq);
11525
+ }
11257
11526
  if (error instanceof DvmError && error.data) capture(error.data);
11527
+ if (error instanceof DvmError && error.code === "replay_rejected") return;
11258
11528
  throw error;
11259
11529
  }
11260
11530
  }
11531
+ function definitelyNotAccepted(error) {
11532
+ if (error instanceof DvmError) {
11533
+ const status2 = error.data?.http_status;
11534
+ return typeof status2 === "number" && status2 >= 400 && status2 < 500;
11535
+ }
11536
+ if (!(error instanceof Error)) return false;
11537
+ if ("code" in error && ["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH"].includes(String(error.code))) return true;
11538
+ if (error instanceof AggregateError) return error.errors.length > 0 && error.errors.every(definitelyNotAccepted);
11539
+ return definitelyNotAccepted(error.cause);
11540
+ }
11261
11541
  async function tryMppCredential(challenges, amountMsats, btcRate) {
11262
11542
  const wallet = loadConfig()?.tempo;
11263
11543
  if (wallet?.method !== "tempo" || !wallet.apiKey) return null;
@@ -11372,21 +11652,20 @@ async function refundJsonField(claims) {
11372
11652
  }
11373
11653
  };
11374
11654
  }
11375
- function printRefundSummaryHuman(claims) {
11376
- for (const claim of claims) {
11377
- const noun = claim.reason === "change" ? "change" : "refund";
11378
- if (claim.claimed) {
11379
- info(`Claimed ${noun} of ${formatAmountBestEffort(claim.amount_msats)} into your wallet.`);
11380
- } else {
11381
- info(
11382
- `${cap(noun)} of ${formatAmountBestEffort(claim.amount_msats)} could not be auto-claimed (the mint may be down). Recover with: dvm wallet receive-token ${claim.cashu_token}`
11383
- );
11384
- }
11655
+ function refundSummaryHuman(claim) {
11656
+ const noun = claim.reason === "change" ? "change" : "refund";
11657
+ if (claim.claimed) {
11658
+ return `Claimed ${noun} of ${formatAmountBestEffort(claim.amount_msats)} into your wallet.`;
11385
11659
  }
11660
+ return `${cap(noun)} of ${formatAmountBestEffort(claim.amount_msats)} could not be auto-claimed (the mint may be down). Recover with: dvm wallet receive-token ${claim.cashu_token}`;
11386
11661
  }
11387
11662
  function cap(s) {
11388
11663
  return s.charAt(0).toUpperCase() + s.slice(1);
11389
11664
  }
11665
+ function withRefundNextAction(jobId, action, claims) {
11666
+ if (action?.type === "respond" || action?.type === "pay") return action;
11667
+ return refundNextAction(jobId, claims) ?? action;
11668
+ }
11390
11669
 
11391
11670
  // src/lib/stream-loop.ts
11392
11671
  async function streamLoop(opts) {
@@ -11396,8 +11675,9 @@ async function streamLoop(opts) {
11396
11675
  const allMessages = [];
11397
11676
  const autoPayments = [];
11398
11677
  const refunds = [];
11399
- const autoPaidSeqs = /* @__PURE__ */ new Set();
11678
+ const answeredSeqs = persistLocalState ? loadAnsweredYieldSeqs(jobId) : /* @__PURE__ */ new Set();
11400
11679
  let justAutoPaid = false;
11680
+ let paymentUnresolved = false;
11401
11681
  let cursor = opts.afterSeq;
11402
11682
  let messageAppendSession = opts.messageAppendSession;
11403
11683
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
@@ -11409,16 +11689,32 @@ async function streamLoop(opts) {
11409
11689
  ...result.amountUsdcMicro !== void 0 && { amount_usdc_microunits: result.amountUsdcMicro },
11410
11690
  display: paidConfirmationDisplay(result, request2.fiat_amount)
11411
11691
  });
11412
- autoPaidSeqs.add(seq);
11692
+ if (persistLocalState) markPaymentRequestPaid(jobId, seq);
11693
+ answeredSeqs.add(seq);
11413
11694
  justAutoPaid = true;
11414
11695
  }
11696
+ let pendingAction = null;
11415
11697
  const pending4 = persistLocalState ? loadJob(jobId)?.pendingCreditPayment : void 0;
11416
11698
  if (pending4 && policy) {
11417
- const result = await handlePaymentRequest(jobId, pending4.request, policy, transport, provider, {
11418
- jobToken,
11419
- requestSeq: pending4.authorization.request_seq
11420
- });
11699
+ let result;
11700
+ try {
11701
+ result = await handlePaymentRequest(jobId, pending4.request, policy, transport, provider, {
11702
+ jobToken,
11703
+ requestSeq: pending4.authorization.request_seq
11704
+ });
11705
+ } catch (error) {
11706
+ if (error instanceof DvmError && error.code === "payment_settling")
11707
+ return { messages: [], autoPayments, refunds, cursor, nextAction: pollNextAction(jobId, paymentInFlightHint(jobId)) };
11708
+ throw error;
11709
+ }
11421
11710
  if (typeof result === "object") recordAutoPayment(result, pending4.request, pending4.authorization.request_seq);
11711
+ else pendingAction = computeNextAction(jobId, [{
11712
+ seq: pending4.authorization.request_seq,
11713
+ from: "provider",
11714
+ timestamp: 0,
11715
+ type: "payment-request",
11716
+ content: pending4.request
11717
+ }]);
11422
11718
  }
11423
11719
  const deadline = opts.timeoutMs === void 0 ? void 0 : Date.now() + Math.max(0, opts.timeoutMs);
11424
11720
  const nextPollOptions = () => {
@@ -11441,7 +11737,9 @@ async function streamLoop(opts) {
11441
11737
  let batchMessages;
11442
11738
  if (streamFn) {
11443
11739
  const streamOpts = {
11444
- onMessage: opts.onMessage,
11740
+ onMessage: (message2) => {
11741
+ if (message2.seq > cursor) opts.onMessage?.(message2);
11742
+ },
11445
11743
  signal: controller?.signal,
11446
11744
  jobToken
11447
11745
  };
@@ -11452,12 +11750,12 @@ async function streamLoop(opts) {
11452
11750
  if (isAbortError(err) || deadline !== void 0 && isMessagePollTimeout(err)) break;
11453
11751
  throw err;
11454
11752
  }
11455
- batchMessages = result.messages;
11753
+ batchMessages = result.messages.filter((message2) => message2.seq > cursor);
11456
11754
  } else {
11457
11755
  const pollOptions = nextPollOptions();
11458
11756
  if (!pollOptions) break;
11459
11757
  try {
11460
- batchMessages = await transport.getMessages(jobId, cursor, provider, pollOptions);
11758
+ batchMessages = (await transport.getMessages(jobId, cursor, provider, pollOptions)).filter((message2) => message2.seq > cursor);
11461
11759
  } catch (err) {
11462
11760
  if (deadline !== void 0 && isMessagePollTimeout(err)) break;
11463
11761
  throw err;
@@ -11477,20 +11775,53 @@ async function streamLoop(opts) {
11477
11775
  refunds.push(...await claimInboundPayments(jobId, batchMessages));
11478
11776
  }
11479
11777
  justAutoPaid = false;
11480
- const lastYield = findLastYield(batchMessages);
11481
- if (lastYield?.type === "payment-request" && autoPaidSeqs.has(lastYield.seq)) {
11482
- justAutoPaid = true;
11778
+ if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
11779
+ for (const seq of answeredYieldSeqs(batchMessages)) answeredSeqs.add(seq);
11780
+ const pendingPayment = pendingPaymentRequest(batchMessages, answeredSeqs);
11781
+ const lastYield2 = findLastYield(batchMessages.filter((message2) => !answeredSeqs.has(message2.seq) && (message2.type !== "payment-request" || message2.seq === pendingPayment?.seq))) ?? findLastYield(batchMessages);
11782
+ if (lastYield2?.type === "payment-request" && answeredSeqs.has(lastYield2.seq)) {
11783
+ if (persistLocalState) markPaymentRequestPaid(jobId, lastYield2.seq);
11483
11784
  break;
11484
11785
  }
11485
- if (lastYield?.type === "payment-request" && policy) {
11486
- const req = lastYield.content;
11786
+ if (lastYield2?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield2.seq)) {
11787
+ const pollOptions = nextPollOptions();
11788
+ try {
11789
+ if (!pollOptions) paymentUnresolved = true;
11790
+ else if (await withJobPaymentLock(jobId, () => reconcileInFlightPaymentRequest(jobId, lastYield2.seq, transport, provider, pollOptions))) {
11791
+ answeredSeqs.add(lastYield2.seq);
11792
+ break;
11793
+ }
11794
+ } catch (error) {
11795
+ if (!isMessagePollTimeout(error) && !(error instanceof DvmError && ["payment_settling", "payment_request_not_pending"].includes(error.code))) throw error;
11796
+ paymentUnresolved = true;
11797
+ }
11798
+ if (paymentUnresolved) {
11799
+ cursor = lastYield2.seq - 1;
11800
+ break;
11801
+ }
11802
+ }
11803
+ if (lastYield2?.type === "payment-request" && lastYield2.seq === pendingPayment?.seq && policy) {
11804
+ const req = lastYield2.content;
11487
11805
  if (req.amount_msats <= policy.autoPayBelowMsats && (policy.maxIncrementMsats === 0 || req.amount_msats <= policy.maxIncrementMsats)) {
11488
- const result = await handlePaymentRequest(jobId, req, policy, transport, provider, {
11489
- jobToken,
11490
- requestSeq: lastYield.seq
11491
- });
11806
+ let result;
11807
+ try {
11808
+ result = await handlePaymentRequest(jobId, req, policy, transport, provider, {
11809
+ jobToken,
11810
+ requestSeq: lastYield2.seq
11811
+ });
11812
+ } catch (error) {
11813
+ if (error instanceof DvmError && error.code === "payment_settling") {
11814
+ paymentUnresolved = true;
11815
+ break;
11816
+ }
11817
+ if (error instanceof DvmError && error.code === "payment_already_sent") {
11818
+ answeredSeqs.add(lastYield2.seq);
11819
+ break;
11820
+ }
11821
+ throw error;
11822
+ }
11492
11823
  if (typeof result === "object") {
11493
- recordAutoPayment(result, req, lastYield.seq);
11824
+ recordAutoPayment(result, req, lastYield2.seq);
11494
11825
  continue;
11495
11826
  }
11496
11827
  if (result === "payment-cap-exceeded") {
@@ -11521,7 +11852,7 @@ async function streamLoop(opts) {
11521
11852
  let recheck = [];
11522
11853
  try {
11523
11854
  if (pollOptions) {
11524
- recheck = await transport.getMessages(jobId, cursor, provider, pollOptions);
11855
+ recheck = (await transport.getMessages(jobId, cursor, provider, pollOptions)).filter((message2) => message2.seq > cursor);
11525
11856
  }
11526
11857
  } catch (err) {
11527
11858
  if (deadline === void 0 || !isMessagePollTimeout(err)) throw err;
@@ -11537,17 +11868,24 @@ async function streamLoop(opts) {
11537
11868
  }
11538
11869
  }
11539
11870
  }
11540
- let nextAction = refundNextAction(jobId, refunds) ?? computeNextAction(jobId, allMessages);
11541
- if (nextAction?.type === "pay") {
11542
- const lastYield = findLastYield(allMessages);
11543
- if (lastYield?.type === "payment-request" && autoPaidSeqs.has(lastYield.seq)) {
11871
+ if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
11872
+ for (const seq of answeredYieldSeqs(allMessages)) answeredSeqs.add(seq);
11873
+ const terminal = allMessages.some((msg) => msg.type === "complete" || msg.type === "cancel");
11874
+ const yieldAction = computeNextAction(jobId, allMessages.filter((message2) => !answeredSeqs.has(message2.seq))) ?? (terminal ? null : pendingAction);
11875
+ let nextAction = withRefundNextAction(jobId, yieldAction ?? (terminal ? null : pollNextAction(jobId)), refunds);
11876
+ const lastYield = findLastYield(allMessages);
11877
+ if (nextAction?.type === "pay" && lastYield?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield.seq))
11878
+ nextAction = { ...nextAction, hint: paymentInFlightHint(jobId) };
11879
+ if (nextAction?.type === "pay" || nextAction?.type === "poll" && !terminal) {
11880
+ if (lastYield?.type === "payment-request" && answeredSeqs.has(lastYield.seq)) {
11544
11881
  nextAction = {
11545
11882
  type: "poll",
11546
11883
  job_id: jobId,
11547
- hint: `Payment already sent for this request; the provider is finalising. Poll the result with 'dvm messages ${jobId}' \u2014 do not pay again.`
11884
+ hint: `Payment already sent for this request; the provider is finalising. Keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\` \u2014 do not pay again.`
11548
11885
  };
11549
11886
  }
11550
11887
  }
11888
+ if (paymentUnresolved) nextAction = pollNextAction(jobId, paymentInFlightHint(jobId));
11551
11889
  return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
11552
11890
  }
11553
11891
  function isMessagePollTimeout(err) {
@@ -12039,7 +12377,8 @@ var HttpsTransport = class {
12039
12377
  jobToken,
12040
12378
  ...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {},
12041
12379
  ...feedbackClaim ? { feedbackClaim } : {},
12042
- ...parseFundingResponse(data)
12380
+ ...parseFundingResponse(data),
12381
+ upfrontPayment: parseUpfrontPayment(data.upfront_payment)
12043
12382
  };
12044
12383
  }
12045
12384
  return {
@@ -12054,7 +12393,8 @@ var HttpsTransport = class {
12054
12393
  ...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {},
12055
12394
  ...feedbackClaim ? { feedbackClaim } : {},
12056
12395
  ...parseSignedReceipt(data.receipt),
12057
- ...parseFundingResponse(data)
12396
+ ...parseFundingResponse(data),
12397
+ upfrontPayment: parseUpfrontPayment(data.upfront_payment)
12058
12398
  };
12059
12399
  }
12060
12400
  async requestResult(provider, requestId, signedJob) {
@@ -12300,6 +12640,21 @@ var HttpsTransport = class {
12300
12640
  }
12301
12641
  }
12302
12642
  async sendMessage(jobId, message2, provider, options) {
12643
+ try {
12644
+ return await this.sendMessageWithSignal(
12645
+ jobId,
12646
+ message2,
12647
+ provider,
12648
+ options,
12649
+ message2.type === "payment" ? AbortSignal.timeout(6e4) : void 0
12650
+ );
12651
+ } catch (error) {
12652
+ if (isAbortError(error) && message2.type === "payment")
12653
+ throw new DvmError("timeout", "Payment send timed out.");
12654
+ throw error;
12655
+ }
12656
+ }
12657
+ async sendMessageWithSignal(jobId, message2, provider, options, signal) {
12303
12658
  const endpoint = provider?.endpoint;
12304
12659
  if (!endpoint) {
12305
12660
  throw new DvmError(
@@ -12309,24 +12664,18 @@ var HttpsTransport = class {
12309
12664
  }
12310
12665
  const url = `${endpoint}/v1/job/${jobId}/messages`;
12311
12666
  const body = JSON.stringify({ type: message2.type, content: message2.content });
12312
- let res;
12313
- try {
12314
- res = await dvmFetch(url, {
12315
- method: "POST",
12316
- headers: { "Content-Type": "application/json", ...jobTokenHeader(options?.jobToken) },
12317
- body
12318
- });
12319
- } catch (err) {
12320
- if (isAbortError(err)) {
12321
- throw new DvmError("timeout", "sendMessage timed out.");
12322
- }
12323
- throw err;
12324
- }
12667
+ const res = await dvmFetch(url, {
12668
+ method: "POST",
12669
+ headers: { "Content-Type": "application/json", ...jobTokenHeader(options?.jobToken) },
12670
+ body,
12671
+ signal
12672
+ });
12325
12673
  if (res.status === 402) {
12326
12674
  let errorBody;
12327
12675
  try {
12328
12676
  errorBody = await res.json();
12329
- } catch {
12677
+ } catch (error2) {
12678
+ if (isAbortError(error2)) throw error2;
12330
12679
  throw new DvmError("payment_insufficient", "Payment required (unparseable response).");
12331
12680
  }
12332
12681
  const error = withDrawFunding(withCreditErrorContext(buildPaymentError(errorBody), errorBody), errorBody);
@@ -12335,8 +12684,11 @@ var HttpsTransport = class {
12335
12684
  }
12336
12685
  if (res.status === 409) {
12337
12686
  const body2 = parseJsonObject(await res.text());
12338
- if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string"))
12339
- throw withDrawFunding(withCreditErrorContext(buildPaymentError(body2), body2), body2);
12687
+ if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string")) {
12688
+ const error = withDrawFunding(withCreditErrorContext(buildPaymentError(body2), body2), body2);
12689
+ error.data = { ...error.data, http_status: res.status };
12690
+ throw error;
12691
+ }
12340
12692
  throw new DvmError(
12341
12693
  "job_terminal",
12342
12694
  "Job is no longer active.",
@@ -12348,7 +12700,9 @@ var HttpsTransport = class {
12348
12700
  const structured = parseStructuredError(text);
12349
12701
  if (structured) {
12350
12702
  const body2 = parseJsonObject(text) ?? {};
12351
- throw withDrawFunding(withCreditErrorContext(structured, body2), body2);
12703
+ const error = withDrawFunding(withCreditErrorContext(structured, body2), body2);
12704
+ error.data = { ...error.data, http_status: res.status };
12705
+ throw error;
12352
12706
  }
12353
12707
  throw providerResponseError("provider_error", `sendMessage failed (${res.status}): ${text}`);
12354
12708
  }
@@ -12538,7 +12892,8 @@ function parseRequestResultResponse(value, requestId, httpStatus) {
12538
12892
  ...data.payload_in === "summary" || data.payload_in === "messages" ? { payloadIn: data.payload_in } : {},
12539
12893
  ...typeof data.job_token === "string" ? { jobToken: data.job_token } : {},
12540
12894
  ...receipt ? { receipt } : {},
12541
- ...parseFundingResponse(data)
12895
+ ...parseFundingResponse(data),
12896
+ upfrontPayment: parseUpfrontPayment(data.upfront_payment)
12542
12897
  };
12543
12898
  }
12544
12899
  function malformedRequestResult(requestId, reason) {
@@ -13480,14 +13835,14 @@ async function confirmRollback(stored, preview, opts) {
13480
13835
  async function withStrandingChecked(removing, commit) {
13481
13836
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
13482
13837
  if (leaving.has("tempo")) {
13483
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-SVPMTND2.js");
13838
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-LGGBDCKK.js");
13484
13839
  await assertTempoWalletIdle2("disconnect");
13485
13840
  }
13486
13841
  if (!leaving.has("x402")) return commit();
13487
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-5EGKBZAE.js");
13488
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-7AVB36WP.js");
13489
- const { ensureAddress: ensureAddress2 } = await import("./internal-5EGKBZAE.js");
13490
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-7BBWAZYJ.js");
13842
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-ZZHCUKOM.js");
13843
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-XGNIMPTB.js");
13844
+ const { ensureAddress: ensureAddress2 } = await import("./internal-ZZHCUKOM.js");
13845
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UJ7EJNQA.js");
13491
13846
  return withX402ChannelLock2(async () => {
13492
13847
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
13493
13848
  if (unsettled.length > 0) {
@@ -13915,7 +14270,7 @@ function creditDrainCommand(handle, creditId) {
13915
14270
  }
13916
14271
 
13917
14272
  // src/commands/wallet-history.ts
13918
- import { createHash } from "crypto";
14273
+ import { createHash as createHash2 } from "crypto";
13919
14274
 
13920
14275
  // src/lib/completed-credit-history.ts
13921
14276
  function completedCreditHistory(query = {}) {
@@ -14060,7 +14415,7 @@ function walletHistory(opts, now = /* @__PURE__ */ new Date()) {
14060
14415
  const windowed = (sinceMs === null ? all : all.filter((e) => e.timestamp >= sinceMs)).slice().sort(
14061
14416
  (a, b) => b.timestamp - a.timestamp || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0)
14062
14417
  );
14063
- const fingerprint = createHash("sha256").update(JSON.stringify(windowed)).digest("hex");
14418
+ const fingerprint = createHash2("sha256").update(JSON.stringify(windowed)).digest("hex");
14064
14419
  if (continuation && continuation.fingerprint !== fingerprint) {
14065
14420
  throw invalidHistoryCursor();
14066
14421
  }
@@ -17854,8 +18209,8 @@ async function probeX402(x402, timeoutMs) {
17854
18209
  let network;
17855
18210
  let address;
17856
18211
  try {
17857
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-7BBWAZYJ.js");
17858
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-5EGKBZAE.js");
18212
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UJ7EJNQA.js");
18213
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-ZZHCUKOM.js");
17859
18214
  const wallet = loadX402Wallet2();
17860
18215
  if (!wallet) {
17861
18216
  const storedKey = x402.privateKey;
@@ -17907,8 +18262,8 @@ async function probeMpp(mpp, timeoutMs) {
17907
18262
  if (!mpp) return null;
17908
18263
  if (mpp.method === "tempo") {
17909
18264
  try {
17910
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-5PKLSWFX.js");
17911
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-5EGKBZAE.js");
18265
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-PLFC443A.js");
18266
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-ZZHCUKOM.js");
17912
18267
  const account = await connectedTempoAccount2();
17913
18268
  if (!account) {
17914
18269
  return {
@@ -18252,9 +18607,9 @@ function checkSecretDirectory(dir, row) {
18252
18607
  const offenders = [];
18253
18608
  for (const name of readdirSync2(dir)) {
18254
18609
  const path = join4(dir, name);
18255
- const stat = statSync3(path);
18256
- if (!stat.isFile()) continue;
18257
- const mode = stat.mode & 511;
18610
+ const stat2 = statSync3(path);
18611
+ if (!stat2.isFile()) continue;
18612
+ const mode = stat2.mode & 511;
18258
18613
  if (mode !== 384) offenders.push({ path, modeOctal: octalMode(mode) });
18259
18614
  }
18260
18615
  row.modeOk = offenders.length === 0;
@@ -18297,12 +18652,12 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
18297
18652
  }
18298
18653
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
18299
18654
  const path = join5(dir, name);
18300
- const stat = statSync4(path);
18301
- if (!stat.isFile()) return null;
18302
- const ageMs2 = Math.max(0, nowMs - stat.mtimeMs);
18655
+ const stat2 = statSync4(path);
18656
+ if (!stat2.isFile()) return null;
18657
+ const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
18303
18658
  return {
18304
18659
  path,
18305
- modifiedAt: stat.mtime.toISOString(),
18660
+ modifiedAt: stat2.mtime.toISOString(),
18306
18661
  ageMs: ageMs2,
18307
18662
  ageDays: Math.floor(ageMs2 / (24 * 60 * 60 * 1e3)),
18308
18663
  age: formatMnemonicBackupAge(ageMs2)
@@ -21283,16 +21638,306 @@ function fullMessageLog(jobId, messages2, afterSeq) {
21283
21638
  return contiguous ? local : void 0;
21284
21639
  }
21285
21640
 
21641
+ // src/lib/message-human.ts
21642
+ function paymentAmount(msg) {
21643
+ if (msg.from === "requester" && msg.content.credit) {
21644
+ const credit = msg.content.credit;
21645
+ const digits = String(credit.amount_micro).padStart(7, "0");
21646
+ const fraction = digits.slice(-6).replace(/0+$/, "");
21647
+ const amount = digits.slice(0, -6) + (fraction ? `.${fraction}` : "");
21648
+ return `${amount} ${credit.currency.toUpperCase()} from prepaid balance`;
21649
+ }
21650
+ return formatAmountBestEffort(msg.content.amount_msats);
21651
+ }
21652
+ function formatMessageHuman(msg, jobId, artifactSession) {
21653
+ const { seq, type } = msg;
21654
+ const prefix = msg.from === "provider" ? "Provider" : "You";
21655
+ if (msg.type !== "progress") finalizeProgressLine();
21656
+ switch (msg.type) {
21657
+ case "text":
21658
+ info(`[${msg.seq}] ${prefix}: ${msg.content.text}`);
21659
+ break;
21660
+ case "prompt":
21661
+ info(`[${msg.seq}] ${prefix} asks: ${msg.content.text}`);
21662
+ if (msg.content.options) {
21663
+ for (const opt of msg.content.options) {
21664
+ info(` - ${opt}`);
21665
+ }
21666
+ }
21667
+ break;
21668
+ case "response":
21669
+ info(msg.content.text ? `[${msg.seq}] ${prefix} answered: ${msg.content.text}${msg.content.data ? " (with structured data)" : ""}` : `[${msg.seq}] ${prefix} sent a structured answer.`);
21670
+ break;
21671
+ case "approval":
21672
+ info(`[${msg.seq}] ${prefix} approved${msg.content.ref_seq !== void 0 ? ` message ${msg.content.ref_seq}` : " the job"}${msg.content.comment ? `: ${msg.content.comment}` : ""}`);
21673
+ break;
21674
+ case "artifact": {
21675
+ const label = msg.content.name ?? msg.content.mime_type ?? "unknown type";
21676
+ if (jobId) {
21677
+ const saved = saveArtifact(msg.content, artifactSession ?? createArtifactSaveSession());
21678
+ if (saved) {
21679
+ info(
21680
+ `[${msg.seq}] ${prefix} sent artifact: ${label} (${saved.bytes.toLocaleString()} bytes \u2192 ${saved.path})`
21681
+ );
21682
+ break;
21683
+ }
21684
+ }
21685
+ info(`[${msg.seq}] ${prefix} sent artifact: ${label}`);
21686
+ break;
21687
+ }
21688
+ case "payment-request":
21689
+ info(
21690
+ `[${msg.seq}] ${prefix} requests ${formatPaymentAmount(msg.content.amount_msats, msg.content.fiat_amount, { anchor: false })}${msg.content.reason ? `: ${msg.content.reason}` : ""}`
21691
+ );
21692
+ break;
21693
+ case "payment": {
21694
+ const amount = paymentAmount(msg);
21695
+ if (msg.from === "provider") {
21696
+ const noun = msg.content.reason === "change" ? "change" : "refund";
21697
+ info(`[${msg.seq}] ${prefix} sent ${noun}: ${amount}`);
21698
+ } else {
21699
+ info(`[${msg.seq}] ${prefix} paid: ${amount}`);
21700
+ }
21701
+ break;
21702
+ }
21703
+ case "complete":
21704
+ info(`[${msg.seq}] Job complete${msg.content.summary ? `: ${msg.content.summary}` : ""}`);
21705
+ break;
21706
+ case "working":
21707
+ info(
21708
+ `[${msg.seq}] Provider is working${msg.content.estimate_seconds ? ` (est. ${String(msg.content.estimate_seconds)}s)` : ""}${msg.content.hint ? `: ${msg.content.hint}` : ""}`
21709
+ );
21710
+ break;
21711
+ case "progress":
21712
+ renderProgressLine(msg.content, msg.seq);
21713
+ break;
21714
+ case "cancel":
21715
+ info(`[${msg.seq}] Cancelled${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
21716
+ break;
21717
+ default:
21718
+ info(`[${seq}] ${prefix} sent a message of type "${type}".`);
21719
+ }
21720
+ }
21721
+
21722
+ // src/lib/next-action-human.ts
21723
+ function nextActionHuman(action) {
21724
+ if (!action) return null;
21725
+ switch (action.type) {
21726
+ case "respond":
21727
+ case "pay": {
21728
+ const command = action.hint.match(/`(dvm[\s\S]*)`/)?.[1];
21729
+ if (command?.startsWith("dvm status ")) return `Next: ${action.type === "pay" ? "the provider's charge of " : ""}${action.display}`;
21730
+ if (action.type === "respond") {
21731
+ return `Next: ${action.display} Provider is waiting for your input. ${command ? `Run \`${command}\`.` : action.hint}`;
21732
+ }
21733
+ return `Next: Payment required to continue: ${action.display}${action.display.endsWith(".") ? "" : "."} Run \`${command ?? `dvm pay ${shellQuoteArg(action.job_id)}`}\`.`;
21734
+ }
21735
+ case "poll": {
21736
+ const hint = typeof action.hint === "string" ? action.hint : action.hint.text;
21737
+ const detail = hint === pollNextAction(action.job_id).hint || hint === "Job submitted, check back for updates" ? "" : hint.trim();
21738
+ const sentence = detail ? `Provider is still working: ${detail}${/[.!?]$/.test(detail) ? "" : "."}` : "Provider is still working.";
21739
+ return `Next: ${sentence} Keep watching with \`dvm messages ${shellQuoteArg(action.job_id)}\`.`;
21740
+ }
21741
+ case "refund":
21742
+ return action.claimed ? null : `Next: ${refundSummaryHuman(action)}`;
21743
+ case "approve":
21744
+ return `Next: ${action.hint}`;
21745
+ }
21746
+ }
21747
+ function printNextActionHuman(action, options = {}) {
21748
+ const line = nextActionHuman(options.terminal ? null : action);
21749
+ const refunds = options.refunds ?? [];
21750
+ for (const [index, claim] of refunds.entries()) {
21751
+ if (line && action?.type === "refund" && !action.claimed && index === refunds.length - 1) continue;
21752
+ info(refundSummaryHuman(claim));
21753
+ }
21754
+ if (line) info(line);
21755
+ }
21756
+
21757
+ // src/lib/wait-for-job.ts
21758
+ async function waitForJob(opts, durationMs, now = Date.now) {
21759
+ const deadline = now() + durationMs;
21760
+ const result = {
21761
+ messages: [],
21762
+ autoPayments: [],
21763
+ refunds: [],
21764
+ cursor: opts.afterSeq,
21765
+ nextAction: pollNextAction(opts.jobId)
21766
+ };
21767
+ const returnedSeqs = /* @__PURE__ */ new Set();
21768
+ const emittedSeqs = /* @__PURE__ */ new Set();
21769
+ const collectMessages = (messages2) => {
21770
+ for (const message2 of messages2) if (!returnedSeqs.has(message2.seq)) {
21771
+ returnedSeqs.add(message2.seq);
21772
+ result.messages.push(message2);
21773
+ }
21774
+ };
21775
+ const onMessage = (message2) => {
21776
+ if (emittedSeqs.has(message2.seq)) return;
21777
+ emittedSeqs.add(message2.seq);
21778
+ opts.onMessage?.(message2);
21779
+ };
21780
+ const messageAppendSession = opts.persistLocalState === false ? void 0 : opts.messageAppendSession ?? createMessageAppendSession(opts.jobId);
21781
+ let backoffMs = 1e3;
21782
+ let firstRead = true;
21783
+ const idleTimeoutMs = opts.timeoutMs ?? JOB_READ_TIMEOUT_MS;
21784
+ async function readWithRetry(read) {
21785
+ while (now() < deadline) {
21786
+ try {
21787
+ return await read();
21788
+ } catch (error) {
21789
+ if (!isAbortError(error) && !(error instanceof DvmError && error.code === "timeout")) throw error;
21790
+ await new Promise((resolve3) => setTimeout(resolve3, Math.min(backoffMs, Math.max(0, deadline - now()))));
21791
+ backoffMs = Math.min(backoffMs * 2, 3e4);
21792
+ }
21793
+ }
21794
+ return void 0;
21795
+ }
21796
+ while (now() < deadline) {
21797
+ const readOptions = () => ({ jobToken: opts.jobToken, timeoutMs: Math.max(1, Math.min(idleTimeoutMs, deadline - now())) });
21798
+ const snapshot = await readWithRetry(() => opts.transport.status(opts.jobId, opts.provider, readOptions()));
21799
+ if (!snapshot) break;
21800
+ if (isTerminalJobStatus(snapshot.status)) {
21801
+ result.nextAction = null;
21802
+ const history = await readWithRetry(() => opts.transport.getMessages(opts.jobId, result.cursor, opts.provider, readOptions()));
21803
+ if (!history) break;
21804
+ const tail = history.filter((message2) => message2.seq > result.cursor);
21805
+ collectMessages(tail);
21806
+ result.cursor = maxSeq(tail, result.cursor);
21807
+ for (const message2 of tail) onMessage(message2);
21808
+ if (opts.persistLocalState !== false) {
21809
+ messageAppendSession?.append(tail);
21810
+ result.refunds.push(...await claimInboundPayments(opts.jobId, tail));
21811
+ }
21812
+ result.nextAction = withRefundNextAction(opts.jobId, null, result.refunds);
21813
+ break;
21814
+ }
21815
+ const inFlight2 = opts.persistLocalState === false ? [] : loadJob(opts.jobId)?.inFlightPaymentRequestSeqs ?? [];
21816
+ let cursorLimit = Infinity;
21817
+ let streamAfter = result.cursor;
21818
+ if (inFlight2.length || firstRead && !opts.afterSeqExplicit && snapshot.status === "awaiting-input") {
21819
+ let unresolved = false;
21820
+ let retryDelayMs = backoffMs;
21821
+ let history;
21822
+ try {
21823
+ history = await readWithRetry(() => withJobPaymentLock(opts.jobId, async (assertOwned) => {
21824
+ const messages2 = await opts.transport.getMessages(opts.jobId, 0, opts.provider, readOptions());
21825
+ assertOwned();
21826
+ for (const seq of loadJob(opts.jobId)?.inFlightPaymentRequestSeqs ?? []) {
21827
+ try {
21828
+ reconcilePaymentRequestHistory(opts.jobId, seq, messages2, snapshot.status, now);
21829
+ } catch (error) {
21830
+ if (!(error instanceof DvmError) || !["payment_settling", "payment_request_not_pending"].includes(error.code)) throw error;
21831
+ if (!loadJob(opts.jobId)?.inFlightPaymentRequestSeqs?.includes(seq)) continue;
21832
+ unresolved = true;
21833
+ cursorLimit = Math.min(cursorLimit, seq - 1);
21834
+ if (typeof error.data?.retry_at_ms === "number")
21835
+ retryDelayMs = Math.min(retryDelayMs, Math.max(1, error.data.retry_at_ms - now()));
21836
+ }
21837
+ }
21838
+ return messages2;
21839
+ }));
21840
+ } catch (error) {
21841
+ if (!(error instanceof DvmError) || error.code !== "payment_settling") throw error;
21842
+ unresolved = true;
21843
+ cursorLimit = Math.min(...inFlight2.map((seq) => seq - 1));
21844
+ history = await readWithRetry(() => opts.transport.getMessages(opts.jobId, 0, opts.provider, readOptions()));
21845
+ }
21846
+ if (!history) break;
21847
+ messageAppendSession?.append(history);
21848
+ const answered = opts.persistLocalState === false ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(opts.jobId);
21849
+ for (const seq of answeredYieldSeqs(history)) answered.add(seq);
21850
+ const pending4 = history.findLast((msg) => msg.from === "provider" && ["prompt", "payment-request", "working", "complete", "cancel"].includes(msg.type) && !answered.has(msg.seq));
21851
+ const newerYield = snapshot.status === "awaiting-input" && pending4 && !answered.has(pending4.seq) && (pending4.type === "prompt" || pending4.type === "payment-request") && !inFlight2.includes(pending4.seq);
21852
+ if (unresolved) {
21853
+ const limit = newerYield ? pending4.seq - 1 : Infinity;
21854
+ const tail = history.filter((message2) => message2.seq > Math.max(opts.afterSeq, result.cursor) && message2.seq <= limit);
21855
+ collectMessages(tail);
21856
+ result.cursor = Math.min(maxSeq(tail, result.cursor), cursorLimit);
21857
+ for (const message2 of tail) onMessage(message2);
21858
+ if (opts.persistLocalState !== false)
21859
+ result.refunds.push(...await claimInboundPayments(opts.jobId, tail));
21860
+ }
21861
+ if (unresolved && !newerYield) {
21862
+ result.nextAction = pollNextAction(opts.jobId);
21863
+ await new Promise((resolve3) => setTimeout(resolve3, Math.min(retryDelayMs, Math.max(0, deadline - now()))));
21864
+ backoffMs = Math.min(backoffMs * 2, 3e4);
21865
+ continue;
21866
+ }
21867
+ streamAfter = result.cursor;
21868
+ if (unresolved && newerYield) streamAfter = pending4.seq - 1;
21869
+ if (pending4 && !answered.has(pending4.seq) && (!opts.afterSeqExplicit || inFlight2.includes(pending4.seq)) && (pending4.type === "prompt" || pending4.type === "payment-request"))
21870
+ streamAfter = Math.min(streamAfter, pending4.seq - 1);
21871
+ }
21872
+ firstRead = false;
21873
+ if (now() >= deadline) break;
21874
+ const next = await streamLoop({
21875
+ ...opts,
21876
+ onMessage,
21877
+ messageAppendSession,
21878
+ afterSeq: streamAfter,
21879
+ timeoutMs: readOptions().timeoutMs
21880
+ });
21881
+ collectMessages(next.messages);
21882
+ result.autoPayments.push(...next.autoPayments);
21883
+ result.refunds.push(...next.refunds);
21884
+ const progressed = next.cursor > result.cursor;
21885
+ result.cursor = Math.min(next.cursor, cursorLimit);
21886
+ result.nextAction = next.nextAction;
21887
+ if (next.nextAction?.type !== "poll") break;
21888
+ if (progressed) backoffMs = 1e3;
21889
+ const delay = Math.min(backoffMs, Math.max(0, deadline - now()));
21890
+ if (delay > 0) await new Promise((resolve3) => setTimeout(resolve3, delay));
21891
+ backoffMs = Math.min(backoffMs * 2, 3e4);
21892
+ }
21893
+ if (opts.persistLocalState !== false) {
21894
+ const remaining = loadJob(opts.jobId)?.inFlightPaymentRequestSeqs ?? [];
21895
+ result.cursor = Math.min(result.cursor, ...remaining.map((seq) => seq - 1));
21896
+ }
21897
+ result.messages.sort((a, b) => a.seq - b.seq);
21898
+ return result;
21899
+ }
21900
+
21286
21901
  // src/commands/messages.ts
21287
21902
  async function messages(jobId, opts) {
21903
+ if (opts.until !== void 0 && !opts.wait || opts.wait && opts.stream === false) {
21904
+ throw new DvmError("invalid_arguments", "Use --until with --wait, and --wait with streaming enabled.");
21905
+ }
21288
21906
  const access = resolveJobAccess(jobId, opts);
21289
21907
  return withJobTokenRedaction(access.jobToken, () => messagesWithAccess(jobId, opts, access));
21290
21908
  }
21291
21909
  async function messagesWithAccess(jobId, opts, access) {
21910
+ const waitDuration = opts.wait ? parseDurationMs(opts.until ?? "12h") : void 0;
21292
21911
  const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
21293
21912
  const { stored, ref, jobToken } = access;
21913
+ function actionFromMessages(batch) {
21914
+ const answered = access.endpointOverridden ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(jobId);
21915
+ const action = computeNextAction(jobId, batch.filter((message2) => !answered.has(message2.seq)));
21916
+ const request2 = batch.findLast((message2) => message2.type === "payment-request");
21917
+ if (action?.type === "pay" && request2 && !access.endpointOverridden && stored?.inFlightPaymentRequestSeqs?.includes(request2.seq))
21918
+ return { ...action, hint: paymentInFlightHint(jobId) };
21919
+ return action;
21920
+ }
21921
+ async function resolveNextAction2(action, messages2) {
21922
+ if (action?.type === "refund") return action;
21923
+ if (streamTerminalStatus(messages2) || !access.endpointOverridden && stored && isTerminalJobStatus(stored.status)) return null;
21924
+ if (!opts.human) return action;
21925
+ try {
21926
+ const readOptions = { jobToken, timeoutMs: opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 };
21927
+ const snapshot = await transport.status(jobId, ref, readOptions);
21928
+ if (isTerminalJobStatus(snapshot.status)) return null;
21929
+ if (action && (action.type !== "poll" || messages2.some((message2) => ["prompt", "payment-request", "working"].includes(message2.type)))) return action;
21930
+ if (snapshot.status === "awaiting-input") {
21931
+ const history = await transport.getMessages(jobId, 0, ref, readOptions);
21932
+ return actionFromMessages(history) ?? pollNextAction(jobId);
21933
+ }
21934
+ return action ?? pollNextAction(jobId);
21935
+ } catch {
21936
+ return action ?? pollNextAction(jobId);
21937
+ }
21938
+ }
21294
21939
  const transport = createDvmTransport();
21295
- const isTerminal = stored?.status === "completed" || stored?.status === "failed";
21940
+ const isTerminal = !access.endpointOverridden && !!stored && isTerminalJobStatus(stored.status);
21296
21941
  const after = opts.after !== void 0 ? Number(opts.after) : opts.stream === false && isTerminal ? 0 : access.endpointOverridden ? 0 : stored?.messageCursor ?? 0;
21297
21942
  if (opts.stream === false) {
21298
21943
  const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 5e3;
@@ -21316,11 +21961,12 @@ async function messagesWithAccess(jobId, opts, access) {
21316
21961
  persistStreamOutcome({ jobId, messages: msgs, cursor: newCursor, afterSeq: after });
21317
21962
  }
21318
21963
  const refunds = access.endpointOverridden ? [] : await claimInboundPayments(jobId, msgs);
21319
- const nextAction = refundNextAction(jobId, refunds) ?? computeNextAction(jobId, msgs);
21964
+ const nextAction = withRefundNextAction(jobId, actionFromMessages(msgs) ?? (streamTerminalStatus(msgs) || isTerminal ? null : pollNextAction(jobId)), refunds);
21320
21965
  const content2 = jobContentFields(
21321
21966
  jobId,
21322
21967
  await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken })
21323
21968
  );
21969
+ const resolvedAction2 = await resolveNextAction2(nextAction, msgs);
21324
21970
  transport.close();
21325
21971
  if (opts.human) {
21326
21972
  info(String(content2.content_hint));
@@ -21331,35 +21977,45 @@ async function messagesWithAccess(jobId, opts, access) {
21331
21977
  formatMessageHuman(msg, jobId, artifactSession);
21332
21978
  }
21333
21979
  finalizeProgressLine();
21334
- printRefundSummaryHuman(refunds);
21335
21980
  }
21981
+ printNextActionHuman(resolvedAction2, { refunds });
21336
21982
  } else {
21337
21983
  json({
21338
21984
  jobId,
21339
21985
  ...content2,
21340
21986
  messages: msgs.map(serialize),
21341
21987
  cursor: newCursor,
21342
- next_action: nextAction,
21988
+ next_action: resolvedAction2,
21343
21989
  ...await refundJsonField(refunds)
21344
21990
  });
21345
21991
  }
21346
21992
  return;
21347
21993
  }
21348
21994
  progressNotice("Streaming messages...", opts.human);
21349
- const result = await streamLoop({
21995
+ const streamOptions = {
21350
21996
  jobId,
21351
21997
  transport,
21352
21998
  provider: ref,
21353
21999
  policy: stored?.policy ?? void 0,
21354
22000
  afterSeq: after,
22001
+ afterSeqExplicit: opts.after !== void 0,
21355
22002
  jobToken,
21356
22003
  persistLocalState: !access.endpointOverridden,
22004
+ timeoutMs: opts.timeout ? Number(opts.timeout) * 1e3 : opts.wait ? 6e4 : 5e3,
21357
22005
  ...opts.human && {
21358
22006
  onMessage: (msg) => {
21359
22007
  if (msg.type === "progress") formatMessageHuman(msg);
21360
22008
  }
21361
22009
  }
21362
- });
22010
+ };
22011
+ const waitDeadline = waitDuration === void 0 ? void 0 : Date.now() + waitDuration;
22012
+ let result;
22013
+ try {
22014
+ result = opts.wait ? await waitForJob(streamOptions, waitDuration) : await streamLoop(streamOptions);
22015
+ } catch (err) {
22016
+ transport.close();
22017
+ throw err;
22018
+ }
21363
22019
  if (!access.endpointOverridden) {
21364
22020
  persistStreamOutcome({
21365
22021
  jobId,
@@ -21370,11 +22026,12 @@ async function messagesWithAccess(jobId, opts, access) {
21370
22026
  }
21371
22027
  const content = jobContentFields(
21372
22028
  jobId,
21373
- await observeJobContent(jobId, transport, ref, {
21374
- timeoutMs: opts.timeout ? Number(opts.timeout) * 1e3 : 5e3,
22029
+ waitDeadline !== void 0 && Date.now() >= waitDeadline ? void 0 : await observeJobContent(jobId, transport, ref, {
22030
+ timeoutMs: waitDeadline === void 0 ? opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now())),
21375
22031
  jobToken
21376
22032
  })
21377
22033
  );
22034
+ const resolvedAction = opts.wait ? result.nextAction : await resolveNextAction2(result.nextAction, result.messages);
21378
22035
  transport.close();
21379
22036
  if (opts.human) {
21380
22037
  info(String(content.content_hint));
@@ -21386,92 +22043,20 @@ async function messagesWithAccess(jobId, opts, access) {
21386
22043
  formatMessageHuman(msg, jobId, artifactSession);
21387
22044
  }
21388
22045
  finalizeProgressLine();
21389
- printRefundSummaryHuman(result.refunds);
21390
22046
  }
22047
+ printNextActionHuman(resolvedAction, { refunds: result.refunds });
21391
22048
  } else {
21392
22049
  json({
21393
22050
  jobId,
21394
22051
  ...content,
21395
22052
  messages: result.messages.map(serialize),
21396
22053
  cursor: result.cursor,
21397
- next_action: result.nextAction,
22054
+ next_action: resolvedAction,
21398
22055
  ...result.autoPayments.length > 0 ? { auto_payments: result.autoPayments } : {},
21399
22056
  ...await refundJsonField(result.refunds)
21400
22057
  });
21401
22058
  }
21402
22059
  }
21403
- function paymentAmount(msg) {
21404
- if (msg.from === "requester" && msg.content.credit) {
21405
- const credit = msg.content.credit;
21406
- const digits = String(credit.amount_micro).padStart(7, "0");
21407
- const fraction = digits.slice(-6).replace(/0+$/, "");
21408
- const amount = digits.slice(0, -6) + (fraction ? `.${fraction}` : "");
21409
- return `${amount} ${credit.currency.toUpperCase()} from prepaid balance`;
21410
- }
21411
- return formatAmountBestEffort(msg.content.amount_msats);
21412
- }
21413
- function formatMessageHuman(msg, jobId, artifactSession) {
21414
- const prefix = msg.from === "provider" ? "Provider" : "You";
21415
- if (msg.type !== "progress") finalizeProgressLine();
21416
- switch (msg.type) {
21417
- case "text":
21418
- info(`[${msg.seq}] ${prefix}: ${msg.content.text}`);
21419
- break;
21420
- case "prompt":
21421
- info(`[${msg.seq}] ${prefix} asks: ${msg.content.text}`);
21422
- if (msg.content.options) {
21423
- for (const opt of msg.content.options) {
21424
- info(` - ${opt}`);
21425
- }
21426
- }
21427
- break;
21428
- case "artifact": {
21429
- const label = msg.content.name ?? msg.content.mime_type ?? "unknown type";
21430
- if (jobId) {
21431
- const saved = saveArtifact(msg.content, artifactSession ?? createArtifactSaveSession());
21432
- if (saved) {
21433
- info(
21434
- `[${msg.seq}] ${prefix} sent artifact: ${label} (${saved.bytes.toLocaleString()} bytes \u2192 ${saved.path})`
21435
- );
21436
- break;
21437
- }
21438
- }
21439
- info(`[${msg.seq}] ${prefix} sent artifact: ${label}`);
21440
- break;
21441
- }
21442
- case "payment-request":
21443
- info(
21444
- `[${msg.seq}] ${prefix} requests ${formatPaymentAmount(msg.content.amount_msats, msg.content.fiat_amount, { anchor: false })}${msg.content.reason ? `: ${msg.content.reason}` : ""}`
21445
- );
21446
- break;
21447
- case "payment": {
21448
- const amount = paymentAmount(msg);
21449
- if (msg.from === "provider") {
21450
- const noun = msg.content.reason === "change" ? "change" : "refund";
21451
- info(`[${msg.seq}] ${prefix} sent ${noun}: ${amount}`);
21452
- } else {
21453
- info(`[${msg.seq}] ${prefix} paid: ${amount}`);
21454
- }
21455
- break;
21456
- }
21457
- case "complete":
21458
- info(`[${msg.seq}] Job complete${msg.content.summary ? `: ${msg.content.summary}` : ""}`);
21459
- break;
21460
- case "working":
21461
- info(
21462
- `[${msg.seq}] Provider is working${msg.content.estimate_seconds ? ` (est. ${String(msg.content.estimate_seconds)}s)` : ""}${msg.content.hint ? `: ${msg.content.hint}` : ""}`
21463
- );
21464
- break;
21465
- case "progress":
21466
- renderProgressLine(msg.content, msg.seq);
21467
- break;
21468
- case "cancel":
21469
- info(`[${msg.seq}] Cancelled${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
21470
- break;
21471
- default:
21472
- info(`[${msg.seq}] ${prefix} [${msg.type}]: ${JSON.stringify(msg.content)}`);
21473
- }
21474
- }
21475
22060
  function serializeMessageForOutput(msg) {
21476
22061
  return serialize(msg);
21477
22062
  }
@@ -21495,6 +22080,7 @@ function serialize(msg) {
21495
22080
  };
21496
22081
  if (msg.content.options) content.options = msg.content.options;
21497
22082
  if (msg.content.schema) content.schema = msg.content.schema;
22083
+ if (msg.content.expires_at_ms !== void 0) content.expires_at_ms = msg.content.expires_at_ms;
21498
22084
  return { ...base, content, display };
21499
22085
  }
21500
22086
  case "artifact": {
@@ -21707,10 +22293,37 @@ async function payWithAccess(jobId, opts, access) {
21707
22293
  const { stored, ref, jobToken } = access;
21708
22294
  const msgs = loadMessages(jobId);
21709
22295
  const pending4 = stored.pendingCreditPayment;
21710
- const paymentMessage = findPendingPaymentRequest(msgs);
21711
- const paymentReq = pending4?.request ?? paymentMessage?.content;
22296
+ const transport = createDvmTransport();
22297
+ const inFlightMessage = msgs.findLast((message2) => message2.from === "provider" && message2.type === "payment-request" && stored.inFlightPaymentRequestSeqs?.includes(message2.seq));
22298
+ let paymentMessage = pendingPaymentRequest(msgs) ?? inFlightMessage;
22299
+ const recovering = pending4 || paymentMessage && stored.inFlightPaymentRequestSeqs?.includes(paymentMessage.seq);
22300
+ if (!recovering) {
22301
+ try {
22302
+ const readOptions = { jobToken, timeoutMs: JOB_READ_TIMEOUT_MS };
22303
+ const snapshot = await transport.status(jobId, ref, readOptions);
22304
+ const history = snapshot.status === "awaiting-input" ? await transport.getMessages(jobId, 0, ref, readOptions) : [];
22305
+ paymentMessage = pendingPaymentRequest(history);
22306
+ } catch (error) {
22307
+ transport.close();
22308
+ throw error;
22309
+ }
22310
+ }
22311
+ const inactiveRequest = isTerminalJobStatus(stored.status) || paymentMessage?.type === "payment-request" && paymentMessage.content.expires_at_ms !== void 0 && paymentMessage.content.expires_at_ms <= Date.now();
22312
+ if (!pending4 && inactiveRequest) {
22313
+ if (paymentMessage && stored.inFlightPaymentRequestSeqs?.includes(paymentMessage.seq) && ref.endpoint && sameEndpoint(stored.endpoint, ref.endpoint)) {
22314
+ try {
22315
+ await reconcileInFlightPaymentRequest(jobId, paymentMessage.seq, transport, ref, { jobToken });
22316
+ } catch (error) {
22317
+ transport.close();
22318
+ throw error;
22319
+ }
22320
+ }
22321
+ paymentMessage = void 0;
22322
+ }
22323
+ const paymentReq = pending4?.request ?? (paymentMessage?.type === "payment-request" ? paymentMessage.content : void 0);
21712
22324
  const requestSeq = pending4?.authorization.request_seq ?? paymentMessage?.seq;
21713
22325
  if (!paymentReq) {
22326
+ transport.close();
21714
22327
  throw new DvmError(
21715
22328
  "no_payment_pending",
21716
22329
  "No pending payment request found for this job.",
@@ -21721,7 +22334,6 @@ async function payWithAccess(jobId, opts, access) {
21721
22334
  applyMintPin(paymentReq.mints ?? [], opts.mint);
21722
22335
  updateJob(jobId, { pinnedMint: opts.mint });
21723
22336
  }
21724
- const transport = createDvmTransport();
21725
22337
  if (!stored.policy) {
21726
22338
  throw new DvmError(
21727
22339
  "no_budget",
@@ -21737,7 +22349,9 @@ async function payWithAccess(jobId, opts, access) {
21737
22349
  jobToken,
21738
22350
  rail,
21739
22351
  maxCashuPrincipalSats,
21740
- requestSeq
22352
+ requestSeq,
22353
+ approval: "explicit",
22354
+ creditRecoveryOnly: pending4 !== void 0
21741
22355
  });
21742
22356
  if (result === "over-budget") {
21743
22357
  transport.close();
@@ -21869,16 +22483,6 @@ function parsePositiveCashuSats(raw2) {
21869
22483
  }
21870
22484
  return value;
21871
22485
  }
21872
- function findPendingPaymentRequest(msgs) {
21873
- for (let i = msgs.length - 1; i >= 0; i--) {
21874
- const msg = msgs[i];
21875
- if (msg.type === "payment") return void 0;
21876
- if (msg.type === "payment-request") {
21877
- return { content: msg.content, seq: msg.seq };
21878
- }
21879
- }
21880
- return void 0;
21881
- }
21882
22486
 
21883
22487
  // src/lib/data-flag.ts
21884
22488
  async function resolveDataFlag(raw2) {
@@ -22421,6 +23025,9 @@ function railList(keys, isKnown, label) {
22421
23025
  }
22422
23026
 
22423
23027
  // src/commands/receipts.ts
23028
+ import { createHash as createHash3 } from "crypto";
23029
+ import { createReadStream } from "fs";
23030
+ import { open, stat } from "fs/promises";
22424
23031
  var DEFAULT_LIMIT2 = 50;
22425
23032
  function receiptsList(opts) {
22426
23033
  const limit = resolveLimit2(opts.limit);
@@ -22466,6 +23073,9 @@ Endpoint: ${entry.endpoint || "(unknown)"}`);
22466
23073
  });
22467
23074
  }
22468
23075
  async function receiptsVerify(jobId, opts) {
23076
+ if (opts.artifact !== void 0 && !opts.file?.length) {
23077
+ throw new DvmError("invalid_argument", "--artifact requires --file.", "Pass --file <path> with --artifact to select the file artifact to check.");
23078
+ }
22469
23079
  const entry = requireStored(jobId);
22470
23080
  const builder = opts.endpoint ? await refetchAnchor(opts.endpoint) : entry.builder ?? loadJob(jobId)?.builderAnchor;
22471
23081
  const delivered = deliveredFromMessages(jobId, entry.receipt);
@@ -22475,9 +23085,15 @@ async function receiptsVerify(jobId, opts) {
22475
23085
  expectedJobId: jobId,
22476
23086
  delivered
22477
23087
  });
23088
+ const files = await verifyFiles(jobId, opts, delivered, result);
23089
+ if (files.some((file) => !["match", "no_signed_digest", "unverifiable"].includes(file.status))) process.exitCode = 1;
22478
23090
  const rate = getLastKnownBtcRate()?.rate ?? 0;
22479
23091
  if (opts.human) {
22480
23092
  renderVerdictHuman(entry, result, rate);
23093
+ for (const file of files) {
23094
+ info(`${file.path}: ${file.display}`);
23095
+ info(` ${file.hint}`);
23096
+ }
22481
23097
  info(`
22482
23098
  Signature: ${result.checks.signature ? "valid" : "INVALID"}`);
22483
23099
  info(`Attestation: ${result.checks.attestation}`);
@@ -22487,10 +23103,90 @@ Signature: ${result.checks.signature ? "valid" : "INVALID"}`);
22487
23103
  }
22488
23104
  json({
22489
23105
  ...storedReceiptJson(entry, result, rate),
23106
+ ...opts.file?.length ? { files } : {},
22490
23107
  anchor_source: opts.endpoint ? "refetched" : "stored",
22491
23108
  hint: receiptHint(result.status, jobId)
22492
23109
  });
22493
23110
  }
23111
+ async function verifyFiles(jobId, opts, delivered, result) {
23112
+ if (!opts.file?.length) return [];
23113
+ const artifacts = (result.checks.result_hash === "ok" ? delivered?.artifactContents ?? [] : []).map((content, index) => ({
23114
+ content,
23115
+ index: index + 1
23116
+ }));
23117
+ const selected = opts.artifact === void 0 ? artifacts : artifacts.filter(
23118
+ ({ content, index }) => /^[1-9]\d*$/.test(opts.artifact) ? String(index) === opts.artifact : content.name === opts.artifact
23119
+ );
23120
+ if (opts.artifact !== void 0 && result.checks.result_hash === "ok" && selected.length === 0) {
23121
+ throw new DvmError(
23122
+ "artifact_not_found",
23123
+ "No artifact matches --artifact.",
23124
+ artifacts.length ? "Select an artifact by its 1-based index, or by its exact name as shown in `dvm messages <job-id>`. JSON output lists them in available_artifacts." : "This receipt has no delivered artifacts to select. Omit --artifact.",
23125
+ { available_artifacts: artifacts.map(({ content, index }) => ({ index, name: content.name === void 0 ? null : asProviderText(content.name) })) }
23126
+ );
23127
+ }
23128
+ if (opts.artifact !== void 0 && selected.length > 1) {
23129
+ throw new DvmError("ambiguous_artifact", "More than one artifact matches --artifact.", "Select its unique 1-based artifact index instead.");
23130
+ }
23131
+ const candidates = selected.filter(
23132
+ ({ content }) => typeof content.url === "string" && content.url.length > 0 && typeof content.sha256 === "string" && /^[a-f0-9]{64}$/i.test(content.sha256)
23133
+ );
23134
+ const files = [];
23135
+ for (const path of opts.file ?? []) {
23136
+ const base = { path, sha256: null, matched_artifact: null };
23137
+ try {
23138
+ if (!(await stat(path)).isFile()) throw new Error("Not a regular file");
23139
+ const file = await open(path, "r");
23140
+ try {
23141
+ if (!(await file.stat()).isFile()) throw new Error("Not a regular file");
23142
+ } finally {
23143
+ await file.close();
23144
+ }
23145
+ if (result.checks.result_hash !== "ok" || result.status === "invalid") {
23146
+ files.push({
23147
+ ...base,
23148
+ status: "unverifiable",
23149
+ display: "The file cannot be checked against signed evidence.",
23150
+ hint: `The receipt could not be checked, so the file cannot be checked against it. Run 'dvm receipts verify ${jobId}' without --file to see why.`
23151
+ });
23152
+ continue;
23153
+ }
23154
+ if (candidates.length === 0) {
23155
+ files.push({
23156
+ ...base,
23157
+ status: "no_signed_digest",
23158
+ display: "No signed file fingerprint is available for this selection.",
23159
+ hint: "The DVM did not sign a usable SHA-256 fingerprint for a URL artifact in this selection. Check --artifact if supplied."
23160
+ });
23161
+ continue;
23162
+ }
23163
+ const hash = createHash3("sha256");
23164
+ let size = 0;
23165
+ for await (const chunk of createReadStream(path)) {
23166
+ size += chunk.length;
23167
+ hash.update(chunk);
23168
+ }
23169
+ const sha2563 = hash.digest("hex");
23170
+ const match = candidates.find(({ content }) => content.sha256.toLowerCase() === sha2563 && (typeof content.size_bytes !== "number" || content.size_bytes === size));
23171
+ files.push({
23172
+ path,
23173
+ sha256: sha2563,
23174
+ matched_artifact: match ? { name: match.content.name === void 0 ? null : asProviderText(match.content.name), index: match.index } : null,
23175
+ status: match ? "match" : "mismatch",
23176
+ display: match ? "The file matches the fingerprint the DVM signed in its receipt." : `The file does not match the fingerprint${candidates.some(({ content }) => typeof content.size_bytes === "number") ? " or size" : ""} the DVM signed in its receipt.`,
23177
+ hint: match ? "The file's bytes match signed evidence; this does not assess the quality of the result." : "Check that you selected the intended file and artifact. Do not rely on this file as the signed result."
23178
+ });
23179
+ } catch {
23180
+ files.push({
23181
+ ...base,
23182
+ status: "unreadable",
23183
+ display: "The local file could not be read.",
23184
+ hint: "Check that the path names an existing, readable file, not a directory, and try again."
23185
+ });
23186
+ }
23187
+ }
23188
+ return files;
23189
+ }
22494
23190
  function receiptsExport(opts) {
22495
23191
  for (const entry of filterReceipts(loadReceipts(), opts)) {
22496
23192
  raw(JSON.stringify(entry));
@@ -22634,7 +23330,7 @@ function buildPolicy(opts, btcRate) {
22634
23330
  }
22635
23331
 
22636
23332
  // src/commands/request.ts
22637
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
23333
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "crypto";
22638
23334
 
22639
23335
  // src/lib/credit-defer.ts
22640
23336
  function noteDeferredFunding(funding) {
@@ -22667,7 +23363,7 @@ async function settleCreditAfterJob(args) {
22667
23363
  }
22668
23364
  }
22669
23365
  if (args.allowTopup !== false) {
22670
- const refill = args.refillPocket ?? (await import("./pocket-refill-SKECWGA3.js")).refillPocketIfLow;
23366
+ const refill = args.refillPocket ?? (await import("./pocket-refill-3ZV36DOA.js")).refillPocketIfLow;
22671
23367
  await refill({ human: args.human }).catch(() => void 0);
22672
23368
  }
22673
23369
  }
@@ -23163,6 +23859,7 @@ function dollarLimitMicro(declaredLimit) {
23163
23859
  }
23164
23860
 
23165
23861
  // src/lib/request-intent-store.ts
23862
+ var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
23166
23863
  import {
23167
23864
  closeSync as closeSync3,
23168
23865
  existsSync as existsSync7,
@@ -23218,6 +23915,31 @@ function loadRequestIntent(requestId) {
23218
23915
  );
23219
23916
  }
23220
23917
  }
23918
+ function recordRequestRailPayment(requestId, payment) {
23919
+ assertRequestId(requestId);
23920
+ if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
23921
+ const dir = intentDirectory(requestId);
23922
+ const target = join8(dir, "intent.json");
23923
+ const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
23924
+ try {
23925
+ const intent = loadRequestIntent(requestId);
23926
+ if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
23927
+ if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
23928
+ throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
23929
+ const temp = join8(dir, `rail.${String(process.pid)}.tmp`);
23930
+ const fd = openSync3(temp, "w", 384);
23931
+ try {
23932
+ writeFileSync4(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
23933
+ fsyncSync(fd);
23934
+ } finally {
23935
+ closeSync3(fd);
23936
+ }
23937
+ renameSync2(temp, target);
23938
+ fsyncDirectory(dir);
23939
+ } finally {
23940
+ release();
23941
+ }
23942
+ }
23221
23943
  function assertNoPaymentOrAuthSecrets(body) {
23222
23944
  if (!containsForbiddenSecret(body)) return;
23223
23945
  throw new DvmError(
@@ -23953,7 +24675,7 @@ async function request(opts) {
23953
24675
  outputCollectedQuotes(receipt.jobId || null, quotes, opts, identity, void 0, action);
23954
24676
  return;
23955
24677
  }
23956
- saveJob({
24678
+ saveSubmittedJob({
23957
24679
  id: receipt.jobId,
23958
24680
  ...transactionRecordFields(receipt),
23959
24681
  endpoint,
@@ -23969,7 +24691,7 @@ async function request(opts) {
23969
24691
  ...requestedMaxCashuFeeSats !== void 0 ? { maxCashuFeeSats: requestedMaxCashuFeeSats } : {},
23970
24692
  // the job cleared by drawing on a prepaid credit — no payment
23971
24693
  // attach, no budget-ledger entry (the funding already counted).
23972
- ...probePlan.mode === "draw" ? { paymentMethod: "credit" } : {},
24694
+ ...probePlan.mode === "draw" ? { paymentMethod: "credit" } : { upfrontRailPayment: "free" },
23973
24695
  ...signing ? { creditBinding: probePlan.mode === "draw" ? { creditId: probePlan.creditId, drawId: probePlan.drawId, callerPubkey: signing.pubkey } : { unbound: true, callerPubkey: signing.pubkey } } : {},
23974
24696
  // persist the anonymous-flow per-job token so subsequent
23975
24697
  // status/messages/pay/cancel commands can present it as `X-Job-Token`.
@@ -23982,11 +24704,15 @@ async function request(opts) {
23982
24704
  ...receiptTrustFields(providerInfo),
23983
24705
  ...localCorrelationJobFields(localCorrelationId)
23984
24706
  });
24707
+ recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment);
23985
24708
  if (noStream) {
23986
24709
  transport.close();
23987
24710
  if (opts.human) {
23988
24711
  info(`Job published: ${receipt.jobId}`);
23989
24712
  echoTraceIdHuman();
24713
+ if (!isTerminalJobStatus(receipt.status)) {
24714
+ printNextActionHuman(pollNextAction(receipt.jobId, "Job submitted, check back for updates"));
24715
+ }
23990
24716
  } else {
23991
24717
  json({
23992
24718
  jobId: receipt.jobId,
@@ -24114,8 +24840,8 @@ async function request(opts) {
24114
24840
  }
24115
24841
  if (captured) renderReceiptHuman(captured);
24116
24842
  finalizeProgressLine();
24117
- printRefundSummaryHuman(result.refunds);
24118
24843
  echoTraceIdHuman();
24844
+ printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: isTerminalJobStatus(receipt.status) || !!streamTerminalStatus(result.messages) });
24119
24845
  } else {
24120
24846
  json({
24121
24847
  jobId: receipt.jobId,
@@ -24188,7 +24914,7 @@ function identityArgs(identity) {
24188
24914
  return identity ? { identity } : {};
24189
24915
  }
24190
24916
  function sha256Hex(value) {
24191
- return createHash2("sha256").update(value, "utf8").digest("hex");
24917
+ return createHash4("sha256").update(value, "utf8").digest("hex");
24192
24918
  }
24193
24919
  async function fetchServerPriceMicro(transport, ref, envelope) {
24194
24920
  try {
@@ -24891,6 +25617,7 @@ async function payWithTempo(args, credential) {
24891
25617
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
24892
25618
  const usdcMicroUnits = Number(tempoCredentialAmountMicro(credential));
24893
25619
  const paidMsats = usdcToMsats(usdcMicroUnits / 1e6, btcRate);
25620
+ if (opts.requestId) recordRequestRailPayment(opts.requestId, { method: "tempo", amountMsats: paidMsats });
24894
25621
  const usd2 = usdcMicroUnits / 1e6;
24895
25622
  const priceLabel = `$${formatUsd(usd2)} USDC`;
24896
25623
  const accountShort = `${account.address.slice(0, 6)}\u2026${account.address.slice(-4)}`;
@@ -24985,7 +25712,7 @@ async function payWithTempo(args, credential) {
24985
25712
  `Verify the Tempo account has at least the quoted amount in ${asset?.label ?? "the rail's settlement token"} on ${tempoNetworkLabel(network)} (chain ${String(chain.chainId)}).${asset ? ` ${tempoWrongAssetHint(asset)}` : ""}`
24986
25713
  );
24987
25714
  }
24988
- addPayment(effectiveJobId, paidMsats);
25715
+ recordUpfrontRailPayment(effectiveJobId, { method: "tempo", amountMsats: paidMsats }, true);
24989
25716
  recordSpend({
24990
25717
  msats: paidMsats,
24991
25718
  btcRate: args.btcRate,
@@ -25224,6 +25951,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
25224
25951
  const priceSats = Math.ceil(chosen.priceMsats / 1e3);
25225
25952
  const maxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
25226
25953
  const baseContext = {
25954
+ upfront_rail_payment: { method: "cashu", amountMsats: chosen.priceMsats },
25227
25955
  dvm_id: identity.dvmId,
25228
25956
  capability: identity.capability,
25229
25957
  pinned_mint: opts.mint,
@@ -25351,6 +26079,8 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
25351
26079
  providerInfo
25352
26080
  });
25353
26081
  }
26082
+ const pricedRequestId = opts.requestId ?? generatedRequestId;
26083
+ if (pricedRequestId) recordRequestRailPayment(pricedRequestId, { method: "cashu", amountMsats: chosen.priceMsats });
25354
26084
  if (fundPlan && signing) {
25355
26085
  ensureProvisionalCredit({
25356
26086
  endpoint: ref.endpoint,
@@ -25629,7 +26359,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
25629
26359
  }
25630
26360
  });
25631
26361
  await collectCashuChange(effectiveJobId, receipt.cashuChange);
25632
- addPayment(effectiveJobId, chosen.priceMsats);
26362
+ recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
25633
26363
  if (fundPlan) {
25634
26364
  recordSpend({
25635
26365
  msats: fundPlan.fundMsats,
@@ -25754,6 +26484,7 @@ async function tryX402UpfrontPayment(args) {
25754
26484
  }
25755
26485
  async function payWithX402(args, proof) {
25756
26486
  const { transport, ref, envelope, chosen, opts, identity, policy, wallet } = args;
26487
+ if (opts.requestId) recordRequestRailPayment(opts.requestId, { method: "x402", amountMsats: proof.amountMsats });
25757
26488
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
25758
26489
  const usdcMicroUnits = Number(proof.amountUsdcMicro);
25759
26490
  const usd2 = usdcMicroUnits / 1e6;
@@ -25838,7 +26569,7 @@ async function payWithX402(args, proof) {
25838
26569
  asset ? `Verify the account ${addressShort} holds at least the quoted amount in ${asset.label} (${asset.address}) on ${asset.networkLabel} \u2014 the chain this DVM advertises, which is not necessarily the one 'dvm wallet balance' reads. A different dollar${asset.confusable ? ` such as ${asset.confusable}` : ""}, or the right one on another chain, cannot settle this payment.` : "Verify the x402 account holds the quoted USDC amount on the advertised network."
25839
26570
  );
25840
26571
  }
25841
- addPayment(effectiveJobId, proof.amountMsats);
26572
+ recordUpfrontRailPayment(effectiveJobId, { method: "x402", amountMsats: proof.amountMsats }, true);
25842
26573
  recordSpend({
25843
26574
  msats: proof.amountMsats,
25844
26575
  btcRate: proof.btcRate,
@@ -25927,19 +26658,6 @@ async function streamToCompletion(baseOpts, deadlineMs) {
25927
26658
  const allMessages = [...result.messages];
25928
26659
  const allAutoPayments = [...result.autoPayments];
25929
26660
  const allRefunds = [...result.refunds];
25930
- if (result.messages.length === 0 && result.nextAction === null) {
25931
- return {
25932
- messages: allMessages,
25933
- autoPayments: allAutoPayments,
25934
- refunds: allRefunds,
25935
- nextAction: {
25936
- type: "poll",
25937
- job_id: baseOpts.jobId,
25938
- hint: "Provider hasn't yielded yet, check back later"
25939
- },
25940
- cursor: result.cursor
25941
- };
25942
- }
25943
26661
  while (result.nextAction?.type === "poll") {
25944
26662
  if (Date.now() >= deadlineMs) break;
25945
26663
  const waitMs = Math.min(
@@ -26040,8 +26758,13 @@ async function streamAfterPayment(args) {
26040
26758
  strictPerCall: args.strictPerCall
26041
26759
  });
26042
26760
  if (recovered) return;
26761
+ const nextAction = pollNextAction(
26762
+ jobId,
26763
+ `Payment sent but the result stream timed out. ${pollNextAction(jobId).hint}`
26764
+ );
26043
26765
  if (human) {
26044
26766
  info(paidTimeoutMessage);
26767
+ printNextActionHuman(nextAction);
26045
26768
  } else {
26046
26769
  json({
26047
26770
  jobId,
@@ -26053,10 +26776,7 @@ async function streamAfterPayment(args) {
26053
26776
  // not the job. `poll`, not `null`: the result is still coming.
26054
26777
  ...takeCreditNoticeFields(),
26055
26778
  ...takeFeedbackNoticeFields(),
26056
- next_action: pollNextAction(
26057
- jobId,
26058
- "Payment sent but the result stream timed out. The job is still running \u2014 check back with 'dvm status'."
26059
- )
26779
+ next_action: nextAction
26060
26780
  });
26061
26781
  }
26062
26782
  throw new DvmError("timeout", paidTimeoutMessage);
@@ -26072,7 +26792,7 @@ async function streamAfterPayment(args) {
26072
26792
  }
26073
26793
  if (captured) renderReceiptHuman(captured);
26074
26794
  finalizeProgressLine();
26075
- printRefundSummaryHuman(result.refunds);
26795
+ printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: !!streamTerminalStatus(result.messages) });
26076
26796
  } else {
26077
26797
  json({
26078
26798
  jobId,
@@ -26315,12 +27035,20 @@ async function requestResult(requestId, opts = {}) {
26315
27035
  pinnedMint: intent.pinnedMint,
26316
27036
  strictPerCall: intent.strictPerCall,
26317
27037
  maxCashuFeeSats: intent.maxCashuFeeSats,
26318
- paymentMethod: paymentMethod(receipt),
27038
+ paymentMethod: creditBinding && !originalData?.fund ? "credit" : intent.railPayment?.method ?? paymentMethod(receipt),
26319
27039
  receiptsSupported: intent.receiptsSupported,
26320
27040
  builderAnchor: intent.builderAnchor,
26321
27041
  ...restored
26322
27042
  });
26323
27043
  }
27044
+ if (!(creditBinding && !originalData?.fund) && existing?.paymentMethod !== "credit") {
27045
+ const accepted = parseUpfrontPayment(receipt.upfrontPayment);
27046
+ const localPayment = intent.railPayment ?? parseUpfrontRailPayment(existing?.upfrontRailPayment);
27047
+ const method = localPayment?.method ?? existing?.paymentMethod ?? accepted?.rail ?? paymentMethod(receipt);
27048
+ const free = existing?.upfrontRailPayment === "free" || accepted?.amount_msats === 0 && !method;
27049
+ recordUpfrontRailPayment(receipt.jobId, localPayment ?? (free ? "free" : accepted && method ? { method, amountMsats: accepted.amount_msats } : void 0));
27050
+ }
27051
+ recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, originalData?.fund !== void 0);
26324
27052
  if (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled") {
26325
27053
  markJobTerminal(receipt.jobId, receipt.status, completionSnapshot(receipt), restored);
26326
27054
  } else {
@@ -26634,6 +27362,99 @@ function outputResults2(resultJson, human, nextAction) {
26634
27362
  }
26635
27363
  }
26636
27364
 
27365
+ // src/lib/job-spend.ts
27366
+ function jobSpend(job, receipt) {
27367
+ const charges = [];
27368
+ const refunds = [];
27369
+ let request2;
27370
+ for (const message2 of loadMessages(job.id).sort((a, b) => a.seq - b.seq)) {
27371
+ if (message2.from === "provider" && message2.type === "payment-request") request2 = message2;
27372
+ if (message2.type !== "payment") continue;
27373
+ const payment = message2.content;
27374
+ if (message2.from === "provider") {
27375
+ refunds.push({
27376
+ seq: message2.seq,
27377
+ amount_msats: payment.amount_msats,
27378
+ display: formatPaymentAmount(payment.amount_msats ?? 0, void 0, { anchor: false }),
27379
+ reason: asProviderText(payment.reason ?? "refund")
27380
+ });
27381
+ continue;
27382
+ }
27383
+ const requestSeq = payment.credit?.request_seq ?? request2?.seq;
27384
+ const ask = request2 && request2.seq === requestSeq ? request2.content : void 0;
27385
+ const booked = payment.credit && job.bookedCreditPayments?.find((entry) => entry.authorization.payment_id === payment.credit?.payment_id);
27386
+ const amount = booked ? booked.amountMsats ?? booked.request.amount_msats : payment.amount_msats ?? ask?.amount_msats ?? 0;
27387
+ const fiat2 = payment.credit ? { amount: payment.credit.amount_micro / 1e6, currency: payment.credit.currency } : ask?.fiat_amount;
27388
+ charges.push({
27389
+ seq: message2.seq,
27390
+ amount_msats: amount,
27391
+ display: formatPaymentAmount(amount, fiat2, { anchor: false }),
27392
+ ...fiat2 && fiat2.amount > 0 ? { fiat_amount: fiat2 } : {},
27393
+ rail: payment.credit ? "credit" : payment.tempo_credential ? "tempo" : payment.x402_payment ? "x402" : payment.cashu_token ? "cashu_p2pk" : "unknown",
27394
+ approval: job.paymentApprovals?.find((entry) => entry.requestSeq === requestSeq)?.approval ?? "unknown",
27395
+ reason: asProviderText(ask?.reason ?? booked?.request.reason ?? "")
27396
+ });
27397
+ request2 = void 0;
27398
+ }
27399
+ const chargeTotal = charges.reduce((sum, charge) => sum + charge.amount_msats, 0);
27400
+ const total = job.totalPaidMsats ?? job.costMsats ?? 0;
27401
+ const knownCredit = job.paymentMethod === "credit" && !hasUnknownUpfrontCredit(job);
27402
+ const upfront = knownCredit ? job.upfrontPayment.amount_msats : Math.max(0, total - chargeTotal);
27403
+ const payments = job.paymentsHonoured ?? charges.length + (upfront > 0 ? 1 : 0);
27404
+ const currency = charges[0]?.fiat_amount?.currency;
27405
+ const fiat = upfront === 0 && currency && charges.every((charge) => charge.fiat_amount?.currency === currency) ? { currency, amount: charges.reduce((sum, charge) => sum + charge.fiat_amount.amount, 0) } : void 0;
27406
+ const totalDisplay = formatPaymentAmount(total, fiat, { anchor: false });
27407
+ const budgetDisplay = job.policy ? formatPaymentAmount(
27408
+ job.policy.maxTotalMsats,
27409
+ fiat && total > 0 ? { currency: fiat.currency, amount: fiat.amount * job.policy.maxTotalMsats / total } : void 0,
27410
+ { anchor: false }
27411
+ ) : void 0;
27412
+ const logMismatch = isTerminalJobStatus(job.status) && (chargeTotal > total || payments !== charges.length + (upfront > 0 ? 1 : 0) || (knownCredit ? total !== chargeTotal + upfront : job.costMsats !== void 0 && total - chargeTotal !== job.costMsats));
27413
+ const receiptMismatch = receipt && job.paymentMethod !== "credit" ? receipt.paid.msats !== total : void 0;
27414
+ const receiptTotalDisplay = receipt ? formatPaymentAmount(receipt.paid.msats, void 0, { anchor: false }) : void 0;
27415
+ let display = job.paymentMethod === "credit" && !knownCredit ? "Paid from prepaid credit; the upfront amount is not recorded locally" + (total > 0 ? `; recorded conversation payments: ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}` : "") : total === 0 && charges.length === 0 ? job.status === "completed" ? "This job was free" : "No charges yet" : `Paid ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}`;
27416
+ if (budgetDisplay) display += `, budget ${budgetDisplay}`;
27417
+ if (refunds.length > 0) display += `, ${refunds.length} refund${refunds.length === 1 ? "" : "s"}`;
27418
+ display += ".";
27419
+ if (logMismatch) display += " Local payment log disagrees with the job record.";
27420
+ if (receipt && job.paymentMethod === "credit" && !knownCredit) display += " The receipt total includes the unrecorded credit draw.";
27421
+ const [receiptLabel, localLabel] = receiptTotalDisplay === totalDisplay ? [`${receipt.paid.msats} msats`, `${total} msats`] : [receiptTotalDisplay, totalDisplay];
27422
+ if (receiptMismatch) display += ` Receipt total ${receiptLabel} differs from local total ${localLabel}; mint fees, returned change, or a payment not recorded locally can explain the difference.`;
27423
+ return {
27424
+ charges,
27425
+ refunds,
27426
+ total_msats: total,
27427
+ total_display: totalDisplay,
27428
+ ...upfront > 0 && (job.paymentMethod !== "credit" || knownCredit) ? {
27429
+ upfront_display: formatPaymentAmount(
27430
+ upfront,
27431
+ knownCredit && job.upfrontPayment?.amount_micro !== void 0 ? { amount: job.upfrontPayment.amount_micro / 1e6, currency: job.upfrontPayment.currency } : void 0,
27432
+ { anchor: false }
27433
+ )
27434
+ } : {},
27435
+ ...budgetDisplay ? { budget_display: budgetDisplay } : {},
27436
+ payments,
27437
+ max_payments: job.policy?.maxPayments ?? null,
27438
+ log_mismatch: logMismatch,
27439
+ ...receipt ? {
27440
+ receipt_total_display: receiptTotalDisplay,
27441
+ ...receiptMismatch !== void 0 ? { receipt_mismatch: receiptMismatch } : {}
27442
+ } : {},
27443
+ display
27444
+ };
27445
+ }
27446
+ function renderSpendHuman(spend, print) {
27447
+ print(spend.display);
27448
+ if (spend.upfront_display) print(` Upfront: ${spend.upfront_display}`);
27449
+ const rails = { cashu_p2pk: "Cashu", tempo: "Tempo", x402: "x402", credit: "prepaid credit", unknown: "payment method not recorded" };
27450
+ const approvals = { auto: "paid automatically", explicit: "you approved", unknown: "approval not recorded" };
27451
+ for (const charge of spend.charges) {
27452
+ print(` [${charge.seq}] ${charge.display} (${rails[charge.rail]}, ${approvals[charge.approval]})${charge.reason.text ? `: ${charge.reason.text}` : ""}`);
27453
+ }
27454
+ for (const refund of spend.refunds) print(` [${refund.seq}] Refund: ${refund.display} (${refund.reason.text})`);
27455
+ if (spend.receipt_total_display) print(` Receipt total: ${spend.receipt_total_display}`);
27456
+ }
27457
+
26637
27458
  // src/commands/status.ts
26638
27459
  async function status(jobId, opts) {
26639
27460
  const access = resolveJobAccess(jobId, opts);
@@ -26744,6 +27565,7 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
26744
27565
  const msgs = fetched?.msgs ?? [];
26745
27566
  const receipt = fetched?.receipt;
26746
27567
  const content = jobContentFields(jobId, fetched?.content);
27568
+ const spend = stored ? jobSpend(loadJob(jobId) ?? stored, receipt?.receipt) : void 0;
26747
27569
  if (opts.human) {
26748
27570
  if (jobStatus === "completed" && completion.summary) {
26749
27571
  info(`Summary:`);
@@ -26754,17 +27576,18 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
26754
27576
  }
26755
27577
  if (jobStatus === "completed" && hint) info(`\u{1F4CE} ${hint}`);
26756
27578
  info(String(content.content_hint));
26757
- if (receipt) renderReceiptHuman(receipt);
26758
27579
  if (msgs.length > 0) {
26759
27580
  info(`
26760
27581
  ${msgs.length} new message(s):`);
26761
- for (const msg of msgs) {
26762
- const prefix = msg.from === "provider" ? "Provider" : "You";
26763
- info(` [${msg.seq}] ${prefix} [${msg.type}]: ${JSON.stringify(msg.content)}`);
26764
- }
27582
+ const artifactSession = createArtifactSaveSession();
27583
+ for (const msg of msgs) formatMessageHuman(msg, jobId, artifactSession);
27584
+ finalizeProgressLine();
26765
27585
  }
26766
27586
  const traceId = getOutputTraceId();
26767
27587
  if (traceId) info(`Trace: ${traceId}`);
27588
+ if (spend) renderSpendHuman(spend, info);
27589
+ if (receipt) renderReceiptHuman(receipt);
27590
+ printNextActionHuman(nextAction);
26768
27591
  return;
26769
27592
  }
26770
27593
  const output = {
@@ -26785,6 +27608,7 @@ ${msgs.length} new message(s):`);
26785
27608
  // do. Both spread blind and are absent when nothing was stashed.
26786
27609
  ...takeCreditNoticeFields(),
26787
27610
  ...takeFeedbackNoticeFields(),
27611
+ ...spend ? { spend } : {},
26788
27612
  next_action: nextAction
26789
27613
  };
26790
27614
  if (opts.messages) {
@@ -26808,16 +27632,16 @@ async function resolveNextAction(jobId, status2, fetched, transport, ref, opts)
26808
27632
  import { statSync as statSync5 } from "fs";
26809
27633
 
26810
27634
  // src/lib/upload-stream.ts
26811
- import { createHash as createHash3 } from "crypto";
26812
- import { createReadStream } from "fs";
27635
+ import { createHash as createHash5 } from "crypto";
27636
+ import { createReadStream as createReadStream2 } from "fs";
26813
27637
  import * as http2 from "http";
26814
27638
  import * as https from "https";
26815
27639
  var UPLOAD_RESPONSE_MAX_BYTES = 64 * 1024;
26816
27640
  function hashFile(filePath) {
26817
27641
  return new Promise((resolve3, reject) => {
26818
- const hasher = createHash3("sha256");
27642
+ const hasher = createHash5("sha256");
26819
27643
  let sizeBytes = 0;
26820
- const stream = createReadStream(filePath);
27644
+ const stream = createReadStream2(filePath);
26821
27645
  stream.on("data", (chunk) => {
26822
27646
  const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
26823
27647
  sizeBytes += buf.byteLength;
@@ -26918,7 +27742,7 @@ function postOnce(opts, idleTimeoutMs) {
26918
27742
  req.destroy(new Error(`socket idle for ${idleTimeoutMs.toString()}ms`));
26919
27743
  });
26920
27744
  req.on("error", reject);
26921
- const body = createReadStream(opts.filePath);
27745
+ const body = createReadStream2(opts.filePath);
26922
27746
  body.on("error", (err) => {
26923
27747
  req.destroy(err);
26924
27748
  reject(err);
@@ -27349,8 +28173,8 @@ function refusePositionalSecret(value, copy) {
27349
28173
  }
27350
28174
  function hasPipedStdin() {
27351
28175
  try {
27352
- const stat = fstatSync(0);
27353
- return stat.isFIFO() || stat.isFile();
28176
+ const stat2 = fstatSync(0);
28177
+ return stat2.isFIFO() || stat2.isFile();
27354
28178
  } catch {
27355
28179
  return false;
27356
28180
  }
@@ -32635,7 +33459,7 @@ function resolveMppEndpoint(identifier) {
32635
33459
  }
32636
33460
 
32637
33461
  // src/commands/wallet-pair.ts
32638
- import { createHash as createHash4, randomBytes as randomBytes5 } from "crypto";
33462
+ import { createHash as createHash6, randomBytes as randomBytes5 } from "crypto";
32639
33463
  import { hostname } from "os";
32640
33464
 
32641
33465
  // node_modules/@noble/ciphers/_arx.js
@@ -33454,7 +34278,7 @@ function hexToBytes2(hex) {
33454
34278
  }
33455
34279
 
33456
34280
  // src/lib/wallet-pairing-store.ts
33457
- var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
34281
+ var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
33458
34282
  import {
33459
34283
  chmodSync as chmodSync2,
33460
34284
  existsSync as existsSync8,
@@ -33555,7 +34379,7 @@ async function withWalletPairingLock(pairingId, fn) {
33555
34379
  if (!existsSync8(path)) return fn();
33556
34380
  let release;
33557
34381
  try {
33558
- release = await import_proper_lockfile.default.lock(path, {
34382
+ release = await import_proper_lockfile3.default.lock(path, {
33559
34383
  lockfilePath: `${path}.lock`,
33560
34384
  realpath: false,
33561
34385
  stale: 12 * 60 * 1e3,
@@ -34007,7 +34831,7 @@ function walletFingerprint(uri) {
34007
34831
  return uri ? sha2562(uri) : null;
34008
34832
  }
34009
34833
  function sha2562(value) {
34010
- return createHash4("sha256").update(value).digest("hex");
34834
+ return createHash6("sha256").update(value).digest("hex");
34011
34835
  }
34012
34836
  function relayHost2(relay) {
34013
34837
  try {
@@ -35303,7 +36127,7 @@ function buildProgram() {
35303
36127
  receiptsShow(jobId, opts);
35304
36128
  }, opts.human);
35305
36129
  });
35306
- receipts.command("verify <job-id>").description("Re-verify a stored receipt offline (signature, attestation, result hash)").option("--endpoint <url>", "Re-fetch the DVM's /v1/info instead of using the stored anchor").option("--human", "Human-readable output instead of JSON").action((jobId, opts) => {
36130
+ receipts.command("verify <job-id>").description("Re-verify a stored receipt offline (signature, attestation, result hash)").option("--file <path>", "Check a downloaded file against signed URL artifact fingerprints (repeatable)", collectOption, []).option("--artifact <name-or-index>", "Select an artifact by exact name or 1-based index for --file").option("--endpoint <url>", "Re-fetch the DVM's /v1/info instead of using the stored anchor").option("--human", "Human-readable output instead of JSON").action((jobId, opts) => {
35307
36131
  return catchErrors(() => receiptsVerify(jobId, opts), opts.human);
35308
36132
  });
35309
36133
  receipts.command("export").description("Write the raw receipt collection to stdout as JSONL").option("--dvm <name>", "Only receipts with this DVM display name").option("--dvm-id <id>", "Only receipts issued by this immutable DVM ID").action((opts) => {
@@ -35389,7 +36213,7 @@ function buildProgram() {
35389
36213
  ).option("--drain-id <id>", "Only the evidence for this drain").option("--export", "Write the raw bundles to stdout as JSONL, un-enveloped").option("--refetch", "Grade against the DVM's live /v1/info instead of the pinned anchor").option("--as <name>", "Caller signing identity whose evidence to read").option("--human", "Human-readable output instead of JSON").action((dvm, opts) => {
35390
36214
  return catchErrors(() => creditReceipts(dvm, opts), opts.human);
35391
36215
  });
35392
- program2.command("messages <job-id>").description("Fetch messages from a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--after <seq>", "Only show messages with seq > N").option("--no-stream", "Non-blocking snapshot instead of streaming until yield").option("--human", "Human-readable output instead of JSON").option("--timeout <sec>", "Override default timeout").action((jobId, opts) => {
36216
+ program2.command("messages <job-id>").description("Fetch messages from a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--after <seq>", "Only show messages with seq > N").option("--no-stream", "Non-blocking snapshot instead of streaming until yield").option("--human", "Human-readable output instead of JSON").option("--wait", "Stay attached until the job needs input or ends").option("--until <duration>", "Wait limit with --wait (default: 12h; e.g. 30s, 5m, 12h)").option("--timeout <sec>", "Read timeout (default: 5s, or 60s with --wait)").action((jobId, opts) => {
35393
36217
  return catchErrors(() => messages(jobId, opts), opts.human);
35394
36218
  });
35395
36219
  program2.command("message <job-id> [text]").description("Send a message in a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option(