@dvmkit/dvm-cli 0.7.0-rc.2 → 0.7.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 (24) hide show
  1. package/dist/{chunk-6QHVPJNX.js → chunk-2I5XAIQ4.js} +3 -3
  2. package/dist/{chunk-RQYMWLX4.js → chunk-3PV36227.js} +2 -2
  3. package/dist/{chunk-7UAQTHNP.js → chunk-5QO3MGMH.js} +4 -4
  4. package/dist/{chunk-PG7MEKJI.js → chunk-5VOAE2CL.js} +2 -2
  5. package/dist/{chunk-JTMBSEZO.js → chunk-6JP6ZBWW.js} +4 -4
  6. package/dist/{chunk-VLZ2K7JL.js → chunk-7674LYNL.js} +29 -7
  7. package/dist/{chunk-ZXVOMXT4.js → chunk-7OA2XUM4.js} +2 -2
  8. package/dist/{chunk-FPWP4S5S.js → chunk-C5XIOTRP.js} +36 -5
  9. package/dist/{chunk-IQV4KG63.js → chunk-EQXNDN5I.js} +2 -2
  10. package/dist/{chunk-U3YRNLZ5.js → chunk-IERBEO4C.js} +3 -3
  11. package/dist/{chunk-VIYUB3XT.js → chunk-LIITTIEN.js} +347 -85
  12. package/dist/{chunk-WN5R367B.js → chunk-ZM5QFHEY.js} +30 -2
  13. package/dist/{client-IDO4IAXG.js → client-PGOH2ION.js} +6 -6
  14. package/dist/dvm.js +1897 -649
  15. package/dist/{internal-7FXJTFBU.js → internal-VIAWW5ED.js} +13 -5
  16. package/dist/{lifecycle-LRS3IBQL.js → lifecycle-VHGTNHHE.js} +6 -6
  17. package/dist/{payout-reporter-WT7XYW42-U2QPDIYC.js → payout-reporter-3UVWPGMO-WWZWXWCG.js} +6 -4
  18. package/dist/{pocket-refill-J5OWRBXH.js → pocket-refill-YY55GISB.js} +10 -10
  19. package/dist/{revenue-reporter-7UR3W2SD-C5OMRGK3.js → revenue-reporter-E56J3NZK-NZ5H27ZI.js} +2 -2
  20. package/dist/{tempo-lifecycle-HS2NIFKT.js → tempo-lifecycle-NDBO3V3A.js} +8 -8
  21. package/dist/{tempo-wallet-BA2LKR45.js → tempo-wallet-BAU7ASWF.js} +7 -7
  22. package/dist/{wallet-RPPUCQUR.js → wallet-RB2RPWIN.js} +7 -7
  23. package/dist/{x402-ZU4GML7Z-RYEACIIT.js → x402-BN26TQZ6-4MWLNZGT.js} +2 -2
  24. package/package.json +2 -2
package/dist/dvm.js CHANGED
@@ -5,10 +5,10 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-U3YRNLZ5.js";
8
+ } from "./chunk-IERBEO4C.js";
9
9
  import {
10
10
  assertX402WalletIdle
11
- } from "./chunk-PG7MEKJI.js";
11
+ } from "./chunk-5VOAE2CL.js";
12
12
  import {
13
13
  DEFAULT_CREDIT_POSTURE,
14
14
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
@@ -47,6 +47,7 @@ import {
47
47
  loadJob,
48
48
  loadLedger,
49
49
  markJobTerminal,
50
+ markPendingSubmissionUnresolved,
50
51
  markProofsInFlight,
51
52
  meltInFlightTimeoutSeconds,
52
53
  needsTopup,
@@ -69,6 +70,7 @@ import {
69
70
  receiptTrustFields,
70
71
  recordFloatSpend,
71
72
  recordSpend,
73
+ recordSpendOnce,
72
74
  renderReceiptHuman,
73
75
  replayStoredReceipt,
74
76
  reservedForMarker,
@@ -84,8 +86,9 @@ import {
84
86
  trustLadderFor,
85
87
  trustOverrideCapMicro,
86
88
  unrecordedFloatBudgetWarning,
87
- updateJob
88
- } from "./chunk-VLZ2K7JL.js";
89
+ updateJob,
90
+ withAcceptedUnresolved
91
+ } from "./chunk-7674LYNL.js";
89
92
  import {
90
93
  assertSupportedX402Network,
91
94
  connectedX402Payer,
@@ -94,7 +97,7 @@ import {
94
97
  repinX402WalletNetwork,
95
98
  saveX402Wallet,
96
99
  x402NetworkLabel
97
- } from "./chunk-6QHVPJNX.js";
100
+ } from "./chunk-2I5XAIQ4.js";
98
101
  import {
99
102
  assertValidBudget,
100
103
  costAnchor,
@@ -106,19 +109,20 @@ import {
106
109
  json,
107
110
  monetaryJson,
108
111
  parseBudget,
112
+ progress,
109
113
  raw,
110
114
  resolveBtcUsdRate,
111
115
  setOutputTraceId,
112
116
  staleRateNotice,
113
117
  tryResolveBtcUsdRate,
114
118
  tryX402Payment
115
- } from "./chunk-RQYMWLX4.js";
119
+ } from "./chunk-3PV36227.js";
116
120
  import {
117
121
  connectedTempoAccount,
118
122
  generateTempoKey,
119
123
  tempoBalanceCheckHint,
120
124
  tempoWrongAssetHint
121
- } from "./chunk-7UAQTHNP.js";
125
+ } from "./chunk-5QO3MGMH.js";
122
126
  import {
123
127
  CREDIT_POSTURES,
124
128
  FEEDBACK_POSTURES,
@@ -135,7 +139,7 @@ import {
135
139
  retireConfigBackup,
136
140
  rollbackConfig,
137
141
  updateConfig
138
- } from "./chunk-ZXVOMXT4.js";
142
+ } from "./chunk-7OA2XUM4.js";
139
143
  import {
140
144
  A,
141
145
  AGENT_MNEMONIC_FILE,
@@ -160,6 +164,7 @@ import {
160
164
  IDENTITIES_FILE,
161
165
  IDENTITIES_VERSION,
162
166
  JOBS_FILE,
167
+ JOB_IDENTITY_HEADER,
163
168
  MESSAGES_DIR,
164
169
  PAIRINGS_DIR,
165
170
  PRIVKEY_HEX_RE,
@@ -261,6 +266,7 @@ import {
261
266
  isPublicRequestId,
262
267
  isSignedJobReceipt,
263
268
  isStablecoinFundRail,
269
+ isStorableJobId,
264
270
  ki,
265
271
  la,
266
272
  listCredits,
@@ -299,6 +305,7 @@ import {
299
305
  offersX402CreditFunding,
300
306
  parseCreditMenu,
301
307
  parseCreditTerms,
308
+ parseJobIdentityHeader,
302
309
  parseNwcUri,
303
310
  parseTraceparent,
304
311
  pendingDrainById,
@@ -376,7 +383,7 @@ import {
376
383
  x402PendingUnsettled,
377
384
  x402RequiredFromError,
378
385
  x402ReservationRelease
379
- } from "./chunk-VIYUB3XT.js";
386
+ } from "./chunk-LIITTIEN.js";
380
387
  import "./chunk-JBU7RKQ3.js";
381
388
  import "./chunk-KDNFUDOG.js";
382
389
  import "./chunk-IUTVV6N5.js";
@@ -417,11 +424,11 @@ import {
417
424
  usdToMsats,
418
425
  usdcToMsats,
419
426
  x402NetworkByCaip2
420
- } from "./chunk-JTMBSEZO.js";
421
- import "./chunk-IQV4KG63.js";
422
- import "./chunk-FPWP4S5S.js";
427
+ } from "./chunk-6JP6ZBWW.js";
428
+ import "./chunk-EQXNDN5I.js";
429
+ import "./chunk-C5XIOTRP.js";
423
430
  import "./chunk-R2DSAZBO.js";
424
- import "./chunk-WN5R367B.js";
431
+ import "./chunk-ZM5QFHEY.js";
425
432
  import {
426
433
  privateKeyToAccount
427
434
  } from "./chunk-EVQERRCP.js";
@@ -9018,6 +9025,724 @@ async function readBoundedBody(response, limit) {
9018
9025
  }
9019
9026
  var MAX_COMPATIBILITY_BODY_BYTES = 16384;
9020
9027
 
9028
+ // src/lib/favorites.ts
9029
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
9030
+ import {
9031
+ closeSync as closeSync2,
9032
+ fchmodSync,
9033
+ fsyncSync,
9034
+ openSync as openSync2,
9035
+ readFileSync as readFileSync3,
9036
+ renameSync,
9037
+ statSync as statSync2,
9038
+ unlinkSync,
9039
+ writeFileSync
9040
+ } from "fs";
9041
+ import { dirname as dirname2 } from "path";
9042
+ var DEFAULT_FILE_MODE = 384;
9043
+ function loadFavorites() {
9044
+ let raw2;
9045
+ try {
9046
+ raw2 = readFileSync3(FAVORITES_FILE, "utf8");
9047
+ } catch (error) {
9048
+ if (nodeErrorCode(error) === "ENOENT") return {};
9049
+ throw unreadableFavorites(error);
9050
+ }
9051
+ try {
9052
+ const parsed = JSON.parse(raw2);
9053
+ if (!isFavoritesMap(parsed)) throw new Error("invalid favorites shape");
9054
+ return parsed;
9055
+ } catch (error) {
9056
+ throw unreadableFavorites(error);
9057
+ }
9058
+ }
9059
+ async function saveFavorite(alias, fav) {
9060
+ return withFavoritesLock(() => {
9061
+ const favs = loadFavorites();
9062
+ const existed = Object.hasOwn(favs, alias);
9063
+ favs[alias] = fav;
9064
+ writeFavorites(favs);
9065
+ return existed;
9066
+ });
9067
+ }
9068
+ async function removeFavorite(alias) {
9069
+ return withFavoritesLock(() => {
9070
+ const favs = loadFavorites();
9071
+ if (!Object.hasOwn(favs, alias)) return false;
9072
+ const { [alias]: _, ...rest } = favs;
9073
+ writeFavorites(rest);
9074
+ return true;
9075
+ });
9076
+ }
9077
+ function resolveEndpoint(input) {
9078
+ if (!input.startsWith("@")) return input;
9079
+ const alias = input.slice(1);
9080
+ const favs = loadFavorites();
9081
+ const fav = Object.hasOwn(favs, alias) ? favs[alias] : void 0;
9082
+ if (!fav) {
9083
+ throw new DvmError(
9084
+ "unknown_favorite",
9085
+ `No favorite named "${alias}".`,
9086
+ "Run 'dvm fav list' to see saved favorites, or 'dvm fav add <endpoint>' to save one."
9087
+ );
9088
+ }
9089
+ return fav.endpoint;
9090
+ }
9091
+ function deriveAlias(endpoint) {
9092
+ try {
9093
+ const hostname2 = new URL(endpoint).hostname;
9094
+ if (hostname2.endsWith(".dvmkit.ai")) {
9095
+ const prefix = hostname2.replace(".dvmkit.ai", "");
9096
+ const dashIdx = prefix.indexOf("--");
9097
+ if (dashIdx !== -1) return prefix.slice(dashIdx + 2);
9098
+ return prefix;
9099
+ }
9100
+ return hostname2.replace(/\.[^.]+$/, "").replace(/\./g, "-");
9101
+ } catch {
9102
+ return endpoint.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
9103
+ }
9104
+ }
9105
+ async function withFavoritesLock(fn) {
9106
+ ensureConfigDir();
9107
+ let release;
9108
+ try {
9109
+ release = await import_proper_lockfile.default.lock(FAVORITES_FILE, {
9110
+ lockfilePath: `${FAVORITES_FILE}.lock`,
9111
+ realpath: false,
9112
+ stale: 3e4,
9113
+ retries: { retries: 10, factor: 1, minTimeout: 100, maxTimeout: 100 }
9114
+ });
9115
+ } catch {
9116
+ throw new DvmError(
9117
+ "favorites_locked",
9118
+ "Another dvm process is updating saved favorites.",
9119
+ "Wait a moment and retry."
9120
+ );
9121
+ }
9122
+ try {
9123
+ return await fn();
9124
+ } finally {
9125
+ await release().catch(() => void 0);
9126
+ }
9127
+ }
9128
+ function writeFavorites(favorites) {
9129
+ const mode = favoritesFileMode();
9130
+ const temporary = `${FAVORITES_FILE}.${String(process.pid)}.${randomSuffix()}.tmp`;
9131
+ const contents = JSON.stringify(favorites, null, 2) + "\n";
9132
+ let fd;
9133
+ try {
9134
+ fd = openSync2(temporary, "wx", mode);
9135
+ fchmodSync(fd, mode);
9136
+ writeFileSync(fd, contents);
9137
+ fsyncSync(fd);
9138
+ closeSync2(fd);
9139
+ fd = void 0;
9140
+ renameSync(temporary, FAVORITES_FILE);
9141
+ fsyncDirectory(dirname2(FAVORITES_FILE));
9142
+ } catch (error) {
9143
+ if (fd !== void 0) {
9144
+ try {
9145
+ closeSync2(fd);
9146
+ } catch {
9147
+ }
9148
+ }
9149
+ try {
9150
+ unlinkSync(temporary);
9151
+ } catch {
9152
+ }
9153
+ throw error;
9154
+ }
9155
+ }
9156
+ function favoritesFileMode() {
9157
+ try {
9158
+ return statSync2(FAVORITES_FILE).mode & 511;
9159
+ } catch (error) {
9160
+ if (nodeErrorCode(error) === "ENOENT") return DEFAULT_FILE_MODE;
9161
+ throw error;
9162
+ }
9163
+ }
9164
+ function fsyncDirectory(path) {
9165
+ const fd = openSync2(path, "r");
9166
+ try {
9167
+ fsyncSync(fd);
9168
+ } finally {
9169
+ closeSync2(fd);
9170
+ }
9171
+ }
9172
+ function randomSuffix() {
9173
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
9174
+ }
9175
+ function unreadableFavorites(error) {
9176
+ return new DvmError(
9177
+ "favorites_unreadable",
9178
+ "Saved favorites are corrupt or unreadable.",
9179
+ `The original file at ${FAVORITES_FILE} was left unchanged. Restore it from a backup, or move it aside before rebuilding favorites.`,
9180
+ {
9181
+ path: FAVORITES_FILE,
9182
+ ...nodeErrorCode(error) ? { error_code: nodeErrorCode(error) } : {}
9183
+ }
9184
+ );
9185
+ }
9186
+ function nodeErrorCode(error) {
9187
+ if (!(error instanceof Error) || !("code" in error)) return void 0;
9188
+ const code = error.code;
9189
+ return typeof code === "string" && /^E[A-Z0-9_]{1,63}$/.test(code) ? code : void 0;
9190
+ }
9191
+ function isFavoritesMap(value) {
9192
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
9193
+ return Object.values(value).every(isFavorite);
9194
+ }
9195
+ function isFavorite(value) {
9196
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
9197
+ const candidate = value;
9198
+ return typeof candidate.endpoint === "string" && typeof candidate.addedAt === "number" && Number.isFinite(candidate.addedAt) && (candidate.name === void 0 || typeof candidate.name === "string");
9199
+ }
9200
+
9201
+ // src/lib/submission-evidence.ts
9202
+ import { createHash, randomUUID } from "crypto";
9203
+ import {
9204
+ closeSync as closeSync3,
9205
+ existsSync as existsSync3,
9206
+ fsyncSync as fsyncSync2,
9207
+ linkSync,
9208
+ openSync as openSync3,
9209
+ readdirSync,
9210
+ readFileSync as readFileSync4,
9211
+ unlinkSync as unlinkSync2,
9212
+ writeFileSync as writeFileSync2
9213
+ } from "fs";
9214
+ import { join as join3 } from "path";
9215
+
9216
+ // src/lib/job-identity.ts
9217
+ var IDENTITY_FAILURE_CODES = {
9218
+ identity_mismatch: "provider_identity_mismatch",
9219
+ body_unreadable: "provider_body_unreadable",
9220
+ router_identity_conflict: "hosting_job_identity_conflict"
9221
+ };
9222
+ var ProviderIdentityError = class extends DvmError {
9223
+ observation;
9224
+ constructor(observation, message2, hint, data, proseSources) {
9225
+ super(IDENTITY_FAILURE_CODES[observation.kind], message2, hint, data, void 0, proseSources);
9226
+ this.observation = observation;
9227
+ }
9228
+ };
9229
+ function isIdentityFailure(err) {
9230
+ return err instanceof ProviderIdentityError;
9231
+ }
9232
+ function isParseableBodyJobId(value) {
9233
+ return typeof value === "string" && value.trim().length > 0 && value.length <= 512 && !hasAsciiControl(value);
9234
+ }
9235
+ function isOpaqueJobToken(value) {
9236
+ return typeof value === "string" && value.length > 0 && value.length <= 4096 && value.trim() === value && !hasAsciiControl(value);
9237
+ }
9238
+ function observedJobId(value) {
9239
+ return isStorableJobId(value) ? value : void 0;
9240
+ }
9241
+ function observeJobId(value) {
9242
+ if (value === void 0) return {};
9243
+ if (isStorableJobId(value)) return { stored: value };
9244
+ return { escaped: escapeObservedValue(value) };
9245
+ }
9246
+ var ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT = 1024;
9247
+ function escapeObservedValue(value) {
9248
+ const source = typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
9249
+ const truncated = source.length > ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT;
9250
+ const quoted = JSON.stringify(
9251
+ truncated ? source.slice(0, ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT) : source
9252
+ ).replace(
9253
+ /[\u007f-\u009f]/gu,
9254
+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
9255
+ );
9256
+ return truncated ? `${quoted} [truncated from ${String(source.length)} characters]` : quoted;
9257
+ }
9258
+ function settleJobIdentity(headerValue, body) {
9259
+ const header = parseJobIdentityHeader(headerValue);
9260
+ const headerJobId = header.kind === "valid" ? header.jobId : void 0;
9261
+ const rawBodyJobId = body?.job_id;
9262
+ const jobToken = isOpaqueJobToken(body?.job_token) ? body.job_token : void 0;
9263
+ const observed = (kind) => {
9264
+ const bodyJob = observeJobId(rawBodyJobId);
9265
+ return {
9266
+ kind: "unresolved",
9267
+ observation: {
9268
+ kind,
9269
+ ...headerJobId ? { headerJobId } : {},
9270
+ ...optionalField("bodyJobId", bodyJob.stored),
9271
+ ...bodyJob.escaped ? { unstorable: { body_job_id: bodyJob.escaped } } : {},
9272
+ ...jobToken ? { jobToken } : {}
9273
+ }
9274
+ };
9275
+ };
9276
+ if (!isParseableBodyJobId(rawBodyJobId)) return observed("body_unreadable");
9277
+ if (headerJobId !== void 0 && headerJobId !== rawBodyJobId) {
9278
+ return observed("identity_mismatch");
9279
+ }
9280
+ return {
9281
+ kind: "settled",
9282
+ jobId: rawBodyJobId,
9283
+ claimAllowed: header.kind !== "invalid",
9284
+ headerInvalid: header.kind === "invalid"
9285
+ };
9286
+ }
9287
+ function routerConflictObservation(status2, body) {
9288
+ if (status2 !== 409 || !body) return void 0;
9289
+ const error = body.error;
9290
+ if (!error || typeof error !== "object" || Array.isArray(error)) return void 0;
9291
+ const envelope = error;
9292
+ if (envelope.code !== IDENTITY_FAILURE_CODES.router_identity_conflict) return void 0;
9293
+ const accepted = observeJobId(envelope.accepted_job_id);
9294
+ return {
9295
+ kind: "router_identity_conflict",
9296
+ ...optionalField("acceptedJobId", accepted.stored),
9297
+ ...accepted.escaped ? { unstorable: { accepted_job_id: accepted.escaped } } : {}
9298
+ };
9299
+ }
9300
+ function jobIdentityHeaderValue(headers) {
9301
+ return headers.get(JOB_IDENTITY_HEADER);
9302
+ }
9303
+ function identityError(observation, providerProse) {
9304
+ const { message: message2, display } = describeIdentityFailure(observation);
9305
+ return new ProviderIdentityError(
9306
+ observation,
9307
+ message2,
9308
+ "Do not pay for this request again. Run 'dvm wallet submissions' to see what was recorded.",
9309
+ {
9310
+ identity_kind: observation.kind,
9311
+ ...identityDataFields(observation),
9312
+ display: providerProse?.display ?? display
9313
+ },
9314
+ providerProse?.proseSources
9315
+ );
9316
+ }
9317
+ function withIdentityRecovery(err, ctx) {
9318
+ 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.`;
9319
+ return new ProviderIdentityError(
9320
+ err.observation,
9321
+ err.message,
9322
+ hint,
9323
+ {
9324
+ ...err.data,
9325
+ ambiguity_id: ctx.ambiguityId,
9326
+ ...ctx.publicRequestId ? { request_id: ctx.publicRequestId } : {},
9327
+ ...ctx.cashuRequestId ? { cashu_request_id: ctx.cashuRequestId } : {},
9328
+ claim_stored: false
9329
+ },
9330
+ err.proseSources
9331
+ );
9332
+ }
9333
+ function withRequestResultRecovery(err, ctx) {
9334
+ const jobId = err.observation.acceptedJobId;
9335
+ const read = `dvm status ${jobId ? shellQuoteArg(jobId) : "<accepted_job_id>"} --endpoint ${shellQuoteArg(ctx.endpoint)} --job-token <job_token_bearer_secret>`;
9336
+ 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.`;
9337
+ return new ProviderIdentityError(
9338
+ err.observation,
9339
+ err.message,
9340
+ hint,
9341
+ { ...err.data, ambiguity_id: ctx.ambiguityId, request_id: ctx.requestId, claim_stored: false },
9342
+ err.proseSources
9343
+ );
9344
+ }
9345
+ function identityDataFields(observation) {
9346
+ return {
9347
+ ...optionalField("header_job_id", observation.headerJobId),
9348
+ ...optionalField("body_job_id", observation.bodyJobId),
9349
+ ...optionalField("body_job_id_escaped", observation.unstorable?.body_job_id),
9350
+ ...optionalField("accepted_job_id", observation.acceptedJobId),
9351
+ ...optionalField("accepted_job_id_escaped", observation.unstorable?.accepted_job_id)
9352
+ };
9353
+ }
9354
+ function warnInvalidJobIdentityHeader() {
9355
+ const display = "The provider sent a malformed job identity header, so it was ignored and the job ID was taken from the response body.";
9356
+ if (process.stderr.isTTY === true) {
9357
+ info(`Warning: ${display}`);
9358
+ return;
9359
+ }
9360
+ progress({ event: "warning", code: "job_identity_header_invalid", display });
9361
+ }
9362
+ function describeIdentityFailure(observation) {
9363
+ switch (observation.kind) {
9364
+ case "identity_mismatch":
9365
+ return {
9366
+ message: `The provider accepted the request but named job ${observation.headerJobId ?? "(unknown)"} in its response header and job ${observation.bodyJobId ?? "(unrepresentable)"} in its body.`,
9367
+ 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."
9368
+ };
9369
+ case "body_unreadable":
9370
+ return {
9371
+ 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.",
9372
+ 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."
9373
+ };
9374
+ case "router_identity_conflict":
9375
+ return {
9376
+ message: `The router had already accepted job ${observation.acceptedJobId ?? "(unknown)"} for this request, and the provider answered with a different job.`,
9377
+ display: "This request was already accepted as a different job. Do not pay for it again."
9378
+ };
9379
+ }
9380
+ }
9381
+ function hasAsciiControl(value) {
9382
+ for (const character of value) {
9383
+ const code = character.charCodeAt(0);
9384
+ if (code <= 31 || code === 127) return true;
9385
+ }
9386
+ return false;
9387
+ }
9388
+ function optionalField(key, value) {
9389
+ return value === void 0 ? {} : { [key]: value };
9390
+ }
9391
+
9392
+ // src/lib/submission-evidence.ts
9393
+ var SUBMISSION_EVIDENCE_DIR = join3(CONFIG_DIR, "submission-evidence");
9394
+ function submissionEvidenceKey(args) {
9395
+ return args.cashuRequestId ?? args.publicRequestId ?? randomUUID();
9396
+ }
9397
+ function recordSubmissionEvidence(input) {
9398
+ const ambiguityId = submissionEvidenceKey(input);
9399
+ const existing = loadSubmissionEvidence(ambiguityId);
9400
+ if (existing) return existing;
9401
+ const { observation } = input;
9402
+ const jobToken = isOpaqueJobToken(observation.jobToken) ? observation.jobToken : void 0;
9403
+ const record = {
9404
+ v: 1,
9405
+ ambiguity_id: ambiguityId,
9406
+ kind: observation.kind,
9407
+ observed_at: new Date((input.now ?? Date.now)()).toISOString(),
9408
+ endpoint: input.endpoint,
9409
+ ...input.dvmId ? { dvm_id: input.dvmId } : {},
9410
+ ...input.capability ? { capability: input.capability } : {},
9411
+ ...input.publicRequestId ? { request_id: input.publicRequestId } : {},
9412
+ ...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
9413
+ rail: input.rail,
9414
+ ...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
9415
+ ...jobToken ? { job_token: jobToken } : {},
9416
+ ...boundedIds(observation),
9417
+ ...observation.unstorable && Object.keys(observation.unstorable).length > 0 ? { unstorable_job_ids: observation.unstorable } : {},
9418
+ claim_stored: false
9419
+ };
9420
+ return publishOnce(record);
9421
+ }
9422
+ function recordLocalJobCollision(input) {
9423
+ const ambiguityId = `${input.publicRequestId}#local-job-collision`;
9424
+ const existing = loadSubmissionEvidence(ambiguityId);
9425
+ if (existing) return existing;
9426
+ const jobToken = isOpaqueJobToken(input.jobToken) ? input.jobToken : void 0;
9427
+ return publishOnce({
9428
+ v: 1,
9429
+ ambiguity_id: ambiguityId,
9430
+ kind: "local_job_collision",
9431
+ observed_at: new Date((input.now ?? Date.now)()).toISOString(),
9432
+ endpoint: input.endpoint,
9433
+ ...input.dvmId ? { dvm_id: input.dvmId } : {},
9434
+ ...input.capability ? { capability: input.capability } : {},
9435
+ request_id: input.publicRequestId,
9436
+ ...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
9437
+ rail: input.rail,
9438
+ ...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
9439
+ ...jobToken ? { job_token: jobToken } : {},
9440
+ ...boundedIds({ acceptedJobId: input.jobId }),
9441
+ claim_stored: false
9442
+ });
9443
+ }
9444
+ function recordIdentityFailure(err, input) {
9445
+ if (identityFailureRecorded(err)) return { error: err, record: null };
9446
+ const record = recordSubmissionEvidence({ ...input, observation: err.observation });
9447
+ return {
9448
+ error: withIdentityRecovery(err, {
9449
+ ambiguityId: record.ambiguity_id,
9450
+ ...input.publicRequestId ? { publicRequestId: input.publicRequestId } : {},
9451
+ ...input.cashuRequestId ? { cashuRequestId: input.cashuRequestId } : {}
9452
+ }),
9453
+ record
9454
+ };
9455
+ }
9456
+ function identityFailureRecorded(err) {
9457
+ return typeof err.data?.ambiguity_id === "string";
9458
+ }
9459
+ function loadSubmissionEvidence(ambiguityId) {
9460
+ const path = evidencePath(ambiguityId);
9461
+ if (!existsSync3(path)) return null;
9462
+ const record = readRecord(path);
9463
+ if (record.ambiguity_id !== ambiguityId) throw unreadable(path, "key mismatch");
9464
+ return record;
9465
+ }
9466
+ function listSubmissionEvidence() {
9467
+ if (!existsSync3(SUBMISSION_EVIDENCE_DIR)) return { records: [], unreadable: [] };
9468
+ const records = [];
9469
+ const unreadable2 = [];
9470
+ for (const name of readdirSync(SUBMISSION_EVIDENCE_DIR).filter((n) => n.endsWith(".json"))) {
9471
+ const path = join3(SUBMISSION_EVIDENCE_DIR, name);
9472
+ try {
9473
+ records.push(readRecord(path));
9474
+ } catch (error) {
9475
+ const cause = error instanceof DvmError ? error.data?.cause : void 0;
9476
+ unreadable2.push({ path, cause: typeof cause === "string" ? cause : "unreadable" });
9477
+ }
9478
+ }
9479
+ records.sort((a, b) => a.observed_at.localeCompare(b.observed_at));
9480
+ return { records, unreadable: unreadable2 };
9481
+ }
9482
+ function journalMarkerFor(record) {
9483
+ const kind = record.kind;
9484
+ if (kind === "local_job_collision") {
9485
+ throw unreadable(evidencePath(record.ambiguity_id), "not an identity failure");
9486
+ }
9487
+ return {
9488
+ kind,
9489
+ observed_at: record.observed_at,
9490
+ ...boundedMarkerIds(record),
9491
+ ambiguity_id: record.ambiguity_id
9492
+ };
9493
+ }
9494
+ function publishOnce(record) {
9495
+ const ambiguityId = record.ambiguity_id;
9496
+ ensureConfigSubdir(SUBMISSION_EVIDENCE_DIR);
9497
+ const target = evidencePath(ambiguityId);
9498
+ const temp = `${target}.${String(process.pid)}.${randomUUID()}.tmp`;
9499
+ const fd = openSync3(temp, "wx", 384);
9500
+ try {
9501
+ writeFileSync2(fd, JSON.stringify(record, null, 2) + "\n");
9502
+ fsyncSync2(fd);
9503
+ } finally {
9504
+ closeSync3(fd);
9505
+ }
9506
+ try {
9507
+ linkSync(temp, target);
9508
+ } catch (error) {
9509
+ if (error.code !== "EEXIST") throw error;
9510
+ } finally {
9511
+ unlinkSync2(temp);
9512
+ }
9513
+ fsyncDirectory2(SUBMISSION_EVIDENCE_DIR);
9514
+ return loadSubmissionEvidence(ambiguityId) ?? record;
9515
+ }
9516
+ function boundedIds(observation) {
9517
+ const header = observedJobId(observation.headerJobId);
9518
+ const body = observedJobId(observation.bodyJobId);
9519
+ const accepted = observedJobId(observation.acceptedJobId);
9520
+ return {
9521
+ ...header !== void 0 ? { header_job_id: header } : {},
9522
+ ...body !== void 0 ? { body_job_id: body } : {},
9523
+ ...accepted !== void 0 ? { accepted_job_id: accepted } : {}
9524
+ };
9525
+ }
9526
+ function boundedMarkerIds(record) {
9527
+ return boundedIds({
9528
+ headerJobId: record.header_job_id,
9529
+ bodyJobId: record.body_job_id,
9530
+ acceptedJobId: record.accepted_job_id
9531
+ });
9532
+ }
9533
+ function evidencePath(ambiguityId) {
9534
+ const name = createHash("sha256").update(ambiguityId).digest("hex");
9535
+ return join3(SUBMISSION_EVIDENCE_DIR, `${name}.json`);
9536
+ }
9537
+ function readRecord(path) {
9538
+ let parsed;
9539
+ try {
9540
+ parsed = JSON.parse(readFileSync4(path, "utf8"));
9541
+ } catch (error) {
9542
+ throw unreadable(path, error instanceof Error ? error.message : String(error));
9543
+ }
9544
+ if (!isEvidenceRecord(parsed)) throw unreadable(path, "invalid shape");
9545
+ return parsed;
9546
+ }
9547
+ function unreadable(path, cause) {
9548
+ return new DvmError(
9549
+ "submission_evidence_unreadable",
9550
+ `A submission evidence record at ${path} is unreadable.`,
9551
+ "Restore it from a backup. Do not pay again for any request it may describe; automatic retries stay off until it reads.",
9552
+ { cause }
9553
+ );
9554
+ }
9555
+ var KINDS = /* @__PURE__ */ new Set([
9556
+ "identity_mismatch",
9557
+ "body_unreadable",
9558
+ "router_identity_conflict",
9559
+ "local_job_collision"
9560
+ ]);
9561
+ var RAILS = /* @__PURE__ */ new Set(["cashu", "x402", "tempo", "credit", "none"]);
9562
+ function isEvidenceRecord(value) {
9563
+ if (!isPlainObject(value)) return false;
9564
+ const record = value;
9565
+ const optionalString = (key) => record[key] === void 0 || typeof record[key] === "string";
9566
+ 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)) && [
9567
+ "dvm_id",
9568
+ "capability",
9569
+ "request_id",
9570
+ "cashu_request_id",
9571
+ "job_token",
9572
+ "header_job_id",
9573
+ "body_job_id",
9574
+ "accepted_job_id"
9575
+ ].every(optionalString);
9576
+ }
9577
+ function isPlainObject(value) {
9578
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9579
+ }
9580
+ function isOptionalStringRecord(value) {
9581
+ return value === void 0 || isPlainObject(value) && Object.values(value).every((entry) => typeof entry === "string");
9582
+ }
9583
+ function fsyncDirectory2(path) {
9584
+ let fd;
9585
+ try {
9586
+ fd = openSync3(path, "r");
9587
+ fsyncSync2(fd);
9588
+ } finally {
9589
+ if (fd !== void 0) closeSync3(fd);
9590
+ }
9591
+ }
9592
+
9593
+ // src/lib/job-access.ts
9594
+ function resolveJobAccess(jobId, opts) {
9595
+ const stored = loadJob(jobId);
9596
+ return resolveJobAccessWithRecord(jobId, opts, stored);
9597
+ }
9598
+ function resolveJobAccessWithRecord(jobId, opts, record) {
9599
+ const endpointOverride = opts.endpoint ?? process.env.DVM_JOB_ENDPOINT;
9600
+ const tokenOverride = opts.jobToken ?? process.env.DVM_JOB_TOKEN;
9601
+ const endpointOverridden = endpointOverride !== void 0;
9602
+ const tokenOverridden = tokenOverride !== void 0;
9603
+ const foreign = record !== null && endpointOverride !== void 0 && !sameEndpoint(resolveEndpoint(endpointOverride), record.endpoint);
9604
+ const stored = foreign ? null : record;
9605
+ const rawEndpoint = endpointOverride ?? stored?.endpoint;
9606
+ const jobToken = tokenOverride ?? stored?.jobToken;
9607
+ if (!stored && rawEndpoint === void 0 && jobToken === void 0) {
9608
+ throw new DvmError(
9609
+ "job_access_required",
9610
+ `Job ${jobId} is not in the local store, and no portable job access was supplied.`,
9611
+ "Pass --endpoint <url> and --job-token <hex>, or set DVM_JOB_ENDPOINT and DVM_JOB_TOKEN."
9612
+ );
9613
+ }
9614
+ if (rawEndpoint === void 0) {
9615
+ throw new DvmError(
9616
+ "job_endpoint_required",
9617
+ `No provider endpoint is available for job ${jobId}.`,
9618
+ "Pass --endpoint <url> or set DVM_JOB_ENDPOINT."
9619
+ );
9620
+ }
9621
+ if (foreign && jobToken === void 0) {
9622
+ throw foreignJobTokenRequired(jobId, record.endpoint, resolveEndpoint(endpointOverride));
9623
+ }
9624
+ if (!stored && jobToken === void 0) {
9625
+ throw new DvmError(
9626
+ "job_token_required",
9627
+ `No job token is available for job ${jobId}.`,
9628
+ "Pass --job-token <hex> or set DVM_JOB_TOKEN."
9629
+ );
9630
+ }
9631
+ if (tokenOverridden && !isJobToken(jobToken)) {
9632
+ throw new DvmError(
9633
+ "invalid_job_token",
9634
+ "The supplied job token is not a 64-character hexadecimal value.",
9635
+ "Copy the job_token returned when the job was submitted; the value is never printed by this command."
9636
+ );
9637
+ }
9638
+ return {
9639
+ stored,
9640
+ ref: { endpoint: validateProviderEndpoint(resolveEndpoint(rawEndpoint)) },
9641
+ ...jobToken !== void 0 ? { jobToken } : {},
9642
+ overridden: endpointOverridden || tokenOverridden,
9643
+ endpointOverridden
9644
+ };
9645
+ }
9646
+ function resolveStoredJobAccess(jobId, opts) {
9647
+ const stored = loadJob(jobId);
9648
+ if (!stored) {
9649
+ throw new DvmError(
9650
+ "job_payment_state_required",
9651
+ `Cannot pay job ${jobId} without its local payment state.`,
9652
+ "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."
9653
+ );
9654
+ }
9655
+ return { ...resolveJobAccessWithRecord(jobId, opts, stored), stored };
9656
+ }
9657
+ async function withJobTokenRedaction(jobToken, action) {
9658
+ try {
9659
+ return await action();
9660
+ } catch (err) {
9661
+ throw redactJobTokenFromError(err, jobToken);
9662
+ }
9663
+ }
9664
+ function redactJobTokenFromError(err, jobToken) {
9665
+ if (!jobToken || !(err instanceof DvmError)) return err;
9666
+ const redact = (value) => value.replaceAll(jobToken, "[REDACTED]");
9667
+ return new DvmError(
9668
+ err.code,
9669
+ redact(err.message),
9670
+ err.hint === void 0 ? void 0 : redact(err.hint),
9671
+ err.data === void 0 ? void 0 : redactRecord(err.data, redact),
9672
+ err.display === void 0 ? void 0 : redact(err.display),
9673
+ err.proseSources
9674
+ );
9675
+ }
9676
+ function sameEndpoint(a, b) {
9677
+ const normalize = (value) => {
9678
+ try {
9679
+ const url = new URL(value);
9680
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
9681
+ } catch {
9682
+ return value.replace(/\/+$/, "");
9683
+ }
9684
+ };
9685
+ return normalize(a) === normalize(b);
9686
+ }
9687
+ function foreignJobTokenRequired(jobId, localEndpoint, endpoint) {
9688
+ const row = evidenceRowWithToken(jobId, endpoint);
9689
+ return new DvmError(
9690
+ "job_token_required",
9691
+ `Local job ${jobId} belongs to ${localEndpoint}. Its job token was issued there and is not sent to ${endpoint}.`,
9692
+ 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.`,
9693
+ {
9694
+ job_id: jobId,
9695
+ local_endpoint: localEndpoint,
9696
+ endpoint,
9697
+ ...row ? { ambiguity_id: row } : {}
9698
+ }
9699
+ );
9700
+ }
9701
+ function evidenceRowWithToken(jobId, endpoint) {
9702
+ let records;
9703
+ try {
9704
+ ({ records } = listSubmissionEvidence());
9705
+ } catch {
9706
+ return void 0;
9707
+ }
9708
+ return records.filter(
9709
+ (record) => record.job_token !== void 0 && sameEndpoint(record.endpoint, endpoint) && [record.header_job_id, record.body_job_id, record.accepted_job_id].includes(jobId)
9710
+ ).at(-1)?.ambiguity_id;
9711
+ }
9712
+ function isJobToken(value) {
9713
+ return value !== void 0 && /^[0-9a-fA-F]{64}$/.test(value);
9714
+ }
9715
+ function validateProviderEndpoint(value) {
9716
+ try {
9717
+ const url = new URL(value);
9718
+ if ((url.protocol === "http:" || url.protocol === "https:") && url.hostname) return value;
9719
+ } catch {
9720
+ }
9721
+ throw new DvmError(
9722
+ "invalid_endpoint",
9723
+ "The supplied job endpoint is not a valid HTTP(S) provider URL.",
9724
+ "Pass a full URL such as https://provider.example, or a favorite alias such as @provider."
9725
+ );
9726
+ }
9727
+ function redactRecord(record, redact) {
9728
+ return Object.fromEntries(
9729
+ Object.entries(record).map(([key, value]) => [key, redactValue(value, redact)])
9730
+ );
9731
+ }
9732
+ function redactValue(value, redact) {
9733
+ if (typeof value === "string") return redact(value);
9734
+ if (Array.isArray(value)) return value.map((entry) => redactValue(entry, redact));
9735
+ if (value && typeof value === "object") {
9736
+ return redactRecord(value, redact);
9737
+ }
9738
+ return value;
9739
+ }
9740
+
9741
+ // src/lib/request-recovery-path.ts
9742
+ function requestRecoveryPath(route, requestId) {
9743
+ return `v1/${route}/${encodeURIComponent(requestId)}`;
9744
+ }
9745
+
9021
9746
  // src/lib/wallet-agent/recovery-submissions.ts
9022
9747
  var RESUME_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
9023
9748
  var RESUME_MAX_ATTEMPTS = 5;
@@ -9030,12 +9755,18 @@ async function sweepPendingSubmissions(opts = {}) {
9030
9755
  httpPost: opts.httpPost ?? createDefaultHttpPost(opts.fetchImpl ?? dvmFetch),
9031
9756
  getWalletForMint: opts.getWalletForMint ?? getWallet,
9032
9757
  readMnemonic: opts.readMnemonic ?? readAgentMnemonic,
9033
- lockPubkey: wallet.lock_pubkey
9758
+ lockPubkey: wallet.lock_pubkey,
9759
+ persistUnresolved: async (entry, observation) => {
9760
+ const marker = journalMarkerFor(recordSubmissionEvidence(evidenceInput(entry, observation)));
9761
+ await markPendingSubmissionUnresolved({ requestId: entry.request_id, marker });
9762
+ return marker;
9763
+ }
9034
9764
  };
9035
9765
  const now = opts.now ?? (() => Date.now());
9766
+ const { entries, unreadable: unreadable2 } = await reconcileEvidenceMarkers(wallet);
9036
9767
  const outcomes = [];
9037
- for (const entry of wallet.pending_submissions) {
9038
- outcomes.push(await resolveEntry(entry, deps, now()));
9768
+ for (const entry of entries) {
9769
+ outcomes.push(await resolveEntry(entry, deps, now(), unreadable2.has(entry.request_id)));
9039
9770
  }
9040
9771
  if (outcomes.some(mutatesWallet)) {
9041
9772
  await withWalletLock(() => {
@@ -9079,6 +9810,19 @@ async function recoverPendingSubmission(opts) {
9079
9810
  "The saved submission does not match the approved strict request binding.",
9080
9811
  "Do not recover by endpoint, mint, or amount. Rebuild evidence for the exact saved request."
9081
9812
  );
9813
+ const evidence = entry.accepted_unresolved ? null : loadSubmissionEvidence(entry.request_id);
9814
+ if (evidence)
9815
+ saveAgentWallet(withAcceptedUnresolved(wallet, entry.request_id, journalMarkerFor(evidence)));
9816
+ if (entry.accepted_unresolved || evidence)
9817
+ throw new DvmError(
9818
+ "submission_accepted_unresolved",
9819
+ "The provider already accepted this submission without stating a settled job identity.",
9820
+ "Do not pay for or resubmit this request. Run 'dvm wallet submissions' to see the recorded evidence and how to read the job.",
9821
+ {
9822
+ request_id: entry.request_id,
9823
+ ambiguity_id: entry.accepted_unresolved?.ambiguity_id ?? entry.request_id
9824
+ }
9825
+ );
9082
9826
  if (entry.output_proofs.length === 0 || entry.swapping)
9083
9827
  throw new DvmError(
9084
9828
  "submission_not_ready",
@@ -9105,8 +9849,25 @@ async function recoverPendingSubmission(opts) {
9105
9849
  });
9106
9850
  const outcome = await shipEntry(
9107
9851
  attempted,
9108
- opts.httpPost ?? createDefaultHttpPost(opts.fetchImpl ?? dvmFetch)
9852
+ opts.httpPost ?? createDefaultHttpPost(opts.fetchImpl ?? dvmFetch),
9853
+ // This function already holds the wallet lock, which is not reentrant.
9854
+ async (target, observation) => {
9855
+ const marker = journalMarkerFor(
9856
+ recordSubmissionEvidence(evidenceInput(target, observation))
9857
+ );
9858
+ const current = loadAgentWallet() ?? wallet;
9859
+ saveAgentWallet(withAcceptedUnresolved(current, target.request_id, marker));
9860
+ return marker;
9861
+ }
9109
9862
  );
9863
+ if (outcome.kind === "accepted_unresolved") {
9864
+ const observation = outcome.observation ?? { kind: outcome.marker.kind };
9865
+ throw withIdentityRecovery(identityError(observation), {
9866
+ ambiguityId: outcome.marker.ambiguity_id,
9867
+ cashuRequestId: entry.request_id,
9868
+ ...publicRequestIdField(entry)
9869
+ });
9870
+ }
9110
9871
  if (outcome.kind === "shipped" || outcome.kind === "already_accepted") {
9111
9872
  const current = loadAgentWallet() ?? wallet;
9112
9873
  saveAgentWallet(applyOutcome(current, outcome, now));
@@ -9120,6 +9881,25 @@ async function recoverPendingSubmission(opts) {
9120
9881
  return { requestId: opts.requestId, outcome: "pending", jobId: null, attemptCount: 1 };
9121
9882
  });
9122
9883
  }
9884
+ async function bookRecoveredSubmissions(args) {
9885
+ const matches = (wallet) => (wallet?.pending_submissions ?? []).filter(
9886
+ (entry) => entry.output_proofs.length > 0 && publicRequestIdOf(entry) === args.publicRequestId && sameEndpoint(entry.endpoint, args.endpoint)
9887
+ );
9888
+ if (matches(loadAgentWallet()).length === 0) return [];
9889
+ const now = args.now ?? (() => Date.now());
9890
+ return withWalletLock(() => {
9891
+ const fresh = loadAgentWallet();
9892
+ const booked = matches(fresh);
9893
+ if (!fresh || booked.length === 0) return [];
9894
+ saveAgentWallet(
9895
+ booked.reduce(
9896
+ (acc, entry) => applyOutcome(acc, { kind: "shipped", entry, jobId: args.jobId }, now),
9897
+ fresh
9898
+ )
9899
+ );
9900
+ return booked.map((entry) => entry.request_id);
9901
+ });
9902
+ }
9123
9903
  function isResumable(entry) {
9124
9904
  return resumeBody(entry) !== null;
9125
9905
  }
@@ -9128,7 +9908,7 @@ function reclaimAtMs(entry) {
9128
9908
  if (!entry.canonical_id || typeof entry.t_expire !== "number") return null;
9129
9909
  return entry.t_expire;
9130
9910
  }
9131
- async function resolveEntry(entry, deps, nowMs) {
9911
+ async function resolveEntry(entry, deps, nowMs, evidenceUnreadable) {
9132
9912
  if (entry.output_proofs.length === 0) {
9133
9913
  const inFlightWindowMs = inFlightTimeoutSeconds() * 1e3;
9134
9914
  if (entry.swapping) {
@@ -9140,6 +9920,15 @@ async function resolveEntry(entry, deps, nowMs) {
9140
9920
  if (reclaimAt !== null && nowMs >= reclaimAt) {
9141
9921
  return reclaimEntry(entry, deps);
9142
9922
  }
9923
+ if (entry.accepted_unresolved) {
9924
+ return {
9925
+ kind: "accepted_unresolved",
9926
+ entry,
9927
+ marker: entry.accepted_unresolved,
9928
+ evidence: evidenceState(entry.accepted_unresolved.ambiguity_id)
9929
+ };
9930
+ }
9931
+ if (evidenceUnreadable) return { kind: "evidence_unreadable", entry };
9143
9932
  if (!isResumable(entry)) {
9144
9933
  return { kind: "unresumable", entry };
9145
9934
  }
@@ -9149,7 +9938,7 @@ async function resolveEntry(entry, deps, nowMs) {
9149
9938
  if ((entry.attempts ?? 0) >= RESUME_MAX_ATTEMPTS) {
9150
9939
  return { kind: "stale", entry, reason: `no response after ${RESUME_MAX_ATTEMPTS} attempts` };
9151
9940
  }
9152
- return shipEntry(entry, deps.httpPost);
9941
+ return shipEntry(entry, deps.httpPost, deps.persistUnresolved);
9153
9942
  }
9154
9943
  async function recoverPreparedSwap(entry, deps) {
9155
9944
  const swapping = entry.swapping;
@@ -9372,7 +10161,14 @@ function isNonNegativeSafeInteger(value) {
9372
10161
  }
9373
10162
  var UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
9374
10163
  var SHA256_RE = /^[a-f0-9]{64}$/;
9375
- async function shipEntry(entry, httpPost) {
10164
+ async function shipEntry(entry, httpPost, persistUnresolved) {
10165
+ const unresolved = async (observation) => ({
10166
+ kind: "accepted_unresolved",
10167
+ entry,
10168
+ marker: await persistUnresolved(entry, observation),
10169
+ evidence: "recorded",
10170
+ observation
10171
+ });
9376
10172
  const token = { mint: entry.mint, proofs: toCashuProofs(entry.output_proofs) };
9377
10173
  const cashuToken = entry.cashu_token ?? ki(token);
9378
10174
  const headers = {
@@ -9381,6 +10177,11 @@ async function shipEntry(entry, httpPost) {
9381
10177
  "X-Cashu-Request-Id": entry.request_id
9382
10178
  };
9383
10179
  const route = entry.context?.route === "credit" ? "/v1/credit" : "/v1/job";
10180
+ const { publicRequestId } = publicRequestIdField(entry);
10181
+ if (publicRequestId && route === "/v1/job") {
10182
+ const readBack = await readBackByRequestId(entry, publicRequestId, httpPost, unresolved);
10183
+ if (readBack) return readBack;
10184
+ }
9384
10185
  let active2 = entry;
9385
10186
  let correctedOnce = false;
9386
10187
  for (; ; ) {
@@ -9405,12 +10206,28 @@ async function shipEntry(entry, httpPost) {
9405
10206
  applyResumedCreditFund(entry, response.body);
9406
10207
  return { kind: "shipped", entry };
9407
10208
  }
9408
- const jobId = typeof response.body?.job_id === "string" ? response.body.job_id : void 0;
9409
- if (jobId && entry.context) {
9410
- saveJob(jobRecordFromEntry(entry, jobId, response.body, response.feedbackClaim));
10209
+ const identity = settleJobIdentity(response.jobIdentity ?? null, response.body);
10210
+ if (identity.kind === "unresolved") return unresolved(identity.observation);
10211
+ if (entry.context) {
10212
+ saveJob(
10213
+ jobRecordFromEntry(
10214
+ entry,
10215
+ identity.jobId,
10216
+ response.body,
10217
+ identity.claimAllowed ? response.feedbackClaim : void 0
10218
+ )
10219
+ );
9411
10220
  }
9412
10221
  await reconcileResumedJobCredit(active2, response.body, httpPost);
9413
- return { kind: "shipped", entry, jobId };
10222
+ return { kind: "shipped", entry, jobId: identity.jobId };
10223
+ }
10224
+ const conflict = routerConflictObservation(response.status, response.body);
10225
+ if (conflict) return unresolved(conflict);
10226
+ if (response.status === 409) {
10227
+ if (!errorCodeOf(response.body)) return unresolved({ kind: "body_unreadable" });
10228
+ if (publicRequestId) {
10229
+ return { kind: "still_pending", entry, reason: errorCodeOf(response.body) ?? "http 409" };
10230
+ }
9414
10231
  }
9415
10232
  if (response.status === 409 || response.body?.error === "replay_rejected") {
9416
10233
  await reconcileResumedJobCredit(active2, response.body, httpPost);
@@ -9443,6 +10260,94 @@ async function shipEntry(entry, httpPost) {
9443
10260
  };
9444
10261
  }
9445
10262
  }
10263
+ async function readBackByRequestId(entry, requestId, httpPost, unresolved) {
10264
+ const body = requestResultBody(entry, requestId);
10265
+ if (!body) return null;
10266
+ let response;
10267
+ try {
10268
+ response = await httpPost({
10269
+ url: `${entry.endpoint}/${requestRecoveryPath("request-result", requestId)}`,
10270
+ headers: { "Content-Type": "application/json" },
10271
+ body: JSON.stringify(body)
10272
+ });
10273
+ } catch (err) {
10274
+ return { kind: "still_pending", entry, reason: `network error: ${errorText(err)}` };
10275
+ }
10276
+ if (response.status === 404 && errorCodeOf(response.body) === "request_not_found") return null;
10277
+ if (response.status >= 200 && response.status < 300) {
10278
+ if (response.body && response.body.request_id !== requestId) {
10279
+ return unresolved({ kind: "body_unreadable" });
10280
+ }
10281
+ const identity = settleJobIdentity(response.jobIdentity ?? null, response.body);
10282
+ if (identity.kind === "unresolved") return unresolved(identity.observation);
10283
+ const saved = saveRecoveredJob(entry, identity.jobId, response.body, requestId);
10284
+ if (saved !== "saved") {
10285
+ const kept = saved === "foreign_endpoint" ? recordLocalJobCollision({
10286
+ ...entryEvidenceContext(entry),
10287
+ publicRequestId: requestId,
10288
+ jobId: identity.jobId,
10289
+ jobToken: response.body?.job_token
10290
+ }) : null;
10291
+ return {
10292
+ kind: "still_pending",
10293
+ entry,
10294
+ reason: `request_result_conflict: job ${identity.jobId} is already a different local job${kept ? `; the recovered job is kept as evidence ${kept.ambiguity_id}` : ""}`
10295
+ };
10296
+ }
10297
+ await reconcileResumedJobCredit(entry, response.body, httpPost);
10298
+ return { kind: "shipped", entry, jobId: identity.jobId };
10299
+ }
10300
+ const conflict = routerConflictObservation(response.status, response.body);
10301
+ if (conflict) return unresolved(conflict);
10302
+ return {
10303
+ kind: "still_pending",
10304
+ entry,
10305
+ reason: `request-result: ${errorCodeOf(response.body) ?? `http ${response.status}`}`
10306
+ };
10307
+ }
10308
+ function requestResultBody(entry, requestId) {
10309
+ const ctx = entry.context;
10310
+ if (!ctx || ctx.route === "credit" || !ctx.signing_pubkey || !ctx.auth_domain) return null;
10311
+ const signer = findSigningIdentityByPubkey(ctx.signing_pubkey);
10312
+ if (!signer) return null;
10313
+ const unsigned = ctx.submit_body.data ?? {};
10314
+ const path = canonicalRequestPath(
10315
+ new URL(
10316
+ requestRecoveryPath("request-result", requestId),
10317
+ `${entry.endpoint.replace(/\/$/, "")}/`
10318
+ ).href
10319
+ );
10320
+ return {
10321
+ ...ctx.submit_body,
10322
+ data: signDvmRequestData(signer.privkey, unsigned, { ...ctx.auth_domain, path })
10323
+ };
10324
+ }
10325
+ function saveRecoveredJob(entry, jobId, body, requestId) {
10326
+ const token = body?.job_token;
10327
+ const jobToken = isOpaqueJobToken(token) ? token : void 0;
10328
+ const existing = loadJob(jobId);
10329
+ if (existing) {
10330
+ if (!sameEndpoint(existing.endpoint, entry.endpoint)) return "foreign_endpoint";
10331
+ if (existing.requestId !== void 0 && existing.requestId !== requestId) return "other_request";
10332
+ updateJob(jobId, {
10333
+ requestId,
10334
+ ...jobToken && !existing.jobToken ? { jobToken } : {}
10335
+ });
10336
+ return "saved";
10337
+ }
10338
+ const { jobToken: _unchecked, ...record } = jobRecordFromEntry(entry, jobId, body, void 0);
10339
+ saveJob({ ...record, requestId, ...jobToken ? { jobToken } : {} });
10340
+ return "saved";
10341
+ }
10342
+ function errorCodeOf(body) {
10343
+ const error = body?.error;
10344
+ if (typeof error === "string") return error;
10345
+ if (error && typeof error === "object" && !Array.isArray(error)) {
10346
+ const code = error.code;
10347
+ if (typeof code === "string") return code;
10348
+ }
10349
+ return null;
10350
+ }
9446
10351
  async function correctFundAmount(entry, body) {
9447
10352
  const ctx = entry.context;
9448
10353
  if (!ctx || ctx.route === "credit") return { kind: "permanent" };
@@ -9458,6 +10363,7 @@ async function correctFundAmount(entry, body) {
9458
10363
  const expected = valuation.micro;
9459
10364
  if (expected === fund.amount_micro) return { kind: "hold" };
9460
10365
  await correctPendingFundAmount({ requestId: entry.request_id, amountMicro: expected });
10366
+ const { request_id: _requestId, ...rest } = data;
9461
10367
  return {
9462
10368
  kind: "corrected",
9463
10369
  entry: {
@@ -9466,7 +10372,7 @@ async function correctFundAmount(entry, body) {
9466
10372
  ...ctx,
9467
10373
  submit_body: {
9468
10374
  ...ctx.submit_body,
9469
- data: { ...data, fund: { ...fund, amount_micro: expected } }
10375
+ data: { ...rest, fund: { ...fund, amount_micro: expected } }
9470
10376
  }
9471
10377
  }
9472
10378
  }
@@ -9602,9 +10508,11 @@ function isCreditWire(value) {
9602
10508
  }
9603
10509
  function jobRecordFromEntry(entry, jobId, body, feedbackClaim) {
9604
10510
  const ctx = entry.context;
10511
+ const { publicRequestId } = publicRequestIdField(entry);
9605
10512
  return {
9606
10513
  id: jobId,
9607
10514
  endpoint: entry.endpoint,
10515
+ ...publicRequestId ? { requestId: publicRequestId } : {},
9608
10516
  ...ctx?.dvm_id ? { dvmId: ctx.dvm_id } : {},
9609
10517
  ...feedbackClaim ? { feedbackClaim } : {},
9610
10518
  ...ctx?.capability ? { capability: ctx.capability } : {},
@@ -9754,16 +10662,76 @@ function createDefaultHttpPost(fetchImpl) {
9754
10662
  "Retry once the DVM is reachable again."
9755
10663
  );
9756
10664
  }
10665
+ const jobIdentity = jobIdentityHeaderValue(res.headers);
9757
10666
  let body;
9758
10667
  try {
9759
- body = await res.json();
10668
+ const parsed = await res.json();
10669
+ body = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
9760
10670
  } catch {
9761
10671
  body = null;
9762
10672
  }
9763
10673
  const feedbackClaim = res.headers.get(ROUTER_FEEDBACK_CLAIM_HEADER) ?? void 0;
9764
- return { status: res.status, body, ...feedbackClaim ? { feedbackClaim } : {} };
10674
+ return {
10675
+ status: res.status,
10676
+ body,
10677
+ jobIdentity,
10678
+ ...feedbackClaim ? { feedbackClaim } : {}
10679
+ };
10680
+ };
10681
+ }
10682
+ async function reconcileEvidenceMarkers(wallet) {
10683
+ const unreadable2 = /* @__PURE__ */ new Set();
10684
+ const orphaned = wallet.pending_submissions.flatMap((entry) => {
10685
+ if (entry.accepted_unresolved) return [];
10686
+ try {
10687
+ const record = loadSubmissionEvidence(entry.request_id);
10688
+ return record ? [{ requestId: entry.request_id, marker: journalMarkerFor(record) }] : [];
10689
+ } catch {
10690
+ unreadable2.add(entry.request_id);
10691
+ return [];
10692
+ }
10693
+ });
10694
+ if (orphaned.length === 0) return { entries: wallet.pending_submissions, unreadable: unreadable2 };
10695
+ return withWalletLock(() => {
10696
+ const fresh = loadAgentWallet() ?? wallet;
10697
+ const next = orphaned.reduce(
10698
+ (acc, { requestId, marker }) => withAcceptedUnresolved(acc, requestId, marker),
10699
+ fresh
10700
+ );
10701
+ saveAgentWallet(next);
10702
+ return { entries: next.pending_submissions, unreadable: unreadable2 };
10703
+ });
10704
+ }
10705
+ function evidenceState(ambiguityId) {
10706
+ try {
10707
+ return loadSubmissionEvidence(ambiguityId) ? "recorded" : "missing";
10708
+ } catch {
10709
+ return "unreadable";
10710
+ }
10711
+ }
10712
+ function evidenceInput(entry, observation) {
10713
+ return { ...entryEvidenceContext(entry), observation, ...publicRequestIdField(entry) };
10714
+ }
10715
+ function entryEvidenceContext(entry) {
10716
+ const ctx = entry.context;
10717
+ return {
10718
+ endpoint: entry.endpoint,
10719
+ ...ctx?.dvm_id ? { dvmId: ctx.dvm_id } : {},
10720
+ ...ctx?.capability ? { capability: ctx.capability } : {},
10721
+ cashuRequestId: entry.request_id,
10722
+ rail: "cashu",
10723
+ railCorrelation: { mint: entry.mint, amount_sats: entry.amount_sats }
9765
10724
  };
9766
10725
  }
10726
+ function publicRequestIdOf(entry) {
10727
+ const data = entry.context?.submit_body.data;
10728
+ const requestId = data && typeof data === "object" && !Array.isArray(data) ? data.request_id : void 0;
10729
+ return isPublicRequestId(requestId) ? requestId : void 0;
10730
+ }
10731
+ function publicRequestIdField(entry) {
10732
+ const publicRequestId = publicRequestIdOf(entry);
10733
+ return publicRequestId ? { publicRequestId } : {};
10734
+ }
9767
10735
 
9768
10736
  // src/lib/agent-wallet-retry.ts
9769
10737
  var TRANSIENT_PAYMENT_BACKOFF_MS = [250, 500, 1e3, 2e3, 4e3];
@@ -10005,8 +10973,8 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
10005
10973
  }
10006
10974
  }
10007
10975
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
10008
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RPPUCQUR.js");
10009
- const { tryX402Payment: tryX402Payment2 } = await import("./client-IDO4IAXG.js");
10976
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RB2RPWIN.js");
10977
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-PGOH2ION.js");
10010
10978
  const wallet = loadX402Wallet2();
10011
10979
  if (wallet) {
10012
10980
  let proof;
@@ -10547,179 +11515,6 @@ async function runDiscoveryLifecycle(options) {
10547
11515
  return { ...summary ? { summary } : {}, messages: messages2, nextAction: result.nextAction };
10548
11516
  }
10549
11517
 
10550
- // src/lib/favorites.ts
10551
- var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
10552
- import {
10553
- closeSync as closeSync2,
10554
- fchmodSync,
10555
- fsyncSync,
10556
- openSync as openSync2,
10557
- readFileSync as readFileSync3,
10558
- renameSync,
10559
- statSync as statSync2,
10560
- unlinkSync,
10561
- writeFileSync
10562
- } from "fs";
10563
- import { dirname as dirname2 } from "path";
10564
- var DEFAULT_FILE_MODE = 384;
10565
- function loadFavorites() {
10566
- let raw2;
10567
- try {
10568
- raw2 = readFileSync3(FAVORITES_FILE, "utf8");
10569
- } catch (error) {
10570
- if (nodeErrorCode(error) === "ENOENT") return {};
10571
- throw unreadableFavorites(error);
10572
- }
10573
- try {
10574
- const parsed = JSON.parse(raw2);
10575
- if (!isFavoritesMap(parsed)) throw new Error("invalid favorites shape");
10576
- return parsed;
10577
- } catch (error) {
10578
- throw unreadableFavorites(error);
10579
- }
10580
- }
10581
- async function saveFavorite(alias, fav) {
10582
- return withFavoritesLock(() => {
10583
- const favs = loadFavorites();
10584
- const existed = Object.hasOwn(favs, alias);
10585
- favs[alias] = fav;
10586
- writeFavorites(favs);
10587
- return existed;
10588
- });
10589
- }
10590
- async function removeFavorite(alias) {
10591
- return withFavoritesLock(() => {
10592
- const favs = loadFavorites();
10593
- if (!Object.hasOwn(favs, alias)) return false;
10594
- const { [alias]: _, ...rest } = favs;
10595
- writeFavorites(rest);
10596
- return true;
10597
- });
10598
- }
10599
- function resolveEndpoint(input) {
10600
- if (!input.startsWith("@")) return input;
10601
- const alias = input.slice(1);
10602
- const favs = loadFavorites();
10603
- const fav = Object.hasOwn(favs, alias) ? favs[alias] : void 0;
10604
- if (!fav) {
10605
- throw new DvmError(
10606
- "unknown_favorite",
10607
- `No favorite named "${alias}".`,
10608
- "Run 'dvm fav list' to see saved favorites, or 'dvm fav add <endpoint>' to save one."
10609
- );
10610
- }
10611
- return fav.endpoint;
10612
- }
10613
- function deriveAlias(endpoint) {
10614
- try {
10615
- const hostname2 = new URL(endpoint).hostname;
10616
- if (hostname2.endsWith(".dvmkit.ai")) {
10617
- const prefix = hostname2.replace(".dvmkit.ai", "");
10618
- const dashIdx = prefix.indexOf("--");
10619
- if (dashIdx !== -1) return prefix.slice(dashIdx + 2);
10620
- return prefix;
10621
- }
10622
- return hostname2.replace(/\.[^.]+$/, "").replace(/\./g, "-");
10623
- } catch {
10624
- return endpoint.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
10625
- }
10626
- }
10627
- async function withFavoritesLock(fn) {
10628
- ensureConfigDir();
10629
- let release;
10630
- try {
10631
- release = await import_proper_lockfile.default.lock(FAVORITES_FILE, {
10632
- lockfilePath: `${FAVORITES_FILE}.lock`,
10633
- realpath: false,
10634
- stale: 3e4,
10635
- retries: { retries: 10, factor: 1, minTimeout: 100, maxTimeout: 100 }
10636
- });
10637
- } catch {
10638
- throw new DvmError(
10639
- "favorites_locked",
10640
- "Another dvm process is updating saved favorites.",
10641
- "Wait a moment and retry."
10642
- );
10643
- }
10644
- try {
10645
- return await fn();
10646
- } finally {
10647
- await release().catch(() => void 0);
10648
- }
10649
- }
10650
- function writeFavorites(favorites) {
10651
- const mode = favoritesFileMode();
10652
- const temporary = `${FAVORITES_FILE}.${String(process.pid)}.${randomSuffix()}.tmp`;
10653
- const contents = JSON.stringify(favorites, null, 2) + "\n";
10654
- let fd;
10655
- try {
10656
- fd = openSync2(temporary, "wx", mode);
10657
- fchmodSync(fd, mode);
10658
- writeFileSync(fd, contents);
10659
- fsyncSync(fd);
10660
- closeSync2(fd);
10661
- fd = void 0;
10662
- renameSync(temporary, FAVORITES_FILE);
10663
- fsyncDirectory(dirname2(FAVORITES_FILE));
10664
- } catch (error) {
10665
- if (fd !== void 0) {
10666
- try {
10667
- closeSync2(fd);
10668
- } catch {
10669
- }
10670
- }
10671
- try {
10672
- unlinkSync(temporary);
10673
- } catch {
10674
- }
10675
- throw error;
10676
- }
10677
- }
10678
- function favoritesFileMode() {
10679
- try {
10680
- return statSync2(FAVORITES_FILE).mode & 511;
10681
- } catch (error) {
10682
- if (nodeErrorCode(error) === "ENOENT") return DEFAULT_FILE_MODE;
10683
- throw error;
10684
- }
10685
- }
10686
- function fsyncDirectory(path) {
10687
- const fd = openSync2(path, "r");
10688
- try {
10689
- fsyncSync(fd);
10690
- } finally {
10691
- closeSync2(fd);
10692
- }
10693
- }
10694
- function randomSuffix() {
10695
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
10696
- }
10697
- function unreadableFavorites(error) {
10698
- return new DvmError(
10699
- "favorites_unreadable",
10700
- "Saved favorites are corrupt or unreadable.",
10701
- `The original file at ${FAVORITES_FILE} was left unchanged. Restore it from a backup, or move it aside before rebuilding favorites.`,
10702
- {
10703
- path: FAVORITES_FILE,
10704
- ...nodeErrorCode(error) ? { error_code: nodeErrorCode(error) } : {}
10705
- }
10706
- );
10707
- }
10708
- function nodeErrorCode(error) {
10709
- if (!(error instanceof Error) || !("code" in error)) return void 0;
10710
- const code = error.code;
10711
- return typeof code === "string" && /^E[A-Z0-9_]{1,63}$/.test(code) ? code : void 0;
10712
- }
10713
- function isFavoritesMap(value) {
10714
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
10715
- return Object.values(value).every(isFavorite);
10716
- }
10717
- function isFavorite(value) {
10718
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
10719
- const candidate = value;
10720
- return typeof candidate.endpoint === "string" && typeof candidate.addedAt === "number" && Number.isFinite(candidate.addedAt) && (candidate.name === void 0 || typeof candidate.name === "string");
10721
- }
10722
-
10723
11518
  // src/lib/discovery-options.ts
10724
11519
  var MAX_TIMER_MS = 2147483647;
10725
11520
  var DECIMAL = /^(?:\d+(?:\.\d*)?|\.\d+)$/;
@@ -11055,20 +11850,59 @@ var HttpsTransport = class {
11055
11850
  throw withCreditErrorContext(buildPaymentError(errorBody), errorBody);
11056
11851
  }
11057
11852
  if (!res.ok && res.status !== 202) {
11058
- const text = await res.text();
11059
- const structured = parseStructuredError(text);
11853
+ let text;
11854
+ try {
11855
+ text = await res.text();
11856
+ } catch {
11857
+ text = null;
11858
+ }
11859
+ const structured = text === null ? null : parseStructuredError(text);
11860
+ if (res.status === 409 && payment !== void 0 && structured === null) {
11861
+ throw identityError({
11862
+ kind: "body_unreadable",
11863
+ ...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {}
11864
+ });
11865
+ }
11866
+ if (text === null) {
11867
+ throw providerResponseError(
11868
+ "provider_error",
11869
+ `Job submission failed (${res.status}); the response body could not be read.`
11870
+ );
11871
+ }
11872
+ const conflict = routerConflictObservation(res.status, parseJsonObject(text));
11873
+ if (conflict) {
11874
+ throw identityError(
11875
+ { ...conflict, ...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {} },
11876
+ structured ? routerProse(structured) : void 0
11877
+ );
11878
+ }
11060
11879
  if (structured) throw structured;
11061
11880
  throw providerResponseError(
11062
11881
  "provider_error",
11063
11882
  `Job submission failed (${res.status}): ${text}`
11064
11883
  );
11065
11884
  }
11066
- const data = await res.json();
11067
- const feedbackClaim = res.headers.get(ROUTER_FEEDBACK_CLAIM_HEADER) ?? void 0;
11885
+ const identityHeader = jobIdentityHeaderValue(res.headers);
11886
+ let parsedBody;
11887
+ try {
11888
+ parsedBody = parseJsonObject(await res.text());
11889
+ } catch {
11890
+ parsedBody = null;
11891
+ }
11892
+ const identity = settleJobIdentity(identityHeader, parsedBody);
11893
+ if (identity.kind === "unresolved") {
11894
+ throw identityError({
11895
+ ...identity.observation,
11896
+ ...tempoTransactionHash ? { transactionHash: tempoTransactionHash } : {}
11897
+ });
11898
+ }
11899
+ if (identity.headerInvalid) warnInvalidJobIdentityHeader();
11900
+ const data = parsedBody;
11901
+ const feedbackClaim = identity.claimAllowed ? res.headers.get(ROUTER_FEEDBACK_CLAIM_HEADER) ?? void 0 : void 0;
11068
11902
  const jobToken = data.job_token;
11069
11903
  if (res.status === 202) {
11070
11904
  return {
11071
- jobId: data.job_id,
11905
+ jobId: identity.jobId,
11072
11906
  status: data.status === "awaiting-input" ? "awaiting-input" : "processing",
11073
11907
  estimatedSeconds: data.estimated_seconds,
11074
11908
  jobToken,
@@ -11078,7 +11912,7 @@ var HttpsTransport = class {
11078
11912
  };
11079
11913
  }
11080
11914
  return {
11081
- jobId: data.job_id,
11915
+ jobId: identity.jobId,
11082
11916
  status: "completed",
11083
11917
  summary: data.summary,
11084
11918
  hasArtifacts: data.has_artifacts,
@@ -11093,7 +11927,7 @@ var HttpsTransport = class {
11093
11927
  };
11094
11928
  }
11095
11929
  async requestResult(provider, requestId, signedJob) {
11096
- const url = `${provider.endpoint}/v1/request-result/${encodeURIComponent(requestId)}`;
11930
+ const url = `${provider.endpoint}/${requestRecoveryPath("request-result", requestId)}`;
11097
11931
  const res = await dvmFetch(url, {
11098
11932
  method: "POST",
11099
11933
  headers: { "Content-Type": "application/json" },
@@ -11103,22 +11937,32 @@ var HttpsTransport = class {
11103
11937
  if (!res.ok && res.status !== 202) {
11104
11938
  const text = await res.text();
11105
11939
  const structured = parseStructuredError(text);
11940
+ const conflict = routerConflictObservation(res.status, parseJsonObject(text));
11941
+ if (conflict) {
11942
+ throw identityError(conflict, structured ? routerProse(structured) : void 0);
11943
+ }
11106
11944
  if (structured) throw structured;
11107
11945
  throw providerResponseError(
11108
11946
  "provider_error",
11109
11947
  `Request lookup failed (${res.status}): ${text}`
11110
11948
  );
11111
11949
  }
11950
+ const identityHeader = parseJobIdentityHeader(jobIdentityHeaderValue(res.headers));
11112
11951
  let data;
11113
11952
  try {
11114
11953
  data = await res.json();
11115
11954
  } catch {
11116
11955
  throw malformedRequestResult(requestId, "response_not_json");
11117
11956
  }
11118
- return parseRequestResultResponse(data, requestId, res.status);
11957
+ const receipt = parseRequestResultResponse(data, requestId, res.status);
11958
+ if (identityHeader.kind === "valid" && identityHeader.jobId !== receipt.jobId) {
11959
+ throw malformedRequestResult(requestId, "job_identity_mismatch");
11960
+ }
11961
+ if (identityHeader.kind === "invalid") warnInvalidJobIdentityHeader();
11962
+ return receipt;
11119
11963
  }
11120
11964
  async requestResume(provider, requestId, signedJob, options) {
11121
- const url = `${provider.endpoint}/v1/request-resume/${encodeURIComponent(requestId)}`;
11965
+ const url = `${provider.endpoint}/${requestRecoveryPath("request-resume", requestId)}`;
11122
11966
  const signal = options?.timeoutMs && options.timeoutMs > 0 ? AbortSignal.timeout(options.timeoutMs) : void 0;
11123
11967
  let res;
11124
11968
  try {
@@ -11483,7 +12327,7 @@ function parseRequestResultResponse(value, requestId, httpStatus) {
11483
12327
  if (data.request_id !== requestId) {
11484
12328
  throw malformedRequestResult(requestId, "request_id_mismatch");
11485
12329
  }
11486
- if (typeof data.job_id !== "string" || data.job_id.trim().length === 0 || data.job_id.length > 512 || hasAsciiControl(data.job_id)) {
12330
+ if (!isParseableBodyJobId(data.job_id)) {
11487
12331
  throw malformedRequestResult(requestId, "job_id_invalid");
11488
12332
  }
11489
12333
  const allowedStatuses = /* @__PURE__ */ new Set([
@@ -11539,16 +12383,6 @@ function parseRequestResultResponse(value, requestId, httpStatus) {
11539
12383
  ...parseFundingResponse(data)
11540
12384
  };
11541
12385
  }
11542
- function isOpaqueJobToken(value) {
11543
- return typeof value === "string" && value.length > 0 && value.length <= 4096 && value.trim() === value && !hasAsciiControl(value);
11544
- }
11545
- function hasAsciiControl(value) {
11546
- for (const character of value) {
11547
- const code = character.charCodeAt(0);
11548
- if (code <= 31 || code === 127) return true;
11549
- }
11550
- return false;
11551
- }
11552
12386
  function malformedRequestResult(requestId, reason) {
11553
12387
  return new DvmError(
11554
12388
  "request_outcome_unknown",
@@ -11683,6 +12517,10 @@ function buildStructuredError(code, fields) {
11683
12517
  function providerResponseError(code, message2) {
11684
12518
  return new DvmError(code, message2, void 0, void 0, void 0, { message: "provider" });
11685
12519
  }
12520
+ function routerProse(structured) {
12521
+ const display = typeof structured.data?.display === "string" ? structured.data.display : void 0;
12522
+ return display !== void 0 ? { display, proseSources: { display: "provider" } } : {};
12523
+ }
11686
12524
  function parseJsonObject(body) {
11687
12525
  try {
11688
12526
  const parsed = JSON.parse(body);
@@ -12242,113 +13080,6 @@ function resolveCapability(info2, requested, dvmId) {
12242
13080
  );
12243
13081
  }
12244
13082
 
12245
- // src/lib/job-access.ts
12246
- function resolveJobAccess(jobId, opts) {
12247
- const stored = loadJob(jobId);
12248
- return resolveJobAccessWithRecord(jobId, opts, stored);
12249
- }
12250
- function resolveJobAccessWithRecord(jobId, opts, stored) {
12251
- const endpointOverride = opts.endpoint ?? process.env.DVM_JOB_ENDPOINT;
12252
- const tokenOverride = opts.jobToken ?? process.env.DVM_JOB_TOKEN;
12253
- const endpointOverridden = endpointOverride !== void 0;
12254
- const tokenOverridden = tokenOverride !== void 0;
12255
- const rawEndpoint = endpointOverride ?? stored?.endpoint;
12256
- const jobToken = tokenOverride ?? stored?.jobToken;
12257
- if (!stored && rawEndpoint === void 0 && jobToken === void 0) {
12258
- throw new DvmError(
12259
- "job_access_required",
12260
- `Job ${jobId} is not in the local store, and no portable job access was supplied.`,
12261
- "Pass --endpoint <url> and --job-token <hex>, or set DVM_JOB_ENDPOINT and DVM_JOB_TOKEN."
12262
- );
12263
- }
12264
- if (rawEndpoint === void 0) {
12265
- throw new DvmError(
12266
- "job_endpoint_required",
12267
- `No provider endpoint is available for job ${jobId}.`,
12268
- "Pass --endpoint <url> or set DVM_JOB_ENDPOINT."
12269
- );
12270
- }
12271
- if (!stored && jobToken === void 0) {
12272
- throw new DvmError(
12273
- "job_token_required",
12274
- `No job token is available for job ${jobId}.`,
12275
- "Pass --job-token <hex> or set DVM_JOB_TOKEN."
12276
- );
12277
- }
12278
- if (tokenOverridden && !isJobToken(jobToken)) {
12279
- throw new DvmError(
12280
- "invalid_job_token",
12281
- "The supplied job token is not a 64-character hexadecimal value.",
12282
- "Copy the job_token returned when the job was submitted; the value is never printed by this command."
12283
- );
12284
- }
12285
- return {
12286
- stored,
12287
- ref: { endpoint: validateProviderEndpoint(resolveEndpoint(rawEndpoint)) },
12288
- ...jobToken !== void 0 ? { jobToken } : {},
12289
- overridden: endpointOverridden || tokenOverridden,
12290
- endpointOverridden
12291
- };
12292
- }
12293
- function resolveStoredJobAccess(jobId, opts) {
12294
- const stored = loadJob(jobId);
12295
- if (!stored) {
12296
- throw new DvmError(
12297
- "job_payment_state_required",
12298
- `Cannot pay job ${jobId} without its local payment state.`,
12299
- "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."
12300
- );
12301
- }
12302
- return { ...resolveJobAccessWithRecord(jobId, opts, stored), stored };
12303
- }
12304
- async function withJobTokenRedaction(jobToken, action) {
12305
- try {
12306
- return await action();
12307
- } catch (err) {
12308
- throw redactJobTokenFromError(err, jobToken);
12309
- }
12310
- }
12311
- function redactJobTokenFromError(err, jobToken) {
12312
- if (!jobToken || !(err instanceof DvmError)) return err;
12313
- const redact = (value) => value.replaceAll(jobToken, "[REDACTED]");
12314
- return new DvmError(
12315
- err.code,
12316
- redact(err.message),
12317
- err.hint === void 0 ? void 0 : redact(err.hint),
12318
- err.data === void 0 ? void 0 : redactRecord(err.data, redact),
12319
- err.display === void 0 ? void 0 : redact(err.display),
12320
- err.proseSources
12321
- );
12322
- }
12323
- function isJobToken(value) {
12324
- return value !== void 0 && /^[0-9a-fA-F]{64}$/.test(value);
12325
- }
12326
- function validateProviderEndpoint(value) {
12327
- try {
12328
- const url = new URL(value);
12329
- if ((url.protocol === "http:" || url.protocol === "https:") && url.hostname) return value;
12330
- } catch {
12331
- }
12332
- throw new DvmError(
12333
- "invalid_endpoint",
12334
- "The supplied job endpoint is not a valid HTTP(S) provider URL.",
12335
- "Pass a full URL such as https://provider.example, or a favorite alias such as @provider."
12336
- );
12337
- }
12338
- function redactRecord(record, redact) {
12339
- return Object.fromEntries(
12340
- Object.entries(record).map(([key, value]) => [key, redactValue(value, redact)])
12341
- );
12342
- }
12343
- function redactValue(value, redact) {
12344
- if (typeof value === "string") return redact(value);
12345
- if (Array.isArray(value)) return value.map((entry) => redactValue(entry, redact));
12346
- if (value && typeof value === "object") {
12347
- return redactRecord(value, redact);
12348
- }
12349
- return value;
12350
- }
12351
-
12352
13083
  // src/commands/dvm-identity.ts
12353
13084
  function dvmIdentity(dvmId, capability) {
12354
13085
  const out = {};
@@ -12587,14 +13318,14 @@ async function confirmRollback(stored, preview, opts) {
12587
13318
  async function withStrandingChecked(removing, commit) {
12588
13319
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
12589
13320
  if (leaving.has("tempo")) {
12590
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-HS2NIFKT.js");
13321
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-NDBO3V3A.js");
12591
13322
  await assertTempoWalletIdle2("disconnect");
12592
13323
  }
12593
13324
  if (!leaving.has("x402")) return commit();
12594
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-7FXJTFBU.js");
12595
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-LRS3IBQL.js");
12596
- const { ensureAddress: ensureAddress2 } = await import("./internal-7FXJTFBU.js");
12597
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RPPUCQUR.js");
13325
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-VIAWW5ED.js");
13326
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-VHGTNHHE.js");
13327
+ const { ensureAddress: ensureAddress2 } = await import("./internal-VIAWW5ED.js");
13328
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RB2RPWIN.js");
12598
13329
  return withX402ChannelLock2(async () => {
12599
13330
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
12600
13331
  if (unsettled.length > 0) {
@@ -13457,7 +14188,7 @@ function creditDrainCommand(handle, creditId) {
13457
14188
  }
13458
14189
 
13459
14190
  // src/commands/wallet-history.ts
13460
- import { createHash } from "crypto";
14191
+ import { createHash as createHash2 } from "crypto";
13461
14192
 
13462
14193
  // src/lib/completed-credit-history.ts
13463
14194
  function completedCreditHistory(query = {}) {
@@ -13602,7 +14333,7 @@ function walletHistory(opts, now = /* @__PURE__ */ new Date()) {
13602
14333
  const windowed = (sinceMs === null ? all : all.filter((e) => e.timestamp >= sinceMs)).slice().sort(
13603
14334
  (a, b) => b.timestamp - a.timestamp || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0)
13604
14335
  );
13605
- const fingerprint = createHash("sha256").update(JSON.stringify(windowed)).digest("hex");
14336
+ const fingerprint = createHash2("sha256").update(JSON.stringify(windowed)).digest("hex");
13606
14337
  if (continuation && continuation.fingerprint !== fingerprint) {
13607
14338
  throw invalidHistoryCursor();
13608
14339
  }
@@ -14626,7 +15357,7 @@ function wireCreditCurrencyTotals(rows) {
14626
15357
 
14627
15358
  // src/lib/credit/drain.ts
14628
15359
  import {
14629
- randomUUID
15360
+ randomUUID as randomUUID2
14630
15361
  } from "crypto";
14631
15362
  async function runCreditDrain(dvm, opts) {
14632
15363
  const endpoint = resolveCreditEndpoint(dvm);
@@ -14758,7 +15489,7 @@ async function runCreditDrain(dvm, opts) {
14758
15489
  const payout = await drainPayout(method, opts, channelBacked, dvm);
14759
15490
  const mintedThisRun = !pending4;
14760
15491
  let drain = pending4 ? reusableDrain(pending4, method, payout) : {
14761
- drainId: opts.drainId ?? randomUUID(),
15492
+ drainId: opts.drainId ?? randomUUID2(),
14762
15493
  creditId,
14763
15494
  method,
14764
15495
  payout,
@@ -15593,7 +16324,7 @@ function refundAddress(address) {
15593
16324
 
15594
16325
  // src/lib/credit/funding.ts
15595
16326
  import {
15596
- randomUUID as randomUUID2
16327
+ randomUUID as randomUUID3
15597
16328
  } from "crypto";
15598
16329
  async function runCreditFund(dvm, opts) {
15599
16330
  const endpoint = resolveCreditEndpoint(dvm);
@@ -15697,7 +16428,7 @@ async function runCreditFund(dvm, opts) {
15697
16428
  transport,
15698
16429
  ref: { endpoint },
15699
16430
  signing: signer,
15700
- creditId: pending4?.creditId ?? opts.creditId ?? (canRefillStoredCredit(stored) ? stored.creditId : signedPending?.creditId ?? randomUUID2()),
16431
+ creditId: pending4?.creditId ?? opts.creditId ?? (canRefillStoredCredit(stored) ? stored.creditId : signedPending?.creditId ?? randomUUID3()),
15701
16432
  amountMicro: fundMicro,
15702
16433
  human: opts.human,
15703
16434
  providerInfo,
@@ -17426,8 +18157,8 @@ async function probeX402(x402, timeoutMs) {
17426
18157
  let network;
17427
18158
  let address;
17428
18159
  try {
17429
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RPPUCQUR.js");
17430
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-7FXJTFBU.js");
18160
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RB2RPWIN.js");
18161
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-VIAWW5ED.js");
17431
18162
  const wallet = loadX402Wallet2();
17432
18163
  if (!wallet) {
17433
18164
  const storedKey = x402.privateKey;
@@ -17479,8 +18210,8 @@ async function probeMpp(mpp, timeoutMs) {
17479
18210
  if (!mpp) return null;
17480
18211
  if (mpp.method === "tempo") {
17481
18212
  try {
17482
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-BA2LKR45.js");
17483
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-7FXJTFBU.js");
18213
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-BAU7ASWF.js");
18214
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-VIAWW5ED.js");
17484
18215
  const account = await connectedTempoAccount2();
17485
18216
  if (!account) {
17486
18217
  return {
@@ -17574,8 +18305,8 @@ function x402WrongAssetHint(asset) {
17574
18305
  }
17575
18306
 
17576
18307
  // src/lib/build-freshness.ts
17577
- import { existsSync as existsSync3, readdirSync, statSync as statSync3 } from "fs";
17578
- import { dirname as dirname3, join as join3 } from "path";
18308
+ import { existsSync as existsSync4, readdirSync as readdirSync2, statSync as statSync3 } from "fs";
18309
+ import { dirname as dirname3, join as join4 } from "path";
17579
18310
  import { fileURLToPath as fileURLToPath2 } from "url";
17580
18311
  var EXTRA_SOURCES = ["package.json", "tsup.config.ts"];
17581
18312
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "__snapshots__"]);
@@ -17594,21 +18325,21 @@ function checkBuildFreshness(opts) {
17594
18325
  skipReason
17595
18326
  });
17596
18327
  if (root === null) return skipped("running_from_source");
17597
- const bundlePath = join3(root, "dist", "dvm.js");
17598
- if (dirname3(moduleDir) !== root || !existsSync3(bundlePath)) {
18328
+ const bundlePath = join4(root, "dist", "dvm.js");
18329
+ if (dirname3(moduleDir) !== root || !existsSync4(bundlePath)) {
17599
18330
  return skipped("running_from_source");
17600
18331
  }
17601
- const srcDir = join3(root, "src");
17602
- if (!existsSync3(srcDir)) return skipped("no_source_tree");
18332
+ const srcDir = join4(root, "src");
18333
+ if (!existsSync4(srcDir)) return skipped("no_source_tree");
17603
18334
  const builtAtMs = statSync3(bundlePath).mtimeMs;
17604
18335
  const newer = [];
17605
18336
  let newestMs = 0;
17606
18337
  const visit = (dir, rel, budget2) => {
17607
18338
  if (budget2.left <= 0) return;
17608
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
18339
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
17609
18340
  if (budget2.left-- <= 0) return;
17610
18341
  if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
17611
- const abs = join3(dir, entry.name);
18342
+ const abs = join4(dir, entry.name);
17612
18343
  const relPath = rel ? `${rel}/${entry.name}` : entry.name;
17613
18344
  if (entry.isDirectory()) {
17614
18345
  visit(abs, relPath, budget2);
@@ -17623,8 +18354,8 @@ function checkBuildFreshness(opts) {
17623
18354
  const budget = { left: MAX_ENTRIES };
17624
18355
  visit(srcDir, "src", budget);
17625
18356
  for (const name of EXTRA_SOURCES) {
17626
- const abs = join3(root, name);
17627
- if (!existsSync3(abs)) continue;
18357
+ const abs = join4(root, name);
18358
+ if (!existsSync4(abs)) continue;
17628
18359
  const mtimeMs = statSync3(abs).mtimeMs;
17629
18360
  if (mtimeMs > newestMs) newestMs = mtimeMs;
17630
18361
  if (mtimeMs > builtAtMs) newer.push({ path: name, mtimeMs });
@@ -17642,7 +18373,7 @@ function checkBuildFreshness(opts) {
17642
18373
  function findPackageRoot(start) {
17643
18374
  let dir = start;
17644
18375
  for (; ; ) {
17645
- if (existsSync3(join3(dir, "package.json"))) return dir;
18376
+ if (existsSync4(join4(dir, "package.json"))) return dir;
17646
18377
  const parent = dirname3(dir);
17647
18378
  if (parent === dir) return null;
17648
18379
  dir = parent;
@@ -17650,18 +18381,18 @@ function findPackageRoot(start) {
17650
18381
  }
17651
18382
 
17652
18383
  // src/lib/caller-state.ts
17653
- import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync4 } from "fs";
17654
- import { basename, join as join4 } from "path";
18384
+ import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync4 } from "fs";
18385
+ import { basename, join as join5 } from "path";
17655
18386
  function detectSetupState() {
17656
18387
  return {
17657
18388
  existingState: {
17658
- jobs: existsSync4(JOBS_FILE),
17659
- messages: existsSync4(MESSAGES_DIR)
18389
+ jobs: existsSync5(JOBS_FILE),
18390
+ messages: existsSync5(MESSAGES_DIR)
17660
18391
  },
17661
18392
  missing: {
17662
- config: !existsSync4(CONFIG_FILE),
17663
- identity: !existsSync4(IDENTITIES_FILE),
17664
- wallet: !existsSync4(WALLET_FILE)
18393
+ config: !existsSync5(CONFIG_FILE),
18394
+ identity: !existsSync5(IDENTITIES_FILE),
18395
+ wallet: !existsSync5(WALLET_FILE)
17665
18396
  }
17666
18397
  };
17667
18398
  }
@@ -17757,6 +18488,16 @@ var FILE_SPECS = [
17757
18488
  directory: true
17758
18489
  },
17759
18490
  { name: "messages", path: MESSAGES_DIR, json: false, secret: false, directory: true },
18491
+ // Evidence of paid calls accepted without a settled job identity. Each file
18492
+ // is 0600 because a record can hold an anonymous job's access token, so
18493
+ // every file in the directory is checked.
18494
+ {
18495
+ name: "submission_evidence",
18496
+ path: SUBMISSION_EVIDENCE_DIR,
18497
+ json: false,
18498
+ secret: true,
18499
+ directory: true
18500
+ },
17760
18501
  // JSONL, not JSON — `json: false` because a whole-file `JSON.parse` would
17761
18502
  // report the healthy multi-line form as corrupt. `dvm receipts list` already
17762
18503
  // skips malformed lines individually.
@@ -17770,31 +18511,33 @@ function findQuarantinedCreditStores() {
17770
18511
  const prefix = `${basename(CREDITS_FILE)}.corrupt-`;
17771
18512
  let entries;
17772
18513
  try {
17773
- entries = readdirSync2(CONFIG_DIR);
18514
+ entries = readdirSync3(CONFIG_DIR);
17774
18515
  } catch {
17775
18516
  return [];
17776
18517
  }
17777
- return entries.filter((name) => name.startsWith(prefix)).sort((a, b) => a < b ? 1 : a > b ? -1 : 0).map((name) => ({ path: join4(CONFIG_DIR, name), name }));
18518
+ return entries.filter((name) => name.startsWith(prefix)).sort((a, b) => a < b ? 1 : a > b ? -1 : 0).map((name) => ({ path: join5(CONFIG_DIR, name), name }));
17778
18519
  }
17779
18520
  function checkOne(spec) {
17780
- const exists = existsSync4(spec.path);
18521
+ const exists = existsSync5(spec.path);
17781
18522
  if (!exists) {
17782
18523
  return { name: spec.name, path: spec.path, exists: false };
17783
18524
  }
17784
18525
  const row = { name: spec.name, path: spec.path, exists: true };
17785
18526
  if (spec.json) {
17786
18527
  try {
17787
- JSON.parse(readFileSync4(spec.path, "utf-8"));
18528
+ JSON.parse(readFileSync5(spec.path, "utf-8"));
17788
18529
  row.parseable = true;
17789
18530
  } catch (err) {
17790
18531
  row.parseable = false;
17791
18532
  row.error = err instanceof Error ? err.message : String(err);
17792
18533
  }
17793
18534
  }
17794
- if (spec.secret) {
18535
+ if (spec.secret && spec.directory) {
18536
+ checkSecretDirectory(spec.path, row);
18537
+ } else if (spec.secret) {
17795
18538
  try {
17796
18539
  const mode = statSync4(spec.path).mode & 511;
17797
- const modeOctal = "0" + mode.toString(8).padStart(3, "0");
18540
+ const modeOctal = octalMode(mode);
17798
18541
  row.modeOk = mode === 384;
17799
18542
  row.modeOctal = modeOctal;
17800
18543
  if (!row.modeOk && !row.error) {
@@ -17807,10 +18550,34 @@ function checkOne(spec) {
17807
18550
  }
17808
18551
  return row;
17809
18552
  }
18553
+ function checkSecretDirectory(dir, row) {
18554
+ try {
18555
+ const offenders = [];
18556
+ for (const name of readdirSync3(dir)) {
18557
+ const path = join5(dir, name);
18558
+ const stat = statSync4(path);
18559
+ if (!stat.isFile()) continue;
18560
+ const mode = stat.mode & 511;
18561
+ if (mode !== 384) offenders.push({ path, modeOctal: octalMode(mode) });
18562
+ }
18563
+ row.modeOk = offenders.length === 0;
18564
+ if (offenders.length > 0) {
18565
+ row.modeOctal = offenders[0].modeOctal;
18566
+ row.offendingPaths = offenders.map((o) => o.path);
18567
+ row.error = `expected mode 0600, found ${row.modeOctal} on ${String(offenders.length)} file(s)`;
18568
+ }
18569
+ } catch (err) {
18570
+ row.modeOk = false;
18571
+ row.error = err instanceof Error ? err.message : String(err);
18572
+ }
18573
+ }
18574
+ function octalMode(mode) {
18575
+ return "0" + mode.toString(8).padStart(3, "0");
18576
+ }
17810
18577
  function readBtcRateCacheAge(now = Date.now()) {
17811
- if (!existsSync4(BTC_RATE_FILE)) return null;
18578
+ if (!existsSync5(BTC_RATE_FILE)) return null;
17812
18579
  try {
17813
- const data = JSON.parse(readFileSync4(BTC_RATE_FILE, "utf-8"));
18580
+ const data = JSON.parse(readFileSync5(BTC_RATE_FILE, "utf-8"));
17814
18581
  if (typeof data.timestamp !== "number") return null;
17815
18582
  return { ageMs: now - data.timestamp };
17816
18583
  } catch {
@@ -17819,20 +18586,20 @@ function readBtcRateCacheAge(now = Date.now()) {
17819
18586
  }
17820
18587
 
17821
18588
  // src/lib/mnemonic-backups.ts
17822
- import { readdirSync as readdirSync3, statSync as statSync5 } from "fs";
17823
- import { basename as basename2, dirname as dirname4, join as join5 } from "path";
18589
+ import { readdirSync as readdirSync4, statSync as statSync5 } from "fs";
18590
+ import { basename as basename2, dirname as dirname4, join as join6 } from "path";
17824
18591
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
17825
18592
  const dir = dirname4(mnemonicFile);
17826
18593
  const prefix = `${basename2(mnemonicFile)}.`;
17827
18594
  let names;
17828
18595
  try {
17829
- names = readdirSync3(dir);
18596
+ names = readdirSync4(dir);
17830
18597
  } catch (err) {
17831
18598
  if (err.code === "ENOENT") return [];
17832
18599
  throw err;
17833
18600
  }
17834
18601
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
17835
- const path = join5(dir, name);
18602
+ const path = join6(dir, name);
17836
18603
  const stat = statSync5(path);
17837
18604
  if (!stat.isFile()) return null;
17838
18605
  const ageMs2 = Math.max(0, nowMs - stat.mtimeMs);
@@ -17881,39 +18648,80 @@ function describePendingSubmissions(wallet, nowMs = Date.now()) {
17881
18648
  (e) => e.state === "stale" || e.state === "unresumable" || e.state === "unreclaimable"
17882
18649
  ).length,
17883
18650
  reclaimable_count: entries.filter((e) => e.state === "reclaimable").length,
17884
- reclaim_failed_count: entries.filter((e) => e.state === "reclaim_failed").length
18651
+ reclaim_failed_count: entries.filter((e) => e.state === "reclaim_failed").length,
18652
+ accepted_unresolved_count: entries.filter((e) => e.state === "accepted_unresolved").length
17885
18653
  };
17886
18654
  }
17887
18655
  function formatPendingSubmission(view) {
17888
18656
  const reqShort = `${view.request_id.slice(0, 8)}\u2026${view.request_id.slice(-4)}`;
17889
18657
  const age = view.age_seconds === null ? "age unknown" : `${formatAge(view.age_seconds)} old`;
17890
18658
  const why = view.reclaim_error ? `: ${view.reclaim_error}` : "";
17891
- return `${view.amount_sats} sats ${view.endpoint} (req ${reqShort}, ${age}, ${view.state}${why})`;
18659
+ const readBack = view.public_request_id ? `; dvm request-result ${view.public_request_id}` : "";
18660
+ return `${view.amount_sats} sats ${view.endpoint} (req ${reqShort}, ${age}, ${view.state}${why}${readBack})`;
17892
18661
  }
17893
18662
  function describeResumedSubmissions(outcomes) {
17894
18663
  const views = [];
17895
18664
  for (const outcome of outcomes) {
18665
+ const publicRequestId = publicRequestIdOf(outcome.entry);
18666
+ const locate = locateAdvice(outcome.entry, publicRequestId);
17896
18667
  if (outcome.kind === "shipped") {
17897
18668
  const jobId = outcome.jobId ?? null;
17898
18669
  views.push({
17899
18670
  request_id: outcome.entry.request_id,
18671
+ ...publicRequestId ? { public_request_id: publicRequestId } : {},
17900
18672
  endpoint: outcome.entry.endpoint,
17901
18673
  amount_sats: outcome.entry.amount_sats,
17902
18674
  job_id: jobId,
17903
- display: jobId ? `${outcome.entry.amount_sats} sats paid to ${outcome.entry.endpoint} was reconciled \u2014 the job resumed as ${jobId}. Look it up with \`dvm status ${jobId}\`.` : `${outcome.entry.amount_sats} sats paid to ${outcome.entry.endpoint} was reconciled, but the provider returned no job id. Quote request ${outcome.entry.request_id} to the provider to locate the result.`
18675
+ display: jobId ? `${outcome.entry.amount_sats} sats paid to ${outcome.entry.endpoint} was reconciled \u2014 the job resumed as ${jobId}. Look it up with \`dvm status ${jobId}\`.` : `${outcome.entry.amount_sats} sats paid to ${outcome.entry.endpoint} was reconciled, but the provider returned no job id. ${locate}`
17904
18676
  });
17905
18677
  } else if (outcome.kind === "already_accepted") {
17906
18678
  views.push({
17907
18679
  request_id: outcome.entry.request_id,
18680
+ ...publicRequestId ? { public_request_id: publicRequestId } : {},
17908
18681
  endpoint: outcome.entry.endpoint,
17909
18682
  amount_sats: outcome.entry.amount_sats,
17910
18683
  job_id: null,
17911
- display: `${outcome.entry.amount_sats} sats paid to ${outcome.entry.endpoint} was already confirmed by the provider, which returned no job id. Quote request ${outcome.entry.request_id} to the provider to locate the result.`
18684
+ display: `${outcome.entry.amount_sats} sats paid to ${outcome.entry.endpoint} was already confirmed by the provider, which returned no job id. ${locate}`
17912
18685
  });
17913
18686
  }
17914
18687
  }
17915
18688
  return views;
17916
18689
  }
18690
+ function describeUnresolvedSubmissions(outcomes) {
18691
+ const views = [];
18692
+ for (const outcome of outcomes) {
18693
+ if (outcome.kind === "evidence_unreadable") {
18694
+ const { entry: entry2 } = outcome;
18695
+ const publicRequestId2 = publicRequestIdOf(entry2);
18696
+ views.push({
18697
+ request_id: entry2.request_id,
18698
+ ...publicRequestId2 ? { public_request_id: publicRequestId2 } : {},
18699
+ endpoint: entry2.endpoint,
18700
+ amount_sats: entry2.amount_sats,
18701
+ ambiguity_id: entry2.request_id,
18702
+ evidence: "unreadable",
18703
+ display: `${entry2.amount_sats} sats paid to ${entry2.endpoint} has an evidence record that cannot be read, so the payment is held and not sent again until the file under ${entry2.request_id} in \`dvm wallet submissions\` is restored. ${locateAdvice(entry2, publicRequestId2)}`
18704
+ });
18705
+ continue;
18706
+ }
18707
+ if (outcome.kind !== "accepted_unresolved") continue;
18708
+ if (outcome.evidence === "recorded" && !outcome.observation) continue;
18709
+ const { entry, marker } = outcome;
18710
+ const publicRequestId = publicRequestIdOf(entry);
18711
+ const readBack = publicRequestId ? ` Read the job back with \`dvm request-result ${publicRequestId}\`, which never pays.` : "";
18712
+ views.push({
18713
+ request_id: entry.request_id,
18714
+ ...publicRequestId ? { public_request_id: publicRequestId } : {},
18715
+ endpoint: entry.endpoint,
18716
+ amount_sats: entry.amount_sats,
18717
+ kind: marker.kind,
18718
+ ambiguity_id: marker.ambiguity_id,
18719
+ evidence: outcome.evidence,
18720
+ display: outcome.evidence === "recorded" ? `${entry.amount_sats} sats paid to ${entry.endpoint} was accepted on retry, but the provider did not say clearly which job it started. It will not be paid for or sent again; \`dvm wallet submissions\` shows the evidence (${marker.ambiguity_id}).${readBack}` : `${entry.amount_sats} sats paid to ${entry.endpoint} was accepted without a clear job ID, and the evidence record ${marker.ambiguity_id} is ${outcome.evidence === "missing" ? "missing from this machine" : "damaged"}. The payment is still never sent again. ${locateAdvice(entry, publicRequestId)}`
18721
+ });
18722
+ }
18723
+ return views;
18724
+ }
17917
18725
  function describeReclaimedSubmissions(outcomes) {
17918
18726
  const views = [];
17919
18727
  for (const outcome of outcomes) {
@@ -17947,6 +18755,34 @@ function describeSkippedReclaims(outcomes) {
17947
18755
  }
17948
18756
  return views;
17949
18757
  }
18758
+ function describeSubmissionEvidence(records) {
18759
+ return records.map((record) => {
18760
+ const { v: _v, job_token: jobToken, ...fields } = record;
18761
+ const jobIds = [
18762
+ ...new Set(
18763
+ [record.header_job_id, record.body_job_id, record.accepted_job_id].filter(
18764
+ (id) => id !== void 0
18765
+ )
18766
+ )
18767
+ ];
18768
+ const collision = record.kind === "local_job_collision";
18769
+ const readJob = [
18770
+ ...record.request_id && !collision ? [`dvm request-result ${record.request_id}`] : [],
18771
+ ...jobToken ? jobIds.map(
18772
+ (jobId) => `DVM_JOB_TOKEN=<job_token_bearer_secret> dvm status ${shellQuoteArg(jobId)} --endpoint ${shellQuoteArg(record.endpoint)}`
18773
+ ) : []
18774
+ ];
18775
+ const what = collision ? `its job${record.accepted_job_id ? ` ${record.accepted_job_id}` : ""} shares its ID with a local job from another provider, so it is kept here rather than in the local job list` : record.kind === "router_identity_conflict" ? "this request had already been accepted as a different job" : record.kind === "identity_mismatch" ? "the provider named two different jobs for it" : "the provider's reply did not state a readable job";
18776
+ const lookup = readJob.length > 0 ? ` Find the job with one of read_job; those lookups never pay.` : jobIds.length > 0 ? ` No job token was received for ${jobIds.join(", ")}, so quote the request to the provider operator.` : " No job ID was observed, so quote the request to the provider operator.";
18777
+ const secret = jobToken ? " job_token_bearer_secret is a bearer secret: treat it like a password and do not share it." : "";
18778
+ return {
18779
+ ...fields,
18780
+ ...jobToken ? { job_token_bearer_secret: jobToken } : {},
18781
+ read_job: readJob,
18782
+ display: `A paid call to ${record.endpoint} was accepted, but ${what}. It was not paid for again.${lookup}${secret}`
18783
+ };
18784
+ });
18785
+ }
17950
18786
  function toView(entry, nowMs) {
17951
18787
  const createdMs = Date.parse(entry.created_at);
17952
18788
  const ageMs2 = Number.isNaN(createdMs) ? Number.POSITIVE_INFINITY : nowMs - createdMs;
@@ -17964,13 +18800,22 @@ function toView(entry, nowMs) {
17964
18800
  at_risk: state !== "awaiting_swap",
17965
18801
  reclaim_at: reclaimAt === null ? null : new Date(reclaimAt).toISOString(),
17966
18802
  reclaim_error: state === "reclaim_failed" || state === "unreclaimable" ? entry.reclaim_error ?? null : null,
18803
+ ...entry.accepted_unresolved ? { accepted_unresolved: entry.accepted_unresolved } : {},
18804
+ ...publicRequestIdOf(entry) ? { public_request_id: publicRequestIdOf(entry) } : {},
17967
18805
  display: describe2(entry, state, reclaimAt, nowMs)
17968
18806
  };
17969
18807
  }
18808
+ function locateAdvice(entry, publicRequestId = publicRequestIdOf(entry)) {
18809
+ return publicRequestId ? `Read the job back with \`dvm request-result ${publicRequestId}\`, which never pays.` : `Quote request ${entry.request_id} to the provider to locate the result.`;
18810
+ }
17970
18811
  function deriveState(entry, ageMs2, attempts, reclaimAt) {
17971
18812
  if (entry.output_proofs.length === 0) {
17972
18813
  return entry.swapping ? "recovering_swap" : "awaiting_swap";
17973
18814
  }
18815
+ if (entry.accepted_unresolved) {
18816
+ if (reclaimAt === null || !entry.reclaim_error) return "accepted_unresolved";
18817
+ return entry.reclaim_terminal ? "unreclaimable" : "reclaim_failed";
18818
+ }
17974
18819
  const resumeOver = !isResumable(entry) || ageMs2 > RESUME_MAX_AGE_MS || attempts >= RESUME_MAX_ATTEMPTS;
17975
18820
  if (resumeOver && reclaimAt !== null) {
17976
18821
  if (!entry.reclaim_error) return "reclaimable";
@@ -17988,7 +18833,7 @@ function describe2(entry, state, reclaimAt, nowMs) {
17988
18833
  case "recovering_swap":
17989
18834
  return `${sats} is tied to a mint swap whose response was interrupted. The wallet is restoring the signed payment or proving the original inputs remain spendable; do not retry or forget request ${entry.request_id}.`;
17990
18835
  case "resumable":
17991
- return `${sats} was paid to ${entry.endpoint} but the provider never confirmed. The next call to any DVM retries it automatically.`;
18836
+ return publicRequestIdOf(entry) ? `${sats} was paid to ${entry.endpoint} but the provider never confirmed. The next call to any DVM reads request ${publicRequestIdOf(entry)} back from the provider, and re-sends the same payment only if the provider never received it.` : `${sats} was paid to ${entry.endpoint} but the provider never confirmed. The next call to any DVM retries it automatically.`;
17992
18837
  case "reclaimable":
17993
18838
  return reclaimAt !== null && reclaimAt > nowMs ? `${sats} was paid to ${entry.endpoint} and the provider never confirmed it. Retries have stopped, but the payment has an expiry: if the provider still hasn't taken it by ${new Date(reclaimAt).toISOString()}, the wallet returns it to your balance on its own. Nothing to do.` : `${sats} was paid to ${entry.endpoint} and the provider never confirmed it. The payment has expired, so the wallet can take it back \u2014 it returns to your balance on the next call or \`dvm wallet show\`.`;
17994
18839
  case "reclaim_failed":
@@ -17996,9 +18841,14 @@ function describe2(entry, state, reclaimAt, nowMs) {
17996
18841
  case "unreclaimable":
17997
18842
  return entry.reclaim_error?.startsWith("worth ") ? `${sats} was paid to ${entry.endpoint}, the provider never took it, and the payment has expired \u2014 but it is too small to be worth taking back: ${entry.reclaim_error}. Retrying will not change that, so treat these sats as spent; \`dvm wallet submissions --forget ${entry.request_id}\` clears the entry once you have stopped caring about it.` : `${sats} was paid to ${entry.endpoint}, the provider never took it, and automatic recovery cannot succeed: ${entry.reclaim_error ?? "the mint rejected the recovery permanently"} Do not delete the entry until the mint operator has reviewed request ${entry.request_id}.`;
17998
18843
  case "stale":
17999
- return `${sats} was paid to ${entry.endpoint} and the provider never confirmed it. Retries have stopped. If the job never ran, ask the provider to look up request ${entry.request_id}.`;
18844
+ return publicRequestIdOf(entry) ? `${sats} was paid to ${entry.endpoint} and the provider never confirmed it. Retries have stopped. ${locateAdvice(entry)}` : `${sats} was paid to ${entry.endpoint} and the provider never confirmed it. Retries have stopped. If the job never ran, ask the provider to look up request ${entry.request_id}.`;
18845
+ case "accepted_unresolved": {
18846
+ const reclaim = reclaimAt === null ? "" : ` If the provider never redeems the payment, the wallet takes it back after ${new Date(reclaimAt).toISOString()}.`;
18847
+ const readBack = publicRequestIdOf(entry) ? ` ${locateAdvice(entry)}` : "";
18848
+ return `${sats} was paid to ${entry.endpoint} and the provider accepted the call, but did not say clearly which job it started. Automatic retries are off for it so it is never paid twice.${reclaim} The recorded evidence is under ${entry.accepted_unresolved?.ambiguity_id ?? entry.request_id} in \`dvm wallet submissions\`.${readBack}`;
18849
+ }
18000
18850
  case "unresumable":
18001
- return entry.context?.signing_pubkey ? `${sats} was paid to ${entry.endpoint} and the provider never confirmed it. The caller identity that signed the call (${entry.context.signing_pubkey.slice(0, 8)}\u2026) is no longer configured, so it cannot be retried. Quote request ${entry.request_id} to the provider.` : `${sats} was paid to ${entry.endpoint} and the provider never confirmed it. This payment cannot be retried automatically. Quote request ${entry.request_id} to the provider.`;
18851
+ return entry.context?.signing_pubkey ? `${sats} was paid to ${entry.endpoint} and the provider never confirmed it. The caller identity that signed the call (${entry.context.signing_pubkey.slice(0, 8)}\u2026) is no longer configured, so it cannot be retried. Quote request ${publicRequestIdOf(entry) ?? entry.request_id} to the provider.` : `${sats} was paid to ${entry.endpoint} and the provider never confirmed it. This payment cannot be retried automatically. Quote request ${entry.request_id} to the provider.`;
18002
18852
  }
18003
18853
  }
18004
18854
  function formatAge(seconds) {
@@ -18369,13 +19219,18 @@ function fileRowToCheck(row) {
18369
19219
  };
18370
19220
  }
18371
19221
  if (row.modeOk === false) {
19222
+ const offending = row.offendingPaths;
18372
19223
  return {
18373
19224
  name: `file_${row.name}`,
18374
19225
  group: "files",
18375
19226
  status: "warn",
18376
- display: `${row.name} has permissions ${row.modeOctal ?? "?"} (expected 0600).`,
18377
- hint: `Tighten permissions: chmod 600 ${row.path}`,
18378
- details: { path: row.path, modeOctal: row.modeOctal }
19227
+ display: offending ? `${row.name} holds ${String(offending.length)} file(s) with permissions other than 0600 (first: ${row.modeOctal ?? "?"}).` : `${row.name} has permissions ${row.modeOctal ?? "?"} (expected 0600).`,
19228
+ hint: `Tighten permissions: chmod 600 ${offending ? offending.map(shellQuoteArg).join(" ") : row.path}`,
19229
+ details: {
19230
+ path: row.path,
19231
+ modeOctal: row.modeOctal,
19232
+ ...offending ? { offending_paths: offending } : {}
19233
+ }
18379
19234
  };
18380
19235
  }
18381
19236
  return {
@@ -19635,11 +20490,11 @@ async function favRm(name, opts) {
19635
20490
  }
19636
20491
 
19637
20492
  // src/lib/byte-source.ts
19638
- import { readFileSync as readFileSync5 } from "fs";
20493
+ import { readFileSync as readFileSync6 } from "fs";
19639
20494
  import { resolve } from "path";
19640
20495
  var STDIN_TIMEOUT_MS = 1e4;
19641
20496
  function readFileText(path) {
19642
- return readFileSync5(resolve(path), "utf-8");
20497
+ return readFileSync6(resolve(path), "utf-8");
19643
20498
  }
19644
20499
  var StdinTimeoutError = class extends Error {
19645
20500
  constructor(timeoutMs) {
@@ -19803,7 +20658,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
19803
20658
  }
19804
20659
 
19805
20660
  // src/lib/feedback-nudges.ts
19806
- import { existsSync as existsSync5, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "fs";
20661
+ import { existsSync as existsSync6, readFileSync as readFileSync7, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync3 } from "fs";
19807
20662
 
19808
20663
  // src/lib/feedback-notice.ts
19809
20664
  function buildFeedbackNudge(args) {
@@ -19855,10 +20710,10 @@ function effectiveFeedbackPosture(config) {
19855
20710
  return { posture: DEFAULT_FEEDBACK_POSTURE, source: "default" };
19856
20711
  }
19857
20712
  function loadFeedbackNudgeState() {
19858
- if (!existsSync5(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
20713
+ if (!existsSync6(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
19859
20714
  try {
19860
20715
  const parsed = JSON.parse(
19861
- readFileSync6(FEEDBACK_NUDGES_FILE, "utf-8")
20716
+ readFileSync7(FEEDBACK_NUDGES_FILE, "utf-8")
19862
20717
  );
19863
20718
  return {
19864
20719
  ...typeof parsed.introShownAt === "string" ? { introShownAt: parsed.introShownAt } : {},
@@ -19947,12 +20802,12 @@ function coercePerDvm(perDvm) {
19947
20802
  function saveState(state) {
19948
20803
  ensureConfigDir();
19949
20804
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
19950
- writeFileSync2(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
20805
+ writeFileSync3(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
19951
20806
  try {
19952
20807
  renameSync2(tmp, FEEDBACK_NUDGES_FILE);
19953
20808
  } catch (err) {
19954
20809
  try {
19955
- unlinkSync2(tmp);
20810
+ unlinkSync3(tmp);
19956
20811
  } catch {
19957
20812
  }
19958
20813
  throw err;
@@ -19961,9 +20816,9 @@ function saveState(state) {
19961
20816
  var nudgedThisInvocation = false;
19962
20817
 
19963
20818
  // src/lib/platform.ts
19964
- import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
20819
+ import { existsSync as existsSync7, mkdirSync, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
19965
20820
  import { homedir } from "os";
19966
- import { join as join6 } from "path";
20821
+ import { join as join7 } from "path";
19967
20822
  function getPlatformUrl() {
19968
20823
  return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
19969
20824
  }
@@ -20532,16 +21387,16 @@ function finalizeProgressLine() {
20532
21387
  import { randomBytes as randomBytes2 } from "crypto";
20533
21388
  import {
20534
21389
  chmodSync,
20535
- closeSync as closeSync3,
21390
+ closeSync as closeSync4,
20536
21391
  mkdtempSync,
20537
- openSync as openSync3,
20538
- readdirSync as readdirSync4,
21392
+ openSync as openSync4,
21393
+ readdirSync as readdirSync5,
20539
21394
  rmdirSync,
20540
- unlinkSync as unlinkSync3,
20541
- writeFileSync as writeFileSync4
21395
+ unlinkSync as unlinkSync4,
21396
+ writeFileSync as writeFileSync5
20542
21397
  } from "fs";
20543
21398
  import { tmpdir } from "os";
20544
- import { join as join7 } from "path";
21399
+ import { join as join8 } from "path";
20545
21400
 
20546
21401
  // src/lib/mime-ext.ts
20547
21402
  var MIME_TO_EXT = {
@@ -20597,11 +21452,11 @@ var ArtifactSaveSession = class {
20597
21452
  let created = false;
20598
21453
  try {
20599
21454
  const directory = this.ensureDirectory();
20600
- path = join7(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
20601
- fd = openSync3(path, "wx", FILE_MODE);
21455
+ path = join8(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
21456
+ fd = openSync4(path, "wx", FILE_MODE);
20602
21457
  created = true;
20603
- writeFileSync4(fd, buf);
20604
- closeSync3(fd);
21458
+ writeFileSync5(fd, buf);
21459
+ closeSync4(fd);
20605
21460
  fd = void 0;
20606
21461
  chmodSync(path, FILE_MODE);
20607
21462
  this.successfulWrites += 1;
@@ -20609,13 +21464,13 @@ var ArtifactSaveSession = class {
20609
21464
  } catch (err) {
20610
21465
  if (fd !== void 0) {
20611
21466
  try {
20612
- closeSync3(fd);
21467
+ closeSync4(fd);
20613
21468
  } catch {
20614
21469
  }
20615
21470
  }
20616
21471
  if (created && path) {
20617
21472
  try {
20618
- unlinkSync3(path);
21473
+ unlinkSync4(path);
20619
21474
  } catch {
20620
21475
  }
20621
21476
  }
@@ -20626,7 +21481,7 @@ var ArtifactSaveSession = class {
20626
21481
  }
20627
21482
  ensureDirectory() {
20628
21483
  if (this.directory) return this.directory;
20629
- const directory = mkdtempSync(join7(tmpdir(), "dvm-artifacts-"));
21484
+ const directory = mkdtempSync(join8(tmpdir(), "dvm-artifacts-"));
20630
21485
  try {
20631
21486
  chmodSync(directory, DIRECTORY_MODE);
20632
21487
  } catch (err) {
@@ -20642,7 +21497,7 @@ var ArtifactSaveSession = class {
20642
21497
  removeEmptyUnreportedDirectory() {
20643
21498
  if (!this.directory || this.successfulWrites > 0) return;
20644
21499
  try {
20645
- if (readdirSync4(this.directory).length === 0) {
21500
+ if (readdirSync5(this.directory).length === 0) {
20646
21501
  rmdirSync(this.directory);
20647
21502
  this.directory = void 0;
20648
21503
  }
@@ -21407,7 +22262,7 @@ function jsonParseErrorLine(jsonText, err) {
21407
22262
  // src/lib/structured-input-hint.ts
21408
22263
  function expectedFieldsFromSchema(schema) {
21409
22264
  const props = schema.properties;
21410
- if (!isPlainObject(props)) return [];
22265
+ if (!isPlainObject2(props)) return [];
21411
22266
  const requiredList = Array.isArray(schema.required) ? schema.required.filter((x) => typeof x === "string") : [];
21412
22267
  const required = new Set(requiredList);
21413
22268
  const out = [];
@@ -21448,11 +22303,11 @@ function buildStructuredInputHint(opts) {
21448
22303
  if (nextAction) data.next_action = nextAction;
21449
22304
  return { message: message2, hint, data };
21450
22305
  }
21451
- function isPlainObject(value) {
22306
+ function isPlainObject2(value) {
21452
22307
  return typeof value === "object" && value !== null && !Array.isArray(value);
21453
22308
  }
21454
22309
  function jsonSchemaType(node) {
21455
- if (!isPlainObject(node)) return "unknown";
22310
+ if (!isPlainObject2(node)) return "unknown";
21456
22311
  const t = node.type;
21457
22312
  if (typeof t === "string") return t;
21458
22313
  if (Array.isArray(t)) return t.filter((x) => typeof x === "string").join("|") || "unknown";
@@ -21530,16 +22385,16 @@ function findInputSchema(info2, capability) {
21530
22385
  if (capability) {
21531
22386
  const cap2 = info2.capabilities?.[capability];
21532
22387
  if (cap2) {
21533
- if (isPlainObject2(cap2.input_schema)) return cap2.input_schema;
21534
- const quote2 = isPlainObject2(cap2.pricing) ? cap2.pricing.quote : void 0;
21535
- if (isPlainObject2(quote2) && isPlainObject2(quote2.schema)) return quote2.schema;
22388
+ if (isPlainObject3(cap2.input_schema)) return cap2.input_schema;
22389
+ const quote2 = isPlainObject3(cap2.pricing) ? cap2.pricing.quote : void 0;
22390
+ if (isPlainObject3(quote2) && isPlainObject3(quote2.schema)) return quote2.schema;
21536
22391
  }
21537
22392
  }
21538
- if (isPlainObject2(info2.inputSchema)) return info2.inputSchema;
21539
- if (info2.quote && isPlainObject2(info2.quote.schema)) return info2.quote.schema;
22393
+ if (isPlainObject3(info2.inputSchema)) return info2.inputSchema;
22394
+ if (info2.quote && isPlainObject3(info2.quote.schema)) return info2.quote.schema;
21540
22395
  return void 0;
21541
22396
  }
21542
- function isPlainObject2(value) {
22397
+ function isPlainObject3(value) {
21543
22398
  return typeof value === "object" && value !== null && !Array.isArray(value);
21544
22399
  }
21545
22400
 
@@ -22088,7 +22943,7 @@ function buildPolicy(opts, btcRate) {
22088
22943
  }
22089
22944
 
22090
22945
  // src/commands/request.ts
22091
- import { createHash as createHash2, randomUUID as randomUUID3 } from "crypto";
22946
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
22092
22947
 
22093
22948
  // src/lib/credit-defer.ts
22094
22949
  function noteDeferredFunding(funding) {
@@ -22121,7 +22976,7 @@ async function settleCreditAfterJob(args) {
22121
22976
  }
22122
22977
  }
22123
22978
  if (args.allowTopup !== false) {
22124
- const refill = args.refillPocket ?? (await import("./pocket-refill-J5OWRBXH.js")).refillPocketIfLow;
22979
+ const refill = args.refillPocket ?? (await import("./pocket-refill-YY55GISB.js")).refillPocketIfLow;
22125
22980
  await refill({ human: args.human }).catch(() => void 0);
22126
22981
  }
22127
22982
  }
@@ -22602,16 +23457,16 @@ function dollarLimitMicro(declaredLimit) {
22602
23457
 
22603
23458
  // src/lib/request-intent-store.ts
22604
23459
  import {
22605
- closeSync as closeSync4,
22606
- existsSync as existsSync7,
22607
- fsyncSync as fsyncSync2,
23460
+ closeSync as closeSync5,
23461
+ existsSync as existsSync8,
23462
+ fsyncSync as fsyncSync3,
22608
23463
  mkdirSync as mkdirSync2,
22609
- openSync as openSync4,
22610
- readFileSync as readFileSync8,
23464
+ openSync as openSync5,
23465
+ readFileSync as readFileSync9,
22611
23466
  renameSync as renameSync3,
22612
- writeFileSync as writeFileSync5
23467
+ writeFileSync as writeFileSync6
22613
23468
  } from "fs";
22614
- import { join as join8 } from "path";
23469
+ import { join as join9 } from "path";
22615
23470
  function saveRequestIntent(intent) {
22616
23471
  assertRequestId(intent.requestId);
22617
23472
  assertNoPaymentOrAuthSecrets(intent.body);
@@ -22623,27 +23478,27 @@ function saveRequestIntent(intent) {
22623
23478
  if (error.code === "EEXIST") return false;
22624
23479
  throw error;
22625
23480
  }
22626
- fsyncDirectory2(REQUEST_INTENTS_DIR);
22627
- const temp = join8(dir, `intent.${String(process.pid)}.tmp`);
22628
- const target = join8(dir, "intent.json");
22629
- const fd = openSync4(temp, "wx", 384);
23481
+ fsyncDirectory3(REQUEST_INTENTS_DIR);
23482
+ const temp = join9(dir, `intent.${String(process.pid)}.tmp`);
23483
+ const target = join9(dir, "intent.json");
23484
+ const fd = openSync5(temp, "wx", 384);
22630
23485
  try {
22631
- writeFileSync5(fd, JSON.stringify(intent, null, 2) + "\n");
22632
- fsyncSync2(fd);
23486
+ writeFileSync6(fd, JSON.stringify(intent, null, 2) + "\n");
23487
+ fsyncSync3(fd);
22633
23488
  } finally {
22634
- closeSync4(fd);
23489
+ closeSync5(fd);
22635
23490
  }
22636
23491
  renameSync3(temp, target);
22637
- fsyncDirectory2(dir);
23492
+ fsyncDirectory3(dir);
22638
23493
  return true;
22639
23494
  }
22640
23495
  function loadRequestIntent(requestId) {
22641
23496
  assertRequestId(requestId);
22642
23497
  const dir = intentDirectory(requestId);
22643
- if (!existsSync7(dir)) return null;
22644
- const path = join8(dir, "intent.json");
23498
+ if (!existsSync8(dir)) return null;
23499
+ const path = join9(dir, "intent.json");
22645
23500
  try {
22646
- const parsed = JSON.parse(readFileSync8(path, "utf8"));
23501
+ const parsed = JSON.parse(readFileSync9(path, "utf8"));
22647
23502
  if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
22648
23503
  throw new Error("invalid shape");
22649
23504
  return parsed;
@@ -22693,15 +23548,15 @@ function assertRequestId(requestId) {
22693
23548
  );
22694
23549
  }
22695
23550
  function intentDirectory(requestId) {
22696
- return join8(REQUEST_INTENTS_DIR, requestId);
23551
+ return join9(REQUEST_INTENTS_DIR, requestId);
22697
23552
  }
22698
- function fsyncDirectory2(path) {
23553
+ function fsyncDirectory3(path) {
22699
23554
  let fd;
22700
23555
  try {
22701
- fd = openSync4(path, "r");
22702
- fsyncSync2(fd);
23556
+ fd = openSync5(path, "r");
23557
+ fsyncSync3(fd);
22703
23558
  } finally {
22704
- if (fd !== void 0) closeSync4(fd);
23559
+ if (fd !== void 0) closeSync5(fd);
22705
23560
  }
22706
23561
  }
22707
23562
  function isRequestIntent(value) {
@@ -23153,6 +24008,7 @@ async function request(opts) {
23153
24008
  );
23154
24009
  let signing;
23155
24010
  let probePlan = { mode: "none" };
24011
+ let drawRequestId;
23156
24012
  if (opts.requestId && !providerInfo.auth?.includes(SIGNED_REQUEST_AUTH_ID)) {
23157
24013
  transport.close();
23158
24014
  throw new DvmError(
@@ -23219,7 +24075,15 @@ async function request(opts) {
23219
24075
  if (probePlan.mode === "draw" && opts.requestId) {
23220
24076
  probePlan = { ...probePlan, drawId: opts.requestId };
23221
24077
  }
23222
- const probeData = probePlan.mode === "draw" ? { ...unsignedData, credit_id: probePlan.creditId, draw_id: probePlan.drawId } : unsignedData;
24078
+ if (probePlan.mode === "draw" && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing })) {
24079
+ drawRequestId = randomUUID4();
24080
+ }
24081
+ const probeData = probePlan.mode === "draw" ? {
24082
+ ...unsignedData,
24083
+ credit_id: probePlan.creditId,
24084
+ draw_id: probePlan.drawId,
24085
+ ...drawRequestId ? { request_id: drawRequestId } : {}
24086
+ } : unsignedData;
23223
24087
  data = signDvmRequestData(signer.privkey, probeData, authDomain);
23224
24088
  if (opts.human) info(`Signed as ${signer.pubkey}.`);
23225
24089
  if (opts.human && probePlan.mode === "draw") {
@@ -23247,78 +24111,63 @@ async function request(opts) {
23247
24111
  outputType: opts.outputType,
23248
24112
  bidMsats: budgetMsats
23249
24113
  });
23250
- if (opts.requestId) {
23251
- const unsigned = unsignRequestData(envelope.data);
23252
- if (!signing || unsigned?.pubkey !== signing.pubkey) {
23253
- transport.close();
23254
- throw new DvmError(
23255
- "request_intent_invalid",
23256
- "Could not persist an authenticated recovery intent.",
23257
- "No payment was attempted. Check the selected caller identity and retry with a fresh request id."
23258
- );
23259
- }
23260
- const body = envelopeToPayload(envelope);
23261
- body.data = unsigned.body;
23262
- const saved = saveRequestIntent({
23263
- v: 2,
23264
- requestId: opts.requestId,
24114
+ let jobRequestId = opts.requestId ?? drawRequestId;
24115
+ if (jobRequestId) {
24116
+ persistRequestIntent({
24117
+ requestId: jobRequestId,
24118
+ transport,
24119
+ envelope,
24120
+ signing,
23265
24121
  endpoint,
23266
- ...dvmId ? { dvmId } : {},
23267
- capability,
23268
- body,
23269
- callerPubkey: signing.pubkey,
24122
+ identity,
23270
24123
  policy,
23271
- ...opts.mint ? { pinnedMint: opts.mint } : {},
23272
- ...opts.strictPerCall ? { strictPerCall: true } : {},
23273
- ...requestedMaxCashuFeeSats !== void 0 ? { maxCashuFeeSats: requestedMaxCashuFeeSats } : {},
23274
- ...receiptTrustFields(providerInfo),
23275
- authAudience: signing.domain.audience,
23276
- createdAt: Date.now()
24124
+ opts,
24125
+ providerInfo
23277
24126
  });
23278
- if (!saved) {
23279
- transport.close();
23280
- throw new DvmError(
23281
- "request_id_exists",
23282
- `Request id ${opts.requestId} already has a local intent.`,
23283
- `Run 'dvm request-result ${opts.requestId}'. Never submit or pay for a replacement under the same id.`,
23284
- { request_id: opts.requestId, status: "unknown" }
23285
- );
23286
- }
23287
24127
  }
23288
24128
  progressNotice("Publishing job request...", opts.human);
23289
24129
  const usedPrimitiveInput = !!opts.input && !opts.data && !hasParams;
23290
- const submitProbe = (env) => withInputSchemaHint(
23291
- transport,
23292
- ref,
23293
- {
23294
- capability,
23295
- identifier,
23296
- command: "request",
23297
- usedPrimitiveInput,
23298
- primitiveInput: opts.input,
23299
- callerRef,
23300
- callerFlag: opts.dvm ? "dvm" : "endpoint"
23301
- },
23302
- () => transport.submit(ref, env, void 0, {
23303
- timeoutMs: noStream ? 0 : timeout
23304
- })
23305
- );
24130
+ const submitProbe = async (env) => {
24131
+ try {
24132
+ return await withInputSchemaHint(
24133
+ transport,
24134
+ ref,
24135
+ {
24136
+ capability,
24137
+ identifier,
24138
+ command: "request",
24139
+ usedPrimitiveInput,
24140
+ primitiveInput: opts.input,
24141
+ callerRef,
24142
+ callerFlag: opts.dvm ? "dvm" : "endpoint"
24143
+ },
24144
+ () => transport.submit(ref, env, void 0, {
24145
+ timeoutMs: noStream ? 0 : timeout
24146
+ })
24147
+ );
24148
+ } catch (err) {
24149
+ if (!isIdentityFailure(err)) throw err;
24150
+ const publicRequestId = opts.requestId ?? envelopeRequestId(env);
24151
+ throw recordIdentityFailure(err, {
24152
+ endpoint,
24153
+ ...dvmId ? { dvmId } : {},
24154
+ capability,
24155
+ ...publicRequestId ? { publicRequestId } : {},
24156
+ ...probeRailEvidence(env)
24157
+ }).error;
24158
+ }
24159
+ };
23306
24160
  let receipt;
23307
24161
  try {
23308
24162
  receipt = await submitProbe(envelope);
23309
24163
  } catch (err) {
23310
24164
  if (opts.requestId) {
23311
24165
  transport.close();
23312
- throw new DvmError(
23313
- "request_outcome_unknown",
23314
- `The provider did not return a definitive result for request ${opts.requestId}.`,
23315
- `Run 'dvm request-result ${opts.requestId}'. This lookup cannot submit a job or repeat a payment.`,
23316
- {
23317
- request_id: opts.requestId,
23318
- status: "unknown",
23319
- cause: err instanceof Error ? err.message : String(err)
23320
- }
23321
- );
24166
+ throw requestOutcomeUnknown(opts.requestId, err);
24167
+ }
24168
+ if (drawRequestId && outcomeUnknownAfterSubmit(err)) {
24169
+ transport.close();
24170
+ throw requestOutcomeUnknown(drawRequestId, err);
23322
24171
  }
23323
24172
  if (opts.creditOnly) throw err;
23324
24173
  if (probePlan.mode !== "draw" || !signing || !(err instanceof DvmError)) throw err;
@@ -23346,6 +24195,7 @@ async function request(opts) {
23346
24195
  receipt = recovered.receipt;
23347
24196
  envelope = recovered.envelope;
23348
24197
  probePlan = recovered.plan;
24198
+ jobRequestId = recovered.requestId;
23349
24199
  }
23350
24200
  if (receipt.status === "payment-required") {
23351
24201
  const quotes = receipt.quotes ?? [];
@@ -23402,7 +24252,7 @@ async function request(opts) {
23402
24252
  dvmId,
23403
24253
  feedbackClaim: receipt.feedbackClaim,
23404
24254
  capability,
23405
- requestId: opts.requestId,
24255
+ requestId: jobRequestId,
23406
24256
  status: "submitted",
23407
24257
  submittedAt: Date.now(),
23408
24258
  policy,
@@ -23431,7 +24281,7 @@ async function request(opts) {
23431
24281
  } else {
23432
24282
  json({
23433
24283
  jobId: receipt.jobId,
23434
- ...requestIdOutputFields(opts),
24284
+ ...requestIdOutputFields(jobRequestId),
23435
24285
  ...transactionOutputFields(receipt),
23436
24286
  ...dvmIdentity(dvmId, capability),
23437
24287
  // mirror `dvm quote`'s post-defaults diagnostic on the
@@ -23485,7 +24335,7 @@ async function request(opts) {
23485
24335
  } else {
23486
24336
  json({
23487
24337
  jobId: receipt.jobId,
23488
- ...requestIdOutputFields(opts),
24338
+ ...requestIdOutputFields(jobRequestId),
23489
24339
  ...transactionOutputFields(receipt),
23490
24340
  ...dvmIdentity(dvmId, capability),
23491
24341
  summary: receipt.summary,
@@ -23560,7 +24410,7 @@ async function request(opts) {
23560
24410
  } else {
23561
24411
  json({
23562
24412
  jobId: receipt.jobId,
23563
- ...requestIdOutputFields(opts),
24413
+ ...requestIdOutputFields(jobRequestId),
23564
24414
  ...transactionOutputFields(receipt),
23565
24415
  ...dvmIdentity(dvmId, capability),
23566
24416
  messages: result.messages.map(serializeMessageForOutput),
@@ -23629,7 +24479,7 @@ function identityArgs(identity) {
23629
24479
  return identity ? { identity } : {};
23630
24480
  }
23631
24481
  function sha256Hex(value) {
23632
- return createHash2("sha256").update(value, "utf8").digest("hex");
24482
+ return createHash3("sha256").update(value, "utf8").digest("hex");
23633
24483
  }
23634
24484
  async function fetchServerPriceMicro(transport, ref, envelope) {
23635
24485
  try {
@@ -23782,12 +24632,43 @@ async function recoverDrawProbe(err, args) {
23782
24632
  const plan = {
23783
24633
  mode: "draw",
23784
24634
  creditId: args.probePlan.creditId,
23785
- drawId: randomUUID3(),
24635
+ drawId: randomUUID4(),
23786
24636
  ...args.probePlan.source ? { source: args.probePlan.source } : {}
23787
24637
  };
23788
- const env = reSign({ credit_id: plan.creditId, draw_id: plan.drawId });
23789
- const receipt = await args.submitProbe(env);
23790
- return { done: false, receipt, envelope: env, plan };
24638
+ const requestId = submitCanCarryGeneratedRequestId({
24639
+ opts: args.opts,
24640
+ providerInfo: args.providerInfo,
24641
+ signing
24642
+ }) ? randomUUID4() : void 0;
24643
+ const env = reSign({
24644
+ credit_id: plan.creditId,
24645
+ draw_id: plan.drawId,
24646
+ ...requestId ? { request_id: requestId } : {}
24647
+ });
24648
+ if (requestId) {
24649
+ persistRequestIntent({
24650
+ requestId,
24651
+ transport: args.transport,
24652
+ envelope: env,
24653
+ signing,
24654
+ endpoint: args.endpoint,
24655
+ identity: args.identity,
24656
+ policy: args.policy,
24657
+ opts: args.opts,
24658
+ providerInfo: args.providerInfo
24659
+ });
24660
+ }
24661
+ let receipt;
24662
+ try {
24663
+ receipt = await args.submitProbe(env);
24664
+ } catch (retryErr) {
24665
+ if (requestId && outcomeUnknownAfterSubmit(retryErr)) {
24666
+ args.transport.close?.();
24667
+ throw requestOutcomeUnknown(requestId, retryErr);
24668
+ }
24669
+ throw retryErr;
24670
+ }
24671
+ return { done: false, receipt, envelope: env, plan, ...requestId ? { requestId } : {} };
23791
24672
  }
23792
24673
  if (err.code === "insufficient_credit") {
23793
24674
  if (args.probePlan.source === "implicit") {
@@ -24062,62 +24943,96 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
24062
24943
  info("Credit funding is Cashu-only for now \u2014 paying per-call on the selected rail.");
24063
24944
  plan = { mode: "none" };
24064
24945
  }
24946
+ let railEnvelope = plainEnvelope;
24947
+ let railOpts = opts;
24948
+ let railSigning = creditCtx?.signing;
24949
+ let generatedRequestId;
24950
+ if (plan.mode === "none" && railSigning && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing: railSigning })) {
24951
+ generatedRequestId = randomUUID4();
24952
+ railSigning = {
24953
+ ...railSigning,
24954
+ unsignedData: { ...railSigning.unsignedData, request_id: generatedRequestId }
24955
+ };
24956
+ railEnvelope = {
24957
+ ...plainEnvelope,
24958
+ data: signDvmRequestData(railSigning.privkey, railSigning.unsignedData, railSigning.domain)
24959
+ };
24960
+ railOpts = { ...opts, requestId: generatedRequestId };
24961
+ persistRequestIntent({
24962
+ requestId: generatedRequestId,
24963
+ transport,
24964
+ envelope: railEnvelope,
24965
+ signing: railSigning,
24966
+ endpoint: ref.endpoint,
24967
+ identity,
24968
+ policy,
24969
+ opts: railOpts,
24970
+ providerInfo
24971
+ });
24972
+ }
24065
24973
  let cashuFellThroughCode;
24066
- for (const rail of selection.rails) {
24067
- if (rail === "cashu_p2pk") {
24068
- const outcome = await tryAgentWalletPayment(
24069
- transport,
24070
- ref,
24071
- plainEnvelope,
24072
- jobId,
24073
- deadlineMs,
24074
- chosen,
24075
- opts,
24076
- identity,
24077
- policy,
24078
- upfrontBtcRate,
24079
- providerInfo,
24080
- plan,
24081
- creditCtx?.signing
24082
- );
24083
- if (outcome.handled) return;
24084
- cashuFellThroughCode = outcome.fellThroughCode ?? cashuFellThroughCode;
24085
- } else if (rail === "tempo" && tempoAccount) {
24086
- const handled = await tryTempoPayment({
24087
- transport,
24088
- ref,
24089
- envelope: plainEnvelope,
24090
- jobId,
24091
- deadlineMs,
24092
- chosen,
24093
- quotes,
24094
- opts,
24095
- identity,
24096
- policy,
24097
- btcRate: upfrontBtcRate,
24098
- account: tempoAccount,
24099
- providerInfo,
24100
- signing: creditCtx?.signing
24101
- });
24102
- if (handled) return;
24103
- } else if (rail === "x402" && x402Wallet) {
24104
- const handled = await tryX402UpfrontPayment({
24105
- transport,
24106
- ref,
24107
- envelope: plainEnvelope,
24108
- jobId,
24109
- deadlineMs,
24110
- chosen,
24111
- opts,
24112
- identity,
24113
- policy,
24114
- btcRate: upfrontBtcRate,
24115
- wallet: x402Wallet,
24116
- providerInfo,
24117
- signing: creditCtx?.signing
24118
- });
24119
- if (handled) return;
24974
+ try {
24975
+ for (const rail of selection.rails) {
24976
+ if (rail === "cashu_p2pk") {
24977
+ const outcome = await tryAgentWalletPayment(
24978
+ transport,
24979
+ ref,
24980
+ railEnvelope,
24981
+ jobId,
24982
+ deadlineMs,
24983
+ chosen,
24984
+ railOpts,
24985
+ identity,
24986
+ policy,
24987
+ upfrontBtcRate,
24988
+ providerInfo,
24989
+ plan,
24990
+ railSigning
24991
+ );
24992
+ if (outcome.handled) return;
24993
+ cashuFellThroughCode = outcome.fellThroughCode ?? cashuFellThroughCode;
24994
+ } else if (rail === "tempo" && tempoAccount) {
24995
+ const handled = await tryTempoPayment({
24996
+ transport,
24997
+ ref,
24998
+ envelope: railEnvelope,
24999
+ jobId,
25000
+ deadlineMs,
25001
+ chosen,
25002
+ quotes,
25003
+ opts: railOpts,
25004
+ identity,
25005
+ policy,
25006
+ btcRate: upfrontBtcRate,
25007
+ account: tempoAccount,
25008
+ providerInfo,
25009
+ signing: railSigning
25010
+ });
25011
+ if (handled) return;
25012
+ } else if (rail === "x402" && x402Wallet) {
25013
+ const handled = await tryX402UpfrontPayment({
25014
+ transport,
25015
+ ref,
25016
+ envelope: railEnvelope,
25017
+ jobId,
25018
+ deadlineMs,
25019
+ chosen,
25020
+ opts: railOpts,
25021
+ identity,
25022
+ policy,
25023
+ btcRate: upfrontBtcRate,
25024
+ wallet: x402Wallet,
25025
+ providerInfo,
25026
+ signing: railSigning
25027
+ });
25028
+ if (handled) return;
25029
+ }
25030
+ }
25031
+ } catch (error) {
25032
+ if (generatedRequestId && leavesOutcomeUnknown(error)) {
25033
+ throw requestOutcomeUnknown(generatedRequestId, error);
24120
25034
  }
25035
+ throw error;
24121
25036
  }
24122
25037
  transport.close?.();
24123
25038
  if (cashuFellThroughCode && agentWallet) {
@@ -24275,7 +25190,7 @@ async function payWithTempo(args, credential) {
24275
25190
  } else {
24276
25191
  json({
24277
25192
  ...dvmFields,
24278
- ...requestIdOutputFields(opts),
25193
+ ...requestIdOutputFields(opts.requestId),
24279
25194
  status: "paying",
24280
25195
  rail: "tempo",
24281
25196
  account: account.address,
@@ -24284,12 +25199,44 @@ async function payWithTempo(args, credential) {
24284
25199
  display: `Paying ${priceLabel} via Tempo (account ${accountShort}).`
24285
25200
  });
24286
25201
  }
24287
- const receipt = await transport.submit(
24288
- ref,
24289
- envelope,
24290
- { mppCredential: credential },
24291
- { timeoutMs: paidSubmitTimeoutMs(args.deadlineMs) }
24292
- );
25202
+ let receipt;
25203
+ try {
25204
+ receipt = await transport.submit(
25205
+ ref,
25206
+ envelope,
25207
+ { mppCredential: credential },
25208
+ { timeoutMs: paidSubmitTimeoutMs(args.deadlineMs) }
25209
+ );
25210
+ } catch (err) {
25211
+ const unconfirmed = (key) => recordUnconfirmedSpend({
25212
+ msats: paidMsats,
25213
+ btcRate,
25214
+ key,
25215
+ endpoint: ref.endpoint,
25216
+ capability: identity.capability
25217
+ });
25218
+ if (!isIdentityFailure(err)) {
25219
+ if (leavesOutcomeUnknown(raisedAfterPayment(err))) {
25220
+ unconfirmed(unconfirmedSpendKey(opts, err));
25221
+ }
25222
+ throw err;
25223
+ }
25224
+ transport.close?.();
25225
+ const { error } = recordIdentityFailure(err, {
25226
+ endpoint: ref.endpoint,
25227
+ ...identity.dvmId ? { dvmId: identity.dvmId } : {},
25228
+ capability: identity.capability,
25229
+ ...opts.requestId ? { publicRequestId: opts.requestId } : {},
25230
+ rail: "tempo",
25231
+ railCorrelation: {
25232
+ account: account.address,
25233
+ amount_usdc_micro: usdcMicroUnits,
25234
+ ...err.observation.transactionHash ? { transaction_hash: err.observation.transactionHash } : {}
25235
+ }
25236
+ });
25237
+ unconfirmed(unconfirmedSpendKey(opts, error));
25238
+ throw error;
25239
+ }
24293
25240
  const effectiveJobId = args.jobId || receipt.jobId;
24294
25241
  if (!args.jobId && receipt.jobId) {
24295
25242
  saveJob({
@@ -24368,7 +25315,7 @@ async function payWithTempo(args, credential) {
24368
25315
  } else {
24369
25316
  json({
24370
25317
  jobId: effectiveJobId,
24371
- ...requestIdOutputFields(opts),
25318
+ ...requestIdOutputFields(opts.requestId),
24372
25319
  ...transactionOutputFields(receipt),
24373
25320
  ...dvmFields,
24374
25321
  summary: receipt.summary,
@@ -24398,7 +25345,7 @@ async function payWithTempo(args, credential) {
24398
25345
  paymentFields: {
24399
25346
  paidWith: "tempo",
24400
25347
  account: account.address,
24401
- ...requestIdOutputFields(opts),
25348
+ ...requestIdOutputFields(opts.requestId),
24402
25349
  ...transactionOutputFields(receipt)
24403
25350
  },
24404
25351
  dvmFields,
@@ -24419,21 +25366,124 @@ function transactionOutputFields(receipt) {
24419
25366
  ...receipt.transactionHash ? { transaction_hash: receipt.transactionHash } : {}
24420
25367
  };
24421
25368
  }
24422
- function requestIdOutputFields(opts) {
24423
- return opts.requestId ? { request_id: opts.requestId } : {};
25369
+ function persistRequestIntent(args) {
25370
+ const { requestId, transport, signing, opts } = args;
25371
+ const unsigned = unsignRequestData(args.envelope.data);
25372
+ if (!signing || unsigned?.pubkey !== signing.pubkey) {
25373
+ transport.close?.();
25374
+ throw new DvmError(
25375
+ "request_intent_invalid",
25376
+ "Could not persist an authenticated recovery intent.",
25377
+ "No payment was attempted. Check the selected caller identity and retry with a fresh request id."
25378
+ );
25379
+ }
25380
+ const body = envelopeToPayload(args.envelope);
25381
+ body.data = unsigned.body;
25382
+ const maxCashuFeeSats = parseMaxCashuFeeSats(opts.maxCashuFeeSats);
25383
+ const saved = saveRequestIntent({
25384
+ v: 2,
25385
+ requestId,
25386
+ endpoint: args.endpoint,
25387
+ ...args.identity.dvmId ? { dvmId: args.identity.dvmId } : {},
25388
+ capability: args.identity.capability,
25389
+ body,
25390
+ callerPubkey: signing.pubkey,
25391
+ policy: args.policy,
25392
+ ...opts.mint ? { pinnedMint: opts.mint } : {},
25393
+ ...opts.strictPerCall ? { strictPerCall: true } : {},
25394
+ ...maxCashuFeeSats !== void 0 ? { maxCashuFeeSats } : {},
25395
+ ...receiptTrustFields(args.providerInfo),
25396
+ authAudience: signing.domain.audience,
25397
+ createdAt: Date.now()
25398
+ });
25399
+ if (!saved) {
25400
+ transport.close?.();
25401
+ throw new DvmError(
25402
+ "request_id_exists",
25403
+ `Request id ${requestId} already has a local intent.`,
25404
+ `Run 'dvm request-result ${requestId}'. Never submit or pay for a replacement under the same id.`,
25405
+ { request_id: requestId, status: "unknown" }
25406
+ );
25407
+ }
25408
+ }
25409
+ function submitCanCarryGeneratedRequestId(args) {
25410
+ return args.opts.requestId === void 0 && args.opts.creditOnly === void 0 && args.providerInfo.requestRecovery === true && args.providerInfo.auth?.includes(SIGNED_REQUEST_AUTH_ID) === true && args.signing !== void 0;
25411
+ }
25412
+ function outcomeUnknownAfterSubmit(err) {
25413
+ if (isIdentityFailure(err)) return true;
25414
+ return err instanceof DvmError && POST_PAYMENT_UNKNOWN_CODES.has(err.code);
25415
+ }
25416
+ function leavesOutcomeUnknown(err) {
25417
+ if (isIdentityFailure(err)) return true;
25418
+ return err instanceof DvmError && postPaymentErrors.has(err) && POST_PAYMENT_UNKNOWN_CODES.has(err.code);
25419
+ }
25420
+ var POST_PAYMENT_UNKNOWN_CODES = /* @__PURE__ */ new Set(["timeout", "provider_unreachable", "request_id_exists"]);
25421
+ var postPaymentErrors = /* @__PURE__ */ new WeakSet();
25422
+ function raisedAfterPayment(err) {
25423
+ if (err !== null && typeof err === "object") postPaymentErrors.add(err);
25424
+ return err;
25425
+ }
25426
+ function recordUnconfirmedSpend(args) {
25427
+ recordSpendOnce({
25428
+ msats: args.msats,
25429
+ btcRate: args.btcRate,
25430
+ jobId: args.key ?? `unconfirmed-${randomUUID4()}`,
25431
+ providerEndpoint: args.endpoint,
25432
+ label: `unconfirmed \xB7 ${args.capability}`
25433
+ });
25434
+ }
25435
+ function unconfirmedSpendKey(opts, err) {
25436
+ if (opts.requestId) return opts.requestId;
25437
+ return typeof err.data?.ambiguity_id === "string" ? err.data.ambiguity_id : void 0;
25438
+ }
25439
+ function probeRailEvidence(env) {
25440
+ const body = unsignRequestData(env.data)?.body;
25441
+ const creditId = typeof body?.credit_id === "string" ? body.credit_id : void 0;
25442
+ const drawId = typeof body?.draw_id === "string" ? body.draw_id : void 0;
25443
+ if (!creditId) return { rail: "none" };
25444
+ return {
25445
+ rail: "credit",
25446
+ railCorrelation: { credit_id: creditId, ...drawId ? { draw_id: drawId } : {} }
25447
+ };
25448
+ }
25449
+ function envelopeRequestId(env) {
25450
+ const requestId = unsignRequestData(env.data)?.body?.request_id;
25451
+ return typeof requestId === "string" ? requestId : void 0;
25452
+ }
25453
+ function requestIdOutputFields(requestId) {
25454
+ return requestId ? { request_id: requestId } : {};
24424
25455
  }
24425
25456
  function normalizedLocalCorrelationId(opts) {
24426
25457
  return opts.localCorrelationId === void 0 ? void 0 : normalizeLocalCorrelationId(opts.localCorrelationId);
24427
25458
  }
24428
25459
  function requestOutcomeUnknown(requestId, cause) {
25460
+ const ambiguityId = isIdentityFailure(cause) && typeof cause.data?.ambiguity_id === "string" ? cause.data.ambiguity_id : void 0;
24429
25461
  return new DvmError(
24430
25462
  "request_outcome_unknown",
24431
25463
  `The provider did not return a definitive result for request ${requestId}.`,
24432
- `Run 'dvm request-result ${requestId}'. This lookup cannot submit a job or repeat a payment.`,
25464
+ `Run 'dvm request-result ${requestId}'. This lookup cannot submit a job or repeat a payment.${ambiguityId ? ` Do not pay for this request again; 'dvm wallet submissions' shows the recorded evidence (${ambiguityId}).` : ""}`,
24433
25465
  {
24434
25466
  request_id: requestId,
24435
25467
  status: "unknown",
24436
- cause: cause instanceof Error ? cause.message : String(cause)
25468
+ cause: cause instanceof Error ? cause.message : String(cause),
25469
+ ...cause instanceof DvmError ? { inner_code: cause.code } : {},
25470
+ ...isIdentityFailure(cause) ? {
25471
+ identity_kind: cause.observation.kind,
25472
+ ...identityDataFields(cause.observation),
25473
+ ...ambiguityId ? { ambiguity_id: ambiguityId } : {},
25474
+ ...typeof cause.data?.cashu_request_id === "string" ? { cashu_request_id: cause.data.cashu_request_id } : {},
25475
+ claim_stored: false
25476
+ } : {},
25477
+ // A Cashu payment already sent is held in the wallet journal under its
25478
+ // own request ID; keep that context rather than letting the public ID
25479
+ // replace it.
25480
+ ...cause instanceof DvmError && cause.data?.spend_committed === true ? {
25481
+ spend_committed: true,
25482
+ ...typeof cause.data.cashu_request_id === "string" ? { cashu_request_id: cause.data.cashu_request_id } : {},
25483
+ ...typeof cause.data.mint === "string" ? { mint: cause.data.mint } : {},
25484
+ ...typeof cause.data.amount_sats === "number" ? { amount_sats: cause.data.amount_sats } : {},
25485
+ ...typeof cause.data.display === "string" ? { display: cause.data.display } : {}
25486
+ } : {}
24437
25487
  }
24438
25488
  );
24439
25489
  }
@@ -24485,10 +25535,20 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
24485
25535
  builderHandle = void 0;
24486
25536
  }
24487
25537
  const spendStartedMs = Date.now();
24488
- let finalEnvelope = envelope;
25538
+ const generatedRequestId = fundPlan && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing }) ? randomUUID4() : void 0;
25539
+ const withGeneratedRequestId = (unsigned) => generatedRequestId ? { ...unsigned, request_id: generatedRequestId } : unsigned;
25540
+ const perCallEnvelope = generatedRequestId && signing ? {
25541
+ ...envelope,
25542
+ data: signDvmRequestData(
25543
+ signing.privkey,
25544
+ withGeneratedRequestId(signing.unsignedData),
25545
+ signing.domain
25546
+ )
25547
+ } : envelope;
25548
+ let finalEnvelope = perCallEnvelope;
24489
25549
  const buildPrepareArgs = () => {
24490
25550
  const activeFund = fundPlan;
24491
- const fundData = activeFund && signing ? {
25551
+ const fundData = activeFund && signing ? withGeneratedRequestId({
24492
25552
  ...signing.unsignedData,
24493
25553
  credit_id: activeFund.creditId,
24494
25554
  draw_id: activeFund.drawId,
@@ -24496,7 +25556,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
24496
25556
  amount_micro: activeFund.wireAmountMicro ?? activeFund.fundMicro,
24497
25557
  commitment: ""
24498
25558
  }
24499
- } : null;
25559
+ }) : null;
24500
25560
  const payload = envelopeToPayload(envelope);
24501
25561
  return {
24502
25562
  amountSats: activeFund ? activeFund.fundSats : priceSats,
@@ -24519,14 +25579,14 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
24519
25579
  submit_body: { ...payload, data: fundData },
24520
25580
  signing_pubkey: signing.pubkey,
24521
25581
  ...baseContext
24522
- } : { ...resumableSubmitBody(envelope, providerInfo), ...baseContext }
25582
+ } : { ...resumableSubmitBody(perCallEnvelope, providerInfo), ...baseContext }
24523
25583
  };
24524
25584
  };
24525
25585
  let prepared = await prepareAgentSpend(buildPrepareArgs());
24526
25586
  if ("error" in prepared && fundPlan && prepared.error.code === "insufficient_balance" && fundPlan.fundSats > priceSats) {
24527
25587
  info("Wallet balance can't cover the credit funding \u2014 paying this job per-call.");
24528
25588
  fundPlan = void 0;
24529
- finalEnvelope = envelope;
25589
+ finalEnvelope = perCallEnvelope;
24530
25590
  prepared = await prepareAgentSpend(buildPrepareArgs());
24531
25591
  }
24532
25592
  if ("error" in prepared) {
@@ -24556,7 +25616,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
24556
25616
  ...envelope,
24557
25617
  data: signDvmRequestData(
24558
25618
  signing.privkey,
24559
- {
25619
+ withGeneratedRequestId({
24560
25620
  ...signing.unsignedData,
24561
25621
  credit_id: fundPlan.creditId,
24562
25622
  draw_id: fundPlan.drawId,
@@ -24564,11 +25624,24 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
24564
25624
  amount_micro: fundPlan.wireAmountMicro ?? fundPlan.fundMicro,
24565
25625
  commitment: sha256Hex(prepared.cashuToken)
24566
25626
  }
24567
- },
25627
+ }),
24568
25628
  signing.domain
24569
25629
  )
24570
25630
  };
24571
25631
  }
25632
+ if (generatedRequestId) {
25633
+ persistRequestIntent({
25634
+ requestId: generatedRequestId,
25635
+ transport,
25636
+ envelope: finalEnvelope,
25637
+ signing,
25638
+ endpoint: ref.endpoint,
25639
+ identity,
25640
+ policy,
25641
+ opts,
25642
+ providerInfo
25643
+ });
25644
+ }
24572
25645
  if (fundPlan && signing) {
24573
25646
  ensureProvisionalCredit({
24574
25647
  endpoint: ref.endpoint,
@@ -24609,7 +25682,8 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
24609
25682
  providerInfo,
24610
25683
  btcRate,
24611
25684
  fundPlan,
24612
- signing
25685
+ signing,
25686
+ generatedRequestId
24613
25687
  );
24614
25688
  return { handled: true };
24615
25689
  }
@@ -24624,28 +25698,32 @@ function resumableSubmitBody(envelope, providerInfo) {
24624
25698
  if (!signed) return { submit_body: payload };
24625
25699
  return { submit_body: { ...payload, data: signed.body }, signing_pubkey: signed.pubkey };
24626
25700
  }
24627
- function withSpentSpendContext(err, prepared) {
25701
+ function withSpentSpendContext(err, prepared, publicRequestId) {
24628
25702
  if (!(err instanceof DvmError) || err.code === "payment_invalid") return err;
24629
25703
  const held = `${prepared.totalSats} sats`;
24630
25704
  const proseSources = {
24631
25705
  ...err.proseSources?.message === "provider" ? { message: "provider" } : {},
24632
25706
  ...err.proseSources?.hint === "provider" ? { hint: "provider" } : {}
24633
25707
  };
24634
- return new DvmError(
24635
- err.code,
24636
- `${err.message} The ${held} payment was already sent \u2014 it is held against request ${prepared.requestId}, not lost.`,
24637
- err.hint,
24638
- {
24639
- ...err.data,
24640
- spend_committed: true,
24641
- request_id: prepared.requestId,
24642
- endpoint: prepared.endpoint,
24643
- mint: prepared.mint,
24644
- amount_sats: prepared.totalSats,
24645
- display: `Your wallet paid ${held} but the provider never confirmed. The payment is held against this request and will be retried automatically on your next call \u2014 check 'dvm wallet show'.`
24646
- },
24647
- void 0,
24648
- Object.keys(proseSources).length > 0 ? proseSources : void 0
25708
+ const requestId = publicRequestId ?? prepared.requestId;
25709
+ return raisedAfterPayment(
25710
+ new DvmError(
25711
+ err.code,
25712
+ `${err.message} The ${held} payment was already sent \u2014 it is held against request ${requestId}, not lost.`,
25713
+ err.hint,
25714
+ {
25715
+ ...err.data,
25716
+ spend_committed: true,
25717
+ request_id: requestId,
25718
+ cashu_request_id: prepared.requestId,
25719
+ endpoint: prepared.endpoint,
25720
+ mint: prepared.mint,
25721
+ amount_sats: prepared.totalSats,
25722
+ display: publicRequestId ? `Your wallet paid ${held} but the provider never confirmed. Your next call reads request ${publicRequestId} back from the provider without paying again \u2014 check 'dvm wallet show'.` : `Your wallet paid ${held} but the provider never confirmed. The payment is held against this request and will be retried automatically on your next call \u2014 check 'dvm wallet show'.`
25723
+ },
25724
+ void 0,
25725
+ Object.keys(proseSources).length > 0 ? proseSources : void 0
25726
+ )
24649
25727
  );
24650
25728
  }
24651
25729
  function expectedFundMicro(err) {
@@ -24677,8 +25755,9 @@ async function submitAgentWalletWithRetry(transport, ref, envelope, prepared, de
24677
25755
  retryTransportFailureOnce: true
24678
25756
  });
24679
25757
  }
24680
- async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, chosen, prepared, opts, identity, policy, providerInfo, btcRate = 0, fundPlan, signing) {
25758
+ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, chosen, prepared, opts, identity, policy, providerInfo, btcRate = 0, fundPlan, signing, generatedRequestId) {
24681
25759
  const dvmFields = dvmIdentity(identity.dvmId, identity.capability);
25760
+ let publicRequestId = opts.requestId ?? generatedRequestId;
24682
25761
  info(
24683
25762
  `Paying ${quoteAmountLabel(chosen, { anchor: false })} via agent wallet (Cashu P2PK, mint: ${prepared.mint})...`
24684
25763
  );
@@ -24696,6 +25775,32 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
24696
25775
  );
24697
25776
  break;
24698
25777
  } catch (err) {
25778
+ if (isIdentityFailure(err)) {
25779
+ transport.close?.();
25780
+ const { error, record } = recordIdentityFailure(err, {
25781
+ endpoint: ref.endpoint,
25782
+ ...identity.dvmId ? { dvmId: identity.dvmId } : {},
25783
+ capability: identity.capability,
25784
+ ...publicRequestId ? { publicRequestId } : {},
25785
+ cashuRequestId: prepared.requestId,
25786
+ rail: "cashu",
25787
+ railCorrelation: {
25788
+ mint: prepared.mint,
25789
+ amount_sats: prepared.totalSats,
25790
+ ...fundPlan ? { credit_id: fundPlan.creditId, draw_id: fundPlan.drawId } : {}
25791
+ }
25792
+ });
25793
+ if (record) {
25794
+ await markPendingSubmissionUnresolved({
25795
+ requestId: prepared.requestId,
25796
+ marker: journalMarkerFor(record)
25797
+ });
25798
+ }
25799
+ if (generatedRequestId && publicRequestId) {
25800
+ throw requestOutcomeUnknown(publicRequestId, error);
25801
+ }
25802
+ throw error;
25803
+ }
24699
25804
  const signedMicro = fundPlan ? fundPlan.wireAmountMicro ?? fundPlan.fundMicro : void 0;
24700
25805
  const expected = !correctedOnce && fundPlan && signing ? expectedFundMicro(err) : void 0;
24701
25806
  if (expected !== void 0 && expected !== signedMicro && fundPlan && signing) {
@@ -24707,6 +25812,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
24707
25812
  requestId: prepared.requestId,
24708
25813
  amountMicro: expected
24709
25814
  });
25815
+ if (generatedRequestId) publicRequestId = void 0;
24710
25816
  activeEnvelope = {
24711
25817
  ...envelope,
24712
25818
  data: signDvmRequestData(
@@ -24726,7 +25832,11 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
24726
25832
  await abandonPendingSubmission({ requestId: prepared.requestId });
24727
25833
  }
24728
25834
  transport.close?.();
24729
- throw withSpentSpendContext(err, prepared);
25835
+ const spent = withSpentSpendContext(err, prepared, publicRequestId);
25836
+ if (generatedRequestId && publicRequestId && leavesOutcomeUnknown(spent)) {
25837
+ throw requestOutcomeUnknown(publicRequestId, spent);
25838
+ }
25839
+ throw spent;
24730
25840
  }
24731
25841
  }
24732
25842
  if (receipt.status === "payment-required") {
@@ -24774,7 +25884,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
24774
25884
  dvmId: identity.dvmId,
24775
25885
  feedbackClaim: receipt.feedbackClaim,
24776
25886
  capability: identity.capability,
24777
- requestId: opts.requestId,
25887
+ requestId: publicRequestId,
24778
25888
  status: "submitted",
24779
25889
  submittedAt: Date.now(),
24780
25890
  policy,
@@ -24940,7 +26050,7 @@ async function payWithX402(args, proof) {
24940
26050
  } else {
24941
26051
  json({
24942
26052
  ...dvmFields,
24943
- ...requestIdOutputFields(opts),
26053
+ ...requestIdOutputFields(opts.requestId),
24944
26054
  status: "paying",
24945
26055
  rail: "x402",
24946
26056
  account: wallet.address,
@@ -24949,12 +26059,43 @@ async function payWithX402(args, proof) {
24949
26059
  display: `Paying ${priceLabel} via x402 (account ${addressShort}).`
24950
26060
  });
24951
26061
  }
24952
- const receipt = await transport.submit(
24953
- ref,
24954
- envelope,
24955
- { x402Payment: proof.paymentHeader, x402Version: proof.x402Version },
24956
- { timeoutMs: paidSubmitTimeoutMs(args.deadlineMs) }
24957
- );
26062
+ let receipt;
26063
+ try {
26064
+ receipt = await transport.submit(
26065
+ ref,
26066
+ envelope,
26067
+ { x402Payment: proof.paymentHeader, x402Version: proof.x402Version },
26068
+ { timeoutMs: paidSubmitTimeoutMs(args.deadlineMs) }
26069
+ );
26070
+ } catch (err) {
26071
+ const unconfirmed = (key) => recordUnconfirmedSpend({
26072
+ msats: proof.amountMsats,
26073
+ btcRate: proof.btcRate,
26074
+ key,
26075
+ endpoint: ref.endpoint,
26076
+ capability: identity.capability
26077
+ });
26078
+ if (!isIdentityFailure(err)) {
26079
+ if (leavesOutcomeUnknown(raisedAfterPayment(err))) {
26080
+ unconfirmed(unconfirmedSpendKey(opts, err));
26081
+ }
26082
+ throw err;
26083
+ }
26084
+ transport.close?.();
26085
+ const { error } = recordIdentityFailure(err, {
26086
+ endpoint: ref.endpoint,
26087
+ ...identity.dvmId ? { dvmId: identity.dvmId } : {},
26088
+ capability: identity.capability,
26089
+ ...opts.requestId ? { publicRequestId: opts.requestId } : {},
26090
+ rail: "x402",
26091
+ railCorrelation: {
26092
+ ...wallet.address ? { account: wallet.address } : {},
26093
+ amount_usdc_micro: usdcMicroUnits
26094
+ }
26095
+ });
26096
+ unconfirmed(unconfirmedSpendKey(opts, error));
26097
+ throw error;
26098
+ }
24958
26099
  const effectiveJobId = args.jobId || receipt.jobId;
24959
26100
  if (!args.jobId && receipt.jobId) {
24960
26101
  saveJob({
@@ -25022,7 +26163,7 @@ async function payWithX402(args, proof) {
25022
26163
  } else {
25023
26164
  json({
25024
26165
  jobId: effectiveJobId,
25025
- ...requestIdOutputFields(opts),
26166
+ ...requestIdOutputFields(opts.requestId),
25026
26167
  ...transactionOutputFields(receipt),
25027
26168
  ...dvmFields,
25028
26169
  summary: receipt.summary,
@@ -25052,7 +26193,7 @@ async function payWithX402(args, proof) {
25052
26193
  paymentFields: {
25053
26194
  paidWith: "x402",
25054
26195
  account: wallet.address,
25055
- ...requestIdOutputFields(opts),
26196
+ ...requestIdOutputFields(opts.requestId),
25056
26197
  ...transactionOutputFields(receipt)
25057
26198
  },
25058
26199
  dvmFields,
@@ -25379,10 +26520,17 @@ async function requestResult(requestId, opts = {}) {
25379
26520
  );
25380
26521
  }
25381
26522
  const transport = createDvmTransport();
25382
- const envelope = signedIntentEnvelope(intent, signer.privkey, `v1/request-result/${requestId}`);
26523
+ const envelope = signedIntentEnvelope(
26524
+ intent,
26525
+ signer.privkey,
26526
+ requestRecoveryPath("request-result", requestId)
26527
+ );
25383
26528
  let receipt;
25384
26529
  try {
25385
26530
  receipt = await transport.requestResult({ endpoint: intent.endpoint }, requestId, envelope);
26531
+ } catch (err) {
26532
+ if (isIdentityFailure(err)) throw recordRequestResultIdentityFailure(err, intent);
26533
+ throw err;
25386
26534
  } finally {
25387
26535
  transport.close();
25388
26536
  }
@@ -25398,6 +26546,30 @@ async function requestResult(requestId, opts = {}) {
25398
26546
  );
25399
26547
  }
25400
26548
  const existing = loadJob(receipt.jobId);
26549
+ if (existing && !sameEndpoint(existing.endpoint, intent.endpoint)) {
26550
+ const kept = recordLocalJobCollision({
26551
+ publicRequestId: requestId,
26552
+ endpoint: intent.endpoint,
26553
+ jobId: receipt.jobId,
26554
+ jobToken: receipt.jobToken,
26555
+ ...intent.dvmId ? { dvmId: intent.dvmId } : {},
26556
+ capability: intent.capability,
26557
+ rail: "none"
26558
+ });
26559
+ const read = `DVM_JOB_TOKEN=<job_token_bearer_secret> dvm status ${shellQuoteArg(receipt.jobId)} --endpoint ${shellQuoteArg(intent.endpoint)}`;
26560
+ throw new DvmError(
26561
+ "request_result_conflict",
26562
+ `Job ${receipt.jobId} is already a local job from another provider, so the recovered job was not added to the local job list.`,
26563
+ kept.job_token ? `Do not overwrite the local record. Read the recovered job with '${read}', taking job_token_bearer_secret from evidence row ${kept.ambiguity_id} in 'dvm wallet submissions'.` : `Do not overwrite the local record. The provider sent no job token for job ${receipt.jobId}, so this caller cannot read it directly; evidence row ${kept.ambiguity_id} in 'dvm wallet submissions' records the request.`,
26564
+ {
26565
+ request_id: requestId,
26566
+ local_job_id: existing.id,
26567
+ local_endpoint: existing.endpoint,
26568
+ server_job_id: receipt.jobId,
26569
+ ambiguity_id: kept.ambiguity_id
26570
+ }
26571
+ );
26572
+ }
25401
26573
  const restored = {
25402
26574
  requestId,
25403
26575
  transactionHash: receipt.transactionHash,
@@ -25441,8 +26613,16 @@ async function requestResult(requestId, opts = {}) {
25441
26613
  });
25442
26614
  }
25443
26615
  const captured = captureTransportReceipt(receipt.jobId, receipt);
26616
+ const confirmed = await bookRecoveredSubmissions({
26617
+ publicRequestId: requestId,
26618
+ endpoint: intent.endpoint,
26619
+ jobId: receipt.jobId
26620
+ });
25444
26621
  if (opts.human) {
25445
26622
  info(`Recovered request ${requestId} as job ${receipt.jobId} (${receipt.status}).`);
26623
+ if (confirmed.length > 0) {
26624
+ info(`The wallet payment held for this request is now confirmed as spent on that job.`);
26625
+ }
25446
26626
  renderReceiptHuman(captured);
25447
26627
  return;
25448
26628
  }
@@ -25453,6 +26633,7 @@ async function requestResult(requestId, opts = {}) {
25453
26633
  ...receipt.transactionHash ? { transaction_hash: receipt.transactionHash } : {},
25454
26634
  ...dvmIdentity(intent.dvmId, intent.capability),
25455
26635
  ...receipt.summary !== void 0 ? { summary: receipt.summary } : {},
26636
+ ...confirmed.length > 0 ? { confirmed_pending_submissions: confirmed } : {},
25456
26637
  ...receiptJsonFields(captured),
25457
26638
  next_action: receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled" ? null : {
25458
26639
  type: "poll",
@@ -25481,6 +26662,21 @@ function signedIntentEnvelope(intent, privkey, route) {
25481
26662
  bidMsats: typeof body.bid_msats === "number" ? body.bid_msats : void 0
25482
26663
  };
25483
26664
  }
26665
+ function recordRequestResultIdentityFailure(err, intent) {
26666
+ const record = recordSubmissionEvidence({
26667
+ observation: err.observation,
26668
+ endpoint: intent.endpoint,
26669
+ ...intent.dvmId ? { dvmId: intent.dvmId } : {},
26670
+ capability: intent.capability,
26671
+ publicRequestId: intent.requestId,
26672
+ rail: "none"
26673
+ });
26674
+ return withRequestResultRecovery(err, {
26675
+ ambiguityId: record.ambiguity_id,
26676
+ requestId: intent.requestId,
26677
+ endpoint: intent.endpoint
26678
+ });
26679
+ }
25484
26680
  function paymentMethod(receipt) {
25485
26681
  if (receipt.receipt?.credit) return "credit";
25486
26682
  const rail = receipt.receipt?.paid.rail;
@@ -25525,7 +26721,7 @@ async function requestResume(requestId, opts = {}) {
25525
26721
  await transport.requestResume(
25526
26722
  { endpoint: intent.endpoint },
25527
26723
  requestId,
25528
- signedIntentEnvelope(intent, signer.privkey, `v1/request-resume/${requestId}`),
26724
+ signedIntentEnvelope(intent, signer.privkey, requestRecoveryPath("request-resume", requestId)),
25529
26725
  timeoutMs === void 0 ? void 0 : { timeoutMs }
25530
26726
  );
25531
26727
  } catch (error) {
@@ -25886,14 +27082,14 @@ async function resolveNextAction(jobId, status2, fetched, transport, ref, opts)
25886
27082
  import { statSync as statSync6 } from "fs";
25887
27083
 
25888
27084
  // src/lib/upload-stream.ts
25889
- import { createHash as createHash3 } from "crypto";
27085
+ import { createHash as createHash4 } from "crypto";
25890
27086
  import { createReadStream } from "fs";
25891
27087
  import * as http2 from "http";
25892
27088
  import * as https from "https";
25893
27089
  var UPLOAD_RESPONSE_MAX_BYTES = 64 * 1024;
25894
27090
  function hashFile(filePath) {
25895
27091
  return new Promise((resolve3, reject) => {
25896
- const hasher = createHash3("sha256");
27092
+ const hasher = createHash4("sha256");
25897
27093
  let sizeBytes = 0;
25898
27094
  const stream = createReadStream(filePath);
25899
27095
  stream.on("data", (chunk) => {
@@ -26368,7 +27564,7 @@ function getRailOnramp(rail) {
26368
27564
  }
26369
27565
 
26370
27566
  // src/lib/secret-input.ts
26371
- import { fstatSync, readFileSync as readFileSync9, realpathSync } from "fs";
27567
+ import { fstatSync, readFileSync as readFileSync10, realpathSync } from "fs";
26372
27568
  import { homedir as homedir2 } from "os";
26373
27569
  import { resolve as resolve2, sep } from "path";
26374
27570
  var BLOCKED_SECRET_PATHS = [
@@ -26448,7 +27644,7 @@ function readSecretFile(path, config) {
26448
27644
  throw err;
26449
27645
  }
26450
27646
  assertSafeFilePath(real);
26451
- return readFileSync9(real, "utf-8").trim();
27647
+ return readFileSync10(real, "utf-8").trim();
26452
27648
  }
26453
27649
  function readSecretStdin(config) {
26454
27650
  return new Promise((resolveStdin, reject) => {
@@ -28144,7 +29340,7 @@ function mnemonicValidationError(result) {
28144
29340
  var import_qrcode = __toESM(require_lib(), 1);
28145
29341
  import { randomBytes as randomBytes3 } from "crypto";
28146
29342
  import { tmpdir as tmpdir2 } from "os";
28147
- import { join as join9 } from "path";
29343
+ import { join as join10 } from "path";
28148
29344
  async function renderQrTerminal(payload) {
28149
29345
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
28150
29346
  }
@@ -28157,7 +29353,7 @@ async function renderQrPng(payload, outPath) {
28157
29353
  });
28158
29354
  }
28159
29355
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
28160
- return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
29356
+ return join10(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
28161
29357
  }
28162
29358
 
28163
29359
  // src/lib/funding-handoff.ts
@@ -29427,6 +30623,7 @@ async function walletShow(opts) {
29427
30623
  const resumedViews = describeResumedSubmissions(submissionSweep.outcomes);
29428
30624
  const reclaimedViews = describeReclaimedSubmissions(submissionSweep.outcomes);
29429
30625
  const skippedReclaimViews = describeSkippedReclaims(submissionSweep.outcomes);
30626
+ const unresolvedViews = describeUnresolvedSubmissions(submissionSweep.outcomes);
29430
30627
  const post = loadAgentWallet() ?? wallet;
29431
30628
  const submissions = describePendingSubmissions(post);
29432
30629
  const lockedToProviderSubmissions = submissions.entries.filter(
@@ -29491,6 +30688,7 @@ async function walletShow(opts) {
29491
30688
  `Reconciled a ${outcome.entry.amount_sats} sat payment to ${outcome.entry.endpoint}${jobSuffix}.`
29492
30689
  );
29493
30690
  }
30691
+ for (const view of unresolvedViews) info(view.display);
29494
30692
  for (const view of reclaimedViews) {
29495
30693
  info(
29496
30694
  `A ${view.amount_sats} sat payment to ${view.endpoint} expired unclaimed \u2014 ${view.reclaimed_sats} sats are back in your balance.`
@@ -29591,6 +30789,7 @@ async function walletShow(opts) {
29591
30789
  const uncheckedHint = sweep.unchecked.length > 0 ? `${sweep.unchecked.length} pending mint(s) could not be checked against their mint on this call \u2014 see sweep.unchecked for the cause and how long to wait. They keep their pending state; don't fund the same invoice again.` : null;
29592
30790
  const stuckReclaims = skippedReclaimViews.filter((v) => !v.terminal);
29593
30791
  const deadReclaims = skippedReclaimViews.filter((v) => v.terminal);
30792
+ const unresolvedHint = unresolvedViews.length > 0 ? `${unresolvedViews.length} paid call(s) need attention: the provider accepted them without a clear job ID \u2014 see accepted_unresolved. Do not pay for them again.` : null;
29594
30793
  const resumedHint = stuckReclaims.length > 0 ? `${stuckReclaims.reduce((sum, v) => sum + v.amount_sats, 0)} sats from ${stuckReclaims.length} expired payment(s) could not be taken back on this call \u2014 see reclaim_skipped for why. The sats are still recoverable.` : resumedViews.length > 0 ? `Reconciled ${resumedViews.length} unconfirmed payment(s) on this call \u2014 see resumed for the job id(s).` : reclaimedViews.length > 0 ? `${reclaimedViews.reduce((sum, v) => sum + v.reclaimed_sats, 0)} sats came back from ${reclaimedViews.length} expired payment(s) the provider never took \u2014 see reclaimed.` : deadReclaims.length > 0 ? `${deadReclaims.reduce((sum, v) => sum + v.amount_sats, 0)} sats from ${deadReclaims.length} expired payment(s) are too small to be worth taking back \u2014 see reclaim_skipped. Retrying will not change that; treat them as spent.` : null;
29595
30794
  json({
29596
30795
  status: "ok",
@@ -29624,10 +30823,13 @@ async function walletShow(opts) {
29624
30823
  // with the reason. Empty is the normal case; a repeating entry here means
29625
30824
  // the self-heal needs a human.
29626
30825
  reclaim_skipped: skippedReclaimViews,
30826
+ // paid calls the provider accepted without a settled job identity,
30827
+ // detected on this call or missing their evidence record.
30828
+ accepted_unresolved: unresolvedViews,
29627
30829
  sweep: summarizeSweep(sweep),
29628
30830
  melt_sweep: summarizeMeltSweep(meltSweep),
29629
30831
  display: railsSnapshot.length === 0 ? "Agent wallet is empty." : `${railsSnapshot.map((r) => r.json.display).join(" \u2014 ")} (~$${totalUsd.toFixed(2)} total)`,
29630
- hint: [uncheckedHint, resumedHint, baseHint].filter(Boolean).join(" ")
30832
+ hint: [uncheckedHint, unresolvedHint, resumedHint, baseHint].filter(Boolean).join(" ")
29631
30833
  });
29632
30834
  }
29633
30835
  }
@@ -31707,7 +32909,7 @@ function resolveMppEndpoint(identifier) {
31707
32909
  }
31708
32910
 
31709
32911
  // src/commands/wallet-pair.ts
31710
- import { createHash as createHash4, randomBytes as randomBytes5 } from "crypto";
32912
+ import { createHash as createHash5, randomBytes as randomBytes5 } from "crypto";
31711
32913
  import { hostname } from "os";
31712
32914
 
31713
32915
  // node_modules/@noble/ciphers/_arx.js
@@ -32529,14 +33731,14 @@ function hexToBytes2(hex) {
32529
33731
  var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
32530
33732
  import {
32531
33733
  chmodSync as chmodSync2,
32532
- existsSync as existsSync8,
32533
- readdirSync as readdirSync5,
32534
- readFileSync as readFileSync10,
33734
+ existsSync as existsSync9,
33735
+ readdirSync as readdirSync6,
33736
+ readFileSync as readFileSync11,
32535
33737
  renameSync as renameSync4,
32536
- unlinkSync as unlinkSync4,
32537
- writeFileSync as writeFileSync6
33738
+ unlinkSync as unlinkSync5,
33739
+ writeFileSync as writeFileSync7
32538
33740
  } from "fs";
32539
- import { join as join10 } from "path";
33741
+ import { join as join11 } from "path";
32540
33742
  var pairingIdPattern = /^[0-9a-f]{64}$/;
32541
33743
  var stateSchema = external_exports.object({
32542
33744
  version: external_exports.literal(1),
@@ -32558,12 +33760,12 @@ var stateSchema = external_exports.object({
32558
33760
  function createWalletPairingState(state) {
32559
33761
  ensurePairingsDirectory();
32560
33762
  const path = pairingPath(state.pairing_id);
32561
- writeFileSync6(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
33763
+ writeFileSync7(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
32562
33764
  chmodSync2(path, 384);
32563
33765
  }
32564
33766
  function loadWalletPairingState(pairingId) {
32565
33767
  const path = pairingPath(pairingId);
32566
- if (!existsSync8(path)) {
33768
+ if (!existsSync9(path)) {
32567
33769
  throw new DvmError(
32568
33770
  "wallet_pairing_not_found",
32569
33771
  "No local state exists for that wallet pairing.",
@@ -32571,7 +33773,7 @@ function loadWalletPairingState(pairingId) {
32571
33773
  );
32572
33774
  }
32573
33775
  try {
32574
- return stateSchema.parse(JSON.parse(readFileSync10(path, "utf8")));
33776
+ return stateSchema.parse(JSON.parse(readFileSync11(path, "utf8")));
32575
33777
  } catch {
32576
33778
  throw new DvmError(
32577
33779
  "wallet_pairing_state_invalid",
@@ -32585,13 +33787,13 @@ function saveWalletPairingState(state) {
32585
33787
  ensurePairingsDirectory();
32586
33788
  const path = pairingPath(state.pairing_id);
32587
33789
  const tmp = `${path}.tmp`;
32588
- writeFileSync6(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
33790
+ writeFileSync7(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
32589
33791
  try {
32590
33792
  renameSync4(tmp, path);
32591
33793
  chmodSync2(path, 384);
32592
33794
  } catch (err) {
32593
33795
  try {
32594
- unlinkSync4(tmp);
33796
+ unlinkSync5(tmp);
32595
33797
  } catch {
32596
33798
  }
32597
33799
  throw err;
@@ -32600,21 +33802,21 @@ function saveWalletPairingState(state) {
32600
33802
  function deleteWalletPairingState(pairingId) {
32601
33803
  const path = pairingPath(pairingId);
32602
33804
  try {
32603
- unlinkSync4(path);
33805
+ unlinkSync5(path);
32604
33806
  } catch (err) {
32605
33807
  if (err.code !== "ENOENT") throw err;
32606
33808
  }
32607
33809
  }
32608
33810
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
32609
- if (!existsSync8(PAIRINGS_DIR)) return 0;
33811
+ if (!existsSync9(PAIRINGS_DIR)) return 0;
32610
33812
  let removed = 0;
32611
- for (const name of readdirSync5(PAIRINGS_DIR)) {
33813
+ for (const name of readdirSync6(PAIRINGS_DIR)) {
32612
33814
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
32613
- const path = join10(PAIRINGS_DIR, name);
33815
+ const path = join11(PAIRINGS_DIR, name);
32614
33816
  try {
32615
- const state = stateSchema.parse(JSON.parse(readFileSync10(path, "utf8")));
33817
+ const state = stateSchema.parse(JSON.parse(readFileSync11(path, "utf8")));
32616
33818
  if (state.manifest.expires_at <= nowSeconds) {
32617
- unlinkSync4(path);
33819
+ unlinkSync5(path);
32618
33820
  removed += 1;
32619
33821
  }
32620
33822
  } catch {
@@ -32624,7 +33826,7 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
32624
33826
  }
32625
33827
  async function withWalletPairingLock(pairingId, fn) {
32626
33828
  const path = pairingPath(pairingId);
32627
- if (!existsSync8(path)) return fn();
33829
+ if (!existsSync9(path)) return fn();
32628
33830
  let release;
32629
33831
  try {
32630
33832
  release = await import_proper_lockfile2.default.lock(path, {
@@ -32654,7 +33856,7 @@ function pairingPath(pairingId) {
32654
33856
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
32655
33857
  );
32656
33858
  }
32657
- return join10(PAIRINGS_DIR, `${pairingId}.json`);
33859
+ return join11(PAIRINGS_DIR, `${pairingId}.json`);
32658
33860
  }
32659
33861
  function ensurePairingsDirectory() {
32660
33862
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -33079,7 +34281,7 @@ function walletFingerprint(uri) {
33079
34281
  return uri ? sha2562(uri) : null;
33080
34282
  }
33081
34283
  function sha2562(value) {
33082
- return createHash4("sha256").update(value).digest("hex");
34284
+ return createHash5("sha256").update(value).digest("hex");
33083
34285
  }
33084
34286
  function relayHost2(relay) {
33085
34287
  try {
@@ -33205,9 +34407,16 @@ async function walletSubmissions(opts) {
33205
34407
  listSubmissions(opts);
33206
34408
  }
33207
34409
  function listSubmissions(opts) {
33208
- const wallet = loadWalletOrThrow();
33209
- const summary = describePendingSubmissions(wallet);
34410
+ const listed = listSubmissionEvidence();
34411
+ const evidence = describeSubmissionEvidence(listed.records);
34412
+ const unreadable2 = listed.unreadable;
34413
+ const wallet = evidence.length > 0 || unreadable2.length > 0 ? loadAgentWallet() : loadWalletOrThrow();
34414
+ const summary = wallet ? describePendingSubmissions(wallet) : EMPTY_SUMMARY;
33210
34415
  if (opts.human) {
34416
+ printEvidenceHuman(evidence);
34417
+ for (const file of unreadable2) {
34418
+ info(`Unreadable evidence record (${file.cause}): ${file.path}. Restore it from a backup; do not pay again for any request it may describe.`);
34419
+ }
33211
34420
  if (summary.entries.length === 0) {
33212
34421
  info("No unconfirmed payments \u2014 every spend has been acknowledged by its provider.");
33213
34422
  return;
@@ -33236,6 +34445,12 @@ function listSubmissions(opts) {
33236
34445
  ` ${summary.reclaim_failed_count} of these have expired but the wallet keeps failing to take the sats back \u2014 the reason is on each line above. Fix the cause and the next call retries; the sats are still recoverable.`
33237
34446
  );
33238
34447
  }
34448
+ if (summary.accepted_unresolved_count > 0) {
34449
+ info("");
34450
+ info(
34451
+ ` ${summary.accepted_unresolved_count} of these were accepted by the provider without a clear job ID. They are never paid for or sent again; the evidence above says how to find each job.`
34452
+ );
34453
+ }
33239
34454
  return;
33240
34455
  }
33241
34456
  json({
@@ -33251,11 +34466,21 @@ function listSubmissions(opts) {
33251
34466
  // not stranded — the sats are recoverable once the cause is fixed — but
33252
34467
  // unlike `reclaimable` this one needs someone to act.
33253
34468
  reclaim_failed_count: summary.reclaim_failed_count,
33254
- display: summary.entries.length === 0 ? "No unconfirmed payments." : `${summary.entries.length} unconfirmed payment(s), ${summary.at_risk_sats} sats spent but not yet confirmed by a provider.`,
34469
+ // Accepted without a settled job identity: held so nothing pays twice.
34470
+ accepted_unresolved_count: summary.accepted_unresolved_count,
34471
+ submission_evidence: evidence,
34472
+ ...unreadable2.length > 0 ? { submission_evidence_unreadable: unreadable2 } : {},
34473
+ display: [
34474
+ summary.entries.length === 0 ? "No unconfirmed payments." : `${summary.entries.length} unconfirmed payment(s), ${summary.at_risk_sats} sats spent but not yet confirmed by a provider.`,
34475
+ evidence.length > 0 ? `${evidence.length} paid call(s) were accepted without a clear job ID; see submission_evidence. None was paid for again.` : null,
34476
+ unreadable2.length > 0 ? `${unreadable2.length} evidence record(s) cannot be read; see submission_evidence_unreadable. The payments they may describe are held and not sent again.` : null
34477
+ ].filter(Boolean).join(" "),
33255
34478
  hint: [
33256
34479
  summary.stranded_count > 0 ? "Entries in state stale/unresumable/unreclaimable will not retry and their sats are not coming back. Close one out with: dvm wallet submissions --forget <request_id> (abandons its sats)." : null,
33257
34480
  summary.reclaimable_count > 0 ? "Entries in state reclaimable need no action \u2014 the wallet takes those sats back after reclaim_at." : null,
33258
34481
  summary.reclaim_failed_count > 0 ? "Entries in state reclaim_failed have expired but could not be taken back \u2014 see each entry's reclaim_error. The sats are recoverable once that is fixed." : null,
34482
+ unreadable2.length > 0 ? "Restore each file in submission_evidence_unreadable from a backup. Do not pay again for any request it may describe." : null,
34483
+ evidence.length > 0 ? "Do not pay for a request listed in submission_evidence again. Each row's read_job lists lookups that never pay; job_token_bearer_secret, where present, is a bearer secret: treat it like a password and do not share it." : null,
33259
34484
  "Resumable entries retry on the next paid call or `dvm wallet show`."
33260
34485
  ].filter(Boolean).join(" ")
33261
34486
  });
@@ -33285,7 +34510,7 @@ async function forgetSubmission(requestId, opts) {
33285
34510
  request_id: requestId,
33286
34511
  endpoint: view.endpoint,
33287
34512
  abandoned_sats: abandoned,
33288
- display: !view.at_risk ? `Forgot request ${requestId}. No sats were spent, so nothing was abandoned.` : view.state === "reclaimable" || view.state === "reclaim_failed" ? `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 and this one was still recoverable: the wallet would have returned it to your balance by itself${view.reclaim_at ? ` after ${view.reclaim_at}` : ""}.` : view.state === "unreclaimable" ? `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 nothing was given up by forgetting it, since ${view.reclaim_error ?? "the mint's fee exceeds the value"}.` : `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 the proofs were locked to the provider with no refund.`,
34513
+ display: !view.at_risk ? `Forgot request ${requestId}. No sats were spent, so nothing was abandoned.` : view.state === "reclaimable" || view.state === "reclaim_failed" ? `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 and this one was still recoverable: the wallet would have returned it to your balance by itself${view.reclaim_at ? ` after ${view.reclaim_at}` : ""}.` : view.state === "accepted_unresolved" ? `Forgot the journal entry for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are no longer tracked; the provider accepted that call, and its evidence stays under submission_evidence.` : view.state === "unreclaimable" ? `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 nothing was given up by forgetting it, since ${view.reclaim_error ?? "the mint's fee exceeds the value"}.` : `Forgot the unconfirmed payment for request ${requestId}. ${abandoned} sats paid to ${view.endpoint} are abandoned \u2014 the proofs were locked to the provider with no refund.`,
33289
34514
  hint: "The entry is gone from the journal. This cannot be undone."
33290
34515
  });
33291
34516
  }
@@ -33306,7 +34531,7 @@ async function confirmForget(view, opts) {
33306
34531
  // caller money they were otherwise getting back. Reaching
33307
34532
  // here at all means they already passed --force.
33308
34533
  `throws away ${view.amount_sats} sats paid to ${view.endpoint} that the wallet can still reclaim by itself, so this cannot be undone`
33309
- ) : view.state === "unreclaimable" ? `clears ${view.amount_sats} sats paid to ${view.endpoint} that are too small to be worth taking back, so nothing recoverable is lost \u2014 but this cannot be undone` : `abandons ${view.amount_sats} sats paid to ${view.endpoint} \u2014 the proofs are locked to the provider with no refund, so this cannot be undone`;
34534
+ ) : view.state === "accepted_unresolved" ? `stops tracking ${view.amount_sats} sats paid to ${view.endpoint} for a call the provider accepted without a clear job ID${view.reclaim_at ? `, including the wallet's claim to take them back after ${view.reclaim_at} if the provider never redeems them` : ""}; the recorded evidence is kept, but this cannot be undone` : view.state === "unreclaimable" ? `clears ${view.amount_sats} sats paid to ${view.endpoint} that are too small to be worth taking back, so nothing recoverable is lost \u2014 but this cannot be undone` : `abandons ${view.amount_sats} sats paid to ${view.endpoint} \u2014 the proofs are locked to the provider with no refund, so this cannot be undone`;
33310
34535
  if (opts.human && process.stdin.isTTY) {
33311
34536
  const rl = createInterface4({ input: process.stdin, output: process.stderr });
33312
34537
  const answer = await new Promise((resolve3) => {
@@ -33329,6 +34554,29 @@ async function confirmForget(view, opts) {
33329
34554
  `This ${consequence}. Use: dvm wallet submissions --forget ${view.request_id} --yes`
33330
34555
  );
33331
34556
  }
34557
+ var EMPTY_SUMMARY = {
34558
+ entries: [],
34559
+ at_risk_sats: 0,
34560
+ stranded_count: 0,
34561
+ reclaimable_count: 0,
34562
+ reclaim_failed_count: 0,
34563
+ accepted_unresolved_count: 0
34564
+ };
34565
+ function printEvidenceHuman(evidence) {
34566
+ if (evidence.length === 0) return;
34567
+ info(`Accepted without a clear job ID: ${evidence.length} (never paid for again)`);
34568
+ for (const row of evidence) {
34569
+ info(` ${row.ambiguity_id} ${row.endpoint} (${row.kind}, ${row.observed_at})`);
34570
+ info(` ${row.display}`);
34571
+ for (const command of row.read_job) info(` read: ${command}`);
34572
+ if (row.job_token_bearer_secret) {
34573
+ info(
34574
+ ` job_token_bearer_secret (treat like a password; do not share): ${row.job_token_bearer_secret}`
34575
+ );
34576
+ }
34577
+ }
34578
+ info("");
34579
+ }
33332
34580
  function loadWalletOrThrow() {
33333
34581
  const wallet = loadAgentWallet();
33334
34582
  if (!wallet) {