@dvmkit/dvm-cli 0.11.3 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,12 +6,16 @@ import {
6
6
  } from "./chunk-7N3HQJKE.js";
7
7
  import {
8
8
  costAnchor,
9
+ formatAmount,
10
+ formatPaymentAmount,
11
+ formatSats,
9
12
  info,
13
+ json,
10
14
  progress,
11
15
  resolveBtcUsdRate,
12
16
  tryResolveBtcUsdRate,
13
17
  tryX402Payment
14
- } from "./chunk-BPWZNIMS.js";
18
+ } from "./chunk-RMYEB2WG.js";
15
19
  import {
16
20
  loadX402Wallet,
17
21
  x402NetworkLabel
@@ -26,6 +30,7 @@ import {
26
30
  FAVORITES_FILE,
27
31
  JOBS_FILE,
28
32
  JOB_IDENTITY_HEADER,
33
+ MESSAGES_DIR,
29
34
  NwcBackend,
30
35
  NwcError,
31
36
  RECENT_SPENDS_CAP,
@@ -38,6 +43,7 @@ import {
38
43
  appendBudgetSpend,
39
44
  appendFundingReceipt,
40
45
  appendReceipt,
46
+ asProviderText,
41
47
  assertTempoSessionChallengeWithinAsk,
42
48
  assertTempoSessionDepositWithinCap,
43
49
  assertTempoSessionVoucherWithinAsk,
@@ -176,6 +182,7 @@ import {
176
182
  X402_BATCH_SETTLEMENT_SCHEME,
177
183
  X402_EXACT_SCHEME,
178
184
  decodePayment,
185
+ isAbortError,
179
186
  isValidEvmPrivateKey,
180
187
  microToSats,
181
188
  msatsToMicro,
@@ -277,23 +284,23 @@ function floatPaymentJson(payment) {
277
284
  };
278
285
  }
279
286
  function floatPaymentDisplay(payment) {
280
- const principal = formatSats(payment.principalMsats);
287
+ const principal = formatSats2(payment.principalMsats);
281
288
  if (payment.walletDebitMsats === null) {
282
- const routing2 = payment.routingFeeMsats === null ? "The wallet did not report its routing fee." : `The wallet reported ${formatSats(payment.routingFeeMsats)} of routing fee.`;
289
+ const routing2 = payment.routingFeeMsats === null ? "The wallet did not report its routing fee." : `The wallet reported ${formatSats2(payment.routingFeeMsats)} of routing fee.`;
283
290
  return `Invoice principal ${principal}; the total wallet debit and total wallet fee are unknown. ${routing2}`;
284
291
  }
285
292
  if (payment.totalWalletFeeMsats === null) {
286
- return `${formatSats(payment.walletDebitMsats)} went out for invoice principal ${principal}; the total wallet fee is unknown.`;
293
+ return `${formatSats2(payment.walletDebitMsats)} went out for invoice principal ${principal}; the total wallet fee is unknown.`;
287
294
  }
288
- const totalFee = formatSats(payment.totalWalletFeeMsats);
295
+ const totalFee = formatSats2(payment.totalWalletFeeMsats);
289
296
  if (payment.routingFeeMsats === null) {
290
- return `${formatSats(payment.walletDebitMsats)} went out: invoice principal ${principal} and total wallet fee ${totalFee}. The wallet did not report its routing fee, so the fee split is unknown.`;
297
+ return `${formatSats2(payment.walletDebitMsats)} went out: invoice principal ${principal} and total wallet fee ${totalFee}. The wallet did not report its routing fee, so the fee split is unknown.`;
291
298
  }
292
- const routing = formatSats(payment.routingFeeMsats);
299
+ const routing = formatSats2(payment.routingFeeMsats);
293
300
  if (payment.unitemizedWalletFeeMsats === null) {
294
- return `${formatSats(payment.walletDebitMsats)} went out: invoice principal ${principal} and total wallet fee ${totalFee}. The wallet reported ${routing} of routing fee; the remaining fee split is unknown.`;
301
+ return `${formatSats2(payment.walletDebitMsats)} went out: invoice principal ${principal} and total wallet fee ${totalFee}. The wallet reported ${routing} of routing fee; the remaining fee split is unknown.`;
295
302
  }
296
- return `${formatSats(payment.walletDebitMsats)} went out: invoice principal ${principal} and total wallet fee ${totalFee} (${routing} wallet-reported routing fee and ${formatSats(payment.unitemizedWalletFeeMsats)} unitemized wallet fee).`;
303
+ return `${formatSats2(payment.walletDebitMsats)} went out: invoice principal ${principal} and total wallet fee ${totalFee} (${routing} wallet-reported routing fee and ${formatSats2(payment.unitemizedWalletFeeMsats)} unitemized wallet fee).`;
297
304
  }
298
305
  function unrecordedFloatBudgetWarning(float) {
299
306
  if (float.statedBudget) return void 0;
@@ -577,7 +584,7 @@ async function probeOnPool(float, opts) {
577
584
  function backendFor(float, opts) {
578
585
  return new NwcBackend(float.conn, opts);
579
586
  }
580
- function formatSats(msats) {
587
+ function formatSats2(msats) {
581
588
  const sats = msats / 1e3;
582
589
  return `${Number.isInteger(sats) ? sats.toLocaleString("en-US") : String(sats)} sats`;
583
590
  }
@@ -1129,6 +1136,528 @@ function bookCreditPayment(jobId, intent) {
1129
1136
  });
1130
1137
  }
1131
1138
 
1139
+ // src/lib/messages/store.ts
1140
+ import {
1141
+ appendFileSync,
1142
+ closeSync as closeSync2,
1143
+ existsSync as existsSync2,
1144
+ openSync as openSync2,
1145
+ readFileSync as readFileSync2,
1146
+ readSync,
1147
+ statSync
1148
+ } from "fs";
1149
+ import { join } from "path";
1150
+ var CHECKPOINT_BYTES = 64;
1151
+ function appendMessages(jobId, messages) {
1152
+ if (messages.length === 0) return;
1153
+ createMessageAppendSession(jobId).append(messages);
1154
+ }
1155
+ function createMessageAppendSession(jobId) {
1156
+ return new FileMessageAppendSession(messageFilePath(jobId));
1157
+ }
1158
+ var FileMessageAppendSession = class {
1159
+ constructor(filePath) {
1160
+ this.filePath = filePath;
1161
+ this.syncFromDisk();
1162
+ }
1163
+ filePath;
1164
+ seqs = /* @__PURE__ */ new Set();
1165
+ identity;
1166
+ offset = 0;
1167
+ pending = Buffer.alloc(0);
1168
+ checkpoint = Buffer.alloc(0);
1169
+ modifiedAt = 0;
1170
+ append(messages) {
1171
+ if (messages.length === 0) return;
1172
+ this.syncFromDisk();
1173
+ const selectedSeqs = new Set(this.seqs);
1174
+ const newMessages = messages.filter((message) => {
1175
+ if (selectedSeqs.has(message.seq)) return false;
1176
+ selectedSeqs.add(message.seq);
1177
+ return true;
1178
+ });
1179
+ if (newMessages.length === 0) return;
1180
+ ensureConfigSubdir(MESSAGES_DIR);
1181
+ const lines = newMessages.map((message) => JSON.stringify(message)).join("\n") + "\n";
1182
+ appendFileSync(this.filePath, lines);
1183
+ this.syncFromDisk();
1184
+ }
1185
+ syncFromDisk() {
1186
+ const snapshot = statFile(this.filePath);
1187
+ if (!snapshot) {
1188
+ this.reset();
1189
+ return;
1190
+ }
1191
+ const identity = fileIdentity(snapshot);
1192
+ const changedFile = !this.identity || !sameIdentity(this.identity, identity);
1193
+ const shrank = snapshot.size < this.offset;
1194
+ const changedSinceRead = snapshot.size !== this.offset || Math.max(snapshot.mtimeMs, snapshot.ctimeMs) !== this.modifiedAt;
1195
+ if (changedFile || shrank || changedSinceRead && !this.checkpointMatches()) {
1196
+ this.reset(identity);
1197
+ }
1198
+ this.identity = identity;
1199
+ this.modifiedAt = Math.max(snapshot.mtimeMs, snapshot.ctimeMs);
1200
+ if (snapshot.size <= this.offset) return;
1201
+ const bytes = readRange(this.filePath, this.offset, snapshot.size);
1202
+ this.offset += bytes.byteLength;
1203
+ this.consume(bytes);
1204
+ this.checkpoint = trailingBytes(this.checkpoint, bytes, CHECKPOINT_BYTES);
1205
+ }
1206
+ checkpointMatches() {
1207
+ if (this.checkpoint.length === 0 || this.offset < this.checkpoint.length) return true;
1208
+ const actual = readRange(
1209
+ this.filePath,
1210
+ this.offset - this.checkpoint.length,
1211
+ this.offset
1212
+ );
1213
+ return actual.equals(this.checkpoint);
1214
+ }
1215
+ consume(bytes) {
1216
+ const combined = Buffer.concat([this.pending, bytes]);
1217
+ const finalNewline = combined.lastIndexOf(10);
1218
+ if (finalNewline === -1) {
1219
+ this.pending = combined;
1220
+ this.parseLine(this.pending);
1221
+ return;
1222
+ }
1223
+ const complete = combined.subarray(0, finalNewline).toString("utf8");
1224
+ for (const line of complete.split("\n")) this.parseLine(line);
1225
+ this.pending = combined.subarray(finalNewline + 1);
1226
+ this.parseLine(this.pending);
1227
+ }
1228
+ parseLine(line) {
1229
+ const text = line.toString().trim();
1230
+ if (!text) return;
1231
+ try {
1232
+ const message = JSON.parse(text);
1233
+ this.seqs.add(message.seq);
1234
+ } catch {
1235
+ }
1236
+ }
1237
+ reset(identity) {
1238
+ this.seqs.clear();
1239
+ this.identity = identity;
1240
+ this.offset = 0;
1241
+ this.pending = Buffer.alloc(0);
1242
+ this.checkpoint = Buffer.alloc(0);
1243
+ this.modifiedAt = 0;
1244
+ }
1245
+ };
1246
+ function loadMessages(jobId, after) {
1247
+ const filePath = messageFilePath(jobId);
1248
+ if (!existsSync2(filePath)) return [];
1249
+ const content = readFileSync2(filePath, "utf-8").trim();
1250
+ if (!content) return [];
1251
+ const messages = [];
1252
+ for (const line of content.split("\n")) {
1253
+ if (!line.trim()) continue;
1254
+ try {
1255
+ const msg = JSON.parse(line);
1256
+ if (after === void 0 || msg.seq > after) {
1257
+ messages.push(msg);
1258
+ }
1259
+ } catch {
1260
+ }
1261
+ }
1262
+ return messages;
1263
+ }
1264
+ function messageFilePath(jobId) {
1265
+ return join(MESSAGES_DIR, `${jobId}.jsonl`);
1266
+ }
1267
+ function statFile(filePath) {
1268
+ try {
1269
+ return statSync(filePath);
1270
+ } catch (error) {
1271
+ if (error.code === "ENOENT") return void 0;
1272
+ throw error;
1273
+ }
1274
+ }
1275
+ function fileIdentity(stats) {
1276
+ return { dev: stats.dev, ino: stats.ino };
1277
+ }
1278
+ function sameIdentity(left, right) {
1279
+ return left.dev === right.dev && left.ino === right.ino;
1280
+ }
1281
+ function readRange(filePath, start, end) {
1282
+ const expected = Math.max(0, end - start);
1283
+ const buffer = Buffer.allocUnsafe(expected);
1284
+ const fd = openSync2(filePath, "r");
1285
+ let total = 0;
1286
+ try {
1287
+ while (total < expected) {
1288
+ const read = readSync(fd, buffer, total, expected - total, start + total);
1289
+ if (read === 0) break;
1290
+ total += read;
1291
+ }
1292
+ } finally {
1293
+ closeSync2(fd);
1294
+ }
1295
+ return total === expected ? buffer : buffer.subarray(0, total);
1296
+ }
1297
+ function trailingBytes(previous, next, limit) {
1298
+ if (next.length >= limit) return Buffer.from(next.subarray(next.length - limit));
1299
+ const combined = Buffer.concat([previous, next]);
1300
+ return Buffer.from(combined.subarray(Math.max(0, combined.length - limit)));
1301
+ }
1302
+
1303
+ // src/lib/messages/index.ts
1304
+ function maxSeq(msgs, fallback) {
1305
+ if (msgs.length === 0) return fallback;
1306
+ return Math.max(...msgs.map((m) => m.seq));
1307
+ }
1308
+
1309
+ // src/lib/provider-output.ts
1310
+ function providerFields(value, fields = Object.keys(value)) {
1311
+ return {
1312
+ ...value,
1313
+ _provider_fields: [.../* @__PURE__ */ new Set([
1314
+ ...Array.isArray(value._provider_fields) ? value._provider_fields : [],
1315
+ ...fields.filter((field) => field !== "_provider_fields" && value[field] !== void 0)
1316
+ ])]
1317
+ };
1318
+ }
1319
+ function guidanceJobArg(jobId) {
1320
+ return /^[A-Za-z0-9_-]+$/.test(jobId) ? shellQuoteArg(jobId) : "'<job_id>'";
1321
+ }
1322
+ function providerJobJson(data, providerJob = true) {
1323
+ const action = data.next_action;
1324
+ json(providerFields({
1325
+ ...data,
1326
+ ...providerJob && action && typeof action === "object" ? { next_action: providerFields(action, ["job_id"]) } : {}
1327
+ }, [...providerJob ? ["jobId"] : [], "capability", "identifier"]));
1328
+ }
1329
+
1330
+ // src/lib/yield-state.ts
1331
+ var JOB_READ_TIMEOUT_MS = 6e4;
1332
+ var PAYMENT_SETTLE_WINDOW_MS = 45e3;
1333
+ function answeredYieldSeqs(messages) {
1334
+ const answered = /* @__PURE__ */ new Set();
1335
+ const prompts = /* @__PURE__ */ new Map();
1336
+ let paymentRequest;
1337
+ for (const message of [...messages].sort((a, b) => a.seq - b.seq)) {
1338
+ if (message.from === "provider") {
1339
+ if (message.type === "payment-request") paymentRequest = message.seq;
1340
+ if (message.type === "prompt") prompts.set(message.content.id, message.seq);
1341
+ } else if (message.type === "response") {
1342
+ const seq = prompts.get(message.content.prompt_id);
1343
+ if (seq !== void 0) answered.add(seq);
1344
+ } else if (message.type === "payment") {
1345
+ const seq = message.content.credit?.request_seq ?? paymentRequest;
1346
+ if (seq !== void 0) answered.add(seq);
1347
+ }
1348
+ }
1349
+ return answered;
1350
+ }
1351
+ function latestProviderPaymentRequest(messages) {
1352
+ return [...messages].sort((a, b) => a.seq - b.seq).findLast((message) => message.from === "provider" && message.type === "payment-request");
1353
+ }
1354
+ function pendingPaymentRequest(messages, answered = answeredYieldSeqs(messages)) {
1355
+ const latest = latestProviderPaymentRequest(messages);
1356
+ if (!latest || answered.has(latest.seq)) return void 0;
1357
+ if (messages.some((message) => message.from === "provider" && message.seq > latest.seq && (message.type === "complete" || message.type === "cancel" || message.type === "working"))) return void 0;
1358
+ return latest;
1359
+ }
1360
+ function loadAnsweredYieldSeqs(jobId) {
1361
+ const answered = answeredYieldSeqs(loadMessages(jobId));
1362
+ const job = loadJob(jobId);
1363
+ for (const seq of job?.paidPaymentRequestSeqs ?? []) answered.add(seq);
1364
+ for (const payment of job?.bookedCreditPayments ?? []) answered.add(payment.authorization.request_seq);
1365
+ return answered;
1366
+ }
1367
+ async function reconcileInFlightPaymentRequest(jobId, requestSeq, transport, provider, options) {
1368
+ const boundedOptions = { ...options, timeoutMs: options.timeoutMs ?? JOB_READ_TIMEOUT_MS };
1369
+ const history = await boundedPaymentRead(jobId, () => transport.getMessages(jobId, 0, provider, boundedOptions), boundedOptions.timeoutMs);
1370
+ const decisionTime = Date.now();
1371
+ const needsStatus = !answeredYieldSeqs(history).has(requestSeq) && decisionTime >= settleUntilMs(jobId, requestSeq, decisionTime);
1372
+ const status = needsStatus ? (await boundedPaymentRead(jobId, () => transport.status(jobId, provider, boundedOptions), boundedOptions.timeoutMs)).status : void 0;
1373
+ return reconcilePaymentRequestHistory(jobId, requestSeq, history, status, () => decisionTime);
1374
+ }
1375
+ function reconcilePaymentRequestHistory(jobId, requestSeq, history, status, now = Date.now) {
1376
+ if (answeredYieldSeqs(history).has(requestSeq)) {
1377
+ markPaymentRequestPaid(jobId, requestSeq);
1378
+ return true;
1379
+ }
1380
+ const superseded = (latestProviderPaymentRequest(history)?.seq ?? -1) > requestSeq;
1381
+ if (superseded) clearPaymentRequestInFlight(jobId, requestSeq);
1382
+ const decisionTime = now();
1383
+ const retryAt = settleUntilMs(jobId, requestSeq, decisionTime);
1384
+ const seconds = Math.ceil((retryAt - decisionTime) / 1e3);
1385
+ if (!superseded && decisionTime < retryAt)
1386
+ throw new DvmError(
1387
+ "payment_settling",
1388
+ "The previous payment may still be processing.",
1389
+ `Retry with \`dvm pay ${shellQuoteArg(jobId)}\` in about ${seconds} ${seconds === 1 ? "second" : "seconds"}, or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`,
1390
+ { retry_at_ms: retryAt }
1391
+ );
1392
+ if (status !== "awaiting-input" || pendingPaymentRequest(history)?.seq !== requestSeq)
1393
+ throw new DvmError(
1394
+ "payment_request_not_pending",
1395
+ "The provider is no longer waiting on this payment request.",
1396
+ `Check the job with \`dvm messages ${shellQuoteArg(jobId)} --wait\` before paying again.`
1397
+ );
1398
+ return false;
1399
+ }
1400
+ function settleUntilMs(jobId, requestSeq, now) {
1401
+ const startedAt = loadJob(jobId)?.inFlightPaymentRequestStartedAtMs?.[requestSeq];
1402
+ return startedAt === void 0 ? 0 : Math.min(startedAt + PAYMENT_SETTLE_WINDOW_MS, now + PAYMENT_SETTLE_WINDOW_MS);
1403
+ }
1404
+ async function boundedPaymentRead(jobId, read, timeoutMs) {
1405
+ let timer;
1406
+ try {
1407
+ return await Promise.race([read(), new Promise((_, reject) => {
1408
+ timer = setTimeout(() => reject(new DvmError("timeout", "Payment recovery read timed out. No new payment was sent.")), timeoutMs);
1409
+ })]);
1410
+ } catch (error) {
1411
+ if (isAbortError(error) || error instanceof DvmError && error.code === "timeout")
1412
+ throw new DvmError(
1413
+ "timeout",
1414
+ "Payment recovery read timed out. No new payment was sent.",
1415
+ `Retry with \`dvm pay ${shellQuoteArg(jobId)}\` or keep watching with \`dvm messages ${shellQuoteArg(jobId)} --wait\`.`
1416
+ );
1417
+ throw error;
1418
+ } finally {
1419
+ if (timer) clearTimeout(timer);
1420
+ }
1421
+ }
1422
+
1423
+ // src/lib/next-action.ts
1424
+ function isTerminalJobStatus(status) {
1425
+ return TERMINAL_STATUSES.has(status);
1426
+ }
1427
+ function pollNextAction(jobId, hint) {
1428
+ return {
1429
+ type: "poll",
1430
+ job_id: jobId,
1431
+ hint: hint ?? `Provider is still working. Keep the job moving unattended with \`dvm messages ${guidanceJobArg(jobId)} --wait\`.`
1432
+ };
1433
+ }
1434
+ function paymentInFlightHint(jobId) {
1435
+ 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.`;
1436
+ }
1437
+ var YIELD_TYPES = /* @__PURE__ */ new Set(["prompt", "payment-request", "working", "complete", "cancel"]);
1438
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
1439
+ "completed",
1440
+ "failed",
1441
+ "cancelled"
1442
+ ]);
1443
+ function computeNextAction(jobId, messages, nowMs = Date.now(), context) {
1444
+ const answered = answeredYieldSeqs(messages);
1445
+ const expiresAtMs = pendingDeadline(messages, answered);
1446
+ for (let i = messages.length - 1; i >= 0; i--) {
1447
+ const msg = messages[i];
1448
+ if (!YIELD_TYPES.has(msg.type) || answered.has(msg.seq)) continue;
1449
+ switch (msg.type) {
1450
+ case "complete":
1451
+ case "cancel":
1452
+ return null;
1453
+ case "prompt": {
1454
+ const c = msg.content;
1455
+ const answer = c.schema ? "--json '<object matching schema>'" : '"<answer>"';
1456
+ const choices = c.options?.length ? ` Choices: ${c.options.map((option) => JSON.stringify(option)).join(", ")}.` : "";
1457
+ const choiceHint = !c.schema && c.options?.length ? " Answer with exactly one of options unless the human chose otherwise." : "";
1458
+ const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Answer" : "Reply", expiresAtMs, nowMs, jobId);
1459
+ const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
1460
+ const action = {
1461
+ type: "respond",
1462
+ job_id: jobId,
1463
+ prompt_id: c.id,
1464
+ prompt: asProviderText(c.text),
1465
+ _provider_fields: [
1466
+ "prompt_id",
1467
+ ...c.schema ? ["schema"] : [],
1468
+ ...c.options?.length ? ["options"] : []
1469
+ ],
1470
+ display: withDeadline(`The provider asks: ${c.text}${choices}`, deadline),
1471
+ 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)
1472
+ };
1473
+ if (c.schema) action.schema = c.schema;
1474
+ if (c.options?.length) action.options = c.options;
1475
+ if (expiresAtMs !== void 0) action.expires_at_ms = expiresAtMs;
1476
+ return action;
1477
+ }
1478
+ case "payment-request": {
1479
+ const c = msg.content;
1480
+ const display = formatPaymentAmount(c.amount_msats, c.fiat_amount);
1481
+ 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);
1482
+ const priceGuidance = safeCurrency ? display : "see the provider price in next_action.fiat_amount";
1483
+ const deadline = deadlineClause(expiresAtMs === validDeadline(c.expires_at_ms) ? "Pay" : "Reply", expiresAtMs, nowMs, jobId);
1484
+ const expired = expiresAtMs !== void 0 && expiresAtMs <= nowMs;
1485
+ const policy = context?.policy;
1486
+ const thresholdHint = !expired && policy && Number.isSafeInteger(c.amount_msats) && c.amount_msats > policy.autoPayBelowMsats && (context?.totalPaidMsats ?? 0) + c.amount_msats <= policy.maxTotalMsats && (policy.maxIncrementMsats === 0 || c.amount_msats <= policy.maxIncrementMsats) ? ` For the next run, use --auto-pay-below ${c.amount_msats} within your approved budget; other payment limits still apply.` : "";
1487
+ return {
1488
+ type: "pay",
1489
+ job_id: jobId,
1490
+ amount_msats: c.amount_msats,
1491
+ // Mirror only a fiat figure the display actually led with: echoing a
1492
+ // zero amount would tell an agent doing budget math the charge is free.
1493
+ ...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount, _provider_fields: ["fiat_amount"] } : {},
1494
+ ...expiresAtMs !== void 0 ? { expires_at_ms: expiresAtMs } : {},
1495
+ display: withDeadline(display, deadline),
1496
+ reason: asProviderText(c.reason),
1497
+ hint: expired ? deadline : withDeadline(`Payment required to continue: ${priceGuidance}. Relay that amount to your human and get approval, then run \`dvm pay ${guidanceJobArg(jobId)}\`. Provider's stated reason is wrapped as { _source: "provider", text: ... } \u2014 verify it matches the work you expect.`, deadline) + thresholdHint
1498
+ };
1499
+ }
1500
+ case "working": {
1501
+ const c = msg.content;
1502
+ return {
1503
+ type: "poll",
1504
+ job_id: jobId,
1505
+ estimate_seconds: c.estimate_seconds,
1506
+ hint: c.hint !== void 0 ? asProviderText(c.hint) : pollNextAction(jobId).hint
1507
+ };
1508
+ }
1509
+ }
1510
+ }
1511
+ return null;
1512
+ }
1513
+ function pendingDeadline(messages, answered) {
1514
+ const prompts = /* @__PURE__ */ new Map();
1515
+ let payment;
1516
+ for (const message of [...messages].sort((a, b) => a.seq - b.seq)) {
1517
+ if (message.from === "provider" && message.type === "prompt") {
1518
+ prompts.set(message.content.id, validDeadline(message.content.expires_at_ms));
1519
+ } else if (message.from === "requester" && message.type === "response") {
1520
+ prompts.delete(message.content.prompt_id);
1521
+ } else if (message.from === "provider" && message.type === "payment-request") {
1522
+ payment = !answered.has(message.seq) && message.content.amount_msats > 0 ? validDeadline(message.content.expires_at_ms) : void 0;
1523
+ }
1524
+ }
1525
+ let earliest = payment;
1526
+ for (const deadline of prompts.values()) {
1527
+ if (deadline !== void 0 && (earliest === void 0 || deadline < earliest)) earliest = deadline;
1528
+ }
1529
+ return earliest;
1530
+ }
1531
+ function validDeadline(value) {
1532
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 864e13 ? value : void 0;
1533
+ }
1534
+ function withDeadline(display, deadline) {
1535
+ if (!deadline) return display;
1536
+ return `${display}${/[.!?]$/.test(display) ? "" : "."} ${deadline}`;
1537
+ }
1538
+ function deadlineClause(action, expiresAtMs, nowMs, jobId) {
1539
+ if (expiresAtMs === void 0) return "";
1540
+ const deadline = new Date(expiresAtMs).toISOString().slice(0, 16).replace("T", " ") + " UTC";
1541
+ if (expiresAtMs <= nowMs) {
1542
+ return `The deadline to ${action.toLowerCase()} (${deadline}) has passed. The provider will probably cancel the job. Check its status with \`dvm status ${guidanceJobArg(jobId)}\`.`;
1543
+ }
1544
+ const minutes = Math.floor((expiresAtMs - nowMs) / 6e4);
1545
+ const hours = Math.floor(minutes / 60);
1546
+ 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";
1547
+ return `${action} by ${deadline} (in ${remaining}), or the provider cancels the job.`;
1548
+ }
1549
+
1550
+ // src/lib/job-settlement.ts
1551
+ function amountDisplay(msats, rail, rate) {
1552
+ const amount = rate === void 0 ? formatPaymentAmount(msats, void 0, { anchor: false }) : rate > 0 ? formatAmount(msats, rate, { anchor: false }) : formatSats(msats);
1553
+ return amount + (rail === "tempo" || rail === "x402" ? " (BTC valuation)" : "");
1554
+ }
1555
+ function unknownSettlement(rail) {
1556
+ return {
1557
+ status: "unknown",
1558
+ settled_msats: null,
1559
+ refunded_msats: 0,
1560
+ rail,
1561
+ evidence: "unknown",
1562
+ display: "Settlement unknown; recorded payments do not prove a final charge or return."
1563
+ };
1564
+ }
1565
+ function receiptSettlement(receipt, verification, rate) {
1566
+ const rail = receipt.paid.rail;
1567
+ if (verification !== "verified" && verification !== "verified_unattested") return unknownSettlement(rail);
1568
+ const amount = amountDisplay(receipt.paid.msats, rail, rate);
1569
+ if (receipt.outcome === "completed") {
1570
+ return {
1571
+ status: receipt.paid.msats === 0 ? "free" : "settled",
1572
+ settled_msats: receipt.paid.msats,
1573
+ refunded_msats: 0,
1574
+ rail,
1575
+ evidence: "receipt",
1576
+ display: receipt.paid.msats === 0 ? "This was a free job." : `Settled ${amount}${rail ? ` via ${rail}` : ""}.`
1577
+ };
1578
+ }
1579
+ if (receipt.credit) {
1580
+ return {
1581
+ status: "released",
1582
+ settled_msats: 0,
1583
+ released_msats: receipt.paid.msats,
1584
+ refunded_msats: 0,
1585
+ rail,
1586
+ evidence: "receipt",
1587
+ display: `Released ${amount} to the provider credit balance${rail ? ` (funding rail: ${rail})` : ""}; no job charge.`
1588
+ };
1589
+ }
1590
+ return unknownSettlement(rail);
1591
+ }
1592
+ function jobSettlement(job, offeredReceipt) {
1593
+ const receipt = offeredReceipt ?? (isSignedJobReceipt(job.receipt) ? job.receipt : void 0);
1594
+ const rail = receipt?.paid.rail ?? job.upfrontPayment?.rail ?? job.paymentMethod ?? null;
1595
+ const total = job.totalPaidMsats ?? job.costMsats;
1596
+ const log = loadMessages(job.id);
1597
+ const inbound = log.filter((message) => message.from === "provider" && message.type === "payment" && message.content.cashu_token && (message.content.reason ?? "refund") === "refund");
1598
+ let refunded = 0;
1599
+ let pending = false;
1600
+ for (const message of inbound) {
1601
+ const amount = job.claimedPaymentAmountsMsats?.[message.seq];
1602
+ if (job.claimedPaymentSeqs?.includes(message.seq) && amount !== void 0 && Number.isSafeInteger(amount) && amount > 0)
1603
+ refunded += amount;
1604
+ else pending = true;
1605
+ }
1606
+ const verified = receipt ? verifyJobReceipt({ receipt, expectedJobId: job.id, builder: job.builderAnchor }) : void 0;
1607
+ const summary = receipt && verified ? receiptSettlement(receipt, verified.status) : void 0;
1608
+ const matching = receipt?.outcome === job.status;
1609
+ if (!isTerminalJobStatus(job.status)) {
1610
+ return {
1611
+ status: "pending",
1612
+ settled_msats: null,
1613
+ refunded_msats: refunded,
1614
+ rail,
1615
+ evidence: "local",
1616
+ display: "Settlement pending; payments sent or held are not the final job charge."
1617
+ };
1618
+ }
1619
+ if (refunded > 0 || pending) {
1620
+ const soundReceipt = matching && (verified?.status === "verified" || verified?.status === "verified_unattested");
1621
+ const expectedTotal = soundReceipt ? receipt.paid.msats : total;
1622
+ const converted = [
1623
+ rail,
1624
+ job.paymentMethod,
1625
+ job.upfrontPayment?.rail,
1626
+ typeof job.upfrontRailPayment === "object" ? job.upfrontRailPayment.method : void 0
1627
+ ].some((method) => method === "tempo" || method === "x402") || log.some((message) => message.from === "requester" && message.type === "payment" && (message.content.tempo_credential || message.content.x402_payment));
1628
+ const full = expectedTotal !== void 0 && expectedTotal > 0 && refunded >= expectedTotal && !converted && (soundReceipt || !hasUnknownUpfrontCredit(job) && !hasUnknownUpfrontRail(job));
1629
+ return {
1630
+ status: full ? "refunded" : pending ? "pending" : "unknown",
1631
+ settled_msats: full ? 0 : null,
1632
+ refunded_msats: refunded,
1633
+ rail: "cashu",
1634
+ evidence: refunded > 0 ? "wallet" : "unknown",
1635
+ display: `${refunded > 0 ? `Refunded ${amountDisplay(refunded, "cashu")} via cashu into your wallet.` : "Refund pending via cashu; no wallet-confirmed amount is recorded."}` + (full ? " No net job charge." : refunded > 0 ? " Final net charge is unknown." : "")
1636
+ };
1637
+ }
1638
+ if (matching && summary && summary.status !== "unknown") return summary;
1639
+ if (summary) return unknownSettlement(rail);
1640
+ if (job.status === "completed" && !hasUnknownUpfrontCredit(job) && !hasUnknownUpfrontRail(job)) {
1641
+ const amount = total ?? 0;
1642
+ return {
1643
+ status: amount === 0 ? "free" : "settled",
1644
+ settled_msats: amount,
1645
+ refunded_msats: 0,
1646
+ rail,
1647
+ evidence: "local",
1648
+ display: amount === 0 ? "This job was free." : `Settled ${amountDisplay(amount, rail)}${rail ? ` via ${rail}` : ""}.`
1649
+ };
1650
+ }
1651
+ return unknownSettlement(rail);
1652
+ }
1653
+ function terminalSettlementFields(jobId, options = {}) {
1654
+ const stored = options.persistLocalState === false ? null : loadJob(jobId);
1655
+ const status = options.status ?? stored?.status ?? options.receipt?.outcome;
1656
+ if (!status || !isTerminalJobStatus(status)) return {};
1657
+ const job = stored ? { ...stored, status } : { id: jobId, endpoint: "", submittedAt: 0, status };
1658
+ return { settlement: options.persistLocalState === false ? options.receipt && options.receipt.outcome === status ? receiptSettlement(options.receipt, verifyJobReceipt({ receipt: options.receipt, expectedJobId: jobId }).status) : unknownSettlement(null) : jobSettlement(job, options.receipt) };
1659
+ }
1660
+
1132
1661
  // src/lib/receipt-verify.ts
1133
1662
  function drainReceiptsDisplay(status, sound, total) {
1134
1663
  const tally = `${String(sound)} of ${String(total)}`;
@@ -1158,7 +1687,9 @@ function drainReceiptsHint(status) {
1158
1687
  function receiptDisplay(receipt, status, rate = 0) {
1159
1688
  const what = `${receipt.dvm}/${receipt.capability} (DVM ID ${receipt.dvm_id})`;
1160
1689
  const when = receiptIssuedAtIso(receipt)?.slice(0, 10);
1161
- return `${VERDICT_PREFIX[status]}: paid ${formatPaid(receipt.paid.msats, rate)} for ${what}, ${receipt.outcome}${when ? ` ${when}` : ""}.`;
1690
+ const settlement = receiptSettlement(receipt, status, rate);
1691
+ const payment = settlement.status === "settled" ? `Settled ${formatPaid(receipt.paid.msats, rate)}` : settlement.status === "free" ? "free job" : settlement.display.replace(/\.$/, "");
1692
+ return `${VERDICT_PREFIX[status]}: ${payment} for ${what}, ${receipt.outcome}${when ? ` ${when}` : ""}.`;
1162
1693
  }
1163
1694
  function receiptIssuedAtIso(receipt) {
1164
1695
  const seconds = receipt.issued_at;
@@ -1236,13 +1767,13 @@ function formatPaid(msats, rate) {
1236
1767
  // src/lib/favorites.ts
1237
1768
  var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
1238
1769
  import {
1239
- closeSync as closeSync2,
1770
+ closeSync as closeSync3,
1240
1771
  fchmodSync,
1241
1772
  fsyncSync as fsyncSync2,
1242
- openSync as openSync2,
1243
- readFileSync as readFileSync2,
1773
+ openSync as openSync3,
1774
+ readFileSync as readFileSync3,
1244
1775
  renameSync as renameSync2,
1245
- statSync,
1776
+ statSync as statSync2,
1246
1777
  unlinkSync,
1247
1778
  writeFileSync as writeFileSync2
1248
1779
  } from "fs";
@@ -1251,7 +1782,7 @@ var DEFAULT_FILE_MODE = 384;
1251
1782
  function loadFavorites() {
1252
1783
  let raw;
1253
1784
  try {
1254
- raw = readFileSync2(FAVORITES_FILE, "utf8");
1785
+ raw = readFileSync3(FAVORITES_FILE, "utf8");
1255
1786
  } catch (error) {
1256
1787
  if (nodeErrorCode(error) === "ENOENT") return {};
1257
1788
  throw unreadableFavorites(error);
@@ -1339,18 +1870,18 @@ function writeFavorites(favorites) {
1339
1870
  const contents = JSON.stringify(favorites, null, 2) + "\n";
1340
1871
  let fd;
1341
1872
  try {
1342
- fd = openSync2(temporary, "wx", mode);
1873
+ fd = openSync3(temporary, "wx", mode);
1343
1874
  fchmodSync(fd, mode);
1344
1875
  writeFileSync2(fd, contents);
1345
1876
  fsyncSync2(fd);
1346
- closeSync2(fd);
1877
+ closeSync3(fd);
1347
1878
  fd = void 0;
1348
1879
  renameSync2(temporary, FAVORITES_FILE);
1349
1880
  fsyncDirectory(dirname2(FAVORITES_FILE));
1350
1881
  } catch (error) {
1351
1882
  if (fd !== void 0) {
1352
1883
  try {
1353
- closeSync2(fd);
1884
+ closeSync3(fd);
1354
1885
  } catch {
1355
1886
  }
1356
1887
  }
@@ -1363,7 +1894,7 @@ function writeFavorites(favorites) {
1363
1894
  }
1364
1895
  function favoritesFileMode() {
1365
1896
  try {
1366
- return statSync(FAVORITES_FILE).mode & 511;
1897
+ return statSync2(FAVORITES_FILE).mode & 511;
1367
1898
  } catch (error) {
1368
1899
  if (nodeErrorCode(error) === "ENOENT") return DEFAULT_FILE_MODE;
1369
1900
  throw error;
@@ -1371,11 +1902,11 @@ function favoritesFileMode() {
1371
1902
  }
1372
1903
  function fsyncDirectory(path) {
1373
1904
  if (process.platform === "win32") return;
1374
- const fd = openSync2(path, "r");
1905
+ const fd = openSync3(path, "r");
1375
1906
  try {
1376
1907
  fsyncSync2(fd);
1377
1908
  } finally {
1378
- closeSync2(fd);
1909
+ closeSync3(fd);
1379
1910
  }
1380
1911
  }
1381
1912
  function randomSuffix() {
@@ -1410,17 +1941,17 @@ function isFavorite(value) {
1410
1941
  // src/lib/submission-evidence.ts
1411
1942
  import { createHash, randomUUID } from "crypto";
1412
1943
  import {
1413
- closeSync as closeSync3,
1414
- existsSync as existsSync2,
1944
+ closeSync as closeSync4,
1945
+ existsSync as existsSync3,
1415
1946
  fsyncSync as fsyncSync3,
1416
1947
  linkSync,
1417
- openSync as openSync3,
1948
+ openSync as openSync4,
1418
1949
  readdirSync,
1419
- readFileSync as readFileSync3,
1950
+ readFileSync as readFileSync4,
1420
1951
  unlinkSync as unlinkSync2,
1421
1952
  writeFileSync as writeFileSync3
1422
1953
  } from "fs";
1423
- import { join } from "path";
1954
+ import { join as join2 } from "path";
1424
1955
 
1425
1956
  // src/lib/job-identity.ts
1426
1957
  var IDENTITY_FAILURE_CODES = {
@@ -1599,7 +2130,7 @@ function optionalField(key, value) {
1599
2130
  }
1600
2131
 
1601
2132
  // src/lib/submission-evidence.ts
1602
- var SUBMISSION_EVIDENCE_DIR = join(CONFIG_DIR, "submission-evidence");
2133
+ var SUBMISSION_EVIDENCE_DIR = join2(CONFIG_DIR, "submission-evidence");
1603
2134
  function submissionEvidenceKey(args) {
1604
2135
  return args.cashuRequestId ?? args.publicRequestId ?? randomUUID();
1605
2136
  }
@@ -1667,17 +2198,17 @@ function identityFailureRecorded(err) {
1667
2198
  }
1668
2199
  function loadSubmissionEvidence(ambiguityId) {
1669
2200
  const path = evidencePath(ambiguityId);
1670
- if (!existsSync2(path)) return null;
2201
+ if (!existsSync3(path)) return null;
1671
2202
  const record = readRecord(path);
1672
2203
  if (record.ambiguity_id !== ambiguityId) throw unreadable(path, "key mismatch");
1673
2204
  return record;
1674
2205
  }
1675
2206
  function listSubmissionEvidence() {
1676
- if (!existsSync2(SUBMISSION_EVIDENCE_DIR)) return { records: [], unreadable: [] };
2207
+ if (!existsSync3(SUBMISSION_EVIDENCE_DIR)) return { records: [], unreadable: [] };
1677
2208
  const records = [];
1678
2209
  const unreadable2 = [];
1679
2210
  for (const name of readdirSync(SUBMISSION_EVIDENCE_DIR).filter((n) => n.endsWith(".json"))) {
1680
- const path = join(SUBMISSION_EVIDENCE_DIR, name);
2211
+ const path = join2(SUBMISSION_EVIDENCE_DIR, name);
1681
2212
  try {
1682
2213
  records.push(readRecord(path));
1683
2214
  } catch (error) {
@@ -1705,12 +2236,12 @@ function publishOnce(record) {
1705
2236
  ensureConfigSubdir(SUBMISSION_EVIDENCE_DIR);
1706
2237
  const target = evidencePath(ambiguityId);
1707
2238
  const temp = `${target}.${String(process.pid)}.${randomUUID()}.tmp`;
1708
- const fd = openSync3(temp, "wx", 384);
2239
+ const fd = openSync4(temp, "wx", 384);
1709
2240
  try {
1710
2241
  writeFileSync3(fd, JSON.stringify(record, null, 2) + "\n");
1711
2242
  fsyncSync3(fd);
1712
2243
  } finally {
1713
- closeSync3(fd);
2244
+ closeSync4(fd);
1714
2245
  }
1715
2246
  try {
1716
2247
  linkSync(temp, target);
@@ -1741,12 +2272,12 @@ function boundedMarkerIds(record) {
1741
2272
  }
1742
2273
  function evidencePath(ambiguityId) {
1743
2274
  const name = createHash("sha256").update(ambiguityId).digest("hex");
1744
- return join(SUBMISSION_EVIDENCE_DIR, `${name}.json`);
2275
+ return join2(SUBMISSION_EVIDENCE_DIR, `${name}.json`);
1745
2276
  }
1746
2277
  function readRecord(path) {
1747
2278
  let parsed;
1748
2279
  try {
1749
- parsed = JSON.parse(readFileSync3(path, "utf8"));
2280
+ parsed = JSON.parse(readFileSync4(path, "utf8"));
1750
2281
  } catch (error) {
1751
2282
  throw unreadable(path, error instanceof Error ? error.message : String(error));
1752
2283
  }
@@ -1792,10 +2323,10 @@ function isOptionalStringRecord(value) {
1792
2323
  function fsyncDirectory2(path) {
1793
2324
  let fd;
1794
2325
  try {
1795
- fd = openSync3(path, "r");
2326
+ fd = openSync4(path, "r");
1796
2327
  fsyncSync3(fd);
1797
2328
  } finally {
1798
- if (fd !== void 0) closeSync3(fd);
2329
+ if (fd !== void 0) closeSync4(fd);
1799
2330
  }
1800
2331
  }
1801
2332
 
@@ -1980,6 +2511,79 @@ function jobDrawFundings(jobId, endpoint, callerPubkey, credit) {
1980
2511
  return (Array.isArray(job.drawFundingReceipts) ? job.drawFundingReceipts : []).filter((receipt) => verifiedFunding(job, receipt) !== void 0).map((receipt) => ({ receipt, builder: job.builderAnchor }));
1981
2512
  }
1982
2513
 
2514
+ // src/lib/completion-hints.ts
2515
+ function buildCompletionHintFields(jobId, input) {
2516
+ const out = {};
2517
+ if (input.hasArtifacts !== void 0) out.has_artifacts = input.hasArtifacts;
2518
+ if (input.artifactCount !== void 0) out.artifact_count = input.artifactCount;
2519
+ if (input.payloadIn) out.payload_in = input.payloadIn;
2520
+ const hint = nextStepHint(jobId, input.payloadIn, input.artifactCount);
2521
+ if (hint) out.next_step_hint = hint;
2522
+ return out;
2523
+ }
2524
+ function nextStepHint(jobId, payloadIn, artifactCount, human = false) {
2525
+ if (payloadIn !== "messages") return void 0;
2526
+ const noun = artifactCount === 1 ? "artifact" : "artifacts";
2527
+ return `Run 'dvm messages ${human ? shellQuoteArg(jobId) : guidanceJobArg(jobId)} --no-stream' to fetch the ${noun}.`;
2528
+ }
2529
+ function completionSnapshot(src) {
2530
+ const out = {};
2531
+ if (src.summary !== void 0) out.summary = src.summary;
2532
+ if (src.message !== void 0) out.message = src.message;
2533
+ if (src.hasArtifacts !== void 0) out.hasArtifacts = src.hasArtifacts;
2534
+ if (src.artifactCount !== void 0) out.artifactCount = src.artifactCount;
2535
+ if (src.payloadIn) out.payloadIn = src.payloadIn;
2536
+ return out;
2537
+ }
2538
+ function completionFromMessages(messages) {
2539
+ const complete = messages.findLast((m) => m.type === "complete");
2540
+ const summary = complete?.type === "complete" ? complete.content.summary : void 0;
2541
+ const artifactCount = messages.filter((m) => m.type === "artifact").length;
2542
+ const out = {
2543
+ hasArtifacts: artifactCount > 0,
2544
+ payloadIn: artifactCount > 0 ? "messages" : "summary"
2545
+ };
2546
+ if (summary !== void 0) out.summary = summary;
2547
+ const terminal = messages.findLast((m) => m.type === "complete" || m.type === "cancel");
2548
+ if (terminal?.type === "cancel" && terminal.content.reason !== void 0)
2549
+ out.message = terminal.content.reason;
2550
+ if (artifactCount > 0) out.artifactCount = artifactCount;
2551
+ return out;
2552
+ }
2553
+
2554
+ // src/lib/job-content.ts
2555
+ function parseJobContent(data) {
2556
+ return {
2557
+ ...data.content_expires_at === null || typeof data.content_expires_at === "number" && Number.isSafeInteger(data.content_expires_at) && Math.abs(data.content_expires_at) <= 864e13 ? { content_expires_at: data.content_expires_at } : {},
2558
+ ...typeof data.content_available === "boolean" ? { content_available: data.content_available } : {}
2559
+ };
2560
+ }
2561
+ function jobContentFields(jobId, observed, human = false) {
2562
+ const metadata = parseJobContent(observed ?? {});
2563
+ const known = metadata.content_expires_at !== void 0 && metadata.content_available !== void 0;
2564
+ 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.";
2565
+ 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.";
2566
+ 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.`;
2567
+ return {
2568
+ ...metadata,
2569
+ content_metadata_source: observed ? "provider" : "unknown",
2570
+ content_metadata_known: known,
2571
+ content_hint: `${availability} ${expiry} ${save}`
2572
+ };
2573
+ }
2574
+ async function observeJobContent(jobId, transport, ref, options) {
2575
+ try {
2576
+ const status = await transport.status(jobId, ref, {
2577
+ ...options,
2578
+ timeoutMs: options.timeoutMs > 0 ? Math.min(options.timeoutMs, 5e3) : 5e3
2579
+ });
2580
+ captureDrawFundingReceipts(jobId, status.drawFundingReceipts, { endpoint: ref.endpoint });
2581
+ return status;
2582
+ } catch {
2583
+ return void 0;
2584
+ }
2585
+ }
2586
+
1983
2587
  // src/lib/receipt-capture.ts
1984
2588
  function captureFundingReceipt(args) {
1985
2589
  if (!args.receipt) return args.parseError ? "unparseable" : "absent";
@@ -2035,8 +2639,10 @@ function captureTransportReceipt(jobId, response) {
2035
2639
  if (response.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
2036
2640
  return captureJobReceipt(jobId, response.receipt, response.receiptParseError);
2037
2641
  }
2038
- function receiptJsonFields(capture) {
2642
+ function receiptJsonFields(capture, jobId) {
2039
2643
  const out = { receipt_verified: capture.status };
2644
+ if (jobId) Object.assign(out, terminalSettlementFields(jobId, { receipt: capture.receipt }));
2645
+ else if (capture.receipt) out.settlement = receiptSettlement(capture.receipt, capture.status);
2040
2646
  if (capture.status !== "absent") out.receipt_display = capture.display;
2041
2647
  if (capture.receipt) {
2042
2648
  out.receipt = capture.receipt;
@@ -2045,10 +2651,18 @@ function receiptJsonFields(capture) {
2045
2651
  if (capture.reason) out.receipt_error = capture.reason;
2046
2652
  return out;
2047
2653
  }
2048
- function renderReceiptHuman(capture) {
2654
+ function renderReceiptHuman(capture, jobId) {
2655
+ if (jobId) {
2656
+ const { settlement } = terminalSettlementFields(jobId, { receipt: capture.receipt });
2657
+ if (settlement) info(settlement.display);
2658
+ }
2049
2659
  if (capture.status === "absent") return;
2050
2660
  info(`\u{1F9FE} ${capture.display}`);
2051
2661
  }
2662
+ function observedSettlementFields(jobId, response, persistLocalState = true) {
2663
+ if (persistLocalState && response?.status && isTerminalJobStatus(response.status) && (response.receipt || response.receiptParseError)) captureTransportReceipt(jobId, response);
2664
+ return terminalSettlementFields(jobId, { status: response?.status, receipt: response?.receipt, persistLocalState });
2665
+ }
2052
2666
  function receiptTrustFields(provider) {
2053
2667
  return {
2054
2668
  ...provider.receipts === true ? { receiptsSupported: true } : {},
@@ -2072,6 +2686,9 @@ async function fetchMissingJobReceipt(jobId, transport, ref) {
2072
2686
  const status = await transport.status(jobId, ref, { jobToken: job.jobToken });
2073
2687
  captureDrawFundingReceipts(jobId, status.drawFundingReceipts, { endpoint: ref.endpoint });
2074
2688
  return {
2689
+ status: status.status,
2690
+ ...completionSnapshot(status),
2691
+ ...parseJobContent(status),
2075
2692
  ...status.receipt ? { receipt: status.receipt } : {},
2076
2693
  ...status.receiptParseError ? { receiptParseError: status.receiptParseError } : {},
2077
2694
  ...status.drawFundingReceipts ? { drawFundingReceipts: status.drawFundingReceipts } : {},
@@ -5594,6 +6211,17 @@ function sleep(ms) {
5594
6211
  return new Promise((resolve) => setTimeout(resolve, ms));
5595
6212
  }
5596
6213
 
6214
+ // src/lib/quote-upfront.ts
6215
+ var unknownPrices = /* @__PURE__ */ new WeakSet();
6216
+ function unknownUpfrontPrice() {
6217
+ const upfront = { amount: 0, currency: "usd" };
6218
+ unknownPrices.add(upfront);
6219
+ return upfront;
6220
+ }
6221
+ function hasKnownUpfrontPrice(quote) {
6222
+ return !unknownPrices.has(quote.upfront);
6223
+ }
6224
+
5597
6225
  // src/lib/credit-policy.ts
5598
6226
  var TIER0_CAP_MICRO = 5e5;
5599
6227
  var TIER1_CAP_MICRO = 2e6;
@@ -5899,18 +6527,39 @@ function planProbeDraw(args) {
5899
6527
  if (stored.reconciliationPending) return skip("reconciliation_pending");
5900
6528
  if (stored.remainingMicro <= 0 && !stored.provisional) return skip("exhausted");
5901
6529
  if (stored.expiryMs > 0 && stored.expiryMs <= now) return skip("expired");
5902
- if (stored.lastPriceMicro !== void 0 && args.btcRate > 0) {
6530
+ if (args.drawCeilingMsats > 0 && args.btcRate > 0) {
6531
+ const priceMicro = probePriceMicro(args);
5903
6532
  const ceilingMicro = msatsToMicro(args.drawCeilingMsats, args.btcRate);
5904
- if (ceilingMicro > 0 && stored.lastPriceMicro > ceilingMicro) {
6533
+ if (priceMicro !== void 0 && ceilingMicro > 0 && priceMicro > ceilingMicro) {
5905
6534
  return skip("price_above_ceiling", {
5906
6535
  ceilingMicro,
5907
- lastPriceMicro: stored.lastPriceMicro,
6536
+ lastPriceMicro: priceMicro,
5908
6537
  ceilingSource: args.drawCeilingSource
5909
6538
  });
5910
6539
  }
5911
6540
  }
5912
6541
  return { mode: "draw", creditId: stored.creditId, drawId: randomUUID4(), source: "prepaid" };
5913
6542
  }
6543
+ function probePriceMicro(args) {
6544
+ const quote = args.quote;
6545
+ if (quote && hasKnownUpfrontPrice(quote) && quote.shape !== "rate" && quote.upfront.currency === "usd") {
6546
+ const micro = quote.upfront.amount_micro ?? Math.round(quote.upfront.amount * 1e6);
6547
+ if (Number.isSafeInteger(micro) && micro >= 0) return micro;
6548
+ }
6549
+ const stored = args.stored;
6550
+ if (!stored || stored.currency !== "usd") return void 0;
6551
+ const candidates = (args.receipts ?? []).filter(
6552
+ ({ receipt }) => receipt.capability === args.capability && receipt.credit?.credit_id === stored.creditId
6553
+ );
6554
+ const latest = completedReceiptsFor(
6555
+ candidates,
6556
+ stored.endpoint,
6557
+ stored.callerPubkey,
6558
+ args.identity
6559
+ ).sort((a, b) => (b.receipt.credit?.ledger_seq ?? 0) - (a.receipt.credit?.ledger_seq ?? 0))[0];
6560
+ const amount = latest?.receipt.credit?.amount;
6561
+ return amount !== void 0 && Number.isSafeInteger(amount) && amount >= 0 ? amount : void 0;
6562
+ }
5914
6563
  function needsTopup(balanceMicro, targetMicro) {
5915
6564
  return targetMicro > 0 && balanceMicro < targetMicro * TOPUP_THRESHOLD_FRACTION;
5916
6565
  }
@@ -6405,6 +7054,13 @@ function errorMessage(err) {
6405
7054
  }
6406
7055
 
6407
7056
  export {
7057
+ providerFields,
7058
+ guidanceJobArg,
7059
+ providerJobJson,
7060
+ appendMessages,
7061
+ createMessageAppendSession,
7062
+ loadMessages,
7063
+ maxSeq,
6408
7064
  normalizeProviderEndpoint,
6409
7065
  sameEndpoint,
6410
7066
  parseUpfrontRailPayment,
@@ -6426,6 +7082,16 @@ export {
6426
7082
  markPaymentRequestPaid,
6427
7083
  mutateCreditPayment,
6428
7084
  bookCreditPayment,
7085
+ JOB_READ_TIMEOUT_MS,
7086
+ answeredYieldSeqs,
7087
+ pendingPaymentRequest,
7088
+ loadAnsweredYieldSeqs,
7089
+ reconcileInFlightPaymentRequest,
7090
+ reconcilePaymentRequestHistory,
7091
+ isTerminalJobStatus,
7092
+ pollNextAction,
7093
+ paymentInFlightHint,
7094
+ computeNextAction,
6429
7095
  loadFavorites,
6430
7096
  saveFavorite,
6431
7097
  removeFavorite,
@@ -6472,6 +7138,9 @@ export {
6472
7138
  parseStatedBudget,
6473
7139
  floatBudgetJson,
6474
7140
  toFloatError,
7141
+ receiptSettlement,
7142
+ jobSettlement,
7143
+ terminalSettlementFields,
6475
7144
  drainReceiptsDisplay,
6476
7145
  drainReceiptsHint,
6477
7146
  receiptDisplay,
@@ -6481,10 +7150,18 @@ export {
6481
7150
  receiptFailureDetail,
6482
7151
  captureDrawFundingReceipts,
6483
7152
  jobDrawFundings,
7153
+ buildCompletionHintFields,
7154
+ nextStepHint,
7155
+ completionSnapshot,
7156
+ completionFromMessages,
7157
+ parseJobContent,
7158
+ jobContentFields,
7159
+ observeJobContent,
6484
7160
  captureFundingReceipt,
6485
7161
  captureTransportReceipt,
6486
7162
  receiptJsonFields,
6487
7163
  renderReceiptHuman,
7164
+ observedSettlementFields,
6488
7165
  receiptTrustFields,
6489
7166
  fetchTrustAnchor,
6490
7167
  fetchMissingJobReceipt,
@@ -6512,6 +7189,7 @@ export {
6512
7189
  pollPendingCreditFundings,
6513
7190
  availableRails,
6514
7191
  pickCreditFundRail,
7192
+ unknownUpfrontPrice,
6515
7193
  DEFAULT_CREDIT_POSTURE,
6516
7194
  trustLadderFor,
6517
7195
  effectiveCreditPosture,