@dvmkit/dvm-cli 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dvm.js CHANGED
@@ -5,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,
@@ -231,13 +233,13 @@ import {
231
233
  withJobTokenRedaction,
232
234
  withRequestResultRecovery,
233
235
  withoutPendingMint
234
- } from "./chunk-GWISSHP6.js";
236
+ } from "./chunk-WGZ3HBST.js";
235
237
  import {
236
238
  connectedTempoAccount,
237
239
  generateTempoKey,
238
240
  tempoBalanceCheckHint,
239
241
  tempoWrongAssetHint
240
- } from "./chunk-L3PHIA5L.js";
242
+ } from "./chunk-AFR5KKJX.js";
241
243
  import {
242
244
  assertSupportedX402Network,
243
245
  connectedX402Payer,
@@ -246,7 +248,7 @@ import {
246
248
  repinX402WalletNetwork,
247
249
  saveX402Wallet,
248
250
  x402NetworkLabel
249
- } from "./chunk-M4Q3DBQO.js";
251
+ } from "./chunk-ITESN5XP.js";
250
252
  import {
251
253
  CREDIT_POSTURES,
252
254
  FEEDBACK_POSTURES,
@@ -263,7 +265,7 @@ import {
263
265
  retireConfigBackup,
264
266
  rollbackConfig,
265
267
  updateConfig
266
- } from "./chunk-BU5E7IDF.js";
268
+ } from "./chunk-YSALCR5X.js";
267
269
  import {
268
270
  addOutputWarnings,
269
271
  assertValidBudget,
@@ -286,10 +288,10 @@ import {
286
288
  tryX402Payment,
287
289
  withOutputWarningContext,
288
290
  withOutputWarnings
289
- } from "./chunk-YRLRHJ6O.js";
291
+ } from "./chunk-23FGJKIX.js";
290
292
  import {
291
293
  assertX402WalletIdle
292
- } from "./chunk-QVX7KPLS.js";
294
+ } from "./chunk-AWK22TUP.js";
293
295
  import {
294
296
  A,
295
297
  AGENT_MNEMONIC_FILE,
@@ -347,6 +349,7 @@ import {
347
349
  assertX402ChannelPayer,
348
350
  attestedDvmIdentity,
349
351
  authenticatedBuilderPubkey,
352
+ ba,
350
353
  base64,
351
354
  bech32,
352
355
  bindCashuTokenToSubmissionContext,
@@ -365,6 +368,7 @@ import {
365
368
  copyBytes,
366
369
  coveringMintsForSpend,
367
370
  createFxFetcher,
371
+ createMintQuoteRetryState,
368
372
  createTempoCloseCredential,
369
373
  deleteAgentMnemonic,
370
374
  deriveAgentMasterKeypair,
@@ -530,7 +534,7 @@ import {
530
534
  x402PendingUnsettled,
531
535
  x402RequiredFromError,
532
536
  x402ReservationRelease
533
- } from "./chunk-CMIEPFKP.js";
537
+ } from "./chunk-AWWLO2WW.js";
534
538
  import "./chunk-JBU7RKQ3.js";
535
539
  import "./chunk-KDNFUDOG.js";
536
540
  import "./chunk-IUTVV6N5.js";
@@ -9946,6 +9950,20 @@ async function receivePaymentCredit(args) {
9946
9950
  return finishPaymentCredit(landing);
9947
9951
  }
9948
9952
 
9953
+ // src/lib/job-read-error.ts
9954
+ var JobGatewayReadError = class extends DvmError {
9955
+ constructor(message2, proseSources) {
9956
+ super("provider_error", message2, void 0, void 0, void 0, proseSources);
9957
+ }
9958
+ };
9959
+ function jobReadHttpError(status2, message2, proseSources) {
9960
+ if (status2 === 502 || status2 === 503 || status2 === 504) return new JobGatewayReadError(message2, proseSources);
9961
+ return new DvmError("provider_error", message2, void 0, void 0, void 0, proseSources);
9962
+ }
9963
+ function isTransientJobReadError(error) {
9964
+ return isAbortError(error) || error instanceof JobGatewayReadError || error instanceof DvmError && ["timeout", "provider_unreachable"].includes(error.code);
9965
+ }
9966
+
9949
9967
  // src/lib/mandate-wait.ts
9950
9968
  var SDK_MANDATE_RESUME_GRACE_MS = 1e4;
9951
9969
  var SDK_MAX_STALE_SWEEP_INTERVAL_MS = 6e4;
@@ -9993,7 +10011,7 @@ async function recoverMandateWinner(jobId, requestSeq, transport, provider, jobT
9993
10011
  if (!loadJob(jobId)?.mandate) return false;
9994
10012
  const history = await transport.getMessages(jobId, 0, provider, { jobToken, timeoutMs: 6e4 });
9995
10013
  appendMessages(jobId, history);
9996
- recordMandatePayments(jobId, history);
10014
+ recordMandatePayments(jobId, history, maxSeq(history, 0));
9997
10015
  return history.some((message2) => mandateCredit(message2)?.request_seq === requestSeq);
9998
10016
  }
9999
10017
  async function declineStoppedAsk(jobId, requestSeq, transport, provider, jobToken) {
@@ -10016,12 +10034,27 @@ async function declineStoppedAsk(jobId, requestSeq, transport, provider, jobToke
10016
10034
  { mandate_wait: true, ...standingStopOutput(loadJob(jobId)) }
10017
10035
  );
10018
10036
  }
10019
- async function guardMandatePayment(jobId, requestSeq, transport, provider, jobToken) {
10037
+ var MandateGuardReadError = class extends Error {
10038
+ constructor(cause) {
10039
+ super("The mandate guard could not confirm the charge within its read budget.", { cause });
10040
+ }
10041
+ };
10042
+ async function guardMandatePayment(jobId, requestSeq, transport, provider, jobToken, waitReadTimeoutMs) {
10020
10043
  const job = loadJob(jobId);
10021
10044
  if (!job?.mandate && !job?.stopRequested) return;
10022
- const history = await transport.getMessages(jobId, 0, provider, { jobToken, timeoutMs: 6e4 });
10045
+ async function read(request2) {
10046
+ const timeoutMs = waitReadTimeoutMs?.() ?? 6e4;
10047
+ if (timeoutMs <= 0) throw new MandateGuardReadError();
10048
+ try {
10049
+ return await request2({ jobToken, timeoutMs });
10050
+ } catch (error) {
10051
+ if (waitReadTimeoutMs && isTransientJobReadError(error)) throw new MandateGuardReadError(error);
10052
+ throw error;
10053
+ }
10054
+ }
10055
+ const history = await read((options) => transport.getMessages(jobId, 0, provider, options));
10023
10056
  appendMessages(jobId, history);
10024
- recordMandatePayments(jobId, history);
10057
+ recordMandatePayments(jobId, history, maxSeq(history, 0));
10025
10058
  const payment = history.find((message2) => message2.from === "requester" && message2.type === "payment" && message2.content.credit?.request_seq === requestSeq);
10026
10059
  if (payment?.type === "payment") {
10027
10060
  const id = payment.content.credit?.payment_id;
@@ -10041,7 +10074,7 @@ async function guardMandatePayment(jobId, requestSeq, transport, provider, jobTo
10041
10074
  );
10042
10075
  }
10043
10076
  const latestAsk = history.findLast((message2) => message2.from === "provider" && message2.type === "payment-request");
10044
- const status2 = await transport.status(jobId, provider, { jobToken, timeoutMs: 6e4 });
10077
+ const status2 = await read((options) => transport.status(jobId, provider, options));
10045
10078
  if (latestAsk?.seq !== requestSeq || status2.status !== "awaiting-input")
10046
10079
  throw new DvmError(
10047
10080
  "payment_request_not_pending",
@@ -10051,11 +10084,6 @@ async function guardMandatePayment(jobId, requestSeq, transport, provider, jobTo
10051
10084
  );
10052
10085
  }
10053
10086
 
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
10087
  // src/lib/payment-lock.ts
10060
10088
  var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
10061
10089
  import { createHash } from "crypto";
@@ -10320,7 +10348,8 @@ async function readBoundedBody(response, limit) {
10320
10348
  }
10321
10349
  body += decoder.decode(value, { stream: true });
10322
10350
  }
10323
- } catch {
10351
+ } catch (err) {
10352
+ if (isAbortError(err)) throw err;
10324
10353
  return void 0;
10325
10354
  } finally {
10326
10355
  reader.releaseLock();
@@ -12154,7 +12183,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
12154
12183
  );
12155
12184
  }
12156
12185
  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);
12186
+ await guardMandatePayment(jobId, opts.requestSeq, transport, provider, opts.jobToken ?? job.jobToken, opts.mandateReadTimeoutMs);
12158
12187
  if (job && hasUnknownUpfrontRail(job))
12159
12188
  throw new DvmError(
12160
12189
  "upfront_rail_unknown",
@@ -12175,7 +12204,7 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
12175
12204
  if (job?.creditOnly && (!matchingEndpoint || !job.creditBinding || "unbound" in job.creditBinding || job.creditBinding.creditId !== job.creditOnly || opts?.rail !== void 0))
12176
12205
  throw new DvmError("credit_only_unavailable", "This job may spend only its original prepaid credit.");
12177
12206
  if (matchingEndpoint && opts?.requestSeq !== void 0)
12178
- await guardMandatePayment(jobId, opts.requestSeq, transport, provider, jobToken);
12207
+ await guardMandatePayment(jobId, opts.requestSeq, transport, provider, jobToken, opts.mandateReadTimeoutMs);
12179
12208
  let balanceRefused = false;
12180
12209
  const booked = matchingEndpoint ? bookedCreditPayment(jobId, opts?.requestSeq) : void 0;
12181
12210
  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 +12376,8 @@ async function handleLockedPaymentRequest(jobId, request2, policy, transport, pr
12347
12376
  }
12348
12377
  }
12349
12378
  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");
12379
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RIHHIQRK.js");
12380
+ const { tryX402Payment: tryX402Payment2 } = await import("./client-5SB2HSH5.js");
12352
12381
  const wallet = loadX402Wallet2();
12353
12382
  if (wallet) {
12354
12383
  let proof;
@@ -12959,6 +12988,7 @@ async function streamLoop(opts) {
12959
12988
  let cursor = opts.afterSeq;
12960
12989
  let messageAppendSession = opts.messageAppendSession;
12961
12990
  const jobToken = opts.jobToken ?? loadJob(jobId)?.jobToken;
12991
+ const paymentOptions = { jobToken, useStoredPolicy: true, mandateReadTimeoutMs: opts.mandateReadTimeoutMs };
12962
12992
  const declined = () => persistLocalState && loadJob(jobId)?.callerDeclined === true;
12963
12993
  async function recordAutoPayment(result, request2, seq) {
12964
12994
  if (result.status === "credited") {
@@ -12987,11 +13017,12 @@ async function streamLoop(opts) {
12987
13017
  let result;
12988
13018
  try {
12989
13019
  result = await handlePaymentRequest(jobId, pending4.request, policy, transport, provider, {
12990
- jobToken,
12991
- requestSeq: pending4.authorization.request_seq,
12992
- useStoredPolicy: true
13020
+ ...paymentOptions,
13021
+ requestSeq: pending4.authorization.request_seq
12993
13022
  });
12994
13023
  } catch (error) {
13024
+ if (error instanceof MandateGuardReadError)
13025
+ return { messages: [], autoPayments, refunds, cursor, nextAction: pollNextAction(jobId) };
12995
13026
  if (error instanceof DvmError && error.code === "payment_already_sent") answeredSeqs.add(pending4.authorization.request_seq);
12996
13027
  else if (error instanceof DvmError && ["payment_settling", "payment_request_not_pending"].includes(error.code))
12997
13028
  return {
@@ -13114,17 +13145,20 @@ async function streamLoop(opts) {
13114
13145
  let result;
13115
13146
  try {
13116
13147
  result = await handlePaymentRequest(jobId, req, activePolicy, transport, provider, {
13117
- jobToken,
13118
- requestSeq: lastYield2.seq,
13119
- useStoredPolicy: true
13148
+ ...paymentOptions,
13149
+ requestSeq: lastYield2.seq
13120
13150
  });
13121
13151
  if (typeof result === "object" && result.status === "credited" && result.credit.ask_open)
13122
13152
  result = await handlePaymentRequest(jobId, req, activePolicy, transport, provider, {
13123
- jobToken,
13124
- requestSeq: lastYield2.seq,
13125
- useStoredPolicy: true
13153
+ ...paymentOptions,
13154
+ requestSeq: lastYield2.seq
13126
13155
  });
13127
13156
  } catch (error) {
13157
+ if (error instanceof MandateGuardReadError) {
13158
+ paymentWaitAction = pollNextAction(jobId);
13159
+ cursor = Math.min(cursor, lastYield2.seq - 1);
13160
+ break;
13161
+ }
13128
13162
  if (error instanceof DvmError && error.code === "payment_credit_choice_required") {
13129
13163
  creditChoiceAction = paymentCreditChoice(jobId, lastYield2.seq, req, false) ?? null;
13130
13164
  cursor = Math.min(cursor, lastYield2.seq - 1);
@@ -13224,7 +13258,7 @@ async function streamLoop(opts) {
13224
13258
  };
13225
13259
  }
13226
13260
  }
13227
- if (paymentUnresolved) nextAction = paymentWaitAction ?? pollNextAction(jobId, paymentInFlightHint(
13261
+ if (paymentWaitAction || paymentUnresolved) nextAction = paymentWaitAction ?? pollNextAction(jobId, paymentInFlightHint(
13228
13262
  jobId,
13229
13263
  heldJob,
13230
13264
  lastYield?.type === "payment-request" ? lastYield.seq : void 0
@@ -13699,21 +13733,40 @@ function paramsToData(params) {
13699
13733
  function jobTokenHeader(jobToken) {
13700
13734
  return jobToken ? { "X-Job-Token": jobToken } : {};
13701
13735
  }
13702
- function messagePollUnreachable(jobId, operation = "fetch messages") {
13736
+ function jobReadUnreachable(jobId, operation = "messages") {
13737
+ if (operation === "status") {
13738
+ const needsSeparator = jobId.startsWith("-");
13739
+ const retryCommand = `dvm status ${needsSeparator ? "-- " : ""}${guidanceJobArg(jobId)}`;
13740
+ const flagPlacement = needsSeparator ? ", with any flags before `--`" : "";
13741
+ return new DvmError(
13742
+ "provider_unreachable",
13743
+ "Could not reach the provider to read job status.",
13744
+ `Retry with \`${retryCommand}\` once the provider is reachable. Keep the same endpoint and job access options${flagPlacement}.`
13745
+ );
13746
+ }
13703
13747
  return new DvmError(
13704
13748
  "provider_unreachable",
13705
- `Could not reach the provider to ${operation} for job ${jobId}.`,
13749
+ `Could not reach the provider to fetch messages for job ${jobId}.`,
13706
13750
  `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
13751
  );
13708
13752
  }
13709
- async function readMessagePollBody(read, jobId, operation) {
13753
+ async function readJobResponse(read, jobId, operation) {
13710
13754
  try {
13711
13755
  return await read();
13712
13756
  } catch (err) {
13713
- if (err instanceof TypeError && !isAbortError(err)) throw messagePollUnreachable(jobId, operation);
13757
+ if (err instanceof TypeError && !isAbortError(err)) throw jobReadUnreachable(jobId, operation);
13714
13758
  throw err;
13715
13759
  }
13716
13760
  }
13761
+ var CreditOperationTimeoutError = class extends DvmError {
13762
+ constructor() {
13763
+ super("timeout", "Credit operation timed out.", "The provider may be starting up. Retry in a few seconds.");
13764
+ }
13765
+ };
13766
+ function rethrowCreditBodyError(err) {
13767
+ if (isAbortError(err)) throw new CreditOperationTimeoutError();
13768
+ throw err;
13769
+ }
13717
13770
  function captureTraceId(res) {
13718
13771
  const tp = res.headers.get("traceparent");
13719
13772
  if (tp) {
@@ -14073,13 +14126,7 @@ var HttpsTransport = class {
14073
14126
  });
14074
14127
  } catch (err) {
14075
14128
  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
- }
14129
+ if (isAbortError(err)) throw new CreditOperationTimeoutError();
14083
14130
  throw new DvmError(
14084
14131
  "provider_unreachable",
14085
14132
  `Could not reach ${url2}: ${err instanceof Error ? err.message : String(err)}`,
@@ -14091,7 +14138,7 @@ var HttpsTransport = class {
14091
14138
  if (!res.ok) {
14092
14139
  const mppChallenges = res.status === 402 && res.headers.get("WWW-Authenticate") ? (await import("./dist-23E7OOCA.js")).Challenge.fromHeadersList(res.headers) : [];
14093
14140
  assertConfiguredTempoChallengeNetwork(mppChallenges, ["charge", "session"]);
14094
- const text = await res.text();
14141
+ const text = await res.text().catch(rethrowCreditBodyError);
14095
14142
  const parsed = parseJsonObject(text);
14096
14143
  const structured = parseStructuredError(text);
14097
14144
  if (structured) {
@@ -14126,7 +14173,7 @@ var HttpsTransport = class {
14126
14173
  `Credit operation failed (${res.status}): ${text}`
14127
14174
  );
14128
14175
  }
14129
- const result = await res.json();
14176
+ const result = await res.json().catch(rethrowCreditBodyError);
14130
14177
  const { menu: rawMenu, funding_receipt: rawFundingReceipt, ...creditResult } = result;
14131
14178
  const menu = parseCreditMenu(rawMenu);
14132
14179
  const x402PaymentResponse = res.headers.get("PAYMENT-RESPONSE") ?? res.headers.get("X-PAYMENT-RESPONSE") ?? void 0;
@@ -14149,7 +14196,7 @@ var HttpsTransport = class {
14149
14196
  const url2 = `${endpoint}/v1/job/${jobId}`;
14150
14197
  const signal = options?.timeoutMs && options.timeoutMs > 0 ? AbortSignal.timeout(options.timeoutMs) : void 0;
14151
14198
  try {
14152
- const res = await readMessagePollBody(() => dvmFetch(url2, { headers: jobTokenHeader(options?.jobToken), signal }), jobId, "read status");
14199
+ const res = await readJobResponse(() => dvmFetch(url2, { headers: jobTokenHeader(options?.jobToken), signal }), jobId, "status");
14153
14200
  captureTraceId(res);
14154
14201
  if (res.status === 404) {
14155
14202
  const storedEndpoint = loadJob(jobId)?.endpoint;
@@ -14159,11 +14206,11 @@ var HttpsTransport = class {
14159
14206
  ));
14160
14207
  }
14161
14208
  if (!res.ok) {
14162
- const credentialErr = jobCredentialError(res.status, await readMessagePollBody(() => res.text(), jobId, "read status"));
14209
+ const credentialErr = jobCredentialError(res.status, await readJobResponse(() => res.text(), jobId, "status"));
14163
14210
  if (credentialErr) throw credentialErr;
14164
- throw new DvmError("provider_error", `Status check failed (${res.status})`);
14211
+ throw jobReadHttpError(res.status, `Status check failed (${res.status})`);
14165
14212
  }
14166
- const data = await readMessagePollBody(() => res.json(), jobId, "read status");
14213
+ const data = await readJobResponse(() => res.json(), jobId, "status");
14167
14214
  return {
14168
14215
  jobId,
14169
14216
  status: data.status,
@@ -14212,15 +14259,15 @@ var HttpsTransport = class {
14212
14259
  });
14213
14260
  } catch (err) {
14214
14261
  if (err instanceof DvmError || isAbortError(err)) throw err;
14215
- throw messagePollUnreachable(jobId);
14262
+ throw jobReadUnreachable(jobId);
14216
14263
  }
14217
14264
  if (!res.ok) {
14218
- const text = await readMessagePollBody(() => res.text(), jobId);
14265
+ const text = await readJobResponse(() => res.text(), jobId);
14219
14266
  const credentialErr = jobCredentialError(res.status, text);
14220
14267
  if (credentialErr) throw credentialErr;
14221
- throw providerResponseError("provider_error", `getMessages failed (${res.status}): ${text}`);
14268
+ throw jobReadHttpError(res.status, `getMessages failed (${res.status}): ${text}`, { message: "provider" });
14222
14269
  }
14223
- const data = await readMessagePollBody(() => res.json(), jobId);
14270
+ const data = await readJobResponse(() => res.json(), jobId);
14224
14271
  return data.messages.map(callerMessageRecognizer(jobId, endpoint));
14225
14272
  } catch (err) {
14226
14273
  if (err instanceof DvmError) throw err;
@@ -14328,20 +14375,20 @@ var HttpsTransport = class {
14328
14375
  throw new DvmError("not_supported", "HTTPS stream requires a provider with an endpoint.");
14329
14376
  }
14330
14377
  const url2 = `${endpoint}/v1/job/${jobId}/messages?after=${afterSeq}`;
14331
- const res = await readMessagePollBody(() => dvmFetch(url2, {
14378
+ const res = await readJobResponse(() => dvmFetch(url2, {
14332
14379
  headers: { Accept: "text/event-stream", ...jobTokenHeader(options?.jobToken) },
14333
14380
  signal: options?.signal
14334
14381
  }), jobId);
14335
14382
  if (!res.ok) {
14336
- const text = await readMessagePollBody(() => res.text(), jobId);
14383
+ const text = await readJobResponse(() => res.text(), jobId);
14337
14384
  const credentialErr = jobCredentialError(res.status, text);
14338
14385
  if (credentialErr) throw credentialErr;
14339
- throw providerResponseError("provider_error", `stream failed (${res.status}): ${text}`);
14386
+ throw jobReadHttpError(res.status, `stream failed (${res.status}): ${text}`, { message: "provider" });
14340
14387
  }
14341
14388
  const contentType = res.headers.get("content-type") ?? "";
14342
14389
  const recognize = callerMessageRecognizer(jobId, endpoint);
14343
14390
  if (contentType.includes("application/json")) {
14344
- const body = await readMessagePollBody(() => res.json(), jobId);
14391
+ const body = await readJobResponse(() => res.json(), jobId);
14345
14392
  const messages2 = (body.messages ?? []).map(recognize);
14346
14393
  const last = messages2.at(-1);
14347
14394
  const reason = last?.type === "complete" ? "complete" : last?.type === "cancel" ? "cancel" : "yield";
@@ -15429,7 +15476,7 @@ async function settleCreditAfterJob(args) {
15429
15476
  }
15430
15477
  }
15431
15478
  if (args.allowTopup !== false) {
15432
- const refill = args.refillPocket ?? (await import("./pocket-refill-OX3WXUZ4.js")).refillPocketIfLow;
15479
+ const refill = args.refillPocket ?? (await import("./pocket-refill-TF7M2XCZ.js")).refillPocketIfLow;
15433
15480
  await refill({ human: args.human }).catch(() => void 0);
15434
15481
  }
15435
15482
  }
@@ -16057,10 +16104,7 @@ async function configReset(opts) {
16057
16104
  // and to `CONNECTED_RAILS`, a blanket grant turns the refusal that would
16058
16105
  // have caught it into a silent credential removal. Without one this fails
16059
16106
  // 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"],
16107
+ preservePin: true,
16064
16108
  patch: (current) => {
16065
16109
  if (current) assertNoConnectedRails(current);
16066
16110
  cleared = planConfigReset(current ?? {}).clear;
@@ -16223,14 +16267,14 @@ async function confirmRollback(stored, preview, opts) {
16223
16267
  async function withStrandingChecked(removing, commit) {
16224
16268
  const leaving = new Set(removing.map((target) => target.split(".")[0]));
16225
16269
  if (leaving.has("tempo")) {
16226
- const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-BOW6OFSI.js");
16270
+ const { assertTempoWalletIdle: assertTempoWalletIdle2 } = await import("./tempo-lifecycle-7EYW5W5Z.js");
16227
16271
  await assertTempoWalletIdle2("disconnect");
16228
16272
  }
16229
16273
  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");
16274
+ const { withX402ChannelLock: withX402ChannelLock2, listPendingX402Fundings: listPendingX402Fundings2, x402PendingUnsettled: x402PendingUnsettled2 } = await import("./internal-EVD5WVAK.js");
16275
+ const { assertX402WalletIdle: assertX402WalletIdle2 } = await import("./lifecycle-GR7WGYVQ.js");
16276
+ const { ensureAddress: ensureAddress2 } = await import("./internal-EVD5WVAK.js");
16277
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RIHHIQRK.js");
16234
16278
  return withX402ChannelLock2(async () => {
16235
16279
  const unsettled = listPendingX402Fundings2().filter((entry) => x402PendingUnsettled2(entry));
16236
16280
  if (unsettled.length > 0) {
@@ -19873,6 +19917,30 @@ async function runCreditDrain(dvm, opts) {
19873
19917
  });
19874
19918
  }
19875
19919
  const signCredit = (body) => signDvmRequestData(signer.privkey, body, authDomain);
19920
+ const postDrain = async (body, payment) => {
19921
+ try {
19922
+ return await creditOp(transport, endpoint, body, payment);
19923
+ } catch (err) {
19924
+ if (!(err instanceof CreditOperationTimeoutError)) throw err;
19925
+ const address = !channelBacked && drain.payout.address;
19926
+ const command = [
19927
+ creditDrainCommand(endpoint, creditId),
19928
+ "--drain-id",
19929
+ shellQuoteArg(drain.drainId),
19930
+ "--method",
19931
+ shellQuoteArg(drain.method),
19932
+ ...address ? ["--address", shellQuoteArg(address)] : [],
19933
+ ..."name" in signer.source ? ["--as", shellQuoteArg(signer.source.name)] : []
19934
+ ].join(" ");
19935
+ const identityHint = signer.source.kind === "env" ? " Keep the same DVM_IDENTITY_KEY." : "";
19936
+ throw new DvmError(
19937
+ "drain_outcome_unknown",
19938
+ `The response for drain ${drain.drainId} timed out. The refund outcome is unknown.`,
19939
+ `Retry with the same drain ID using \`${command}\`.${identityHint}`,
19940
+ { status: "unknown", retryable: true, credit_id: creditId, drain_id: drain.drainId, next_command: command }
19941
+ );
19942
+ }
19943
+ };
19876
19944
  let result;
19877
19945
  let anchorRead = { reachable: false };
19878
19946
  let x402AtRisk;
@@ -19911,7 +19979,7 @@ async function runCreditDrain(dvm, opts) {
19911
19979
  mppAtRiskMicro = authorized < deposit ? authorized : deposit;
19912
19980
  if (!drain.mppCredential) {
19913
19981
  try {
19914
- return await creditOp(transport, endpoint, body);
19982
+ return await postDrain(body);
19915
19983
  } catch (err) {
19916
19984
  const challenge = tempoSessionChallenge(err);
19917
19985
  if (!challenge) throw err;
@@ -19923,11 +19991,11 @@ async function runCreditDrain(dvm, opts) {
19923
19991
  });
19924
19992
  drain = { ...drain, mppCredential: credential };
19925
19993
  recordPendingDrain(endpoint, signer.pubkey, drain, ...identityArg);
19926
- return creditOp(transport, endpoint, body, { mppCredentialRaw: credential });
19994
+ return postDrain(body, { mppCredentialRaw: credential });
19927
19995
  }
19928
19996
  }
19929
19997
  try {
19930
- return await creditOp(transport, endpoint, body, {
19998
+ return await postDrain(body, {
19931
19999
  mppCredentialRaw: drain.mppCredential
19932
20000
  });
19933
20001
  } catch (err) {
@@ -19944,7 +20012,7 @@ async function runCreditDrain(dvm, opts) {
19944
20012
  drain = { ...drain, mppCredential: credential };
19945
20013
  recordPendingDrain(endpoint, signer.pubkey, drain, ...identityArg);
19946
20014
  const refreshedBody = signCredit(unsignedBody());
19947
- return creditOp(transport, endpoint, refreshedBody, {
20015
+ return postDrain(refreshedBody, {
19948
20016
  mppCredentialRaw: credential
19949
20017
  });
19950
20018
  }
@@ -19965,9 +20033,7 @@ async function runCreditDrain(dvm, opts) {
19965
20033
  callerPubkey: signer.pubkey,
19966
20034
  creditId,
19967
20035
  depositMicro: Math.max(stored?.targetMicro ?? 0, 1),
19968
- post: (paymentHeader) => creditOp(
19969
- transport,
19970
- endpoint,
20036
+ post: (paymentHeader) => postDrain(
19971
20037
  signCredit(unsignedBody()),
19972
20038
  paymentHeader ? { x402Payment: paymentHeader, x402Version: 2 } : void 0
19973
20039
  )
@@ -19979,7 +20045,7 @@ async function runCreditDrain(dvm, opts) {
19979
20045
  result = await closeChannel();
19980
20046
  } else {
19981
20047
  try {
19982
- result = await creditOp(transport, endpoint, signCredit(unsignedBody()));
20048
+ result = await postDrain(signCredit(unsignedBody()));
19983
20049
  } catch (err) {
19984
20050
  if (!(err instanceof DvmError) || !x402RequiredFromError(err)) throw err;
19985
20051
  drain = { ...drain, payout: {} };
@@ -19990,7 +20056,7 @@ async function runCreditDrain(dvm, opts) {
19990
20056
  } else if (drain.method === "stripe") {
19991
20057
  const card = await postCardDrain({
19992
20058
  drainId: () => drain.drainId,
19993
- post: () => creditOp(transport, endpoint, signCredit(unsignedBody())),
20059
+ post: () => postDrain(signCredit(unsignedBody())),
19994
20060
  adopt: (blocking) => {
19995
20061
  clearPendingDrain(endpoint, signer.pubkey, drain, ...identityArg);
19996
20062
  drain = { ...drain, drainId: blocking, creditId };
@@ -20000,7 +20066,7 @@ async function runCreditDrain(dvm, opts) {
20000
20066
  result = card.result;
20001
20067
  cardAdoptedFrom = card.adoptedFrom;
20002
20068
  } else {
20003
- result = await creditOp(transport, endpoint, signCredit(unsignedBody()));
20069
+ result = await postDrain(signCredit(unsignedBody()));
20004
20070
  }
20005
20071
  if (result.drain?.receipts.length) {
20006
20072
  anchorRead = await fetchTrustAnchor(transport, { endpoint });
@@ -23009,8 +23075,8 @@ async function probeX402(x402, timeoutMs) {
23009
23075
  let network;
23010
23076
  let address;
23011
23077
  try {
23012
- const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-CZV4TOJ3.js");
23013
- const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-TUEXUURQ.js");
23078
+ const { loadX402Wallet: loadX402Wallet2 } = await import("./wallet-RIHHIQRK.js");
23079
+ const { getX402Balance, ensureAddress: ensureAddress2, usdcContractByCaip2 } = await import("./internal-EVD5WVAK.js");
23014
23080
  const wallet = loadX402Wallet2();
23015
23081
  if (!wallet) {
23016
23082
  const storedKey = x402.privateKey;
@@ -23062,8 +23128,8 @@ async function probeMpp(mpp, timeoutMs) {
23062
23128
  if (!mpp) return null;
23063
23129
  if (mpp.method === "tempo") {
23064
23130
  try {
23065
- const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-D424H37T.js");
23066
- const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-TUEXUURQ.js");
23131
+ const { connectedTempoAccount: connectedTempoAccount2 } = await import("./tempo-wallet-QOC3BHVE.js");
23132
+ const { getTempoUsdcBalance: getTempoUsdcBalance3, resolveTempoNetwork: resolveTempoNetwork2 } = await import("./internal-EVD5WVAK.js");
23067
23133
  const account = await connectedTempoAccount2();
23068
23134
  if (!account) {
23069
23135
  return {
@@ -26537,7 +26603,7 @@ function paymentAmount(msg) {
26537
26603
  }
26538
26604
  return formatAmountBestEffort(msg.content.amount_msats);
26539
26605
  }
26540
- function formatMessageHuman(msg, jobId, artifactSession) {
26606
+ function formatMessageHuman(msg, jobId, artifactSession, mandateReport) {
26541
26607
  const { seq, type } = msg;
26542
26608
  const prefix = msg.from === "provider" ? "Provider" : "You";
26543
26609
  if (msg.type !== "progress") finalizeProgressLine();
@@ -26579,15 +26645,10 @@ function formatMessageHuman(msg, jobId, artifactSession) {
26579
26645
  );
26580
26646
  break;
26581
26647
  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
- }
26648
+ const report = mandateReport ?? readMandatePaymentReport(msg, jobId);
26649
+ if (report) {
26650
+ info(`[${msg.seq}] ${report.display}`);
26651
+ break;
26591
26652
  }
26592
26653
  const amount = paymentAmount(msg);
26593
26654
  if (msg.from === "provider") {
@@ -26696,19 +26757,21 @@ function createWaitPaymentLines(opts) {
26696
26757
  if (booking.jobId === opts.jobId && booking.approval === "auto") write(bookedPayment(booking), booking.requestSeq);
26697
26758
  }) : () => void 0;
26698
26759
  return {
26699
- onMessage(message2) {
26700
- opts.onMessage?.(message2);
26701
- emitted.add(message2.seq);
26760
+ onMessage(message2, fullHistoryThrough) {
26702
26761
  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
- }
26762
+ const useLocalState = opts.persistLocalState !== false;
26763
+ const payment = mandateCredit(message2) ? mandatePaymentReports(
26764
+ useLocalState ? loadJob(opts.jobId) : void 0,
26765
+ useLocalState ? [...observed, ...loadMessages(opts.jobId)] : observed,
26766
+ fullHistoryThrough
26767
+ ).find((entry) => entry.seq === message2.seq) : void 0;
26768
+ opts.onMessage?.(message2, payment);
26769
+ emitted.add(message2.seq);
26770
+ if (useLocalState && payment) write({
26771
+ ...payment,
26772
+ rail: "credit",
26773
+ reason: { _source: "provider", text: "" }
26774
+ }, payment.request_seq, true);
26712
26775
  const pending4 = waiting.get(message2.seq);
26713
26776
  if (pending4) write(pending4, message2.seq);
26714
26777
  },
@@ -26742,12 +26805,12 @@ async function waitForJob(opts, durationMs, now = Date.now) {
26742
26805
  if (!opts.onAutoPayment) return waitAttached(opts, durationMs, now);
26743
26806
  const payments = createWaitPaymentLines(opts);
26744
26807
  try {
26745
- return await waitAttached({ ...opts, onMessage: payments.onMessage, onAutoPayment: payments.onAutoPayment }, durationMs, now);
26808
+ return await waitAttached({ ...opts, onAutoPayment: payments.onAutoPayment }, durationMs, now, payments);
26746
26809
  } finally {
26747
26810
  payments.finish();
26748
26811
  }
26749
26812
  }
26750
- async function waitAttached(opts, durationMs, now) {
26813
+ async function waitAttached(opts, durationMs, now, payments) {
26751
26814
  const deadline = now() + durationMs;
26752
26815
  const result = {
26753
26816
  messages: [],
@@ -26767,7 +26830,8 @@ async function waitAttached(opts, durationMs, now) {
26767
26830
  const onMessage = (message2) => {
26768
26831
  if (emittedSeqs.has(message2.seq)) return;
26769
26832
  emittedSeqs.add(message2.seq);
26770
- opts.onMessage?.(message2);
26833
+ if (payments) payments.onMessage(message2, result.fullHistoryThrough);
26834
+ else opts.onMessage?.(message2);
26771
26835
  };
26772
26836
  const messageAppendSession = opts.persistLocalState === false ? void 0 : opts.messageAppendSession ?? createMessageAppendSession(opts.jobId);
26773
26837
  let backoffMs = 1e3;
@@ -26797,13 +26861,15 @@ async function waitAttached(opts, durationMs, now) {
26797
26861
  result.nextAction = null;
26798
26862
  const history = await readWithRetry(() => opts.transport.getMessages(opts.jobId, result.cursor, opts.provider, readOptions()));
26799
26863
  if (!history) break;
26800
- const tail = history.filter((message2) => message2.seq > result.cursor);
26864
+ if (result.cursor === 0 && snapshot.content_available !== false)
26865
+ result.fullHistoryThrough = maxSeq(history, 0);
26866
+ const tail = history.filter((message2) => message2.seq > result.cursor).sort((a, b) => a.seq - b.seq);
26801
26867
  collectMessages(tail);
26802
26868
  result.cursor = maxSeq(tail, result.cursor);
26803
26869
  for (const message2 of tail) onMessage(message2);
26804
26870
  if (opts.persistLocalState !== false) {
26805
26871
  messageAppendSession?.append(tail);
26806
- await settleRecordedPayments(opts.jobId);
26872
+ await settleRecordedPayments(opts.jobId, result.fullHistoryThrough);
26807
26873
  result.refunds.push(...await claimInboundPayments(opts.jobId, tail));
26808
26874
  }
26809
26875
  result.nextAction = withRefundNextAction(opts.jobId, null, result.refunds);
@@ -26842,7 +26908,9 @@ async function waitAttached(opts, durationMs, now) {
26842
26908
  }
26843
26909
  if (!history) break;
26844
26910
  messageAppendSession?.append(history);
26845
- if (opts.persistLocalState !== false) await settleRecordedPayments(opts.jobId);
26911
+ if (messageAppendSession && snapshot.content_available !== false)
26912
+ result.fullHistoryThrough = maxSeq(history, 0);
26913
+ if (opts.persistLocalState !== false) await settleRecordedPayments(opts.jobId, result.fullHistoryThrough);
26846
26914
  const answered = opts.persistLocalState === false ? /* @__PURE__ */ new Set() : loadAnsweredYieldSeqs(opts.jobId);
26847
26915
  for (const seq of answeredYieldSeqs(history)) answered.add(seq);
26848
26916
  const pending4 = history.findLast((msg) => msg.from === "provider" && ["prompt", "payment-request", "working", "complete", "cancel"].includes(msg.type) && !answered.has(msg.seq));
@@ -26876,7 +26944,8 @@ async function waitAttached(opts, durationMs, now) {
26876
26944
  messageAppendSession,
26877
26945
  afterSeq: streamAfter,
26878
26946
  retryUnreachableReads: true,
26879
- timeoutMs: readOptions().timeoutMs
26947
+ timeoutMs: readOptions().timeoutMs,
26948
+ mandateReadTimeoutMs: () => Math.min(idleTimeoutMs, deadline - now())
26880
26949
  });
26881
26950
  collectMessages(next.messages);
26882
26951
  result.autoPayments.push(...next.autoPayments);
@@ -26931,6 +27000,24 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
26931
27000
  const artifactSession = opts.human ? createArtifactSaveSession() : void 0;
26932
27001
  const { stored, ref, jobToken } = access;
26933
27002
  const json3 = (data) => providerJobJson(data, !!stored);
27003
+ function mandateOutput(batch, fullHistoryThrough) {
27004
+ const bySeq = /* @__PURE__ */ new Map();
27005
+ if ((opts.human || access.endpointOverridden) && !batch.some(mandateCredit)) return { summary: {}, bySeq };
27006
+ const summary = mandatePaymentSummary(
27007
+ access.endpointOverridden ? void 0 : loadJob(jobId),
27008
+ access.endpointOverridden ? batch : [...batch, ...loadMessages(jobId)],
27009
+ fullHistoryThrough
27010
+ );
27011
+ for (const report of summary.mandate_payments ?? []) bySeq.set(report.seq, report);
27012
+ if (access.endpointOverridden && !opts.wait) return { summary: {}, bySeq };
27013
+ if (access.endpointOverridden && summary.mandate_payments) {
27014
+ summary.mandate_payments = summary.mandate_payments.map((report) => providerFields({
27015
+ ...report,
27016
+ amount: providerFields(report.amount, ["amount_micro", "currency"])
27017
+ }, ["seq", "request_seq", "amount_msats"]));
27018
+ }
27019
+ return { summary, bySeq };
27020
+ }
26934
27021
  function actionFromMessages(batch) {
26935
27022
  return readNextAction(jobId, batch, { ignoreLocalState: access.endpointOverridden, context: stored ?? void 0 });
26936
27023
  }
@@ -26972,13 +27059,12 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
26972
27059
  }
26973
27060
  throw err;
26974
27061
  }
26975
- if (!access.endpointOverridden) {
26976
- appendMessages(jobId, msgs);
26977
- await settleRecordedPayments(jobId);
26978
- }
27062
+ if (!access.endpointOverridden) appendMessages(jobId, msgs);
26979
27063
  const newCursor = maxSeq(msgs, after);
26980
27064
  const providerStatus2 = await observeJobContent(jobId, transport, ref, { timeoutMs: timeout, jobToken });
27065
+ const fullHistoryThrough = after === 0 && providerStatus2?.content_available !== false ? newCursor : void 0;
26981
27066
  if (!access.endpointOverridden) {
27067
+ await settleRecordedPayments(jobId, fullHistoryThrough);
26982
27068
  persistStreamOutcome({ jobId, messages: msgs, cursor: newCursor, afterSeq: after, providerStatus: providerStatus2 });
26983
27069
  }
26984
27070
  const refunds = access.endpointOverridden ? [] : await claimInboundPayments(jobId, msgs);
@@ -26994,6 +27080,7 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
26994
27080
  timeoutMs: timeout
26995
27081
  });
26996
27082
  transport.close();
27083
+ const mandate2 = mandateOutput(msgs, fullHistoryThrough);
26997
27084
  if (opts.human) {
26998
27085
  renderSettlementHuman(settlement2);
26999
27086
  if (unanswered2) info(unanswered2.display);
@@ -27002,7 +27089,7 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27002
27089
  info("No new messages.");
27003
27090
  } else {
27004
27091
  for (const msg of msgs) {
27005
- formatMessageHuman(msg, jobId, artifactSession);
27092
+ formatMessageHuman(msg, jobId, artifactSession, mandate2.bySeq.get(msg.seq));
27006
27093
  }
27007
27094
  finalizeProgressLine();
27008
27095
  }
@@ -27012,9 +27099,9 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27012
27099
  jobId,
27013
27100
  ...content2,
27014
27101
  ...settlement2,
27015
- ...!access.endpointOverridden ? mandatePaymentSummary(loadJob(jobId), loadMessages(jobId)) : {},
27102
+ ...mandate2.summary,
27016
27103
  ...unanswered2 ? { unanswered_payment_request: unanswered2 } : {},
27017
- messages: msgs.map((msg) => serialize(msg, access.endpointOverridden ? void 0 : jobId)),
27104
+ messages: msgs.map((msg) => serialize(msg, mandate2.bySeq.get(msg.seq))),
27018
27105
  cursor: newCursor,
27019
27106
  next_action: resolvedAction2,
27020
27107
  ...await refundJsonField(refunds)
@@ -27046,9 +27133,9 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27046
27133
  }
27047
27134
  },
27048
27135
  ...streamEvents && {
27049
- onMessage: (msg) => {
27136
+ onMessage: (msg, mandateReport) => {
27050
27137
  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) });
27138
+ jsonEvent({ event: "message", ...serialize(msg, mandateReport) });
27052
27139
  messageLines++;
27053
27140
  lastDelivered = Math.max(lastDelivered, msg.seq);
27054
27141
  },
@@ -27077,6 +27164,25 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27077
27164
  timeoutMs: waitDeadline === void 0 ? opts.timeout ? Number(opts.timeout) * 1e3 : 5e3 : Math.max(1, Math.min(streamOptions.timeoutMs, waitDeadline - Date.now())),
27078
27165
  jobToken
27079
27166
  });
27167
+ const observed = providerStatus ?? result.providerStatus;
27168
+ let mandate = mandateOutput(result.messages, result.fullHistoryThrough);
27169
+ 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)) {
27170
+ const remainingMs = waitDeadline - Date.now();
27171
+ if (remainingMs > 0) {
27172
+ const history = await transport.getMessages(jobId, 0, ref, {
27173
+ timeoutMs: Math.min(streamOptions.timeoutMs, remainingMs),
27174
+ jobToken
27175
+ }).catch(() => void 0);
27176
+ if (history) {
27177
+ const fullHistoryThrough = Math.max(result.fullHistoryThrough ?? 0, maxSeq(history, 0));
27178
+ if (!access.endpointOverridden) {
27179
+ appendMessages(jobId, history);
27180
+ await settleRecordedPayments(jobId, fullHistoryThrough);
27181
+ }
27182
+ mandate = mandateOutput([...history, ...result.messages], fullHistoryThrough);
27183
+ }
27184
+ }
27185
+ }
27080
27186
  if (!access.endpointOverridden) {
27081
27187
  persistStreamOutcome({
27082
27188
  jobId,
@@ -27088,7 +27194,6 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27088
27194
  }
27089
27195
  const content = jobContentFields(jobId, providerStatus, opts.human);
27090
27196
  const resolvedAction = await resolveNextAction2(result.nextAction, result.messages, providerStatus?.status ?? result.providerStatus?.status);
27091
- const observed = providerStatus ?? result.providerStatus;
27092
27197
  const currency = access.endpointOverridden ? await providerCurrency({ receipt: observed?.receipt, status: observed, messages: result.messages, transport, ref }) : void 0;
27093
27198
  const settlement = await observedSettlementFields(jobId, observed, !access.endpointOverridden, currency);
27094
27199
  const unanswered = await readUnansweredPaymentRequest(jobId, observed?.status ?? (access.endpointOverridden ? void 0 : loadJob(jobId)?.status), access, transport, {
@@ -27107,7 +27212,7 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27107
27212
  } else {
27108
27213
  for (const msg of result.messages) {
27109
27214
  if (msg.type === "progress") continue;
27110
- formatMessageHuman(msg, jobId, artifactSession);
27215
+ formatMessageHuman(msg, jobId, artifactSession, mandate.bySeq.get(msg.seq));
27111
27216
  }
27112
27217
  finalizeProgressLine();
27113
27218
  }
@@ -27118,7 +27223,7 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27118
27223
  jobId,
27119
27224
  ...content,
27120
27225
  ...settlement,
27121
- ...!access.endpointOverridden ? mandatePaymentSummary(loadJob(jobId), loadMessages(jobId)) : {},
27226
+ ...mandate.summary,
27122
27227
  ...unanswered ? { unanswered_payment_request: unanswered } : {},
27123
27228
  message_count: messageLines,
27124
27229
  auto_payment_count: paymentLines,
@@ -27131,9 +27236,9 @@ async function messagesWithAccess(jobId, opts, access, waitDuration) {
27131
27236
  jobId,
27132
27237
  ...content,
27133
27238
  ...settlement,
27134
- ...!access.endpointOverridden ? mandatePaymentSummary(loadJob(jobId), loadMessages(jobId)) : {},
27239
+ ...mandate.summary,
27135
27240
  ...unanswered ? { unanswered_payment_request: unanswered } : {},
27136
- messages: result.messages.map((msg) => serialize(msg, access.endpointOverridden ? void 0 : jobId)),
27241
+ messages: result.messages.map((msg) => serialize(msg, mandate.bySeq.get(msg.seq))),
27137
27242
  cursor: result.cursor,
27138
27243
  next_action: resolvedAction,
27139
27244
  ...result.autoPayments.length > 0 ? { auto_payments: result.autoPayments } : {},
@@ -27145,9 +27250,9 @@ function serializeMessageForOutput(msg) {
27145
27250
  return serialize(msg);
27146
27251
  }
27147
27252
  function serializeJobMessageForOutput(msg, jobId) {
27148
- return serialize(msg, jobId);
27253
+ return serialize(msg, readMandatePaymentReport(msg, jobId));
27149
27254
  }
27150
- function serialize(msg, jobId) {
27255
+ function serialize(msg, mandateReport) {
27151
27256
  const fromProvider = !isCallerMessage(msg);
27152
27257
  const base = providerFields(
27153
27258
  { seq: msg.seq, from: msg.from, timestamp: msg.timestamp, type: msg.type, content: msg.content },
@@ -27197,13 +27302,8 @@ function serialize(msg, jobId) {
27197
27302
  };
27198
27303
  }
27199
27304
  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
- }
27305
+ const report = mandateReport ?? readMandatePaymentReport(msg);
27306
+ if (report) return { ...base, ...report, content: { ...msg.content } };
27207
27307
  const amount = paymentAmount(msg);
27208
27308
  const display = msg.from === "provider" ? `${msg.content.reason === "change" ? "Change" : "Refund"} sent: ${amount}` : `Payment sent: ${amount}`;
27209
27309
  return { ...base, content: { ...msg.content }, display };
@@ -32403,7 +32503,7 @@ async function statusWithAccess(jobId, opts, access) {
32403
32503
  msgs = await transport.getMessages(jobId, after, ref, { timeoutMs: timeout, jobToken });
32404
32504
  if (!access.endpointOverridden) {
32405
32505
  appendMessages(jobId, msgs);
32406
- await settleRecordedPayments(jobId);
32506
+ await settleRecordedPayments(jobId, after === 0 && result.content_available !== false ? maxSeq(msgs, 0) : void 0);
32407
32507
  }
32408
32508
  if (opts.messages) newCursor = maxSeq(msgs, after);
32409
32509
  }
@@ -35093,6 +35193,75 @@ function examples(fetcher) {
35093
35193
  return parts.join(", ");
35094
35194
  }
35095
35195
 
35196
+ // src/lib/wallet-agent/collect.ts
35197
+ import { setTimeout as sleepFor } from "timers/promises";
35198
+ var POLL_INTERVAL_MS = 2e3;
35199
+ var PRE_EXPIRY_POLL_LEAD_MS = 500;
35200
+ var EXPIRY_MARGIN_MS = 5e3;
35201
+ var MAX_TIMER_MS2 = 2147483647;
35202
+ async function collectPendingMint(entry, cashuWallet, durationMs) {
35203
+ const start = Date.now();
35204
+ const expiry = entry.expires_at === void 0 ? Infinity : entry.expires_at * 1e3;
35205
+ const durationDeadline = start + durationMs;
35206
+ const pollUntil = Math.min(expiry, durationDeadline);
35207
+ const deadline = Math.min(expiry + EXPIRY_MARGIN_MS, durationDeadline);
35208
+ const elapsedReason = expiry <= durationDeadline ? "quote_expired" : "duration_elapsed";
35209
+ if (expiry <= start) return { kind: "stopped", reason: "quote_expired" };
35210
+ const preExpiryPollAt = expiry <= durationDeadline ? expiry - PRE_EXPIRY_POLL_LEAD_MS : pollUntil;
35211
+ const retryState = createMintQuoteRetryState();
35212
+ try {
35213
+ let startedAt = Date.now();
35214
+ while (startedAt < deadline) {
35215
+ const catchUp = startedAt >= pollUntil;
35216
+ const checkDeadline = catchUp ? deadline : pollUntil;
35217
+ const signal = AbortSignal.timeout(Math.min(MAX_TIMER_MS2, deadline - startedAt));
35218
+ ba({ signal });
35219
+ const outcome = await retryMintQuoteOperation(async () => {
35220
+ const pass = await reconcilePendingMint(entry, {
35221
+ getWalletForMint: async () => cashuWallet,
35222
+ pollDeadlineMs: checkDeadline,
35223
+ quoteRetryTimeoutMs: Math.max(0, checkDeadline - Date.now()),
35224
+ deadlineMs: deadline
35225
+ });
35226
+ if (pass.kind === "error") throw pass.cause;
35227
+ return pass;
35228
+ }, { deadlineMs: checkDeadline, quoteId: entry.quote_id, state: retryState }).catch(() => void 0);
35229
+ if (!outcome) {
35230
+ return { kind: "stopped", reason: Date.now() >= pollUntil ? elapsedReason : "mint_unavailable" };
35231
+ }
35232
+ switch (outcome.kind) {
35233
+ case "minted":
35234
+ case "restored":
35235
+ return { kind: "collected", proofs: outcome.proofs };
35236
+ case "already_issued":
35237
+ return { kind: "already_issued" };
35238
+ case "no_longer_pending": {
35239
+ if (Date.now() >= checkDeadline) return { kind: "stopped", reason: "no_longer_pending" };
35240
+ const quote2 = await cashuWallet.checkMintQuoteBolt11(entry.quote_id).catch(() => void 0);
35241
+ return quote2?.state === sa.ISSUED ? { kind: "already_issued" } : { kind: "stopped", reason: "no_longer_pending" };
35242
+ }
35243
+ case "expired":
35244
+ return { kind: "stopped", reason: "quote_expired" };
35245
+ case "paid_refused":
35246
+ return { kind: "stopped", reason: "paid_uncollected" };
35247
+ case "still_pending":
35248
+ case "busy": {
35249
+ if (catchUp) return { kind: "stopped", reason: elapsedReason };
35250
+ const now = Date.now();
35251
+ const nextCheck = outcome.kind === "busy" ? Math.min(pollUntil, now + 100) : startedAt >= preExpiryPollAt ? pollUntil : Math.min(preExpiryPollAt, now + POLL_INTERVAL_MS);
35252
+ const delay = nextCheck - now;
35253
+ if (delay > 0) await sleepFor(delay);
35254
+ break;
35255
+ }
35256
+ }
35257
+ startedAt = Date.now();
35258
+ }
35259
+ return { kind: "stopped", reason: elapsedReason };
35260
+ } finally {
35261
+ ba({});
35262
+ }
35263
+ }
35264
+
35096
35265
  // src/lib/error-handler.ts
35097
35266
  import { readFileSync as readFileSync11 } from "fs";
35098
35267
  import { dirname as dirname4, isAbsolute as isAbsolute2, join as join12, relative as relative2, sep as sep3 } from "path";
@@ -35807,10 +35976,10 @@ var NON_FUNGIBLE_MINT_NOTE = "Balances are per-mint: each mint is a separate cus
35807
35976
  async function walletFund(amount, opts) {
35808
35977
  const rail = (opts.rail ?? "cashu").toLowerCase();
35809
35978
  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) {
35979
+ if (opts.mint !== void 0 || opts.timeout !== void 0 || opts.sats || opts.testSkipLightning || opts.float === false || opts.wait === false || opts.collectFor !== void 0) {
35811
35980
  throw new DvmError(
35812
35981
  "invalid_flags_for_rail",
35813
- "--mint, --timeout, --sats, --test-skip-lightning, --no-float, and --no-wait only apply to --rail cashu.",
35982
+ "--mint, --timeout, --sats, --test-skip-lightning, --no-float, --no-wait, and --collect-for only apply to --rail cashu.",
35814
35983
  `Drop these flags when running \`dvm wallet fund --rail ${rail}\`.`
35815
35984
  );
35816
35985
  }
@@ -35825,6 +35994,16 @@ async function walletFund(amount, opts) {
35825
35994
  "Supported rails: cashu (default), tempo, x402."
35826
35995
  );
35827
35996
  }
35997
+ let collectForMs;
35998
+ if (opts.collectFor !== void 0) {
35999
+ if (opts.wait !== false) {
36000
+ throw new DvmError("invalid_fund_options", "--collect-for requires --no-wait.");
36001
+ }
36002
+ collectForMs = parseDurationMs(opts.collectFor);
36003
+ if (collectForMs === 0) {
36004
+ throw new DvmError("invalid_arguments", "--collect-for requires a positive duration, such as 30s or 2m.");
36005
+ }
36006
+ }
35828
36007
  if (opts.wait === false && opts.testSkipLightning) {
35829
36008
  throw new DvmError(
35830
36009
  "invalid_fund_options",
@@ -35849,6 +36028,7 @@ async function walletFund(amount, opts) {
35849
36028
  "Run `dvm wallet init` first to generate a lock keypair."
35850
36029
  );
35851
36030
  }
36031
+ const lockPubkey = wallet.lock_pubkey;
35852
36032
  const sweep = await reconcilePendingMints();
35853
36033
  const meltSweep = await reconcilePendingMelts().catch(emptyMeltSweep);
35854
36034
  const funding = effectiveFundingMint(wallet.mints);
@@ -35936,7 +36116,7 @@ async function walletFund(amount, opts) {
35936
36116
  if (opts.wait === false) {
35937
36117
  info(`Quote ID: ${quote2.quote}`);
35938
36118
  if (expiresAt) info(`Invoice expires: ${expiresAt}`);
35939
- info("After payment, run `dvm wallet show` to collect the sats and check the new balance.");
36119
+ 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
36120
  info(` \u21B3 ${collectDeadlineHint(expiresAt)}`);
35941
36121
  } else {
35942
36122
  info(
@@ -35959,6 +36139,7 @@ async function walletFund(amount, opts) {
35959
36139
  relay: { copy_text: invoice, standalone: true },
35960
36140
  expires_at: expiresAt,
35961
36141
  ...opts.wait === false ? { collect_before: expiresAt } : {},
36142
+ ...collectForMs === void 0 ? {} : { collection_state: "waiting" },
35962
36143
  lock_pubkey: wallet.lock_pubkey,
35963
36144
  display: `Pay ${sats} sats to the Lightning invoice to fund ${amountPhrase} into the agent wallet at ${mintUrl} (${selectionPhrase}). Scannable QR at ${qrImagePath}.`,
35964
36145
  ...opts.wait === false ? {
@@ -35967,13 +36148,27 @@ async function walletFund(amount, opts) {
35967
36148
  sweep: summarizeSweep(sweep),
35968
36149
  melt_sweep: summarizeMeltSweep(meltSweep)
35969
36150
  } : {},
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."
36151
+ 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
36152
  });
35972
36153
  }
35973
36154
  };
35974
36155
  if (opts.wait === false) {
35975
- const { quote: quote2 } = await createPendingMintQuote(sats, { mintUrl });
36156
+ const { quote: quote2, pending: pending4, cashuWallet } = await createPendingMintQuote(sats, { mintUrl });
35976
36157
  await onInvoice(quote2.request, quote2);
36158
+ if (collectForMs !== void 0) {
36159
+ const outcome = await collectPendingMint(pending4, cashuWallet, collectForMs);
36160
+ if (outcome.kind === "collected") {
36161
+ reportMinted({
36162
+ mint: mintUrl,
36163
+ amount_sats: sats,
36164
+ quote_id: quote2.quote,
36165
+ denominations: outcome.proofs.map((proof) => proof.amount),
36166
+ proofs: outcome.proofs
36167
+ });
36168
+ } else {
36169
+ reportCollectionOutcome(pending4, outcome, human);
36170
+ }
36171
+ }
35977
36172
  return;
35978
36173
  }
35979
36174
  const result = await fundWithRecoverableWait(sats, {
@@ -36036,31 +36231,62 @@ async function walletFund(amount, opts) {
36036
36231
  },
36037
36232
  onInvoice
36038
36233
  });
36039
- const totalProofSats = result.proofs.reduce((sum, p) => sum + p.amount, 0);
36234
+ reportMinted(result);
36235
+ function reportMinted(result2) {
36236
+ const totalProofSats = result2.proofs.reduce((sum, p) => sum + p.amount, 0);
36237
+ if (human) {
36238
+ info("");
36239
+ info(
36240
+ `Minted ${totalProofSats} sats at ${mintUrl} (${selectionPhrase}) across ${result2.proofs.length} P2PK-locked proofs.`
36241
+ );
36242
+ info(`Smart denomination split: ${formatDenominations(result2.denominations)}.`);
36243
+ info(`Locked to lock pubkey: ${lockPubkey}`);
36244
+ } else {
36245
+ json({
36246
+ status: "minted",
36247
+ mint: mintUrl,
36248
+ mint_selection: mintSelection,
36249
+ amount_sats: sats,
36250
+ ...amountSourceFields(amt),
36251
+ sats_minted: totalProofSats,
36252
+ proof_count: result2.proofs.length,
36253
+ denominations: result2.denominations,
36254
+ lock_pubkey: lockPubkey,
36255
+ quote_id: result2.quote_id,
36256
+ ...collectForMs === void 0 ? {} : { collection_state: "collected" },
36257
+ sweep: summarizeSweep(sweep),
36258
+ melt_sweep: summarizeMeltSweep(meltSweep),
36259
+ ...result2.float_payment ? { float_payment: floatPaymentJson(result2.float_payment) } : {},
36260
+ 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.`,
36261
+ hint: "Inspect the resulting balance with `dvm wallet show`."
36262
+ });
36263
+ }
36264
+ }
36265
+ }
36266
+ function reportCollectionOutcome(entry, outcome, human) {
36267
+ const expiryMs = entry.expires_at === void 0 ? null : entry.expires_at * 1e3;
36268
+ const collectBefore = expiryMs === null ? null : new Date(expiryMs).toISOString();
36269
+ const nextStep = "dvm wallet show";
36270
+ const reason = outcome.kind === "stopped" ? outcome.reason : void 0;
36271
+ const alreadyIssued = outcome.kind === "already_issued";
36272
+ const display = alreadyIssued ? `The mint reports quote ${entry.quote_id} was already issued.` : `Collection ended for quote ${entry.quote_id}.`;
36273
+ const stopPayment = reason === "quote_expired" || reason === "paid_uncollected" || reason === "no_longer_pending" || expiryMs !== null && expiryMs <= Date.now();
36274
+ const deadlineHint = collectBefore ? ` The mint named ${collectBefore} as the deadline.` : "";
36275
+ 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
36276
  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}`);
36277
+ info(`${display} ${hint}`);
36047
36278
  } else {
36048
36279
  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`."
36280
+ status: alreadyIssued ? "already_issued" : "collection_stopped",
36281
+ collection_state: alreadyIssued ? "already_issued" : "needs_wallet_show",
36282
+ ...reason ? { reason } : {},
36283
+ quote_id: entry.quote_id,
36284
+ mint: entry.mint,
36285
+ amount_sats: entry.amount_sats,
36286
+ collect_before: collectBefore,
36287
+ next_step: nextStep,
36288
+ display,
36289
+ hint
36064
36290
  });
36065
36291
  }
36066
36292
  }
@@ -46409,6 +46635,9 @@ Docs:
46409
46635
  ).option("--mint <url>", "Cashu mint URL (default: configured mint, or Coinos)").option("--timeout <sec>", "Override DVM_FUND_TIMEOUT_SEC (default 600s)").option(
46410
46636
  "--no-wait",
46411
46637
  "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."
46638
+ ).option(
46639
+ "--collect-for <duration>",
46640
+ "With --no-wait, print the invoice and stay open to collect for up to this long (e.g. 30s or 2m)."
46412
46641
  ).option(
46413
46642
  "--test-skip-lightning",
46414
46643
  "Skip Lightning \u2014 for test mints that auto-pay invoices (FakeWallet). Cashu rail only."