@dvmkit/dvm-cli 0.9.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/{chunk-BHR7QHJG.js → chunk-3R2GM6AD.js} +2 -2
  2. package/dist/{chunk-5R3BLFVO.js → chunk-6EYBCGGD.js} +2 -2
  3. package/dist/{chunk-BCDMVIPI.js → chunk-7N3HQJKE.js} +4 -4
  4. package/dist/{chunk-C7ZNQONB.js → chunk-BPWZNIMS.js} +2 -2
  5. package/dist/{chunk-PMPHS3LS.js → chunk-GEZVSJDM.js} +3 -3
  6. package/dist/{chunk-GD25CUI4.js → chunk-GHNF2I5C.js} +4 -4
  7. package/dist/{chunk-XDYBVNFS.js → chunk-HWWW7JEM.js} +3 -3
  8. package/dist/{chunk-MVVKMKWR.js → chunk-JJBRTWWS.js} +984 -24
  9. package/dist/{chunk-HUBCGZJL.js → chunk-K562SFVD.js} +2 -2
  10. package/dist/{chunk-6XTWANVN.js → chunk-MBSCP52L.js} +1073 -252
  11. package/dist/{chunk-QDOY3JF2.js → chunk-MMXHV3KC.js} +2 -2
  12. package/dist/{chunk-IEWV3CM2.js → chunk-UVFFMKU4.js} +3 -1
  13. package/dist/{client-MMJYIMKJ.js → client-DS4QJ346.js} +6 -6
  14. package/dist/dvm.js +1379 -1171
  15. package/dist/{internal-LRW4XR3J.js → internal-ZZHCUKOM.js} +15 -5
  16. package/dist/{lifecycle-QE3KHIHQ.js → lifecycle-XGNIMPTB.js} +6 -6
  17. package/dist/{payout-reporter-NXWQVKXW-KHVN6C4Z.js → payout-reporter-DDQ7FGRC-OKICJCC2.js} +2 -2
  18. package/dist/{pocket-refill-J3BME4O3.js → pocket-refill-3ZV36DOA.js} +10 -10
  19. package/dist/{revenue-reporter-HD4GMXGD-LAZU45ZA.js → revenue-reporter-RIEHBKRA-75BDPVVX.js} +2 -2
  20. package/dist/{tempo-lifecycle-HJQYBOZR.js → tempo-lifecycle-LGGBDCKK.js} +8 -8
  21. package/dist/{tempo-wallet-XN72C2GK.js → tempo-wallet-PLFC443A.js} +7 -7
  22. package/dist/{wallet-UEQTGVJE.js → wallet-UJ7EJNQA.js} +7 -7
  23. package/dist/{x402-RUJ4LUKF-ZB7JM22B.js → x402-AY6P5KV4-SIZF7YNW.js} +2 -2
  24. package/package.json +6 -3
  25. package/skills/dvm/calling.md +17 -1
@@ -3,7 +3,7 @@ import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
5
  connectedTempoAccount
6
- } from "./chunk-BCDMVIPI.js";
6
+ } from "./chunk-7N3HQJKE.js";
7
7
  import {
8
8
  costAnchor,
9
9
  info,
@@ -11,18 +11,21 @@ import {
11
11
  resolveBtcUsdRate,
12
12
  tryResolveBtcUsdRate,
13
13
  tryX402Payment
14
- } from "./chunk-C7ZNQONB.js";
14
+ } from "./chunk-BPWZNIMS.js";
15
15
  import {
16
16
  loadX402Wallet,
17
17
  x402NetworkLabel
18
- } from "./chunk-PMPHS3LS.js";
18
+ } from "./chunk-GEZVSJDM.js";
19
19
  import {
20
20
  isCreditPosture,
21
21
  loadConfig
22
- } from "./chunk-QDOY3JF2.js";
22
+ } from "./chunk-MMXHV3KC.js";
23
23
  import {
24
24
  BUDGET_FILE,
25
+ CONFIG_DIR,
26
+ FAVORITES_FILE,
25
27
  JOBS_FILE,
28
+ JOB_IDENTITY_HEADER,
26
29
  NwcBackend,
27
30
  NwcError,
28
31
  RECENT_SPENDS_CAP,
@@ -62,6 +65,7 @@ import {
62
65
  createX402BatchPayment,
63
66
  deriveAgentRefundSubkeyPubkey,
64
67
  ensureConfigDir,
68
+ ensureConfigSubdir,
65
69
  findX402Channel,
66
70
  formatUsd,
67
71
  fundingModeForTempoIntent,
@@ -69,9 +73,11 @@ import {
69
73
  getLastKnownBtcRate,
70
74
  getWallet,
71
75
  isCreditFundRail,
76
+ isDrawFundingReceipt,
72
77
  isSignableExactRequirement,
73
78
  isSignedJobReceipt,
74
79
  isStablecoinFundRail,
80
+ isStorableJobId,
75
81
  ki,
76
82
  listPendingFundings,
77
83
  listPendingX402Fundings,
@@ -95,6 +101,7 @@ import {
95
101
  offersX402CreditChannel,
96
102
  offersX402CreditFlavour,
97
103
  offersX402CreditFunding,
104
+ parseJobIdentityHeader,
98
105
  parseNwcUri,
99
106
  persistTempoOpenCredential,
100
107
  prepareP2PKMint,
@@ -118,6 +125,7 @@ import {
118
125
  selectProofsForSpend,
119
126
  serializeOutputData,
120
127
  sha256hex,
128
+ shellQuoteArg,
121
129
  signDvmRequestData,
122
130
  signedRequestDomain,
123
131
  swapSendReserve,
@@ -135,6 +143,7 @@ import {
135
143
  tempoSessionPriorCumulativeMicro,
136
144
  toAgentProof,
137
145
  toCashuProofs,
146
+ verifyDrawFundingReceiptChain,
138
147
  verifyFundingReceiptChain,
139
148
  verifyJobReceipt,
140
149
  windowEnd,
@@ -157,7 +166,7 @@ import {
157
166
  x402PendingUnsettled,
158
167
  x402RequiredFromError,
159
168
  x402VoucherPendingState
160
- } from "./chunk-6XTWANVN.js";
169
+ } from "./chunk-MBSCP52L.js";
161
170
  import {
162
171
  Challenge_exports,
163
172
  Credential_exports
@@ -174,7 +183,7 @@ import {
174
183
  redactUrlsInText,
175
184
  usdToMsats,
176
185
  x402NetworkToCaip2
177
- } from "./chunk-GD25CUI4.js";
186
+ } from "./chunk-GHNF2I5C.js";
178
187
  import {
179
188
  privateKeyToAccount
180
189
  } from "./chunk-EVQERRCP.js";
@@ -786,7 +795,7 @@ function supportsMethod(methods, method) {
786
795
  }
787
796
 
788
797
  // src/lib/credit-policy.ts
789
- import { randomUUID as randomUUID3 } from "crypto";
798
+ import { randomUUID as randomUUID4 } from "crypto";
790
799
 
791
800
  // src/lib/payment-rails/tempo-credential.ts
792
801
  async function buildTempoCredential(args) {
@@ -857,17 +866,118 @@ function fail(mode, refusal) {
857
866
  }
858
867
 
859
868
  // src/lib/credit-fund.ts
860
- import { randomUUID as randomUUID2 } from "crypto";
869
+ import { randomUUID as randomUUID3 } from "crypto";
861
870
 
862
871
  // src/lib/job-store.ts
863
872
  import { existsSync, readFileSync, writeFileSync, renameSync, openSync, closeSync, fsyncSync } from "fs";
864
873
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
865
874
  import { dirname } from "path";
875
+
876
+ // src/lib/upfront-payment.ts
877
+ function parseUpfrontRailPayment(value) {
878
+ if (!value || typeof value !== "object") return void 0;
879
+ const raw = value;
880
+ if (!["cashu", "x402", "tempo"].includes(raw.method) || !Number.isSafeInteger(raw.amountMsats) || raw.amountMsats < 0) return void 0;
881
+ return { method: raw.method, amountMsats: raw.amountMsats };
882
+ }
883
+ function parseUpfrontPayment(value) {
884
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
885
+ const raw = value;
886
+ if (!Number.isSafeInteger(raw.amount_msats) || Number(raw.amount_msats) < 0) return void 0;
887
+ for (const key of ["amount_micro", "native_amount"]) {
888
+ if (raw[key] !== void 0 && (!Number.isSafeInteger(raw[key]) || Number(raw[key]) < 0)) return void 0;
889
+ }
890
+ if (raw.amount_micro === void 0 !== (raw.currency === void 0) || raw.currency !== void 0 && (typeof raw.currency !== "string" || !/^[a-z]{3}$/.test(raw.currency))) return void 0;
891
+ if (raw.credit_id === void 0 !== (raw.draw_id === void 0)) return void 0;
892
+ for (const key of ["credit_id", "draw_id", "native_asset"]) {
893
+ if (raw[key] !== void 0 && (typeof raw[key] !== "string" || raw[key].trim().length === 0)) return void 0;
894
+ }
895
+ if (raw.rail !== void 0 && !["cashu", "x402", "tempo", "lightning"].includes(String(raw.rail))) return void 0;
896
+ return {
897
+ amount_msats: raw.amount_msats,
898
+ ...raw.amount_micro !== void 0 ? { amount_micro: raw.amount_micro, currency: raw.currency } : {},
899
+ ...raw.rail !== void 0 ? { rail: raw.rail } : {},
900
+ ...raw.native_amount !== void 0 ? { native_amount: raw.native_amount } : {},
901
+ ...raw.native_asset !== void 0 ? { native_asset: raw.native_asset } : {},
902
+ ...raw.credit_id !== void 0 ? { credit_id: raw.credit_id, draw_id: raw.draw_id } : {}
903
+ };
904
+ }
905
+
906
+ // src/lib/job-store.ts
866
907
  function saveJob(job) {
867
908
  mutateJobs((jobs) => {
868
909
  jobs.push(job);
869
910
  });
870
911
  }
912
+ function saveSubmittedJob(job) {
913
+ mutateJobs((jobs) => {
914
+ const existing = jobs.find((entry) => entry.id === job.id);
915
+ if (!existing) jobs.push(job);
916
+ else if (existing.endpoint !== job.endpoint || existing.requestId && existing.requestId !== job.requestId)
917
+ throw new Error("Submitted job conflicts with an existing local job.");
918
+ });
919
+ }
920
+ function recordUpfrontCreditPayment(jobId, value, paidOnRail = false) {
921
+ const payment = parseUpfrontPayment(value);
922
+ mutateJobs((jobs) => {
923
+ const job = jobs.find((entry) => entry.id === jobId);
924
+ if (!job || !payment) return;
925
+ if (paidOnRail || job.paymentMethod && job.paymentMethod !== "credit") {
926
+ job.upfrontPayment ??= payment;
927
+ return;
928
+ }
929
+ if (!payment.credit_id || !payment.draw_id) {
930
+ if (job.paymentMethod === "credit") job.upfrontCreditConflict = true;
931
+ return;
932
+ }
933
+ const binding = job.creditBinding;
934
+ if (!binding || "unbound" in binding || binding.creditId !== payment.credit_id || binding.drawId !== payment.draw_id) {
935
+ job.upfrontCreditConflict = true;
936
+ return;
937
+ }
938
+ if (job.upfrontPayment && JSON.stringify(job.upfrontPayment) !== JSON.stringify(payment)) {
939
+ job.upfrontCreditConflict = true;
940
+ return;
941
+ }
942
+ job.upfrontPayment = payment;
943
+ job.paymentMethod = "credit";
944
+ if (job.upfrontCreditBooked) return;
945
+ job.totalPaidMsats = (job.totalPaidMsats ?? 0) + payment.amount_msats;
946
+ job.paymentsHonoured = (job.paymentsHonoured ?? 0) + (payment.amount_msats > 0 ? 1 : 0);
947
+ job.upfrontCreditBooked = true;
948
+ });
949
+ }
950
+ function hasUnknownUpfrontCredit(job) {
951
+ return job.upfrontCreditConflict === true || job.paymentMethod === "credit" && (!job.upfrontCreditBooked || !parseUpfrontPayment(job.upfrontPayment));
952
+ }
953
+ function recordUpfrontRailPayment(jobId, value, freshSubmit = false) {
954
+ const payment = parseUpfrontRailPayment(value);
955
+ mutateJobs((jobs) => {
956
+ const job = jobs.find((entry) => entry.id === jobId);
957
+ if (!job) return;
958
+ const booked = parseUpfrontRailPayment(job.upfrontRailPayment);
959
+ if (booked) {
960
+ if (payment && (booked.method !== payment.method || booked.amountMsats !== payment.amountMsats))
961
+ job.upfrontRailConflict = true;
962
+ return;
963
+ }
964
+ if (value === "free" || job.upfrontRailPayment === "free" && !payment) {
965
+ job.upfrontRailPayment = "free";
966
+ return;
967
+ }
968
+ if (!payment || !freshSubmit && ((job.totalPaidMsats ?? 0) !== 0 || (job.paymentsHonoured ?? 0) !== 0)) {
969
+ job.upfrontRailPayment = "unknown";
970
+ return;
971
+ }
972
+ job.totalPaidMsats = (job.totalPaidMsats ?? 0) + payment.amountMsats;
973
+ job.paymentsHonoured = (job.paymentsHonoured ?? 0) + (payment.amountMsats > 0 ? 1 : 0);
974
+ job.paymentMethod = payment.method;
975
+ job.upfrontRailPayment = payment;
976
+ });
977
+ }
978
+ function hasUnknownUpfrontRail(job) {
979
+ return job.upfrontRailPayment === "unknown" || job.upfrontRailConflict === true;
980
+ }
871
981
  function updateJob(id, update) {
872
982
  mutateJobs((jobs) => {
873
983
  const idx = jobs.findIndex((j) => j.id === id);
@@ -896,15 +1006,53 @@ function loadAllJobs() {
896
1006
  return [];
897
1007
  }
898
1008
  }
899
- function addPayment(jobId, amountMsats) {
1009
+ function addPayment(jobId, amountMsats, approval) {
900
1010
  mutateJobs((jobs) => {
901
1011
  const job = jobs.find((entry) => entry.id === jobId);
902
1012
  if (!job) return;
903
1013
  job.totalPaidMsats = (job.totalPaidMsats ?? 0) + amountMsats;
904
1014
  job.paymentsHonoured = (job.paymentsHonoured ?? 0) + 1;
1015
+ if (approval) (job.paymentApprovals ??= []).push(approval);
905
1016
  if (job.creditBinding && "unbound" in job.creditBinding) delete job.creditBinding;
906
1017
  });
907
1018
  }
1019
+ function markPaymentRequestInFlight(jobId, requestSeq) {
1020
+ mutateJobs((jobs) => {
1021
+ const job = jobs.find((entry) => entry.id === jobId);
1022
+ if (job) {
1023
+ if (!job.inFlightPaymentRequestSeqs?.includes(requestSeq))
1024
+ (job.inFlightPaymentRequestSeqs ??= []).push(requestSeq);
1025
+ (job.inFlightPaymentRequestStartedAtMs ??= {})[requestSeq] = Date.now();
1026
+ }
1027
+ });
1028
+ }
1029
+ function clearPaymentRequestInFlight(jobId, requestSeq) {
1030
+ mutateJobs((jobs) => {
1031
+ const job = jobs.find((entry) => entry.id === jobId);
1032
+ if (!job?.inFlightPaymentRequestSeqs) return;
1033
+ job.inFlightPaymentRequestSeqs = job.inFlightPaymentRequestSeqs.filter((seq) => seq !== requestSeq);
1034
+ if (!job.inFlightPaymentRequestSeqs.length) delete job.inFlightPaymentRequestSeqs;
1035
+ clearPaymentRequestStartTime(job, requestSeq);
1036
+ });
1037
+ }
1038
+ function markPaymentRequestPaid(jobId, requestSeq) {
1039
+ mutateJobs((jobs) => {
1040
+ const job = jobs.find((entry) => entry.id === jobId);
1041
+ if (!job) return;
1042
+ if (!job.paidPaymentRequestSeqs?.includes(requestSeq))
1043
+ (job.paidPaymentRequestSeqs ??= []).push(requestSeq);
1044
+ if (job.inFlightPaymentRequestSeqs) {
1045
+ job.inFlightPaymentRequestSeqs = job.inFlightPaymentRequestSeqs.filter((seq) => seq !== requestSeq);
1046
+ if (!job.inFlightPaymentRequestSeqs.length) delete job.inFlightPaymentRequestSeqs;
1047
+ }
1048
+ clearPaymentRequestStartTime(job, requestSeq);
1049
+ });
1050
+ }
1051
+ function clearPaymentRequestStartTime(job, requestSeq) {
1052
+ if (!job.inFlightPaymentRequestStartedAtMs) return;
1053
+ delete job.inFlightPaymentRequestStartedAtMs[requestSeq];
1054
+ if (!Object.keys(job.inFlightPaymentRequestStartedAtMs).length) delete job.inFlightPaymentRequestStartedAtMs;
1055
+ }
908
1056
  function writeJobs(jobs) {
909
1057
  ensureConfigDir();
910
1058
  const temporary = `${JOBS_FILE}.${process.pid}.tmp`;
@@ -916,11 +1064,13 @@ function writeJobs(jobs) {
916
1064
  closeSync(fd);
917
1065
  }
918
1066
  renameSync(temporary, JOBS_FILE);
919
- const directory = openSync(dirname(JOBS_FILE), "r");
920
- try {
921
- fsyncSync(directory);
922
- } finally {
923
- closeSync(directory);
1067
+ if (process.platform !== "win32") {
1068
+ const directory = openSync(dirname(JOBS_FILE), "r");
1069
+ try {
1070
+ fsyncSync(directory);
1071
+ } finally {
1072
+ closeSync(directory);
1073
+ }
924
1074
  }
925
1075
  }
926
1076
  function mutateJobs(change) {
@@ -949,6 +1099,10 @@ function bookCreditPayment(jobId, intent) {
949
1099
  job.totalPaidMsats = (job.totalPaidMsats ?? 0) + (intent.amountMsats ?? intent.request.amount_msats);
950
1100
  job.paymentsHonoured = (job.paymentsHonoured ?? 0) + 1;
951
1101
  (job.bookedCreditPayments ??= []).push(intent);
1102
+ if (intent.approval) (job.paymentApprovals ??= []).push({
1103
+ requestSeq: intent.authorization.request_seq,
1104
+ approval: intent.approval
1105
+ });
952
1106
  }
953
1107
  if (job.pendingCreditPayment?.authorization.payment_id === intent.authorization.payment_id)
954
1108
  delete job.pendingCreditPayment;
@@ -1015,6 +1169,8 @@ function receiptFailureDetail(reason) {
1015
1169
  return "The receipt names a different job than the one it was collected for \u2014 it is not proof of this job, whoever signed it.";
1016
1170
  case "drain_id_mismatch":
1017
1171
  return "The receipt names a different reclaim than the one it is filed under \u2014 it is not evidence of this drain, whoever signed it.";
1172
+ case "draw_id_mismatch":
1173
+ return "The funding receipt names a different draw than the job's accepted credit draw.";
1018
1174
  case "credit_id_mismatch":
1019
1175
  return "The receipt names a different credit than the one this reclaim was against \u2014 it is not evidence of this refund, whoever signed it.";
1020
1176
  case "fund_id_mismatch":
@@ -1025,6 +1181,8 @@ function receiptFailureDetail(reason) {
1025
1181
  return "The signed post-funding balance differs from the provider's fresh balance response.";
1026
1182
  case "funding_ledger_seq_mismatch":
1027
1183
  return "The signed funding sequence differs from the provider's fresh balance response.";
1184
+ case "funding_currency_mismatch":
1185
+ return "The signed funding currency differs from the credit's native currency.";
1028
1186
  case "caller_pubkey_mismatch":
1029
1187
  return "The funding receipt names a different caller than the key that submitted the funding.";
1030
1188
  case "signature_invalid":
@@ -1055,6 +1213,764 @@ function formatPaid(msats, rate) {
1055
1213
  return `~$${formatUsd(usd)} (${satsLabel}, ${costAnchor(usd)})`;
1056
1214
  }
1057
1215
 
1216
+ // src/lib/favorites.ts
1217
+ var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
1218
+ import {
1219
+ closeSync as closeSync2,
1220
+ fchmodSync,
1221
+ fsyncSync as fsyncSync2,
1222
+ openSync as openSync2,
1223
+ readFileSync as readFileSync2,
1224
+ renameSync as renameSync2,
1225
+ statSync,
1226
+ unlinkSync,
1227
+ writeFileSync as writeFileSync2
1228
+ } from "fs";
1229
+ import { dirname as dirname2 } from "path";
1230
+ var DEFAULT_FILE_MODE = 384;
1231
+ function loadFavorites() {
1232
+ let raw;
1233
+ try {
1234
+ raw = readFileSync2(FAVORITES_FILE, "utf8");
1235
+ } catch (error) {
1236
+ if (nodeErrorCode(error) === "ENOENT") return {};
1237
+ throw unreadableFavorites(error);
1238
+ }
1239
+ try {
1240
+ const parsed = JSON.parse(raw);
1241
+ if (!isFavoritesMap(parsed)) throw new Error("invalid favorites shape");
1242
+ return parsed;
1243
+ } catch (error) {
1244
+ throw unreadableFavorites(error);
1245
+ }
1246
+ }
1247
+ async function saveFavorite(alias, fav) {
1248
+ return withFavoritesLock(() => {
1249
+ const favs = loadFavorites();
1250
+ const existed = Object.hasOwn(favs, alias);
1251
+ favs[alias] = fav;
1252
+ writeFavorites(favs);
1253
+ return existed;
1254
+ });
1255
+ }
1256
+ async function removeFavorite(alias) {
1257
+ return withFavoritesLock(() => {
1258
+ const favs = loadFavorites();
1259
+ if (!Object.hasOwn(favs, alias)) return false;
1260
+ const { [alias]: _, ...rest } = favs;
1261
+ writeFavorites(rest);
1262
+ return true;
1263
+ });
1264
+ }
1265
+ function resolveEndpoint(input) {
1266
+ if (!input.startsWith("@")) return input;
1267
+ const alias = input.slice(1);
1268
+ const favs = loadFavorites();
1269
+ const fav = Object.hasOwn(favs, alias) ? favs[alias] : void 0;
1270
+ if (!fav) {
1271
+ throw new DvmError(
1272
+ "unknown_favorite",
1273
+ `No favorite named "${alias}".`,
1274
+ "Run 'dvm fav list' to see saved favorites, or 'dvm fav add <endpoint>' to save one."
1275
+ );
1276
+ }
1277
+ return fav.endpoint;
1278
+ }
1279
+ function deriveAlias(endpoint) {
1280
+ try {
1281
+ const hostname = new URL(endpoint).hostname;
1282
+ if (hostname.endsWith(".dvmkit.ai")) {
1283
+ const prefix = hostname.replace(".dvmkit.ai", "");
1284
+ const dashIdx = prefix.indexOf("--");
1285
+ if (dashIdx !== -1) return prefix.slice(dashIdx + 2);
1286
+ return prefix;
1287
+ }
1288
+ return hostname.replace(/\.[^.]+$/, "").replace(/\./g, "-");
1289
+ } catch {
1290
+ return endpoint.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
1291
+ }
1292
+ }
1293
+ async function withFavoritesLock(fn) {
1294
+ ensureConfigDir();
1295
+ let release;
1296
+ try {
1297
+ release = await import_proper_lockfile2.default.lock(FAVORITES_FILE, {
1298
+ lockfilePath: `${FAVORITES_FILE}.lock`,
1299
+ realpath: false,
1300
+ stale: 3e4,
1301
+ retries: { retries: 10, factor: 1, minTimeout: 100, maxTimeout: 100 }
1302
+ });
1303
+ } catch {
1304
+ throw new DvmError(
1305
+ "favorites_locked",
1306
+ "Another dvm process is updating saved favorites.",
1307
+ "Wait a moment and retry."
1308
+ );
1309
+ }
1310
+ try {
1311
+ return await fn();
1312
+ } finally {
1313
+ await release().catch(() => void 0);
1314
+ }
1315
+ }
1316
+ function writeFavorites(favorites) {
1317
+ const mode = favoritesFileMode();
1318
+ const temporary = `${FAVORITES_FILE}.${String(process.pid)}.${randomSuffix()}.tmp`;
1319
+ const contents = JSON.stringify(favorites, null, 2) + "\n";
1320
+ let fd;
1321
+ try {
1322
+ fd = openSync2(temporary, "wx", mode);
1323
+ fchmodSync(fd, mode);
1324
+ writeFileSync2(fd, contents);
1325
+ fsyncSync2(fd);
1326
+ closeSync2(fd);
1327
+ fd = void 0;
1328
+ renameSync2(temporary, FAVORITES_FILE);
1329
+ fsyncDirectory(dirname2(FAVORITES_FILE));
1330
+ } catch (error) {
1331
+ if (fd !== void 0) {
1332
+ try {
1333
+ closeSync2(fd);
1334
+ } catch {
1335
+ }
1336
+ }
1337
+ try {
1338
+ unlinkSync(temporary);
1339
+ } catch {
1340
+ }
1341
+ throw error;
1342
+ }
1343
+ }
1344
+ function favoritesFileMode() {
1345
+ try {
1346
+ return statSync(FAVORITES_FILE).mode & 511;
1347
+ } catch (error) {
1348
+ if (nodeErrorCode(error) === "ENOENT") return DEFAULT_FILE_MODE;
1349
+ throw error;
1350
+ }
1351
+ }
1352
+ function fsyncDirectory(path) {
1353
+ if (process.platform === "win32") return;
1354
+ const fd = openSync2(path, "r");
1355
+ try {
1356
+ fsyncSync2(fd);
1357
+ } finally {
1358
+ closeSync2(fd);
1359
+ }
1360
+ }
1361
+ function randomSuffix() {
1362
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
1363
+ }
1364
+ function unreadableFavorites(error) {
1365
+ return new DvmError(
1366
+ "favorites_unreadable",
1367
+ "Saved favorites are corrupt or unreadable.",
1368
+ `The original file at ${FAVORITES_FILE} was left unchanged. Restore it from a backup, or move it aside before rebuilding favorites.`,
1369
+ {
1370
+ path: FAVORITES_FILE,
1371
+ ...nodeErrorCode(error) ? { error_code: nodeErrorCode(error) } : {}
1372
+ }
1373
+ );
1374
+ }
1375
+ function nodeErrorCode(error) {
1376
+ if (!(error instanceof Error) || !("code" in error)) return void 0;
1377
+ const code = error.code;
1378
+ return typeof code === "string" && /^E[A-Z0-9_]{1,63}$/.test(code) ? code : void 0;
1379
+ }
1380
+ function isFavoritesMap(value) {
1381
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1382
+ return Object.values(value).every(isFavorite);
1383
+ }
1384
+ function isFavorite(value) {
1385
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1386
+ const candidate = value;
1387
+ return typeof candidate.endpoint === "string" && typeof candidate.addedAt === "number" && Number.isFinite(candidate.addedAt) && (candidate.name === void 0 || typeof candidate.name === "string");
1388
+ }
1389
+
1390
+ // src/lib/submission-evidence.ts
1391
+ import { createHash, randomUUID } from "crypto";
1392
+ import {
1393
+ closeSync as closeSync3,
1394
+ existsSync as existsSync2,
1395
+ fsyncSync as fsyncSync3,
1396
+ linkSync,
1397
+ openSync as openSync3,
1398
+ readdirSync,
1399
+ readFileSync as readFileSync3,
1400
+ unlinkSync as unlinkSync2,
1401
+ writeFileSync as writeFileSync3
1402
+ } from "fs";
1403
+ import { join } from "path";
1404
+
1405
+ // src/lib/job-identity.ts
1406
+ var IDENTITY_FAILURE_CODES = {
1407
+ identity_mismatch: "provider_identity_mismatch",
1408
+ body_unreadable: "provider_body_unreadable",
1409
+ router_identity_conflict: "hosting_job_identity_conflict"
1410
+ };
1411
+ var ProviderIdentityError = class extends DvmError {
1412
+ observation;
1413
+ constructor(observation, message, hint, data, proseSources) {
1414
+ super(IDENTITY_FAILURE_CODES[observation.kind], message, hint, data, void 0, proseSources);
1415
+ this.observation = observation;
1416
+ }
1417
+ };
1418
+ function isIdentityFailure(err) {
1419
+ return err instanceof ProviderIdentityError;
1420
+ }
1421
+ function isParseableBodyJobId(value) {
1422
+ return typeof value === "string" && value.trim().length > 0 && value.length <= 512 && !hasAsciiControl(value);
1423
+ }
1424
+ function isOpaqueJobToken(value) {
1425
+ return typeof value === "string" && value.length > 0 && value.length <= 4096 && value.trim() === value && !hasAsciiControl(value);
1426
+ }
1427
+ function observedJobId(value) {
1428
+ return isStorableJobId(value) ? value : void 0;
1429
+ }
1430
+ function observeJobId(value) {
1431
+ if (value === void 0) return {};
1432
+ if (isStorableJobId(value)) return { stored: value };
1433
+ return { escaped: escapeObservedValue(value) };
1434
+ }
1435
+ var ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT = 1024;
1436
+ function escapeObservedValue(value) {
1437
+ const source = typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
1438
+ const truncated = source.length > ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT;
1439
+ const quoted = JSON.stringify(
1440
+ truncated ? source.slice(0, ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT) : source
1441
+ ).replace(
1442
+ /[\u007f-\u009f]/gu,
1443
+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
1444
+ );
1445
+ return truncated ? `${quoted} [truncated from ${String(source.length)} characters]` : quoted;
1446
+ }
1447
+ function settleJobIdentity(headerValue, body) {
1448
+ const header = parseJobIdentityHeader(headerValue);
1449
+ const headerJobId = header.kind === "valid" ? header.jobId : void 0;
1450
+ const rawBodyJobId = body?.job_id;
1451
+ const jobToken = isOpaqueJobToken(body?.job_token) ? body.job_token : void 0;
1452
+ const observed = (kind) => {
1453
+ const bodyJob = observeJobId(rawBodyJobId);
1454
+ return {
1455
+ kind: "unresolved",
1456
+ observation: {
1457
+ kind,
1458
+ ...headerJobId ? { headerJobId } : {},
1459
+ ...optionalField("bodyJobId", bodyJob.stored),
1460
+ ...bodyJob.escaped ? { unstorable: { body_job_id: bodyJob.escaped } } : {},
1461
+ ...jobToken ? { jobToken } : {}
1462
+ }
1463
+ };
1464
+ };
1465
+ if (!isParseableBodyJobId(rawBodyJobId)) return observed("body_unreadable");
1466
+ if (headerJobId !== void 0 && headerJobId !== rawBodyJobId) {
1467
+ return observed("identity_mismatch");
1468
+ }
1469
+ return {
1470
+ kind: "settled",
1471
+ jobId: rawBodyJobId,
1472
+ claimAllowed: header.kind !== "invalid",
1473
+ headerInvalid: header.kind === "invalid"
1474
+ };
1475
+ }
1476
+ function routerConflictObservation(status, body) {
1477
+ if (status !== 409 || !body) return void 0;
1478
+ const error = body.error;
1479
+ if (!error || typeof error !== "object" || Array.isArray(error)) return void 0;
1480
+ const envelope = error;
1481
+ if (envelope.code !== IDENTITY_FAILURE_CODES.router_identity_conflict) return void 0;
1482
+ const accepted = observeJobId(envelope.accepted_job_id);
1483
+ return {
1484
+ kind: "router_identity_conflict",
1485
+ ...optionalField("acceptedJobId", accepted.stored),
1486
+ ...accepted.escaped ? { unstorable: { accepted_job_id: accepted.escaped } } : {}
1487
+ };
1488
+ }
1489
+ function jobIdentityHeaderValue(headers) {
1490
+ return headers.get(JOB_IDENTITY_HEADER);
1491
+ }
1492
+ function identityError(observation, providerProse) {
1493
+ const { message, display } = describeIdentityFailure(observation);
1494
+ return new ProviderIdentityError(
1495
+ observation,
1496
+ message,
1497
+ "Do not pay for this request again. Run 'dvm wallet submissions' to see what was recorded.",
1498
+ {
1499
+ identity_kind: observation.kind,
1500
+ ...identityDataFields(observation),
1501
+ display: providerProse?.display ?? display
1502
+ },
1503
+ providerProse?.proseSources
1504
+ );
1505
+ }
1506
+ function withIdentityRecovery(err, ctx) {
1507
+ const hint = ctx.publicRequestId ? `Run 'dvm request-result ${ctx.publicRequestId}' to read the accepted job. Do not pay for this request again; 'dvm wallet submissions' shows the recorded evidence (${ctx.ambiguityId}).` : `Run 'dvm wallet submissions' to see the recorded evidence (${ctx.ambiguityId}) and how to read each job it names. Do not pay for this request again.`;
1508
+ return new ProviderIdentityError(
1509
+ err.observation,
1510
+ err.message,
1511
+ hint,
1512
+ {
1513
+ ...err.data,
1514
+ ambiguity_id: ctx.ambiguityId,
1515
+ ...ctx.publicRequestId ? { request_id: ctx.publicRequestId } : {},
1516
+ ...ctx.cashuRequestId ? { cashu_request_id: ctx.cashuRequestId } : {},
1517
+ claim_stored: false
1518
+ },
1519
+ err.proseSources
1520
+ );
1521
+ }
1522
+ function withRequestResultRecovery(err, ctx) {
1523
+ const jobId = err.observation.acceptedJobId;
1524
+ const read = `dvm status ${jobId ? shellQuoteArg(jobId) : "<accepted_job_id>"} --endpoint ${shellQuoteArg(ctx.endpoint)} --job-token <job_token_bearer_secret>`;
1525
+ const hint = `Do not pay again. Running request-result again meets the same refusal while the provider keeps answering with a different job. Read ${jobId ? `job ${jobId}` : "the accepted job"} directly with '${read}', taking the job token from a row for request ${ctx.requestId} in 'dvm wallet submissions' (this refusal is recorded as ${ctx.ambiguityId}). If no row for it holds a job token, this caller never received one for that job.`;
1526
+ return new ProviderIdentityError(
1527
+ err.observation,
1528
+ err.message,
1529
+ hint,
1530
+ { ...err.data, ambiguity_id: ctx.ambiguityId, request_id: ctx.requestId, claim_stored: false },
1531
+ err.proseSources
1532
+ );
1533
+ }
1534
+ function identityDataFields(observation) {
1535
+ return {
1536
+ ...optionalField("header_job_id", observation.headerJobId),
1537
+ ...optionalField("body_job_id", observation.bodyJobId),
1538
+ ...optionalField("body_job_id_escaped", observation.unstorable?.body_job_id),
1539
+ ...optionalField("accepted_job_id", observation.acceptedJobId),
1540
+ ...optionalField("accepted_job_id_escaped", observation.unstorable?.accepted_job_id)
1541
+ };
1542
+ }
1543
+ function warnInvalidJobIdentityHeader() {
1544
+ const display = "The provider sent a malformed job identity header, so it was ignored and the job ID was taken from the response body.";
1545
+ if (process.stderr.isTTY === true) {
1546
+ info(`Warning: ${display}`);
1547
+ return;
1548
+ }
1549
+ progress({ event: "warning", code: "job_identity_header_invalid", display });
1550
+ }
1551
+ function describeIdentityFailure(observation) {
1552
+ switch (observation.kind) {
1553
+ case "identity_mismatch":
1554
+ return {
1555
+ message: `The provider accepted the request but named job ${observation.headerJobId ?? "(unknown)"} in its response header and job ${observation.bodyJobId ?? "(unrepresentable)"} in its body.`,
1556
+ display: "The provider took this request but gave two different job IDs for it, so it is unclear which job is yours. Do not pay for it again."
1557
+ };
1558
+ case "body_unreadable":
1559
+ return {
1560
+ message: observation.headerJobId ? `The provider accepted the request as job ${observation.headerJobId}, but its response body could not be read.` : "The provider accepted the request, but its response did not state a readable job ID.",
1561
+ display: "The provider took this request but its reply could not be read, so it is unclear which job is yours. Do not pay for it again."
1562
+ };
1563
+ case "router_identity_conflict":
1564
+ return {
1565
+ message: `The router had already accepted job ${observation.acceptedJobId ?? "(unknown)"} for this request, and the provider answered with a different job.`,
1566
+ display: "This request was already accepted as a different job. Do not pay for it again."
1567
+ };
1568
+ }
1569
+ }
1570
+ function hasAsciiControl(value) {
1571
+ for (const character of value) {
1572
+ const code = character.charCodeAt(0);
1573
+ if (code <= 31 || code === 127) return true;
1574
+ }
1575
+ return false;
1576
+ }
1577
+ function optionalField(key, value) {
1578
+ return value === void 0 ? {} : { [key]: value };
1579
+ }
1580
+
1581
+ // src/lib/submission-evidence.ts
1582
+ var SUBMISSION_EVIDENCE_DIR = join(CONFIG_DIR, "submission-evidence");
1583
+ function submissionEvidenceKey(args) {
1584
+ return args.cashuRequestId ?? args.publicRequestId ?? randomUUID();
1585
+ }
1586
+ function recordSubmissionEvidence(input) {
1587
+ const ambiguityId = submissionEvidenceKey(input);
1588
+ const existing = loadSubmissionEvidence(ambiguityId);
1589
+ if (existing) return existing;
1590
+ const { observation } = input;
1591
+ const jobToken = isOpaqueJobToken(observation.jobToken) ? observation.jobToken : void 0;
1592
+ const record = {
1593
+ v: 1,
1594
+ ambiguity_id: ambiguityId,
1595
+ kind: observation.kind,
1596
+ observed_at: new Date((input.now ?? Date.now)()).toISOString(),
1597
+ endpoint: input.endpoint,
1598
+ ...input.dvmId ? { dvm_id: input.dvmId } : {},
1599
+ ...input.capability ? { capability: input.capability } : {},
1600
+ ...input.publicRequestId ? { request_id: input.publicRequestId } : {},
1601
+ ...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
1602
+ rail: input.rail,
1603
+ ...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
1604
+ ...jobToken ? { job_token: jobToken } : {},
1605
+ ...boundedIds(observation),
1606
+ ...observation.unstorable && Object.keys(observation.unstorable).length > 0 ? { unstorable_job_ids: observation.unstorable } : {},
1607
+ claim_stored: false
1608
+ };
1609
+ return publishOnce(record);
1610
+ }
1611
+ function recordLocalJobCollision(input) {
1612
+ const ambiguityId = `${input.publicRequestId}#local-job-collision`;
1613
+ const existing = loadSubmissionEvidence(ambiguityId);
1614
+ if (existing) return existing;
1615
+ const jobToken = isOpaqueJobToken(input.jobToken) ? input.jobToken : void 0;
1616
+ return publishOnce({
1617
+ v: 1,
1618
+ ambiguity_id: ambiguityId,
1619
+ kind: "local_job_collision",
1620
+ observed_at: new Date((input.now ?? Date.now)()).toISOString(),
1621
+ endpoint: input.endpoint,
1622
+ ...input.dvmId ? { dvm_id: input.dvmId } : {},
1623
+ ...input.capability ? { capability: input.capability } : {},
1624
+ request_id: input.publicRequestId,
1625
+ ...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
1626
+ rail: input.rail,
1627
+ ...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
1628
+ ...jobToken ? { job_token: jobToken } : {},
1629
+ ...boundedIds({ acceptedJobId: input.jobId }),
1630
+ claim_stored: false
1631
+ });
1632
+ }
1633
+ function recordIdentityFailure(err, input) {
1634
+ if (identityFailureRecorded(err)) return { error: err, record: null };
1635
+ const record = recordSubmissionEvidence({ ...input, observation: err.observation });
1636
+ return {
1637
+ error: withIdentityRecovery(err, {
1638
+ ambiguityId: record.ambiguity_id,
1639
+ ...input.publicRequestId ? { publicRequestId: input.publicRequestId } : {},
1640
+ ...input.cashuRequestId ? { cashuRequestId: input.cashuRequestId } : {}
1641
+ }),
1642
+ record
1643
+ };
1644
+ }
1645
+ function identityFailureRecorded(err) {
1646
+ return typeof err.data?.ambiguity_id === "string";
1647
+ }
1648
+ function loadSubmissionEvidence(ambiguityId) {
1649
+ const path = evidencePath(ambiguityId);
1650
+ if (!existsSync2(path)) return null;
1651
+ const record = readRecord(path);
1652
+ if (record.ambiguity_id !== ambiguityId) throw unreadable(path, "key mismatch");
1653
+ return record;
1654
+ }
1655
+ function listSubmissionEvidence() {
1656
+ if (!existsSync2(SUBMISSION_EVIDENCE_DIR)) return { records: [], unreadable: [] };
1657
+ const records = [];
1658
+ const unreadable2 = [];
1659
+ for (const name of readdirSync(SUBMISSION_EVIDENCE_DIR).filter((n) => n.endsWith(".json"))) {
1660
+ const path = join(SUBMISSION_EVIDENCE_DIR, name);
1661
+ try {
1662
+ records.push(readRecord(path));
1663
+ } catch (error) {
1664
+ const cause = error instanceof DvmError ? error.data?.cause : void 0;
1665
+ unreadable2.push({ path, cause: typeof cause === "string" ? cause : "unreadable" });
1666
+ }
1667
+ }
1668
+ records.sort((a, b) => a.observed_at.localeCompare(b.observed_at));
1669
+ return { records, unreadable: unreadable2 };
1670
+ }
1671
+ function journalMarkerFor(record) {
1672
+ const kind = record.kind;
1673
+ if (kind === "local_job_collision") {
1674
+ throw unreadable(evidencePath(record.ambiguity_id), "not an identity failure");
1675
+ }
1676
+ return {
1677
+ kind,
1678
+ observed_at: record.observed_at,
1679
+ ...boundedMarkerIds(record),
1680
+ ambiguity_id: record.ambiguity_id
1681
+ };
1682
+ }
1683
+ function publishOnce(record) {
1684
+ const ambiguityId = record.ambiguity_id;
1685
+ ensureConfigSubdir(SUBMISSION_EVIDENCE_DIR);
1686
+ const target = evidencePath(ambiguityId);
1687
+ const temp = `${target}.${String(process.pid)}.${randomUUID()}.tmp`;
1688
+ const fd = openSync3(temp, "wx", 384);
1689
+ try {
1690
+ writeFileSync3(fd, JSON.stringify(record, null, 2) + "\n");
1691
+ fsyncSync3(fd);
1692
+ } finally {
1693
+ closeSync3(fd);
1694
+ }
1695
+ try {
1696
+ linkSync(temp, target);
1697
+ } catch (error) {
1698
+ if (error.code !== "EEXIST") throw error;
1699
+ } finally {
1700
+ unlinkSync2(temp);
1701
+ }
1702
+ fsyncDirectory2(SUBMISSION_EVIDENCE_DIR);
1703
+ return loadSubmissionEvidence(ambiguityId) ?? record;
1704
+ }
1705
+ function boundedIds(observation) {
1706
+ const header = observedJobId(observation.headerJobId);
1707
+ const body = observedJobId(observation.bodyJobId);
1708
+ const accepted = observedJobId(observation.acceptedJobId);
1709
+ return {
1710
+ ...header !== void 0 ? { header_job_id: header } : {},
1711
+ ...body !== void 0 ? { body_job_id: body } : {},
1712
+ ...accepted !== void 0 ? { accepted_job_id: accepted } : {}
1713
+ };
1714
+ }
1715
+ function boundedMarkerIds(record) {
1716
+ return boundedIds({
1717
+ headerJobId: record.header_job_id,
1718
+ bodyJobId: record.body_job_id,
1719
+ acceptedJobId: record.accepted_job_id
1720
+ });
1721
+ }
1722
+ function evidencePath(ambiguityId) {
1723
+ const name = createHash("sha256").update(ambiguityId).digest("hex");
1724
+ return join(SUBMISSION_EVIDENCE_DIR, `${name}.json`);
1725
+ }
1726
+ function readRecord(path) {
1727
+ let parsed;
1728
+ try {
1729
+ parsed = JSON.parse(readFileSync3(path, "utf8"));
1730
+ } catch (error) {
1731
+ throw unreadable(path, error instanceof Error ? error.message : String(error));
1732
+ }
1733
+ if (!isEvidenceRecord(parsed)) throw unreadable(path, "invalid shape");
1734
+ return parsed;
1735
+ }
1736
+ function unreadable(path, cause) {
1737
+ return new DvmError(
1738
+ "submission_evidence_unreadable",
1739
+ `A submission evidence record at ${path} is unreadable.`,
1740
+ "Restore it from a backup. Do not pay again for any request it may describe; automatic retries stay off until it reads.",
1741
+ { cause }
1742
+ );
1743
+ }
1744
+ var KINDS = /* @__PURE__ */ new Set([
1745
+ "identity_mismatch",
1746
+ "body_unreadable",
1747
+ "router_identity_conflict",
1748
+ "local_job_collision"
1749
+ ]);
1750
+ var RAILS = /* @__PURE__ */ new Set(["cashu", "x402", "tempo", "credit", "none"]);
1751
+ function isEvidenceRecord(value) {
1752
+ if (!isPlainObject(value)) return false;
1753
+ const record = value;
1754
+ const optionalString = (key) => record[key] === void 0 || typeof record[key] === "string";
1755
+ return record.v === 1 && typeof record.ambiguity_id === "string" && KINDS.has(record.kind) && typeof record.observed_at === "string" && typeof record.endpoint === "string" && RAILS.has(record.rail) && record.claim_stored === false && isOptionalStringRecord(record.unstorable_job_ids) && (record.rail_correlation === void 0 || isPlainObject(record.rail_correlation)) && [
1756
+ "dvm_id",
1757
+ "capability",
1758
+ "request_id",
1759
+ "cashu_request_id",
1760
+ "job_token",
1761
+ "header_job_id",
1762
+ "body_job_id",
1763
+ "accepted_job_id"
1764
+ ].every(optionalString);
1765
+ }
1766
+ function isPlainObject(value) {
1767
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1768
+ }
1769
+ function isOptionalStringRecord(value) {
1770
+ return value === void 0 || isPlainObject(value) && Object.values(value).every((entry) => typeof entry === "string");
1771
+ }
1772
+ function fsyncDirectory2(path) {
1773
+ let fd;
1774
+ try {
1775
+ fd = openSync3(path, "r");
1776
+ fsyncSync3(fd);
1777
+ } finally {
1778
+ if (fd !== void 0) closeSync3(fd);
1779
+ }
1780
+ }
1781
+
1782
+ // src/lib/job-access.ts
1783
+ function resolveJobAccess(jobId, opts) {
1784
+ const stored = loadJob(jobId);
1785
+ return resolveJobAccessWithRecord(jobId, opts, stored);
1786
+ }
1787
+ function resolveJobAccessWithRecord(jobId, opts, record) {
1788
+ const endpointOverride = opts.endpoint ?? process.env.DVM_JOB_ENDPOINT;
1789
+ const tokenOverride = opts.jobToken ?? process.env.DVM_JOB_TOKEN;
1790
+ const endpointOverridden = endpointOverride !== void 0;
1791
+ const tokenOverridden = tokenOverride !== void 0;
1792
+ const foreign = record !== null && endpointOverride !== void 0 && !sameEndpoint(resolveEndpoint(endpointOverride), record.endpoint);
1793
+ const stored = foreign ? null : record;
1794
+ const rawEndpoint = endpointOverride ?? stored?.endpoint;
1795
+ const jobToken = tokenOverride ?? stored?.jobToken;
1796
+ if (!stored && rawEndpoint === void 0 && jobToken === void 0) {
1797
+ throw new DvmError(
1798
+ "job_access_required",
1799
+ `Job ${jobId} is not in the local store, and no portable job access was supplied.`,
1800
+ "Pass --endpoint <url> and --job-token <hex>, or set DVM_JOB_ENDPOINT and DVM_JOB_TOKEN."
1801
+ );
1802
+ }
1803
+ if (rawEndpoint === void 0) {
1804
+ throw new DvmError(
1805
+ "job_endpoint_required",
1806
+ `No provider endpoint is available for job ${jobId}.`,
1807
+ "Pass --endpoint <url> or set DVM_JOB_ENDPOINT."
1808
+ );
1809
+ }
1810
+ if (foreign && jobToken === void 0) {
1811
+ throw foreignJobTokenRequired(jobId, record.endpoint, resolveEndpoint(endpointOverride));
1812
+ }
1813
+ if (!stored && jobToken === void 0) {
1814
+ throw new DvmError(
1815
+ "job_token_required",
1816
+ `No job token is available for job ${jobId}.`,
1817
+ "Pass --job-token <hex> or set DVM_JOB_TOKEN."
1818
+ );
1819
+ }
1820
+ if (tokenOverridden && !isJobToken(jobToken)) {
1821
+ throw new DvmError(
1822
+ "invalid_job_token",
1823
+ "The supplied job token is not a 64-character hexadecimal value.",
1824
+ "Copy the job_token returned when the job was submitted; the value is never printed by this command."
1825
+ );
1826
+ }
1827
+ return {
1828
+ stored,
1829
+ ref: { endpoint: validateProviderEndpoint(resolveEndpoint(rawEndpoint)) },
1830
+ ...jobToken !== void 0 ? { jobToken } : {},
1831
+ overridden: endpointOverridden || tokenOverridden,
1832
+ endpointOverridden
1833
+ };
1834
+ }
1835
+ function resolveStoredJobAccess(jobId, opts) {
1836
+ const stored = loadJob(jobId);
1837
+ if (!stored) {
1838
+ throw new DvmError(
1839
+ "job_payment_state_required",
1840
+ `Cannot pay job ${jobId} without its local payment state.`,
1841
+ "Run 'dvm pay' where the job record and message history are available (normally the submitting machine). An endpoint and job token cannot reconstruct its pending request and spending policy."
1842
+ );
1843
+ }
1844
+ return { ...resolveJobAccessWithRecord(jobId, opts, stored), stored };
1845
+ }
1846
+ async function withJobTokenRedaction(jobToken, action) {
1847
+ try {
1848
+ return await action();
1849
+ } catch (err) {
1850
+ throw redactJobTokenFromError(err, jobToken);
1851
+ }
1852
+ }
1853
+ function redactJobTokenFromError(err, jobToken) {
1854
+ if (!jobToken || !(err instanceof DvmError)) return err;
1855
+ const redact = (value) => value.replaceAll(jobToken, "[REDACTED]");
1856
+ return new DvmError(
1857
+ err.code,
1858
+ redact(err.message),
1859
+ err.hint === void 0 ? void 0 : redact(err.hint),
1860
+ err.data === void 0 ? void 0 : redactRecord(err.data, redact),
1861
+ err.display === void 0 ? void 0 : redact(err.display),
1862
+ err.proseSources
1863
+ );
1864
+ }
1865
+ function sameEndpoint(a, b) {
1866
+ const normalize = (value) => {
1867
+ try {
1868
+ const url = new URL(value);
1869
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
1870
+ } catch {
1871
+ return value.replace(/\/+$/, "");
1872
+ }
1873
+ };
1874
+ return normalize(a) === normalize(b);
1875
+ }
1876
+ function foreignJobTokenRequired(jobId, localEndpoint, endpoint) {
1877
+ const row = evidenceRowWithToken(jobId, endpoint);
1878
+ return new DvmError(
1879
+ "job_token_required",
1880
+ `Local job ${jobId} belongs to ${localEndpoint}. Its job token was issued there and is not sent to ${endpoint}.`,
1881
+ row ? `The job token for ${jobId} at ${endpoint} is job_token_bearer_secret on evidence row ${row} in 'dvm wallet submissions'. Pass it with --job-token or DVM_JOB_TOKEN.` : `Pass the job token ${endpoint} issued for ${jobId} with --job-token or DVM_JOB_TOKEN. No evidence row in 'dvm wallet submissions' holds one for it.`,
1882
+ {
1883
+ job_id: jobId,
1884
+ local_endpoint: localEndpoint,
1885
+ endpoint,
1886
+ ...row ? { ambiguity_id: row } : {}
1887
+ }
1888
+ );
1889
+ }
1890
+ function evidenceRowWithToken(jobId, endpoint) {
1891
+ let records;
1892
+ try {
1893
+ ({ records } = listSubmissionEvidence());
1894
+ } catch {
1895
+ return void 0;
1896
+ }
1897
+ return records.filter(
1898
+ (record) => record.job_token !== void 0 && sameEndpoint(record.endpoint, endpoint) && [record.header_job_id, record.body_job_id, record.accepted_job_id].includes(jobId)
1899
+ ).at(-1)?.ambiguity_id;
1900
+ }
1901
+ function isJobToken(value) {
1902
+ return value !== void 0 && /^[0-9a-fA-F]{64}$/.test(value);
1903
+ }
1904
+ function validateProviderEndpoint(value) {
1905
+ try {
1906
+ const url = new URL(value);
1907
+ if ((url.protocol === "http:" || url.protocol === "https:") && url.hostname) return value;
1908
+ } catch {
1909
+ }
1910
+ throw new DvmError(
1911
+ "invalid_endpoint",
1912
+ "The supplied job endpoint is not a valid HTTP(S) provider URL.",
1913
+ "Pass a full URL such as https://provider.example, or a favorite alias such as @provider."
1914
+ );
1915
+ }
1916
+ function redactRecord(record, redact) {
1917
+ return Object.fromEntries(
1918
+ Object.entries(record).map(([key, value]) => [key, redactValue(value, redact)])
1919
+ );
1920
+ }
1921
+ function redactValue(value, redact) {
1922
+ if (typeof value === "string") return redact(value);
1923
+ if (Array.isArray(value)) return value.map((entry) => redactValue(entry, redact));
1924
+ if (value && typeof value === "object") {
1925
+ return redactRecord(value, redact);
1926
+ }
1927
+ return value;
1928
+ }
1929
+
1930
+ // src/lib/draw-funding.ts
1931
+ function verifiedFunding(job, receipt, fundId) {
1932
+ const binding = job.creditBinding;
1933
+ if (!binding || "unbound" in binding || !isDrawFundingReceipt(receipt)) return;
1934
+ const verdict = verifyDrawFundingReceiptChain({
1935
+ receipt,
1936
+ builder: job.builderAnchor,
1937
+ expectedJobId: job.id,
1938
+ expectedCreditId: binding.creditId,
1939
+ expectedDrawId: binding.drawId,
1940
+ expectedCallerPubkey: binding.callerPubkey,
1941
+ ...fundId ? { expectedFundId: fundId } : {}
1942
+ });
1943
+ if (verdict.status === "verified" || verdict.status === "verified_unattested") return receipt;
1944
+ }
1945
+ function captureDrawFundingReceipts(jobId, receipts, opts) {
1946
+ if (!receipts?.length || !loadJob(jobId)) return;
1947
+ try {
1948
+ mutateCreditPayment(jobId, (job) => {
1949
+ if (opts?.endpoint && !sameEndpoint(job.endpoint, opts.endpoint)) return;
1950
+ for (const raw of receipts) {
1951
+ const receipt = verifiedFunding(job, raw, opts?.fundId);
1952
+ if (!receipt) {
1953
+ info("Warning: mid-job funding evidence did not verify; credit comparisons remain unchanged.");
1954
+ continue;
1955
+ }
1956
+ const held = (Array.isArray(job.drawFundingReceipts) ? job.drawFundingReceipts : []).filter((entry) => verifiedFunding(job, entry) !== void 0);
1957
+ if (!held.some((entry) => entry.fund_id === receipt.fund_id)) {
1958
+ held.push(receipt);
1959
+ job.drawFundingReceipts = held;
1960
+ }
1961
+ }
1962
+ });
1963
+ } catch (error) {
1964
+ info(`Warning: could not store mid-job funding evidence: ${error instanceof Error ? error.message : String(error)}`);
1965
+ }
1966
+ }
1967
+ function jobDrawFundings(jobId, endpoint, callerPubkey, credit) {
1968
+ const job = loadJob(jobId);
1969
+ const binding = job?.creditBinding;
1970
+ if (!job || !sameEndpoint(job.endpoint, endpoint) || !binding || "unbound" in binding || binding.callerPubkey !== callerPubkey || binding.creditId !== credit.credit_id || binding.drawId !== credit.draw_id) return [];
1971
+ return (Array.isArray(job.drawFundingReceipts) ? job.drawFundingReceipts : []).filter((receipt) => verifiedFunding(job, receipt) !== void 0).map((receipt) => ({ receipt, builder: job.builderAnchor }));
1972
+ }
1973
+
1058
1974
  // src/lib/receipt-capture.ts
1059
1975
  function captureFundingReceipt(args) {
1060
1976
  if (!args.receipt) return args.parseError ? "unparseable" : "absent";
@@ -1106,6 +2022,8 @@ function captureJobReceipt(jobId, receipt, parseError) {
1106
2022
  return toCapture(receipt, result);
1107
2023
  }
1108
2024
  function captureTransportReceipt(jobId, response) {
2025
+ captureDrawFundingReceipts(jobId, response.drawFundingReceipts);
2026
+ if (response.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
1109
2027
  return captureJobReceipt(jobId, response.receipt, response.receiptParseError);
1110
2028
  }
1111
2029
  function receiptJsonFields(capture) {
@@ -1143,9 +2061,12 @@ async function fetchMissingJobReceipt(jobId, transport, ref) {
1143
2061
  if (held) return { receipt: held };
1144
2062
  try {
1145
2063
  const status = await transport.status(jobId, ref, { jobToken: job.jobToken });
2064
+ captureDrawFundingReceipts(jobId, status.drawFundingReceipts, { endpoint: ref.endpoint });
1146
2065
  return {
1147
2066
  ...status.receipt ? { receipt: status.receipt } : {},
1148
- ...status.receiptParseError ? { receiptParseError: status.receiptParseError } : {}
2067
+ ...status.receiptParseError ? { receiptParseError: status.receiptParseError } : {},
2068
+ ...status.drawFundingReceipts ? { drawFundingReceipts: status.drawFundingReceipts } : {},
2069
+ ...status.drawFundingReceiptParseError ? { drawFundingReceiptParseError: status.drawFundingReceiptParseError } : {}
1149
2070
  };
1150
2071
  } catch {
1151
2072
  return {};
@@ -1222,7 +2143,7 @@ function persistParseError(jobId, receiptParseError) {
1222
2143
  }
1223
2144
 
1224
2145
  // src/lib/wallet-agent/spend.ts
1225
- import { randomUUID } from "crypto";
2146
+ import { randomUUID as randomUUID2 } from "crypto";
1226
2147
 
1227
2148
  // src/lib/wallet-agent/builder-handle.ts
1228
2149
  var BUILDER_RESERVE_PREFIX = "builder/";
@@ -1394,7 +2315,7 @@ async function prepareAgentSpend(args) {
1394
2315
  submitContext = { ...submitContext, binding_fingerprint: bindingFingerprint };
1395
2316
  }
1396
2317
  const now = args.now ?? (() => Date.now());
1397
- const uuid = args.uuid ?? (() => randomUUID());
2318
+ const uuid = args.uuid ?? (() => randomUUID2());
1398
2319
  const timeoutSec = args.inFlightTimeoutSec ?? inFlightTimeoutSeconds();
1399
2320
  const getWalletForMint = args.getWalletForMint ?? getWallet;
1400
2321
  const refundClause = resolveRefundClause(args.cashuP2pk, args.locktimeSeconds, now(), {
@@ -2098,7 +3019,7 @@ async function runCreditFunding(args) {
2098
3019
  }
2099
3020
  clearPending(pending);
2100
3021
  }
2101
- const fundId = args.fundId ?? randomUUID2();
3022
+ const fundId = args.fundId ?? randomUUID3();
2102
3023
  const base = { creditId: args.creditId, fundId };
2103
3024
  const eligible = args.fundingMode ? availableRails(args).filter(isStablecoinFundRail) : availableRails(args);
2104
3025
  const x402Network = loadX402Wallet()?.network;
@@ -4866,7 +5787,7 @@ function planCreditForQuote(args) {
4866
5787
  return {
4867
5788
  mode: "topup",
4868
5789
  creditId: stored.creditId,
4869
- drawId: randomUUID3(),
5790
+ drawId: randomUUID4(),
4870
5791
  ...fundAmounts(fundMicro2, args.btcRate),
4871
5792
  currency: menu.currency,
4872
5793
  targetMicro: targetMicro2,
@@ -4893,13 +5814,13 @@ function planCreditForQuote(args) {
4893
5814
  }
4894
5815
  const openRoute = routeFor(fundMicro);
4895
5816
  if (openRoute.route === "deferred") {
4896
- return defer("open", randomUUID3(), fundMicro, targetMicro, fundMicro);
5817
+ return defer("open", randomUUID4(), fundMicro, targetMicro, fundMicro);
4897
5818
  }
4898
5819
  if (!canCashu) return none;
4899
5820
  return {
4900
5821
  mode: "open",
4901
- creditId: randomUUID3(),
4902
- drawId: randomUUID3(),
5822
+ creditId: randomUUID4(),
5823
+ drawId: randomUUID4(),
4903
5824
  ...fundAmounts(fundMicro, args.btcRate),
4904
5825
  currency: menu.currency,
4905
5826
  targetMicro,
@@ -4925,7 +5846,7 @@ function planProbeDraw(args) {
4925
5846
  return {
4926
5847
  mode: "draw",
4927
5848
  creditId: implicit.creditId,
4928
- drawId: randomUUID3(),
5849
+ drawId: randomUUID4(),
4929
5850
  source: "implicit"
4930
5851
  };
4931
5852
  }
@@ -4957,7 +5878,7 @@ function planProbeDraw(args) {
4957
5878
  });
4958
5879
  }
4959
5880
  }
4960
- return { mode: "draw", creditId: stored.creditId, drawId: randomUUID3(), source: "prepaid" };
5881
+ return { mode: "draw", creditId: stored.creditId, drawId: randomUUID4(), source: "prepaid" };
4961
5882
  }
4962
5883
  function needsTopup(balanceMicro, targetMicro) {
4963
5884
  return targetMicro > 0 && balanceMicro < targetMicro * TOPUP_THRESHOLD_FRACTION;
@@ -5453,14 +6374,51 @@ function errorMessage(err) {
5453
6374
  }
5454
6375
 
5455
6376
  export {
6377
+ parseUpfrontRailPayment,
6378
+ parseUpfrontPayment,
5456
6379
  saveJob,
6380
+ saveSubmittedJob,
6381
+ recordUpfrontCreditPayment,
6382
+ hasUnknownUpfrontCredit,
6383
+ recordUpfrontRailPayment,
6384
+ hasUnknownUpfrontRail,
5457
6385
  updateJob,
5458
6386
  markJobTerminal,
5459
6387
  loadJob,
5460
6388
  loadAllJobs,
5461
6389
  addPayment,
6390
+ markPaymentRequestInFlight,
6391
+ clearPaymentRequestInFlight,
6392
+ markPaymentRequestPaid,
5462
6393
  mutateCreditPayment,
5463
6394
  bookCreditPayment,
6395
+ loadFavorites,
6396
+ saveFavorite,
6397
+ removeFavorite,
6398
+ resolveEndpoint,
6399
+ deriveAlias,
6400
+ isIdentityFailure,
6401
+ isParseableBodyJobId,
6402
+ isOpaqueJobToken,
6403
+ settleJobIdentity,
6404
+ routerConflictObservation,
6405
+ jobIdentityHeaderValue,
6406
+ identityError,
6407
+ withIdentityRecovery,
6408
+ withRequestResultRecovery,
6409
+ identityDataFields,
6410
+ warnInvalidJobIdentityHeader,
6411
+ SUBMISSION_EVIDENCE_DIR,
6412
+ recordSubmissionEvidence,
6413
+ recordLocalJobCollision,
6414
+ recordIdentityFailure,
6415
+ loadSubmissionEvidence,
6416
+ listSubmissionEvidence,
6417
+ journalMarkerFor,
6418
+ resolveJobAccess,
6419
+ resolveStoredJobAccess,
6420
+ withJobTokenRedaction,
6421
+ sameEndpoint,
5464
6422
  buildTempoCredential,
5465
6423
  loadLedger,
5466
6424
  saveLedger,
@@ -5488,6 +6446,8 @@ export {
5488
6446
  epochMsToIso,
5489
6447
  receiptHint,
5490
6448
  receiptFailureDetail,
6449
+ captureDrawFundingReceipts,
6450
+ jobDrawFundings,
5491
6451
  captureFundingReceipt,
5492
6452
  captureTransportReceipt,
5493
6453
  receiptJsonFields,