@dvmkit/dvm-cli 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dvm.js CHANGED
@@ -5,15 +5,17 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-XDYBVNFS.js";
8
+ } from "./chunk-3YU6KRCX.js";
9
9
  import {
10
10
  assertX402WalletIdle
11
- } from "./chunk-5R3BLFVO.js";
11
+ } from "./chunk-TGRY23IF.js";
12
12
  import {
13
13
  DEFAULT_CREDIT_POSTURE,
14
14
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
15
15
  NWC_FUNDING_FLOAT_ROLE,
16
+ SUBMISSION_EVIDENCE_DIR,
16
17
  abandonPendingSubmission,
18
+ abandonSubmissionInWallet,
17
19
  addPayment,
18
20
  assertFloatBudget,
19
21
  automaticCreditBoundRail,
@@ -21,10 +23,12 @@ import {
21
23
  backfillTrustAnchor,
22
24
  bookCreditPayment,
23
25
  buildTempoCredential,
26
+ captureDrawFundingReceipts,
24
27
  captureFundingReceipt,
25
28
  captureTransportReceipt,
26
29
  commitAgentSpend,
27
30
  correctPendingFundAmount,
31
+ deriveAlias,
28
32
  describeMintBounds,
29
33
  drainReceiptsDisplay,
30
34
  drainReceiptsHint,
@@ -42,11 +46,22 @@ import {
42
46
  fundAgentWallet,
43
47
  fundCredit,
44
48
  fundTimeoutMs,
49
+ identityDataFields,
50
+ identityError,
45
51
  inFlightTimeoutSeconds,
52
+ isIdentityFailure,
53
+ isOpaqueJobToken,
54
+ isParseableBodyJobId,
55
+ jobDrawFundings,
56
+ jobIdentityHeaderValue,
57
+ journalMarkerFor,
58
+ listSubmissionEvidence,
46
59
  loadAllJobs,
60
+ loadFavorites,
47
61
  loadFloat,
48
62
  loadJob,
49
63
  loadLedger,
64
+ loadSubmissionEvidence,
50
65
  markJobTerminal,
51
66
  markPendingSubmissionUnresolved,
52
67
  markProofsInFlight,
@@ -71,15 +86,26 @@ import {
71
86
  receiptJsonFields,
72
87
  receiptTrustFields,
73
88
  recordFloatSpend,
89
+ recordIdentityFailure,
90
+ recordLocalJobCollision,
74
91
  recordSpend,
75
92
  recordSpendOnce,
93
+ recordSubmissionEvidence,
94
+ removeFavorite,
76
95
  renderReceiptHuman,
77
96
  replayStoredReceipt,
78
97
  reservedForMarker,
98
+ resolveEndpoint,
79
99
  resolveFundMint,
100
+ resolveJobAccess,
101
+ resolveStoredJobAccess,
80
102
  revertInFlight,
103
+ routerConflictObservation,
104
+ sameEndpoint,
105
+ saveFavorite,
81
106
  saveJob,
82
107
  saveLedger,
108
+ settleJobIdentity,
83
109
  statusSnapshot,
84
110
  sweepPendingMints,
85
111
  sweepStaleInFlight,
@@ -89,14 +115,18 @@ import {
89
115
  trustOverrideCapMicro,
90
116
  unrecordedFloatBudgetWarning,
91
117
  updateJob,
92
- withAcceptedUnresolved
93
- } from "./chunk-Y3X74XH2.js";
118
+ warnInvalidJobIdentityHeader,
119
+ withAcceptedUnresolved,
120
+ withIdentityRecovery,
121
+ withJobTokenRedaction,
122
+ withRequestResultRecovery
123
+ } from "./chunk-Q45TAYK2.js";
94
124
  import {
95
125
  connectedTempoAccount,
96
126
  generateTempoKey,
97
127
  tempoBalanceCheckHint,
98
128
  tempoWrongAssetHint
99
- } from "./chunk-BCDMVIPI.js";
129
+ } from "./chunk-NXXU3BSJ.js";
100
130
  import {
101
131
  assertValidBudget,
102
132
  costAnchor,
@@ -108,14 +138,13 @@ import {
108
138
  json,
109
139
  monetaryJson,
110
140
  parseBudget,
111
- progress,
112
141
  raw,
113
142
  resolveBtcUsdRate,
114
143
  setOutputTraceId,
115
144
  staleRateNotice,
116
145
  tryResolveBtcUsdRate,
117
146
  tryX402Payment
118
- } from "./chunk-C7ZNQONB.js";
147
+ } from "./chunk-C3HMFGYP.js";
119
148
  import {
120
149
  assertSupportedX402Network,
121
150
  connectedX402Payer,
@@ -124,7 +153,7 @@ import {
124
153
  repinX402WalletNetwork,
125
154
  saveX402Wallet,
126
155
  x402NetworkLabel
127
- } from "./chunk-PMPHS3LS.js";
156
+ } from "./chunk-MTGQK7KA.js";
128
157
  import {
129
158
  CREDIT_POSTURES,
130
159
  FEEDBACK_POSTURES,
@@ -141,7 +170,7 @@ import {
141
170
  retireConfigBackup,
142
171
  rollbackConfig,
143
172
  updateConfig
144
- } from "./chunk-QDOY3JF2.js";
173
+ } from "./chunk-GMOKL4PQ.js";
145
174
  import {
146
175
  A,
147
176
  AGENT_MNEMONIC_FILE,
@@ -166,7 +195,6 @@ import {
166
195
  IDENTITIES_FILE,
167
196
  IDENTITIES_VERSION,
168
197
  JOBS_FILE,
169
- JOB_IDENTITY_HEADER,
170
198
  MESSAGES_DIR,
171
199
  PAIRINGS_DIR,
172
200
  PRIVKEY_HEX_RE,
@@ -264,11 +292,11 @@ import {
264
292
  isCreditFundRail,
265
293
  isCreditFundingMode,
266
294
  isDrainReceipt,
295
+ isDrawFundingReceipt,
267
296
  isFundingReceipt,
268
297
  isPublicRequestId,
269
298
  isSignedJobReceipt,
270
299
  isStablecoinFundRail,
271
- isStorableJobId,
272
300
  ki,
273
301
  la,
274
302
  listCredits,
@@ -386,7 +414,7 @@ import {
386
414
  x402PendingUnsettled,
387
415
  x402RequiredFromError,
388
416
  x402ReservationRelease
389
- } from "./chunk-6XTWANVN.js";
417
+ } from "./chunk-CWWZM4M6.js";
390
418
  import "./chunk-JBU7RKQ3.js";
391
419
  import "./chunk-KDNFUDOG.js";
392
420
  import "./chunk-IUTVV6N5.js";
@@ -8746,14 +8774,19 @@ function computeNextAction(jobId, messages2) {
8746
8774
  return null;
8747
8775
  case "prompt": {
8748
8776
  const c = msg.content;
8777
+ const answer = c.schema ? "--json '<object matching schema>'" : '"<answer>"';
8778
+ const choices = c.options?.length ? ` Choices: ${c.options.map((option) => JSON.stringify(option)).join(", ")}.` : "";
8779
+ const choiceHint = !c.schema && c.options?.length ? " Answer with exactly one of options unless the human chose otherwise." : "";
8749
8780
  const action = {
8750
8781
  type: "respond",
8751
8782
  job_id: jobId,
8752
8783
  prompt_id: c.id,
8753
8784
  prompt: asProviderText(c.text),
8754
- hint: "Provider is waiting for your input. Verify the question makes sense for your task before responding."
8785
+ display: `The provider asks: ${c.text}${choices}`,
8786
+ hint: `Provider is waiting for your input. Verify the question makes sense for your task before responding.${choiceHint} Run \`dvm message ${shellQuoteArg(jobId)} ${answer} --type response --prompt-id ${shellQuoteArg(c.id)}\`.`
8755
8787
  };
8756
8788
  if (c.schema) action.schema = c.schema;
8789
+ if (c.options?.length) action.options = c.options;
8757
8790
  return action;
8758
8791
  }
8759
8792
  case "payment-request": {
@@ -8768,7 +8801,7 @@ function computeNextAction(jobId, messages2) {
8768
8801
  ...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount } : {},
8769
8802
  display,
8770
8803
  reason: asProviderText(c.reason),
8771
- hint: `Payment required to continue: ${display}. Relay that amount to your human and get approval, then run 'dvm pay ${jobId}'. Provider's stated reason is wrapped as { _source: "provider", text: ... } \u2014 verify it matches the work you expect.`
8804
+ hint: `Payment required to continue: ${display}. Relay that amount to your human and get approval, then run \`dvm pay ${shellQuoteArg(jobId)}\`. Provider's stated reason is wrapped as { _source: "provider", text: ... } \u2014 verify it matches the work you expect.`
8772
8805
  };
8773
8806
  }
8774
8807
  case "working": {
@@ -8833,736 +8866,23 @@ function formatPaidAmount(result, fiat) {
8833
8866
  return formatPaymentAmount(result.amountMsats, fiat, { anchor: false });
8834
8867
  }
8835
8868
 
8836
- // src/lib/favorites.ts
8837
- var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
8838
- import {
8839
- closeSync as closeSync2,
8840
- fchmodSync,
8841
- fsyncSync,
8842
- openSync as openSync2,
8843
- readFileSync as readFileSync2,
8844
- renameSync,
8845
- statSync as statSync2,
8846
- unlinkSync,
8847
- writeFileSync
8848
- } from "fs";
8849
- import { dirname } from "path";
8850
- var DEFAULT_FILE_MODE = 384;
8851
- function loadFavorites() {
8852
- let raw2;
8853
- try {
8854
- raw2 = readFileSync2(FAVORITES_FILE, "utf8");
8855
- } catch (error) {
8856
- if (nodeErrorCode(error) === "ENOENT") return {};
8857
- throw unreadableFavorites(error);
8858
- }
8859
- try {
8860
- const parsed = JSON.parse(raw2);
8861
- if (!isFavoritesMap(parsed)) throw new Error("invalid favorites shape");
8862
- return parsed;
8863
- } catch (error) {
8864
- throw unreadableFavorites(error);
8865
- }
8866
- }
8867
- async function saveFavorite(alias, fav) {
8868
- return withFavoritesLock(() => {
8869
- const favs = loadFavorites();
8870
- const existed = Object.hasOwn(favs, alias);
8871
- favs[alias] = fav;
8872
- writeFavorites(favs);
8873
- return existed;
8874
- });
8875
- }
8876
- async function removeFavorite(alias) {
8877
- return withFavoritesLock(() => {
8878
- const favs = loadFavorites();
8879
- if (!Object.hasOwn(favs, alias)) return false;
8880
- const { [alias]: _, ...rest } = favs;
8881
- writeFavorites(rest);
8882
- return true;
8883
- });
8884
- }
8885
- function resolveEndpoint(input) {
8886
- if (!input.startsWith("@")) return input;
8887
- const alias = input.slice(1);
8888
- const favs = loadFavorites();
8889
- const fav = Object.hasOwn(favs, alias) ? favs[alias] : void 0;
8890
- if (!fav) {
8891
- throw new DvmError(
8892
- "unknown_favorite",
8893
- `No favorite named "${alias}".`,
8894
- "Run 'dvm fav list' to see saved favorites, or 'dvm fav add <endpoint>' to save one."
8895
- );
8896
- }
8897
- return fav.endpoint;
8898
- }
8899
- function deriveAlias(endpoint) {
8900
- try {
8901
- const hostname2 = new URL(endpoint).hostname;
8902
- if (hostname2.endsWith(".dvmkit.ai")) {
8903
- const prefix = hostname2.replace(".dvmkit.ai", "");
8904
- const dashIdx = prefix.indexOf("--");
8905
- if (dashIdx !== -1) return prefix.slice(dashIdx + 2);
8906
- return prefix;
8907
- }
8908
- return hostname2.replace(/\.[^.]+$/, "").replace(/\./g, "-");
8909
- } catch {
8910
- return endpoint.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
8911
- }
8912
- }
8913
- async function withFavoritesLock(fn) {
8914
- ensureConfigDir();
8915
- let release;
8916
- try {
8917
- release = await import_proper_lockfile.default.lock(FAVORITES_FILE, {
8918
- lockfilePath: `${FAVORITES_FILE}.lock`,
8919
- realpath: false,
8920
- stale: 3e4,
8921
- retries: { retries: 10, factor: 1, minTimeout: 100, maxTimeout: 100 }
8922
- });
8923
- } catch {
8924
- throw new DvmError(
8925
- "favorites_locked",
8926
- "Another dvm process is updating saved favorites.",
8927
- "Wait a moment and retry."
8928
- );
8929
- }
8930
- try {
8931
- return await fn();
8932
- } finally {
8933
- await release().catch(() => void 0);
8934
- }
8935
- }
8936
- function writeFavorites(favorites) {
8937
- const mode = favoritesFileMode();
8938
- const temporary = `${FAVORITES_FILE}.${String(process.pid)}.${randomSuffix()}.tmp`;
8939
- const contents = JSON.stringify(favorites, null, 2) + "\n";
8940
- let fd;
8941
- try {
8942
- fd = openSync2(temporary, "wx", mode);
8943
- fchmodSync(fd, mode);
8944
- writeFileSync(fd, contents);
8945
- fsyncSync(fd);
8946
- closeSync2(fd);
8947
- fd = void 0;
8948
- renameSync(temporary, FAVORITES_FILE);
8949
- fsyncDirectory(dirname(FAVORITES_FILE));
8950
- } catch (error) {
8951
- if (fd !== void 0) {
8952
- try {
8953
- closeSync2(fd);
8954
- } catch {
8955
- }
8956
- }
8957
- try {
8958
- unlinkSync(temporary);
8959
- } catch {
8960
- }
8961
- throw error;
8962
- }
8963
- }
8964
- function favoritesFileMode() {
8965
- try {
8966
- return statSync2(FAVORITES_FILE).mode & 511;
8967
- } catch (error) {
8968
- if (nodeErrorCode(error) === "ENOENT") return DEFAULT_FILE_MODE;
8969
- throw error;
8970
- }
8971
- }
8972
- function fsyncDirectory(path) {
8973
- const fd = openSync2(path, "r");
8974
- try {
8975
- fsyncSync(fd);
8976
- } finally {
8977
- closeSync2(fd);
8978
- }
8979
- }
8980
- function randomSuffix() {
8981
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
8982
- }
8983
- function unreadableFavorites(error) {
8984
- return new DvmError(
8985
- "favorites_unreadable",
8986
- "Saved favorites are corrupt or unreadable.",
8987
- `The original file at ${FAVORITES_FILE} was left unchanged. Restore it from a backup, or move it aside before rebuilding favorites.`,
8988
- {
8989
- path: FAVORITES_FILE,
8990
- ...nodeErrorCode(error) ? { error_code: nodeErrorCode(error) } : {}
8991
- }
8992
- );
8993
- }
8994
- function nodeErrorCode(error) {
8995
- if (!(error instanceof Error) || !("code" in error)) return void 0;
8996
- const code = error.code;
8997
- return typeof code === "string" && /^E[A-Z0-9_]{1,63}$/.test(code) ? code : void 0;
8998
- }
8999
- function isFavoritesMap(value) {
9000
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
9001
- return Object.values(value).every(isFavorite);
9002
- }
9003
- function isFavorite(value) {
9004
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
9005
- const candidate = value;
9006
- return typeof candidate.endpoint === "string" && typeof candidate.addedAt === "number" && Number.isFinite(candidate.addedAt) && (candidate.name === void 0 || typeof candidate.name === "string");
9007
- }
9008
-
9009
- // src/lib/submission-evidence.ts
9010
- import { createHash, randomUUID } from "crypto";
9011
- import {
9012
- closeSync as closeSync3,
9013
- existsSync as existsSync2,
9014
- fsyncSync as fsyncSync2,
9015
- linkSync,
9016
- openSync as openSync3,
9017
- readdirSync,
9018
- readFileSync as readFileSync3,
9019
- unlinkSync as unlinkSync2,
9020
- writeFileSync as writeFileSync2
9021
- } from "fs";
9022
- import { join as join2 } from "path";
9023
-
9024
- // src/lib/job-identity.ts
9025
- var IDENTITY_FAILURE_CODES = {
9026
- identity_mismatch: "provider_identity_mismatch",
9027
- body_unreadable: "provider_body_unreadable",
9028
- router_identity_conflict: "hosting_job_identity_conflict"
9029
- };
9030
- var ProviderIdentityError = class extends DvmError {
9031
- observation;
9032
- constructor(observation, message2, hint, data, proseSources) {
9033
- super(IDENTITY_FAILURE_CODES[observation.kind], message2, hint, data, void 0, proseSources);
9034
- this.observation = observation;
9035
- }
9036
- };
9037
- function isIdentityFailure(err) {
9038
- return err instanceof ProviderIdentityError;
9039
- }
9040
- function isParseableBodyJobId(value) {
9041
- return typeof value === "string" && value.trim().length > 0 && value.length <= 512 && !hasAsciiControl(value);
9042
- }
9043
- function isOpaqueJobToken(value) {
9044
- return typeof value === "string" && value.length > 0 && value.length <= 4096 && value.trim() === value && !hasAsciiControl(value);
9045
- }
9046
- function observedJobId(value) {
9047
- return isStorableJobId(value) ? value : void 0;
9048
- }
9049
- function observeJobId(value) {
9050
- if (value === void 0) return {};
9051
- if (isStorableJobId(value)) return { stored: value };
9052
- return { escaped: escapeObservedValue(value) };
9053
- }
9054
- var ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT = 1024;
9055
- function escapeObservedValue(value) {
9056
- const source = typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
9057
- const truncated = source.length > ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT;
9058
- const quoted = JSON.stringify(
9059
- truncated ? source.slice(0, ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT) : source
9060
- ).replace(
9061
- /[\u007f-\u009f]/gu,
9062
- (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
9063
- );
9064
- return truncated ? `${quoted} [truncated from ${String(source.length)} characters]` : quoted;
9065
- }
9066
- function settleJobIdentity(headerValue, body) {
9067
- const header = parseJobIdentityHeader(headerValue);
9068
- const headerJobId = header.kind === "valid" ? header.jobId : void 0;
9069
- const rawBodyJobId = body?.job_id;
9070
- const jobToken = isOpaqueJobToken(body?.job_token) ? body.job_token : void 0;
9071
- const observed = (kind) => {
9072
- const bodyJob = observeJobId(rawBodyJobId);
9073
- return {
9074
- kind: "unresolved",
9075
- observation: {
9076
- kind,
9077
- ...headerJobId ? { headerJobId } : {},
9078
- ...optionalField("bodyJobId", bodyJob.stored),
9079
- ...bodyJob.escaped ? { unstorable: { body_job_id: bodyJob.escaped } } : {},
9080
- ...jobToken ? { jobToken } : {}
9081
- }
9082
- };
9083
- };
9084
- if (!isParseableBodyJobId(rawBodyJobId)) return observed("body_unreadable");
9085
- if (headerJobId !== void 0 && headerJobId !== rawBodyJobId) {
9086
- return observed("identity_mismatch");
9087
- }
9088
- return {
9089
- kind: "settled",
9090
- jobId: rawBodyJobId,
9091
- claimAllowed: header.kind !== "invalid",
9092
- headerInvalid: header.kind === "invalid"
9093
- };
9094
- }
9095
- function routerConflictObservation(status2, body) {
9096
- if (status2 !== 409 || !body) return void 0;
9097
- const error = body.error;
9098
- if (!error || typeof error !== "object" || Array.isArray(error)) return void 0;
9099
- const envelope = error;
9100
- if (envelope.code !== IDENTITY_FAILURE_CODES.router_identity_conflict) return void 0;
9101
- const accepted = observeJobId(envelope.accepted_job_id);
9102
- return {
9103
- kind: "router_identity_conflict",
9104
- ...optionalField("acceptedJobId", accepted.stored),
9105
- ...accepted.escaped ? { unstorable: { accepted_job_id: accepted.escaped } } : {}
9106
- };
9107
- }
9108
- function jobIdentityHeaderValue(headers) {
9109
- return headers.get(JOB_IDENTITY_HEADER);
9110
- }
9111
- function identityError(observation, providerProse) {
9112
- const { message: message2, display } = describeIdentityFailure(observation);
9113
- return new ProviderIdentityError(
9114
- observation,
9115
- message2,
9116
- "Do not pay for this request again. Run 'dvm wallet submissions' to see what was recorded.",
9117
- {
9118
- identity_kind: observation.kind,
9119
- ...identityDataFields(observation),
9120
- display: providerProse?.display ?? display
9121
- },
9122
- providerProse?.proseSources
9123
- );
9124
- }
9125
- function withIdentityRecovery(err, ctx) {
9126
- 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.`;
9127
- return new ProviderIdentityError(
9128
- err.observation,
9129
- err.message,
9130
- hint,
9131
- {
9132
- ...err.data,
9133
- ambiguity_id: ctx.ambiguityId,
9134
- ...ctx.publicRequestId ? { request_id: ctx.publicRequestId } : {},
9135
- ...ctx.cashuRequestId ? { cashu_request_id: ctx.cashuRequestId } : {},
9136
- claim_stored: false
9137
- },
9138
- err.proseSources
9139
- );
9140
- }
9141
- function withRequestResultRecovery(err, ctx) {
9142
- const jobId = err.observation.acceptedJobId;
9143
- const read = `dvm status ${jobId ? shellQuoteArg(jobId) : "<accepted_job_id>"} --endpoint ${shellQuoteArg(ctx.endpoint)} --job-token <job_token_bearer_secret>`;
9144
- 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.`;
9145
- return new ProviderIdentityError(
9146
- err.observation,
9147
- err.message,
9148
- hint,
9149
- { ...err.data, ambiguity_id: ctx.ambiguityId, request_id: ctx.requestId, claim_stored: false },
9150
- err.proseSources
9151
- );
9152
- }
9153
- function identityDataFields(observation) {
9154
- return {
9155
- ...optionalField("header_job_id", observation.headerJobId),
9156
- ...optionalField("body_job_id", observation.bodyJobId),
9157
- ...optionalField("body_job_id_escaped", observation.unstorable?.body_job_id),
9158
- ...optionalField("accepted_job_id", observation.acceptedJobId),
9159
- ...optionalField("accepted_job_id_escaped", observation.unstorable?.accepted_job_id)
9160
- };
9161
- }
9162
- function warnInvalidJobIdentityHeader() {
9163
- const display = "The provider sent a malformed job identity header, so it was ignored and the job ID was taken from the response body.";
9164
- if (process.stderr.isTTY === true) {
9165
- info(`Warning: ${display}`);
9166
- return;
9167
- }
9168
- progress({ event: "warning", code: "job_identity_header_invalid", display });
9169
- }
9170
- function describeIdentityFailure(observation) {
9171
- switch (observation.kind) {
9172
- case "identity_mismatch":
9173
- return {
9174
- message: `The provider accepted the request but named job ${observation.headerJobId ?? "(unknown)"} in its response header and job ${observation.bodyJobId ?? "(unrepresentable)"} in its body.`,
9175
- 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."
9176
- };
9177
- case "body_unreadable":
9178
- return {
9179
- 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.",
9180
- 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."
9181
- };
9182
- case "router_identity_conflict":
9183
- return {
9184
- message: `The router had already accepted job ${observation.acceptedJobId ?? "(unknown)"} for this request, and the provider answered with a different job.`,
9185
- display: "This request was already accepted as a different job. Do not pay for it again."
9186
- };
9187
- }
9188
- }
9189
- function hasAsciiControl(value) {
9190
- for (const character of value) {
9191
- const code = character.charCodeAt(0);
9192
- if (code <= 31 || code === 127) return true;
9193
- }
9194
- return false;
9195
- }
9196
- function optionalField(key, value) {
9197
- return value === void 0 ? {} : { [key]: value };
9198
- }
9199
-
9200
- // src/lib/submission-evidence.ts
9201
- var SUBMISSION_EVIDENCE_DIR = join2(CONFIG_DIR, "submission-evidence");
9202
- function submissionEvidenceKey(args) {
9203
- return args.cashuRequestId ?? args.publicRequestId ?? randomUUID();
9204
- }
9205
- function recordSubmissionEvidence(input) {
9206
- const ambiguityId = submissionEvidenceKey(input);
9207
- const existing = loadSubmissionEvidence(ambiguityId);
9208
- if (existing) return existing;
9209
- const { observation } = input;
9210
- const jobToken = isOpaqueJobToken(observation.jobToken) ? observation.jobToken : void 0;
9211
- const record = {
9212
- v: 1,
9213
- ambiguity_id: ambiguityId,
9214
- kind: observation.kind,
9215
- observed_at: new Date((input.now ?? Date.now)()).toISOString(),
9216
- endpoint: input.endpoint,
9217
- ...input.dvmId ? { dvm_id: input.dvmId } : {},
9218
- ...input.capability ? { capability: input.capability } : {},
9219
- ...input.publicRequestId ? { request_id: input.publicRequestId } : {},
9220
- ...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
9221
- rail: input.rail,
9222
- ...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
9223
- ...jobToken ? { job_token: jobToken } : {},
9224
- ...boundedIds(observation),
9225
- ...observation.unstorable && Object.keys(observation.unstorable).length > 0 ? { unstorable_job_ids: observation.unstorable } : {},
9226
- claim_stored: false
9227
- };
9228
- return publishOnce(record);
9229
- }
9230
- function recordLocalJobCollision(input) {
9231
- const ambiguityId = `${input.publicRequestId}#local-job-collision`;
9232
- const existing = loadSubmissionEvidence(ambiguityId);
9233
- if (existing) return existing;
9234
- const jobToken = isOpaqueJobToken(input.jobToken) ? input.jobToken : void 0;
9235
- return publishOnce({
9236
- v: 1,
9237
- ambiguity_id: ambiguityId,
9238
- kind: "local_job_collision",
9239
- observed_at: new Date((input.now ?? Date.now)()).toISOString(),
9240
- endpoint: input.endpoint,
9241
- ...input.dvmId ? { dvm_id: input.dvmId } : {},
9242
- ...input.capability ? { capability: input.capability } : {},
9243
- request_id: input.publicRequestId,
9244
- ...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
9245
- rail: input.rail,
9246
- ...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
9247
- ...jobToken ? { job_token: jobToken } : {},
9248
- ...boundedIds({ acceptedJobId: input.jobId }),
9249
- claim_stored: false
9250
- });
9251
- }
9252
- function recordIdentityFailure(err, input) {
9253
- if (identityFailureRecorded(err)) return { error: err, record: null };
9254
- const record = recordSubmissionEvidence({ ...input, observation: err.observation });
9255
- return {
9256
- error: withIdentityRecovery(err, {
9257
- ambiguityId: record.ambiguity_id,
9258
- ...input.publicRequestId ? { publicRequestId: input.publicRequestId } : {},
9259
- ...input.cashuRequestId ? { cashuRequestId: input.cashuRequestId } : {}
9260
- }),
9261
- record
9262
- };
9263
- }
9264
- function identityFailureRecorded(err) {
9265
- return typeof err.data?.ambiguity_id === "string";
9266
- }
9267
- function loadSubmissionEvidence(ambiguityId) {
9268
- const path = evidencePath(ambiguityId);
9269
- if (!existsSync2(path)) return null;
9270
- const record = readRecord(path);
9271
- if (record.ambiguity_id !== ambiguityId) throw unreadable(path, "key mismatch");
9272
- return record;
9273
- }
9274
- function listSubmissionEvidence() {
9275
- if (!existsSync2(SUBMISSION_EVIDENCE_DIR)) return { records: [], unreadable: [] };
9276
- const records = [];
9277
- const unreadable2 = [];
9278
- for (const name of readdirSync(SUBMISSION_EVIDENCE_DIR).filter((n) => n.endsWith(".json"))) {
9279
- const path = join2(SUBMISSION_EVIDENCE_DIR, name);
9280
- try {
9281
- records.push(readRecord(path));
9282
- } catch (error) {
9283
- const cause = error instanceof DvmError ? error.data?.cause : void 0;
9284
- unreadable2.push({ path, cause: typeof cause === "string" ? cause : "unreadable" });
9285
- }
9286
- }
9287
- records.sort((a, b) => a.observed_at.localeCompare(b.observed_at));
9288
- return { records, unreadable: unreadable2 };
9289
- }
9290
- function journalMarkerFor(record) {
9291
- const kind = record.kind;
9292
- if (kind === "local_job_collision") {
9293
- throw unreadable(evidencePath(record.ambiguity_id), "not an identity failure");
9294
- }
9295
- return {
9296
- kind,
9297
- observed_at: record.observed_at,
9298
- ...boundedMarkerIds(record),
9299
- ambiguity_id: record.ambiguity_id
9300
- };
9301
- }
9302
- function publishOnce(record) {
9303
- const ambiguityId = record.ambiguity_id;
9304
- ensureConfigSubdir(SUBMISSION_EVIDENCE_DIR);
9305
- const target = evidencePath(ambiguityId);
9306
- const temp = `${target}.${String(process.pid)}.${randomUUID()}.tmp`;
9307
- const fd = openSync3(temp, "wx", 384);
9308
- try {
9309
- writeFileSync2(fd, JSON.stringify(record, null, 2) + "\n");
9310
- fsyncSync2(fd);
9311
- } finally {
9312
- closeSync3(fd);
9313
- }
9314
- try {
9315
- linkSync(temp, target);
9316
- } catch (error) {
9317
- if (error.code !== "EEXIST") throw error;
9318
- } finally {
9319
- unlinkSync2(temp);
9320
- }
9321
- fsyncDirectory2(SUBMISSION_EVIDENCE_DIR);
9322
- return loadSubmissionEvidence(ambiguityId) ?? record;
9323
- }
9324
- function boundedIds(observation) {
9325
- const header = observedJobId(observation.headerJobId);
9326
- const body = observedJobId(observation.bodyJobId);
9327
- const accepted = observedJobId(observation.acceptedJobId);
9328
- return {
9329
- ...header !== void 0 ? { header_job_id: header } : {},
9330
- ...body !== void 0 ? { body_job_id: body } : {},
9331
- ...accepted !== void 0 ? { accepted_job_id: accepted } : {}
9332
- };
9333
- }
9334
- function boundedMarkerIds(record) {
9335
- return boundedIds({
9336
- headerJobId: record.header_job_id,
9337
- bodyJobId: record.body_job_id,
9338
- acceptedJobId: record.accepted_job_id
9339
- });
9340
- }
9341
- function evidencePath(ambiguityId) {
9342
- const name = createHash("sha256").update(ambiguityId).digest("hex");
9343
- return join2(SUBMISSION_EVIDENCE_DIR, `${name}.json`);
9344
- }
9345
- function readRecord(path) {
9346
- let parsed;
9347
- try {
9348
- parsed = JSON.parse(readFileSync3(path, "utf8"));
9349
- } catch (error) {
9350
- throw unreadable(path, error instanceof Error ? error.message : String(error));
9351
- }
9352
- if (!isEvidenceRecord(parsed)) throw unreadable(path, "invalid shape");
9353
- return parsed;
9354
- }
9355
- function unreadable(path, cause) {
9356
- return new DvmError(
9357
- "submission_evidence_unreadable",
9358
- `A submission evidence record at ${path} is unreadable.`,
9359
- "Restore it from a backup. Do not pay again for any request it may describe; automatic retries stay off until it reads.",
9360
- { cause }
9361
- );
9362
- }
9363
- var KINDS = /* @__PURE__ */ new Set([
9364
- "identity_mismatch",
9365
- "body_unreadable",
9366
- "router_identity_conflict",
9367
- "local_job_collision"
9368
- ]);
9369
- var RAILS = /* @__PURE__ */ new Set(["cashu", "x402", "tempo", "credit", "none"]);
9370
- function isEvidenceRecord(value) {
9371
- if (!isPlainObject(value)) return false;
9372
- const record = value;
9373
- const optionalString = (key) => record[key] === void 0 || typeof record[key] === "string";
9374
- 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)) && [
9375
- "dvm_id",
9376
- "capability",
9377
- "request_id",
9378
- "cashu_request_id",
9379
- "job_token",
9380
- "header_job_id",
9381
- "body_job_id",
9382
- "accepted_job_id"
9383
- ].every(optionalString);
9384
- }
9385
- function isPlainObject(value) {
9386
- return typeof value === "object" && value !== null && !Array.isArray(value);
9387
- }
9388
- function isOptionalStringRecord(value) {
9389
- return value === void 0 || isPlainObject(value) && Object.values(value).every((entry) => typeof entry === "string");
9390
- }
9391
- function fsyncDirectory2(path) {
9392
- let fd;
9393
- try {
9394
- fd = openSync3(path, "r");
9395
- fsyncSync2(fd);
9396
- } finally {
9397
- if (fd !== void 0) closeSync3(fd);
9398
- }
9399
- }
9400
-
9401
- // src/lib/job-access.ts
9402
- function resolveJobAccess(jobId, opts) {
9403
- const stored = loadJob(jobId);
9404
- return resolveJobAccessWithRecord(jobId, opts, stored);
9405
- }
9406
- function resolveJobAccessWithRecord(jobId, opts, record) {
9407
- const endpointOverride = opts.endpoint ?? process.env.DVM_JOB_ENDPOINT;
9408
- const tokenOverride = opts.jobToken ?? process.env.DVM_JOB_TOKEN;
9409
- const endpointOverridden = endpointOverride !== void 0;
9410
- const tokenOverridden = tokenOverride !== void 0;
9411
- const foreign = record !== null && endpointOverride !== void 0 && !sameEndpoint(resolveEndpoint(endpointOverride), record.endpoint);
9412
- const stored = foreign ? null : record;
9413
- const rawEndpoint = endpointOverride ?? stored?.endpoint;
9414
- const jobToken = tokenOverride ?? stored?.jobToken;
9415
- if (!stored && rawEndpoint === void 0 && jobToken === void 0) {
9416
- throw new DvmError(
9417
- "job_access_required",
9418
- `Job ${jobId} is not in the local store, and no portable job access was supplied.`,
9419
- "Pass --endpoint <url> and --job-token <hex>, or set DVM_JOB_ENDPOINT and DVM_JOB_TOKEN."
9420
- );
9421
- }
9422
- if (rawEndpoint === void 0) {
9423
- throw new DvmError(
9424
- "job_endpoint_required",
9425
- `No provider endpoint is available for job ${jobId}.`,
9426
- "Pass --endpoint <url> or set DVM_JOB_ENDPOINT."
9427
- );
9428
- }
9429
- if (foreign && jobToken === void 0) {
9430
- throw foreignJobTokenRequired(jobId, record.endpoint, resolveEndpoint(endpointOverride));
9431
- }
9432
- if (!stored && jobToken === void 0) {
9433
- throw new DvmError(
9434
- "job_token_required",
9435
- `No job token is available for job ${jobId}.`,
9436
- "Pass --job-token <hex> or set DVM_JOB_TOKEN."
9437
- );
9438
- }
9439
- if (tokenOverridden && !isJobToken(jobToken)) {
9440
- throw new DvmError(
9441
- "invalid_job_token",
9442
- "The supplied job token is not a 64-character hexadecimal value.",
9443
- "Copy the job_token returned when the job was submitted; the value is never printed by this command."
9444
- );
9445
- }
9446
- return {
9447
- stored,
9448
- ref: { endpoint: validateProviderEndpoint(resolveEndpoint(rawEndpoint)) },
9449
- ...jobToken !== void 0 ? { jobToken } : {},
9450
- overridden: endpointOverridden || tokenOverridden,
9451
- endpointOverridden
9452
- };
9453
- }
9454
- function resolveStoredJobAccess(jobId, opts) {
9455
- const stored = loadJob(jobId);
9456
- if (!stored) {
9457
- throw new DvmError(
9458
- "job_payment_state_required",
9459
- `Cannot pay job ${jobId} without its local payment state.`,
9460
- "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."
9461
- );
9462
- }
9463
- return { ...resolveJobAccessWithRecord(jobId, opts, stored), stored };
9464
- }
9465
- async function withJobTokenRedaction(jobToken, action) {
9466
- try {
9467
- return await action();
9468
- } catch (err) {
9469
- throw redactJobTokenFromError(err, jobToken);
9470
- }
9471
- }
9472
- function redactJobTokenFromError(err, jobToken) {
9473
- if (!jobToken || !(err instanceof DvmError)) return err;
9474
- const redact = (value) => value.replaceAll(jobToken, "[REDACTED]");
9475
- return new DvmError(
9476
- err.code,
9477
- redact(err.message),
9478
- err.hint === void 0 ? void 0 : redact(err.hint),
9479
- err.data === void 0 ? void 0 : redactRecord(err.data, redact),
9480
- err.display === void 0 ? void 0 : redact(err.display),
9481
- err.proseSources
9482
- );
9483
- }
9484
- function sameEndpoint(a, b) {
9485
- const normalize = (value) => {
9486
- try {
9487
- const url = new URL(value);
9488
- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
9489
- } catch {
9490
- return value.replace(/\/+$/, "");
9491
- }
9492
- };
9493
- return normalize(a) === normalize(b);
9494
- }
9495
- function foreignJobTokenRequired(jobId, localEndpoint, endpoint) {
9496
- const row = evidenceRowWithToken(jobId, endpoint);
9497
- return new DvmError(
9498
- "job_token_required",
9499
- `Local job ${jobId} belongs to ${localEndpoint}. Its job token was issued there and is not sent to ${endpoint}.`,
9500
- 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.`,
9501
- {
9502
- job_id: jobId,
9503
- local_endpoint: localEndpoint,
9504
- endpoint,
9505
- ...row ? { ambiguity_id: row } : {}
9506
- }
9507
- );
9508
- }
9509
- function evidenceRowWithToken(jobId, endpoint) {
9510
- let records;
9511
- try {
9512
- ({ records } = listSubmissionEvidence());
9513
- } catch {
9514
- return void 0;
9515
- }
9516
- return records.filter(
9517
- (record) => record.job_token !== void 0 && sameEndpoint(record.endpoint, endpoint) && [record.header_job_id, record.body_job_id, record.accepted_job_id].includes(jobId)
9518
- ).at(-1)?.ambiguity_id;
9519
- }
9520
- function isJobToken(value) {
9521
- return value !== void 0 && /^[0-9a-fA-F]{64}$/.test(value);
9522
- }
9523
- function validateProviderEndpoint(value) {
9524
- try {
9525
- const url = new URL(value);
9526
- if ((url.protocol === "http:" || url.protocol === "https:") && url.hostname) return value;
9527
- } catch {
9528
- }
9529
- throw new DvmError(
9530
- "invalid_endpoint",
9531
- "The supplied job endpoint is not a valid HTTP(S) provider URL.",
9532
- "Pass a full URL such as https://provider.example, or a favorite alias such as @provider."
9533
- );
9534
- }
9535
- function redactRecord(record, redact) {
9536
- return Object.fromEntries(
9537
- Object.entries(record).map(([key, value]) => [key, redactValue(value, redact)])
9538
- );
9539
- }
9540
- function redactValue(value, redact) {
9541
- if (typeof value === "string") return redact(value);
9542
- if (Array.isArray(value)) return value.map((entry) => redactValue(entry, redact));
9543
- if (value && typeof value === "object") {
9544
- return redactRecord(value, redact);
9545
- }
9546
- return value;
9547
- }
9548
-
9549
8869
  // src/lib/credit-payment.ts
9550
- import { randomUUID as randomUUID2 } from "crypto";
8870
+ import { randomUUID } from "crypto";
9551
8871
 
9552
8872
  // src/lib/caller-version.ts
9553
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
9554
- import { dirname as dirname2, join as join3 } from "path";
8873
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
8874
+ import { dirname, join as join2 } from "path";
9555
8875
  import { fileURLToPath } from "url";
9556
8876
  var CALLER_VERSION = readCallerVersion();
9557
8877
  function readCallerVersion() {
9558
- let dir = dirname2(fileURLToPath(import.meta.url));
8878
+ let dir = dirname(fileURLToPath(import.meta.url));
9559
8879
  for (; ; ) {
9560
- const manifestPath = join3(dir, "package.json");
9561
- if (existsSync3(manifestPath)) {
8880
+ const manifestPath = join2(dir, "package.json");
8881
+ if (existsSync2(manifestPath)) {
9562
8882
  const manifest = readManifest(manifestPath);
9563
8883
  if (manifest.name === "@dvmkit/dvm-cli") return manifest.version;
9564
8884
  }
9565
- const parent = dirname2(dir);
8885
+ const parent = dirname(dir);
9566
8886
  if (parent === dir) {
9567
8887
  throw new Error(`No @dvmkit/dvm-cli package.json found walking up from ${import.meta.url}`);
9568
8888
  }
@@ -9570,7 +8890,7 @@ function readCallerVersion() {
9570
8890
  }
9571
8891
  }
9572
8892
  function readManifest(path) {
9573
- return JSON.parse(readFileSync4(path, "utf8"));
8893
+ return JSON.parse(readFileSync2(path, "utf8"));
9574
8894
  }
9575
8895
 
9576
8896
  // src/lib/client-compatibility.ts
@@ -10367,7 +9687,7 @@ async function tryCreditPayment(args) {
10367
9687
  const eligible = stored && stored.currency === ask.currency && stored.status === "active" && !stored.reconciliationPending && !stored.selectionCleared && (stored.expiryMs === 0 || stored.expiryMs > Date.now()) && stored.remainingMicro >= ask.amount_micro;
10368
9688
  const creditId = implicit?.creditId ?? (eligible ? stored.creditId : void 0);
10369
9689
  if (!creditId) return false;
10370
- binding = { creditId, drawId: randomUUID2(), callerPubkey: signer.pubkey };
9690
+ binding = { creditId, drawId: randomUUID(), callerPubkey: signer.pubkey };
10371
9691
  }
10372
9692
  if (!Number.isSafeInteger(request2.amount_msats) || request2.amount_msats <= 0) return false;
10373
9693
  const rate = await balanceCurrencyRate(ask.currency);
@@ -10395,7 +9715,7 @@ async function tryCreditPayment(args) {
10395
9715
  const authorization = signDvmRequestData(signer.privkey, {
10396
9716
  credit_id: selectedBinding.creditId,
10397
9717
  draw_id: selectedBinding.drawId,
10398
- payment_id: randomUUID2(),
9718
+ payment_id: randomUUID(),
10399
9719
  request_seq: requestSeq,
10400
9720
  amount_micro: ask.amount_micro,
10401
9721
  currency: ask.currency
@@ -10449,10 +9769,10 @@ async function sweepPendingSubmissions(opts = {}) {
10449
9769
  }
10450
9770
  };
10451
9771
  const now = opts.now ?? (() => Date.now());
10452
- const { entries, unreadable: unreadable2 } = await reconcileEvidenceMarkers(wallet);
9772
+ const { entries, unreadable } = await reconcileEvidenceMarkers(wallet);
10453
9773
  const outcomes = [];
10454
9774
  for (const entry of entries) {
10455
- outcomes.push(await resolveEntry(entry, deps, now(), unreadable2.has(entry.request_id)));
9775
+ outcomes.push(await resolveEntry(entry, deps, now(), unreadable.has(entry.request_id)));
10456
9776
  }
10457
9777
  if (outcomes.some(mutatesWallet)) {
10458
9778
  await withWalletLock(() => {
@@ -11256,7 +10576,13 @@ function applyOutcome(wallet, outcome, now) {
11256
10576
  recent_spends: [...dropped.recent_spends, recentSpend].slice(-RECENT_SPENDS_CAP)
11257
10577
  };
11258
10578
  }
11259
- if (outcome.kind === "abandoned" || outcome.kind === "pruned") {
10579
+ if (outcome.kind === "abandoned") {
10580
+ return abandonSubmissionInWallet(wallet, {
10581
+ requestId: outcome.entry.request_id,
10582
+ preserveRecovery: true
10583
+ });
10584
+ }
10585
+ if (outcome.kind === "pruned") {
11260
10586
  return drop();
11261
10587
  }
11262
10588
  if (outcome.kind === "swap_restored") {
@@ -11382,18 +10708,18 @@ function createDefaultHttpPost(fetchImpl) {
11382
10708
  };
11383
10709
  }
11384
10710
  async function reconcileEvidenceMarkers(wallet) {
11385
- const unreadable2 = /* @__PURE__ */ new Set();
10711
+ const unreadable = /* @__PURE__ */ new Set();
11386
10712
  const orphaned = wallet.pending_submissions.flatMap((entry) => {
11387
10713
  if (entry.accepted_unresolved) return [];
11388
10714
  try {
11389
10715
  const record = loadSubmissionEvidence(entry.request_id);
11390
10716
  return record ? [{ requestId: entry.request_id, marker: journalMarkerFor(record) }] : [];
11391
10717
  } catch {
11392
- unreadable2.add(entry.request_id);
10718
+ unreadable.add(entry.request_id);
11393
10719
  return [];
11394
10720
  }
11395
10721
  });
11396
- if (orphaned.length === 0) return { entries: wallet.pending_submissions, unreadable: unreadable2 };
10722
+ if (orphaned.length === 0) return { entries: wallet.pending_submissions, unreadable };
11397
10723
  return withWalletLock(() => {
11398
10724
  const fresh = loadAgentWallet() ?? wallet;
11399
10725
  const next = orphaned.reduce(
@@ -11401,7 +10727,7 @@ async function reconcileEvidenceMarkers(wallet) {
11401
10727
  fresh
11402
10728
  );
11403
10729
  saveAgentWallet(next);
11404
- return { entries: next.pending_submissions, unreadable: unreadable2 };
10730
+ return { entries: next.pending_submissions, unreadable };
11405
10731
  });
11406
10732
  }
11407
10733
  function evidenceState(ambiguityId) {
@@ -11705,8 +11031,8 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11705
11031
  }
11706
11032
  }
11707
11033
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11708
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UEQTGVJE.js");
11709
- const { tryX402Payment: tryX402Payment2 } = await import("./client-MMJYIMKJ.js");
11034
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-7BBWAZYJ.js");
11035
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-MFSKFSV4.js");
11710
11036
  const wallet = loadX402Wallet2();
11711
11037
  if (wallet) {
11712
11038
  let proof;
@@ -11735,7 +11061,8 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11735
11061
  }
11736
11062
  if (proof) {
11737
11063
  await enforceGlobalBudget({ plannedMsats: proof.amountMsats, btcRate: proof.btcRate });
11738
- await transport.sendMessage(
11064
+ await sendRailPayment(
11065
+ transport,
11739
11066
  jobId,
11740
11067
  {
11741
11068
  type: "payment",
@@ -11770,7 +11097,8 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11770
11097
  if (cred) {
11771
11098
  const paidMsats = usdcToMsats(Number(tempoCredentialAmountMicro(cred)) / 1e6, tempoRate);
11772
11099
  await enforceGlobalBudget({ plannedMsats: paidMsats, btcRate: tempoRate });
11773
- await transport.sendMessage(
11100
+ await sendRailPayment(
11101
+ transport,
11774
11102
  jobId,
11775
11103
  {
11776
11104
  type: "payment",
@@ -11867,7 +11195,7 @@ async function tryAgentWalletMidJobPayment(args) {
11867
11195
  });
11868
11196
  } catch (err) {
11869
11197
  if (err instanceof DvmError && err.code === "payment_invalid") {
11870
- await abandonPendingSubmission({ requestId: prepared.requestId });
11198
+ await abandonPendingSubmission({ requestId: prepared.requestId, preserveRecovery: true });
11871
11199
  }
11872
11200
  throw err;
11873
11201
  }
@@ -11894,7 +11222,8 @@ async function tryAgentWalletMidJobPayment(args) {
11894
11222
  async function sendMidJobPaymentWithRetry(args) {
11895
11223
  const { jobId, amountMsats, prepared, transport, provider, jobToken } = args;
11896
11224
  await withAgentWalletPaymentRetry({
11897
- attempt: () => transport.sendMessage(
11225
+ attempt: () => sendRailPayment(
11226
+ transport,
11898
11227
  jobId,
11899
11228
  {
11900
11229
  type: "payment",
@@ -11913,6 +11242,22 @@ async function sendMidJobPaymentWithRetry(args) {
11913
11242
  sleep: args.sleep
11914
11243
  });
11915
11244
  }
11245
+ async function sendRailPayment(transport, jobId, message2, provider, options) {
11246
+ const capture = (evidence) => {
11247
+ if (evidence.drawFundingReceiptParseError) info("Warning: mid-job funding evidence has an invalid shape.");
11248
+ if (evidence.drawFundingReceipt) captureDrawFundingReceipts(jobId, [evidence.drawFundingReceipt], {
11249
+ endpoint: provider.endpoint,
11250
+ ...typeof message2.content.cashu_request_id === "string" ? { fundId: message2.content.cashu_request_id } : {}
11251
+ });
11252
+ };
11253
+ try {
11254
+ const result = await transport.sendMessage(jobId, message2, provider, options);
11255
+ if (result) capture(result);
11256
+ } catch (error) {
11257
+ if (error instanceof DvmError && error.data) capture(error.data);
11258
+ throw error;
11259
+ }
11260
+ }
11916
11261
  async function tryMppCredential(challenges, amountMsats, btcRate) {
11917
11262
  const wallet = loadConfig()?.tempo;
11918
11263
  if (wallet?.method !== "tempo" || !wallet.apiKey) return null;
@@ -12361,6 +11706,7 @@ async function observeJobContent(jobId, transport, ref, options) {
12361
11706
  ...options,
12362
11707
  timeoutMs: options.timeoutMs > 0 ? Math.min(options.timeoutMs, 5e3) : 5e3
12363
11708
  });
11709
+ captureDrawFundingReceipts(jobId, status2.drawFundingReceipts, { endpoint: ref.endpoint });
12364
11710
  return parseJobContent(status2);
12365
11711
  } catch {
12366
11712
  return void 0;
@@ -12983,14 +12329,14 @@ var HttpsTransport = class {
12983
12329
  } catch {
12984
12330
  throw new DvmError("payment_insufficient", "Payment required (unparseable response).");
12985
12331
  }
12986
- const error = withCreditErrorContext(buildPaymentError(errorBody), errorBody);
12332
+ const error = withDrawFunding(withCreditErrorContext(buildPaymentError(errorBody), errorBody), errorBody);
12987
12333
  error.data = { ...error.data, http_status: 402 };
12988
12334
  throw error;
12989
12335
  }
12990
12336
  if (res.status === 409) {
12991
12337
  const body2 = parseJsonObject(await res.text());
12992
12338
  if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string"))
12993
- throw withCreditErrorContext(buildPaymentError(body2), body2);
12339
+ throw withDrawFunding(withCreditErrorContext(buildPaymentError(body2), body2), body2);
12994
12340
  throw new DvmError(
12995
12341
  "job_terminal",
12996
12342
  "Job is no longer active.",
@@ -13000,14 +12346,21 @@ var HttpsTransport = class {
13000
12346
  if (!res.ok) {
13001
12347
  const text = await res.text();
13002
12348
  const structured = parseStructuredError(text);
13003
- if (structured) throw withCreditErrorContext(structured, parseJsonObject(text) ?? {});
12349
+ if (structured) {
12350
+ const body2 = parseJsonObject(text) ?? {};
12351
+ throw withDrawFunding(withCreditErrorContext(structured, body2), body2);
12352
+ }
13004
12353
  throw providerResponseError("provider_error", `sendMessage failed (${res.status}): ${text}`);
13005
12354
  }
12355
+ if (message2.type !== "payment") return;
12356
+ const acknowledgement = parseJsonObject(await res.text());
13006
12357
  if (message2.type === "payment" && message2.content.credit) {
13007
- const body2 = parseJsonObject(await res.text());
13008
- if (res.status !== 201 || !Number.isSafeInteger(body2?.seq) || Number(body2?.seq) < 0)
12358
+ if (res.status !== 201 || !Number.isSafeInteger(acknowledgement?.seq) || Number(acknowledgement?.seq) < 0)
13009
12359
  throw new DvmError("invalid_credit_payment_response", "The balance payment outcome is unknown; replay the saved payment.");
13010
12360
  }
12361
+ if (acknowledgement && Number.isSafeInteger(acknowledgement.seq) && Number(acknowledgement.seq) >= 0) {
12362
+ return { seq: Number(acknowledgement.seq), ...parseDrawFundingReceipt(acknowledgement.draw_funding_receipt) };
12363
+ }
13011
12364
  }
13012
12365
  async stream(jobId, afterSeq, provider, options) {
13013
12366
  const endpoint = provider?.endpoint;
@@ -13106,12 +12459,24 @@ function parseFundingReceipt(value) {
13106
12459
  return isFundingReceipt(value) ? { fundingReceipt: value } : { fundingReceiptParseError: "shape_invalid" };
13107
12460
  }
13108
12461
  function parseFundingResponse(data) {
12462
+ const raw2 = data.draw_funding_receipts;
13109
12463
  return {
13110
12464
  ...parseFundingReceipt(data.funding_receipt),
13111
12465
  ...typeof data.funded_micro === "number" ? { fundedMicro: data.funded_micro } : {},
13112
- ...data.credit && typeof data.credit === "object" && !Array.isArray(data.credit) ? { credit: data.credit } : {}
12466
+ ...data.credit && typeof data.credit === "object" && !Array.isArray(data.credit) ? { credit: data.credit } : {},
12467
+ ...Array.isArray(raw2) ? { drawFundingReceipts: raw2.filter(isDrawFundingReceipt) } : {},
12468
+ ...raw2 !== void 0 && (!Array.isArray(raw2) || !raw2.every(isDrawFundingReceipt)) ? { drawFundingReceiptParseError: "shape_invalid" } : {}
13113
12469
  };
13114
12470
  }
12471
+ function parseDrawFundingReceipt(value) {
12472
+ if (value === void 0) return {};
12473
+ return isDrawFundingReceipt(value) ? { drawFundingReceipt: value } : { drawFundingReceiptParseError: "shape_invalid" };
12474
+ }
12475
+ function withDrawFunding(error, body) {
12476
+ const evidence = parseDrawFundingReceipt(body.draw_funding_receipt);
12477
+ if (Object.keys(evidence).length) error.data = { ...error.data, ...evidence };
12478
+ return error;
12479
+ }
13115
12480
  function parseRequestResultResponse(value, requestId, httpStatus) {
13116
12481
  if (!value || typeof value !== "object" || Array.isArray(value)) {
13117
12482
  throw malformedRequestResult(requestId, "response_not_object");
@@ -14115,14 +13480,14 @@ async function confirmRollback(stored, preview, opts) {
14115
13480
  async function withStrandingChecked(removing, commit) {
14116
13481
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
14117
13482
  if (leaving.has("tempo")) {
14118
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-HJQYBOZR.js");
13483
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-SVPMTND2.js");
14119
13484
  await assertTempoWalletIdle2("disconnect");
14120
13485
  }
14121
13486
  if (!leaving.has("x402")) return commit();
14122
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-LRW4XR3J.js");
14123
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-QE3KHIHQ.js");
14124
- const { ensureAddress: ensureAddress2 } = await import("./internal-LRW4XR3J.js");
14125
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UEQTGVJE.js");
13487
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-5EGKBZAE.js");
13488
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-7AVB36WP.js");
13489
+ const { ensureAddress: ensureAddress2 } = await import("./internal-5EGKBZAE.js");
13490
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-7BBWAZYJ.js");
14126
13491
  return withX402ChannelLock2(async () => {
14127
13492
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
14128
13493
  if (unsettled.length > 0) {
@@ -14550,7 +13915,7 @@ function creditDrainCommand(handle, creditId) {
14550
13915
  }
14551
13916
 
14552
13917
  // src/commands/wallet-history.ts
14553
- import { createHash as createHash2 } from "crypto";
13918
+ import { createHash } from "crypto";
14554
13919
 
14555
13920
  // src/lib/completed-credit-history.ts
14556
13921
  function completedCreditHistory(query = {}) {
@@ -14695,7 +14060,7 @@ function walletHistory(opts, now = /* @__PURE__ */ new Date()) {
14695
14060
  const windowed = (sinceMs === null ? all : all.filter((e) => e.timestamp >= sinceMs)).slice().sort(
14696
14061
  (a, b) => b.timestamp - a.timestamp || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0)
14697
14062
  );
14698
- const fingerprint = createHash2("sha256").update(JSON.stringify(windowed)).digest("hex");
14063
+ const fingerprint = createHash("sha256").update(JSON.stringify(windowed)).digest("hex");
14699
14064
  if (continuation && continuation.fingerprint !== fingerprint) {
14700
14065
  throw invalidHistoryCursor();
14701
14066
  }
@@ -15633,7 +14998,7 @@ function wireCreditCurrencyTotals(rows) {
15633
14998
 
15634
14999
  // src/lib/credit/drain.ts
15635
15000
  import {
15636
- randomUUID as randomUUID3
15001
+ randomUUID as randomUUID2
15637
15002
  } from "crypto";
15638
15003
  async function runCreditDrain(dvm, opts) {
15639
15004
  const endpoint = resolveCreditEndpoint(dvm);
@@ -15777,7 +15142,7 @@ async function runCreditDrain(dvm, opts) {
15777
15142
  const payout = await drainPayout(method, opts, channelBacked, dvm);
15778
15143
  const mintedThisRun = !pending4;
15779
15144
  let drain = pending4 ? reusableDrain(pending4, method, payout) : {
15780
- drainId: opts.drainId ?? randomUUID3(),
15145
+ drainId: opts.drainId ?? randomUUID2(),
15781
15146
  creditId,
15782
15147
  method,
15783
15148
  payout,
@@ -16648,7 +16013,7 @@ function refundAddress(address) {
16648
16013
 
16649
16014
  // src/lib/credit/funding.ts
16650
16015
  import {
16651
- randomUUID as randomUUID4
16016
+ randomUUID as randomUUID3
16652
16017
  } from "crypto";
16653
16018
  async function runCreditFund(dvm, opts) {
16654
16019
  const endpoint = resolveCreditEndpoint(dvm);
@@ -16714,6 +16079,14 @@ async function runCreditFund(dvm, opts) {
16714
16079
  });
16715
16080
  const configPin = effectiveFundingRail(config?.credit, endpoint, attestedIdentity);
16716
16081
  const boundRail = pinnedRail(stored, opts.creditId);
16082
+ if (!pending4 && !signedPending && flagRail && boundRail && flagRail !== boundRail) {
16083
+ throw new DvmError(
16084
+ "credit_rail_conflict",
16085
+ `This credit was opened over ${boundRail}, so it cannot be topped up over ${flagRail}. Nothing was paid.`,
16086
+ `Use --rail ${boundRail} for this credit, or supply a new --credit-id to open a separate credit over ${flagRail}.`,
16087
+ { credit_id: stored?.creditId, credit_rail: boundRail, requested_rail: flagRail }
16088
+ );
16089
+ }
16717
16090
  const railSource = flagRail ? "flag" : boundRail ? "credit_bound" : configPin.source === "per_dvm" || configPin.source === "global" ? configPin.source : void 0;
16718
16091
  const rail = pending4?.rail ?? flagRail ?? boundRail ?? configPin.rail;
16719
16092
  let amountMicro = pending4?.amountMicro ?? signedPending?.amountMicro ?? explicitMicro ?? (targetJobs === void 0 ? defaultFundMicro(stored) : void 0);
@@ -16752,7 +16125,7 @@ async function runCreditFund(dvm, opts) {
16752
16125
  transport,
16753
16126
  ref: { endpoint },
16754
16127
  signing: signer,
16755
- creditId: pending4?.creditId ?? opts.creditId ?? (canRefillStoredCredit(stored) ? stored.creditId : signedPending?.creditId ?? randomUUID4()),
16128
+ creditId: pending4?.creditId ?? opts.creditId ?? (canRefillStoredCredit(stored) ? stored.creditId : signedPending?.creditId ?? randomUUID3()),
16756
16129
  amountMicro: fundMicro,
16757
16130
  human: opts.human,
16758
16131
  providerInfo,
@@ -18481,8 +17854,8 @@ async function probeX402(x402, timeoutMs) {
18481
17854
  let network;
18482
17855
  let address;
18483
17856
  try {
18484
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UEQTGVJE.js");
18485
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-LRW4XR3J.js");
17857
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-7BBWAZYJ.js");
17858
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-5EGKBZAE.js");
18486
17859
  const wallet = loadX402Wallet2();
18487
17860
  if (!wallet) {
18488
17861
  const storedKey = x402.privateKey;
@@ -18534,8 +17907,8 @@ async function probeMpp(mpp, timeoutMs) {
18534
17907
  if (!mpp) return null;
18535
17908
  if (mpp.method === "tempo") {
18536
17909
  try {
18537
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-XN72C2GK.js");
18538
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-LRW4XR3J.js");
17910
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-5PKLSWFX.js");
17911
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-5EGKBZAE.js");
18539
17912
  const account = await connectedTempoAccount2();
18540
17913
  if (!account) {
18541
17914
  return {
@@ -18629,15 +18002,15 @@ function x402WrongAssetHint(asset) {
18629
18002
  }
18630
18003
 
18631
18004
  // src/lib/build-freshness.ts
18632
- import { existsSync as existsSync4, readdirSync as readdirSync2, statSync as statSync3 } from "fs";
18633
- import { dirname as dirname3, join as join4 } from "path";
18005
+ import { existsSync as existsSync3, readdirSync, statSync as statSync2 } from "fs";
18006
+ import { dirname as dirname2, join as join3 } from "path";
18634
18007
  import { fileURLToPath as fileURLToPath2 } from "url";
18635
18008
  var EXTRA_SOURCES = ["package.json", "tsup.config.ts"];
18636
18009
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "__snapshots__"]);
18637
18010
  var MAX_ENTRIES = 2e4;
18638
18011
  function checkBuildFreshness(opts) {
18639
18012
  const now = opts?.now ?? Date.now;
18640
- const moduleDir = opts?.moduleDir ?? dirname3(fileURLToPath2(import.meta.url));
18013
+ const moduleDir = opts?.moduleDir ?? dirname2(fileURLToPath2(import.meta.url));
18641
18014
  const root = findPackageRoot(moduleDir);
18642
18015
  const skipped = (skipReason) => ({
18643
18016
  status: "not_applicable",
@@ -18649,28 +18022,28 @@ function checkBuildFreshness(opts) {
18649
18022
  skipReason
18650
18023
  });
18651
18024
  if (root === null) return skipped("running_from_source");
18652
- const bundlePath = join4(root, "dist", "dvm.js");
18653
- if (dirname3(moduleDir) !== root || !existsSync4(bundlePath)) {
18025
+ const bundlePath = join3(root, "dist", "dvm.js");
18026
+ if (dirname2(moduleDir) !== root || !existsSync3(bundlePath)) {
18654
18027
  return skipped("running_from_source");
18655
18028
  }
18656
- const srcDir = join4(root, "src");
18657
- if (!existsSync4(srcDir)) return skipped("no_source_tree");
18658
- const builtAtMs = statSync3(bundlePath).mtimeMs;
18029
+ const srcDir = join3(root, "src");
18030
+ if (!existsSync3(srcDir)) return skipped("no_source_tree");
18031
+ const builtAtMs = statSync2(bundlePath).mtimeMs;
18659
18032
  const newer = [];
18660
18033
  let newestMs = 0;
18661
18034
  const visit = (dir, rel, budget2) => {
18662
18035
  if (budget2.left <= 0) return;
18663
- for (const entry of readdirSync2(dir, { withFileTypes: true })) {
18036
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
18664
18037
  if (budget2.left-- <= 0) return;
18665
18038
  if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
18666
- const abs = join4(dir, entry.name);
18039
+ const abs = join3(dir, entry.name);
18667
18040
  const relPath = rel ? `${rel}/${entry.name}` : entry.name;
18668
18041
  if (entry.isDirectory()) {
18669
18042
  visit(abs, relPath, budget2);
18670
18043
  continue;
18671
18044
  }
18672
18045
  if (!entry.isFile()) continue;
18673
- const mtimeMs = statSync3(abs).mtimeMs;
18046
+ const mtimeMs = statSync2(abs).mtimeMs;
18674
18047
  if (mtimeMs > newestMs) newestMs = mtimeMs;
18675
18048
  if (mtimeMs > builtAtMs) newer.push({ path: relPath, mtimeMs });
18676
18049
  }
@@ -18678,9 +18051,9 @@ function checkBuildFreshness(opts) {
18678
18051
  const budget = { left: MAX_ENTRIES };
18679
18052
  visit(srcDir, "src", budget);
18680
18053
  for (const name of EXTRA_SOURCES) {
18681
- const abs = join4(root, name);
18682
- if (!existsSync4(abs)) continue;
18683
- const mtimeMs = statSync3(abs).mtimeMs;
18054
+ const abs = join3(root, name);
18055
+ if (!existsSync3(abs)) continue;
18056
+ const mtimeMs = statSync2(abs).mtimeMs;
18684
18057
  if (mtimeMs > newestMs) newestMs = mtimeMs;
18685
18058
  if (mtimeMs > builtAtMs) newer.push({ path: name, mtimeMs });
18686
18059
  }
@@ -18697,26 +18070,26 @@ function checkBuildFreshness(opts) {
18697
18070
  function findPackageRoot(start) {
18698
18071
  let dir = start;
18699
18072
  for (; ; ) {
18700
- if (existsSync4(join4(dir, "package.json"))) return dir;
18701
- const parent = dirname3(dir);
18073
+ if (existsSync3(join3(dir, "package.json"))) return dir;
18074
+ const parent = dirname2(dir);
18702
18075
  if (parent === dir) return null;
18703
18076
  dir = parent;
18704
18077
  }
18705
18078
  }
18706
18079
 
18707
18080
  // src/lib/caller-state.ts
18708
- import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync4 } from "fs";
18709
- import { basename, join as join5 } from "path";
18081
+ import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync3, statSync as statSync3 } from "fs";
18082
+ import { basename, join as join4 } from "path";
18710
18083
  function detectSetupState() {
18711
18084
  return {
18712
18085
  existingState: {
18713
- jobs: existsSync5(JOBS_FILE),
18714
- messages: existsSync5(MESSAGES_DIR)
18086
+ jobs: existsSync4(JOBS_FILE),
18087
+ messages: existsSync4(MESSAGES_DIR)
18715
18088
  },
18716
18089
  missing: {
18717
- config: !existsSync5(CONFIG_FILE),
18718
- identity: !existsSync5(IDENTITIES_FILE),
18719
- wallet: !existsSync5(WALLET_FILE)
18090
+ config: !existsSync4(CONFIG_FILE),
18091
+ identity: !existsSync4(IDENTITIES_FILE),
18092
+ wallet: !existsSync4(WALLET_FILE)
18720
18093
  }
18721
18094
  };
18722
18095
  }
@@ -18835,21 +18208,21 @@ function findQuarantinedCreditStores() {
18835
18208
  const prefix = `${basename(CREDITS_FILE)}.corrupt-`;
18836
18209
  let entries;
18837
18210
  try {
18838
- entries = readdirSync3(CONFIG_DIR);
18211
+ entries = readdirSync2(CONFIG_DIR);
18839
18212
  } catch {
18840
18213
  return [];
18841
18214
  }
18842
- 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 }));
18215
+ 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 }));
18843
18216
  }
18844
18217
  function checkOne(spec) {
18845
- const exists = existsSync5(spec.path);
18218
+ const exists = existsSync4(spec.path);
18846
18219
  if (!exists) {
18847
18220
  return { name: spec.name, path: spec.path, exists: false };
18848
18221
  }
18849
18222
  const row = { name: spec.name, path: spec.path, exists: true };
18850
18223
  if (spec.json) {
18851
18224
  try {
18852
- JSON.parse(readFileSync5(spec.path, "utf-8"));
18225
+ JSON.parse(readFileSync3(spec.path, "utf-8"));
18853
18226
  row.parseable = true;
18854
18227
  } catch (err) {
18855
18228
  row.parseable = false;
@@ -18860,7 +18233,7 @@ function checkOne(spec) {
18860
18233
  checkSecretDirectory(spec.path, row);
18861
18234
  } else if (spec.secret) {
18862
18235
  try {
18863
- const mode = statSync4(spec.path).mode & 511;
18236
+ const mode = statSync3(spec.path).mode & 511;
18864
18237
  const modeOctal = octalMode(mode);
18865
18238
  row.modeOk = mode === 384;
18866
18239
  row.modeOctal = modeOctal;
@@ -18877,9 +18250,9 @@ function checkOne(spec) {
18877
18250
  function checkSecretDirectory(dir, row) {
18878
18251
  try {
18879
18252
  const offenders = [];
18880
- for (const name of readdirSync3(dir)) {
18881
- const path = join5(dir, name);
18882
- const stat = statSync4(path);
18253
+ for (const name of readdirSync2(dir)) {
18254
+ const path = join4(dir, name);
18255
+ const stat = statSync3(path);
18883
18256
  if (!stat.isFile()) continue;
18884
18257
  const mode = stat.mode & 511;
18885
18258
  if (mode !== 384) offenders.push({ path, modeOctal: octalMode(mode) });
@@ -18899,9 +18272,9 @@ function octalMode(mode) {
18899
18272
  return "0" + mode.toString(8).padStart(3, "0");
18900
18273
  }
18901
18274
  function readBtcRateCacheAge(now = Date.now()) {
18902
- if (!existsSync5(BTC_RATE_FILE)) return null;
18275
+ if (!existsSync4(BTC_RATE_FILE)) return null;
18903
18276
  try {
18904
- const data = JSON.parse(readFileSync5(BTC_RATE_FILE, "utf-8"));
18277
+ const data = JSON.parse(readFileSync3(BTC_RATE_FILE, "utf-8"));
18905
18278
  if (typeof data.timestamp !== "number") return null;
18906
18279
  return { ageMs: now - data.timestamp };
18907
18280
  } catch {
@@ -18910,21 +18283,21 @@ function readBtcRateCacheAge(now = Date.now()) {
18910
18283
  }
18911
18284
 
18912
18285
  // src/lib/mnemonic-backups.ts
18913
- import { readdirSync as readdirSync4, statSync as statSync5 } from "fs";
18914
- import { basename as basename2, dirname as dirname4, join as join6 } from "path";
18286
+ import { readdirSync as readdirSync3, statSync as statSync4 } from "fs";
18287
+ import { basename as basename2, dirname as dirname3, join as join5 } from "path";
18915
18288
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
18916
- const dir = dirname4(mnemonicFile);
18289
+ const dir = dirname3(mnemonicFile);
18917
18290
  const prefix = `${basename2(mnemonicFile)}.`;
18918
18291
  let names;
18919
18292
  try {
18920
- names = readdirSync4(dir);
18293
+ names = readdirSync3(dir);
18921
18294
  } catch (err) {
18922
18295
  if (err.code === "ENOENT") return [];
18923
18296
  throw err;
18924
18297
  }
18925
18298
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
18926
- const path = join6(dir, name);
18927
- const stat = statSync5(path);
18299
+ const path = join5(dir, name);
18300
+ const stat = statSync4(path);
18928
18301
  if (!stat.isFile()) return null;
18929
18302
  const ageMs2 = Math.max(0, nowMs - stat.mtimeMs);
18930
18303
  return {
@@ -20814,11 +20187,11 @@ async function favRm(name, opts) {
20814
20187
  }
20815
20188
 
20816
20189
  // src/lib/byte-source.ts
20817
- import { readFileSync as readFileSync6 } from "fs";
20190
+ import { readFileSync as readFileSync4 } from "fs";
20818
20191
  import { resolve } from "path";
20819
20192
  var STDIN_TIMEOUT_MS = 1e4;
20820
20193
  function readFileText(path) {
20821
- return readFileSync6(resolve(path), "utf-8");
20194
+ return readFileSync4(resolve(path), "utf-8");
20822
20195
  }
20823
20196
  var StdinTimeoutError = class extends Error {
20824
20197
  constructor(timeoutMs) {
@@ -20982,7 +20355,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
20982
20355
  }
20983
20356
 
20984
20357
  // src/lib/feedback-nudges.ts
20985
- import { existsSync as existsSync6, readFileSync as readFileSync7, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync3 } from "fs";
20358
+ import { existsSync as existsSync5, readFileSync as readFileSync5, renameSync, unlinkSync, writeFileSync } from "fs";
20986
20359
 
20987
20360
  // src/lib/feedback-notice.ts
20988
20361
  function buildFeedbackNudge(args) {
@@ -21034,10 +20407,10 @@ function effectiveFeedbackPosture(config) {
21034
20407
  return { posture: DEFAULT_FEEDBACK_POSTURE, source: "default" };
21035
20408
  }
21036
20409
  function loadFeedbackNudgeState() {
21037
- if (!existsSync6(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
20410
+ if (!existsSync5(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
21038
20411
  try {
21039
20412
  const parsed = JSON.parse(
21040
- readFileSync7(FEEDBACK_NUDGES_FILE, "utf-8")
20413
+ readFileSync5(FEEDBACK_NUDGES_FILE, "utf-8")
21041
20414
  );
21042
20415
  return {
21043
20416
  ...typeof parsed.introShownAt === "string" ? { introShownAt: parsed.introShownAt } : {},
@@ -21126,12 +20499,12 @@ function coercePerDvm(perDvm) {
21126
20499
  function saveState(state) {
21127
20500
  ensureConfigDir();
21128
20501
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
21129
- writeFileSync3(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
20502
+ writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
21130
20503
  try {
21131
- renameSync2(tmp, FEEDBACK_NUDGES_FILE);
20504
+ renameSync(tmp, FEEDBACK_NUDGES_FILE);
21132
20505
  } catch (err) {
21133
20506
  try {
21134
- unlinkSync3(tmp);
20507
+ unlinkSync(tmp);
21135
20508
  } catch {
21136
20509
  }
21137
20510
  throw err;
@@ -21140,9 +20513,9 @@ function saveState(state) {
21140
20513
  var nudgedThisInvocation = false;
21141
20514
 
21142
20515
  // src/lib/platform.ts
21143
- import { existsSync as existsSync7, mkdirSync, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
20516
+ import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "fs";
21144
20517
  import { homedir } from "os";
21145
- import { join as join7 } from "path";
20518
+ import { join as join6 } from "path";
21146
20519
  function getPlatformUrl() {
21147
20520
  return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
21148
20521
  }
@@ -21711,16 +21084,16 @@ function finalizeProgressLine() {
21711
21084
  import { randomBytes as randomBytes2 } from "crypto";
21712
21085
  import {
21713
21086
  chmodSync,
21714
- closeSync as closeSync4,
21087
+ closeSync as closeSync2,
21715
21088
  mkdtempSync,
21716
- openSync as openSync4,
21717
- readdirSync as readdirSync5,
21089
+ openSync as openSync2,
21090
+ readdirSync as readdirSync4,
21718
21091
  rmdirSync,
21719
- unlinkSync as unlinkSync4,
21720
- writeFileSync as writeFileSync5
21092
+ unlinkSync as unlinkSync2,
21093
+ writeFileSync as writeFileSync3
21721
21094
  } from "fs";
21722
21095
  import { tmpdir } from "os";
21723
- import { join as join8 } from "path";
21096
+ import { join as join7 } from "path";
21724
21097
 
21725
21098
  // src/lib/mime-ext.ts
21726
21099
  var MIME_TO_EXT = {
@@ -21776,11 +21149,11 @@ var ArtifactSaveSession = class {
21776
21149
  let created = false;
21777
21150
  try {
21778
21151
  const directory = this.ensureDirectory();
21779
- path = join8(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
21780
- fd = openSync4(path, "wx", FILE_MODE);
21152
+ path = join7(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
21153
+ fd = openSync2(path, "wx", FILE_MODE);
21781
21154
  created = true;
21782
- writeFileSync5(fd, buf);
21783
- closeSync4(fd);
21155
+ writeFileSync3(fd, buf);
21156
+ closeSync2(fd);
21784
21157
  fd = void 0;
21785
21158
  chmodSync(path, FILE_MODE);
21786
21159
  this.successfulWrites += 1;
@@ -21788,13 +21161,13 @@ var ArtifactSaveSession = class {
21788
21161
  } catch (err) {
21789
21162
  if (fd !== void 0) {
21790
21163
  try {
21791
- closeSync4(fd);
21164
+ closeSync2(fd);
21792
21165
  } catch {
21793
21166
  }
21794
21167
  }
21795
21168
  if (created && path) {
21796
21169
  try {
21797
- unlinkSync4(path);
21170
+ unlinkSync2(path);
21798
21171
  } catch {
21799
21172
  }
21800
21173
  }
@@ -21805,7 +21178,7 @@ var ArtifactSaveSession = class {
21805
21178
  }
21806
21179
  ensureDirectory() {
21807
21180
  if (this.directory) return this.directory;
21808
- const directory = mkdtempSync(join8(tmpdir(), "dvm-artifacts-"));
21181
+ const directory = mkdtempSync(join7(tmpdir(), "dvm-artifacts-"));
21809
21182
  try {
21810
21183
  chmodSync(directory, DIRECTORY_MODE);
21811
21184
  } catch (err) {
@@ -21821,7 +21194,7 @@ var ArtifactSaveSession = class {
21821
21194
  removeEmptyUnreportedDirectory() {
21822
21195
  if (!this.directory || this.successfulWrites > 0) return;
21823
21196
  try {
21824
- if (readdirSync5(this.directory).length === 0) {
21197
+ if (readdirSync4(this.directory).length === 0) {
21825
21198
  rmdirSync(this.directory);
21826
21199
  this.directory = void 0;
21827
21200
  }
@@ -22601,7 +21974,7 @@ function jsonParseErrorLine(jsonText, err) {
22601
21974
  // src/lib/structured-input-hint.ts
22602
21975
  function expectedFieldsFromSchema(schema) {
22603
21976
  const props = schema.properties;
22604
- if (!isPlainObject2(props)) return [];
21977
+ if (!isPlainObject(props)) return [];
22605
21978
  const requiredList = Array.isArray(schema.required) ? schema.required.filter((x) => typeof x === "string") : [];
22606
21979
  const required = new Set(requiredList);
22607
21980
  const out = [];
@@ -22642,11 +22015,11 @@ function buildStructuredInputHint(opts) {
22642
22015
  if (nextAction) data.next_action = nextAction;
22643
22016
  return { message: message2, hint, data };
22644
22017
  }
22645
- function isPlainObject2(value) {
22018
+ function isPlainObject(value) {
22646
22019
  return typeof value === "object" && value !== null && !Array.isArray(value);
22647
22020
  }
22648
22021
  function jsonSchemaType(node) {
22649
- if (!isPlainObject2(node)) return "unknown";
22022
+ if (!isPlainObject(node)) return "unknown";
22650
22023
  const t = node.type;
22651
22024
  if (typeof t === "string") return t;
22652
22025
  if (Array.isArray(t)) return t.filter((x) => typeof x === "string").join("|") || "unknown";
@@ -22724,16 +22097,16 @@ function findInputSchema(info2, capability) {
22724
22097
  if (capability) {
22725
22098
  const cap2 = info2.capabilities?.[capability];
22726
22099
  if (cap2) {
22727
- if (isPlainObject3(cap2.input_schema)) return cap2.input_schema;
22728
- const quote2 = isPlainObject3(cap2.pricing) ? cap2.pricing.quote : void 0;
22729
- if (isPlainObject3(quote2) && isPlainObject3(quote2.schema)) return quote2.schema;
22100
+ if (isPlainObject2(cap2.input_schema)) return cap2.input_schema;
22101
+ const quote2 = isPlainObject2(cap2.pricing) ? cap2.pricing.quote : void 0;
22102
+ if (isPlainObject2(quote2) && isPlainObject2(quote2.schema)) return quote2.schema;
22730
22103
  }
22731
22104
  }
22732
- if (isPlainObject3(info2.inputSchema)) return info2.inputSchema;
22733
- if (info2.quote && isPlainObject3(info2.quote.schema)) return info2.quote.schema;
22105
+ if (isPlainObject2(info2.inputSchema)) return info2.inputSchema;
22106
+ if (info2.quote && isPlainObject2(info2.quote.schema)) return info2.quote.schema;
22734
22107
  return void 0;
22735
22108
  }
22736
- function isPlainObject3(value) {
22109
+ function isPlainObject2(value) {
22737
22110
  return typeof value === "object" && value !== null && !Array.isArray(value);
22738
22111
  }
22739
22112
 
@@ -23261,7 +22634,7 @@ function buildPolicy(opts, btcRate) {
23261
22634
  }
23262
22635
 
23263
22636
  // src/commands/request.ts
23264
- import { createHash as createHash3, randomUUID as randomUUID5 } from "crypto";
22637
+ import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
23265
22638
 
23266
22639
  // src/lib/credit-defer.ts
23267
22640
  function noteDeferredFunding(funding) {
@@ -23294,10 +22667,27 @@ async function settleCreditAfterJob(args) {
23294
22667
  }
23295
22668
  }
23296
22669
  if (args.allowTopup !== false) {
23297
- const refill = args.refillPocket ?? (await import("./pocket-refill-DGA7UD7L.js")).refillPocketIfLow;
22670
+ const refill = args.refillPocket ?? (await import("./pocket-refill-SKECWGA3.js")).refillPocketIfLow;
23298
22671
  await refill({ human: args.human }).catch(() => void 0);
23299
22672
  }
23300
22673
  }
22674
+ async function settleCreditAfterRead(args) {
22675
+ const { job, capture } = args;
22676
+ const binding = job.creditBinding;
22677
+ const receipt = capture.receipt;
22678
+ if (job.strictPerCall || !binding || "unbound" in binding || !receipt?.credit || receipt.job_id !== job.id || receipt.requester_pubkey !== binding.callerPubkey || receipt.credit.credit_id !== binding.creditId || receipt.credit.draw_id !== binding.drawId || receipt.credit.credit_id.startsWith("imp:")) return;
22679
+ const builder = loadJob(job.id)?.builderAnchor ?? job.builderAnchor;
22680
+ await settleCreditAfterJob({
22681
+ capture,
22682
+ transport: args.transport,
22683
+ ref: { endpoint: job.endpoint },
22684
+ dvmId: job.dvmId,
22685
+ providerInfo: builder ? { builder } : void 0,
22686
+ callerPubkey: binding.callerPubkey,
22687
+ allowTopup: false,
22688
+ human: args.human
22689
+ });
22690
+ }
23301
22691
  function settleIdentity(args) {
23302
22692
  return providerDvmIdentity(args.providerInfo);
23303
22693
  }
@@ -23315,15 +22705,13 @@ function noticeDvm(args) {
23315
22705
  async function settle(args) {
23316
22706
  const receipt = args.capture?.receipt;
23317
22707
  const credit = receipt?.credit;
23318
- if (!receipt || !credit || !args.signing) return;
22708
+ const callerPubkey = args.signing?.pubkey ?? args.callerPubkey;
22709
+ if (!receipt || !credit || !callerPubkey || args.capture?.status !== "verified" && args.capture?.status !== "verified_unattested" || receipt.requester_pubkey !== callerPubkey) return;
23319
22710
  if (credit.credit_id.startsWith("imp:")) {
23320
- if (args.capture?.status !== "verified" && args.capture?.status !== "verified_unattested" || receipt.requester_pubkey !== args.signing.pubkey) {
23321
- return;
23322
- }
23323
22711
  const applied2 = applyImplicitReceiptCredit({
23324
22712
  endpoint: args.ref.endpoint,
23325
22713
  ...settleIdentityArgs(args),
23326
- callerPubkey: args.signing.pubkey,
22714
+ callerPubkey,
23327
22715
  jobId: receipt.job_id,
23328
22716
  outcome: receipt.outcome,
23329
22717
  credit,
@@ -23336,16 +22724,17 @@ async function settle(args) {
23336
22724
  const applied = applyReceiptCredit({
23337
22725
  endpoint: args.ref.endpoint,
23338
22726
  ...settleIdentityArgs(args),
23339
- callerPubkey: args.signing.pubkey,
22727
+ callerPubkey,
23340
22728
  jobId: receipt.job_id,
23341
22729
  outcome: receipt.outcome,
23342
- credit
22730
+ credit,
22731
+ drawFundings: jobDrawFundings(receipt.job_id, args.ref.endpoint, callerPubkey, credit)
23343
22732
  });
23344
22733
  if (!applied.credit) return;
23345
22734
  if (applied.mismatch) {
23346
22735
  renderBalanceMismatch(args.ref.endpoint, applied.mismatch);
23347
22736
  }
23348
- if (args.allowTopup === false) return;
22737
+ if (args.allowTopup === false || !args.signing) return;
23349
22738
  if (receipt.outcome !== "completed") return;
23350
22739
  const record = applied.credit;
23351
22740
  if (record.status !== "active") return;
@@ -23775,16 +23164,16 @@ function dollarLimitMicro(declaredLimit) {
23775
23164
 
23776
23165
  // src/lib/request-intent-store.ts
23777
23166
  import {
23778
- closeSync as closeSync5,
23779
- existsSync as existsSync8,
23780
- fsyncSync as fsyncSync3,
23167
+ closeSync as closeSync3,
23168
+ existsSync as existsSync7,
23169
+ fsyncSync,
23781
23170
  mkdirSync as mkdirSync2,
23782
- openSync as openSync5,
23783
- readFileSync as readFileSync9,
23784
- renameSync as renameSync3,
23785
- writeFileSync as writeFileSync6
23171
+ openSync as openSync3,
23172
+ readFileSync as readFileSync7,
23173
+ renameSync as renameSync2,
23174
+ writeFileSync as writeFileSync4
23786
23175
  } from "fs";
23787
- import { join as join9 } from "path";
23176
+ import { join as join8 } from "path";
23788
23177
  function saveRequestIntent(intent) {
23789
23178
  assertRequestId(intent.requestId);
23790
23179
  assertNoPaymentOrAuthSecrets(intent.body);
@@ -23796,27 +23185,27 @@ function saveRequestIntent(intent) {
23796
23185
  if (error.code === "EEXIST") return false;
23797
23186
  throw error;
23798
23187
  }
23799
- fsyncDirectory3(REQUEST_INTENTS_DIR);
23800
- const temp = join9(dir, `intent.${String(process.pid)}.tmp`);
23801
- const target = join9(dir, "intent.json");
23802
- const fd = openSync5(temp, "wx", 384);
23188
+ fsyncDirectory(REQUEST_INTENTS_DIR);
23189
+ const temp = join8(dir, `intent.${String(process.pid)}.tmp`);
23190
+ const target = join8(dir, "intent.json");
23191
+ const fd = openSync3(temp, "wx", 384);
23803
23192
  try {
23804
- writeFileSync6(fd, JSON.stringify(intent, null, 2) + "\n");
23805
- fsyncSync3(fd);
23193
+ writeFileSync4(fd, JSON.stringify(intent, null, 2) + "\n");
23194
+ fsyncSync(fd);
23806
23195
  } finally {
23807
- closeSync5(fd);
23196
+ closeSync3(fd);
23808
23197
  }
23809
- renameSync3(temp, target);
23810
- fsyncDirectory3(dir);
23198
+ renameSync2(temp, target);
23199
+ fsyncDirectory(dir);
23811
23200
  return true;
23812
23201
  }
23813
23202
  function loadRequestIntent(requestId) {
23814
23203
  assertRequestId(requestId);
23815
23204
  const dir = intentDirectory(requestId);
23816
- if (!existsSync8(dir)) return null;
23817
- const path = join9(dir, "intent.json");
23205
+ if (!existsSync7(dir)) return null;
23206
+ const path = join8(dir, "intent.json");
23818
23207
  try {
23819
- const parsed = JSON.parse(readFileSync9(path, "utf8"));
23208
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
23820
23209
  if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
23821
23210
  throw new Error("invalid shape");
23822
23211
  return parsed;
@@ -23866,15 +23255,16 @@ function assertRequestId(requestId) {
23866
23255
  );
23867
23256
  }
23868
23257
  function intentDirectory(requestId) {
23869
- return join9(REQUEST_INTENTS_DIR, requestId);
23258
+ return join8(REQUEST_INTENTS_DIR, requestId);
23870
23259
  }
23871
- function fsyncDirectory3(path) {
23260
+ function fsyncDirectory(path) {
23261
+ if (process.platform === "win32") return;
23872
23262
  let fd;
23873
23263
  try {
23874
- fd = openSync5(path, "r");
23875
- fsyncSync3(fd);
23264
+ fd = openSync3(path, "r");
23265
+ fsyncSync(fd);
23876
23266
  } finally {
23877
- if (fd !== void 0) closeSync5(fd);
23267
+ if (fd !== void 0) closeSync3(fd);
23878
23268
  }
23879
23269
  }
23880
23270
  function isRequestIntent(value) {
@@ -24394,7 +23784,7 @@ async function request(opts) {
24394
23784
  probePlan = { ...probePlan, drawId: opts.requestId };
24395
23785
  }
24396
23786
  if (probePlan.mode === "draw" && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing })) {
24397
- drawRequestId = randomUUID5();
23787
+ drawRequestId = randomUUID4();
24398
23788
  }
24399
23789
  const probeData = probePlan.mode === "draw" ? {
24400
23790
  ...unsignedData,
@@ -24798,7 +24188,7 @@ function identityArgs(identity) {
24798
24188
  return identity ? { identity } : {};
24799
24189
  }
24800
24190
  function sha256Hex(value) {
24801
- return createHash3("sha256").update(value, "utf8").digest("hex");
24191
+ return createHash2("sha256").update(value, "utf8").digest("hex");
24802
24192
  }
24803
24193
  async function fetchServerPriceMicro(transport, ref, envelope) {
24804
24194
  try {
@@ -24951,14 +24341,14 @@ async function recoverDrawProbe(err, args) {
24951
24341
  const plan = {
24952
24342
  mode: "draw",
24953
24343
  creditId: args.probePlan.creditId,
24954
- drawId: randomUUID5(),
24344
+ drawId: randomUUID4(),
24955
24345
  ...args.probePlan.source ? { source: args.probePlan.source } : {}
24956
24346
  };
24957
24347
  const requestId = submitCanCarryGeneratedRequestId({
24958
24348
  opts: args.opts,
24959
24349
  providerInfo: args.providerInfo,
24960
24350
  signing
24961
- }) ? randomUUID5() : void 0;
24351
+ }) ? randomUUID4() : void 0;
24962
24352
  const env = reSign({
24963
24353
  credit_id: plan.creditId,
24964
24354
  draw_id: plan.drawId,
@@ -25267,7 +24657,7 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
25267
24657
  let railSigning = creditCtx?.signing;
25268
24658
  let generatedRequestId;
25269
24659
  if (plan.mode === "none" && railSigning && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing: railSigning })) {
25270
- generatedRequestId = randomUUID5();
24660
+ generatedRequestId = randomUUID4();
25271
24661
  railSigning = {
25272
24662
  ...railSigning,
25273
24663
  unsignedData: { ...railSigning.unsignedData, request_id: generatedRequestId }
@@ -25746,7 +25136,7 @@ function recordUnconfirmedSpend(args) {
25746
25136
  recordSpendOnce({
25747
25137
  msats: args.msats,
25748
25138
  btcRate: args.btcRate,
25749
- jobId: args.key ?? `unconfirmed-${randomUUID5()}`,
25139
+ jobId: args.key ?? `unconfirmed-${randomUUID4()}`,
25750
25140
  providerEndpoint: args.endpoint,
25751
25141
  label: `unconfirmed \xB7 ${args.capability}`
25752
25142
  });
@@ -25854,7 +25244,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
25854
25244
  builderHandle = void 0;
25855
25245
  }
25856
25246
  const spendStartedMs = Date.now();
25857
- const generatedRequestId = fundPlan && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing }) ? randomUUID5() : void 0;
25247
+ const generatedRequestId = fundPlan && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing }) ? randomUUID4() : void 0;
25858
25248
  const withGeneratedRequestId = (unsigned) => generatedRequestId ? { ...unsigned, request_id: generatedRequestId } : unsigned;
25859
25249
  const perCallEnvelope = generatedRequestId && signing ? {
25860
25250
  ...envelope,
@@ -26940,6 +26330,10 @@ async function requestResult(requestId, opts = {}) {
26940
26330
  });
26941
26331
  }
26942
26332
  const captured = captureTransportReceipt(receipt.jobId, receipt);
26333
+ const recovered = loadJob(receipt.jobId);
26334
+ if (recovered && (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled")) {
26335
+ await settleCreditAfterRead({ job: recovered, capture: captured, transport, human: opts.human });
26336
+ }
26943
26337
  const confirmed = await bookRecoveredSubmissions({
26944
26338
  publicRequestId: requestId,
26945
26339
  endpoint: intent.endpoint,
@@ -27249,8 +26643,8 @@ async function statusWithAccess(jobId, opts, access) {
27249
26643
  const { stored, ref, jobToken } = access;
27250
26644
  if (stored && !access.overridden && isTerminalJobStatus(stored.status) && stored.completion && !opts.messages) {
27251
26645
  let receipt2 = replayStoredReceipt(stored);
26646
+ const transport2 = createDvmTransport();
27252
26647
  if (stored.receiptsSupported && receipt2.status === "absent") {
27253
- const transport2 = createDvmTransport();
27254
26648
  const fetched = await fetchMissingJobReceipt(jobId, transport2, ref);
27255
26649
  if (fetched.receipt || fetched.receiptParseError) {
27256
26650
  if (fetched.receipt && !stored.builderAnchor) {
@@ -27258,8 +26652,9 @@ async function statusWithAccess(jobId, opts, access) {
27258
26652
  }
27259
26653
  receipt2 = captureTransportReceipt(jobId, fetched);
27260
26654
  }
27261
- transport2.close();
27262
26655
  }
26656
+ await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
26657
+ transport2.close();
27263
26658
  renderStatus(jobId, stored, stored.status, stored.completion, "local", null, opts, {
27264
26659
  receipt: receipt2
27265
26660
  });
@@ -27269,6 +26664,7 @@ async function statusWithAccess(jobId, opts, access) {
27269
26664
  const transport = createDvmTransport();
27270
26665
  progressNotice("Checking job status...", opts.human);
27271
26666
  const result = await transport.status(jobId, ref, { timeoutMs: timeout, jobToken });
26667
+ if (stored && !access.endpointOverridden) captureDrawFundingReceipts(jobId, result.drawFundingReceipts, { endpoint: ref.endpoint });
27272
26668
  let msgs = [];
27273
26669
  let newCursor;
27274
26670
  if (opts.messages) {
@@ -27294,6 +26690,9 @@ async function statusWithAccess(jobId, opts, access) {
27294
26690
  await backfillTrustAnchor(jobId, transport, ref);
27295
26691
  }
27296
26692
  receipt = stored && !access.endpointOverridden ? captureTransportReceipt(jobId, result) : transientReceiptCapture(jobId, result);
26693
+ if (stored && !access.endpointOverridden) {
26694
+ await settleCreditAfterRead({ job: stored, capture: receipt, transport, human: opts.human });
26695
+ }
27297
26696
  if (stored && !access.endpointOverridden && !isTerminalJobStatus(stored.status)) {
27298
26697
  noteFeedbackAfterTerminal({
27299
26698
  jobId,
@@ -27406,17 +26805,17 @@ async function resolveNextAction(jobId, status2, fetched, transport, ref, opts)
27406
26805
  }
27407
26806
 
27408
26807
  // src/commands/upload.ts
27409
- import { statSync as statSync6 } from "fs";
26808
+ import { statSync as statSync5 } from "fs";
27410
26809
 
27411
26810
  // src/lib/upload-stream.ts
27412
- import { createHash as createHash4 } from "crypto";
26811
+ import { createHash as createHash3 } from "crypto";
27413
26812
  import { createReadStream } from "fs";
27414
26813
  import * as http2 from "http";
27415
26814
  import * as https from "https";
27416
26815
  var UPLOAD_RESPONSE_MAX_BYTES = 64 * 1024;
27417
26816
  function hashFile(filePath) {
27418
26817
  return new Promise((resolve3, reject) => {
27419
- const hasher = createHash4("sha256");
26818
+ const hasher = createHash3("sha256");
27420
26819
  let sizeBytes = 0;
27421
26820
  const stream = createReadStream(filePath);
27422
26821
  stream.on("data", (chunk) => {
@@ -27629,7 +27028,7 @@ async function upload(dvmRef, opts) {
27629
27028
  const target = resolveUploadTarget(qualified?.slug ?? dvmId, kind);
27630
27029
  let sizeOnDisk;
27631
27030
  try {
27632
- const st = statSync6(opts.file);
27031
+ const st = statSync5(opts.file);
27633
27032
  if (!st.isFile()) {
27634
27033
  throw new DvmError(
27635
27034
  "invalid_argument",
@@ -27891,7 +27290,7 @@ function getRailOnramp(rail) {
27891
27290
  }
27892
27291
 
27893
27292
  // src/lib/secret-input.ts
27894
- import { fstatSync, readFileSync as readFileSync10, realpathSync } from "fs";
27293
+ import { fstatSync, readFileSync as readFileSync8, realpathSync } from "fs";
27895
27294
  import { homedir as homedir2 } from "os";
27896
27295
  import { resolve as resolve2, sep } from "path";
27897
27296
  var BLOCKED_SECRET_PATHS = [
@@ -27971,7 +27370,7 @@ function readSecretFile(path, config) {
27971
27370
  throw err;
27972
27371
  }
27973
27372
  assertSafeFilePath(real);
27974
- return readFileSync10(real, "utf-8").trim();
27373
+ return readFileSync8(real, "utf-8").trim();
27975
27374
  }
27976
27375
  function readSecretStdin(config) {
27977
27376
  return new Promise((resolveStdin, reject) => {
@@ -29667,7 +29066,7 @@ function mnemonicValidationError(result) {
29667
29066
  var import_qrcode = __toESM(require_lib(), 1);
29668
29067
  import { randomBytes as randomBytes3 } from "crypto";
29669
29068
  import { tmpdir as tmpdir2 } from "os";
29670
- import { join as join10 } from "path";
29069
+ import { join as join9 } from "path";
29671
29070
  async function renderQrTerminal(payload) {
29672
29071
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
29673
29072
  }
@@ -29680,7 +29079,7 @@ async function renderQrPng(payload, outPath) {
29680
29079
  });
29681
29080
  }
29682
29081
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
29683
- return join10(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
29082
+ return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
29684
29083
  }
29685
29084
 
29686
29085
  // src/lib/funding-handoff.ts
@@ -33236,7 +32635,7 @@ function resolveMppEndpoint(identifier) {
33236
32635
  }
33237
32636
 
33238
32637
  // src/commands/wallet-pair.ts
33239
- import { createHash as createHash5, randomBytes as randomBytes5 } from "crypto";
32638
+ import { createHash as createHash4, randomBytes as randomBytes5 } from "crypto";
33240
32639
  import { hostname } from "os";
33241
32640
 
33242
32641
  // node_modules/@noble/ciphers/_arx.js
@@ -34055,17 +33454,17 @@ function hexToBytes2(hex) {
34055
33454
  }
34056
33455
 
34057
33456
  // src/lib/wallet-pairing-store.ts
34058
- var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
33457
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
34059
33458
  import {
34060
33459
  chmodSync as chmodSync2,
34061
- existsSync as existsSync9,
34062
- readdirSync as readdirSync6,
34063
- readFileSync as readFileSync11,
34064
- renameSync as renameSync4,
34065
- unlinkSync as unlinkSync5,
34066
- writeFileSync as writeFileSync7
33460
+ existsSync as existsSync8,
33461
+ readdirSync as readdirSync5,
33462
+ readFileSync as readFileSync9,
33463
+ renameSync as renameSync3,
33464
+ unlinkSync as unlinkSync3,
33465
+ writeFileSync as writeFileSync5
34067
33466
  } from "fs";
34068
- import { join as join11 } from "path";
33467
+ import { join as join10 } from "path";
34069
33468
  var pairingIdPattern = /^[0-9a-f]{64}$/;
34070
33469
  var stateSchema = external_exports.object({
34071
33470
  version: external_exports.literal(1),
@@ -34087,12 +33486,12 @@ var stateSchema = external_exports.object({
34087
33486
  function createWalletPairingState(state) {
34088
33487
  ensurePairingsDirectory();
34089
33488
  const path = pairingPath(state.pairing_id);
34090
- writeFileSync7(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
33489
+ writeFileSync5(path, JSON.stringify(state, null, 2) + "\n", { mode: 384, flag: "wx" });
34091
33490
  chmodSync2(path, 384);
34092
33491
  }
34093
33492
  function loadWalletPairingState(pairingId) {
34094
33493
  const path = pairingPath(pairingId);
34095
- if (!existsSync9(path)) {
33494
+ if (!existsSync8(path)) {
34096
33495
  throw new DvmError(
34097
33496
  "wallet_pairing_not_found",
34098
33497
  "No local state exists for that wallet pairing.",
@@ -34100,7 +33499,7 @@ function loadWalletPairingState(pairingId) {
34100
33499
  );
34101
33500
  }
34102
33501
  try {
34103
- return stateSchema.parse(JSON.parse(readFileSync11(path, "utf8")));
33502
+ return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34104
33503
  } catch {
34105
33504
  throw new DvmError(
34106
33505
  "wallet_pairing_state_invalid",
@@ -34114,13 +33513,13 @@ function saveWalletPairingState(state) {
34114
33513
  ensurePairingsDirectory();
34115
33514
  const path = pairingPath(state.pairing_id);
34116
33515
  const tmp = `${path}.tmp`;
34117
- writeFileSync7(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
33516
+ writeFileSync5(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
34118
33517
  try {
34119
- renameSync4(tmp, path);
33518
+ renameSync3(tmp, path);
34120
33519
  chmodSync2(path, 384);
34121
33520
  } catch (err) {
34122
33521
  try {
34123
- unlinkSync5(tmp);
33522
+ unlinkSync3(tmp);
34124
33523
  } catch {
34125
33524
  }
34126
33525
  throw err;
@@ -34129,21 +33528,21 @@ function saveWalletPairingState(state) {
34129
33528
  function deleteWalletPairingState(pairingId) {
34130
33529
  const path = pairingPath(pairingId);
34131
33530
  try {
34132
- unlinkSync5(path);
33531
+ unlinkSync3(path);
34133
33532
  } catch (err) {
34134
33533
  if (err.code !== "ENOENT") throw err;
34135
33534
  }
34136
33535
  }
34137
33536
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
34138
- if (!existsSync9(PAIRINGS_DIR)) return 0;
33537
+ if (!existsSync8(PAIRINGS_DIR)) return 0;
34139
33538
  let removed = 0;
34140
- for (const name of readdirSync6(PAIRINGS_DIR)) {
33539
+ for (const name of readdirSync5(PAIRINGS_DIR)) {
34141
33540
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
34142
- const path = join11(PAIRINGS_DIR, name);
33541
+ const path = join10(PAIRINGS_DIR, name);
34143
33542
  try {
34144
- const state = stateSchema.parse(JSON.parse(readFileSync11(path, "utf8")));
33543
+ const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34145
33544
  if (state.manifest.expires_at <= nowSeconds) {
34146
- unlinkSync5(path);
33545
+ unlinkSync3(path);
34147
33546
  removed += 1;
34148
33547
  }
34149
33548
  } catch {
@@ -34153,10 +33552,10 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
34153
33552
  }
34154
33553
  async function withWalletPairingLock(pairingId, fn) {
34155
33554
  const path = pairingPath(pairingId);
34156
- if (!existsSync9(path)) return fn();
33555
+ if (!existsSync8(path)) return fn();
34157
33556
  let release;
34158
33557
  try {
34159
- release = await import_proper_lockfile2.default.lock(path, {
33558
+ release = await import_proper_lockfile.default.lock(path, {
34160
33559
  lockfilePath: `${path}.lock`,
34161
33560
  realpath: false,
34162
33561
  stale: 12 * 60 * 1e3,
@@ -34183,7 +33582,7 @@ function pairingPath(pairingId) {
34183
33582
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
34184
33583
  );
34185
33584
  }
34186
- return join11(PAIRINGS_DIR, `${pairingId}.json`);
33585
+ return join10(PAIRINGS_DIR, `${pairingId}.json`);
34187
33586
  }
34188
33587
  function ensurePairingsDirectory() {
34189
33588
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -34608,7 +34007,7 @@ function walletFingerprint(uri) {
34608
34007
  return uri ? sha2562(uri) : null;
34609
34008
  }
34610
34009
  function sha2562(value) {
34611
- return createHash5("sha256").update(value).digest("hex");
34010
+ return createHash4("sha256").update(value).digest("hex");
34612
34011
  }
34613
34012
  function relayHost2(relay) {
34614
34013
  try {
@@ -34736,12 +34135,12 @@ async function walletSubmissions(opts) {
34736
34135
  function listSubmissions(opts) {
34737
34136
  const listed = listSubmissionEvidence();
34738
34137
  const evidence = describeSubmissionEvidence(listed.records);
34739
- const unreadable2 = listed.unreadable;
34740
- const wallet = evidence.length > 0 || unreadable2.length > 0 ? loadAgentWallet() : loadWalletOrThrow();
34138
+ const unreadable = listed.unreadable;
34139
+ const wallet = evidence.length > 0 || unreadable.length > 0 ? loadAgentWallet() : loadWalletOrThrow();
34741
34140
  const summary = wallet ? describePendingSubmissions(wallet) : EMPTY_SUMMARY;
34742
34141
  if (opts.human) {
34743
34142
  printEvidenceHuman(evidence);
34744
- for (const file of unreadable2) {
34143
+ for (const file of unreadable) {
34745
34144
  info(`Unreadable evidence record (${file.cause}): ${file.path}. Restore it from a backup; do not pay again for any request it may describe.`);
34746
34145
  }
34747
34146
  if (summary.entries.length === 0) {
@@ -34796,17 +34195,17 @@ function listSubmissions(opts) {
34796
34195
  // Accepted without a settled job identity: held so nothing pays twice.
34797
34196
  accepted_unresolved_count: summary.accepted_unresolved_count,
34798
34197
  submission_evidence: evidence,
34799
- ...unreadable2.length > 0 ? { submission_evidence_unreadable: unreadable2 } : {},
34198
+ ...unreadable.length > 0 ? { submission_evidence_unreadable: unreadable } : {},
34800
34199
  display: [
34801
34200
  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.`,
34802
34201
  evidence.length > 0 ? `${evidence.length} paid call(s) were accepted without a clear job ID; see submission_evidence. None was paid for again.` : null,
34803
- 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
34202
+ unreadable.length > 0 ? `${unreadable.length} evidence record(s) cannot be read; see submission_evidence_unreadable. The payments they may describe are held and not sent again.` : null
34804
34203
  ].filter(Boolean).join(" "),
34805
34204
  hint: [
34806
34205
  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,
34807
34206
  summary.reclaimable_count > 0 ? "Entries in state reclaimable need no action \u2014 the wallet takes those sats back after reclaim_at." : null,
34808
34207
  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,
34809
- unreadable2.length > 0 ? "Restore each file in submission_evidence_unreadable from a backup. Do not pay again for any request it may describe." : null,
34208
+ unreadable.length > 0 ? "Restore each file in submission_evidence_unreadable from a backup. Do not pay again for any request it may describe." : null,
34810
34209
  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,
34811
34210
  "Resumable entries retry on the next paid call or `dvm wallet show`."
34812
34211
  ].filter(Boolean).join(" ")