@dvmkit/dvm-cli 0.11.3 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dvm.js CHANGED
@@ -12,23 +12,31 @@ import {
12
12
  import {
13
13
  DEFAULT_CREDIT_POSTURE,
14
14
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
15
+ JOB_READ_TIMEOUT_MS,
15
16
  NWC_FUNDING_FLOAT_ROLE,
16
17
  SUBMISSION_EVIDENCE_DIR,
17
18
  abandonPendingSubmission,
18
19
  abandonSubmissionInWallet,
19
20
  addPayment,
21
+ answeredYieldSeqs,
22
+ appendMessages,
20
23
  assertFloatBudget,
21
24
  automaticCreditBoundRail,
22
25
  availableRails,
23
26
  backfillTrustAnchor,
24
27
  bookCreditPayment,
28
+ buildCompletionHintFields,
25
29
  buildTempoCredential,
26
30
  captureDrawFundingReceipts,
27
31
  captureFundingReceipt,
28
32
  captureTransportReceipt,
29
33
  clearPaymentRequestInFlight,
30
34
  commitAgentSpend,
35
+ completionFromMessages,
36
+ completionSnapshot,
37
+ computeNextAction,
31
38
  correctPendingFundAmount,
39
+ createMessageAppendSession,
32
40
  deriveAlias,
33
41
  describeMintBounds,
34
42
  drainReceiptsDisplay,
@@ -47,6 +55,7 @@ import {
47
55
  fundAgentWallet,
48
56
  fundCredit,
49
57
  fundTimeoutMs,
58
+ guidanceJobArg,
50
59
  hasUnknownUpfrontCredit,
51
60
  hasUnknownUpfrontRail,
52
61
  identityDataFields,
@@ -55,44 +64,62 @@ import {
55
64
  isIdentityFailure,
56
65
  isOpaqueJobToken,
57
66
  isParseableBodyJobId,
67
+ isTerminalJobStatus,
68
+ jobContentFields,
58
69
  jobDrawFundings,
59
70
  jobIdentityHeaderValue,
71
+ jobSettlement,
60
72
  journalMarkerFor,
61
73
  listSubmissionEvidence,
62
74
  loadAllJobs,
75
+ loadAnsweredYieldSeqs,
63
76
  loadFavorites,
64
77
  loadFloat,
65
78
  loadJob,
66
79
  loadLedger,
80
+ loadMessages,
67
81
  loadSubmissionEvidence,
68
82
  markJobTerminal,
69
83
  markPaymentRequestInFlight,
70
84
  markPaymentRequestPaid,
71
85
  markPendingSubmissionUnresolved,
72
86
  markProofsInFlight,
87
+ maxSeq,
73
88
  meltInFlightTimeoutSeconds,
74
89
  mutateCreditPayment,
75
90
  needsTopup,
91
+ nextStepHint,
76
92
  normalizeProviderEndpoint,
93
+ observeJobContent,
94
+ observedSettlementFields,
95
+ parseJobContent,
77
96
  parseLocktime,
78
97
  parseStatedBudget,
79
98
  parseUpfrontPayment,
80
99
  parseUpfrontRailPayment,
81
100
  payViaFloat,
101
+ paymentInFlightHint,
102
+ pendingPaymentRequest,
82
103
  pickCreditFundRail,
83
104
  planCreditForQuote,
84
105
  planProbeDraw,
106
+ pollNextAction,
85
107
  pollPendingCreditFundings,
86
108
  pollUntilPaidOrTimeout,
87
109
  prepareAgentSpend,
88
110
  probeFloat,
89
111
  proofKey,
112
+ providerFields,
113
+ providerJobJson,
90
114
  receiptDisplay,
91
115
  receiptFailureDetail,
92
116
  receiptHint,
93
117
  receiptIssuedAtIso,
94
118
  receiptJsonFields,
119
+ receiptSettlement,
95
120
  receiptTrustFields,
121
+ reconcileInFlightPaymentRequest,
122
+ reconcilePaymentRequestHistory,
96
123
  recordCallerMessageHash,
97
124
  recordFloatSpend,
98
125
  recordIdentityFailure,
@@ -121,10 +148,12 @@ import {
121
148
  statusSnapshot,
122
149
  sweepPendingMints,
123
150
  sweepStaleInFlight,
151
+ terminalSettlementFields,
124
152
  tierCapOverrides,
125
153
  toFloatError,
126
154
  trustLadderFor,
127
155
  trustOverrideCapMicro,
156
+ unknownUpfrontPrice,
128
157
  unrecordedFloatBudgetWarning,
129
158
  updateJob,
130
159
  warnInvalidJobIdentityHeader,
@@ -132,7 +161,7 @@ import {
132
161
  withIdentityRecovery,
133
162
  withJobTokenRedaction,
134
163
  withRequestResultRecovery
135
- } from "./chunk-MIYOOJRL.js";
164
+ } from "./chunk-WPTJM5A7.js";
136
165
  import {
137
166
  connectedTempoAccount,
138
167
  generateTempoKey,
@@ -140,6 +169,7 @@ import {
140
169
  tempoWrongAssetHint
141
170
  } from "./chunk-7N3HQJKE.js";
142
171
  import {
172
+ addOutputWarnings,
143
173
  assertValidBudget,
144
174
  costAnchor,
145
175
  formatAmount,
@@ -155,8 +185,9 @@ import {
155
185
  setOutputTraceId,
156
186
  staleRateNotice,
157
187
  tryResolveBtcUsdRate,
158
- tryX402Payment
159
- } from "./chunk-BPWZNIMS.js";
188
+ tryX402Payment,
189
+ withOutputWarnings
190
+ } from "./chunk-RMYEB2WG.js";
160
191
  import {
161
192
  assertSupportedX402Network,
162
193
  connectedX402Payer,
@@ -8526,27 +8557,6 @@ var {
8526
8557
  Help
8527
8558
  } = import_index.default;
8528
8559
 
8529
- // src/lib/provider-output.ts
8530
- function providerFields(value, fields = Object.keys(value)) {
8531
- return {
8532
- ...value,
8533
- _provider_fields: [.../* @__PURE__ */ new Set([
8534
- ...Array.isArray(value._provider_fields) ? value._provider_fields : [],
8535
- ...fields.filter((field) => field !== "_provider_fields" && value[field] !== void 0)
8536
- ])]
8537
- };
8538
- }
8539
- function guidanceJobArg(jobId) {
8540
- return /^[A-Za-z0-9_-]+$/.test(jobId) ? shellQuoteArg(jobId) : "'<job_id>'";
8541
- }
8542
- function providerJobJson(data, providerJob = true) {
8543
- const action = data.next_action;
8544
- json(providerFields({
8545
- ...data,
8546
- ...providerJob && action && typeof action === "object" ? { next_action: providerFields(action, ["job_id"]) } : {}
8547
- }, [...providerJob ? ["jobId"] : [], "capability", "identifier"]));
8548
- }
8549
-
8550
8560
  // src/lib/discovery-rows.ts
8551
8561
  function buildDiscoveryRows(entries) {
8552
8562
  return entries.flatMap((entry) => {
@@ -8610,176 +8620,6 @@ function renderDiscoveryDisplay(row, indent) {
8610
8620
  }
8611
8621
  }
8612
8622
 
8613
- // src/lib/messages/store.ts
8614
- import {
8615
- appendFileSync,
8616
- closeSync,
8617
- existsSync,
8618
- openSync,
8619
- readFileSync,
8620
- readSync,
8621
- statSync
8622
- } from "fs";
8623
- import { join } from "path";
8624
- var CHECKPOINT_BYTES = 64;
8625
- function appendMessages(jobId, messages2) {
8626
- if (messages2.length === 0) return;
8627
- createMessageAppendSession(jobId).append(messages2);
8628
- }
8629
- function createMessageAppendSession(jobId) {
8630
- return new FileMessageAppendSession(messageFilePath(jobId));
8631
- }
8632
- var FileMessageAppendSession = class {
8633
- constructor(filePath) {
8634
- this.filePath = filePath;
8635
- this.syncFromDisk();
8636
- }
8637
- filePath;
8638
- seqs = /* @__PURE__ */ new Set();
8639
- identity;
8640
- offset = 0;
8641
- pending = Buffer.alloc(0);
8642
- checkpoint = Buffer.alloc(0);
8643
- modifiedAt = 0;
8644
- append(messages2) {
8645
- if (messages2.length === 0) return;
8646
- this.syncFromDisk();
8647
- const selectedSeqs = new Set(this.seqs);
8648
- const newMessages = messages2.filter((message2) => {
8649
- if (selectedSeqs.has(message2.seq)) return false;
8650
- selectedSeqs.add(message2.seq);
8651
- return true;
8652
- });
8653
- if (newMessages.length === 0) return;
8654
- ensureConfigSubdir(MESSAGES_DIR);
8655
- const lines = newMessages.map((message2) => JSON.stringify(message2)).join("\n") + "\n";
8656
- appendFileSync(this.filePath, lines);
8657
- this.syncFromDisk();
8658
- }
8659
- syncFromDisk() {
8660
- const snapshot = statFile(this.filePath);
8661
- if (!snapshot) {
8662
- this.reset();
8663
- return;
8664
- }
8665
- const identity = fileIdentity(snapshot);
8666
- const changedFile = !this.identity || !sameIdentity(this.identity, identity);
8667
- const shrank = snapshot.size < this.offset;
8668
- const changedSinceRead = snapshot.size !== this.offset || Math.max(snapshot.mtimeMs, snapshot.ctimeMs) !== this.modifiedAt;
8669
- if (changedFile || shrank || changedSinceRead && !this.checkpointMatches()) {
8670
- this.reset(identity);
8671
- }
8672
- this.identity = identity;
8673
- this.modifiedAt = Math.max(snapshot.mtimeMs, snapshot.ctimeMs);
8674
- if (snapshot.size <= this.offset) return;
8675
- const bytes = readRange(this.filePath, this.offset, snapshot.size);
8676
- this.offset += bytes.byteLength;
8677
- this.consume(bytes);
8678
- this.checkpoint = trailingBytes(this.checkpoint, bytes, CHECKPOINT_BYTES);
8679
- }
8680
- checkpointMatches() {
8681
- if (this.checkpoint.length === 0 || this.offset < this.checkpoint.length) return true;
8682
- const actual = readRange(
8683
- this.filePath,
8684
- this.offset - this.checkpoint.length,
8685
- this.offset
8686
- );
8687
- return actual.equals(this.checkpoint);
8688
- }
8689
- consume(bytes) {
8690
- const combined = Buffer.concat([this.pending, bytes]);
8691
- const finalNewline = combined.lastIndexOf(10);
8692
- if (finalNewline === -1) {
8693
- this.pending = combined;
8694
- this.parseLine(this.pending);
8695
- return;
8696
- }
8697
- const complete = combined.subarray(0, finalNewline).toString("utf8");
8698
- for (const line of complete.split("\n")) this.parseLine(line);
8699
- this.pending = combined.subarray(finalNewline + 1);
8700
- this.parseLine(this.pending);
8701
- }
8702
- parseLine(line) {
8703
- const text = line.toString().trim();
8704
- if (!text) return;
8705
- try {
8706
- const message2 = JSON.parse(text);
8707
- this.seqs.add(message2.seq);
8708
- } catch {
8709
- }
8710
- }
8711
- reset(identity) {
8712
- this.seqs.clear();
8713
- this.identity = identity;
8714
- this.offset = 0;
8715
- this.pending = Buffer.alloc(0);
8716
- this.checkpoint = Buffer.alloc(0);
8717
- this.modifiedAt = 0;
8718
- }
8719
- };
8720
- function loadMessages(jobId, after) {
8721
- const filePath = messageFilePath(jobId);
8722
- if (!existsSync(filePath)) return [];
8723
- const content = readFileSync(filePath, "utf-8").trim();
8724
- if (!content) return [];
8725
- const messages2 = [];
8726
- for (const line of content.split("\n")) {
8727
- if (!line.trim()) continue;
8728
- try {
8729
- const msg = JSON.parse(line);
8730
- if (after === void 0 || msg.seq > after) {
8731
- messages2.push(msg);
8732
- }
8733
- } catch {
8734
- }
8735
- }
8736
- return messages2;
8737
- }
8738
- function messageFilePath(jobId) {
8739
- return join(MESSAGES_DIR, `${jobId}.jsonl`);
8740
- }
8741
- function statFile(filePath) {
8742
- try {
8743
- return statSync(filePath);
8744
- } catch (error) {
8745
- if (error.code === "ENOENT") return void 0;
8746
- throw error;
8747
- }
8748
- }
8749
- function fileIdentity(stats) {
8750
- return { dev: stats.dev, ino: stats.ino };
8751
- }
8752
- function sameIdentity(left, right) {
8753
- return left.dev === right.dev && left.ino === right.ino;
8754
- }
8755
- function readRange(filePath, start, end) {
8756
- const expected = Math.max(0, end - start);
8757
- const buffer = Buffer.allocUnsafe(expected);
8758
- const fd = openSync(filePath, "r");
8759
- let total = 0;
8760
- try {
8761
- while (total < expected) {
8762
- const read = readSync(fd, buffer, total, expected - total, start + total);
8763
- if (read === 0) break;
8764
- total += read;
8765
- }
8766
- } finally {
8767
- closeSync(fd);
8768
- }
8769
- return total === expected ? buffer : buffer.subarray(0, total);
8770
- }
8771
- function trailingBytes(previous, next, limit) {
8772
- if (next.length >= limit) return Buffer.from(next.subarray(next.length - limit));
8773
- const combined = Buffer.concat([previous, next]);
8774
- return Buffer.from(combined.subarray(Math.max(0, combined.length - limit)));
8775
- }
8776
-
8777
- // src/lib/messages/index.ts
8778
- function maxSeq(msgs, fallback) {
8779
- if (msgs.length === 0) return fallback;
8780
- return Math.max(...msgs.map((m) => m.seq));
8781
- }
8782
-
8783
8623
  // src/lib/payment-lock.ts
8784
8624
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
8785
8625
  import { createHash } from "crypto";
@@ -8819,224 +8659,6 @@ async function withJobPaymentLock(jobId, action) {
8819
8659
  }
8820
8660
  }
8821
8661
 
8822
- // src/lib/yield-state.ts
8823
- var JOB_READ_TIMEOUT_MS = 6e4;
8824
- var PAYMENT_SETTLE_WINDOW_MS = 45e3;
8825
- function answeredYieldSeqs(messages2) {
8826
- const answered = /* @__PURE__ */ new Set();
8827
- const prompts = /* @__PURE__ */ new Map();
8828
- let paymentRequest;
8829
- for (const message2 of [...messages2].sort((a, b) => a.seq - b.seq)) {
8830
- if (message2.from === "provider") {
8831
- if (message2.type === "payment-request") paymentRequest = message2.seq;
8832
- if (message2.type === "prompt") prompts.set(message2.content.id, message2.seq);
8833
- } else if (message2.type === "response") {
8834
- const seq = prompts.get(message2.content.prompt_id);
8835
- if (seq !== void 0) answered.add(seq);
8836
- } else if (message2.type === "payment") {
8837
- const seq = message2.content.credit?.request_seq ?? paymentRequest;
8838
- if (seq !== void 0) answered.add(seq);
8839
- }
8840
- }
8841
- return answered;
8842
- }
8843
- function latestProviderPaymentRequest(messages2) {
8844
- return [...messages2].sort((a, b) => a.seq - b.seq).findLast((message2) => message2.from === "provider" && message2.type === "payment-request");
8845
- }
8846
- function pendingPaymentRequest(messages2, answered = answeredYieldSeqs(messages2)) {
8847
- const latest = latestProviderPaymentRequest(messages2);
8848
- if (!latest || answered.has(latest.seq)) return void 0;
8849
- if (messages2.some((message2) => message2.from === "provider" && message2.seq > latest.seq && (message2.type === "complete" || message2.type === "cancel" || message2.type === "working"))) return void 0;
8850
- return latest;
8851
- }
8852
- function loadAnsweredYieldSeqs(jobId) {
8853
- const answered = answeredYieldSeqs(loadMessages(jobId));
8854
- const job = loadJob(jobId);
8855
- for (const seq of job?.paidPaymentRequestSeqs ?? []) answered.add(seq);
8856
- for (const payment of job?.bookedCreditPayments ?? []) answered.add(payment.authorization.request_seq);
8857
- return answered;
8858
- }
8859
- async function reconcileInFlightPaymentRequest(jobId, requestSeq, transport, provider, options) {
8860
- const boundedOptions = { ...options, timeoutMs: options.timeoutMs ?? JOB_READ_TIMEOUT_MS };
8861
- const history = await boundedPaymentRead(jobId, () => transport.getMessages(jobId, 0, provider, boundedOptions), boundedOptions.timeoutMs);
8862
- const decisionTime = Date.now();
8863
- const needsStatus = !answeredYieldSeqs(history).has(requestSeq) && decisionTime >= settleUntilMs(jobId, requestSeq, decisionTime);
8864
- const status2 = needsStatus ? (await boundedPaymentRead(jobId, () => transport.status(jobId, provider, boundedOptions), boundedOptions.timeoutMs)).status : void 0;
8865
- return reconcilePaymentRequestHistory(jobId, requestSeq, history, status2, () => decisionTime);
8866
- }
8867
- function reconcilePaymentRequestHistory(jobId, requestSeq, history, status2, now = Date.now) {
8868
- if (answeredYieldSeqs(history).has(requestSeq)) {
8869
- markPaymentRequestPaid(jobId, requestSeq);
8870
- return true;
8871
- }
8872
- const superseded = (latestProviderPaymentRequest(history)?.seq ?? -1) > requestSeq;
8873
- if (superseded) clearPaymentRequestInFlight(jobId, requestSeq);
8874
- const decisionTime = now();
8875
- const retryAt = settleUntilMs(jobId, requestSeq, decisionTime);
8876
- const seconds = Math.ceil((retryAt - decisionTime) / 1e3);
8877
- if (!superseded && decisionTime < retryAt)
8878
- throw new DvmError(
8879
- "payment_settling",
8880
- "The previous payment may still be processing.",
8881
- `Retry with \`dvm pay ${shellQuoteArg(jobId)}\` in about ${seconds} ${seconds === 1 ? "second" : "seconds"}, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`,
8882
- { retry_at_ms: retryAt }
8883
- );
8884
- if (status2 !== "awaiting-input" || pendingPaymentRequest(history)?.seq !== requestSeq)
8885
- throw new DvmError(
8886
- "payment_request_not_pending",
8887
- "The provider is no longer waiting on this payment request.",
8888
- `Check the job with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
8889
- );
8890
- return false;
8891
- }
8892
- function settleUntilMs(jobId, requestSeq, now) {
8893
- const startedAt = loadJob(jobId)?.inFlightPaymentRequestStartedAtMs?.[requestSeq];
8894
- return startedAt === void 0 ? 0 : Math.min(startedAt + PAYMENT_SETTLE_WINDOW_MS, now + PAYMENT_SETTLE_WINDOW_MS);
8895
- }
8896
- async function boundedPaymentRead(jobId, read, timeoutMs) {
8897
- let timer;
8898
- try {
8899
- return await Promise.race([read(), new Promise((_, reject) => {
8900
- timer = setTimeout(() => reject(new DvmError("timeout", "Payment recovery read timed out. No new payment was sent.")), timeoutMs);
8901
- })]);
8902
- } catch (error) {
8903
- if (isAbortError(error) || error instanceof DvmError && error.code === "timeout")
8904
- throw new DvmError(
8905
- "timeout",
8906
- "Payment recovery read timed out. No new payment was sent.",
8907
- `Retry with \`dvm pay ${shellQuoteArg(jobId)}\` or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`
8908
- );
8909
- throw error;
8910
- } finally {
8911
- if (timer) clearTimeout(timer);
8912
- }
8913
- }
8914
-
8915
- // src/lib/next-action.ts
8916
- function isTerminalJobStatus(status2) {
8917
- return TERMINAL_STATUSES.has(status2);
8918
- }
8919
- function pollNextAction(jobId, hint) {
8920
- return {
8921
- type: "poll",
8922
- job_id: jobId,
8923
- hint: hint ?? `Provider is still working. Keep the job moving unattended with \`dvm messages ${guidanceJobArg(jobId)} --wait\`.`
8924
- };
8925
- }
8926
- function paymentInFlightHint(jobId) {
8927
- return `A payment may already have been sent for this request. Resolve it with \`dvm pay ${guidanceJobArg(jobId)}\`; it checks provider history before paying again.`;
8928
- }
8929
- var YIELD_TYPES = /* @__PURE__ */ new Set(["prompt", "payment-request", "working", "complete", "cancel"]);
8930
- var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
8931
- "completed",
8932
- "failed",
8933
- "cancelled"
8934
- ]);
8935
- function computeNextAction(jobId, messages2, nowMs = Date.now()) {
8936
- const answered = answeredYieldSeqs(messages2);
8937
- const expiresAtMs = pendingDeadline(messages2, answered);
8938
- for (let i = messages2.length - 1; i >= 0; i--) {
8939
- const msg = messages2[i];
8940
- if (!YIELD_TYPES.has(msg.type) || answered.has(msg.seq)) continue;
8941
- switch (msg.type) {
8942
- case "complete":
8943
- case "cancel":
8944
- return null;
8945
- case "prompt": {
8946
- const c = msg.content;
8947
- const answer = c.schema ? "--json '<object matching schema>'" : '"<answer>"';
8948
- const choices = c.options?.length ? ` Choices: ${c.options.map((option) => JSON.stringify(option)).join(", ")}.` : "";
8949
- const choiceHint = !c.schema && c.options?.length ? " Answer with exactly one of options unless the human chose otherwise." : "";
8950
- const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Answer" : "Reply", expiresAtMs, nowMs, jobId);
8951
- const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
8952
- const action = {
8953
- type: "respond",
8954
- job_id: jobId,
8955
- prompt_id: c.id,
8956
- prompt: asProviderText(c.text),
8957
- _provider_fields: [
8958
- "prompt_id",
8959
- ...c.schema ? ["schema"] : [],
8960
- ...c.options?.length ? ["options"] : []
8961
- ],
8962
- display: withDeadline(`The provider asks: ${c.text}${choices}`, deadline),
8963
- hint: expired ? deadline : withDeadline(`Provider is waiting for your input. Verify the question makes sense for your task before responding.${choiceHint} Run \`dvm message ${guidanceJobArg(jobId)} ${answer} --type response --prompt-id '<prompt_id>'\`.`, deadline)
8964
- };
8965
- if (c.schema) action.schema = c.schema;
8966
- if (c.options?.length) action.options = c.options;
8967
- if (expiresAtMs !== void 0) action.expires_at_ms = expiresAtMs;
8968
- return action;
8969
- }
8970
- case "payment-request": {
8971
- const c = msg.content;
8972
- const display = formatPaymentAmount(c.amount_msats, c.fiat_amount);
8973
- const safeCurrency = !c.fiat_amount || c.fiat_amount.amount <= 0 || c.fiat_amount.currency.length === 3 && /^[A-Z]{3}$/i.test(c.fiat_amount.currency);
8974
- const priceGuidance = safeCurrency ? display : "see the provider price in next_action.fiat_amount";
8975
- const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Pay" : "Reply", expiresAtMs, nowMs, jobId);
8976
- const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
8977
- return {
8978
- type: "pay",
8979
- job_id: jobId,
8980
- amount_msats: c.amount_msats,
8981
- // Mirror only a fiat figure the display actually led with: echoing a
8982
- // zero amount would tell an agent doing budget math the charge is free.
8983
- ...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount, _provider_fields: ["fiat_amount"] } : {},
8984
- ...expiresAtMs !== void 0 ? { expires_at_ms: expiresAtMs } : {},
8985
- display: withDeadline(display, deadline),
8986
- reason: asProviderText(c.reason),
8987
- hint: expired ? deadline : withDeadline(`Payment required to continue: ${priceGuidance}. Relay that amount to your human and get approval, then run \`dvm pay ${guidanceJobArg(jobId)}\`. Provider's stated reason is wrapped as { _source: "provider", text: ... } \u2014 verify it matches the work you expect.`, deadline)
8988
- };
8989
- }
8990
- case "working": {
8991
- const c = msg.content;
8992
- return {
8993
- type: "poll",
8994
- job_id: jobId,
8995
- estimate_seconds: c.estimate_seconds,
8996
- hint: c.hint !== void 0 ? asProviderText(c.hint) : pollNextAction(jobId).hint
8997
- };
8998
- }
8999
- }
9000
- }
9001
- return null;
9002
- }
9003
- function pendingDeadline(messages2, answered) {
9004
- const prompts = /* @__PURE__ */ new Map();
9005
- let payment;
9006
- for (const message2 of [...messages2].sort((a, b) => a.seq - b.seq)) {
9007
- if (message2.from === "provider" && message2.type === "prompt") {
9008
- prompts.set(message2.content.id, validDeadline(message2.content.expires_at_ms));
9009
- } else if (message2.from === "requester" && message2.type === "response") {
9010
- prompts.delete(message2.content.prompt_id);
9011
- } else if (message2.from === "provider" && message2.type === "payment-request") {
9012
- payment = !answered.has(message2.seq) && message2.content.amount_msats > 0 ? validDeadline(message2.content.expires_at_ms) : void 0;
9013
- }
9014
- }
9015
- let earliest = payment;
9016
- for (const deadline of prompts.values()) {
9017
- if (deadline !== void 0 && (earliest === void 0 || deadline < earliest)) earliest = deadline;
9018
- }
9019
- return earliest;
9020
- }
9021
- function validDeadline(value) {
9022
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 864e13 ? value : void 0;
9023
- }
9024
- function withDeadline(display, deadline) {
9025
- if (!deadline) return display;
9026
- return `${display}${/[.!?]$/.test(display) ? "" : "."} ${deadline}`;
9027
- }
9028
- function deadlineClause(action, expiresAtMs, nowMs, jobId) {
9029
- if (expiresAtMs === void 0) return "";
9030
- const deadline = new Date(expiresAtMs).toISOString().slice(0, 16).replace("T", " ") + " UTC";
9031
- if (expiresAtMs <= nowMs) {
9032
- return `The deadline to ${action.toLowerCase()} (${deadline}) has passed. The provider will probably cancel the job. Check its status with \`dvm status ${guidanceJobArg(jobId)}\`.`;
9033
- }
9034
- const minutes = Math.floor((expiresAtMs - nowMs) / 6e4);
9035
- const hours = Math.floor(minutes / 60);
9036
- 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";
9037
- return `${action} by ${deadline} (in ${remaining}), or the provider cancels the job.`;
9038
- }
9039
-
9040
8662
  // src/lib/rail-labels.ts
9041
8663
  var PAYMENT_RAIL_KEYS = ["cashu", "cashu_p2pk", "x402", "tempo"];
9042
8664
  function isPaymentRailKey(value) {
@@ -9076,7 +8698,7 @@ function railLabelAtSentenceStart(label) {
9076
8698
 
9077
8699
  // src/lib/payment-copy.ts
9078
8700
  function paidConfirmationDisplay(result, fiat) {
9079
- return `Paid ${formatPaidAmount(result, fiat)} via ${paymentRailLabel(result.rail)}.`;
8701
+ return `${result.rail === "credit" ? "Held" : "Sent"} ${formatPaidAmount(result, fiat)} via ${paymentRailLabel(result.rail)}; final settlement follows the job outcome.`;
9080
8702
  }
9081
8703
  function formatPaidAmount(result, fiat) {
9082
8704
  if (result.amountUsdcMicro !== void 0) {
@@ -9089,15 +8711,15 @@ function formatPaidAmount(result, fiat) {
9089
8711
  import { randomUUID } from "crypto";
9090
8712
 
9091
8713
  // src/lib/caller-version.ts
9092
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
9093
- import { dirname, join as join2 } from "path";
8714
+ import { existsSync, readFileSync } from "fs";
8715
+ import { dirname, join } from "path";
9094
8716
  import { fileURLToPath } from "url";
9095
8717
  var CALLER_VERSION = readCallerVersion();
9096
8718
  function readCallerVersion() {
9097
8719
  let dir = dirname(fileURLToPath(import.meta.url));
9098
8720
  for (; ; ) {
9099
- const manifestPath = join2(dir, "package.json");
9100
- if (existsSync2(manifestPath)) {
8721
+ const manifestPath = join(dir, "package.json");
8722
+ if (existsSync(manifestPath)) {
9101
8723
  const manifest = readManifest(manifestPath);
9102
8724
  if (manifest.name === "@dvmkit/dvm-cli") return manifest.version;
9103
8725
  }
@@ -9109,7 +8731,7 @@ function readCallerVersion() {
9109
8731
  }
9110
8732
  }
9111
8733
  function readManifest(path) {
9112
- return JSON.parse(readFileSync2(path, "utf8"));
8734
+ return JSON.parse(readFileSync(path, "utf8"));
9113
8735
  }
9114
8736
 
9115
8737
  // src/lib/client-compatibility.ts
@@ -9507,7 +9129,7 @@ function buildCreditDrawSkipped(args) {
9507
9129
  const last = `$${formatUsd((skip.lastPriceMicro ?? 0) / 1e6)}`;
9508
9130
  const ceiling = `$${formatUsd((skip.ceilingMicro ?? 0) / 1e6)}`;
9509
9131
  return {
9510
- display: `${parked}, but the last job here drew ${last}, above the ${ceiling} ceiling this request declared \u2014 so it was left undrawn and this job pays per-call instead.`,
9132
+ display: `${parked}, but this capability's quoted or last drawn price is ${last}, above the ${ceiling} ceiling this request declared \u2014 so it was left undrawn and this job pays per-call instead.`,
9511
9133
  hint: raiseCeilingHint(skip.ceilingSource, last)
9512
9134
  };
9513
9135
  }
@@ -11178,6 +10800,148 @@ function parseTempoNetwork(value, source) {
11178
10800
  );
11179
10801
  }
11180
10802
 
10803
+ // src/lib/request-intent-store.ts
10804
+ var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
10805
+ import {
10806
+ closeSync,
10807
+ existsSync as existsSync2,
10808
+ fsyncSync,
10809
+ mkdirSync,
10810
+ openSync,
10811
+ readFileSync as readFileSync2,
10812
+ renameSync,
10813
+ writeFileSync
10814
+ } from "fs";
10815
+ import { join as join2 } from "path";
10816
+ function saveRequestIntent(intent) {
10817
+ assertRequestId(intent.requestId);
10818
+ assertNoPaymentOrAuthSecrets(intent.body);
10819
+ ensureConfigSubdir(REQUEST_INTENTS_DIR);
10820
+ const dir = intentDirectory(intent.requestId);
10821
+ try {
10822
+ mkdirSync(dir, { mode: 448 });
10823
+ } catch (error) {
10824
+ if (error.code === "EEXIST") return false;
10825
+ throw error;
10826
+ }
10827
+ fsyncDirectory(REQUEST_INTENTS_DIR);
10828
+ const temp = join2(dir, `intent.${String(process.pid)}.tmp`);
10829
+ const target = join2(dir, "intent.json");
10830
+ const fd = openSync(temp, "wx", 384);
10831
+ try {
10832
+ writeFileSync(fd, JSON.stringify(intent, null, 2) + "\n");
10833
+ fsyncSync(fd);
10834
+ } finally {
10835
+ closeSync(fd);
10836
+ }
10837
+ renameSync(temp, target);
10838
+ fsyncDirectory(dir);
10839
+ return true;
10840
+ }
10841
+ function loadRequestIntent(requestId) {
10842
+ assertRequestId(requestId);
10843
+ const dir = intentDirectory(requestId);
10844
+ if (!existsSync2(dir)) return null;
10845
+ const path = join2(dir, "intent.json");
10846
+ try {
10847
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
10848
+ if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
10849
+ throw new Error("invalid shape");
10850
+ return parsed;
10851
+ } catch (error) {
10852
+ throw new DvmError(
10853
+ "request_intent_unreadable",
10854
+ `The saved request intent for ${requestId} is incomplete or unreadable.`,
10855
+ "Do not submit a replacement request. The provider may already have accepted and charged the original; restore this intent from backup before using request-result.",
10856
+ { request_id: requestId, cause: error instanceof Error ? error.message : String(error) }
10857
+ );
10858
+ }
10859
+ }
10860
+ function recordRequestRailPayment(requestId, payment) {
10861
+ assertRequestId(requestId);
10862
+ if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
10863
+ const dir = intentDirectory(requestId);
10864
+ const target = join2(dir, "intent.json");
10865
+ const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
10866
+ try {
10867
+ const intent = loadRequestIntent(requestId);
10868
+ if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
10869
+ if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
10870
+ throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
10871
+ const temp = join2(dir, `rail.${String(process.pid)}.tmp`);
10872
+ const fd = openSync(temp, "w", 384);
10873
+ try {
10874
+ writeFileSync(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
10875
+ fsyncSync(fd);
10876
+ } finally {
10877
+ closeSync(fd);
10878
+ }
10879
+ renameSync(temp, target);
10880
+ fsyncDirectory(dir);
10881
+ } finally {
10882
+ release();
10883
+ }
10884
+ }
10885
+ function assertNoPaymentOrAuthSecrets(body) {
10886
+ if (!containsForbiddenSecret(body)) return;
10887
+ throw new DvmError(
10888
+ "request_intent_contains_secret",
10889
+ "Request recovery cannot persist a payment credential, bearer token, or request auth signature.",
10890
+ "No payment was attempted. Remove the secret-bearing input or omit --request-id."
10891
+ );
10892
+ }
10893
+ function containsForbiddenSecret(value) {
10894
+ if (typeof value === "string") return /^Bearer\s/i.test(value);
10895
+ if (!value || typeof value !== "object") return false;
10896
+ if (Array.isArray(value)) return value.some(containsForbiddenSecret);
10897
+ const record = value;
10898
+ if (["pubkey", "timestamp", "nonce", "signature"].every((key) => Object.hasOwn(record, key))) {
10899
+ return true;
10900
+ }
10901
+ const forbidden = /* @__PURE__ */ new Set([
10902
+ "authorization",
10903
+ "bearer_token",
10904
+ "access_token",
10905
+ "cashu_token",
10906
+ "x402_payment",
10907
+ "tempo_credential"
10908
+ ]);
10909
+ return Object.entries(record).some(
10910
+ ([key, child]) => forbidden.has(key.toLowerCase()) || containsForbiddenSecret(child)
10911
+ );
10912
+ }
10913
+ function assertRequestId(requestId) {
10914
+ if (isPublicRequestId(requestId)) return;
10915
+ throw new DvmError(
10916
+ "invalid_request_id",
10917
+ "Invalid request id.",
10918
+ "Use 1\u2013128 characters: letters, digits, dot, underscore, colon, or hyphen."
10919
+ );
10920
+ }
10921
+ function intentDirectory(requestId) {
10922
+ return join2(REQUEST_INTENTS_DIR, requestId);
10923
+ }
10924
+ function fsyncDirectory(path) {
10925
+ if (process.platform === "win32") return;
10926
+ let fd;
10927
+ try {
10928
+ fd = openSync(path, "r");
10929
+ fsyncSync(fd);
10930
+ } finally {
10931
+ if (fd !== void 0) closeSync(fd);
10932
+ }
10933
+ }
10934
+ function isRequestIntent(value) {
10935
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
10936
+ const candidate = value;
10937
+ return candidate.v === 2 && isPublicRequestId(candidate.requestId) && typeof candidate.endpoint === "string" && typeof candidate.capability === "string" && typeof candidate.callerPubkey === "string" && isSignedRequestAudience(candidate.authAudience) && typeof candidate.createdAt === "number" && typeof candidate.body === "object" && candidate.body !== null && !Array.isArray(candidate.body) && typeof candidate.policy === "object" && candidate.policy !== null;
10938
+ }
10939
+ function isSignedRequestAudience(value) {
10940
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
10941
+ const candidate = value;
10942
+ return typeof candidate.dvm_id === "string" && typeof candidate.builder_pubkey === "string";
10943
+ }
10944
+
11181
10945
  // src/lib/payment-responder.ts
11182
10946
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11183
10947
  return withJobPaymentLock(jobId, (assertOwned) => {
@@ -11192,6 +10956,28 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11192
10956
  }
11193
10957
  });
11194
10958
  return handleLockedPaymentRequest(jobId, request2, policy, guardedTransport, provider, opts);
10959
+ }).catch((error) => {
10960
+ if (!(error instanceof DvmError)) throw error;
10961
+ const job = loadJob(jobId);
10962
+ if (!job || !provider.endpoint || !sameEndpoint(job.endpoint, provider.endpoint)) throw error;
10963
+ let requestId;
10964
+ if (job.requestId && isPublicRequestId(job.requestId)) {
10965
+ try {
10966
+ const intent = loadRequestIntent(job.requestId);
10967
+ if (intent && sameEndpoint(intent.endpoint, job.endpoint)) requestId = job.requestId;
10968
+ } catch {
10969
+ }
10970
+ }
10971
+ const command = requestId ? `dvm request-result ${shellQuoteArg(requestId)}` : `dvm status ${guidanceJobArg(jobId)}`;
10972
+ const recovery = `The job was already accepted. Inspect it with \`${command}\` before submitting a replacement. This read cannot submit a job or send payment.`;
10973
+ error.data = providerFields({
10974
+ ...error.data,
10975
+ job_id: jobId,
10976
+ ...requestId ? { request_id: requestId } : {},
10977
+ next_action: providerFields({ ...pollNextAction(jobId, recovery) }, ["job_id"]),
10978
+ next_step: [typeof error.data?.next_step === "string" ? error.data.next_step : void 0, recovery].filter(Boolean).join(" ")
10979
+ }, ["job_id"]);
10980
+ throw error;
11195
10981
  });
11196
10982
  }
11197
10983
  async function handleLockedPaymentRequest(jobId, request2, policy, transport, provider, opts) {
@@ -11221,6 +11007,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11221
11007
  const matchingEndpoint = !!job && !!provider.endpoint && sameEndpoint(job.endpoint, provider.endpoint);
11222
11008
  if (!matchingEndpoint && job?.pendingCreditPayment)
11223
11009
  throw new DvmError("credit_payment_endpoint_mismatch", "Recover this balance payment at its original endpoint.");
11010
+ if (job?.creditOnly && (!matchingEndpoint || !job.creditBinding || "unbound" in job.creditBinding || job.creditBinding.creditId !== job.creditOnly || opts?.rail !== void 0))
11011
+ throw new DvmError("credit_only_unavailable", "This job may spend only its original prepaid credit.");
11224
11012
  let balanceRefused = false;
11225
11013
  const booked = matchingEndpoint ? bookedCreditPayment(jobId, opts?.requestSeq) : void 0;
11226
11014
  if (booked && (booked.request.amount_msats !== request2.amount_msats || booked.request.credit?.amount_micro !== request2.credit?.amount_micro || booked.request.credit?.currency !== request2.credit?.currency))
@@ -11283,6 +11071,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11283
11071
  });
11284
11072
  if (creditPaid !== false) return { status: "paid", rail: "credit", amountMsats: creditPaid };
11285
11073
  }
11074
+ if (job?.creditOnly)
11075
+ throw new DvmError("credit_only_unavailable", "The selected prepaid credit cannot pay this ask; no fresh payment was attempted.");
11286
11076
  const btcRate = await enforceGlobalBudget({ plannedMsats: request2.amount_msats });
11287
11077
  const cashuPrincipalSats = Math.ceil(request2.amount_msats / 1e3);
11288
11078
  if (opts?.maxCashuPrincipalSats !== void 0 && (opts.rail !== "cashu" || !Number.isSafeInteger(opts.maxCashuPrincipalSats) || opts.maxCashuPrincipalSats <= 0)) {
@@ -11319,7 +11109,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11319
11109
  }
11320
11110
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11321
11111
  const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UJ7EJNQA.js");
11322
- const { tryX402Payment: tryX402Payment2 } = await import("./client-DS4QJ346.js");
11112
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-V7KAPCAG.js");
11323
11113
  const wallet = loadX402Wallet2();
11324
11114
  if (wallet) {
11325
11115
  let proof;
@@ -11750,7 +11540,7 @@ async function streamLoop(opts) {
11750
11540
  timestamp: 0,
11751
11541
  type: "payment-request",
11752
11542
  content: pending4.request
11753
- }]);
11543
+ }], void 0, policy ? { policy, totalPaidMsats: loadJob(jobId)?.totalPaidMsats } : void 0);
11754
11544
  }
11755
11545
  const deadline = opts.timeoutMs === void 0 ? void 0 : Date.now() + Math.max(0, opts.timeoutMs);
11756
11546
  const nextPollOptions = () => {
@@ -11907,7 +11697,7 @@ async function streamLoop(opts) {
11907
11697
  if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
11908
11698
  for (const seq of answeredYieldSeqs(allMessages)) answeredSeqs.add(seq);
11909
11699
  const terminal = allMessages.some((msg) => msg.type === "complete" || msg.type === "cancel");
11910
- const yieldAction = computeNextAction(jobId, allMessages.filter((message2) => !answeredSeqs.has(message2.seq))) ?? (terminal ? null : pendingAction);
11700
+ const yieldAction = computeNextAction(jobId, allMessages.filter((message2) => !answeredSeqs.has(message2.seq)), void 0, policy ? { policy, totalPaidMsats: loadJob(jobId)?.totalPaidMsats } : void 0) ?? (terminal ? null : pendingAction);
11911
11701
  let nextAction = withRefundNextAction(jobId, yieldAction ?? (terminal ? null : pollNextAction(jobId)), refunds);
11912
11702
  const lastYield = findLastYield(allMessages);
11913
11703
  if (nextAction?.type === "pay" && lastYield?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield.seq))
@@ -12092,39 +11882,6 @@ function isCallerMessage(message2) {
12092
11882
  return callerMessages.has(message2);
12093
11883
  }
12094
11884
 
12095
- // src/lib/job-content.ts
12096
- function parseJobContent(data) {
12097
- return {
12098
- ...data.content_expires_at === null || typeof data.content_expires_at === "number" && Number.isSafeInteger(data.content_expires_at) && Math.abs(data.content_expires_at) <= 864e13 ? { content_expires_at: data.content_expires_at } : {},
12099
- ...typeof data.content_available === "boolean" ? { content_available: data.content_available } : {}
12100
- };
12101
- }
12102
- function jobContentFields(jobId, observed, human = false) {
12103
- const metadata = parseJobContent(observed ?? {});
12104
- const known = metadata.content_expires_at !== void 0 && metadata.content_available !== void 0;
12105
- const availability = metadata.content_available === false ? "Provider content is unavailable. The job outcome and financial receipt remain separate evidence." : metadata.content_available === true ? "Provider content is available." : "Current provider content availability is unknown.";
12106
- const expiry = metadata.content_expires_at === null ? "No automatic content expiry is scheduled." : metadata.content_expires_at !== void 0 ? `Automatic content expiry: ${new Date(metadata.content_expires_at).toISOString()}. A passed deadline alone does not prove content is unavailable.` : "Current automatic content expiry is unknown.";
12107
- const save = metadata.content_available === false ? `Check existing local saves and 'dvm receipts verify ${human ? shellQuoteArg(jobId) : guidanceJobArg(jobId)}' for stored receipt evidence.` : `Save message output with 'dvm messages ${human ? shellQuoteArg(jobId) : guidanceJobArg(jobId)} --no-stream > messages.json'. For portable jobs, retain your original --endpoint and --job-token options before the redirection, or keep DVM_JOB_ENDPOINT and DVM_JOB_TOKEN set. Use '--human' to save artifacts to private temporary files at the printed paths. Reads do not extend expiry.`;
12108
- return {
12109
- ...metadata,
12110
- content_metadata_source: observed ? "provider" : "unknown",
12111
- content_metadata_known: known,
12112
- content_hint: `${availability} ${expiry} ${save}`
12113
- };
12114
- }
12115
- async function observeJobContent(jobId, transport, ref, options) {
12116
- try {
12117
- const status2 = await transport.status(jobId, ref, {
12118
- ...options,
12119
- timeoutMs: options.timeoutMs > 0 ? Math.min(options.timeoutMs, 5e3) : 5e3
12120
- });
12121
- captureDrawFundingReceipts(jobId, status2.drawFundingReceipts, { endpoint: ref.endpoint });
12122
- return parseJobContent(status2);
12123
- } catch {
12124
- return void 0;
12125
- }
12126
- }
12127
-
12128
11885
  // src/lib/job-envelope.ts
12129
11886
  function buildJobEnvelope(opts) {
12130
11887
  const envelope = {
@@ -12235,6 +11992,14 @@ var HttpsTransport = class {
12235
11992
  }
12236
11993
  throw err;
12237
11994
  }
11995
+ if (res.status === 404) {
11996
+ await res.body?.cancel();
11997
+ throw new DvmError(
11998
+ "not_a_dvm_endpoint",
11999
+ `No DVM descriptor was found at ${url}.`,
12000
+ "Check the DVM base URL: it must serve /v1/info. A capability URL must end in a name advertised by its parent DVM."
12001
+ );
12002
+ }
12238
12003
  if (!res.ok) {
12239
12004
  throw providerResponseError(
12240
12005
  "provider_error",
@@ -12277,13 +12042,15 @@ var HttpsTransport = class {
12277
12042
  ...builder ? { builder } : {}
12278
12043
  };
12279
12044
  }
12280
- async quote(provider, job) {
12045
+ async quote(provider, job, options) {
12281
12046
  const url = `${provider.endpoint}/v1/quote`;
12282
12047
  const body = JSON.stringify(envelopeToPayload(job));
12048
+ const signal = options?.timeoutMs && options.timeoutMs > 0 ? AbortSignal.timeout(options.timeoutMs) : void 0;
12283
12049
  const res = await dvmFetch(url, {
12284
12050
  method: "POST",
12285
12051
  headers: { "Content-Type": "application/json" },
12286
- body
12052
+ body,
12053
+ signal
12287
12054
  });
12288
12055
  captureTraceId(res);
12289
12056
  if (!res.ok) {
@@ -12295,7 +12062,7 @@ var HttpsTransport = class {
12295
12062
  const data = await res.json();
12296
12063
  const upfront = parseUpfront(data);
12297
12064
  const description = typeof data.description === "string" ? data.description : "";
12298
- const advisorySats = await deriveAdvisorySats(upfront, data);
12065
+ const advisorySats = await deriveAdvisorySats(upfront, data, options?.btcRate);
12299
12066
  const quote2 = {
12300
12067
  upfront,
12301
12068
  description,
@@ -13013,7 +12780,7 @@ function x402RequiredUsdcMicro(required) {
13013
12780
  }
13014
12781
  return required.accepts.at(0)?.maxAmountRequired;
13015
12782
  }
13016
- var YIELD_TYPES2 = /* @__PURE__ */ new Set(["prompt", "payment-request", "working", "complete", "cancel"]);
12783
+ var YIELD_TYPES = /* @__PURE__ */ new Set(["prompt", "payment-request", "working", "complete", "cancel"]);
13017
12784
  async function parseSSEStream(res, options, recognize = (message2) => message2) {
13018
12785
  const messages2 = [];
13019
12786
  if (!res.body) {
@@ -13040,7 +12807,7 @@ async function parseSSEStream(res, options, recognize = (message2) => message2)
13040
12807
  const msg = recognize(JSON.parse(json2));
13041
12808
  messages2.push(msg);
13042
12809
  options?.onMessage?.(msg);
13043
- if (YIELD_TYPES2.has(msg.type)) {
12810
+ if (YIELD_TYPES.has(msg.type)) {
13044
12811
  if (msg.type === "complete") lastReason = "complete";
13045
12812
  else if (msg.type === "cancel") lastReason = "cancel";
13046
12813
  else lastReason = "yield";
@@ -13231,14 +12998,15 @@ function parseUpfront(data) {
13231
12998
  };
13232
12999
  }
13233
13000
  }
13234
- return { amount: 0, currency: "usd" };
13001
+ return unknownUpfrontPrice();
13235
13002
  }
13236
13003
  function exactMicro(raw2) {
13237
13004
  return typeof raw2 === "number" && Number.isSafeInteger(raw2) && raw2 > 0 ? raw2 : void 0;
13238
13005
  }
13239
- async function deriveAdvisorySats(upfront, data) {
13006
+ async function deriveAdvisorySats(upfront, data, btcRate) {
13240
13007
  if (typeof data.price_msats === "number") return data.price_msats;
13241
13008
  if (upfront.currency !== "usd" || upfront.amount <= 0) return void 0;
13009
+ if (btcRate !== void 0) return Number.isFinite(btcRate) && btcRate > 0 ? usdToMsats(upfront.amount, btcRate) : void 0;
13242
13010
  try {
13243
13011
  const rate = await fetchBtcUsdRate();
13244
13012
  return usdToMsats(upfront.amount, rate);
@@ -13654,7 +13422,7 @@ function resolveDvmReference(raw2) {
13654
13422
  function isValidHandle(handle) {
13655
13423
  return handle.length >= 2 && handle.length <= 20 && HANDLE_RE.test(handle) && !handle.includes("--");
13656
13424
  }
13657
- function resolveCapability(info2, requested, dvmId) {
13425
+ function resolveCapability(info2, requested, dvmId, endpoint) {
13658
13426
  const caps = info2.capabilities ? Object.keys(info2.capabilities) : [];
13659
13427
  const reference = dvmId ?? "this endpoint";
13660
13428
  if (caps.length === 0) {
@@ -13669,7 +13437,7 @@ function resolveCapability(info2, requested, dvmId) {
13669
13437
  throw new DvmError(
13670
13438
  "unknown_capability",
13671
13439
  `"${requested}" is not a capability of ${reference}.`,
13672
- dvmId ? `Pass -d ${dvmId}/<capability> using a name from available_capabilities.` : "Choose a name from available_capabilities. Run `dvm search` to find a qualified identifier.",
13440
+ capabilityRetryHint(caps, dvmId, endpoint),
13673
13441
  { available_capabilities: caps, _provider_fields: ["available_capabilities"] }
13674
13442
  );
13675
13443
  }
@@ -13677,10 +13445,34 @@ function resolveCapability(info2, requested, dvmId) {
13677
13445
  throw new DvmError(
13678
13446
  "ambiguous_capability",
13679
13447
  `${reference} has multiple capabilities; specify one from available_capabilities.`,
13680
- dvmId ? `Pass -d ${dvmId}/<capability> using a name from available_capabilities.` : "Run `dvm search` to find a qualified identifier for the capability you need.",
13448
+ capabilityRetryHint(caps, dvmId, endpoint),
13681
13449
  { available_capabilities: caps, _provider_fields: ["available_capabilities"] }
13682
13450
  );
13683
13451
  }
13452
+ function capabilityQuoteCommand(endpoint, capability, dvmId) {
13453
+ const target = dvmId ? `-d ${shellQuoteArg(formatIdentifier(dvmId, capability))}` : `--endpoint ${shellQuoteArg(`${endpoint.replace(/\/+$/, "")}/${encodeURIComponent(capability)}`)}`;
13454
+ return `dvm quote ${target}`;
13455
+ }
13456
+ function capabilityRetryHint(caps, dvmId, endpoint) {
13457
+ const capability = caps.find((name) => TAG_NAME_RE.test(name));
13458
+ if (!capability || !dvmId && !endpoint) {
13459
+ return endpoint ? `Inspect the available_capabilities with \`dvm describe ${shellQuoteArg(endpoint)}\`.` : "Choose a name from available_capabilities and append /<capability> to your DVM reference.";
13460
+ }
13461
+ const command = capabilityQuoteCommand(endpoint ?? "", capability, dvmId);
13462
+ let alternate = "";
13463
+ if (endpoint && !dvmId) {
13464
+ const url = new URL(endpoint);
13465
+ if (url.protocol === "https:" && !url.port && (url.pathname === "/" || url.pathname === "") && url.hostname.endsWith(".dvmkit.ai")) {
13466
+ const hostId = url.hostname.slice(0, -".dvmkit.ai".length);
13467
+ try {
13468
+ parseDvmIdentifier(hostId);
13469
+ alternate = ` Or \`${capabilityQuoteCommand(endpoint, capability, hostId)} --data '{}'\`.`;
13470
+ } catch {
13471
+ }
13472
+ }
13473
+ }
13474
+ return `Try \`${command} --data '{}'\` using a name from available_capabilities. Replace --data '{}' with the input for that capability.${alternate}`;
13475
+ }
13684
13476
 
13685
13477
  // src/commands/dvm-identity.ts
13686
13478
  function dvmIdentity(dvmId, capability) {
@@ -13703,7 +13495,12 @@ async function cancelWithAccess(jobId, opts, access) {
13703
13495
  progressNotice("Cancelling job...", opts.human);
13704
13496
  await transport.cancel(jobId, opts.reason, ref, { jobToken });
13705
13497
  transport.close();
13706
- if (!access.endpointOverridden) markJobTerminal(jobId, "cancelled", {});
13498
+ if (!access.endpointOverridden) markJobTerminal(
13499
+ jobId,
13500
+ "cancelled",
13501
+ opts.reason !== void 0 ? { message: opts.reason } : {},
13502
+ { callerCancelled: true }
13503
+ );
13707
13504
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
13708
13505
  if (opts.human) {
13709
13506
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
@@ -17821,6 +17618,85 @@ function invalidOperation(message2, hint) {
17821
17618
  return new DvmError("invalid_argument", message2, hint);
17822
17619
  }
17823
17620
 
17621
+ // src/lib/warmup-provider.ts
17622
+ var DEFAULT_BUDGET_MS = 3e4;
17623
+ var DEFAULT_MAX_ATTEMPTS = 4;
17624
+ var DEFAULT_BASE_BACKOFF_MS = 400;
17625
+ var MAX_BACKOFF_MS = 4e3;
17626
+ async function warmupProvider(transport, ref, options = {}) {
17627
+ const budgetMs = options.budgetMs ?? DEFAULT_BUDGET_MS;
17628
+ const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
17629
+ const baseBackoffMs = options.baseBackoffMs ?? DEFAULT_BASE_BACKOFF_MS;
17630
+ const sleep = options.sleep ?? defaultSleep2;
17631
+ const { endpoint } = ref;
17632
+ const deadline = Date.now() + budgetMs;
17633
+ let lastErr;
17634
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
17635
+ const remaining = deadline - Date.now();
17636
+ if (remaining <= 0) break;
17637
+ const attemptsLeft = maxAttempts - attempt + 1;
17638
+ const timeoutMs = Math.max(1, Math.floor(remaining / attemptsLeft));
17639
+ try {
17640
+ return await transport.describe(ref, { timeoutMs });
17641
+ } catch (err) {
17642
+ lastErr = err;
17643
+ if (err instanceof DvmError && ["unsupported_version", "not_a_dvm_endpoint"].includes(err.code)) throw err;
17644
+ const budgetLeft = deadline - Date.now();
17645
+ if (attempt >= maxAttempts || budgetLeft <= 0) break;
17646
+ const futureAttempts = maxAttempts - attempt;
17647
+ const backoff = Math.min(
17648
+ baseBackoffMs * 2 ** (attempt - 1),
17649
+ MAX_BACKOFF_MS,
17650
+ Math.max(0, budgetLeft - futureAttempts)
17651
+ );
17652
+ if (backoff > 0) await sleep(backoff);
17653
+ }
17654
+ }
17655
+ if (isAbortError(lastErr) || lastErr instanceof DvmError && lastErr.code === "timeout") {
17656
+ throw new DvmError(
17657
+ "endpoint_unreachable",
17658
+ `Provider at ${endpoint} did not respond within ${budgetMs / 1e3}s.`,
17659
+ "The endpoint may be down or the address may be incorrect. Check with 'dvm info <endpoint>'."
17660
+ );
17661
+ }
17662
+ throw new DvmError(
17663
+ "endpoint_unreachable",
17664
+ `Could not reach provider at ${endpoint}: ${lastErr instanceof Error ? lastErr.message : String(lastErr)}`,
17665
+ "Check the endpoint URL and your network connection."
17666
+ );
17667
+ }
17668
+ var defaultSleep2 = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
17669
+
17670
+ // src/lib/resolve-provider-endpoint.ts
17671
+ async function resolveProviderEndpoint2(transport, input, options = {}) {
17672
+ const endpoint = normalizeProviderEndpoint(input);
17673
+ const budgetMs = options.budgetMs ?? 3e4;
17674
+ const start = Date.now();
17675
+ try {
17676
+ return { endpoint, info: await warmupProvider(transport, { endpoint }, { ...options, budgetMs }) };
17677
+ } catch (error) {
17678
+ if (!options.capabilityPath || !(error instanceof DvmError) || error.code !== "not_a_dvm_endpoint") {
17679
+ throw error;
17680
+ }
17681
+ const url = new URL(endpoint);
17682
+ const slash = url.pathname.lastIndexOf("/");
17683
+ const segment = url.pathname.slice(slash + 1);
17684
+ if (!segment) throw error;
17685
+ let capability;
17686
+ try {
17687
+ capability = decodeURIComponent(segment);
17688
+ } catch {
17689
+ throw error;
17690
+ }
17691
+ const parent = `${url.origin}${url.pathname.slice(0, slash)}`;
17692
+ const remaining = budgetMs - (Date.now() - start);
17693
+ if (remaining <= 0) throw error;
17694
+ const info2 = await warmupProvider(transport, { endpoint: parent }, { ...options, budgetMs: remaining });
17695
+ if (!info2.capabilities || Object.keys(info2.capabilities).length === 0) throw error;
17696
+ return { endpoint: parent, info: info2, capability };
17697
+ }
17698
+ }
17699
+
17824
17700
  // src/commands/describe.ts
17825
17701
  async function describe(input, opts) {
17826
17702
  let endpoint;
@@ -17830,14 +17706,21 @@ async function describe(input, opts) {
17830
17706
  } else if (/^https?:\/\//.test(input)) {
17831
17707
  endpoint = input;
17832
17708
  } else {
17833
- const resolved = resolveDvmReference(input);
17834
- endpoint = resolved.endpoint;
17835
- qualifiedDvmId = resolved.qualified?.dvmId;
17709
+ const resolved2 = resolveDvmReference(input);
17710
+ endpoint = resolved2.endpoint;
17711
+ qualifiedDvmId = resolved2.qualified?.dvmId;
17836
17712
  }
17837
17713
  const transport = createDvmTransport();
17838
- const ref = { endpoint };
17839
17714
  progressNotice("Fetching provider info...", opts.human);
17840
- const providerInfo = await transport.describe(ref);
17715
+ const resolved = await resolveProviderEndpoint2(transport, endpoint, {
17716
+ capabilityPath: input.startsWith("@") || /^https?:\/\//.test(input),
17717
+ maxAttempts: 1
17718
+ });
17719
+ endpoint = resolved.endpoint;
17720
+ const providerInfo = resolved.info;
17721
+ if (resolved.capability !== void 0) {
17722
+ resolveCapability(providerInfo, resolved.capability, qualifiedDvmId, endpoint);
17723
+ }
17841
17724
  if (opts.human) {
17842
17725
  info(providerInfo.name ?? "(unnamed)");
17843
17726
  if (providerInfo.about) info(` ${providerInfo.about}`);
@@ -17873,7 +17756,7 @@ function renderCapabilitiesHuman(providerInfo, endpoint, qualifiedDvmId) {
17873
17756
  info(` ${capName}`);
17874
17757
  if (cap2.description) info(` ${cap2.description}`);
17875
17758
  const identifier = qualifiedDvmId ? multiCap ? `${qualifiedDvmId}/${capName}` : qualifiedDvmId : void 0;
17876
- const quoteCommand = identifier ? `dvm quote -d ${identifier}` : `dvm quote --endpoint ${endpoint}`;
17759
+ const quoteCommand = identifier ? `dvm quote -d ${identifier}` : capabilityQuoteCommand(endpoint, capName);
17877
17760
  const priceLine = formatCapabilityPrice(cap2.pricing, quoteCommand);
17878
17761
  if (priceLine) info(` ${priceLine}`);
17879
17762
  const schema = cap2.input_schema;
@@ -18449,7 +18332,7 @@ function x402WrongAssetHint(asset) {
18449
18332
  }
18450
18333
 
18451
18334
  // src/lib/build-freshness.ts
18452
- import { existsSync as existsSync3, readdirSync, statSync as statSync2 } from "fs";
18335
+ import { existsSync as existsSync3, readdirSync, statSync } from "fs";
18453
18336
  import { dirname as dirname2, join as join3 } from "path";
18454
18337
  import { fileURLToPath as fileURLToPath2 } from "url";
18455
18338
  var EXTRA_SOURCES = ["package.json", "tsup.config.ts"];
@@ -18475,7 +18358,7 @@ function checkBuildFreshness(opts) {
18475
18358
  }
18476
18359
  const srcDir = join3(root, "src");
18477
18360
  if (!existsSync3(srcDir)) return skipped("no_source_tree");
18478
- const builtAtMs = statSync2(bundlePath).mtimeMs;
18361
+ const builtAtMs = statSync(bundlePath).mtimeMs;
18479
18362
  const newer = [];
18480
18363
  let newestMs = 0;
18481
18364
  const visit = (dir, rel, budget2) => {
@@ -18490,7 +18373,7 @@ function checkBuildFreshness(opts) {
18490
18373
  continue;
18491
18374
  }
18492
18375
  if (!entry.isFile()) continue;
18493
- const mtimeMs = statSync2(abs).mtimeMs;
18376
+ const mtimeMs = statSync(abs).mtimeMs;
18494
18377
  if (mtimeMs > newestMs) newestMs = mtimeMs;
18495
18378
  if (mtimeMs > builtAtMs) newer.push({ path: relPath, mtimeMs });
18496
18379
  }
@@ -18500,7 +18383,7 @@ function checkBuildFreshness(opts) {
18500
18383
  for (const name of EXTRA_SOURCES) {
18501
18384
  const abs = join3(root, name);
18502
18385
  if (!existsSync3(abs)) continue;
18503
- const mtimeMs = statSync2(abs).mtimeMs;
18386
+ const mtimeMs = statSync(abs).mtimeMs;
18504
18387
  if (mtimeMs > newestMs) newestMs = mtimeMs;
18505
18388
  if (mtimeMs > builtAtMs) newer.push({ path: name, mtimeMs });
18506
18389
  }
@@ -18525,7 +18408,7 @@ function findPackageRoot(start) {
18525
18408
  }
18526
18409
 
18527
18410
  // src/lib/caller-state.ts
18528
- import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync3, statSync as statSync3 } from "fs";
18411
+ import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync3, statSync as statSync2 } from "fs";
18529
18412
  import { basename, join as join4 } from "path";
18530
18413
  function detectSetupState() {
18531
18414
  return {
@@ -18680,7 +18563,7 @@ function checkOne(spec) {
18680
18563
  checkSecretDirectory(spec.path, row);
18681
18564
  } else if (spec.secret) {
18682
18565
  try {
18683
- const mode = statSync3(spec.path).mode & 511;
18566
+ const mode = statSync2(spec.path).mode & 511;
18684
18567
  const modeOctal = octalMode(mode);
18685
18568
  row.modeOk = mode === 384;
18686
18569
  row.modeOctal = modeOctal;
@@ -18699,7 +18582,7 @@ function checkSecretDirectory(dir, row) {
18699
18582
  const offenders = [];
18700
18583
  for (const name of readdirSync2(dir)) {
18701
18584
  const path = join4(dir, name);
18702
- const stat2 = statSync3(path);
18585
+ const stat2 = statSync2(path);
18703
18586
  if (!stat2.isFile()) continue;
18704
18587
  const mode = stat2.mode & 511;
18705
18588
  if (mode !== 384) offenders.push({ path, modeOctal: octalMode(mode) });
@@ -18730,7 +18613,7 @@ function readBtcRateCacheAge(now = Date.now()) {
18730
18613
  }
18731
18614
 
18732
18615
  // src/lib/mnemonic-backups.ts
18733
- import { readdirSync as readdirSync3, statSync as statSync4 } from "fs";
18616
+ import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
18734
18617
  import { basename as basename2, dirname as dirname3, join as join5 } from "path";
18735
18618
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
18736
18619
  const dir = dirname3(mnemonicFile);
@@ -18744,7 +18627,7 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
18744
18627
  }
18745
18628
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
18746
18629
  const path = join5(dir, name);
18747
- const stat2 = statSync4(path);
18630
+ const stat2 = statSync3(path);
18748
18631
  if (!stat2.isFile()) return null;
18749
18632
  const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
18750
18633
  return {
@@ -20802,7 +20685,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
20802
20685
  }
20803
20686
 
20804
20687
  // src/lib/feedback-nudges.ts
20805
- import { existsSync as existsSync5, readFileSync as readFileSync5, renameSync, unlinkSync, writeFileSync } from "fs";
20688
+ import { existsSync as existsSync5, readFileSync as readFileSync5, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
20806
20689
 
20807
20690
  // src/lib/feedback-notice.ts
20808
20691
  function buildFeedbackNudge(args) {
@@ -20946,9 +20829,9 @@ function coercePerDvm(perDvm) {
20946
20829
  function saveState(state) {
20947
20830
  ensureConfigDir();
20948
20831
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
20949
- writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
20832
+ writeFileSync2(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
20950
20833
  try {
20951
- renameSync(tmp, FEEDBACK_NUDGES_FILE);
20834
+ renameSync2(tmp, FEEDBACK_NUDGES_FILE);
20952
20835
  } catch (err) {
20953
20836
  try {
20954
20837
  unlinkSync(tmp);
@@ -20960,7 +20843,7 @@ function saveState(state) {
20960
20843
  var nudgedThisInvocation = false;
20961
20844
 
20962
20845
  // src/lib/platform.ts
20963
- import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "fs";
20846
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
20964
20847
  import { homedir } from "os";
20965
20848
  import { join as join6 } from "path";
20966
20849
  function getPlatformUrl() {
@@ -21537,7 +21420,7 @@ import {
21537
21420
  readdirSync as readdirSync4,
21538
21421
  rmdirSync,
21539
21422
  unlinkSync as unlinkSync2,
21540
- writeFileSync as writeFileSync3
21423
+ writeFileSync as writeFileSync4
21541
21424
  } from "fs";
21542
21425
  import { tmpdir } from "os";
21543
21426
  import { join as join7 } from "path";
@@ -21599,7 +21482,7 @@ var ArtifactSaveSession = class {
21599
21482
  path = join7(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
21600
21483
  fd = openSync2(path, "wx", FILE_MODE);
21601
21484
  created = true;
21602
- writeFileSync3(fd, buf);
21485
+ writeFileSync4(fd, buf);
21603
21486
  closeSync2(fd);
21604
21487
  fd = void 0;
21605
21488
  chmodSync(path, FILE_MODE);
@@ -21664,50 +21547,24 @@ function formatBytes(bytes) {
21664
21547
  return `${bytes.toLocaleString("en-US")} bytes`;
21665
21548
  }
21666
21549
 
21667
- // src/lib/completion-hints.ts
21668
- function buildCompletionHintFields(jobId, input) {
21669
- const out = {};
21670
- if (input.hasArtifacts !== void 0) out.has_artifacts = input.hasArtifacts;
21671
- if (input.artifactCount !== void 0) out.artifact_count = input.artifactCount;
21672
- if (input.payloadIn) out.payload_in = input.payloadIn;
21673
- const hint = nextStepHint(jobId, input.payloadIn, input.artifactCount);
21674
- if (hint) out.next_step_hint = hint;
21675
- return out;
21676
- }
21677
- function nextStepHint(jobId, payloadIn, artifactCount, human = false) {
21678
- if (payloadIn !== "messages") return void 0;
21679
- const noun = artifactCount === 1 ? "artifact" : "artifacts";
21680
- return `Run 'dvm messages ${human ? shellQuoteArg(jobId) : guidanceJobArg(jobId)} --no-stream' to fetch the ${noun}.`;
21681
- }
21682
- function completionSnapshot(src) {
21683
- const out = {};
21684
- if (src.summary !== void 0) out.summary = src.summary;
21685
- if (src.message !== void 0) out.message = src.message;
21686
- if (src.hasArtifacts !== void 0) out.hasArtifacts = src.hasArtifacts;
21687
- if (src.artifactCount !== void 0) out.artifactCount = src.artifactCount;
21688
- if (src.payloadIn) out.payloadIn = src.payloadIn;
21689
- return out;
21690
- }
21691
- function completionFromMessages(messages2) {
21692
- const complete = messages2.findLast((m) => m.type === "complete");
21693
- const summary = complete?.type === "complete" ? complete.content.summary : void 0;
21694
- const artifactCount = messages2.filter((m) => m.type === "artifact").length;
21695
- const out = {
21696
- hasArtifacts: artifactCount > 0,
21697
- payloadIn: artifactCount > 0 ? "messages" : "summary"
21698
- };
21699
- if (summary !== void 0) out.summary = summary;
21700
- if (artifactCount > 0) out.artifactCount = artifactCount;
21701
- return out;
21702
- }
21703
-
21704
21550
  // src/lib/stream-outcome.ts
21705
21551
  function persistStreamOutcome(outcome) {
21706
- const { jobId, messages: messages2, cursor, afterSeq, extra } = outcome;
21707
- const terminal = streamTerminalStatus(messages2);
21552
+ const { jobId, messages: messages2, cursor, afterSeq, extra, providerStatus } = outcome;
21553
+ const stored = loadJob(jobId);
21554
+ const callerCancelled = outcome.callerCancelled ?? stored?.callerCancelled;
21555
+ const terminal = streamTerminalStatus(messages2, { providerStatus, callerCancelled });
21708
21556
  const log = terminal ? fullMessageLog(jobId, messages2, afterSeq) : void 0;
21709
- if (terminal && log) {
21710
- const completion = completionFromMessages(log);
21557
+ const providerTerminal = providerStatus?.status && isTerminalJobStatus(providerStatus.status);
21558
+ if (terminal && (log || providerTerminal)) {
21559
+ const saved = stored?.status === terminal ? stored.completion : void 0;
21560
+ const fromLog = log?.some((m) => m.type === "complete" || m.type === "cancel") ? completionFromMessages(log) : void 0;
21561
+ const retained = saved ?? fromLog;
21562
+ const completion = providerStatus?.content_available === false && retained ? retained : {
21563
+ ...saved,
21564
+ ...fromLog,
21565
+ ...terminal === "cancelled" && callerCancelled && stored?.completion?.message !== void 0 ? { message: stored.completion.message } : {},
21566
+ ...providerTerminal ? completionSnapshot(providerStatus) : {}
21567
+ };
21711
21568
  markJobTerminal(jobId, terminal, completion, {
21712
21569
  messageCursor: cursor,
21713
21570
  ...extra
@@ -21717,10 +21574,13 @@ function persistStreamOutcome(outcome) {
21717
21574
  updateJob(jobId, { messageCursor: cursor });
21718
21575
  return void 0;
21719
21576
  }
21720
- function streamTerminalStatus(messages2) {
21577
+ function streamTerminalStatus(messages2, context = {}) {
21578
+ const providerStatus = context.providerStatus?.status;
21579
+ if (providerStatus && isTerminalJobStatus(providerStatus)) return providerStatus;
21721
21580
  const last = messages2.findLast((m) => m.type === "complete" || m.type === "cancel");
21722
21581
  if (!last) return void 0;
21723
- return last.type === "complete" ? "completed" : "cancelled";
21582
+ if (last.type === "complete") return "completed";
21583
+ return context.callerCancelled ? "cancelled" : "failed";
21724
21584
  }
21725
21585
  function fullMessageLog(jobId, messages2, afterSeq) {
21726
21586
  if (afterSeq === 0) return messages2;
@@ -21788,7 +21648,7 @@ function formatMessageHuman(msg, jobId, artifactSession) {
21788
21648
  const noun = msg.content.reason === "change" ? "change" : "refund";
21789
21649
  info(`[${msg.seq}] ${prefix} sent ${noun}: ${amount}`);
21790
21650
  } else {
21791
- info(`[${msg.seq}] ${prefix} paid: ${amount}`);
21651
+ info(`[${msg.seq}] ${prefix} sent payment: ${amount}`);
21792
21652
  }
21793
21653
  break;
21794
21654
  }
@@ -21804,7 +21664,7 @@ function formatMessageHuman(msg, jobId, artifactSession) {
21804
21664
  renderProgressLine(msg.content, msg.seq);
21805
21665
  break;
21806
21666
  case "cancel":
21807
- info(`[${msg.seq}] Cancelled${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
21667
+ info(`[${msg.seq}] Job ended${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
21808
21668
  break;
21809
21669
  default:
21810
21670
  info(`[${seq}] ${prefix} sent a message of type "${type}".`);
@@ -21824,7 +21684,8 @@ function nextActionHuman(action) {
21824
21684
  if (action.type === "respond") {
21825
21685
  return `Next: ${display} Provider is waiting for your input. ${command ? `Run \`${command}\`.` : action.hint}`;
21826
21686
  }
21827
- return `Next: Payment required to continue: ${display}${display.endsWith(".") ? "" : "."} Run \`${command ?? `dvm pay ${shellQuoteArg(action.job_id)}`}\`.`;
21687
+ const thresholdHint = action.hint.match(/ For the next run, use --auto-pay-below .+$/)?.[0] ?? "";
21688
+ return `Next: Payment required to continue: ${display}${display.endsWith(".") ? "" : "."} Run \`${command ?? `dvm pay ${shellQuoteArg(action.job_id)}`}\`.${thresholdHint}`;
21828
21689
  }
21829
21690
  case "poll": {
21830
21691
  const hint = typeof action.hint === "string" ? action.hint : action.hint.text;
@@ -21892,6 +21753,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
21892
21753
  const snapshot = await readWithRetry(() => opts.transport.status(opts.jobId, opts.provider, readOptions()));
21893
21754
  if (!snapshot) break;
21894
21755
  if (isTerminalJobStatus(snapshot.status)) {
21756
+ result.providerStatus = snapshot;
21895
21757
  result.nextAction = null;
21896
21758
  const history = await readWithRetry(() => opts.transport.getMessages(opts.jobId, result.cursor, opts.provider, readOptions()));
21897
21759
  if (!history) break;
@@ -22007,16 +21869,17 @@ async function messagesWithAccess(jobId, opts, access) {
22007
21869
  const json2 = (data) => providerJobJson(data, !!stored);
22008
21870
  function actionFromMessages(batch) {
22009
21871
  const answered = access.endpointOverridden ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(jobId);
22010
- const action = computeNextAction(jobId, batch.filter((message2) => !answered.has(message2.seq)));
21872
+ const action = computeNextAction(jobId, batch.filter((message2) => !answered.has(message2.seq)), void 0, access.endpointOverridden ? void 0 : stored ?? void 0);
22011
21873
  const request2 = batch.findLast((message2) => message2.type === "payment-request");
22012
21874
  if (action?.type === "pay" && request2 && !access.endpointOverridden && stored?.inFlightPaymentRequestSeqs?.includes(request2.seq))
22013
21875
  return { ...action, hint: paymentInFlightHint(jobId) };
22014
21876
  return action;
22015
21877
  }
22016
- async function resolveNextAction2(action, messages2) {
21878
+ async function resolveNextAction2(action, messages2, observedStatus) {
22017
21879
  if (action?.type === "refund") return action;
21880
+ if (observedStatus && isTerminalJobStatus(observedStatus)) return null;
22018
21881
  if (streamTerminalStatus(messages2) || !access.endpointOverridden && stored && isTerminalJobStatus(stored.status)) return null;
22019
- if (!opts.human) return action;
21882
+ if (!opts.human || opts.wait) return action;
22020
21883
  try {
22021
21884
  const readOptions = { jobToken, timeoutMs: opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 };
22022
21885
  const snapshot = await transport.status(jobId, ref, readOptions);
@@ -22052,19 +21915,18 @@ async function messagesWithAccess(jobId, opts, access) {
22052
21915
  }
22053
21916
  if (!access.endpointOverridden) appendMessages(jobId, msgs);
22054
21917
  const newCursor = maxSeq(msgs, after);
21918
+ const providerStatus2 = await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken });
22055
21919
  if (!access.endpointOverridden) {
22056
- persistStreamOutcome({ jobId, messages: msgs, cursor: newCursor, afterSeq: after });
21920
+ persistStreamOutcome({ jobId, messages: msgs, cursor: newCursor, afterSeq: after, providerStatus: providerStatus2 });
22057
21921
  }
22058
21922
  const refunds = access.endpointOverridden ? [] : await claimInboundPayments(jobId, msgs);
22059
- const nextAction = withRefundNextAction(jobId, actionFromMessages(msgs) ?? (streamTerminalStatus(msgs) || isTerminal ? null : pollNextAction(jobId)), refunds);
22060
- const content2 = jobContentFields(
22061
- jobId,
22062
- await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken }),
22063
- opts.human
22064
- );
22065
- const resolvedAction2 = await resolveNextAction2(nextAction, msgs);
21923
+ const nextAction = withRefundNextAction(jobId, actionFromMessages(msgs) ?? (streamTerminalStatus(msgs, { providerStatus: providerStatus2 }) || isTerminal ? null : pollNextAction(jobId)), refunds);
21924
+ const content2 = jobContentFields(jobId, providerStatus2, opts.human);
21925
+ const resolvedAction2 = await resolveNextAction2(nextAction, msgs, providerStatus2?.status);
21926
+ const settlement2 = observedSettlementFields(jobId, providerStatus2, !access.endpointOverridden);
22066
21927
  transport.close();
22067
21928
  if (opts.human) {
21929
+ if (settlement2.settlement) info(settlement2.settlement.display);
22068
21930
  info(String(content2.content_hint));
22069
21931
  if (msgs.length === 0) {
22070
21932
  info("No new messages.");
@@ -22079,6 +21941,7 @@ async function messagesWithAccess(jobId, opts, access) {
22079
21941
  json2({
22080
21942
  jobId,
22081
21943
  ...content2,
21944
+ ...settlement2,
22082
21945
  messages: msgs.map(serialize),
22083
21946
  cursor: newCursor,
22084
21947
  next_action: resolvedAction2,
@@ -22112,25 +21975,25 @@ async function messagesWithAccess(jobId, opts, access) {
22112
21975
  transport.close();
22113
21976
  throw err;
22114
21977
  }
21978
+ const providerStatus = waitDeadline !== void 0 && Date.now() >= waitDeadline ? void 0 : await observeJobContent(jobId, transport, ref, {
21979
+ timeoutMs: waitDeadline === void 0 ? opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now())),
21980
+ jobToken
21981
+ });
22115
21982
  if (!access.endpointOverridden) {
22116
21983
  persistStreamOutcome({
22117
21984
  jobId,
22118
21985
  messages: result.messages,
22119
21986
  cursor: result.cursor,
22120
- afterSeq: after
21987
+ afterSeq: after,
21988
+ providerStatus: providerStatus ?? result.providerStatus
22121
21989
  });
22122
21990
  }
22123
- const content = jobContentFields(
22124
- jobId,
22125
- waitDeadline !== void 0 && Date.now() >= waitDeadline ? void 0 : await observeJobContent(jobId, transport, ref, {
22126
- timeoutMs: waitDeadline === void 0 ? opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now())),
22127
- jobToken
22128
- }),
22129
- opts.human
22130
- );
22131
- const resolvedAction = opts.wait ? result.nextAction : await resolveNextAction2(result.nextAction, result.messages);
21991
+ const content = jobContentFields(jobId, providerStatus, opts.human);
21992
+ const resolvedAction = await resolveNextAction2(result.nextAction, result.messages, providerStatus?.status ?? result.providerStatus?.status);
21993
+ const settlement = observedSettlementFields(jobId, providerStatus ?? result.providerStatus, !access.endpointOverridden);
22132
21994
  transport.close();
22133
21995
  if (opts.human) {
21996
+ if (settlement.settlement) info(settlement.settlement.display);
22134
21997
  info(String(content.content_hint));
22135
21998
  if (result.messages.length === 0) {
22136
21999
  info("No new messages.");
@@ -22146,6 +22009,7 @@ async function messagesWithAccess(jobId, opts, access) {
22146
22009
  json2({
22147
22010
  jobId,
22148
22011
  ...content,
22012
+ ...settlement,
22149
22013
  messages: result.messages.map(serialize),
22150
22014
  cursor: result.cursor,
22151
22015
  next_action: resolvedAction,
@@ -22208,7 +22072,7 @@ function serialize(msg) {
22208
22072
  }
22209
22073
  case "payment": {
22210
22074
  const amount = paymentAmount(msg);
22211
- const display = msg.from === "provider" ? `${msg.content.reason === "change" ? "Change" : "Refund"} sent: ${amount}` : `Paid: ${amount}`;
22075
+ const display = msg.from === "provider" ? `${msg.content.reason === "change" ? "Change" : "Refund"} sent: ${amount}` : `Payment sent: ${amount}`;
22212
22076
  return { ...base, content: { ...msg.content }, display };
22213
22077
  }
22214
22078
  case "complete": {
@@ -22234,7 +22098,7 @@ function serialize(msg) {
22234
22098
  return { ...base, content, display };
22235
22099
  }
22236
22100
  case "cancel": {
22237
- const display = `Cancelled${msg.content.reason ? `: ${msg.content.reason}` : ""}`;
22101
+ const display = `Job ended${msg.content.reason ? `: ${msg.content.reason}` : ""}`;
22238
22102
  const content = { ...msg.content };
22239
22103
  if (fromProvider && msg.content.reason !== void 0) {
22240
22104
  content.reason = asProviderText(msg.content.reason);
@@ -22273,6 +22137,8 @@ async function messageWithAccess(jobId, text, opts, access) {
22273
22137
  const transport = createDvmTransport();
22274
22138
  progressNotice("Sending message...", opts.human);
22275
22139
  await transport.sendMessage(jobId, outbound, ref, { jobToken });
22140
+ if (msgType === "cancel" && !access.endpointOverridden)
22141
+ markJobTerminal(jobId, "cancelled", { message: text }, { callerCancelled: true });
22276
22142
  const timeoutMs = opts.timeout ? Number(opts.timeout) * 1e3 : void 0;
22277
22143
  const afterSeq = access.endpointOverridden ? 0 : stored?.messageCursor ?? 0;
22278
22144
  const result = await streamLoop({
@@ -22285,10 +22151,17 @@ async function messageWithAccess(jobId, text, opts, access) {
22285
22151
  jobToken,
22286
22152
  persistLocalState: !access.endpointOverridden
22287
22153
  });
22288
- if (!access.endpointOverridden) {
22289
- persistStreamOutcome({ jobId, messages: result.messages, cursor: result.cursor, afterSeq });
22290
- }
22291
- const streamedTerminal = result.nextAction === null ? streamTerminalStatus(result.messages) : void 0;
22154
+ const providerStatus = await observeJobContent(jobId, transport, ref, { timeoutMs: timeoutMs ?? 5e3, jobToken });
22155
+ const outcome = {
22156
+ jobId,
22157
+ messages: result.messages,
22158
+ cursor: result.cursor,
22159
+ afterSeq,
22160
+ providerStatus,
22161
+ callerCancelled: msgType === "cancel" || stored?.callerCancelled
22162
+ };
22163
+ if (!access.endpointOverridden) persistStreamOutcome(outcome);
22164
+ const streamedTerminal = streamTerminalStatus(result.messages, outcome);
22292
22165
  if (streamedTerminal && stored && !access.endpointOverridden) {
22293
22166
  noteFeedbackAfterTerminal({
22294
22167
  jobId,
@@ -22298,13 +22171,11 @@ async function messageWithAccess(jobId, text, opts, access) {
22298
22171
  human: opts.human
22299
22172
  });
22300
22173
  }
22301
- const content = jobContentFields(
22302
- jobId,
22303
- await observeJobContent(jobId, transport, ref, { timeoutMs: timeoutMs ?? 5e3, jobToken }),
22304
- opts.human
22305
- );
22174
+ const content = jobContentFields(jobId, providerStatus, opts.human);
22175
+ const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden);
22306
22176
  transport.close();
22307
22177
  if (opts.human) {
22178
+ if (settlement.settlement) info(settlement.settlement.display);
22308
22179
  info(String(content.content_hint));
22309
22180
  info(`Message sent (type: ${msgType}).`);
22310
22181
  for (const msg of result.messages) {
@@ -22315,6 +22186,7 @@ async function messageWithAccess(jobId, text, opts, access) {
22315
22186
  json2({
22316
22187
  jobId,
22317
22188
  ...content,
22189
+ ...settlement,
22318
22190
  sent: { type: outbound.type, content: outbound.content },
22319
22191
  messages: result.messages.map(serializeMessageForOutput),
22320
22192
  ...takeCreditNoticeFields(),
@@ -22498,12 +22370,14 @@ async function payWithAccess(jobId, opts, access) {
22498
22370
  jobToken,
22499
22371
  persistLocalState: !access.endpointOverridden
22500
22372
  });
22501
- const streamedTerminal = streamResult.nextAction === null ? streamTerminalStatus(streamResult.messages) : void 0;
22373
+ const providerStatus = await observeJobContent(jobId, transport, ref, { timeoutMs: timeoutMs ?? 5e3, jobToken });
22374
+ const streamedTerminal = streamResult.nextAction === null ? streamTerminalStatus(streamResult.messages, { providerStatus, callerCancelled: !access.endpointOverridden && loadJob(jobId)?.callerCancelled }) : void 0;
22502
22375
  const completion = access.endpointOverridden ? streamedTerminal ? completionFromMessages(streamResult.messages) : void 0 : persistStreamOutcome({
22503
22376
  jobId,
22504
22377
  messages: streamResult.messages,
22505
22378
  cursor: streamResult.cursor,
22506
- afterSeq
22379
+ afterSeq,
22380
+ providerStatus
22507
22381
  });
22508
22382
  if (streamedTerminal && !access.endpointOverridden) {
22509
22383
  noteFeedbackAfterTerminal({
@@ -22514,9 +22388,11 @@ async function payWithAccess(jobId, opts, access) {
22514
22388
  human: opts.human
22515
22389
  });
22516
22390
  }
22391
+ const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden);
22517
22392
  transport.close();
22518
22393
  const identifier = stored.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
22519
22394
  if (opts.human) {
22395
+ if (settlement.settlement) info(settlement.settlement.display);
22520
22396
  info(`${paid.display}${identifier ? ` [${identifier}]` : ""}`);
22521
22397
  for (const msg of streamResult.messages) {
22522
22398
  formatMessageHuman(msg, jobId, artifactSession);
@@ -22531,12 +22407,9 @@ async function payWithAccess(jobId, opts, access) {
22531
22407
  jobId,
22532
22408
  ...dvmIdentity(stored.dvmId, stored.capability),
22533
22409
  paid,
22410
+ ...settlement,
22534
22411
  messages: streamResult.messages.map(serializeMessageForOutput),
22535
- // A payment that resumes the handler through to `complete` ends the job
22536
- // here, and this path has no transport receipt to read the outcome off —
22537
- // so without these an agent that pays sees `next_action: null` and can't
22538
- // tell whether the payload is the summary or artifacts it must go fetch
22539
- // Mirrors what `dvm request` renders on the upfront-paid arc.
22412
+ // Retain delivery hints when the payment resumes work through completion.
22540
22413
  ...completion?.summary !== void 0 ? { summary: completion.summary, _provider_fields: ["summary"] } : {},
22541
22414
  ...completion ? buildCompletionHintFields(jobId, completion) : {},
22542
22415
  ...takeCreditNoticeFields(),
@@ -22592,6 +22465,87 @@ function parsePositiveCashuSats(raw2) {
22592
22465
  return value;
22593
22466
  }
22594
22467
 
22468
+ // src/lib/policy.ts
22469
+ function buildPolicy(opts, btcRate) {
22470
+ if (opts.maxPayments === void 0) {
22471
+ throw new DvmError(
22472
+ "missing_max_payments",
22473
+ "Cannot build a spending policy without a payment count cap.",
22474
+ "Pass --max-payments <n> on dvm request. Use 0 for free jobs, 1 for typical paid jobs, or higher for multi-turn flows that may require progressive payments."
22475
+ );
22476
+ }
22477
+ if (!Number.isInteger(opts.maxPayments) || opts.maxPayments < 0) {
22478
+ throw new DvmError(
22479
+ "invalid_max_payments",
22480
+ "Invalid value for --max-payments.",
22481
+ "Pass a non-negative integer (e.g. --max-payments 1)."
22482
+ );
22483
+ }
22484
+ const maxTotalMsats = opts.budget ? parseBudget(opts.budget, btcRate) : 0;
22485
+ const autoPayBelowMsats = opts.autoPayBelow ? parseBudget(opts.autoPayBelow, btcRate) : Math.floor(maxTotalMsats * 0.2);
22486
+ const maxIncrementMsats = opts.maxIncrement ? parseBudget(opts.maxIncrement, btcRate) : maxTotalMsats;
22487
+ return { maxTotalMsats, autoPayBelowMsats, maxIncrementMsats, maxPayments: opts.maxPayments };
22488
+ }
22489
+
22490
+ // src/lib/auto-pay-warning.ts
22491
+ function positive(value) {
22492
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
22493
+ }
22494
+ function autoPayWarnings(quotes, limits, ceiling, btcRate = getLastKnownBtcRate()?.rate ?? 0) {
22495
+ if (!limits.budget && !limits.autoPayBelow) return [];
22496
+ if (!positive(btcRate)) {
22497
+ const quoted = quotes.find((quote2) => quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount) && positive(quote2.priceMsats));
22498
+ btcRate = getLastKnownBtcRate()?.rate ?? (quoted ? quoted.upfront.amount * 1e11 / quoted.priceMsats : 0);
22499
+ }
22500
+ const amounts = [];
22501
+ for (const quote2 of quotes) {
22502
+ if (quote2.upfront?.currency === "usd" && positive(quote2.upfront.amount)) amounts.push(quote2.upfront.amount);
22503
+ const rate = quote2.rate;
22504
+ if (rate?.per_unit?.currency === "usd" && positive(rate.per_unit.amount) && positive(rate.max_units)) {
22505
+ const maximum2 = Number((rate.per_unit.amount * rate.max_units).toPrecision(15));
22506
+ if (positive(maximum2)) amounts.push(maximum2);
22507
+ }
22508
+ }
22509
+ let source = "quote";
22510
+ if (!amounts.length && ceiling && typeof ceiling === "object") {
22511
+ const max = ceiling;
22512
+ if (max.currency === "usd" && positive(max.amount)) {
22513
+ amounts.push(max.amount);
22514
+ source = "provider_ceiling";
22515
+ }
22516
+ }
22517
+ if (!amounts.length) return [];
22518
+ const maximumUsd = Math.max(...amounts);
22519
+ let bound;
22520
+ let maximum;
22521
+ let flag;
22522
+ if (positive(btcRate)) {
22523
+ const policy = buildPolicy({ ...limits, maxPayments: 0 }, btcRate);
22524
+ const maximumMsats = usdToMsats(maximumUsd, btcRate);
22525
+ if (!Number.isSafeInteger(maximumMsats) || maximumMsats <= policy.autoPayBelowMsats) return [];
22526
+ bound = `${policy.autoPayBelowMsats} msats`;
22527
+ maximum = `$${maximumUsd} USD (${maximumMsats} msats)`;
22528
+ flag = String(maximumMsats);
22529
+ } else {
22530
+ const declared = limits.autoPayBelow ?? limits.budget;
22531
+ if (!declared || !/^\$\d+(?:\.\d+)?$/.test(declared)) return [];
22532
+ const boundUsd = Number(declared.slice(1)) * (limits.autoPayBelow ? 1 : 0.2);
22533
+ if (!Number.isFinite(boundUsd) || maximumUsd <= boundUsd) return [];
22534
+ bound = `$${Number(boundUsd.toPrecision(15))} USD`;
22535
+ maximum = `$${maximumUsd} USD`;
22536
+ flag = `'$${maximumUsd}'`;
22537
+ }
22538
+ const subject = source === "provider_ceiling" ? "this provider's advertised job ceiling" : "the quote's largest possible charge";
22539
+ return [{
22540
+ code: "auto_pay_bound_exceeded",
22541
+ bound,
22542
+ maximum,
22543
+ auto_pay_below: flag,
22544
+ source,
22545
+ display: `Auto-pay bound: ${bound}; ${subject}: ${maximum}. For the next request, use --auto-pay-below ${flag} within your approved budget. The total budget, increment and payment-count limits still apply.`
22546
+ }];
22547
+ }
22548
+
22595
22549
  // src/lib/data-flag.ts
22596
22550
  async function resolveDataFlag(raw2) {
22597
22551
  let jsonText;
@@ -22822,57 +22776,11 @@ function isPlainObject2(value) {
22822
22776
  return typeof value === "object" && value !== null && !Array.isArray(value);
22823
22777
  }
22824
22778
 
22825
- // src/lib/warmup-provider.ts
22826
- var DEFAULT_BUDGET_MS = 3e4;
22827
- var DEFAULT_MAX_ATTEMPTS = 4;
22828
- var DEFAULT_BASE_BACKOFF_MS = 400;
22829
- var MAX_BACKOFF_MS = 4e3;
22830
- async function warmupProvider(transport, ref, options = {}) {
22831
- const budgetMs = options.budgetMs ?? DEFAULT_BUDGET_MS;
22832
- const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
22833
- const baseBackoffMs = options.baseBackoffMs ?? DEFAULT_BASE_BACKOFF_MS;
22834
- const sleep = options.sleep ?? defaultSleep2;
22835
- const { endpoint } = ref;
22836
- const deadline = Date.now() + budgetMs;
22837
- let lastErr;
22838
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
22839
- const remaining = deadline - Date.now();
22840
- if (remaining <= 0) break;
22841
- const attemptsLeft = maxAttempts - attempt + 1;
22842
- const timeoutMs = Math.max(1, Math.floor(remaining / attemptsLeft));
22843
- try {
22844
- return await transport.describe(ref, { timeoutMs });
22845
- } catch (err) {
22846
- lastErr = err;
22847
- if (err instanceof DvmError && err.code === "unsupported_version") throw err;
22848
- const budgetLeft = deadline - Date.now();
22849
- if (attempt >= maxAttempts || budgetLeft <= 0) break;
22850
- const futureAttempts = maxAttempts - attempt;
22851
- const backoff = Math.min(
22852
- baseBackoffMs * 2 ** (attempt - 1),
22853
- MAX_BACKOFF_MS,
22854
- Math.max(0, budgetLeft - futureAttempts)
22855
- );
22856
- if (backoff > 0) await sleep(backoff);
22857
- }
22858
- }
22859
- if (isAbortError(lastErr) || lastErr instanceof DvmError && lastErr.code === "timeout") {
22860
- throw new DvmError(
22861
- "endpoint_unreachable",
22862
- `Provider at ${endpoint} did not respond within ${budgetMs / 1e3}s.`,
22863
- "The endpoint may be down or the address may be incorrect. Check with 'dvm info <endpoint>'."
22864
- );
22865
- }
22866
- throw new DvmError(
22867
- "endpoint_unreachable",
22868
- `Could not reach provider at ${endpoint}: ${lastErr instanceof Error ? lastErr.message : String(lastErr)}`,
22869
- "Check the endpoint URL and your network connection."
22870
- );
22871
- }
22872
- var defaultSleep2 = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
22873
-
22874
22779
  // src/commands/quote.ts
22875
22780
  async function quote(opts) {
22781
+ return withOutputWarnings(() => quoteWithWarnings(opts));
22782
+ }
22783
+ async function quoteWithWarnings(opts) {
22876
22784
  if (!opts.dvm && !opts.endpoint) {
22877
22785
  throw new DvmError(
22878
22786
  "endpoint_required",
@@ -22913,22 +22821,28 @@ async function quote(opts) {
22913
22821
  data = paramsToData(opts.param);
22914
22822
  }
22915
22823
  const transport = createDvmTransport();
22916
- const ref = { endpoint };
22917
22824
  const WARMUP_TIMEOUT_MS = 3e4;
22918
22825
  const warmupStart = Date.now();
22919
22826
  let providerInfo;
22920
22827
  try {
22921
- providerInfo = await warmupProvider(transport, ref, { budgetMs: WARMUP_TIMEOUT_MS });
22828
+ const resolved = await resolveProviderEndpoint2(transport, endpoint, {
22829
+ budgetMs: WARMUP_TIMEOUT_MS,
22830
+ capabilityPath: !opts.dvm
22831
+ });
22832
+ endpoint = resolved.endpoint;
22833
+ requestedCapability ??= resolved.capability;
22834
+ providerInfo = resolved.info;
22922
22835
  } catch (err) {
22923
22836
  transport.close();
22924
22837
  throw err;
22925
22838
  }
22839
+ const ref = { endpoint };
22926
22840
  const warmupMs = Date.now() - warmupStart;
22927
22841
  if (opts.human && warmupMs > 1e3) {
22928
22842
  info(`Provider woke up in ${(warmupMs / 1e3).toFixed(1)}s.`);
22929
22843
  }
22930
22844
  const dvmId = canonicalDvmId;
22931
- const capability = resolveCapability(providerInfo, requestedCapability, dvmId);
22845
+ const capability = resolveCapability(providerInfo, requestedCapability, dvmId, endpoint);
22932
22846
  const identifier = dvmId ? formatIdentifier(dvmId, capability) : endpoint;
22933
22847
  if (opts.human) info(`Quoting ${identifier}...`);
22934
22848
  const inputSchema = providerInfo.capabilities?.[capability]?.input_schema ?? providerInfo.inputSchema;
@@ -22990,11 +22904,18 @@ async function quote(opts) {
22990
22904
  throw new DvmError("no_quotes", "No quotes received from provider.");
22991
22905
  }
22992
22906
  const q = quotes[0];
22907
+ const pricing = providerInfo.capabilities?.[capability]?.pricing;
22908
+ addOutputWarnings(autoPayWarnings([q], {
22909
+ budget: opts.budget ?? config?.defaultBudget,
22910
+ autoPayBelow: opts.autoPayBelow ?? config?.autoPayThreshold
22911
+ }, pricing?.max ?? providerInfo.pricing?.max), opts.human);
22993
22912
  const attestedIdentity = providerDvmIdentity(providerInfo);
22994
22913
  const stored = signerPubkey ? loadCredit(endpoint, signerPubkey, attestedIdentity) : void 0;
22995
22914
  const routeBtcRate = q.priceMsats > 0 && q.upfront.amount > 0 ? q.upfront.amount * 1e11 / q.priceMsats : void 0;
22996
22915
  const probePlan = planProbeDraw({
22997
22916
  stored,
22917
+ capability,
22918
+ quote: q,
22998
22919
  drawCeilingMsats: 0,
22999
22920
  drawCeilingSource: "budget",
23000
22921
  btcRate: routeBtcRate ?? 0,
@@ -23344,6 +23265,7 @@ function listEntryJson(entry, status2, rate) {
23344
23265
  // see `receiptIssuedAtIso`. The raw number stays intact under `receipt`.
23345
23266
  issued_at: receiptIssuedAtIso(entry.receipt),
23346
23267
  paid_msats: entry.receipt.paid.msats,
23268
+ settlement: receiptSettlement(entry.receipt, status2),
23347
23269
  receipt_verified: status2,
23348
23270
  display: receiptDisplay(entry.receipt, status2, rate)
23349
23271
  };
@@ -23355,6 +23277,7 @@ function storedReceiptJson(entry, result, rate) {
23355
23277
  receipt: entry.receipt,
23356
23278
  receipt_verified: result.status,
23357
23279
  receipt_checks: result.checks,
23280
+ settlement: receiptSettlement(entry.receipt, result.status),
23358
23281
  ...result.reason ? { receipt_error: result.reason, receipt_error_detail: receiptFailureDetail(result.reason) } : {},
23359
23282
  // The DVM's terminal reason is provider free text — an agent relaying it
23360
23283
  // must be able to see that it is untrusted (docs/cli.md).
@@ -23415,28 +23338,6 @@ function artifactContent(msg) {
23415
23338
  return msg.content;
23416
23339
  }
23417
23340
 
23418
- // src/lib/policy.ts
23419
- function buildPolicy(opts, btcRate) {
23420
- if (opts.maxPayments === void 0) {
23421
- throw new DvmError(
23422
- "missing_max_payments",
23423
- "Cannot build a spending policy without a payment count cap.",
23424
- "Pass --max-payments <n> on dvm request. Use 0 for free jobs, 1 for typical paid jobs, or higher for multi-turn flows that may require progressive payments."
23425
- );
23426
- }
23427
- if (!Number.isInteger(opts.maxPayments) || opts.maxPayments < 0) {
23428
- throw new DvmError(
23429
- "invalid_max_payments",
23430
- "Invalid value for --max-payments.",
23431
- "Pass a non-negative integer (e.g. --max-payments 1)."
23432
- );
23433
- }
23434
- const maxTotalMsats = opts.budget ? parseBudget(opts.budget, btcRate) : 0;
23435
- const autoPayBelowMsats = opts.autoPayBelow ? parseBudget(opts.autoPayBelow, btcRate) : Math.floor(maxTotalMsats * 0.2);
23436
- const maxIncrementMsats = opts.maxIncrement ? parseBudget(opts.maxIncrement, btcRate) : maxTotalMsats;
23437
- return { maxTotalMsats, autoPayBelowMsats, maxIncrementMsats, maxPayments: opts.maxPayments };
23438
- }
23439
-
23440
23341
  // src/commands/request.ts
23441
23342
  import { createHash as createHash5, randomUUID as randomUUID4 } from "crypto";
23442
23343
 
@@ -23471,7 +23372,7 @@ async function settleCreditAfterJob(args) {
23471
23372
  }
23472
23373
  }
23473
23374
  if (args.allowTopup !== false) {
23474
- const refill = args.refillPocket ?? (await import("./pocket-refill-JYYODE6X.js")).refillPocketIfLow;
23375
+ const refill = args.refillPocket ?? (await import("./pocket-refill-Z4YT7CHW.js")).refillPocketIfLow;
23475
23376
  await refill({ human: args.human }).catch(() => void 0);
23476
23377
  }
23477
23378
  }
@@ -23966,148 +23867,6 @@ function dollarLimitMicro(declaredLimit) {
23966
23867
  return whole * 1000000n + fraction;
23967
23868
  }
23968
23869
 
23969
- // src/lib/request-intent-store.ts
23970
- var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
23971
- import {
23972
- closeSync as closeSync3,
23973
- existsSync as existsSync7,
23974
- fsyncSync,
23975
- mkdirSync as mkdirSync2,
23976
- openSync as openSync3,
23977
- readFileSync as readFileSync7,
23978
- renameSync as renameSync2,
23979
- writeFileSync as writeFileSync4
23980
- } from "fs";
23981
- import { join as join8 } from "path";
23982
- function saveRequestIntent(intent) {
23983
- assertRequestId(intent.requestId);
23984
- assertNoPaymentOrAuthSecrets(intent.body);
23985
- ensureConfigSubdir(REQUEST_INTENTS_DIR);
23986
- const dir = intentDirectory(intent.requestId);
23987
- try {
23988
- mkdirSync2(dir, { mode: 448 });
23989
- } catch (error) {
23990
- if (error.code === "EEXIST") return false;
23991
- throw error;
23992
- }
23993
- fsyncDirectory(REQUEST_INTENTS_DIR);
23994
- const temp = join8(dir, `intent.${String(process.pid)}.tmp`);
23995
- const target = join8(dir, "intent.json");
23996
- const fd = openSync3(temp, "wx", 384);
23997
- try {
23998
- writeFileSync4(fd, JSON.stringify(intent, null, 2) + "\n");
23999
- fsyncSync(fd);
24000
- } finally {
24001
- closeSync3(fd);
24002
- }
24003
- renameSync2(temp, target);
24004
- fsyncDirectory(dir);
24005
- return true;
24006
- }
24007
- function loadRequestIntent(requestId) {
24008
- assertRequestId(requestId);
24009
- const dir = intentDirectory(requestId);
24010
- if (!existsSync7(dir)) return null;
24011
- const path = join8(dir, "intent.json");
24012
- try {
24013
- const parsed = JSON.parse(readFileSync7(path, "utf8"));
24014
- if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
24015
- throw new Error("invalid shape");
24016
- return parsed;
24017
- } catch (error) {
24018
- throw new DvmError(
24019
- "request_intent_unreadable",
24020
- `The saved request intent for ${requestId} is incomplete or unreadable.`,
24021
- "Do not submit a replacement request. The provider may already have accepted and charged the original; restore this intent from backup before using request-result.",
24022
- { request_id: requestId, cause: error instanceof Error ? error.message : String(error) }
24023
- );
24024
- }
24025
- }
24026
- function recordRequestRailPayment(requestId, payment) {
24027
- assertRequestId(requestId);
24028
- if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
24029
- const dir = intentDirectory(requestId);
24030
- const target = join8(dir, "intent.json");
24031
- const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
24032
- try {
24033
- const intent = loadRequestIntent(requestId);
24034
- if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
24035
- if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
24036
- throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
24037
- const temp = join8(dir, `rail.${String(process.pid)}.tmp`);
24038
- const fd = openSync3(temp, "w", 384);
24039
- try {
24040
- writeFileSync4(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
24041
- fsyncSync(fd);
24042
- } finally {
24043
- closeSync3(fd);
24044
- }
24045
- renameSync2(temp, target);
24046
- fsyncDirectory(dir);
24047
- } finally {
24048
- release();
24049
- }
24050
- }
24051
- function assertNoPaymentOrAuthSecrets(body) {
24052
- if (!containsForbiddenSecret(body)) return;
24053
- throw new DvmError(
24054
- "request_intent_contains_secret",
24055
- "Request recovery cannot persist a payment credential, bearer token, or request auth signature.",
24056
- "No payment was attempted. Remove the secret-bearing input or omit --request-id."
24057
- );
24058
- }
24059
- function containsForbiddenSecret(value) {
24060
- if (typeof value === "string") return /^Bearer\s/i.test(value);
24061
- if (!value || typeof value !== "object") return false;
24062
- if (Array.isArray(value)) return value.some(containsForbiddenSecret);
24063
- const record = value;
24064
- if (["pubkey", "timestamp", "nonce", "signature"].every((key) => Object.hasOwn(record, key))) {
24065
- return true;
24066
- }
24067
- const forbidden = /* @__PURE__ */ new Set([
24068
- "authorization",
24069
- "bearer_token",
24070
- "access_token",
24071
- "cashu_token",
24072
- "x402_payment",
24073
- "tempo_credential"
24074
- ]);
24075
- return Object.entries(record).some(
24076
- ([key, child]) => forbidden.has(key.toLowerCase()) || containsForbiddenSecret(child)
24077
- );
24078
- }
24079
- function assertRequestId(requestId) {
24080
- if (isPublicRequestId(requestId)) return;
24081
- throw new DvmError(
24082
- "invalid_request_id",
24083
- "Invalid request id.",
24084
- "Use 1\u2013128 characters: letters, digits, dot, underscore, colon, or hyphen."
24085
- );
24086
- }
24087
- function intentDirectory(requestId) {
24088
- return join8(REQUEST_INTENTS_DIR, requestId);
24089
- }
24090
- function fsyncDirectory(path) {
24091
- if (process.platform === "win32") return;
24092
- let fd;
24093
- try {
24094
- fd = openSync3(path, "r");
24095
- fsyncSync(fd);
24096
- } finally {
24097
- if (fd !== void 0) closeSync3(fd);
24098
- }
24099
- }
24100
- function isRequestIntent(value) {
24101
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
24102
- const candidate = value;
24103
- return candidate.v === 2 && isPublicRequestId(candidate.requestId) && typeof candidate.endpoint === "string" && typeof candidate.capability === "string" && typeof candidate.callerPubkey === "string" && isSignedRequestAudience(candidate.authAudience) && typeof candidate.createdAt === "number" && typeof candidate.body === "object" && candidate.body !== null && !Array.isArray(candidate.body) && typeof candidate.policy === "object" && candidate.policy !== null;
24104
- }
24105
- function isSignedRequestAudience(value) {
24106
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
24107
- const candidate = value;
24108
- return typeof candidate.dvm_id === "string" && typeof candidate.builder_pubkey === "string";
24109
- }
24110
-
24111
23870
  // src/lib/wallet-agent/balance.ts
24112
23871
  function groupProofsByMint(proofs) {
24113
23872
  const out = /* @__PURE__ */ new Map();
@@ -24394,6 +24153,9 @@ function resolveBudget(current, minimumMsats) {
24394
24153
 
24395
24154
  // src/commands/request.ts
24396
24155
  async function request(opts) {
24156
+ return withOutputWarnings(() => requestWithWarnings(opts));
24157
+ }
24158
+ async function requestWithWarnings(opts) {
24397
24159
  const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
24398
24160
  const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 3e4;
24399
24161
  const requestedMaxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
@@ -24455,7 +24217,7 @@ async function request(opts) {
24455
24217
  const config = loadConfig();
24456
24218
  const effectiveBudget = opts.budget ?? config?.defaultBudget;
24457
24219
  const effectiveAutoPayBelow = opts.autoPayBelow ?? config?.autoPayThreshold;
24458
- const autoPayConsent = opts.autoPay === true || opts.autoPayBelow !== void 0 && opts.autoPayBelow.trim() !== "";
24220
+ const autoPayConsent = !opts.creditOnly && (opts.autoPay === true || opts.autoPayBelow !== void 0 && opts.autoPayBelow.trim() !== "");
24459
24221
  const DEFAULT_MAX_PAYMENTS = 5;
24460
24222
  let maxPaymentsN;
24461
24223
  if (opts.maxPayments !== void 0) {
@@ -24484,12 +24246,16 @@ async function request(opts) {
24484
24246
  }
24485
24247
  }
24486
24248
  const transport = createDvmTransport();
24487
- const ref = { endpoint };
24488
24249
  const WARMUP_TIMEOUT_MS = 3e4;
24489
24250
  const warmupStart = Date.now();
24490
- const providerInfo = await warmupProvider(transport, ref, {
24491
- budgetMs: WARMUP_TIMEOUT_MS
24251
+ const resolvedEndpoint = await resolveProviderEndpoint2(transport, endpoint, {
24252
+ budgetMs: WARMUP_TIMEOUT_MS,
24253
+ capabilityPath: !opts.dvm
24492
24254
  });
24255
+ endpoint = resolvedEndpoint.endpoint;
24256
+ requestedCapability ??= resolvedEndpoint.capability;
24257
+ const providerInfo = resolvedEndpoint.info;
24258
+ const ref = { endpoint };
24493
24259
  if (opts.requestId && providerInfo.requestRecovery !== true) {
24494
24260
  transport.close();
24495
24261
  throw new DvmError(
@@ -24503,7 +24269,7 @@ async function request(opts) {
24503
24269
  info(`Provider woke up in ${(warmupMs / 1e3).toFixed(1)}s.`);
24504
24270
  }
24505
24271
  const dvmId = canonicalDvmId;
24506
- const capability = resolveCapability(providerInfo, requestedCapability, dvmId);
24272
+ const capability = resolveCapability(providerInfo, requestedCapability, dvmId, endpoint);
24507
24273
  const identity = { dvmId, capability };
24508
24274
  const identifier = dvmId ? formatIdentifier(dvmId, capability) : endpoint;
24509
24275
  if (opts.human) info(`Targeting ${identifier}.`);
@@ -24569,6 +24335,41 @@ async function request(opts) {
24569
24335
  ...opts.requestId ? { request_id: opts.requestId } : {}
24570
24336
  };
24571
24337
  signing = { privkey: signer.privkey, pubkey: signer.pubkey, unsignedData, domain: authDomain };
24338
+ }
24339
+ const deadlineMs = Date.now() + timeout;
24340
+ const envelopeBase = buildJobEnvelope({
24341
+ capability,
24342
+ input: inputText,
24343
+ params: opts.param,
24344
+ data,
24345
+ outputType: opts.outputType,
24346
+ bidMsats: budgetMsats
24347
+ });
24348
+ let previewQuotes = [];
24349
+ if (policy.maxTotalMsats > 0 || policy.autoPayBelowMsats > 0) {
24350
+ try {
24351
+ const quoteData = signing ? signDvmRequestData(signing.privkey, signing.unsignedData, signedRequestDomain({
24352
+ provider: providerInfo,
24353
+ endpoint,
24354
+ method: "POST",
24355
+ path: "v1/quote",
24356
+ capability
24357
+ })) : data;
24358
+ previewQuotes = await transport.quote(ref, { ...envelopeBase, data: quoteData }, {
24359
+ // Leave the rest of the job deadline available for submission and work.
24360
+ timeoutMs: Math.min(1e3, Math.max(1, Math.floor(timeout / 10))),
24361
+ btcRate
24362
+ });
24363
+ } catch {
24364
+ }
24365
+ }
24366
+ const pricing = providerInfo.capabilities?.[capability]?.pricing;
24367
+ const warningLimits = { budget: effectiveBudget, autoPayBelow: effectiveAutoPayBelow };
24368
+ const previewWarnings = autoPayWarnings(previewQuotes, warningLimits, pricing?.max ?? providerInfo.pricing?.max, btcRate);
24369
+ addOutputWarnings(previewWarnings, opts.human);
24370
+ if (signing) {
24371
+ const signer = signing;
24372
+ const unsignedData = signing.unsignedData;
24572
24373
  const storedRecord = opts.strictPerCall ? void 0 : loadCredit(endpoint, signer.pubkey, attestedIdentity);
24573
24374
  const storedCredit = storedRecord?.selectionCleared ? void 0 : storedRecord;
24574
24375
  if (opts.creditOnly && storedCredit?.creditId !== opts.creditOnly) {
@@ -24581,16 +24382,20 @@ async function request(opts) {
24581
24382
  );
24582
24383
  }
24583
24384
  const implicitCredits = opts.strictPerCall || opts.creditOnly ? [] : loadImplicitCredits(endpoint, signer.pubkey, attestedIdentity);
24584
- if (storedCredit?.lastPriceMicro !== void 0 && btcRate === 0) {
24385
+ if (storedCredit && btcRate === 0 && (policy.maxTotalMsats > 0 || policy.autoPayBelowMsats > 0)) {
24585
24386
  btcRate = (await tryResolveBtcUsdRate())?.rate ?? 0;
24586
24387
  }
24587
24388
  const drawCeiling = effectiveAutoPayBelow !== void 0 && effectiveAutoPayBelow.trim() !== "" ? {
24588
24389
  msats: policy.autoPayBelowMsats,
24589
24390
  source: opts.autoPayBelow !== void 0 ? "auto_pay_below" : "config_threshold"
24590
24391
  } : { msats: policy.maxTotalMsats, source: "budget" };
24591
- const drawStored = opts.creditOnly && storedCredit ? (({ lastPriceMicro: _lastPriceMicro, ...credit }) => credit)(storedCredit) : storedCredit;
24592
24392
  probePlan = opts.strictPerCall ? { mode: "none" } : planProbeDraw({
24593
- stored: drawStored,
24393
+ stored: storedCredit,
24394
+ capability,
24395
+ ...opts.creditOnly ? {} : {
24396
+ quote: previewQuotes[0],
24397
+ receipts: storedCredit && drawCeiling.msats > 0 ? loadReceipts() : []
24398
+ },
24594
24399
  implicit: implicitCredits,
24595
24400
  drawCeilingMsats: drawCeiling.msats,
24596
24401
  drawCeilingSource: drawCeiling.source,
@@ -24622,7 +24427,7 @@ async function request(opts) {
24622
24427
  draw_id: probePlan.drawId,
24623
24428
  ...drawRequestId ? { request_id: drawRequestId } : {}
24624
24429
  } : unsignedData;
24625
- data = signDvmRequestData(signer.privkey, probeData, authDomain);
24430
+ data = signDvmRequestData(signer.privkey, probeData, signing.domain);
24626
24431
  if (opts.human) info(`Signed as ${signer.pubkey}.`);
24627
24432
  if (opts.human && probePlan.mode === "draw") {
24628
24433
  info(
@@ -24640,15 +24445,7 @@ async function request(opts) {
24640
24445
  );
24641
24446
  }
24642
24447
  }
24643
- const deadlineMs = Date.now() + timeout;
24644
- let envelope = buildJobEnvelope({
24645
- capability,
24646
- input: inputText,
24647
- params: opts.param,
24648
- data,
24649
- outputType: opts.outputType,
24650
- bidMsats: budgetMsats
24651
- });
24448
+ let envelope = { ...envelopeBase, data };
24652
24449
  let jobRequestId = opts.requestId ?? drawRequestId;
24653
24450
  if (jobRequestId) {
24654
24451
  persistRequestIntent({
@@ -24737,6 +24534,11 @@ async function request(opts) {
24737
24534
  }
24738
24535
  if (receipt.status === "payment-required") {
24739
24536
  const quotes = receipt.quotes ?? [];
24537
+ if (opts.creditOnly) {
24538
+ transport.close();
24539
+ throw new DvmError("credit_only_unavailable", "The selected prepaid credit did not cover this submission; no fresh payment was attempted.");
24540
+ }
24541
+ if (!previewWarnings.length) addOutputWarnings(autoPayWarnings(quotes, warningLimits, void 0, btcRate), opts.human);
24740
24542
  if (autoPayConsent && quotes.length > 0) {
24741
24543
  const pay2 = () => handleAutoPayQuotes(
24742
24544
  transport,
@@ -24795,6 +24597,7 @@ async function request(opts) {
24795
24597
  submittedAt: Date.now(),
24796
24598
  policy,
24797
24599
  pinnedMint: opts.mint,
24600
+ ...opts.creditOnly ? { creditOnly: opts.creditOnly } : {},
24798
24601
  ...opts.strictPerCall ? { strictPerCall: true } : {},
24799
24602
  ...requestedMaxCashuFeeSats !== void 0 ? { maxCashuFeeSats: requestedMaxCashuFeeSats } : {},
24800
24603
  // the job cleared by drawing on a prepaid credit — no payment
@@ -24813,7 +24616,7 @@ async function request(opts) {
24813
24616
  ...localCorrelationJobFields(localCorrelationId)
24814
24617
  });
24815
24618
  recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment);
24816
- if (noStream) {
24619
+ if (noStream && !isTerminalJobStatus(receipt.status)) {
24817
24620
  transport.close();
24818
24621
  if (opts.human) {
24819
24622
  info(`Job published: ${receipt.jobId}`);
@@ -24859,6 +24662,7 @@ async function request(opts) {
24859
24662
  dvmId,
24860
24663
  providerInfo,
24861
24664
  signing,
24665
+ allowTopup: !opts.creditOnly,
24862
24666
  human: opts.human
24863
24667
  });
24864
24668
  noteFeedbackAfterTerminal({
@@ -24873,7 +24677,7 @@ async function request(opts) {
24873
24677
  console.log(receipt.summary);
24874
24678
  const hint = nextStepHint(receipt.jobId, receipt.payloadIn, receipt.artifactCount, true);
24875
24679
  if (hint) info(`\u{1F4CE} ${hint}`);
24876
- renderReceiptHuman(captured);
24680
+ renderReceiptHuman(captured, receipt.jobId);
24877
24681
  echoTraceIdHuman();
24878
24682
  } else {
24879
24683
  providerJobJson({
@@ -24884,7 +24688,7 @@ async function request(opts) {
24884
24688
  summary: receipt.summary,
24885
24689
  _provider_fields: ["summary"],
24886
24690
  ...buildCompletionHintFields(receipt.jobId, receipt),
24887
- ...receiptJsonFields(captured),
24691
+ ...receiptJsonFields(captured, receipt.jobId),
24888
24692
  ...takeCreditNoticeFields(),
24889
24693
  ...takeFeedbackNoticeFields(),
24890
24694
  next_action: null
@@ -24911,11 +24715,14 @@ async function request(opts) {
24911
24715
  },
24912
24716
  deadlineMs
24913
24717
  );
24914
- const completion = persistStreamOutcome(streamOutcome(receipt.jobId, result));
24915
- const captured = result.nextAction === null ? captureTransportReceipt(
24916
- receipt.jobId,
24917
- await fetchMissingJobReceipt(receipt.jobId, transport, ref)
24918
- ) : void 0;
24718
+ const providerStatus = result.nextAction === null ? await fetchMissingJobReceipt(receipt.jobId, transport, ref) : void 0;
24719
+ const outcome = {
24720
+ ...streamOutcome(receipt.jobId, result),
24721
+ providerStatus,
24722
+ callerCancelled: loadJob(receipt.jobId)?.callerCancelled
24723
+ };
24724
+ const completion = persistStreamOutcome(outcome);
24725
+ const captured = providerStatus ? captureTransportReceipt(receipt.jobId, providerStatus) : void 0;
24919
24726
  if (captured && !opts.strictPerCall) {
24920
24727
  await settleCreditAfterJob({
24921
24728
  capture: captured,
@@ -24924,10 +24731,11 @@ async function request(opts) {
24924
24731
  dvmId,
24925
24732
  providerInfo,
24926
24733
  signing,
24734
+ allowTopup: !opts.creditOnly,
24927
24735
  human: opts.human
24928
24736
  });
24929
24737
  }
24930
- const streamedTerminal = result.nextAction === null ? streamTerminalStatus(result.messages) : void 0;
24738
+ const streamedTerminal = streamTerminalStatus(result.messages, outcome);
24931
24739
  if (streamedTerminal) {
24932
24740
  noteFeedbackAfterTerminal({
24933
24741
  jobId: receipt.jobId,
@@ -24939,6 +24747,8 @@ async function request(opts) {
24939
24747
  }
24940
24748
  transport.close();
24941
24749
  if (opts.human) {
24750
+ if (streamedTerminal === "failed" || streamedTerminal === "cancelled")
24751
+ info(`Status: ${streamedTerminal}${completion?.message ? `: ${completion.message}` : ""}`);
24942
24752
  for (const msg of result.messages) {
24943
24753
  if (msg.type === "progress") continue;
24944
24754
  formatMessageHuman(msg, receipt.jobId, artifactSession);
@@ -24947,7 +24757,11 @@ async function request(opts) {
24947
24757
  const hint = nextStepHint(receipt.jobId, completion.payloadIn, completion.artifactCount, true);
24948
24758
  if (hint) info(`\u{1F4CE} ${hint}`);
24949
24759
  }
24950
- if (captured) renderReceiptHuman(captured);
24760
+ if (captured) renderReceiptHuman(captured, receipt.jobId);
24761
+ else {
24762
+ const { settlement } = terminalSettlementFields(receipt.jobId);
24763
+ if (settlement) info(settlement.display);
24764
+ }
24951
24765
  finalizeProgressLine();
24952
24766
  echoTraceIdHuman();
24953
24767
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: isTerminalJobStatus(receipt.status) || !!streamTerminalStatus(result.messages) });
@@ -24958,14 +24772,20 @@ async function request(opts) {
24958
24772
  ...transactionOutputFields(receipt),
24959
24773
  ...dvmIdentity(dvmId, capability),
24960
24774
  messages: result.messages.map(serializeMessageForOutput),
24775
+ ...streamedTerminal ? { status: streamedTerminal } : {},
24776
+ ...completion?.message !== void 0 ? { message: completion.message } : {},
24961
24777
  // A job that streams to `complete` — including one auto-paid through a
24962
24778
  // mid-job `requestPayment` — has no receipt carrying the outcome, so
24963
24779
  // these come off the streamed log instead. Without them this arc
24964
24780
  // returned `next_action: null` and nothing else: no summary, and no
24965
24781
  // signal that a payload was waiting in artifacts.
24966
- ...completion?.summary !== void 0 ? { summary: completion.summary, _provider_fields: ["summary"] } : {},
24782
+ ...completion?.summary !== void 0 ? { summary: completion.summary } : {},
24783
+ _provider_fields: [
24784
+ ...completion?.summary !== void 0 ? ["summary"] : [],
24785
+ ...completion?.message !== void 0 ? ["message"] : []
24786
+ ],
24967
24787
  ...completion ? buildCompletionHintFields(receipt.jobId, completion) : {},
24968
- ...captured ? receiptJsonFields(captured) : {},
24788
+ ...captured ? receiptJsonFields(captured, receipt.jobId) : terminalSettlementFields(receipt.jobId),
24969
24789
  ...takeCreditNoticeFields(),
24970
24790
  ...takeFeedbackNoticeFields(),
24971
24791
  next_action: result.nextAction,
@@ -24975,10 +24795,18 @@ async function request(opts) {
24975
24795
  }
24976
24796
  return;
24977
24797
  }
24978
- case "failed": {
24979
- markJobTerminal(receipt.jobId, "failed", completionSnapshot(receipt));
24798
+ case "failed":
24799
+ case "cancelled": {
24800
+ const terminalStatus = receipt.status;
24980
24801
  const failureMessages = await transport.getMessages(receipt.jobId, 0, ref, { jobToken: receipt.jobToken }).catch(() => []);
24981
24802
  appendMessages(receipt.jobId, failureMessages);
24803
+ const completion = persistStreamOutcome({
24804
+ jobId: receipt.jobId,
24805
+ messages: failureMessages,
24806
+ cursor: maxSeq(failureMessages, 0),
24807
+ afterSeq: 0,
24808
+ providerStatus: { status: terminalStatus, ...completionSnapshot(receipt) }
24809
+ });
24982
24810
  const captured = captureTransportReceipt(receipt.jobId, receipt);
24983
24811
  if (!opts.strictPerCall)
24984
24812
  await settleCreditAfterJob({
@@ -24995,7 +24823,7 @@ async function request(opts) {
24995
24823
  jobId: receipt.jobId,
24996
24824
  dvmId,
24997
24825
  endpoint,
24998
- status: "failed",
24826
+ status: terminalStatus,
24999
24827
  human: opts.human
25000
24828
  });
25001
24829
  transport.close();
@@ -25003,12 +24831,13 @@ async function request(opts) {
25003
24831
  for (const msg of failureMessages) {
25004
24832
  formatMessageHuman(msg, receipt.jobId, artifactSession);
25005
24833
  }
25006
- renderReceiptHuman(captured);
24834
+ renderReceiptHuman(captured, receipt.jobId);
25007
24835
  }
25008
- throw new DvmError("job_failed", "Job failed.", void 0, {
25009
- ...receiptJsonFields(captured),
24836
+ throw new DvmError(terminalStatus === "failed" ? "job_failed" : "cancelled", completion?.message ?? `Job ${terminalStatus}.`, void 0, {
24837
+ status: terminalStatus,
24838
+ ...receiptJsonFields(captured, receipt.jobId),
25010
24839
  ...failureMessages.length > 0 ? { messages: failureMessages.map(serializeMessageForOutput) } : {}
25011
- });
24840
+ }, void 0, completion?.message !== void 0 ? { message: "provider" } : void 0);
25012
24841
  }
25013
24842
  }
25014
24843
  }
@@ -25673,11 +25502,11 @@ function validateCreditOnlyOptions(opts) {
25673
25502
  "invalid_credit_only",
25674
25503
  "--credit-only must name one non-empty public credit id of at most 128 characters."
25675
25504
  );
25676
- if (opts.strictPerCall || opts.autoPay === true || opts.autoPayBelow !== void 0)
25505
+ if (opts.strictPerCall || opts.autoPay === true)
25677
25506
  throw new DvmError(
25678
25507
  "credit_only_payment_conflict",
25679
25508
  "--credit-only cannot be combined with a fresh-payment consent mode.",
25680
- "Omit --auto-pay, --auto-pay-below, and --strict-per-call; the selected prepaid balance is the only allowed payment source."
25509
+ "Omit --auto-pay and --strict-per-call; the selected prepaid balance is the only allowed payment source."
25681
25510
  );
25682
25511
  if (opts.budget === void 0 || !opts.requestId)
25683
25512
  throw new DvmError(
@@ -25856,7 +25685,7 @@ async function payWithTempo(args, credential) {
25856
25685
  console.log(receipt.summary);
25857
25686
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
25858
25687
  if (hint) info(`\u{1F4CE} ${hint}`);
25859
- renderReceiptHuman(captured);
25688
+ renderReceiptHuman(captured, effectiveJobId);
25860
25689
  } else {
25861
25690
  providerJobJson({
25862
25691
  jobId: effectiveJobId,
@@ -25866,7 +25695,7 @@ async function payWithTempo(args, credential) {
25866
25695
  summary: receipt.summary,
25867
25696
  _provider_fields: ["summary"],
25868
25697
  ...buildCompletionHintFields(effectiveJobId, receipt),
25869
- ...receiptJsonFields(captured),
25698
+ ...receiptJsonFields(captured, effectiveJobId),
25870
25699
  paidWith: "tempo",
25871
25700
  account: account.address,
25872
25701
  ...takeCreditNoticeFields(),
@@ -25936,6 +25765,7 @@ function persistRequestIntent(args) {
25936
25765
  callerPubkey: signing.pubkey,
25937
25766
  policy: args.policy,
25938
25767
  ...opts.mint ? { pinnedMint: opts.mint } : {},
25768
+ ...opts.creditOnly ? { creditOnly: opts.creditOnly } : {},
25939
25769
  ...opts.strictPerCall ? { strictPerCall: true } : {},
25940
25770
  ...maxCashuFeeSats !== void 0 ? { maxCashuFeeSats } : {},
25941
25771
  ...receiptTrustFields(args.providerInfo),
@@ -26003,6 +25833,9 @@ function normalizedLocalCorrelationId(opts) {
26003
25833
  return opts.localCorrelationId === void 0 ? void 0 : normalizeLocalCorrelationId(opts.localCorrelationId);
26004
25834
  }
26005
25835
  function requestOutcomeUnknown(requestId, cause) {
25836
+ if (cause instanceof DvmError && typeof cause.data?.job_id === "string" && loadJob(cause.data.job_id)?.requestId === requestId) {
25837
+ return cause;
25838
+ }
26006
25839
  const ambiguityId = isIdentityFailure(cause) && typeof cause.data?.ambiguity_id === "string" ? cause.data.ambiguity_id : void 0;
26007
25840
  return new DvmError(
26008
25841
  "request_outcome_unknown",
@@ -26516,7 +26349,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
26516
26349
  console.log(receipt.summary);
26517
26350
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
26518
26351
  if (hint) info(`\u{1F4CE} ${hint}`);
26519
- renderReceiptHuman(captured);
26352
+ renderReceiptHuman(captured, effectiveJobId);
26520
26353
  } else {
26521
26354
  providerJobJson({
26522
26355
  jobId: effectiveJobId,
@@ -26524,7 +26357,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
26524
26357
  summary: receipt.summary,
26525
26358
  _provider_fields: ["summary"],
26526
26359
  ...buildCompletionHintFields(effectiveJobId, receipt),
26527
- ...receiptJsonFields(captured),
26360
+ ...receiptJsonFields(captured, effectiveJobId),
26528
26361
  paidWith: "cashu_p2pk",
26529
26362
  mint: prepared.mint,
26530
26363
  amountSats: prepared.totalSats,
@@ -26717,7 +26550,7 @@ async function payWithX402(args, proof) {
26717
26550
  console.log(receipt.summary);
26718
26551
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
26719
26552
  if (hint) info(`\u{1F4CE} ${hint}`);
26720
- renderReceiptHuman(captured);
26553
+ renderReceiptHuman(captured, effectiveJobId);
26721
26554
  } else {
26722
26555
  providerJobJson({
26723
26556
  jobId: effectiveJobId,
@@ -26727,7 +26560,7 @@ async function payWithX402(args, proof) {
26727
26560
  summary: receipt.summary,
26728
26561
  _provider_fields: ["summary"],
26729
26562
  ...buildCompletionHintFields(effectiveJobId, receipt),
26730
- ...receiptJsonFields(captured),
26563
+ ...receiptJsonFields(captured, effectiveJobId),
26731
26564
  paidWith: "x402",
26732
26565
  account: wallet.address,
26733
26566
  ...takeCreditNoticeFields(),
@@ -26830,10 +26663,14 @@ async function streamAfterPayment(args) {
26830
26663
  },
26831
26664
  deadlineMs
26832
26665
  );
26833
- const completion = persistStreamOutcome(
26834
- streamOutcome(jobId, result, { costMsats: chosen.priceMsats, paymentMethod: paymentMethod2 })
26835
- );
26836
- const captured = result.nextAction === null ? captureTransportReceipt(jobId, await fetchMissingJobReceipt(jobId, transport, ref)) : void 0;
26666
+ const providerStatus = result.nextAction === null ? await fetchMissingJobReceipt(jobId, transport, ref) : void 0;
26667
+ const outcome = {
26668
+ ...streamOutcome(jobId, result, { costMsats: chosen.priceMsats, paymentMethod: paymentMethod2 }),
26669
+ providerStatus,
26670
+ callerCancelled: loadJob(jobId)?.callerCancelled
26671
+ };
26672
+ const completion = persistStreamOutcome(outcome);
26673
+ const captured = providerStatus ? captureTransportReceipt(jobId, providerStatus) : void 0;
26837
26674
  if (captured && !args.strictPerCall) {
26838
26675
  await settleCreditAfterJob({
26839
26676
  capture: captured,
@@ -26845,7 +26682,7 @@ async function streamAfterPayment(args) {
26845
26682
  human
26846
26683
  });
26847
26684
  }
26848
- const streamedTerminal = result.nextAction === null ? streamTerminalStatus(result.messages) : void 0;
26685
+ const streamedTerminal = streamTerminalStatus(result.messages, outcome);
26849
26686
  if (streamedTerminal) {
26850
26687
  noteFeedbackAfterTerminal({
26851
26688
  jobId,
@@ -26896,6 +26733,8 @@ async function streamAfterPayment(args) {
26896
26733
  throw new DvmError("timeout", paidTimeoutMessage);
26897
26734
  }
26898
26735
  if (human) {
26736
+ if (streamedTerminal === "failed" || streamedTerminal === "cancelled")
26737
+ info(`Status: ${streamedTerminal}${completion?.message ? `: ${completion.message}` : ""}`);
26899
26738
  for (const msg of result.messages) {
26900
26739
  if (msg.type === "progress") continue;
26901
26740
  formatMessageHuman(msg, jobId, artifactSession);
@@ -26904,7 +26743,11 @@ async function streamAfterPayment(args) {
26904
26743
  const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, true);
26905
26744
  if (hint) info(`\u{1F4CE} ${hint}`);
26906
26745
  }
26907
- if (captured) renderReceiptHuman(captured);
26746
+ if (captured) renderReceiptHuman(captured, jobId);
26747
+ else {
26748
+ const { settlement } = terminalSettlementFields(jobId);
26749
+ if (settlement) info(settlement.display);
26750
+ }
26908
26751
  finalizeProgressLine();
26909
26752
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: !!streamTerminalStatus(result.messages) });
26910
26753
  } else {
@@ -26912,12 +26755,18 @@ async function streamAfterPayment(args) {
26912
26755
  jobId,
26913
26756
  ...dvmFields,
26914
26757
  messages: result.messages.map(serializeMessageForOutput),
26758
+ ...streamedTerminal ? { status: streamedTerminal } : {},
26759
+ ...completion?.message !== void 0 ? { message: completion.message } : {},
26915
26760
  // Same as the unpaid arc above: the outcome is only knowable from the
26916
26761
  // streamed log here, so render it rather than leaving the agent to dig
26917
26762
  // the summary out of `messages` and guess about artifacts.
26918
- ...completion?.summary !== void 0 ? { summary: completion.summary, _provider_fields: ["summary"] } : {},
26763
+ ...completion?.summary !== void 0 ? { summary: completion.summary } : {},
26764
+ _provider_fields: [
26765
+ ...completion?.summary !== void 0 ? ["summary"] : [],
26766
+ ...completion?.message !== void 0 ? ["message"] : []
26767
+ ],
26919
26768
  ...completion ? buildCompletionHintFields(jobId, completion) : {},
26920
- ...captured ? receiptJsonFields(captured) : {},
26769
+ ...captured ? receiptJsonFields(captured, jobId) : terminalSettlementFields(jobId),
26921
26770
  ...takeCreditNoticeFields(),
26922
26771
  ...takeFeedbackNoticeFields(),
26923
26772
  next_action: result.nextAction,
@@ -26963,7 +26812,7 @@ async function recoverViaStatusPoll(args) {
26963
26812
  });
26964
26813
  if (human) {
26965
26814
  info(status2.summary ?? "Job completed (recovered via status check).");
26966
- renderReceiptHuman(captured);
26815
+ renderReceiptHuman(captured, jobId);
26967
26816
  } else {
26968
26817
  providerJobJson({
26969
26818
  jobId,
@@ -26973,7 +26822,7 @@ async function recoverViaStatusPoll(args) {
26973
26822
  _provider_fields: ["summary"],
26974
26823
  recovered: true,
26975
26824
  ...paymentFields,
26976
- ...receiptJsonFields(captured),
26825
+ ...receiptJsonFields(captured, jobId),
26977
26826
  ...takeCreditNoticeFields(),
26978
26827
  ...takeFeedbackNoticeFields(),
26979
26828
  next_action: null
@@ -26995,7 +26844,7 @@ async function recoverViaStatusPoll(args) {
26995
26844
  const errorMsg = status2.message ?? `Job ${status2.status}.`;
26996
26845
  if (human) {
26997
26846
  info(errorMsg);
26998
- renderReceiptHuman(captured);
26847
+ renderReceiptHuman(captured, jobId);
26999
26848
  } else {
27000
26849
  providerJobJson({
27001
26850
  jobId,
@@ -27004,7 +26853,7 @@ async function recoverViaStatusPoll(args) {
27004
26853
  message: errorMsg,
27005
26854
  ...status2.message !== void 0 ? { _provider_fields: ["message"] } : {},
27006
26855
  ...paymentFields,
27007
- ...receiptJsonFields(captured),
26856
+ ...receiptJsonFields(captured, jobId),
27008
26857
  ...takeCreditNoticeFields(),
27009
26858
  ...takeFeedbackNoticeFields(),
27010
26859
  next_action: null
@@ -27131,6 +26980,7 @@ async function requestResult(requestId, opts = {}) {
27131
26980
  const creditBinding = typeof originalData?.credit_id === "string" && typeof originalData.draw_id === "string" ? { creditId: originalData.credit_id, drawId: originalData.draw_id, callerPubkey: intent.callerPubkey } : void 0;
27132
26981
  const restored = {
27133
26982
  ...creditBinding ? { creditBinding } : {},
26983
+ ...intent.creditOnly ? { creditOnly: intent.creditOnly } : {},
27134
26984
  requestId,
27135
26985
  transactionHash: receipt.transactionHash,
27136
26986
  jobToken: receipt.jobToken,
@@ -27492,6 +27342,7 @@ function outputResults2(resultJson, human, nextAction) {
27492
27342
 
27493
27343
  // src/lib/job-spend.ts
27494
27344
  function jobSpend(job, receipt) {
27345
+ const settlement = jobSettlement(job, receipt);
27495
27346
  const charges = [];
27496
27347
  const refunds = [];
27497
27348
  let request2;
@@ -27531,21 +27382,36 @@ function jobSpend(job, receipt) {
27531
27382
  const payments = job.paymentsHonoured ?? charges.length + (upfront > 0 ? 1 : 0);
27532
27383
  const currency = charges[0]?.fiat_amount?.currency;
27533
27384
  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;
27534
- const totalDisplay = formatPaymentAmount(total, fiat, { anchor: false });
27385
+ const converted = [
27386
+ job.paymentMethod,
27387
+ job.upfrontPayment?.rail,
27388
+ receipt?.paid.rail,
27389
+ typeof job.upfrontRailPayment === "object" ? job.upfrontRailPayment?.method : void 0,
27390
+ ...charges.map((charge) => charge.rail)
27391
+ ].some((rail) => rail === "tempo" || rail === "x402");
27392
+ const valuationLabel = converted ? " (BTC valuation)" : "";
27393
+ const totalDisplay = formatPaymentAmount(total, fiat, { anchor: false }) + valuationLabel;
27535
27394
  const budgetDisplay = job.policy ? formatPaymentAmount(
27536
27395
  job.policy.maxTotalMsats,
27537
27396
  fiat && total > 0 ? { currency: fiat.currency, amount: fiat.amount * job.policy.maxTotalMsats / total } : void 0,
27538
27397
  { anchor: false }
27539
27398
  ) : void 0;
27540
27399
  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));
27541
- const receiptMismatch = receipt && job.paymentMethod !== "credit" ? receipt.paid.msats !== total : void 0;
27542
- const receiptTotalDisplay = receipt ? formatPaymentAmount(receipt.paid.msats, void 0, { anchor: false }) : void 0;
27543
- 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"}`;
27400
+ const receiptMismatch = receipt && job.paymentMethod !== "credit" && !converted ? receipt.paid.msats !== total : void 0;
27401
+ const receiptTotalDisplay = receipt ? formatPaymentAmount(receipt.paid.msats, void 0, { anchor: false }) + valuationLabel : void 0;
27402
+ const settled = settlement.status === "settled" || settlement.status === "free";
27403
+ const receiptHeadline = settled && settlement.evidence === "receipt" && (settlement.settled_msats !== total || job.paymentMethod === "credit" && !knownCredit);
27404
+ let display = receiptHeadline ? `${settlement.display.replace(/\.$/, "")}; recorded payments: ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}` : !settled && isTerminalJobStatus(job.status) ? settlement.display.replace(/\.$/, "") : job.paymentMethod === "credit" && !knownCredit ? "Drawn 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" : `${settled ? "Settled" : "Sent or held"} ${totalDisplay} over ${payments} charge${payments === 1 ? "" : "s"}`;
27405
+ if (job.paymentMethod === "credit" && !knownCredit && settlement.status === "unknown")
27406
+ display = `Drawn from prepaid credit; the upfront amount is not recorded locally. ${display}`;
27407
+ else if (job.paymentMethod === "credit" && !knownCredit && receiptHeadline)
27408
+ display += "; Drawn from prepaid credit; the upfront amount is not recorded locally";
27544
27409
  if (budgetDisplay) display += `, budget ${budgetDisplay}`;
27545
27410
  if (refunds.length > 0) display += `, ${refunds.length} refund${refunds.length === 1 ? "" : "s"}`;
27546
27411
  display += ".";
27547
27412
  if (logMismatch) display += " Local payment log disagrees with the job record.";
27548
27413
  if (receipt && job.paymentMethod === "credit" && !knownCredit) display += " The receipt total includes the unrecorded credit draw.";
27414
+ if (receipt && converted) display += " Receipt comparison is unknown: local records lack comparable native settlement amounts for Tempo/x402 payments. Converted BTC totals can differ with exchange rates and do not establish a difference in token principal or fees.";
27549
27415
  const [receiptLabel, localLabel] = receiptTotalDisplay === totalDisplay ? [`${receipt.paid.msats} msats`, `${total} msats`] : [receiptTotalDisplay, totalDisplay];
27550
27416
  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.`;
27551
27417
  return {
@@ -27553,6 +27419,7 @@ function jobSpend(job, receipt) {
27553
27419
  refunds,
27554
27420
  total_msats: total,
27555
27421
  total_display: totalDisplay,
27422
+ settlement,
27556
27423
  ...upfront > 0 && (job.paymentMethod !== "credit" || knownCredit) ? {
27557
27424
  upfront_display: formatPaymentAmount(
27558
27425
  upfront,
@@ -27575,7 +27442,7 @@ function renderSpendHuman(spend, print) {
27575
27442
  print(spend.display);
27576
27443
  if (spend.upfront_display) print(` Upfront: ${spend.upfront_display}`);
27577
27444
  const rails = { cashu_p2pk: "Cashu", tempo: "Tempo", x402: "x402", credit: "prepaid credit", unknown: "payment method not recorded" };
27578
- const approvals = { auto: "paid automatically", explicit: "you approved", unknown: "approval not recorded" };
27445
+ const approvals = { auto: "sent automatically", explicit: "you approved", unknown: "approval not recorded" };
27579
27446
  for (const charge of spend.charges) {
27580
27447
  print(` [${charge.seq}] ${charge.display} (${rails[charge.rail]}, ${approvals[charge.approval]})${charge.reason.text ? `: ${charge.reason.text}` : ""}`);
27581
27448
  }
@@ -27592,9 +27459,17 @@ async function statusWithAccess(jobId, opts, access) {
27592
27459
  const { stored, ref, jobToken } = access;
27593
27460
  if (stored && !access.overridden && isTerminalJobStatus(stored.status) && stored.completion && !opts.messages) {
27594
27461
  let receipt2 = replayStoredReceipt(stored);
27462
+ let terminalStatus = stored.status;
27463
+ let completion2 = stored.completion;
27595
27464
  const transport2 = createDvmTransport();
27596
27465
  if (stored.receiptsSupported && receipt2.status === "absent") {
27597
27466
  const fetched = await fetchMissingJobReceipt(jobId, transport2, ref);
27467
+ if (fetched.status && isTerminalJobStatus(fetched.status)) {
27468
+ const saved = stored.status === fetched.status ? completion2 : void 0;
27469
+ terminalStatus = fetched.status;
27470
+ completion2 = fetched.content_available === false && saved ? saved : { ...saved, ...completionSnapshot(fetched) };
27471
+ markJobTerminal(jobId, terminalStatus, completion2);
27472
+ }
27598
27473
  if (fetched.receipt || fetched.receiptParseError) {
27599
27474
  if (fetched.receipt && !stored.builderAnchor) {
27600
27475
  await backfillTrustAnchor(jobId, transport2, ref);
@@ -27604,7 +27479,7 @@ async function statusWithAccess(jobId, opts, access) {
27604
27479
  }
27605
27480
  await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
27606
27481
  transport2.close();
27607
- renderStatus(jobId, stored, stored.status, stored.completion, "local", null, opts, {
27482
+ renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
27608
27483
  receipt: receipt2
27609
27484
  });
27610
27485
  return;
@@ -27624,9 +27499,17 @@ async function statusWithAccess(jobId, opts, access) {
27624
27499
  }
27625
27500
  const nextAction = await resolveNextAction(jobId, result.status, msgs, transport, ref, {
27626
27501
  timeoutMs: timeout,
27627
- jobToken
27502
+ jobToken,
27503
+ context: access.endpointOverridden ? void 0 : stored ?? void 0
27628
27504
  });
27629
27505
  const completion = completionSnapshot(result);
27506
+ const reasonUnavailable = completion.message === void 0 || result.content_available === false && completion.message === "";
27507
+ if (reasonUnavailable && (result.status === "failed" || result.status === "cancelled")) {
27508
+ const savedReason = !access.endpointOverridden && stored?.status === result.status ? stored.completion?.message : void 0;
27509
+ const terminal = msgs.findLast((message2) => message2.type === "complete" || message2.type === "cancel");
27510
+ const reason = savedReason ?? (terminal?.type === "cancel" ? terminal.content.reason : void 0);
27511
+ if (reason !== void 0) completion.message = reason;
27512
+ }
27630
27513
  let receipt;
27631
27514
  if (isTerminalJobStatus(result.status)) {
27632
27515
  if (stored && !access.endpointOverridden) {
@@ -27693,7 +27576,15 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
27693
27576
  const msgs = fetched?.msgs ?? [];
27694
27577
  const receipt = fetched?.receipt;
27695
27578
  const content = jobContentFields(jobId, fetched?.content, opts.human);
27696
- const spend = stored ? jobSpend(loadJob(jobId) ?? stored, receipt?.receipt) : void 0;
27579
+ const spend = stored ? jobSpend({
27580
+ ...loadJob(jobId) ?? stored,
27581
+ status: jobStatus
27582
+ }, receipt?.receipt) : void 0;
27583
+ const settlement = terminalSettlementFields(jobId, {
27584
+ status: jobStatus,
27585
+ receipt: receipt?.receipt,
27586
+ persistLocalState: !!stored
27587
+ });
27697
27588
  if (opts.human) {
27698
27589
  if (jobStatus === "completed" && completion.summary) {
27699
27590
  info(`Summary:`);
@@ -27714,6 +27605,7 @@ ${msgs.length} new message(s):`);
27714
27605
  const traceId = getOutputTraceId();
27715
27606
  if (traceId) info(`Trace: ${traceId}`);
27716
27607
  if (spend) renderSpendHuman(spend, info);
27608
+ else if (settlement.settlement) info(settlement.settlement.display);
27717
27609
  if (receipt) renderReceiptHuman(receipt);
27718
27610
  printNextActionHuman(nextAction);
27719
27611
  return;
@@ -27735,6 +27627,7 @@ ${msgs.length} new message(s):`);
27735
27627
  // terminal responses only. On a still-running job "absent" would
27736
27628
  // read as "this DVM doesn't issue receipts" rather than "not yet".
27737
27629
  ...receipt ? receiptJsonFields(receipt) : {},
27630
+ ...settlement,
27738
27631
  // `dvm status` is a job-terminal emission for `--no-stream`
27739
27632
  // jobs, so it drains the deferred-notice sinks like the request terminals
27740
27633
  // do. Both spread blind and are absent when nothing was stashed.
@@ -27752,16 +27645,16 @@ ${msgs.length} new message(s):`);
27752
27645
  async function resolveNextAction(jobId, status2, fetched, transport, ref, opts) {
27753
27646
  if (isTerminalJobStatus(status2)) return null;
27754
27647
  if (status2 === "awaiting-input") {
27755
- const fromBatch = computeNextAction(jobId, fetched);
27648
+ const fromBatch = computeNextAction(jobId, fetched, void 0, opts.context);
27756
27649
  if (fromBatch) return fromBatch;
27757
27650
  const history = await transport.getMessages(jobId, 0, ref, opts);
27758
- return computeNextAction(jobId, history) ?? pollNextAction(jobId);
27651
+ return computeNextAction(jobId, history, void 0, opts.context) ?? pollNextAction(jobId);
27759
27652
  }
27760
27653
  return pollNextAction(jobId);
27761
27654
  }
27762
27655
 
27763
27656
  // src/commands/upload.ts
27764
- import { statSync as statSync5 } from "fs";
27657
+ import { statSync as statSync4 } from "fs";
27765
27658
 
27766
27659
  // src/lib/upload-stream.ts
27767
27660
  import { createHash as createHash6 } from "crypto";
@@ -27984,7 +27877,7 @@ async function upload(dvmRef, opts) {
27984
27877
  const target = resolveUploadTarget(qualified?.slug ?? dvmId, kind);
27985
27878
  let sizeOnDisk;
27986
27879
  try {
27987
- const st = statSync5(opts.file);
27880
+ const st = statSync4(opts.file);
27988
27881
  if (!st.isFile()) {
27989
27882
  throw new DvmError(
27990
27883
  "invalid_argument",
@@ -28246,7 +28139,7 @@ function getRailOnramp(rail) {
28246
28139
  }
28247
28140
 
28248
28141
  // src/lib/secret-input.ts
28249
- import { fstatSync, readFileSync as readFileSync8, realpathSync } from "fs";
28142
+ import { fstatSync, readFileSync as readFileSync7, realpathSync } from "fs";
28250
28143
  import { homedir as homedir2 } from "os";
28251
28144
  import { resolve as resolve2, sep } from "path";
28252
28145
  var BLOCKED_SECRET_PATHS = [
@@ -28326,7 +28219,7 @@ function readSecretFile(path, config) {
28326
28219
  throw err;
28327
28220
  }
28328
28221
  assertSafeFilePath(real);
28329
- return readFileSync8(real, "utf-8").trim();
28222
+ return readFileSync7(real, "utf-8").trim();
28330
28223
  }
28331
28224
  function readSecretStdin(config) {
28332
28225
  return new Promise((resolveStdin, reject) => {
@@ -30022,7 +29915,7 @@ function mnemonicValidationError(result) {
30022
29915
  var import_qrcode = __toESM(require_lib(), 1);
30023
29916
  import { randomBytes as randomBytes3 } from "crypto";
30024
29917
  import { tmpdir as tmpdir2 } from "os";
30025
- import { join as join9 } from "path";
29918
+ import { join as join8 } from "path";
30026
29919
  async function renderQrTerminal(payload) {
30027
29920
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
30028
29921
  }
@@ -30035,7 +29928,7 @@ async function renderQrPng(payload, outPath) {
30035
29928
  });
30036
29929
  }
30037
29930
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
30038
- return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
29931
+ return join8(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
30039
29932
  }
30040
29933
 
30041
29934
  // src/lib/funding-handoff.ts
@@ -34414,14 +34307,14 @@ function hexToBytes2(hex) {
34414
34307
  var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
34415
34308
  import {
34416
34309
  chmodSync as chmodSync2,
34417
- existsSync as existsSync8,
34310
+ existsSync as existsSync7,
34418
34311
  readdirSync as readdirSync5,
34419
- readFileSync as readFileSync9,
34312
+ readFileSync as readFileSync8,
34420
34313
  renameSync as renameSync3,
34421
34314
  unlinkSync as unlinkSync3,
34422
34315
  writeFileSync as writeFileSync5
34423
34316
  } from "fs";
34424
- import { join as join10 } from "path";
34317
+ import { join as join9 } from "path";
34425
34318
  var pairingIdPattern = /^[0-9a-f]{64}$/;
34426
34319
  var stateSchema = external_exports.object({
34427
34320
  version: external_exports.literal(1),
@@ -34448,7 +34341,7 @@ function createWalletPairingState(state) {
34448
34341
  }
34449
34342
  function loadWalletPairingState(pairingId) {
34450
34343
  const path = pairingPath(pairingId);
34451
- if (!existsSync8(path)) {
34344
+ if (!existsSync7(path)) {
34452
34345
  throw new DvmError(
34453
34346
  "wallet_pairing_not_found",
34454
34347
  "No local state exists for that wallet pairing.",
@@ -34456,7 +34349,7 @@ function loadWalletPairingState(pairingId) {
34456
34349
  );
34457
34350
  }
34458
34351
  try {
34459
- return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34352
+ return stateSchema.parse(JSON.parse(readFileSync8(path, "utf8")));
34460
34353
  } catch {
34461
34354
  throw new DvmError(
34462
34355
  "wallet_pairing_state_invalid",
@@ -34491,13 +34384,13 @@ function deleteWalletPairingState(pairingId) {
34491
34384
  }
34492
34385
  }
34493
34386
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
34494
- if (!existsSync8(PAIRINGS_DIR)) return 0;
34387
+ if (!existsSync7(PAIRINGS_DIR)) return 0;
34495
34388
  let removed = 0;
34496
34389
  for (const name of readdirSync5(PAIRINGS_DIR)) {
34497
34390
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
34498
- const path = join10(PAIRINGS_DIR, name);
34391
+ const path = join9(PAIRINGS_DIR, name);
34499
34392
  try {
34500
- const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34393
+ const state = stateSchema.parse(JSON.parse(readFileSync8(path, "utf8")));
34501
34394
  if (state.manifest.expires_at <= nowSeconds) {
34502
34395
  unlinkSync3(path);
34503
34396
  removed += 1;
@@ -34509,7 +34402,7 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
34509
34402
  }
34510
34403
  async function withWalletPairingLock(pairingId, fn) {
34511
34404
  const path = pairingPath(pairingId);
34512
- if (!existsSync8(path)) return fn();
34405
+ if (!existsSync7(path)) return fn();
34513
34406
  let release;
34514
34407
  try {
34515
34408
  release = await import_proper_lockfile3.default.lock(path, {
@@ -34539,7 +34432,7 @@ function pairingPath(pairingId) {
34539
34432
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
34540
34433
  );
34541
34434
  }
34542
- return join10(PAIRINGS_DIR, `${pairingId}.json`);
34435
+ return join9(PAIRINGS_DIR, `${pairingId}.json`);
34543
34436
  }
34544
34437
  function ensurePairingsDirectory() {
34545
34438
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -36168,7 +36061,7 @@ function buildProgram() {
36168
36061
  program2.command("quote").description("Get a price quote from a DVM provider").option(
36169
36062
  "-d, --dvm <identifier>",
36170
36063
  "Qualified DVM or DVM/capability identifier (e.g. `dvmkit--narrate`, `dvmkit--cast/add-episode`). Alternative to --endpoint."
36171
- ).option("--endpoint <url>", "Provider HTTPS endpoint URL (alternative to -d)").option("-i, --input <text>", "Input text (primitive-input DVMs)").option(
36064
+ ).option("--endpoint <url>", "Provider HTTPS base URL or URL/capability (alternative to -d)").option("-i, --input <text>", "Input text (primitive-input DVMs)").option(
36172
36065
  "--data <json>",
36173
36066
  "Structured data for inputSchema DVMs (JSON object, or @path/to/file.json, or @- for stdin)"
36174
36067
  ).option(
@@ -36176,7 +36069,7 @@ function buildProgram() {
36176
36069
  "Job parameter (repeatable). Agent-friendly form for DVMs with an inputSchema (bool/number/string + repeats \u2192 array). Use --data for nested values.",
36177
36070
  collectOption,
36178
36071
  []
36179
- ).option("--output-type <mime>", "Desired output MIME type").option(
36072
+ ).option("--budget <amount>", "Preview the request budget (millisats or $USD); authorizes no payment").option("--auto-pay-below <amount>", "Preview the per-charge auto-pay bound; authorizes no payment").option("--output-type <mime>", "Desired output MIME type").option(
36180
36073
  "--as <identity>",
36181
36074
  "Caller signing identity (for descriptor-auth DVMs). Defaults to the lone configured identity or `defaultIdentity` in config."
36182
36075
  ).option("--human", "Human-readable output instead of JSON").action((opts) => {
@@ -36188,7 +36081,7 @@ function buildProgram() {
36188
36081
  program2.command("request").description("Submit a job request to a DVM provider").option(
36189
36082
  "-d, --dvm <identifier>",
36190
36083
  "Qualified DVM or DVM/capability identifier (e.g. `dvmkit--narrate`, `dvmkit--cast/add-episode`). Alternative to --endpoint."
36191
- ).option("--endpoint <url>", "Provider HTTPS endpoint URL (alternative to -d)").option("-i, --input <text>", "Input text (primitive-input DVMs)").option(
36084
+ ).option("--endpoint <url>", "Provider HTTPS base URL or URL/capability (alternative to -d)").option("-i, --input <text>", "Input text (primitive-input DVMs)").option(
36192
36085
  "--param <key=value>",
36193
36086
  "Job parameter (repeatable). Agent-friendly form for DVMs with an inputSchema (bool/number/string + repeats \u2192 array). Use --data for nested values.",
36194
36087
  collectOption,
@@ -36201,7 +36094,7 @@ function buildProgram() {
36201
36094
  "Draw only from this exact already-selected prepaid credit; requires --budget and --request-id, permits no fresh payment fallback"
36202
36095
  ).option(
36203
36096
  "--auto-pay-below <amount>",
36204
- "Auto-pay any single charge at or below this \u2014 upfront quote or mid-job (millisats or $USD). Bounded consent: implies --auto-pay."
36097
+ "Auto-pay any single charge at or below this \u2014 upfront quote or mid-job (millisats or $USD). Bounded consent: implies --auto-pay, except with --credit-only where only that prepaid credit may be spent."
36205
36098
  ).option("--max-increment <amount>", "Max single payment (millisats or $USD)").option(
36206
36099
  "--max-payments <n>",
36207
36100
  "Max payments to honour per job (default: 5); 0 = free, 1 = typical, 3+ = multi-turn"