@dvmkit/dvm-cli 0.21.0 → 0.22.1

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,7 +5,7 @@ import {
5
5
  assertTempoWalletIdle,
6
6
  findSigningIdentityByPubkey,
7
7
  resolveSigningIdentity
8
- } from "./chunk-7UGJALAX.js";
8
+ } from "./chunk-X2CKIG2D.js";
9
9
  import {
10
10
  DEFAULT_CREDIT_POSTURE,
11
11
  DEFAULT_RESERVE_LOCKTIME_SECONDS,
@@ -153,6 +153,7 @@ import {
153
153
  proofKey,
154
154
  providerFields,
155
155
  providerJobJson,
156
+ readMandatePaymentReport,
156
157
  receiptCurrencyHint,
157
158
  receiptDisplay,
158
159
  receiptFailureDetail,
@@ -166,6 +167,7 @@ import {
166
167
  reclaimIntentIds,
167
168
  reconcileInFlightPaymentRequest,
168
169
  reconcilePaymentRequestHistory,
170
+ reconcilePendingMint,
169
171
  recordBudgetRefusal,
170
172
  recordCallerMessageHash,
171
173
  recordFloatSpend,
@@ -176,6 +178,7 @@ import {
176
178
  recordReclaimIntent,
177
179
  recordSpend,
178
180
  recordSpendOnce,
181
+ recordStatusMessageHistory,
179
182
  recordSubmissionEvidence,
180
183
  recordSubmissionVerdicts,
181
184
  recordUpfrontCreditPayment,
@@ -231,13 +234,13 @@ import {
231
234
  withJobTokenRedaction,
232
235
  withRequestResultRecovery,
233
236
  withoutPendingMint
234
- } from "./chunk-GWISSHP6.js";
237
+ } from "./chunk-2K4ARVPA.js";
235
238
  import {
236
239
  connectedTempoAccount,
237
240
  generateTempoKey,
238
241
  tempoBalanceCheckHint,
239
242
  tempoWrongAssetHint
240
- } from "./chunk-L3PHIA5L.js";
243
+ } from "./chunk-AFR5KKJX.js";
241
244
  import {
242
245
  assertSupportedX402Network,
243
246
  connectedX402Payer,
@@ -246,7 +249,7 @@ import {
246
249
  repinX402WalletNetwork,
247
250
  saveX402Wallet,
248
251
  x402NetworkLabel
249
- } from "./chunk-M4Q3DBQO.js";
252
+ } from "./chunk-ITESN5XP.js";
250
253
  import {
251
254
  CREDIT_POSTURES,
252
255
  FEEDBACK_POSTURES,
@@ -263,7 +266,7 @@ import {
263
266
  retireConfigBackup,
264
267
  rollbackConfig,
265
268
  updateConfig
266
- } from "./chunk-BU5E7IDF.js";
269
+ } from "./chunk-YSALCR5X.js";
267
270
  import {
268
271
  addOutputWarnings,
269
272
  assertValidBudget,
@@ -286,10 +289,10 @@ import {
286
289
  tryX402Payment,
287
290
  withOutputWarningContext,
288
291
  withOutputWarnings
289
- } from "./chunk-YRLRHJ6O.js";
292
+ } from "./chunk-23FGJKIX.js";
290
293
  import {
291
294
  assertX402WalletIdle
292
- } from "./chunk-QVX7KPLS.js";
295
+ } from "./chunk-AWK22TUP.js";
293
296
  import {
294
297
  A,
295
298
  AGENT_MNEMONIC_FILE,
@@ -347,6 +350,7 @@ import {
347
350
  assertX402ChannelPayer,
348
351
  attestedDvmIdentity,
349
352
  authenticatedBuilderPubkey,
353
+ ba,
350
354
  base64,
351
355
  bech32,
352
356
  bindCashuTokenToSubmissionContext,
@@ -365,6 +369,7 @@ import {
365
369
  copyBytes,
366
370
  coveringMintsForSpend,
367
371
  createFxFetcher,
372
+ createMintQuoteRetryState,
368
373
  createTempoCloseCredential,
369
374
  deleteAgentMnemonic,
370
375
  deriveAgentMasterKeypair,
@@ -530,7 +535,7 @@ import {
530
535
  x402PendingUnsettled,
531
536
  x402RequiredFromError,
532
537
  x402ReservationRelease
533
- } from "./chunk-CMIEPFKP.js";
538
+ } from "./chunk-AWWLO2WW.js";
534
539
  import "./chunk-JBU7RKQ3.js";
535
540
  import "./chunk-KDNFUDOG.js";
536
541
  import "./chunk-IUTVV6N5.js";
@@ -9946,6 +9951,20 @@ async function receivePaymentCredit(args) {
9946
9951
  return finishPaymentCredit(landing);
9947
9952
  }
9948
9953
 
9954
+ // src/lib/job-read-error.ts
9955
+ var JobGatewayReadError = class extends DvmError {
9956
+ constructor(message2, proseSources) {
9957
+ super("provider_error", message2, void 0, void 0, void 0, proseSources);
9958
+ }
9959
+ };
9960
+ function jobReadHttpError(status2, message2, proseSources) {
9961
+ if (status2 === 502 || status2 === 503 || status2 === 504) return new JobGatewayReadError(message2, proseSources);
9962
+ return new DvmError("provider_error", message2, void 0, void 0, void 0, proseSources);
9963
+ }
9964
+ function isTransientJobReadError(error) {
9965
+ return isAbortError(error) || error instanceof JobGatewayReadError || error instanceof DvmError && ["timeout", "provider_unreachable"].includes(error.code);
9966
+ }
9967
+
9949
9968
  // src/lib/mandate-wait.ts
9950
9969
  var SDK_MANDATE_RESUME_GRACE_MS = 1e4;
9951
9970
  var SDK_MAX_STALE_SWEEP_INTERVAL_MS = 6e4;
@@ -9993,7 +10012,7 @@ async function recoverMandateWinner(jobId, requestSeq, transport, provider, jobT
9993
10012
  if (!loadJob(jobId)?.mandate) return false;
9994
10013
  const history = await transport.getMessages(jobId, 0, provider, { jobToken, timeoutMs: 6e4 });
9995
10014
  appendMessages(jobId, history);
9996
- recordMandatePayments(jobId, history);
10015
+ recordMandatePayments(jobId, history, maxSeq(history, 0));
9997
10016
  return history.some((message2) => mandateCredit(message2)?.request_seq === requestSeq);
9998
10017
  }
9999
10018
  async function declineStoppedAsk(jobId, requestSeq, transport, provider, jobToken) {
@@ -10016,12 +10035,27 @@ async function declineStoppedAsk(jobId, requestSeq, transport, provider, jobToke
10016
10035
  { mandate_wait: true, ...standingStopOutput(loadJob(jobId)) }
10017
10036
  );
10018
10037
  }
10019
- async function guardMandatePayment(jobId, requestSeq, transport, provider, jobToken) {
10038
+ var MandateGuardReadError = class extends Error {
10039
+ constructor(cause) {
10040
+ super("The mandate guard could not confirm the charge within its read budget.", { cause });
10041
+ }
10042
+ };
10043
+ async function guardMandatePayment(jobId, requestSeq, transport, provider, jobToken, waitReadTimeoutMs) {
10020
10044
  const job = loadJob(jobId);
10021
10045
  if (!job?.mandate && !job?.stopRequested) return;
10022
- const history = await transport.getMessages(jobId, 0, provider, { jobToken, timeoutMs: 6e4 });
10046
+ async function read(request2) {
10047
+ const timeoutMs = waitReadTimeoutMs?.() ?? 6e4;
10048
+ if (timeoutMs <= 0) throw new MandateGuardReadError();
10049
+ try {
10050
+ return await request2({ jobToken, timeoutMs });
10051
+ } catch (error) {
10052
+ if (waitReadTimeoutMs && isTransientJobReadError(error)) throw new MandateGuardReadError(error);
10053
+ throw error;
10054
+ }
10055
+ }
10056
+ const history = await read((options) => transport.getMessages(jobId, 0, provider, options));
10023
10057
  appendMessages(jobId, history);
10024
- recordMandatePayments(jobId, history);
10058
+ recordMandatePayments(jobId, history, maxSeq(history, 0));
10025
10059
  const payment = history.find((message2) => message2.from === "requester" && message2.type === "payment" && message2.content.credit?.request_seq === requestSeq);
10026
10060
  if (payment?.type === "payment") {
10027
10061
  const id = payment.content.credit?.payment_id;
@@ -10041,7 +10075,7 @@ async function guardMandatePayment(jobId, requestSeq, transport, provider, jobTo
10041
10075
  );
10042
10076
  }
10043
10077
  const latestAsk = history.findLast((message2) => message2.from === "provider" && message2.type === "payment-request");
10044
- const status2 = await transport.status(jobId, provider, { jobToken, timeoutMs: 6e4 });
10078
+ const status2 = await read((options) => transport.status(jobId, provider, options));
10045
10079
  if (latestAsk?.seq !== requestSeq || status2.status !== "awaiting-input")
10046
10080
  throw new DvmError(
10047
10081
  "payment_request_not_pending",
@@ -10051,11 +10085,6 @@ async function guardMandatePayment(jobId, requestSeq, transport, provider, jobTo
10051
10085
  );
10052
10086
  }
10053
10087
 
10054
- // src/lib/job-read-error.ts
10055
- function isTransientJobReadError(error) {
10056
- return isAbortError(error) || error instanceof DvmError && ["timeout", "provider_unreachable"].includes(error.code);
10057
- }
10058
-
10059
10088
  // src/lib/payment-lock.ts
10060
10089
  var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
10061
10090
  import { createHash } from "crypto";
@@ -10320,7 +10349,8 @@ async function readBoundedBody(response, limit) {
10320
10349
  }
10321
10350
  body += decoder.decode(value, { stream: true });
10322
10351
  }
10323
- } catch {
10352
+ } catch (err) {
10353
+ if (isAbortError(err)) throw err;
10324
10354
  return void 0;
10325
10355
  } finally {
10326
10356
  reader.releaseLock();
@@ -12154,7 +12184,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
12154
12184
  );
12155
12185
  }
12156
12186
  if (job?.stopRequested && opts?.requestSeq !== void 0 && provider.endpoint && sameEndpoint(job.endpoint, provider.endpoint))
12157
- await guardMandatePayment(jobId, opts.requestSeq, transport, provider, opts.jobToken ?? job.jobToken);
12187
+ await guardMandatePayment(jobId, opts.requestSeq, transport, provider, opts.jobToken ?? job.jobToken, opts.mandateReadTimeoutMs);
12158
12188
  if (job && hasUnknownUpfrontRail(job))
12159
12189
  throw new DvmError(
12160
12190
  "upfront_rail_unknown",
@@ -12175,7 +12205,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
12175
12205
  if (job?.creditOnly && (!matchingEndpoint || !job.creditBinding || "unbound" in job.creditBinding || job.creditBinding.creditId !== job.creditOnly || opts?.rail !== void 0))
12176
12206
  throw new DvmError("credit_only_unavailable", "This job may spend only its original prepaid credit.");
12177
12207
  if (matchingEndpoint && opts?.requestSeq !== void 0)
12178
- await guardMandatePayment(jobId, opts.requestSeq, transport, provider, jobToken);
12208
+ await guardMandatePayment(jobId, opts.requestSeq, transport, provider, jobToken, opts.mandateReadTimeoutMs);
12179
12209
  let balanceRefused = false;
12180
12210
  const booked = matchingEndpoint ? bookedCreditPayment(jobId, opts?.requestSeq) : void 0;
12181
12211
  if (booked && (booked.request.amount_msats !== request2.amount_msats || booked.request.credit?.amount_micro !== request2.credit?.amount_micro || booked.request.credit?.currency !== request2.credit?.currency))
@@ -12347,8 +12377,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
12347
12377
  }
12348
12378
  }
12349
12379
  if ((opts?.rail === void 0 || opts.rail === "x402") && request2.x402) {
12350
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-CZV4TOJ3.js");
12351
- const { tryX402Payment: tryX402Payment2 } = await import("./client-MJZL7XTD.js");
12380
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RIHHIQRK.js");
12381
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-5SB2HSH5.js");
12352
12382
  const wallet = loadX402Wallet2();
12353
12383
  if (wallet) {
12354
12384
  let proof;
@@ -12959,6 +12989,7 @@ async function streamLoop(opts) {
12959
12989
  let cursor = opts.afterSeq;
12960
12990
  let messageAppendSession = opts.messageAppendSession;
12961
12991
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
12992
+ const paymentOptions = { jobToken, useStoredPolicy: true, mandateReadTimeoutMs: opts.mandateReadTimeoutMs };
12962
12993
  const declined = () => persistLocalState && loadJob(jobId)?.callerDeclined === true;
12963
12994
  async function recordAutoPayment(result, request2, seq) {
12964
12995
  if (result.status === "credited") {
@@ -12987,11 +13018,12 @@ async function streamLoop(opts) {
12987
13018
  let result;
12988
13019
  try {
12989
13020
  result = await handlePaymentRequest(jobId, pending4.request, policy, transport, provider, {
12990
- jobToken,
12991
- requestSeq: pending4.authorization.request_seq,
12992
- useStoredPolicy: true
13021
+ ...paymentOptions,
13022
+ requestSeq: pending4.authorization.request_seq
12993
13023
  });
12994
13024
  } catch (error) {
13025
+ if (error instanceof MandateGuardReadError)
13026
+ return { messages: [], autoPayments, refunds, cursor, nextAction: pollNextAction(jobId) };
12995
13027
  if (error instanceof DvmError && error.code === "payment_already_sent") answeredSeqs.add(pending4.authorization.request_seq);
12996
13028
  else if (error instanceof DvmError && ["payment_settling", "payment_request_not_pending"].includes(error.code))
12997
13029
  return {
@@ -13114,17 +13146,20 @@ async function streamLoop(opts) {
13114
13146
  let result;
13115
13147
  try {
13116
13148
  result = await handlePaymentRequest(jobId, req, activePolicy, transport, provider, {
13117
- jobToken,
13118
- requestSeq: lastYield2.seq,
13119
- useStoredPolicy: true
13149
+ ...paymentOptions,
13150
+ requestSeq: lastYield2.seq
13120
13151
  });
13121
13152
  if (typeof result === "object" && result.status === "credited" && result.credit.ask_open)
13122
13153
  result = await handlePaymentRequest(jobId, req, activePolicy, transport, provider, {
13123
- jobToken,
13124
- requestSeq: lastYield2.seq,
13125
- useStoredPolicy: true
13154
+ ...paymentOptions,
13155
+ requestSeq: lastYield2.seq
13126
13156
  });
13127
13157
  } catch (error) {
13158
+ if (error instanceof MandateGuardReadError) {
13159
+ paymentWaitAction = pollNextAction(jobId);
13160
+ cursor = Math.min(cursor, lastYield2.seq - 1);
13161
+ break;
13162
+ }
13128
13163
  if (error instanceof DvmError && error.code === "payment_credit_choice_required") {
13129
13164
  creditChoiceAction = paymentCreditChoice(jobId, lastYield2.seq, req, false) ?? null;
13130
13165
  cursor = Math.min(cursor, lastYield2.seq - 1);
@@ -13224,7 +13259,7 @@ async function streamLoop(opts) {
13224
13259
  };
13225
13260
  }
13226
13261
  }
13227
- if (paymentUnresolved) nextAction = paymentWaitAction ?? pollNextAction(jobId, paymentInFlightHint(
13262
+ if (paymentWaitAction || paymentUnresolved) nextAction = paymentWaitAction ?? pollNextAction(jobId, paymentInFlightHint(
13228
13263
  jobId,
13229
13264
  heldJob,
13230
13265
  lastYield?.type === "payment-request" ? lastYield.seq : void 0
@@ -13699,21 +13734,40 @@ function paramsToData(params) {
13699
13734
  function jobTokenHeader(jobToken) {
13700
13735
  return jobToken ? { "X-Job-Token": jobToken } : {};
13701
13736
  }
13702
- function messagePollUnreachable(jobId, operation = "fetch messages") {
13737
+ function jobReadUnreachable(jobId, operation = "messages") {
13738
+ if (operation === "status") {
13739
+ const needsSeparator = jobId.startsWith("-");
13740
+ const retryCommand = `dvm status ${needsSeparator ? "-- " : ""}${guidanceJobArg(jobId)}`;
13741
+ const flagPlacement = needsSeparator ? ", with any flags before `--`" : "";
13742
+ return new DvmError(
13743
+ "provider_unreachable",
13744
+ "Could not reach the provider to read job status.",
13745
+ `Retry with \`${retryCommand}\` once the provider is reachable. Keep the same endpoint and job access options${flagPlacement}.`
13746
+ );
13747
+ }
13703
13748
  return new DvmError(
13704
13749
  "provider_unreachable",
13705
- `Could not reach the provider to ${operation} for job ${jobId}.`,
13750
+ `Could not reach the provider to fetch messages for job ${jobId}.`,
13706
13751
  `The provider may be down or unreachable from this network. Continue watching this job with \`dvm messages ${shellQuoteArg(jobId)} --wait\` once it is back.`
13707
13752
  );
13708
13753
  }
13709
- async function readMessagePollBody(read, jobId, operation) {
13754
+ async function readJobResponse(read, jobId, operation) {
13710
13755
  try {
13711
13756
  return await read();
13712
13757
  } catch (err) {
13713
- if (err instanceof TypeError && !isAbortError(err)) throw messagePollUnreachable(jobId, operation);
13758
+ if (err instanceof TypeError && !isAbortError(err)) throw jobReadUnreachable(jobId, operation);
13714
13759
  throw err;
13715
13760
  }
13716
13761
  }
13762
+ var CreditOperationTimeoutError = class extends DvmError {
13763
+ constructor() {
13764
+ super("timeout", "Credit operation timed out.", "The provider may be starting up. Retry in a few seconds.");
13765
+ }
13766
+ };
13767
+ function rethrowCreditBodyError(err) {
13768
+ if (isAbortError(err)) throw new CreditOperationTimeoutError();
13769
+ throw err;
13770
+ }
13717
13771
  function captureTraceId(res) {
13718
13772
  const tp = res.headers.get("traceparent");
13719
13773
  if (tp) {
@@ -14073,13 +14127,7 @@ var HttpsTransport = class {
14073
14127
  });
14074
14128
  } catch (err) {
14075
14129
  if (err instanceof DvmError) throw err;
14076
- if (isAbortError(err)) {
14077
- throw new DvmError(
14078
- "timeout",
14079
- "Credit operation timed out.",
14080
- "The provider may be starting up. Retry in a few seconds."
14081
- );
14082
- }
14130
+ if (isAbortError(err)) throw new CreditOperationTimeoutError();
14083
14131
  throw new DvmError(
14084
14132
  "provider_unreachable",
14085
14133
  `Could not reach ${url2}: ${err instanceof Error ? err.message : String(err)}`,
@@ -14091,7 +14139,7 @@ var HttpsTransport = class {
14091
14139
  if (!res.ok) {
14092
14140
  const mppChallenges = res.status === 402 && res.headers.get("WWW-Authenticate") ? (await import("./dist-23E7OOCA.js")).Challenge.fromHeadersList(res.headers) : [];
14093
14141
  assertConfiguredTempoChallengeNetwork(mppChallenges, ["charge", "session"]);
14094
- const text = await res.text();
14142
+ const text = await res.text().catch(rethrowCreditBodyError);
14095
14143
  const parsed = parseJsonObject(text);
14096
14144
  const structured = parseStructuredError(text);
14097
14145
  if (structured) {
@@ -14126,7 +14174,7 @@ var HttpsTransport = class {
14126
14174
  `Credit operation failed (${res.status}): ${text}`
14127
14175
  );
14128
14176
  }
14129
- const result = await res.json();
14177
+ const result = await res.json().catch(rethrowCreditBodyError);
14130
14178
  const { menu: rawMenu, funding_receipt: rawFundingReceipt, ...creditResult } = result;
14131
14179
  const menu = parseCreditMenu(rawMenu);
14132
14180
  const x402PaymentResponse = res.headers.get("PAYMENT-RESPONSE") ?? res.headers.get("X-PAYMENT-RESPONSE") ?? void 0;
@@ -14149,7 +14197,7 @@ var HttpsTransport = class {
14149
14197
  const url2 = `${endpoint}/v1/job/${jobId}`;
14150
14198
  const signal = options?.timeoutMs && options.timeoutMs > 0 ? AbortSignal.timeout(options.timeoutMs) : void 0;
14151
14199
  try {
14152
- const res = await readMessagePollBody(() => dvmFetch(url2, { headers: jobTokenHeader(options?.jobToken), signal }), jobId, "read status");
14200
+ const res = await readJobResponse(() => dvmFetch(url2, { headers: jobTokenHeader(options?.jobToken), signal }), jobId, "status");
14153
14201
  captureTraceId(res);
14154
14202
  if (res.status === 404) {
14155
14203
  const storedEndpoint = loadJob(jobId)?.endpoint;
@@ -14159,11 +14207,11 @@ var HttpsTransport = class {
14159
14207
  ));
14160
14208
  }
14161
14209
  if (!res.ok) {
14162
- const credentialErr = jobCredentialError(res.status, await readMessagePollBody(() => res.text(), jobId, "read status"));
14210
+ const credentialErr = jobCredentialError(res.status, await readJobResponse(() => res.text(), jobId, "status"));
14163
14211
  if (credentialErr) throw credentialErr;
14164
- throw new DvmError("provider_error", `Status check failed (${res.status})`);
14212
+ throw jobReadHttpError(res.status, `Status check failed (${res.status})`);
14165
14213
  }
14166
- const data = await readMessagePollBody(() => res.json(), jobId, "read status");
14214
+ const data = await readJobResponse(() => res.json(), jobId, "status");
14167
14215
  return {
14168
14216
  jobId,
14169
14217
  status: data.status,
@@ -14202,29 +14250,60 @@ var HttpsTransport = class {
14202
14250
  );
14203
14251
  }
14204
14252
  const url2 = `${endpoint}/v1/job/${jobId}/messages?after=${after}`;
14205
- const signal = options?.timeoutMs && options.timeoutMs > 0 ? AbortSignal.timeout(options.timeoutMs) : void 0;
14206
- try {
14207
- let res;
14253
+ const timeoutMs = options?.timeoutMs ?? 0;
14254
+ const download = options?.idleTimeout && timeoutMs > 0 ? new AbortController() : void 0;
14255
+ const idleTimer = download && setTimeout(() => {
14256
+ download.abort(new DOMException("Message poll timed out.", "TimeoutError"));
14257
+ }, timeoutMs);
14258
+ const signal = download?.signal ?? (timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : void 0);
14259
+ const fetchMessages = async (stream = false) => {
14208
14260
  try {
14209
- res = await dvmFetch(url2, {
14210
- headers: jobTokenHeader(options?.jobToken),
14261
+ return await dvmFetch(url2, {
14262
+ headers: {
14263
+ ...jobTokenHeader(options?.jobToken),
14264
+ ...stream && { Accept: "text/event-stream" }
14265
+ },
14211
14266
  signal
14212
14267
  });
14213
14268
  } catch (err) {
14214
14269
  if (err instanceof DvmError || isAbortError(err)) throw err;
14215
- throw messagePollUnreachable(jobId);
14270
+ throw jobReadUnreachable(jobId);
14271
+ }
14272
+ };
14273
+ try {
14274
+ const beforeSeq = options?.beforeSeq;
14275
+ let res = await fetchMessages(beforeSeq !== void 0);
14276
+ if (beforeSeq !== void 0 && res.status === 406) {
14277
+ res.body?.cancel().catch(() => void 0);
14278
+ res = await fetchMessages();
14279
+ }
14280
+ if (beforeSeq !== void 0 && res.ok && res.headers.get("content-type")?.includes("text/event-stream")) {
14281
+ const result = await parseSSEStream(res, void 0, callerMessageRecognizer(jobId, endpoint), beforeSeq);
14282
+ if (result.reason !== "error") return result.messages;
14283
+ if (signal?.aborted) throw signal.reason;
14284
+ res = await fetchMessages();
14216
14285
  }
14217
14286
  if (!res.ok) {
14218
- const text = await readMessagePollBody(() => res.text(), jobId);
14287
+ const text = await readJobResponse(() => res.text(), jobId);
14219
14288
  const credentialErr = jobCredentialError(res.status, text);
14220
14289
  if (credentialErr) throw credentialErr;
14221
- throw providerResponseError("provider_error", `getMessages failed (${res.status}): ${text}`);
14290
+ throw jobReadHttpError(res.status, `getMessages failed (${res.status}): ${text}`, { message: "provider" });
14291
+ }
14292
+ let body = res;
14293
+ if (idleTimer && res.body) {
14294
+ idleTimer.refresh();
14295
+ body = new Response(res.body.pipeThrough(new TransformStream({
14296
+ transform(chunk, controller) {
14297
+ if (chunk.byteLength > 0) idleTimer.refresh();
14298
+ controller.enqueue(chunk);
14299
+ }
14300
+ })));
14222
14301
  }
14223
- const data = await readMessagePollBody(() => res.json(), jobId);
14224
- return data.messages.map(callerMessageRecognizer(jobId, endpoint));
14302
+ const data = await readJobResponse(() => body.json(), jobId);
14303
+ const messages2 = beforeSeq === void 0 ? data.messages : data.messages.filter((message2) => message2.seq < beforeSeq);
14304
+ return messages2.map(callerMessageRecognizer(jobId, endpoint));
14225
14305
  } catch (err) {
14226
- if (err instanceof DvmError) throw err;
14227
- if (isAbortError(err)) {
14306
+ if (download?.signal.aborted || isAbortError(err)) {
14228
14307
  throw new DvmError(
14229
14308
  "timeout",
14230
14309
  "Message poll timed out.",
@@ -14232,6 +14311,8 @@ var HttpsTransport = class {
14232
14311
  );
14233
14312
  }
14234
14313
  throw err;
14314
+ } finally {
14315
+ clearTimeout(idleTimer);
14235
14316
  }
14236
14317
  }
14237
14318
  async sendMessage(jobId, message2, provider, options) {
@@ -14328,20 +14409,20 @@ var HttpsTransport = class {
14328
14409
  throw new DvmError("not_supported", "HTTPS stream requires a provider with an endpoint.");
14329
14410
  }
14330
14411
  const url2 = `${endpoint}/v1/job/${jobId}/messages?after=${afterSeq}`;
14331
- const res = await readMessagePollBody(() => dvmFetch(url2, {
14412
+ const res = await readJobResponse(() => dvmFetch(url2, {
14332
14413
  headers: { Accept: "text/event-stream", ...jobTokenHeader(options?.jobToken) },
14333
14414
  signal: options?.signal
14334
14415
  }), jobId);
14335
14416
  if (!res.ok) {
14336
- const text = await readMessagePollBody(() => res.text(), jobId);
14417
+ const text = await readJobResponse(() => res.text(), jobId);
14337
14418
  const credentialErr = jobCredentialError(res.status, text);
14338
14419
  if (credentialErr) throw credentialErr;
14339
- throw providerResponseError("provider_error", `stream failed (${res.status}): ${text}`);
14420
+ throw jobReadHttpError(res.status, `stream failed (${res.status}): ${text}`, { message: "provider" });
14340
14421
  }
14341
14422
  const contentType = res.headers.get("content-type") ?? "";
14342
14423
  const recognize = callerMessageRecognizer(jobId, endpoint);
14343
14424
  if (contentType.includes("application/json")) {
14344
- const body = await readMessagePollBody(() => res.json(), jobId);
14425
+ const body = await readJobResponse(() => res.json(), jobId);
14345
14426
  const messages2 = (body.messages ?? []).map(recognize);
14346
14427
  const last = messages2.at(-1);
14347
14428
  const reason = last?.type === "complete" ? "complete" : last?.type === "cancel" ? "cancel" : "yield";
@@ -14545,7 +14626,7 @@ function x402RequiredUsdcMicro(required) {
14545
14626
  return required.accepts.at(0)?.maxAmountRequired;
14546
14627
  }
14547
14628
  var YIELD_TYPES = /* @__PURE__ */ new Set(["prompt", "payment-request", "working", "complete", "cancel"]);
14548
- async function parseSSEStream(res, options, recognize = (message2) => message2) {
14629
+ async function parseSSEStream(res, options, recognize = (message2) => message2, beforeSeq) {
14549
14630
  const messages2 = [];
14550
14631
  if (!res.body) {
14551
14632
  return { messages: messages2, reason: "error" };
@@ -14553,7 +14634,7 @@ async function parseSSEStream(res, options, recognize = (message2) => message2)
14553
14634
  const reader = res.body.getReader();
14554
14635
  const decoder = new TextDecoder();
14555
14636
  let buffer = "";
14556
- let lastReason = "yield";
14637
+ let lastReason = beforeSeq === void 0 ? "yield" : "error";
14557
14638
  try {
14558
14639
  for (; ; ) {
14559
14640
  const { done, value } = await reader.read();
@@ -14569,9 +14650,13 @@ async function parseSSEStream(res, options, recognize = (message2) => message2)
14569
14650
  const json3 = dataLine.slice("data:".length).trim();
14570
14651
  try {
14571
14652
  const msg = recognize(JSON.parse(json3));
14653
+ if (beforeSeq !== void 0 && msg.seq >= beforeSeq) {
14654
+ reader.cancel().catch(() => void 0);
14655
+ return { messages: messages2, reason: "yield" };
14656
+ }
14572
14657
  messages2.push(msg);
14573
14658
  options?.onMessage?.(msg);
14574
- if (YIELD_TYPES.has(msg.type)) {
14659
+ if (beforeSeq === void 0 && YIELD_TYPES.has(msg.type)) {
14575
14660
  if (msg.type === "complete") lastReason = "complete";
14576
14661
  else if (msg.type === "cancel") lastReason = "cancel";
14577
14662
  else lastReason = "yield";
@@ -15140,7 +15225,7 @@ async function readTerminalCompletion(args) {
15140
15225
  delete completion.artifactCount;
15141
15226
  delete completion.payloadIn;
15142
15227
  try {
15143
- const messages2 = await transport.getMessages(jobId, 0, ref, {
15228
+ const messages2 = args.readMessages ? await args.readMessages() : await transport.getMessages(jobId, 0, ref, {
15144
15229
  jobToken,
15145
15230
  timeoutMs: args.timeoutMs ?? 5e3
15146
15231
  });
@@ -15429,7 +15514,7 @@ async function settleCreditAfterJob(args) {
15429
15514
  }
15430
15515
  }
15431
15516
  if (args.allowTopup !== false) {
15432
- const refill = args.refillPocket ?? (await import("./pocket-refill-OX3WXUZ4.js")).refillPocketIfLow;
15517
+ const refill = args.refillPocket ?? (await import("./pocket-refill-MS6SL7FZ.js")).refillPocketIfLow;
15433
15518
  await refill({ human: args.human }).catch(() => void 0);
15434
15519
  }
15435
15520
  }
@@ -16057,10 +16142,7 @@ async function configReset(opts) {
16057
16142
  // and to `CONNECTED_RAILS`, a blanket grant turns the refusal that would
16058
16143
  // have caught it into a silent credential removal. Without one this fails
16059
16144
  // closed with `config_protected_field`.
16060
- //
16061
- // The pin was taken a moment ago and is the survivor of this command, so
16062
- // only the rolling copy is swept.
16063
- sweepSlots: ["backup"],
16145
+ preservePin: true,
16064
16146
  patch: (current) => {
16065
16147
  if (current) assertNoConnectedRails(current);
16066
16148
  cleared = planConfigReset(current ?? {}).clear;
@@ -16223,14 +16305,14 @@ async function confirmRollback(stored, preview, opts) {
16223
16305
  async function withStrandingChecked(removing, commit) {
16224
16306
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
16225
16307
  if (leaving.has("tempo")) {
16226
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-BOW6OFSI.js");
16308
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-7EYW5W5Z.js");
16227
16309
  await assertTempoWalletIdle2("disconnect");
16228
16310
  }
16229
16311
  if (!leaving.has("x402")) return commit();
16230
- const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-TUEXUURQ.js");
16231
- const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-7PSR5CYB.js");
16232
- const { ensureAddress: ensureAddress2 } = await import("./internal-TUEXUURQ.js");
16233
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-CZV4TOJ3.js");
16312
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-EVD5WVAK.js");
16313
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-GR7WGYVQ.js");
16314
+ const { ensureAddress: ensureAddress2 } = await import("./internal-EVD5WVAK.js");
16315
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RIHHIQRK.js");
16234
16316
  return withX402ChannelLock2(async () => {
16235
16317
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
16236
16318
  if (unsettled.length > 0) {
@@ -19873,6 +19955,30 @@ async function runCreditDrain(dvm, opts) {
19873
19955
  });
19874
19956
  }
19875
19957
  const signCredit = (body) => signDvmRequestData(signer.privkey, body, authDomain);
19958
+ const postDrain = async (body, payment) => {
19959
+ try {
19960
+ return await creditOp(transport, endpoint, body, payment);
19961
+ } catch (err) {
19962
+ if (!(err instanceof CreditOperationTimeoutError)) throw err;
19963
+ const address = !channelBacked && drain.payout.address;
19964
+ const command = [
19965
+ creditDrainCommand(endpoint, creditId),
19966
+ "--drain-id",
19967
+ shellQuoteArg(drain.drainId),
19968
+ "--method",
19969
+ shellQuoteArg(drain.method),
19970
+ ...address ? ["--address", shellQuoteArg(address)] : [],
19971
+ ..."name" in signer.source ? ["--as", shellQuoteArg(signer.source.name)] : []
19972
+ ].join(" ");
19973
+ const identityHint = signer.source.kind === "env" ? " Keep the same DVM_IDENTITY_KEY." : "";
19974
+ throw new DvmError(
19975
+ "drain_outcome_unknown",
19976
+ `The response for drain ${drain.drainId} timed out. The refund outcome is unknown.`,
19977
+ `Retry with the same drain ID using \`${command}\`.${identityHint}`,
19978
+ { status: "unknown", retryable: true, credit_id: creditId, drain_id: drain.drainId, next_command: command }
19979
+ );
19980
+ }
19981
+ };
19876
19982
  let result;
19877
19983
  let anchorRead = { reachable: false };
19878
19984
  let x402AtRisk;
@@ -19911,7 +20017,7 @@ async function runCreditDrain(dvm, opts) {
19911
20017
  mppAtRiskMicro = authorized < deposit ? authorized : deposit;
19912
20018
  if (!drain.mppCredential) {
19913
20019
  try {
19914
- return await creditOp(transport, endpoint, body);
20020
+ return await postDrain(body);
19915
20021
  } catch (err) {
19916
20022
  const challenge = tempoSessionChallenge(err);
19917
20023
  if (!challenge) throw err;
@@ -19923,11 +20029,11 @@ async function runCreditDrain(dvm, opts) {
19923
20029
  });
19924
20030
  drain = { ...drain, mppCredential: credential };
19925
20031
  recordPendingDrain(endpoint, signer.pubkey, drain, ...identityArg);
19926
- return creditOp(transport, endpoint, body, { mppCredentialRaw: credential });
20032
+ return postDrain(body, { mppCredentialRaw: credential });
19927
20033
  }
19928
20034
  }
19929
20035
  try {
19930
- return await creditOp(transport, endpoint, body, {
20036
+ return await postDrain(body, {
19931
20037
  mppCredentialRaw: drain.mppCredential
19932
20038
  });
19933
20039
  } catch (err) {
@@ -19944,7 +20050,7 @@ async function runCreditDrain(dvm, opts) {
19944
20050
  drain = { ...drain, mppCredential: credential };
19945
20051
  recordPendingDrain(endpoint, signer.pubkey, drain, ...identityArg);
19946
20052
  const refreshedBody = signCredit(unsignedBody());
19947
- return creditOp(transport, endpoint, refreshedBody, {
20053
+ return postDrain(refreshedBody, {
19948
20054
  mppCredentialRaw: credential
19949
20055
  });
19950
20056
  }
@@ -19965,9 +20071,7 @@ async function runCreditDrain(dvm, opts) {
19965
20071
  callerPubkey: signer.pubkey,
19966
20072
  creditId,
19967
20073
  depositMicro: Math.max(stored?.targetMicro ?? 0, 1),
19968
- post: (paymentHeader) => creditOp(
19969
- transport,
19970
- endpoint,
20074
+ post: (paymentHeader) => postDrain(
19971
20075
  signCredit(unsignedBody()),
19972
20076
  paymentHeader ? { x402Payment: paymentHeader, x402Version: 2 } : void 0
19973
20077
  )
@@ -19979,7 +20083,7 @@ async function runCreditDrain(dvm, opts) {
19979
20083
  result = await closeChannel();
19980
20084
  } else {
19981
20085
  try {
19982
- result = await creditOp(transport, endpoint, signCredit(unsignedBody()));
20086
+ result = await postDrain(signCredit(unsignedBody()));
19983
20087
  } catch (err) {
19984
20088
  if (!(err instanceof DvmError) || !x402RequiredFromError(err)) throw err;
19985
20089
  drain = { ...drain, payout: {} };
@@ -19990,7 +20094,7 @@ async function runCreditDrain(dvm, opts) {
19990
20094
  } else if (drain.method === "stripe") {
19991
20095
  const card = await postCardDrain({
19992
20096
  drainId: () => drain.drainId,
19993
- post: () => creditOp(transport, endpoint, signCredit(unsignedBody())),
20097
+ post: () => postDrain(signCredit(unsignedBody())),
19994
20098
  adopt: (blocking) => {
19995
20099
  clearPendingDrain(endpoint, signer.pubkey, drain, ...identityArg);
19996
20100
  drain = { ...drain, drainId: blocking, creditId };
@@ -20000,7 +20104,7 @@ async function runCreditDrain(dvm, opts) {
20000
20104
  result = card.result;
20001
20105
  cardAdoptedFrom = card.adoptedFrom;
20002
20106
  } else {
20003
- result = await creditOp(transport, endpoint, signCredit(unsignedBody()));
20107
+ result = await postDrain(signCredit(unsignedBody()));
20004
20108
  }
20005
20109
  if (result.drain?.receipts.length) {
20006
20110
  anchorRead = await fetchTrustAnchor(transport, { endpoint });
@@ -23009,8 +23113,8 @@ async function probeX402(x402, timeoutMs) {
23009
23113
  let network;
23010
23114
  let address;
23011
23115
  try {
23012
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-CZV4TOJ3.js");
23013
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-TUEXUURQ.js");
23116
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RIHHIQRK.js");
23117
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-EVD5WVAK.js");
23014
23118
  const wallet = loadX402Wallet2();
23015
23119
  if (!wallet) {
23016
23120
  const storedKey = x402.privateKey;
@@ -23062,8 +23166,8 @@ async function probeMpp(mpp, timeoutMs) {
23062
23166
  if (!mpp) return null;
23063
23167
  if (mpp.method === "tempo") {
23064
23168
  try {
23065
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-D424H37T.js");
23066
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-TUEXUURQ.js");
23169
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-QOC3BHVE.js");
23170
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-EVD5WVAK.js");
23067
23171
  const account = await connectedTempoAccount2();
23068
23172
  if (!account) {
23069
23173
  return {
@@ -26537,7 +26641,7 @@ function paymentAmount(msg) {
26537
26641
  }
26538
26642
  return formatAmountBestEffort(msg.content.amount_msats);
26539
26643
  }
26540
- function formatMessageHuman(msg, jobId, artifactSession) {
26644
+ function formatMessageHuman(msg, jobId, artifactSession, mandateReport) {
26541
26645
  const { seq, type } = msg;
26542
26646
  const prefix = msg.from === "provider" ? "Provider" : "You";
26543
26647
  if (msg.type !== "progress") finalizeProgressLine();
@@ -26579,15 +26683,10 @@ function formatMessageHuman(msg, jobId, artifactSession) {
26579
26683
  );
26580
26684
  break;
26581
26685
  case "payment": {
26582
- if (mandateCredit(msg)) {
26583
- const report = mandatePaymentReports(
26584
- jobId ? loadJob(jobId) : void 0,
26585
- [...jobId ? loadMessages(jobId) : [], msg]
26586
- ).find((entry) => entry.seq === msg.seq);
26587
- if (report) {
26588
- info(`[${msg.seq}] ${report.display}`);
26589
- break;
26590
- }
26686
+ const report = mandateReport ?? readMandatePaymentReport(msg, jobId);
26687
+ if (report) {
26688
+ info(`[${msg.seq}] ${report.display}`);
26689
+ break;
26591
26690
  }
26592
26691
  const amount = paymentAmount(msg);
26593
26692
  if (msg.from === "provider") {
@@ -26696,19 +26795,21 @@ function createWaitPaymentLines(opts) {
26696
26795
  if (booking.jobId === opts.jobId && booking.approval === "auto") write(bookedPayment(booking), booking.requestSeq);
26697
26796
  }) : () => void 0;
26698
26797
  return {
26699
- onMessage(message2) {
26700
- opts.onMessage?.(message2);
26701
- emitted.add(message2.seq);
26798
+ onMessage(message2, fullHistoryThrough) {
26702
26799
  observed.push(message2);
26703
- if (opts.persistLocalState !== false && mandateCredit(message2)) {
26704
- const history = [...loadMessages(opts.jobId), ...observed];
26705
- const payment = mandatePaymentReports(loadJob(opts.jobId), history).find((entry) => entry.seq === message2.seq);
26706
- if (payment) write({
26707
- ...payment,
26708
- rail: "credit",
26709
- reason: { _source: "provider", text: "" }
26710
- }, payment.request_seq, true);
26711
- }
26800
+ const useLocalState = opts.persistLocalState !== false;
26801
+ const payment = mandateCredit(message2) ? mandatePaymentReports(
26802
+ useLocalState ? loadJob(opts.jobId) : void 0,
26803
+ useLocalState ? [...observed, ...loadMessages(opts.jobId)] : observed,
26804
+ fullHistoryThrough
26805
+ ).find((entry) => entry.seq === message2.seq) : void 0;
26806
+ opts.onMessage?.(message2, payment);
26807
+ emitted.add(message2.seq);
26808
+ if (useLocalState && payment) write({
26809
+ ...payment,
26810
+ rail: "credit",
26811
+ reason: { _source: "provider", text: "" }
26812
+ }, payment.request_seq, true);
26712
26813
  const pending4 = waiting.get(message2.seq);
26713
26814
  if (pending4) write(pending4, message2.seq);
26714
26815
  },
@@ -26742,12 +26843,12 @@ async function waitForJob(opts, durationMs, now = Date.now) {
26742
26843
  if (!opts.onAutoPayment) return waitAttached(opts, durationMs, now);
26743
26844
  const payments = createWaitPaymentLines(opts);
26744
26845
  try {
26745
- return await waitAttached({ ...opts, onMessage: payments.onMessage, onAutoPayment: payments.onAutoPayment }, durationMs, now);
26846
+ return await waitAttached({ ...opts, onAutoPayment: payments.onAutoPayment }, durationMs, now, payments);
26746
26847
  } finally {
26747
26848
  payments.finish();
26748
26849
  }
26749
26850
  }
26750
- async function waitAttached(opts, durationMs, now) {
26851
+ async function waitAttached(opts, durationMs, now, payments) {
26751
26852
  const deadline = now() + durationMs;
26752
26853
  const result = {
26753
26854
  messages: [],
@@ -26767,7 +26868,8 @@ async function waitAttached(opts, durationMs, now) {
26767
26868
  const onMessage = (message2) => {
26768
26869
  if (emittedSeqs.has(message2.seq)) return;
26769
26870
  emittedSeqs.add(message2.seq);
26770
- opts.onMessage?.(message2);
26871
+ if (payments) payments.onMessage(message2, result.fullHistoryThrough);
26872
+ else opts.onMessage?.(message2);
26771
26873
  };
26772
26874
  const messageAppendSession = opts.persistLocalState === false ? void 0 : opts.messageAppendSession ?? createMessageAppendSession(opts.jobId);
26773
26875
  let backoffMs = 1e3;
@@ -26797,13 +26899,15 @@ async function waitAttached(opts, durationMs, now) {
26797
26899
  result.nextAction = null;
26798
26900
  const history = await readWithRetry(() => opts.transport.getMessages(opts.jobId, result.cursor, opts.provider, readOptions()));
26799
26901
  if (!history) break;
26800
- const tail = history.filter((message2) => message2.seq > result.cursor);
26902
+ if (result.cursor === 0 && snapshot.content_available !== false)
26903
+ result.fullHistoryThrough = maxSeq(history, 0);
26904
+ const tail = history.filter((message2) => message2.seq > result.cursor).sort((a, b) => a.seq - b.seq);
26801
26905
  collectMessages(tail);
26802
26906
  result.cursor = maxSeq(tail, result.cursor);
26803
26907
  for (const message2 of tail) onMessage(message2);
26804
26908
  if (opts.persistLocalState !== false) {
26805
26909
  messageAppendSession?.append(tail);
26806
- await settleRecordedPayments(opts.jobId);
26910
+ await settleRecordedPayments(opts.jobId, result.fullHistoryThrough);
26807
26911
  result.refunds.push(...await claimInboundPayments(opts.jobId, tail));
26808
26912
  }
26809
26913
  result.nextAction = withRefundNextAction(opts.jobId, null, result.refunds);
@@ -26842,7 +26946,9 @@ async function waitAttached(opts, durationMs, now) {
26842
26946
  }
26843
26947
  if (!history) break;
26844
26948
  messageAppendSession?.append(history);
26845
- if (opts.persistLocalState !== false) await settleRecordedPayments(opts.jobId);
26949
+ if (messageAppendSession && snapshot.content_available !== false)
26950
+ result.fullHistoryThrough = maxSeq(history, 0);
26951
+ if (opts.persistLocalState !== false) await settleRecordedPayments(opts.jobId, result.fullHistoryThrough);
26846
26952
  const answered = opts.persistLocalState === false ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(opts.jobId);
26847
26953
  for (const seq of answeredYieldSeqs(history)) answered.add(seq);
26848
26954
  const pending4 = history.findLast((msg) => msg.from === "provider" && ["prompt", "payment-request", "working", "complete", "cancel"].includes(msg.type) && !answered.has(msg.seq));
@@ -26876,7 +26982,8 @@ async function waitAttached(opts, durationMs, now) {
26876
26982
  messageAppendSession,
26877
26983
  afterSeq: streamAfter,
26878
26984
  retryUnreachableReads: true,
26879
- timeoutMs: readOptions().timeoutMs
26985
+ timeoutMs: readOptions().timeoutMs,
26986
+ mandateReadTimeoutMs: () => Math.min(idleTimeoutMs, deadline - now())
26880
26987
  });
26881
26988
  collectMessages(next.messages);
26882
26989
  result.autoPayments.push(...next.autoPayments);
@@ -26931,6 +27038,24 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
26931
27038
  const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
26932
27039
  const { stored, ref, jobToken } = access;
26933
27040
  const json3 = (data) => providerJobJson(data, !!stored);
27041
+ function mandateOutput(batch, fullHistoryThrough) {
27042
+ const bySeq = /* @__PURE__ */ new Map();
27043
+ if ((opts.human || access.endpointOverridden) && !batch.some(mandateCredit)) return { summary: {}, bySeq };
27044
+ const summary = mandatePaymentSummary(
27045
+ access.endpointOverridden ? void 0 : loadJob(jobId),
27046
+ access.endpointOverridden ? batch : [...batch, ...loadMessages(jobId)],
27047
+ fullHistoryThrough
27048
+ );
27049
+ for (const report of summary.mandate_payments ?? []) bySeq.set(report.seq, report);
27050
+ if (access.endpointOverridden && !opts.wait) return { summary: {}, bySeq };
27051
+ if (access.endpointOverridden && summary.mandate_payments) {
27052
+ summary.mandate_payments = summary.mandate_payments.map((report) => providerFields({
27053
+ ...report,
27054
+ amount: providerFields(report.amount, ["amount_micro", "currency"])
27055
+ }, ["seq", "request_seq", "amount_msats"]));
27056
+ }
27057
+ return { summary, bySeq };
27058
+ }
26934
27059
  function actionFromMessages(batch) {
26935
27060
  return readNextAction(jobId, batch, { ignoreLocalState: access.endpointOverridden, context: stored ?? void 0 });
26936
27061
  }
@@ -26945,7 +27070,7 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
26945
27070
  if (isTerminalJobStatus(snapshot.status)) return null;
26946
27071
  if (action && (action.type !== "poll" || messages2.some((message2) => ["prompt", "payment-request", "working"].includes(message2.type)))) return action;
26947
27072
  if (snapshot.status === "awaiting-input") {
26948
- const history = await transport.getMessages(jobId, 0, ref, readOptions);
27073
+ const history = await transport.getMessages(jobId, 0, ref, { ...readOptions, ...opts.stream === false && { idleTimeout: true } });
26949
27074
  return actionFromMessages(history) ?? pollNextAction(jobId);
26950
27075
  }
26951
27076
  return action ?? pollNextAction(jobId);
@@ -26961,7 +27086,7 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
26961
27086
  progressNotice("Fetching messages...", opts.human);
26962
27087
  let msgs;
26963
27088
  try {
26964
- msgs = await transport.getMessages(jobId, after, ref, { timeoutMs: timeout, jobToken });
27089
+ msgs = await transport.getMessages(jobId, after, ref, { timeoutMs: timeout, jobToken, idleTimeout: true });
26965
27090
  } catch (err) {
26966
27091
  if (err instanceof DvmError && err.code === "provider_unreachable" && isTerminal && !access.endpointOverridden && loadMessages(jobId).some((message2) => message2.type === "complete" || message2.type === "cancel")) {
26967
27092
  throw new DvmError(
@@ -26972,13 +27097,12 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
26972
27097
  }
26973
27098
  throw err;
26974
27099
  }
26975
- if (!access.endpointOverridden) {
26976
- appendMessages(jobId, msgs);
26977
- await settleRecordedPayments(jobId);
26978
- }
27100
+ if (!access.endpointOverridden) appendMessages(jobId, msgs);
26979
27101
  const newCursor = maxSeq(msgs, after);
26980
27102
  const providerStatus2 = await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken });
27103
+ const fullHistoryThrough = after === 0 && providerStatus2?.content_available !== false ? newCursor : void 0;
26981
27104
  if (!access.endpointOverridden) {
27105
+ await settleRecordedPayments(jobId, fullHistoryThrough);
26982
27106
  persistStreamOutcome({ jobId, messages: msgs, cursor: newCursor, afterSeq: after, providerStatus: providerStatus2 });
26983
27107
  }
26984
27108
  const refunds = access.endpointOverridden ? [] : await claimInboundPayments(jobId, msgs);
@@ -26994,6 +27118,7 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
26994
27118
  timeoutMs: timeout
26995
27119
  });
26996
27120
  transport.close();
27121
+ const mandate2 = mandateOutput(msgs, fullHistoryThrough);
26997
27122
  if (opts.human) {
26998
27123
  renderSettlementHuman(settlement2);
26999
27124
  if (unanswered2) info(unanswered2.display);
@@ -27002,7 +27127,7 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27002
27127
  info("No new messages.");
27003
27128
  } else {
27004
27129
  for (const msg of msgs) {
27005
- formatMessageHuman(msg, jobId, artifactSession);
27130
+ formatMessageHuman(msg, jobId, artifactSession, mandate2.bySeq.get(msg.seq));
27006
27131
  }
27007
27132
  finalizeProgressLine();
27008
27133
  }
@@ -27012,9 +27137,9 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27012
27137
  jobId,
27013
27138
  ...content2,
27014
27139
  ...settlement2,
27015
- ...!access.endpointOverridden ? mandatePaymentSummary(loadJob(jobId), loadMessages(jobId)) : {},
27140
+ ...mandate2.summary,
27016
27141
  ...unanswered2 ? { unanswered_payment_request: unanswered2 } : {},
27017
- messages: msgs.map((msg) => serialize(msg, access.endpointOverridden ? void 0 : jobId)),
27142
+ messages: msgs.map((msg) => serialize(msg, mandate2.bySeq.get(msg.seq))),
27018
27143
  cursor: newCursor,
27019
27144
  next_action: resolvedAction2,
27020
27145
  ...await refundJsonField(refunds)
@@ -27046,9 +27171,9 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27046
27171
  }
27047
27172
  },
27048
27173
  ...streamEvents && {
27049
- onMessage: (msg) => {
27174
+ onMessage: (msg, mandateReport) => {
27050
27175
  if (msg.seq <= skipThrough && !((msg.type === "payment-request" || msg.type === "prompt") && !loadAnsweredYieldSeqs(jobId).has(msg.seq))) return;
27051
- jsonEvent({ event: "message", ...serialize(msg, access.endpointOverridden ? void 0 : jobId) });
27176
+ jsonEvent({ event: "message", ...serialize(msg, mandateReport) });
27052
27177
  messageLines++;
27053
27178
  lastDelivered = Math.max(lastDelivered, msg.seq);
27054
27179
  },
@@ -27077,6 +27202,25 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27077
27202
  timeoutMs: waitDeadline === void 0 ? opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now())),
27078
27203
  jobToken
27079
27204
  });
27205
+ const observed = providerStatus ?? result.providerStatus;
27206
+ let mandate = mandateOutput(result.messages, result.fullHistoryThrough);
27207
+ if (waitDeadline !== void 0 && after === 0 && streamTerminalStatus(result.messages) && observed?.content_available !== false && result.messages.some((message2) => mandate.bySeq.get(message2.seq)?.request_seq_unverified)) {
27208
+ const remainingMs = waitDeadline - Date.now();
27209
+ if (remainingMs > 0) {
27210
+ const history = await transport.getMessages(jobId, 0, ref, {
27211
+ timeoutMs: Math.min(streamOptions.timeoutMs, remainingMs),
27212
+ jobToken
27213
+ }).catch(() => void 0);
27214
+ if (history) {
27215
+ const fullHistoryThrough = Math.max(result.fullHistoryThrough ?? 0, maxSeq(history, 0));
27216
+ if (!access.endpointOverridden) {
27217
+ appendMessages(jobId, history);
27218
+ await settleRecordedPayments(jobId, fullHistoryThrough);
27219
+ }
27220
+ mandate = mandateOutput([...history, ...result.messages], fullHistoryThrough);
27221
+ }
27222
+ }
27223
+ }
27080
27224
  if (!access.endpointOverridden) {
27081
27225
  persistStreamOutcome({
27082
27226
  jobId,
@@ -27088,7 +27232,6 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27088
27232
  }
27089
27233
  const content = jobContentFields(jobId, providerStatus, opts.human);
27090
27234
  const resolvedAction = await resolveNextAction2(result.nextAction, result.messages, providerStatus?.status ?? result.providerStatus?.status);
27091
- const observed = providerStatus ?? result.providerStatus;
27092
27235
  const currency = access.endpointOverridden ? await providerCurrency({ receipt: observed?.receipt, status: observed, messages: result.messages, transport, ref }) : void 0;
27093
27236
  const settlement = await observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
27094
27237
  const unanswered = await readUnansweredPaymentRequest(jobId, observed?.status ?? (access.endpointOverridden ? void 0 : loadJob(jobId)?.status), access, transport, {
@@ -27107,7 +27250,7 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27107
27250
  } else {
27108
27251
  for (const msg of result.messages) {
27109
27252
  if (msg.type === "progress") continue;
27110
- formatMessageHuman(msg, jobId, artifactSession);
27253
+ formatMessageHuman(msg, jobId, artifactSession, mandate.bySeq.get(msg.seq));
27111
27254
  }
27112
27255
  finalizeProgressLine();
27113
27256
  }
@@ -27118,7 +27261,7 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27118
27261
  jobId,
27119
27262
  ...content,
27120
27263
  ...settlement,
27121
- ...!access.endpointOverridden ? mandatePaymentSummary(loadJob(jobId), loadMessages(jobId)) : {},
27264
+ ...mandate.summary,
27122
27265
  ...unanswered ? { unanswered_payment_request: unanswered } : {},
27123
27266
  message_count: messageLines,
27124
27267
  auto_payment_count: paymentLines,
@@ -27131,9 +27274,9 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27131
27274
  jobId,
27132
27275
  ...content,
27133
27276
  ...settlement,
27134
- ...!access.endpointOverridden ? mandatePaymentSummary(loadJob(jobId), loadMessages(jobId)) : {},
27277
+ ...mandate.summary,
27135
27278
  ...unanswered ? { unanswered_payment_request: unanswered } : {},
27136
- messages: result.messages.map((msg) => serialize(msg, access.endpointOverridden ? void 0 : jobId)),
27279
+ messages: result.messages.map((msg) => serialize(msg, mandate.bySeq.get(msg.seq))),
27137
27280
  cursor: result.cursor,
27138
27281
  next_action: resolvedAction,
27139
27282
  ...result.autoPayments.length > 0 ? { auto_payments: result.autoPayments } : {},
@@ -27145,9 +27288,9 @@ function serializeMessageForOutput(msg) {
27145
27288
  return serialize(msg);
27146
27289
  }
27147
27290
  function serializeJobMessageForOutput(msg, jobId) {
27148
- return serialize(msg, jobId);
27291
+ return serialize(msg, readMandatePaymentReport(msg, jobId));
27149
27292
  }
27150
- function serialize(msg, jobId) {
27293
+ function serialize(msg, mandateReport) {
27151
27294
  const fromProvider = !isCallerMessage(msg);
27152
27295
  const base = providerFields(
27153
27296
  { seq: msg.seq, from: msg.from, timestamp: msg.timestamp, type: msg.type, content: msg.content },
@@ -27197,13 +27340,8 @@ function serialize(msg, jobId) {
27197
27340
  };
27198
27341
  }
27199
27342
  case "payment": {
27200
- if (mandateCredit(msg)) {
27201
- const report = mandatePaymentReports(
27202
- jobId ? loadJob(jobId) : void 0,
27203
- [...jobId ? loadMessages(jobId) : [], msg]
27204
- ).find((entry) => entry.seq === msg.seq);
27205
- if (report) return { ...base, ...report, content: { ...msg.content } };
27206
- }
27343
+ const report = mandateReport ?? readMandatePaymentReport(msg);
27344
+ if (report) return { ...base, ...report, content: { ...msg.content } };
27207
27345
  const amount = paymentAmount(msg);
27208
27346
  const display = msg.from === "provider" ? `${msg.content.reason === "change" ? "Change" : "Refund"} sent: ${amount}` : `Payment sent: ${amount}`;
27209
27347
  return { ...base, content: { ...msg.content }, display };
@@ -32225,6 +32363,9 @@ function outputResults2(resultJson, human, nextAction) {
32225
32363
  }
32226
32364
  }
32227
32365
 
32366
+ // src/commands/status.ts
32367
+ import { createHash as createHash6 } from "crypto";
32368
+
32228
32369
  // src/lib/job-spend.ts
32229
32370
  function jobSpend(job, receipt) {
32230
32371
  const settlement = jobSettlement(job, receipt);
@@ -32342,12 +32483,15 @@ function renderSpendHuman(spend, print) {
32342
32483
  }
32343
32484
 
32344
32485
  // src/commands/status.ts
32486
+ var MAX_STATUS_GAP_PROBES = 2;
32345
32487
  async function status(jobId, opts) {
32346
32488
  const access = resolveJobAccess(jobId, opts);
32347
32489
  return withJobTokenRedaction(access.jobToken, () => withOutputWarnings(() => statusWithAccess(jobId, opts, access), opts.human));
32348
32490
  }
32349
32491
  async function statusWithAccess(jobId, opts, access) {
32350
32492
  const { stored, ref, jobToken } = access;
32493
+ const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 5e3;
32494
+ const readOptions = { timeoutMs: timeout, jobToken };
32351
32495
  if (stored && !access.overridden && isTerminalJobStatus(stored.status) && (stored.completion || stored.status !== "completed") && !opts.messages) {
32352
32496
  let receipt2 = replayStoredReceipt(stored);
32353
32497
  let terminalStatus = stored.status;
@@ -32376,7 +32520,14 @@ async function statusWithAccess(jobId, opts, access) {
32376
32520
  status: { ...completion2, ...content, status: terminalStatus },
32377
32521
  transport: transport2,
32378
32522
  ref,
32379
- jobToken
32523
+ ...readOptions,
32524
+ ...stored.mandate && { readMessages: async () => {
32525
+ const { batch, history: history2 } = await readStatusMessages(jobId, access, transport2, {
32526
+ ...readOptions,
32527
+ status: terminalStatus
32528
+ });
32529
+ return history2 ?? batch;
32530
+ } }
32380
32531
  });
32381
32532
  markJobTerminal(jobId, terminalStatus, completion2);
32382
32533
  }
@@ -32390,26 +32541,20 @@ async function statusWithAccess(jobId, opts, access) {
32390
32541
  });
32391
32542
  return;
32392
32543
  }
32393
- const timeout = opts.timeout ? Number(opts.timeout) * 1e3 : 5e3;
32394
32544
  const transport = createDvmTransport();
32395
32545
  progressNotice("Checking job status...", opts.human);
32396
- const result = await transport.status(jobId, ref, { timeoutMs: timeout, jobToken });
32546
+ const result = await transport.status(jobId, ref, readOptions);
32397
32547
  if (stored && !access.endpointOverridden) captureDrawFundingReceipts(jobId, result.drawFundingReceipts, { endpoint: ref.endpoint });
32398
32548
  if (!access.endpointOverridden && result.stop_requested) rememberStandingStop(jobId, result.display);
32399
- let msgs = [];
32400
- let newCursor;
32401
- if (opts.messages || stored?.mandate && !access.endpointOverridden) {
32402
- const after = access.endpointOverridden || !opts.messages ? 0 : stored?.messageCursor ?? 0;
32403
- msgs = await transport.getMessages(jobId, after, ref, { timeoutMs: timeout, jobToken });
32404
- if (!access.endpointOverridden) {
32405
- appendMessages(jobId, msgs);
32406
- await settleRecordedPayments(jobId);
32407
- }
32408
- if (opts.messages) newCursor = maxSeq(msgs, after);
32409
- }
32410
- const nextAction = await resolveNextAction(jobId, result.status, msgs, transport, ref, {
32411
- timeoutMs: timeout,
32412
- jobToken,
32549
+ const { batch: msgs, history, cursor: newCursor } = opts.messages || stored?.mandate && !access.endpointOverridden ? await readStatusMessages(jobId, access, transport, {
32550
+ ...readOptions,
32551
+ status: result.status,
32552
+ deliver: opts.messages,
32553
+ contentAvailable: result.content_available,
32554
+ hasArtifacts: result.hasArtifacts
32555
+ }) : { batch: [] };
32556
+ const nextAction = await resolveNextAction(jobId, result.status, msgs, history, transport, ref, {
32557
+ ...readOptions,
32413
32558
  context: access.endpointOverridden ? void 0 : stored ?? void 0,
32414
32559
  ignoreLocalState: access.endpointOverridden
32415
32560
  });
@@ -32417,7 +32562,7 @@ async function statusWithAccess(jobId, opts, access) {
32417
32562
  const reasonUnavailable = completion.message === void 0 || result.content_available === false && completion.message === "";
32418
32563
  if (reasonUnavailable && (result.status === "failed" || result.status === "cancelled")) {
32419
32564
  const savedReason = !access.endpointOverridden && stored?.status === result.status ? stored.completion?.message : void 0;
32420
- const terminal = msgs.findLast((message2) => message2.type === "complete" || message2.type === "cancel" || message2.type === "decline");
32565
+ const terminal = (history ?? msgs).findLast((message2) => message2.type === "complete" || message2.type === "cancel" || message2.type === "decline");
32421
32566
  const reason = savedReason ?? (terminal?.type === "cancel" || terminal?.type === "decline" ? terminal.content.reason : void 0);
32422
32567
  if (reason !== void 0) completion.message = reason;
32423
32568
  }
@@ -32429,7 +32574,8 @@ async function statusWithAccess(jobId, opts, access) {
32429
32574
  ref,
32430
32575
  jobToken,
32431
32576
  timeoutMs: timeout,
32432
- saved: !access.endpointOverridden && stored?.status === result.status ? stored.completion : void 0
32577
+ saved: !access.endpointOverridden && stored?.status === result.status ? stored.completion : void 0,
32578
+ ...history && { readMessages: async () => history }
32433
32579
  });
32434
32580
  }
32435
32581
  let receipt;
@@ -32465,7 +32611,8 @@ async function statusWithAccess(jobId, opts, access) {
32465
32611
  if (Object.keys(updates).length > 0) updateObservedJob(jobId, updates);
32466
32612
  }
32467
32613
  const unanswered = await readUnansweredPaymentRequest(jobId, result.status, access, transport, {
32468
- messages: msgs,
32614
+ messages: history ?? msgs,
32615
+ fullHistory: history !== void 0,
32469
32616
  timeoutMs: timeout,
32470
32617
  localOnly: result.content_available === false
32471
32618
  });
@@ -32582,13 +32729,97 @@ ${msgs.length} new message(s):`);
32582
32729
  }
32583
32730
  providerJobJson(output, !!stored);
32584
32731
  }
32585
- async function resolveNextAction(jobId, status2, fetched, transport, ref, opts) {
32732
+ async function readStatusMessages(jobId, access, transport, { status: status2, deliver, contentAvailable, hasArtifacts, ...readOptions }) {
32733
+ const stored = access.endpointOverridden ? null : access.stored;
32734
+ const deliveryAfter = stored?.messageCursor ?? 0;
32735
+ const useCache = !!stored?.mandate && contentAvailable !== false;
32736
+ const cached2 = useCache ? loadMessages(jobId) : [];
32737
+ const checkpoint = stored?.statusMessageHistory;
32738
+ const useSparseHistory = !isTerminalJobStatus(status2) || status2 === "completed" && typeof hasArtifacts === "boolean";
32739
+ const covered = statusHistoryCursor(cached2, useSparseHistory ? checkpoint : void 0);
32740
+ const after = deliver ? useCache ? Math.min(deliveryAfter, covered) : deliveryAfter : covered;
32741
+ const deadline = performance.now() + readOptions.timeoutMs;
32742
+ const tail = await transport.getMessages(jobId, after, access.ref, readOptions);
32743
+ const recovered = [];
32744
+ let promptGapScan = checkpoint?.promptGapScan;
32745
+ if (useCache && status2 === "awaiting-input" && checkpoint) {
32746
+ const gaps = openPromptGaps([...cached2, ...tail], after);
32747
+ const previousScan = promptGapScan;
32748
+ const remaining = previousScan ? gaps.filter((gap) => gap.after > previousScan.after && gap.after < previousScan.through) : [];
32749
+ const through = remaining.length && previousScan ? previousScan.through : after;
32750
+ for (const gap of (remaining.length ? remaining : gaps).slice(0, MAX_STATUS_GAP_PROBES)) {
32751
+ const timeoutMs = readOptions.timeoutMs > 0 ? Math.floor(deadline - performance.now()) : readOptions.timeoutMs;
32752
+ if (readOptions.timeoutMs > 0 && timeoutMs < 1) break;
32753
+ try {
32754
+ const messages2 = await transport.getMessages(jobId, gap.after, access.ref, {
32755
+ ...readOptions,
32756
+ timeoutMs,
32757
+ beforeSeq: gap.before
32758
+ });
32759
+ for (const message2 of messages2) recovered.push(message2);
32760
+ } catch (error) {
32761
+ if (!isTransientJobReadError(error)) throw error;
32762
+ }
32763
+ promptGapScan = { after: gap.after, through };
32764
+ }
32765
+ }
32766
+ const history = contentAvailable !== false && (useCache || after === 0) ? [...new Map([...cached2.filter((message2) => message2.seq <= after), ...recovered, ...tail].map((message2) => [message2.seq, message2])).values()].sort((a, b) => a.seq - b.seq) : void 0;
32767
+ if (!access.endpointOverridden) {
32768
+ appendMessages(jobId, [...recovered, ...tail]);
32769
+ const fullHistoryThrough = history === void 0 ? void 0 : Math.max(after, history.at(-1)?.seq ?? 0);
32770
+ await settleRecordedPayments(jobId, fullHistoryThrough);
32771
+ if (useCache && !isTerminalJobStatus(status2) && history && fullHistoryThrough && Number.isSafeInteger(fullHistoryThrough)) {
32772
+ recordStatusMessageHistory(jobId, {
32773
+ through: fullHistoryThrough,
32774
+ sequenceDigest: historySequenceDigest(history, fullHistoryThrough),
32775
+ ...promptGapScan && { promptGapScan }
32776
+ }, checkpoint);
32777
+ }
32778
+ }
32779
+ const batch = deliver && after < deliveryAfter ? tail.filter((message2) => message2.seq > deliveryAfter) : tail;
32780
+ const cursor = deliver ? Math.max(deliveryAfter, maxSeq(batch, deliveryAfter)) : void 0;
32781
+ return { batch, history, cursor };
32782
+ }
32783
+ function statusHistoryCursor(cached2, checkpoint) {
32784
+ const sequences = new Set(cached2.map((message2) => message2.seq));
32785
+ const contiguous = contiguousSequenceThrough(sequences, 0);
32786
+ if (!checkpoint || !Number.isSafeInteger(checkpoint.through) || checkpoint.through <= contiguous || !sequences.has(checkpoint.through) || checkpoint.sequenceDigest !== historySequenceDigest(cached2, checkpoint.through)) return contiguous;
32787
+ return contiguousSequenceThrough(sequences, checkpoint.through);
32788
+ }
32789
+ function openPromptGaps(cached2, through) {
32790
+ const answered = answeredYieldSeqs(cached2);
32791
+ let previous = through;
32792
+ for (const message2 of cached2) {
32793
+ if (message2.from === "provider" && message2.type === "prompt" && !answered.has(message2.seq)) {
32794
+ previous = Math.min(previous, message2.seq);
32795
+ }
32796
+ }
32797
+ if (previous >= through) return [];
32798
+ const sequences = [...new Set(cached2.map((message2) => message2.seq).filter((seq) => seq > previous && seq <= through))].sort((a, b) => a - b);
32799
+ if (sequences.at(-1) !== through) sequences.push(through + 1);
32800
+ const gaps = [];
32801
+ for (const seq of sequences) {
32802
+ if (seq > previous + 1) gaps.push({ after: previous, before: seq });
32803
+ previous = seq;
32804
+ }
32805
+ return gaps;
32806
+ }
32807
+ function contiguousSequenceThrough(sequences, after) {
32808
+ while (after < Number.MAX_SAFE_INTEGER && sequences.has(after + 1)) after++;
32809
+ return after;
32810
+ }
32811
+ function historySequenceDigest(messages2, through) {
32812
+ const sequences = [...new Set(messages2.map((message2) => message2.seq).filter((seq) => seq <= through))].sort((a, b) => a - b);
32813
+ return createHash6("sha256").update(JSON.stringify(sequences)).digest("hex");
32814
+ }
32815
+ async function resolveNextAction(jobId, status2, fetched, history, transport, ref, opts) {
32586
32816
  if (isTerminalJobStatus(status2)) return null;
32587
32817
  if (status2 === "awaiting-input") {
32818
+ if (history) return readNextAction(jobId, history, opts) ?? pollNextAction(jobId);
32588
32819
  const fromBatch = readNextAction(jobId, fetched, opts);
32589
32820
  if (fromBatch) return fromBatch;
32590
- const history = await transport.getMessages(jobId, 0, ref, opts);
32591
- return readNextAction(jobId, history, opts) ?? pollNextAction(jobId);
32821
+ const fullLog = await transport.getMessages(jobId, 0, ref, opts);
32822
+ return readNextAction(jobId, fullLog, opts) ?? pollNextAction(jobId);
32592
32823
  }
32593
32824
  return pollNextAction(jobId);
32594
32825
  }
@@ -32597,14 +32828,14 @@ async function resolveNextAction(jobId, status2, fetched, transport, ref, opts)
32597
32828
  import { statSync as statSync4 } from "fs";
32598
32829
 
32599
32830
  // src/lib/upload-stream.ts
32600
- import { createHash as createHash6 } from "crypto";
32831
+ import { createHash as createHash7 } from "crypto";
32601
32832
  import { createReadStream as createReadStream2 } from "fs";
32602
32833
  import * as http2 from "http";
32603
32834
  import * as https from "https";
32604
32835
  var UPLOAD_RESPONSE_MAX_BYTES = 64 * 1024;
32605
32836
  function hashFile(filePath) {
32606
32837
  return new Promise((resolve3, reject) => {
32607
- const hasher = createHash6("sha256");
32838
+ const hasher = createHash7("sha256");
32608
32839
  let sizeBytes = 0;
32609
32840
  const stream = createReadStream2(filePath);
32610
32841
  stream.on("data", (chunk) => {
@@ -35093,6 +35324,75 @@ function examples(fetcher) {
35093
35324
  return parts.join(", ");
35094
35325
  }
35095
35326
 
35327
+ // src/lib/wallet-agent/collect.ts
35328
+ import { setTimeout as sleepFor } from "timers/promises";
35329
+ var POLL_INTERVAL_MS = 2e3;
35330
+ var PRE_EXPIRY_POLL_LEAD_MS = 500;
35331
+ var EXPIRY_MARGIN_MS = 5e3;
35332
+ var MAX_TIMER_MS2 = 2147483647;
35333
+ async function collectPendingMint(entry, cashuWallet, durationMs) {
35334
+ const start = Date.now();
35335
+ const expiry = entry.expires_at === void 0 ? Infinity : entry.expires_at * 1e3;
35336
+ const durationDeadline = start + durationMs;
35337
+ const pollUntil = Math.min(expiry, durationDeadline);
35338
+ const deadline = Math.min(expiry + EXPIRY_MARGIN_MS, durationDeadline);
35339
+ const elapsedReason = expiry <= durationDeadline ? "quote_expired" : "duration_elapsed";
35340
+ if (expiry <= start) return { kind: "stopped", reason: "quote_expired" };
35341
+ const preExpiryPollAt = expiry <= durationDeadline ? expiry - PRE_EXPIRY_POLL_LEAD_MS : pollUntil;
35342
+ const retryState = createMintQuoteRetryState();
35343
+ try {
35344
+ let startedAt = Date.now();
35345
+ while (startedAt < deadline) {
35346
+ const catchUp = startedAt >= pollUntil;
35347
+ const checkDeadline = catchUp ? deadline : pollUntil;
35348
+ const signal = AbortSignal.timeout(Math.min(MAX_TIMER_MS2, deadline - startedAt));
35349
+ ba({ signal });
35350
+ const outcome = await retryMintQuoteOperation(async () => {
35351
+ const pass = await reconcilePendingMint(entry, {
35352
+ getWalletForMint: async () => cashuWallet,
35353
+ pollDeadlineMs: checkDeadline,
35354
+ quoteRetryTimeoutMs: Math.max(0, checkDeadline - Date.now()),
35355
+ deadlineMs: deadline
35356
+ });
35357
+ if (pass.kind === "error") throw pass.cause;
35358
+ return pass;
35359
+ }, { deadlineMs: checkDeadline, quoteId: entry.quote_id, state: retryState }).catch(() => void 0);
35360
+ if (!outcome) {
35361
+ return { kind: "stopped", reason: Date.now() >= pollUntil ? elapsedReason : "mint_unavailable" };
35362
+ }
35363
+ switch (outcome.kind) {
35364
+ case "minted":
35365
+ case "restored":
35366
+ return { kind: "collected", proofs: outcome.proofs };
35367
+ case "already_issued":
35368
+ return { kind: "already_issued" };
35369
+ case "no_longer_pending": {
35370
+ if (Date.now() >= checkDeadline) return { kind: "stopped", reason: "no_longer_pending" };
35371
+ const quote2 = await cashuWallet.checkMintQuoteBolt11(entry.quote_id).catch(() => void 0);
35372
+ return quote2?.state === sa.ISSUED ? { kind: "already_issued" } : { kind: "stopped", reason: "no_longer_pending" };
35373
+ }
35374
+ case "expired":
35375
+ return { kind: "stopped", reason: "quote_expired" };
35376
+ case "paid_refused":
35377
+ return { kind: "stopped", reason: "paid_uncollected" };
35378
+ case "still_pending":
35379
+ case "busy": {
35380
+ if (catchUp) return { kind: "stopped", reason: elapsedReason };
35381
+ const now = Date.now();
35382
+ const nextCheck = outcome.kind === "busy" ? Math.min(pollUntil, now + 100) : startedAt >= preExpiryPollAt ? pollUntil : Math.min(preExpiryPollAt, now + POLL_INTERVAL_MS);
35383
+ const delay = nextCheck - now;
35384
+ if (delay > 0) await sleepFor(delay);
35385
+ break;
35386
+ }
35387
+ }
35388
+ startedAt = Date.now();
35389
+ }
35390
+ return { kind: "stopped", reason: elapsedReason };
35391
+ } finally {
35392
+ ba({});
35393
+ }
35394
+ }
35395
+
35096
35396
  // src/lib/error-handler.ts
35097
35397
  import { readFileSync as readFileSync11 } from "fs";
35098
35398
  import { dirname as dirname4, isAbsolute as isAbsolute2, join as join12, relative as relative2, sep as sep3 } from "path";
@@ -35807,10 +36107,10 @@ var NON_FUNGIBLE_MINT_NOTE = "Balances are per-mint: each mint is a separate cus
35807
36107
  async function walletFund(amount, opts) {
35808
36108
  const rail = (opts.rail ?? "cashu").toLowerCase();
35809
36109
  if (rail === "tempo" || rail === "x402") {
35810
- if (opts.mint !== void 0 || opts.timeout !== void 0 || opts.sats || opts.testSkipLightning || opts.float === false || opts.wait === false) {
36110
+ if (opts.mint !== void 0 || opts.timeout !== void 0 || opts.sats || opts.testSkipLightning || opts.float === false || opts.wait === false || opts.collectFor !== void 0) {
35811
36111
  throw new DvmError(
35812
36112
  "invalid_flags_for_rail",
35813
- "--mint, --timeout, --sats, --test-skip-lightning, --no-float, and --no-wait only apply to --rail cashu.",
36113
+ "--mint, --timeout, --sats, --test-skip-lightning, --no-float, --no-wait, and --collect-for only apply to --rail cashu.",
35814
36114
  `Drop these flags when running \`dvm wallet fund --rail ${rail}\`.`
35815
36115
  );
35816
36116
  }
@@ -35825,6 +36125,16 @@ async function walletFund(amount, opts) {
35825
36125
  "Supported rails: cashu (default), tempo, x402."
35826
36126
  );
35827
36127
  }
36128
+ let collectForMs;
36129
+ if (opts.collectFor !== void 0) {
36130
+ if (opts.wait !== false) {
36131
+ throw new DvmError("invalid_fund_options", "--collect-for requires --no-wait.");
36132
+ }
36133
+ collectForMs = parseDurationMs(opts.collectFor);
36134
+ if (collectForMs === 0) {
36135
+ throw new DvmError("invalid_arguments", "--collect-for requires a positive duration, such as 30s or 2m.");
36136
+ }
36137
+ }
35828
36138
  if (opts.wait === false && opts.testSkipLightning) {
35829
36139
  throw new DvmError(
35830
36140
  "invalid_fund_options",
@@ -35849,6 +36159,7 @@ async function walletFund(amount, opts) {
35849
36159
  "Run `dvm wallet init` first to generate a lock keypair."
35850
36160
  );
35851
36161
  }
36162
+ const lockPubkey = wallet.lock_pubkey;
35852
36163
  const sweep = await reconcilePendingMints();
35853
36164
  const meltSweep = await reconcilePendingMelts().catch(emptyMeltSweep);
35854
36165
  const funding = effectiveFundingMint(wallet.mints);
@@ -35936,7 +36247,7 @@ async function walletFund(amount, opts) {
35936
36247
  if (opts.wait === false) {
35937
36248
  info(`Quote ID: ${quote2.quote}`);
35938
36249
  if (expiresAt) info(`Invoice expires: ${expiresAt}`);
35939
- info("After payment, run `dvm wallet show` to collect the sats and check the new balance.");
36250
+ info(collectForMs === void 0 ? "After payment, run `dvm wallet show` to collect the sats and check the new balance." : `Waiting up to ${opts.collectFor} to collect payment, subject to the quote expiry.`);
35940
36251
  info(` \u21B3 ${collectDeadlineHint(expiresAt)}`);
35941
36252
  } else {
35942
36253
  info(
@@ -35959,6 +36270,7 @@ async function walletFund(amount, opts) {
35959
36270
  relay: { copy_text: invoice, standalone: true },
35960
36271
  expires_at: expiresAt,
35961
36272
  ...opts.wait === false ? { collect_before: expiresAt } : {},
36273
+ ...collectForMs === void 0 ? {} : { collection_state: "waiting" },
35962
36274
  lock_pubkey: wallet.lock_pubkey,
35963
36275
  display: `Pay ${sats} sats to the Lightning invoice to fund ${amountPhrase} into the agent wallet at ${mintUrl} (${selectionPhrase}). Scannable QR at ${qrImagePath}.`,
35964
36276
  ...opts.wait === false ? {
@@ -35967,13 +36279,27 @@ async function walletFund(amount, opts) {
35967
36279
  sweep: summarizeSweep(sweep),
35968
36280
  melt_sweep: summarizeMeltSweep(meltSweep)
35969
36281
  } : {},
35970
- hint: opts.wait === false ? `Forward the QR PNG (or raw invoice) to a human. After payment, run \`dvm wallet show\` to collect the sats and check the new balance. ${collectDeadlineHint(expiresAt)} Funding is still pending.` : "Forward the QR PNG (or raw invoice) to a human; the CLI will mint P2PK-locked Cashu proofs into ~/.dvm/wallet.json once paid."
36282
+ hint: collectForMs !== void 0 ? `Forward the QR PNG (or raw invoice) to a human now. This command is waiting for payment. ${collectDeadlineHint(expiresAt)}` : opts.wait === false ? `Forward the QR PNG (or raw invoice) to a human. After payment, run \`dvm wallet show\` to collect the sats and check the new balance. ${collectDeadlineHint(expiresAt)} Funding is still pending.` : "Forward the QR PNG (or raw invoice) to a human; the CLI will mint P2PK-locked Cashu proofs into ~/.dvm/wallet.json once paid."
35971
36283
  });
35972
36284
  }
35973
36285
  };
35974
36286
  if (opts.wait === false) {
35975
- const { quote: quote2 } = await createPendingMintQuote(sats, { mintUrl });
36287
+ const { quote: quote2, pending: pending4, cashuWallet } = await createPendingMintQuote(sats, { mintUrl });
35976
36288
  await onInvoice(quote2.request, quote2);
36289
+ if (collectForMs !== void 0) {
36290
+ const outcome = await collectPendingMint(pending4, cashuWallet, collectForMs);
36291
+ if (outcome.kind === "collected") {
36292
+ reportMinted({
36293
+ mint: mintUrl,
36294
+ amount_sats: sats,
36295
+ quote_id: quote2.quote,
36296
+ denominations: outcome.proofs.map((proof) => proof.amount),
36297
+ proofs: outcome.proofs
36298
+ });
36299
+ } else {
36300
+ reportCollectionOutcome(pending4, outcome, human);
36301
+ }
36302
+ }
35977
36303
  return;
35978
36304
  }
35979
36305
  const result = await fundWithRecoverableWait(sats, {
@@ -36036,31 +36362,62 @@ async function walletFund(amount, opts) {
36036
36362
  },
36037
36363
  onInvoice
36038
36364
  });
36039
- const totalProofSats = result.proofs.reduce((sum, p) => sum + p.amount, 0);
36365
+ reportMinted(result);
36366
+ function reportMinted(result2) {
36367
+ const totalProofSats = result2.proofs.reduce((sum, p) => sum + p.amount, 0);
36368
+ if (human) {
36369
+ info("");
36370
+ info(
36371
+ `Minted ${totalProofSats} sats at ${mintUrl} (${selectionPhrase}) across ${result2.proofs.length} P2PK-locked proofs.`
36372
+ );
36373
+ info(`Smart denomination split: ${formatDenominations(result2.denominations)}.`);
36374
+ info(`Locked to lock pubkey: ${lockPubkey}`);
36375
+ } else {
36376
+ json({
36377
+ status: "minted",
36378
+ mint: mintUrl,
36379
+ mint_selection: mintSelection,
36380
+ amount_sats: sats,
36381
+ ...amountSourceFields(amt),
36382
+ sats_minted: totalProofSats,
36383
+ proof_count: result2.proofs.length,
36384
+ denominations: result2.denominations,
36385
+ lock_pubkey: lockPubkey,
36386
+ quote_id: result2.quote_id,
36387
+ ...collectForMs === void 0 ? {} : { collection_state: "collected" },
36388
+ sweep: summarizeSweep(sweep),
36389
+ melt_sweep: summarizeMeltSweep(meltSweep),
36390
+ ...result2.float_payment ? { float_payment: floatPaymentJson(result2.float_payment) } : {},
36391
+ display: result2.float_payment ? `Topped up ${totalProofSats} sats from your Lightning wallet into the agent wallet at ${mintUrl} (${selectionPhrase}). ${floatPaymentDisplay(result2.float_payment)} No action needed.` : `Minted ${totalProofSats} sats at ${mintUrl} (${selectionPhrase}), locked to lock pubkey.`,
36392
+ hint: "Inspect the resulting balance with `dvm wallet show`."
36393
+ });
36394
+ }
36395
+ }
36396
+ }
36397
+ function reportCollectionOutcome(entry, outcome, human) {
36398
+ const expiryMs = entry.expires_at === void 0 ? null : entry.expires_at * 1e3;
36399
+ const collectBefore = expiryMs === null ? null : new Date(expiryMs).toISOString();
36400
+ const nextStep = "dvm wallet show";
36401
+ const reason = outcome.kind === "stopped" ? outcome.reason : void 0;
36402
+ const alreadyIssued = outcome.kind === "already_issued";
36403
+ const display = alreadyIssued ? `The mint reports quote ${entry.quote_id} was already issued.` : `Collection ended for quote ${entry.quote_id}.`;
36404
+ const stopPayment = reason === "quote_expired" || reason === "paid_uncollected" || reason === "no_longer_pending" || expiryMs !== null && expiryMs <= Date.now();
36405
+ const deadlineHint = collectBefore ? ` The mint named ${collectBefore} as the deadline.` : "";
36406
+ const hint = alreadyIssued ? `Run \`${nextStep}\` to check the balance.` : stopPayment ? `Run \`${nextStep}\` to check the wallet before taking further action.${deadlineHint} Do not pay this invoice now.` : `Run \`${nextStep}\` after payment to collect or check for collection. ${collectDeadlineHint(collectBefore)}`;
36040
36407
  if (human) {
36041
- info("");
36042
- info(
36043
- `Minted ${totalProofSats} sats at ${mintUrl} (${selectionPhrase}) across ${result.proofs.length} P2PK-locked proofs.`
36044
- );
36045
- info(`Smart denomination split: ${formatDenominations(result.denominations)}.`);
36046
- info(`Locked to lock pubkey: ${wallet.lock_pubkey}`);
36408
+ info(`${display} ${hint}`);
36047
36409
  } else {
36048
36410
  json({
36049
- status: "minted",
36050
- mint: mintUrl,
36051
- mint_selection: mintSelection,
36052
- amount_sats: sats,
36053
- ...amountSourceFields(amt),
36054
- sats_minted: totalProofSats,
36055
- proof_count: result.proofs.length,
36056
- denominations: result.denominations,
36057
- lock_pubkey: wallet.lock_pubkey,
36058
- quote_id: result.quote_id,
36059
- sweep: summarizeSweep(sweep),
36060
- melt_sweep: summarizeMeltSweep(meltSweep),
36061
- ...result.float_payment ? { float_payment: floatPaymentJson(result.float_payment) } : {},
36062
- display: result.float_payment ? `Topped up ${totalProofSats} sats from your Lightning wallet into the agent wallet at ${mintUrl} (${selectionPhrase}). ${floatPaymentDisplay(result.float_payment)} No action needed.` : `Minted ${totalProofSats} sats at ${mintUrl} (${selectionPhrase}), locked to lock pubkey.`,
36063
- hint: "Inspect the resulting balance with `dvm wallet show`."
36411
+ status: alreadyIssued ? "already_issued" : "collection_stopped",
36412
+ collection_state: alreadyIssued ? "already_issued" : "needs_wallet_show",
36413
+ ...reason ? { reason } : {},
36414
+ quote_id: entry.quote_id,
36415
+ mint: entry.mint,
36416
+ amount_sats: entry.amount_sats,
36417
+ collect_before: collectBefore,
36418
+ next_step: nextStep,
36419
+ display,
36420
+ hint
36064
36421
  });
36065
36422
  }
36066
36423
  }
@@ -36814,12 +37171,12 @@ import { randomUUID as randomUUID5 } from "crypto";
36814
37171
 
36815
37172
  // src/lib/wallet-agent/release-intents.ts
36816
37173
  var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
36817
- import { createHash as createHash7 } from "crypto";
37174
+ import { createHash as createHash8 } from "crypto";
36818
37175
  import { dirname as dirname5, join as join13 } from "path";
36819
37176
  var intents = journalFile("release-intents.json");
36820
37177
  async function withReleaseLock(walletPubkey, builderHandle, mint, operation) {
36821
37178
  ensureConfigDir();
36822
- const key = createHash7("sha256").update(JSON.stringify([walletPubkey, builderHandle, mint])).digest("hex");
37179
+ const key = createHash8("sha256").update(JSON.stringify([walletPubkey, builderHandle, mint])).digest("hex");
36823
37180
  let unlock;
36824
37181
  try {
36825
37182
  unlock = await import_proper_lockfile3.default.lock(join13(dirname5(JOBS_FILE), `release-${key}`), {
@@ -39045,7 +39402,7 @@ function resolveMppEndpoint(identifier) {
39045
39402
  }
39046
39403
 
39047
39404
  // src/commands/wallet-pair.ts
39048
- import { createHash as createHash8, randomBytes as randomBytes5 } from "crypto";
39405
+ import { createHash as createHash9, randomBytes as randomBytes5 } from "crypto";
39049
39406
  import { hostname as hostname2 } from "os";
39050
39407
 
39051
39408
  // node_modules/nostr-tools/lib/esm/pure.js
@@ -40496,7 +40853,7 @@ function walletFingerprint(uri) {
40496
40853
  return uri ? sha2562(uri) : null;
40497
40854
  }
40498
40855
  function sha2562(value) {
40499
- return createHash8("sha256").update(value).digest("hex");
40856
+ return createHash9("sha256").update(value).digest("hex");
40500
40857
  }
40501
40858
  function relayHost2(relay) {
40502
40859
  try {
@@ -46232,7 +46589,7 @@ function buildProgram() {
46232
46589
  } }).exitOverride((error) => {
46233
46590
  if (error.exitCode === 0 || !jsonWait()) process.exit(error.exitCode);
46234
46591
  handleError(new DvmError("invalid_arguments", error.message.replace(/^error: /, "")), false, { event: "error" });
46235
- }).description("Fetch messages from a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--after <seq>", "Only show messages with seq > N").option("--no-stream", "Non-blocking snapshot instead of streaming until yield").option("--human", "Human-readable output instead of JSON").option("--wait", "Stay attached until the job needs input or ends; JSON output is one line per event").option("--until <duration>", "Wait limit with --wait (default: 12h; e.g. 30s, 5m, 12h, 1h30m)").option("--timeout <sec>", "Read timeout (default: 5s, or 60s with --wait)").action((jobId, opts) => {
46592
+ }).description("Fetch messages from a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option("--after <seq>", "Only show messages with seq > N").option("--no-stream", "Non-blocking snapshot instead of streaming until yield").option("--human", "Human-readable output instead of JSON").option("--wait", "Stay attached until the job needs input or ends; JSON output is one line per event").option("--until <duration>", "Wait limit with --wait (default: 12h; e.g. 30s, 5m, 12h, 1h30m)").option("--timeout <sec>", "Read timeout (default: 5s, or 60s with --wait). With --no-stream, the download times out after this long without data.").action((jobId, opts) => {
46236
46593
  return catchErrors(() => messages(jobId, opts), opts.human, opts.wait && !opts.human ? { event: "error" } : void 0);
46237
46594
  });
46238
46595
  program2.command("message <job-id> [text]").description("Send a message in a job conversation").option("--endpoint <url>", "Provider URL override (env: DVM_JOB_ENDPOINT)").option("--job-token <hex>", "Job bearer token override (env: DVM_JOB_TOKEN)").option(
@@ -46409,6 +46766,9 @@ Docs:
46409
46766
  ).option("--mint <url>", "Cashu mint URL (default: configured mint, or Coinos)").option("--timeout <sec>", "Override DVM_FUND_TIMEOUT_SEC (default 600s)").option(
46410
46767
  "--no-wait",
46411
46768
  "Print a human-paid Lightning invoice and exit; collect after payment with 'dvm wallet show'. Cashu only; use --no-float if a float is connected."
46769
+ ).option(
46770
+ "--collect-for <duration>",
46771
+ "With --no-wait, print the invoice and stay open to collect for up to this long (e.g. 30s or 2m)."
46412
46772
  ).option(
46413
46773
  "--test-skip-lightning",
46414
46774
  "Skip Lightning \u2014 for test mints that auto-pay invoices (FakeWallet). Cashu rail only."