@dvmkit/dvm-cli 0.9.1 → 0.10.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.
- package/dist/{chunk-XDYBVNFS.js → chunk-3YU6KRCX.js} +2 -2
- package/dist/{chunk-C7ZNQONB.js → chunk-C3HMFGYP.js} +1 -1
- package/dist/{chunk-6XTWANVN.js → chunk-CWWZM4M6.js} +519 -58
- package/dist/{chunk-QDOY3JF2.js → chunk-GMOKL4PQ.js} +1 -1
- package/dist/{chunk-PMPHS3LS.js → chunk-MTGQK7KA.js} +2 -2
- package/dist/{chunk-BCDMVIPI.js → chunk-NXXU3BSJ.js} +3 -3
- package/dist/{chunk-Y3X74XH2.js → chunk-Q45TAYK2.js} +850 -38
- package/dist/{chunk-5R3BLFVO.js → chunk-TGRY23IF.js} +1 -1
- package/dist/{client-MMJYIMKJ.js → client-MFSKFSV4.js} +2 -2
- package/dist/dvm.js +325 -926
- package/dist/{internal-LRW4XR3J.js → internal-5EGKBZAE.js} +11 -1
- package/dist/{lifecycle-QE3KHIHQ.js → lifecycle-7AVB36WP.js} +2 -2
- package/dist/{pocket-refill-DGA7UD7L.js → pocket-refill-SKECWGA3.js} +6 -6
- package/dist/{tempo-lifecycle-HJQYBOZR.js → tempo-lifecycle-SVPMTND2.js} +4 -4
- package/dist/{tempo-wallet-XN72C2GK.js → tempo-wallet-5PKLSWFX.js} +3 -3
- package/dist/{wallet-UEQTGVJE.js → wallet-7BBWAZYJ.js} +3 -3
- package/package.json +6 -3
- package/skills/dvm/calling.md +2 -0
|
@@ -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-
|
|
6
|
+
} from "./chunk-NXXU3BSJ.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-
|
|
14
|
+
} from "./chunk-C3HMFGYP.js";
|
|
15
15
|
import {
|
|
16
16
|
loadX402Wallet,
|
|
17
17
|
x402NetworkLabel
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-MTGQK7KA.js";
|
|
19
19
|
import {
|
|
20
20
|
isCreditPosture,
|
|
21
21
|
loadConfig
|
|
22
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-GMOKL4PQ.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-
|
|
169
|
+
} from "./chunk-CWWZM4M6.js";
|
|
161
170
|
import {
|
|
162
171
|
Challenge_exports,
|
|
163
172
|
Credential_exports
|
|
@@ -786,7 +795,7 @@ function supportsMethod(methods, method) {
|
|
|
786
795
|
}
|
|
787
796
|
|
|
788
797
|
// src/lib/credit-policy.ts
|
|
789
|
-
import { randomUUID as
|
|
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,7 +866,7 @@ function fail(mode, refusal) {
|
|
|
857
866
|
}
|
|
858
867
|
|
|
859
868
|
// src/lib/credit-fund.ts
|
|
860
|
-
import { randomUUID as
|
|
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";
|
|
@@ -916,11 +925,13 @@ function writeJobs(jobs) {
|
|
|
916
925
|
closeSync(fd);
|
|
917
926
|
}
|
|
918
927
|
renameSync(temporary, JOBS_FILE);
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
928
|
+
if (process.platform !== "win32") {
|
|
929
|
+
const directory = openSync(dirname(JOBS_FILE), "r");
|
|
930
|
+
try {
|
|
931
|
+
fsyncSync(directory);
|
|
932
|
+
} finally {
|
|
933
|
+
closeSync(directory);
|
|
934
|
+
}
|
|
924
935
|
}
|
|
925
936
|
}
|
|
926
937
|
function mutateJobs(change) {
|
|
@@ -1015,6 +1026,8 @@ function receiptFailureDetail(reason) {
|
|
|
1015
1026
|
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
1027
|
case "drain_id_mismatch":
|
|
1017
1028
|
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.";
|
|
1029
|
+
case "draw_id_mismatch":
|
|
1030
|
+
return "The funding receipt names a different draw than the job's accepted credit draw.";
|
|
1018
1031
|
case "credit_id_mismatch":
|
|
1019
1032
|
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
1033
|
case "fund_id_mismatch":
|
|
@@ -1025,6 +1038,8 @@ function receiptFailureDetail(reason) {
|
|
|
1025
1038
|
return "The signed post-funding balance differs from the provider's fresh balance response.";
|
|
1026
1039
|
case "funding_ledger_seq_mismatch":
|
|
1027
1040
|
return "The signed funding sequence differs from the provider's fresh balance response.";
|
|
1041
|
+
case "funding_currency_mismatch":
|
|
1042
|
+
return "The signed funding currency differs from the credit's native currency.";
|
|
1028
1043
|
case "caller_pubkey_mismatch":
|
|
1029
1044
|
return "The funding receipt names a different caller than the key that submitted the funding.";
|
|
1030
1045
|
case "signature_invalid":
|
|
@@ -1055,6 +1070,764 @@ function formatPaid(msats, rate) {
|
|
|
1055
1070
|
return `~$${formatUsd(usd)} (${satsLabel}, ${costAnchor(usd)})`;
|
|
1056
1071
|
}
|
|
1057
1072
|
|
|
1073
|
+
// src/lib/favorites.ts
|
|
1074
|
+
var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
|
|
1075
|
+
import {
|
|
1076
|
+
closeSync as closeSync2,
|
|
1077
|
+
fchmodSync,
|
|
1078
|
+
fsyncSync as fsyncSync2,
|
|
1079
|
+
openSync as openSync2,
|
|
1080
|
+
readFileSync as readFileSync2,
|
|
1081
|
+
renameSync as renameSync2,
|
|
1082
|
+
statSync,
|
|
1083
|
+
unlinkSync,
|
|
1084
|
+
writeFileSync as writeFileSync2
|
|
1085
|
+
} from "fs";
|
|
1086
|
+
import { dirname as dirname2 } from "path";
|
|
1087
|
+
var DEFAULT_FILE_MODE = 384;
|
|
1088
|
+
function loadFavorites() {
|
|
1089
|
+
let raw;
|
|
1090
|
+
try {
|
|
1091
|
+
raw = readFileSync2(FAVORITES_FILE, "utf8");
|
|
1092
|
+
} catch (error) {
|
|
1093
|
+
if (nodeErrorCode(error) === "ENOENT") return {};
|
|
1094
|
+
throw unreadableFavorites(error);
|
|
1095
|
+
}
|
|
1096
|
+
try {
|
|
1097
|
+
const parsed = JSON.parse(raw);
|
|
1098
|
+
if (!isFavoritesMap(parsed)) throw new Error("invalid favorites shape");
|
|
1099
|
+
return parsed;
|
|
1100
|
+
} catch (error) {
|
|
1101
|
+
throw unreadableFavorites(error);
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
async function saveFavorite(alias, fav) {
|
|
1105
|
+
return withFavoritesLock(() => {
|
|
1106
|
+
const favs = loadFavorites();
|
|
1107
|
+
const existed = Object.hasOwn(favs, alias);
|
|
1108
|
+
favs[alias] = fav;
|
|
1109
|
+
writeFavorites(favs);
|
|
1110
|
+
return existed;
|
|
1111
|
+
});
|
|
1112
|
+
}
|
|
1113
|
+
async function removeFavorite(alias) {
|
|
1114
|
+
return withFavoritesLock(() => {
|
|
1115
|
+
const favs = loadFavorites();
|
|
1116
|
+
if (!Object.hasOwn(favs, alias)) return false;
|
|
1117
|
+
const { [alias]: _, ...rest } = favs;
|
|
1118
|
+
writeFavorites(rest);
|
|
1119
|
+
return true;
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
function resolveEndpoint(input) {
|
|
1123
|
+
if (!input.startsWith("@")) return input;
|
|
1124
|
+
const alias = input.slice(1);
|
|
1125
|
+
const favs = loadFavorites();
|
|
1126
|
+
const fav = Object.hasOwn(favs, alias) ? favs[alias] : void 0;
|
|
1127
|
+
if (!fav) {
|
|
1128
|
+
throw new DvmError(
|
|
1129
|
+
"unknown_favorite",
|
|
1130
|
+
`No favorite named "${alias}".`,
|
|
1131
|
+
"Run 'dvm fav list' to see saved favorites, or 'dvm fav add <endpoint>' to save one."
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
return fav.endpoint;
|
|
1135
|
+
}
|
|
1136
|
+
function deriveAlias(endpoint) {
|
|
1137
|
+
try {
|
|
1138
|
+
const hostname = new URL(endpoint).hostname;
|
|
1139
|
+
if (hostname.endsWith(".dvmkit.ai")) {
|
|
1140
|
+
const prefix = hostname.replace(".dvmkit.ai", "");
|
|
1141
|
+
const dashIdx = prefix.indexOf("--");
|
|
1142
|
+
if (dashIdx !== -1) return prefix.slice(dashIdx + 2);
|
|
1143
|
+
return prefix;
|
|
1144
|
+
}
|
|
1145
|
+
return hostname.replace(/\.[^.]+$/, "").replace(/\./g, "-");
|
|
1146
|
+
} catch {
|
|
1147
|
+
return endpoint.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
async function withFavoritesLock(fn) {
|
|
1151
|
+
ensureConfigDir();
|
|
1152
|
+
let release;
|
|
1153
|
+
try {
|
|
1154
|
+
release = await import_proper_lockfile2.default.lock(FAVORITES_FILE, {
|
|
1155
|
+
lockfilePath: `${FAVORITES_FILE}.lock`,
|
|
1156
|
+
realpath: false,
|
|
1157
|
+
stale: 3e4,
|
|
1158
|
+
retries: { retries: 10, factor: 1, minTimeout: 100, maxTimeout: 100 }
|
|
1159
|
+
});
|
|
1160
|
+
} catch {
|
|
1161
|
+
throw new DvmError(
|
|
1162
|
+
"favorites_locked",
|
|
1163
|
+
"Another dvm process is updating saved favorites.",
|
|
1164
|
+
"Wait a moment and retry."
|
|
1165
|
+
);
|
|
1166
|
+
}
|
|
1167
|
+
try {
|
|
1168
|
+
return await fn();
|
|
1169
|
+
} finally {
|
|
1170
|
+
await release().catch(() => void 0);
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
function writeFavorites(favorites) {
|
|
1174
|
+
const mode = favoritesFileMode();
|
|
1175
|
+
const temporary = `${FAVORITES_FILE}.${String(process.pid)}.${randomSuffix()}.tmp`;
|
|
1176
|
+
const contents = JSON.stringify(favorites, null, 2) + "\n";
|
|
1177
|
+
let fd;
|
|
1178
|
+
try {
|
|
1179
|
+
fd = openSync2(temporary, "wx", mode);
|
|
1180
|
+
fchmodSync(fd, mode);
|
|
1181
|
+
writeFileSync2(fd, contents);
|
|
1182
|
+
fsyncSync2(fd);
|
|
1183
|
+
closeSync2(fd);
|
|
1184
|
+
fd = void 0;
|
|
1185
|
+
renameSync2(temporary, FAVORITES_FILE);
|
|
1186
|
+
fsyncDirectory(dirname2(FAVORITES_FILE));
|
|
1187
|
+
} catch (error) {
|
|
1188
|
+
if (fd !== void 0) {
|
|
1189
|
+
try {
|
|
1190
|
+
closeSync2(fd);
|
|
1191
|
+
} catch {
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
try {
|
|
1195
|
+
unlinkSync(temporary);
|
|
1196
|
+
} catch {
|
|
1197
|
+
}
|
|
1198
|
+
throw error;
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
function favoritesFileMode() {
|
|
1202
|
+
try {
|
|
1203
|
+
return statSync(FAVORITES_FILE).mode & 511;
|
|
1204
|
+
} catch (error) {
|
|
1205
|
+
if (nodeErrorCode(error) === "ENOENT") return DEFAULT_FILE_MODE;
|
|
1206
|
+
throw error;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
function fsyncDirectory(path) {
|
|
1210
|
+
if (process.platform === "win32") return;
|
|
1211
|
+
const fd = openSync2(path, "r");
|
|
1212
|
+
try {
|
|
1213
|
+
fsyncSync2(fd);
|
|
1214
|
+
} finally {
|
|
1215
|
+
closeSync2(fd);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
function randomSuffix() {
|
|
1219
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
1220
|
+
}
|
|
1221
|
+
function unreadableFavorites(error) {
|
|
1222
|
+
return new DvmError(
|
|
1223
|
+
"favorites_unreadable",
|
|
1224
|
+
"Saved favorites are corrupt or unreadable.",
|
|
1225
|
+
`The original file at ${FAVORITES_FILE} was left unchanged. Restore it from a backup, or move it aside before rebuilding favorites.`,
|
|
1226
|
+
{
|
|
1227
|
+
path: FAVORITES_FILE,
|
|
1228
|
+
...nodeErrorCode(error) ? { error_code: nodeErrorCode(error) } : {}
|
|
1229
|
+
}
|
|
1230
|
+
);
|
|
1231
|
+
}
|
|
1232
|
+
function nodeErrorCode(error) {
|
|
1233
|
+
if (!(error instanceof Error) || !("code" in error)) return void 0;
|
|
1234
|
+
const code = error.code;
|
|
1235
|
+
return typeof code === "string" && /^E[A-Z0-9_]{1,63}$/.test(code) ? code : void 0;
|
|
1236
|
+
}
|
|
1237
|
+
function isFavoritesMap(value) {
|
|
1238
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1239
|
+
return Object.values(value).every(isFavorite);
|
|
1240
|
+
}
|
|
1241
|
+
function isFavorite(value) {
|
|
1242
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1243
|
+
const candidate = value;
|
|
1244
|
+
return typeof candidate.endpoint === "string" && typeof candidate.addedAt === "number" && Number.isFinite(candidate.addedAt) && (candidate.name === void 0 || typeof candidate.name === "string");
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
// src/lib/submission-evidence.ts
|
|
1248
|
+
import { createHash, randomUUID } from "crypto";
|
|
1249
|
+
import {
|
|
1250
|
+
closeSync as closeSync3,
|
|
1251
|
+
existsSync as existsSync2,
|
|
1252
|
+
fsyncSync as fsyncSync3,
|
|
1253
|
+
linkSync,
|
|
1254
|
+
openSync as openSync3,
|
|
1255
|
+
readdirSync,
|
|
1256
|
+
readFileSync as readFileSync3,
|
|
1257
|
+
unlinkSync as unlinkSync2,
|
|
1258
|
+
writeFileSync as writeFileSync3
|
|
1259
|
+
} from "fs";
|
|
1260
|
+
import { join } from "path";
|
|
1261
|
+
|
|
1262
|
+
// src/lib/job-identity.ts
|
|
1263
|
+
var IDENTITY_FAILURE_CODES = {
|
|
1264
|
+
identity_mismatch: "provider_identity_mismatch",
|
|
1265
|
+
body_unreadable: "provider_body_unreadable",
|
|
1266
|
+
router_identity_conflict: "hosting_job_identity_conflict"
|
|
1267
|
+
};
|
|
1268
|
+
var ProviderIdentityError = class extends DvmError {
|
|
1269
|
+
observation;
|
|
1270
|
+
constructor(observation, message, hint, data, proseSources) {
|
|
1271
|
+
super(IDENTITY_FAILURE_CODES[observation.kind], message, hint, data, void 0, proseSources);
|
|
1272
|
+
this.observation = observation;
|
|
1273
|
+
}
|
|
1274
|
+
};
|
|
1275
|
+
function isIdentityFailure(err) {
|
|
1276
|
+
return err instanceof ProviderIdentityError;
|
|
1277
|
+
}
|
|
1278
|
+
function isParseableBodyJobId(value) {
|
|
1279
|
+
return typeof value === "string" && value.trim().length > 0 && value.length <= 512 && !hasAsciiControl(value);
|
|
1280
|
+
}
|
|
1281
|
+
function isOpaqueJobToken(value) {
|
|
1282
|
+
return typeof value === "string" && value.length > 0 && value.length <= 4096 && value.trim() === value && !hasAsciiControl(value);
|
|
1283
|
+
}
|
|
1284
|
+
function observedJobId(value) {
|
|
1285
|
+
return isStorableJobId(value) ? value : void 0;
|
|
1286
|
+
}
|
|
1287
|
+
function observeJobId(value) {
|
|
1288
|
+
if (value === void 0) return {};
|
|
1289
|
+
if (isStorableJobId(value)) return { stored: value };
|
|
1290
|
+
return { escaped: escapeObservedValue(value) };
|
|
1291
|
+
}
|
|
1292
|
+
var ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT = 1024;
|
|
1293
|
+
function escapeObservedValue(value) {
|
|
1294
|
+
const source = typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
|
|
1295
|
+
const truncated = source.length > ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT;
|
|
1296
|
+
const quoted = JSON.stringify(
|
|
1297
|
+
truncated ? source.slice(0, ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT) : source
|
|
1298
|
+
).replace(
|
|
1299
|
+
/[\u007f-\u009f]/gu,
|
|
1300
|
+
(character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
|
|
1301
|
+
);
|
|
1302
|
+
return truncated ? `${quoted} [truncated from ${String(source.length)} characters]` : quoted;
|
|
1303
|
+
}
|
|
1304
|
+
function settleJobIdentity(headerValue, body) {
|
|
1305
|
+
const header = parseJobIdentityHeader(headerValue);
|
|
1306
|
+
const headerJobId = header.kind === "valid" ? header.jobId : void 0;
|
|
1307
|
+
const rawBodyJobId = body?.job_id;
|
|
1308
|
+
const jobToken = isOpaqueJobToken(body?.job_token) ? body.job_token : void 0;
|
|
1309
|
+
const observed = (kind) => {
|
|
1310
|
+
const bodyJob = observeJobId(rawBodyJobId);
|
|
1311
|
+
return {
|
|
1312
|
+
kind: "unresolved",
|
|
1313
|
+
observation: {
|
|
1314
|
+
kind,
|
|
1315
|
+
...headerJobId ? { headerJobId } : {},
|
|
1316
|
+
...optionalField("bodyJobId", bodyJob.stored),
|
|
1317
|
+
...bodyJob.escaped ? { unstorable: { body_job_id: bodyJob.escaped } } : {},
|
|
1318
|
+
...jobToken ? { jobToken } : {}
|
|
1319
|
+
}
|
|
1320
|
+
};
|
|
1321
|
+
};
|
|
1322
|
+
if (!isParseableBodyJobId(rawBodyJobId)) return observed("body_unreadable");
|
|
1323
|
+
if (headerJobId !== void 0 && headerJobId !== rawBodyJobId) {
|
|
1324
|
+
return observed("identity_mismatch");
|
|
1325
|
+
}
|
|
1326
|
+
return {
|
|
1327
|
+
kind: "settled",
|
|
1328
|
+
jobId: rawBodyJobId,
|
|
1329
|
+
claimAllowed: header.kind !== "invalid",
|
|
1330
|
+
headerInvalid: header.kind === "invalid"
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
function routerConflictObservation(status, body) {
|
|
1334
|
+
if (status !== 409 || !body) return void 0;
|
|
1335
|
+
const error = body.error;
|
|
1336
|
+
if (!error || typeof error !== "object" || Array.isArray(error)) return void 0;
|
|
1337
|
+
const envelope = error;
|
|
1338
|
+
if (envelope.code !== IDENTITY_FAILURE_CODES.router_identity_conflict) return void 0;
|
|
1339
|
+
const accepted = observeJobId(envelope.accepted_job_id);
|
|
1340
|
+
return {
|
|
1341
|
+
kind: "router_identity_conflict",
|
|
1342
|
+
...optionalField("acceptedJobId", accepted.stored),
|
|
1343
|
+
...accepted.escaped ? { unstorable: { accepted_job_id: accepted.escaped } } : {}
|
|
1344
|
+
};
|
|
1345
|
+
}
|
|
1346
|
+
function jobIdentityHeaderValue(headers) {
|
|
1347
|
+
return headers.get(JOB_IDENTITY_HEADER);
|
|
1348
|
+
}
|
|
1349
|
+
function identityError(observation, providerProse) {
|
|
1350
|
+
const { message, display } = describeIdentityFailure(observation);
|
|
1351
|
+
return new ProviderIdentityError(
|
|
1352
|
+
observation,
|
|
1353
|
+
message,
|
|
1354
|
+
"Do not pay for this request again. Run 'dvm wallet submissions' to see what was recorded.",
|
|
1355
|
+
{
|
|
1356
|
+
identity_kind: observation.kind,
|
|
1357
|
+
...identityDataFields(observation),
|
|
1358
|
+
display: providerProse?.display ?? display
|
|
1359
|
+
},
|
|
1360
|
+
providerProse?.proseSources
|
|
1361
|
+
);
|
|
1362
|
+
}
|
|
1363
|
+
function withIdentityRecovery(err, ctx) {
|
|
1364
|
+
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.`;
|
|
1365
|
+
return new ProviderIdentityError(
|
|
1366
|
+
err.observation,
|
|
1367
|
+
err.message,
|
|
1368
|
+
hint,
|
|
1369
|
+
{
|
|
1370
|
+
...err.data,
|
|
1371
|
+
ambiguity_id: ctx.ambiguityId,
|
|
1372
|
+
...ctx.publicRequestId ? { request_id: ctx.publicRequestId } : {},
|
|
1373
|
+
...ctx.cashuRequestId ? { cashu_request_id: ctx.cashuRequestId } : {},
|
|
1374
|
+
claim_stored: false
|
|
1375
|
+
},
|
|
1376
|
+
err.proseSources
|
|
1377
|
+
);
|
|
1378
|
+
}
|
|
1379
|
+
function withRequestResultRecovery(err, ctx) {
|
|
1380
|
+
const jobId = err.observation.acceptedJobId;
|
|
1381
|
+
const read = `dvm status ${jobId ? shellQuoteArg(jobId) : "<accepted_job_id>"} --endpoint ${shellQuoteArg(ctx.endpoint)} --job-token <job_token_bearer_secret>`;
|
|
1382
|
+
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.`;
|
|
1383
|
+
return new ProviderIdentityError(
|
|
1384
|
+
err.observation,
|
|
1385
|
+
err.message,
|
|
1386
|
+
hint,
|
|
1387
|
+
{ ...err.data, ambiguity_id: ctx.ambiguityId, request_id: ctx.requestId, claim_stored: false },
|
|
1388
|
+
err.proseSources
|
|
1389
|
+
);
|
|
1390
|
+
}
|
|
1391
|
+
function identityDataFields(observation) {
|
|
1392
|
+
return {
|
|
1393
|
+
...optionalField("header_job_id", observation.headerJobId),
|
|
1394
|
+
...optionalField("body_job_id", observation.bodyJobId),
|
|
1395
|
+
...optionalField("body_job_id_escaped", observation.unstorable?.body_job_id),
|
|
1396
|
+
...optionalField("accepted_job_id", observation.acceptedJobId),
|
|
1397
|
+
...optionalField("accepted_job_id_escaped", observation.unstorable?.accepted_job_id)
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
function warnInvalidJobIdentityHeader() {
|
|
1401
|
+
const display = "The provider sent a malformed job identity header, so it was ignored and the job ID was taken from the response body.";
|
|
1402
|
+
if (process.stderr.isTTY === true) {
|
|
1403
|
+
info(`Warning: ${display}`);
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
progress({ event: "warning", code: "job_identity_header_invalid", display });
|
|
1407
|
+
}
|
|
1408
|
+
function describeIdentityFailure(observation) {
|
|
1409
|
+
switch (observation.kind) {
|
|
1410
|
+
case "identity_mismatch":
|
|
1411
|
+
return {
|
|
1412
|
+
message: `The provider accepted the request but named job ${observation.headerJobId ?? "(unknown)"} in its response header and job ${observation.bodyJobId ?? "(unrepresentable)"} in its body.`,
|
|
1413
|
+
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."
|
|
1414
|
+
};
|
|
1415
|
+
case "body_unreadable":
|
|
1416
|
+
return {
|
|
1417
|
+
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.",
|
|
1418
|
+
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."
|
|
1419
|
+
};
|
|
1420
|
+
case "router_identity_conflict":
|
|
1421
|
+
return {
|
|
1422
|
+
message: `The router had already accepted job ${observation.acceptedJobId ?? "(unknown)"} for this request, and the provider answered with a different job.`,
|
|
1423
|
+
display: "This request was already accepted as a different job. Do not pay for it again."
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
function hasAsciiControl(value) {
|
|
1428
|
+
for (const character of value) {
|
|
1429
|
+
const code = character.charCodeAt(0);
|
|
1430
|
+
if (code <= 31 || code === 127) return true;
|
|
1431
|
+
}
|
|
1432
|
+
return false;
|
|
1433
|
+
}
|
|
1434
|
+
function optionalField(key, value) {
|
|
1435
|
+
return value === void 0 ? {} : { [key]: value };
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// src/lib/submission-evidence.ts
|
|
1439
|
+
var SUBMISSION_EVIDENCE_DIR = join(CONFIG_DIR, "submission-evidence");
|
|
1440
|
+
function submissionEvidenceKey(args) {
|
|
1441
|
+
return args.cashuRequestId ?? args.publicRequestId ?? randomUUID();
|
|
1442
|
+
}
|
|
1443
|
+
function recordSubmissionEvidence(input) {
|
|
1444
|
+
const ambiguityId = submissionEvidenceKey(input);
|
|
1445
|
+
const existing = loadSubmissionEvidence(ambiguityId);
|
|
1446
|
+
if (existing) return existing;
|
|
1447
|
+
const { observation } = input;
|
|
1448
|
+
const jobToken = isOpaqueJobToken(observation.jobToken) ? observation.jobToken : void 0;
|
|
1449
|
+
const record = {
|
|
1450
|
+
v: 1,
|
|
1451
|
+
ambiguity_id: ambiguityId,
|
|
1452
|
+
kind: observation.kind,
|
|
1453
|
+
observed_at: new Date((input.now ?? Date.now)()).toISOString(),
|
|
1454
|
+
endpoint: input.endpoint,
|
|
1455
|
+
...input.dvmId ? { dvm_id: input.dvmId } : {},
|
|
1456
|
+
...input.capability ? { capability: input.capability } : {},
|
|
1457
|
+
...input.publicRequestId ? { request_id: input.publicRequestId } : {},
|
|
1458
|
+
...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
|
|
1459
|
+
rail: input.rail,
|
|
1460
|
+
...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
|
|
1461
|
+
...jobToken ? { job_token: jobToken } : {},
|
|
1462
|
+
...boundedIds(observation),
|
|
1463
|
+
...observation.unstorable && Object.keys(observation.unstorable).length > 0 ? { unstorable_job_ids: observation.unstorable } : {},
|
|
1464
|
+
claim_stored: false
|
|
1465
|
+
};
|
|
1466
|
+
return publishOnce(record);
|
|
1467
|
+
}
|
|
1468
|
+
function recordLocalJobCollision(input) {
|
|
1469
|
+
const ambiguityId = `${input.publicRequestId}#local-job-collision`;
|
|
1470
|
+
const existing = loadSubmissionEvidence(ambiguityId);
|
|
1471
|
+
if (existing) return existing;
|
|
1472
|
+
const jobToken = isOpaqueJobToken(input.jobToken) ? input.jobToken : void 0;
|
|
1473
|
+
return publishOnce({
|
|
1474
|
+
v: 1,
|
|
1475
|
+
ambiguity_id: ambiguityId,
|
|
1476
|
+
kind: "local_job_collision",
|
|
1477
|
+
observed_at: new Date((input.now ?? Date.now)()).toISOString(),
|
|
1478
|
+
endpoint: input.endpoint,
|
|
1479
|
+
...input.dvmId ? { dvm_id: input.dvmId } : {},
|
|
1480
|
+
...input.capability ? { capability: input.capability } : {},
|
|
1481
|
+
request_id: input.publicRequestId,
|
|
1482
|
+
...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
|
|
1483
|
+
rail: input.rail,
|
|
1484
|
+
...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
|
|
1485
|
+
...jobToken ? { job_token: jobToken } : {},
|
|
1486
|
+
...boundedIds({ acceptedJobId: input.jobId }),
|
|
1487
|
+
claim_stored: false
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
function recordIdentityFailure(err, input) {
|
|
1491
|
+
if (identityFailureRecorded(err)) return { error: err, record: null };
|
|
1492
|
+
const record = recordSubmissionEvidence({ ...input, observation: err.observation });
|
|
1493
|
+
return {
|
|
1494
|
+
error: withIdentityRecovery(err, {
|
|
1495
|
+
ambiguityId: record.ambiguity_id,
|
|
1496
|
+
...input.publicRequestId ? { publicRequestId: input.publicRequestId } : {},
|
|
1497
|
+
...input.cashuRequestId ? { cashuRequestId: input.cashuRequestId } : {}
|
|
1498
|
+
}),
|
|
1499
|
+
record
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
function identityFailureRecorded(err) {
|
|
1503
|
+
return typeof err.data?.ambiguity_id === "string";
|
|
1504
|
+
}
|
|
1505
|
+
function loadSubmissionEvidence(ambiguityId) {
|
|
1506
|
+
const path = evidencePath(ambiguityId);
|
|
1507
|
+
if (!existsSync2(path)) return null;
|
|
1508
|
+
const record = readRecord(path);
|
|
1509
|
+
if (record.ambiguity_id !== ambiguityId) throw unreadable(path, "key mismatch");
|
|
1510
|
+
return record;
|
|
1511
|
+
}
|
|
1512
|
+
function listSubmissionEvidence() {
|
|
1513
|
+
if (!existsSync2(SUBMISSION_EVIDENCE_DIR)) return { records: [], unreadable: [] };
|
|
1514
|
+
const records = [];
|
|
1515
|
+
const unreadable2 = [];
|
|
1516
|
+
for (const name of readdirSync(SUBMISSION_EVIDENCE_DIR).filter((n) => n.endsWith(".json"))) {
|
|
1517
|
+
const path = join(SUBMISSION_EVIDENCE_DIR, name);
|
|
1518
|
+
try {
|
|
1519
|
+
records.push(readRecord(path));
|
|
1520
|
+
} catch (error) {
|
|
1521
|
+
const cause = error instanceof DvmError ? error.data?.cause : void 0;
|
|
1522
|
+
unreadable2.push({ path, cause: typeof cause === "string" ? cause : "unreadable" });
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
records.sort((a, b) => a.observed_at.localeCompare(b.observed_at));
|
|
1526
|
+
return { records, unreadable: unreadable2 };
|
|
1527
|
+
}
|
|
1528
|
+
function journalMarkerFor(record) {
|
|
1529
|
+
const kind = record.kind;
|
|
1530
|
+
if (kind === "local_job_collision") {
|
|
1531
|
+
throw unreadable(evidencePath(record.ambiguity_id), "not an identity failure");
|
|
1532
|
+
}
|
|
1533
|
+
return {
|
|
1534
|
+
kind,
|
|
1535
|
+
observed_at: record.observed_at,
|
|
1536
|
+
...boundedMarkerIds(record),
|
|
1537
|
+
ambiguity_id: record.ambiguity_id
|
|
1538
|
+
};
|
|
1539
|
+
}
|
|
1540
|
+
function publishOnce(record) {
|
|
1541
|
+
const ambiguityId = record.ambiguity_id;
|
|
1542
|
+
ensureConfigSubdir(SUBMISSION_EVIDENCE_DIR);
|
|
1543
|
+
const target = evidencePath(ambiguityId);
|
|
1544
|
+
const temp = `${target}.${String(process.pid)}.${randomUUID()}.tmp`;
|
|
1545
|
+
const fd = openSync3(temp, "wx", 384);
|
|
1546
|
+
try {
|
|
1547
|
+
writeFileSync3(fd, JSON.stringify(record, null, 2) + "\n");
|
|
1548
|
+
fsyncSync3(fd);
|
|
1549
|
+
} finally {
|
|
1550
|
+
closeSync3(fd);
|
|
1551
|
+
}
|
|
1552
|
+
try {
|
|
1553
|
+
linkSync(temp, target);
|
|
1554
|
+
} catch (error) {
|
|
1555
|
+
if (error.code !== "EEXIST") throw error;
|
|
1556
|
+
} finally {
|
|
1557
|
+
unlinkSync2(temp);
|
|
1558
|
+
}
|
|
1559
|
+
fsyncDirectory2(SUBMISSION_EVIDENCE_DIR);
|
|
1560
|
+
return loadSubmissionEvidence(ambiguityId) ?? record;
|
|
1561
|
+
}
|
|
1562
|
+
function boundedIds(observation) {
|
|
1563
|
+
const header = observedJobId(observation.headerJobId);
|
|
1564
|
+
const body = observedJobId(observation.bodyJobId);
|
|
1565
|
+
const accepted = observedJobId(observation.acceptedJobId);
|
|
1566
|
+
return {
|
|
1567
|
+
...header !== void 0 ? { header_job_id: header } : {},
|
|
1568
|
+
...body !== void 0 ? { body_job_id: body } : {},
|
|
1569
|
+
...accepted !== void 0 ? { accepted_job_id: accepted } : {}
|
|
1570
|
+
};
|
|
1571
|
+
}
|
|
1572
|
+
function boundedMarkerIds(record) {
|
|
1573
|
+
return boundedIds({
|
|
1574
|
+
headerJobId: record.header_job_id,
|
|
1575
|
+
bodyJobId: record.body_job_id,
|
|
1576
|
+
acceptedJobId: record.accepted_job_id
|
|
1577
|
+
});
|
|
1578
|
+
}
|
|
1579
|
+
function evidencePath(ambiguityId) {
|
|
1580
|
+
const name = createHash("sha256").update(ambiguityId).digest("hex");
|
|
1581
|
+
return join(SUBMISSION_EVIDENCE_DIR, `${name}.json`);
|
|
1582
|
+
}
|
|
1583
|
+
function readRecord(path) {
|
|
1584
|
+
let parsed;
|
|
1585
|
+
try {
|
|
1586
|
+
parsed = JSON.parse(readFileSync3(path, "utf8"));
|
|
1587
|
+
} catch (error) {
|
|
1588
|
+
throw unreadable(path, error instanceof Error ? error.message : String(error));
|
|
1589
|
+
}
|
|
1590
|
+
if (!isEvidenceRecord(parsed)) throw unreadable(path, "invalid shape");
|
|
1591
|
+
return parsed;
|
|
1592
|
+
}
|
|
1593
|
+
function unreadable(path, cause) {
|
|
1594
|
+
return new DvmError(
|
|
1595
|
+
"submission_evidence_unreadable",
|
|
1596
|
+
`A submission evidence record at ${path} is unreadable.`,
|
|
1597
|
+
"Restore it from a backup. Do not pay again for any request it may describe; automatic retries stay off until it reads.",
|
|
1598
|
+
{ cause }
|
|
1599
|
+
);
|
|
1600
|
+
}
|
|
1601
|
+
var KINDS = /* @__PURE__ */ new Set([
|
|
1602
|
+
"identity_mismatch",
|
|
1603
|
+
"body_unreadable",
|
|
1604
|
+
"router_identity_conflict",
|
|
1605
|
+
"local_job_collision"
|
|
1606
|
+
]);
|
|
1607
|
+
var RAILS = /* @__PURE__ */ new Set(["cashu", "x402", "tempo", "credit", "none"]);
|
|
1608
|
+
function isEvidenceRecord(value) {
|
|
1609
|
+
if (!isPlainObject(value)) return false;
|
|
1610
|
+
const record = value;
|
|
1611
|
+
const optionalString = (key) => record[key] === void 0 || typeof record[key] === "string";
|
|
1612
|
+
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)) && [
|
|
1613
|
+
"dvm_id",
|
|
1614
|
+
"capability",
|
|
1615
|
+
"request_id",
|
|
1616
|
+
"cashu_request_id",
|
|
1617
|
+
"job_token",
|
|
1618
|
+
"header_job_id",
|
|
1619
|
+
"body_job_id",
|
|
1620
|
+
"accepted_job_id"
|
|
1621
|
+
].every(optionalString);
|
|
1622
|
+
}
|
|
1623
|
+
function isPlainObject(value) {
|
|
1624
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1625
|
+
}
|
|
1626
|
+
function isOptionalStringRecord(value) {
|
|
1627
|
+
return value === void 0 || isPlainObject(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
1628
|
+
}
|
|
1629
|
+
function fsyncDirectory2(path) {
|
|
1630
|
+
let fd;
|
|
1631
|
+
try {
|
|
1632
|
+
fd = openSync3(path, "r");
|
|
1633
|
+
fsyncSync3(fd);
|
|
1634
|
+
} finally {
|
|
1635
|
+
if (fd !== void 0) closeSync3(fd);
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
// src/lib/job-access.ts
|
|
1640
|
+
function resolveJobAccess(jobId, opts) {
|
|
1641
|
+
const stored = loadJob(jobId);
|
|
1642
|
+
return resolveJobAccessWithRecord(jobId, opts, stored);
|
|
1643
|
+
}
|
|
1644
|
+
function resolveJobAccessWithRecord(jobId, opts, record) {
|
|
1645
|
+
const endpointOverride = opts.endpoint ?? process.env.DVM_JOB_ENDPOINT;
|
|
1646
|
+
const tokenOverride = opts.jobToken ?? process.env.DVM_JOB_TOKEN;
|
|
1647
|
+
const endpointOverridden = endpointOverride !== void 0;
|
|
1648
|
+
const tokenOverridden = tokenOverride !== void 0;
|
|
1649
|
+
const foreign = record !== null && endpointOverride !== void 0 && !sameEndpoint(resolveEndpoint(endpointOverride), record.endpoint);
|
|
1650
|
+
const stored = foreign ? null : record;
|
|
1651
|
+
const rawEndpoint = endpointOverride ?? stored?.endpoint;
|
|
1652
|
+
const jobToken = tokenOverride ?? stored?.jobToken;
|
|
1653
|
+
if (!stored && rawEndpoint === void 0 && jobToken === void 0) {
|
|
1654
|
+
throw new DvmError(
|
|
1655
|
+
"job_access_required",
|
|
1656
|
+
`Job ${jobId} is not in the local store, and no portable job access was supplied.`,
|
|
1657
|
+
"Pass --endpoint <url> and --job-token <hex>, or set DVM_JOB_ENDPOINT and DVM_JOB_TOKEN."
|
|
1658
|
+
);
|
|
1659
|
+
}
|
|
1660
|
+
if (rawEndpoint === void 0) {
|
|
1661
|
+
throw new DvmError(
|
|
1662
|
+
"job_endpoint_required",
|
|
1663
|
+
`No provider endpoint is available for job ${jobId}.`,
|
|
1664
|
+
"Pass --endpoint <url> or set DVM_JOB_ENDPOINT."
|
|
1665
|
+
);
|
|
1666
|
+
}
|
|
1667
|
+
if (foreign && jobToken === void 0) {
|
|
1668
|
+
throw foreignJobTokenRequired(jobId, record.endpoint, resolveEndpoint(endpointOverride));
|
|
1669
|
+
}
|
|
1670
|
+
if (!stored && jobToken === void 0) {
|
|
1671
|
+
throw new DvmError(
|
|
1672
|
+
"job_token_required",
|
|
1673
|
+
`No job token is available for job ${jobId}.`,
|
|
1674
|
+
"Pass --job-token <hex> or set DVM_JOB_TOKEN."
|
|
1675
|
+
);
|
|
1676
|
+
}
|
|
1677
|
+
if (tokenOverridden && !isJobToken(jobToken)) {
|
|
1678
|
+
throw new DvmError(
|
|
1679
|
+
"invalid_job_token",
|
|
1680
|
+
"The supplied job token is not a 64-character hexadecimal value.",
|
|
1681
|
+
"Copy the job_token returned when the job was submitted; the value is never printed by this command."
|
|
1682
|
+
);
|
|
1683
|
+
}
|
|
1684
|
+
return {
|
|
1685
|
+
stored,
|
|
1686
|
+
ref: { endpoint: validateProviderEndpoint(resolveEndpoint(rawEndpoint)) },
|
|
1687
|
+
...jobToken !== void 0 ? { jobToken } : {},
|
|
1688
|
+
overridden: endpointOverridden || tokenOverridden,
|
|
1689
|
+
endpointOverridden
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
function resolveStoredJobAccess(jobId, opts) {
|
|
1693
|
+
const stored = loadJob(jobId);
|
|
1694
|
+
if (!stored) {
|
|
1695
|
+
throw new DvmError(
|
|
1696
|
+
"job_payment_state_required",
|
|
1697
|
+
`Cannot pay job ${jobId} without its local payment state.`,
|
|
1698
|
+
"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."
|
|
1699
|
+
);
|
|
1700
|
+
}
|
|
1701
|
+
return { ...resolveJobAccessWithRecord(jobId, opts, stored), stored };
|
|
1702
|
+
}
|
|
1703
|
+
async function withJobTokenRedaction(jobToken, action) {
|
|
1704
|
+
try {
|
|
1705
|
+
return await action();
|
|
1706
|
+
} catch (err) {
|
|
1707
|
+
throw redactJobTokenFromError(err, jobToken);
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
function redactJobTokenFromError(err, jobToken) {
|
|
1711
|
+
if (!jobToken || !(err instanceof DvmError)) return err;
|
|
1712
|
+
const redact = (value) => value.replaceAll(jobToken, "[REDACTED]");
|
|
1713
|
+
return new DvmError(
|
|
1714
|
+
err.code,
|
|
1715
|
+
redact(err.message),
|
|
1716
|
+
err.hint === void 0 ? void 0 : redact(err.hint),
|
|
1717
|
+
err.data === void 0 ? void 0 : redactRecord(err.data, redact),
|
|
1718
|
+
err.display === void 0 ? void 0 : redact(err.display),
|
|
1719
|
+
err.proseSources
|
|
1720
|
+
);
|
|
1721
|
+
}
|
|
1722
|
+
function sameEndpoint(a, b) {
|
|
1723
|
+
const normalize = (value) => {
|
|
1724
|
+
try {
|
|
1725
|
+
const url = new URL(value);
|
|
1726
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
1727
|
+
} catch {
|
|
1728
|
+
return value.replace(/\/+$/, "");
|
|
1729
|
+
}
|
|
1730
|
+
};
|
|
1731
|
+
return normalize(a) === normalize(b);
|
|
1732
|
+
}
|
|
1733
|
+
function foreignJobTokenRequired(jobId, localEndpoint, endpoint) {
|
|
1734
|
+
const row = evidenceRowWithToken(jobId, endpoint);
|
|
1735
|
+
return new DvmError(
|
|
1736
|
+
"job_token_required",
|
|
1737
|
+
`Local job ${jobId} belongs to ${localEndpoint}. Its job token was issued there and is not sent to ${endpoint}.`,
|
|
1738
|
+
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.`,
|
|
1739
|
+
{
|
|
1740
|
+
job_id: jobId,
|
|
1741
|
+
local_endpoint: localEndpoint,
|
|
1742
|
+
endpoint,
|
|
1743
|
+
...row ? { ambiguity_id: row } : {}
|
|
1744
|
+
}
|
|
1745
|
+
);
|
|
1746
|
+
}
|
|
1747
|
+
function evidenceRowWithToken(jobId, endpoint) {
|
|
1748
|
+
let records;
|
|
1749
|
+
try {
|
|
1750
|
+
({ records } = listSubmissionEvidence());
|
|
1751
|
+
} catch {
|
|
1752
|
+
return void 0;
|
|
1753
|
+
}
|
|
1754
|
+
return records.filter(
|
|
1755
|
+
(record) => record.job_token !== void 0 && sameEndpoint(record.endpoint, endpoint) && [record.header_job_id, record.body_job_id, record.accepted_job_id].includes(jobId)
|
|
1756
|
+
).at(-1)?.ambiguity_id;
|
|
1757
|
+
}
|
|
1758
|
+
function isJobToken(value) {
|
|
1759
|
+
return value !== void 0 && /^[0-9a-fA-F]{64}$/.test(value);
|
|
1760
|
+
}
|
|
1761
|
+
function validateProviderEndpoint(value) {
|
|
1762
|
+
try {
|
|
1763
|
+
const url = new URL(value);
|
|
1764
|
+
if ((url.protocol === "http:" || url.protocol === "https:") && url.hostname) return value;
|
|
1765
|
+
} catch {
|
|
1766
|
+
}
|
|
1767
|
+
throw new DvmError(
|
|
1768
|
+
"invalid_endpoint",
|
|
1769
|
+
"The supplied job endpoint is not a valid HTTP(S) provider URL.",
|
|
1770
|
+
"Pass a full URL such as https://provider.example, or a favorite alias such as @provider."
|
|
1771
|
+
);
|
|
1772
|
+
}
|
|
1773
|
+
function redactRecord(record, redact) {
|
|
1774
|
+
return Object.fromEntries(
|
|
1775
|
+
Object.entries(record).map(([key, value]) => [key, redactValue(value, redact)])
|
|
1776
|
+
);
|
|
1777
|
+
}
|
|
1778
|
+
function redactValue(value, redact) {
|
|
1779
|
+
if (typeof value === "string") return redact(value);
|
|
1780
|
+
if (Array.isArray(value)) return value.map((entry) => redactValue(entry, redact));
|
|
1781
|
+
if (value && typeof value === "object") {
|
|
1782
|
+
return redactRecord(value, redact);
|
|
1783
|
+
}
|
|
1784
|
+
return value;
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
// src/lib/draw-funding.ts
|
|
1788
|
+
function verifiedFunding(job, receipt, fundId) {
|
|
1789
|
+
const binding = job.creditBinding;
|
|
1790
|
+
if (!binding || "unbound" in binding || !isDrawFundingReceipt(receipt)) return;
|
|
1791
|
+
const verdict = verifyDrawFundingReceiptChain({
|
|
1792
|
+
receipt,
|
|
1793
|
+
builder: job.builderAnchor,
|
|
1794
|
+
expectedJobId: job.id,
|
|
1795
|
+
expectedCreditId: binding.creditId,
|
|
1796
|
+
expectedDrawId: binding.drawId,
|
|
1797
|
+
expectedCallerPubkey: binding.callerPubkey,
|
|
1798
|
+
...fundId ? { expectedFundId: fundId } : {}
|
|
1799
|
+
});
|
|
1800
|
+
if (verdict.status === "verified" || verdict.status === "verified_unattested") return receipt;
|
|
1801
|
+
}
|
|
1802
|
+
function captureDrawFundingReceipts(jobId, receipts, opts) {
|
|
1803
|
+
if (!receipts?.length || !loadJob(jobId)) return;
|
|
1804
|
+
try {
|
|
1805
|
+
mutateCreditPayment(jobId, (job) => {
|
|
1806
|
+
if (opts?.endpoint && !sameEndpoint(job.endpoint, opts.endpoint)) return;
|
|
1807
|
+
for (const raw of receipts) {
|
|
1808
|
+
const receipt = verifiedFunding(job, raw, opts?.fundId);
|
|
1809
|
+
if (!receipt) {
|
|
1810
|
+
info("Warning: mid-job funding evidence did not verify; credit comparisons remain unchanged.");
|
|
1811
|
+
continue;
|
|
1812
|
+
}
|
|
1813
|
+
const held = (Array.isArray(job.drawFundingReceipts) ? job.drawFundingReceipts : []).filter((entry) => verifiedFunding(job, entry) !== void 0);
|
|
1814
|
+
if (!held.some((entry) => entry.fund_id === receipt.fund_id)) {
|
|
1815
|
+
held.push(receipt);
|
|
1816
|
+
job.drawFundingReceipts = held;
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
});
|
|
1820
|
+
} catch (error) {
|
|
1821
|
+
info(`Warning: could not store mid-job funding evidence: ${error instanceof Error ? error.message : String(error)}`);
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
function jobDrawFundings(jobId, endpoint, callerPubkey, credit) {
|
|
1825
|
+
const job = loadJob(jobId);
|
|
1826
|
+
const binding = job?.creditBinding;
|
|
1827
|
+
if (!job || !sameEndpoint(job.endpoint, endpoint) || !binding || "unbound" in binding || binding.callerPubkey !== callerPubkey || binding.creditId !== credit.credit_id || binding.drawId !== credit.draw_id) return [];
|
|
1828
|
+
return (Array.isArray(job.drawFundingReceipts) ? job.drawFundingReceipts : []).filter((receipt) => verifiedFunding(job, receipt) !== void 0).map((receipt) => ({ receipt, builder: job.builderAnchor }));
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1058
1831
|
// src/lib/receipt-capture.ts
|
|
1059
1832
|
function captureFundingReceipt(args) {
|
|
1060
1833
|
if (!args.receipt) return args.parseError ? "unparseable" : "absent";
|
|
@@ -1106,6 +1879,8 @@ function captureJobReceipt(jobId, receipt, parseError) {
|
|
|
1106
1879
|
return toCapture(receipt, result);
|
|
1107
1880
|
}
|
|
1108
1881
|
function captureTransportReceipt(jobId, response) {
|
|
1882
|
+
captureDrawFundingReceipts(jobId, response.drawFundingReceipts);
|
|
1883
|
+
if (response.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
|
|
1109
1884
|
return captureJobReceipt(jobId, response.receipt, response.receiptParseError);
|
|
1110
1885
|
}
|
|
1111
1886
|
function receiptJsonFields(capture) {
|
|
@@ -1143,9 +1918,12 @@ async function fetchMissingJobReceipt(jobId, transport, ref) {
|
|
|
1143
1918
|
if (held) return { receipt: held };
|
|
1144
1919
|
try {
|
|
1145
1920
|
const status = await transport.status(jobId, ref, { jobToken: job.jobToken });
|
|
1921
|
+
captureDrawFundingReceipts(jobId, status.drawFundingReceipts, { endpoint: ref.endpoint });
|
|
1146
1922
|
return {
|
|
1147
1923
|
...status.receipt ? { receipt: status.receipt } : {},
|
|
1148
|
-
...status.receiptParseError ? { receiptParseError: status.receiptParseError } : {}
|
|
1924
|
+
...status.receiptParseError ? { receiptParseError: status.receiptParseError } : {},
|
|
1925
|
+
...status.drawFundingReceipts ? { drawFundingReceipts: status.drawFundingReceipts } : {},
|
|
1926
|
+
...status.drawFundingReceiptParseError ? { drawFundingReceiptParseError: status.drawFundingReceiptParseError } : {}
|
|
1149
1927
|
};
|
|
1150
1928
|
} catch {
|
|
1151
1929
|
return {};
|
|
@@ -1222,7 +2000,7 @@ function persistParseError(jobId, receiptParseError) {
|
|
|
1222
2000
|
}
|
|
1223
2001
|
|
|
1224
2002
|
// src/lib/wallet-agent/spend.ts
|
|
1225
|
-
import { randomUUID } from "crypto";
|
|
2003
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1226
2004
|
|
|
1227
2005
|
// src/lib/wallet-agent/builder-handle.ts
|
|
1228
2006
|
var BUILDER_RESERVE_PREFIX = "builder/";
|
|
@@ -1394,7 +2172,7 @@ async function prepareAgentSpend(args) {
|
|
|
1394
2172
|
submitContext = { ...submitContext, binding_fingerprint: bindingFingerprint };
|
|
1395
2173
|
}
|
|
1396
2174
|
const now = args.now ?? (() => Date.now());
|
|
1397
|
-
const uuid = args.uuid ?? (() =>
|
|
2175
|
+
const uuid = args.uuid ?? (() => randomUUID2());
|
|
1398
2176
|
const timeoutSec = args.inFlightTimeoutSec ?? inFlightTimeoutSeconds();
|
|
1399
2177
|
const getWalletForMint = args.getWalletForMint ?? getWallet;
|
|
1400
2178
|
const refundClause = resolveRefundClause(args.cashuP2pk, args.locktimeSeconds, now(), {
|
|
@@ -1841,20 +2619,24 @@ async function abandonPendingSubmission(args) {
|
|
|
1841
2619
|
await withWalletLock(() => {
|
|
1842
2620
|
const wallet = loadAgentWallet();
|
|
1843
2621
|
if (!wallet) return;
|
|
1844
|
-
|
|
1845
|
-
const shippedKeys = new Set(submission?.output_proofs.map((p) => `${p.secret}:${p.C}`) ?? []);
|
|
1846
|
-
const next = {
|
|
1847
|
-
...wallet,
|
|
1848
|
-
proofs: wallet.proofs.map(
|
|
1849
|
-
(p) => shippedKeys.has(`${p.secret}:${p.C}`) && p.status === "in_flight" ? { ...p, status: "valid", in_flight_until_ms: void 0 } : p
|
|
1850
|
-
),
|
|
1851
|
-
pending_submissions: wallet.pending_submissions.filter(
|
|
1852
|
-
(s) => s.request_id !== args.requestId
|
|
1853
|
-
)
|
|
1854
|
-
};
|
|
1855
|
-
saveAgentWallet(next);
|
|
2622
|
+
saveAgentWallet(abandonSubmissionInWallet(wallet, args));
|
|
1856
2623
|
});
|
|
1857
2624
|
}
|
|
2625
|
+
function abandonSubmissionInWallet(wallet, args) {
|
|
2626
|
+
const submission = wallet.pending_submissions.find((s) => s.request_id === args.requestId);
|
|
2627
|
+
const shippedKeys = new Set(submission?.output_proofs.map((p) => `${p.secret}:${p.C}`) ?? []);
|
|
2628
|
+
const walletKeys = new Set(wallet.proofs.map((p) => `${p.secret}:${p.C}`));
|
|
2629
|
+
const retain = args.preserveRecovery && [...shippedKeys].some((key) => !walletKeys.has(key));
|
|
2630
|
+
return {
|
|
2631
|
+
...wallet,
|
|
2632
|
+
proofs: wallet.proofs.map(
|
|
2633
|
+
(p) => shippedKeys.has(`${p.secret}:${p.C}`) && p.status === "in_flight" ? { ...p, status: "valid", in_flight_until_ms: void 0 } : p
|
|
2634
|
+
),
|
|
2635
|
+
pending_submissions: retain ? wallet.pending_submissions.map(
|
|
2636
|
+
(s) => s.request_id === args.requestId ? { ...s, context: void 0 } : s
|
|
2637
|
+
) : wallet.pending_submissions.filter((s) => s.request_id !== args.requestId)
|
|
2638
|
+
};
|
|
2639
|
+
}
|
|
1858
2640
|
async function markPendingSubmissionUnresolved(args) {
|
|
1859
2641
|
await withWalletLock(() => {
|
|
1860
2642
|
const wallet = loadAgentWallet();
|
|
@@ -2094,7 +2876,7 @@ async function runCreditFunding(args) {
|
|
|
2094
2876
|
}
|
|
2095
2877
|
clearPending(pending);
|
|
2096
2878
|
}
|
|
2097
|
-
const fundId = args.fundId ??
|
|
2879
|
+
const fundId = args.fundId ?? randomUUID3();
|
|
2098
2880
|
const base = { creditId: args.creditId, fundId };
|
|
2099
2881
|
const eligible = args.fundingMode ? availableRails(args).filter(isStablecoinFundRail) : availableRails(args);
|
|
2100
2882
|
const x402Network = loadX402Wallet()?.network;
|
|
@@ -3300,21 +4082,21 @@ async function fundOverCashu(args, fundId) {
|
|
|
3300
4082
|
} catch (err) {
|
|
3301
4083
|
const required = boundRail(err);
|
|
3302
4084
|
if (required) {
|
|
3303
|
-
await abandonPendingSubmission({ requestId: prepared.requestId
|
|
4085
|
+
await abandonPendingSubmission({ requestId: prepared.requestId, preserveRecovery: true });
|
|
3304
4086
|
return {
|
|
3305
4087
|
...base,
|
|
3306
4088
|
status: "unavailable",
|
|
3307
4089
|
requiredRail: required,
|
|
3308
|
-
display: `This credit was opened over ${required}, so an ecash top-up can't be added to it.`
|
|
4090
|
+
display: `This credit was opened over ${required}, so an ecash top-up can't be added to it. The prepared ecash remains tracked for recovery.`
|
|
3309
4091
|
};
|
|
3310
4092
|
}
|
|
3311
4093
|
if (err instanceof DvmError && CREDIT_PERMANENT_REFUSALS.has(err.code)) {
|
|
3312
|
-
await abandonPendingSubmission({ requestId: prepared.requestId
|
|
4094
|
+
await abandonPendingSubmission({ requestId: prepared.requestId, preserveRecovery: true });
|
|
3313
4095
|
return {
|
|
3314
4096
|
...base,
|
|
3315
4097
|
status: "refused",
|
|
3316
4098
|
error: err,
|
|
3317
|
-
display: `The DVM refused the funding (${err.code})
|
|
4099
|
+
display: `The DVM refused the funding (${err.code}). The ${String(prepared.totalSats)} sats of prepared ecash remain tracked for recovery. ${err.message}`,
|
|
3318
4100
|
hint: err.hint
|
|
3319
4101
|
};
|
|
3320
4102
|
}
|
|
@@ -4862,7 +5644,7 @@ function planCreditForQuote(args) {
|
|
|
4862
5644
|
return {
|
|
4863
5645
|
mode: "topup",
|
|
4864
5646
|
creditId: stored.creditId,
|
|
4865
|
-
drawId:
|
|
5647
|
+
drawId: randomUUID4(),
|
|
4866
5648
|
...fundAmounts(fundMicro2, args.btcRate),
|
|
4867
5649
|
currency: menu.currency,
|
|
4868
5650
|
targetMicro: targetMicro2,
|
|
@@ -4889,13 +5671,13 @@ function planCreditForQuote(args) {
|
|
|
4889
5671
|
}
|
|
4890
5672
|
const openRoute = routeFor(fundMicro);
|
|
4891
5673
|
if (openRoute.route === "deferred") {
|
|
4892
|
-
return defer("open",
|
|
5674
|
+
return defer("open", randomUUID4(), fundMicro, targetMicro, fundMicro);
|
|
4893
5675
|
}
|
|
4894
5676
|
if (!canCashu) return none;
|
|
4895
5677
|
return {
|
|
4896
5678
|
mode: "open",
|
|
4897
|
-
creditId:
|
|
4898
|
-
drawId:
|
|
5679
|
+
creditId: randomUUID4(),
|
|
5680
|
+
drawId: randomUUID4(),
|
|
4899
5681
|
...fundAmounts(fundMicro, args.btcRate),
|
|
4900
5682
|
currency: menu.currency,
|
|
4901
5683
|
targetMicro,
|
|
@@ -4921,7 +5703,7 @@ function planProbeDraw(args) {
|
|
|
4921
5703
|
return {
|
|
4922
5704
|
mode: "draw",
|
|
4923
5705
|
creditId: implicit.creditId,
|
|
4924
|
-
drawId:
|
|
5706
|
+
drawId: randomUUID4(),
|
|
4925
5707
|
source: "implicit"
|
|
4926
5708
|
};
|
|
4927
5709
|
}
|
|
@@ -4953,7 +5735,7 @@ function planProbeDraw(args) {
|
|
|
4953
5735
|
});
|
|
4954
5736
|
}
|
|
4955
5737
|
}
|
|
4956
|
-
return { mode: "draw", creditId: stored.creditId, drawId:
|
|
5738
|
+
return { mode: "draw", creditId: stored.creditId, drawId: randomUUID4(), source: "prepaid" };
|
|
4957
5739
|
}
|
|
4958
5740
|
function needsTopup(balanceMicro, targetMicro) {
|
|
4959
5741
|
return targetMicro > 0 && balanceMicro < targetMicro * TOPUP_THRESHOLD_FRACTION;
|
|
@@ -5457,6 +6239,33 @@ export {
|
|
|
5457
6239
|
addPayment,
|
|
5458
6240
|
mutateCreditPayment,
|
|
5459
6241
|
bookCreditPayment,
|
|
6242
|
+
loadFavorites,
|
|
6243
|
+
saveFavorite,
|
|
6244
|
+
removeFavorite,
|
|
6245
|
+
resolveEndpoint,
|
|
6246
|
+
deriveAlias,
|
|
6247
|
+
isIdentityFailure,
|
|
6248
|
+
isParseableBodyJobId,
|
|
6249
|
+
isOpaqueJobToken,
|
|
6250
|
+
settleJobIdentity,
|
|
6251
|
+
routerConflictObservation,
|
|
6252
|
+
jobIdentityHeaderValue,
|
|
6253
|
+
identityError,
|
|
6254
|
+
withIdentityRecovery,
|
|
6255
|
+
withRequestResultRecovery,
|
|
6256
|
+
identityDataFields,
|
|
6257
|
+
warnInvalidJobIdentityHeader,
|
|
6258
|
+
SUBMISSION_EVIDENCE_DIR,
|
|
6259
|
+
recordSubmissionEvidence,
|
|
6260
|
+
recordLocalJobCollision,
|
|
6261
|
+
recordIdentityFailure,
|
|
6262
|
+
loadSubmissionEvidence,
|
|
6263
|
+
listSubmissionEvidence,
|
|
6264
|
+
journalMarkerFor,
|
|
6265
|
+
resolveJobAccess,
|
|
6266
|
+
resolveStoredJobAccess,
|
|
6267
|
+
withJobTokenRedaction,
|
|
6268
|
+
sameEndpoint,
|
|
5460
6269
|
buildTempoCredential,
|
|
5461
6270
|
loadLedger,
|
|
5462
6271
|
saveLedger,
|
|
@@ -5484,6 +6293,8 @@ export {
|
|
|
5484
6293
|
epochMsToIso,
|
|
5485
6294
|
receiptHint,
|
|
5486
6295
|
receiptFailureDetail,
|
|
6296
|
+
captureDrawFundingReceipts,
|
|
6297
|
+
jobDrawFundings,
|
|
5487
6298
|
captureFundingReceipt,
|
|
5488
6299
|
captureTransportReceipt,
|
|
5489
6300
|
receiptJsonFields,
|
|
@@ -5508,6 +6319,7 @@ export {
|
|
|
5508
6319
|
commitAgentSpend,
|
|
5509
6320
|
correctPendingFundAmount,
|
|
5510
6321
|
abandonPendingSubmission,
|
|
6322
|
+
abandonSubmissionInWallet,
|
|
5511
6323
|
markPendingSubmissionUnresolved,
|
|
5512
6324
|
withAcceptedUnresolved,
|
|
5513
6325
|
fundCredit,
|