@dvmkit/dvm-cli 0.9.2 → 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-5R3BLFVO.js → chunk-6EYBCGGD.js} +2 -2
  3. package/dist/{chunk-BCDMVIPI.js → chunk-7N3HQJKE.js} +4 -4
  4. package/dist/{chunk-C7ZNQONB.js → chunk-BPWZNIMS.js} +2 -2
  5. package/dist/{chunk-PMPHS3LS.js → chunk-GEZVSJDM.js} +3 -3
  6. package/dist/{chunk-GD25CUI4.js → chunk-GHNF2I5C.js} +4 -4
  7. package/dist/{chunk-XDYBVNFS.js → chunk-HWWW7JEM.js} +3 -3
  8. package/dist/{chunk-MVVKMKWR.js → chunk-JJBRTWWS.js} +984 -24
  9. package/dist/{chunk-HUBCGZJL.js → chunk-K562SFVD.js} +2 -2
  10. package/dist/{chunk-6XTWANVN.js → chunk-MBSCP52L.js} +1073 -252
  11. package/dist/{chunk-QDOY3JF2.js → chunk-MMXHV3KC.js} +2 -2
  12. package/dist/{chunk-IEWV3CM2.js → chunk-UVFFMKU4.js} +3 -1
  13. package/dist/{client-MMJYIMKJ.js → client-DS4QJ346.js} +6 -6
  14. package/dist/dvm.js +1379 -1171
  15. package/dist/{internal-LRW4XR3J.js → internal-ZZHCUKOM.js} +15 -5
  16. package/dist/{lifecycle-QE3KHIHQ.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-J3BME4O3.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-HJQYBOZR.js → tempo-lifecycle-LGGBDCKK.js} +8 -8
  21. package/dist/{tempo-wallet-XN72C2GK.js → tempo-wallet-PLFC443A.js} +7 -7
  22. package/dist/{wallet-UEQTGVJE.js → wallet-UJ7EJNQA.js} +7 -7
  23. package/dist/{x402-RUJ4LUKF-ZB7JM22B.js → x402-AY6P5KV4-SIZF7YNW.js} +2 -2
  24. package/package.json +6 -3
  25. package/skills/dvm/calling.md +17 -1
package/dist/dvm.js CHANGED
@@ -5,14 +5,15 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-XDYBVNFS.js";
8
+ } from "./chunk-HWWW7JEM.js";
9
9
  import {
10
10
  assertX402WalletIdle
11
- } from "./chunk-5R3BLFVO.js";
11
+ } from "./chunk-6EYBCGGD.js";
12
12
  import {
13
13
  DEFAULT_CREDIT_POSTURE,
14
14
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
15
15
  NWC_FUNDING_FLOAT_ROLE,
16
+ SUBMISSION_EVIDENCE_DIR,
16
17
  abandonPendingSubmission,
17
18
  abandonSubmissionInWallet,
18
19
  addPayment,
@@ -22,10 +23,13 @@ import {
22
23
  backfillTrustAnchor,
23
24
  bookCreditPayment,
24
25
  buildTempoCredential,
26
+ captureDrawFundingReceipts,
25
27
  captureFundingReceipt,
26
28
  captureTransportReceipt,
29
+ clearPaymentRequestInFlight,
27
30
  commitAgentSpend,
28
31
  correctPendingFundAmount,
32
+ deriveAlias,
29
33
  describeMintBounds,
30
34
  drainReceiptsDisplay,
31
35
  drainReceiptsHint,
@@ -43,12 +47,27 @@ import {
43
47
  fundAgentWallet,
44
48
  fundCredit,
45
49
  fundTimeoutMs,
50
+ hasUnknownUpfrontCredit,
51
+ hasUnknownUpfrontRail,
52
+ identityDataFields,
53
+ identityError,
46
54
  inFlightTimeoutSeconds,
55
+ isIdentityFailure,
56
+ isOpaqueJobToken,
57
+ isParseableBodyJobId,
58
+ jobDrawFundings,
59
+ jobIdentityHeaderValue,
60
+ journalMarkerFor,
61
+ listSubmissionEvidence,
47
62
  loadAllJobs,
63
+ loadFavorites,
48
64
  loadFloat,
49
65
  loadJob,
50
66
  loadLedger,
67
+ loadSubmissionEvidence,
51
68
  markJobTerminal,
69
+ markPaymentRequestInFlight,
70
+ markPaymentRequestPaid,
52
71
  markPendingSubmissionUnresolved,
53
72
  markProofsInFlight,
54
73
  meltInFlightTimeoutSeconds,
@@ -56,6 +75,8 @@ import {
56
75
  needsTopup,
57
76
  parseLocktime,
58
77
  parseStatedBudget,
78
+ parseUpfrontPayment,
79
+ parseUpfrontRailPayment,
59
80
  payViaFloat,
60
81
  pickCreditFundRail,
61
82
  planCreditForQuote,
@@ -72,15 +93,29 @@ import {
72
93
  receiptJsonFields,
73
94
  receiptTrustFields,
74
95
  recordFloatSpend,
96
+ recordIdentityFailure,
97
+ recordLocalJobCollision,
75
98
  recordSpend,
76
99
  recordSpendOnce,
100
+ recordSubmissionEvidence,
101
+ recordUpfrontCreditPayment,
102
+ recordUpfrontRailPayment,
103
+ removeFavorite,
77
104
  renderReceiptHuman,
78
105
  replayStoredReceipt,
79
106
  reservedForMarker,
107
+ resolveEndpoint,
80
108
  resolveFundMint,
109
+ resolveJobAccess,
110
+ resolveStoredJobAccess,
81
111
  revertInFlight,
112
+ routerConflictObservation,
113
+ sameEndpoint,
114
+ saveFavorite,
82
115
  saveJob,
83
116
  saveLedger,
117
+ saveSubmittedJob,
118
+ settleJobIdentity,
84
119
  statusSnapshot,
85
120
  sweepPendingMints,
86
121
  sweepStaleInFlight,
@@ -90,14 +125,18 @@ import {
90
125
  trustOverrideCapMicro,
91
126
  unrecordedFloatBudgetWarning,
92
127
  updateJob,
93
- withAcceptedUnresolved
94
- } from "./chunk-MVVKMKWR.js";
128
+ warnInvalidJobIdentityHeader,
129
+ withAcceptedUnresolved,
130
+ withIdentityRecovery,
131
+ withJobTokenRedaction,
132
+ withRequestResultRecovery
133
+ } from "./chunk-JJBRTWWS.js";
95
134
  import {
96
135
  connectedTempoAccount,
97
136
  generateTempoKey,
98
137
  tempoBalanceCheckHint,
99
138
  tempoWrongAssetHint
100
- } from "./chunk-BCDMVIPI.js";
139
+ } from "./chunk-7N3HQJKE.js";
101
140
  import {
102
141
  assertValidBudget,
103
142
  costAnchor,
@@ -109,14 +148,13 @@ import {
109
148
  json,
110
149
  monetaryJson,
111
150
  parseBudget,
112
- progress,
113
151
  raw,
114
152
  resolveBtcUsdRate,
115
153
  setOutputTraceId,
116
154
  staleRateNotice,
117
155
  tryResolveBtcUsdRate,
118
156
  tryX402Payment
119
- } from "./chunk-C7ZNQONB.js";
157
+ } from "./chunk-BPWZNIMS.js";
120
158
  import {
121
159
  assertSupportedX402Network,
122
160
  connectedX402Payer,
@@ -125,7 +163,7 @@ import {
125
163
  repinX402WalletNetwork,
126
164
  saveX402Wallet,
127
165
  x402NetworkLabel
128
- } from "./chunk-PMPHS3LS.js";
166
+ } from "./chunk-GEZVSJDM.js";
129
167
  import {
130
168
  CREDIT_POSTURES,
131
169
  FEEDBACK_POSTURES,
@@ -142,7 +180,7 @@ import {
142
180
  retireConfigBackup,
143
181
  rollbackConfig,
144
182
  updateConfig
145
- } from "./chunk-QDOY3JF2.js";
183
+ } from "./chunk-MMXHV3KC.js";
146
184
  import {
147
185
  A,
148
186
  AGENT_MNEMONIC_FILE,
@@ -167,7 +205,6 @@ import {
167
205
  IDENTITIES_FILE,
168
206
  IDENTITIES_VERSION,
169
207
  JOBS_FILE,
170
- JOB_IDENTITY_HEADER,
171
208
  MESSAGES_DIR,
172
209
  PAIRINGS_DIR,
173
210
  PRIVKEY_HEX_RE,
@@ -265,11 +302,11 @@ import {
265
302
  isCreditFundRail,
266
303
  isCreditFundingMode,
267
304
  isDrainReceipt,
305
+ isDrawFundingReceipt,
268
306
  isFundingReceipt,
269
307
  isPublicRequestId,
270
308
  isSignedJobReceipt,
271
309
  isStablecoinFundRail,
272
- isStorableJobId,
273
310
  ki,
274
311
  la,
275
312
  listCredits,
@@ -387,7 +424,7 @@ import {
387
424
  x402PendingUnsettled,
388
425
  x402RequiredFromError,
389
426
  x402ReservationRelease
390
- } from "./chunk-6XTWANVN.js";
427
+ } from "./chunk-MBSCP52L.js";
391
428
  import "./chunk-JBU7RKQ3.js";
392
429
  import "./chunk-KDNFUDOG.js";
393
430
  import "./chunk-IUTVV6N5.js";
@@ -428,11 +465,11 @@ import {
428
465
  usdToMsats,
429
466
  usdcToMsats,
430
467
  x402NetworkByCaip2
431
- } from "./chunk-GD25CUI4.js";
432
- import "./chunk-HUBCGZJL.js";
433
- import "./chunk-BHR7QHJG.js";
468
+ } from "./chunk-GHNF2I5C.js";
469
+ import "./chunk-K562SFVD.js";
470
+ import "./chunk-3R2GM6AD.js";
434
471
  import "./chunk-R2DSAZBO.js";
435
- import "./chunk-IEWV3CM2.js";
472
+ import "./chunk-UVFFMKU4.js";
436
473
  import {
437
474
  privateKeyToAccount
438
475
  } from "./chunk-EVQERRCP.js";
@@ -5197,11 +5234,11 @@ var require_dijkstra = __commonJS({
5197
5234
  var predecessors = {};
5198
5235
  var costs = {};
5199
5236
  costs[s] = 0;
5200
- var open = dijkstra.PriorityQueue.make();
5201
- open.push(s, 0);
5237
+ var open2 = dijkstra.PriorityQueue.make();
5238
+ open2.push(s, 0);
5202
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;
5203
- while (!open.empty()) {
5204
- closest = open.pop();
5240
+ while (!open2.empty()) {
5241
+ closest = open2.pop();
5205
5242
  u = closest.value;
5206
5243
  cost_of_s_to_u = closest.cost;
5207
5244
  adjacent_nodes = graph[u] || {};
@@ -5213,7 +5250,7 @@ var require_dijkstra = __commonJS({
5213
5250
  first_visit = typeof costs[v] === "undefined";
5214
5251
  if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
5215
5252
  costs[v] = cost_of_s_to_u_plus_cost_of_e;
5216
- 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);
5217
5254
  predecessors[v] = u;
5218
5255
  }
5219
5256
  }
@@ -8720,6 +8757,138 @@ function maxSeq(msgs, fallback) {
8720
8757
  return Math.max(...msgs.map((m) => m.seq));
8721
8758
  }
8722
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
+
8723
8892
  // src/lib/next-action.ts
8724
8893
  function isTerminalJobStatus(status2) {
8725
8894
  return TERMINAL_STATUSES.has(status2);
@@ -8728,38 +8897,53 @@ function pollNextAction(jobId, hint) {
8728
8897
  return {
8729
8898
  type: "poll",
8730
8899
  job_id: jobId,
8731
- 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\`.`
8732
8901
  };
8733
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
+ }
8734
8906
  var YIELD_TYPES = /* @__PURE__ */ new Set(["prompt", "payment-request", "working", "complete", "cancel"]);
8735
8907
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
8736
8908
  "completed",
8737
8909
  "failed",
8738
8910
  "cancelled"
8739
8911
  ]);
8740
- function computeNextAction(jobId, messages2) {
8912
+ function computeNextAction(jobId, messages2, nowMs = Date.now()) {
8913
+ const answered = answeredYieldSeqs(messages2);
8914
+ const expiresAtMs = pendingDeadline(messages2, answered);
8741
8915
  for (let i = messages2.length - 1; i >= 0; i--) {
8742
8916
  const msg = messages2[i];
8743
- if (!YIELD_TYPES.has(msg.type)) continue;
8917
+ if (!YIELD_TYPES.has(msg.type) || answered.has(msg.seq)) continue;
8744
8918
  switch (msg.type) {
8745
8919
  case "complete":
8746
8920
  case "cancel":
8747
8921
  return null;
8748
8922
  case "prompt": {
8749
8923
  const c = msg.content;
8924
+ const answer = c.schema ? "--json '<object matching schema>'" : '"<answer>"';
8925
+ const choices = c.options?.length ? ` Choices: ${c.options.map((option) => JSON.stringify(option)).join(", ")}.` : "";
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;
8750
8929
  const action = {
8751
8930
  type: "respond",
8752
8931
  job_id: jobId,
8753
8932
  prompt_id: c.id,
8754
8933
  prompt: asProviderText(c.text),
8755
- hint: "Provider is waiting for your input. Verify the question makes sense for your task before responding."
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)
8756
8936
  };
8757
8937
  if (c.schema) action.schema = c.schema;
8938
+ if (c.options?.length) action.options = c.options;
8939
+ if (expiresAtMs !== void 0) action.expires_at_ms = expiresAtMs;
8758
8940
  return action;
8759
8941
  }
8760
8942
  case "payment-request": {
8761
8943
  const c = msg.content;
8762
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;
8763
8947
  return {
8764
8948
  type: "pay",
8765
8949
  job_id: jobId,
@@ -8767,9 +8951,10 @@ function computeNextAction(jobId, messages2) {
8767
8951
  // Mirror only a fiat figure the display actually led with: echoing a
8768
8952
  // zero amount would tell an agent doing budget math the charge is free.
8769
8953
  ...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount } : {},
8770
- display,
8954
+ ...expiresAtMs !== void 0 ? { expires_at_ms: expiresAtMs } : {},
8955
+ display: withDeadline(display, deadline),
8771
8956
  reason: asProviderText(c.reason),
8772
- hint: `Payment required to continue: ${display}. Relay that amount to your human and get approval, then run 'dvm pay ${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)
8773
8958
  };
8774
8959
  }
8775
8960
  case "working": {
@@ -8778,13 +8963,49 @@ function computeNextAction(jobId, messages2) {
8778
8963
  type: "poll",
8779
8964
  job_id: jobId,
8780
8965
  estimate_seconds: c.estimate_seconds,
8781
- 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
8782
8967
  };
8783
8968
  }
8784
8969
  }
8785
8970
  }
8786
8971
  return null;
8787
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
+ }
8788
9009
 
8789
9010
  // src/lib/rail-labels.ts
8790
9011
  var PAYMENT_RAIL_KEYS = ["cashu", "cashu_p2pk", "x402", "tempo"];
@@ -8834,736 +9055,23 @@ function formatPaidAmount(result, fiat) {
8834
9055
  return formatPaymentAmount(result.amountMsats, fiat, { anchor: false });
8835
9056
  }
8836
9057
 
8837
- // src/lib/favorites.ts
8838
- var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
8839
- import {
8840
- closeSync as closeSync2,
8841
- fchmodSync,
8842
- fsyncSync,
8843
- openSync as openSync2,
8844
- readFileSync as readFileSync2,
8845
- renameSync,
8846
- statSync as statSync2,
8847
- unlinkSync,
8848
- writeFileSync
8849
- } from "fs";
8850
- import { dirname } from "path";
8851
- var DEFAULT_FILE_MODE = 384;
8852
- function loadFavorites() {
8853
- let raw2;
8854
- try {
8855
- raw2 = readFileSync2(FAVORITES_FILE, "utf8");
8856
- } catch (error) {
8857
- if (nodeErrorCode(error) === "ENOENT") return {};
8858
- throw unreadableFavorites(error);
8859
- }
8860
- try {
8861
- const parsed = JSON.parse(raw2);
8862
- if (!isFavoritesMap(parsed)) throw new Error("invalid favorites shape");
8863
- return parsed;
8864
- } catch (error) {
8865
- throw unreadableFavorites(error);
8866
- }
8867
- }
8868
- async function saveFavorite(alias, fav) {
8869
- return withFavoritesLock(() => {
8870
- const favs = loadFavorites();
8871
- const existed = Object.hasOwn(favs, alias);
8872
- favs[alias] = fav;
8873
- writeFavorites(favs);
8874
- return existed;
8875
- });
8876
- }
8877
- async function removeFavorite(alias) {
8878
- return withFavoritesLock(() => {
8879
- const favs = loadFavorites();
8880
- if (!Object.hasOwn(favs, alias)) return false;
8881
- const { [alias]: _, ...rest } = favs;
8882
- writeFavorites(rest);
8883
- return true;
8884
- });
8885
- }
8886
- function resolveEndpoint(input) {
8887
- if (!input.startsWith("@")) return input;
8888
- const alias = input.slice(1);
8889
- const favs = loadFavorites();
8890
- const fav = Object.hasOwn(favs, alias) ? favs[alias] : void 0;
8891
- if (!fav) {
8892
- throw new DvmError(
8893
- "unknown_favorite",
8894
- `No favorite named "${alias}".`,
8895
- "Run 'dvm fav list' to see saved favorites, or 'dvm fav add <endpoint>' to save one."
8896
- );
8897
- }
8898
- return fav.endpoint;
8899
- }
8900
- function deriveAlias(endpoint) {
8901
- try {
8902
- const hostname2 = new URL(endpoint).hostname;
8903
- if (hostname2.endsWith(".dvmkit.ai")) {
8904
- const prefix = hostname2.replace(".dvmkit.ai", "");
8905
- const dashIdx = prefix.indexOf("--");
8906
- if (dashIdx !== -1) return prefix.slice(dashIdx + 2);
8907
- return prefix;
8908
- }
8909
- return hostname2.replace(/\.[^.]+$/, "").replace(/\./g, "-");
8910
- } catch {
8911
- return endpoint.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
8912
- }
8913
- }
8914
- async function withFavoritesLock(fn) {
8915
- ensureConfigDir();
8916
- let release;
8917
- try {
8918
- release = await import_proper_lockfile.default.lock(FAVORITES_FILE, {
8919
- lockfilePath: `${FAVORITES_FILE}.lock`,
8920
- realpath: false,
8921
- stale: 3e4,
8922
- retries: { retries: 10, factor: 1, minTimeout: 100, maxTimeout: 100 }
8923
- });
8924
- } catch {
8925
- throw new DvmError(
8926
- "favorites_locked",
8927
- "Another dvm process is updating saved favorites.",
8928
- "Wait a moment and retry."
8929
- );
8930
- }
8931
- try {
8932
- return await fn();
8933
- } finally {
8934
- await release().catch(() => void 0);
8935
- }
8936
- }
8937
- function writeFavorites(favorites) {
8938
- const mode = favoritesFileMode();
8939
- const temporary = `${FAVORITES_FILE}.${String(process.pid)}.${randomSuffix()}.tmp`;
8940
- const contents = JSON.stringify(favorites, null, 2) + "\n";
8941
- let fd;
8942
- try {
8943
- fd = openSync2(temporary, "wx", mode);
8944
- fchmodSync(fd, mode);
8945
- writeFileSync(fd, contents);
8946
- fsyncSync(fd);
8947
- closeSync2(fd);
8948
- fd = void 0;
8949
- renameSync(temporary, FAVORITES_FILE);
8950
- fsyncDirectory(dirname(FAVORITES_FILE));
8951
- } catch (error) {
8952
- if (fd !== void 0) {
8953
- try {
8954
- closeSync2(fd);
8955
- } catch {
8956
- }
8957
- }
8958
- try {
8959
- unlinkSync(temporary);
8960
- } catch {
8961
- }
8962
- throw error;
8963
- }
8964
- }
8965
- function favoritesFileMode() {
8966
- try {
8967
- return statSync2(FAVORITES_FILE).mode & 511;
8968
- } catch (error) {
8969
- if (nodeErrorCode(error) === "ENOENT") return DEFAULT_FILE_MODE;
8970
- throw error;
8971
- }
8972
- }
8973
- function fsyncDirectory(path) {
8974
- const fd = openSync2(path, "r");
8975
- try {
8976
- fsyncSync(fd);
8977
- } finally {
8978
- closeSync2(fd);
8979
- }
8980
- }
8981
- function randomSuffix() {
8982
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
8983
- }
8984
- function unreadableFavorites(error) {
8985
- return new DvmError(
8986
- "favorites_unreadable",
8987
- "Saved favorites are corrupt or unreadable.",
8988
- `The original file at ${FAVORITES_FILE} was left unchanged. Restore it from a backup, or move it aside before rebuilding favorites.`,
8989
- {
8990
- path: FAVORITES_FILE,
8991
- ...nodeErrorCode(error) ? { error_code: nodeErrorCode(error) } : {}
8992
- }
8993
- );
8994
- }
8995
- function nodeErrorCode(error) {
8996
- if (!(error instanceof Error) || !("code" in error)) return void 0;
8997
- const code = error.code;
8998
- return typeof code === "string" && /^E[A-Z0-9_]{1,63}$/.test(code) ? code : void 0;
8999
- }
9000
- function isFavoritesMap(value) {
9001
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
9002
- return Object.values(value).every(isFavorite);
9003
- }
9004
- function isFavorite(value) {
9005
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
9006
- const candidate = value;
9007
- return typeof candidate.endpoint === "string" && typeof candidate.addedAt === "number" && Number.isFinite(candidate.addedAt) && (candidate.name === void 0 || typeof candidate.name === "string");
9008
- }
9009
-
9010
- // src/lib/submission-evidence.ts
9011
- import { createHash, randomUUID } from "crypto";
9012
- import {
9013
- closeSync as closeSync3,
9014
- existsSync as existsSync2,
9015
- fsyncSync as fsyncSync2,
9016
- linkSync,
9017
- openSync as openSync3,
9018
- readdirSync,
9019
- readFileSync as readFileSync3,
9020
- unlinkSync as unlinkSync2,
9021
- writeFileSync as writeFileSync2
9022
- } from "fs";
9023
- import { join as join2 } from "path";
9024
-
9025
- // src/lib/job-identity.ts
9026
- var IDENTITY_FAILURE_CODES = {
9027
- identity_mismatch: "provider_identity_mismatch",
9028
- body_unreadable: "provider_body_unreadable",
9029
- router_identity_conflict: "hosting_job_identity_conflict"
9030
- };
9031
- var ProviderIdentityError = class extends DvmError {
9032
- observation;
9033
- constructor(observation, message2, hint, data, proseSources) {
9034
- super(IDENTITY_FAILURE_CODES[observation.kind], message2, hint, data, void 0, proseSources);
9035
- this.observation = observation;
9036
- }
9037
- };
9038
- function isIdentityFailure(err) {
9039
- return err instanceof ProviderIdentityError;
9040
- }
9041
- function isParseableBodyJobId(value) {
9042
- return typeof value === "string" && value.trim().length > 0 && value.length <= 512 && !hasAsciiControl(value);
9043
- }
9044
- function isOpaqueJobToken(value) {
9045
- return typeof value === "string" && value.length > 0 && value.length <= 4096 && value.trim() === value && !hasAsciiControl(value);
9046
- }
9047
- function observedJobId(value) {
9048
- return isStorableJobId(value) ? value : void 0;
9049
- }
9050
- function observeJobId(value) {
9051
- if (value === void 0) return {};
9052
- if (isStorableJobId(value)) return { stored: value };
9053
- return { escaped: escapeObservedValue(value) };
9054
- }
9055
- var ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT = 1024;
9056
- function escapeObservedValue(value) {
9057
- const source = typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
9058
- const truncated = source.length > ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT;
9059
- const quoted = JSON.stringify(
9060
- truncated ? source.slice(0, ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT) : source
9061
- ).replace(
9062
- /[\u007f-\u009f]/gu,
9063
- (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
9064
- );
9065
- return truncated ? `${quoted} [truncated from ${String(source.length)} characters]` : quoted;
9066
- }
9067
- function settleJobIdentity(headerValue, body) {
9068
- const header = parseJobIdentityHeader(headerValue);
9069
- const headerJobId = header.kind === "valid" ? header.jobId : void 0;
9070
- const rawBodyJobId = body?.job_id;
9071
- const jobToken = isOpaqueJobToken(body?.job_token) ? body.job_token : void 0;
9072
- const observed = (kind) => {
9073
- const bodyJob = observeJobId(rawBodyJobId);
9074
- return {
9075
- kind: "unresolved",
9076
- observation: {
9077
- kind,
9078
- ...headerJobId ? { headerJobId } : {},
9079
- ...optionalField("bodyJobId", bodyJob.stored),
9080
- ...bodyJob.escaped ? { unstorable: { body_job_id: bodyJob.escaped } } : {},
9081
- ...jobToken ? { jobToken } : {}
9082
- }
9083
- };
9084
- };
9085
- if (!isParseableBodyJobId(rawBodyJobId)) return observed("body_unreadable");
9086
- if (headerJobId !== void 0 && headerJobId !== rawBodyJobId) {
9087
- return observed("identity_mismatch");
9088
- }
9089
- return {
9090
- kind: "settled",
9091
- jobId: rawBodyJobId,
9092
- claimAllowed: header.kind !== "invalid",
9093
- headerInvalid: header.kind === "invalid"
9094
- };
9095
- }
9096
- function routerConflictObservation(status2, body) {
9097
- if (status2 !== 409 || !body) return void 0;
9098
- const error = body.error;
9099
- if (!error || typeof error !== "object" || Array.isArray(error)) return void 0;
9100
- const envelope = error;
9101
- if (envelope.code !== IDENTITY_FAILURE_CODES.router_identity_conflict) return void 0;
9102
- const accepted = observeJobId(envelope.accepted_job_id);
9103
- return {
9104
- kind: "router_identity_conflict",
9105
- ...optionalField("acceptedJobId", accepted.stored),
9106
- ...accepted.escaped ? { unstorable: { accepted_job_id: accepted.escaped } } : {}
9107
- };
9108
- }
9109
- function jobIdentityHeaderValue(headers) {
9110
- return headers.get(JOB_IDENTITY_HEADER);
9111
- }
9112
- function identityError(observation, providerProse) {
9113
- const { message: message2, display } = describeIdentityFailure(observation);
9114
- return new ProviderIdentityError(
9115
- observation,
9116
- message2,
9117
- "Do not pay for this request again. Run 'dvm wallet submissions' to see what was recorded.",
9118
- {
9119
- identity_kind: observation.kind,
9120
- ...identityDataFields(observation),
9121
- display: providerProse?.display ?? display
9122
- },
9123
- providerProse?.proseSources
9124
- );
9125
- }
9126
- function withIdentityRecovery(err, ctx) {
9127
- const hint = ctx.publicRequestId ? `Run 'dvm request-result ${ctx.publicRequestId}' to read the accepted job. Do not pay for this request again; 'dvm wallet submissions' shows the recorded evidence (${ctx.ambiguityId}).` : `Run 'dvm wallet submissions' to see the recorded evidence (${ctx.ambiguityId}) and how to read each job it names. Do not pay for this request again.`;
9128
- return new ProviderIdentityError(
9129
- err.observation,
9130
- err.message,
9131
- hint,
9132
- {
9133
- ...err.data,
9134
- ambiguity_id: ctx.ambiguityId,
9135
- ...ctx.publicRequestId ? { request_id: ctx.publicRequestId } : {},
9136
- ...ctx.cashuRequestId ? { cashu_request_id: ctx.cashuRequestId } : {},
9137
- claim_stored: false
9138
- },
9139
- err.proseSources
9140
- );
9141
- }
9142
- function withRequestResultRecovery(err, ctx) {
9143
- const jobId = err.observation.acceptedJobId;
9144
- const read = `dvm status ${jobId ? shellQuoteArg(jobId) : "<accepted_job_id>"} --endpoint ${shellQuoteArg(ctx.endpoint)} --job-token <job_token_bearer_secret>`;
9145
- const hint = `Do not pay again. Running request-result again meets the same refusal while the provider keeps answering with a different job. Read ${jobId ? `job ${jobId}` : "the accepted job"} directly with '${read}', taking the job token from a row for request ${ctx.requestId} in 'dvm wallet submissions' (this refusal is recorded as ${ctx.ambiguityId}). If no row for it holds a job token, this caller never received one for that job.`;
9146
- return new ProviderIdentityError(
9147
- err.observation,
9148
- err.message,
9149
- hint,
9150
- { ...err.data, ambiguity_id: ctx.ambiguityId, request_id: ctx.requestId, claim_stored: false },
9151
- err.proseSources
9152
- );
9153
- }
9154
- function identityDataFields(observation) {
9155
- return {
9156
- ...optionalField("header_job_id", observation.headerJobId),
9157
- ...optionalField("body_job_id", observation.bodyJobId),
9158
- ...optionalField("body_job_id_escaped", observation.unstorable?.body_job_id),
9159
- ...optionalField("accepted_job_id", observation.acceptedJobId),
9160
- ...optionalField("accepted_job_id_escaped", observation.unstorable?.accepted_job_id)
9161
- };
9162
- }
9163
- function warnInvalidJobIdentityHeader() {
9164
- const display = "The provider sent a malformed job identity header, so it was ignored and the job ID was taken from the response body.";
9165
- if (process.stderr.isTTY === true) {
9166
- info(`Warning: ${display}`);
9167
- return;
9168
- }
9169
- progress({ event: "warning", code: "job_identity_header_invalid", display });
9170
- }
9171
- function describeIdentityFailure(observation) {
9172
- switch (observation.kind) {
9173
- case "identity_mismatch":
9174
- return {
9175
- message: `The provider accepted the request but named job ${observation.headerJobId ?? "(unknown)"} in its response header and job ${observation.bodyJobId ?? "(unrepresentable)"} in its body.`,
9176
- display: "The provider took this request but gave two different job IDs for it, so it is unclear which job is yours. Do not pay for it again."
9177
- };
9178
- case "body_unreadable":
9179
- return {
9180
- message: observation.headerJobId ? `The provider accepted the request as job ${observation.headerJobId}, but its response body could not be read.` : "The provider accepted the request, but its response did not state a readable job ID.",
9181
- display: "The provider took this request but its reply could not be read, so it is unclear which job is yours. Do not pay for it again."
9182
- };
9183
- case "router_identity_conflict":
9184
- return {
9185
- message: `The router had already accepted job ${observation.acceptedJobId ?? "(unknown)"} for this request, and the provider answered with a different job.`,
9186
- display: "This request was already accepted as a different job. Do not pay for it again."
9187
- };
9188
- }
9189
- }
9190
- function hasAsciiControl(value) {
9191
- for (const character of value) {
9192
- const code = character.charCodeAt(0);
9193
- if (code <= 31 || code === 127) return true;
9194
- }
9195
- return false;
9196
- }
9197
- function optionalField(key, value) {
9198
- return value === void 0 ? {} : { [key]: value };
9199
- }
9200
-
9201
- // src/lib/submission-evidence.ts
9202
- var SUBMISSION_EVIDENCE_DIR = join2(CONFIG_DIR, "submission-evidence");
9203
- function submissionEvidenceKey(args) {
9204
- return args.cashuRequestId ?? args.publicRequestId ?? randomUUID();
9205
- }
9206
- function recordSubmissionEvidence(input) {
9207
- const ambiguityId = submissionEvidenceKey(input);
9208
- const existing = loadSubmissionEvidence(ambiguityId);
9209
- if (existing) return existing;
9210
- const { observation } = input;
9211
- const jobToken = isOpaqueJobToken(observation.jobToken) ? observation.jobToken : void 0;
9212
- const record = {
9213
- v: 1,
9214
- ambiguity_id: ambiguityId,
9215
- kind: observation.kind,
9216
- observed_at: new Date((input.now ?? Date.now)()).toISOString(),
9217
- endpoint: input.endpoint,
9218
- ...input.dvmId ? { dvm_id: input.dvmId } : {},
9219
- ...input.capability ? { capability: input.capability } : {},
9220
- ...input.publicRequestId ? { request_id: input.publicRequestId } : {},
9221
- ...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
9222
- rail: input.rail,
9223
- ...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
9224
- ...jobToken ? { job_token: jobToken } : {},
9225
- ...boundedIds(observation),
9226
- ...observation.unstorable && Object.keys(observation.unstorable).length > 0 ? { unstorable_job_ids: observation.unstorable } : {},
9227
- claim_stored: false
9228
- };
9229
- return publishOnce(record);
9230
- }
9231
- function recordLocalJobCollision(input) {
9232
- const ambiguityId = `${input.publicRequestId}#local-job-collision`;
9233
- const existing = loadSubmissionEvidence(ambiguityId);
9234
- if (existing) return existing;
9235
- const jobToken = isOpaqueJobToken(input.jobToken) ? input.jobToken : void 0;
9236
- return publishOnce({
9237
- v: 1,
9238
- ambiguity_id: ambiguityId,
9239
- kind: "local_job_collision",
9240
- observed_at: new Date((input.now ?? Date.now)()).toISOString(),
9241
- endpoint: input.endpoint,
9242
- ...input.dvmId ? { dvm_id: input.dvmId } : {},
9243
- ...input.capability ? { capability: input.capability } : {},
9244
- request_id: input.publicRequestId,
9245
- ...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
9246
- rail: input.rail,
9247
- ...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
9248
- ...jobToken ? { job_token: jobToken } : {},
9249
- ...boundedIds({ acceptedJobId: input.jobId }),
9250
- claim_stored: false
9251
- });
9252
- }
9253
- function recordIdentityFailure(err, input) {
9254
- if (identityFailureRecorded(err)) return { error: err, record: null };
9255
- const record = recordSubmissionEvidence({ ...input, observation: err.observation });
9256
- return {
9257
- error: withIdentityRecovery(err, {
9258
- ambiguityId: record.ambiguity_id,
9259
- ...input.publicRequestId ? { publicRequestId: input.publicRequestId } : {},
9260
- ...input.cashuRequestId ? { cashuRequestId: input.cashuRequestId } : {}
9261
- }),
9262
- record
9263
- };
9264
- }
9265
- function identityFailureRecorded(err) {
9266
- return typeof err.data?.ambiguity_id === "string";
9267
- }
9268
- function loadSubmissionEvidence(ambiguityId) {
9269
- const path = evidencePath(ambiguityId);
9270
- if (!existsSync2(path)) return null;
9271
- const record = readRecord(path);
9272
- if (record.ambiguity_id !== ambiguityId) throw unreadable(path, "key mismatch");
9273
- return record;
9274
- }
9275
- function listSubmissionEvidence() {
9276
- if (!existsSync2(SUBMISSION_EVIDENCE_DIR)) return { records: [], unreadable: [] };
9277
- const records = [];
9278
- const unreadable2 = [];
9279
- for (const name of readdirSync(SUBMISSION_EVIDENCE_DIR).filter((n) => n.endsWith(".json"))) {
9280
- const path = join2(SUBMISSION_EVIDENCE_DIR, name);
9281
- try {
9282
- records.push(readRecord(path));
9283
- } catch (error) {
9284
- const cause = error instanceof DvmError ? error.data?.cause : void 0;
9285
- unreadable2.push({ path, cause: typeof cause === "string" ? cause : "unreadable" });
9286
- }
9287
- }
9288
- records.sort((a, b) => a.observed_at.localeCompare(b.observed_at));
9289
- return { records, unreadable: unreadable2 };
9290
- }
9291
- function journalMarkerFor(record) {
9292
- const kind = record.kind;
9293
- if (kind === "local_job_collision") {
9294
- throw unreadable(evidencePath(record.ambiguity_id), "not an identity failure");
9295
- }
9296
- return {
9297
- kind,
9298
- observed_at: record.observed_at,
9299
- ...boundedMarkerIds(record),
9300
- ambiguity_id: record.ambiguity_id
9301
- };
9302
- }
9303
- function publishOnce(record) {
9304
- const ambiguityId = record.ambiguity_id;
9305
- ensureConfigSubdir(SUBMISSION_EVIDENCE_DIR);
9306
- const target = evidencePath(ambiguityId);
9307
- const temp = `${target}.${String(process.pid)}.${randomUUID()}.tmp`;
9308
- const fd = openSync3(temp, "wx", 384);
9309
- try {
9310
- writeFileSync2(fd, JSON.stringify(record, null, 2) + "\n");
9311
- fsyncSync2(fd);
9312
- } finally {
9313
- closeSync3(fd);
9314
- }
9315
- try {
9316
- linkSync(temp, target);
9317
- } catch (error) {
9318
- if (error.code !== "EEXIST") throw error;
9319
- } finally {
9320
- unlinkSync2(temp);
9321
- }
9322
- fsyncDirectory2(SUBMISSION_EVIDENCE_DIR);
9323
- return loadSubmissionEvidence(ambiguityId) ?? record;
9324
- }
9325
- function boundedIds(observation) {
9326
- const header = observedJobId(observation.headerJobId);
9327
- const body = observedJobId(observation.bodyJobId);
9328
- const accepted = observedJobId(observation.acceptedJobId);
9329
- return {
9330
- ...header !== void 0 ? { header_job_id: header } : {},
9331
- ...body !== void 0 ? { body_job_id: body } : {},
9332
- ...accepted !== void 0 ? { accepted_job_id: accepted } : {}
9333
- };
9334
- }
9335
- function boundedMarkerIds(record) {
9336
- return boundedIds({
9337
- headerJobId: record.header_job_id,
9338
- bodyJobId: record.body_job_id,
9339
- acceptedJobId: record.accepted_job_id
9340
- });
9341
- }
9342
- function evidencePath(ambiguityId) {
9343
- const name = createHash("sha256").update(ambiguityId).digest("hex");
9344
- return join2(SUBMISSION_EVIDENCE_DIR, `${name}.json`);
9345
- }
9346
- function readRecord(path) {
9347
- let parsed;
9348
- try {
9349
- parsed = JSON.parse(readFileSync3(path, "utf8"));
9350
- } catch (error) {
9351
- throw unreadable(path, error instanceof Error ? error.message : String(error));
9352
- }
9353
- if (!isEvidenceRecord(parsed)) throw unreadable(path, "invalid shape");
9354
- return parsed;
9355
- }
9356
- function unreadable(path, cause) {
9357
- return new DvmError(
9358
- "submission_evidence_unreadable",
9359
- `A submission evidence record at ${path} is unreadable.`,
9360
- "Restore it from a backup. Do not pay again for any request it may describe; automatic retries stay off until it reads.",
9361
- { cause }
9362
- );
9363
- }
9364
- var KINDS = /* @__PURE__ */ new Set([
9365
- "identity_mismatch",
9366
- "body_unreadable",
9367
- "router_identity_conflict",
9368
- "local_job_collision"
9369
- ]);
9370
- var RAILS = /* @__PURE__ */ new Set(["cashu", "x402", "tempo", "credit", "none"]);
9371
- function isEvidenceRecord(value) {
9372
- if (!isPlainObject(value)) return false;
9373
- const record = value;
9374
- const optionalString = (key) => record[key] === void 0 || typeof record[key] === "string";
9375
- return record.v === 1 && typeof record.ambiguity_id === "string" && KINDS.has(record.kind) && typeof record.observed_at === "string" && typeof record.endpoint === "string" && RAILS.has(record.rail) && record.claim_stored === false && isOptionalStringRecord(record.unstorable_job_ids) && (record.rail_correlation === void 0 || isPlainObject(record.rail_correlation)) && [
9376
- "dvm_id",
9377
- "capability",
9378
- "request_id",
9379
- "cashu_request_id",
9380
- "job_token",
9381
- "header_job_id",
9382
- "body_job_id",
9383
- "accepted_job_id"
9384
- ].every(optionalString);
9385
- }
9386
- function isPlainObject(value) {
9387
- return typeof value === "object" && value !== null && !Array.isArray(value);
9388
- }
9389
- function isOptionalStringRecord(value) {
9390
- return value === void 0 || isPlainObject(value) && Object.values(value).every((entry) => typeof entry === "string");
9391
- }
9392
- function fsyncDirectory2(path) {
9393
- let fd;
9394
- try {
9395
- fd = openSync3(path, "r");
9396
- fsyncSync2(fd);
9397
- } finally {
9398
- if (fd !== void 0) closeSync3(fd);
9399
- }
9400
- }
9401
-
9402
- // src/lib/job-access.ts
9403
- function resolveJobAccess(jobId, opts) {
9404
- const stored = loadJob(jobId);
9405
- return resolveJobAccessWithRecord(jobId, opts, stored);
9406
- }
9407
- function resolveJobAccessWithRecord(jobId, opts, record) {
9408
- const endpointOverride = opts.endpoint ?? process.env.DVM_JOB_ENDPOINT;
9409
- const tokenOverride = opts.jobToken ?? process.env.DVM_JOB_TOKEN;
9410
- const endpointOverridden = endpointOverride !== void 0;
9411
- const tokenOverridden = tokenOverride !== void 0;
9412
- const foreign = record !== null && endpointOverride !== void 0 && !sameEndpoint(resolveEndpoint(endpointOverride), record.endpoint);
9413
- const stored = foreign ? null : record;
9414
- const rawEndpoint = endpointOverride ?? stored?.endpoint;
9415
- const jobToken = tokenOverride ?? stored?.jobToken;
9416
- if (!stored && rawEndpoint === void 0 && jobToken === void 0) {
9417
- throw new DvmError(
9418
- "job_access_required",
9419
- `Job ${jobId} is not in the local store, and no portable job access was supplied.`,
9420
- "Pass --endpoint <url> and --job-token <hex>, or set DVM_JOB_ENDPOINT and DVM_JOB_TOKEN."
9421
- );
9422
- }
9423
- if (rawEndpoint === void 0) {
9424
- throw new DvmError(
9425
- "job_endpoint_required",
9426
- `No provider endpoint is available for job ${jobId}.`,
9427
- "Pass --endpoint <url> or set DVM_JOB_ENDPOINT."
9428
- );
9429
- }
9430
- if (foreign && jobToken === void 0) {
9431
- throw foreignJobTokenRequired(jobId, record.endpoint, resolveEndpoint(endpointOverride));
9432
- }
9433
- if (!stored && jobToken === void 0) {
9434
- throw new DvmError(
9435
- "job_token_required",
9436
- `No job token is available for job ${jobId}.`,
9437
- "Pass --job-token <hex> or set DVM_JOB_TOKEN."
9438
- );
9439
- }
9440
- if (tokenOverridden && !isJobToken(jobToken)) {
9441
- throw new DvmError(
9442
- "invalid_job_token",
9443
- "The supplied job token is not a 64-character hexadecimal value.",
9444
- "Copy the job_token returned when the job was submitted; the value is never printed by this command."
9445
- );
9446
- }
9447
- return {
9448
- stored,
9449
- ref: { endpoint: validateProviderEndpoint(resolveEndpoint(rawEndpoint)) },
9450
- ...jobToken !== void 0 ? { jobToken } : {},
9451
- overridden: endpointOverridden || tokenOverridden,
9452
- endpointOverridden
9453
- };
9454
- }
9455
- function resolveStoredJobAccess(jobId, opts) {
9456
- const stored = loadJob(jobId);
9457
- if (!stored) {
9458
- throw new DvmError(
9459
- "job_payment_state_required",
9460
- `Cannot pay job ${jobId} without its local payment state.`,
9461
- "Run 'dvm pay' where the job record and message history are available (normally the submitting machine). An endpoint and job token cannot reconstruct its pending request and spending policy."
9462
- );
9463
- }
9464
- return { ...resolveJobAccessWithRecord(jobId, opts, stored), stored };
9465
- }
9466
- async function withJobTokenRedaction(jobToken, action) {
9467
- try {
9468
- return await action();
9469
- } catch (err) {
9470
- throw redactJobTokenFromError(err, jobToken);
9471
- }
9472
- }
9473
- function redactJobTokenFromError(err, jobToken) {
9474
- if (!jobToken || !(err instanceof DvmError)) return err;
9475
- const redact = (value) => value.replaceAll(jobToken, "[REDACTED]");
9476
- return new DvmError(
9477
- err.code,
9478
- redact(err.message),
9479
- err.hint === void 0 ? void 0 : redact(err.hint),
9480
- err.data === void 0 ? void 0 : redactRecord(err.data, redact),
9481
- err.display === void 0 ? void 0 : redact(err.display),
9482
- err.proseSources
9483
- );
9484
- }
9485
- function sameEndpoint(a, b) {
9486
- const normalize = (value) => {
9487
- try {
9488
- const url = new URL(value);
9489
- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
9490
- } catch {
9491
- return value.replace(/\/+$/, "");
9492
- }
9493
- };
9494
- return normalize(a) === normalize(b);
9495
- }
9496
- function foreignJobTokenRequired(jobId, localEndpoint, endpoint) {
9497
- const row = evidenceRowWithToken(jobId, endpoint);
9498
- return new DvmError(
9499
- "job_token_required",
9500
- `Local job ${jobId} belongs to ${localEndpoint}. Its job token was issued there and is not sent to ${endpoint}.`,
9501
- row ? `The job token for ${jobId} at ${endpoint} is job_token_bearer_secret on evidence row ${row} in 'dvm wallet submissions'. Pass it with --job-token or DVM_JOB_TOKEN.` : `Pass the job token ${endpoint} issued for ${jobId} with --job-token or DVM_JOB_TOKEN. No evidence row in 'dvm wallet submissions' holds one for it.`,
9502
- {
9503
- job_id: jobId,
9504
- local_endpoint: localEndpoint,
9505
- endpoint,
9506
- ...row ? { ambiguity_id: row } : {}
9507
- }
9508
- );
9509
- }
9510
- function evidenceRowWithToken(jobId, endpoint) {
9511
- let records;
9512
- try {
9513
- ({ records } = listSubmissionEvidence());
9514
- } catch {
9515
- return void 0;
9516
- }
9517
- return records.filter(
9518
- (record) => record.job_token !== void 0 && sameEndpoint(record.endpoint, endpoint) && [record.header_job_id, record.body_job_id, record.accepted_job_id].includes(jobId)
9519
- ).at(-1)?.ambiguity_id;
9520
- }
9521
- function isJobToken(value) {
9522
- return value !== void 0 && /^[0-9a-fA-F]{64}$/.test(value);
9523
- }
9524
- function validateProviderEndpoint(value) {
9525
- try {
9526
- const url = new URL(value);
9527
- if ((url.protocol === "http:" || url.protocol === "https:") && url.hostname) return value;
9528
- } catch {
9529
- }
9530
- throw new DvmError(
9531
- "invalid_endpoint",
9532
- "The supplied job endpoint is not a valid HTTP(S) provider URL.",
9533
- "Pass a full URL such as https://provider.example, or a favorite alias such as @provider."
9534
- );
9535
- }
9536
- function redactRecord(record, redact) {
9537
- return Object.fromEntries(
9538
- Object.entries(record).map(([key, value]) => [key, redactValue(value, redact)])
9539
- );
9540
- }
9541
- function redactValue(value, redact) {
9542
- if (typeof value === "string") return redact(value);
9543
- if (Array.isArray(value)) return value.map((entry) => redactValue(entry, redact));
9544
- if (value && typeof value === "object") {
9545
- return redactRecord(value, redact);
9546
- }
9547
- return value;
9548
- }
9549
-
9550
9058
  // src/lib/credit-payment.ts
9551
- import { randomUUID as randomUUID2 } from "crypto";
9059
+ import { randomUUID } from "crypto";
9552
9060
 
9553
9061
  // src/lib/caller-version.ts
9554
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
9555
- import { dirname as dirname2, join as join3 } from "path";
9062
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
9063
+ import { dirname, join as join2 } from "path";
9556
9064
  import { fileURLToPath } from "url";
9557
9065
  var CALLER_VERSION = readCallerVersion();
9558
9066
  function readCallerVersion() {
9559
- let dir = dirname2(fileURLToPath(import.meta.url));
9067
+ let dir = dirname(fileURLToPath(import.meta.url));
9560
9068
  for (; ; ) {
9561
- const manifestPath = join3(dir, "package.json");
9562
- if (existsSync3(manifestPath)) {
9069
+ const manifestPath = join2(dir, "package.json");
9070
+ if (existsSync2(manifestPath)) {
9563
9071
  const manifest = readManifest(manifestPath);
9564
9072
  if (manifest.name === "@dvmkit/dvm-cli") return manifest.version;
9565
9073
  }
9566
- const parent = dirname2(dir);
9074
+ const parent = dirname(dir);
9567
9075
  if (parent === dir) {
9568
9076
  throw new Error(`No @dvmkit/dvm-cli package.json found walking up from ${import.meta.url}`);
9569
9077
  }
@@ -9571,7 +9079,7 @@ function readCallerVersion() {
9571
9079
  }
9572
9080
  }
9573
9081
  function readManifest(path) {
9574
- return JSON.parse(readFileSync4(path, "utf8"));
9082
+ return JSON.parse(readFileSync2(path, "utf8"));
9575
9083
  }
9576
9084
 
9577
9085
  // src/lib/client-compatibility.ts
@@ -10346,7 +9854,11 @@ async function sendCreditPayment(jobId, intent, transport, provider, jobToken) {
10346
9854
  async function tryCreditPayment(args) {
10347
9855
  const { jobId, request: request2, requestSeq, transport, provider, jobToken } = args;
10348
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.");
10349
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.");
10350
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;
10351
9863
  const signer = findSigningIdentityByPubkey(job.creditBinding.callerPubkey);
10352
9864
  if (!signer) return false;
@@ -10368,7 +9880,7 @@ async function tryCreditPayment(args) {
10368
9880
  const eligible = stored && stored.currency === ask.currency && stored.status === "active" && !stored.reconciliationPending && !stored.selectionCleared && (stored.expiryMs === 0 || stored.expiryMs > Date.now()) && stored.remainingMicro >= ask.amount_micro;
10369
9881
  const creditId = implicit?.creditId ?? (eligible ? stored.creditId : void 0);
10370
9882
  if (!creditId) return false;
10371
- binding = { creditId, drawId: randomUUID2(), callerPubkey: signer.pubkey };
9883
+ binding = { creditId, drawId: randomUUID(), callerPubkey: signer.pubkey };
10372
9884
  }
10373
9885
  if (!Number.isSafeInteger(request2.amount_msats) || request2.amount_msats <= 0) return false;
10374
9886
  const rate = await balanceCurrencyRate(ask.currency);
@@ -10396,7 +9908,7 @@ async function tryCreditPayment(args) {
10396
9908
  const authorization = signDvmRequestData(signer.privkey, {
10397
9909
  credit_id: selectedBinding.creditId,
10398
9910
  draw_id: selectedBinding.drawId,
10399
- payment_id: randomUUID2(),
9911
+ payment_id: randomUUID(),
10400
9912
  request_seq: requestSeq,
10401
9913
  amount_micro: ask.amount_micro,
10402
9914
  currency: ask.currency
@@ -10418,6 +9930,7 @@ async function tryCreditPayment(args) {
10418
9930
  authorization,
10419
9931
  request: request2,
10420
9932
  amountMsats,
9933
+ approval: args.approval,
10421
9934
  ..."unbound" in job.creditBinding ? { selectedUnbound: true } : {}
10422
9935
  };
10423
9936
  return current.pendingCreditPayment;
@@ -10450,10 +9963,10 @@ async function sweepPendingSubmissions(opts = {}) {
10450
9963
  }
10451
9964
  };
10452
9965
  const now = opts.now ?? (() => Date.now());
10453
- const { entries, unreadable: unreadable2 } = await reconcileEvidenceMarkers(wallet);
9966
+ const { entries, unreadable } = await reconcileEvidenceMarkers(wallet);
10454
9967
  const outcomes = [];
10455
9968
  for (const entry of entries) {
10456
- outcomes.push(await resolveEntry(entry, deps, now(), unreadable2.has(entry.request_id)));
9969
+ outcomes.push(await resolveEntry(entry, deps, now(), unreadable.has(entry.request_id)));
10457
9970
  }
10458
9971
  if (outcomes.some(mutatesWallet)) {
10459
9972
  await withWalletLock(() => {
@@ -10578,6 +10091,7 @@ async function bookRecoveredSubmissions(args) {
10578
10091
  const fresh = loadAgentWallet();
10579
10092
  const booked = matches(fresh);
10580
10093
  if (!fresh || booked.length === 0) return [];
10094
+ for (const entry of booked) restoreUpfrontRailPayment(entry, args.jobId, null);
10581
10095
  saveAgentWallet(
10582
10096
  booked.reduce(
10583
10097
  (acc, entry) => applyOutcome(acc, { kind: "shipped", entry, jobId: args.jobId }, now),
@@ -10912,6 +10426,8 @@ async function shipEntry(entry, httpPost, persistUnresolved) {
10912
10426
  ...record.jobToken && !existing.jobToken ? { jobToken: record.jobToken } : {}
10913
10427
  });
10914
10428
  } else saveJob(record);
10429
+ restoreUpfrontRailPayment(active2, identity.jobId, response.body);
10430
+ recordUpfrontCreditPayment(identity.jobId, response.body?.upfront_payment, true);
10915
10431
  }
10916
10432
  await reconcileResumedJobCredit(active2, response.body, httpPost);
10917
10433
  return { kind: "shipped", entry, jobId: identity.jobId };
@@ -11029,12 +10545,21 @@ function saveRecoveredJob(entry, jobId, body, requestId) {
11029
10545
  requestId,
11030
10546
  ...jobToken && !existing.jobToken ? { jobToken } : {}
11031
10547
  });
10548
+ recordUpfrontCreditPayment(jobId, body?.upfront_payment, true);
10549
+ restoreUpfrontRailPayment(entry, jobId, body);
11032
10550
  return "saved";
11033
10551
  }
11034
10552
  const { jobToken: _unchecked, ...record } = jobRecordFromEntry(entry, jobId, body, void 0);
11035
10553
  saveJob({ ...record, requestId, ...jobToken ? { jobToken } : {} });
10554
+ recordUpfrontCreditPayment(jobId, body?.upfront_payment, true);
10555
+ restoreUpfrontRailPayment(entry, jobId, body);
11036
10556
  return "saved";
11037
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
+ }
11038
10563
  function errorCodeOf(body) {
11039
10564
  const error = body?.error;
11040
10565
  if (typeof error === "string") return error;
@@ -11252,6 +10777,7 @@ function applyOutcome(wallet, outcome, now) {
11252
10777
  signed_at_ms: now()
11253
10778
  };
11254
10779
  const dropped = drop();
10780
+ if (dropped.recent_spends.some((spend) => spend.request_id === recentSpend.request_id)) return dropped;
11255
10781
  return {
11256
10782
  ...dropped,
11257
10783
  recent_spends: [...dropped.recent_spends, recentSpend].slice(-RECENT_SPENDS_CAP)
@@ -11389,18 +10915,18 @@ function createDefaultHttpPost(fetchImpl) {
11389
10915
  };
11390
10916
  }
11391
10917
  async function reconcileEvidenceMarkers(wallet) {
11392
- const unreadable2 = /* @__PURE__ */ new Set();
10918
+ const unreadable = /* @__PURE__ */ new Set();
11393
10919
  const orphaned = wallet.pending_submissions.flatMap((entry) => {
11394
10920
  if (entry.accepted_unresolved) return [];
11395
10921
  try {
11396
10922
  const record = loadSubmissionEvidence(entry.request_id);
11397
10923
  return record ? [{ requestId: entry.request_id, marker: journalMarkerFor(record) }] : [];
11398
10924
  } catch {
11399
- unreadable2.add(entry.request_id);
10925
+ unreadable.add(entry.request_id);
11400
10926
  return [];
11401
10927
  }
11402
10928
  });
11403
- if (orphaned.length === 0) return { entries: wallet.pending_submissions, unreadable: unreadable2 };
10929
+ if (orphaned.length === 0) return { entries: wallet.pending_submissions, unreadable };
11404
10930
  return withWalletLock(() => {
11405
10931
  const fresh = loadAgentWallet() ?? wallet;
11406
10932
  const next = orphaned.reduce(
@@ -11408,7 +10934,7 @@ async function reconcileEvidenceMarkers(wallet) {
11408
10934
  fresh
11409
10935
  );
11410
10936
  saveAgentWallet(next);
11411
- return { entries: next.pending_submissions, unreadable: unreadable2 };
10937
+ return { entries: next.pending_submissions, unreadable };
11412
10938
  });
11413
10939
  }
11414
10940
  function evidenceState(ambiguityId) {
@@ -11624,7 +11150,38 @@ function parseTempoNetwork(value, source) {
11624
11150
 
11625
11151
  // src/lib/payment-responder.ts
11626
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
+ };
11627
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
+ );
11628
11185
  const spent = job?.totalPaidMsats ?? 0;
11629
11186
  const paymentsHonoured = job?.paymentsHonoured ?? 0;
11630
11187
  const pinnedMint = job?.pinnedMint;
@@ -11651,6 +11208,22 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11651
11208
  if (pending4.authorization.request_seq !== opts?.requestSeq)
11652
11209
  throw new DvmError("credit_payment_retry_required", "The prior balance payment was refused; reload this job's pending ask.");
11653
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
+ }
11654
11227
  if (policy.maxIncrementMsats > 0 && request2.amount_msats > policy.maxIncrementMsats) {
11655
11228
  return "over-budget";
11656
11229
  }
@@ -11673,6 +11246,7 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11673
11246
  request: request2,
11674
11247
  policy,
11675
11248
  requestSeq: opts?.requestSeq,
11249
+ approval: opts?.approval ?? "auto",
11676
11250
  transport,
11677
11251
  provider,
11678
11252
  jobToken
@@ -11705,15 +11279,17 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11705
11279
  pinnedMint,
11706
11280
  maxCashuFeeSats,
11707
11281
  strictPerCall,
11708
- jobToken
11282
+ approval,
11283
+ jobToken,
11284
+ requestSeq: matchingEndpoint ? opts?.requestSeq : void 0
11709
11285
  });
11710
11286
  if (paid) {
11711
11287
  return { status: "paid", rail: "cashu_p2pk", amountMsats: request2.amount_msats };
11712
11288
  }
11713
11289
  }
11714
11290
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11715
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UEQTGVJE.js");
11716
- const { tryX402Payment: tryX402Payment2 } = await import("./client-MMJYIMKJ.js");
11291
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UJ7EJNQA.js");
11292
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-DS4QJ346.js");
11717
11293
  const wallet = loadX402Wallet2();
11718
11294
  if (wallet) {
11719
11295
  let proof;
@@ -11742,7 +11318,8 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11742
11318
  }
11743
11319
  if (proof) {
11744
11320
  await enforceGlobalBudget({ plannedMsats: proof.amountMsats, btcRate: proof.btcRate });
11745
- await transport.sendMessage(
11321
+ await sendRailPayment(
11322
+ transport,
11746
11323
  jobId,
11747
11324
  {
11748
11325
  type: "payment",
@@ -11752,9 +11329,10 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11752
11329
  }
11753
11330
  },
11754
11331
  provider,
11755
- { jobToken }
11332
+ { jobToken },
11333
+ matchingEndpoint ? opts?.requestSeq : void 0
11756
11334
  );
11757
- addPayment(jobId, proof.amountMsats);
11335
+ addPayment(jobId, proof.amountMsats, approval);
11758
11336
  recordSpend({
11759
11337
  msats: proof.amountMsats,
11760
11338
  btcRate: proof.btcRate,
@@ -11777,7 +11355,8 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11777
11355
  if (cred) {
11778
11356
  const paidMsats = usdcToMsats(Number(tempoCredentialAmountMicro(cred)) / 1e6, tempoRate);
11779
11357
  await enforceGlobalBudget({ plannedMsats: paidMsats, btcRate: tempoRate });
11780
- await transport.sendMessage(
11358
+ await sendRailPayment(
11359
+ transport,
11781
11360
  jobId,
11782
11361
  {
11783
11362
  type: "payment",
@@ -11787,9 +11366,10 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11787
11366
  }
11788
11367
  },
11789
11368
  provider,
11790
- { jobToken }
11369
+ { jobToken },
11370
+ matchingEndpoint ? opts?.requestSeq : void 0
11791
11371
  );
11792
- addPayment(jobId, paidMsats);
11372
+ addPayment(jobId, paidMsats, approval);
11793
11373
  recordSpend({
11794
11374
  msats: paidMsats,
11795
11375
  btcRate: tempoRate,
@@ -11816,6 +11396,7 @@ async function tryAgentWalletMidJobPayment(args) {
11816
11396
  pinnedMint,
11817
11397
  maxCashuFeeSats,
11818
11398
  strictPerCall,
11399
+ approval,
11819
11400
  jobToken
11820
11401
  } = args;
11821
11402
  if (!strictPerCall) await sweepPendingSubmissions({ fetchImpl: dvmFetch }).catch(() => void 0);
@@ -11870,7 +11451,8 @@ async function tryAgentWalletMidJobPayment(args) {
11870
11451
  prepared,
11871
11452
  transport,
11872
11453
  provider,
11873
- jobToken
11454
+ jobToken,
11455
+ requestSeq: args.requestSeq
11874
11456
  });
11875
11457
  } catch (err) {
11876
11458
  if (err instanceof DvmError && err.code === "payment_invalid") {
@@ -11888,7 +11470,7 @@ async function tryAgentWalletMidJobPayment(args) {
11888
11470
  signed_at_ms: Date.now()
11889
11471
  }
11890
11472
  });
11891
- addPayment(jobId, request2.amount_msats);
11473
+ addPayment(jobId, request2.amount_msats, approval);
11892
11474
  recordSpend({
11893
11475
  msats: request2.amount_msats,
11894
11476
  btcRate,
@@ -11901,7 +11483,8 @@ async function tryAgentWalletMidJobPayment(args) {
11901
11483
  async function sendMidJobPaymentWithRetry(args) {
11902
11484
  const { jobId, amountMsats, prepared, transport, provider, jobToken } = args;
11903
11485
  await withAgentWalletPaymentRetry({
11904
- attempt: () => transport.sendMessage(
11486
+ attempt: () => sendRailPayment(
11487
+ transport,
11905
11488
  jobId,
11906
11489
  {
11907
11490
  type: "payment",
@@ -11913,13 +11496,48 @@ async function sendMidJobPaymentWithRetry(args) {
11913
11496
  }
11914
11497
  },
11915
11498
  provider,
11916
- { jobToken }
11499
+ { jobToken },
11500
+ args.requestSeq
11917
11501
  ),
11918
11502
  intendedLockPubkey: prepared.intendedLockPubkey,
11919
11503
  refetchInfo: () => transport.describe(provider),
11920
11504
  sleep: args.sleep
11921
11505
  });
11922
11506
  }
11507
+ async function sendRailPayment(transport, jobId, message2, provider, options, requestSeq) {
11508
+ const capture = (evidence) => {
11509
+ if (evidence.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
11510
+ if (evidence.drawFundingReceipt) captureDrawFundingReceipts(jobId, [evidence.drawFundingReceipt], {
11511
+ endpoint: provider.endpoint,
11512
+ ...typeof message2.content.cashu_request_id === "string" ? { fundId: message2.content.cashu_request_id } : {}
11513
+ });
11514
+ };
11515
+ if (requestSeq !== void 0) markPaymentRequestInFlight(jobId, requestSeq);
11516
+ try {
11517
+ const result = await transport.sendMessage(jobId, message2, provider, options);
11518
+ if (requestSeq !== void 0) markPaymentRequestPaid(jobId, requestSeq);
11519
+ if (result) capture(result);
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
+ }
11526
+ if (error instanceof DvmError && error.data) capture(error.data);
11527
+ if (error instanceof DvmError && error.code === "replay_rejected") return;
11528
+ throw error;
11529
+ }
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
+ }
11923
11541
  async function tryMppCredential(challenges, amountMsats, btcRate) {
11924
11542
  const wallet = loadConfig()?.tempo;
11925
11543
  if (wallet?.method !== "tempo" || !wallet.apiKey) return null;
@@ -12034,21 +11652,20 @@ async function refundJsonField(claims) {
12034
11652
  }
12035
11653
  };
12036
11654
  }
12037
- function printRefundSummaryHuman(claims) {
12038
- for (const claim of claims) {
12039
- const noun = claim.reason === "change" ? "change" : "refund";
12040
- if (claim.claimed) {
12041
- info(`Claimed ${noun} of ${formatAmountBestEffort(claim.amount_msats)} into your wallet.`);
12042
- } else {
12043
- info(
12044
- `${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}`
12045
- );
12046
- }
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.`;
12047
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}`;
12048
11661
  }
12049
11662
  function cap(s) {
12050
11663
  return s.charAt(0).toUpperCase() + s.slice(1);
12051
11664
  }
11665
+ function withRefundNextAction(jobId, action, claims) {
11666
+ if (action?.type === "respond" || action?.type === "pay") return action;
11667
+ return refundNextAction(jobId, claims) ?? action;
11668
+ }
12052
11669
 
12053
11670
  // src/lib/stream-loop.ts
12054
11671
  async function streamLoop(opts) {
@@ -12058,8 +11675,9 @@ async function streamLoop(opts) {
12058
11675
  const allMessages = [];
12059
11676
  const autoPayments = [];
12060
11677
  const refunds = [];
12061
- const autoPaidSeqs = /* @__PURE__ */ new Set();
11678
+ const answeredSeqs = persistLocalState ? loadAnsweredYieldSeqs(jobId) : /* @__PURE__ */ new Set();
12062
11679
  let justAutoPaid = false;
11680
+ let paymentUnresolved = false;
12063
11681
  let cursor = opts.afterSeq;
12064
11682
  let messageAppendSession = opts.messageAppendSession;
12065
11683
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
@@ -12071,16 +11689,32 @@ async function streamLoop(opts) {
12071
11689
  ...result.amountUsdcMicro !== void 0 && { amount_usdc_microunits: result.amountUsdcMicro },
12072
11690
  display: paidConfirmationDisplay(result, request2.fiat_amount)
12073
11691
  });
12074
- autoPaidSeqs.add(seq);
11692
+ if (persistLocalState) markPaymentRequestPaid(jobId, seq);
11693
+ answeredSeqs.add(seq);
12075
11694
  justAutoPaid = true;
12076
11695
  }
11696
+ let pendingAction = null;
12077
11697
  const pending4 = persistLocalState ? loadJob(jobId)?.pendingCreditPayment : void 0;
12078
11698
  if (pending4 && policy) {
12079
- const result = await handlePaymentRequest(jobId, pending4.request, policy, transport, provider, {
12080
- jobToken,
12081
- requestSeq: pending4.authorization.request_seq
12082
- });
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
+ }
12083
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
+ }]);
12084
11718
  }
12085
11719
  const deadline = opts.timeoutMs === void 0 ? void 0 : Date.now() + Math.max(0, opts.timeoutMs);
12086
11720
  const nextPollOptions = () => {
@@ -12103,7 +11737,9 @@ async function streamLoop(opts) {
12103
11737
  let batchMessages;
12104
11738
  if (streamFn) {
12105
11739
  const streamOpts = {
12106
- onMessage: opts.onMessage,
11740
+ onMessage: (message2) => {
11741
+ if (message2.seq > cursor) opts.onMessage?.(message2);
11742
+ },
12107
11743
  signal: controller?.signal,
12108
11744
  jobToken
12109
11745
  };
@@ -12114,12 +11750,12 @@ async function streamLoop(opts) {
12114
11750
  if (isAbortError(err) || deadline !== void 0 && isMessagePollTimeout(err)) break;
12115
11751
  throw err;
12116
11752
  }
12117
- batchMessages = result.messages;
11753
+ batchMessages = result.messages.filter((message2) => message2.seq > cursor);
12118
11754
  } else {
12119
11755
  const pollOptions = nextPollOptions();
12120
11756
  if (!pollOptions) break;
12121
11757
  try {
12122
- batchMessages = await transport.getMessages(jobId, cursor, provider, pollOptions);
11758
+ batchMessages = (await transport.getMessages(jobId, cursor, provider, pollOptions)).filter((message2) => message2.seq > cursor);
12123
11759
  } catch (err) {
12124
11760
  if (deadline !== void 0 && isMessagePollTimeout(err)) break;
12125
11761
  throw err;
@@ -12139,20 +11775,53 @@ async function streamLoop(opts) {
12139
11775
  refunds.push(...await claimInboundPayments(jobId, batchMessages));
12140
11776
  }
12141
11777
  justAutoPaid = false;
12142
- const lastYield = findLastYield(batchMessages);
12143
- if (lastYield?.type === "payment-request" && autoPaidSeqs.has(lastYield.seq)) {
12144
- 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);
12145
11784
  break;
12146
11785
  }
12147
- if (lastYield?.type === "payment-request" && policy) {
12148
- 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;
12149
11805
  if (req.amount_msats <= policy.autoPayBelowMsats && (policy.maxIncrementMsats === 0 || req.amount_msats <= policy.maxIncrementMsats)) {
12150
- const result = await handlePaymentRequest(jobId, req, policy, transport, provider, {
12151
- jobToken,
12152
- requestSeq: lastYield.seq
12153
- });
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
+ }
12154
11823
  if (typeof result === "object") {
12155
- recordAutoPayment(result, req, lastYield.seq);
11824
+ recordAutoPayment(result, req, lastYield2.seq);
12156
11825
  continue;
12157
11826
  }
12158
11827
  if (result === "payment-cap-exceeded") {
@@ -12183,7 +11852,7 @@ async function streamLoop(opts) {
12183
11852
  let recheck = [];
12184
11853
  try {
12185
11854
  if (pollOptions) {
12186
- recheck = await transport.getMessages(jobId, cursor, provider, pollOptions);
11855
+ recheck = (await transport.getMessages(jobId, cursor, provider, pollOptions)).filter((message2) => message2.seq > cursor);
12187
11856
  }
12188
11857
  } catch (err) {
12189
11858
  if (deadline === void 0 || !isMessagePollTimeout(err)) throw err;
@@ -12199,17 +11868,24 @@ async function streamLoop(opts) {
12199
11868
  }
12200
11869
  }
12201
11870
  }
12202
- let nextAction = refundNextAction(jobId, refunds) ?? computeNextAction(jobId, allMessages);
12203
- if (nextAction?.type === "pay") {
12204
- const lastYield = findLastYield(allMessages);
12205
- 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)) {
12206
11881
  nextAction = {
12207
11882
  type: "poll",
12208
11883
  job_id: jobId,
12209
- 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.`
12210
11885
  };
12211
11886
  }
12212
11887
  }
11888
+ if (paymentUnresolved) nextAction = pollNextAction(jobId, paymentInFlightHint(jobId));
12213
11889
  return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
12214
11890
  }
12215
11891
  function isMessagePollTimeout(err) {
@@ -12368,6 +12044,7 @@ async function observeJobContent(jobId, transport, ref, options) {
12368
12044
  ...options,
12369
12045
  timeoutMs: options.timeoutMs > 0 ? Math.min(options.timeoutMs, 5e3) : 5e3
12370
12046
  });
12047
+ captureDrawFundingReceipts(jobId, status2.drawFundingReceipts, { endpoint: ref.endpoint });
12371
12048
  return parseJobContent(status2);
12372
12049
  } catch {
12373
12050
  return void 0;
@@ -12700,7 +12377,8 @@ var HttpsTransport = class {
12700
12377
  jobToken,
12701
12378
  ...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {},
12702
12379
  ...feedbackClaim ? { feedbackClaim } : {},
12703
- ...parseFundingResponse(data)
12380
+ ...parseFundingResponse(data),
12381
+ upfrontPayment: parseUpfrontPayment(data.upfront_payment)
12704
12382
  };
12705
12383
  }
12706
12384
  return {
@@ -12715,7 +12393,8 @@ var HttpsTransport = class {
12715
12393
  ...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {},
12716
12394
  ...feedbackClaim ? { feedbackClaim } : {},
12717
12395
  ...parseSignedReceipt(data.receipt),
12718
- ...parseFundingResponse(data)
12396
+ ...parseFundingResponse(data),
12397
+ upfrontPayment: parseUpfrontPayment(data.upfront_payment)
12719
12398
  };
12720
12399
  }
12721
12400
  async requestResult(provider, requestId, signedJob) {
@@ -12961,6 +12640,21 @@ var HttpsTransport = class {
12961
12640
  }
12962
12641
  }
12963
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) {
12964
12658
  const endpoint = provider?.endpoint;
12965
12659
  if (!endpoint) {
12966
12660
  throw new DvmError(
@@ -12970,34 +12664,31 @@ var HttpsTransport = class {
12970
12664
  }
12971
12665
  const url = `${endpoint}/v1/job/${jobId}/messages`;
12972
12666
  const body = JSON.stringify({ type: message2.type, content: message2.content });
12973
- let res;
12974
- try {
12975
- res = await dvmFetch(url, {
12976
- method: "POST",
12977
- headers: { "Content-Type": "application/json", ...jobTokenHeader(options?.jobToken) },
12978
- body
12979
- });
12980
- } catch (err) {
12981
- if (isAbortError(err)) {
12982
- throw new DvmError("timeout", "sendMessage timed out.");
12983
- }
12984
- throw err;
12985
- }
12667
+ const res = await dvmFetch(url, {
12668
+ method: "POST",
12669
+ headers: { "Content-Type": "application/json", ...jobTokenHeader(options?.jobToken) },
12670
+ body,
12671
+ signal
12672
+ });
12986
12673
  if (res.status === 402) {
12987
12674
  let errorBody;
12988
12675
  try {
12989
12676
  errorBody = await res.json();
12990
- } catch {
12677
+ } catch (error2) {
12678
+ if (isAbortError(error2)) throw error2;
12991
12679
  throw new DvmError("payment_insufficient", "Payment required (unparseable response).");
12992
12680
  }
12993
- const error = withCreditErrorContext(buildPaymentError(errorBody), errorBody);
12681
+ const error = withDrawFunding(withCreditErrorContext(buildPaymentError(errorBody), errorBody), errorBody);
12994
12682
  error.data = { ...error.data, http_status: 402 };
12995
12683
  throw error;
12996
12684
  }
12997
12685
  if (res.status === 409) {
12998
12686
  const body2 = parseJsonObject(await res.text());
12999
- if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string"))
13000
- throw withCreditErrorContext(buildPaymentError(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
+ }
13001
12692
  throw new DvmError(
13002
12693
  "job_terminal",
13003
12694
  "Job is no longer active.",
@@ -13007,14 +12698,23 @@ var HttpsTransport = class {
13007
12698
  if (!res.ok) {
13008
12699
  const text = await res.text();
13009
12700
  const structured = parseStructuredError(text);
13010
- if (structured) throw withCreditErrorContext(structured, parseJsonObject(text) ?? {});
12701
+ if (structured) {
12702
+ const body2 = parseJsonObject(text) ?? {};
12703
+ const error = withDrawFunding(withCreditErrorContext(structured, body2), body2);
12704
+ error.data = { ...error.data, http_status: res.status };
12705
+ throw error;
12706
+ }
13011
12707
  throw providerResponseError("provider_error", `sendMessage failed (${res.status}): ${text}`);
13012
12708
  }
12709
+ if (message2.type !== "payment") return;
12710
+ const acknowledgement = parseJsonObject(await res.text());
13013
12711
  if (message2.type === "payment" && message2.content.credit) {
13014
- const body2 = parseJsonObject(await res.text());
13015
- if (res.status !== 201 || !Number.isSafeInteger(body2?.seq) || Number(body2?.seq) < 0)
12712
+ if (res.status !== 201 || !Number.isSafeInteger(acknowledgement?.seq) || Number(acknowledgement?.seq) < 0)
13016
12713
  throw new DvmError("invalid_credit_payment_response", "The balance payment outcome is unknown; replay the saved payment.");
13017
12714
  }
12715
+ if (acknowledgement && Number.isSafeInteger(acknowledgement.seq) && Number(acknowledgement.seq) >= 0) {
12716
+ return { seq: Number(acknowledgement.seq), ...parseDrawFundingReceipt(acknowledgement.draw_funding_receipt) };
12717
+ }
13018
12718
  }
13019
12719
  async stream(jobId, afterSeq, provider, options) {
13020
12720
  const endpoint = provider?.endpoint;
@@ -13113,12 +12813,24 @@ function parseFundingReceipt(value) {
13113
12813
  return isFundingReceipt(value) ? { fundingReceipt: value } : { fundingReceiptParseError: "shape_invalid" };
13114
12814
  }
13115
12815
  function parseFundingResponse(data) {
12816
+ const raw2 = data.draw_funding_receipts;
13116
12817
  return {
13117
12818
  ...parseFundingReceipt(data.funding_receipt),
13118
12819
  ...typeof data.funded_micro === "number" ? { fundedMicro: data.funded_micro } : {},
13119
- ...data.credit && typeof data.credit === "object" && !Array.isArray(data.credit) ? { credit: data.credit } : {}
12820
+ ...data.credit && typeof data.credit === "object" && !Array.isArray(data.credit) ? { credit: data.credit } : {},
12821
+ ...Array.isArray(raw2) ? { drawFundingReceipts: raw2.filter(isDrawFundingReceipt) } : {},
12822
+ ...raw2 !== void 0 && (!Array.isArray(raw2) || !raw2.every(isDrawFundingReceipt)) ? { drawFundingReceiptParseError: "shape_invalid" } : {}
13120
12823
  };
13121
12824
  }
12825
+ function parseDrawFundingReceipt(value) {
12826
+ if (value === void 0) return {};
12827
+ return isDrawFundingReceipt(value) ? { drawFundingReceipt: value } : { drawFundingReceiptParseError: "shape_invalid" };
12828
+ }
12829
+ function withDrawFunding(error, body) {
12830
+ const evidence = parseDrawFundingReceipt(body.draw_funding_receipt);
12831
+ if (Object.keys(evidence).length) error.data = { ...error.data, ...evidence };
12832
+ return error;
12833
+ }
13122
12834
  function parseRequestResultResponse(value, requestId, httpStatus) {
13123
12835
  if (!value || typeof value !== "object" || Array.isArray(value)) {
13124
12836
  throw malformedRequestResult(requestId, "response_not_object");
@@ -13180,7 +12892,8 @@ function parseRequestResultResponse(value, requestId, httpStatus) {
13180
12892
  ...data.payload_in === "summary" || data.payload_in === "messages" ? { payloadIn: data.payload_in } : {},
13181
12893
  ...typeof data.job_token === "string" ? { jobToken: data.job_token } : {},
13182
12894
  ...receipt ? { receipt } : {},
13183
- ...parseFundingResponse(data)
12895
+ ...parseFundingResponse(data),
12896
+ upfrontPayment: parseUpfrontPayment(data.upfront_payment)
13184
12897
  };
13185
12898
  }
13186
12899
  function malformedRequestResult(requestId, reason) {
@@ -14122,14 +13835,14 @@ async function confirmRollback(stored, preview, opts) {
14122
13835
  async function withStrandingChecked(removing, commit) {
14123
13836
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
14124
13837
  if (leaving.has("tempo")) {
14125
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-HJQYBOZR.js");
13838
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-LGGBDCKK.js");
14126
13839
  await assertTempoWalletIdle2("disconnect");
14127
13840
  }
14128
13841
  if (!leaving.has("x402")) return commit();
14129
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-LRW4XR3J.js");
14130
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-QE3KHIHQ.js");
14131
- const { ensureAddress: ensureAddress2 } = await import("./internal-LRW4XR3J.js");
14132
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UEQTGVJE.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");
14133
13846
  return withX402ChannelLock2(async () => {
14134
13847
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
14135
13848
  if (unsettled.length > 0) {
@@ -15640,7 +15353,7 @@ function wireCreditCurrencyTotals(rows) {
15640
15353
 
15641
15354
  // src/lib/credit/drain.ts
15642
15355
  import {
15643
- randomUUID as randomUUID3
15356
+ randomUUID as randomUUID2
15644
15357
  } from "crypto";
15645
15358
  async function runCreditDrain(dvm, opts) {
15646
15359
  const endpoint = resolveCreditEndpoint(dvm);
@@ -15784,7 +15497,7 @@ async function runCreditDrain(dvm, opts) {
15784
15497
  const payout = await drainPayout(method, opts, channelBacked, dvm);
15785
15498
  const mintedThisRun = !pending4;
15786
15499
  let drain = pending4 ? reusableDrain(pending4, method, payout) : {
15787
- drainId: opts.drainId ?? randomUUID3(),
15500
+ drainId: opts.drainId ?? randomUUID2(),
15788
15501
  creditId,
15789
15502
  method,
15790
15503
  payout,
@@ -16655,7 +16368,7 @@ function refundAddress(address) {
16655
16368
 
16656
16369
  // src/lib/credit/funding.ts
16657
16370
  import {
16658
- randomUUID as randomUUID4
16371
+ randomUUID as randomUUID3
16659
16372
  } from "crypto";
16660
16373
  async function runCreditFund(dvm, opts) {
16661
16374
  const endpoint = resolveCreditEndpoint(dvm);
@@ -16767,7 +16480,7 @@ async function runCreditFund(dvm, opts) {
16767
16480
  transport,
16768
16481
  ref: { endpoint },
16769
16482
  signing: signer,
16770
- creditId: pending4?.creditId ?? opts.creditId ?? (canRefillStoredCredit(stored) ? stored.creditId : signedPending?.creditId ?? randomUUID4()),
16483
+ creditId: pending4?.creditId ?? opts.creditId ?? (canRefillStoredCredit(stored) ? stored.creditId : signedPending?.creditId ?? randomUUID3()),
16771
16484
  amountMicro: fundMicro,
16772
16485
  human: opts.human,
16773
16486
  providerInfo,
@@ -18496,8 +18209,8 @@ async function probeX402(x402, timeoutMs) {
18496
18209
  let network;
18497
18210
  let address;
18498
18211
  try {
18499
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UEQTGVJE.js");
18500
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-LRW4XR3J.js");
18212
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UJ7EJNQA.js");
18213
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-ZZHCUKOM.js");
18501
18214
  const wallet = loadX402Wallet2();
18502
18215
  if (!wallet) {
18503
18216
  const storedKey = x402.privateKey;
@@ -18549,8 +18262,8 @@ async function probeMpp(mpp, timeoutMs) {
18549
18262
  if (!mpp) return null;
18550
18263
  if (mpp.method === "tempo") {
18551
18264
  try {
18552
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-XN72C2GK.js");
18553
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-LRW4XR3J.js");
18265
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-PLFC443A.js");
18266
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-ZZHCUKOM.js");
18554
18267
  const account = await connectedTempoAccount2();
18555
18268
  if (!account) {
18556
18269
  return {
@@ -18644,15 +18357,15 @@ function x402WrongAssetHint(asset) {
18644
18357
  }
18645
18358
 
18646
18359
  // src/lib/build-freshness.ts
18647
- import { existsSync as existsSync4, readdirSync as readdirSync2, statSync as statSync3 } from "fs";
18648
- import { dirname as dirname3, join as join4 } from "path";
18360
+ import { existsSync as existsSync3, readdirSync, statSync as statSync2 } from "fs";
18361
+ import { dirname as dirname2, join as join3 } from "path";
18649
18362
  import { fileURLToPath as fileURLToPath2 } from "url";
18650
18363
  var EXTRA_SOURCES = ["package.json", "tsup.config.ts"];
18651
18364
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "__snapshots__"]);
18652
18365
  var MAX_ENTRIES = 2e4;
18653
18366
  function checkBuildFreshness(opts) {
18654
18367
  const now = opts?.now ?? Date.now;
18655
- const moduleDir = opts?.moduleDir ?? dirname3(fileURLToPath2(import.meta.url));
18368
+ const moduleDir = opts?.moduleDir ?? dirname2(fileURLToPath2(import.meta.url));
18656
18369
  const root = findPackageRoot(moduleDir);
18657
18370
  const skipped = (skipReason) => ({
18658
18371
  status: "not_applicable",
@@ -18664,28 +18377,28 @@ function checkBuildFreshness(opts) {
18664
18377
  skipReason
18665
18378
  });
18666
18379
  if (root === null) return skipped("running_from_source");
18667
- const bundlePath = join4(root, "dist", "dvm.js");
18668
- if (dirname3(moduleDir) !== root || !existsSync4(bundlePath)) {
18380
+ const bundlePath = join3(root, "dist", "dvm.js");
18381
+ if (dirname2(moduleDir) !== root || !existsSync3(bundlePath)) {
18669
18382
  return skipped("running_from_source");
18670
18383
  }
18671
- const srcDir = join4(root, "src");
18672
- if (!existsSync4(srcDir)) return skipped("no_source_tree");
18673
- const builtAtMs = statSync3(bundlePath).mtimeMs;
18384
+ const srcDir = join3(root, "src");
18385
+ if (!existsSync3(srcDir)) return skipped("no_source_tree");
18386
+ const builtAtMs = statSync2(bundlePath).mtimeMs;
18674
18387
  const newer = [];
18675
18388
  let newestMs = 0;
18676
18389
  const visit = (dir, rel, budget2) => {
18677
18390
  if (budget2.left <= 0) return;
18678
- for (const entry of readdirSync2(dir, { withFileTypes: true })) {
18391
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
18679
18392
  if (budget2.left-- <= 0) return;
18680
18393
  if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
18681
- const abs = join4(dir, entry.name);
18394
+ const abs = join3(dir, entry.name);
18682
18395
  const relPath = rel ? `${rel}/${entry.name}` : entry.name;
18683
18396
  if (entry.isDirectory()) {
18684
18397
  visit(abs, relPath, budget2);
18685
18398
  continue;
18686
18399
  }
18687
18400
  if (!entry.isFile()) continue;
18688
- const mtimeMs = statSync3(abs).mtimeMs;
18401
+ const mtimeMs = statSync2(abs).mtimeMs;
18689
18402
  if (mtimeMs > newestMs) newestMs = mtimeMs;
18690
18403
  if (mtimeMs > builtAtMs) newer.push({ path: relPath, mtimeMs });
18691
18404
  }
@@ -18693,9 +18406,9 @@ function checkBuildFreshness(opts) {
18693
18406
  const budget = { left: MAX_ENTRIES };
18694
18407
  visit(srcDir, "src", budget);
18695
18408
  for (const name of EXTRA_SOURCES) {
18696
- const abs = join4(root, name);
18697
- if (!existsSync4(abs)) continue;
18698
- const mtimeMs = statSync3(abs).mtimeMs;
18409
+ const abs = join3(root, name);
18410
+ if (!existsSync3(abs)) continue;
18411
+ const mtimeMs = statSync2(abs).mtimeMs;
18699
18412
  if (mtimeMs > newestMs) newestMs = mtimeMs;
18700
18413
  if (mtimeMs > builtAtMs) newer.push({ path: name, mtimeMs });
18701
18414
  }
@@ -18712,26 +18425,26 @@ function checkBuildFreshness(opts) {
18712
18425
  function findPackageRoot(start) {
18713
18426
  let dir = start;
18714
18427
  for (; ; ) {
18715
- if (existsSync4(join4(dir, "package.json"))) return dir;
18716
- const parent = dirname3(dir);
18428
+ if (existsSync3(join3(dir, "package.json"))) return dir;
18429
+ const parent = dirname2(dir);
18717
18430
  if (parent === dir) return null;
18718
18431
  dir = parent;
18719
18432
  }
18720
18433
  }
18721
18434
 
18722
18435
  // src/lib/caller-state.ts
18723
- import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync4 } from "fs";
18724
- import { basename, join as join5 } from "path";
18436
+ import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync3, statSync as statSync3 } from "fs";
18437
+ import { basename, join as join4 } from "path";
18725
18438
  function detectSetupState() {
18726
18439
  return {
18727
18440
  existingState: {
18728
- jobs: existsSync5(JOBS_FILE),
18729
- messages: existsSync5(MESSAGES_DIR)
18441
+ jobs: existsSync4(JOBS_FILE),
18442
+ messages: existsSync4(MESSAGES_DIR)
18730
18443
  },
18731
18444
  missing: {
18732
- config: !existsSync5(CONFIG_FILE),
18733
- identity: !existsSync5(IDENTITIES_FILE),
18734
- wallet: !existsSync5(WALLET_FILE)
18445
+ config: !existsSync4(CONFIG_FILE),
18446
+ identity: !existsSync4(IDENTITIES_FILE),
18447
+ wallet: !existsSync4(WALLET_FILE)
18735
18448
  }
18736
18449
  };
18737
18450
  }
@@ -18850,21 +18563,21 @@ function findQuarantinedCreditStores() {
18850
18563
  const prefix = `${basename(CREDITS_FILE)}.corrupt-`;
18851
18564
  let entries;
18852
18565
  try {
18853
- entries = readdirSync3(CONFIG_DIR);
18566
+ entries = readdirSync2(CONFIG_DIR);
18854
18567
  } catch {
18855
18568
  return [];
18856
18569
  }
18857
- return entries.filter((name) => name.startsWith(prefix)).sort((a, b) => a < b ? 1 : a > b ? -1 : 0).map((name) => ({ path: join5(CONFIG_DIR, name), name }));
18570
+ return entries.filter((name) => name.startsWith(prefix)).sort((a, b) => a < b ? 1 : a > b ? -1 : 0).map((name) => ({ path: join4(CONFIG_DIR, name), name }));
18858
18571
  }
18859
18572
  function checkOne(spec) {
18860
- const exists = existsSync5(spec.path);
18573
+ const exists = existsSync4(spec.path);
18861
18574
  if (!exists) {
18862
18575
  return { name: spec.name, path: spec.path, exists: false };
18863
18576
  }
18864
18577
  const row = { name: spec.name, path: spec.path, exists: true };
18865
18578
  if (spec.json) {
18866
18579
  try {
18867
- JSON.parse(readFileSync5(spec.path, "utf-8"));
18580
+ JSON.parse(readFileSync3(spec.path, "utf-8"));
18868
18581
  row.parseable = true;
18869
18582
  } catch (err) {
18870
18583
  row.parseable = false;
@@ -18875,7 +18588,7 @@ function checkOne(spec) {
18875
18588
  checkSecretDirectory(spec.path, row);
18876
18589
  } else if (spec.secret) {
18877
18590
  try {
18878
- const mode = statSync4(spec.path).mode & 511;
18591
+ const mode = statSync3(spec.path).mode & 511;
18879
18592
  const modeOctal = octalMode(mode);
18880
18593
  row.modeOk = mode === 384;
18881
18594
  row.modeOctal = modeOctal;
@@ -18892,11 +18605,11 @@ function checkOne(spec) {
18892
18605
  function checkSecretDirectory(dir, row) {
18893
18606
  try {
18894
18607
  const offenders = [];
18895
- for (const name of readdirSync3(dir)) {
18896
- const path = join5(dir, name);
18897
- const stat = statSync4(path);
18898
- if (!stat.isFile()) continue;
18899
- const mode = stat.mode & 511;
18608
+ for (const name of readdirSync2(dir)) {
18609
+ const path = join4(dir, name);
18610
+ const stat2 = statSync3(path);
18611
+ if (!stat2.isFile()) continue;
18612
+ const mode = stat2.mode & 511;
18900
18613
  if (mode !== 384) offenders.push({ path, modeOctal: octalMode(mode) });
18901
18614
  }
18902
18615
  row.modeOk = offenders.length === 0;
@@ -18914,9 +18627,9 @@ function octalMode(mode) {
18914
18627
  return "0" + mode.toString(8).padStart(3, "0");
18915
18628
  }
18916
18629
  function readBtcRateCacheAge(now = Date.now()) {
18917
- if (!existsSync5(BTC_RATE_FILE)) return null;
18630
+ if (!existsSync4(BTC_RATE_FILE)) return null;
18918
18631
  try {
18919
- const data = JSON.parse(readFileSync5(BTC_RATE_FILE, "utf-8"));
18632
+ const data = JSON.parse(readFileSync3(BTC_RATE_FILE, "utf-8"));
18920
18633
  if (typeof data.timestamp !== "number") return null;
18921
18634
  return { ageMs: now - data.timestamp };
18922
18635
  } catch {
@@ -18925,26 +18638,26 @@ function readBtcRateCacheAge(now = Date.now()) {
18925
18638
  }
18926
18639
 
18927
18640
  // src/lib/mnemonic-backups.ts
18928
- import { readdirSync as readdirSync4, statSync as statSync5 } from "fs";
18929
- import { basename as basename2, dirname as dirname4, join as join6 } from "path";
18641
+ import { readdirSync as readdirSync3, statSync as statSync4 } from "fs";
18642
+ import { basename as basename2, dirname as dirname3, join as join5 } from "path";
18930
18643
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
18931
- const dir = dirname4(mnemonicFile);
18644
+ const dir = dirname3(mnemonicFile);
18932
18645
  const prefix = `${basename2(mnemonicFile)}.`;
18933
18646
  let names;
18934
18647
  try {
18935
- names = readdirSync4(dir);
18648
+ names = readdirSync3(dir);
18936
18649
  } catch (err) {
18937
18650
  if (err.code === "ENOENT") return [];
18938
18651
  throw err;
18939
18652
  }
18940
18653
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
18941
- const path = join6(dir, name);
18942
- const stat = statSync5(path);
18943
- if (!stat.isFile()) return null;
18944
- const ageMs2 = Math.max(0, nowMs - stat.mtimeMs);
18654
+ const path = join5(dir, name);
18655
+ const stat2 = statSync4(path);
18656
+ if (!stat2.isFile()) return null;
18657
+ const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
18945
18658
  return {
18946
18659
  path,
18947
- modifiedAt: stat.mtime.toISOString(),
18660
+ modifiedAt: stat2.mtime.toISOString(),
18948
18661
  ageMs: ageMs2,
18949
18662
  ageDays: Math.floor(ageMs2 / (24 * 60 * 60 * 1e3)),
18950
18663
  age: formatMnemonicBackupAge(ageMs2)
@@ -20829,11 +20542,11 @@ async function favRm(name, opts) {
20829
20542
  }
20830
20543
 
20831
20544
  // src/lib/byte-source.ts
20832
- import { readFileSync as readFileSync6 } from "fs";
20545
+ import { readFileSync as readFileSync4 } from "fs";
20833
20546
  import { resolve } from "path";
20834
20547
  var STDIN_TIMEOUT_MS = 1e4;
20835
20548
  function readFileText(path) {
20836
- return readFileSync6(resolve(path), "utf-8");
20549
+ return readFileSync4(resolve(path), "utf-8");
20837
20550
  }
20838
20551
  var StdinTimeoutError = class extends Error {
20839
20552
  constructor(timeoutMs) {
@@ -20997,7 +20710,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
20997
20710
  }
20998
20711
 
20999
20712
  // src/lib/feedback-nudges.ts
21000
- import { existsSync as existsSync6, readFileSync as readFileSync7, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync3 } from "fs";
20713
+ import { existsSync as existsSync5, readFileSync as readFileSync5, renameSync, unlinkSync, writeFileSync } from "fs";
21001
20714
 
21002
20715
  // src/lib/feedback-notice.ts
21003
20716
  function buildFeedbackNudge(args) {
@@ -21049,10 +20762,10 @@ function effectiveFeedbackPosture(config) {
21049
20762
  return { posture: DEFAULT_FEEDBACK_POSTURE, source: "default" };
21050
20763
  }
21051
20764
  function loadFeedbackNudgeState() {
21052
- if (!existsSync6(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
20765
+ if (!existsSync5(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
21053
20766
  try {
21054
20767
  const parsed = JSON.parse(
21055
- readFileSync7(FEEDBACK_NUDGES_FILE, "utf-8")
20768
+ readFileSync5(FEEDBACK_NUDGES_FILE, "utf-8")
21056
20769
  );
21057
20770
  return {
21058
20771
  ...typeof parsed.introShownAt === "string" ? { introShownAt: parsed.introShownAt } : {},
@@ -21141,12 +20854,12 @@ function coercePerDvm(perDvm) {
21141
20854
  function saveState(state) {
21142
20855
  ensureConfigDir();
21143
20856
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
21144
- writeFileSync3(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
20857
+ writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
21145
20858
  try {
21146
- renameSync2(tmp, FEEDBACK_NUDGES_FILE);
20859
+ renameSync(tmp, FEEDBACK_NUDGES_FILE);
21147
20860
  } catch (err) {
21148
20861
  try {
21149
- unlinkSync3(tmp);
20862
+ unlinkSync(tmp);
21150
20863
  } catch {
21151
20864
  }
21152
20865
  throw err;
@@ -21155,9 +20868,9 @@ function saveState(state) {
21155
20868
  var nudgedThisInvocation = false;
21156
20869
 
21157
20870
  // src/lib/platform.ts
21158
- import { existsSync as existsSync7, mkdirSync, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
20871
+ import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "fs";
21159
20872
  import { homedir } from "os";
21160
- import { join as join7 } from "path";
20873
+ import { join as join6 } from "path";
21161
20874
  function getPlatformUrl() {
21162
20875
  return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
21163
20876
  }
@@ -21726,16 +21439,16 @@ function finalizeProgressLine() {
21726
21439
  import { randomBytes as randomBytes2 } from "crypto";
21727
21440
  import {
21728
21441
  chmodSync,
21729
- closeSync as closeSync4,
21442
+ closeSync as closeSync2,
21730
21443
  mkdtempSync,
21731
- openSync as openSync4,
21732
- readdirSync as readdirSync5,
21444
+ openSync as openSync2,
21445
+ readdirSync as readdirSync4,
21733
21446
  rmdirSync,
21734
- unlinkSync as unlinkSync4,
21735
- writeFileSync as writeFileSync5
21447
+ unlinkSync as unlinkSync2,
21448
+ writeFileSync as writeFileSync3
21736
21449
  } from "fs";
21737
21450
  import { tmpdir } from "os";
21738
- import { join as join8 } from "path";
21451
+ import { join as join7 } from "path";
21739
21452
 
21740
21453
  // src/lib/mime-ext.ts
21741
21454
  var MIME_TO_EXT = {
@@ -21791,11 +21504,11 @@ var ArtifactSaveSession = class {
21791
21504
  let created = false;
21792
21505
  try {
21793
21506
  const directory = this.ensureDirectory();
21794
- path = join8(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
21795
- fd = openSync4(path, "wx", FILE_MODE);
21507
+ path = join7(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
21508
+ fd = openSync2(path, "wx", FILE_MODE);
21796
21509
  created = true;
21797
- writeFileSync5(fd, buf);
21798
- closeSync4(fd);
21510
+ writeFileSync3(fd, buf);
21511
+ closeSync2(fd);
21799
21512
  fd = void 0;
21800
21513
  chmodSync(path, FILE_MODE);
21801
21514
  this.successfulWrites += 1;
@@ -21803,13 +21516,13 @@ var ArtifactSaveSession = class {
21803
21516
  } catch (err) {
21804
21517
  if (fd !== void 0) {
21805
21518
  try {
21806
- closeSync4(fd);
21519
+ closeSync2(fd);
21807
21520
  } catch {
21808
21521
  }
21809
21522
  }
21810
21523
  if (created && path) {
21811
21524
  try {
21812
- unlinkSync4(path);
21525
+ unlinkSync2(path);
21813
21526
  } catch {
21814
21527
  }
21815
21528
  }
@@ -21820,7 +21533,7 @@ var ArtifactSaveSession = class {
21820
21533
  }
21821
21534
  ensureDirectory() {
21822
21535
  if (this.directory) return this.directory;
21823
- const directory = mkdtempSync(join8(tmpdir(), "dvm-artifacts-"));
21536
+ const directory = mkdtempSync(join7(tmpdir(), "dvm-artifacts-"));
21824
21537
  try {
21825
21538
  chmodSync(directory, DIRECTORY_MODE);
21826
21539
  } catch (err) {
@@ -21836,7 +21549,7 @@ var ArtifactSaveSession = class {
21836
21549
  removeEmptyUnreportedDirectory() {
21837
21550
  if (!this.directory || this.successfulWrites > 0) return;
21838
21551
  try {
21839
- if (readdirSync5(this.directory).length === 0) {
21552
+ if (readdirSync4(this.directory).length === 0) {
21840
21553
  rmdirSync(this.directory);
21841
21554
  this.directory = void 0;
21842
21555
  }
@@ -21925,123 +21638,7 @@ function fullMessageLog(jobId, messages2, afterSeq) {
21925
21638
  return contiguous ? local : void 0;
21926
21639
  }
21927
21640
 
21928
- // src/commands/messages.ts
21929
- async function messages(jobId, opts) {
21930
- const access = resolveJobAccess(jobId, opts);
21931
- return withJobTokenRedaction(access.jobToken, () => messagesWithAccess(jobId, opts, access));
21932
- }
21933
- async function messagesWithAccess(jobId, opts, access) {
21934
- const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
21935
- const { stored, ref, jobToken } = access;
21936
- const transport = createDvmTransport();
21937
- const isTerminal = stored?.status === "completed" || stored?.status === "failed";
21938
- const after = opts.after !== void 0 ? Number(opts.after) : opts.stream === false && isTerminal ? 0 : access.endpointOverridden ? 0 : stored?.messageCursor ?? 0;
21939
- if (opts.stream === false) {
21940
- const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 5e3;
21941
- progressNotice("Fetching messages...", opts.human);
21942
- let msgs;
21943
- try {
21944
- msgs = await transport.getMessages(jobId, after, ref, { timeoutMs: timeout, jobToken });
21945
- } catch (err) {
21946
- if (err instanceof DvmError && err.code === "provider_unreachable" && isTerminal && !access.endpointOverridden && loadMessages(jobId).some((message2) => message2.type === "complete" || message2.type === "cancel")) {
21947
- throw new DvmError(
21948
- "retained_messages_offline",
21949
- `Could not fetch messages for ${stored?.status} job ${jobId}; its provider is unreachable.`,
21950
- `A terminal message is in the local message log. Inspect that log and run 'dvm receipts verify ${jobId}' to check any stored receipt and result hash offline, or restart the provider to fetch messages again.`
21951
- );
21952
- }
21953
- throw err;
21954
- }
21955
- if (!access.endpointOverridden) appendMessages(jobId, msgs);
21956
- const newCursor = maxSeq(msgs, after);
21957
- if (!access.endpointOverridden) {
21958
- persistStreamOutcome({ jobId, messages: msgs, cursor: newCursor, afterSeq: after });
21959
- }
21960
- const refunds = access.endpointOverridden ? [] : await claimInboundPayments(jobId, msgs);
21961
- const nextAction = refundNextAction(jobId, refunds) ?? computeNextAction(jobId, msgs);
21962
- const content2 = jobContentFields(
21963
- jobId,
21964
- await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken })
21965
- );
21966
- transport.close();
21967
- if (opts.human) {
21968
- info(String(content2.content_hint));
21969
- if (msgs.length === 0) {
21970
- info("No new messages.");
21971
- } else {
21972
- for (const msg of msgs) {
21973
- formatMessageHuman(msg, jobId, artifactSession);
21974
- }
21975
- finalizeProgressLine();
21976
- printRefundSummaryHuman(refunds);
21977
- }
21978
- } else {
21979
- json({
21980
- jobId,
21981
- ...content2,
21982
- messages: msgs.map(serialize),
21983
- cursor: newCursor,
21984
- next_action: nextAction,
21985
- ...await refundJsonField(refunds)
21986
- });
21987
- }
21988
- return;
21989
- }
21990
- progressNotice("Streaming messages...", opts.human);
21991
- const result = await streamLoop({
21992
- jobId,
21993
- transport,
21994
- provider: ref,
21995
- policy: stored?.policy ?? void 0,
21996
- afterSeq: after,
21997
- jobToken,
21998
- persistLocalState: !access.endpointOverridden,
21999
- ...opts.human && {
22000
- onMessage: (msg) => {
22001
- if (msg.type === "progress") formatMessageHuman(msg);
22002
- }
22003
- }
22004
- });
22005
- if (!access.endpointOverridden) {
22006
- persistStreamOutcome({
22007
- jobId,
22008
- messages: result.messages,
22009
- cursor: result.cursor,
22010
- afterSeq: after
22011
- });
22012
- }
22013
- const content = jobContentFields(
22014
- jobId,
22015
- await observeJobContent(jobId, transport, ref, {
22016
- timeoutMs: opts.timeout ? Number(opts.timeout) * 1e3 : 5e3,
22017
- jobToken
22018
- })
22019
- );
22020
- transport.close();
22021
- if (opts.human) {
22022
- info(String(content.content_hint));
22023
- if (result.messages.length === 0) {
22024
- info("No new messages.");
22025
- } else {
22026
- for (const msg of result.messages) {
22027
- if (msg.type === "progress") continue;
22028
- formatMessageHuman(msg, jobId, artifactSession);
22029
- }
22030
- finalizeProgressLine();
22031
- printRefundSummaryHuman(result.refunds);
22032
- }
22033
- } else {
22034
- json({
22035
- jobId,
22036
- ...content,
22037
- messages: result.messages.map(serialize),
22038
- cursor: result.cursor,
22039
- next_action: result.nextAction,
22040
- ...result.autoPayments.length > 0 ? { auto_payments: result.autoPayments } : {},
22041
- ...await refundJsonField(result.refunds)
22042
- });
22043
- }
22044
- }
21641
+ // src/lib/message-human.ts
22045
21642
  function paymentAmount(msg) {
22046
21643
  if (msg.from === "requester" && msg.content.credit) {
22047
21644
  const credit = msg.content.credit;
@@ -22053,6 +21650,7 @@ function paymentAmount(msg) {
22053
21650
  return formatAmountBestEffort(msg.content.amount_msats);
22054
21651
  }
22055
21652
  function formatMessageHuman(msg, jobId, artifactSession) {
21653
+ const { seq, type } = msg;
22056
21654
  const prefix = msg.from === "provider" ? "Provider" : "You";
22057
21655
  if (msg.type !== "progress") finalizeProgressLine();
22058
21656
  switch (msg.type) {
@@ -22067,6 +21665,12 @@ function formatMessageHuman(msg, jobId, artifactSession) {
22067
21665
  }
22068
21666
  }
22069
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;
22070
21674
  case "artifact": {
22071
21675
  const label = msg.content.name ?? msg.content.mime_type ?? "unknown type";
22072
21676
  if (jobId) {
@@ -22111,7 +21715,346 @@ function formatMessageHuman(msg, jobId, artifactSession) {
22111
21715
  info(`[${msg.seq}] Cancelled${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
22112
21716
  break;
22113
21717
  default:
22114
- info(`[${msg.seq}] ${prefix} [${msg.type}]: ${JSON.stringify(msg.content)}`);
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
+
21901
+ // src/commands/messages.ts
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
+ }
21906
+ const access = resolveJobAccess(jobId, opts);
21907
+ return withJobTokenRedaction(access.jobToken, () => messagesWithAccess(jobId, opts, access));
21908
+ }
21909
+ async function messagesWithAccess(jobId, opts, access) {
21910
+ const waitDuration = opts.wait ? parseDurationMs(opts.until ?? "12h") : void 0;
21911
+ const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
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
+ }
21939
+ const transport = createDvmTransport();
21940
+ const isTerminal = !access.endpointOverridden && !!stored && isTerminalJobStatus(stored.status);
21941
+ const after = opts.after !== void 0 ? Number(opts.after) : opts.stream === false && isTerminal ? 0 : access.endpointOverridden ? 0 : stored?.messageCursor ?? 0;
21942
+ if (opts.stream === false) {
21943
+ const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 5e3;
21944
+ progressNotice("Fetching messages...", opts.human);
21945
+ let msgs;
21946
+ try {
21947
+ msgs = await transport.getMessages(jobId, after, ref, { timeoutMs: timeout, jobToken });
21948
+ } catch (err) {
21949
+ if (err instanceof DvmError && err.code === "provider_unreachable" && isTerminal && !access.endpointOverridden && loadMessages(jobId).some((message2) => message2.type === "complete" || message2.type === "cancel")) {
21950
+ throw new DvmError(
21951
+ "retained_messages_offline",
21952
+ `Could not fetch messages for ${stored?.status} job ${jobId}; its provider is unreachable.`,
21953
+ `A terminal message is in the local message log. Inspect that log and run 'dvm receipts verify ${jobId}' to check any stored receipt and result hash offline, or restart the provider to fetch messages again.`
21954
+ );
21955
+ }
21956
+ throw err;
21957
+ }
21958
+ if (!access.endpointOverridden) appendMessages(jobId, msgs);
21959
+ const newCursor = maxSeq(msgs, after);
21960
+ if (!access.endpointOverridden) {
21961
+ persistStreamOutcome({ jobId, messages: msgs, cursor: newCursor, afterSeq: after });
21962
+ }
21963
+ const refunds = access.endpointOverridden ? [] : await claimInboundPayments(jobId, msgs);
21964
+ const nextAction = withRefundNextAction(jobId, actionFromMessages(msgs) ?? (streamTerminalStatus(msgs) || isTerminal ? null : pollNextAction(jobId)), refunds);
21965
+ const content2 = jobContentFields(
21966
+ jobId,
21967
+ await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken })
21968
+ );
21969
+ const resolvedAction2 = await resolveNextAction2(nextAction, msgs);
21970
+ transport.close();
21971
+ if (opts.human) {
21972
+ info(String(content2.content_hint));
21973
+ if (msgs.length === 0) {
21974
+ info("No new messages.");
21975
+ } else {
21976
+ for (const msg of msgs) {
21977
+ formatMessageHuman(msg, jobId, artifactSession);
21978
+ }
21979
+ finalizeProgressLine();
21980
+ }
21981
+ printNextActionHuman(resolvedAction2, { refunds });
21982
+ } else {
21983
+ json({
21984
+ jobId,
21985
+ ...content2,
21986
+ messages: msgs.map(serialize),
21987
+ cursor: newCursor,
21988
+ next_action: resolvedAction2,
21989
+ ...await refundJsonField(refunds)
21990
+ });
21991
+ }
21992
+ return;
21993
+ }
21994
+ progressNotice("Streaming messages...", opts.human);
21995
+ const streamOptions = {
21996
+ jobId,
21997
+ transport,
21998
+ provider: ref,
21999
+ policy: stored?.policy ?? void 0,
22000
+ afterSeq: after,
22001
+ afterSeqExplicit: opts.after !== void 0,
22002
+ jobToken,
22003
+ persistLocalState: !access.endpointOverridden,
22004
+ timeoutMs: opts.timeout ? Number(opts.timeout) * 1e3 : opts.wait ? 6e4 : 5e3,
22005
+ ...opts.human && {
22006
+ onMessage: (msg) => {
22007
+ if (msg.type === "progress") formatMessageHuman(msg);
22008
+ }
22009
+ }
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
+ }
22019
+ if (!access.endpointOverridden) {
22020
+ persistStreamOutcome({
22021
+ jobId,
22022
+ messages: result.messages,
22023
+ cursor: result.cursor,
22024
+ afterSeq: after
22025
+ });
22026
+ }
22027
+ const content = jobContentFields(
22028
+ jobId,
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())),
22031
+ jobToken
22032
+ })
22033
+ );
22034
+ const resolvedAction = opts.wait ? result.nextAction : await resolveNextAction2(result.nextAction, result.messages);
22035
+ transport.close();
22036
+ if (opts.human) {
22037
+ info(String(content.content_hint));
22038
+ if (result.messages.length === 0) {
22039
+ info("No new messages.");
22040
+ } else {
22041
+ for (const msg of result.messages) {
22042
+ if (msg.type === "progress") continue;
22043
+ formatMessageHuman(msg, jobId, artifactSession);
22044
+ }
22045
+ finalizeProgressLine();
22046
+ }
22047
+ printNextActionHuman(resolvedAction, { refunds: result.refunds });
22048
+ } else {
22049
+ json({
22050
+ jobId,
22051
+ ...content,
22052
+ messages: result.messages.map(serialize),
22053
+ cursor: result.cursor,
22054
+ next_action: resolvedAction,
22055
+ ...result.autoPayments.length > 0 ? { auto_payments: result.autoPayments } : {},
22056
+ ...await refundJsonField(result.refunds)
22057
+ });
22115
22058
  }
22116
22059
  }
22117
22060
  function serializeMessageForOutput(msg) {
@@ -22137,6 +22080,7 @@ function serialize(msg) {
22137
22080
  };
22138
22081
  if (msg.content.options) content.options = msg.content.options;
22139
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;
22140
22084
  return { ...base, content, display };
22141
22085
  }
22142
22086
  case "artifact": {
@@ -22349,10 +22293,37 @@ async function payWithAccess(jobId, opts, access) {
22349
22293
  const { stored, ref, jobToken } = access;
22350
22294
  const msgs = loadMessages(jobId);
22351
22295
  const pending4 = stored.pendingCreditPayment;
22352
- const paymentMessage = findPendingPaymentRequest(msgs);
22353
- 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);
22354
22324
  const requestSeq = pending4?.authorization.request_seq ?? paymentMessage?.seq;
22355
22325
  if (!paymentReq) {
22326
+ transport.close();
22356
22327
  throw new DvmError(
22357
22328
  "no_payment_pending",
22358
22329
  "No pending payment request found for this job.",
@@ -22363,7 +22334,6 @@ async function payWithAccess(jobId, opts, access) {
22363
22334
  applyMintPin(paymentReq.mints ?? [], opts.mint);
22364
22335
  updateJob(jobId, { pinnedMint: opts.mint });
22365
22336
  }
22366
- const transport = createDvmTransport();
22367
22337
  if (!stored.policy) {
22368
22338
  throw new DvmError(
22369
22339
  "no_budget",
@@ -22379,7 +22349,9 @@ async function payWithAccess(jobId, opts, access) {
22379
22349
  jobToken,
22380
22350
  rail,
22381
22351
  maxCashuPrincipalSats,
22382
- requestSeq
22352
+ requestSeq,
22353
+ approval: "explicit",
22354
+ creditRecoveryOnly: pending4 !== void 0
22383
22355
  });
22384
22356
  if (result === "over-budget") {
22385
22357
  transport.close();
@@ -22511,16 +22483,6 @@ function parsePositiveCashuSats(raw2) {
22511
22483
  }
22512
22484
  return value;
22513
22485
  }
22514
- function findPendingPaymentRequest(msgs) {
22515
- for (let i = msgs.length - 1; i >= 0; i--) {
22516
- const msg = msgs[i];
22517
- if (msg.type === "payment") return void 0;
22518
- if (msg.type === "payment-request") {
22519
- return { content: msg.content, seq: msg.seq };
22520
- }
22521
- }
22522
- return void 0;
22523
- }
22524
22486
 
22525
22487
  // src/lib/data-flag.ts
22526
22488
  async function resolveDataFlag(raw2) {
@@ -22616,7 +22578,7 @@ function jsonParseErrorLine(jsonText, err) {
22616
22578
  // src/lib/structured-input-hint.ts
22617
22579
  function expectedFieldsFromSchema(schema) {
22618
22580
  const props = schema.properties;
22619
- if (!isPlainObject2(props)) return [];
22581
+ if (!isPlainObject(props)) return [];
22620
22582
  const requiredList = Array.isArray(schema.required) ? schema.required.filter((x) => typeof x === "string") : [];
22621
22583
  const required = new Set(requiredList);
22622
22584
  const out = [];
@@ -22657,11 +22619,11 @@ function buildStructuredInputHint(opts) {
22657
22619
  if (nextAction) data.next_action = nextAction;
22658
22620
  return { message: message2, hint, data };
22659
22621
  }
22660
- function isPlainObject2(value) {
22622
+ function isPlainObject(value) {
22661
22623
  return typeof value === "object" && value !== null && !Array.isArray(value);
22662
22624
  }
22663
22625
  function jsonSchemaType(node) {
22664
- if (!isPlainObject2(node)) return "unknown";
22626
+ if (!isPlainObject(node)) return "unknown";
22665
22627
  const t = node.type;
22666
22628
  if (typeof t === "string") return t;
22667
22629
  if (Array.isArray(t)) return t.filter((x) => typeof x === "string").join("|") || "unknown";
@@ -22739,16 +22701,16 @@ function findInputSchema(info2, capability) {
22739
22701
  if (capability) {
22740
22702
  const cap2 = info2.capabilities?.[capability];
22741
22703
  if (cap2) {
22742
- if (isPlainObject3(cap2.input_schema)) return cap2.input_schema;
22743
- const quote2 = isPlainObject3(cap2.pricing) ? cap2.pricing.quote : void 0;
22744
- if (isPlainObject3(quote2) && isPlainObject3(quote2.schema)) return quote2.schema;
22704
+ if (isPlainObject2(cap2.input_schema)) return cap2.input_schema;
22705
+ const quote2 = isPlainObject2(cap2.pricing) ? cap2.pricing.quote : void 0;
22706
+ if (isPlainObject2(quote2) && isPlainObject2(quote2.schema)) return quote2.schema;
22745
22707
  }
22746
22708
  }
22747
- if (isPlainObject3(info2.inputSchema)) return info2.inputSchema;
22748
- if (info2.quote && isPlainObject3(info2.quote.schema)) return info2.quote.schema;
22709
+ if (isPlainObject2(info2.inputSchema)) return info2.inputSchema;
22710
+ if (info2.quote && isPlainObject2(info2.quote.schema)) return info2.quote.schema;
22749
22711
  return void 0;
22750
22712
  }
22751
- function isPlainObject3(value) {
22713
+ function isPlainObject2(value) {
22752
22714
  return typeof value === "object" && value !== null && !Array.isArray(value);
22753
22715
  }
22754
22716
 
@@ -23063,6 +23025,9 @@ function railList(keys, isKnown, label) {
23063
23025
  }
23064
23026
 
23065
23027
  // src/commands/receipts.ts
23028
+ import { createHash as createHash3 } from "crypto";
23029
+ import { createReadStream } from "fs";
23030
+ import { open, stat } from "fs/promises";
23066
23031
  var DEFAULT_LIMIT2 = 50;
23067
23032
  function receiptsList(opts) {
23068
23033
  const limit = resolveLimit2(opts.limit);
@@ -23108,6 +23073,9 @@ Endpoint: ${entry.endpoint || "(unknown)"}`);
23108
23073
  });
23109
23074
  }
23110
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
+ }
23111
23079
  const entry = requireStored(jobId);
23112
23080
  const builder = opts.endpoint ? await refetchAnchor(opts.endpoint) : entry.builder ?? loadJob(jobId)?.builderAnchor;
23113
23081
  const delivered = deliveredFromMessages(jobId, entry.receipt);
@@ -23117,9 +23085,15 @@ async function receiptsVerify(jobId, opts) {
23117
23085
  expectedJobId: jobId,
23118
23086
  delivered
23119
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;
23120
23090
  const rate = getLastKnownBtcRate()?.rate ?? 0;
23121
23091
  if (opts.human) {
23122
23092
  renderVerdictHuman(entry, result, rate);
23093
+ for (const file of files) {
23094
+ info(`${file.path}: ${file.display}`);
23095
+ info(` ${file.hint}`);
23096
+ }
23123
23097
  info(`
23124
23098
  Signature: ${result.checks.signature ? "valid" : "INVALID"}`);
23125
23099
  info(`Attestation: ${result.checks.attestation}`);
@@ -23129,10 +23103,90 @@ Signature: ${result.checks.signature ? "valid" : "INVALID"}`);
23129
23103
  }
23130
23104
  json({
23131
23105
  ...storedReceiptJson(entry, result, rate),
23106
+ ...opts.file?.length ? { files } : {},
23132
23107
  anchor_source: opts.endpoint ? "refetched" : "stored",
23133
23108
  hint: receiptHint(result.status, jobId)
23134
23109
  });
23135
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
+ }
23136
23190
  function receiptsExport(opts) {
23137
23191
  for (const entry of filterReceipts(loadReceipts(), opts)) {
23138
23192
  raw(JSON.stringify(entry));
@@ -23276,7 +23330,7 @@ function buildPolicy(opts, btcRate) {
23276
23330
  }
23277
23331
 
23278
23332
  // src/commands/request.ts
23279
- import { createHash as createHash3, randomUUID as randomUUID5 } from "crypto";
23333
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "crypto";
23280
23334
 
23281
23335
  // src/lib/credit-defer.ts
23282
23336
  function noteDeferredFunding(funding) {
@@ -23309,10 +23363,27 @@ async function settleCreditAfterJob(args) {
23309
23363
  }
23310
23364
  }
23311
23365
  if (args.allowTopup !== false) {
23312
- const refill = args.refillPocket ?? (await import("./pocket-refill-J3BME4O3.js")).refillPocketIfLow;
23366
+ const refill = args.refillPocket ?? (await import("./pocket-refill-3ZV36DOA.js")).refillPocketIfLow;
23313
23367
  await refill({ human: args.human }).catch(() => void 0);
23314
23368
  }
23315
23369
  }
23370
+ async function settleCreditAfterRead(args) {
23371
+ const { job, capture } = args;
23372
+ const binding = job.creditBinding;
23373
+ const receipt = capture.receipt;
23374
+ if (job.strictPerCall || !binding || "unbound" in binding || !receipt?.credit || receipt.job_id !== job.id || receipt.requester_pubkey !== binding.callerPubkey || receipt.credit.credit_id !== binding.creditId || receipt.credit.draw_id !== binding.drawId || receipt.credit.credit_id.startsWith("imp:")) return;
23375
+ const builder = loadJob(job.id)?.builderAnchor ?? job.builderAnchor;
23376
+ await settleCreditAfterJob({
23377
+ capture,
23378
+ transport: args.transport,
23379
+ ref: { endpoint: job.endpoint },
23380
+ dvmId: job.dvmId,
23381
+ providerInfo: builder ? { builder } : void 0,
23382
+ callerPubkey: binding.callerPubkey,
23383
+ allowTopup: false,
23384
+ human: args.human
23385
+ });
23386
+ }
23316
23387
  function settleIdentity(args) {
23317
23388
  return providerDvmIdentity(args.providerInfo);
23318
23389
  }
@@ -23330,15 +23401,13 @@ function noticeDvm(args) {
23330
23401
  async function settle(args) {
23331
23402
  const receipt = args.capture?.receipt;
23332
23403
  const credit = receipt?.credit;
23333
- if (!receipt || !credit || !args.signing) return;
23404
+ const callerPubkey = args.signing?.pubkey ?? args.callerPubkey;
23405
+ if (!receipt || !credit || !callerPubkey || args.capture?.status !== "verified" && args.capture?.status !== "verified_unattested" || receipt.requester_pubkey !== callerPubkey) return;
23334
23406
  if (credit.credit_id.startsWith("imp:")) {
23335
- if (args.capture?.status !== "verified" && args.capture?.status !== "verified_unattested" || receipt.requester_pubkey !== args.signing.pubkey) {
23336
- return;
23337
- }
23338
23407
  const applied2 = applyImplicitReceiptCredit({
23339
23408
  endpoint: args.ref.endpoint,
23340
23409
  ...settleIdentityArgs(args),
23341
- callerPubkey: args.signing.pubkey,
23410
+ callerPubkey,
23342
23411
  jobId: receipt.job_id,
23343
23412
  outcome: receipt.outcome,
23344
23413
  credit,
@@ -23351,16 +23420,17 @@ async function settle(args) {
23351
23420
  const applied = applyReceiptCredit({
23352
23421
  endpoint: args.ref.endpoint,
23353
23422
  ...settleIdentityArgs(args),
23354
- callerPubkey: args.signing.pubkey,
23423
+ callerPubkey,
23355
23424
  jobId: receipt.job_id,
23356
23425
  outcome: receipt.outcome,
23357
- credit
23426
+ credit,
23427
+ drawFundings: jobDrawFundings(receipt.job_id, args.ref.endpoint, callerPubkey, credit)
23358
23428
  });
23359
23429
  if (!applied.credit) return;
23360
23430
  if (applied.mismatch) {
23361
23431
  renderBalanceMismatch(args.ref.endpoint, applied.mismatch);
23362
23432
  }
23363
- if (args.allowTopup === false) return;
23433
+ if (args.allowTopup === false || !args.signing) return;
23364
23434
  if (receipt.outcome !== "completed") return;
23365
23435
  const record = applied.credit;
23366
23436
  if (record.status !== "active") return;
@@ -23789,17 +23859,18 @@ function dollarLimitMicro(declaredLimit) {
23789
23859
  }
23790
23860
 
23791
23861
  // src/lib/request-intent-store.ts
23862
+ var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
23792
23863
  import {
23793
- closeSync as closeSync5,
23794
- existsSync as existsSync8,
23795
- fsyncSync as fsyncSync3,
23864
+ closeSync as closeSync3,
23865
+ existsSync as existsSync7,
23866
+ fsyncSync,
23796
23867
  mkdirSync as mkdirSync2,
23797
- openSync as openSync5,
23798
- readFileSync as readFileSync9,
23799
- renameSync as renameSync3,
23800
- writeFileSync as writeFileSync6
23868
+ openSync as openSync3,
23869
+ readFileSync as readFileSync7,
23870
+ renameSync as renameSync2,
23871
+ writeFileSync as writeFileSync4
23801
23872
  } from "fs";
23802
- import { join as join9 } from "path";
23873
+ import { join as join8 } from "path";
23803
23874
  function saveRequestIntent(intent) {
23804
23875
  assertRequestId(intent.requestId);
23805
23876
  assertNoPaymentOrAuthSecrets(intent.body);
@@ -23811,27 +23882,27 @@ function saveRequestIntent(intent) {
23811
23882
  if (error.code === "EEXIST") return false;
23812
23883
  throw error;
23813
23884
  }
23814
- fsyncDirectory3(REQUEST_INTENTS_DIR);
23815
- const temp = join9(dir, `intent.${String(process.pid)}.tmp`);
23816
- const target = join9(dir, "intent.json");
23817
- const fd = openSync5(temp, "wx", 384);
23885
+ fsyncDirectory(REQUEST_INTENTS_DIR);
23886
+ const temp = join8(dir, `intent.${String(process.pid)}.tmp`);
23887
+ const target = join8(dir, "intent.json");
23888
+ const fd = openSync3(temp, "wx", 384);
23818
23889
  try {
23819
- writeFileSync6(fd, JSON.stringify(intent, null, 2) + "\n");
23820
- fsyncSync3(fd);
23890
+ writeFileSync4(fd, JSON.stringify(intent, null, 2) + "\n");
23891
+ fsyncSync(fd);
23821
23892
  } finally {
23822
- closeSync5(fd);
23893
+ closeSync3(fd);
23823
23894
  }
23824
- renameSync3(temp, target);
23825
- fsyncDirectory3(dir);
23895
+ renameSync2(temp, target);
23896
+ fsyncDirectory(dir);
23826
23897
  return true;
23827
23898
  }
23828
23899
  function loadRequestIntent(requestId) {
23829
23900
  assertRequestId(requestId);
23830
23901
  const dir = intentDirectory(requestId);
23831
- if (!existsSync8(dir)) return null;
23832
- const path = join9(dir, "intent.json");
23902
+ if (!existsSync7(dir)) return null;
23903
+ const path = join8(dir, "intent.json");
23833
23904
  try {
23834
- const parsed = JSON.parse(readFileSync9(path, "utf8"));
23905
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
23835
23906
  if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
23836
23907
  throw new Error("invalid shape");
23837
23908
  return parsed;
@@ -23844,6 +23915,31 @@ function loadRequestIntent(requestId) {
23844
23915
  );
23845
23916
  }
23846
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
+ }
23847
23943
  function assertNoPaymentOrAuthSecrets(body) {
23848
23944
  if (!containsForbiddenSecret(body)) return;
23849
23945
  throw new DvmError(
@@ -23881,15 +23977,16 @@ function assertRequestId(requestId) {
23881
23977
  );
23882
23978
  }
23883
23979
  function intentDirectory(requestId) {
23884
- return join9(REQUEST_INTENTS_DIR, requestId);
23980
+ return join8(REQUEST_INTENTS_DIR, requestId);
23885
23981
  }
23886
- function fsyncDirectory3(path) {
23982
+ function fsyncDirectory(path) {
23983
+ if (process.platform === "win32") return;
23887
23984
  let fd;
23888
23985
  try {
23889
- fd = openSync5(path, "r");
23890
- fsyncSync3(fd);
23986
+ fd = openSync3(path, "r");
23987
+ fsyncSync(fd);
23891
23988
  } finally {
23892
- if (fd !== void 0) closeSync5(fd);
23989
+ if (fd !== void 0) closeSync3(fd);
23893
23990
  }
23894
23991
  }
23895
23992
  function isRequestIntent(value) {
@@ -24409,7 +24506,7 @@ async function request(opts) {
24409
24506
  probePlan = { ...probePlan, drawId: opts.requestId };
24410
24507
  }
24411
24508
  if (probePlan.mode === "draw" && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing })) {
24412
- drawRequestId = randomUUID5();
24509
+ drawRequestId = randomUUID4();
24413
24510
  }
24414
24511
  const probeData = probePlan.mode === "draw" ? {
24415
24512
  ...unsignedData,
@@ -24578,7 +24675,7 @@ async function request(opts) {
24578
24675
  outputCollectedQuotes(receipt.jobId || null, quotes, opts, identity, void 0, action);
24579
24676
  return;
24580
24677
  }
24581
- saveJob({
24678
+ saveSubmittedJob({
24582
24679
  id: receipt.jobId,
24583
24680
  ...transactionRecordFields(receipt),
24584
24681
  endpoint,
@@ -24594,7 +24691,7 @@ async function request(opts) {
24594
24691
  ...requestedMaxCashuFeeSats !== void 0 ? { maxCashuFeeSats: requestedMaxCashuFeeSats } : {},
24595
24692
  // the job cleared by drawing on a prepaid credit — no payment
24596
24693
  // attach, no budget-ledger entry (the funding already counted).
24597
- ...probePlan.mode === "draw" ? { paymentMethod: "credit" } : {},
24694
+ ...probePlan.mode === "draw" ? { paymentMethod: "credit" } : { upfrontRailPayment: "free" },
24598
24695
  ...signing ? { creditBinding: probePlan.mode === "draw" ? { creditId: probePlan.creditId, drawId: probePlan.drawId, callerPubkey: signing.pubkey } : { unbound: true, callerPubkey: signing.pubkey } } : {},
24599
24696
  // persist the anonymous-flow per-job token so subsequent
24600
24697
  // status/messages/pay/cancel commands can present it as `X-Job-Token`.
@@ -24607,11 +24704,15 @@ async function request(opts) {
24607
24704
  ...receiptTrustFields(providerInfo),
24608
24705
  ...localCorrelationJobFields(localCorrelationId)
24609
24706
  });
24707
+ recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment);
24610
24708
  if (noStream) {
24611
24709
  transport.close();
24612
24710
  if (opts.human) {
24613
24711
  info(`Job published: ${receipt.jobId}`);
24614
24712
  echoTraceIdHuman();
24713
+ if (!isTerminalJobStatus(receipt.status)) {
24714
+ printNextActionHuman(pollNextAction(receipt.jobId, "Job submitted, check back for updates"));
24715
+ }
24615
24716
  } else {
24616
24717
  json({
24617
24718
  jobId: receipt.jobId,
@@ -24739,8 +24840,8 @@ async function request(opts) {
24739
24840
  }
24740
24841
  if (captured) renderReceiptHuman(captured);
24741
24842
  finalizeProgressLine();
24742
- printRefundSummaryHuman(result.refunds);
24743
24843
  echoTraceIdHuman();
24844
+ printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: isTerminalJobStatus(receipt.status) || !!streamTerminalStatus(result.messages) });
24744
24845
  } else {
24745
24846
  json({
24746
24847
  jobId: receipt.jobId,
@@ -24813,7 +24914,7 @@ function identityArgs(identity) {
24813
24914
  return identity ? { identity } : {};
24814
24915
  }
24815
24916
  function sha256Hex(value) {
24816
- return createHash3("sha256").update(value, "utf8").digest("hex");
24917
+ return createHash4("sha256").update(value, "utf8").digest("hex");
24817
24918
  }
24818
24919
  async function fetchServerPriceMicro(transport, ref, envelope) {
24819
24920
  try {
@@ -24966,14 +25067,14 @@ async function recoverDrawProbe(err, args) {
24966
25067
  const plan = {
24967
25068
  mode: "draw",
24968
25069
  creditId: args.probePlan.creditId,
24969
- drawId: randomUUID5(),
25070
+ drawId: randomUUID4(),
24970
25071
  ...args.probePlan.source ? { source: args.probePlan.source } : {}
24971
25072
  };
24972
25073
  const requestId = submitCanCarryGeneratedRequestId({
24973
25074
  opts: args.opts,
24974
25075
  providerInfo: args.providerInfo,
24975
25076
  signing
24976
- }) ? randomUUID5() : void 0;
25077
+ }) ? randomUUID4() : void 0;
24977
25078
  const env = reSign({
24978
25079
  credit_id: plan.creditId,
24979
25080
  draw_id: plan.drawId,
@@ -25282,7 +25383,7 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
25282
25383
  let railSigning = creditCtx?.signing;
25283
25384
  let generatedRequestId;
25284
25385
  if (plan.mode === "none" && railSigning && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing: railSigning })) {
25285
- generatedRequestId = randomUUID5();
25386
+ generatedRequestId = randomUUID4();
25286
25387
  railSigning = {
25287
25388
  ...railSigning,
25288
25389
  unsignedData: { ...railSigning.unsignedData, request_id: generatedRequestId }
@@ -25516,6 +25617,7 @@ async function payWithTempo(args, credential) {
25516
25617
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
25517
25618
  const usdcMicroUnits = Number(tempoCredentialAmountMicro(credential));
25518
25619
  const paidMsats = usdcToMsats(usdcMicroUnits / 1e6, btcRate);
25620
+ if (opts.requestId) recordRequestRailPayment(opts.requestId, { method: "tempo", amountMsats: paidMsats });
25519
25621
  const usd2 = usdcMicroUnits / 1e6;
25520
25622
  const priceLabel = `$${formatUsd(usd2)} USDC`;
25521
25623
  const accountShort = `${account.address.slice(0, 6)}\u2026${account.address.slice(-4)}`;
@@ -25610,7 +25712,7 @@ async function payWithTempo(args, credential) {
25610
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)}` : ""}`
25611
25713
  );
25612
25714
  }
25613
- addPayment(effectiveJobId, paidMsats);
25715
+ recordUpfrontRailPayment(effectiveJobId, { method: "tempo", amountMsats: paidMsats }, true);
25614
25716
  recordSpend({
25615
25717
  msats: paidMsats,
25616
25718
  btcRate: args.btcRate,
@@ -25761,7 +25863,7 @@ function recordUnconfirmedSpend(args) {
25761
25863
  recordSpendOnce({
25762
25864
  msats: args.msats,
25763
25865
  btcRate: args.btcRate,
25764
- jobId: args.key ?? `unconfirmed-${randomUUID5()}`,
25866
+ jobId: args.key ?? `unconfirmed-${randomUUID4()}`,
25765
25867
  providerEndpoint: args.endpoint,
25766
25868
  label: `unconfirmed \xB7 ${args.capability}`
25767
25869
  });
@@ -25849,6 +25951,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
25849
25951
  const priceSats = Math.ceil(chosen.priceMsats / 1e3);
25850
25952
  const maxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
25851
25953
  const baseContext = {
25954
+ upfront_rail_payment: { method: "cashu", amountMsats: chosen.priceMsats },
25852
25955
  dvm_id: identity.dvmId,
25853
25956
  capability: identity.capability,
25854
25957
  pinned_mint: opts.mint,
@@ -25869,7 +25972,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
25869
25972
  builderHandle = void 0;
25870
25973
  }
25871
25974
  const spendStartedMs = Date.now();
25872
- const generatedRequestId = fundPlan && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing }) ? randomUUID5() : void 0;
25975
+ const generatedRequestId = fundPlan && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing }) ? randomUUID4() : void 0;
25873
25976
  const withGeneratedRequestId = (unsigned) => generatedRequestId ? { ...unsigned, request_id: generatedRequestId } : unsigned;
25874
25977
  const perCallEnvelope = generatedRequestId && signing ? {
25875
25978
  ...envelope,
@@ -25976,6 +26079,8 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
25976
26079
  providerInfo
25977
26080
  });
25978
26081
  }
26082
+ const pricedRequestId = opts.requestId ?? generatedRequestId;
26083
+ if (pricedRequestId) recordRequestRailPayment(pricedRequestId, { method: "cashu", amountMsats: chosen.priceMsats });
25979
26084
  if (fundPlan && signing) {
25980
26085
  ensureProvisionalCredit({
25981
26086
  endpoint: ref.endpoint,
@@ -26254,7 +26359,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
26254
26359
  }
26255
26360
  });
26256
26361
  await collectCashuChange(effectiveJobId, receipt.cashuChange);
26257
- addPayment(effectiveJobId, chosen.priceMsats);
26362
+ recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
26258
26363
  if (fundPlan) {
26259
26364
  recordSpend({
26260
26365
  msats: fundPlan.fundMsats,
@@ -26379,6 +26484,7 @@ async function tryX402UpfrontPayment(args) {
26379
26484
  }
26380
26485
  async function payWithX402(args, proof) {
26381
26486
  const { transport, ref, envelope, chosen, opts, identity, policy, wallet } = args;
26487
+ if (opts.requestId) recordRequestRailPayment(opts.requestId, { method: "x402", amountMsats: proof.amountMsats });
26382
26488
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
26383
26489
  const usdcMicroUnits = Number(proof.amountUsdcMicro);
26384
26490
  const usd2 = usdcMicroUnits / 1e6;
@@ -26463,7 +26569,7 @@ async function payWithX402(args, proof) {
26463
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."
26464
26570
  );
26465
26571
  }
26466
- addPayment(effectiveJobId, proof.amountMsats);
26572
+ recordUpfrontRailPayment(effectiveJobId, { method: "x402", amountMsats: proof.amountMsats }, true);
26467
26573
  recordSpend({
26468
26574
  msats: proof.amountMsats,
26469
26575
  btcRate: proof.btcRate,
@@ -26552,19 +26658,6 @@ async function streamToCompletion(baseOpts, deadlineMs) {
26552
26658
  const allMessages = [...result.messages];
26553
26659
  const allAutoPayments = [...result.autoPayments];
26554
26660
  const allRefunds = [...result.refunds];
26555
- if (result.messages.length === 0 && result.nextAction === null) {
26556
- return {
26557
- messages: allMessages,
26558
- autoPayments: allAutoPayments,
26559
- refunds: allRefunds,
26560
- nextAction: {
26561
- type: "poll",
26562
- job_id: baseOpts.jobId,
26563
- hint: "Provider hasn't yielded yet, check back later"
26564
- },
26565
- cursor: result.cursor
26566
- };
26567
- }
26568
26661
  while (result.nextAction?.type === "poll") {
26569
26662
  if (Date.now() >= deadlineMs) break;
26570
26663
  const waitMs = Math.min(
@@ -26665,8 +26758,13 @@ async function streamAfterPayment(args) {
26665
26758
  strictPerCall: args.strictPerCall
26666
26759
  });
26667
26760
  if (recovered) return;
26761
+ const nextAction = pollNextAction(
26762
+ jobId,
26763
+ `Payment sent but the result stream timed out. ${pollNextAction(jobId).hint}`
26764
+ );
26668
26765
  if (human) {
26669
26766
  info(paidTimeoutMessage);
26767
+ printNextActionHuman(nextAction);
26670
26768
  } else {
26671
26769
  json({
26672
26770
  jobId,
@@ -26678,10 +26776,7 @@ async function streamAfterPayment(args) {
26678
26776
  // not the job. `poll`, not `null`: the result is still coming.
26679
26777
  ...takeCreditNoticeFields(),
26680
26778
  ...takeFeedbackNoticeFields(),
26681
- next_action: pollNextAction(
26682
- jobId,
26683
- "Payment sent but the result stream timed out. The job is still running \u2014 check back with 'dvm status'."
26684
- )
26779
+ next_action: nextAction
26685
26780
  });
26686
26781
  }
26687
26782
  throw new DvmError("timeout", paidTimeoutMessage);
@@ -26697,7 +26792,7 @@ async function streamAfterPayment(args) {
26697
26792
  }
26698
26793
  if (captured) renderReceiptHuman(captured);
26699
26794
  finalizeProgressLine();
26700
- printRefundSummaryHuman(result.refunds);
26795
+ printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: !!streamTerminalStatus(result.messages) });
26701
26796
  } else {
26702
26797
  json({
26703
26798
  jobId,
@@ -26940,12 +27035,20 @@ async function requestResult(requestId, opts = {}) {
26940
27035
  pinnedMint: intent.pinnedMint,
26941
27036
  strictPerCall: intent.strictPerCall,
26942
27037
  maxCashuFeeSats: intent.maxCashuFeeSats,
26943
- paymentMethod: paymentMethod(receipt),
27038
+ paymentMethod: creditBinding && !originalData?.fund ? "credit" : intent.railPayment?.method ?? paymentMethod(receipt),
26944
27039
  receiptsSupported: intent.receiptsSupported,
26945
27040
  builderAnchor: intent.builderAnchor,
26946
27041
  ...restored
26947
27042
  });
26948
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);
26949
27052
  if (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled") {
26950
27053
  markJobTerminal(receipt.jobId, receipt.status, completionSnapshot(receipt), restored);
26951
27054
  } else {
@@ -26955,6 +27058,10 @@ async function requestResult(requestId, opts = {}) {
26955
27058
  });
26956
27059
  }
26957
27060
  const captured = captureTransportReceipt(receipt.jobId, receipt);
27061
+ const recovered = loadJob(receipt.jobId);
27062
+ if (recovered && (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled")) {
27063
+ await settleCreditAfterRead({ job: recovered, capture: captured, transport, human: opts.human });
27064
+ }
26958
27065
  const confirmed = await bookRecoveredSubmissions({
26959
27066
  publicRequestId: requestId,
26960
27067
  endpoint: intent.endpoint,
@@ -27255,6 +27362,99 @@ function outputResults2(resultJson, human, nextAction) {
27255
27362
  }
27256
27363
  }
27257
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
+
27258
27458
  // src/commands/status.ts
27259
27459
  async function status(jobId, opts) {
27260
27460
  const access = resolveJobAccess(jobId, opts);
@@ -27264,8 +27464,8 @@ async function statusWithAccess(jobId, opts, access) {
27264
27464
  const { stored, ref, jobToken } = access;
27265
27465
  if (stored && !access.overridden && isTerminalJobStatus(stored.status) && stored.completion && !opts.messages) {
27266
27466
  let receipt2 = replayStoredReceipt(stored);
27467
+ const transport2 = createDvmTransport();
27267
27468
  if (stored.receiptsSupported && receipt2.status === "absent") {
27268
- const transport2 = createDvmTransport();
27269
27469
  const fetched = await fetchMissingJobReceipt(jobId, transport2, ref);
27270
27470
  if (fetched.receipt || fetched.receiptParseError) {
27271
27471
  if (fetched.receipt && !stored.builderAnchor) {
@@ -27273,8 +27473,9 @@ async function statusWithAccess(jobId, opts, access) {
27273
27473
  }
27274
27474
  receipt2 = captureTransportReceipt(jobId, fetched);
27275
27475
  }
27276
- transport2.close();
27277
27476
  }
27477
+ await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
27478
+ transport2.close();
27278
27479
  renderStatus(jobId, stored, stored.status, stored.completion, "local", null, opts, {
27279
27480
  receipt: receipt2
27280
27481
  });
@@ -27284,6 +27485,7 @@ async function statusWithAccess(jobId, opts, access) {
27284
27485
  const transport = createDvmTransport();
27285
27486
  progressNotice("Checking job status...", opts.human);
27286
27487
  const result = await transport.status(jobId, ref, { timeoutMs: timeout, jobToken });
27488
+ if (stored && !access.endpointOverridden) captureDrawFundingReceipts(jobId, result.drawFundingReceipts, { endpoint: ref.endpoint });
27287
27489
  let msgs = [];
27288
27490
  let newCursor;
27289
27491
  if (opts.messages) {
@@ -27309,6 +27511,9 @@ async function statusWithAccess(jobId, opts, access) {
27309
27511
  await backfillTrustAnchor(jobId, transport, ref);
27310
27512
  }
27311
27513
  receipt = stored && !access.endpointOverridden ? captureTransportReceipt(jobId, result) : transientReceiptCapture(jobId, result);
27514
+ if (stored && !access.endpointOverridden) {
27515
+ await settleCreditAfterRead({ job: stored, capture: receipt, transport, human: opts.human });
27516
+ }
27312
27517
  if (stored && !access.endpointOverridden && !isTerminalJobStatus(stored.status)) {
27313
27518
  noteFeedbackAfterTerminal({
27314
27519
  jobId,
@@ -27360,6 +27565,7 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
27360
27565
  const msgs = fetched?.msgs ?? [];
27361
27566
  const receipt = fetched?.receipt;
27362
27567
  const content = jobContentFields(jobId, fetched?.content);
27568
+ const spend = stored ? jobSpend(loadJob(jobId) ?? stored, receipt?.receipt) : void 0;
27363
27569
  if (opts.human) {
27364
27570
  if (jobStatus === "completed" && completion.summary) {
27365
27571
  info(`Summary:`);
@@ -27370,17 +27576,18 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
27370
27576
  }
27371
27577
  if (jobStatus === "completed" && hint) info(`\u{1F4CE} ${hint}`);
27372
27578
  info(String(content.content_hint));
27373
- if (receipt) renderReceiptHuman(receipt);
27374
27579
  if (msgs.length > 0) {
27375
27580
  info(`
27376
27581
  ${msgs.length} new message(s):`);
27377
- for (const msg of msgs) {
27378
- const prefix = msg.from === "provider" ? "Provider" : "You";
27379
- info(` [${msg.seq}] ${prefix} [${msg.type}]: ${JSON.stringify(msg.content)}`);
27380
- }
27582
+ const artifactSession = createArtifactSaveSession();
27583
+ for (const msg of msgs) formatMessageHuman(msg, jobId, artifactSession);
27584
+ finalizeProgressLine();
27381
27585
  }
27382
27586
  const traceId = getOutputTraceId();
27383
27587
  if (traceId) info(`Trace: ${traceId}`);
27588
+ if (spend) renderSpendHuman(spend, info);
27589
+ if (receipt) renderReceiptHuman(receipt);
27590
+ printNextActionHuman(nextAction);
27384
27591
  return;
27385
27592
  }
27386
27593
  const output = {
@@ -27401,6 +27608,7 @@ ${msgs.length} new message(s):`);
27401
27608
  // do. Both spread blind and are absent when nothing was stashed.
27402
27609
  ...takeCreditNoticeFields(),
27403
27610
  ...takeFeedbackNoticeFields(),
27611
+ ...spend ? { spend } : {},
27404
27612
  next_action: nextAction
27405
27613
  };
27406
27614
  if (opts.messages) {
@@ -27421,19 +27629,19 @@ async function resolveNextAction(jobId, status2, fetched, transport, ref, opts)
27421
27629
  }
27422
27630
 
27423
27631
  // src/commands/upload.ts
27424
- import { statSync as statSync6 } from "fs";
27632
+ import { statSync as statSync5 } from "fs";
27425
27633
 
27426
27634
  // src/lib/upload-stream.ts
27427
- import { createHash as createHash4 } from "crypto";
27428
- import { createReadStream } from "fs";
27635
+ import { createHash as createHash5 } from "crypto";
27636
+ import { createReadStream as createReadStream2 } from "fs";
27429
27637
  import * as http2 from "http";
27430
27638
  import * as https from "https";
27431
27639
  var UPLOAD_RESPONSE_MAX_BYTES = 64 * 1024;
27432
27640
  function hashFile(filePath) {
27433
27641
  return new Promise((resolve3, reject) => {
27434
- const hasher = createHash4("sha256");
27642
+ const hasher = createHash5("sha256");
27435
27643
  let sizeBytes = 0;
27436
- const stream = createReadStream(filePath);
27644
+ const stream = createReadStream2(filePath);
27437
27645
  stream.on("data", (chunk) => {
27438
27646
  const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
27439
27647
  sizeBytes += buf.byteLength;
@@ -27534,7 +27742,7 @@ function postOnce(opts, idleTimeoutMs) {
27534
27742
  req.destroy(new Error(`socket idle for ${idleTimeoutMs.toString()}ms`));
27535
27743
  });
27536
27744
  req.on("error", reject);
27537
- const body = createReadStream(opts.filePath);
27745
+ const body = createReadStream2(opts.filePath);
27538
27746
  body.on("error", (err) => {
27539
27747
  req.destroy(err);
27540
27748
  reject(err);
@@ -27644,7 +27852,7 @@ async function upload(dvmRef, opts) {
27644
27852
  const target = resolveUploadTarget(qualified?.slug ?? dvmId, kind);
27645
27853
  let sizeOnDisk;
27646
27854
  try {
27647
- const st = statSync6(opts.file);
27855
+ const st = statSync5(opts.file);
27648
27856
  if (!st.isFile()) {
27649
27857
  throw new DvmError(
27650
27858
  "invalid_argument",
@@ -27906,7 +28114,7 @@ function getRailOnramp(rail) {
27906
28114
  }
27907
28115
 
27908
28116
  // src/lib/secret-input.ts
27909
- import { fstatSync, readFileSync as readFileSync10, realpathSync } from "fs";
28117
+ import { fstatSync, readFileSync as readFileSync8, realpathSync } from "fs";
27910
28118
  import { homedir as homedir2 } from "os";
27911
28119
  import { resolve as resolve2, sep } from "path";
27912
28120
  var BLOCKED_SECRET_PATHS = [
@@ -27965,8 +28173,8 @@ function refusePositionalSecret(value, copy) {
27965
28173
  }
27966
28174
  function hasPipedStdin() {
27967
28175
  try {
27968
- const stat = fstatSync(0);
27969
- return stat.isFIFO() || stat.isFile();
28176
+ const stat2 = fstatSync(0);
28177
+ return stat2.isFIFO() || stat2.isFile();
27970
28178
  } catch {
27971
28179
  return false;
27972
28180
  }
@@ -27986,7 +28194,7 @@ function readSecretFile(path, config) {
27986
28194
  throw err;
27987
28195
  }
27988
28196
  assertSafeFilePath(real);
27989
- return readFileSync10(real, "utf-8").trim();
28197
+ return readFileSync8(real, "utf-8").trim();
27990
28198
  }
27991
28199
  function readSecretStdin(config) {
27992
28200
  return new Promise((resolveStdin, reject) => {
@@ -29682,7 +29890,7 @@ function mnemonicValidationError(result) {
29682
29890
  var import_qrcode = __toESM(require_lib(), 1);
29683
29891
  import { randomBytes as randomBytes3 } from "crypto";
29684
29892
  import { tmpdir as tmpdir2 } from "os";
29685
- import { join as join10 } from "path";
29893
+ import { join as join9 } from "path";
29686
29894
  async function renderQrTerminal(payload) {
29687
29895
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
29688
29896
  }
@@ -29695,7 +29903,7 @@ async function renderQrPng(payload, outPath) {
29695
29903
  });
29696
29904
  }
29697
29905
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
29698
- return join10(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
29906
+ return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
29699
29907
  }
29700
29908
 
29701
29909
  // src/lib/funding-handoff.ts
@@ -33251,7 +33459,7 @@ function resolveMppEndpoint(identifier) {
33251
33459
  }
33252
33460
 
33253
33461
  // src/commands/wallet-pair.ts
33254
- import { createHash as createHash5, randomBytes as randomBytes5 } from "crypto";
33462
+ import { createHash as createHash6, randomBytes as randomBytes5 } from "crypto";
33255
33463
  import { hostname } from "os";
33256
33464
 
33257
33465
  // node_modules/@noble/ciphers/_arx.js
@@ -34070,17 +34278,17 @@ function hexToBytes2(hex) {
34070
34278
  }
34071
34279
 
34072
34280
  // src/lib/wallet-pairing-store.ts
34073
- var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
34281
+ var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
34074
34282
  import {
34075
34283
  chmodSync as chmodSync2,
34076
- existsSync as existsSync9,
34077
- readdirSync as readdirSync6,
34078
- readFileSync as readFileSync11,
34079
- renameSync as renameSync4,
34080
- unlinkSync as unlinkSync5,
34081
- writeFileSync as writeFileSync7
34284
+ existsSync as existsSync8,
34285
+ readdirSync as readdirSync5,
34286
+ readFileSync as readFileSync9,
34287
+ renameSync as renameSync3,
34288
+ unlinkSync as unlinkSync3,
34289
+ writeFileSync as writeFileSync5
34082
34290
  } from "fs";
34083
- import { join as join11 } from "path";
34291
+ import { join as join10 } from "path";
34084
34292
  var pairingIdPattern = /^[0-9a-f]{64}$/;
34085
34293
  var stateSchema = external_exports.object({
34086
34294
  version: external_exports.literal(1),
@@ -34102,12 +34310,12 @@ var stateSchema = external_exports.object({
34102
34310
  function createWalletPairingState(state) {
34103
34311
  ensurePairingsDirectory();
34104
34312
  const path = pairingPath(state.pairing_id);
34105
- writeFileSync7(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
34313
+ writeFileSync5(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
34106
34314
  chmodSync2(path, 384);
34107
34315
  }
34108
34316
  function loadWalletPairingState(pairingId) {
34109
34317
  const path = pairingPath(pairingId);
34110
- if (!existsSync9(path)) {
34318
+ if (!existsSync8(path)) {
34111
34319
  throw new DvmError(
34112
34320
  "wallet_pairing_not_found",
34113
34321
  "No local state exists for that wallet pairing.",
@@ -34115,7 +34323,7 @@ function loadWalletPairingState(pairingId) {
34115
34323
  );
34116
34324
  }
34117
34325
  try {
34118
- return stateSchema.parse(JSON.parse(readFileSync11(path, "utf8")));
34326
+ return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34119
34327
  } catch {
34120
34328
  throw new DvmError(
34121
34329
  "wallet_pairing_state_invalid",
@@ -34129,13 +34337,13 @@ function saveWalletPairingState(state) {
34129
34337
  ensurePairingsDirectory();
34130
34338
  const path = pairingPath(state.pairing_id);
34131
34339
  const tmp = `${path}.tmp`;
34132
- writeFileSync7(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
34340
+ writeFileSync5(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
34133
34341
  try {
34134
- renameSync4(tmp, path);
34342
+ renameSync3(tmp, path);
34135
34343
  chmodSync2(path, 384);
34136
34344
  } catch (err) {
34137
34345
  try {
34138
- unlinkSync5(tmp);
34346
+ unlinkSync3(tmp);
34139
34347
  } catch {
34140
34348
  }
34141
34349
  throw err;
@@ -34144,21 +34352,21 @@ function saveWalletPairingState(state) {
34144
34352
  function deleteWalletPairingState(pairingId) {
34145
34353
  const path = pairingPath(pairingId);
34146
34354
  try {
34147
- unlinkSync5(path);
34355
+ unlinkSync3(path);
34148
34356
  } catch (err) {
34149
34357
  if (err.code !== "ENOENT") throw err;
34150
34358
  }
34151
34359
  }
34152
34360
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
34153
- if (!existsSync9(PAIRINGS_DIR)) return 0;
34361
+ if (!existsSync8(PAIRINGS_DIR)) return 0;
34154
34362
  let removed = 0;
34155
- for (const name of readdirSync6(PAIRINGS_DIR)) {
34363
+ for (const name of readdirSync5(PAIRINGS_DIR)) {
34156
34364
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
34157
- const path = join11(PAIRINGS_DIR, name);
34365
+ const path = join10(PAIRINGS_DIR, name);
34158
34366
  try {
34159
- const state = stateSchema.parse(JSON.parse(readFileSync11(path, "utf8")));
34367
+ const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34160
34368
  if (state.manifest.expires_at <= nowSeconds) {
34161
- unlinkSync5(path);
34369
+ unlinkSync3(path);
34162
34370
  removed += 1;
34163
34371
  }
34164
34372
  } catch {
@@ -34168,10 +34376,10 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
34168
34376
  }
34169
34377
  async function withWalletPairingLock(pairingId, fn) {
34170
34378
  const path = pairingPath(pairingId);
34171
- if (!existsSync9(path)) return fn();
34379
+ if (!existsSync8(path)) return fn();
34172
34380
  let release;
34173
34381
  try {
34174
- release = await import_proper_lockfile2.default.lock(path, {
34382
+ release = await import_proper_lockfile3.default.lock(path, {
34175
34383
  lockfilePath: `${path}.lock`,
34176
34384
  realpath: false,
34177
34385
  stale: 12 * 60 * 1e3,
@@ -34198,7 +34406,7 @@ function pairingPath(pairingId) {
34198
34406
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
34199
34407
  );
34200
34408
  }
34201
- return join11(PAIRINGS_DIR, `${pairingId}.json`);
34409
+ return join10(PAIRINGS_DIR, `${pairingId}.json`);
34202
34410
  }
34203
34411
  function ensurePairingsDirectory() {
34204
34412
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -34623,7 +34831,7 @@ function walletFingerprint(uri) {
34623
34831
  return uri ? sha2562(uri) : null;
34624
34832
  }
34625
34833
  function sha2562(value) {
34626
- return createHash5("sha256").update(value).digest("hex");
34834
+ return createHash6("sha256").update(value).digest("hex");
34627
34835
  }
34628
34836
  function relayHost2(relay) {
34629
34837
  try {
@@ -34751,12 +34959,12 @@ async function walletSubmissions(opts) {
34751
34959
  function listSubmissions(opts) {
34752
34960
  const listed = listSubmissionEvidence();
34753
34961
  const evidence = describeSubmissionEvidence(listed.records);
34754
- const unreadable2 = listed.unreadable;
34755
- const wallet = evidence.length > 0 || unreadable2.length > 0 ? loadAgentWallet() : loadWalletOrThrow();
34962
+ const unreadable = listed.unreadable;
34963
+ const wallet = evidence.length > 0 || unreadable.length > 0 ? loadAgentWallet() : loadWalletOrThrow();
34756
34964
  const summary = wallet ? describePendingSubmissions(wallet) : EMPTY_SUMMARY;
34757
34965
  if (opts.human) {
34758
34966
  printEvidenceHuman(evidence);
34759
- for (const file of unreadable2) {
34967
+ for (const file of unreadable) {
34760
34968
  info(`Unreadable evidence record (${file.cause}): ${file.path}. Restore it from a backup; do not pay again for any request it may describe.`);
34761
34969
  }
34762
34970
  if (summary.entries.length === 0) {
@@ -34811,17 +35019,17 @@ function listSubmissions(opts) {
34811
35019
  // Accepted without a settled job identity: held so nothing pays twice.
34812
35020
  accepted_unresolved_count: summary.accepted_unresolved_count,
34813
35021
  submission_evidence: evidence,
34814
- ...unreadable2.length > 0 ? { submission_evidence_unreadable: unreadable2 } : {},
35022
+ ...unreadable.length > 0 ? { submission_evidence_unreadable: unreadable } : {},
34815
35023
  display: [
34816
35024
  summary.entries.length === 0 ? "No unconfirmed payments." : `${summary.entries.length} unconfirmed payment(s), ${summary.at_risk_sats} sats spent but not yet confirmed by a provider.`,
34817
35025
  evidence.length > 0 ? `${evidence.length} paid call(s) were accepted without a clear job ID; see submission_evidence. None was paid for again.` : null,
34818
- unreadable2.length > 0 ? `${unreadable2.length} evidence record(s) cannot be read; see submission_evidence_unreadable. The payments they may describe are held and not sent again.` : null
35026
+ unreadable.length > 0 ? `${unreadable.length} evidence record(s) cannot be read; see submission_evidence_unreadable. The payments they may describe are held and not sent again.` : null
34819
35027
  ].filter(Boolean).join(" "),
34820
35028
  hint: [
34821
35029
  summary.stranded_count > 0 ? "Entries in state stale/unresumable/unreclaimable will not retry and their sats are not coming back. Close one out with: dvm wallet submissions --forget <request_id> (abandons its sats)." : null,
34822
35030
  summary.reclaimable_count > 0 ? "Entries in state reclaimable need no action \u2014 the wallet takes those sats back after reclaim_at." : null,
34823
35031
  summary.reclaim_failed_count > 0 ? "Entries in state reclaim_failed have expired but could not be taken back \u2014 see each entry's reclaim_error. The sats are recoverable once that is fixed." : null,
34824
- unreadable2.length > 0 ? "Restore each file in submission_evidence_unreadable from a backup. Do not pay again for any request it may describe." : null,
35032
+ unreadable.length > 0 ? "Restore each file in submission_evidence_unreadable from a backup. Do not pay again for any request it may describe." : null,
34825
35033
  evidence.length > 0 ? "Do not pay for a request listed in submission_evidence again. Each row's read_job lists lookups that never pay; job_token_bearer_secret, where present, is a bearer secret: treat it like a password and do not share it." : null,
34826
35034
  "Resumable entries retry on the next paid call or `dvm wallet show`."
34827
35035
  ].filter(Boolean).join(" ")
@@ -35919,7 +36127,7 @@ function buildProgram() {
35919
36127
  receiptsShow(jobId, opts);
35920
36128
  }, opts.human);
35921
36129
  });
35922
- 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) => {
35923
36131
  return catchErrors(() => receiptsVerify(jobId, opts), opts.human);
35924
36132
  });
35925
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) => {
@@ -36005,7 +36213,7 @@ function buildProgram() {
36005
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) => {
36006
36214
  return catchErrors(() => creditReceipts(dvm, opts), opts.human);
36007
36215
  });
36008
- 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) => {
36009
36217
  return catchErrors(() => messages(jobId, opts), opts.human);
36010
36218
  });
36011
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(