@dvmkit/dvm-cli 0.9.2 → 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,14 +5,15 @@ 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,
17
18
  abandonSubmissionInWallet,
18
19
  addPayment,
@@ -22,10 +23,12 @@ import {
22
23
  backfillTrustAnchor,
23
24
  bookCreditPayment,
24
25
  buildTempoCredential,
26
+ captureDrawFundingReceipts,
25
27
  captureFundingReceipt,
26
28
  captureTransportReceipt,
27
29
  commitAgentSpend,
28
30
  correctPendingFundAmount,
31
+ deriveAlias,
29
32
  describeMintBounds,
30
33
  drainReceiptsDisplay,
31
34
  drainReceiptsHint,
@@ -43,11 +46,22 @@ import {
43
46
  fundAgentWallet,
44
47
  fundCredit,
45
48
  fundTimeoutMs,
49
+ identityDataFields,
50
+ identityError,
46
51
  inFlightTimeoutSeconds,
52
+ isIdentityFailure,
53
+ isOpaqueJobToken,
54
+ isParseableBodyJobId,
55
+ jobDrawFundings,
56
+ jobIdentityHeaderValue,
57
+ journalMarkerFor,
58
+ listSubmissionEvidence,
47
59
  loadAllJobs,
60
+ loadFavorites,
48
61
  loadFloat,
49
62
  loadJob,
50
63
  loadLedger,
64
+ loadSubmissionEvidence,
51
65
  markJobTerminal,
52
66
  markPendingSubmissionUnresolved,
53
67
  markProofsInFlight,
@@ -72,15 +86,26 @@ import {
72
86
  receiptJsonFields,
73
87
  receiptTrustFields,
74
88
  recordFloatSpend,
89
+ recordIdentityFailure,
90
+ recordLocalJobCollision,
75
91
  recordSpend,
76
92
  recordSpendOnce,
93
+ recordSubmissionEvidence,
94
+ removeFavorite,
77
95
  renderReceiptHuman,
78
96
  replayStoredReceipt,
79
97
  reservedForMarker,
98
+ resolveEndpoint,
80
99
  resolveFundMint,
100
+ resolveJobAccess,
101
+ resolveStoredJobAccess,
81
102
  revertInFlight,
103
+ routerConflictObservation,
104
+ sameEndpoint,
105
+ saveFavorite,
82
106
  saveJob,
83
107
  saveLedger,
108
+ settleJobIdentity,
84
109
  statusSnapshot,
85
110
  sweepPendingMints,
86
111
  sweepStaleInFlight,
@@ -90,14 +115,18 @@ import {
90
115
  trustOverrideCapMicro,
91
116
  unrecordedFloatBudgetWarning,
92
117
  updateJob,
93
- withAcceptedUnresolved
94
- } from "./chunk-MVVKMKWR.js";
118
+ warnInvalidJobIdentityHeader,
119
+ withAcceptedUnresolved,
120
+ withIdentityRecovery,
121
+ withJobTokenRedaction,
122
+ withRequestResultRecovery
123
+ } from "./chunk-Q45TAYK2.js";
95
124
  import {
96
125
  connectedTempoAccount,
97
126
  generateTempoKey,
98
127
  tempoBalanceCheckHint,
99
128
  tempoWrongAssetHint
100
- } from "./chunk-BCDMVIPI.js";
129
+ } from "./chunk-NXXU3BSJ.js";
101
130
  import {
102
131
  assertValidBudget,
103
132
  costAnchor,
@@ -109,14 +138,13 @@ import {
109
138
  json,
110
139
  monetaryJson,
111
140
  parseBudget,
112
- progress,
113
141
  raw,
114
142
  resolveBtcUsdRate,
115
143
  setOutputTraceId,
116
144
  staleRateNotice,
117
145
  tryResolveBtcUsdRate,
118
146
  tryX402Payment
119
- } from "./chunk-C7ZNQONB.js";
147
+ } from "./chunk-C3HMFGYP.js";
120
148
  import {
121
149
  assertSupportedX402Network,
122
150
  connectedX402Payer,
@@ -125,7 +153,7 @@ import {
125
153
  repinX402WalletNetwork,
126
154
  saveX402Wallet,
127
155
  x402NetworkLabel
128
- } from "./chunk-PMPHS3LS.js";
156
+ } from "./chunk-MTGQK7KA.js";
129
157
  import {
130
158
  CREDIT_POSTURES,
131
159
  FEEDBACK_POSTURES,
@@ -142,7 +170,7 @@ import {
142
170
  retireConfigBackup,
143
171
  rollbackConfig,
144
172
  updateConfig
145
- } from "./chunk-QDOY3JF2.js";
173
+ } from "./chunk-GMOKL4PQ.js";
146
174
  import {
147
175
  A,
148
176
  AGENT_MNEMONIC_FILE,
@@ -167,7 +195,6 @@ import {
167
195
  IDENTITIES_FILE,
168
196
  IDENTITIES_VERSION,
169
197
  JOBS_FILE,
170
- JOB_IDENTITY_HEADER,
171
198
  MESSAGES_DIR,
172
199
  PAIRINGS_DIR,
173
200
  PRIVKEY_HEX_RE,
@@ -265,11 +292,11 @@ import {
265
292
  isCreditFundRail,
266
293
  isCreditFundingMode,
267
294
  isDrainReceipt,
295
+ isDrawFundingReceipt,
268
296
  isFundingReceipt,
269
297
  isPublicRequestId,
270
298
  isSignedJobReceipt,
271
299
  isStablecoinFundRail,
272
- isStorableJobId,
273
300
  ki,
274
301
  la,
275
302
  listCredits,
@@ -387,7 +414,7 @@ import {
387
414
  x402PendingUnsettled,
388
415
  x402RequiredFromError,
389
416
  x402ReservationRelease
390
- } from "./chunk-6XTWANVN.js";
417
+ } from "./chunk-CWWZM4M6.js";
391
418
  import "./chunk-JBU7RKQ3.js";
392
419
  import "./chunk-KDNFUDOG.js";
393
420
  import "./chunk-IUTVV6N5.js";
@@ -8747,14 +8774,19 @@ function computeNextAction(jobId, messages2) {
8747
8774
  return null;
8748
8775
  case "prompt": {
8749
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." : "";
8750
8780
  const action = {
8751
8781
  type: "respond",
8752
8782
  job_id: jobId,
8753
8783
  prompt_id: c.id,
8754
8784
  prompt: asProviderText(c.text),
8755
- 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)}\`.`
8756
8787
  };
8757
8788
  if (c.schema) action.schema = c.schema;
8789
+ if (c.options?.length) action.options = c.options;
8758
8790
  return action;
8759
8791
  }
8760
8792
  case "payment-request": {
@@ -8769,7 +8801,7 @@ function computeNextAction(jobId, messages2) {
8769
8801
  ...c.fiat_amount && c.fiat_amount.amount > 0 ? { fiat_amount: c.fiat_amount } : {},
8770
8802
  display,
8771
8803
  reason: asProviderText(c.reason),
8772
- 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.`
8773
8805
  };
8774
8806
  }
8775
8807
  case "working": {
@@ -8834,736 +8866,23 @@ function formatPaidAmount(result, fiat) {
8834
8866
  return formatPaymentAmount(result.amountMsats, fiat, { anchor: false });
8835
8867
  }
8836
8868
 
8837
- // src/lib/favorites.ts
8838
- var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
8839
- import {
8840
- closeSync as closeSync2,
8841
- fchmodSync,
8842
- fsyncSync,
8843
- openSync as openSync2,
8844
- readFileSync as readFileSync2,
8845
- renameSync,
8846
- statSync as statSync2,
8847
- unlinkSync,
8848
- writeFileSync
8849
- } from "fs";
8850
- import { dirname } from "path";
8851
- var DEFAULT_FILE_MODE = 384;
8852
- function loadFavorites() {
8853
- let raw2;
8854
- try {
8855
- raw2 = readFileSync2(FAVORITES_FILE, "utf8");
8856
- } catch (error) {
8857
- if (nodeErrorCode(error) === "ENOENT") return {};
8858
- throw unreadableFavorites(error);
8859
- }
8860
- try {
8861
- const parsed = JSON.parse(raw2);
8862
- if (!isFavoritesMap(parsed)) throw new Error("invalid favorites shape");
8863
- return parsed;
8864
- } catch (error) {
8865
- throw unreadableFavorites(error);
8866
- }
8867
- }
8868
- async function saveFavorite(alias, fav) {
8869
- return withFavoritesLock(() => {
8870
- const favs = loadFavorites();
8871
- const existed = Object.hasOwn(favs, alias);
8872
- favs[alias] = fav;
8873
- writeFavorites(favs);
8874
- return existed;
8875
- });
8876
- }
8877
- async function removeFavorite(alias) {
8878
- return withFavoritesLock(() => {
8879
- const favs = loadFavorites();
8880
- if (!Object.hasOwn(favs, alias)) return false;
8881
- const { [alias]: _, ...rest } = favs;
8882
- writeFavorites(rest);
8883
- return true;
8884
- });
8885
- }
8886
- function resolveEndpoint(input) {
8887
- if (!input.startsWith("@")) return input;
8888
- const alias = input.slice(1);
8889
- const favs = loadFavorites();
8890
- const fav = Object.hasOwn(favs, alias) ? favs[alias] : void 0;
8891
- if (!fav) {
8892
- throw new DvmError(
8893
- "unknown_favorite",
8894
- `No favorite named "${alias}".`,
8895
- "Run 'dvm fav list' to see saved favorites, or 'dvm fav add <endpoint>' to save one."
8896
- );
8897
- }
8898
- return fav.endpoint;
8899
- }
8900
- function deriveAlias(endpoint) {
8901
- try {
8902
- const hostname2 = new URL(endpoint).hostname;
8903
- if (hostname2.endsWith(".dvmkit.ai")) {
8904
- const prefix = hostname2.replace(".dvmkit.ai", "");
8905
- const dashIdx = prefix.indexOf("--");
8906
- if (dashIdx !== -1) return prefix.slice(dashIdx + 2);
8907
- return prefix;
8908
- }
8909
- return hostname2.replace(/\.[^.]+$/, "").replace(/\./g, "-");
8910
- } catch {
8911
- return endpoint.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
8912
- }
8913
- }
8914
- async function withFavoritesLock(fn) {
8915
- ensureConfigDir();
8916
- let release;
8917
- try {
8918
- release = await import_proper_lockfile.default.lock(FAVORITES_FILE, {
8919
- lockfilePath: `${FAVORITES_FILE}.lock`,
8920
- realpath: false,
8921
- stale: 3e4,
8922
- retries: { retries: 10, factor: 1, minTimeout: 100, maxTimeout: 100 }
8923
- });
8924
- } catch {
8925
- throw new DvmError(
8926
- "favorites_locked",
8927
- "Another dvm process is updating saved favorites.",
8928
- "Wait a moment and retry."
8929
- );
8930
- }
8931
- try {
8932
- return await fn();
8933
- } finally {
8934
- await release().catch(() => void 0);
8935
- }
8936
- }
8937
- function writeFavorites(favorites) {
8938
- const mode = favoritesFileMode();
8939
- const temporary = `${FAVORITES_FILE}.${String(process.pid)}.${randomSuffix()}.tmp`;
8940
- const contents = JSON.stringify(favorites, null, 2) + "\n";
8941
- let fd;
8942
- try {
8943
- fd = openSync2(temporary, "wx", mode);
8944
- fchmodSync(fd, mode);
8945
- writeFileSync(fd, contents);
8946
- fsyncSync(fd);
8947
- closeSync2(fd);
8948
- fd = void 0;
8949
- renameSync(temporary, FAVORITES_FILE);
8950
- fsyncDirectory(dirname(FAVORITES_FILE));
8951
- } catch (error) {
8952
- if (fd !== void 0) {
8953
- try {
8954
- closeSync2(fd);
8955
- } catch {
8956
- }
8957
- }
8958
- try {
8959
- unlinkSync(temporary);
8960
- } catch {
8961
- }
8962
- throw error;
8963
- }
8964
- }
8965
- function favoritesFileMode() {
8966
- try {
8967
- return statSync2(FAVORITES_FILE).mode & 511;
8968
- } catch (error) {
8969
- if (nodeErrorCode(error) === "ENOENT") return DEFAULT_FILE_MODE;
8970
- throw error;
8971
- }
8972
- }
8973
- function fsyncDirectory(path) {
8974
- const fd = openSync2(path, "r");
8975
- try {
8976
- fsyncSync(fd);
8977
- } finally {
8978
- closeSync2(fd);
8979
- }
8980
- }
8981
- function randomSuffix() {
8982
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
8983
- }
8984
- function unreadableFavorites(error) {
8985
- return new DvmError(
8986
- "favorites_unreadable",
8987
- "Saved favorites are corrupt or unreadable.",
8988
- `The original file at ${FAVORITES_FILE} was left unchanged. Restore it from a backup, or move it aside before rebuilding favorites.`,
8989
- {
8990
- path: FAVORITES_FILE,
8991
- ...nodeErrorCode(error) ? { error_code: nodeErrorCode(error) } : {}
8992
- }
8993
- );
8994
- }
8995
- function nodeErrorCode(error) {
8996
- if (!(error instanceof Error) || !("code" in error)) return void 0;
8997
- const code = error.code;
8998
- return typeof code === "string" && /^E[A-Z0-9_]{1,63}$/.test(code) ? code : void 0;
8999
- }
9000
- function isFavoritesMap(value) {
9001
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
9002
- return Object.values(value).every(isFavorite);
9003
- }
9004
- function isFavorite(value) {
9005
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
9006
- const candidate = value;
9007
- return typeof candidate.endpoint === "string" && typeof candidate.addedAt === "number" && Number.isFinite(candidate.addedAt) && (candidate.name === void 0 || typeof candidate.name === "string");
9008
- }
9009
-
9010
- // src/lib/submission-evidence.ts
9011
- import { createHash, randomUUID } from "crypto";
9012
- import {
9013
- closeSync as closeSync3,
9014
- existsSync as existsSync2,
9015
- fsyncSync as fsyncSync2,
9016
- linkSync,
9017
- openSync as openSync3,
9018
- readdirSync,
9019
- readFileSync as readFileSync3,
9020
- unlinkSync as unlinkSync2,
9021
- writeFileSync as writeFileSync2
9022
- } from "fs";
9023
- import { join as join2 } from "path";
9024
-
9025
- // src/lib/job-identity.ts
9026
- var IDENTITY_FAILURE_CODES = {
9027
- identity_mismatch: "provider_identity_mismatch",
9028
- body_unreadable: "provider_body_unreadable",
9029
- router_identity_conflict: "hosting_job_identity_conflict"
9030
- };
9031
- var ProviderIdentityError = class extends DvmError {
9032
- observation;
9033
- constructor(observation, message2, hint, data, proseSources) {
9034
- super(IDENTITY_FAILURE_CODES[observation.kind], message2, hint, data, void 0, proseSources);
9035
- this.observation = observation;
9036
- }
9037
- };
9038
- function isIdentityFailure(err) {
9039
- return err instanceof ProviderIdentityError;
9040
- }
9041
- function isParseableBodyJobId(value) {
9042
- return typeof value === "string" && value.trim().length > 0 && value.length <= 512 && !hasAsciiControl(value);
9043
- }
9044
- function isOpaqueJobToken(value) {
9045
- return typeof value === "string" && value.length > 0 && value.length <= 4096 && value.trim() === value && !hasAsciiControl(value);
9046
- }
9047
- function observedJobId(value) {
9048
- return isStorableJobId(value) ? value : void 0;
9049
- }
9050
- function observeJobId(value) {
9051
- if (value === void 0) return {};
9052
- if (isStorableJobId(value)) return { stored: value };
9053
- return { escaped: escapeObservedValue(value) };
9054
- }
9055
- var ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT = 1024;
9056
- function escapeObservedValue(value) {
9057
- const source = typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
9058
- const truncated = source.length > ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT;
9059
- const quoted = JSON.stringify(
9060
- truncated ? source.slice(0, ESCAPED_OBSERVED_VALUE_SOURCE_LIMIT) : source
9061
- ).replace(
9062
- /[\u007f-\u009f]/gu,
9063
- (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
9064
- );
9065
- return truncated ? `${quoted} [truncated from ${String(source.length)} characters]` : quoted;
9066
- }
9067
- function settleJobIdentity(headerValue, body) {
9068
- const header = parseJobIdentityHeader(headerValue);
9069
- const headerJobId = header.kind === "valid" ? header.jobId : void 0;
9070
- const rawBodyJobId = body?.job_id;
9071
- const jobToken = isOpaqueJobToken(body?.job_token) ? body.job_token : void 0;
9072
- const observed = (kind) => {
9073
- const bodyJob = observeJobId(rawBodyJobId);
9074
- return {
9075
- kind: "unresolved",
9076
- observation: {
9077
- kind,
9078
- ...headerJobId ? { headerJobId } : {},
9079
- ...optionalField("bodyJobId", bodyJob.stored),
9080
- ...bodyJob.escaped ? { unstorable: { body_job_id: bodyJob.escaped } } : {},
9081
- ...jobToken ? { jobToken } : {}
9082
- }
9083
- };
9084
- };
9085
- if (!isParseableBodyJobId(rawBodyJobId)) return observed("body_unreadable");
9086
- if (headerJobId !== void 0 && headerJobId !== rawBodyJobId) {
9087
- return observed("identity_mismatch");
9088
- }
9089
- return {
9090
- kind: "settled",
9091
- jobId: rawBodyJobId,
9092
- claimAllowed: header.kind !== "invalid",
9093
- headerInvalid: header.kind === "invalid"
9094
- };
9095
- }
9096
- function routerConflictObservation(status2, body) {
9097
- if (status2 !== 409 || !body) return void 0;
9098
- const error = body.error;
9099
- if (!error || typeof error !== "object" || Array.isArray(error)) return void 0;
9100
- const envelope = error;
9101
- if (envelope.code !== IDENTITY_FAILURE_CODES.router_identity_conflict) return void 0;
9102
- const accepted = observeJobId(envelope.accepted_job_id);
9103
- return {
9104
- kind: "router_identity_conflict",
9105
- ...optionalField("acceptedJobId", accepted.stored),
9106
- ...accepted.escaped ? { unstorable: { accepted_job_id: accepted.escaped } } : {}
9107
- };
9108
- }
9109
- function jobIdentityHeaderValue(headers) {
9110
- return headers.get(JOB_IDENTITY_HEADER);
9111
- }
9112
- function identityError(observation, providerProse) {
9113
- const { message: message2, display } = describeIdentityFailure(observation);
9114
- return new ProviderIdentityError(
9115
- observation,
9116
- message2,
9117
- "Do not pay for this request again. Run 'dvm wallet submissions' to see what was recorded.",
9118
- {
9119
- identity_kind: observation.kind,
9120
- ...identityDataFields(observation),
9121
- display: providerProse?.display ?? display
9122
- },
9123
- providerProse?.proseSources
9124
- );
9125
- }
9126
- function withIdentityRecovery(err, ctx) {
9127
- 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.`;
9128
- return new ProviderIdentityError(
9129
- err.observation,
9130
- err.message,
9131
- hint,
9132
- {
9133
- ...err.data,
9134
- ambiguity_id: ctx.ambiguityId,
9135
- ...ctx.publicRequestId ? { request_id: ctx.publicRequestId } : {},
9136
- ...ctx.cashuRequestId ? { cashu_request_id: ctx.cashuRequestId } : {},
9137
- claim_stored: false
9138
- },
9139
- err.proseSources
9140
- );
9141
- }
9142
- function withRequestResultRecovery(err, ctx) {
9143
- const jobId = err.observation.acceptedJobId;
9144
- const read = `dvm status ${jobId ? shellQuoteArg(jobId) : "<accepted_job_id>"} --endpoint ${shellQuoteArg(ctx.endpoint)} --job-token <job_token_bearer_secret>`;
9145
- 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.`;
9146
- return new ProviderIdentityError(
9147
- err.observation,
9148
- err.message,
9149
- hint,
9150
- { ...err.data, ambiguity_id: ctx.ambiguityId, request_id: ctx.requestId, claim_stored: false },
9151
- err.proseSources
9152
- );
9153
- }
9154
- function identityDataFields(observation) {
9155
- return {
9156
- ...optionalField("header_job_id", observation.headerJobId),
9157
- ...optionalField("body_job_id", observation.bodyJobId),
9158
- ...optionalField("body_job_id_escaped", observation.unstorable?.body_job_id),
9159
- ...optionalField("accepted_job_id", observation.acceptedJobId),
9160
- ...optionalField("accepted_job_id_escaped", observation.unstorable?.accepted_job_id)
9161
- };
9162
- }
9163
- function warnInvalidJobIdentityHeader() {
9164
- const display = "The provider sent a malformed job identity header, so it was ignored and the job ID was taken from the response body.";
9165
- if (process.stderr.isTTY === true) {
9166
- info(`Warning: ${display}`);
9167
- return;
9168
- }
9169
- progress({ event: "warning", code: "job_identity_header_invalid", display });
9170
- }
9171
- function describeIdentityFailure(observation) {
9172
- switch (observation.kind) {
9173
- case "identity_mismatch":
9174
- return {
9175
- message: `The provider accepted the request but named job ${observation.headerJobId ?? "(unknown)"} in its response header and job ${observation.bodyJobId ?? "(unrepresentable)"} in its body.`,
9176
- 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."
9177
- };
9178
- case "body_unreadable":
9179
- return {
9180
- 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.",
9181
- 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."
9182
- };
9183
- case "router_identity_conflict":
9184
- return {
9185
- message: `The router had already accepted job ${observation.acceptedJobId ?? "(unknown)"} for this request, and the provider answered with a different job.`,
9186
- display: "This request was already accepted as a different job. Do not pay for it again."
9187
- };
9188
- }
9189
- }
9190
- function hasAsciiControl(value) {
9191
- for (const character of value) {
9192
- const code = character.charCodeAt(0);
9193
- if (code <= 31 || code === 127) return true;
9194
- }
9195
- return false;
9196
- }
9197
- function optionalField(key, value) {
9198
- return value === void 0 ? {} : { [key]: value };
9199
- }
9200
-
9201
- // src/lib/submission-evidence.ts
9202
- var SUBMISSION_EVIDENCE_DIR = join2(CONFIG_DIR, "submission-evidence");
9203
- function submissionEvidenceKey(args) {
9204
- return args.cashuRequestId ?? args.publicRequestId ?? randomUUID();
9205
- }
9206
- function recordSubmissionEvidence(input) {
9207
- const ambiguityId = submissionEvidenceKey(input);
9208
- const existing = loadSubmissionEvidence(ambiguityId);
9209
- if (existing) return existing;
9210
- const { observation } = input;
9211
- const jobToken = isOpaqueJobToken(observation.jobToken) ? observation.jobToken : void 0;
9212
- const record = {
9213
- v: 1,
9214
- ambiguity_id: ambiguityId,
9215
- kind: observation.kind,
9216
- observed_at: new Date((input.now ?? Date.now)()).toISOString(),
9217
- endpoint: input.endpoint,
9218
- ...input.dvmId ? { dvm_id: input.dvmId } : {},
9219
- ...input.capability ? { capability: input.capability } : {},
9220
- ...input.publicRequestId ? { request_id: input.publicRequestId } : {},
9221
- ...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
9222
- rail: input.rail,
9223
- ...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
9224
- ...jobToken ? { job_token: jobToken } : {},
9225
- ...boundedIds(observation),
9226
- ...observation.unstorable && Object.keys(observation.unstorable).length > 0 ? { unstorable_job_ids: observation.unstorable } : {},
9227
- claim_stored: false
9228
- };
9229
- return publishOnce(record);
9230
- }
9231
- function recordLocalJobCollision(input) {
9232
- const ambiguityId = `${input.publicRequestId}#local-job-collision`;
9233
- const existing = loadSubmissionEvidence(ambiguityId);
9234
- if (existing) return existing;
9235
- const jobToken = isOpaqueJobToken(input.jobToken) ? input.jobToken : void 0;
9236
- return publishOnce({
9237
- v: 1,
9238
- ambiguity_id: ambiguityId,
9239
- kind: "local_job_collision",
9240
- observed_at: new Date((input.now ?? Date.now)()).toISOString(),
9241
- endpoint: input.endpoint,
9242
- ...input.dvmId ? { dvm_id: input.dvmId } : {},
9243
- ...input.capability ? { capability: input.capability } : {},
9244
- request_id: input.publicRequestId,
9245
- ...input.cashuRequestId ? { cashu_request_id: input.cashuRequestId } : {},
9246
- rail: input.rail,
9247
- ...input.railCorrelation && Object.keys(input.railCorrelation).length > 0 ? { rail_correlation: input.railCorrelation } : {},
9248
- ...jobToken ? { job_token: jobToken } : {},
9249
- ...boundedIds({ acceptedJobId: input.jobId }),
9250
- claim_stored: false
9251
- });
9252
- }
9253
- function recordIdentityFailure(err, input) {
9254
- if (identityFailureRecorded(err)) return { error: err, record: null };
9255
- const record = recordSubmissionEvidence({ ...input, observation: err.observation });
9256
- return {
9257
- error: withIdentityRecovery(err, {
9258
- ambiguityId: record.ambiguity_id,
9259
- ...input.publicRequestId ? { publicRequestId: input.publicRequestId } : {},
9260
- ...input.cashuRequestId ? { cashuRequestId: input.cashuRequestId } : {}
9261
- }),
9262
- record
9263
- };
9264
- }
9265
- function identityFailureRecorded(err) {
9266
- return typeof err.data?.ambiguity_id === "string";
9267
- }
9268
- function loadSubmissionEvidence(ambiguityId) {
9269
- const path = evidencePath(ambiguityId);
9270
- if (!existsSync2(path)) return null;
9271
- const record = readRecord(path);
9272
- if (record.ambiguity_id !== ambiguityId) throw unreadable(path, "key mismatch");
9273
- return record;
9274
- }
9275
- function listSubmissionEvidence() {
9276
- if (!existsSync2(SUBMISSION_EVIDENCE_DIR)) return { records: [], unreadable: [] };
9277
- const records = [];
9278
- const unreadable2 = [];
9279
- for (const name of readdirSync(SUBMISSION_EVIDENCE_DIR).filter((n) => n.endsWith(".json"))) {
9280
- const path = join2(SUBMISSION_EVIDENCE_DIR, name);
9281
- try {
9282
- records.push(readRecord(path));
9283
- } catch (error) {
9284
- const cause = error instanceof DvmError ? error.data?.cause : void 0;
9285
- unreadable2.push({ path, cause: typeof cause === "string" ? cause : "unreadable" });
9286
- }
9287
- }
9288
- records.sort((a, b) => a.observed_at.localeCompare(b.observed_at));
9289
- return { records, unreadable: unreadable2 };
9290
- }
9291
- function journalMarkerFor(record) {
9292
- const kind = record.kind;
9293
- if (kind === "local_job_collision") {
9294
- throw unreadable(evidencePath(record.ambiguity_id), "not an identity failure");
9295
- }
9296
- return {
9297
- kind,
9298
- observed_at: record.observed_at,
9299
- ...boundedMarkerIds(record),
9300
- ambiguity_id: record.ambiguity_id
9301
- };
9302
- }
9303
- function publishOnce(record) {
9304
- const ambiguityId = record.ambiguity_id;
9305
- ensureConfigSubdir(SUBMISSION_EVIDENCE_DIR);
9306
- const target = evidencePath(ambiguityId);
9307
- const temp = `${target}.${String(process.pid)}.${randomUUID()}.tmp`;
9308
- const fd = openSync3(temp, "wx", 384);
9309
- try {
9310
- writeFileSync2(fd, JSON.stringify(record, null, 2) + "\n");
9311
- fsyncSync2(fd);
9312
- } finally {
9313
- closeSync3(fd);
9314
- }
9315
- try {
9316
- linkSync(temp, target);
9317
- } catch (error) {
9318
- if (error.code !== "EEXIST") throw error;
9319
- } finally {
9320
- unlinkSync2(temp);
9321
- }
9322
- fsyncDirectory2(SUBMISSION_EVIDENCE_DIR);
9323
- return loadSubmissionEvidence(ambiguityId) ?? record;
9324
- }
9325
- function boundedIds(observation) {
9326
- const header = observedJobId(observation.headerJobId);
9327
- const body = observedJobId(observation.bodyJobId);
9328
- const accepted = observedJobId(observation.acceptedJobId);
9329
- return {
9330
- ...header !== void 0 ? { header_job_id: header } : {},
9331
- ...body !== void 0 ? { body_job_id: body } : {},
9332
- ...accepted !== void 0 ? { accepted_job_id: accepted } : {}
9333
- };
9334
- }
9335
- function boundedMarkerIds(record) {
9336
- return boundedIds({
9337
- headerJobId: record.header_job_id,
9338
- bodyJobId: record.body_job_id,
9339
- acceptedJobId: record.accepted_job_id
9340
- });
9341
- }
9342
- function evidencePath(ambiguityId) {
9343
- const name = createHash("sha256").update(ambiguityId).digest("hex");
9344
- return join2(SUBMISSION_EVIDENCE_DIR, `${name}.json`);
9345
- }
9346
- function readRecord(path) {
9347
- let parsed;
9348
- try {
9349
- parsed = JSON.parse(readFileSync3(path, "utf8"));
9350
- } catch (error) {
9351
- throw unreadable(path, error instanceof Error ? error.message : String(error));
9352
- }
9353
- if (!isEvidenceRecord(parsed)) throw unreadable(path, "invalid shape");
9354
- return parsed;
9355
- }
9356
- function unreadable(path, cause) {
9357
- return new DvmError(
9358
- "submission_evidence_unreadable",
9359
- `A submission evidence record at ${path} is unreadable.`,
9360
- "Restore it from a backup. Do not pay again for any request it may describe; automatic retries stay off until it reads.",
9361
- { cause }
9362
- );
9363
- }
9364
- var KINDS = /* @__PURE__ */ new Set([
9365
- "identity_mismatch",
9366
- "body_unreadable",
9367
- "router_identity_conflict",
9368
- "local_job_collision"
9369
- ]);
9370
- var RAILS = /* @__PURE__ */ new Set(["cashu", "x402", "tempo", "credit", "none"]);
9371
- function isEvidenceRecord(value) {
9372
- if (!isPlainObject(value)) return false;
9373
- const record = value;
9374
- const optionalString = (key) => record[key] === void 0 || typeof record[key] === "string";
9375
- 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)) && [
9376
- "dvm_id",
9377
- "capability",
9378
- "request_id",
9379
- "cashu_request_id",
9380
- "job_token",
9381
- "header_job_id",
9382
- "body_job_id",
9383
- "accepted_job_id"
9384
- ].every(optionalString);
9385
- }
9386
- function isPlainObject(value) {
9387
- return typeof value === "object" && value !== null && !Array.isArray(value);
9388
- }
9389
- function isOptionalStringRecord(value) {
9390
- return value === void 0 || isPlainObject(value) && Object.values(value).every((entry) => typeof entry === "string");
9391
- }
9392
- function fsyncDirectory2(path) {
9393
- let fd;
9394
- try {
9395
- fd = openSync3(path, "r");
9396
- fsyncSync2(fd);
9397
- } finally {
9398
- if (fd !== void 0) closeSync3(fd);
9399
- }
9400
- }
9401
-
9402
- // src/lib/job-access.ts
9403
- function resolveJobAccess(jobId, opts) {
9404
- const stored = loadJob(jobId);
9405
- return resolveJobAccessWithRecord(jobId, opts, stored);
9406
- }
9407
- function resolveJobAccessWithRecord(jobId, opts, record) {
9408
- const endpointOverride = opts.endpoint ?? process.env.DVM_JOB_ENDPOINT;
9409
- const tokenOverride = opts.jobToken ?? process.env.DVM_JOB_TOKEN;
9410
- const endpointOverridden = endpointOverride !== void 0;
9411
- const tokenOverridden = tokenOverride !== void 0;
9412
- const foreign = record !== null && endpointOverride !== void 0 && !sameEndpoint(resolveEndpoint(endpointOverride), record.endpoint);
9413
- const stored = foreign ? null : record;
9414
- const rawEndpoint = endpointOverride ?? stored?.endpoint;
9415
- const jobToken = tokenOverride ?? stored?.jobToken;
9416
- if (!stored && rawEndpoint === void 0 && jobToken === void 0) {
9417
- throw new DvmError(
9418
- "job_access_required",
9419
- `Job ${jobId} is not in the local store, and no portable job access was supplied.`,
9420
- "Pass --endpoint <url> and --job-token <hex>, or set DVM_JOB_ENDPOINT and DVM_JOB_TOKEN."
9421
- );
9422
- }
9423
- if (rawEndpoint === void 0) {
9424
- throw new DvmError(
9425
- "job_endpoint_required",
9426
- `No provider endpoint is available for job ${jobId}.`,
9427
- "Pass --endpoint <url> or set DVM_JOB_ENDPOINT."
9428
- );
9429
- }
9430
- if (foreign && jobToken === void 0) {
9431
- throw foreignJobTokenRequired(jobId, record.endpoint, resolveEndpoint(endpointOverride));
9432
- }
9433
- if (!stored && jobToken === void 0) {
9434
- throw new DvmError(
9435
- "job_token_required",
9436
- `No job token is available for job ${jobId}.`,
9437
- "Pass --job-token <hex> or set DVM_JOB_TOKEN."
9438
- );
9439
- }
9440
- if (tokenOverridden && !isJobToken(jobToken)) {
9441
- throw new DvmError(
9442
- "invalid_job_token",
9443
- "The supplied job token is not a 64-character hexadecimal value.",
9444
- "Copy the job_token returned when the job was submitted; the value is never printed by this command."
9445
- );
9446
- }
9447
- return {
9448
- stored,
9449
- ref: { endpoint: validateProviderEndpoint(resolveEndpoint(rawEndpoint)) },
9450
- ...jobToken !== void 0 ? { jobToken } : {},
9451
- overridden: endpointOverridden || tokenOverridden,
9452
- endpointOverridden
9453
- };
9454
- }
9455
- function resolveStoredJobAccess(jobId, opts) {
9456
- const stored = loadJob(jobId);
9457
- if (!stored) {
9458
- throw new DvmError(
9459
- "job_payment_state_required",
9460
- `Cannot pay job ${jobId} without its local payment state.`,
9461
- "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."
9462
- );
9463
- }
9464
- return { ...resolveJobAccessWithRecord(jobId, opts, stored), stored };
9465
- }
9466
- async function withJobTokenRedaction(jobToken, action) {
9467
- try {
9468
- return await action();
9469
- } catch (err) {
9470
- throw redactJobTokenFromError(err, jobToken);
9471
- }
9472
- }
9473
- function redactJobTokenFromError(err, jobToken) {
9474
- if (!jobToken || !(err instanceof DvmError)) return err;
9475
- const redact = (value) => value.replaceAll(jobToken, "[REDACTED]");
9476
- return new DvmError(
9477
- err.code,
9478
- redact(err.message),
9479
- err.hint === void 0 ? void 0 : redact(err.hint),
9480
- err.data === void 0 ? void 0 : redactRecord(err.data, redact),
9481
- err.display === void 0 ? void 0 : redact(err.display),
9482
- err.proseSources
9483
- );
9484
- }
9485
- function sameEndpoint(a, b) {
9486
- const normalize = (value) => {
9487
- try {
9488
- const url = new URL(value);
9489
- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
9490
- } catch {
9491
- return value.replace(/\/+$/, "");
9492
- }
9493
- };
9494
- return normalize(a) === normalize(b);
9495
- }
9496
- function foreignJobTokenRequired(jobId, localEndpoint, endpoint) {
9497
- const row = evidenceRowWithToken(jobId, endpoint);
9498
- return new DvmError(
9499
- "job_token_required",
9500
- `Local job ${jobId} belongs to ${localEndpoint}. Its job token was issued there and is not sent to ${endpoint}.`,
9501
- 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.`,
9502
- {
9503
- job_id: jobId,
9504
- local_endpoint: localEndpoint,
9505
- endpoint,
9506
- ...row ? { ambiguity_id: row } : {}
9507
- }
9508
- );
9509
- }
9510
- function evidenceRowWithToken(jobId, endpoint) {
9511
- let records;
9512
- try {
9513
- ({ records } = listSubmissionEvidence());
9514
- } catch {
9515
- return void 0;
9516
- }
9517
- return records.filter(
9518
- (record) => record.job_token !== void 0 && sameEndpoint(record.endpoint, endpoint) && [record.header_job_id, record.body_job_id, record.accepted_job_id].includes(jobId)
9519
- ).at(-1)?.ambiguity_id;
9520
- }
9521
- function isJobToken(value) {
9522
- return value !== void 0 && /^[0-9a-fA-F]{64}$/.test(value);
9523
- }
9524
- function validateProviderEndpoint(value) {
9525
- try {
9526
- const url = new URL(value);
9527
- if ((url.protocol === "http:" || url.protocol === "https:") && url.hostname) return value;
9528
- } catch {
9529
- }
9530
- throw new DvmError(
9531
- "invalid_endpoint",
9532
- "The supplied job endpoint is not a valid HTTP(S) provider URL.",
9533
- "Pass a full URL such as https://provider.example, or a favorite alias such as @provider."
9534
- );
9535
- }
9536
- function redactRecord(record, redact) {
9537
- return Object.fromEntries(
9538
- Object.entries(record).map(([key, value]) => [key, redactValue(value, redact)])
9539
- );
9540
- }
9541
- function redactValue(value, redact) {
9542
- if (typeof value === "string") return redact(value);
9543
- if (Array.isArray(value)) return value.map((entry) => redactValue(entry, redact));
9544
- if (value && typeof value === "object") {
9545
- return redactRecord(value, redact);
9546
- }
9547
- return value;
9548
- }
9549
-
9550
8869
  // src/lib/credit-payment.ts
9551
- import { randomUUID as randomUUID2 } from "crypto";
8870
+ import { randomUUID } from "crypto";
9552
8871
 
9553
8872
  // src/lib/caller-version.ts
9554
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
9555
- 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";
9556
8875
  import { fileURLToPath } from "url";
9557
8876
  var CALLER_VERSION = readCallerVersion();
9558
8877
  function readCallerVersion() {
9559
- let dir = dirname2(fileURLToPath(import.meta.url));
8878
+ let dir = dirname(fileURLToPath(import.meta.url));
9560
8879
  for (; ; ) {
9561
- const manifestPath = join3(dir, "package.json");
9562
- if (existsSync3(manifestPath)) {
8880
+ const manifestPath = join2(dir, "package.json");
8881
+ if (existsSync2(manifestPath)) {
9563
8882
  const manifest = readManifest(manifestPath);
9564
8883
  if (manifest.name === "@dvmkit/dvm-cli") return manifest.version;
9565
8884
  }
9566
- const parent = dirname2(dir);
8885
+ const parent = dirname(dir);
9567
8886
  if (parent === dir) {
9568
8887
  throw new Error(`No @dvmkit/dvm-cli package.json found walking up from ${import.meta.url}`);
9569
8888
  }
@@ -9571,7 +8890,7 @@ function readCallerVersion() {
9571
8890
  }
9572
8891
  }
9573
8892
  function readManifest(path) {
9574
- return JSON.parse(readFileSync4(path, "utf8"));
8893
+ return JSON.parse(readFileSync2(path, "utf8"));
9575
8894
  }
9576
8895
 
9577
8896
  // src/lib/client-compatibility.ts
@@ -10368,7 +9687,7 @@ async function tryCreditPayment(args) {
10368
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;
10369
9688
  const creditId = implicit?.creditId ?? (eligible ? stored.creditId : void 0);
10370
9689
  if (!creditId) return false;
10371
- binding = { creditId, drawId: randomUUID2(), callerPubkey: signer.pubkey };
9690
+ binding = { creditId, drawId: randomUUID(), callerPubkey: signer.pubkey };
10372
9691
  }
10373
9692
  if (!Number.isSafeInteger(request2.amount_msats) || request2.amount_msats <= 0) return false;
10374
9693
  const rate = await balanceCurrencyRate(ask.currency);
@@ -10396,7 +9715,7 @@ async function tryCreditPayment(args) {
10396
9715
  const authorization = signDvmRequestData(signer.privkey, {
10397
9716
  credit_id: selectedBinding.creditId,
10398
9717
  draw_id: selectedBinding.drawId,
10399
- payment_id: randomUUID2(),
9718
+ payment_id: randomUUID(),
10400
9719
  request_seq: requestSeq,
10401
9720
  amount_micro: ask.amount_micro,
10402
9721
  currency: ask.currency
@@ -10450,10 +9769,10 @@ async function sweepPendingSubmissions(opts = {}) {
10450
9769
  }
10451
9770
  };
10452
9771
  const now = opts.now ?? (() => Date.now());
10453
- const { entries, unreadable: unreadable2 } = await reconcileEvidenceMarkers(wallet);
9772
+ const { entries, unreadable } = await reconcileEvidenceMarkers(wallet);
10454
9773
  const outcomes = [];
10455
9774
  for (const entry of entries) {
10456
- 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)));
10457
9776
  }
10458
9777
  if (outcomes.some(mutatesWallet)) {
10459
9778
  await withWalletLock(() => {
@@ -11389,18 +10708,18 @@ function createDefaultHttpPost(fetchImpl) {
11389
10708
  };
11390
10709
  }
11391
10710
  async function reconcileEvidenceMarkers(wallet) {
11392
- const unreadable2 = /* @__PURE__ */ new Set();
10711
+ const unreadable = /* @__PURE__ */ new Set();
11393
10712
  const orphaned = wallet.pending_submissions.flatMap((entry) => {
11394
10713
  if (entry.accepted_unresolved) return [];
11395
10714
  try {
11396
10715
  const record = loadSubmissionEvidence(entry.request_id);
11397
10716
  return record ? [{ requestId: entry.request_id, marker: journalMarkerFor(record) }] : [];
11398
10717
  } catch {
11399
- unreadable2.add(entry.request_id);
10718
+ unreadable.add(entry.request_id);
11400
10719
  return [];
11401
10720
  }
11402
10721
  });
11403
- if (orphaned.length === 0) return { entries: wallet.pending_submissions, unreadable: unreadable2 };
10722
+ if (orphaned.length === 0) return { entries: wallet.pending_submissions, unreadable };
11404
10723
  return withWalletLock(() => {
11405
10724
  const fresh = loadAgentWallet() ?? wallet;
11406
10725
  const next = orphaned.reduce(
@@ -11408,7 +10727,7 @@ async function reconcileEvidenceMarkers(wallet) {
11408
10727
  fresh
11409
10728
  );
11410
10729
  saveAgentWallet(next);
11411
- return { entries: next.pending_submissions, unreadable: unreadable2 };
10730
+ return { entries: next.pending_submissions, unreadable };
11412
10731
  });
11413
10732
  }
11414
10733
  function evidenceState(ambiguityId) {
@@ -11712,8 +11031,8 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11712
11031
  }
11713
11032
  }
11714
11033
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11715
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UEQTGVJE.js");
11716
- 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");
11717
11036
  const wallet = loadX402Wallet2();
11718
11037
  if (wallet) {
11719
11038
  let proof;
@@ -11742,7 +11061,8 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11742
11061
  }
11743
11062
  if (proof) {
11744
11063
  await enforceGlobalBudget({ plannedMsats: proof.amountMsats, btcRate: proof.btcRate });
11745
- await transport.sendMessage(
11064
+ await sendRailPayment(
11065
+ transport,
11746
11066
  jobId,
11747
11067
  {
11748
11068
  type: "payment",
@@ -11777,7 +11097,8 @@ async function handlePaymentRequest(jobId, request2, policy, transport, provider
11777
11097
  if (cred) {
11778
11098
  const paidMsats = usdcToMsats(Number(tempoCredentialAmountMicro(cred)) / 1e6, tempoRate);
11779
11099
  await enforceGlobalBudget({ plannedMsats: paidMsats, btcRate: tempoRate });
11780
- await transport.sendMessage(
11100
+ await sendRailPayment(
11101
+ transport,
11781
11102
  jobId,
11782
11103
  {
11783
11104
  type: "payment",
@@ -11901,7 +11222,8 @@ async function tryAgentWalletMidJobPayment(args) {
11901
11222
  async function sendMidJobPaymentWithRetry(args) {
11902
11223
  const { jobId, amountMsats, prepared, transport, provider, jobToken } = args;
11903
11224
  await withAgentWalletPaymentRetry({
11904
- attempt: () => transport.sendMessage(
11225
+ attempt: () => sendRailPayment(
11226
+ transport,
11905
11227
  jobId,
11906
11228
  {
11907
11229
  type: "payment",
@@ -11920,6 +11242,22 @@ async function sendMidJobPaymentWithRetry(args) {
11920
11242
  sleep: args.sleep
11921
11243
  });
11922
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
+ }
11923
11261
  async function tryMppCredential(challenges, amountMsats, btcRate) {
11924
11262
  const wallet = loadConfig()?.tempo;
11925
11263
  if (wallet?.method !== "tempo" || !wallet.apiKey) return null;
@@ -12368,6 +11706,7 @@ async function observeJobContent(jobId, transport, ref, options) {
12368
11706
  ...options,
12369
11707
  timeoutMs: options.timeoutMs > 0 ? Math.min(options.timeoutMs, 5e3) : 5e3
12370
11708
  });
11709
+ captureDrawFundingReceipts(jobId, status2.drawFundingReceipts, { endpoint: ref.endpoint });
12371
11710
  return parseJobContent(status2);
12372
11711
  } catch {
12373
11712
  return void 0;
@@ -12990,14 +12329,14 @@ var HttpsTransport = class {
12990
12329
  } catch {
12991
12330
  throw new DvmError("payment_insufficient", "Payment required (unparseable response).");
12992
12331
  }
12993
- const error = withCreditErrorContext(buildPaymentError(errorBody), errorBody);
12332
+ const error = withDrawFunding(withCreditErrorContext(buildPaymentError(errorBody), errorBody), errorBody);
12994
12333
  error.data = { ...error.data, http_status: 402 };
12995
12334
  throw error;
12996
12335
  }
12997
12336
  if (res.status === 409) {
12998
12337
  const body2 = parseJsonObject(await res.text());
12999
12338
  if (body2 && (body2.error === "replay_rejected" || message2.type === "payment" && message2.content.credit && typeof body2.error === "string"))
13000
- throw withCreditErrorContext(buildPaymentError(body2), body2);
12339
+ throw withDrawFunding(withCreditErrorContext(buildPaymentError(body2), body2), body2);
13001
12340
  throw new DvmError(
13002
12341
  "job_terminal",
13003
12342
  "Job is no longer active.",
@@ -13007,14 +12346,21 @@ var HttpsTransport = class {
13007
12346
  if (!res.ok) {
13008
12347
  const text = await res.text();
13009
12348
  const structured = parseStructuredError(text);
13010
- if (structured) throw withCreditErrorContext(structured, parseJsonObject(text) ?? {});
12349
+ if (structured) {
12350
+ const body2 = parseJsonObject(text) ?? {};
12351
+ throw withDrawFunding(withCreditErrorContext(structured, body2), body2);
12352
+ }
13011
12353
  throw providerResponseError("provider_error", `sendMessage failed (${res.status}): ${text}`);
13012
12354
  }
12355
+ if (message2.type !== "payment") return;
12356
+ const acknowledgement = parseJsonObject(await res.text());
13013
12357
  if (message2.type === "payment" && message2.content.credit) {
13014
- const body2 = parseJsonObject(await res.text());
13015
- 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)
13016
12359
  throw new DvmError("invalid_credit_payment_response", "The balance payment outcome is unknown; replay the saved payment.");
13017
12360
  }
12361
+ if (acknowledgement && Number.isSafeInteger(acknowledgement.seq) && Number(acknowledgement.seq) >= 0) {
12362
+ return { seq: Number(acknowledgement.seq), ...parseDrawFundingReceipt(acknowledgement.draw_funding_receipt) };
12363
+ }
13018
12364
  }
13019
12365
  async stream(jobId, afterSeq, provider, options) {
13020
12366
  const endpoint = provider?.endpoint;
@@ -13113,12 +12459,24 @@ function parseFundingReceipt(value) {
13113
12459
  return isFundingReceipt(value) ? { fundingReceipt: value } : { fundingReceiptParseError: "shape_invalid" };
13114
12460
  }
13115
12461
  function parseFundingResponse(data) {
12462
+ const raw2 = data.draw_funding_receipts;
13116
12463
  return {
13117
12464
  ...parseFundingReceipt(data.funding_receipt),
13118
12465
  ...typeof data.funded_micro === "number" ? { fundedMicro: data.funded_micro } : {},
13119
- ...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" } : {}
13120
12469
  };
13121
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
+ }
13122
12480
  function parseRequestResultResponse(value, requestId, httpStatus) {
13123
12481
  if (!value || typeof value !== "object" || Array.isArray(value)) {
13124
12482
  throw malformedRequestResult(requestId, "response_not_object");
@@ -14122,14 +13480,14 @@ async function confirmRollback(stored, preview, opts) {
14122
13480
  async function withStrandingChecked(removing, commit) {
14123
13481
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
14124
13482
  if (leaving.has("tempo")) {
14125
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-HJQYBOZR.js");
13483
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-SVPMTND2.js");
14126
13484
  await assertTempoWalletIdle2("disconnect");
14127
13485
  }
14128
13486
  if (!leaving.has("x402")) return commit();
14129
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-LRW4XR3J.js");
14130
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-QE3KHIHQ.js");
14131
- const { ensureAddress: ensureAddress2 } = await import("./internal-LRW4XR3J.js");
14132
- 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");
14133
13491
  return withX402ChannelLock2(async () => {
14134
13492
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
14135
13493
  if (unsettled.length > 0) {
@@ -14557,7 +13915,7 @@ function creditDrainCommand(handle, creditId) {
14557
13915
  }
14558
13916
 
14559
13917
  // src/commands/wallet-history.ts
14560
- import { createHash as createHash2 } from "crypto";
13918
+ import { createHash } from "crypto";
14561
13919
 
14562
13920
  // src/lib/completed-credit-history.ts
14563
13921
  function completedCreditHistory(query = {}) {
@@ -14702,7 +14060,7 @@ function walletHistory(opts, now = /* @__PURE__ */ new Date()) {
14702
14060
  const windowed = (sinceMs === null ? all : all.filter((e) => e.timestamp >= sinceMs)).slice().sort(
14703
14061
  (a, b) => b.timestamp - a.timestamp || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0)
14704
14062
  );
14705
- const fingerprint = createHash2("sha256").update(JSON.stringify(windowed)).digest("hex");
14063
+ const fingerprint = createHash("sha256").update(JSON.stringify(windowed)).digest("hex");
14706
14064
  if (continuation && continuation.fingerprint !== fingerprint) {
14707
14065
  throw invalidHistoryCursor();
14708
14066
  }
@@ -15640,7 +14998,7 @@ function wireCreditCurrencyTotals(rows) {
15640
14998
 
15641
14999
  // src/lib/credit/drain.ts
15642
15000
  import {
15643
- randomUUID as randomUUID3
15001
+ randomUUID as randomUUID2
15644
15002
  } from "crypto";
15645
15003
  async function runCreditDrain(dvm, opts) {
15646
15004
  const endpoint = resolveCreditEndpoint(dvm);
@@ -15784,7 +15142,7 @@ async function runCreditDrain(dvm, opts) {
15784
15142
  const payout = await drainPayout(method, opts, channelBacked, dvm);
15785
15143
  const mintedThisRun = !pending4;
15786
15144
  let drain = pending4 ? reusableDrain(pending4, method, payout) : {
15787
- drainId: opts.drainId ?? randomUUID3(),
15145
+ drainId: opts.drainId ?? randomUUID2(),
15788
15146
  creditId,
15789
15147
  method,
15790
15148
  payout,
@@ -16655,7 +16013,7 @@ function refundAddress(address) {
16655
16013
 
16656
16014
  // src/lib/credit/funding.ts
16657
16015
  import {
16658
- randomUUID as randomUUID4
16016
+ randomUUID as randomUUID3
16659
16017
  } from "crypto";
16660
16018
  async function runCreditFund(dvm, opts) {
16661
16019
  const endpoint = resolveCreditEndpoint(dvm);
@@ -16767,7 +16125,7 @@ async function runCreditFund(dvm, opts) {
16767
16125
  transport,
16768
16126
  ref: { endpoint },
16769
16127
  signing: signer,
16770
- 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()),
16771
16129
  amountMicro: fundMicro,
16772
16130
  human: opts.human,
16773
16131
  providerInfo,
@@ -18496,8 +17854,8 @@ async function probeX402(x402, timeoutMs) {
18496
17854
  let network;
18497
17855
  let address;
18498
17856
  try {
18499
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-UEQTGVJE.js");
18500
- 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");
18501
17859
  const wallet = loadX402Wallet2();
18502
17860
  if (!wallet) {
18503
17861
  const storedKey = x402.privateKey;
@@ -18549,8 +17907,8 @@ async function probeMpp(mpp, timeoutMs) {
18549
17907
  if (!mpp) return null;
18550
17908
  if (mpp.method === "tempo") {
18551
17909
  try {
18552
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-XN72C2GK.js");
18553
- 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");
18554
17912
  const account = await connectedTempoAccount2();
18555
17913
  if (!account) {
18556
17914
  return {
@@ -18644,15 +18002,15 @@ function x402WrongAssetHint(asset) {
18644
18002
  }
18645
18003
 
18646
18004
  // src/lib/build-freshness.ts
18647
- import { existsSync as existsSync4, readdirSync as readdirSync2, statSync as statSync3 } from "fs";
18648
- 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";
18649
18007
  import { fileURLToPath as fileURLToPath2 } from "url";
18650
18008
  var EXTRA_SOURCES = ["package.json", "tsup.config.ts"];
18651
18009
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "__snapshots__"]);
18652
18010
  var MAX_ENTRIES = 2e4;
18653
18011
  function checkBuildFreshness(opts) {
18654
18012
  const now = opts?.now ?? Date.now;
18655
- const moduleDir = opts?.moduleDir ?? dirname3(fileURLToPath2(import.meta.url));
18013
+ const moduleDir = opts?.moduleDir ?? dirname2(fileURLToPath2(import.meta.url));
18656
18014
  const root = findPackageRoot(moduleDir);
18657
18015
  const skipped = (skipReason) => ({
18658
18016
  status: "not_applicable",
@@ -18664,28 +18022,28 @@ function checkBuildFreshness(opts) {
18664
18022
  skipReason
18665
18023
  });
18666
18024
  if (root === null) return skipped("running_from_source");
18667
- const bundlePath = join4(root, "dist", "dvm.js");
18668
- if (dirname3(moduleDir) !== root || !existsSync4(bundlePath)) {
18025
+ const bundlePath = join3(root, "dist", "dvm.js");
18026
+ if (dirname2(moduleDir) !== root || !existsSync3(bundlePath)) {
18669
18027
  return skipped("running_from_source");
18670
18028
  }
18671
- const srcDir = join4(root, "src");
18672
- if (!existsSync4(srcDir)) return skipped("no_source_tree");
18673
- 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;
18674
18032
  const newer = [];
18675
18033
  let newestMs = 0;
18676
18034
  const visit = (dir, rel, budget2) => {
18677
18035
  if (budget2.left <= 0) return;
18678
- for (const entry of readdirSync2(dir, { withFileTypes: true })) {
18036
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
18679
18037
  if (budget2.left-- <= 0) return;
18680
18038
  if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
18681
- const abs = join4(dir, entry.name);
18039
+ const abs = join3(dir, entry.name);
18682
18040
  const relPath = rel ? `${rel}/${entry.name}` : entry.name;
18683
18041
  if (entry.isDirectory()) {
18684
18042
  visit(abs, relPath, budget2);
18685
18043
  continue;
18686
18044
  }
18687
18045
  if (!entry.isFile()) continue;
18688
- const mtimeMs = statSync3(abs).mtimeMs;
18046
+ const mtimeMs = statSync2(abs).mtimeMs;
18689
18047
  if (mtimeMs > newestMs) newestMs = mtimeMs;
18690
18048
  if (mtimeMs > builtAtMs) newer.push({ path: relPath, mtimeMs });
18691
18049
  }
@@ -18693,9 +18051,9 @@ function checkBuildFreshness(opts) {
18693
18051
  const budget = { left: MAX_ENTRIES };
18694
18052
  visit(srcDir, "src", budget);
18695
18053
  for (const name of EXTRA_SOURCES) {
18696
- const abs = join4(root, name);
18697
- if (!existsSync4(abs)) continue;
18698
- const mtimeMs = statSync3(abs).mtimeMs;
18054
+ const abs = join3(root, name);
18055
+ if (!existsSync3(abs)) continue;
18056
+ const mtimeMs = statSync2(abs).mtimeMs;
18699
18057
  if (mtimeMs > newestMs) newestMs = mtimeMs;
18700
18058
  if (mtimeMs > builtAtMs) newer.push({ path: name, mtimeMs });
18701
18059
  }
@@ -18712,26 +18070,26 @@ function checkBuildFreshness(opts) {
18712
18070
  function findPackageRoot(start) {
18713
18071
  let dir = start;
18714
18072
  for (; ; ) {
18715
- if (existsSync4(join4(dir, "package.json"))) return dir;
18716
- const parent = dirname3(dir);
18073
+ if (existsSync3(join3(dir, "package.json"))) return dir;
18074
+ const parent = dirname2(dir);
18717
18075
  if (parent === dir) return null;
18718
18076
  dir = parent;
18719
18077
  }
18720
18078
  }
18721
18079
 
18722
18080
  // src/lib/caller-state.ts
18723
- import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync4 } from "fs";
18724
- 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";
18725
18083
  function detectSetupState() {
18726
18084
  return {
18727
18085
  existingState: {
18728
- jobs: existsSync5(JOBS_FILE),
18729
- messages: existsSync5(MESSAGES_DIR)
18086
+ jobs: existsSync4(JOBS_FILE),
18087
+ messages: existsSync4(MESSAGES_DIR)
18730
18088
  },
18731
18089
  missing: {
18732
- config: !existsSync5(CONFIG_FILE),
18733
- identity: !existsSync5(IDENTITIES_FILE),
18734
- wallet: !existsSync5(WALLET_FILE)
18090
+ config: !existsSync4(CONFIG_FILE),
18091
+ identity: !existsSync4(IDENTITIES_FILE),
18092
+ wallet: !existsSync4(WALLET_FILE)
18735
18093
  }
18736
18094
  };
18737
18095
  }
@@ -18850,21 +18208,21 @@ function findQuarantinedCreditStores() {
18850
18208
  const prefix = `${basename(CREDITS_FILE)}.corrupt-`;
18851
18209
  let entries;
18852
18210
  try {
18853
- entries = readdirSync3(CONFIG_DIR);
18211
+ entries = readdirSync2(CONFIG_DIR);
18854
18212
  } catch {
18855
18213
  return [];
18856
18214
  }
18857
- 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 }));
18858
18216
  }
18859
18217
  function checkOne(spec) {
18860
- const exists = existsSync5(spec.path);
18218
+ const exists = existsSync4(spec.path);
18861
18219
  if (!exists) {
18862
18220
  return { name: spec.name, path: spec.path, exists: false };
18863
18221
  }
18864
18222
  const row = { name: spec.name, path: spec.path, exists: true };
18865
18223
  if (spec.json) {
18866
18224
  try {
18867
- JSON.parse(readFileSync5(spec.path, "utf-8"));
18225
+ JSON.parse(readFileSync3(spec.path, "utf-8"));
18868
18226
  row.parseable = true;
18869
18227
  } catch (err) {
18870
18228
  row.parseable = false;
@@ -18875,7 +18233,7 @@ function checkOne(spec) {
18875
18233
  checkSecretDirectory(spec.path, row);
18876
18234
  } else if (spec.secret) {
18877
18235
  try {
18878
- const mode = statSync4(spec.path).mode & 511;
18236
+ const mode = statSync3(spec.path).mode & 511;
18879
18237
  const modeOctal = octalMode(mode);
18880
18238
  row.modeOk = mode === 384;
18881
18239
  row.modeOctal = modeOctal;
@@ -18892,9 +18250,9 @@ function checkOne(spec) {
18892
18250
  function checkSecretDirectory(dir, row) {
18893
18251
  try {
18894
18252
  const offenders = [];
18895
- for (const name of readdirSync3(dir)) {
18896
- const path = join5(dir, name);
18897
- const stat = statSync4(path);
18253
+ for (const name of readdirSync2(dir)) {
18254
+ const path = join4(dir, name);
18255
+ const stat = statSync3(path);
18898
18256
  if (!stat.isFile()) continue;
18899
18257
  const mode = stat.mode & 511;
18900
18258
  if (mode !== 384) offenders.push({ path, modeOctal: octalMode(mode) });
@@ -18914,9 +18272,9 @@ function octalMode(mode) {
18914
18272
  return "0" + mode.toString(8).padStart(3, "0");
18915
18273
  }
18916
18274
  function readBtcRateCacheAge(now = Date.now()) {
18917
- if (!existsSync5(BTC_RATE_FILE)) return null;
18275
+ if (!existsSync4(BTC_RATE_FILE)) return null;
18918
18276
  try {
18919
- const data = JSON.parse(readFileSync5(BTC_RATE_FILE, "utf-8"));
18277
+ const data = JSON.parse(readFileSync3(BTC_RATE_FILE, "utf-8"));
18920
18278
  if (typeof data.timestamp !== "number") return null;
18921
18279
  return { ageMs: now - data.timestamp };
18922
18280
  } catch {
@@ -18925,21 +18283,21 @@ function readBtcRateCacheAge(now = Date.now()) {
18925
18283
  }
18926
18284
 
18927
18285
  // src/lib/mnemonic-backups.ts
18928
- import { readdirSync as readdirSync4, statSync as statSync5 } from "fs";
18929
- 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";
18930
18288
  function findMnemonicBackups(mnemonicFile, nowMs = Date.now()) {
18931
- const dir = dirname4(mnemonicFile);
18289
+ const dir = dirname3(mnemonicFile);
18932
18290
  const prefix = `${basename2(mnemonicFile)}.`;
18933
18291
  let names;
18934
18292
  try {
18935
- names = readdirSync4(dir);
18293
+ names = readdirSync3(dir);
18936
18294
  } catch (err) {
18937
18295
  if (err.code === "ENOENT") return [];
18938
18296
  throw err;
18939
18297
  }
18940
18298
  return names.filter((name) => name.startsWith(prefix) && name.endsWith(".bak")).map((name) => {
18941
- const path = join6(dir, name);
18942
- const stat = statSync5(path);
18299
+ const path = join5(dir, name);
18300
+ const stat = statSync4(path);
18943
18301
  if (!stat.isFile()) return null;
18944
18302
  const ageMs2 = Math.max(0, nowMs - stat.mtimeMs);
18945
18303
  return {
@@ -20829,11 +20187,11 @@ async function favRm(name, opts) {
20829
20187
  }
20830
20188
 
20831
20189
  // src/lib/byte-source.ts
20832
- import { readFileSync as readFileSync6 } from "fs";
20190
+ import { readFileSync as readFileSync4 } from "fs";
20833
20191
  import { resolve } from "path";
20834
20192
  var STDIN_TIMEOUT_MS = 1e4;
20835
20193
  function readFileText(path) {
20836
- return readFileSync6(resolve(path), "utf-8");
20194
+ return readFileSync4(resolve(path), "utf-8");
20837
20195
  }
20838
20196
  var StdinTimeoutError = class extends Error {
20839
20197
  constructor(timeoutMs) {
@@ -20997,7 +20355,7 @@ function callerPlatformResponseError(code, remote, fallbackMessage) {
20997
20355
  }
20998
20356
 
20999
20357
  // src/lib/feedback-nudges.ts
21000
- 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";
21001
20359
 
21002
20360
  // src/lib/feedback-notice.ts
21003
20361
  function buildFeedbackNudge(args) {
@@ -21049,10 +20407,10 @@ function effectiveFeedbackPosture(config) {
21049
20407
  return { posture: DEFAULT_FEEDBACK_POSTURE, source: "default" };
21050
20408
  }
21051
20409
  function loadFeedbackNudgeState() {
21052
- if (!existsSync6(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
20410
+ if (!existsSync5(FEEDBACK_NUDGES_FILE)) return { perDvm: {} };
21053
20411
  try {
21054
20412
  const parsed = JSON.parse(
21055
- readFileSync7(FEEDBACK_NUDGES_FILE, "utf-8")
20413
+ readFileSync5(FEEDBACK_NUDGES_FILE, "utf-8")
21056
20414
  );
21057
20415
  return {
21058
20416
  ...typeof parsed.introShownAt === "string" ? { introShownAt: parsed.introShownAt } : {},
@@ -21141,12 +20499,12 @@ function coercePerDvm(perDvm) {
21141
20499
  function saveState(state) {
21142
20500
  ensureConfigDir();
21143
20501
  const tmp = `${FEEDBACK_NUDGES_FILE}.${process.pid}.tmp`;
21144
- writeFileSync3(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
20502
+ writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
21145
20503
  try {
21146
- renameSync2(tmp, FEEDBACK_NUDGES_FILE);
20504
+ renameSync(tmp, FEEDBACK_NUDGES_FILE);
21147
20505
  } catch (err) {
21148
20506
  try {
21149
- unlinkSync3(tmp);
20507
+ unlinkSync(tmp);
21150
20508
  } catch {
21151
20509
  }
21152
20510
  throw err;
@@ -21155,9 +20513,9 @@ function saveState(state) {
21155
20513
  var nudgedThisInvocation = false;
21156
20514
 
21157
20515
  // src/lib/platform.ts
21158
- 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";
21159
20517
  import { homedir } from "os";
21160
- import { join as join7 } from "path";
20518
+ import { join as join6 } from "path";
21161
20519
  function getPlatformUrl() {
21162
20520
  return process.env.DVMKIT_PLATFORM_URL ?? "https://api.dvmkit.dev";
21163
20521
  }
@@ -21726,16 +21084,16 @@ function finalizeProgressLine() {
21726
21084
  import { randomBytes as randomBytes2 } from "crypto";
21727
21085
  import {
21728
21086
  chmodSync,
21729
- closeSync as closeSync4,
21087
+ closeSync as closeSync2,
21730
21088
  mkdtempSync,
21731
- openSync as openSync4,
21732
- readdirSync as readdirSync5,
21089
+ openSync as openSync2,
21090
+ readdirSync as readdirSync4,
21733
21091
  rmdirSync,
21734
- unlinkSync as unlinkSync4,
21735
- writeFileSync as writeFileSync5
21092
+ unlinkSync as unlinkSync2,
21093
+ writeFileSync as writeFileSync3
21736
21094
  } from "fs";
21737
21095
  import { tmpdir } from "os";
21738
- import { join as join8 } from "path";
21096
+ import { join as join7 } from "path";
21739
21097
 
21740
21098
  // src/lib/mime-ext.ts
21741
21099
  var MIME_TO_EXT = {
@@ -21791,11 +21149,11 @@ var ArtifactSaveSession = class {
21791
21149
  let created = false;
21792
21150
  try {
21793
21151
  const directory = this.ensureDirectory();
21794
- path = join8(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
21795
- fd = openSync4(path, "wx", FILE_MODE);
21152
+ path = join7(directory, `artifact-${randomBytes2(16).toString("hex")}.${ext}`);
21153
+ fd = openSync2(path, "wx", FILE_MODE);
21796
21154
  created = true;
21797
- writeFileSync5(fd, buf);
21798
- closeSync4(fd);
21155
+ writeFileSync3(fd, buf);
21156
+ closeSync2(fd);
21799
21157
  fd = void 0;
21800
21158
  chmodSync(path, FILE_MODE);
21801
21159
  this.successfulWrites += 1;
@@ -21803,13 +21161,13 @@ var ArtifactSaveSession = class {
21803
21161
  } catch (err) {
21804
21162
  if (fd !== void 0) {
21805
21163
  try {
21806
- closeSync4(fd);
21164
+ closeSync2(fd);
21807
21165
  } catch {
21808
21166
  }
21809
21167
  }
21810
21168
  if (created && path) {
21811
21169
  try {
21812
- unlinkSync4(path);
21170
+ unlinkSync2(path);
21813
21171
  } catch {
21814
21172
  }
21815
21173
  }
@@ -21820,7 +21178,7 @@ var ArtifactSaveSession = class {
21820
21178
  }
21821
21179
  ensureDirectory() {
21822
21180
  if (this.directory) return this.directory;
21823
- const directory = mkdtempSync(join8(tmpdir(), "dvm-artifacts-"));
21181
+ const directory = mkdtempSync(join7(tmpdir(), "dvm-artifacts-"));
21824
21182
  try {
21825
21183
  chmodSync(directory, DIRECTORY_MODE);
21826
21184
  } catch (err) {
@@ -21836,7 +21194,7 @@ var ArtifactSaveSession = class {
21836
21194
  removeEmptyUnreportedDirectory() {
21837
21195
  if (!this.directory || this.successfulWrites > 0) return;
21838
21196
  try {
21839
- if (readdirSync5(this.directory).length === 0) {
21197
+ if (readdirSync4(this.directory).length === 0) {
21840
21198
  rmdirSync(this.directory);
21841
21199
  this.directory = void 0;
21842
21200
  }
@@ -22616,7 +21974,7 @@ function jsonParseErrorLine(jsonText, err) {
22616
21974
  // src/lib/structured-input-hint.ts
22617
21975
  function expectedFieldsFromSchema(schema) {
22618
21976
  const props = schema.properties;
22619
- if (!isPlainObject2(props)) return [];
21977
+ if (!isPlainObject(props)) return [];
22620
21978
  const requiredList = Array.isArray(schema.required) ? schema.required.filter((x) => typeof x === "string") : [];
22621
21979
  const required = new Set(requiredList);
22622
21980
  const out = [];
@@ -22657,11 +22015,11 @@ function buildStructuredInputHint(opts) {
22657
22015
  if (nextAction) data.next_action = nextAction;
22658
22016
  return { message: message2, hint, data };
22659
22017
  }
22660
- function isPlainObject2(value) {
22018
+ function isPlainObject(value) {
22661
22019
  return typeof value === "object" && value !== null && !Array.isArray(value);
22662
22020
  }
22663
22021
  function jsonSchemaType(node) {
22664
- if (!isPlainObject2(node)) return "unknown";
22022
+ if (!isPlainObject(node)) return "unknown";
22665
22023
  const t = node.type;
22666
22024
  if (typeof t === "string") return t;
22667
22025
  if (Array.isArray(t)) return t.filter((x) => typeof x === "string").join("|") || "unknown";
@@ -22739,16 +22097,16 @@ function findInputSchema(info2, capability) {
22739
22097
  if (capability) {
22740
22098
  const cap2 = info2.capabilities?.[capability];
22741
22099
  if (cap2) {
22742
- if (isPlainObject3(cap2.input_schema)) return cap2.input_schema;
22743
- const quote2 = isPlainObject3(cap2.pricing) ? cap2.pricing.quote : void 0;
22744
- 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;
22745
22103
  }
22746
22104
  }
22747
- if (isPlainObject3(info2.inputSchema)) return info2.inputSchema;
22748
- 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;
22749
22107
  return void 0;
22750
22108
  }
22751
- function isPlainObject3(value) {
22109
+ function isPlainObject2(value) {
22752
22110
  return typeof value === "object" && value !== null && !Array.isArray(value);
22753
22111
  }
22754
22112
 
@@ -23276,7 +22634,7 @@ function buildPolicy(opts, btcRate) {
23276
22634
  }
23277
22635
 
23278
22636
  // src/commands/request.ts
23279
- import { createHash as createHash3, randomUUID as randomUUID5 } from "crypto";
22637
+ import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
23280
22638
 
23281
22639
  // src/lib/credit-defer.ts
23282
22640
  function noteDeferredFunding(funding) {
@@ -23309,10 +22667,27 @@ async function settleCreditAfterJob(args) {
23309
22667
  }
23310
22668
  }
23311
22669
  if (args.allowTopup !== false) {
23312
- const refill = args.refillPocket ?? (await import("./pocket-refill-J3BME4O3.js")).refillPocketIfLow;
22670
+ const refill = args.refillPocket ?? (await import("./pocket-refill-SKECWGA3.js")).refillPocketIfLow;
23313
22671
  await refill({ human: args.human }).catch(() => void 0);
23314
22672
  }
23315
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
+ }
23316
22691
  function settleIdentity(args) {
23317
22692
  return providerDvmIdentity(args.providerInfo);
23318
22693
  }
@@ -23330,15 +22705,13 @@ function noticeDvm(args) {
23330
22705
  async function settle(args) {
23331
22706
  const receipt = args.capture?.receipt;
23332
22707
  const credit = receipt?.credit;
23333
- 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;
23334
22710
  if (credit.credit_id.startsWith("imp:")) {
23335
- if (args.capture?.status !== "verified" && args.capture?.status !== "verified_unattested" || receipt.requester_pubkey !== args.signing.pubkey) {
23336
- return;
23337
- }
23338
22711
  const applied2 = applyImplicitReceiptCredit({
23339
22712
  endpoint: args.ref.endpoint,
23340
22713
  ...settleIdentityArgs(args),
23341
- callerPubkey: args.signing.pubkey,
22714
+ callerPubkey,
23342
22715
  jobId: receipt.job_id,
23343
22716
  outcome: receipt.outcome,
23344
22717
  credit,
@@ -23351,16 +22724,17 @@ async function settle(args) {
23351
22724
  const applied = applyReceiptCredit({
23352
22725
  endpoint: args.ref.endpoint,
23353
22726
  ...settleIdentityArgs(args),
23354
- callerPubkey: args.signing.pubkey,
22727
+ callerPubkey,
23355
22728
  jobId: receipt.job_id,
23356
22729
  outcome: receipt.outcome,
23357
- credit
22730
+ credit,
22731
+ drawFundings: jobDrawFundings(receipt.job_id, args.ref.endpoint, callerPubkey, credit)
23358
22732
  });
23359
22733
  if (!applied.credit) return;
23360
22734
  if (applied.mismatch) {
23361
22735
  renderBalanceMismatch(args.ref.endpoint, applied.mismatch);
23362
22736
  }
23363
- if (args.allowTopup === false) return;
22737
+ if (args.allowTopup === false || !args.signing) return;
23364
22738
  if (receipt.outcome !== "completed") return;
23365
22739
  const record = applied.credit;
23366
22740
  if (record.status !== "active") return;
@@ -23790,16 +23164,16 @@ function dollarLimitMicro(declaredLimit) {
23790
23164
 
23791
23165
  // src/lib/request-intent-store.ts
23792
23166
  import {
23793
- closeSync as closeSync5,
23794
- existsSync as existsSync8,
23795
- fsyncSync as fsyncSync3,
23167
+ closeSync as closeSync3,
23168
+ existsSync as existsSync7,
23169
+ fsyncSync,
23796
23170
  mkdirSync as mkdirSync2,
23797
- openSync as openSync5,
23798
- readFileSync as readFileSync9,
23799
- renameSync as renameSync3,
23800
- writeFileSync as writeFileSync6
23171
+ openSync as openSync3,
23172
+ readFileSync as readFileSync7,
23173
+ renameSync as renameSync2,
23174
+ writeFileSync as writeFileSync4
23801
23175
  } from "fs";
23802
- import { join as join9 } from "path";
23176
+ import { join as join8 } from "path";
23803
23177
  function saveRequestIntent(intent) {
23804
23178
  assertRequestId(intent.requestId);
23805
23179
  assertNoPaymentOrAuthSecrets(intent.body);
@@ -23811,27 +23185,27 @@ function saveRequestIntent(intent) {
23811
23185
  if (error.code === "EEXIST") return false;
23812
23186
  throw error;
23813
23187
  }
23814
- fsyncDirectory3(REQUEST_INTENTS_DIR);
23815
- const temp = join9(dir, `intent.${String(process.pid)}.tmp`);
23816
- const target = join9(dir, "intent.json");
23817
- 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);
23818
23192
  try {
23819
- writeFileSync6(fd, JSON.stringify(intent, null, 2) + "\n");
23820
- fsyncSync3(fd);
23193
+ writeFileSync4(fd, JSON.stringify(intent, null, 2) + "\n");
23194
+ fsyncSync(fd);
23821
23195
  } finally {
23822
- closeSync5(fd);
23196
+ closeSync3(fd);
23823
23197
  }
23824
- renameSync3(temp, target);
23825
- fsyncDirectory3(dir);
23198
+ renameSync2(temp, target);
23199
+ fsyncDirectory(dir);
23826
23200
  return true;
23827
23201
  }
23828
23202
  function loadRequestIntent(requestId) {
23829
23203
  assertRequestId(requestId);
23830
23204
  const dir = intentDirectory(requestId);
23831
- if (!existsSync8(dir)) return null;
23832
- const path = join9(dir, "intent.json");
23205
+ if (!existsSync7(dir)) return null;
23206
+ const path = join8(dir, "intent.json");
23833
23207
  try {
23834
- const parsed = JSON.parse(readFileSync9(path, "utf8"));
23208
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
23835
23209
  if (!isRequestIntent(parsed) || parsed.requestId !== requestId)
23836
23210
  throw new Error("invalid shape");
23837
23211
  return parsed;
@@ -23881,15 +23255,16 @@ function assertRequestId(requestId) {
23881
23255
  );
23882
23256
  }
23883
23257
  function intentDirectory(requestId) {
23884
- return join9(REQUEST_INTENTS_DIR, requestId);
23258
+ return join8(REQUEST_INTENTS_DIR, requestId);
23885
23259
  }
23886
- function fsyncDirectory3(path) {
23260
+ function fsyncDirectory(path) {
23261
+ if (process.platform === "win32") return;
23887
23262
  let fd;
23888
23263
  try {
23889
- fd = openSync5(path, "r");
23890
- fsyncSync3(fd);
23264
+ fd = openSync3(path, "r");
23265
+ fsyncSync(fd);
23891
23266
  } finally {
23892
- if (fd !== void 0) closeSync5(fd);
23267
+ if (fd !== void 0) closeSync3(fd);
23893
23268
  }
23894
23269
  }
23895
23270
  function isRequestIntent(value) {
@@ -24409,7 +23784,7 @@ async function request(opts) {
24409
23784
  probePlan = { ...probePlan, drawId: opts.requestId };
24410
23785
  }
24411
23786
  if (probePlan.mode === "draw" && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing })) {
24412
- drawRequestId = randomUUID5();
23787
+ drawRequestId = randomUUID4();
24413
23788
  }
24414
23789
  const probeData = probePlan.mode === "draw" ? {
24415
23790
  ...unsignedData,
@@ -24813,7 +24188,7 @@ function identityArgs(identity) {
24813
24188
  return identity ? { identity } : {};
24814
24189
  }
24815
24190
  function sha256Hex(value) {
24816
- return createHash3("sha256").update(value, "utf8").digest("hex");
24191
+ return createHash2("sha256").update(value, "utf8").digest("hex");
24817
24192
  }
24818
24193
  async function fetchServerPriceMicro(transport, ref, envelope) {
24819
24194
  try {
@@ -24966,14 +24341,14 @@ async function recoverDrawProbe(err, args) {
24966
24341
  const plan = {
24967
24342
  mode: "draw",
24968
24343
  creditId: args.probePlan.creditId,
24969
- drawId: randomUUID5(),
24344
+ drawId: randomUUID4(),
24970
24345
  ...args.probePlan.source ? { source: args.probePlan.source } : {}
24971
24346
  };
24972
24347
  const requestId = submitCanCarryGeneratedRequestId({
24973
24348
  opts: args.opts,
24974
24349
  providerInfo: args.providerInfo,
24975
24350
  signing
24976
- }) ? randomUUID5() : void 0;
24351
+ }) ? randomUUID4() : void 0;
24977
24352
  const env = reSign({
24978
24353
  credit_id: plan.creditId,
24979
24354
  draw_id: plan.drawId,
@@ -25282,7 +24657,7 @@ async function handleAutoPayQuotes(transport, ref, envelope, jobId, deadlineMs,
25282
24657
  let railSigning = creditCtx?.signing;
25283
24658
  let generatedRequestId;
25284
24659
  if (plan.mode === "none" && railSigning && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing: railSigning })) {
25285
- generatedRequestId = randomUUID5();
24660
+ generatedRequestId = randomUUID4();
25286
24661
  railSigning = {
25287
24662
  ...railSigning,
25288
24663
  unsignedData: { ...railSigning.unsignedData, request_id: generatedRequestId }
@@ -25761,7 +25136,7 @@ function recordUnconfirmedSpend(args) {
25761
25136
  recordSpendOnce({
25762
25137
  msats: args.msats,
25763
25138
  btcRate: args.btcRate,
25764
- jobId: args.key ?? `unconfirmed-${randomUUID5()}`,
25139
+ jobId: args.key ?? `unconfirmed-${randomUUID4()}`,
25765
25140
  providerEndpoint: args.endpoint,
25766
25141
  label: `unconfirmed \xB7 ${args.capability}`
25767
25142
  });
@@ -25869,7 +25244,7 @@ async function tryAgentWalletPayment(transport, ref, envelope, jobId, deadlineMs
25869
25244
  builderHandle = void 0;
25870
25245
  }
25871
25246
  const spendStartedMs = Date.now();
25872
- const generatedRequestId = fundPlan && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing }) ? randomUUID5() : void 0;
25247
+ const generatedRequestId = fundPlan && submitCanCarryGeneratedRequestId({ opts, providerInfo, signing }) ? randomUUID4() : void 0;
25873
25248
  const withGeneratedRequestId = (unsigned) => generatedRequestId ? { ...unsigned, request_id: generatedRequestId } : unsigned;
25874
25249
  const perCallEnvelope = generatedRequestId && signing ? {
25875
25250
  ...envelope,
@@ -26955,6 +26330,10 @@ async function requestResult(requestId, opts = {}) {
26955
26330
  });
26956
26331
  }
26957
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
+ }
26958
26337
  const confirmed = await bookRecoveredSubmissions({
26959
26338
  publicRequestId: requestId,
26960
26339
  endpoint: intent.endpoint,
@@ -27264,8 +26643,8 @@ async function statusWithAccess(jobId, opts, access) {
27264
26643
  const { stored, ref, jobToken } = access;
27265
26644
  if (stored && !access.overridden && isTerminalJobStatus(stored.status) && stored.completion && !opts.messages) {
27266
26645
  let receipt2 = replayStoredReceipt(stored);
26646
+ const transport2 = createDvmTransport();
27267
26647
  if (stored.receiptsSupported && receipt2.status === "absent") {
27268
- const transport2 = createDvmTransport();
27269
26648
  const fetched = await fetchMissingJobReceipt(jobId, transport2, ref);
27270
26649
  if (fetched.receipt || fetched.receiptParseError) {
27271
26650
  if (fetched.receipt && !stored.builderAnchor) {
@@ -27273,8 +26652,9 @@ async function statusWithAccess(jobId, opts, access) {
27273
26652
  }
27274
26653
  receipt2 = captureTransportReceipt(jobId, fetched);
27275
26654
  }
27276
- transport2.close();
27277
26655
  }
26656
+ await settleCreditAfterRead({ job: stored, capture: receipt2, transport: transport2, human: opts.human });
26657
+ transport2.close();
27278
26658
  renderStatus(jobId, stored, stored.status, stored.completion, "local", null, opts, {
27279
26659
  receipt: receipt2
27280
26660
  });
@@ -27284,6 +26664,7 @@ async function statusWithAccess(jobId, opts, access) {
27284
26664
  const transport = createDvmTransport();
27285
26665
  progressNotice("Checking job status...", opts.human);
27286
26666
  const result = await transport.status(jobId, ref, { timeoutMs: timeout, jobToken });
26667
+ if (stored && !access.endpointOverridden) captureDrawFundingReceipts(jobId, result.drawFundingReceipts, { endpoint: ref.endpoint });
27287
26668
  let msgs = [];
27288
26669
  let newCursor;
27289
26670
  if (opts.messages) {
@@ -27309,6 +26690,9 @@ async function statusWithAccess(jobId, opts, access) {
27309
26690
  await backfillTrustAnchor(jobId, transport, ref);
27310
26691
  }
27311
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
+ }
27312
26696
  if (stored && !access.endpointOverridden && !isTerminalJobStatus(stored.status)) {
27313
26697
  noteFeedbackAfterTerminal({
27314
26698
  jobId,
@@ -27421,17 +26805,17 @@ async function resolveNextAction(jobId, status2, fetched, transport, ref, opts)
27421
26805
  }
27422
26806
 
27423
26807
  // src/commands/upload.ts
27424
- import { statSync as statSync6 } from "fs";
26808
+ import { statSync as statSync5 } from "fs";
27425
26809
 
27426
26810
  // src/lib/upload-stream.ts
27427
- import { createHash as createHash4 } from "crypto";
26811
+ import { createHash as createHash3 } from "crypto";
27428
26812
  import { createReadStream } from "fs";
27429
26813
  import * as http2 from "http";
27430
26814
  import * as https from "https";
27431
26815
  var UPLOAD_RESPONSE_MAX_BYTES = 64 * 1024;
27432
26816
  function hashFile(filePath) {
27433
26817
  return new Promise((resolve3, reject) => {
27434
- const hasher = createHash4("sha256");
26818
+ const hasher = createHash3("sha256");
27435
26819
  let sizeBytes = 0;
27436
26820
  const stream = createReadStream(filePath);
27437
26821
  stream.on("data", (chunk) => {
@@ -27644,7 +27028,7 @@ async function upload(dvmRef, opts) {
27644
27028
  const target = resolveUploadTarget(qualified?.slug ?? dvmId, kind);
27645
27029
  let sizeOnDisk;
27646
27030
  try {
27647
- const st = statSync6(opts.file);
27031
+ const st = statSync5(opts.file);
27648
27032
  if (!st.isFile()) {
27649
27033
  throw new DvmError(
27650
27034
  "invalid_argument",
@@ -27906,7 +27290,7 @@ function getRailOnramp(rail) {
27906
27290
  }
27907
27291
 
27908
27292
  // src/lib/secret-input.ts
27909
- import { fstatSync, readFileSync as readFileSync10, realpathSync } from "fs";
27293
+ import { fstatSync, readFileSync as readFileSync8, realpathSync } from "fs";
27910
27294
  import { homedir as homedir2 } from "os";
27911
27295
  import { resolve as resolve2, sep } from "path";
27912
27296
  var BLOCKED_SECRET_PATHS = [
@@ -27986,7 +27370,7 @@ function readSecretFile(path, config) {
27986
27370
  throw err;
27987
27371
  }
27988
27372
  assertSafeFilePath(real);
27989
- return readFileSync10(real, "utf-8").trim();
27373
+ return readFileSync8(real, "utf-8").trim();
27990
27374
  }
27991
27375
  function readSecretStdin(config) {
27992
27376
  return new Promise((resolveStdin, reject) => {
@@ -29682,7 +29066,7 @@ function mnemonicValidationError(result) {
29682
29066
  var import_qrcode = __toESM(require_lib(), 1);
29683
29067
  import { randomBytes as randomBytes3 } from "crypto";
29684
29068
  import { tmpdir as tmpdir2 } from "os";
29685
- import { join as join10 } from "path";
29069
+ import { join as join9 } from "path";
29686
29070
  async function renderQrTerminal(payload) {
29687
29071
  return (0, import_qrcode.toString)(payload, { type: "terminal", small: true });
29688
29072
  }
@@ -29695,7 +29079,7 @@ async function renderQrPng(payload, outPath) {
29695
29079
  });
29696
29080
  }
29697
29081
  function defaultQrImagePath(prefix = "dvm-wallet-fund") {
29698
- return join10(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
29082
+ return join9(tmpdir2(), `${prefix}-${randomBytes3(8).toString("hex")}.png`);
29699
29083
  }
29700
29084
 
29701
29085
  // src/lib/funding-handoff.ts
@@ -33251,7 +32635,7 @@ function resolveMppEndpoint(identifier) {
33251
32635
  }
33252
32636
 
33253
32637
  // src/commands/wallet-pair.ts
33254
- import { createHash as createHash5, randomBytes as randomBytes5 } from "crypto";
32638
+ import { createHash as createHash4, randomBytes as randomBytes5 } from "crypto";
33255
32639
  import { hostname } from "os";
33256
32640
 
33257
32641
  // node_modules/@noble/ciphers/_arx.js
@@ -34070,17 +33454,17 @@ function hexToBytes2(hex) {
34070
33454
  }
34071
33455
 
34072
33456
  // src/lib/wallet-pairing-store.ts
34073
- var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
33457
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
34074
33458
  import {
34075
33459
  chmodSync as chmodSync2,
34076
- existsSync as existsSync9,
34077
- readdirSync as readdirSync6,
34078
- readFileSync as readFileSync11,
34079
- renameSync as renameSync4,
34080
- unlinkSync as unlinkSync5,
34081
- 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
34082
33466
  } from "fs";
34083
- import { join as join11 } from "path";
33467
+ import { join as join10 } from "path";
34084
33468
  var pairingIdPattern = /^[0-9a-f]{64}$/;
34085
33469
  var stateSchema = external_exports.object({
34086
33470
  version: external_exports.literal(1),
@@ -34102,12 +33486,12 @@ var stateSchema = external_exports.object({
34102
33486
  function createWalletPairingState(state) {
34103
33487
  ensurePairingsDirectory();
34104
33488
  const path = pairingPath(state.pairing_id);
34105
- 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" });
34106
33490
  chmodSync2(path, 384);
34107
33491
  }
34108
33492
  function loadWalletPairingState(pairingId) {
34109
33493
  const path = pairingPath(pairingId);
34110
- if (!existsSync9(path)) {
33494
+ if (!existsSync8(path)) {
34111
33495
  throw new DvmError(
34112
33496
  "wallet_pairing_not_found",
34113
33497
  "No local state exists for that wallet pairing.",
@@ -34115,7 +33499,7 @@ function loadWalletPairingState(pairingId) {
34115
33499
  );
34116
33500
  }
34117
33501
  try {
34118
- return stateSchema.parse(JSON.parse(readFileSync11(path, "utf8")));
33502
+ return stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34119
33503
  } catch {
34120
33504
  throw new DvmError(
34121
33505
  "wallet_pairing_state_invalid",
@@ -34129,13 +33513,13 @@ function saveWalletPairingState(state) {
34129
33513
  ensurePairingsDirectory();
34130
33514
  const path = pairingPath(state.pairing_id);
34131
33515
  const tmp = `${path}.tmp`;
34132
- writeFileSync7(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
33516
+ writeFileSync5(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
34133
33517
  try {
34134
- renameSync4(tmp, path);
33518
+ renameSync3(tmp, path);
34135
33519
  chmodSync2(path, 384);
34136
33520
  } catch (err) {
34137
33521
  try {
34138
- unlinkSync5(tmp);
33522
+ unlinkSync3(tmp);
34139
33523
  } catch {
34140
33524
  }
34141
33525
  throw err;
@@ -34144,21 +33528,21 @@ function saveWalletPairingState(state) {
34144
33528
  function deleteWalletPairingState(pairingId) {
34145
33529
  const path = pairingPath(pairingId);
34146
33530
  try {
34147
- unlinkSync5(path);
33531
+ unlinkSync3(path);
34148
33532
  } catch (err) {
34149
33533
  if (err.code !== "ENOENT") throw err;
34150
33534
  }
34151
33535
  }
34152
33536
  function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() / 1e3)) {
34153
- if (!existsSync9(PAIRINGS_DIR)) return 0;
33537
+ if (!existsSync8(PAIRINGS_DIR)) return 0;
34154
33538
  let removed = 0;
34155
- for (const name of readdirSync6(PAIRINGS_DIR)) {
33539
+ for (const name of readdirSync5(PAIRINGS_DIR)) {
34156
33540
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
34157
- const path = join11(PAIRINGS_DIR, name);
33541
+ const path = join10(PAIRINGS_DIR, name);
34158
33542
  try {
34159
- const state = stateSchema.parse(JSON.parse(readFileSync11(path, "utf8")));
33543
+ const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
34160
33544
  if (state.manifest.expires_at <= nowSeconds) {
34161
- unlinkSync5(path);
33545
+ unlinkSync3(path);
34162
33546
  removed += 1;
34163
33547
  }
34164
33548
  } catch {
@@ -34168,10 +33552,10 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
34168
33552
  }
34169
33553
  async function withWalletPairingLock(pairingId, fn) {
34170
33554
  const path = pairingPath(pairingId);
34171
- if (!existsSync9(path)) return fn();
33555
+ if (!existsSync8(path)) return fn();
34172
33556
  let release;
34173
33557
  try {
34174
- release = await import_proper_lockfile2.default.lock(path, {
33558
+ release = await import_proper_lockfile.default.lock(path, {
34175
33559
  lockfilePath: `${path}.lock`,
34176
33560
  realpath: false,
34177
33561
  stale: 12 * 60 * 1e3,
@@ -34198,7 +33582,7 @@ function pairingPath(pairingId) {
34198
33582
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
34199
33583
  );
34200
33584
  }
34201
- return join11(PAIRINGS_DIR, `${pairingId}.json`);
33585
+ return join10(PAIRINGS_DIR, `${pairingId}.json`);
34202
33586
  }
34203
33587
  function ensurePairingsDirectory() {
34204
33588
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -34623,7 +34007,7 @@ function walletFingerprint(uri) {
34623
34007
  return uri ? sha2562(uri) : null;
34624
34008
  }
34625
34009
  function sha2562(value) {
34626
- return createHash5("sha256").update(value).digest("hex");
34010
+ return createHash4("sha256").update(value).digest("hex");
34627
34011
  }
34628
34012
  function relayHost2(relay) {
34629
34013
  try {
@@ -34751,12 +34135,12 @@ async function walletSubmissions(opts) {
34751
34135
  function listSubmissions(opts) {
34752
34136
  const listed = listSubmissionEvidence();
34753
34137
  const evidence = describeSubmissionEvidence(listed.records);
34754
- const unreadable2 = listed.unreadable;
34755
- 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();
34756
34140
  const summary = wallet ? describePendingSubmissions(wallet) : EMPTY_SUMMARY;
34757
34141
  if (opts.human) {
34758
34142
  printEvidenceHuman(evidence);
34759
- for (const file of unreadable2) {
34143
+ for (const file of unreadable) {
34760
34144
  info(`Unreadable evidence record (${file.cause}): ${file.path}. Restore it from a backup; do not pay again for any request it may describe.`);
34761
34145
  }
34762
34146
  if (summary.entries.length === 0) {
@@ -34811,17 +34195,17 @@ function listSubmissions(opts) {
34811
34195
  // Accepted without a settled job identity: held so nothing pays twice.
34812
34196
  accepted_unresolved_count: summary.accepted_unresolved_count,
34813
34197
  submission_evidence: evidence,
34814
- ...unreadable2.length > 0 ? { submission_evidence_unreadable: unreadable2 } : {},
34198
+ ...unreadable.length > 0 ? { submission_evidence_unreadable: unreadable } : {},
34815
34199
  display: [
34816
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.`,
34817
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,
34818
- 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
34819
34203
  ].filter(Boolean).join(" "),
34820
34204
  hint: [
34821
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,
34822
34206
  summary.reclaimable_count > 0 ? "Entries in state reclaimable need no action \u2014 the wallet takes those sats back after reclaim_at." : null,
34823
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,
34824
- 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,
34825
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,
34826
34210
  "Resumable entries retry on the next paid call or `dvm wallet show`."
34827
34211
  ].filter(Boolean).join(" ")