@dvmkit/dvm-cli 0.12.0 → 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-PWOTICNA.js";
164
+ } from "./chunk-WPTJM5A7.js";
136
165
  import {
137
166
  connectedTempoAccount,
138
167
  generateTempoKey,
@@ -158,7 +187,7 @@ import {
158
187
  tryResolveBtcUsdRate,
159
188
  tryX402Payment,
160
189
  withOutputWarnings
161
- } from "./chunk-IQKAJ4AN.js";
190
+ } from "./chunk-RMYEB2WG.js";
162
191
  import {
163
192
  assertSupportedX402Network,
164
193
  connectedX402Payer,
@@ -8528,27 +8557,6 @@ var {
8528
8557
  Help
8529
8558
  } = import_index.default;
8530
8559
 
8531
- // src/lib/provider-output.ts
8532
- function providerFields(value, fields = Object.keys(value)) {
8533
- return {
8534
- ...value,
8535
- _provider_fields: [.../* @__PURE__ */ new Set([
8536
- ...Array.isArray(value._provider_fields) ? value._provider_fields : [],
8537
- ...fields.filter((field) => field !== "_provider_fields" && value[field] !== void 0)
8538
- ])]
8539
- };
8540
- }
8541
- function guidanceJobArg(jobId) {
8542
- return /^[A-Za-z0-9_-]+$/.test(jobId) ? shellQuoteArg(jobId) : "'<job_id>'";
8543
- }
8544
- function providerJobJson(data, providerJob = true) {
8545
- const action = data.next_action;
8546
- json(providerFields({
8547
- ...data,
8548
- ...providerJob && action && typeof action === "object" ? { next_action: providerFields(action, ["job_id"]) } : {}
8549
- }, [...providerJob ? ["jobId"] : [], "capability", "identifier"]));
8550
- }
8551
-
8552
8560
  // src/lib/discovery-rows.ts
8553
8561
  function buildDiscoveryRows(entries) {
8554
8562
  return entries.flatMap((entry) => {
@@ -8612,176 +8620,6 @@ function renderDiscoveryDisplay(row, indent) {
8612
8620
  }
8613
8621
  }
8614
8622
 
8615
- // src/lib/messages/store.ts
8616
- import {
8617
- appendFileSync,
8618
- closeSync,
8619
- existsSync,
8620
- openSync,
8621
- readFileSync,
8622
- readSync,
8623
- statSync
8624
- } from "fs";
8625
- import { join } from "path";
8626
- var CHECKPOINT_BYTES = 64;
8627
- function appendMessages(jobId, messages2) {
8628
- if (messages2.length === 0) return;
8629
- createMessageAppendSession(jobId).append(messages2);
8630
- }
8631
- function createMessageAppendSession(jobId) {
8632
- return new FileMessageAppendSession(messageFilePath(jobId));
8633
- }
8634
- var FileMessageAppendSession = class {
8635
- constructor(filePath) {
8636
- this.filePath = filePath;
8637
- this.syncFromDisk();
8638
- }
8639
- filePath;
8640
- seqs = /* @__PURE__ */ new Set();
8641
- identity;
8642
- offset = 0;
8643
- pending = Buffer.alloc(0);
8644
- checkpoint = Buffer.alloc(0);
8645
- modifiedAt = 0;
8646
- append(messages2) {
8647
- if (messages2.length === 0) return;
8648
- this.syncFromDisk();
8649
- const selectedSeqs = new Set(this.seqs);
8650
- const newMessages = messages2.filter((message2) => {
8651
- if (selectedSeqs.has(message2.seq)) return false;
8652
- selectedSeqs.add(message2.seq);
8653
- return true;
8654
- });
8655
- if (newMessages.length === 0) return;
8656
- ensureConfigSubdir(MESSAGES_DIR);
8657
- const lines = newMessages.map((message2) => JSON.stringify(message2)).join("\n") + "\n";
8658
- appendFileSync(this.filePath, lines);
8659
- this.syncFromDisk();
8660
- }
8661
- syncFromDisk() {
8662
- const snapshot = statFile(this.filePath);
8663
- if (!snapshot) {
8664
- this.reset();
8665
- return;
8666
- }
8667
- const identity = fileIdentity(snapshot);
8668
- const changedFile = !this.identity || !sameIdentity(this.identity, identity);
8669
- const shrank = snapshot.size < this.offset;
8670
- const changedSinceRead = snapshot.size !== this.offset || Math.max(snapshot.mtimeMs, snapshot.ctimeMs) !== this.modifiedAt;
8671
- if (changedFile || shrank || changedSinceRead && !this.checkpointMatches()) {
8672
- this.reset(identity);
8673
- }
8674
- this.identity = identity;
8675
- this.modifiedAt = Math.max(snapshot.mtimeMs, snapshot.ctimeMs);
8676
- if (snapshot.size <= this.offset) return;
8677
- const bytes = readRange(this.filePath, this.offset, snapshot.size);
8678
- this.offset += bytes.byteLength;
8679
- this.consume(bytes);
8680
- this.checkpoint = trailingBytes(this.checkpoint, bytes, CHECKPOINT_BYTES);
8681
- }
8682
- checkpointMatches() {
8683
- if (this.checkpoint.length === 0 || this.offset < this.checkpoint.length) return true;
8684
- const actual = readRange(
8685
- this.filePath,
8686
- this.offset - this.checkpoint.length,
8687
- this.offset
8688
- );
8689
- return actual.equals(this.checkpoint);
8690
- }
8691
- consume(bytes) {
8692
- const combined = Buffer.concat([this.pending, bytes]);
8693
- const finalNewline = combined.lastIndexOf(10);
8694
- if (finalNewline === -1) {
8695
- this.pending = combined;
8696
- this.parseLine(this.pending);
8697
- return;
8698
- }
8699
- const complete = combined.subarray(0, finalNewline).toString("utf8");
8700
- for (const line of complete.split("\n")) this.parseLine(line);
8701
- this.pending = combined.subarray(finalNewline + 1);
8702
- this.parseLine(this.pending);
8703
- }
8704
- parseLine(line) {
8705
- const text = line.toString().trim();
8706
- if (!text) return;
8707
- try {
8708
- const message2 = JSON.parse(text);
8709
- this.seqs.add(message2.seq);
8710
- } catch {
8711
- }
8712
- }
8713
- reset(identity) {
8714
- this.seqs.clear();
8715
- this.identity = identity;
8716
- this.offset = 0;
8717
- this.pending = Buffer.alloc(0);
8718
- this.checkpoint = Buffer.alloc(0);
8719
- this.modifiedAt = 0;
8720
- }
8721
- };
8722
- function loadMessages(jobId, after) {
8723
- const filePath = messageFilePath(jobId);
8724
- if (!existsSync(filePath)) return [];
8725
- const content = readFileSync(filePath, "utf-8").trim();
8726
- if (!content) return [];
8727
- const messages2 = [];
8728
- for (const line of content.split("\n")) {
8729
- if (!line.trim()) continue;
8730
- try {
8731
- const msg = JSON.parse(line);
8732
- if (after === void 0 || msg.seq > after) {
8733
- messages2.push(msg);
8734
- }
8735
- } catch {
8736
- }
8737
- }
8738
- return messages2;
8739
- }
8740
- function messageFilePath(jobId) {
8741
- return join(MESSAGES_DIR, `${jobId}.jsonl`);
8742
- }
8743
- function statFile(filePath) {
8744
- try {
8745
- return statSync(filePath);
8746
- } catch (error) {
8747
- if (error.code === "ENOENT") return void 0;
8748
- throw error;
8749
- }
8750
- }
8751
- function fileIdentity(stats) {
8752
- return { dev: stats.dev, ino: stats.ino };
8753
- }
8754
- function sameIdentity(left, right) {
8755
- return left.dev === right.dev && left.ino === right.ino;
8756
- }
8757
- function readRange(filePath, start, end) {
8758
- const expected = Math.max(0, end - start);
8759
- const buffer = Buffer.allocUnsafe(expected);
8760
- const fd = openSync(filePath, "r");
8761
- let total = 0;
8762
- try {
8763
- while (total < expected) {
8764
- const read = readSync(fd, buffer, total, expected - total, start + total);
8765
- if (read === 0) break;
8766
- total += read;
8767
- }
8768
- } finally {
8769
- closeSync(fd);
8770
- }
8771
- return total === expected ? buffer : buffer.subarray(0, total);
8772
- }
8773
- function trailingBytes(previous, next, limit) {
8774
- if (next.length >= limit) return Buffer.from(next.subarray(next.length - limit));
8775
- const combined = Buffer.concat([previous, next]);
8776
- return Buffer.from(combined.subarray(Math.max(0, combined.length - limit)));
8777
- }
8778
-
8779
- // src/lib/messages/index.ts
8780
- function maxSeq(msgs, fallback) {
8781
- if (msgs.length === 0) return fallback;
8782
- return Math.max(...msgs.map((m) => m.seq));
8783
- }
8784
-
8785
8623
  // src/lib/payment-lock.ts
8786
8624
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
8787
8625
  import { createHash } from "crypto";
@@ -8821,226 +8659,6 @@ async function withJobPaymentLock(jobId, action) {
8821
8659
  }
8822
8660
  }
8823
8661
 
8824
- // src/lib/yield-state.ts
8825
- var JOB_READ_TIMEOUT_MS = 6e4;
8826
- var PAYMENT_SETTLE_WINDOW_MS = 45e3;
8827
- function answeredYieldSeqs(messages2) {
8828
- const answered = /* @__PURE__ */ new Set();
8829
- const prompts = /* @__PURE__ */ new Map();
8830
- let paymentRequest;
8831
- for (const message2 of [...messages2].sort((a, b) => a.seq - b.seq)) {
8832
- if (message2.from === "provider") {
8833
- if (message2.type === "payment-request") paymentRequest = message2.seq;
8834
- if (message2.type === "prompt") prompts.set(message2.content.id, message2.seq);
8835
- } else if (message2.type === "response") {
8836
- const seq = prompts.get(message2.content.prompt_id);
8837
- if (seq !== void 0) answered.add(seq);
8838
- } else if (message2.type === "payment") {
8839
- const seq = message2.content.credit?.request_seq ?? paymentRequest;
8840
- if (seq !== void 0) answered.add(seq);
8841
- }
8842
- }
8843
- return answered;
8844
- }
8845
- function latestProviderPaymentRequest(messages2) {
8846
- return [...messages2].sort((a, b) => a.seq - b.seq).findLast((message2) => message2.from === "provider" && message2.type === "payment-request");
8847
- }
8848
- function pendingPaymentRequest(messages2, answered = answeredYieldSeqs(messages2)) {
8849
- const latest = latestProviderPaymentRequest(messages2);
8850
- if (!latest || answered.has(latest.seq)) return void 0;
8851
- if (messages2.some((message2) => message2.from === "provider" && message2.seq > latest.seq && (message2.type === "complete" || message2.type === "cancel" || message2.type === "working"))) return void 0;
8852
- return latest;
8853
- }
8854
- function loadAnsweredYieldSeqs(jobId) {
8855
- const answered = answeredYieldSeqs(loadMessages(jobId));
8856
- const job = loadJob(jobId);
8857
- for (const seq of job?.paidPaymentRequestSeqs ?? []) answered.add(seq);
8858
- for (const payment of job?.bookedCreditPayments ?? []) answered.add(payment.authorization.request_seq);
8859
- return answered;
8860
- }
8861
- async function reconcileInFlightPaymentRequest(jobId, requestSeq, transport, provider, options) {
8862
- const boundedOptions = { ...options, timeoutMs: options.timeoutMs ?? JOB_READ_TIMEOUT_MS };
8863
- const history = await boundedPaymentRead(jobId, () => transport.getMessages(jobId, 0, provider, boundedOptions), boundedOptions.timeoutMs);
8864
- const decisionTime = Date.now();
8865
- const needsStatus = !answeredYieldSeqs(history).has(requestSeq) && decisionTime >= settleUntilMs(jobId, requestSeq, decisionTime);
8866
- const status2 = needsStatus ? (await boundedPaymentRead(jobId, () => transport.status(jobId, provider, boundedOptions), boundedOptions.timeoutMs)).status : void 0;
8867
- return reconcilePaymentRequestHistory(jobId, requestSeq, history, status2, () => decisionTime);
8868
- }
8869
- function reconcilePaymentRequestHistory(jobId, requestSeq, history, status2, now = Date.now) {
8870
- if (answeredYieldSeqs(history).has(requestSeq)) {
8871
- markPaymentRequestPaid(jobId, requestSeq);
8872
- return true;
8873
- }
8874
- const superseded = (latestProviderPaymentRequest(history)?.seq ?? -1) > requestSeq;
8875
- if (superseded) clearPaymentRequestInFlight(jobId, requestSeq);
8876
- const decisionTime = now();
8877
- const retryAt = settleUntilMs(jobId, requestSeq, decisionTime);
8878
- const seconds = Math.ceil((retryAt - decisionTime) / 1e3);
8879
- if (!superseded && decisionTime < retryAt)
8880
- throw new DvmError(
8881
- "payment_settling",
8882
- "The previous payment may still be processing.",
8883
- `Retry with \`dvm pay ${shellQuoteArg(jobId)}\` in about ${seconds} ${seconds === 1 ? "second" : "seconds"}, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`,
8884
- { retry_at_ms: retryAt }
8885
- );
8886
- if (status2 !== "awaiting-input" || pendingPaymentRequest(history)?.seq !== requestSeq)
8887
- throw new DvmError(
8888
- "payment_request_not_pending",
8889
- "The provider is no longer waiting on this payment request.",
8890
- `Check the job with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
8891
- );
8892
- return false;
8893
- }
8894
- function settleUntilMs(jobId, requestSeq, now) {
8895
- const startedAt = loadJob(jobId)?.inFlightPaymentRequestStartedAtMs?.[requestSeq];
8896
- return startedAt === void 0 ? 0 : Math.min(startedAt + PAYMENT_SETTLE_WINDOW_MS, now + PAYMENT_SETTLE_WINDOW_MS);
8897
- }
8898
- async function boundedPaymentRead(jobId, read, timeoutMs) {
8899
- let timer;
8900
- try {
8901
- return await Promise.race([read(), new Promise((_, reject) => {
8902
- timer = setTimeout(() => reject(new DvmError("timeout", "Payment recovery read timed out. No new payment was sent.")), timeoutMs);
8903
- })]);
8904
- } catch (error) {
8905
- if (isAbortError(error) || error instanceof DvmError && error.code === "timeout")
8906
- throw new DvmError(
8907
- "timeout",
8908
- "Payment recovery read timed out. No new payment was sent.",
8909
- `Retry with \`dvm pay ${shellQuoteArg(jobId)}\` or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`
8910
- );
8911
- throw error;
8912
- } finally {
8913
- if (timer) clearTimeout(timer);
8914
- }
8915
- }
8916
-
8917
- // src/lib/next-action.ts
8918
- function isTerminalJobStatus(status2) {
8919
- return TERMINAL_STATUSES.has(status2);
8920
- }
8921
- function pollNextAction(jobId, hint) {
8922
- return {
8923
- type: "poll",
8924
- job_id: jobId,
8925
- hint: hint ?? `Provider is still working. Keep the job moving unattended with \`dvm messages ${guidanceJobArg(jobId)} --wait\`.`
8926
- };
8927
- }
8928
- function paymentInFlightHint(jobId) {
8929
- 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.`;
8930
- }
8931
- var YIELD_TYPES = /* @__PURE__ */ new Set(["prompt", "payment-request", "working", "complete", "cancel"]);
8932
- var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
8933
- "completed",
8934
- "failed",
8935
- "cancelled"
8936
- ]);
8937
- function computeNextAction(jobId, messages2, nowMs = Date.now(), context) {
8938
- const answered = answeredYieldSeqs(messages2);
8939
- const expiresAtMs = pendingDeadline(messages2, answered);
8940
- for (let i = messages2.length - 1; i >= 0; i--) {
8941
- const msg = messages2[i];
8942
- if (!YIELD_TYPES.has(msg.type) || answered.has(msg.seq)) continue;
8943
- switch (msg.type) {
8944
- case "complete":
8945
- case "cancel":
8946
- return null;
8947
- case "prompt": {
8948
- const c = msg.content;
8949
- const answer = c.schema ? "--json '<object matching schema>'" : '"<answer>"';
8950
- const choices = c.options?.length ? ` Choices: ${c.options.map((option) => JSON.stringify(option)).join(", ")}.` : "";
8951
- const choiceHint = !c.schema && c.options?.length ? " Answer with exactly one of options unless the human chose otherwise." : "";
8952
- const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Answer" : "Reply", expiresAtMs, nowMs, jobId);
8953
- const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
8954
- const action = {
8955
- type: "respond",
8956
- job_id: jobId,
8957
- prompt_id: c.id,
8958
- prompt: asProviderText(c.text),
8959
- _provider_fields: [
8960
- "prompt_id",
8961
- ...c.schema ? ["schema"] : [],
8962
- ...c.options?.length ? ["options"] : []
8963
- ],
8964
- display: withDeadline(`The provider asks: ${c.text}${choices}`, deadline),
8965
- 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)
8966
- };
8967
- if (c.schema) action.schema = c.schema;
8968
- if (c.options?.length) action.options = c.options;
8969
- if (expiresAtMs !== void 0) action.expires_at_ms = expiresAtMs;
8970
- return action;
8971
- }
8972
- case "payment-request": {
8973
- const c = msg.content;
8974
- const display = formatPaymentAmount(c.amount_msats, c.fiat_amount);
8975
- 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);
8976
- const priceGuidance = safeCurrency ? display : "see the provider price in next_action.fiat_amount";
8977
- const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Pay" : "Reply", expiresAtMs, nowMs, jobId);
8978
- const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
8979
- const policy = context?.policy;
8980
- const thresholdHint = !expired && policy && Number.isSafeInteger(c.amount_msats) && c.amount_msats > policy.autoPayBelowMsats && (context?.totalPaidMsats ?? 0) + c.amount_msats <= policy.maxTotalMsats && (policy.maxIncrementMsats === 0 || c.amount_msats <= policy.maxIncrementMsats) ? ` For the next run, use --auto-pay-below ${c.amount_msats} within your approved budget; other payment limits still apply.` : "";
8981
- return {
8982
- type: "pay",
8983
- job_id: jobId,
8984
- amount_msats: c.amount_msats,
8985
- // Mirror only a fiat figure the display actually led with: echoing a
8986
- // zero amount would tell an agent doing budget math the charge is free.
8987
- ...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount, _provider_fields: ["fiat_amount"] } : {},
8988
- ...expiresAtMs !== void 0 ? { expires_at_ms: expiresAtMs } : {},
8989
- display: withDeadline(display, deadline),
8990
- reason: asProviderText(c.reason),
8991
- 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) + thresholdHint
8992
- };
8993
- }
8994
- case "working": {
8995
- const c = msg.content;
8996
- return {
8997
- type: "poll",
8998
- job_id: jobId,
8999
- estimate_seconds: c.estimate_seconds,
9000
- hint: c.hint !== void 0 ? asProviderText(c.hint) : pollNextAction(jobId).hint
9001
- };
9002
- }
9003
- }
9004
- }
9005
- return null;
9006
- }
9007
- function pendingDeadline(messages2, answered) {
9008
- const prompts = /* @__PURE__ */ new Map();
9009
- let payment;
9010
- for (const message2 of [...messages2].sort((a, b) => a.seq - b.seq)) {
9011
- if (message2.from === "provider" && message2.type === "prompt") {
9012
- prompts.set(message2.content.id, validDeadline(message2.content.expires_at_ms));
9013
- } else if (message2.from === "requester" && message2.type === "response") {
9014
- prompts.delete(message2.content.prompt_id);
9015
- } else if (message2.from === "provider" && message2.type === "payment-request") {
9016
- payment = !answered.has(message2.seq) && message2.content.amount_msats > 0 ? validDeadline(message2.content.expires_at_ms) : void 0;
9017
- }
9018
- }
9019
- let earliest = payment;
9020
- for (const deadline of prompts.values()) {
9021
- if (deadline !== void 0 && (earliest === void 0 || deadline < earliest)) earliest = deadline;
9022
- }
9023
- return earliest;
9024
- }
9025
- function validDeadline(value) {
9026
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 864e13 ? value : void 0;
9027
- }
9028
- function withDeadline(display, deadline) {
9029
- if (!deadline) return display;
9030
- return `${display}${/[.!?]$/.test(display) ? "" : "."} ${deadline}`;
9031
- }
9032
- function deadlineClause(action, expiresAtMs, nowMs, jobId) {
9033
- if (expiresAtMs === void 0) return "";
9034
- const deadline = new Date(expiresAtMs).toISOString().slice(0, 16).replace("T", " ") + " UTC";
9035
- if (expiresAtMs <= nowMs) {
9036
- return `The deadline to ${action.toLowerCase()} (${deadline}) has passed. The provider will probably cancel the job. Check its status with \`dvm status ${guidanceJobArg(jobId)}\`.`;
9037
- }
9038
- const minutes = Math.floor((expiresAtMs - nowMs) / 6e4);
9039
- const hours = Math.floor(minutes / 60);
9040
- 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";
9041
- return `${action} by ${deadline} (in ${remaining}), or the provider cancels the job.`;
9042
- }
9043
-
9044
8662
  // src/lib/rail-labels.ts
9045
8663
  var PAYMENT_RAIL_KEYS = ["cashu", "cashu_p2pk", "x402", "tempo"];
9046
8664
  function isPaymentRailKey(value) {
@@ -9080,7 +8698,7 @@ function railLabelAtSentenceStart(label) {
9080
8698
 
9081
8699
  // src/lib/payment-copy.ts
9082
8700
  function paidConfirmationDisplay(result, fiat) {
9083
- 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.`;
9084
8702
  }
9085
8703
  function formatPaidAmount(result, fiat) {
9086
8704
  if (result.amountUsdcMicro !== void 0) {
@@ -9093,15 +8711,15 @@ function formatPaidAmount(result, fiat) {
9093
8711
  import { randomUUID } from "crypto";
9094
8712
 
9095
8713
  // src/lib/caller-version.ts
9096
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
9097
- import { dirname, join as join2 } from "path";
8714
+ import { existsSync, readFileSync } from "fs";
8715
+ import { dirname, join } from "path";
9098
8716
  import { fileURLToPath } from "url";
9099
8717
  var CALLER_VERSION = readCallerVersion();
9100
8718
  function readCallerVersion() {
9101
8719
  let dir = dirname(fileURLToPath(import.meta.url));
9102
8720
  for (; ; ) {
9103
- const manifestPath = join2(dir, "package.json");
9104
- if (existsSync2(manifestPath)) {
8721
+ const manifestPath = join(dir, "package.json");
8722
+ if (existsSync(manifestPath)) {
9105
8723
  const manifest = readManifest(manifestPath);
9106
8724
  if (manifest.name === "@dvmkit/dvm-cli") return manifest.version;
9107
8725
  }
@@ -9113,7 +8731,7 @@ function readCallerVersion() {
9113
8731
  }
9114
8732
  }
9115
8733
  function readManifest(path) {
9116
- return JSON.parse(readFileSync2(path, "utf8"));
8734
+ return JSON.parse(readFileSync(path, "utf8"));
9117
8735
  }
9118
8736
 
9119
8737
  // src/lib/client-compatibility.ts
@@ -9511,7 +9129,7 @@ function buildCreditDrawSkipped(args) {
9511
9129
  const last = `$${formatUsd((skip.lastPriceMicro ?? 0) / 1e6)}`;
9512
9130
  const ceiling = `$${formatUsd((skip.ceilingMicro ?? 0) / 1e6)}`;
9513
9131
  return {
9514
- 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.`,
9515
9133
  hint: raiseCeilingHint(skip.ceilingSource, last)
9516
9134
  };
9517
9135
  }
@@ -11182,6 +10800,148 @@ function parseTempoNetwork(value, source) {
11182
10800
  );
11183
10801
  }
11184
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
+
11185
10945
  // src/lib/payment-responder.ts
11186
10946
  async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
11187
10947
  return withJobPaymentLock(jobId, (assertOwned) => {
@@ -11196,6 +10956,28 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11196
10956
  }
11197
10957
  });
11198
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;
11199
10981
  });
11200
10982
  }
11201
10983
  async function handleLockedPaymentRequest(jobId, request2, policy, transport, provider, opts) {
@@ -11327,7 +11109,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11327
11109
  }
11328
11110
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11329
11111
  const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UJ7EJNQA.js");
11330
- const { tryX402Payment: tryX402Payment2 } = await import("./client-HEWHZMS2.js");
11112
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-V7KAPCAG.js");
11331
11113
  const wallet = loadX402Wallet2();
11332
11114
  if (wallet) {
11333
11115
  let proof;
@@ -12100,39 +11882,6 @@ function isCallerMessage(message2) {
12100
11882
  return callerMessages.has(message2);
12101
11883
  }
12102
11884
 
12103
- // src/lib/job-content.ts
12104
- function parseJobContent(data) {
12105
- return {
12106
- ...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 } : {},
12107
- ...typeof data.content_available === "boolean" ? { content_available: data.content_available } : {}
12108
- };
12109
- }
12110
- function jobContentFields(jobId, observed, human = false) {
12111
- const metadata = parseJobContent(observed ?? {});
12112
- const known = metadata.content_expires_at !== void 0 && metadata.content_available !== void 0;
12113
- 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.";
12114
- 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.";
12115
- 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.`;
12116
- return {
12117
- ...metadata,
12118
- content_metadata_source: observed ? "provider" : "unknown",
12119
- content_metadata_known: known,
12120
- content_hint: `${availability} ${expiry} ${save}`
12121
- };
12122
- }
12123
- async function observeJobContent(jobId, transport, ref, options) {
12124
- try {
12125
- const status2 = await transport.status(jobId, ref, {
12126
- ...options,
12127
- timeoutMs: options.timeoutMs > 0 ? Math.min(options.timeoutMs, 5e3) : 5e3
12128
- });
12129
- captureDrawFundingReceipts(jobId, status2.drawFundingReceipts, { endpoint: ref.endpoint });
12130
- return parseJobContent(status2);
12131
- } catch {
12132
- return void 0;
12133
- }
12134
- }
12135
-
12136
11885
  // src/lib/job-envelope.ts
12137
11886
  function buildJobEnvelope(opts) {
12138
11887
  const envelope = {
@@ -12243,6 +11992,14 @@ var HttpsTransport = class {
12243
11992
  }
12244
11993
  throw err;
12245
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
+ }
12246
12003
  if (!res.ok) {
12247
12004
  throw providerResponseError(
12248
12005
  "provider_error",
@@ -13023,7 +12780,7 @@ function x402RequiredUsdcMicro(required) {
13023
12780
  }
13024
12781
  return required.accepts.at(0)?.maxAmountRequired;
13025
12782
  }
13026
- 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"]);
13027
12784
  async function parseSSEStream(res, options, recognize = (message2) => message2) {
13028
12785
  const messages2 = [];
13029
12786
  if (!res.body) {
@@ -13050,7 +12807,7 @@ async function parseSSEStream(res, options, recognize = (message2) => message2)
13050
12807
  const msg = recognize(JSON.parse(json2));
13051
12808
  messages2.push(msg);
13052
12809
  options?.onMessage?.(msg);
13053
- if (YIELD_TYPES2.has(msg.type)) {
12810
+ if (YIELD_TYPES.has(msg.type)) {
13054
12811
  if (msg.type === "complete") lastReason = "complete";
13055
12812
  else if (msg.type === "cancel") lastReason = "cancel";
13056
12813
  else lastReason = "yield";
@@ -13241,7 +12998,7 @@ function parseUpfront(data) {
13241
12998
  };
13242
12999
  }
13243
13000
  }
13244
- return { amount: 0, currency: "usd" };
13001
+ return unknownUpfrontPrice();
13245
13002
  }
13246
13003
  function exactMicro(raw2) {
13247
13004
  return typeof raw2 === "number" && Number.isSafeInteger(raw2) && raw2 > 0 ? raw2 : void 0;
@@ -13665,7 +13422,7 @@ function resolveDvmReference(raw2) {
13665
13422
  function isValidHandle(handle) {
13666
13423
  return handle.length >= 2 && handle.length <= 20 && HANDLE_RE.test(handle) && !handle.includes("--");
13667
13424
  }
13668
- function resolveCapability(info2, requested, dvmId) {
13425
+ function resolveCapability(info2, requested, dvmId, endpoint) {
13669
13426
  const caps = info2.capabilities ? Object.keys(info2.capabilities) : [];
13670
13427
  const reference = dvmId ?? "this endpoint";
13671
13428
  if (caps.length === 0) {
@@ -13680,7 +13437,7 @@ function resolveCapability(info2, requested, dvmId) {
13680
13437
  throw new DvmError(
13681
13438
  "unknown_capability",
13682
13439
  `"${requested}" is not a capability of ${reference}.`,
13683
- 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),
13684
13441
  { available_capabilities: caps, _provider_fields: ["available_capabilities"] }
13685
13442
  );
13686
13443
  }
@@ -13688,10 +13445,34 @@ function resolveCapability(info2, requested, dvmId) {
13688
13445
  throw new DvmError(
13689
13446
  "ambiguous_capability",
13690
13447
  `${reference} has multiple capabilities; specify one from available_capabilities.`,
13691
- 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),
13692
13449
  { available_capabilities: caps, _provider_fields: ["available_capabilities"] }
13693
13450
  );
13694
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
+ }
13695
13476
 
13696
13477
  // src/commands/dvm-identity.ts
13697
13478
  function dvmIdentity(dvmId, capability) {
@@ -13714,7 +13495,12 @@ async function cancelWithAccess(jobId, opts, access) {
13714
13495
  progressNotice("Cancelling job...", opts.human);
13715
13496
  await transport.cancel(jobId, opts.reason, ref, { jobToken });
13716
13497
  transport.close();
13717
- 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
+ );
13718
13504
  const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
13719
13505
  if (opts.human) {
13720
13506
  info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
@@ -17832,6 +17618,85 @@ function invalidOperation(message2, hint) {
17832
17618
  return new DvmError("invalid_argument", message2, hint);
17833
17619
  }
17834
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
+
17835
17700
  // src/commands/describe.ts
17836
17701
  async function describe(input, opts) {
17837
17702
  let endpoint;
@@ -17841,14 +17706,21 @@ async function describe(input, opts) {
17841
17706
  } else if (/^https?:\/\//.test(input)) {
17842
17707
  endpoint = input;
17843
17708
  } else {
17844
- const resolved = resolveDvmReference(input);
17845
- endpoint = resolved.endpoint;
17846
- qualifiedDvmId = resolved.qualified?.dvmId;
17709
+ const resolved2 = resolveDvmReference(input);
17710
+ endpoint = resolved2.endpoint;
17711
+ qualifiedDvmId = resolved2.qualified?.dvmId;
17847
17712
  }
17848
17713
  const transport = createDvmTransport();
17849
- const ref = { endpoint };
17850
17714
  progressNotice("Fetching provider info...", opts.human);
17851
- 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
+ }
17852
17724
  if (opts.human) {
17853
17725
  info(providerInfo.name ?? "(unnamed)");
17854
17726
  if (providerInfo.about) info(` ${providerInfo.about}`);
@@ -17884,7 +17756,7 @@ function renderCapabilitiesHuman(providerInfo, endpoint, qualifiedDvmId) {
17884
17756
  info(` ${capName}`);
17885
17757
  if (cap2.description) info(` ${cap2.description}`);
17886
17758
  const identifier = qualifiedDvmId ? multiCap ? `${qualifiedDvmId}/${capName}` : qualifiedDvmId : void 0;
17887
- const quoteCommand = identifier ? `dvm quote -d ${identifier}` : `dvm quote --endpoint ${endpoint}`;
17759
+ const quoteCommand = identifier ? `dvm quote -d ${identifier}` : capabilityQuoteCommand(endpoint, capName);
17888
17760
  const priceLine = formatCapabilityPrice(cap2.pricing, quoteCommand);
17889
17761
  if (priceLine) info(` ${priceLine}`);
17890
17762
  const schema = cap2.input_schema;
@@ -18460,7 +18332,7 @@ function x402WrongAssetHint(asset) {
18460
18332
  }
18461
18333
 
18462
18334
  // src/lib/build-freshness.ts
18463
- import { existsSync as existsSync3, readdirSync, statSync as statSync2 } from "fs";
18335
+ import { existsSync as existsSync3, readdirSync, statSync } from "fs";
18464
18336
  import { dirname as dirname2, join as join3 } from "path";
18465
18337
  import { fileURLToPath as fileURLToPath2 } from "url";
18466
18338
  var EXTRA_SOURCES = ["package.json", "tsup.config.ts"];
@@ -18486,7 +18358,7 @@ function checkBuildFreshness(opts) {
18486
18358
  }
18487
18359
  const srcDir = join3(root, "src");
18488
18360
  if (!existsSync3(srcDir)) return skipped("no_source_tree");
18489
- const builtAtMs = statSync2(bundlePath).mtimeMs;
18361
+ const builtAtMs = statSync(bundlePath).mtimeMs;
18490
18362
  const newer = [];
18491
18363
  let newestMs = 0;
18492
18364
  const visit = (dir, rel, budget2) => {
@@ -18501,7 +18373,7 @@ function checkBuildFreshness(opts) {
18501
18373
  continue;
18502
18374
  }
18503
18375
  if (!entry.isFile()) continue;
18504
- const mtimeMs = statSync2(abs).mtimeMs;
18376
+ const mtimeMs = statSync(abs).mtimeMs;
18505
18377
  if (mtimeMs > newestMs) newestMs = mtimeMs;
18506
18378
  if (mtimeMs > builtAtMs) newer.push({ path: relPath, mtimeMs });
18507
18379
  }
@@ -18511,7 +18383,7 @@ function checkBuildFreshness(opts) {
18511
18383
  for (const name of EXTRA_SOURCES) {
18512
18384
  const abs = join3(root, name);
18513
18385
  if (!existsSync3(abs)) continue;
18514
- const mtimeMs = statSync2(abs).mtimeMs;
18386
+ const mtimeMs = statSync(abs).mtimeMs;
18515
18387
  if (mtimeMs > newestMs) newestMs = mtimeMs;
18516
18388
  if (mtimeMs > builtAtMs) newer.push({ path: name, mtimeMs });
18517
18389
  }
@@ -18536,7 +18408,7 @@ function findPackageRoot(start) {
18536
18408
  }
18537
18409
 
18538
18410
  // src/lib/caller-state.ts
18539
- 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";
18540
18412
  import { basename, join as join4 } from "path";
18541
18413
  function detectSetupState() {
18542
18414
  return {
@@ -18691,7 +18563,7 @@ function checkOne(spec) {
18691
18563
  checkSecretDirectory(spec.path, row);
18692
18564
  } else if (spec.secret) {
18693
18565
  try {
18694
- const mode = statSync3(spec.path).mode & 511;
18566
+ const mode = statSync2(spec.path).mode & 511;
18695
18567
  const modeOctal = octalMode(mode);
18696
18568
  row.modeOk = mode === 384;
18697
18569
  row.modeOctal = modeOctal;
@@ -18710,7 +18582,7 @@ function checkSecretDirectory(dir, row) {
18710
18582
  const offenders = [];
18711
18583
  for (const name of readdirSync2(dir)) {
18712
18584
  const path = join4(dir, name);
18713
- const stat2 = statSync3(path);
18585
+ const stat2 = statSync2(path);
18714
18586
  if (!stat2.isFile()) continue;
18715
18587
  const mode = stat2.mode & 511;
18716
18588
  if (mode !== 384) offenders.push({ path, modeOctal: octalMode(mode) });
@@ -18741,7 +18613,7 @@ function readBtcRateCacheAge(now = Date.now()) {
18741
18613
  }
18742
18614
 
18743
18615
  // src/lib/mnemonic-backups.ts
18744
- import { readdirSync as readdirSync3, statSync as statSync4 } from "fs";
18616
+ import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
18745
18617
  import { basename as basename2, dirname as dirname3, join as join5 } from "path";
18746
18618
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
18747
18619
  const dir = dirname3(mnemonicFile);
@@ -18755,7 +18627,7 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
18755
18627
  }
18756
18628
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
18757
18629
  const path = join5(dir, name);
18758
- const stat2 = statSync4(path);
18630
+ const stat2 = statSync3(path);
18759
18631
  if (!stat2.isFile()) return null;
18760
18632
  const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
18761
18633
  return {
@@ -20813,7 +20685,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
20813
20685
  }
20814
20686
 
20815
20687
  // src/lib/feedback-nudges.ts
20816
- 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";
20817
20689
 
20818
20690
  // src/lib/feedback-notice.ts
20819
20691
  function buildFeedbackNudge(args) {
@@ -20957,9 +20829,9 @@ function coercePerDvm(perDvm) {
20957
20829
  function saveState(state) {
20958
20830
  ensureConfigDir();
20959
20831
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
20960
- writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
20832
+ writeFileSync2(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
20961
20833
  try {
20962
- renameSync(tmp, FEEDBACK_NUDGES_FILE);
20834
+ renameSync2(tmp, FEEDBACK_NUDGES_FILE);
20963
20835
  } catch (err) {
20964
20836
  try {
20965
20837
  unlinkSync(tmp);
@@ -20971,7 +20843,7 @@ function saveState(state) {
20971
20843
  var nudgedThisInvocation = false;
20972
20844
 
20973
20845
  // src/lib/platform.ts
20974
- 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";
20975
20847
  import { homedir } from "os";
20976
20848
  import { join as join6 } from "path";
20977
20849
  function getPlatformUrl() {
@@ -21548,7 +21420,7 @@ import {
21548
21420
  readdirSync as readdirSync4,
21549
21421
  rmdirSync,
21550
21422
  unlinkSync as unlinkSync2,
21551
- writeFileSync as writeFileSync3
21423
+ writeFileSync as writeFileSync4
21552
21424
  } from "fs";
21553
21425
  import { tmpdir } from "os";
21554
21426
  import { join as join7 } from "path";
@@ -21610,7 +21482,7 @@ var ArtifactSaveSession = class {
21610
21482
  path = join7(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
21611
21483
  fd = openSync2(path, "wx", FILE_MODE);
21612
21484
  created = true;
21613
- writeFileSync3(fd, buf);
21485
+ writeFileSync4(fd, buf);
21614
21486
  closeSync2(fd);
21615
21487
  fd = void 0;
21616
21488
  chmodSync(path, FILE_MODE);
@@ -21675,50 +21547,24 @@ function formatBytes(bytes) {
21675
21547
  return `${bytes.toLocaleString("en-US")} bytes`;
21676
21548
  }
21677
21549
 
21678
- // src/lib/completion-hints.ts
21679
- function buildCompletionHintFields(jobId, input) {
21680
- const out = {};
21681
- if (input.hasArtifacts !== void 0) out.has_artifacts = input.hasArtifacts;
21682
- if (input.artifactCount !== void 0) out.artifact_count = input.artifactCount;
21683
- if (input.payloadIn) out.payload_in = input.payloadIn;
21684
- const hint = nextStepHint(jobId, input.payloadIn, input.artifactCount);
21685
- if (hint) out.next_step_hint = hint;
21686
- return out;
21687
- }
21688
- function nextStepHint(jobId, payloadIn, artifactCount, human = false) {
21689
- if (payloadIn !== "messages") return void 0;
21690
- const noun = artifactCount === 1 ? "artifact" : "artifacts";
21691
- return `Run 'dvm messages ${human ? shellQuoteArg(jobId) : guidanceJobArg(jobId)} --no-stream' to fetch the ${noun}.`;
21692
- }
21693
- function completionSnapshot(src) {
21694
- const out = {};
21695
- if (src.summary !== void 0) out.summary = src.summary;
21696
- if (src.message !== void 0) out.message = src.message;
21697
- if (src.hasArtifacts !== void 0) out.hasArtifacts = src.hasArtifacts;
21698
- if (src.artifactCount !== void 0) out.artifactCount = src.artifactCount;
21699
- if (src.payloadIn) out.payloadIn = src.payloadIn;
21700
- return out;
21701
- }
21702
- function completionFromMessages(messages2) {
21703
- const complete = messages2.findLast((m) => m.type === "complete");
21704
- const summary = complete?.type === "complete" ? complete.content.summary : void 0;
21705
- const artifactCount = messages2.filter((m) => m.type === "artifact").length;
21706
- const out = {
21707
- hasArtifacts: artifactCount > 0,
21708
- payloadIn: artifactCount > 0 ? "messages" : "summary"
21709
- };
21710
- if (summary !== void 0) out.summary = summary;
21711
- if (artifactCount > 0) out.artifactCount = artifactCount;
21712
- return out;
21713
- }
21714
-
21715
21550
  // src/lib/stream-outcome.ts
21716
21551
  function persistStreamOutcome(outcome) {
21717
- const { jobId, messages: messages2, cursor, afterSeq, extra } = outcome;
21718
- 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 });
21719
21556
  const log = terminal ? fullMessageLog(jobId, messages2, afterSeq) : void 0;
21720
- if (terminal && log) {
21721
- 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
+ };
21722
21568
  markJobTerminal(jobId, terminal, completion, {
21723
21569
  messageCursor: cursor,
21724
21570
  ...extra
@@ -21728,10 +21574,13 @@ function persistStreamOutcome(outcome) {
21728
21574
  updateJob(jobId, { messageCursor: cursor });
21729
21575
  return void 0;
21730
21576
  }
21731
- function streamTerminalStatus(messages2) {
21577
+ function streamTerminalStatus(messages2, context = {}) {
21578
+ const providerStatus = context.providerStatus?.status;
21579
+ if (providerStatus && isTerminalJobStatus(providerStatus)) return providerStatus;
21732
21580
  const last = messages2.findLast((m) => m.type === "complete" || m.type === "cancel");
21733
21581
  if (!last) return void 0;
21734
- return last.type === "complete" ? "completed" : "cancelled";
21582
+ if (last.type === "complete") return "completed";
21583
+ return context.callerCancelled ? "cancelled" : "failed";
21735
21584
  }
21736
21585
  function fullMessageLog(jobId, messages2, afterSeq) {
21737
21586
  if (afterSeq === 0) return messages2;
@@ -21799,7 +21648,7 @@ function formatMessageHuman(msg, jobId, artifactSession) {
21799
21648
  const noun = msg.content.reason === "change" ? "change" : "refund";
21800
21649
  info(`[${msg.seq}] ${prefix} sent ${noun}: ${amount}`);
21801
21650
  } else {
21802
- info(`[${msg.seq}] ${prefix} paid: ${amount}`);
21651
+ info(`[${msg.seq}] ${prefix} sent payment: ${amount}`);
21803
21652
  }
21804
21653
  break;
21805
21654
  }
@@ -21815,7 +21664,7 @@ function formatMessageHuman(msg, jobId, artifactSession) {
21815
21664
  renderProgressLine(msg.content, msg.seq);
21816
21665
  break;
21817
21666
  case "cancel":
21818
- info(`[${msg.seq}] Cancelled${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
21667
+ info(`[${msg.seq}] Job ended${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
21819
21668
  break;
21820
21669
  default:
21821
21670
  info(`[${seq}] ${prefix} sent a message of type "${type}".`);
@@ -21904,6 +21753,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
21904
21753
  const snapshot = await readWithRetry(() => opts.transport.status(opts.jobId, opts.provider, readOptions()));
21905
21754
  if (!snapshot) break;
21906
21755
  if (isTerminalJobStatus(snapshot.status)) {
21756
+ result.providerStatus = snapshot;
21907
21757
  result.nextAction = null;
21908
21758
  const history = await readWithRetry(() => opts.transport.getMessages(opts.jobId, result.cursor, opts.provider, readOptions()));
21909
21759
  if (!history) break;
@@ -22025,10 +21875,11 @@ async function messagesWithAccess(jobId, opts, access) {
22025
21875
  return { ...action, hint: paymentInFlightHint(jobId) };
22026
21876
  return action;
22027
21877
  }
22028
- async function resolveNextAction2(action, messages2) {
21878
+ async function resolveNextAction2(action, messages2, observedStatus) {
22029
21879
  if (action?.type === "refund") return action;
21880
+ if (observedStatus && isTerminalJobStatus(observedStatus)) return null;
22030
21881
  if (streamTerminalStatus(messages2) || !access.endpointOverridden && stored && isTerminalJobStatus(stored.status)) return null;
22031
- if (!opts.human) return action;
21882
+ if (!opts.human || opts.wait) return action;
22032
21883
  try {
22033
21884
  const readOptions = { jobToken, timeoutMs: opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 };
22034
21885
  const snapshot = await transport.status(jobId, ref, readOptions);
@@ -22064,19 +21915,18 @@ async function messagesWithAccess(jobId, opts, access) {
22064
21915
  }
22065
21916
  if (!access.endpointOverridden) appendMessages(jobId, msgs);
22066
21917
  const newCursor = maxSeq(msgs, after);
21918
+ const providerStatus2 = await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken });
22067
21919
  if (!access.endpointOverridden) {
22068
- persistStreamOutcome({ jobId, messages: msgs, cursor: newCursor, afterSeq: after });
21920
+ persistStreamOutcome({ jobId, messages: msgs, cursor: newCursor, afterSeq: after, providerStatus: providerStatus2 });
22069
21921
  }
22070
21922
  const refunds = access.endpointOverridden ? [] : await claimInboundPayments(jobId, msgs);
22071
- const nextAction = withRefundNextAction(jobId, actionFromMessages(msgs) ?? (streamTerminalStatus(msgs) || isTerminal ? null : pollNextAction(jobId)), refunds);
22072
- const content2 = jobContentFields(
22073
- jobId,
22074
- await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken }),
22075
- opts.human
22076
- );
22077
- 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);
22078
21927
  transport.close();
22079
21928
  if (opts.human) {
21929
+ if (settlement2.settlement) info(settlement2.settlement.display);
22080
21930
  info(String(content2.content_hint));
22081
21931
  if (msgs.length === 0) {
22082
21932
  info("No new messages.");
@@ -22091,6 +21941,7 @@ async function messagesWithAccess(jobId, opts, access) {
22091
21941
  json2({
22092
21942
  jobId,
22093
21943
  ...content2,
21944
+ ...settlement2,
22094
21945
  messages: msgs.map(serialize),
22095
21946
  cursor: newCursor,
22096
21947
  next_action: resolvedAction2,
@@ -22124,25 +21975,25 @@ async function messagesWithAccess(jobId, opts, access) {
22124
21975
  transport.close();
22125
21976
  throw err;
22126
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
+ });
22127
21982
  if (!access.endpointOverridden) {
22128
21983
  persistStreamOutcome({
22129
21984
  jobId,
22130
21985
  messages: result.messages,
22131
21986
  cursor: result.cursor,
22132
- afterSeq: after
21987
+ afterSeq: after,
21988
+ providerStatus: providerStatus ?? result.providerStatus
22133
21989
  });
22134
21990
  }
22135
- const content = jobContentFields(
22136
- jobId,
22137
- waitDeadline !== void 0 && Date.now() >= waitDeadline ? void 0 : await observeJobContent(jobId, transport, ref, {
22138
- timeoutMs: waitDeadline === void 0 ? opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now())),
22139
- jobToken
22140
- }),
22141
- opts.human
22142
- );
22143
- 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);
22144
21994
  transport.close();
22145
21995
  if (opts.human) {
21996
+ if (settlement.settlement) info(settlement.settlement.display);
22146
21997
  info(String(content.content_hint));
22147
21998
  if (result.messages.length === 0) {
22148
21999
  info("No new messages.");
@@ -22158,6 +22009,7 @@ async function messagesWithAccess(jobId, opts, access) {
22158
22009
  json2({
22159
22010
  jobId,
22160
22011
  ...content,
22012
+ ...settlement,
22161
22013
  messages: result.messages.map(serialize),
22162
22014
  cursor: result.cursor,
22163
22015
  next_action: resolvedAction,
@@ -22220,7 +22072,7 @@ function serialize(msg) {
22220
22072
  }
22221
22073
  case "payment": {
22222
22074
  const amount = paymentAmount(msg);
22223
- 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}`;
22224
22076
  return { ...base, content: { ...msg.content }, display };
22225
22077
  }
22226
22078
  case "complete": {
@@ -22246,7 +22098,7 @@ function serialize(msg) {
22246
22098
  return { ...base, content, display };
22247
22099
  }
22248
22100
  case "cancel": {
22249
- const display = `Cancelled${msg.content.reason ? `: ${msg.content.reason}` : ""}`;
22101
+ const display = `Job ended${msg.content.reason ? `: ${msg.content.reason}` : ""}`;
22250
22102
  const content = { ...msg.content };
22251
22103
  if (fromProvider && msg.content.reason !== void 0) {
22252
22104
  content.reason = asProviderText(msg.content.reason);
@@ -22285,6 +22137,8 @@ async function messageWithAccess(jobId, text, opts, access) {
22285
22137
  const transport = createDvmTransport();
22286
22138
  progressNotice("Sending message...", opts.human);
22287
22139
  await transport.sendMessage(jobId, outbound, ref, { jobToken });
22140
+ if (msgType === "cancel" && !access.endpointOverridden)
22141
+ markJobTerminal(jobId, "cancelled", { message: text }, { callerCancelled: true });
22288
22142
  const timeoutMs = opts.timeout ? Number(opts.timeout) * 1e3 : void 0;
22289
22143
  const afterSeq = access.endpointOverridden ? 0 : stored?.messageCursor ?? 0;
22290
22144
  const result = await streamLoop({
@@ -22297,10 +22151,17 @@ async function messageWithAccess(jobId, text, opts, access) {
22297
22151
  jobToken,
22298
22152
  persistLocalState: !access.endpointOverridden
22299
22153
  });
22300
- if (!access.endpointOverridden) {
22301
- persistStreamOutcome({ jobId, messages: result.messages, cursor: result.cursor, afterSeq });
22302
- }
22303
- 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);
22304
22165
  if (streamedTerminal && stored && !access.endpointOverridden) {
22305
22166
  noteFeedbackAfterTerminal({
22306
22167
  jobId,
@@ -22310,13 +22171,11 @@ async function messageWithAccess(jobId, text, opts, access) {
22310
22171
  human: opts.human
22311
22172
  });
22312
22173
  }
22313
- const content = jobContentFields(
22314
- jobId,
22315
- await observeJobContent(jobId, transport, ref, { timeoutMs: timeoutMs ?? 5e3, jobToken }),
22316
- opts.human
22317
- );
22174
+ const content = jobContentFields(jobId, providerStatus, opts.human);
22175
+ const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden);
22318
22176
  transport.close();
22319
22177
  if (opts.human) {
22178
+ if (settlement.settlement) info(settlement.settlement.display);
22320
22179
  info(String(content.content_hint));
22321
22180
  info(`Message sent (type: ${msgType}).`);
22322
22181
  for (const msg of result.messages) {
@@ -22327,6 +22186,7 @@ async function messageWithAccess(jobId, text, opts, access) {
22327
22186
  json2({
22328
22187
  jobId,
22329
22188
  ...content,
22189
+ ...settlement,
22330
22190
  sent: { type: outbound.type, content: outbound.content },
22331
22191
  messages: result.messages.map(serializeMessageForOutput),
22332
22192
  ...takeCreditNoticeFields(),
@@ -22510,12 +22370,14 @@ async function payWithAccess(jobId, opts, access) {
22510
22370
  jobToken,
22511
22371
  persistLocalState: !access.endpointOverridden
22512
22372
  });
22513
- 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;
22514
22375
  const completion = access.endpointOverridden ? streamedTerminal ? completionFromMessages(streamResult.messages) : void 0 : persistStreamOutcome({
22515
22376
  jobId,
22516
22377
  messages: streamResult.messages,
22517
22378
  cursor: streamResult.cursor,
22518
- afterSeq
22379
+ afterSeq,
22380
+ providerStatus
22519
22381
  });
22520
22382
  if (streamedTerminal && !access.endpointOverridden) {
22521
22383
  noteFeedbackAfterTerminal({
@@ -22526,9 +22388,11 @@ async function payWithAccess(jobId, opts, access) {
22526
22388
  human: opts.human
22527
22389
  });
22528
22390
  }
22391
+ const settlement = observedSettlementFields(jobId, providerStatus, !access.endpointOverridden);
22529
22392
  transport.close();
22530
22393
  const identifier = stored.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
22531
22394
  if (opts.human) {
22395
+ if (settlement.settlement) info(settlement.settlement.display);
22532
22396
  info(`${paid.display}${identifier ? ` [${identifier}]` : ""}`);
22533
22397
  for (const msg of streamResult.messages) {
22534
22398
  formatMessageHuman(msg, jobId, artifactSession);
@@ -22543,12 +22407,9 @@ async function payWithAccess(jobId, opts, access) {
22543
22407
  jobId,
22544
22408
  ...dvmIdentity(stored.dvmId, stored.capability),
22545
22409
  paid,
22410
+ ...settlement,
22546
22411
  messages: streamResult.messages.map(serializeMessageForOutput),
22547
- // A payment that resumes the handler through to `complete` ends the job
22548
- // here, and this path has no transport receipt to read the outcome off —
22549
- // so without these an agent that pays sees `next_action: null` and can't
22550
- // tell whether the payload is the summary or artifacts it must go fetch
22551
- // Mirrors what `dvm request` renders on the upfront-paid arc.
22412
+ // Retain delivery hints when the payment resumes work through completion.
22552
22413
  ...completion?.summary !== void 0 ? { summary: completion.summary, _provider_fields: ["summary"] } : {},
22553
22414
  ...completion ? buildCompletionHintFields(jobId, completion) : {},
22554
22415
  ...takeCreditNoticeFields(),
@@ -22915,55 +22776,6 @@ function isPlainObject2(value) {
22915
22776
  return typeof value === "object" && value !== null && !Array.isArray(value);
22916
22777
  }
22917
22778
 
22918
- // src/lib/warmup-provider.ts
22919
- var DEFAULT_BUDGET_MS = 3e4;
22920
- var DEFAULT_MAX_ATTEMPTS = 4;
22921
- var DEFAULT_BASE_BACKOFF_MS = 400;
22922
- var MAX_BACKOFF_MS = 4e3;
22923
- async function warmupProvider(transport, ref, options = {}) {
22924
- const budgetMs = options.budgetMs ?? DEFAULT_BUDGET_MS;
22925
- const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
22926
- const baseBackoffMs = options.baseBackoffMs ?? DEFAULT_BASE_BACKOFF_MS;
22927
- const sleep = options.sleep ?? defaultSleep2;
22928
- const { endpoint } = ref;
22929
- const deadline = Date.now() + budgetMs;
22930
- let lastErr;
22931
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
22932
- const remaining = deadline - Date.now();
22933
- if (remaining <= 0) break;
22934
- const attemptsLeft = maxAttempts - attempt + 1;
22935
- const timeoutMs = Math.max(1, Math.floor(remaining / attemptsLeft));
22936
- try {
22937
- return await transport.describe(ref, { timeoutMs });
22938
- } catch (err) {
22939
- lastErr = err;
22940
- if (err instanceof DvmError && err.code === "unsupported_version") throw err;
22941
- const budgetLeft = deadline - Date.now();
22942
- if (attempt >= maxAttempts || budgetLeft <= 0) break;
22943
- const futureAttempts = maxAttempts - attempt;
22944
- const backoff = Math.min(
22945
- baseBackoffMs * 2 ** (attempt - 1),
22946
- MAX_BACKOFF_MS,
22947
- Math.max(0, budgetLeft - futureAttempts)
22948
- );
22949
- if (backoff > 0) await sleep(backoff);
22950
- }
22951
- }
22952
- if (isAbortError(lastErr) || lastErr instanceof DvmError && lastErr.code === "timeout") {
22953
- throw new DvmError(
22954
- "endpoint_unreachable",
22955
- `Provider at ${endpoint} did not respond within ${budgetMs / 1e3}s.`,
22956
- "The endpoint may be down or the address may be incorrect. Check with 'dvm info <endpoint>'."
22957
- );
22958
- }
22959
- throw new DvmError(
22960
- "endpoint_unreachable",
22961
- `Could not reach provider at ${endpoint}: ${lastErr instanceof Error ? lastErr.message : String(lastErr)}`,
22962
- "Check the endpoint URL and your network connection."
22963
- );
22964
- }
22965
- var defaultSleep2 = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
22966
-
22967
22779
  // src/commands/quote.ts
22968
22780
  async function quote(opts) {
22969
22781
  return withOutputWarnings(() => quoteWithWarnings(opts));
@@ -23009,22 +22821,28 @@ async function quoteWithWarnings(opts) {
23009
22821
  data = paramsToData(opts.param);
23010
22822
  }
23011
22823
  const transport = createDvmTransport();
23012
- const ref = { endpoint };
23013
22824
  const WARMUP_TIMEOUT_MS = 3e4;
23014
22825
  const warmupStart = Date.now();
23015
22826
  let providerInfo;
23016
22827
  try {
23017
- 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;
23018
22835
  } catch (err) {
23019
22836
  transport.close();
23020
22837
  throw err;
23021
22838
  }
22839
+ const ref = { endpoint };
23022
22840
  const warmupMs = Date.now() - warmupStart;
23023
22841
  if (opts.human && warmupMs > 1e3) {
23024
22842
  info(`Provider woke up in ${(warmupMs / 1e3).toFixed(1)}s.`);
23025
22843
  }
23026
22844
  const dvmId = canonicalDvmId;
23027
- const capability = resolveCapability(providerInfo, requestedCapability, dvmId);
22845
+ const capability = resolveCapability(providerInfo, requestedCapability, dvmId, endpoint);
23028
22846
  const identifier = dvmId ? formatIdentifier(dvmId, capability) : endpoint;
23029
22847
  if (opts.human) info(`Quoting ${identifier}...`);
23030
22848
  const inputSchema = providerInfo.capabilities?.[capability]?.input_schema ?? providerInfo.inputSchema;
@@ -23096,6 +22914,8 @@ async function quoteWithWarnings(opts) {
23096
22914
  const routeBtcRate = q.priceMsats > 0 && q.upfront.amount > 0 ? q.upfront.amount * 1e11 / q.priceMsats : void 0;
23097
22915
  const probePlan = planProbeDraw({
23098
22916
  stored,
22917
+ capability,
22918
+ quote: q,
23099
22919
  drawCeilingMsats: 0,
23100
22920
  drawCeilingSource: "budget",
23101
22921
  btcRate: routeBtcRate ?? 0,
@@ -23445,6 +23265,7 @@ function listEntryJson(entry, status2, rate) {
23445
23265
  // see `receiptIssuedAtIso`. The raw number stays intact under `receipt`.
23446
23266
  issued_at: receiptIssuedAtIso(entry.receipt),
23447
23267
  paid_msats: entry.receipt.paid.msats,
23268
+ settlement: receiptSettlement(entry.receipt, status2),
23448
23269
  receipt_verified: status2,
23449
23270
  display: receiptDisplay(entry.receipt, status2, rate)
23450
23271
  };
@@ -23456,6 +23277,7 @@ function storedReceiptJson(entry, result, rate) {
23456
23277
  receipt: entry.receipt,
23457
23278
  receipt_verified: result.status,
23458
23279
  receipt_checks: result.checks,
23280
+ settlement: receiptSettlement(entry.receipt, result.status),
23459
23281
  ...result.reason ? { receipt_error: result.reason, receipt_error_detail: receiptFailureDetail(result.reason) } : {},
23460
23282
  // The DVM's terminal reason is provider free text — an agent relaying it
23461
23283
  // must be able to see that it is untrusted (docs/cli.md).
@@ -23550,7 +23372,7 @@ async function settleCreditAfterJob(args) {
23550
23372
  }
23551
23373
  }
23552
23374
  if (args.allowTopup !== false) {
23553
- const refill = args.refillPocket ?? (await import("./pocket-refill-PMY77T54.js")).refillPocketIfLow;
23375
+ const refill = args.refillPocket ?? (await import("./pocket-refill-Z4YT7CHW.js")).refillPocketIfLow;
23554
23376
  await refill({ human: args.human }).catch(() => void 0);
23555
23377
  }
23556
23378
  }
@@ -24045,148 +23867,6 @@ function dollarLimitMicro(declaredLimit) {
24045
23867
  return whole * 1000000n + fraction;
24046
23868
  }
24047
23869
 
24048
- // src/lib/request-intent-store.ts
24049
- var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
24050
- import {
24051
- closeSync as closeSync3,
24052
- existsSync as existsSync7,
24053
- fsyncSync,
24054
- mkdirSync as mkdirSync2,
24055
- openSync as openSync3,
24056
- readFileSync as readFileSync7,
24057
- renameSync as renameSync2,
24058
- writeFileSync as writeFileSync4
24059
- } from "fs";
24060
- import { join as join8 } from "path";
24061
- function saveRequestIntent(intent) {
24062
- assertRequestId(intent.requestId);
24063
- assertNoPaymentOrAuthSecrets(intent.body);
24064
- ensureConfigSubdir(REQUEST_INTENTS_DIR);
24065
- const dir = intentDirectory(intent.requestId);
24066
- try {
24067
- mkdirSync2(dir, { mode: 448 });
24068
- } catch (error) {
24069
- if (error.code === "EEXIST") return false;
24070
- throw error;
24071
- }
24072
- fsyncDirectory(REQUEST_INTENTS_DIR);
24073
- const temp = join8(dir, `intent.${String(process.pid)}.tmp`);
24074
- const target = join8(dir, "intent.json");
24075
- const fd = openSync3(temp, "wx", 384);
24076
- try {
24077
- writeFileSync4(fd, JSON.stringify(intent, null, 2) + "\n");
24078
- fsyncSync(fd);
24079
- } finally {
24080
- closeSync3(fd);
24081
- }
24082
- renameSync2(temp, target);
24083
- fsyncDirectory(dir);
24084
- return true;
24085
- }
24086
- function loadRequestIntent(requestId) {
24087
- assertRequestId(requestId);
24088
- const dir = intentDirectory(requestId);
24089
- if (!existsSync7(dir)) return null;
24090
- const path = join8(dir, "intent.json");
24091
- try {
24092
- const parsed = JSON.parse(readFileSync7(path, "utf8"));
24093
- if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
24094
- throw new Error("invalid shape");
24095
- return parsed;
24096
- } catch (error) {
24097
- throw new DvmError(
24098
- "request_intent_unreadable",
24099
- `The saved request intent for ${requestId} is incomplete or unreadable.`,
24100
- "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.",
24101
- { request_id: requestId, cause: error instanceof Error ? error.message : String(error) }
24102
- );
24103
- }
24104
- }
24105
- function recordRequestRailPayment(requestId, payment) {
24106
- assertRequestId(requestId);
24107
- if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
24108
- const dir = intentDirectory(requestId);
24109
- const target = join8(dir, "intent.json");
24110
- const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
24111
- try {
24112
- const intent = loadRequestIntent(requestId);
24113
- if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
24114
- if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
24115
- throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
24116
- const temp = join8(dir, `rail.${String(process.pid)}.tmp`);
24117
- const fd = openSync3(temp, "w", 384);
24118
- try {
24119
- writeFileSync4(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
24120
- fsyncSync(fd);
24121
- } finally {
24122
- closeSync3(fd);
24123
- }
24124
- renameSync2(temp, target);
24125
- fsyncDirectory(dir);
24126
- } finally {
24127
- release();
24128
- }
24129
- }
24130
- function assertNoPaymentOrAuthSecrets(body) {
24131
- if (!containsForbiddenSecret(body)) return;
24132
- throw new DvmError(
24133
- "request_intent_contains_secret",
24134
- "Request recovery cannot persist a payment credential, bearer token, or request auth signature.",
24135
- "No payment was attempted. Remove the secret-bearing input or omit --request-id."
24136
- );
24137
- }
24138
- function containsForbiddenSecret(value) {
24139
- if (typeof value === "string") return /^Bearer\s/i.test(value);
24140
- if (!value || typeof value !== "object") return false;
24141
- if (Array.isArray(value)) return value.some(containsForbiddenSecret);
24142
- const record = value;
24143
- if (["pubkey", "timestamp", "nonce", "signature"].every((key) => Object.hasOwn(record, key))) {
24144
- return true;
24145
- }
24146
- const forbidden = /* @__PURE__ */ new Set([
24147
- "authorization",
24148
- "bearer_token",
24149
- "access_token",
24150
- "cashu_token",
24151
- "x402_payment",
24152
- "tempo_credential"
24153
- ]);
24154
- return Object.entries(record).some(
24155
- ([key, child]) => forbidden.has(key.toLowerCase()) || containsForbiddenSecret(child)
24156
- );
24157
- }
24158
- function assertRequestId(requestId) {
24159
- if (isPublicRequestId(requestId)) return;
24160
- throw new DvmError(
24161
- "invalid_request_id",
24162
- "Invalid request id.",
24163
- "Use 1\u2013128 characters: letters, digits, dot, underscore, colon, or hyphen."
24164
- );
24165
- }
24166
- function intentDirectory(requestId) {
24167
- return join8(REQUEST_INTENTS_DIR, requestId);
24168
- }
24169
- function fsyncDirectory(path) {
24170
- if (process.platform === "win32") return;
24171
- let fd;
24172
- try {
24173
- fd = openSync3(path, "r");
24174
- fsyncSync(fd);
24175
- } finally {
24176
- if (fd !== void 0) closeSync3(fd);
24177
- }
24178
- }
24179
- function isRequestIntent(value) {
24180
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
24181
- const candidate = value;
24182
- 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;
24183
- }
24184
- function isSignedRequestAudience(value) {
24185
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
24186
- const candidate = value;
24187
- return typeof candidate.dvm_id === "string" && typeof candidate.builder_pubkey === "string";
24188
- }
24189
-
24190
23870
  // src/lib/wallet-agent/balance.ts
24191
23871
  function groupProofsByMint(proofs) {
24192
23872
  const out = /* @__PURE__ */ new Map();
@@ -24566,12 +24246,16 @@ async function requestWithWarnings(opts) {
24566
24246
  }
24567
24247
  }
24568
24248
  const transport = createDvmTransport();
24569
- const ref = { endpoint };
24570
24249
  const WARMUP_TIMEOUT_MS = 3e4;
24571
24250
  const warmupStart = Date.now();
24572
- const providerInfo = await warmupProvider(transport, ref, {
24573
- budgetMs: WARMUP_TIMEOUT_MS
24251
+ const resolvedEndpoint = await resolveProviderEndpoint2(transport, endpoint, {
24252
+ budgetMs: WARMUP_TIMEOUT_MS,
24253
+ capabilityPath: !opts.dvm
24574
24254
  });
24255
+ endpoint = resolvedEndpoint.endpoint;
24256
+ requestedCapability ??= resolvedEndpoint.capability;
24257
+ const providerInfo = resolvedEndpoint.info;
24258
+ const ref = { endpoint };
24575
24259
  if (opts.requestId && providerInfo.requestRecovery !== true) {
24576
24260
  transport.close();
24577
24261
  throw new DvmError(
@@ -24585,7 +24269,7 @@ async function requestWithWarnings(opts) {
24585
24269
  info(`Provider woke up in ${(warmupMs / 1e3).toFixed(1)}s.`);
24586
24270
  }
24587
24271
  const dvmId = canonicalDvmId;
24588
- const capability = resolveCapability(providerInfo, requestedCapability, dvmId);
24272
+ const capability = resolveCapability(providerInfo, requestedCapability, dvmId, endpoint);
24589
24273
  const identity = { dvmId, capability };
24590
24274
  const identifier = dvmId ? formatIdentifier(dvmId, capability) : endpoint;
24591
24275
  if (opts.human) info(`Targeting ${identifier}.`);
@@ -24651,6 +24335,41 @@ async function requestWithWarnings(opts) {
24651
24335
  ...opts.requestId ? { request_id: opts.requestId } : {}
24652
24336
  };
24653
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;
24654
24373
  const storedRecord = opts.strictPerCall ? void 0 : loadCredit(endpoint, signer.pubkey, attestedIdentity);
24655
24374
  const storedCredit = storedRecord?.selectionCleared ? void 0 : storedRecord;
24656
24375
  if (opts.creditOnly && storedCredit?.creditId !== opts.creditOnly) {
@@ -24663,16 +24382,20 @@ async function requestWithWarnings(opts) {
24663
24382
  );
24664
24383
  }
24665
24384
  const implicitCredits = opts.strictPerCall || opts.creditOnly ? [] : loadImplicitCredits(endpoint, signer.pubkey, attestedIdentity);
24666
- if (storedCredit?.lastPriceMicro !== void 0 && btcRate === 0) {
24385
+ if (storedCredit && btcRate === 0 && (policy.maxTotalMsats > 0 || policy.autoPayBelowMsats > 0)) {
24667
24386
  btcRate = (await tryResolveBtcUsdRate())?.rate ?? 0;
24668
24387
  }
24669
24388
  const drawCeiling = effectiveAutoPayBelow !== void 0 && effectiveAutoPayBelow.trim() !== "" ? {
24670
24389
  msats: policy.autoPayBelowMsats,
24671
24390
  source: opts.autoPayBelow !== void 0 ? "auto_pay_below" : "config_threshold"
24672
24391
  } : { msats: policy.maxTotalMsats, source: "budget" };
24673
- const drawStored = opts.creditOnly && storedCredit ? (({ lastPriceMicro: _lastPriceMicro, ...credit }) => credit)(storedCredit) : storedCredit;
24674
24392
  probePlan = opts.strictPerCall ? { mode: "none" } : planProbeDraw({
24675
- stored: drawStored,
24393
+ stored: storedCredit,
24394
+ capability,
24395
+ ...opts.creditOnly ? {} : {
24396
+ quote: previewQuotes[0],
24397
+ receipts: storedCredit && drawCeiling.msats > 0 ? loadReceipts() : []
24398
+ },
24676
24399
  implicit: implicitCredits,
24677
24400
  drawCeilingMsats: drawCeiling.msats,
24678
24401
  drawCeilingSource: drawCeiling.source,
@@ -24704,7 +24427,7 @@ async function requestWithWarnings(opts) {
24704
24427
  draw_id: probePlan.drawId,
24705
24428
  ...drawRequestId ? { request_id: drawRequestId } : {}
24706
24429
  } : unsignedData;
24707
- data = signDvmRequestData(signer.privkey, probeData, authDomain);
24430
+ data = signDvmRequestData(signer.privkey, probeData, signing.domain);
24708
24431
  if (opts.human) info(`Signed as ${signer.pubkey}.`);
24709
24432
  if (opts.human && probePlan.mode === "draw") {
24710
24433
  info(
@@ -24722,37 +24445,7 @@ async function requestWithWarnings(opts) {
24722
24445
  );
24723
24446
  }
24724
24447
  }
24725
- const deadlineMs = Date.now() + timeout;
24726
- let envelope = buildJobEnvelope({
24727
- capability,
24728
- input: inputText,
24729
- params: opts.param,
24730
- data,
24731
- outputType: opts.outputType,
24732
- bidMsats: budgetMsats
24733
- });
24734
- let previewQuotes = [];
24735
- if (policy.maxTotalMsats > 0 || policy.autoPayBelowMsats > 0) {
24736
- try {
24737
- const quoteData = signing ? signDvmRequestData(signing.privkey, signing.unsignedData, signedRequestDomain({
24738
- provider: providerInfo,
24739
- endpoint,
24740
- method: "POST",
24741
- path: "v1/quote",
24742
- capability
24743
- })) : data;
24744
- previewQuotes = await transport.quote(ref, { ...envelope, data: quoteData }, {
24745
- // Leave the rest of the job deadline available for submission and work.
24746
- timeoutMs: Math.min(1e3, Math.max(1, Math.floor(timeout / 10))),
24747
- btcRate
24748
- });
24749
- } catch {
24750
- }
24751
- }
24752
- const pricing = providerInfo.capabilities?.[capability]?.pricing;
24753
- const warningLimits = { budget: effectiveBudget, autoPayBelow: effectiveAutoPayBelow };
24754
- const previewWarnings = autoPayWarnings(previewQuotes, warningLimits, pricing?.max ?? providerInfo.pricing?.max, btcRate);
24755
- addOutputWarnings(previewWarnings, opts.human);
24448
+ let envelope = { ...envelopeBase, data };
24756
24449
  let jobRequestId = opts.requestId ?? drawRequestId;
24757
24450
  if (jobRequestId) {
24758
24451
  persistRequestIntent({
@@ -24923,7 +24616,7 @@ async function requestWithWarnings(opts) {
24923
24616
  ...localCorrelationJobFields(localCorrelationId)
24924
24617
  });
24925
24618
  recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment);
24926
- if (noStream) {
24619
+ if (noStream && !isTerminalJobStatus(receipt.status)) {
24927
24620
  transport.close();
24928
24621
  if (opts.human) {
24929
24622
  info(`Job published: ${receipt.jobId}`);
@@ -24984,7 +24677,7 @@ async function requestWithWarnings(opts) {
24984
24677
  console.log(receipt.summary);
24985
24678
  const hint = nextStepHint(receipt.jobId, receipt.payloadIn, receipt.artifactCount, true);
24986
24679
  if (hint) info(`\u{1F4CE} ${hint}`);
24987
- renderReceiptHuman(captured);
24680
+ renderReceiptHuman(captured, receipt.jobId);
24988
24681
  echoTraceIdHuman();
24989
24682
  } else {
24990
24683
  providerJobJson({
@@ -24995,7 +24688,7 @@ async function requestWithWarnings(opts) {
24995
24688
  summary: receipt.summary,
24996
24689
  _provider_fields: ["summary"],
24997
24690
  ...buildCompletionHintFields(receipt.jobId, receipt),
24998
- ...receiptJsonFields(captured),
24691
+ ...receiptJsonFields(captured, receipt.jobId),
24999
24692
  ...takeCreditNoticeFields(),
25000
24693
  ...takeFeedbackNoticeFields(),
25001
24694
  next_action: null
@@ -25022,11 +24715,14 @@ async function requestWithWarnings(opts) {
25022
24715
  },
25023
24716
  deadlineMs
25024
24717
  );
25025
- const completion = persistStreamOutcome(streamOutcome(receipt.jobId, result));
25026
- const captured = result.nextAction === null ? captureTransportReceipt(
25027
- receipt.jobId,
25028
- await fetchMissingJobReceipt(receipt.jobId, transport, ref)
25029
- ) : 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;
25030
24726
  if (captured && !opts.strictPerCall) {
25031
24727
  await settleCreditAfterJob({
25032
24728
  capture: captured,
@@ -25039,7 +24735,7 @@ async function requestWithWarnings(opts) {
25039
24735
  human: opts.human
25040
24736
  });
25041
24737
  }
25042
- const streamedTerminal = result.nextAction === null ? streamTerminalStatus(result.messages) : void 0;
24738
+ const streamedTerminal = streamTerminalStatus(result.messages, outcome);
25043
24739
  if (streamedTerminal) {
25044
24740
  noteFeedbackAfterTerminal({
25045
24741
  jobId: receipt.jobId,
@@ -25051,6 +24747,8 @@ async function requestWithWarnings(opts) {
25051
24747
  }
25052
24748
  transport.close();
25053
24749
  if (opts.human) {
24750
+ if (streamedTerminal === "failed" || streamedTerminal === "cancelled")
24751
+ info(`Status: ${streamedTerminal}${completion?.message ? `: ${completion.message}` : ""}`);
25054
24752
  for (const msg of result.messages) {
25055
24753
  if (msg.type === "progress") continue;
25056
24754
  formatMessageHuman(msg, receipt.jobId, artifactSession);
@@ -25059,7 +24757,11 @@ async function requestWithWarnings(opts) {
25059
24757
  const hint = nextStepHint(receipt.jobId, completion.payloadIn, completion.artifactCount, true);
25060
24758
  if (hint) info(`\u{1F4CE} ${hint}`);
25061
24759
  }
25062
- 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
+ }
25063
24765
  finalizeProgressLine();
25064
24766
  echoTraceIdHuman();
25065
24767
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: isTerminalJobStatus(receipt.status) || !!streamTerminalStatus(result.messages) });
@@ -25070,14 +24772,20 @@ async function requestWithWarnings(opts) {
25070
24772
  ...transactionOutputFields(receipt),
25071
24773
  ...dvmIdentity(dvmId, capability),
25072
24774
  messages: result.messages.map(serializeMessageForOutput),
24775
+ ...streamedTerminal ? { status: streamedTerminal } : {},
24776
+ ...completion?.message !== void 0 ? { message: completion.message } : {},
25073
24777
  // A job that streams to `complete` — including one auto-paid through a
25074
24778
  // mid-job `requestPayment` — has no receipt carrying the outcome, so
25075
24779
  // these come off the streamed log instead. Without them this arc
25076
24780
  // returned `next_action: null` and nothing else: no summary, and no
25077
24781
  // signal that a payload was waiting in artifacts.
25078
- ...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
+ ],
25079
24787
  ...completion ? buildCompletionHintFields(receipt.jobId, completion) : {},
25080
- ...captured ? receiptJsonFields(captured) : {},
24788
+ ...captured ? receiptJsonFields(captured, receipt.jobId) : terminalSettlementFields(receipt.jobId),
25081
24789
  ...takeCreditNoticeFields(),
25082
24790
  ...takeFeedbackNoticeFields(),
25083
24791
  next_action: result.nextAction,
@@ -25087,10 +24795,18 @@ async function requestWithWarnings(opts) {
25087
24795
  }
25088
24796
  return;
25089
24797
  }
25090
- case "failed": {
25091
- markJobTerminal(receipt.jobId, "failed", completionSnapshot(receipt));
24798
+ case "failed":
24799
+ case "cancelled": {
24800
+ const terminalStatus = receipt.status;
25092
24801
  const failureMessages = await transport.getMessages(receipt.jobId, 0, ref, { jobToken: receipt.jobToken }).catch(() => []);
25093
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
+ });
25094
24810
  const captured = captureTransportReceipt(receipt.jobId, receipt);
25095
24811
  if (!opts.strictPerCall)
25096
24812
  await settleCreditAfterJob({
@@ -25107,7 +24823,7 @@ async function requestWithWarnings(opts) {
25107
24823
  jobId: receipt.jobId,
25108
24824
  dvmId,
25109
24825
  endpoint,
25110
- status: "failed",
24826
+ status: terminalStatus,
25111
24827
  human: opts.human
25112
24828
  });
25113
24829
  transport.close();
@@ -25115,12 +24831,13 @@ async function requestWithWarnings(opts) {
25115
24831
  for (const msg of failureMessages) {
25116
24832
  formatMessageHuman(msg, receipt.jobId, artifactSession);
25117
24833
  }
25118
- renderReceiptHuman(captured);
24834
+ renderReceiptHuman(captured, receipt.jobId);
25119
24835
  }
25120
- throw new DvmError("job_failed", "Job failed.", void 0, {
25121
- ...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),
25122
24839
  ...failureMessages.length > 0 ? { messages: failureMessages.map(serializeMessageForOutput) } : {}
25123
- });
24840
+ }, void 0, completion?.message !== void 0 ? { message: "provider" } : void 0);
25124
24841
  }
25125
24842
  }
25126
24843
  }
@@ -25968,7 +25685,7 @@ async function payWithTempo(args, credential) {
25968
25685
  console.log(receipt.summary);
25969
25686
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
25970
25687
  if (hint) info(`\u{1F4CE} ${hint}`);
25971
- renderReceiptHuman(captured);
25688
+ renderReceiptHuman(captured, effectiveJobId);
25972
25689
  } else {
25973
25690
  providerJobJson({
25974
25691
  jobId: effectiveJobId,
@@ -25978,7 +25695,7 @@ async function payWithTempo(args, credential) {
25978
25695
  summary: receipt.summary,
25979
25696
  _provider_fields: ["summary"],
25980
25697
  ...buildCompletionHintFields(effectiveJobId, receipt),
25981
- ...receiptJsonFields(captured),
25698
+ ...receiptJsonFields(captured, effectiveJobId),
25982
25699
  paidWith: "tempo",
25983
25700
  account: account.address,
25984
25701
  ...takeCreditNoticeFields(),
@@ -26116,6 +25833,9 @@ function normalizedLocalCorrelationId(opts) {
26116
25833
  return opts.localCorrelationId === void 0 ? void 0 : normalizeLocalCorrelationId(opts.localCorrelationId);
26117
25834
  }
26118
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
+ }
26119
25839
  const ambiguityId = isIdentityFailure(cause) && typeof cause.data?.ambiguity_id === "string" ? cause.data.ambiguity_id : void 0;
26120
25840
  return new DvmError(
26121
25841
  "request_outcome_unknown",
@@ -26629,7 +26349,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
26629
26349
  console.log(receipt.summary);
26630
26350
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
26631
26351
  if (hint) info(`\u{1F4CE} ${hint}`);
26632
- renderReceiptHuman(captured);
26352
+ renderReceiptHuman(captured, effectiveJobId);
26633
26353
  } else {
26634
26354
  providerJobJson({
26635
26355
  jobId: effectiveJobId,
@@ -26637,7 +26357,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
26637
26357
  summary: receipt.summary,
26638
26358
  _provider_fields: ["summary"],
26639
26359
  ...buildCompletionHintFields(effectiveJobId, receipt),
26640
- ...receiptJsonFields(captured),
26360
+ ...receiptJsonFields(captured, effectiveJobId),
26641
26361
  paidWith: "cashu_p2pk",
26642
26362
  mint: prepared.mint,
26643
26363
  amountSats: prepared.totalSats,
@@ -26830,7 +26550,7 @@ async function payWithX402(args, proof) {
26830
26550
  console.log(receipt.summary);
26831
26551
  const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
26832
26552
  if (hint) info(`\u{1F4CE} ${hint}`);
26833
- renderReceiptHuman(captured);
26553
+ renderReceiptHuman(captured, effectiveJobId);
26834
26554
  } else {
26835
26555
  providerJobJson({
26836
26556
  jobId: effectiveJobId,
@@ -26840,7 +26560,7 @@ async function payWithX402(args, proof) {
26840
26560
  summary: receipt.summary,
26841
26561
  _provider_fields: ["summary"],
26842
26562
  ...buildCompletionHintFields(effectiveJobId, receipt),
26843
- ...receiptJsonFields(captured),
26563
+ ...receiptJsonFields(captured, effectiveJobId),
26844
26564
  paidWith: "x402",
26845
26565
  account: wallet.address,
26846
26566
  ...takeCreditNoticeFields(),
@@ -26943,10 +26663,14 @@ async function streamAfterPayment(args) {
26943
26663
  },
26944
26664
  deadlineMs
26945
26665
  );
26946
- const completion = persistStreamOutcome(
26947
- streamOutcome(jobId, result, { costMsats: chosen.priceMsats, paymentMethod: paymentMethod2 })
26948
- );
26949
- 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;
26950
26674
  if (captured && !args.strictPerCall) {
26951
26675
  await settleCreditAfterJob({
26952
26676
  capture: captured,
@@ -26958,7 +26682,7 @@ async function streamAfterPayment(args) {
26958
26682
  human
26959
26683
  });
26960
26684
  }
26961
- const streamedTerminal = result.nextAction === null ? streamTerminalStatus(result.messages) : void 0;
26685
+ const streamedTerminal = streamTerminalStatus(result.messages, outcome);
26962
26686
  if (streamedTerminal) {
26963
26687
  noteFeedbackAfterTerminal({
26964
26688
  jobId,
@@ -27009,6 +26733,8 @@ async function streamAfterPayment(args) {
27009
26733
  throw new DvmError("timeout", paidTimeoutMessage);
27010
26734
  }
27011
26735
  if (human) {
26736
+ if (streamedTerminal === "failed" || streamedTerminal === "cancelled")
26737
+ info(`Status: ${streamedTerminal}${completion?.message ? `: ${completion.message}` : ""}`);
27012
26738
  for (const msg of result.messages) {
27013
26739
  if (msg.type === "progress") continue;
27014
26740
  formatMessageHuman(msg, jobId, artifactSession);
@@ -27017,7 +26743,11 @@ async function streamAfterPayment(args) {
27017
26743
  const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, true);
27018
26744
  if (hint) info(`\u{1F4CE} ${hint}`);
27019
26745
  }
27020
- if (captured) renderReceiptHuman(captured);
26746
+ if (captured) renderReceiptHuman(captured, jobId);
26747
+ else {
26748
+ const { settlement } = terminalSettlementFields(jobId);
26749
+ if (settlement) info(settlement.display);
26750
+ }
27021
26751
  finalizeProgressLine();
27022
26752
  printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: !!streamTerminalStatus(result.messages) });
27023
26753
  } else {
@@ -27025,12 +26755,18 @@ async function streamAfterPayment(args) {
27025
26755
  jobId,
27026
26756
  ...dvmFields,
27027
26757
  messages: result.messages.map(serializeMessageForOutput),
26758
+ ...streamedTerminal ? { status: streamedTerminal } : {},
26759
+ ...completion?.message !== void 0 ? { message: completion.message } : {},
27028
26760
  // Same as the unpaid arc above: the outcome is only knowable from the
27029
26761
  // streamed log here, so render it rather than leaving the agent to dig
27030
26762
  // the summary out of `messages` and guess about artifacts.
27031
- ...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
+ ],
27032
26768
  ...completion ? buildCompletionHintFields(jobId, completion) : {},
27033
- ...captured ? receiptJsonFields(captured) : {},
26769
+ ...captured ? receiptJsonFields(captured, jobId) : terminalSettlementFields(jobId),
27034
26770
  ...takeCreditNoticeFields(),
27035
26771
  ...takeFeedbackNoticeFields(),
27036
26772
  next_action: result.nextAction,
@@ -27076,7 +26812,7 @@ async function recoverViaStatusPoll(args) {
27076
26812
  });
27077
26813
  if (human) {
27078
26814
  info(status2.summary ?? "Job completed (recovered via status check).");
27079
- renderReceiptHuman(captured);
26815
+ renderReceiptHuman(captured, jobId);
27080
26816
  } else {
27081
26817
  providerJobJson({
27082
26818
  jobId,
@@ -27086,7 +26822,7 @@ async function recoverViaStatusPoll(args) {
27086
26822
  _provider_fields: ["summary"],
27087
26823
  recovered: true,
27088
26824
  ...paymentFields,
27089
- ...receiptJsonFields(captured),
26825
+ ...receiptJsonFields(captured, jobId),
27090
26826
  ...takeCreditNoticeFields(),
27091
26827
  ...takeFeedbackNoticeFields(),
27092
26828
  next_action: null
@@ -27108,7 +26844,7 @@ async function recoverViaStatusPoll(args) {
27108
26844
  const errorMsg = status2.message ?? `Job ${status2.status}.`;
27109
26845
  if (human) {
27110
26846
  info(errorMsg);
27111
- renderReceiptHuman(captured);
26847
+ renderReceiptHuman(captured, jobId);
27112
26848
  } else {
27113
26849
  providerJobJson({
27114
26850
  jobId,
@@ -27117,7 +26853,7 @@ async function recoverViaStatusPoll(args) {
27117
26853
  message: errorMsg,
27118
26854
  ...status2.message !== void 0 ? { _provider_fields: ["message"] } : {},
27119
26855
  ...paymentFields,
27120
- ...receiptJsonFields(captured),
26856
+ ...receiptJsonFields(captured, jobId),
27121
26857
  ...takeCreditNoticeFields(),
27122
26858
  ...takeFeedbackNoticeFields(),
27123
26859
  next_action: null
@@ -27606,6 +27342,7 @@ function outputResults2(resultJson, human, nextAction) {
27606
27342
 
27607
27343
  // src/lib/job-spend.ts
27608
27344
  function jobSpend(job, receipt) {
27345
+ const settlement = jobSettlement(job, receipt);
27609
27346
  const charges = [];
27610
27347
  const refunds = [];
27611
27348
  let request2;
@@ -27645,21 +27382,36 @@ function jobSpend(job, receipt) {
27645
27382
  const payments = job.paymentsHonoured ?? charges.length + (upfront > 0 ? 1 : 0);
27646
27383
  const currency = charges[0]?.fiat_amount?.currency;
27647
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;
27648
- 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;
27649
27394
  const budgetDisplay = job.policy ? formatPaymentAmount(
27650
27395
  job.policy.maxTotalMsats,
27651
27396
  fiat && total > 0 ? { currency: fiat.currency, amount: fiat.amount * job.policy.maxTotalMsats / total } : void 0,
27652
27397
  { anchor: false }
27653
27398
  ) : void 0;
27654
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));
27655
- const receiptMismatch = receipt && job.paymentMethod !== "credit" ? receipt.paid.msats !== total : void 0;
27656
- const receiptTotalDisplay = receipt ? formatPaymentAmount(receipt.paid.msats, void 0, { anchor: false }) : void 0;
27657
- 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";
27658
27409
  if (budgetDisplay) display += `, budget ${budgetDisplay}`;
27659
27410
  if (refunds.length > 0) display += `, ${refunds.length} refund${refunds.length === 1 ? "" : "s"}`;
27660
27411
  display += ".";
27661
27412
  if (logMismatch) display += " Local payment log disagrees with the job record.";
27662
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.";
27663
27415
  const [receiptLabel, localLabel] = receiptTotalDisplay === totalDisplay ? [`${receipt.paid.msats} msats`, `${total} msats`] : [receiptTotalDisplay, totalDisplay];
27664
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.`;
27665
27417
  return {
@@ -27667,6 +27419,7 @@ function jobSpend(job, receipt) {
27667
27419
  refunds,
27668
27420
  total_msats: total,
27669
27421
  total_display: totalDisplay,
27422
+ settlement,
27670
27423
  ...upfront > 0 && (job.paymentMethod !== "credit" || knownCredit) ? {
27671
27424
  upfront_display: formatPaymentAmount(
27672
27425
  upfront,
@@ -27689,7 +27442,7 @@ function renderSpendHuman(spend, print) {
27689
27442
  print(spend.display);
27690
27443
  if (spend.upfront_display) print(` Upfront: ${spend.upfront_display}`);
27691
27444
  const rails = { cashu_p2pk: "Cashu", tempo: "Tempo", x402: "x402", credit: "prepaid credit", unknown: "payment method not recorded" };
27692
- 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" };
27693
27446
  for (const charge of spend.charges) {
27694
27447
  print(` [${charge.seq}] ${charge.display} (${rails[charge.rail]}, ${approvals[charge.approval]})${charge.reason.text ? `: ${charge.reason.text}` : ""}`);
27695
27448
  }
@@ -27706,9 +27459,17 @@ async function statusWithAccess(jobId, opts, access) {
27706
27459
  const { stored, ref, jobToken } = access;
27707
27460
  if (stored && !access.overridden && isTerminalJobStatus(stored.status) && stored.completion && !opts.messages) {
27708
27461
  let receipt2 = replayStoredReceipt(stored);
27462
+ let terminalStatus = stored.status;
27463
+ let completion2 = stored.completion;
27709
27464
  const transport2 = createDvmTransport();
27710
27465
  if (stored.receiptsSupported && receipt2.status === "absent") {
27711
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
+ }
27712
27473
  if (fetched.receipt || fetched.receiptParseError) {
27713
27474
  if (fetched.receipt && !stored.builderAnchor) {
27714
27475
  await backfillTrustAnchor(jobId, transport2, ref);
@@ -27718,7 +27479,7 @@ async function statusWithAccess(jobId, opts, access) {
27718
27479
  }
27719
27480
  await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
27720
27481
  transport2.close();
27721
- renderStatus(jobId, stored, stored.status, stored.completion, "local", null, opts, {
27482
+ renderStatus(jobId, stored, terminalStatus, completion2, "local", null, opts, {
27722
27483
  receipt: receipt2
27723
27484
  });
27724
27485
  return;
@@ -27742,6 +27503,13 @@ async function statusWithAccess(jobId, opts, access) {
27742
27503
  context: access.endpointOverridden ? void 0 : stored ?? void 0
27743
27504
  });
27744
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
+ }
27745
27513
  let receipt;
27746
27514
  if (isTerminalJobStatus(result.status)) {
27747
27515
  if (stored && !access.endpointOverridden) {
@@ -27808,7 +27576,15 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
27808
27576
  const msgs = fetched?.msgs ?? [];
27809
27577
  const receipt = fetched?.receipt;
27810
27578
  const content = jobContentFields(jobId, fetched?.content, opts.human);
27811
- 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
+ });
27812
27588
  if (opts.human) {
27813
27589
  if (jobStatus === "completed" && completion.summary) {
27814
27590
  info(`Summary:`);
@@ -27829,6 +27605,7 @@ ${msgs.length} new message(s):`);
27829
27605
  const traceId = getOutputTraceId();
27830
27606
  if (traceId) info(`Trace: ${traceId}`);
27831
27607
  if (spend) renderSpendHuman(spend, info);
27608
+ else if (settlement.settlement) info(settlement.settlement.display);
27832
27609
  if (receipt) renderReceiptHuman(receipt);
27833
27610
  printNextActionHuman(nextAction);
27834
27611
  return;
@@ -27850,6 +27627,7 @@ ${msgs.length} new message(s):`);
27850
27627
  // terminal responses only. On a still-running job "absent" would
27851
27628
  // read as "this DVM doesn't issue receipts" rather than "not yet".
27852
27629
  ...receipt ? receiptJsonFields(receipt) : {},
27630
+ ...settlement,
27853
27631
  // `dvm status` is a job-terminal emission for `--no-stream`
27854
27632
  // jobs, so it drains the deferred-notice sinks like the request terminals
27855
27633
  // do. Both spread blind and are absent when nothing was stashed.
@@ -27876,7 +27654,7 @@ async function resolveNextAction(jobId, status2, fetched, transport, ref, opts)
27876
27654
  }
27877
27655
 
27878
27656
  // src/commands/upload.ts
27879
- import { statSync as statSync5 } from "fs";
27657
+ import { statSync as statSync4 } from "fs";
27880
27658
 
27881
27659
  // src/lib/upload-stream.ts
27882
27660
  import { createHash as createHash6 } from "crypto";
@@ -28099,7 +27877,7 @@ async function upload(dvmRef, opts) {
28099
27877
  const target = resolveUploadTarget(qualified?.slug ?? dvmId, kind);
28100
27878
  let sizeOnDisk;
28101
27879
  try {
28102
- const st = statSync5(opts.file);
27880
+ const st = statSync4(opts.file);
28103
27881
  if (!st.isFile()) {
28104
27882
  throw new DvmError(
28105
27883
  "invalid_argument",
@@ -28361,7 +28139,7 @@ function getRailOnramp(rail) {
28361
28139
  }
28362
28140
 
28363
28141
  // src/lib/secret-input.ts
28364
- import { fstatSync, readFileSync as readFileSync8, realpathSync } from "fs";
28142
+ import { fstatSync, readFileSync as readFileSync7, realpathSync } from "fs";
28365
28143
  import { homedir as homedir2 } from "os";
28366
28144
  import { resolve as resolve2, sep } from "path";
28367
28145
  var BLOCKED_SECRET_PATHS = [
@@ -28441,7 +28219,7 @@ function readSecretFile(path, config) {
28441
28219
  throw err;
28442
28220
  }
28443
28221
  assertSafeFilePath(real);
28444
- return readFileSync8(real, "utf-8").trim();
28222
+ return readFileSync7(real, "utf-8").trim();
28445
28223
  }
28446
28224
  function readSecretStdin(config) {
28447
28225
  return new Promise((resolveStdin, reject) => {
@@ -30137,7 +29915,7 @@ function mnemonicValidationError(result) {
30137
29915
  var import_qrcode = __toESM(require_lib(), 1);
30138
29916
  import { randomBytes as randomBytes3 } from "crypto";
30139
29917
  import { tmpdir as tmpdir2 } from "os";
30140
- import { join as join9 } from "path";
29918
+ import { join as join8 } from "path";
30141
29919
  async function renderQrTerminal(payload) {
30142
29920
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
30143
29921
  }
@@ -30150,7 +29928,7 @@ async function renderQrPng(payload, outPath) {
30150
29928
  });
30151
29929
  }
30152
29930
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
30153
- return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
29931
+ return join8(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
30154
29932
  }
30155
29933
 
30156
29934
  // src/lib/funding-handoff.ts
@@ -34529,14 +34307,14 @@ function hexToBytes2(hex) {
34529
34307
  var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
34530
34308
  import {
34531
34309
  chmodSync as chmodSync2,
34532
- existsSync as existsSync8,
34310
+ existsSync as existsSync7,
34533
34311
  readdirSync as readdirSync5,
34534
- readFileSync as readFileSync9,
34312
+ readFileSync as readFileSync8,
34535
34313
  renameSync as renameSync3,
34536
34314
  unlinkSync as unlinkSync3,
34537
34315
  writeFileSync as writeFileSync5
34538
34316
  } from "fs";
34539
- import { join as join10 } from "path";
34317
+ import { join as join9 } from "path";
34540
34318
  var pairingIdPattern = /^[0-9a-f]{64}$/;
34541
34319
  var stateSchema = external_exports.object({
34542
34320
  version: external_exports.literal(1),
@@ -34563,7 +34341,7 @@ function createWalletPairingState(state) {
34563
34341
  }
34564
34342
  function loadWalletPairingState(pairingId) {
34565
34343
  const path = pairingPath(pairingId);
34566
- if (!existsSync8(path)) {
34344
+ if (!existsSync7(path)) {
34567
34345
  throw new DvmError(
34568
34346
  "wallet_pairing_not_found",
34569
34347
  "No local state exists for that wallet pairing.",
@@ -34571,7 +34349,7 @@ function loadWalletPairingState(pairingId) {
34571
34349
  );
34572
34350
  }
34573
34351
  try {
34574
- return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34352
+ return stateSchema.parse(JSON.parse(readFileSync8(path, "utf8")));
34575
34353
  } catch {
34576
34354
  throw new DvmError(
34577
34355
  "wallet_pairing_state_invalid",
@@ -34606,13 +34384,13 @@ function deleteWalletPairingState(pairingId) {
34606
34384
  }
34607
34385
  }
34608
34386
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
34609
- if (!existsSync8(PAIRINGS_DIR)) return 0;
34387
+ if (!existsSync7(PAIRINGS_DIR)) return 0;
34610
34388
  let removed = 0;
34611
34389
  for (const name of readdirSync5(PAIRINGS_DIR)) {
34612
34390
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
34613
- const path = join10(PAIRINGS_DIR, name);
34391
+ const path = join9(PAIRINGS_DIR, name);
34614
34392
  try {
34615
- const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34393
+ const state = stateSchema.parse(JSON.parse(readFileSync8(path, "utf8")));
34616
34394
  if (state.manifest.expires_at <= nowSeconds) {
34617
34395
  unlinkSync3(path);
34618
34396
  removed += 1;
@@ -34624,7 +34402,7 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
34624
34402
  }
34625
34403
  async function withWalletPairingLock(pairingId, fn) {
34626
34404
  const path = pairingPath(pairingId);
34627
- if (!existsSync8(path)) return fn();
34405
+ if (!existsSync7(path)) return fn();
34628
34406
  let release;
34629
34407
  try {
34630
34408
  release = await import_proper_lockfile3.default.lock(path, {
@@ -34654,7 +34432,7 @@ function pairingPath(pairingId) {
34654
34432
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
34655
34433
  );
34656
34434
  }
34657
- return join10(PAIRINGS_DIR, `${pairingId}.json`);
34435
+ return join9(PAIRINGS_DIR, `${pairingId}.json`);
34658
34436
  }
34659
34437
  function ensurePairingsDirectory() {
34660
34438
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -36283,7 +36061,7 @@ function buildProgram() {
36283
36061
  program2.command("quote").description("Get a price quote from a DVM provider").option(
36284
36062
  "-d, --dvm <identifier>",
36285
36063
  "Qualified DVM or DVM/capability identifier (e.g. `dvmkit--narrate`, `dvmkit--cast/add-episode`). Alternative to --endpoint."
36286
- ).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(
36287
36065
  "--data <json>",
36288
36066
  "Structured data for inputSchema DVMs (JSON object, or @path/to/file.json, or @- for stdin)"
36289
36067
  ).option(
@@ -36303,7 +36081,7 @@ function buildProgram() {
36303
36081
  program2.command("request").description("Submit a job request to a DVM provider").option(
36304
36082
  "-d, --dvm <identifier>",
36305
36083
  "Qualified DVM or DVM/capability identifier (e.g. `dvmkit--narrate`, `dvmkit--cast/add-episode`). Alternative to --endpoint."
36306
- ).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(
36307
36085
  "--param <key=value>",
36308
36086
  "Job parameter (repeatable). Agent-friendly form for DVMs with an inputSchema (bool/number/string + repeats \u2192 array). Use --data for nested values.",
36309
36087
  collectOption,