@dvmkit/dvm-cli 0.10.0 → 0.11.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/{chunk-BHR7QHJG.js → chunk-3R2GM6AD.js} +2 -2
- package/dist/{chunk-TGRY23IF.js → chunk-6EYBCGGD.js} +2 -2
- package/dist/{chunk-NXXU3BSJ.js → chunk-7N3HQJKE.js} +4 -4
- package/dist/{chunk-C3HMFGYP.js → chunk-BPWZNIMS.js} +2 -2
- package/dist/{chunk-MTGQK7KA.js → chunk-GEZVSJDM.js} +3 -3
- package/dist/{chunk-GD25CUI4.js → chunk-GHNF2I5C.js} +4 -4
- package/dist/{chunk-3YU6KRCX.js → chunk-HWWW7JEM.js} +3 -3
- package/dist/{chunk-Q45TAYK2.js → chunk-JJBRTWWS.js} +160 -7
- package/dist/{chunk-HUBCGZJL.js → chunk-K562SFVD.js} +2 -2
- package/dist/{chunk-CWWZM4M6.js → chunk-MBSCP52L.js} +564 -204
- package/dist/{chunk-GMOKL4PQ.js → chunk-MMXHV3KC.js} +2 -2
- package/dist/{chunk-IEWV3CM2.js → chunk-UVFFMKU4.js} +3 -1
- package/dist/{client-MFSKFSV4.js → client-DS4QJ346.js} +6 -6
- package/dist/dvm.js +1196 -300
- package/dist/{internal-5EGKBZAE.js → internal-ZZHCUKOM.js} +5 -5
- package/dist/{lifecycle-7AVB36WP.js → lifecycle-XGNIMPTB.js} +6 -6
- package/dist/{payout-reporter-NXWQVKXW-KHVN6C4Z.js → payout-reporter-DDQ7FGRC-OKICJCC2.js} +2 -2
- package/dist/{pocket-refill-SKECWGA3.js → pocket-refill-3ZV36DOA.js} +10 -10
- package/dist/{revenue-reporter-HD4GMXGD-LAZU45ZA.js → revenue-reporter-RIEHBKRA-75BDPVVX.js} +2 -2
- package/dist/{tempo-lifecycle-SVPMTND2.js → tempo-lifecycle-LGGBDCKK.js} +8 -8
- package/dist/{tempo-wallet-5PKLSWFX.js → tempo-wallet-PLFC443A.js} +7 -7
- package/dist/{wallet-7BBWAZYJ.js → wallet-UJ7EJNQA.js} +7 -7
- package/dist/{x402-RUJ4LUKF-ZB7JM22B.js → x402-AY6P5KV4-SIZF7YNW.js} +2 -2
- package/package.json +2 -2
- package/skills/dvm/SKILL.md +2 -2
- package/skills/dvm/calling.md +23 -1
package/dist/dvm.js
CHANGED
|
@@ -5,10 +5,10 @@ import {
|
|
|
5
5
|
assertTempoWalletIdle,
|
|
6
6
|
findSigningIdentityByPubkey,
|
|
7
7
|
resolveSigningIdentity
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-HWWW7JEM.js";
|
|
9
9
|
import {
|
|
10
10
|
assertX402WalletIdle
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-6EYBCGGD.js";
|
|
12
12
|
import {
|
|
13
13
|
DEFAULT_CREDIT_POSTURE,
|
|
14
14
|
DEFAULT_RESERVE_LOCKTIME_SECONDS,
|
|
@@ -26,6 +26,7 @@ import {
|
|
|
26
26
|
captureDrawFundingReceipts,
|
|
27
27
|
captureFundingReceipt,
|
|
28
28
|
captureTransportReceipt,
|
|
29
|
+
clearPaymentRequestInFlight,
|
|
29
30
|
commitAgentSpend,
|
|
30
31
|
correctPendingFundAmount,
|
|
31
32
|
deriveAlias,
|
|
@@ -46,6 +47,8 @@ import {
|
|
|
46
47
|
fundAgentWallet,
|
|
47
48
|
fundCredit,
|
|
48
49
|
fundTimeoutMs,
|
|
50
|
+
hasUnknownUpfrontCredit,
|
|
51
|
+
hasUnknownUpfrontRail,
|
|
49
52
|
identityDataFields,
|
|
50
53
|
identityError,
|
|
51
54
|
inFlightTimeoutSeconds,
|
|
@@ -63,6 +66,8 @@ import {
|
|
|
63
66
|
loadLedger,
|
|
64
67
|
loadSubmissionEvidence,
|
|
65
68
|
markJobTerminal,
|
|
69
|
+
markPaymentRequestInFlight,
|
|
70
|
+
markPaymentRequestPaid,
|
|
66
71
|
markPendingSubmissionUnresolved,
|
|
67
72
|
markProofsInFlight,
|
|
68
73
|
meltInFlightTimeoutSeconds,
|
|
@@ -70,6 +75,8 @@ import {
|
|
|
70
75
|
needsTopup,
|
|
71
76
|
parseLocktime,
|
|
72
77
|
parseStatedBudget,
|
|
78
|
+
parseUpfrontPayment,
|
|
79
|
+
parseUpfrontRailPayment,
|
|
73
80
|
payViaFloat,
|
|
74
81
|
pickCreditFundRail,
|
|
75
82
|
planCreditForQuote,
|
|
@@ -91,6 +98,8 @@ import {
|
|
|
91
98
|
recordSpend,
|
|
92
99
|
recordSpendOnce,
|
|
93
100
|
recordSubmissionEvidence,
|
|
101
|
+
recordUpfrontCreditPayment,
|
|
102
|
+
recordUpfrontRailPayment,
|
|
94
103
|
removeFavorite,
|
|
95
104
|
renderReceiptHuman,
|
|
96
105
|
replayStoredReceipt,
|
|
@@ -105,6 +114,7 @@ import {
|
|
|
105
114
|
saveFavorite,
|
|
106
115
|
saveJob,
|
|
107
116
|
saveLedger,
|
|
117
|
+
saveSubmittedJob,
|
|
108
118
|
settleJobIdentity,
|
|
109
119
|
statusSnapshot,
|
|
110
120
|
sweepPendingMints,
|
|
@@ -120,13 +130,13 @@ import {
|
|
|
120
130
|
withIdentityRecovery,
|
|
121
131
|
withJobTokenRedaction,
|
|
122
132
|
withRequestResultRecovery
|
|
123
|
-
} from "./chunk-
|
|
133
|
+
} from "./chunk-JJBRTWWS.js";
|
|
124
134
|
import {
|
|
125
135
|
connectedTempoAccount,
|
|
126
136
|
generateTempoKey,
|
|
127
137
|
tempoBalanceCheckHint,
|
|
128
138
|
tempoWrongAssetHint
|
|
129
|
-
} from "./chunk-
|
|
139
|
+
} from "./chunk-7N3HQJKE.js";
|
|
130
140
|
import {
|
|
131
141
|
assertValidBudget,
|
|
132
142
|
costAnchor,
|
|
@@ -144,7 +154,7 @@ import {
|
|
|
144
154
|
staleRateNotice,
|
|
145
155
|
tryResolveBtcUsdRate,
|
|
146
156
|
tryX402Payment
|
|
147
|
-
} from "./chunk-
|
|
157
|
+
} from "./chunk-BPWZNIMS.js";
|
|
148
158
|
import {
|
|
149
159
|
assertSupportedX402Network,
|
|
150
160
|
connectedX402Payer,
|
|
@@ -153,7 +163,7 @@ import {
|
|
|
153
163
|
repinX402WalletNetwork,
|
|
154
164
|
saveX402Wallet,
|
|
155
165
|
x402NetworkLabel
|
|
156
|
-
} from "./chunk-
|
|
166
|
+
} from "./chunk-GEZVSJDM.js";
|
|
157
167
|
import {
|
|
158
168
|
CREDIT_POSTURES,
|
|
159
169
|
FEEDBACK_POSTURES,
|
|
@@ -170,7 +180,7 @@ import {
|
|
|
170
180
|
retireConfigBackup,
|
|
171
181
|
rollbackConfig,
|
|
172
182
|
updateConfig
|
|
173
|
-
} from "./chunk-
|
|
183
|
+
} from "./chunk-MMXHV3KC.js";
|
|
174
184
|
import {
|
|
175
185
|
A,
|
|
176
186
|
AGENT_MNEMONIC_FILE,
|
|
@@ -414,7 +424,7 @@ import {
|
|
|
414
424
|
x402PendingUnsettled,
|
|
415
425
|
x402RequiredFromError,
|
|
416
426
|
x402ReservationRelease
|
|
417
|
-
} from "./chunk-
|
|
427
|
+
} from "./chunk-MBSCP52L.js";
|
|
418
428
|
import "./chunk-JBU7RKQ3.js";
|
|
419
429
|
import "./chunk-KDNFUDOG.js";
|
|
420
430
|
import "./chunk-IUTVV6N5.js";
|
|
@@ -455,11 +465,11 @@ import {
|
|
|
455
465
|
usdToMsats,
|
|
456
466
|
usdcToMsats,
|
|
457
467
|
x402NetworkByCaip2
|
|
458
|
-
} from "./chunk-
|
|
459
|
-
import "./chunk-
|
|
460
|
-
import "./chunk-
|
|
468
|
+
} from "./chunk-GHNF2I5C.js";
|
|
469
|
+
import "./chunk-K562SFVD.js";
|
|
470
|
+
import "./chunk-3R2GM6AD.js";
|
|
461
471
|
import "./chunk-R2DSAZBO.js";
|
|
462
|
-
import "./chunk-
|
|
472
|
+
import "./chunk-UVFFMKU4.js";
|
|
463
473
|
import {
|
|
464
474
|
privateKeyToAccount
|
|
465
475
|
} from "./chunk-EVQERRCP.js";
|
|
@@ -5224,11 +5234,11 @@ var require_dijkstra = __commonJS({
|
|
|
5224
5234
|
var predecessors = {};
|
|
5225
5235
|
var costs = {};
|
|
5226
5236
|
costs[s] = 0;
|
|
5227
|
-
var
|
|
5228
|
-
|
|
5237
|
+
var open2 = dijkstra.PriorityQueue.make();
|
|
5238
|
+
open2.push(s, 0);
|
|
5229
5239
|
var closest, u, v, cost_of_s_to_u, adjacent_nodes, cost_of_e, cost_of_s_to_u_plus_cost_of_e, cost_of_s_to_v, first_visit;
|
|
5230
|
-
while (!
|
|
5231
|
-
closest =
|
|
5240
|
+
while (!open2.empty()) {
|
|
5241
|
+
closest = open2.pop();
|
|
5232
5242
|
u = closest.value;
|
|
5233
5243
|
cost_of_s_to_u = closest.cost;
|
|
5234
5244
|
adjacent_nodes = graph[u] || {};
|
|
@@ -5240,7 +5250,7 @@ var require_dijkstra = __commonJS({
|
|
|
5240
5250
|
first_visit = typeof costs[v] === "undefined";
|
|
5241
5251
|
if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
|
|
5242
5252
|
costs[v] = cost_of_s_to_u_plus_cost_of_e;
|
|
5243
|
-
|
|
5253
|
+
open2.push(v, cost_of_s_to_u_plus_cost_of_e);
|
|
5244
5254
|
predecessors[v] = u;
|
|
5245
5255
|
}
|
|
5246
5256
|
}
|
|
@@ -8747,6 +8757,159 @@ function maxSeq(msgs, fallback) {
|
|
|
8747
8757
|
return Math.max(...msgs.map((m) => m.seq));
|
|
8748
8758
|
}
|
|
8749
8759
|
|
|
8760
|
+
// src/lib/payment-lock.ts
|
|
8761
|
+
var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
|
|
8762
|
+
import { createHash } from "crypto";
|
|
8763
|
+
async function withJobPaymentLock(jobId, action) {
|
|
8764
|
+
ensureConfigDir();
|
|
8765
|
+
const key = createHash("sha256").update(jobId).digest("hex");
|
|
8766
|
+
let compromised = false;
|
|
8767
|
+
const assertOwned = () => {
|
|
8768
|
+
if (compromised) throw new DvmError(
|
|
8769
|
+
"payment_settling",
|
|
8770
|
+
"Payment lock ownership was lost.",
|
|
8771
|
+
`Retry shortly with \`dvm pay ${shellQuoteArg(jobId)}\`, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`
|
|
8772
|
+
);
|
|
8773
|
+
};
|
|
8774
|
+
let release;
|
|
8775
|
+
try {
|
|
8776
|
+
release = import_proper_lockfile.default.lockSync(`${JOBS_FILE}.payment-${key}`, {
|
|
8777
|
+
realpath: false,
|
|
8778
|
+
stale: 12e4,
|
|
8779
|
+
update: 1e4,
|
|
8780
|
+
onCompromised: () => {
|
|
8781
|
+
compromised = true;
|
|
8782
|
+
}
|
|
8783
|
+
});
|
|
8784
|
+
} catch (error) {
|
|
8785
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "ELOCKED") throw error;
|
|
8786
|
+
throw new DvmError(
|
|
8787
|
+
"payment_settling",
|
|
8788
|
+
"Another dvm process is paying this job.",
|
|
8789
|
+
`Retry shortly with \`dvm pay ${shellQuoteArg(jobId)}\`, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`. If the lock is stale, it can take up to 2 minutes to clear.`
|
|
8790
|
+
);
|
|
8791
|
+
}
|
|
8792
|
+
try {
|
|
8793
|
+
return await action(assertOwned);
|
|
8794
|
+
} finally {
|
|
8795
|
+
if (!compromised) release();
|
|
8796
|
+
}
|
|
8797
|
+
}
|
|
8798
|
+
|
|
8799
|
+
// src/lib/provider-output.ts
|
|
8800
|
+
function providerFields(value, fields = Object.keys(value)) {
|
|
8801
|
+
return {
|
|
8802
|
+
...value,
|
|
8803
|
+
_provider_fields: [.../* @__PURE__ */ new Set([
|
|
8804
|
+
...Array.isArray(value._provider_fields) ? value._provider_fields : [],
|
|
8805
|
+
...fields.filter((field) => field !== "_provider_fields" && value[field] !== void 0)
|
|
8806
|
+
])]
|
|
8807
|
+
};
|
|
8808
|
+
}
|
|
8809
|
+
function guidanceJobArg(jobId) {
|
|
8810
|
+
return /^[A-Za-z0-9_-]+$/.test(jobId) ? shellQuoteArg(jobId) : "'<job_id>'";
|
|
8811
|
+
}
|
|
8812
|
+
function providerJobJson(data, providerJob = true) {
|
|
8813
|
+
const action = data.next_action;
|
|
8814
|
+
json(providerFields({
|
|
8815
|
+
...data,
|
|
8816
|
+
...providerJob && action && typeof action === "object" ? { next_action: providerFields(action, ["job_id"]) } : {}
|
|
8817
|
+
}, [...providerJob ? ["jobId"] : [], "capability", "identifier"]));
|
|
8818
|
+
}
|
|
8819
|
+
|
|
8820
|
+
// src/lib/yield-state.ts
|
|
8821
|
+
var JOB_READ_TIMEOUT_MS = 6e4;
|
|
8822
|
+
var PAYMENT_SETTLE_WINDOW_MS = 45e3;
|
|
8823
|
+
function answeredYieldSeqs(messages2) {
|
|
8824
|
+
const answered = /* @__PURE__ */ new Set();
|
|
8825
|
+
const prompts = /* @__PURE__ */ new Map();
|
|
8826
|
+
let paymentRequest;
|
|
8827
|
+
for (const message2 of [...messages2].sort((a, b) => a.seq - b.seq)) {
|
|
8828
|
+
if (message2.from === "provider") {
|
|
8829
|
+
if (message2.type === "payment-request") paymentRequest = message2.seq;
|
|
8830
|
+
if (message2.type === "prompt") prompts.set(message2.content.id, message2.seq);
|
|
8831
|
+
} else if (message2.type === "response") {
|
|
8832
|
+
const seq = prompts.get(message2.content.prompt_id);
|
|
8833
|
+
if (seq !== void 0) answered.add(seq);
|
|
8834
|
+
} else if (message2.type === "payment") {
|
|
8835
|
+
const seq = message2.content.credit?.request_seq ?? paymentRequest;
|
|
8836
|
+
if (seq !== void 0) answered.add(seq);
|
|
8837
|
+
}
|
|
8838
|
+
}
|
|
8839
|
+
return answered;
|
|
8840
|
+
}
|
|
8841
|
+
function latestProviderPaymentRequest(messages2) {
|
|
8842
|
+
return [...messages2].sort((a, b) => a.seq - b.seq).findLast((message2) => message2.from === "provider" && message2.type === "payment-request");
|
|
8843
|
+
}
|
|
8844
|
+
function pendingPaymentRequest(messages2, answered = answeredYieldSeqs(messages2)) {
|
|
8845
|
+
const latest = latestProviderPaymentRequest(messages2);
|
|
8846
|
+
if (!latest || answered.has(latest.seq)) return void 0;
|
|
8847
|
+
if (messages2.some((message2) => message2.from === "provider" && message2.seq > latest.seq && (message2.type === "complete" || message2.type === "cancel" || message2.type === "working"))) return void 0;
|
|
8848
|
+
return latest;
|
|
8849
|
+
}
|
|
8850
|
+
function loadAnsweredYieldSeqs(jobId) {
|
|
8851
|
+
const answered = answeredYieldSeqs(loadMessages(jobId));
|
|
8852
|
+
const job = loadJob(jobId);
|
|
8853
|
+
for (const seq of job?.paidPaymentRequestSeqs ?? []) answered.add(seq);
|
|
8854
|
+
for (const payment of job?.bookedCreditPayments ?? []) answered.add(payment.authorization.request_seq);
|
|
8855
|
+
return answered;
|
|
8856
|
+
}
|
|
8857
|
+
async function reconcileInFlightPaymentRequest(jobId, requestSeq, transport, provider, options) {
|
|
8858
|
+
const boundedOptions = { ...options, timeoutMs: options.timeoutMs ?? JOB_READ_TIMEOUT_MS };
|
|
8859
|
+
const history = await boundedPaymentRead(jobId, () => transport.getMessages(jobId, 0, provider, boundedOptions), boundedOptions.timeoutMs);
|
|
8860
|
+
const decisionTime = Date.now();
|
|
8861
|
+
const needsStatus = !answeredYieldSeqs(history).has(requestSeq) && decisionTime >= settleUntilMs(jobId, requestSeq, decisionTime);
|
|
8862
|
+
const status2 = needsStatus ? (await boundedPaymentRead(jobId, () => transport.status(jobId, provider, boundedOptions), boundedOptions.timeoutMs)).status : void 0;
|
|
8863
|
+
return reconcilePaymentRequestHistory(jobId, requestSeq, history, status2, () => decisionTime);
|
|
8864
|
+
}
|
|
8865
|
+
function reconcilePaymentRequestHistory(jobId, requestSeq, history, status2, now = Date.now) {
|
|
8866
|
+
if (answeredYieldSeqs(history).has(requestSeq)) {
|
|
8867
|
+
markPaymentRequestPaid(jobId, requestSeq);
|
|
8868
|
+
return true;
|
|
8869
|
+
}
|
|
8870
|
+
const superseded = (latestProviderPaymentRequest(history)?.seq ?? -1) > requestSeq;
|
|
8871
|
+
if (superseded) clearPaymentRequestInFlight(jobId, requestSeq);
|
|
8872
|
+
const decisionTime = now();
|
|
8873
|
+
const retryAt = settleUntilMs(jobId, requestSeq, decisionTime);
|
|
8874
|
+
const seconds = Math.ceil((retryAt - decisionTime) / 1e3);
|
|
8875
|
+
if (!superseded && decisionTime < retryAt)
|
|
8876
|
+
throw new DvmError(
|
|
8877
|
+
"payment_settling",
|
|
8878
|
+
"The previous payment may still be processing.",
|
|
8879
|
+
`Retry with \`dvm pay ${shellQuoteArg(jobId)}\` in about ${seconds} ${seconds === 1 ? "second" : "seconds"}, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`,
|
|
8880
|
+
{ retry_at_ms: retryAt }
|
|
8881
|
+
);
|
|
8882
|
+
if (status2 !== "awaiting-input" || pendingPaymentRequest(history)?.seq !== requestSeq)
|
|
8883
|
+
throw new DvmError(
|
|
8884
|
+
"payment_request_not_pending",
|
|
8885
|
+
"The provider is no longer waiting on this payment request.",
|
|
8886
|
+
`Check the job with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
|
|
8887
|
+
);
|
|
8888
|
+
return false;
|
|
8889
|
+
}
|
|
8890
|
+
function settleUntilMs(jobId, requestSeq, now) {
|
|
8891
|
+
const startedAt = loadJob(jobId)?.inFlightPaymentRequestStartedAtMs?.[requestSeq];
|
|
8892
|
+
return startedAt === void 0 ? 0 : Math.min(startedAt + PAYMENT_SETTLE_WINDOW_MS, now + PAYMENT_SETTLE_WINDOW_MS);
|
|
8893
|
+
}
|
|
8894
|
+
async function boundedPaymentRead(jobId, read, timeoutMs) {
|
|
8895
|
+
let timer;
|
|
8896
|
+
try {
|
|
8897
|
+
return await Promise.race([read(), new Promise((_, reject) => {
|
|
8898
|
+
timer = setTimeout(() => reject(new DvmError("timeout", "Payment recovery read timed out. No new payment was sent.")), timeoutMs);
|
|
8899
|
+
})]);
|
|
8900
|
+
} catch (error) {
|
|
8901
|
+
if (isAbortError(error) || error instanceof DvmError && error.code === "timeout")
|
|
8902
|
+
throw new DvmError(
|
|
8903
|
+
"timeout",
|
|
8904
|
+
"Payment recovery read timed out. No new payment was sent.",
|
|
8905
|
+
`Retry with \`dvm pay ${shellQuoteArg(jobId)}\` or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`
|
|
8906
|
+
);
|
|
8907
|
+
throw error;
|
|
8908
|
+
} finally {
|
|
8909
|
+
if (timer) clearTimeout(timer);
|
|
8910
|
+
}
|
|
8911
|
+
}
|
|
8912
|
+
|
|
8750
8913
|
// src/lib/next-action.ts
|
|
8751
8914
|
function isTerminalJobStatus(status2) {
|
|
8752
8915
|
return TERMINAL_STATUSES.has(status2);
|
|
@@ -8755,19 +8918,24 @@ function pollNextAction(jobId, hint) {
|
|
|
8755
8918
|
return {
|
|
8756
8919
|
type: "poll",
|
|
8757
8920
|
job_id: jobId,
|
|
8758
|
-
hint: hint ??
|
|
8921
|
+
hint: hint ?? `Provider is still working. Keep the job moving unattended with \`dvm messages ${guidanceJobArg(jobId)} --wait\`.`
|
|
8759
8922
|
};
|
|
8760
8923
|
}
|
|
8924
|
+
function paymentInFlightHint(jobId) {
|
|
8925
|
+
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.`;
|
|
8926
|
+
}
|
|
8761
8927
|
var YIELD_TYPES = /* @__PURE__ */ new Set(["prompt", "payment-request", "working", "complete", "cancel"]);
|
|
8762
8928
|
var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
8763
8929
|
"completed",
|
|
8764
8930
|
"failed",
|
|
8765
8931
|
"cancelled"
|
|
8766
8932
|
]);
|
|
8767
|
-
function computeNextAction(jobId, messages2) {
|
|
8933
|
+
function computeNextAction(jobId, messages2, nowMs = Date.now()) {
|
|
8934
|
+
const answered = answeredYieldSeqs(messages2);
|
|
8935
|
+
const expiresAtMs = pendingDeadline(messages2, answered);
|
|
8768
8936
|
for (let i = messages2.length - 1; i >= 0; i--) {
|
|
8769
8937
|
const msg = messages2[i];
|
|
8770
|
-
if (!YIELD_TYPES.has(msg.type)) continue;
|
|
8938
|
+
if (!YIELD_TYPES.has(msg.type) || answered.has(msg.seq)) continue;
|
|
8771
8939
|
switch (msg.type) {
|
|
8772
8940
|
case "complete":
|
|
8773
8941
|
case "cancel":
|
|
@@ -8777,31 +8945,44 @@ function computeNextAction(jobId, messages2) {
|
|
|
8777
8945
|
const answer = c.schema ? "--json '<object matching schema>'" : '"<answer>"';
|
|
8778
8946
|
const choices = c.options?.length ? ` Choices: ${c.options.map((option) => JSON.stringify(option)).join(", ")}.` : "";
|
|
8779
8947
|
const choiceHint = !c.schema && c.options?.length ? " Answer with exactly one of options unless the human chose otherwise." : "";
|
|
8948
|
+
const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Answer" : "Reply", expiresAtMs, nowMs, jobId);
|
|
8949
|
+
const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
|
|
8780
8950
|
const action = {
|
|
8781
8951
|
type: "respond",
|
|
8782
8952
|
job_id: jobId,
|
|
8783
8953
|
prompt_id: c.id,
|
|
8784
8954
|
prompt: asProviderText(c.text),
|
|
8785
|
-
|
|
8786
|
-
|
|
8955
|
+
_provider_fields: [
|
|
8956
|
+
"prompt_id",
|
|
8957
|
+
...c.schema ? ["schema"] : [],
|
|
8958
|
+
...c.options?.length ? ["options"] : []
|
|
8959
|
+
],
|
|
8960
|
+
display: withDeadline(`The provider asks: ${c.text}${choices}`, deadline),
|
|
8961
|
+
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)
|
|
8787
8962
|
};
|
|
8788
8963
|
if (c.schema) action.schema = c.schema;
|
|
8789
8964
|
if (c.options?.length) action.options = c.options;
|
|
8965
|
+
if (expiresAtMs !== void 0) action.expires_at_ms = expiresAtMs;
|
|
8790
8966
|
return action;
|
|
8791
8967
|
}
|
|
8792
8968
|
case "payment-request": {
|
|
8793
8969
|
const c = msg.content;
|
|
8794
8970
|
const display = formatPaymentAmount(c.amount_msats, c.fiat_amount);
|
|
8971
|
+
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);
|
|
8972
|
+
const priceGuidance = safeCurrency ? display : "see the provider price in next_action.fiat_amount";
|
|
8973
|
+
const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Pay" : "Reply", expiresAtMs, nowMs, jobId);
|
|
8974
|
+
const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
|
|
8795
8975
|
return {
|
|
8796
8976
|
type: "pay",
|
|
8797
8977
|
job_id: jobId,
|
|
8798
8978
|
amount_msats: c.amount_msats,
|
|
8799
8979
|
// Mirror only a fiat figure the display actually led with: echoing a
|
|
8800
8980
|
// zero amount would tell an agent doing budget math the charge is free.
|
|
8801
|
-
...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount } : {},
|
|
8802
|
-
|
|
8981
|
+
...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount, _provider_fields: ["fiat_amount"] } : {},
|
|
8982
|
+
...expiresAtMs !== void 0 ? { expires_at_ms: expiresAtMs } : {},
|
|
8983
|
+
display: withDeadline(display, deadline),
|
|
8803
8984
|
reason: asProviderText(c.reason),
|
|
8804
|
-
hint: `Payment required to continue: ${
|
|
8985
|
+
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)
|
|
8805
8986
|
};
|
|
8806
8987
|
}
|
|
8807
8988
|
case "working": {
|
|
@@ -8810,13 +8991,49 @@ function computeNextAction(jobId, messages2) {
|
|
|
8810
8991
|
type: "poll",
|
|
8811
8992
|
job_id: jobId,
|
|
8812
8993
|
estimate_seconds: c.estimate_seconds,
|
|
8813
|
-
hint: c.hint !== void 0 ? asProviderText(c.hint) :
|
|
8994
|
+
hint: c.hint !== void 0 ? asProviderText(c.hint) : pollNextAction(jobId).hint
|
|
8814
8995
|
};
|
|
8815
8996
|
}
|
|
8816
8997
|
}
|
|
8817
8998
|
}
|
|
8818
8999
|
return null;
|
|
8819
9000
|
}
|
|
9001
|
+
function pendingDeadline(messages2, answered) {
|
|
9002
|
+
const prompts = /* @__PURE__ */ new Map();
|
|
9003
|
+
let payment;
|
|
9004
|
+
for (const message2 of [...messages2].sort((a, b) => a.seq - b.seq)) {
|
|
9005
|
+
if (message2.from === "provider" && message2.type === "prompt") {
|
|
9006
|
+
prompts.set(message2.content.id, validDeadline(message2.content.expires_at_ms));
|
|
9007
|
+
} else if (message2.from === "requester" && message2.type === "response") {
|
|
9008
|
+
prompts.delete(message2.content.prompt_id);
|
|
9009
|
+
} else if (message2.from === "provider" && message2.type === "payment-request") {
|
|
9010
|
+
payment = !answered.has(message2.seq) && message2.content.amount_msats > 0 ? validDeadline(message2.content.expires_at_ms) : void 0;
|
|
9011
|
+
}
|
|
9012
|
+
}
|
|
9013
|
+
let earliest = payment;
|
|
9014
|
+
for (const deadline of prompts.values()) {
|
|
9015
|
+
if (deadline !== void 0 && (earliest === void 0 || deadline < earliest)) earliest = deadline;
|
|
9016
|
+
}
|
|
9017
|
+
return earliest;
|
|
9018
|
+
}
|
|
9019
|
+
function validDeadline(value) {
|
|
9020
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 864e13 ? value : void 0;
|
|
9021
|
+
}
|
|
9022
|
+
function withDeadline(display, deadline) {
|
|
9023
|
+
if (!deadline) return display;
|
|
9024
|
+
return `${display}${/[.!?]$/.test(display) ? "" : "."} ${deadline}`;
|
|
9025
|
+
}
|
|
9026
|
+
function deadlineClause(action, expiresAtMs, nowMs, jobId) {
|
|
9027
|
+
if (expiresAtMs === void 0) return "";
|
|
9028
|
+
const deadline = new Date(expiresAtMs).toISOString().slice(0, 16).replace("T", " ") + " UTC";
|
|
9029
|
+
if (expiresAtMs <= nowMs) {
|
|
9030
|
+
return `The deadline to ${action.toLowerCase()} (${deadline}) has passed. The provider will probably cancel the job. Check its status with \`dvm status ${guidanceJobArg(jobId)}\`.`;
|
|
9031
|
+
}
|
|
9032
|
+
const minutes = Math.floor((expiresAtMs - nowMs) / 6e4);
|
|
9033
|
+
const hours = Math.floor(minutes / 60);
|
|
9034
|
+
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";
|
|
9035
|
+
return `${action} by ${deadline} (in ${remaining}), or the provider cancels the job.`;
|
|
9036
|
+
}
|
|
8820
9037
|
|
|
8821
9038
|
// src/lib/rail-labels.ts
|
|
8822
9039
|
var PAYMENT_RAIL_KEYS = ["cashu", "cashu_p2pk", "x402", "tempo"];
|
|
@@ -9665,7 +9882,11 @@ async function sendCreditPayment(jobId, intent, transport, provider, jobToken) {
|
|
|
9665
9882
|
async function tryCreditPayment(args) {
|
|
9666
9883
|
const { jobId, request: request2, requestSeq, transport, provider, jobToken } = args;
|
|
9667
9884
|
const job = loadJob(jobId);
|
|
9885
|
+
if (job && hasUnknownUpfrontRail(job))
|
|
9886
|
+
throw new DvmError("upfront_rail_unknown", "Recover the original upfront rail charge before another balance payment.");
|
|
9668
9887
|
const ask = request2.credit;
|
|
9888
|
+
if (job && hasUnknownUpfrontCredit(job))
|
|
9889
|
+
throw new DvmError("upfront_credit_unknown", "The original upfront credit debit must be recovered before another balance payment.");
|
|
9669
9890
|
if (!job?.creditBinding || !ask || !Number.isSafeInteger(requestSeq) || requestSeq < 0 || !Number.isSafeInteger(ask.amount_micro) || ask.amount_micro <= 0 || !/^[a-z]{3}$/.test(ask.currency)) return false;
|
|
9670
9891
|
const signer = findSigningIdentityByPubkey(job.creditBinding.callerPubkey);
|
|
9671
9892
|
if (!signer) return false;
|
|
@@ -9737,6 +9958,7 @@ async function tryCreditPayment(args) {
|
|
|
9737
9958
|
authorization,
|
|
9738
9959
|
request: request2,
|
|
9739
9960
|
amountMsats,
|
|
9961
|
+
approval: args.approval,
|
|
9740
9962
|
..."unbound" in job.creditBinding ? { selectedUnbound: true } : {}
|
|
9741
9963
|
};
|
|
9742
9964
|
return current.pendingCreditPayment;
|
|
@@ -9897,6 +10119,7 @@ async function bookRecoveredSubmissions(args) {
|
|
|
9897
10119
|
const fresh = loadAgentWallet();
|
|
9898
10120
|
const booked = matches(fresh);
|
|
9899
10121
|
if (!fresh || booked.length === 0) return [];
|
|
10122
|
+
for (const entry of booked) restoreUpfrontRailPayment(entry, args.jobId, null);
|
|
9900
10123
|
saveAgentWallet(
|
|
9901
10124
|
booked.reduce(
|
|
9902
10125
|
(acc, entry) => applyOutcome(acc, { kind: "shipped", entry, jobId: args.jobId }, now),
|
|
@@ -10231,6 +10454,8 @@ async function shipEntry(entry, httpPost, persistUnresolved) {
|
|
|
10231
10454
|
...record.jobToken && !existing.jobToken ? { jobToken: record.jobToken } : {}
|
|
10232
10455
|
});
|
|
10233
10456
|
} else saveJob(record);
|
|
10457
|
+
restoreUpfrontRailPayment(active2, identity.jobId, response.body);
|
|
10458
|
+
recordUpfrontCreditPayment(identity.jobId, response.body?.upfront_payment, true);
|
|
10234
10459
|
}
|
|
10235
10460
|
await reconcileResumedJobCredit(active2, response.body, httpPost);
|
|
10236
10461
|
return { kind: "shipped", entry, jobId: identity.jobId };
|
|
@@ -10348,12 +10573,21 @@ function saveRecoveredJob(entry, jobId, body, requestId) {
|
|
|
10348
10573
|
requestId,
|
|
10349
10574
|
...jobToken && !existing.jobToken ? { jobToken } : {}
|
|
10350
10575
|
});
|
|
10576
|
+
recordUpfrontCreditPayment(jobId, body?.upfront_payment, true);
|
|
10577
|
+
restoreUpfrontRailPayment(entry, jobId, body);
|
|
10351
10578
|
return "saved";
|
|
10352
10579
|
}
|
|
10353
10580
|
const { jobToken: _unchecked, ...record } = jobRecordFromEntry(entry, jobId, body, void 0);
|
|
10354
10581
|
saveJob({ ...record, requestId, ...jobToken ? { jobToken } : {} });
|
|
10582
|
+
recordUpfrontCreditPayment(jobId, body?.upfront_payment, true);
|
|
10583
|
+
restoreUpfrontRailPayment(entry, jobId, body);
|
|
10355
10584
|
return "saved";
|
|
10356
10585
|
}
|
|
10586
|
+
function restoreUpfrontRailPayment(entry, jobId, body) {
|
|
10587
|
+
const context = entry.context;
|
|
10588
|
+
const accepted = parseUpfrontPayment(body?.upfront_payment);
|
|
10589
|
+
recordUpfrontRailPayment(jobId, context?.upfront_rail_payment ?? (accepted ? { method: "cashu", amountMsats: accepted.amount_msats } : void 0));
|
|
10590
|
+
}
|
|
10357
10591
|
function errorCodeOf(body) {
|
|
10358
10592
|
const error = body?.error;
|
|
10359
10593
|
if (typeof error === "string") return error;
|
|
@@ -10571,6 +10805,7 @@ function applyOutcome(wallet, outcome, now) {
|
|
|
10571
10805
|
signed_at_ms: now()
|
|
10572
10806
|
};
|
|
10573
10807
|
const dropped = drop();
|
|
10808
|
+
if (dropped.recent_spends.some((spend) => spend.request_id === recentSpend.request_id)) return dropped;
|
|
10574
10809
|
return {
|
|
10575
10810
|
...dropped,
|
|
10576
10811
|
recent_spends: [...dropped.recent_spends, recentSpend].slice(-RECENT_SPENDS_CAP)
|
|
@@ -10943,7 +11178,38 @@ function parseTempoNetwork(value, source) {
|
|
|
10943
11178
|
|
|
10944
11179
|
// src/lib/payment-responder.ts
|
|
10945
11180
|
async function handlePaymentRequest(jobId, request2, policy, transport, provider, opts) {
|
|
11181
|
+
return withJobPaymentLock(jobId, (assertOwned) => {
|
|
11182
|
+
const guardedTransport = new Proxy(transport, {
|
|
11183
|
+
get(target, key) {
|
|
11184
|
+
if (key === "sendMessage") return async (...args) => {
|
|
11185
|
+
assertOwned();
|
|
11186
|
+
return target.sendMessage(...args);
|
|
11187
|
+
};
|
|
11188
|
+
const value = Reflect.get(target, key, target);
|
|
11189
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
11190
|
+
}
|
|
11191
|
+
});
|
|
11192
|
+
return handleLockedPaymentRequest(jobId, request2, policy, guardedTransport, provider, opts);
|
|
11193
|
+
});
|
|
11194
|
+
}
|
|
11195
|
+
async function handleLockedPaymentRequest(jobId, request2, policy, transport, provider, opts) {
|
|
11196
|
+
const approval = opts?.requestSeq === void 0 ? void 0 : {
|
|
11197
|
+
requestSeq: opts.requestSeq,
|
|
11198
|
+
approval: opts.approval ?? "auto"
|
|
11199
|
+
};
|
|
10946
11200
|
const job = loadJob(jobId);
|
|
11201
|
+
if (job && hasUnknownUpfrontRail(job))
|
|
11202
|
+
throw new DvmError(
|
|
11203
|
+
"upfront_rail_unknown",
|
|
11204
|
+
"The original upfront rail charge is unknown or conflicting.",
|
|
11205
|
+
"Recover the original job price before authorizing more payments."
|
|
11206
|
+
);
|
|
11207
|
+
if (job && hasUnknownUpfrontCredit(job))
|
|
11208
|
+
throw new DvmError(
|
|
11209
|
+
"upfront_credit_unknown",
|
|
11210
|
+
"The original upfront credit debit is unknown or conflicting.",
|
|
11211
|
+
"Recover the accepted upfront amount with 'dvm request-result' before authorizing more payments."
|
|
11212
|
+
);
|
|
10947
11213
|
const spent = job?.totalPaidMsats ?? 0;
|
|
10948
11214
|
const paymentsHonoured = job?.paymentsHonoured ?? 0;
|
|
10949
11215
|
const pinnedMint = job?.pinnedMint;
|
|
@@ -10970,6 +11236,22 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
|
|
|
10970
11236
|
if (pending4.authorization.request_seq !== opts?.requestSeq)
|
|
10971
11237
|
throw new DvmError("credit_payment_retry_required", "The prior balance payment was refused; reload this job's pending ask.");
|
|
10972
11238
|
}
|
|
11239
|
+
if (opts?.creditRecoveryOnly)
|
|
11240
|
+
throw new DvmError(
|
|
11241
|
+
"credit_payment_retry_required",
|
|
11242
|
+
"The saved balance payment was not recovered; no replacement payment was sent.",
|
|
11243
|
+
`Run \`dvm status ${shellQuoteArg(jobId)}\` to refresh the job, then run \`dvm pay ${shellQuoteArg(jobId)}\` only if payment is still requested.`
|
|
11244
|
+
);
|
|
11245
|
+
if (matchingEndpoint && opts?.requestSeq !== void 0) {
|
|
11246
|
+
if (job.inFlightPaymentRequestSeqs?.includes(opts.requestSeq))
|
|
11247
|
+
await reconcileInFlightPaymentRequest(jobId, opts.requestSeq, transport, provider, { jobToken });
|
|
11248
|
+
if (loadAnsweredYieldSeqs(jobId).has(opts.requestSeq))
|
|
11249
|
+
throw new DvmError(
|
|
11250
|
+
"payment_already_sent",
|
|
11251
|
+
"Payment already sent for this request.",
|
|
11252
|
+
`Keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
|
|
11253
|
+
);
|
|
11254
|
+
}
|
|
10973
11255
|
if (policy.maxIncrementMsats > 0 && request2.amount_msats > policy.maxIncrementMsats) {
|
|
10974
11256
|
return "over-budget";
|
|
10975
11257
|
}
|
|
@@ -10992,6 +11274,7 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
|
|
|
10992
11274
|
request: request2,
|
|
10993
11275
|
policy,
|
|
10994
11276
|
requestSeq: opts?.requestSeq,
|
|
11277
|
+
approval: opts?.approval ?? "auto",
|
|
10995
11278
|
transport,
|
|
10996
11279
|
provider,
|
|
10997
11280
|
jobToken
|
|
@@ -11024,15 +11307,17 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
|
|
|
11024
11307
|
pinnedMint,
|
|
11025
11308
|
maxCashuFeeSats,
|
|
11026
11309
|
strictPerCall,
|
|
11027
|
-
|
|
11310
|
+
approval,
|
|
11311
|
+
jobToken,
|
|
11312
|
+
requestSeq: matchingEndpoint ? opts?.requestSeq : void 0
|
|
11028
11313
|
});
|
|
11029
11314
|
if (paid) {
|
|
11030
11315
|
return { status: "paid", rail: "cashu_p2pk", amountMsats: request2.amount_msats };
|
|
11031
11316
|
}
|
|
11032
11317
|
}
|
|
11033
11318
|
if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
|
|
11034
|
-
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-
|
|
11035
|
-
const { tryX402Payment: tryX402Payment2 } = await import("./client-
|
|
11319
|
+
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UJ7EJNQA.js");
|
|
11320
|
+
const { tryX402Payment: tryX402Payment2 } = await import("./client-DS4QJ346.js");
|
|
11036
11321
|
const wallet = loadX402Wallet2();
|
|
11037
11322
|
if (wallet) {
|
|
11038
11323
|
let proof;
|
|
@@ -11072,9 +11357,10 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
|
|
|
11072
11357
|
}
|
|
11073
11358
|
},
|
|
11074
11359
|
provider,
|
|
11075
|
-
{ jobToken }
|
|
11360
|
+
{ jobToken },
|
|
11361
|
+
matchingEndpoint ? opts?.requestSeq : void 0
|
|
11076
11362
|
);
|
|
11077
|
-
addPayment(jobId, proof.amountMsats);
|
|
11363
|
+
addPayment(jobId, proof.amountMsats, approval);
|
|
11078
11364
|
recordSpend({
|
|
11079
11365
|
msats: proof.amountMsats,
|
|
11080
11366
|
btcRate: proof.btcRate,
|
|
@@ -11108,9 +11394,10 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
|
|
|
11108
11394
|
}
|
|
11109
11395
|
},
|
|
11110
11396
|
provider,
|
|
11111
|
-
{ jobToken }
|
|
11397
|
+
{ jobToken },
|
|
11398
|
+
matchingEndpoint ? opts?.requestSeq : void 0
|
|
11112
11399
|
);
|
|
11113
|
-
addPayment(jobId, paidMsats);
|
|
11400
|
+
addPayment(jobId, paidMsats, approval);
|
|
11114
11401
|
recordSpend({
|
|
11115
11402
|
msats: paidMsats,
|
|
11116
11403
|
btcRate: tempoRate,
|
|
@@ -11137,6 +11424,7 @@ async function tryAgentWalletMidJobPayment(args) {
|
|
|
11137
11424
|
pinnedMint,
|
|
11138
11425
|
maxCashuFeeSats,
|
|
11139
11426
|
strictPerCall,
|
|
11427
|
+
approval,
|
|
11140
11428
|
jobToken
|
|
11141
11429
|
} = args;
|
|
11142
11430
|
if (!strictPerCall) await sweepPendingSubmissions({ fetchImpl: dvmFetch }).catch(() => void 0);
|
|
@@ -11191,7 +11479,8 @@ async function tryAgentWalletMidJobPayment(args) {
|
|
|
11191
11479
|
prepared,
|
|
11192
11480
|
transport,
|
|
11193
11481
|
provider,
|
|
11194
|
-
jobToken
|
|
11482
|
+
jobToken,
|
|
11483
|
+
requestSeq: args.requestSeq
|
|
11195
11484
|
});
|
|
11196
11485
|
} catch (err) {
|
|
11197
11486
|
if (err instanceof DvmError && err.code === "payment_invalid") {
|
|
@@ -11209,7 +11498,7 @@ async function tryAgentWalletMidJobPayment(args) {
|
|
|
11209
11498
|
signed_at_ms: Date.now()
|
|
11210
11499
|
}
|
|
11211
11500
|
});
|
|
11212
|
-
addPayment(jobId, request2.amount_msats);
|
|
11501
|
+
addPayment(jobId, request2.amount_msats, approval);
|
|
11213
11502
|
recordSpend({
|
|
11214
11503
|
msats: request2.amount_msats,
|
|
11215
11504
|
btcRate,
|
|
@@ -11235,14 +11524,15 @@ async function sendMidJobPaymentWithRetry(args) {
|
|
|
11235
11524
|
}
|
|
11236
11525
|
},
|
|
11237
11526
|
provider,
|
|
11238
|
-
{ jobToken }
|
|
11527
|
+
{ jobToken },
|
|
11528
|
+
args.requestSeq
|
|
11239
11529
|
),
|
|
11240
11530
|
intendedLockPubkey: prepared.intendedLockPubkey,
|
|
11241
11531
|
refetchInfo: () => transport.describe(provider),
|
|
11242
11532
|
sleep: args.sleep
|
|
11243
11533
|
});
|
|
11244
11534
|
}
|
|
11245
|
-
async function sendRailPayment(transport, jobId, message2, provider, options) {
|
|
11535
|
+
async function sendRailPayment(transport, jobId, message2, provider, options, requestSeq) {
|
|
11246
11536
|
const capture = (evidence) => {
|
|
11247
11537
|
if (evidence.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
|
|
11248
11538
|
if (evidence.drawFundingReceipt) captureDrawFundingReceipts(jobId, [evidence.drawFundingReceipt], {
|
|
@@ -11250,14 +11540,32 @@ async function sendRailPayment(transport, jobId, message2, provider, options) {
|
|
|
11250
11540
|
...typeof message2.content.cashu_request_id === "string" ? { fundId: message2.content.cashu_request_id } : {}
|
|
11251
11541
|
});
|
|
11252
11542
|
};
|
|
11543
|
+
if (requestSeq !== void 0) markPaymentRequestInFlight(jobId, requestSeq);
|
|
11253
11544
|
try {
|
|
11254
11545
|
const result = await transport.sendMessage(jobId, message2, provider, options);
|
|
11546
|
+
if (requestSeq !== void 0) markPaymentRequestPaid(jobId, requestSeq);
|
|
11255
11547
|
if (result) capture(result);
|
|
11256
11548
|
} catch (error) {
|
|
11549
|
+
if (requestSeq !== void 0) {
|
|
11550
|
+
if (error instanceof DvmError && error.code === "replay_rejected") markPaymentRequestPaid(jobId, requestSeq);
|
|
11551
|
+
else if (definitelyNotAccepted(error)) clearPaymentRequestInFlight(jobId, requestSeq);
|
|
11552
|
+
else markPaymentRequestInFlight(jobId, requestSeq);
|
|
11553
|
+
}
|
|
11257
11554
|
if (error instanceof DvmError && error.data) capture(error.data);
|
|
11555
|
+
if (error instanceof DvmError && error.code === "replay_rejected") return;
|
|
11258
11556
|
throw error;
|
|
11259
11557
|
}
|
|
11260
11558
|
}
|
|
11559
|
+
function definitelyNotAccepted(error) {
|
|
11560
|
+
if (error instanceof DvmError) {
|
|
11561
|
+
const status2 = error.data?.http_status;
|
|
11562
|
+
return typeof status2 === "number" && status2 >= 400 && status2 < 500;
|
|
11563
|
+
}
|
|
11564
|
+
if (!(error instanceof Error)) return false;
|
|
11565
|
+
if ("code" in error && ["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH"].includes(String(error.code))) return true;
|
|
11566
|
+
if (error instanceof AggregateError) return error.errors.length > 0 && error.errors.every(definitelyNotAccepted);
|
|
11567
|
+
return definitelyNotAccepted(error.cause);
|
|
11568
|
+
}
|
|
11261
11569
|
async function tryMppCredential(challenges, amountMsats, btcRate) {
|
|
11262
11570
|
const wallet = loadConfig()?.tempo;
|
|
11263
11571
|
if (wallet?.method !== "tempo" || !wallet.apiKey) return null;
|
|
@@ -11343,7 +11651,7 @@ function refundNextAction(jobId, claims) {
|
|
|
11343
11651
|
reason: claim.reason,
|
|
11344
11652
|
claimed: false,
|
|
11345
11653
|
cashu_token: claim.cashu_token,
|
|
11346
|
-
hint: `The provider sent a ${noun} but the auto-claim into your wallet failed (the mint may be unreachable). Claim it manually with 'dvm wallet receive-token <cashu_token>' \u2014 the token is in this action's 'cashu_token' field, don't lose it. Or retry the auto-claim with 'dvm messages ${jobId} --no-stream' (re-running plain 'dvm messages' won't retry \u2014 its cursor has already advanced past this message).`
|
|
11654
|
+
hint: `The provider sent a ${noun} but the auto-claim into your wallet failed (the mint may be unreachable). Claim it manually with 'dvm wallet receive-token <cashu_token>' \u2014 the token is in this action's 'cashu_token' field, don't lose it. Or retry the auto-claim with 'dvm messages ${guidanceJobArg(jobId)} --no-stream' (re-running plain 'dvm messages' won't retry \u2014 its cursor has already advanced past this message).`
|
|
11347
11655
|
};
|
|
11348
11656
|
}
|
|
11349
11657
|
return {
|
|
@@ -11372,21 +11680,20 @@ async function refundJsonField(claims) {
|
|
|
11372
11680
|
}
|
|
11373
11681
|
};
|
|
11374
11682
|
}
|
|
11375
|
-
function
|
|
11376
|
-
|
|
11377
|
-
|
|
11378
|
-
|
|
11379
|
-
info(`Claimed ${noun} of ${formatAmountBestEffort(claim.amount_msats)} into your wallet.`);
|
|
11380
|
-
} else {
|
|
11381
|
-
info(
|
|
11382
|
-
`${cap(noun)} of ${formatAmountBestEffort(claim.amount_msats)} could not be auto-claimed (the mint may be down). Recover with: dvm wallet receive-token ${claim.cashu_token}`
|
|
11383
|
-
);
|
|
11384
|
-
}
|
|
11683
|
+
function refundSummaryHuman(claim) {
|
|
11684
|
+
const noun = claim.reason === "change" ? "change" : "refund";
|
|
11685
|
+
if (claim.claimed) {
|
|
11686
|
+
return `Claimed ${noun} of ${formatAmountBestEffort(claim.amount_msats)} into your wallet.`;
|
|
11385
11687
|
}
|
|
11688
|
+
return `${cap(noun)} of ${formatAmountBestEffort(claim.amount_msats)} could not be auto-claimed (the mint may be down). Recover with: dvm wallet receive-token ${claim.cashu_token}`;
|
|
11386
11689
|
}
|
|
11387
11690
|
function cap(s) {
|
|
11388
11691
|
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
11389
11692
|
}
|
|
11693
|
+
function withRefundNextAction(jobId, action, claims) {
|
|
11694
|
+
if (action?.type === "respond" || action?.type === "pay") return action;
|
|
11695
|
+
return refundNextAction(jobId, claims) ?? action;
|
|
11696
|
+
}
|
|
11390
11697
|
|
|
11391
11698
|
// src/lib/stream-loop.ts
|
|
11392
11699
|
async function streamLoop(opts) {
|
|
@@ -11396,8 +11703,9 @@ async function streamLoop(opts) {
|
|
|
11396
11703
|
const allMessages = [];
|
|
11397
11704
|
const autoPayments = [];
|
|
11398
11705
|
const refunds = [];
|
|
11399
|
-
const
|
|
11706
|
+
const answeredSeqs = persistLocalState ? loadAnsweredYieldSeqs(jobId) : /* @__PURE__ */ new Set();
|
|
11400
11707
|
let justAutoPaid = false;
|
|
11708
|
+
let paymentUnresolved = false;
|
|
11401
11709
|
let cursor = opts.afterSeq;
|
|
11402
11710
|
let messageAppendSession = opts.messageAppendSession;
|
|
11403
11711
|
const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
|
|
@@ -11409,16 +11717,32 @@ async function streamLoop(opts) {
|
|
|
11409
11717
|
...result.amountUsdcMicro !== void 0 && { amount_usdc_microunits: result.amountUsdcMicro },
|
|
11410
11718
|
display: paidConfirmationDisplay(result, request2.fiat_amount)
|
|
11411
11719
|
});
|
|
11412
|
-
|
|
11720
|
+
if (persistLocalState) markPaymentRequestPaid(jobId, seq);
|
|
11721
|
+
answeredSeqs.add(seq);
|
|
11413
11722
|
justAutoPaid = true;
|
|
11414
11723
|
}
|
|
11724
|
+
let pendingAction = null;
|
|
11415
11725
|
const pending4 = persistLocalState ? loadJob(jobId)?.pendingCreditPayment : void 0;
|
|
11416
11726
|
if (pending4 && policy) {
|
|
11417
|
-
|
|
11418
|
-
|
|
11419
|
-
|
|
11420
|
-
|
|
11727
|
+
let result;
|
|
11728
|
+
try {
|
|
11729
|
+
result = await handlePaymentRequest(jobId, pending4.request, policy, transport, provider, {
|
|
11730
|
+
jobToken,
|
|
11731
|
+
requestSeq: pending4.authorization.request_seq
|
|
11732
|
+
});
|
|
11733
|
+
} catch (error) {
|
|
11734
|
+
if (error instanceof DvmError && error.code === "payment_settling")
|
|
11735
|
+
return { messages: [], autoPayments, refunds, cursor, nextAction: pollNextAction(jobId, paymentInFlightHint(jobId)) };
|
|
11736
|
+
throw error;
|
|
11737
|
+
}
|
|
11421
11738
|
if (typeof result === "object") recordAutoPayment(result, pending4.request, pending4.authorization.request_seq);
|
|
11739
|
+
else pendingAction = computeNextAction(jobId, [{
|
|
11740
|
+
seq: pending4.authorization.request_seq,
|
|
11741
|
+
from: "provider",
|
|
11742
|
+
timestamp: 0,
|
|
11743
|
+
type: "payment-request",
|
|
11744
|
+
content: pending4.request
|
|
11745
|
+
}]);
|
|
11422
11746
|
}
|
|
11423
11747
|
const deadline = opts.timeoutMs === void 0 ? void 0 : Date.now() + Math.max(0, opts.timeoutMs);
|
|
11424
11748
|
const nextPollOptions = () => {
|
|
@@ -11441,7 +11765,9 @@ async function streamLoop(opts) {
|
|
|
11441
11765
|
let batchMessages;
|
|
11442
11766
|
if (streamFn) {
|
|
11443
11767
|
const streamOpts = {
|
|
11444
|
-
onMessage:
|
|
11768
|
+
onMessage: (message2) => {
|
|
11769
|
+
if (message2.seq > cursor) opts.onMessage?.(message2);
|
|
11770
|
+
},
|
|
11445
11771
|
signal: controller?.signal,
|
|
11446
11772
|
jobToken
|
|
11447
11773
|
};
|
|
@@ -11452,12 +11778,12 @@ async function streamLoop(opts) {
|
|
|
11452
11778
|
if (isAbortError(err) || deadline !== void 0 && isMessagePollTimeout(err)) break;
|
|
11453
11779
|
throw err;
|
|
11454
11780
|
}
|
|
11455
|
-
batchMessages = result.messages;
|
|
11781
|
+
batchMessages = result.messages.filter((message2) => message2.seq > cursor);
|
|
11456
11782
|
} else {
|
|
11457
11783
|
const pollOptions = nextPollOptions();
|
|
11458
11784
|
if (!pollOptions) break;
|
|
11459
11785
|
try {
|
|
11460
|
-
batchMessages = await transport.getMessages(jobId, cursor, provider, pollOptions);
|
|
11786
|
+
batchMessages = (await transport.getMessages(jobId, cursor, provider, pollOptions)).filter((message2) => message2.seq > cursor);
|
|
11461
11787
|
} catch (err) {
|
|
11462
11788
|
if (deadline !== void 0 && isMessagePollTimeout(err)) break;
|
|
11463
11789
|
throw err;
|
|
@@ -11477,20 +11803,53 @@ async function streamLoop(opts) {
|
|
|
11477
11803
|
refunds.push(...await claimInboundPayments(jobId, batchMessages));
|
|
11478
11804
|
}
|
|
11479
11805
|
justAutoPaid = false;
|
|
11480
|
-
const
|
|
11481
|
-
|
|
11482
|
-
|
|
11806
|
+
if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
|
|
11807
|
+
for (const seq of answeredYieldSeqs(batchMessages)) answeredSeqs.add(seq);
|
|
11808
|
+
const pendingPayment = pendingPaymentRequest(batchMessages, answeredSeqs);
|
|
11809
|
+
const lastYield2 = findLastYield(batchMessages.filter((message2) => !answeredSeqs.has(message2.seq) && (message2.type !== "payment-request" || message2.seq === pendingPayment?.seq))) ?? findLastYield(batchMessages);
|
|
11810
|
+
if (lastYield2?.type === "payment-request" && answeredSeqs.has(lastYield2.seq)) {
|
|
11811
|
+
if (persistLocalState) markPaymentRequestPaid(jobId, lastYield2.seq);
|
|
11483
11812
|
break;
|
|
11484
11813
|
}
|
|
11485
|
-
if (
|
|
11486
|
-
const
|
|
11814
|
+
if (lastYield2?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield2.seq)) {
|
|
11815
|
+
const pollOptions = nextPollOptions();
|
|
11816
|
+
try {
|
|
11817
|
+
if (!pollOptions) paymentUnresolved = true;
|
|
11818
|
+
else if (await withJobPaymentLock(jobId, () => reconcileInFlightPaymentRequest(jobId, lastYield2.seq, transport, provider, pollOptions))) {
|
|
11819
|
+
answeredSeqs.add(lastYield2.seq);
|
|
11820
|
+
break;
|
|
11821
|
+
}
|
|
11822
|
+
} catch (error) {
|
|
11823
|
+
if (!isMessagePollTimeout(error) && !(error instanceof DvmError && ["payment_settling", "payment_request_not_pending"].includes(error.code))) throw error;
|
|
11824
|
+
paymentUnresolved = true;
|
|
11825
|
+
}
|
|
11826
|
+
if (paymentUnresolved) {
|
|
11827
|
+
cursor = lastYield2.seq - 1;
|
|
11828
|
+
break;
|
|
11829
|
+
}
|
|
11830
|
+
}
|
|
11831
|
+
if (lastYield2?.type === "payment-request" && lastYield2.seq === pendingPayment?.seq && policy) {
|
|
11832
|
+
const req = lastYield2.content;
|
|
11487
11833
|
if (req.amount_msats <= policy.autoPayBelowMsats && (policy.maxIncrementMsats === 0 || req.amount_msats <= policy.maxIncrementMsats)) {
|
|
11488
|
-
|
|
11489
|
-
|
|
11490
|
-
|
|
11491
|
-
|
|
11834
|
+
let result;
|
|
11835
|
+
try {
|
|
11836
|
+
result = await handlePaymentRequest(jobId, req, policy, transport, provider, {
|
|
11837
|
+
jobToken,
|
|
11838
|
+
requestSeq: lastYield2.seq
|
|
11839
|
+
});
|
|
11840
|
+
} catch (error) {
|
|
11841
|
+
if (error instanceof DvmError && error.code === "payment_settling") {
|
|
11842
|
+
paymentUnresolved = true;
|
|
11843
|
+
break;
|
|
11844
|
+
}
|
|
11845
|
+
if (error instanceof DvmError && error.code === "payment_already_sent") {
|
|
11846
|
+
answeredSeqs.add(lastYield2.seq);
|
|
11847
|
+
break;
|
|
11848
|
+
}
|
|
11849
|
+
throw error;
|
|
11850
|
+
}
|
|
11492
11851
|
if (typeof result === "object") {
|
|
11493
|
-
recordAutoPayment(result, req,
|
|
11852
|
+
recordAutoPayment(result, req, lastYield2.seq);
|
|
11494
11853
|
continue;
|
|
11495
11854
|
}
|
|
11496
11855
|
if (result === "payment-cap-exceeded") {
|
|
@@ -11521,7 +11880,7 @@ async function streamLoop(opts) {
|
|
|
11521
11880
|
let recheck = [];
|
|
11522
11881
|
try {
|
|
11523
11882
|
if (pollOptions) {
|
|
11524
|
-
recheck = await transport.getMessages(jobId, cursor, provider, pollOptions);
|
|
11883
|
+
recheck = (await transport.getMessages(jobId, cursor, provider, pollOptions)).filter((message2) => message2.seq > cursor);
|
|
11525
11884
|
}
|
|
11526
11885
|
} catch (err) {
|
|
11527
11886
|
if (deadline === void 0 || !isMessagePollTimeout(err)) throw err;
|
|
@@ -11537,17 +11896,24 @@ async function streamLoop(opts) {
|
|
|
11537
11896
|
}
|
|
11538
11897
|
}
|
|
11539
11898
|
}
|
|
11540
|
-
|
|
11541
|
-
|
|
11542
|
-
|
|
11543
|
-
|
|
11899
|
+
if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
|
|
11900
|
+
for (const seq of answeredYieldSeqs(allMessages)) answeredSeqs.add(seq);
|
|
11901
|
+
const terminal = allMessages.some((msg) => msg.type === "complete" || msg.type === "cancel");
|
|
11902
|
+
const yieldAction = computeNextAction(jobId, allMessages.filter((message2) => !answeredSeqs.has(message2.seq))) ?? (terminal ? null : pendingAction);
|
|
11903
|
+
let nextAction = withRefundNextAction(jobId, yieldAction ?? (terminal ? null : pollNextAction(jobId)), refunds);
|
|
11904
|
+
const lastYield = findLastYield(allMessages);
|
|
11905
|
+
if (nextAction?.type === "pay" && lastYield?.type === "payment-request" && persistLocalState && loadJob(jobId)?.inFlightPaymentRequestSeqs?.includes(lastYield.seq))
|
|
11906
|
+
nextAction = { ...nextAction, hint: paymentInFlightHint(jobId) };
|
|
11907
|
+
if (nextAction?.type === "pay" || nextAction?.type === "poll" && !terminal) {
|
|
11908
|
+
if (lastYield?.type === "payment-request" && answeredSeqs.has(lastYield.seq)) {
|
|
11544
11909
|
nextAction = {
|
|
11545
11910
|
type: "poll",
|
|
11546
11911
|
job_id: jobId,
|
|
11547
|
-
hint: `Payment already sent for this request; the provider is finalising.
|
|
11912
|
+
hint: `Payment already sent for this request; the provider is finalising. Keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\` \u2014 do not pay again.`
|
|
11548
11913
|
};
|
|
11549
11914
|
}
|
|
11550
11915
|
}
|
|
11916
|
+
if (paymentUnresolved) nextAction = pollNextAction(jobId, paymentInFlightHint(jobId));
|
|
11551
11917
|
return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
|
|
11552
11918
|
}
|
|
11553
11919
|
function isMessagePollTimeout(err) {
|
|
@@ -11687,12 +12053,12 @@ function parseJobContent(data) {
|
|
|
11687
12053
|
...typeof data.content_available === "boolean" ? { content_available: data.content_available } : {}
|
|
11688
12054
|
};
|
|
11689
12055
|
}
|
|
11690
|
-
function jobContentFields(jobId, observed) {
|
|
12056
|
+
function jobContentFields(jobId, observed, human = false) {
|
|
11691
12057
|
const metadata = parseJobContent(observed ?? {});
|
|
11692
12058
|
const known = metadata.content_expires_at !== void 0 && metadata.content_available !== void 0;
|
|
11693
12059
|
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.";
|
|
11694
12060
|
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.";
|
|
11695
|
-
const save = metadata.content_available === false ? `Check existing local saves and 'dvm receipts verify ${jobId}' for stored receipt evidence.` : `Save message output with 'dvm messages ${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.`;
|
|
12061
|
+
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.`;
|
|
11696
12062
|
return {
|
|
11697
12063
|
...metadata,
|
|
11698
12064
|
content_metadata_source: observed ? "provider" : "unknown",
|
|
@@ -12039,7 +12405,8 @@ var HttpsTransport = class {
|
|
|
12039
12405
|
jobToken,
|
|
12040
12406
|
...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {},
|
|
12041
12407
|
...feedbackClaim ? { feedbackClaim } : {},
|
|
12042
|
-
...parseFundingResponse(data)
|
|
12408
|
+
...parseFundingResponse(data),
|
|
12409
|
+
upfrontPayment: parseUpfrontPayment(data.upfront_payment)
|
|
12043
12410
|
};
|
|
12044
12411
|
}
|
|
12045
12412
|
return {
|
|
@@ -12054,7 +12421,8 @@ var HttpsTransport = class {
|
|
|
12054
12421
|
...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {},
|
|
12055
12422
|
...feedbackClaim ? { feedbackClaim } : {},
|
|
12056
12423
|
...parseSignedReceipt(data.receipt),
|
|
12057
|
-
...parseFundingResponse(data)
|
|
12424
|
+
...parseFundingResponse(data),
|
|
12425
|
+
upfrontPayment: parseUpfrontPayment(data.upfront_payment)
|
|
12058
12426
|
};
|
|
12059
12427
|
}
|
|
12060
12428
|
async requestResult(provider, requestId, signedJob) {
|
|
@@ -12300,6 +12668,21 @@ var HttpsTransport = class {
|
|
|
12300
12668
|
}
|
|
12301
12669
|
}
|
|
12302
12670
|
async sendMessage(jobId, message2, provider, options) {
|
|
12671
|
+
try {
|
|
12672
|
+
return await this.sendMessageWithSignal(
|
|
12673
|
+
jobId,
|
|
12674
|
+
message2,
|
|
12675
|
+
provider,
|
|
12676
|
+
options,
|
|
12677
|
+
message2.type === "payment" ? AbortSignal.timeout(6e4) : void 0
|
|
12678
|
+
);
|
|
12679
|
+
} catch (error) {
|
|
12680
|
+
if (isAbortError(error) && message2.type === "payment")
|
|
12681
|
+
throw new DvmError("timeout", "Payment send timed out.");
|
|
12682
|
+
throw error;
|
|
12683
|
+
}
|
|
12684
|
+
}
|
|
12685
|
+
async sendMessageWithSignal(jobId, message2, provider, options, signal) {
|
|
12303
12686
|
const endpoint = provider?.endpoint;
|
|
12304
12687
|
if (!endpoint) {
|
|
12305
12688
|
throw new DvmError(
|
|
@@ -12309,24 +12692,18 @@ var HttpsTransport = class {
|
|
|
12309
12692
|
}
|
|
12310
12693
|
const url = `${endpoint}/v1/job/${jobId}/messages`;
|
|
12311
12694
|
const body = JSON.stringify({ type: message2.type, content: message2.content });
|
|
12312
|
-
|
|
12313
|
-
|
|
12314
|
-
|
|
12315
|
-
|
|
12316
|
-
|
|
12317
|
-
|
|
12318
|
-
});
|
|
12319
|
-
} catch (err) {
|
|
12320
|
-
if (isAbortError(err)) {
|
|
12321
|
-
throw new DvmError("timeout", "sendMessage timed out.");
|
|
12322
|
-
}
|
|
12323
|
-
throw err;
|
|
12324
|
-
}
|
|
12695
|
+
const res = await dvmFetch(url, {
|
|
12696
|
+
method: "POST",
|
|
12697
|
+
headers: { "Content-Type": "application/json", ...jobTokenHeader(options?.jobToken) },
|
|
12698
|
+
body,
|
|
12699
|
+
signal
|
|
12700
|
+
});
|
|
12325
12701
|
if (res.status === 402) {
|
|
12326
12702
|
let errorBody;
|
|
12327
12703
|
try {
|
|
12328
12704
|
errorBody = await res.json();
|
|
12329
|
-
} catch {
|
|
12705
|
+
} catch (error2) {
|
|
12706
|
+
if (isAbortError(error2)) throw error2;
|
|
12330
12707
|
throw new DvmError("payment_insufficient", "Payment required (unparseable response).");
|
|
12331
12708
|
}
|
|
12332
12709
|
const error = withDrawFunding(withCreditErrorContext(buildPaymentError(errorBody), errorBody), errorBody);
|
|
@@ -12335,8 +12712,11 @@ var HttpsTransport = class {
|
|
|
12335
12712
|
}
|
|
12336
12713
|
if (res.status === 409) {
|
|
12337
12714
|
const body2 = parseJsonObject(await res.text());
|
|
12338
|
-
if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string"))
|
|
12339
|
-
|
|
12715
|
+
if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string")) {
|
|
12716
|
+
const error = withDrawFunding(withCreditErrorContext(buildPaymentError(body2), body2), body2);
|
|
12717
|
+
error.data = { ...error.data, http_status: res.status };
|
|
12718
|
+
throw error;
|
|
12719
|
+
}
|
|
12340
12720
|
throw new DvmError(
|
|
12341
12721
|
"job_terminal",
|
|
12342
12722
|
"Job is no longer active.",
|
|
@@ -12348,7 +12728,9 @@ var HttpsTransport = class {
|
|
|
12348
12728
|
const structured = parseStructuredError(text);
|
|
12349
12729
|
if (structured) {
|
|
12350
12730
|
const body2 = parseJsonObject(text) ?? {};
|
|
12351
|
-
|
|
12731
|
+
const error = withDrawFunding(withCreditErrorContext(structured, body2), body2);
|
|
12732
|
+
error.data = { ...error.data, http_status: res.status };
|
|
12733
|
+
throw error;
|
|
12352
12734
|
}
|
|
12353
12735
|
throw providerResponseError("provider_error", `sendMessage failed (${res.status}): ${text}`);
|
|
12354
12736
|
}
|
|
@@ -12538,7 +12920,8 @@ function parseRequestResultResponse(value, requestId, httpStatus) {
|
|
|
12538
12920
|
...data.payload_in === "summary" || data.payload_in === "messages" ? { payloadIn: data.payload_in } : {},
|
|
12539
12921
|
...typeof data.job_token === "string" ? { jobToken: data.job_token } : {},
|
|
12540
12922
|
...receipt ? { receipt } : {},
|
|
12541
|
-
...parseFundingResponse(data)
|
|
12923
|
+
...parseFundingResponse(data),
|
|
12924
|
+
upfrontPayment: parseUpfrontPayment(data.upfront_payment)
|
|
12542
12925
|
};
|
|
12543
12926
|
}
|
|
12544
12927
|
function malformedRequestResult(requestId, reason) {
|
|
@@ -13226,19 +13609,19 @@ function resolveCapability(info2, requested, dvmId) {
|
|
|
13226
13609
|
}
|
|
13227
13610
|
if (requested !== void 0) {
|
|
13228
13611
|
if (caps.includes(requested)) return requested;
|
|
13229
|
-
const list2 = dvmId ? caps.map((c) => `${dvmId}/${c}`).join(", ") : caps.join(", ");
|
|
13230
13612
|
throw new DvmError(
|
|
13231
13613
|
"unknown_capability",
|
|
13232
13614
|
`"${requested}" is not a capability of ${reference}.`,
|
|
13233
|
-
dvmId ? `
|
|
13615
|
+
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.",
|
|
13616
|
+
{ available_capabilities: caps, _provider_fields: ["available_capabilities"] }
|
|
13234
13617
|
);
|
|
13235
13618
|
}
|
|
13236
13619
|
if (caps.length === 1) return caps[0];
|
|
13237
|
-
const list = dvmId ? caps.map((c) => `${dvmId}/${c}`).join(", ") : caps.join(", ");
|
|
13238
13620
|
throw new DvmError(
|
|
13239
13621
|
"ambiguous_capability",
|
|
13240
|
-
|
|
13241
|
-
dvmId ? `Pass -d ${dvmId}/<capability>
|
|
13622
|
+
`${reference} has multiple capabilities; specify one from available_capabilities.`,
|
|
13623
|
+
dvmId ? `Pass -d ${dvmId}/<capability> using a name from available_capabilities.` : "Run `dvm search` to find a qualified identifier for the capability you need.",
|
|
13624
|
+
{ available_capabilities: caps, _provider_fields: ["available_capabilities"] }
|
|
13242
13625
|
);
|
|
13243
13626
|
}
|
|
13244
13627
|
|
|
@@ -13258,6 +13641,7 @@ async function cancel(jobId, opts) {
|
|
|
13258
13641
|
}
|
|
13259
13642
|
async function cancelWithAccess(jobId, opts, access) {
|
|
13260
13643
|
const { stored, ref, jobToken } = access;
|
|
13644
|
+
const json2 = (data) => providerJobJson(data, !!stored);
|
|
13261
13645
|
const transport = createDvmTransport();
|
|
13262
13646
|
progressNotice("Cancelling job...", opts.human);
|
|
13263
13647
|
await transport.cancel(jobId, opts.reason, ref, { jobToken });
|
|
@@ -13267,7 +13651,7 @@ async function cancelWithAccess(jobId, opts, access) {
|
|
|
13267
13651
|
if (opts.human) {
|
|
13268
13652
|
info(`Job ${jobId}${identifier ? ` [${identifier}]` : ""} cancelled.`);
|
|
13269
13653
|
} else {
|
|
13270
|
-
|
|
13654
|
+
json2({
|
|
13271
13655
|
jobId,
|
|
13272
13656
|
...dvmIdentity(stored?.dvmId, stored?.capability),
|
|
13273
13657
|
status: "cancelled",
|
|
@@ -13480,14 +13864,14 @@ async function confirmRollback(stored, preview, opts) {
|
|
|
13480
13864
|
async function withStrandingChecked(removing, commit) {
|
|
13481
13865
|
const leaving = new Set(removing.map((target) => target.split(".")[0]));
|
|
13482
13866
|
if (leaving.has("tempo")) {
|
|
13483
|
-
const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-
|
|
13867
|
+
const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-LGGBDCKK.js");
|
|
13484
13868
|
await assertTempoWalletIdle2("disconnect");
|
|
13485
13869
|
}
|
|
13486
13870
|
if (!leaving.has("x402")) return commit();
|
|
13487
|
-
const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-
|
|
13488
|
-
const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-
|
|
13489
|
-
const { ensureAddress: ensureAddress2 } = await import("./internal-
|
|
13490
|
-
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-
|
|
13871
|
+
const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-ZZHCUKOM.js");
|
|
13872
|
+
const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-XGNIMPTB.js");
|
|
13873
|
+
const { ensureAddress: ensureAddress2 } = await import("./internal-ZZHCUKOM.js");
|
|
13874
|
+
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UJ7EJNQA.js");
|
|
13491
13875
|
return withX402ChannelLock2(async () => {
|
|
13492
13876
|
const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
|
|
13493
13877
|
if (unsettled.length > 0) {
|
|
@@ -13915,7 +14299,7 @@ function creditDrainCommand(handle, creditId) {
|
|
|
13915
14299
|
}
|
|
13916
14300
|
|
|
13917
14301
|
// src/commands/wallet-history.ts
|
|
13918
|
-
import { createHash } from "crypto";
|
|
14302
|
+
import { createHash as createHash2 } from "crypto";
|
|
13919
14303
|
|
|
13920
14304
|
// src/lib/completed-credit-history.ts
|
|
13921
14305
|
function completedCreditHistory(query = {}) {
|
|
@@ -14060,7 +14444,7 @@ function walletHistory(opts, now = /* @__PURE__ */ new Date()) {
|
|
|
14060
14444
|
const windowed = (sinceMs === null ? all : all.filter((e) => e.timestamp >= sinceMs)).slice().sort(
|
|
14061
14445
|
(a, b) => b.timestamp - a.timestamp || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0)
|
|
14062
14446
|
);
|
|
14063
|
-
const fingerprint =
|
|
14447
|
+
const fingerprint = createHash2("sha256").update(JSON.stringify(windowed)).digest("hex");
|
|
14064
14448
|
if (continuation && continuation.fingerprint !== fingerprint) {
|
|
14065
14449
|
throw invalidHistoryCursor();
|
|
14066
14450
|
}
|
|
@@ -17409,7 +17793,13 @@ async function describe(input, opts) {
|
|
|
17409
17793
|
if (providerInfo.name !== void 0) wrapped.name = asProviderTextOpt(providerInfo.name);
|
|
17410
17794
|
if (providerInfo.about !== void 0) wrapped.about = asProviderTextOpt(providerInfo.about);
|
|
17411
17795
|
if (providerInfo.tags) wrapped.tags = providerInfo.tags.map((t) => asProviderText(t));
|
|
17412
|
-
|
|
17796
|
+
if (providerInfo.capabilities) {
|
|
17797
|
+
wrapped.capabilities = Object.fromEntries(Object.entries(providerInfo.capabilities).map(([name, capability]) => [
|
|
17798
|
+
name,
|
|
17799
|
+
{ ...capability, ...capability.description !== void 0 ? { description: asProviderText(capability.description) } : {} }
|
|
17800
|
+
]));
|
|
17801
|
+
}
|
|
17802
|
+
json({ endpoint, ...providerFields(wrapped) });
|
|
17413
17803
|
}
|
|
17414
17804
|
transport.close();
|
|
17415
17805
|
}
|
|
@@ -17854,8 +18244,8 @@ async function probeX402(x402, timeoutMs) {
|
|
|
17854
18244
|
let network;
|
|
17855
18245
|
let address;
|
|
17856
18246
|
try {
|
|
17857
|
-
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-
|
|
17858
|
-
const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-
|
|
18247
|
+
const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UJ7EJNQA.js");
|
|
18248
|
+
const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-ZZHCUKOM.js");
|
|
17859
18249
|
const wallet = loadX402Wallet2();
|
|
17860
18250
|
if (!wallet) {
|
|
17861
18251
|
const storedKey = x402.privateKey;
|
|
@@ -17907,8 +18297,8 @@ async function probeMpp(mpp, timeoutMs) {
|
|
|
17907
18297
|
if (!mpp) return null;
|
|
17908
18298
|
if (mpp.method === "tempo") {
|
|
17909
18299
|
try {
|
|
17910
|
-
const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-
|
|
17911
|
-
const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-
|
|
18300
|
+
const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-PLFC443A.js");
|
|
18301
|
+
const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-ZZHCUKOM.js");
|
|
17912
18302
|
const account = await connectedTempoAccount2();
|
|
17913
18303
|
if (!account) {
|
|
17914
18304
|
return {
|
|
@@ -18252,9 +18642,9 @@ function checkSecretDirectory(dir, row) {
|
|
|
18252
18642
|
const offenders = [];
|
|
18253
18643
|
for (const name of readdirSync2(dir)) {
|
|
18254
18644
|
const path = join4(dir, name);
|
|
18255
|
-
const
|
|
18256
|
-
if (!
|
|
18257
|
-
const mode =
|
|
18645
|
+
const stat2 = statSync3(path);
|
|
18646
|
+
if (!stat2.isFile()) continue;
|
|
18647
|
+
const mode = stat2.mode & 511;
|
|
18258
18648
|
if (mode !== 384) offenders.push({ path, modeOctal: octalMode(mode) });
|
|
18259
18649
|
}
|
|
18260
18650
|
row.modeOk = offenders.length === 0;
|
|
@@ -18297,12 +18687,12 @@ function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
|
|
|
18297
18687
|
}
|
|
18298
18688
|
return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
|
|
18299
18689
|
const path = join5(dir, name);
|
|
18300
|
-
const
|
|
18301
|
-
if (!
|
|
18302
|
-
const ageMs2 = Math.max(0, nowMs -
|
|
18690
|
+
const stat2 = statSync4(path);
|
|
18691
|
+
if (!stat2.isFile()) return null;
|
|
18692
|
+
const ageMs2 = Math.max(0, nowMs - stat2.mtimeMs);
|
|
18303
18693
|
return {
|
|
18304
18694
|
path,
|
|
18305
|
-
modifiedAt:
|
|
18695
|
+
modifiedAt: stat2.mtime.toISOString(),
|
|
18306
18696
|
ageMs: ageMs2,
|
|
18307
18697
|
ageDays: Math.floor(ageMs2 / (24 * 60 * 60 * 1e3)),
|
|
18308
18698
|
age: formatMnemonicBackupAge(ageMs2)
|
|
@@ -21227,10 +21617,10 @@ function buildCompletionHintFields(jobId, input) {
|
|
|
21227
21617
|
if (hint) out.next_step_hint = hint;
|
|
21228
21618
|
return out;
|
|
21229
21619
|
}
|
|
21230
|
-
function nextStepHint(jobId, payloadIn, artifactCount) {
|
|
21620
|
+
function nextStepHint(jobId, payloadIn, artifactCount, human = false) {
|
|
21231
21621
|
if (payloadIn !== "messages") return void 0;
|
|
21232
21622
|
const noun = artifactCount === 1 ? "artifact" : "artifacts";
|
|
21233
|
-
return `Run 'dvm messages ${jobId} --no-stream' to fetch the ${noun}.`;
|
|
21623
|
+
return `Run 'dvm messages ${human ? shellQuoteArg(jobId) : guidanceJobArg(jobId)} --no-stream' to fetch the ${noun}.`;
|
|
21234
21624
|
}
|
|
21235
21625
|
function completionSnapshot(src) {
|
|
21236
21626
|
const out = {};
|
|
@@ -21283,16 +21673,309 @@ function fullMessageLog(jobId, messages2, afterSeq) {
|
|
|
21283
21673
|
return contiguous ? local : void 0;
|
|
21284
21674
|
}
|
|
21285
21675
|
|
|
21676
|
+
// src/lib/message-human.ts
|
|
21677
|
+
function paymentAmount(msg) {
|
|
21678
|
+
if (msg.from === "requester" && msg.content.credit) {
|
|
21679
|
+
const credit = msg.content.credit;
|
|
21680
|
+
const digits = String(credit.amount_micro).padStart(7, "0");
|
|
21681
|
+
const fraction = digits.slice(-6).replace(/0+$/, "");
|
|
21682
|
+
const amount = digits.slice(0, -6) + (fraction ? `.${fraction}` : "");
|
|
21683
|
+
return `${amount} ${credit.currency.toUpperCase()} from prepaid balance`;
|
|
21684
|
+
}
|
|
21685
|
+
return formatAmountBestEffort(msg.content.amount_msats);
|
|
21686
|
+
}
|
|
21687
|
+
function formatMessageHuman(msg, jobId, artifactSession) {
|
|
21688
|
+
const { seq, type } = msg;
|
|
21689
|
+
const prefix = msg.from === "provider" ? "Provider" : "You";
|
|
21690
|
+
if (msg.type !== "progress") finalizeProgressLine();
|
|
21691
|
+
switch (msg.type) {
|
|
21692
|
+
case "text":
|
|
21693
|
+
info(`[${msg.seq}] ${prefix}: ${msg.content.text}`);
|
|
21694
|
+
break;
|
|
21695
|
+
case "prompt":
|
|
21696
|
+
info(`[${msg.seq}] ${prefix} asks: ${msg.content.text}`);
|
|
21697
|
+
if (msg.content.options) {
|
|
21698
|
+
for (const opt of msg.content.options) {
|
|
21699
|
+
info(` - ${opt}`);
|
|
21700
|
+
}
|
|
21701
|
+
}
|
|
21702
|
+
break;
|
|
21703
|
+
case "response":
|
|
21704
|
+
info(msg.content.text ? `[${msg.seq}] ${prefix} answered: ${msg.content.text}${msg.content.data ? " (with structured data)" : ""}` : `[${msg.seq}] ${prefix} sent a structured answer.`);
|
|
21705
|
+
break;
|
|
21706
|
+
case "approval":
|
|
21707
|
+
info(`[${msg.seq}] ${prefix} approved${msg.content.ref_seq !== void 0 ? ` message ${msg.content.ref_seq}` : " the job"}${msg.content.comment ? `: ${msg.content.comment}` : ""}`);
|
|
21708
|
+
break;
|
|
21709
|
+
case "artifact": {
|
|
21710
|
+
const label = msg.content.name ?? msg.content.mime_type ?? "unknown type";
|
|
21711
|
+
if (jobId) {
|
|
21712
|
+
const saved = saveArtifact(msg.content, artifactSession ?? createArtifactSaveSession());
|
|
21713
|
+
if (saved) {
|
|
21714
|
+
info(
|
|
21715
|
+
`[${msg.seq}] ${prefix} sent artifact: ${label} (${saved.bytes.toLocaleString()} bytes \u2192 ${saved.path})`
|
|
21716
|
+
);
|
|
21717
|
+
break;
|
|
21718
|
+
}
|
|
21719
|
+
}
|
|
21720
|
+
info(`[${msg.seq}] ${prefix} sent artifact: ${label}`);
|
|
21721
|
+
break;
|
|
21722
|
+
}
|
|
21723
|
+
case "payment-request":
|
|
21724
|
+
info(
|
|
21725
|
+
`[${msg.seq}] ${prefix} requests ${formatPaymentAmount(msg.content.amount_msats, msg.content.fiat_amount, { anchor: false })}${msg.content.reason ? `: ${msg.content.reason}` : ""}`
|
|
21726
|
+
);
|
|
21727
|
+
break;
|
|
21728
|
+
case "payment": {
|
|
21729
|
+
const amount = paymentAmount(msg);
|
|
21730
|
+
if (msg.from === "provider") {
|
|
21731
|
+
const noun = msg.content.reason === "change" ? "change" : "refund";
|
|
21732
|
+
info(`[${msg.seq}] ${prefix} sent ${noun}: ${amount}`);
|
|
21733
|
+
} else {
|
|
21734
|
+
info(`[${msg.seq}] ${prefix} paid: ${amount}`);
|
|
21735
|
+
}
|
|
21736
|
+
break;
|
|
21737
|
+
}
|
|
21738
|
+
case "complete":
|
|
21739
|
+
info(`[${msg.seq}] Job complete${msg.content.summary ? `: ${msg.content.summary}` : ""}`);
|
|
21740
|
+
break;
|
|
21741
|
+
case "working":
|
|
21742
|
+
info(
|
|
21743
|
+
`[${msg.seq}] Provider is working${msg.content.estimate_seconds ? ` (est. ${String(msg.content.estimate_seconds)}s)` : ""}${msg.content.hint ? `: ${msg.content.hint}` : ""}`
|
|
21744
|
+
);
|
|
21745
|
+
break;
|
|
21746
|
+
case "progress":
|
|
21747
|
+
renderProgressLine(msg.content, msg.seq);
|
|
21748
|
+
break;
|
|
21749
|
+
case "cancel":
|
|
21750
|
+
info(`[${msg.seq}] Cancelled${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
|
|
21751
|
+
break;
|
|
21752
|
+
default:
|
|
21753
|
+
info(`[${seq}] ${prefix} sent a message of type "${type}".`);
|
|
21754
|
+
}
|
|
21755
|
+
}
|
|
21756
|
+
|
|
21757
|
+
// src/lib/next-action-human.ts
|
|
21758
|
+
function nextActionHuman(action) {
|
|
21759
|
+
if (!action) return null;
|
|
21760
|
+
switch (action.type) {
|
|
21761
|
+
case "respond":
|
|
21762
|
+
case "pay": {
|
|
21763
|
+
const display = action.display.replace(/`dvm status '<job_id>'`/g, () => `\`dvm status ${shellQuoteArg(action.job_id)}\``);
|
|
21764
|
+
const template = action.hint.match(/`(dvm[\s\S]*)`/)?.[1]?.replace(/^(dvm (?:message|pay|status)) '<job_id>'/, (_, prefix) => `${prefix} ${shellQuoteArg(action.job_id)}`);
|
|
21765
|
+
const command = action.type === "respond" ? template?.replace("--prompt-id '<prompt_id>'", () => `--prompt-id ${shellQuoteArg(action.prompt_id)}`) : template;
|
|
21766
|
+
if (command?.startsWith("dvm status ")) return `Next: ${action.type === "pay" ? "the provider's charge of " : ""}${display}`;
|
|
21767
|
+
if (action.type === "respond") {
|
|
21768
|
+
return `Next: ${display} Provider is waiting for your input. ${command ? `Run \`${command}\`.` : action.hint}`;
|
|
21769
|
+
}
|
|
21770
|
+
return `Next: Payment required to continue: ${display}${display.endsWith(".") ? "" : "."} Run \`${command ?? `dvm pay ${shellQuoteArg(action.job_id)}`}\`.`;
|
|
21771
|
+
}
|
|
21772
|
+
case "poll": {
|
|
21773
|
+
const hint = typeof action.hint === "string" ? action.hint : action.hint.text;
|
|
21774
|
+
const detail = hint === pollNextAction(action.job_id).hint || hint === "Job submitted, check back for updates" ? "" : hint.trim();
|
|
21775
|
+
const sentence = detail ? `Provider is still working: ${detail}${/[.!?]$/.test(detail) ? "" : "."}` : "Provider is still working.";
|
|
21776
|
+
return `Next: ${sentence} Keep watching with \`dvm messages ${shellQuoteArg(action.job_id)}\`.`;
|
|
21777
|
+
}
|
|
21778
|
+
case "refund":
|
|
21779
|
+
return action.claimed ? null : `Next: ${refundSummaryHuman(action)}`;
|
|
21780
|
+
case "approve":
|
|
21781
|
+
return `Next: ${action.hint}`;
|
|
21782
|
+
}
|
|
21783
|
+
}
|
|
21784
|
+
function printNextActionHuman(action, options = {}) {
|
|
21785
|
+
const line = nextActionHuman(options.terminal ? null : action);
|
|
21786
|
+
const refunds = options.refunds ?? [];
|
|
21787
|
+
for (const [index, claim] of refunds.entries()) {
|
|
21788
|
+
if (line && action?.type === "refund" && !action.claimed && index === refunds.length - 1) continue;
|
|
21789
|
+
info(refundSummaryHuman(claim));
|
|
21790
|
+
}
|
|
21791
|
+
if (line) info(line);
|
|
21792
|
+
}
|
|
21793
|
+
|
|
21794
|
+
// src/lib/wait-for-job.ts
|
|
21795
|
+
async function waitForJob(opts, durationMs, now = Date.now) {
|
|
21796
|
+
const deadline = now() + durationMs;
|
|
21797
|
+
const result = {
|
|
21798
|
+
messages: [],
|
|
21799
|
+
autoPayments: [],
|
|
21800
|
+
refunds: [],
|
|
21801
|
+
cursor: opts.afterSeq,
|
|
21802
|
+
nextAction: pollNextAction(opts.jobId)
|
|
21803
|
+
};
|
|
21804
|
+
const returnedSeqs = /* @__PURE__ */ new Set();
|
|
21805
|
+
const emittedSeqs = /* @__PURE__ */ new Set();
|
|
21806
|
+
const collectMessages = (messages2) => {
|
|
21807
|
+
for (const message2 of messages2) if (!returnedSeqs.has(message2.seq)) {
|
|
21808
|
+
returnedSeqs.add(message2.seq);
|
|
21809
|
+
result.messages.push(message2);
|
|
21810
|
+
}
|
|
21811
|
+
};
|
|
21812
|
+
const onMessage = (message2) => {
|
|
21813
|
+
if (emittedSeqs.has(message2.seq)) return;
|
|
21814
|
+
emittedSeqs.add(message2.seq);
|
|
21815
|
+
opts.onMessage?.(message2);
|
|
21816
|
+
};
|
|
21817
|
+
const messageAppendSession = opts.persistLocalState === false ? void 0 : opts.messageAppendSession ?? createMessageAppendSession(opts.jobId);
|
|
21818
|
+
let backoffMs = 1e3;
|
|
21819
|
+
let firstRead = true;
|
|
21820
|
+
const idleTimeoutMs = opts.timeoutMs ?? JOB_READ_TIMEOUT_MS;
|
|
21821
|
+
async function readWithRetry(read) {
|
|
21822
|
+
while (now() < deadline) {
|
|
21823
|
+
try {
|
|
21824
|
+
return await read();
|
|
21825
|
+
} catch (error) {
|
|
21826
|
+
if (!isAbortError(error) && !(error instanceof DvmError && error.code === "timeout")) throw error;
|
|
21827
|
+
await new Promise((resolve3) => setTimeout(resolve3, Math.min(backoffMs, Math.max(0, deadline - now()))));
|
|
21828
|
+
backoffMs = Math.min(backoffMs * 2, 3e4);
|
|
21829
|
+
}
|
|
21830
|
+
}
|
|
21831
|
+
return void 0;
|
|
21832
|
+
}
|
|
21833
|
+
while (now() < deadline) {
|
|
21834
|
+
const readOptions = () => ({ jobToken: opts.jobToken, timeoutMs: Math.max(1, Math.min(idleTimeoutMs, deadline - now())) });
|
|
21835
|
+
const snapshot = await readWithRetry(() => opts.transport.status(opts.jobId, opts.provider, readOptions()));
|
|
21836
|
+
if (!snapshot) break;
|
|
21837
|
+
if (isTerminalJobStatus(snapshot.status)) {
|
|
21838
|
+
result.nextAction = null;
|
|
21839
|
+
const history = await readWithRetry(() => opts.transport.getMessages(opts.jobId, result.cursor, opts.provider, readOptions()));
|
|
21840
|
+
if (!history) break;
|
|
21841
|
+
const tail = history.filter((message2) => message2.seq > result.cursor);
|
|
21842
|
+
collectMessages(tail);
|
|
21843
|
+
result.cursor = maxSeq(tail, result.cursor);
|
|
21844
|
+
for (const message2 of tail) onMessage(message2);
|
|
21845
|
+
if (opts.persistLocalState !== false) {
|
|
21846
|
+
messageAppendSession?.append(tail);
|
|
21847
|
+
result.refunds.push(...await claimInboundPayments(opts.jobId, tail));
|
|
21848
|
+
}
|
|
21849
|
+
result.nextAction = withRefundNextAction(opts.jobId, null, result.refunds);
|
|
21850
|
+
break;
|
|
21851
|
+
}
|
|
21852
|
+
const inFlight2 = opts.persistLocalState === false ? [] : loadJob(opts.jobId)?.inFlightPaymentRequestSeqs ?? [];
|
|
21853
|
+
let cursorLimit = Infinity;
|
|
21854
|
+
let streamAfter = result.cursor;
|
|
21855
|
+
if (inFlight2.length || firstRead && !opts.afterSeqExplicit && snapshot.status === "awaiting-input") {
|
|
21856
|
+
let unresolved = false;
|
|
21857
|
+
let retryDelayMs = backoffMs;
|
|
21858
|
+
let history;
|
|
21859
|
+
try {
|
|
21860
|
+
history = await readWithRetry(() => withJobPaymentLock(opts.jobId, async (assertOwned) => {
|
|
21861
|
+
const messages2 = await opts.transport.getMessages(opts.jobId, 0, opts.provider, readOptions());
|
|
21862
|
+
assertOwned();
|
|
21863
|
+
for (const seq of loadJob(opts.jobId)?.inFlightPaymentRequestSeqs ?? []) {
|
|
21864
|
+
try {
|
|
21865
|
+
reconcilePaymentRequestHistory(opts.jobId, seq, messages2, snapshot.status, now);
|
|
21866
|
+
} catch (error) {
|
|
21867
|
+
if (!(error instanceof DvmError) || !["payment_settling", "payment_request_not_pending"].includes(error.code)) throw error;
|
|
21868
|
+
if (!loadJob(opts.jobId)?.inFlightPaymentRequestSeqs?.includes(seq)) continue;
|
|
21869
|
+
unresolved = true;
|
|
21870
|
+
cursorLimit = Math.min(cursorLimit, seq - 1);
|
|
21871
|
+
if (typeof error.data?.retry_at_ms === "number")
|
|
21872
|
+
retryDelayMs = Math.min(retryDelayMs, Math.max(1, error.data.retry_at_ms - now()));
|
|
21873
|
+
}
|
|
21874
|
+
}
|
|
21875
|
+
return messages2;
|
|
21876
|
+
}));
|
|
21877
|
+
} catch (error) {
|
|
21878
|
+
if (!(error instanceof DvmError) || error.code !== "payment_settling") throw error;
|
|
21879
|
+
unresolved = true;
|
|
21880
|
+
cursorLimit = Math.min(...inFlight2.map((seq) => seq - 1));
|
|
21881
|
+
history = await readWithRetry(() => opts.transport.getMessages(opts.jobId, 0, opts.provider, readOptions()));
|
|
21882
|
+
}
|
|
21883
|
+
if (!history) break;
|
|
21884
|
+
messageAppendSession?.append(history);
|
|
21885
|
+
const answered = opts.persistLocalState === false ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(opts.jobId);
|
|
21886
|
+
for (const seq of answeredYieldSeqs(history)) answered.add(seq);
|
|
21887
|
+
const pending4 = history.findLast((msg) => msg.from === "provider" && ["prompt", "payment-request", "working", "complete", "cancel"].includes(msg.type) && !answered.has(msg.seq));
|
|
21888
|
+
const newerYield = snapshot.status === "awaiting-input" && pending4 && !answered.has(pending4.seq) && (pending4.type === "prompt" || pending4.type === "payment-request") && !inFlight2.includes(pending4.seq);
|
|
21889
|
+
if (unresolved) {
|
|
21890
|
+
const limit = newerYield ? pending4.seq - 1 : Infinity;
|
|
21891
|
+
const tail = history.filter((message2) => message2.seq > Math.max(opts.afterSeq, result.cursor) && message2.seq <= limit);
|
|
21892
|
+
collectMessages(tail);
|
|
21893
|
+
result.cursor = Math.min(maxSeq(tail, result.cursor), cursorLimit);
|
|
21894
|
+
for (const message2 of tail) onMessage(message2);
|
|
21895
|
+
if (opts.persistLocalState !== false)
|
|
21896
|
+
result.refunds.push(...await claimInboundPayments(opts.jobId, tail));
|
|
21897
|
+
}
|
|
21898
|
+
if (unresolved && !newerYield) {
|
|
21899
|
+
result.nextAction = pollNextAction(opts.jobId);
|
|
21900
|
+
await new Promise((resolve3) => setTimeout(resolve3, Math.min(retryDelayMs, Math.max(0, deadline - now()))));
|
|
21901
|
+
backoffMs = Math.min(backoffMs * 2, 3e4);
|
|
21902
|
+
continue;
|
|
21903
|
+
}
|
|
21904
|
+
streamAfter = result.cursor;
|
|
21905
|
+
if (unresolved && newerYield) streamAfter = pending4.seq - 1;
|
|
21906
|
+
if (pending4 && !answered.has(pending4.seq) && (!opts.afterSeqExplicit || inFlight2.includes(pending4.seq)) && (pending4.type === "prompt" || pending4.type === "payment-request"))
|
|
21907
|
+
streamAfter = Math.min(streamAfter, pending4.seq - 1);
|
|
21908
|
+
}
|
|
21909
|
+
firstRead = false;
|
|
21910
|
+
if (now() >= deadline) break;
|
|
21911
|
+
const next = await streamLoop({
|
|
21912
|
+
...opts,
|
|
21913
|
+
onMessage,
|
|
21914
|
+
messageAppendSession,
|
|
21915
|
+
afterSeq: streamAfter,
|
|
21916
|
+
timeoutMs: readOptions().timeoutMs
|
|
21917
|
+
});
|
|
21918
|
+
collectMessages(next.messages);
|
|
21919
|
+
result.autoPayments.push(...next.autoPayments);
|
|
21920
|
+
result.refunds.push(...next.refunds);
|
|
21921
|
+
const progressed = next.cursor > result.cursor;
|
|
21922
|
+
result.cursor = Math.min(next.cursor, cursorLimit);
|
|
21923
|
+
result.nextAction = next.nextAction;
|
|
21924
|
+
if (next.nextAction?.type !== "poll") break;
|
|
21925
|
+
if (progressed) backoffMs = 1e3;
|
|
21926
|
+
const delay = Math.min(backoffMs, Math.max(0, deadline - now()));
|
|
21927
|
+
if (delay > 0) await new Promise((resolve3) => setTimeout(resolve3, delay));
|
|
21928
|
+
backoffMs = Math.min(backoffMs * 2, 3e4);
|
|
21929
|
+
}
|
|
21930
|
+
if (opts.persistLocalState !== false) {
|
|
21931
|
+
const remaining = loadJob(opts.jobId)?.inFlightPaymentRequestSeqs ?? [];
|
|
21932
|
+
result.cursor = Math.min(result.cursor, ...remaining.map((seq) => seq - 1));
|
|
21933
|
+
}
|
|
21934
|
+
result.messages.sort((a, b) => a.seq - b.seq);
|
|
21935
|
+
return result;
|
|
21936
|
+
}
|
|
21937
|
+
|
|
21286
21938
|
// src/commands/messages.ts
|
|
21287
21939
|
async function messages(jobId, opts) {
|
|
21940
|
+
if (opts.until !== void 0 && !opts.wait || opts.wait && opts.stream === false) {
|
|
21941
|
+
throw new DvmError("invalid_arguments", "Use --until with --wait, and --wait with streaming enabled.");
|
|
21942
|
+
}
|
|
21288
21943
|
const access = resolveJobAccess(jobId, opts);
|
|
21289
21944
|
return withJobTokenRedaction(access.jobToken, () => messagesWithAccess(jobId, opts, access));
|
|
21290
21945
|
}
|
|
21291
21946
|
async function messagesWithAccess(jobId, opts, access) {
|
|
21947
|
+
const waitDuration = opts.wait ? parseDurationMs(opts.until ?? "12h") : void 0;
|
|
21292
21948
|
const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
|
|
21293
21949
|
const { stored, ref, jobToken } = access;
|
|
21950
|
+
const json2 = (data) => providerJobJson(data, !!stored);
|
|
21951
|
+
function actionFromMessages(batch) {
|
|
21952
|
+
const answered = access.endpointOverridden ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(jobId);
|
|
21953
|
+
const action = computeNextAction(jobId, batch.filter((message2) => !answered.has(message2.seq)));
|
|
21954
|
+
const request2 = batch.findLast((message2) => message2.type === "payment-request");
|
|
21955
|
+
if (action?.type === "pay" && request2 && !access.endpointOverridden && stored?.inFlightPaymentRequestSeqs?.includes(request2.seq))
|
|
21956
|
+
return { ...action, hint: paymentInFlightHint(jobId) };
|
|
21957
|
+
return action;
|
|
21958
|
+
}
|
|
21959
|
+
async function resolveNextAction2(action, messages2) {
|
|
21960
|
+
if (action?.type === "refund") return action;
|
|
21961
|
+
if (streamTerminalStatus(messages2) || !access.endpointOverridden && stored && isTerminalJobStatus(stored.status)) return null;
|
|
21962
|
+
if (!opts.human) return action;
|
|
21963
|
+
try {
|
|
21964
|
+
const readOptions = { jobToken, timeoutMs: opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 };
|
|
21965
|
+
const snapshot = await transport.status(jobId, ref, readOptions);
|
|
21966
|
+
if (isTerminalJobStatus(snapshot.status)) return null;
|
|
21967
|
+
if (action && (action.type !== "poll" || messages2.some((message2) => ["prompt", "payment-request", "working"].includes(message2.type)))) return action;
|
|
21968
|
+
if (snapshot.status === "awaiting-input") {
|
|
21969
|
+
const history = await transport.getMessages(jobId, 0, ref, readOptions);
|
|
21970
|
+
return actionFromMessages(history) ?? pollNextAction(jobId);
|
|
21971
|
+
}
|
|
21972
|
+
return action ?? pollNextAction(jobId);
|
|
21973
|
+
} catch {
|
|
21974
|
+
return action ?? pollNextAction(jobId);
|
|
21975
|
+
}
|
|
21976
|
+
}
|
|
21294
21977
|
const transport = createDvmTransport();
|
|
21295
|
-
const isTerminal =
|
|
21978
|
+
const isTerminal = !access.endpointOverridden && !!stored && isTerminalJobStatus(stored.status);
|
|
21296
21979
|
const after = opts.after !== void 0 ? Number(opts.after) : opts.stream === false && isTerminal ? 0 : access.endpointOverridden ? 0 : stored?.messageCursor ?? 0;
|
|
21297
21980
|
if (opts.stream === false) {
|
|
21298
21981
|
const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 5e3;
|
|
@@ -21316,11 +21999,13 @@ async function messagesWithAccess(jobId, opts, access) {
|
|
|
21316
21999
|
persistStreamOutcome({ jobId, messages: msgs, cursor: newCursor, afterSeq: after });
|
|
21317
22000
|
}
|
|
21318
22001
|
const refunds = access.endpointOverridden ? [] : await claimInboundPayments(jobId, msgs);
|
|
21319
|
-
const nextAction =
|
|
22002
|
+
const nextAction = withRefundNextAction(jobId, actionFromMessages(msgs) ?? (streamTerminalStatus(msgs) || isTerminal ? null : pollNextAction(jobId)), refunds);
|
|
21320
22003
|
const content2 = jobContentFields(
|
|
21321
22004
|
jobId,
|
|
21322
|
-
await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken })
|
|
22005
|
+
await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken }),
|
|
22006
|
+
opts.human
|
|
21323
22007
|
);
|
|
22008
|
+
const resolvedAction2 = await resolveNextAction2(nextAction, msgs);
|
|
21324
22009
|
transport.close();
|
|
21325
22010
|
if (opts.human) {
|
|
21326
22011
|
info(String(content2.content_hint));
|
|
@@ -21331,35 +22016,45 @@ async function messagesWithAccess(jobId, opts, access) {
|
|
|
21331
22016
|
formatMessageHuman(msg, jobId, artifactSession);
|
|
21332
22017
|
}
|
|
21333
22018
|
finalizeProgressLine();
|
|
21334
|
-
printRefundSummaryHuman(refunds);
|
|
21335
22019
|
}
|
|
22020
|
+
printNextActionHuman(resolvedAction2, { refunds });
|
|
21336
22021
|
} else {
|
|
21337
|
-
|
|
22022
|
+
json2({
|
|
21338
22023
|
jobId,
|
|
21339
22024
|
...content2,
|
|
21340
22025
|
messages: msgs.map(serialize),
|
|
21341
22026
|
cursor: newCursor,
|
|
21342
|
-
next_action:
|
|
22027
|
+
next_action: resolvedAction2,
|
|
21343
22028
|
...await refundJsonField(refunds)
|
|
21344
22029
|
});
|
|
21345
22030
|
}
|
|
21346
22031
|
return;
|
|
21347
22032
|
}
|
|
21348
22033
|
progressNotice("Streaming messages...", opts.human);
|
|
21349
|
-
const
|
|
22034
|
+
const streamOptions = {
|
|
21350
22035
|
jobId,
|
|
21351
22036
|
transport,
|
|
21352
22037
|
provider: ref,
|
|
21353
22038
|
policy: stored?.policy ?? void 0,
|
|
21354
22039
|
afterSeq: after,
|
|
22040
|
+
afterSeqExplicit: opts.after !== void 0,
|
|
21355
22041
|
jobToken,
|
|
21356
22042
|
persistLocalState: !access.endpointOverridden,
|
|
22043
|
+
timeoutMs: opts.timeout ? Number(opts.timeout) * 1e3 : opts.wait ? 6e4 : 5e3,
|
|
21357
22044
|
...opts.human && {
|
|
21358
22045
|
onMessage: (msg) => {
|
|
21359
22046
|
if (msg.type === "progress") formatMessageHuman(msg);
|
|
21360
22047
|
}
|
|
21361
22048
|
}
|
|
21362
|
-
}
|
|
22049
|
+
};
|
|
22050
|
+
const waitDeadline = waitDuration === void 0 ? void 0 : Date.now() + waitDuration;
|
|
22051
|
+
let result;
|
|
22052
|
+
try {
|
|
22053
|
+
result = opts.wait ? await waitForJob(streamOptions, waitDuration) : await streamLoop(streamOptions);
|
|
22054
|
+
} catch (err) {
|
|
22055
|
+
transport.close();
|
|
22056
|
+
throw err;
|
|
22057
|
+
}
|
|
21363
22058
|
if (!access.endpointOverridden) {
|
|
21364
22059
|
persistStreamOutcome({
|
|
21365
22060
|
jobId,
|
|
@@ -21370,11 +22065,13 @@ async function messagesWithAccess(jobId, opts, access) {
|
|
|
21370
22065
|
}
|
|
21371
22066
|
const content = jobContentFields(
|
|
21372
22067
|
jobId,
|
|
21373
|
-
await observeJobContent(jobId, transport, ref, {
|
|
21374
|
-
timeoutMs: opts.timeout ? Number(opts.timeout) * 1e3 : 5e3,
|
|
22068
|
+
waitDeadline !== void 0 && Date.now() >= waitDeadline ? void 0 : await observeJobContent(jobId, transport, ref, {
|
|
22069
|
+
timeoutMs: waitDeadline === void 0 ? opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now())),
|
|
21375
22070
|
jobToken
|
|
21376
|
-
})
|
|
22071
|
+
}),
|
|
22072
|
+
opts.human
|
|
21377
22073
|
);
|
|
22074
|
+
const resolvedAction = opts.wait ? result.nextAction : await resolveNextAction2(result.nextAction, result.messages);
|
|
21378
22075
|
transport.close();
|
|
21379
22076
|
if (opts.human) {
|
|
21380
22077
|
info(String(content.content_hint));
|
|
@@ -21386,97 +22083,31 @@ async function messagesWithAccess(jobId, opts, access) {
|
|
|
21386
22083
|
formatMessageHuman(msg, jobId, artifactSession);
|
|
21387
22084
|
}
|
|
21388
22085
|
finalizeProgressLine();
|
|
21389
|
-
printRefundSummaryHuman(result.refunds);
|
|
21390
22086
|
}
|
|
22087
|
+
printNextActionHuman(resolvedAction, { refunds: result.refunds });
|
|
21391
22088
|
} else {
|
|
21392
|
-
|
|
22089
|
+
json2({
|
|
21393
22090
|
jobId,
|
|
21394
22091
|
...content,
|
|
21395
22092
|
messages: result.messages.map(serialize),
|
|
21396
22093
|
cursor: result.cursor,
|
|
21397
|
-
next_action:
|
|
22094
|
+
next_action: resolvedAction,
|
|
21398
22095
|
...result.autoPayments.length > 0 ? { auto_payments: result.autoPayments } : {},
|
|
21399
22096
|
...await refundJsonField(result.refunds)
|
|
21400
22097
|
});
|
|
21401
22098
|
}
|
|
21402
22099
|
}
|
|
21403
|
-
function paymentAmount(msg) {
|
|
21404
|
-
if (msg.from === "requester" && msg.content.credit) {
|
|
21405
|
-
const credit = msg.content.credit;
|
|
21406
|
-
const digits = String(credit.amount_micro).padStart(7, "0");
|
|
21407
|
-
const fraction = digits.slice(-6).replace(/0+$/, "");
|
|
21408
|
-
const amount = digits.slice(0, -6) + (fraction ? `.${fraction}` : "");
|
|
21409
|
-
return `${amount} ${credit.currency.toUpperCase()} from prepaid balance`;
|
|
21410
|
-
}
|
|
21411
|
-
return formatAmountBestEffort(msg.content.amount_msats);
|
|
21412
|
-
}
|
|
21413
|
-
function formatMessageHuman(msg, jobId, artifactSession) {
|
|
21414
|
-
const prefix = msg.from === "provider" ? "Provider" : "You";
|
|
21415
|
-
if (msg.type !== "progress") finalizeProgressLine();
|
|
21416
|
-
switch (msg.type) {
|
|
21417
|
-
case "text":
|
|
21418
|
-
info(`[${msg.seq}] ${prefix}: ${msg.content.text}`);
|
|
21419
|
-
break;
|
|
21420
|
-
case "prompt":
|
|
21421
|
-
info(`[${msg.seq}] ${prefix} asks: ${msg.content.text}`);
|
|
21422
|
-
if (msg.content.options) {
|
|
21423
|
-
for (const opt of msg.content.options) {
|
|
21424
|
-
info(` - ${opt}`);
|
|
21425
|
-
}
|
|
21426
|
-
}
|
|
21427
|
-
break;
|
|
21428
|
-
case "artifact": {
|
|
21429
|
-
const label = msg.content.name ?? msg.content.mime_type ?? "unknown type";
|
|
21430
|
-
if (jobId) {
|
|
21431
|
-
const saved = saveArtifact(msg.content, artifactSession ?? createArtifactSaveSession());
|
|
21432
|
-
if (saved) {
|
|
21433
|
-
info(
|
|
21434
|
-
`[${msg.seq}] ${prefix} sent artifact: ${label} (${saved.bytes.toLocaleString()} bytes \u2192 ${saved.path})`
|
|
21435
|
-
);
|
|
21436
|
-
break;
|
|
21437
|
-
}
|
|
21438
|
-
}
|
|
21439
|
-
info(`[${msg.seq}] ${prefix} sent artifact: ${label}`);
|
|
21440
|
-
break;
|
|
21441
|
-
}
|
|
21442
|
-
case "payment-request":
|
|
21443
|
-
info(
|
|
21444
|
-
`[${msg.seq}] ${prefix} requests ${formatPaymentAmount(msg.content.amount_msats, msg.content.fiat_amount, { anchor: false })}${msg.content.reason ? `: ${msg.content.reason}` : ""}`
|
|
21445
|
-
);
|
|
21446
|
-
break;
|
|
21447
|
-
case "payment": {
|
|
21448
|
-
const amount = paymentAmount(msg);
|
|
21449
|
-
if (msg.from === "provider") {
|
|
21450
|
-
const noun = msg.content.reason === "change" ? "change" : "refund";
|
|
21451
|
-
info(`[${msg.seq}] ${prefix} sent ${noun}: ${amount}`);
|
|
21452
|
-
} else {
|
|
21453
|
-
info(`[${msg.seq}] ${prefix} paid: ${amount}`);
|
|
21454
|
-
}
|
|
21455
|
-
break;
|
|
21456
|
-
}
|
|
21457
|
-
case "complete":
|
|
21458
|
-
info(`[${msg.seq}] Job complete${msg.content.summary ? `: ${msg.content.summary}` : ""}`);
|
|
21459
|
-
break;
|
|
21460
|
-
case "working":
|
|
21461
|
-
info(
|
|
21462
|
-
`[${msg.seq}] Provider is working${msg.content.estimate_seconds ? ` (est. ${String(msg.content.estimate_seconds)}s)` : ""}${msg.content.hint ? `: ${msg.content.hint}` : ""}`
|
|
21463
|
-
);
|
|
21464
|
-
break;
|
|
21465
|
-
case "progress":
|
|
21466
|
-
renderProgressLine(msg.content, msg.seq);
|
|
21467
|
-
break;
|
|
21468
|
-
case "cancel":
|
|
21469
|
-
info(`[${msg.seq}] Cancelled${msg.content.reason ? `: ${msg.content.reason}` : ""}`);
|
|
21470
|
-
break;
|
|
21471
|
-
default:
|
|
21472
|
-
info(`[${msg.seq}] ${prefix} [${msg.type}]: ${JSON.stringify(msg.content)}`);
|
|
21473
|
-
}
|
|
21474
|
-
}
|
|
21475
22100
|
function serializeMessageForOutput(msg) {
|
|
21476
22101
|
return serialize(msg);
|
|
21477
22102
|
}
|
|
21478
22103
|
function serialize(msg) {
|
|
21479
|
-
const base = {
|
|
22104
|
+
const base = {
|
|
22105
|
+
seq: msg.seq,
|
|
22106
|
+
from: msg.from,
|
|
22107
|
+
timestamp: msg.timestamp,
|
|
22108
|
+
type: msg.type,
|
|
22109
|
+
...msg.from === "provider" ? { _provider_fields: ["seq", "from", "timestamp", "type", "content"] } : {}
|
|
22110
|
+
};
|
|
21480
22111
|
const fromProvider = msg.from === "provider";
|
|
21481
22112
|
switch (msg.type) {
|
|
21482
22113
|
case "text": {
|
|
@@ -21493,8 +22124,14 @@ function serialize(msg) {
|
|
|
21493
22124
|
id: msg.content.id,
|
|
21494
22125
|
text: asProviderText(msg.content.text)
|
|
21495
22126
|
};
|
|
22127
|
+
content._provider_fields = [
|
|
22128
|
+
"id",
|
|
22129
|
+
...msg.content.options ? ["options"] : [],
|
|
22130
|
+
...msg.content.schema ? ["schema"] : []
|
|
22131
|
+
];
|
|
21496
22132
|
if (msg.content.options) content.options = msg.content.options;
|
|
21497
22133
|
if (msg.content.schema) content.schema = msg.content.schema;
|
|
22134
|
+
if (msg.content.expires_at_ms !== void 0) content.expires_at_ms = msg.content.expires_at_ms;
|
|
21498
22135
|
return { ...base, content, display };
|
|
21499
22136
|
}
|
|
21500
22137
|
case "artifact": {
|
|
@@ -21570,6 +22207,7 @@ async function message(jobId, text, opts) {
|
|
|
21570
22207
|
async function messageWithAccess(jobId, text, opts, access) {
|
|
21571
22208
|
const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
|
|
21572
22209
|
const { stored, ref, jobToken } = access;
|
|
22210
|
+
const json2 = (data) => providerJobJson(data, !!stored);
|
|
21573
22211
|
const msgType = opts.type ?? (opts.json ? "response" : "text");
|
|
21574
22212
|
if (msgType === "response" && !opts.promptId && !opts.json) {
|
|
21575
22213
|
throw new DvmError("invalid_input", "--prompt-id is required when --type is 'response'.");
|
|
@@ -21608,7 +22246,8 @@ async function messageWithAccess(jobId, text, opts, access) {
|
|
|
21608
22246
|
}
|
|
21609
22247
|
const content = jobContentFields(
|
|
21610
22248
|
jobId,
|
|
21611
|
-
await observeJobContent(jobId, transport, ref, { timeoutMs: timeoutMs ?? 5e3, jobToken })
|
|
22249
|
+
await observeJobContent(jobId, transport, ref, { timeoutMs: timeoutMs ?? 5e3, jobToken }),
|
|
22250
|
+
opts.human
|
|
21612
22251
|
);
|
|
21613
22252
|
transport.close();
|
|
21614
22253
|
if (opts.human) {
|
|
@@ -21619,7 +22258,7 @@ async function messageWithAccess(jobId, text, opts, access) {
|
|
|
21619
22258
|
}
|
|
21620
22259
|
finalizeProgressLine();
|
|
21621
22260
|
} else {
|
|
21622
|
-
|
|
22261
|
+
json2({
|
|
21623
22262
|
jobId,
|
|
21624
22263
|
...content,
|
|
21625
22264
|
sent: { type: outbound.type, content: outbound.content },
|
|
@@ -21705,12 +22344,40 @@ async function payWithAccess(jobId, opts, access) {
|
|
|
21705
22344
|
}
|
|
21706
22345
|
const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
|
|
21707
22346
|
const { stored, ref, jobToken } = access;
|
|
22347
|
+
const json2 = (data) => providerJobJson(data, !!stored);
|
|
21708
22348
|
const msgs = loadMessages(jobId);
|
|
21709
22349
|
const pending4 = stored.pendingCreditPayment;
|
|
21710
|
-
const
|
|
21711
|
-
const
|
|
22350
|
+
const transport = createDvmTransport();
|
|
22351
|
+
const inFlightMessage = msgs.findLast((message2) => message2.from === "provider" && message2.type === "payment-request" && stored.inFlightPaymentRequestSeqs?.includes(message2.seq));
|
|
22352
|
+
let paymentMessage = pendingPaymentRequest(msgs) ?? inFlightMessage;
|
|
22353
|
+
const recovering = pending4 || paymentMessage && stored.inFlightPaymentRequestSeqs?.includes(paymentMessage.seq);
|
|
22354
|
+
if (!recovering) {
|
|
22355
|
+
try {
|
|
22356
|
+
const readOptions = { jobToken, timeoutMs: JOB_READ_TIMEOUT_MS };
|
|
22357
|
+
const snapshot = await transport.status(jobId, ref, readOptions);
|
|
22358
|
+
const history = snapshot.status === "awaiting-input" ? await transport.getMessages(jobId, 0, ref, readOptions) : [];
|
|
22359
|
+
paymentMessage = pendingPaymentRequest(history);
|
|
22360
|
+
} catch (error) {
|
|
22361
|
+
transport.close();
|
|
22362
|
+
throw error;
|
|
22363
|
+
}
|
|
22364
|
+
}
|
|
22365
|
+
const inactiveRequest = isTerminalJobStatus(stored.status) || paymentMessage?.type === "payment-request" && paymentMessage.content.expires_at_ms !== void 0 && paymentMessage.content.expires_at_ms <= Date.now();
|
|
22366
|
+
if (!pending4 && inactiveRequest) {
|
|
22367
|
+
if (paymentMessage && stored.inFlightPaymentRequestSeqs?.includes(paymentMessage.seq) && ref.endpoint && sameEndpoint(stored.endpoint, ref.endpoint)) {
|
|
22368
|
+
try {
|
|
22369
|
+
await reconcileInFlightPaymentRequest(jobId, paymentMessage.seq, transport, ref, { jobToken });
|
|
22370
|
+
} catch (error) {
|
|
22371
|
+
transport.close();
|
|
22372
|
+
throw error;
|
|
22373
|
+
}
|
|
22374
|
+
}
|
|
22375
|
+
paymentMessage = void 0;
|
|
22376
|
+
}
|
|
22377
|
+
const paymentReq = pending4?.request ?? (paymentMessage?.type === "payment-request" ? paymentMessage.content : void 0);
|
|
21712
22378
|
const requestSeq = pending4?.authorization.request_seq ?? paymentMessage?.seq;
|
|
21713
22379
|
if (!paymentReq) {
|
|
22380
|
+
transport.close();
|
|
21714
22381
|
throw new DvmError(
|
|
21715
22382
|
"no_payment_pending",
|
|
21716
22383
|
"No pending payment request found for this job.",
|
|
@@ -21721,7 +22388,6 @@ async function payWithAccess(jobId, opts, access) {
|
|
|
21721
22388
|
applyMintPin(paymentReq.mints ?? [], opts.mint);
|
|
21722
22389
|
updateJob(jobId, { pinnedMint: opts.mint });
|
|
21723
22390
|
}
|
|
21724
|
-
const transport = createDvmTransport();
|
|
21725
22391
|
if (!stored.policy) {
|
|
21726
22392
|
throw new DvmError(
|
|
21727
22393
|
"no_budget",
|
|
@@ -21737,7 +22403,9 @@ async function payWithAccess(jobId, opts, access) {
|
|
|
21737
22403
|
jobToken,
|
|
21738
22404
|
rail,
|
|
21739
22405
|
maxCashuPrincipalSats,
|
|
21740
|
-
requestSeq
|
|
22406
|
+
requestSeq,
|
|
22407
|
+
approval: "explicit",
|
|
22408
|
+
creditRecoveryOnly: pending4 !== void 0
|
|
21741
22409
|
});
|
|
21742
22410
|
if (result === "over-budget") {
|
|
21743
22411
|
transport.close();
|
|
@@ -21800,12 +22468,12 @@ async function payWithAccess(jobId, opts, access) {
|
|
|
21800
22468
|
formatMessageHuman(msg, jobId, artifactSession);
|
|
21801
22469
|
}
|
|
21802
22470
|
if (completion) {
|
|
21803
|
-
const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount);
|
|
22471
|
+
const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, true);
|
|
21804
22472
|
if (hint) info(`\u{1F4CE} ${hint}`);
|
|
21805
22473
|
}
|
|
21806
22474
|
finalizeProgressLine();
|
|
21807
22475
|
} else {
|
|
21808
|
-
|
|
22476
|
+
json2({
|
|
21809
22477
|
jobId,
|
|
21810
22478
|
...dvmIdentity(stored.dvmId, stored.capability),
|
|
21811
22479
|
paid,
|
|
@@ -21815,7 +22483,7 @@ async function payWithAccess(jobId, opts, access) {
|
|
|
21815
22483
|
// so without these an agent that pays sees `next_action: null` and can't
|
|
21816
22484
|
// tell whether the payload is the summary or artifacts it must go fetch
|
|
21817
22485
|
// Mirrors what `dvm request` renders on the upfront-paid arc.
|
|
21818
|
-
...completion?.summary !== void 0 ? { summary: completion.summary } : {},
|
|
22486
|
+
...completion?.summary !== void 0 ? { summary: completion.summary, _provider_fields: ["summary"] } : {},
|
|
21819
22487
|
...completion ? buildCompletionHintFields(jobId, completion) : {},
|
|
21820
22488
|
...takeCreditNoticeFields(),
|
|
21821
22489
|
...takeFeedbackNoticeFields(),
|
|
@@ -21869,16 +22537,6 @@ function parsePositiveCashuSats(raw2) {
|
|
|
21869
22537
|
}
|
|
21870
22538
|
return value;
|
|
21871
22539
|
}
|
|
21872
|
-
function findPendingPaymentRequest(msgs) {
|
|
21873
|
-
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
21874
|
-
const msg = msgs[i];
|
|
21875
|
-
if (msg.type === "payment") return void 0;
|
|
21876
|
-
if (msg.type === "payment-request") {
|
|
21877
|
-
return { content: msg.content, seq: msg.seq };
|
|
21878
|
-
}
|
|
21879
|
-
}
|
|
21880
|
-
return void 0;
|
|
21881
|
-
}
|
|
21882
22540
|
|
|
21883
22541
|
// src/lib/data-flag.ts
|
|
21884
22542
|
async function resolveDataFlag(raw2) {
|
|
@@ -22421,6 +23079,9 @@ function railList(keys, isKnown, label) {
|
|
|
22421
23079
|
}
|
|
22422
23080
|
|
|
22423
23081
|
// src/commands/receipts.ts
|
|
23082
|
+
import { createHash as createHash3 } from "crypto";
|
|
23083
|
+
import { createReadStream } from "fs";
|
|
23084
|
+
import { open, stat } from "fs/promises";
|
|
22424
23085
|
var DEFAULT_LIMIT2 = 50;
|
|
22425
23086
|
function receiptsList(opts) {
|
|
22426
23087
|
const limit = resolveLimit2(opts.limit);
|
|
@@ -22466,6 +23127,9 @@ Endpoint: ${entry.endpoint || "(unknown)"}`);
|
|
|
22466
23127
|
});
|
|
22467
23128
|
}
|
|
22468
23129
|
async function receiptsVerify(jobId, opts) {
|
|
23130
|
+
if (opts.artifact !== void 0 && !opts.file?.length) {
|
|
23131
|
+
throw new DvmError("invalid_argument", "--artifact requires --file.", "Pass --file <path> with --artifact to select the file artifact to check.");
|
|
23132
|
+
}
|
|
22469
23133
|
const entry = requireStored(jobId);
|
|
22470
23134
|
const builder = opts.endpoint ? await refetchAnchor(opts.endpoint) : entry.builder ?? loadJob(jobId)?.builderAnchor;
|
|
22471
23135
|
const delivered = deliveredFromMessages(jobId, entry.receipt);
|
|
@@ -22475,9 +23139,15 @@ async function receiptsVerify(jobId, opts) {
|
|
|
22475
23139
|
expectedJobId: jobId,
|
|
22476
23140
|
delivered
|
|
22477
23141
|
});
|
|
23142
|
+
const files = await verifyFiles(jobId, opts, delivered, result);
|
|
23143
|
+
if (files.some((file) => !["match", "no_signed_digest", "unverifiable"].includes(file.status))) process.exitCode = 1;
|
|
22478
23144
|
const rate = getLastKnownBtcRate()?.rate ?? 0;
|
|
22479
23145
|
if (opts.human) {
|
|
22480
23146
|
renderVerdictHuman(entry, result, rate);
|
|
23147
|
+
for (const file of files) {
|
|
23148
|
+
info(`${file.path}: ${file.display}`);
|
|
23149
|
+
info(` ${file.hint}`);
|
|
23150
|
+
}
|
|
22481
23151
|
info(`
|
|
22482
23152
|
Signature: ${result.checks.signature ? "valid" : "INVALID"}`);
|
|
22483
23153
|
info(`Attestation: ${result.checks.attestation}`);
|
|
@@ -22487,10 +23157,90 @@ Signature: ${result.checks.signature ? "valid" : "INVALID"}`);
|
|
|
22487
23157
|
}
|
|
22488
23158
|
json({
|
|
22489
23159
|
...storedReceiptJson(entry, result, rate),
|
|
23160
|
+
...opts.file?.length ? { files } : {},
|
|
22490
23161
|
anchor_source: opts.endpoint ? "refetched" : "stored",
|
|
22491
23162
|
hint: receiptHint(result.status, jobId)
|
|
22492
23163
|
});
|
|
22493
23164
|
}
|
|
23165
|
+
async function verifyFiles(jobId, opts, delivered, result) {
|
|
23166
|
+
if (!opts.file?.length) return [];
|
|
23167
|
+
const artifacts = (result.checks.result_hash === "ok" ? delivered?.artifactContents ?? [] : []).map((content, index) => ({
|
|
23168
|
+
content,
|
|
23169
|
+
index: index + 1
|
|
23170
|
+
}));
|
|
23171
|
+
const selected = opts.artifact === void 0 ? artifacts : artifacts.filter(
|
|
23172
|
+
({ content, index }) => /^[1-9]\d*$/.test(opts.artifact) ? String(index) === opts.artifact : content.name === opts.artifact
|
|
23173
|
+
);
|
|
23174
|
+
if (opts.artifact !== void 0 && result.checks.result_hash === "ok" && selected.length === 0) {
|
|
23175
|
+
throw new DvmError(
|
|
23176
|
+
"artifact_not_found",
|
|
23177
|
+
"No artifact matches --artifact.",
|
|
23178
|
+
artifacts.length ? "Select an artifact by its 1-based index, or by its exact name as shown in `dvm messages <job-id>`. JSON output lists them in available_artifacts." : "This receipt has no delivered artifacts to select. Omit --artifact.",
|
|
23179
|
+
{ available_artifacts: artifacts.map(({ content, index }) => ({ index, name: content.name === void 0 ? null : asProviderText(content.name) })) }
|
|
23180
|
+
);
|
|
23181
|
+
}
|
|
23182
|
+
if (opts.artifact !== void 0 && selected.length > 1) {
|
|
23183
|
+
throw new DvmError("ambiguous_artifact", "More than one artifact matches --artifact.", "Select its unique 1-based artifact index instead.");
|
|
23184
|
+
}
|
|
23185
|
+
const candidates = selected.filter(
|
|
23186
|
+
({ content }) => typeof content.url === "string" && content.url.length > 0 && typeof content.sha256 === "string" && /^[a-f0-9]{64}$/i.test(content.sha256)
|
|
23187
|
+
);
|
|
23188
|
+
const files = [];
|
|
23189
|
+
for (const path of opts.file ?? []) {
|
|
23190
|
+
const base = { path, sha256: null, matched_artifact: null };
|
|
23191
|
+
try {
|
|
23192
|
+
if (!(await stat(path)).isFile()) throw new Error("Not a regular file");
|
|
23193
|
+
const file = await open(path, "r");
|
|
23194
|
+
try {
|
|
23195
|
+
if (!(await file.stat()).isFile()) throw new Error("Not a regular file");
|
|
23196
|
+
} finally {
|
|
23197
|
+
await file.close();
|
|
23198
|
+
}
|
|
23199
|
+
if (result.checks.result_hash !== "ok" || result.status === "invalid") {
|
|
23200
|
+
files.push({
|
|
23201
|
+
...base,
|
|
23202
|
+
status: "unverifiable",
|
|
23203
|
+
display: "The file cannot be checked against signed evidence.",
|
|
23204
|
+
hint: `The receipt could not be checked, so the file cannot be checked against it. Run 'dvm receipts verify ${jobId}' without --file to see why.`
|
|
23205
|
+
});
|
|
23206
|
+
continue;
|
|
23207
|
+
}
|
|
23208
|
+
if (candidates.length === 0) {
|
|
23209
|
+
files.push({
|
|
23210
|
+
...base,
|
|
23211
|
+
status: "no_signed_digest",
|
|
23212
|
+
display: "No signed file fingerprint is available for this selection.",
|
|
23213
|
+
hint: "The DVM did not sign a usable SHA-256 fingerprint for a URL artifact in this selection. Check --artifact if supplied."
|
|
23214
|
+
});
|
|
23215
|
+
continue;
|
|
23216
|
+
}
|
|
23217
|
+
const hash = createHash3("sha256");
|
|
23218
|
+
let size = 0;
|
|
23219
|
+
for await (const chunk of createReadStream(path)) {
|
|
23220
|
+
size += chunk.length;
|
|
23221
|
+
hash.update(chunk);
|
|
23222
|
+
}
|
|
23223
|
+
const sha2563 = hash.digest("hex");
|
|
23224
|
+
const match = candidates.find(({ content }) => content.sha256.toLowerCase() === sha2563 && (typeof content.size_bytes !== "number" || content.size_bytes === size));
|
|
23225
|
+
files.push({
|
|
23226
|
+
path,
|
|
23227
|
+
sha256: sha2563,
|
|
23228
|
+
matched_artifact: match ? { name: match.content.name === void 0 ? null : asProviderText(match.content.name), index: match.index } : null,
|
|
23229
|
+
status: match ? "match" : "mismatch",
|
|
23230
|
+
display: match ? "The file matches the fingerprint the DVM signed in its receipt." : `The file does not match the fingerprint${candidates.some(({ content }) => typeof content.size_bytes === "number") ? " or size" : ""} the DVM signed in its receipt.`,
|
|
23231
|
+
hint: match ? "The file's bytes match signed evidence; this does not assess the quality of the result." : "Check that you selected the intended file and artifact. Do not rely on this file as the signed result."
|
|
23232
|
+
});
|
|
23233
|
+
} catch {
|
|
23234
|
+
files.push({
|
|
23235
|
+
...base,
|
|
23236
|
+
status: "unreadable",
|
|
23237
|
+
display: "The local file could not be read.",
|
|
23238
|
+
hint: "Check that the path names an existing, readable file, not a directory, and try again."
|
|
23239
|
+
});
|
|
23240
|
+
}
|
|
23241
|
+
}
|
|
23242
|
+
return files;
|
|
23243
|
+
}
|
|
22494
23244
|
function receiptsExport(opts) {
|
|
22495
23245
|
for (const entry of filterReceipts(loadReceipts(), opts)) {
|
|
22496
23246
|
raw(JSON.stringify(entry));
|
|
@@ -22634,7 +23384,7 @@ function buildPolicy(opts, btcRate) {
|
|
|
22634
23384
|
}
|
|
22635
23385
|
|
|
22636
23386
|
// src/commands/request.ts
|
|
22637
|
-
import { createHash as
|
|
23387
|
+
import { createHash as createHash4, randomUUID as randomUUID4 } from "crypto";
|
|
22638
23388
|
|
|
22639
23389
|
// src/lib/credit-defer.ts
|
|
22640
23390
|
function noteDeferredFunding(funding) {
|
|
@@ -22667,7 +23417,7 @@ async function settleCreditAfterJob(args) {
|
|
|
22667
23417
|
}
|
|
22668
23418
|
}
|
|
22669
23419
|
if (args.allowTopup !== false) {
|
|
22670
|
-
const refill = args.refillPocket ?? (await import("./pocket-refill-
|
|
23420
|
+
const refill = args.refillPocket ?? (await import("./pocket-refill-3ZV36DOA.js")).refillPocketIfLow;
|
|
22671
23421
|
await refill({ human: args.human }).catch(() => void 0);
|
|
22672
23422
|
}
|
|
22673
23423
|
}
|
|
@@ -23163,6 +23913,7 @@ function dollarLimitMicro(declaredLimit) {
|
|
|
23163
23913
|
}
|
|
23164
23914
|
|
|
23165
23915
|
// src/lib/request-intent-store.ts
|
|
23916
|
+
var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
|
|
23166
23917
|
import {
|
|
23167
23918
|
closeSync as closeSync3,
|
|
23168
23919
|
existsSync as existsSync7,
|
|
@@ -23218,6 +23969,31 @@ function loadRequestIntent(requestId) {
|
|
|
23218
23969
|
);
|
|
23219
23970
|
}
|
|
23220
23971
|
}
|
|
23972
|
+
function recordRequestRailPayment(requestId, payment) {
|
|
23973
|
+
assertRequestId(requestId);
|
|
23974
|
+
if (!parseUpfrontRailPayment(payment)) throw new DvmError("invalid_upfront_payment", "Invalid upfront rail price.");
|
|
23975
|
+
const dir = intentDirectory(requestId);
|
|
23976
|
+
const target = join8(dir, "intent.json");
|
|
23977
|
+
const release = import_proper_lockfile2.default.lockSync(target, { realpath: false });
|
|
23978
|
+
try {
|
|
23979
|
+
const intent = loadRequestIntent(requestId);
|
|
23980
|
+
if (!intent) throw new DvmError("request_not_found", "No saved request intent exists for this rail payment.");
|
|
23981
|
+
if (intent.railPayment && JSON.stringify(intent.railPayment) !== JSON.stringify(payment))
|
|
23982
|
+
throw new DvmError("upfront_payment_conflict", "This request already records a different upfront rail price.");
|
|
23983
|
+
const temp = join8(dir, `rail.${String(process.pid)}.tmp`);
|
|
23984
|
+
const fd = openSync3(temp, "w", 384);
|
|
23985
|
+
try {
|
|
23986
|
+
writeFileSync4(fd, JSON.stringify({ ...intent, railPayment: payment }, null, 2) + "\n");
|
|
23987
|
+
fsyncSync(fd);
|
|
23988
|
+
} finally {
|
|
23989
|
+
closeSync3(fd);
|
|
23990
|
+
}
|
|
23991
|
+
renameSync2(temp, target);
|
|
23992
|
+
fsyncDirectory(dir);
|
|
23993
|
+
} finally {
|
|
23994
|
+
release();
|
|
23995
|
+
}
|
|
23996
|
+
}
|
|
23221
23997
|
function assertNoPaymentOrAuthSecrets(body) {
|
|
23222
23998
|
if (!containsForbiddenSecret(body)) return;
|
|
23223
23999
|
throw new DvmError(
|
|
@@ -23953,7 +24729,7 @@ async function request(opts) {
|
|
|
23953
24729
|
outputCollectedQuotes(receipt.jobId || null, quotes, opts, identity, void 0, action);
|
|
23954
24730
|
return;
|
|
23955
24731
|
}
|
|
23956
|
-
|
|
24732
|
+
saveSubmittedJob({
|
|
23957
24733
|
id: receipt.jobId,
|
|
23958
24734
|
...transactionRecordFields(receipt),
|
|
23959
24735
|
endpoint,
|
|
@@ -23969,7 +24745,7 @@ async function request(opts) {
|
|
|
23969
24745
|
...requestedMaxCashuFeeSats !== void 0 ? { maxCashuFeeSats: requestedMaxCashuFeeSats } : {},
|
|
23970
24746
|
// the job cleared by drawing on a prepaid credit — no payment
|
|
23971
24747
|
// attach, no budget-ledger entry (the funding already counted).
|
|
23972
|
-
...probePlan.mode === "draw" ? { paymentMethod: "credit" } : {},
|
|
24748
|
+
...probePlan.mode === "draw" ? { paymentMethod: "credit" } : { upfrontRailPayment: "free" },
|
|
23973
24749
|
...signing ? { creditBinding: probePlan.mode === "draw" ? { creditId: probePlan.creditId, drawId: probePlan.drawId, callerPubkey: signing.pubkey } : { unbound: true, callerPubkey: signing.pubkey } } : {},
|
|
23974
24750
|
// persist the anonymous-flow per-job token so subsequent
|
|
23975
24751
|
// status/messages/pay/cancel commands can present it as `X-Job-Token`.
|
|
@@ -23982,13 +24758,17 @@ async function request(opts) {
|
|
|
23982
24758
|
...receiptTrustFields(providerInfo),
|
|
23983
24759
|
...localCorrelationJobFields(localCorrelationId)
|
|
23984
24760
|
});
|
|
24761
|
+
recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment);
|
|
23985
24762
|
if (noStream) {
|
|
23986
24763
|
transport.close();
|
|
23987
24764
|
if (opts.human) {
|
|
23988
24765
|
info(`Job published: ${receipt.jobId}`);
|
|
23989
24766
|
echoTraceIdHuman();
|
|
24767
|
+
if (!isTerminalJobStatus(receipt.status)) {
|
|
24768
|
+
printNextActionHuman(pollNextAction(receipt.jobId, "Job submitted, check back for updates"));
|
|
24769
|
+
}
|
|
23990
24770
|
} else {
|
|
23991
|
-
|
|
24771
|
+
providerJobJson({
|
|
23992
24772
|
jobId: receipt.jobId,
|
|
23993
24773
|
...requestIdOutputFields(jobRequestId),
|
|
23994
24774
|
...transactionOutputFields(receipt),
|
|
@@ -23997,7 +24777,7 @@ async function request(opts) {
|
|
|
23997
24777
|
// noStream branch (closest analog — one shot, no live stream).
|
|
23998
24778
|
// Streaming paths surface the actual job result, which already
|
|
23999
24779
|
// tells the agent what the server processed.
|
|
24000
|
-
...normalizedInput && Object.keys(appliedDefaults).length > 0 ? { normalized_input: normalizedInput, applied_defaults: appliedDefaults } : {},
|
|
24780
|
+
...normalizedInput && Object.keys(appliedDefaults).length > 0 ? providerFields({ normalized_input: providerFields(normalizedInput, Object.keys(appliedDefaults)), applied_defaults: appliedDefaults }, ["applied_defaults"]) : {},
|
|
24001
24781
|
// This branch returns before the job has an outcome, so it is the only
|
|
24002
24782
|
// JSON the caller gets — a credit notice stashed during the probe has
|
|
24003
24783
|
// nowhere else to land. The feedback sink deliberately does
|
|
@@ -24037,17 +24817,18 @@ async function request(opts) {
|
|
|
24037
24817
|
transport.close();
|
|
24038
24818
|
if (opts.human) {
|
|
24039
24819
|
console.log(receipt.summary);
|
|
24040
|
-
const hint = nextStepHint(receipt.jobId, receipt.payloadIn, receipt.artifactCount);
|
|
24820
|
+
const hint = nextStepHint(receipt.jobId, receipt.payloadIn, receipt.artifactCount, true);
|
|
24041
24821
|
if (hint) info(`\u{1F4CE} ${hint}`);
|
|
24042
24822
|
renderReceiptHuman(captured);
|
|
24043
24823
|
echoTraceIdHuman();
|
|
24044
24824
|
} else {
|
|
24045
|
-
|
|
24825
|
+
providerJobJson({
|
|
24046
24826
|
jobId: receipt.jobId,
|
|
24047
24827
|
...requestIdOutputFields(jobRequestId),
|
|
24048
24828
|
...transactionOutputFields(receipt),
|
|
24049
24829
|
...dvmIdentity(dvmId, capability),
|
|
24050
24830
|
summary: receipt.summary,
|
|
24831
|
+
_provider_fields: ["summary"],
|
|
24051
24832
|
...buildCompletionHintFields(receipt.jobId, receipt),
|
|
24052
24833
|
...receiptJsonFields(captured),
|
|
24053
24834
|
...takeCreditNoticeFields(),
|
|
@@ -24109,15 +24890,15 @@ async function request(opts) {
|
|
|
24109
24890
|
formatMessageHuman(msg, receipt.jobId, artifactSession);
|
|
24110
24891
|
}
|
|
24111
24892
|
if (completion) {
|
|
24112
|
-
const hint = nextStepHint(receipt.jobId, completion.payloadIn, completion.artifactCount);
|
|
24893
|
+
const hint = nextStepHint(receipt.jobId, completion.payloadIn, completion.artifactCount, true);
|
|
24113
24894
|
if (hint) info(`\u{1F4CE} ${hint}`);
|
|
24114
24895
|
}
|
|
24115
24896
|
if (captured) renderReceiptHuman(captured);
|
|
24116
24897
|
finalizeProgressLine();
|
|
24117
|
-
printRefundSummaryHuman(result.refunds);
|
|
24118
24898
|
echoTraceIdHuman();
|
|
24899
|
+
printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: isTerminalJobStatus(receipt.status) || !!streamTerminalStatus(result.messages) });
|
|
24119
24900
|
} else {
|
|
24120
|
-
|
|
24901
|
+
providerJobJson({
|
|
24121
24902
|
jobId: receipt.jobId,
|
|
24122
24903
|
...requestIdOutputFields(jobRequestId),
|
|
24123
24904
|
...transactionOutputFields(receipt),
|
|
@@ -24128,7 +24909,7 @@ async function request(opts) {
|
|
|
24128
24909
|
// these come off the streamed log instead. Without them this arc
|
|
24129
24910
|
// returned `next_action: null` and nothing else: no summary, and no
|
|
24130
24911
|
// signal that a payload was waiting in artifacts.
|
|
24131
|
-
...completion?.summary !== void 0 ? { summary: completion.summary } : {},
|
|
24912
|
+
...completion?.summary !== void 0 ? { summary: completion.summary, _provider_fields: ["summary"] } : {},
|
|
24132
24913
|
...completion ? buildCompletionHintFields(receipt.jobId, completion) : {},
|
|
24133
24914
|
...captured ? receiptJsonFields(captured) : {},
|
|
24134
24915
|
...takeCreditNoticeFields(),
|
|
@@ -24188,7 +24969,7 @@ function identityArgs(identity) {
|
|
|
24188
24969
|
return identity ? { identity } : {};
|
|
24189
24970
|
}
|
|
24190
24971
|
function sha256Hex(value) {
|
|
24191
|
-
return
|
|
24972
|
+
return createHash4("sha256").update(value, "utf8").digest("hex");
|
|
24192
24973
|
}
|
|
24193
24974
|
async function fetchServerPriceMicro(transport, ref, envelope) {
|
|
24194
24975
|
try {
|
|
@@ -24891,13 +25672,14 @@ async function payWithTempo(args, credential) {
|
|
|
24891
25672
|
const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
|
|
24892
25673
|
const usdcMicroUnits = Number(tempoCredentialAmountMicro(credential));
|
|
24893
25674
|
const paidMsats = usdcToMsats(usdcMicroUnits / 1e6, btcRate);
|
|
25675
|
+
if (opts.requestId) recordRequestRailPayment(opts.requestId, { method: "tempo", amountMsats: paidMsats });
|
|
24894
25676
|
const usd2 = usdcMicroUnits / 1e6;
|
|
24895
25677
|
const priceLabel = `$${formatUsd(usd2)} USDC`;
|
|
24896
25678
|
const accountShort = `${account.address.slice(0, 6)}\u2026${account.address.slice(-4)}`;
|
|
24897
25679
|
if (opts.human) {
|
|
24898
25680
|
info(`Paying ${priceLabel} via Tempo (account ${accountShort})...`);
|
|
24899
25681
|
} else {
|
|
24900
|
-
|
|
25682
|
+
providerJobJson({
|
|
24901
25683
|
...dvmFields,
|
|
24902
25684
|
...requestIdOutputFields(opts.requestId),
|
|
24903
25685
|
status: "paying",
|
|
@@ -24985,7 +25767,7 @@ async function payWithTempo(args, credential) {
|
|
|
24985
25767
|
`Verify the Tempo account has at least the quoted amount in ${asset?.label ?? "the rail's settlement token"} on ${tempoNetworkLabel(network)} (chain ${String(chain.chainId)}).${asset ? ` ${tempoWrongAssetHint(asset)}` : ""}`
|
|
24986
25768
|
);
|
|
24987
25769
|
}
|
|
24988
|
-
|
|
25770
|
+
recordUpfrontRailPayment(effectiveJobId, { method: "tempo", amountMsats: paidMsats }, true);
|
|
24989
25771
|
recordSpend({
|
|
24990
25772
|
msats: paidMsats,
|
|
24991
25773
|
btcRate: args.btcRate,
|
|
@@ -25018,16 +25800,17 @@ async function payWithTempo(args, credential) {
|
|
|
25018
25800
|
transport.close?.();
|
|
25019
25801
|
if (opts.human) {
|
|
25020
25802
|
console.log(receipt.summary);
|
|
25021
|
-
const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount);
|
|
25803
|
+
const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
|
|
25022
25804
|
if (hint) info(`\u{1F4CE} ${hint}`);
|
|
25023
25805
|
renderReceiptHuman(captured);
|
|
25024
25806
|
} else {
|
|
25025
|
-
|
|
25807
|
+
providerJobJson({
|
|
25026
25808
|
jobId: effectiveJobId,
|
|
25027
25809
|
...requestIdOutputFields(opts.requestId),
|
|
25028
25810
|
...transactionOutputFields(receipt),
|
|
25029
25811
|
...dvmFields,
|
|
25030
25812
|
summary: receipt.summary,
|
|
25813
|
+
_provider_fields: ["summary"],
|
|
25031
25814
|
...buildCompletionHintFields(effectiveJobId, receipt),
|
|
25032
25815
|
...receiptJsonFields(captured),
|
|
25033
25816
|
paidWith: "tempo",
|
|
@@ -25224,6 +26007,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
|
|
|
25224
26007
|
const priceSats = Math.ceil(chosen.priceMsats / 1e3);
|
|
25225
26008
|
const maxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
|
|
25226
26009
|
const baseContext = {
|
|
26010
|
+
upfront_rail_payment: { method: "cashu", amountMsats: chosen.priceMsats },
|
|
25227
26011
|
dvm_id: identity.dvmId,
|
|
25228
26012
|
capability: identity.capability,
|
|
25229
26013
|
pinned_mint: opts.mint,
|
|
@@ -25351,6 +26135,8 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
|
|
|
25351
26135
|
providerInfo
|
|
25352
26136
|
});
|
|
25353
26137
|
}
|
|
26138
|
+
const pricedRequestId = opts.requestId ?? generatedRequestId;
|
|
26139
|
+
if (pricedRequestId) recordRequestRailPayment(pricedRequestId, { method: "cashu", amountMsats: chosen.priceMsats });
|
|
25354
26140
|
if (fundPlan && signing) {
|
|
25355
26141
|
ensureProvisionalCredit({
|
|
25356
26142
|
endpoint: ref.endpoint,
|
|
@@ -25629,7 +26415,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
|
|
|
25629
26415
|
}
|
|
25630
26416
|
});
|
|
25631
26417
|
await collectCashuChange(effectiveJobId, receipt.cashuChange);
|
|
25632
|
-
|
|
26418
|
+
recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
|
|
25633
26419
|
if (fundPlan) {
|
|
25634
26420
|
recordSpend({
|
|
25635
26421
|
msats: fundPlan.fundMsats,
|
|
@@ -25674,14 +26460,15 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
|
|
|
25674
26460
|
transport.close?.();
|
|
25675
26461
|
if (opts.human) {
|
|
25676
26462
|
console.log(receipt.summary);
|
|
25677
|
-
const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount);
|
|
26463
|
+
const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
|
|
25678
26464
|
if (hint) info(`\u{1F4CE} ${hint}`);
|
|
25679
26465
|
renderReceiptHuman(captured);
|
|
25680
26466
|
} else {
|
|
25681
|
-
|
|
26467
|
+
providerJobJson({
|
|
25682
26468
|
jobId: effectiveJobId,
|
|
25683
26469
|
...dvmFields,
|
|
25684
26470
|
summary: receipt.summary,
|
|
26471
|
+
_provider_fields: ["summary"],
|
|
25685
26472
|
...buildCompletionHintFields(effectiveJobId, receipt),
|
|
25686
26473
|
...receiptJsonFields(captured),
|
|
25687
26474
|
paidWith: "cashu_p2pk",
|
|
@@ -25754,6 +26541,7 @@ async function tryX402UpfrontPayment(args) {
|
|
|
25754
26541
|
}
|
|
25755
26542
|
async function payWithX402(args, proof) {
|
|
25756
26543
|
const { transport, ref, envelope, chosen, opts, identity, policy, wallet } = args;
|
|
26544
|
+
if (opts.requestId) recordRequestRailPayment(opts.requestId, { method: "x402", amountMsats: proof.amountMsats });
|
|
25757
26545
|
const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
|
|
25758
26546
|
const usdcMicroUnits = Number(proof.amountUsdcMicro);
|
|
25759
26547
|
const usd2 = usdcMicroUnits / 1e6;
|
|
@@ -25762,7 +26550,7 @@ async function payWithX402(args, proof) {
|
|
|
25762
26550
|
if (opts.human) {
|
|
25763
26551
|
info(`Paying ${priceLabel} via x402 (account ${addressShort})...`);
|
|
25764
26552
|
} else {
|
|
25765
|
-
|
|
26553
|
+
providerJobJson({
|
|
25766
26554
|
...dvmFields,
|
|
25767
26555
|
...requestIdOutputFields(opts.requestId),
|
|
25768
26556
|
status: "paying",
|
|
@@ -25838,7 +26626,7 @@ async function payWithX402(args, proof) {
|
|
|
25838
26626
|
asset ? `Verify the account ${addressShort} holds at least the quoted amount in ${asset.label} (${asset.address}) on ${asset.networkLabel} \u2014 the chain this DVM advertises, which is not necessarily the one 'dvm wallet balance' reads. A different dollar${asset.confusable ? ` such as ${asset.confusable}` : ""}, or the right one on another chain, cannot settle this payment.` : "Verify the x402 account holds the quoted USDC amount on the advertised network."
|
|
25839
26627
|
);
|
|
25840
26628
|
}
|
|
25841
|
-
|
|
26629
|
+
recordUpfrontRailPayment(effectiveJobId, { method: "x402", amountMsats: proof.amountMsats }, true);
|
|
25842
26630
|
recordSpend({
|
|
25843
26631
|
msats: proof.amountMsats,
|
|
25844
26632
|
btcRate: proof.btcRate,
|
|
@@ -25871,16 +26659,17 @@ async function payWithX402(args, proof) {
|
|
|
25871
26659
|
transport.close?.();
|
|
25872
26660
|
if (opts.human) {
|
|
25873
26661
|
console.log(receipt.summary);
|
|
25874
|
-
const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount);
|
|
26662
|
+
const hint = nextStepHint(effectiveJobId, receipt.payloadIn, receipt.artifactCount, true);
|
|
25875
26663
|
if (hint) info(`\u{1F4CE} ${hint}`);
|
|
25876
26664
|
renderReceiptHuman(captured);
|
|
25877
26665
|
} else {
|
|
25878
|
-
|
|
26666
|
+
providerJobJson({
|
|
25879
26667
|
jobId: effectiveJobId,
|
|
25880
26668
|
...requestIdOutputFields(opts.requestId),
|
|
25881
26669
|
...transactionOutputFields(receipt),
|
|
25882
26670
|
...dvmFields,
|
|
25883
26671
|
summary: receipt.summary,
|
|
26672
|
+
_provider_fields: ["summary"],
|
|
25884
26673
|
...buildCompletionHintFields(effectiveJobId, receipt),
|
|
25885
26674
|
...receiptJsonFields(captured),
|
|
25886
26675
|
paidWith: "x402",
|
|
@@ -25927,19 +26716,6 @@ async function streamToCompletion(baseOpts, deadlineMs) {
|
|
|
25927
26716
|
const allMessages = [...result.messages];
|
|
25928
26717
|
const allAutoPayments = [...result.autoPayments];
|
|
25929
26718
|
const allRefunds = [...result.refunds];
|
|
25930
|
-
if (result.messages.length === 0 && result.nextAction === null) {
|
|
25931
|
-
return {
|
|
25932
|
-
messages: allMessages,
|
|
25933
|
-
autoPayments: allAutoPayments,
|
|
25934
|
-
refunds: allRefunds,
|
|
25935
|
-
nextAction: {
|
|
25936
|
-
type: "poll",
|
|
25937
|
-
job_id: baseOpts.jobId,
|
|
25938
|
-
hint: "Provider hasn't yielded yet, check back later"
|
|
25939
|
-
},
|
|
25940
|
-
cursor: result.cursor
|
|
25941
|
-
};
|
|
25942
|
-
}
|
|
25943
26719
|
while (result.nextAction?.type === "poll") {
|
|
25944
26720
|
if (Date.now() >= deadlineMs) break;
|
|
25945
26721
|
const waitMs = Math.min(
|
|
@@ -26040,10 +26816,15 @@ async function streamAfterPayment(args) {
|
|
|
26040
26816
|
strictPerCall: args.strictPerCall
|
|
26041
26817
|
});
|
|
26042
26818
|
if (recovered) return;
|
|
26819
|
+
const nextAction = pollNextAction(
|
|
26820
|
+
jobId,
|
|
26821
|
+
`Payment sent but the result stream timed out. ${pollNextAction(jobId).hint}`
|
|
26822
|
+
);
|
|
26043
26823
|
if (human) {
|
|
26044
26824
|
info(paidTimeoutMessage);
|
|
26825
|
+
printNextActionHuman(nextAction);
|
|
26045
26826
|
} else {
|
|
26046
|
-
|
|
26827
|
+
providerJobJson({
|
|
26047
26828
|
jobId,
|
|
26048
26829
|
...dvmFields,
|
|
26049
26830
|
status: "paid-timeout",
|
|
@@ -26053,10 +26834,7 @@ async function streamAfterPayment(args) {
|
|
|
26053
26834
|
// not the job. `poll`, not `null`: the result is still coming.
|
|
26054
26835
|
...takeCreditNoticeFields(),
|
|
26055
26836
|
...takeFeedbackNoticeFields(),
|
|
26056
|
-
next_action:
|
|
26057
|
-
jobId,
|
|
26058
|
-
"Payment sent but the result stream timed out. The job is still running \u2014 check back with 'dvm status'."
|
|
26059
|
-
)
|
|
26837
|
+
next_action: nextAction
|
|
26060
26838
|
});
|
|
26061
26839
|
}
|
|
26062
26840
|
throw new DvmError("timeout", paidTimeoutMessage);
|
|
@@ -26067,21 +26845,21 @@ async function streamAfterPayment(args) {
|
|
|
26067
26845
|
formatMessageHuman(msg, jobId, artifactSession);
|
|
26068
26846
|
}
|
|
26069
26847
|
if (completion) {
|
|
26070
|
-
const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount);
|
|
26848
|
+
const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, true);
|
|
26071
26849
|
if (hint) info(`\u{1F4CE} ${hint}`);
|
|
26072
26850
|
}
|
|
26073
26851
|
if (captured) renderReceiptHuman(captured);
|
|
26074
26852
|
finalizeProgressLine();
|
|
26075
|
-
|
|
26853
|
+
printNextActionHuman(result.nextAction, { refunds: result.refunds, terminal: !!streamTerminalStatus(result.messages) });
|
|
26076
26854
|
} else {
|
|
26077
|
-
|
|
26855
|
+
providerJobJson({
|
|
26078
26856
|
jobId,
|
|
26079
26857
|
...dvmFields,
|
|
26080
26858
|
messages: result.messages.map(serializeMessageForOutput),
|
|
26081
26859
|
// Same as the unpaid arc above: the outcome is only knowable from the
|
|
26082
26860
|
// streamed log here, so render it rather than leaving the agent to dig
|
|
26083
26861
|
// the summary out of `messages` and guess about artifacts.
|
|
26084
|
-
...completion?.summary !== void 0 ? { summary: completion.summary } : {},
|
|
26862
|
+
...completion?.summary !== void 0 ? { summary: completion.summary, _provider_fields: ["summary"] } : {},
|
|
26085
26863
|
...completion ? buildCompletionHintFields(jobId, completion) : {},
|
|
26086
26864
|
...captured ? receiptJsonFields(captured) : {},
|
|
26087
26865
|
...takeCreditNoticeFields(),
|
|
@@ -26131,11 +26909,12 @@ async function recoverViaStatusPoll(args) {
|
|
|
26131
26909
|
info(status2.summary ?? "Job completed (recovered via status check).");
|
|
26132
26910
|
renderReceiptHuman(captured);
|
|
26133
26911
|
} else {
|
|
26134
|
-
|
|
26912
|
+
providerJobJson({
|
|
26135
26913
|
jobId,
|
|
26136
26914
|
...dvmFields,
|
|
26137
26915
|
status: "completed",
|
|
26138
26916
|
summary: status2.summary ?? null,
|
|
26917
|
+
_provider_fields: ["summary"],
|
|
26139
26918
|
recovered: true,
|
|
26140
26919
|
...paymentFields,
|
|
26141
26920
|
...receiptJsonFields(captured),
|
|
@@ -26162,11 +26941,12 @@ async function recoverViaStatusPoll(args) {
|
|
|
26162
26941
|
info(errorMsg);
|
|
26163
26942
|
renderReceiptHuman(captured);
|
|
26164
26943
|
} else {
|
|
26165
|
-
|
|
26944
|
+
providerJobJson({
|
|
26166
26945
|
jobId,
|
|
26167
26946
|
...dvmFields,
|
|
26168
26947
|
status: status2.status,
|
|
26169
26948
|
message: errorMsg,
|
|
26949
|
+
...status2.message !== void 0 ? { _provider_fields: ["message"] } : {},
|
|
26170
26950
|
...paymentFields,
|
|
26171
26951
|
...receiptJsonFields(captured),
|
|
26172
26952
|
...takeCreditNoticeFields(),
|
|
@@ -26174,7 +26954,14 @@ async function recoverViaStatusPoll(args) {
|
|
|
26174
26954
|
next_action: null
|
|
26175
26955
|
});
|
|
26176
26956
|
}
|
|
26177
|
-
throw new DvmError(
|
|
26957
|
+
throw new DvmError(
|
|
26958
|
+
status2.status === "failed" ? "provider_error" : "cancelled",
|
|
26959
|
+
errorMsg,
|
|
26960
|
+
void 0,
|
|
26961
|
+
void 0,
|
|
26962
|
+
void 0,
|
|
26963
|
+
status2.message !== void 0 ? { message: "provider" } : void 0
|
|
26964
|
+
);
|
|
26178
26965
|
}
|
|
26179
26966
|
return false;
|
|
26180
26967
|
}
|
|
@@ -26315,12 +27102,20 @@ async function requestResult(requestId, opts = {}) {
|
|
|
26315
27102
|
pinnedMint: intent.pinnedMint,
|
|
26316
27103
|
strictPerCall: intent.strictPerCall,
|
|
26317
27104
|
maxCashuFeeSats: intent.maxCashuFeeSats,
|
|
26318
|
-
paymentMethod: paymentMethod(receipt),
|
|
27105
|
+
paymentMethod: creditBinding && !originalData?.fund ? "credit" : intent.railPayment?.method ?? paymentMethod(receipt),
|
|
26319
27106
|
receiptsSupported: intent.receiptsSupported,
|
|
26320
27107
|
builderAnchor: intent.builderAnchor,
|
|
26321
27108
|
...restored
|
|
26322
27109
|
});
|
|
26323
27110
|
}
|
|
27111
|
+
if (!(creditBinding && !originalData?.fund) && existing?.paymentMethod !== "credit") {
|
|
27112
|
+
const accepted = parseUpfrontPayment(receipt.upfrontPayment);
|
|
27113
|
+
const localPayment = intent.railPayment ?? parseUpfrontRailPayment(existing?.upfrontRailPayment);
|
|
27114
|
+
const method = localPayment?.method ?? existing?.paymentMethod ?? accepted?.rail ?? paymentMethod(receipt);
|
|
27115
|
+
const free = existing?.upfrontRailPayment === "free" || accepted?.amount_msats === 0 && !method;
|
|
27116
|
+
recordUpfrontRailPayment(receipt.jobId, localPayment ?? (free ? "free" : accepted && method ? { method, amountMsats: accepted.amount_msats } : void 0));
|
|
27117
|
+
}
|
|
27118
|
+
recordUpfrontCreditPayment(receipt.jobId, receipt.upfrontPayment, originalData?.fund !== void 0);
|
|
26324
27119
|
if (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled") {
|
|
26325
27120
|
markJobTerminal(receipt.jobId, receipt.status, completionSnapshot(receipt), restored);
|
|
26326
27121
|
} else {
|
|
@@ -26634,6 +27429,99 @@ function outputResults2(resultJson, human, nextAction) {
|
|
|
26634
27429
|
}
|
|
26635
27430
|
}
|
|
26636
27431
|
|
|
27432
|
+
// src/lib/job-spend.ts
|
|
27433
|
+
function jobSpend(job, receipt) {
|
|
27434
|
+
const charges = [];
|
|
27435
|
+
const refunds = [];
|
|
27436
|
+
let request2;
|
|
27437
|
+
for (const message2 of loadMessages(job.id).sort((a, b) => a.seq - b.seq)) {
|
|
27438
|
+
if (message2.from === "provider" && message2.type === "payment-request") request2 = message2;
|
|
27439
|
+
if (message2.type !== "payment") continue;
|
|
27440
|
+
const payment = message2.content;
|
|
27441
|
+
if (message2.from === "provider") {
|
|
27442
|
+
refunds.push({
|
|
27443
|
+
seq: message2.seq,
|
|
27444
|
+
amount_msats: payment.amount_msats,
|
|
27445
|
+
display: formatPaymentAmount(payment.amount_msats ?? 0, void 0, { anchor: false }),
|
|
27446
|
+
reason: asProviderText(payment.reason ?? "refund")
|
|
27447
|
+
});
|
|
27448
|
+
continue;
|
|
27449
|
+
}
|
|
27450
|
+
const requestSeq = payment.credit?.request_seq ?? request2?.seq;
|
|
27451
|
+
const ask = request2 && request2.seq === requestSeq ? request2.content : void 0;
|
|
27452
|
+
const booked = payment.credit && job.bookedCreditPayments?.find((entry) => entry.authorization.payment_id === payment.credit?.payment_id);
|
|
27453
|
+
const amount = booked ? booked.amountMsats ?? booked.request.amount_msats : payment.amount_msats ?? ask?.amount_msats ?? 0;
|
|
27454
|
+
const fiat2 = payment.credit ? { amount: payment.credit.amount_micro / 1e6, currency: payment.credit.currency } : ask?.fiat_amount;
|
|
27455
|
+
charges.push({
|
|
27456
|
+
seq: message2.seq,
|
|
27457
|
+
amount_msats: amount,
|
|
27458
|
+
display: formatPaymentAmount(amount, fiat2, { anchor: false }),
|
|
27459
|
+
...fiat2 && fiat2.amount > 0 ? { fiat_amount: fiat2 } : {},
|
|
27460
|
+
rail: payment.credit ? "credit" : payment.tempo_credential ? "tempo" : payment.x402_payment ? "x402" : payment.cashu_token ? "cashu_p2pk" : "unknown",
|
|
27461
|
+
approval: job.paymentApprovals?.find((entry) => entry.requestSeq === requestSeq)?.approval ?? "unknown",
|
|
27462
|
+
reason: asProviderText(ask?.reason ?? booked?.request.reason ?? "")
|
|
27463
|
+
});
|
|
27464
|
+
request2 = void 0;
|
|
27465
|
+
}
|
|
27466
|
+
const chargeTotal = charges.reduce((sum, charge) => sum + charge.amount_msats, 0);
|
|
27467
|
+
const total = job.totalPaidMsats ?? job.costMsats ?? 0;
|
|
27468
|
+
const knownCredit = job.paymentMethod === "credit" && !hasUnknownUpfrontCredit(job);
|
|
27469
|
+
const upfront = knownCredit ? job.upfrontPayment.amount_msats : Math.max(0, total - chargeTotal);
|
|
27470
|
+
const payments = job.paymentsHonoured ?? charges.length + (upfront > 0 ? 1 : 0);
|
|
27471
|
+
const currency = charges[0]?.fiat_amount?.currency;
|
|
27472
|
+
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;
|
|
27473
|
+
const totalDisplay = formatPaymentAmount(total, fiat, { anchor: false });
|
|
27474
|
+
const budgetDisplay = job.policy ? formatPaymentAmount(
|
|
27475
|
+
job.policy.maxTotalMsats,
|
|
27476
|
+
fiat && total > 0 ? { currency: fiat.currency, amount: fiat.amount * job.policy.maxTotalMsats / total } : void 0,
|
|
27477
|
+
{ anchor: false }
|
|
27478
|
+
) : void 0;
|
|
27479
|
+
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));
|
|
27480
|
+
const receiptMismatch = receipt && job.paymentMethod !== "credit" ? receipt.paid.msats !== total : void 0;
|
|
27481
|
+
const receiptTotalDisplay = receipt ? formatPaymentAmount(receipt.paid.msats, void 0, { anchor: false }) : void 0;
|
|
27482
|
+
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"}`;
|
|
27483
|
+
if (budgetDisplay) display += `, budget ${budgetDisplay}`;
|
|
27484
|
+
if (refunds.length > 0) display += `, ${refunds.length} refund${refunds.length === 1 ? "" : "s"}`;
|
|
27485
|
+
display += ".";
|
|
27486
|
+
if (logMismatch) display += " Local payment log disagrees with the job record.";
|
|
27487
|
+
if (receipt && job.paymentMethod === "credit" && !knownCredit) display += " The receipt total includes the unrecorded credit draw.";
|
|
27488
|
+
const [receiptLabel, localLabel] = receiptTotalDisplay === totalDisplay ? [`${receipt.paid.msats} msats`, `${total} msats`] : [receiptTotalDisplay, totalDisplay];
|
|
27489
|
+
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.`;
|
|
27490
|
+
return {
|
|
27491
|
+
charges,
|
|
27492
|
+
refunds,
|
|
27493
|
+
total_msats: total,
|
|
27494
|
+
total_display: totalDisplay,
|
|
27495
|
+
...upfront > 0 && (job.paymentMethod !== "credit" || knownCredit) ? {
|
|
27496
|
+
upfront_display: formatPaymentAmount(
|
|
27497
|
+
upfront,
|
|
27498
|
+
knownCredit && job.upfrontPayment?.amount_micro !== void 0 ? { amount: job.upfrontPayment.amount_micro / 1e6, currency: job.upfrontPayment.currency } : void 0,
|
|
27499
|
+
{ anchor: false }
|
|
27500
|
+
)
|
|
27501
|
+
} : {},
|
|
27502
|
+
...budgetDisplay ? { budget_display: budgetDisplay } : {},
|
|
27503
|
+
payments,
|
|
27504
|
+
max_payments: job.policy?.maxPayments ?? null,
|
|
27505
|
+
log_mismatch: logMismatch,
|
|
27506
|
+
...receipt ? {
|
|
27507
|
+
receipt_total_display: receiptTotalDisplay,
|
|
27508
|
+
...receiptMismatch !== void 0 ? { receipt_mismatch: receiptMismatch } : {}
|
|
27509
|
+
} : {},
|
|
27510
|
+
display
|
|
27511
|
+
};
|
|
27512
|
+
}
|
|
27513
|
+
function renderSpendHuman(spend, print) {
|
|
27514
|
+
print(spend.display);
|
|
27515
|
+
if (spend.upfront_display) print(` Upfront: ${spend.upfront_display}`);
|
|
27516
|
+
const rails = { cashu_p2pk: "Cashu", tempo: "Tempo", x402: "x402", credit: "prepaid credit", unknown: "payment method not recorded" };
|
|
27517
|
+
const approvals = { auto: "paid automatically", explicit: "you approved", unknown: "approval not recorded" };
|
|
27518
|
+
for (const charge of spend.charges) {
|
|
27519
|
+
print(` [${charge.seq}] ${charge.display} (${rails[charge.rail]}, ${approvals[charge.approval]})${charge.reason.text ? `: ${charge.reason.text}` : ""}`);
|
|
27520
|
+
}
|
|
27521
|
+
for (const refund of spend.refunds) print(` [${refund.seq}] Refund: ${refund.display} (${refund.reason.text})`);
|
|
27522
|
+
if (spend.receipt_total_display) print(` Receipt total: ${spend.receipt_total_display}`);
|
|
27523
|
+
}
|
|
27524
|
+
|
|
26637
27525
|
// src/commands/status.ts
|
|
26638
27526
|
async function status(jobId, opts) {
|
|
26639
27527
|
const access = resolveJobAccess(jobId, opts);
|
|
@@ -26740,10 +27628,11 @@ function transientReceiptCapture(jobId, response) {
|
|
|
26740
27628
|
}
|
|
26741
27629
|
function renderStatus(jobId, stored, jobStatus, completion, source, nextAction, opts, fetched) {
|
|
26742
27630
|
const identifier = stored?.dvmId ? formatIdentifier(stored.dvmId, stored.capability) : void 0;
|
|
26743
|
-
const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount);
|
|
27631
|
+
const hint = nextStepHint(jobId, completion.payloadIn, completion.artifactCount, opts.human);
|
|
26744
27632
|
const msgs = fetched?.msgs ?? [];
|
|
26745
27633
|
const receipt = fetched?.receipt;
|
|
26746
|
-
const content = jobContentFields(jobId, fetched?.content);
|
|
27634
|
+
const content = jobContentFields(jobId, fetched?.content, opts.human);
|
|
27635
|
+
const spend = stored ? jobSpend(loadJob(jobId) ?? stored, receipt?.receipt) : void 0;
|
|
26747
27636
|
if (opts.human) {
|
|
26748
27637
|
if (jobStatus === "completed" && completion.summary) {
|
|
26749
27638
|
info(`Summary:`);
|
|
@@ -26754,17 +27643,18 @@ function renderStatus(jobId, stored, jobStatus, completion, source, nextAction,
|
|
|
26754
27643
|
}
|
|
26755
27644
|
if (jobStatus === "completed" && hint) info(`\u{1F4CE} ${hint}`);
|
|
26756
27645
|
info(String(content.content_hint));
|
|
26757
|
-
if (receipt) renderReceiptHuman(receipt);
|
|
26758
27646
|
if (msgs.length > 0) {
|
|
26759
27647
|
info(`
|
|
26760
27648
|
${msgs.length} new message(s):`);
|
|
26761
|
-
|
|
26762
|
-
|
|
26763
|
-
|
|
26764
|
-
}
|
|
27649
|
+
const artifactSession = createArtifactSaveSession();
|
|
27650
|
+
for (const msg of msgs) formatMessageHuman(msg, jobId, artifactSession);
|
|
27651
|
+
finalizeProgressLine();
|
|
26765
27652
|
}
|
|
26766
27653
|
const traceId = getOutputTraceId();
|
|
26767
27654
|
if (traceId) info(`Trace: ${traceId}`);
|
|
27655
|
+
if (spend) renderSpendHuman(spend, info);
|
|
27656
|
+
if (receipt) renderReceiptHuman(receipt);
|
|
27657
|
+
printNextActionHuman(nextAction);
|
|
26768
27658
|
return;
|
|
26769
27659
|
}
|
|
26770
27660
|
const output = {
|
|
@@ -26773,6 +27663,10 @@ ${msgs.length} new message(s):`);
|
|
|
26773
27663
|
...dvmIdentity(stored?.dvmId, stored?.capability),
|
|
26774
27664
|
status: jobStatus,
|
|
26775
27665
|
source,
|
|
27666
|
+
_provider_fields: [
|
|
27667
|
+
...completion.summary ? ["summary"] : [],
|
|
27668
|
+
...completion.message ? ["message"] : []
|
|
27669
|
+
],
|
|
26776
27670
|
...content,
|
|
26777
27671
|
...completion.summary ? { summary: completion.summary } : {},
|
|
26778
27672
|
...jobStatus === "completed" ? buildCompletionHintFields(jobId, completion) : {},
|
|
@@ -26785,13 +27679,14 @@ ${msgs.length} new message(s):`);
|
|
|
26785
27679
|
// do. Both spread blind and are absent when nothing was stashed.
|
|
26786
27680
|
...takeCreditNoticeFields(),
|
|
26787
27681
|
...takeFeedbackNoticeFields(),
|
|
27682
|
+
...spend ? { spend } : {},
|
|
26788
27683
|
next_action: nextAction
|
|
26789
27684
|
};
|
|
26790
27685
|
if (opts.messages) {
|
|
26791
27686
|
output.messages = msgs.map(serializeMessageForOutput);
|
|
26792
27687
|
output.cursor = fetched?.cursor ?? 0;
|
|
26793
27688
|
}
|
|
26794
|
-
|
|
27689
|
+
providerJobJson(output, !!stored);
|
|
26795
27690
|
}
|
|
26796
27691
|
async function resolveNextAction(jobId, status2, fetched, transport, ref, opts) {
|
|
26797
27692
|
if (isTerminalJobStatus(status2)) return null;
|
|
@@ -26808,16 +27703,16 @@ async function resolveNextAction(jobId, status2, fetched, transport, ref, opts)
|
|
|
26808
27703
|
import { statSync as statSync5 } from "fs";
|
|
26809
27704
|
|
|
26810
27705
|
// src/lib/upload-stream.ts
|
|
26811
|
-
import { createHash as
|
|
26812
|
-
import { createReadStream } from "fs";
|
|
27706
|
+
import { createHash as createHash5 } from "crypto";
|
|
27707
|
+
import { createReadStream as createReadStream2 } from "fs";
|
|
26813
27708
|
import * as http2 from "http";
|
|
26814
27709
|
import * as https from "https";
|
|
26815
27710
|
var UPLOAD_RESPONSE_MAX_BYTES = 64 * 1024;
|
|
26816
27711
|
function hashFile(filePath) {
|
|
26817
27712
|
return new Promise((resolve3, reject) => {
|
|
26818
|
-
const hasher =
|
|
27713
|
+
const hasher = createHash5("sha256");
|
|
26819
27714
|
let sizeBytes = 0;
|
|
26820
|
-
const stream =
|
|
27715
|
+
const stream = createReadStream2(filePath);
|
|
26821
27716
|
stream.on("data", (chunk) => {
|
|
26822
27717
|
const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
26823
27718
|
sizeBytes += buf.byteLength;
|
|
@@ -26918,7 +27813,7 @@ function postOnce(opts, idleTimeoutMs) {
|
|
|
26918
27813
|
req.destroy(new Error(`socket idle for ${idleTimeoutMs.toString()}ms`));
|
|
26919
27814
|
});
|
|
26920
27815
|
req.on("error", reject);
|
|
26921
|
-
const body =
|
|
27816
|
+
const body = createReadStream2(opts.filePath);
|
|
26922
27817
|
body.on("error", (err) => {
|
|
26923
27818
|
req.destroy(err);
|
|
26924
27819
|
reject(err);
|
|
@@ -27349,8 +28244,8 @@ function refusePositionalSecret(value, copy) {
|
|
|
27349
28244
|
}
|
|
27350
28245
|
function hasPipedStdin() {
|
|
27351
28246
|
try {
|
|
27352
|
-
const
|
|
27353
|
-
return
|
|
28247
|
+
const stat2 = fstatSync(0);
|
|
28248
|
+
return stat2.isFIFO() || stat2.isFile();
|
|
27354
28249
|
} catch {
|
|
27355
28250
|
return false;
|
|
27356
28251
|
}
|
|
@@ -29546,7 +30441,8 @@ function handleError(err, human) {
|
|
|
29546
30441
|
const display = typeof dataDisplay === "string" ? dataDisplay : err.display;
|
|
29547
30442
|
const dataNextStep = err.data?.next_step;
|
|
29548
30443
|
const nextStep = typeof dataNextStep === "string" ? dataNextStep : void 0;
|
|
29549
|
-
|
|
30444
|
+
const capabilities = Array.isArray(err.data?.available_capabilities) ? `Available capabilities: ${err.data.available_capabilities.join(", ")}` : void 0;
|
|
30445
|
+
info([`Error: ${err.message}`, display, capabilities, nextStep, err.hint].filter(Boolean).join("\n"));
|
|
29550
30446
|
} else {
|
|
29551
30447
|
const error = {
|
|
29552
30448
|
code: err.code,
|
|
@@ -32635,7 +33531,7 @@ function resolveMppEndpoint(identifier) {
|
|
|
32635
33531
|
}
|
|
32636
33532
|
|
|
32637
33533
|
// src/commands/wallet-pair.ts
|
|
32638
|
-
import { createHash as
|
|
33534
|
+
import { createHash as createHash6, randomBytes as randomBytes5 } from "crypto";
|
|
32639
33535
|
import { hostname } from "os";
|
|
32640
33536
|
|
|
32641
33537
|
// node_modules/@noble/ciphers/_arx.js
|
|
@@ -33454,7 +34350,7 @@ function hexToBytes2(hex) {
|
|
|
33454
34350
|
}
|
|
33455
34351
|
|
|
33456
34352
|
// src/lib/wallet-pairing-store.ts
|
|
33457
|
-
var
|
|
34353
|
+
var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
|
|
33458
34354
|
import {
|
|
33459
34355
|
chmodSync as chmodSync2,
|
|
33460
34356
|
existsSync as existsSync8,
|
|
@@ -33555,7 +34451,7 @@ async function withWalletPairingLock(pairingId, fn) {
|
|
|
33555
34451
|
if (!existsSync8(path)) return fn();
|
|
33556
34452
|
let release;
|
|
33557
34453
|
try {
|
|
33558
|
-
release = await
|
|
34454
|
+
release = await import_proper_lockfile3.default.lock(path, {
|
|
33559
34455
|
lockfilePath: `${path}.lock`,
|
|
33560
34456
|
realpath: false,
|
|
33561
34457
|
stale: 12 * 60 * 1e3,
|
|
@@ -34007,7 +34903,7 @@ function walletFingerprint(uri) {
|
|
|
34007
34903
|
return uri ? sha2562(uri) : null;
|
|
34008
34904
|
}
|
|
34009
34905
|
function sha2562(value) {
|
|
34010
|
-
return
|
|
34906
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
34011
34907
|
}
|
|
34012
34908
|
function relayHost2(relay) {
|
|
34013
34909
|
try {
|
|
@@ -35303,7 +36199,7 @@ function buildProgram() {
|
|
|
35303
36199
|
receiptsShow(jobId, opts);
|
|
35304
36200
|
}, opts.human);
|
|
35305
36201
|
});
|
|
35306
|
-
receipts.command("verify <job-id>").description("Re-verify a stored receipt offline (signature, attestation, result hash)").option("--endpoint <url>", "Re-fetch the DVM's /v1/info instead of using the stored anchor").option("--human", "Human-readable output instead of JSON").action((jobId, opts) => {
|
|
36202
|
+
receipts.command("verify <job-id>").description("Re-verify a stored receipt offline (signature, attestation, result hash)").option("--file <path>", "Check a downloaded file against signed URL artifact fingerprints (repeatable)", collectOption, []).option("--artifact <name-or-index>", "Select an artifact by exact name or 1-based index for --file").option("--endpoint <url>", "Re-fetch the DVM's /v1/info instead of using the stored anchor").option("--human", "Human-readable output instead of JSON").action((jobId, opts) => {
|
|
35307
36203
|
return catchErrors(() => receiptsVerify(jobId, opts), opts.human);
|
|
35308
36204
|
});
|
|
35309
36205
|
receipts.command("export").description("Write the raw receipt collection to stdout as JSONL").option("--dvm <name>", "Only receipts with this DVM display name").option("--dvm-id <id>", "Only receipts issued by this immutable DVM ID").action((opts) => {
|
|
@@ -35389,7 +36285,7 @@ function buildProgram() {
|
|
|
35389
36285
|
).option("--drain-id <id>", "Only the evidence for this drain").option("--export", "Write the raw bundles to stdout as JSONL, un-enveloped").option("--refetch", "Grade against the DVM's live /v1/info instead of the pinned anchor").option("--as <name>", "Caller signing identity whose evidence to read").option("--human", "Human-readable output instead of JSON").action((dvm, opts) => {
|
|
35390
36286
|
return catchErrors(() => creditReceipts(dvm, opts), opts.human);
|
|
35391
36287
|
});
|
|
35392
|
-
program2.command("messages <job-id>").description("Fetch messages from a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--after <seq>", "Only show messages with seq > N").option("--no-stream", "Non-blocking snapshot instead of streaming until yield").option("--human", "Human-readable output instead of JSON").option("--timeout <sec>", "
|
|
36288
|
+
program2.command("messages <job-id>").description("Fetch messages from a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--after <seq>", "Only show messages with seq > N").option("--no-stream", "Non-blocking snapshot instead of streaming until yield").option("--human", "Human-readable output instead of JSON").option("--wait", "Stay attached until the job needs input or ends").option("--until <duration>", "Wait limit with --wait (default: 12h; e.g. 30s, 5m, 12h)").option("--timeout <sec>", "Read timeout (default: 5s, or 60s with --wait)").action((jobId, opts) => {
|
|
35393
36289
|
return catchErrors(() => messages(jobId, opts), opts.human);
|
|
35394
36290
|
});
|
|
35395
36291
|
program2.command("message <job-id> [text]").description("Send a message in a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option(
|