@dvmkit/dvm-cli 0.15.2 → 0.15.3

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.
@@ -10,13 +10,15 @@ import {
10
10
  formatAmount,
11
11
  formatPaymentAmount,
12
12
  formatSats,
13
+ hasUnsavedJobState,
13
14
  info,
15
+ jobPersistence,
14
16
  json,
15
17
  progress,
16
18
  resolveBtcUsdRate,
17
19
  tryResolveBtcUsdRate,
18
20
  tryX402Payment
19
- } from "./chunk-5SHB3MZ7.js";
21
+ } from "./chunk-F45ETHDP.js";
20
22
  import {
21
23
  loadX402Wallet,
22
24
  x402NetworkLabel
@@ -2041,13 +2043,18 @@ function saveJob(job) {
2041
2043
  jobs.push(job);
2042
2044
  });
2043
2045
  }
2046
+ function saveAcceptedJob(job) {
2047
+ mutateJobs((jobs) => {
2048
+ jobs.push(job);
2049
+ }, true);
2050
+ }
2044
2051
  function saveSubmittedJob(job) {
2045
2052
  mutateJobs((jobs) => {
2046
2053
  const existing = jobs.find((entry) => entry.id === job.id);
2047
2054
  if (!existing) jobs.push(job);
2048
2055
  else if (existing.endpoint !== job.endpoint || existing.requestId && existing.requestId !== job.requestId)
2049
2056
  throw new Error("Submitted job conflicts with an existing local job.");
2050
- });
2057
+ }, true);
2051
2058
  }
2052
2059
  function recordUpfrontCreditPayment(jobId, value, paidOnRail = false) {
2053
2060
  const payment = parseUpfrontPayment(value);
@@ -2077,7 +2084,7 @@ function recordUpfrontCreditPayment(jobId, value, paidOnRail = false) {
2077
2084
  job.totalPaidMsats = (job.totalPaidMsats ?? 0) + payment.amount_msats;
2078
2085
  job.paymentsHonoured = (job.paymentsHonoured ?? 0) + (payment.amount_msats > 0 ? 1 : 0);
2079
2086
  job.upfrontCreditBooked = true;
2080
- });
2087
+ }, true);
2081
2088
  }
2082
2089
  function hasUnknownUpfrontCredit(job) {
2083
2090
  return job.upfrontCreditConflict === true || job.paymentMethod === "credit" && (!job.upfrontCreditBooked || !parseUpfrontPayment(job.upfrontPayment));
@@ -2105,7 +2112,7 @@ function recordUpfrontRailPayment(jobId, value, freshSubmit = false) {
2105
2112
  job.paymentsHonoured = (job.paymentsHonoured ?? 0) + (payment.amountMsats > 0 ? 1 : 0);
2106
2113
  job.paymentMethod = payment.method;
2107
2114
  job.upfrontRailPayment = payment;
2108
- });
2115
+ }, true);
2109
2116
  }
2110
2117
  function hasUnknownUpfrontRail(job) {
2111
2118
  return job.upfrontRailPayment === "unknown" || job.upfrontRailConflict === true;
@@ -2116,16 +2123,22 @@ function updateJob(id, update) {
2116
2123
  if (idx !== -1) jobs[idx] = { ...jobs[idx], ...update };
2117
2124
  });
2118
2125
  }
2126
+ function updateObservedJob(id, update) {
2127
+ mutateJobs((jobs) => {
2128
+ const idx = jobs.findIndex((j) => j.id === id);
2129
+ if (idx !== -1) jobs[idx] = { ...jobs[idx], ...update };
2130
+ }, true);
2131
+ }
2119
2132
  function recordCallerMessageHash(jobId, endpoint, hash) {
2120
2133
  mutateJobs((jobs) => {
2121
2134
  const job = jobs.find((entry) => entry.id === jobId && sameEndpoint(entry.endpoint, endpoint));
2122
2135
  if (job) job.callerMessageHashes = [.../* @__PURE__ */ new Set([...job.callerMessageHashes ?? [], hash])];
2123
- });
2136
+ }, true);
2124
2137
  }
2125
2138
  function markJobTerminal(id, status, completion, extra) {
2126
2139
  const existing = loadJob(id);
2127
2140
  if (!existing) return;
2128
- updateJob(id, {
2141
+ updateObservedJob(id, {
2129
2142
  ...extra,
2130
2143
  status,
2131
2144
  completedAt: existing.completedAt ?? Date.now(),
@@ -2137,6 +2150,8 @@ function loadJob(id) {
2137
2150
  return jobs.find((j) => j.id === id) ?? null;
2138
2151
  }
2139
2152
  function loadAllJobs() {
2153
+ const unsaved = jobPersistence.getStore()?.unsaved;
2154
+ if (unsaved) return structuredClone(unsaved);
2140
2155
  if (!existsSync2(JOBS_FILE)) return [];
2141
2156
  try {
2142
2157
  return JSON.parse(readFileSync2(JOBS_FILE, "utf-8"));
@@ -2148,7 +2163,7 @@ function addPayment(jobId, amountMsats, approval) {
2148
2163
  mutateJobs((jobs) => {
2149
2164
  const job = jobs.find((entry) => entry.id === jobId);
2150
2165
  if (job) bookPayment(job, amountMsats, approval);
2151
- });
2166
+ }, true);
2152
2167
  }
2153
2168
  function bookPayment(job, amountMsats, approval) {
2154
2169
  job.totalPaidMsats = (job.totalPaidMsats ?? 0) + amountMsats;
@@ -2184,7 +2199,7 @@ function clearUnconfirmedSubmission(job, requestSeq) {
2184
2199
  if (!Object.keys(job.unconfirmedPaymentSubmissions).length) delete job.unconfirmedPaymentSubmissions;
2185
2200
  }
2186
2201
  function markPaymentRequestPaid(jobId, requestSeq) {
2187
- return mutateJobs((jobs) => {
2202
+ const booked2 = mutateJobs((jobs) => {
2188
2203
  const job = jobs.find((entry) => entry.id === jobId);
2189
2204
  if (!job) return void 0;
2190
2205
  if (!job.paidPaymentRequestSeqs?.includes(requestSeq))
@@ -2194,15 +2209,16 @@ function markPaymentRequestPaid(jobId, requestSeq) {
2194
2209
  if (!job.inFlightPaymentRequestSeqs.length) delete job.inFlightPaymentRequestSeqs;
2195
2210
  }
2196
2211
  clearPaymentRequestStartTime(job, requestSeq);
2197
- const booked2 = job.unconfirmedPaymentSubmissions?.[requestSeq];
2212
+ const booked3 = job.unconfirmedPaymentSubmissions?.[requestSeq];
2198
2213
  clearUnconfirmedSubmission(job, requestSeq);
2199
- if (booked2) bookPayment(job, booked2.amountMsats, booked2.approval ? { requestSeq, approval: booked2.approval } : void 0);
2200
- if (booked2 && !booked2.blocked && job.askPaymentBlocks?.[requestSeq]) {
2214
+ if (booked3) bookPayment(job, booked3.amountMsats, booked3.approval ? { requestSeq, approval: booked3.approval } : void 0);
2215
+ if (booked3 && !booked3.blocked && job.askPaymentBlocks?.[requestSeq]) {
2201
2216
  delete job.askPaymentBlocks[requestSeq];
2202
2217
  if (!Object.keys(job.askPaymentBlocks).length) delete job.askPaymentBlocks;
2203
2218
  }
2204
- return booked2;
2205
- });
2219
+ return booked3;
2220
+ }, true);
2221
+ return hasUnsavedJobState() ? void 0 : booked2;
2206
2222
  }
2207
2223
  function markPaymentRequestAnswered(jobId, requestSeq) {
2208
2224
  mutateJobs((jobs) => {
@@ -2213,7 +2229,7 @@ function markPaymentRequestAnswered(jobId, requestSeq) {
2213
2229
  job.inFlightPaymentRequestSeqs = job.inFlightPaymentRequestSeqs?.filter((seq) => seq !== requestSeq);
2214
2230
  if (!job.inFlightPaymentRequestSeqs?.length) delete job.inFlightPaymentRequestSeqs;
2215
2231
  clearPaymentRequestStartTime(job, requestSeq);
2216
- });
2232
+ }, true);
2217
2233
  }
2218
2234
  function blockHeldPayment(jobId, requestSeq, blocked) {
2219
2235
  mutateJobs((jobs) => {
@@ -2231,7 +2247,7 @@ function clearAskPaymentBlocks(jobId) {
2231
2247
  mutateJobs((jobs) => {
2232
2248
  const job = jobs.find((entry) => entry.id === jobId);
2233
2249
  if (job) delete job.askPaymentBlocks;
2234
- });
2250
+ }, true);
2235
2251
  }
2236
2252
  function releaseReclaimedSubmissions(cashuRequestIds) {
2237
2253
  if (cashuRequestIds.size === 0) return;
@@ -2280,25 +2296,75 @@ function writeJobs(jobs) {
2280
2296
  }
2281
2297
  }
2282
2298
  }
2283
- function mutateJobs(change) {
2284
- ensureConfigDir();
2285
- const release = import_proper_lockfile.default.lockSync(JOBS_FILE, { realpath: false });
2299
+ var lockWait = new Int32Array(new SharedArrayBuffer(4));
2300
+ function acquireJobsLock() {
2301
+ const deadline = performance.now() + 1e3;
2302
+ for (let attempt = 0; ; attempt++) {
2303
+ try {
2304
+ return import_proper_lockfile.default.lockSync(JOBS_FILE, { realpath: false });
2305
+ } catch (error) {
2306
+ if (error.code !== "ELOCKED" || attempt >= 40 || performance.now() >= deadline) throw error;
2307
+ Atomics.wait(lockWait, 0, 0, Math.min(25, Math.max(0, deadline - performance.now())));
2308
+ }
2309
+ }
2310
+ }
2311
+ function mutateJobs(change, observed = false) {
2312
+ const session = jobPersistence.getStore();
2313
+ const retain = (jobs2) => {
2314
+ if (!session) throw new Error("Job persistence session unavailable.");
2315
+ session.unsaved = structuredClone(jobs2);
2316
+ session.warn();
2317
+ };
2318
+ if (hasUnsavedJobState()) {
2319
+ if (!observed) throw new DvmError(
2320
+ "local_job_state_unsaved",
2321
+ "Local job state must be saved before another payment can be sent.",
2322
+ "Refresh the job once local storage is available; do not submit a replacement."
2323
+ );
2324
+ const jobs2 = loadAllJobs();
2325
+ const result = change(jobs2);
2326
+ retain(jobs2);
2327
+ return result;
2328
+ }
2329
+ let release;
2330
+ try {
2331
+ ensureConfigDir();
2332
+ release = acquireJobsLock();
2333
+ } catch (error) {
2334
+ if (!observed || !session) throw error;
2335
+ const jobs2 = loadAllJobs();
2336
+ const result = change(jobs2);
2337
+ retain(jobs2);
2338
+ return result;
2339
+ }
2340
+ const jobs = loadAllJobs();
2341
+ let mutationCompleted = false;
2286
2342
  try {
2287
- const jobs = loadAllJobs();
2288
2343
  const before = JSON.stringify(jobs);
2289
2344
  const result = change(jobs);
2290
- if (JSON.stringify(jobs) !== before) writeJobs(jobs);
2345
+ mutationCompleted = true;
2346
+ try {
2347
+ if (JSON.stringify(jobs) !== before) writeJobs(jobs);
2348
+ } catch (error) {
2349
+ if (!observed || !session) throw error;
2350
+ retain(jobs);
2351
+ }
2291
2352
  return result;
2292
2353
  } finally {
2293
- release();
2354
+ try {
2355
+ release();
2356
+ } catch (error) {
2357
+ if (!mutationCompleted || !observed || !session) throw error;
2358
+ retain(jobs);
2359
+ }
2294
2360
  }
2295
2361
  }
2296
- function mutateCreditPayment(jobId, change) {
2362
+ function mutateCreditPayment(jobId, change, observed = false) {
2297
2363
  return mutateJobs((jobs) => {
2298
2364
  const job = jobs.find((entry) => entry.id === jobId);
2299
2365
  if (!job) throw new Error("Cannot persist a balance payment for an unknown job.");
2300
2366
  return change(job);
2301
- });
2367
+ }, observed);
2302
2368
  }
2303
2369
  function bookCreditPayment(jobId, intent) {
2304
2370
  mutateCreditPayment(jobId, (job) => {
@@ -2313,7 +2379,7 @@ function bookCreditPayment(jobId, intent) {
2313
2379
  }
2314
2380
  if (job.pendingCreditPayment?.authorization.payment_id === intent.authorization.payment_id)
2315
2381
  delete job.pendingCreditPayment;
2316
- });
2382
+ }, true);
2317
2383
  }
2318
2384
 
2319
2385
  // src/lib/messages/store.ts
@@ -3475,6 +3541,7 @@ async function applyJournalledVerdicts() {
3475
3541
  });
3476
3542
  }
3477
3543
  }
3544
+ if (hasUnsavedJobState()) return;
3478
3545
  const applied = new Set(landed.map((verdict) => verdict.requestId));
3479
3546
  withVerdictsLock(() => writeVerdicts(readVerdicts().filter((verdict) => !applied.has(verdict.requestId))));
3480
3547
  }
@@ -4998,7 +5065,7 @@ function captureDrawFundingReceipts(jobId, receipts, opts) {
4998
5065
  job.drawFundingReceipts = held;
4999
5066
  }
5000
5067
  }
5001
- });
5068
+ }, true);
5002
5069
  } catch (error) {
5003
5070
  info(`Warning: could not store mid-job funding evidence: ${error instanceof Error ? error.message : String(error)}`);
5004
5071
  }
@@ -5219,7 +5286,7 @@ async function backfillTrustAnchor(jobId, transport, ref) {
5219
5286
  try {
5220
5287
  const provider = await transport.describe(ref);
5221
5288
  const fields = receiptTrustFields(provider);
5222
- if (Object.keys(fields).length > 0) updateJob(jobId, fields);
5289
+ if (Object.keys(fields).length > 0) updateObservedJob(jobId, fields);
5223
5290
  return fields.builderAnchor;
5224
5291
  } catch {
5225
5292
  return void 0;
@@ -5263,7 +5330,7 @@ function toCapture(receipt, result, context = receiptPieceContext(receipt), endp
5263
5330
  }
5264
5331
  function persist(jobId, receipt, verification, job) {
5265
5332
  try {
5266
- updateJob(jobId, { receipt });
5333
+ updateObservedJob(jobId, { receipt });
5267
5334
  appendReceipt({
5268
5335
  receipt,
5269
5336
  endpoint: job?.endpoint ?? "",
@@ -5279,7 +5346,7 @@ function persist(jobId, receipt, verification, job) {
5279
5346
  }
5280
5347
  function persistParseError(jobId, receiptParseError) {
5281
5348
  try {
5282
- updateJob(jobId, { receiptParseError });
5349
+ updateObservedJob(jobId, { receiptParseError });
5283
5350
  } catch (err) {
5284
5351
  info(
5285
5352
  `Warning: could not store job receipt diagnostic: ${err instanceof Error ? err.message : String(err)}`
@@ -8783,12 +8850,14 @@ export {
8783
8850
  parseUpfrontRailPayment,
8784
8851
  parseUpfrontPayment,
8785
8852
  saveJob,
8853
+ saveAcceptedJob,
8786
8854
  saveSubmittedJob,
8787
8855
  recordUpfrontCreditPayment,
8788
8856
  hasUnknownUpfrontCredit,
8789
8857
  recordUpfrontRailPayment,
8790
8858
  hasUnknownUpfrontRail,
8791
8859
  updateJob,
8860
+ updateObservedJob,
8792
8861
  recordCallerMessageHash,
8793
8862
  markJobTerminal,
8794
8863
  loadJob,
@@ -8860,6 +8929,7 @@ export {
8860
8929
  withAcceptedUnresolved,
8861
8930
  midJobSpendLabel,
8862
8931
  finishBookedSubmission,
8932
+ journalFile,
8863
8933
  recordReclaimIntent,
8864
8934
  loadReclaimIntent,
8865
8935
  clearReclaimIntent,
@@ -36,13 +36,33 @@ import {
36
36
  import { randomBytes } from "crypto";
37
37
 
38
38
  // src/lib/output.ts
39
- import { AsyncLocalStorage } from "async_hooks";
39
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
40
40
  import { writeSync } from "fs";
41
- var warnings = new AsyncLocalStorage();
42
- function withOutputWarnings(run) {
43
- return warnings.run([], run);
41
+
42
+ // src/lib/job-persistence.ts
43
+ import { AsyncLocalStorage } from "async_hooks";
44
+ var jobPersistence = new AsyncLocalStorage();
45
+ function hasUnsavedJobState() {
46
+ return jobPersistence.getStore()?.unsaved !== void 0;
47
+ }
48
+ function withJobPersistence(run, warn) {
49
+ if (jobPersistence.getStore()) return run();
50
+ return jobPersistence.run({ warn }, run);
51
+ }
52
+
53
+ // src/lib/output.ts
54
+ var warnings = new AsyncLocalStorage2();
55
+ function withOutputWarnings(run, human) {
56
+ return warnings.run([], () => withJobPersistence(run, () => {
57
+ addOutputWarnings([{
58
+ code: "local_job_state_unsaved",
59
+ display: "The provider's outcome is unchanged, but local job state could not be saved and may lag. Automatic payments are paused for this command.",
60
+ hint: "Once local storage is available, refresh the job with dvm status <job_id> --messages before paying or submitting a replacement."
61
+ }], human);
62
+ }));
44
63
  }
45
64
  function sameWarning(prior, entry) {
65
+ if (prior.code === "local_job_state_unsaved" && entry.code === "local_job_state_unsaved") return true;
46
66
  if (prior.code === "auto_pay_bound_exceeded" && entry.code === "auto_pay_bound_exceeded") {
47
67
  return prior.auto_pay_below === entry.auto_pay_below && prior.source === entry.source;
48
68
  }
@@ -419,6 +439,8 @@ async function priceableRate(btcRate) {
419
439
  }
420
440
 
421
441
  export {
442
+ jobPersistence,
443
+ hasUnsavedJobState,
422
444
  withOutputWarnings,
423
445
  addOutputWarnings,
424
446
  setOutputTraceId,
@@ -3,7 +3,7 @@ import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
5
  tryX402Payment
6
- } from "./chunk-5SHB3MZ7.js";
6
+ } from "./chunk-F45ETHDP.js";
7
7
  import "./chunk-YQJRKWNT.js";
8
8
  import "./chunk-JBU7RKQ3.js";
9
9
  import "./chunk-KDNFUDOG.js";
package/dist/dvm.js CHANGED
@@ -83,6 +83,7 @@ import {
83
83
  jobDrawFundings,
84
84
  jobIdentityHeaderValue,
85
85
  jobSettlement,
86
+ journalFile,
86
87
  journalMarkerFor,
87
88
  listPendingCardFundings,
88
89
  listSubmissionEvidence,
@@ -166,6 +167,7 @@ import {
166
167
  revertInFlight,
167
168
  routerConflictObservation,
168
169
  sameEndpoint,
170
+ saveAcceptedJob,
169
171
  saveFavorite,
170
172
  saveJob,
171
173
  saveLedger,
@@ -188,13 +190,14 @@ import {
188
190
  unrecordedFloatBudgetWarning,
189
191
  unresendablePaymentHint,
190
192
  updateJob,
193
+ updateObservedJob,
191
194
  walletHistory,
192
195
  warnInvalidJobIdentityHeader,
193
196
  withAcceptedUnresolved,
194
197
  withIdentityRecovery,
195
198
  withJobTokenRedaction,
196
199
  withRequestResultRecovery
197
- } from "./chunk-ECJO73RZ.js";
200
+ } from "./chunk-DZHEYRS2.js";
198
201
  import {
199
202
  connectedTempoAccount,
200
203
  generateTempoKey,
@@ -209,6 +212,7 @@ import {
209
212
  formatAmountBestEffort,
210
213
  formatPaymentAmount,
211
214
  getOutputTraceId,
215
+ hasUnsavedJobState,
212
216
  info,
213
217
  json,
214
218
  monetaryJson,
@@ -220,7 +224,7 @@ import {
220
224
  tryResolveBtcUsdRate,
221
225
  tryX402Payment,
222
226
  withOutputWarnings
223
- } from "./chunk-5SHB3MZ7.js";
227
+ } from "./chunk-F45ETHDP.js";
224
228
  import {
225
229
  assertSupportedX402Network,
226
230
  connectedX402Payer,
@@ -11179,9 +11183,9 @@ function configuredTempoNetwork() {
11179
11183
  if (tempo?.method !== "tempo") return null;
11180
11184
  return parseTempoNetwork(tempo.network, "config.tempo.network") ?? "mainnet";
11181
11185
  }
11182
- function assertTempoChallengeNetwork(challenges, network, intents) {
11186
+ function assertTempoChallengeNetwork(challenges, network, intents2) {
11183
11187
  const expected = resolveTempoNetwork(network);
11184
- const acceptedIntents = intents ? new Set(intents) : null;
11188
+ const acceptedIntents = intents2 ? new Set(intents2) : null;
11185
11189
  for (const challenge of challenges) {
11186
11190
  if (challenge.method !== "tempo" || acceptedIntents && !acceptedIntents.has(challenge.intent))
11187
11191
  continue;
@@ -11201,9 +11205,9 @@ function assertTempoChallengeNetwork(challenges, network, intents) {
11201
11205
  );
11202
11206
  }
11203
11207
  }
11204
- function assertConfiguredTempoChallengeNetwork(challenges, intents) {
11208
+ function assertConfiguredTempoChallengeNetwork(challenges, intents2) {
11205
11209
  const network = configuredTempoNetwork();
11206
- if (network) assertTempoChallengeNetwork(challenges, network, intents);
11210
+ if (network) assertTempoChallengeNetwork(challenges, network, intents2);
11207
11211
  }
11208
11212
  function assertTempoChannelNetwork(association, account) {
11209
11213
  const network = tempoAccountNetwork(account);
@@ -11602,7 +11606,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
11602
11606
  }
11603
11607
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
11604
11608
  const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-Z3FDX43V.js");
11605
- const { tryX402Payment: tryX402Payment2 } = await import("./client-YIHI4AIC.js");
11609
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-NBC2IDA2.js");
11606
11610
  const wallet = loadX402Wallet2();
11607
11611
  if (wallet) {
11608
11612
  let proof;
@@ -12049,7 +12053,7 @@ async function claimInboundPayments(jobId, messages2) {
12049
12053
  if (claimedMsats > 0) {
12050
12054
  claimedSeqs.add(msg.seq);
12051
12055
  claimedAmounts[msg.seq] = claimedMsats;
12052
- updateJob(jobId, { claimedPaymentSeqs: [...claimedSeqs], claimedPaymentAmountsMsats: claimedAmounts });
12056
+ updateObservedJob(jobId, { claimedPaymentSeqs: [...claimedSeqs], claimedPaymentAmountsMsats: claimedAmounts });
12053
12057
  results.push({
12054
12058
  seq: msg.seq,
12055
12059
  amount_msats: claimedMsats,
@@ -12133,6 +12137,13 @@ function withRefundNextAction(jobId, action, claims) {
12133
12137
  // src/lib/stream-loop.ts
12134
12138
  async function streamLoop(opts) {
12135
12139
  const { jobId, transport, provider } = opts;
12140
+ if (hasUnsavedJobState()) return {
12141
+ messages: [],
12142
+ autoPayments: [],
12143
+ refunds: [],
12144
+ cursor: opts.afterSeq,
12145
+ nextAction: pollNextAction(jobId, "Local state may lag; refresh this job before another payment.")
12146
+ };
12136
12147
  const persistLocalState = opts.persistLocalState !== false;
12137
12148
  const policy = persistLocalState ? opts.policy : void 0;
12138
12149
  const allMessages = [];
@@ -12196,7 +12207,7 @@ async function streamLoop(opts) {
12196
12207
  }
12197
12208
  try {
12198
12209
  for (; ; ) {
12199
- if (deadline !== void 0 && Date.now() >= deadline) break;
12210
+ if (hasUnsavedJobState() || deadline !== void 0 && Date.now() >= deadline) break;
12200
12211
  const streamFn = transport.stream?.bind(transport);
12201
12212
  let batchMessages;
12202
12213
  if (streamFn) {
@@ -12235,9 +12246,11 @@ async function streamLoop(opts) {
12235
12246
  messageAppendSession ??= createMessageAppendSession(jobId);
12236
12247
  messageAppendSession.append(batchMessages);
12237
12248
  await settleRecordedPayments(jobId);
12249
+ if (hasUnsavedJobState()) break;
12238
12250
  }
12239
12251
  if (persistLocalState) {
12240
12252
  refunds.push(...await claimInboundPayments(jobId, batchMessages));
12253
+ if (hasUnsavedJobState()) break;
12241
12254
  }
12242
12255
  justAutoPaid = false;
12243
12256
  if (persistLocalState) for (const seq of loadAnsweredYieldSeqs(jobId)) answeredSeqs.add(seq);
@@ -12314,7 +12327,7 @@ async function streamLoop(opts) {
12314
12327
  } finally {
12315
12328
  if (timer) clearTimeout(timer);
12316
12329
  }
12317
- if (justAutoPaid) {
12330
+ if (justAutoPaid && !hasUnsavedJobState()) {
12318
12331
  const pollOptions = nextPollOptions();
12319
12332
  let recheck = [];
12320
12333
  try {
@@ -12359,6 +12372,8 @@ async function streamLoop(opts) {
12359
12372
  heldJob,
12360
12373
  lastYield?.type === "payment-request" ? lastYield.seq : void 0
12361
12374
  ));
12375
+ if (hasUnsavedJobState() && !terminal)
12376
+ nextAction = pollNextAction(jobId, "Local state may lag; refresh this job before another payment.");
12362
12377
  return { messages: allMessages, autoPayments, refunds, nextAction, cursor };
12363
12378
  }
12364
12379
  function isMessagePollTimeout(err) {
@@ -12421,7 +12436,7 @@ function persistStreamOutcome(outcome) {
12421
12436
  });
12422
12437
  return completion;
12423
12438
  }
12424
- updateJob(jobId, { messageCursor: cursor });
12439
+ updateObservedJob(jobId, { messageCursor: cursor });
12425
12440
  return void 0;
12426
12441
  }
12427
12442
  function streamTerminalStatus(messages2, context = {}) {
@@ -14351,6 +14366,7 @@ function creditDrainCommand(handle, creditId) {
14351
14366
  // src/lib/credit-topup.ts
14352
14367
  async function settleCreditAfterJob(args) {
14353
14368
  const deferred = args.deferred ?? takeDeferredFunding();
14369
+ if (hasUnsavedJobState()) return;
14354
14370
  try {
14355
14371
  await settle(args);
14356
14372
  } catch (err) {
@@ -14368,7 +14384,7 @@ async function settleCreditAfterJob(args) {
14368
14384
  }
14369
14385
  }
14370
14386
  if (args.allowTopup !== false) {
14371
- const refill = args.refillPocket ?? (await import("./pocket-refill-XZTMPTP6.js")).refillPocketIfLow;
14387
+ const refill = args.refillPocket ?? (await import("./pocket-refill-LCDXSC74.js")).refillPocketIfLow;
14372
14388
  await refill({ human: args.human }).catch(() => void 0);
14373
14389
  }
14374
14390
  }
@@ -14775,7 +14791,7 @@ function dvmIdentity(dvmId, capability) {
14775
14791
  // src/commands/cancel.ts
14776
14792
  async function cancel(jobId, opts) {
14777
14793
  const access = resolveJobAccess(jobId, opts);
14778
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => cancelWithAccess(jobId, opts, access)));
14794
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => cancelWithAccess(jobId, opts, access), opts.human));
14779
14795
  }
14780
14796
  async function cancelWithAccess(jobId, opts, access) {
14781
14797
  const { stored, ref, jobToken } = access;
@@ -14851,7 +14867,7 @@ function expectsReceipt(jobId, stored) {
14851
14867
  // src/commands/decline.ts
14852
14868
  async function decline(jobId, opts) {
14853
14869
  const access = resolveJobAccess(jobId, opts);
14854
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => declineWithAccess(jobId, opts, access)));
14870
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => declineWithAccess(jobId, opts, access), opts.human));
14855
14871
  }
14856
14872
  async function declineWithAccess(jobId, opts, access) {
14857
14873
  const { stored, ref, jobToken } = access;
@@ -18652,6 +18668,10 @@ async function runCreditDrain(dvm, opts) {
18652
18668
  });
18653
18669
  return;
18654
18670
  }
18671
+ if (method === "tempo" && isKnownEmptyTempoCredit(stored, creditId) && !opts.drainId && !pendingDrainFor(stored, creditId) && !tempoSession) {
18672
+ renderAlreadyDrained({ human: opts.human === true, endpoint, creditId });
18673
+ return;
18674
+ }
18655
18675
  const canPersist = !stored || stored.creditId === creditId;
18656
18676
  const named = opts.drainId ? pendingDrainById(stored, opts.drainId) : void 0;
18657
18677
  if (named?.creditId !== void 0 && named.creditId !== creditId) {
@@ -18973,6 +18993,10 @@ async function runCreditDrain(dvm, opts) {
18973
18993
  if (!stored) forgetCredit(endpoint, signer.pubkey, ...identityArg);
18974
18994
  else if (mintedThisRun) clearPendingDrain(endpoint, signer.pubkey, drain, ...identityArg);
18975
18995
  }
18996
+ if (err instanceof DvmError && err.code === "tempo_channel_exit_required" && err.data?.drain_registered === false && isKnownEmptyTempoCredit(stored, creditId)) {
18997
+ renderAlreadyDrained({ human: opts.human === true, endpoint, creditId });
18998
+ return;
18999
+ }
18976
19000
  if (err instanceof DvmError && err.code === "tempo_channel_exit_required") {
18977
19001
  const local2 = tempoExitRequiredCopy(exitRecovery, err.data?.channel_id, err.data?.status);
18978
19002
  const display2 = retirement ? `${local2.display} ${retirement}` : local2.display;
@@ -19429,6 +19453,27 @@ function localDrainCopy(wire, requested, exitRecovery) {
19429
19453
  );
19430
19454
  }
19431
19455
  }
19456
+ function isKnownEmptyTempoCredit(stored, creditId) {
19457
+ return stored?.creditId === creditId && stored.status === "drained" && stored.remainingMicro <= 0 && !stored.provisional && !stored.discrepancy;
19458
+ }
19459
+ function renderAlreadyDrained(args) {
19460
+ const display = "This credit is already drained: its earlier drain was sent, so nothing is owed and no refund is pending.";
19461
+ const hint = "Nothing remains to reclaim, so no further drain or on-chain action is needed. A fresh credit can open when you next need one.";
19462
+ if (args.human) {
19463
+ info(display);
19464
+ info(hint);
19465
+ return;
19466
+ }
19467
+ json({
19468
+ op: "drain",
19469
+ endpoint: args.endpoint,
19470
+ credit_id: args.creditId,
19471
+ already_drained: true,
19472
+ balance_micro: 0,
19473
+ display,
19474
+ hint
19475
+ });
19476
+ }
19432
19477
  function tempoExitRequiredCopy(recovery, channelId, status2) {
19433
19478
  const channel = typeof channelId === "string" ? ` Channel ID: ${channelId}.` : "";
19434
19479
  const pending4 = status2 === "pending";
@@ -25434,7 +25479,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25434
25479
  }
25435
25480
  return void 0;
25436
25481
  }
25437
- while (now() < deadline) {
25482
+ while (now() < deadline && !hasUnsavedJobState()) {
25438
25483
  const readOptions = () => ({ jobToken: opts.jobToken, timeoutMs: Math.max(1, Math.min(idleTimeoutMs, deadline - now())) });
25439
25484
  const snapshot = await readWithRetry(() => opts.transport.status(opts.jobId, opts.provider, readOptions()));
25440
25485
  if (!snapshot) break;
@@ -25528,7 +25573,7 @@ async function waitForJob(opts, durationMs, now = Date.now) {
25528
25573
  const progressed = next.cursor > result.cursor;
25529
25574
  result.cursor = Math.min(next.cursor, cursorLimit);
25530
25575
  result.nextAction = next.nextAction;
25531
- if (next.nextAction?.type !== "poll") break;
25576
+ if (hasUnsavedJobState() || next.nextAction?.type !== "poll") break;
25532
25577
  if (progressed) backoffMs = 1e3;
25533
25578
  const delay = Math.min(backoffMs, Math.max(0, deadline - now()));
25534
25579
  if (delay > 0) await new Promise((resolve3) => setTimeout(resolve3, delay));
@@ -25548,7 +25593,7 @@ async function messages(jobId, opts) {
25548
25593
  throw new DvmError("invalid_arguments", "Use --until with --wait, and --wait with streaming enabled.");
25549
25594
  }
25550
25595
  const access = resolveJobAccess(jobId, opts);
25551
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => messagesWithAccess(jobId, opts, access)));
25596
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => messagesWithAccess(jobId, opts, access), opts.human));
25552
25597
  }
25553
25598
  async function messagesWithAccess(jobId, opts, access) {
25554
25599
  const waitDuration = opts.wait ? parseDurationMs(opts.until ?? "12h") : void 0;
@@ -25808,7 +25853,7 @@ async function message(jobId, text, opts) {
25808
25853
  const access = resolveJobAccess(jobId, opts);
25809
25854
  return withJobTokenRedaction(
25810
25855
  access.jobToken,
25811
- () => withOutputWarnings(() => messageWithAccess(jobId, text, opts, access))
25856
+ () => withOutputWarnings(() => messageWithAccess(jobId, text, opts, access), opts.human)
25812
25857
  );
25813
25858
  }
25814
25859
  async function messageWithAccess(jobId, text, opts, access) {
@@ -25946,7 +25991,7 @@ function parseForcedRail(raw2) {
25946
25991
  // src/commands/pay.ts
25947
25992
  async function pay(jobId, opts) {
25948
25993
  const access = resolveStoredJobAccess(jobId, opts);
25949
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => payWithAccess(jobId, opts, access)));
25994
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => payWithAccess(jobId, opts, access), opts.human));
25950
25995
  }
25951
25996
  async function payWithAccess(jobId, opts, access) {
25952
25997
  const rail = parseForcedRail(opts.rail);
@@ -26469,7 +26514,7 @@ function isPlainObject2(value) {
26469
26514
 
26470
26515
  // src/commands/quote.ts
26471
26516
  async function quote(opts) {
26472
- return withOutputWarnings(() => quoteWithWarnings(opts));
26517
+ return withOutputWarnings(() => quoteWithWarnings(opts), opts.human);
26473
26518
  }
26474
26519
  async function quoteWithWarnings(opts) {
26475
26520
  if (!opts.dvm && !opts.endpoint) {
@@ -27502,7 +27547,7 @@ async function request(opts) {
27502
27547
  } catch (error) {
27503
27548
  throw stage.intentReached ? error : markRefusedBeforeSend(opts.requestId, error);
27504
27549
  }
27505
- });
27550
+ }, opts.human);
27506
27551
  }
27507
27552
  function markRefusedBeforeSend(requestId, error) {
27508
27553
  if (!requestId || !(error instanceof DvmError)) return error;
@@ -28055,7 +28100,7 @@ async function requestWithWarnings(opts, stage) {
28055
28100
  }
28056
28101
  case "awaiting-input":
28057
28102
  case "processing": {
28058
- updateJob(receipt.jobId, {
28103
+ updateObservedJob(receipt.jobId, {
28059
28104
  status: receipt.status === "awaiting-input" ? "awaiting-input" : "processing"
28060
28105
  });
28061
28106
  const result = await streamToCompletion(
@@ -28967,7 +29012,7 @@ async function payWithTempo(args, credential) {
28967
29012
  }
28968
29013
  const effectiveJobId = args.jobId || receipt.jobId;
28969
29014
  if (!args.jobId && receipt.jobId) {
28970
- saveJob({
29015
+ saveAcceptedJob({
28971
29016
  id: effectiveJobId,
28972
29017
  ...transactionRecordFields(receipt),
28973
29018
  endpoint: ref.endpoint,
@@ -29059,7 +29104,7 @@ async function payWithTempo(args, credential) {
29059
29104
  }
29060
29105
  return;
29061
29106
  }
29062
- updateJob(effectiveJobId, {
29107
+ updateObservedJob(effectiveJobId, {
29063
29108
  status: "processing",
29064
29109
  paymentMethod: "tempo"
29065
29110
  });
@@ -29628,7 +29673,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29628
29673
  }
29629
29674
  const effectiveJobId = jobId || receipt.jobId;
29630
29675
  if (!jobId && receipt.jobId) {
29631
- saveJob({
29676
+ saveAcceptedJob({
29632
29677
  id: effectiveJobId,
29633
29678
  ...transactionRecordFields(receipt),
29634
29679
  endpoint: ref.endpoint,
@@ -29660,7 +29705,9 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29660
29705
  ...localCorrelationJobFields(normalizedLocalCorrelationId(opts))
29661
29706
  });
29662
29707
  }
29663
- await commitAgentSpend({
29708
+ await collectCashuChange(effectiveJobId, receipt.cashuChange);
29709
+ recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
29710
+ if (!hasUnsavedJobState()) await commitAgentSpend({
29664
29711
  requestId: prepared.requestId,
29665
29712
  recentSpend: {
29666
29713
  request_id: prepared.requestId,
@@ -29670,9 +29717,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29670
29717
  signed_at_ms: Date.now()
29671
29718
  }
29672
29719
  });
29673
- await collectCashuChange(effectiveJobId, receipt.cashuChange);
29674
- recordUpfrontRailPayment(effectiveJobId, { method: "cashu", amountMsats: chosen.priceMsats }, true);
29675
- if (fundPlan) {
29720
+ if (!hasUnsavedJobState() && fundPlan) {
29676
29721
  recordSpend({
29677
29722
  msats: fundPlan.fundMsats,
29678
29723
  btcRate,
@@ -29681,7 +29726,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29681
29726
  providerEndpoint: ref.endpoint,
29682
29727
  label: `credit fund \xB7 ${identity.dvmId ?? identity.capability}`
29683
29728
  });
29684
- } else {
29729
+ } else if (!hasUnsavedJobState()) {
29685
29730
  recordSpend({
29686
29731
  msats: chosen.priceMsats,
29687
29732
  btcRate,
@@ -29740,7 +29785,7 @@ async function payWithAgentWallet(transport, ref, envelope, jobId, deadlineMs, c
29740
29785
  }
29741
29786
  return;
29742
29787
  }
29743
- updateJob(effectiveJobId, {
29788
+ updateObservedJob(effectiveJobId, {
29744
29789
  status: "processing",
29745
29790
  paymentMethod: "cashu"
29746
29791
  });
@@ -29858,7 +29903,7 @@ async function payWithX402(args, proof) {
29858
29903
  }
29859
29904
  const effectiveJobId = args.jobId || receipt.jobId;
29860
29905
  if (!args.jobId && receipt.jobId) {
29861
- saveJob({
29906
+ saveAcceptedJob({
29862
29907
  id: effectiveJobId,
29863
29908
  ...transactionRecordFields(receipt),
29864
29909
  endpoint: ref.endpoint,
@@ -29939,7 +29984,7 @@ async function payWithX402(args, proof) {
29939
29984
  }
29940
29985
  return;
29941
29986
  }
29942
- updateJob(effectiveJobId, {
29987
+ updateObservedJob(effectiveJobId, {
29943
29988
  status: "processing",
29944
29989
  paymentMethod: "x402"
29945
29990
  });
@@ -29974,7 +30019,7 @@ async function streamToCompletion(baseOpts, deadlineMs) {
29974
30019
  const allMessages = [...result.messages];
29975
30020
  const allAutoPayments = [...result.autoPayments];
29976
30021
  const allRefunds = [...result.refunds];
29977
- while (result.nextAction?.type === "poll") {
30022
+ while (result.nextAction?.type === "poll" && !hasUnsavedJobState()) {
29978
30023
  if (Date.now() >= deadlineMs) break;
29979
30024
  const waitMs = Math.min(
29980
30025
  Math.max((result.nextAction.estimate_seconds ?? 0) * 1e3, MIN_POLL_WAIT_MS),
@@ -30062,7 +30107,7 @@ async function streamAfterPayment(args) {
30062
30107
  });
30063
30108
  }
30064
30109
  transport.close?.();
30065
- if (result.messages.length === 0) {
30110
+ if (result.messages.length === 0 && !hasUnsavedJobState()) {
30066
30111
  const recovered = await recoverViaStatusPoll({
30067
30112
  jobId,
30068
30113
  transport,
@@ -30121,7 +30166,7 @@ async function streamAfterPayment(args) {
30121
30166
  jobId,
30122
30167
  ...dvmFields,
30123
30168
  messages: result.messages.map(serializeMessageForOutput),
30124
- ...streamedTerminal ? { status: streamedTerminal } : {},
30169
+ ...streamedTerminal ? { status: streamedTerminal } : hasUnsavedJobState() ? { status: "processing" } : {},
30125
30170
  ...completion?.message !== void 0 ? { message: completion.message } : {},
30126
30171
  // Same as the unpaid arc above: the outcome is only knowable from the
30127
30172
  // streamed log here, so render it rather than leaving the agent to dig
@@ -30246,7 +30291,7 @@ async function collectCashuChange(jobId, cashuChange) {
30246
30291
  } catch {
30247
30292
  }
30248
30293
  if (sats > 0) {
30249
- updateJob(jobId, { changeProcessed: true });
30294
+ updateObservedJob(jobId, { changeProcessed: true });
30250
30295
  info(`Received ${sats} sats change.`);
30251
30296
  }
30252
30297
  }
@@ -30267,6 +30312,9 @@ async function readStdin() {
30267
30312
 
30268
30313
  // src/commands/request-result.ts
30269
30314
  async function requestResult(requestId, opts = {}) {
30315
+ return withOutputWarnings(() => requestResultWithWarnings(requestId, opts), opts.human);
30316
+ }
30317
+ async function requestResultWithWarnings(requestId, opts) {
30270
30318
  if (!isPublicRequestId(requestId)) {
30271
30319
  throw new DvmError(
30272
30320
  "invalid_request_id",
@@ -30359,9 +30407,9 @@ async function requestResult(requestId, opts = {}) {
30359
30407
  "Do not overwrite the local record."
30360
30408
  );
30361
30409
  }
30362
- updateJob(receipt.jobId, restored);
30410
+ updateObservedJob(receipt.jobId, restored);
30363
30411
  } else {
30364
- saveJob({
30412
+ saveAcceptedJob({
30365
30413
  id: receipt.jobId,
30366
30414
  endpoint: intent.endpoint,
30367
30415
  dvmId: intent.dvmId,
@@ -30389,7 +30437,7 @@ async function requestResult(requestId, opts = {}) {
30389
30437
  if (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled") {
30390
30438
  markJobTerminal(receipt.jobId, receipt.status, completionSnapshot(receipt), restored);
30391
30439
  } else {
30392
- updateJob(receipt.jobId, {
30440
+ updateObservedJob(receipt.jobId, {
30393
30441
  status: receipt.status === "awaiting-input" ? "awaiting-input" : "processing",
30394
30442
  ...restored
30395
30443
  });
@@ -30399,7 +30447,7 @@ async function requestResult(requestId, opts = {}) {
30399
30447
  if (recovered && (receipt.status === "completed" || receipt.status === "failed" || receipt.status === "cancelled")) {
30400
30448
  await settleCreditAfterRead({ job: recovered, capture: captured, transport, human: opts.human });
30401
30449
  }
30402
- const confirmed = await bookRecoveredSubmissions({
30450
+ const confirmed = hasUnsavedJobState() ? [] : await bookRecoveredSubmissions({
30403
30451
  publicRequestId: requestId,
30404
30452
  endpoint: intent.endpoint,
30405
30453
  jobId: receipt.jobId
@@ -30495,7 +30543,7 @@ function paymentMethod(receipt) {
30495
30543
 
30496
30544
  // src/commands/request-resume.ts
30497
30545
  async function requestResume(requestId, opts = {}) {
30498
- return withOutputWarnings(() => resumeRequest(requestId, opts));
30546
+ return withOutputWarnings(() => resumeRequest(requestId, opts), opts.human);
30499
30547
  }
30500
30548
  async function resumeRequest(requestId, opts) {
30501
30549
  if (!isPublicRequestId(requestId)) {
@@ -30848,7 +30896,7 @@ function renderSpendHuman(spend, print) {
30848
30896
  // src/commands/status.ts
30849
30897
  async function status(jobId, opts) {
30850
30898
  const access = resolveJobAccess(jobId, opts);
30851
- return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => statusWithAccess(jobId, opts, access)));
30899
+ return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => statusWithAccess(jobId, opts, access), opts.human));
30852
30900
  }
30853
30901
  async function statusWithAccess(jobId, opts, access) {
30854
30902
  const { stored, ref, jobToken } = access;
@@ -30963,7 +31011,7 @@ async function statusWithAccess(jobId, opts, access) {
30963
31011
  const updates = {};
30964
31012
  if (result.status === "processing") updates.status = "processing";
30965
31013
  if (newCursor !== void 0) updates.messageCursor = newCursor;
30966
- if (Object.keys(updates).length > 0) updateJob(jobId, updates);
31014
+ if (Object.keys(updates).length > 0) updateObservedJob(jobId, updates);
30967
31015
  }
30968
31016
  transport.close();
30969
31017
  renderStatus(jobId, stored, result.status, completion, "provider", nextAction, opts, {
@@ -35016,6 +35064,57 @@ async function writeInvoicePng(invoice, outPath) {
35016
35064
  }
35017
35065
 
35018
35066
  // src/lib/wallet-agent/release.ts
35067
+ import { randomUUID as randomUUID5 } from "crypto";
35068
+
35069
+ // src/lib/wallet-agent/release-intents.ts
35070
+ var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
35071
+ import { createHash as createHash6 } from "crypto";
35072
+ import { dirname as dirname4, join as join10 } from "path";
35073
+ var intents = journalFile("release-intents.json");
35074
+ async function withReleaseLock(walletPubkey, builderHandle, mint, operation) {
35075
+ ensureConfigDir();
35076
+ const key = createHash6("sha256").update(JSON.stringify([walletPubkey, builderHandle, mint])).digest("hex");
35077
+ let unlock;
35078
+ try {
35079
+ unlock = await import_proper_lockfile3.default.lock(join10(dirname4(JOBS_FILE), `release-${key}`), {
35080
+ realpath: false,
35081
+ stale: 2 * 6e4,
35082
+ retries: 0
35083
+ });
35084
+ } catch {
35085
+ throw new Error("Could not acquire the release lock; another release may be running for this builder and mint. Retry `dvm wallet release` shortly.");
35086
+ }
35087
+ try {
35088
+ return await operation();
35089
+ } finally {
35090
+ try {
35091
+ await unlock();
35092
+ } catch {
35093
+ }
35094
+ }
35095
+ }
35096
+ function allReleaseIntents() {
35097
+ return intents.read();
35098
+ }
35099
+ function loadReleaseIntent(walletPubkey, builderHandle, mint) {
35100
+ return intents.read().find(
35101
+ (intent) => intent.walletPubkey === walletPubkey && intent.builderHandle === builderHandle && intent.mint === mint
35102
+ );
35103
+ }
35104
+ function recordReleaseIntent(intent) {
35105
+ intents.withLock(() => {
35106
+ if (loadReleaseIntent(intent.walletPubkey, intent.builderHandle, intent.mint)) {
35107
+ throw new Error("Another release is awaiting recovery; retry `dvm wallet release`.");
35108
+ }
35109
+ intents.write([...intents.read(), intent]);
35110
+ });
35111
+ }
35112
+ function clearReleaseIntent(intent) {
35113
+ intents.withLock(() => intents.write(intents.read().filter((held) => held.id !== intent.id)));
35114
+ }
35115
+
35116
+ // src/lib/wallet-agent/release.ts
35117
+ var RELEASE_IN_FLIGHT_MS = 2 * 6e4;
35019
35118
  async function releaseAgentReserve(opts) {
35020
35119
  const cashu = opts.providerInfo.cashu;
35021
35120
  if (!cashu?.canonical_id) {
@@ -35045,9 +35144,6 @@ async function releaseAgentReserve(opts) {
35045
35144
  const candidates = initial.proofs.filter(
35046
35145
  (p) => p.reserved_for === marker && p.status === "valid" && typeof p.t_expire === "number" && p.t_expire < now
35047
35146
  );
35048
- if (candidates.length === 0) {
35049
- return { builder_handle: opts.builderHandle, output_mode: outputMode, mints: [] };
35050
- }
35051
35147
  const getWalletForMint = opts.getWalletForMint ?? getWallet;
35052
35148
  const byMint = /* @__PURE__ */ new Map();
35053
35149
  for (const p of candidates) {
@@ -35055,47 +35151,60 @@ async function releaseAgentReserve(opts) {
35055
35151
  bucket.push(p);
35056
35152
  byMint.set(p.mint, bucket);
35057
35153
  }
35154
+ for (const intent of allReleaseIntents()) {
35155
+ if (intent.walletPubkey === initial.lock_pubkey && intent.builderHandle === opts.builderHandle && !byMint.has(intent.mint)) {
35156
+ byMint.set(intent.mint, []);
35157
+ }
35158
+ }
35058
35159
  const outcomes = [];
35059
35160
  for (const [mintUrl, mintProofs] of byMint) {
35060
- outcomes.push(
35061
- await releaseAtMint(
35161
+ try {
35162
+ outcomes.push(await withReleaseLock(
35163
+ initial.lock_pubkey,
35164
+ opts.builderHandle,
35062
35165
  mintUrl,
35063
- mintProofs,
35064
- refund.privkey,
35065
- initial,
35066
- outputMode,
35067
- getWalletForMint
35068
- )
35069
- );
35166
+ () => releaseAtMint(mintUrl, mintProofs, refund.privkey, initial, outputMode, getWalletForMint, opts.builderHandle, now)
35167
+ ));
35168
+ } catch (err) {
35169
+ outcomes.push({ mint: mintUrl, output_mode: null, alreadySpent: [], pending: [], reclaimedInputs: [], reclaimedOutputs: [], error: errorText2(err) });
35170
+ }
35070
35171
  }
35071
- return { builder_handle: opts.builderHandle, output_mode: outputMode, mints: outcomes };
35172
+ const modes = new Set(outcomes.flatMap((outcome) => outcome.output_mode === null ? [] : [outcome.output_mode]));
35173
+ return {
35174
+ builder_handle: opts.builderHandle,
35175
+ output_mode: modes.size > 1 ? "mixed" : modes.values().next().value ?? outputMode,
35176
+ mints: outcomes
35177
+ };
35072
35178
  }
35073
- async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, outputMode, getWalletForMint) {
35179
+ async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, outputMode, getWalletForMint, builderHandle, now) {
35180
+ const outcome = {
35181
+ mint: mintUrl,
35182
+ output_mode: null,
35183
+ alreadySpent: [],
35184
+ pending: [],
35185
+ reclaimedInputs: [],
35186
+ reclaimedOutputs: [],
35187
+ error: null
35188
+ };
35074
35189
  let cashuWallet;
35075
35190
  try {
35076
35191
  cashuWallet = await getWalletForMint(mintUrl);
35192
+ const intent2 = loadReleaseIntent(initial.lock_pubkey, builderHandle, mintUrl);
35193
+ if (intent2) {
35194
+ const recovered = await recoverRelease(intent2, cashuWallet, outcome, now);
35195
+ if (recovered) return recovered;
35196
+ }
35197
+ const available = new Set(currentWallet(initial.lock_pubkey).proofs.filter((p) => p.mint === mintUrl && p.status === "valid").map(proofIdKey));
35198
+ mintProofs = mintProofs.filter((p) => available.has(proofIdKey(p)));
35077
35199
  } catch (err) {
35078
- return {
35079
- mint: mintUrl,
35080
- alreadySpent: [],
35081
- pending: [],
35082
- reclaimedInputs: [],
35083
- reclaimedOutputs: [],
35084
- error: err instanceof Error ? err.message : String(err)
35085
- };
35200
+ return { ...outcome, error: errorText2(err) };
35086
35201
  }
35202
+ if (mintProofs.length === 0) return outcome;
35087
35203
  let grouped;
35088
35204
  try {
35089
35205
  grouped = await cashuWallet.groupProofsByState(toCashuProofs(mintProofs));
35090
35206
  } catch (err) {
35091
- return {
35092
- mint: mintUrl,
35093
- alreadySpent: [],
35094
- pending: [],
35095
- reclaimedInputs: [],
35096
- reclaimedOutputs: [],
35097
- error: err instanceof Error ? err.message : String(err)
35098
- };
35207
+ return { ...outcome, error: errorText2(err) };
35099
35208
  }
35100
35209
  const spentSecrets = new Set(grouped.spent.map((p) => p.secret));
35101
35210
  const pendingSecrets = new Set(grouped.pending.map((p) => p.secret));
@@ -35104,29 +35213,24 @@ async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, output
35104
35213
  const unspent = mintProofs.filter(
35105
35214
  (p) => !spentSecrets.has(p.secret) && !pendingSecrets.has(p.secret)
35106
35215
  );
35107
- if (alreadySpent.length > 0) {
35216
+ outcome.pending = pending4;
35217
+ try {
35108
35218
  await withWalletLock(() => {
35109
- const fresh = loadAgentWallet() ?? initial;
35110
- const spentKeys = new Set(alreadySpent.map((p) => proofIdKey(p)));
35111
- saveAgentWallet({
35112
- ...fresh,
35113
- proofs: fresh.proofs.filter((p) => !spentKeys.has(proofIdKey(p)))
35114
- });
35219
+ assertNoRelease(initial.lock_pubkey, builderHandle, mintUrl);
35220
+ const fresh = currentWallet(initial.lock_pubkey);
35221
+ if (alreadySpent.length > 0) {
35222
+ const spentKeys = new Set(alreadySpent.map(proofIdKey));
35223
+ saveAgentWallet({ ...fresh, proofs: fresh.proofs.filter((p) => p.mint !== mintUrl || !spentKeys.has(proofIdKey(p))) });
35224
+ }
35115
35225
  });
35226
+ outcome.alreadySpent = alreadySpent;
35227
+ } catch (err) {
35228
+ return { ...outcome, error: errorText2(err) };
35116
35229
  }
35117
- if (unspent.length === 0) {
35118
- return {
35119
- mint: mintUrl,
35120
- alreadySpent,
35121
- pending: pending4,
35122
- reclaimedInputs: [],
35123
- reclaimedOutputs: [],
35124
- error: null
35125
- };
35126
- }
35230
+ if (unspent.length === 0) return outcome;
35127
35231
  const totalSats = unspent.reduce((sum, p) => sum + p.amount, 0);
35128
35232
  const inputs = toCashuProofs(unspent);
35129
- let outputs;
35233
+ let preview;
35130
35234
  try {
35131
35235
  const swapFeeSats = swapFeeForProofs(cashuWallet, inputs);
35132
35236
  const reclaimSats = totalSats - swapFeeSats;
@@ -35136,38 +35240,134 @@ async function releaseAtMint(mintUrl, mintProofs, refundPrivkey, initial, output
35136
35240
  );
35137
35241
  }
35138
35242
  const builder = cashuWallet.ops.send(reclaimSats, inputs).privkey(refundPrivkey);
35139
- const result = outputMode === "locked" ? await builder.asP2PK({ pubkey: initial.lock_pubkey }).run() : await builder.asRandom().run();
35140
- outputs = result.send;
35243
+ preview = outputMode === "locked" ? await builder.asP2PK({ pubkey: initial.lock_pubkey }).keepAsP2PK({ pubkey: initial.lock_pubkey }).prepare() : await builder.asRandom().keepAsRandom().prepare();
35141
35244
  } catch (err) {
35142
- return {
35143
- mint: mintUrl,
35144
- alreadySpent,
35145
- pending: pending4,
35146
- reclaimedInputs: [],
35147
- reclaimedOutputs: [],
35148
- error: err instanceof Error ? err.message : String(err)
35149
- };
35245
+ return { ...outcome, error: errorText2(err) };
35150
35246
  }
35151
- const reclaimedOutputs = outputs.map(
35152
- (p) => toAgentProof(p, mintUrl, outputMode === "locked" ? initial.lock_pubkey : null)
35153
- );
35154
- await withWalletLock(() => {
35155
- const fresh = loadAgentWallet() ?? initial;
35156
- const inputKeys = new Set(unspent.map((p) => proofIdKey(p)));
35157
- saveAgentWallet({
35158
- ...fresh,
35159
- proofs: [...fresh.proofs.filter((p) => !inputKeys.has(proofIdKey(p))), ...reclaimedOutputs]
35247
+ const selected = new Set(preview.inputs.map(proofIdKey));
35248
+ const intent = {
35249
+ id: randomUUID5(),
35250
+ builderHandle,
35251
+ mint: mintUrl,
35252
+ walletPubkey: initial.lock_pubkey,
35253
+ lockPubkey: outputMode === "locked" ? initial.lock_pubkey : null,
35254
+ keysetId: preview.keysetId,
35255
+ inputs: unspent.filter((p) => selected.has(proofIdKey(p))),
35256
+ outputs: serializeOutputData([...preview.sendOutputs ?? [], ...preview.keepOutputs ?? []]),
35257
+ createdAt: now
35258
+ };
35259
+ try {
35260
+ await withWalletLock(() => {
35261
+ const fresh = currentWallet(initial.lock_pubkey);
35262
+ const available = new Set(fresh.proofs.filter((p) => p.mint === mintUrl && p.status === "valid").map(proofIdKey));
35263
+ if (intent.inputs.length === 0 || !intent.inputs.every((p) => available.has(proofIdKey(p)))) {
35264
+ throw new Error("Reserve proofs changed during release; retry `dvm wallet release`.");
35265
+ }
35266
+ recordReleaseIntent(intent);
35160
35267
  });
35161
- });
35268
+ } catch (err) {
35269
+ return { ...outcome, error: `Could not record the release, so nothing was swapped: ${errorText2(err)}` };
35270
+ }
35271
+ let outputs;
35272
+ try {
35273
+ const result = await cashuWallet.completeSwap(preview, refundPrivkey);
35274
+ const inputKeys = new Set(inputs.map(proofIdKey));
35275
+ outputs = [...result.send, ...result.keep.filter((p) => !inputKeys.has(proofIdKey(p)))];
35276
+ } catch (err) {
35277
+ if (err instanceof te) {
35278
+ try {
35279
+ clearReleaseIntent(intent);
35280
+ } catch {
35281
+ }
35282
+ }
35283
+ return { ...outcome, error: errorText2(err) };
35284
+ }
35285
+ return commitRelease(intent, outputs, outcome);
35286
+ }
35287
+ async function commitRelease(intent, outputs, outcome) {
35288
+ const reclaimedOutputs = outputs.map((p) => toAgentProof(p, intent.mint, intent.lockPubkey));
35289
+ let saved = false;
35290
+ let cleanupError;
35291
+ try {
35292
+ await withWalletLock(() => {
35293
+ const fresh = currentWallet(intent.walletPubkey);
35294
+ const active2 = loadReleaseIntent(intent.walletPubkey, intent.builderHandle, intent.mint);
35295
+ if (active2?.id !== intent.id) return;
35296
+ const inputKeys = new Set(intent.inputs.map(proofIdKey));
35297
+ if (fresh.proofs.some((p) => p.mint === intent.mint && inputKeys.has(proofIdKey(p)))) {
35298
+ const existing = new Set(fresh.proofs.filter((p) => p.mint === intent.mint).map(proofIdKey));
35299
+ saveAgentWallet({
35300
+ ...fresh,
35301
+ proofs: [
35302
+ ...fresh.proofs.filter((p) => p.mint !== intent.mint || !inputKeys.has(proofIdKey(p))),
35303
+ ...reclaimedOutputs.filter((p) => !existing.has(proofIdKey(p)))
35304
+ ]
35305
+ });
35306
+ saved = true;
35307
+ }
35308
+ try {
35309
+ clearReleaseIntent(intent);
35310
+ } catch (err) {
35311
+ cleanupError = err;
35312
+ }
35313
+ });
35314
+ } catch (err) {
35315
+ return { ...outcome, error: `Release result is not saved to the wallet: ${errorText2(err)}. Retry \`dvm wallet release\` to recover it.` };
35316
+ }
35162
35317
  return {
35163
- mint: mintUrl,
35164
- alreadySpent,
35165
- pending: pending4,
35166
- reclaimedInputs: unspent,
35167
- reclaimedOutputs,
35168
- error: null
35318
+ ...outcome,
35319
+ output_mode: saved && reclaimedOutputs.length > 0 ? intent.lockPubkey === null ? "unlocked" : "locked" : null,
35320
+ reclaimedInputs: saved ? intent.inputs : [],
35321
+ reclaimedOutputs: saved ? reclaimedOutputs : [],
35322
+ error: cleanupError ? `Release saved, but recovery journal cleanup failed: ${errorText2(cleanupError)}. Retry \`dvm wallet release\`.` : null
35169
35323
  };
35170
35324
  }
35325
+ async function recoverRelease(intent, cashuWallet, outcome, now) {
35326
+ const fresh = currentWallet(intent.walletPubkey);
35327
+ const inputKeys = new Set(intent.inputs.map(proofIdKey));
35328
+ if (!fresh.proofs.some((p) => p.mint === intent.mint && inputKeys.has(proofIdKey(p)))) {
35329
+ return commitRelease(intent, [], outcome);
35330
+ }
35331
+ let restored = [];
35332
+ let restoreError;
35333
+ try {
35334
+ restored = await restoreProofsFromOutputs(cashuWallet, intent.keysetId, intent.outputs);
35335
+ } catch (err) {
35336
+ restoreError = err;
35337
+ }
35338
+ if (restored.length === intent.outputs.length && restored.length > 0) {
35339
+ return commitRelease(intent, restored, outcome);
35340
+ }
35341
+ if (restored.length > 0) {
35342
+ return { ...outcome, error: "The mint restored only part of the release outputs; retry `dvm wallet release`." };
35343
+ }
35344
+ const states = await cashuWallet.groupProofsByState(toCashuProofs(intent.inputs));
35345
+ if (now - intent.createdAt < RELEASE_IN_FLIGHT_MS) {
35346
+ return { ...outcome, error: "Another release may still be in flight; retry `dvm wallet release` shortly." };
35347
+ }
35348
+ const unspent = new Set(states.unspent.map((p) => proofIdKey(p)));
35349
+ if (states.pending.length === 0 && (intent.inputs.every((p) => unspent.has(proofIdKey(p))) || restoreError === void 0)) {
35350
+ await withWalletLock(() => clearReleaseIntent(intent));
35351
+ return null;
35352
+ }
35353
+ return {
35354
+ ...outcome,
35355
+ error: `Release recovery is pending${restoreError ? `: ${errorText2(restoreError)}` : ": the mint still reports inputs pending"}. Retry \`dvm wallet release\`.`
35356
+ };
35357
+ }
35358
+ function currentWallet(pubkey) {
35359
+ const wallet = loadAgentWallet();
35360
+ if (!wallet || wallet.lock_pubkey !== pubkey) throw new Error("The agent wallet changed during release.");
35361
+ return wallet;
35362
+ }
35363
+ function assertNoRelease(walletPubkey, builderHandle, mint) {
35364
+ if (loadReleaseIntent(walletPubkey, builderHandle, mint)) {
35365
+ throw new Error("Another release is awaiting recovery; retry `dvm wallet release`.");
35366
+ }
35367
+ }
35368
+ function errorText2(err) {
35369
+ return err instanceof Error ? err.message : String(err);
35370
+ }
35171
35371
  function proofIdKey(p) {
35172
35372
  return `${p.secret}:${p.C}`;
35173
35373
  }
@@ -35487,7 +35687,8 @@ async function walletRelease(opts) {
35487
35687
  `Released ${totals.reclaimedSats} sats at ${builderHandle} (output mode: ${result.output_mode}).`
35488
35688
  );
35489
35689
  for (const mintOutcome of result.mints) {
35490
- info(` ${mintOutcome.mint}:`);
35690
+ const policy = mintOutcome.output_mode === null ? "" : ` (output mode: ${mintOutcome.output_mode})`;
35691
+ info(` ${mintOutcome.mint}${policy}:`);
35491
35692
  info(
35492
35693
  ` reclaimed: ${sumSats(mintOutcome.reclaimedOutputs)} sats from ${mintOutcome.reclaimedInputs.length} proof(s)`
35493
35694
  );
@@ -35513,6 +35714,7 @@ async function walletRelease(opts) {
35513
35714
  pending_sats: totals.pendingSats,
35514
35715
  mints: result.mints.map((m) => ({
35515
35716
  mint: m.mint,
35717
+ output_mode: m.output_mode,
35516
35718
  reclaimed_sats: sumSats(m.reclaimedOutputs),
35517
35719
  reclaimed_input_count: m.reclaimedInputs.length,
35518
35720
  already_spent_sats: sumSats(m.alreadySpent),
@@ -36709,7 +36911,7 @@ function resolveMppEndpoint(identifier) {
36709
36911
  }
36710
36912
 
36711
36913
  // src/commands/wallet-pair.ts
36712
- import { createHash as createHash6, randomBytes as randomBytes5 } from "crypto";
36914
+ import { createHash as createHash7, randomBytes as randomBytes5 } from "crypto";
36713
36915
  import { hostname as hostname2 } from "os";
36714
36916
 
36715
36917
  // node_modules/nostr-tools/lib/esm/pure.js
@@ -37607,7 +37809,7 @@ function hexToBytes2(hex2) {
37607
37809
  }
37608
37810
 
37609
37811
  // src/lib/wallet-pairing-store.ts
37610
- var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
37812
+ var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
37611
37813
  import {
37612
37814
  chmodSync as chmodSync2,
37613
37815
  existsSync as existsSync8,
@@ -37617,7 +37819,7 @@ import {
37617
37819
  unlinkSync as unlinkSync3,
37618
37820
  writeFileSync as writeFileSync6
37619
37821
  } from "fs";
37620
- import { join as join10 } from "path";
37822
+ import { join as join11 } from "path";
37621
37823
  var pairingIdPattern = /^[0-9a-f]{64}$/;
37622
37824
  var stateSchema = external_exports.object({
37623
37825
  version: external_exports.literal(1),
@@ -37691,7 +37893,7 @@ function cleanupExpiredWalletPairingStates(nowSeconds = Math.floor(Date.now() /
37691
37893
  let removed = 0;
37692
37894
  for (const name of readdirSync5(PAIRINGS_DIR)) {
37693
37895
  if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
37694
- const path = join10(PAIRINGS_DIR, name);
37896
+ const path = join11(PAIRINGS_DIR, name);
37695
37897
  try {
37696
37898
  const state = stateSchema.parse(JSON.parse(readFileSync9(path, "utf8")));
37697
37899
  if (state.manifest.expires_at <= nowSeconds) {
@@ -37708,7 +37910,7 @@ async function withWalletPairingLock(pairingId, fn) {
37708
37910
  if (!existsSync8(path)) return fn();
37709
37911
  let release;
37710
37912
  try {
37711
- release = await import_proper_lockfile3.default.lock(path, {
37913
+ release = await import_proper_lockfile4.default.lock(path, {
37712
37914
  lockfilePath: `${path}.lock`,
37713
37915
  realpath: false,
37714
37916
  stale: 12 * 60 * 1e3,
@@ -37735,7 +37937,7 @@ function pairingPath(pairingId) {
37735
37937
  "Wallet pairing id must be 64 lowercase hexadecimal characters."
37736
37938
  );
37737
37939
  }
37738
- return join10(PAIRINGS_DIR, `${pairingId}.json`);
37940
+ return join11(PAIRINGS_DIR, `${pairingId}.json`);
37739
37941
  }
37740
37942
  function ensurePairingsDirectory() {
37741
37943
  ensureConfigSubdir(PAIRINGS_DIR);
@@ -38160,7 +38362,7 @@ function walletFingerprint(uri) {
38160
38362
  return uri ? sha2562(uri) : null;
38161
38363
  }
38162
38364
  function sha2562(value) {
38163
- return createHash6("sha256").update(value).digest("hex");
38365
+ return createHash7("sha256").update(value).digest("hex");
38164
38366
  }
38165
38367
  function relayHost2(relay) {
38166
38368
  try {
@@ -13,12 +13,12 @@ import {
13
13
  recordFloatSpend,
14
14
  resolveFundMint,
15
15
  sweepPendingMints
16
- } from "./chunk-ECJO73RZ.js";
16
+ } from "./chunk-DZHEYRS2.js";
17
17
  import "./chunk-HJ2JYBTT.js";
18
18
  import {
19
19
  info,
20
20
  tryResolveBtcUsdRate
21
- } from "./chunk-5SHB3MZ7.js";
21
+ } from "./chunk-F45ETHDP.js";
22
22
  import "./chunk-UWVMG4VG.js";
23
23
  import {
24
24
  loadConfig
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dvmkit/dvm-cli",
3
- "version": "0.15.2",
3
+ "version": "0.15.3",
4
4
  "description": "Command-line client and agent skill for Digital Vending Machines: pay-per-use HTTPS services AI agents can find, pay, and call with no account or API key",
5
5
  "author": "DVM Technologies Ltd",
6
6
  "keywords": [