@dvmkit/dvm-cli 0.10.0 → 0.11.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.
Files changed (25) hide show
  1. package/dist/{chunk-BHR7QHJG.js → chunk-3R2GM6AD.js} +2 -2
  2. package/dist/{chunk-TGRY23IF.js → chunk-6EYBCGGD.js} +2 -2
  3. package/dist/{chunk-NXXU3BSJ.js → chunk-7N3HQJKE.js} +4 -4
  4. package/dist/{chunk-C3HMFGYP.js → chunk-BPWZNIMS.js} +2 -2
  5. package/dist/{chunk-MTGQK7KA.js → chunk-GEZVSJDM.js} +3 -3
  6. package/dist/{chunk-GD25CUI4.js → chunk-GHNF2I5C.js} +4 -4
  7. package/dist/{chunk-3YU6KRCX.js → chunk-HWWW7JEM.js} +3 -3
  8. package/dist/{chunk-Q45TAYK2.js → chunk-JJBRTWWS.js} +160 -7
  9. package/dist/{chunk-HUBCGZJL.js → chunk-K562SFVD.js} +2 -2
  10. package/dist/{chunk-CWWZM4M6.js → chunk-MBSCP52L.js} +564 -204
  11. package/dist/{chunk-GMOKL4PQ.js → chunk-MMXHV3KC.js} +2 -2
  12. package/dist/{chunk-IEWV3CM2.js → chunk-UVFFMKU4.js} +3 -1
  13. package/dist/{client-MFSKFSV4.js → client-DS4QJ346.js} +6 -6
  14. package/dist/dvm.js +1075 -251
  15. package/dist/{internal-5EGKBZAE.js → internal-ZZHCUKOM.js} +5 -5
  16. package/dist/{lifecycle-7AVB36WP.js → lifecycle-XGNIMPTB.js} +6 -6
  17. package/dist/{payout-reporter-NXWQVKXW-KHVN6C4Z.js → payout-reporter-DDQ7FGRC-OKICJCC2.js} +2 -2
  18. package/dist/{pocket-refill-SKECWGA3.js → pocket-refill-3ZV36DOA.js} +10 -10
  19. package/dist/{revenue-reporter-HD4GMXGD-LAZU45ZA.js → revenue-reporter-RIEHBKRA-75BDPVVX.js} +2 -2
  20. package/dist/{tempo-lifecycle-SVPMTND2.js → tempo-lifecycle-LGGBDCKK.js} +8 -8
  21. package/dist/{tempo-wallet-5PKLSWFX.js → tempo-wallet-PLFC443A.js} +7 -7
  22. package/dist/{wallet-7BBWAZYJ.js → wallet-UJ7EJNQA.js} +7 -7
  23. package/dist/{x402-RUJ4LUKF-ZB7JM22B.js → x402-AY6P5KV4-SIZF7YNW.js} +2 -2
  24. package/package.json +2 -2
  25. package/skills/dvm/calling.md +15 -1
@@ -322,10 +322,10 @@ import {
322
322
  x402ResourceServer,
323
323
  x402SupportedNetworksHint,
324
324
  x402Version
325
- } from "./chunk-GD25CUI4.js";
325
+ } from "./chunk-GHNF2I5C.js";
326
326
  import {
327
327
  x402EarnedCeiling
328
- } from "./chunk-BHR7QHJG.js";
328
+ } from "./chunk-3R2GM6AD.js";
329
329
  import {
330
330
  withSdkInitLock
331
331
  } from "./chunk-R2DSAZBO.js";
@@ -338,7 +338,7 @@ import {
338
338
  extendDiagnosticIdentityAuthority,
339
339
  projectDiagnosticFields,
340
340
  projectSpanRow
341
- } from "./chunk-IEWV3CM2.js";
341
+ } from "./chunk-UVFFMKU4.js";
342
342
  import {
343
343
  privateKeyToAccount
344
344
  } from "./chunk-EVQERRCP.js";
@@ -1987,7 +1987,7 @@ var require_proper_lockfile = __commonJS({
1987
1987
  // node_modules/@dvmkit/sdk/dist/chunk-A262WVYX.js
1988
1988
  var CAPABILITY_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
1989
1989
 
1990
- // node_modules/@dvmkit/sdk/dist/chunk-M4NFYEEY.js
1990
+ // node_modules/@dvmkit/sdk/dist/chunk-QRYGBKCR.js
1991
1991
  import { createHash } from "crypto";
1992
1992
 
1993
1993
  // node_modules/@noble/ciphers/utils.js
@@ -3930,7 +3930,7 @@ var getPublicKey2 = i2.getPublicKey;
3930
3930
  var finalizeEvent2 = i2.finalizeEvent;
3931
3931
  var verifyEvent2 = i2.verifyEvent;
3932
3932
 
3933
- // node_modules/@dvmkit/sdk/dist/chunk-M4NFYEEY.js
3933
+ // node_modules/@dvmkit/sdk/dist/chunk-QRYGBKCR.js
3934
3934
  var X402_SELF_RELAY_KEY = "DVMKIT_X402_SELF_RELAY_KEY";
3935
3935
  var X402_RECEIVER_AUTHORIZER_KEY = "DVMKIT_X402_RECEIVER_AUTHORIZER_KEY";
3936
3936
  var X402_BATCH_SETTLEMENT_KEY = "DVMKIT_X402_BATCH_SETTLEMENT";
@@ -5016,7 +5016,7 @@ function verifyDrainReceipt(receipt) {
5016
5016
  }
5017
5017
  }
5018
5018
 
5019
- // node_modules/@dvmkit/sdk/dist/chunk-5JSPTVIK.js
5019
+ // node_modules/@dvmkit/sdk/dist/chunk-LZFZGY7L.js
5020
5020
  import { homedir } from "os";
5021
5021
  import { join as join3 } from "path";
5022
5022
  import { chmodSync, mkdirSync, statSync } from "fs";
@@ -10259,7 +10259,7 @@ zero
10259
10259
  zone
10260
10260
  zoo`.split("\n");
10261
10261
 
10262
- // node_modules/@dvmkit/sdk/dist/chunk-5JSPTVIK.js
10262
+ // node_modules/@dvmkit/sdk/dist/chunk-LZFZGY7L.js
10263
10263
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
10264
10264
  import { existsSync as existsSync4, readFileSync as readFileSync4, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs";
10265
10265
 
@@ -20233,7 +20233,7 @@ function expand(hash4, prk, info, length = 32) {
20233
20233
  }
20234
20234
  var hkdf = (hash4, ikm, salt, info, length) => expand(hash4, extract(hash4, ikm, salt), info, length);
20235
20235
 
20236
- // node_modules/@dvmkit/sdk/dist/chunk-5JSPTVIK.js
20236
+ // node_modules/@dvmkit/sdk/dist/chunk-LZFZGY7L.js
20237
20237
  import { randomBytes as randomBytes6 } from "crypto";
20238
20238
  import {
20239
20239
  chmodSync as chmodSync4,
@@ -21985,7 +21985,7 @@ function canonicalRequestPath(pathOrUrl) {
21985
21985
  return parsed.pathname.startsWith("/") ? parsed.pathname : `/${parsed.pathname}`;
21986
21986
  }
21987
21987
 
21988
- // node_modules/@dvmkit/sdk/dist/chunk-7KQLPVV7.js
21988
+ // node_modules/@dvmkit/sdk/dist/chunk-7NZRJPEP.js
21989
21989
  function createConsoleLogger(_jobId) {
21990
21990
  return {
21991
21991
  debug(_message, data) {
@@ -22055,7 +22055,7 @@ var StepCache = class _StepCache {
22055
22055
  }
22056
22056
  };
22057
22057
 
22058
- // node_modules/@dvmkit/sdk/dist/chunk-LDKV4UHI.js
22058
+ // node_modules/@dvmkit/sdk/dist/chunk-CVT5LTAK.js
22059
22059
  var InvalidCurrencyError = class extends Error {
22060
22060
  code = "invalid_currency";
22061
22061
  raw;
@@ -22507,7 +22507,7 @@ function resolveFxSourceFromEnv(env) {
22507
22507
  return raw2;
22508
22508
  }
22509
22509
 
22510
- // node_modules/@dvmkit/sdk/dist/chunk-EP7OVWI5.js
22510
+ // node_modules/@dvmkit/sdk/dist/chunk-FOXGN4KQ.js
22511
22511
  import { AsyncLocalStorage } from "async_hooks";
22512
22512
  var postgresRecovery = new AsyncLocalStorage();
22513
22513
  function withPostgresRecoveryContext(context, operation) {
@@ -22664,7 +22664,7 @@ function truncateUtf8(value, maxBytes) {
22664
22664
  return result;
22665
22665
  }
22666
22666
 
22667
- // node_modules/@dvmkit/sdk/dist/chunk-HNXMWHLU.js
22667
+ // node_modules/@dvmkit/sdk/dist/chunk-R7FH7SHX.js
22668
22668
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
22669
22669
  import { randomBytes as randomBytes7, randomUUID } from "crypto";
22670
22670
  import { hostname } from "os";
@@ -31463,7 +31463,7 @@ function parseStoreValue(value) {
31463
31463
  return parsed;
31464
31464
  }
31465
31465
 
31466
- // node_modules/@dvmkit/sdk/dist/chunk-NS2OMIU7.js
31466
+ // node_modules/@dvmkit/sdk/dist/chunk-RQK7OFJO.js
31467
31467
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
31468
31468
  var PostgresTempoSessionStore = class {
31469
31469
  constructor(pool) {
@@ -32041,7 +32041,7 @@ function acceptanceVoucherAmount(acceptance, key, current, next) {
32041
32041
  return authorized !== void 0 && authorized >= acceptance.cumulativeAmount ? acceptance.cumulativeAmount : void 0;
32042
32042
  }
32043
32043
 
32044
- // node_modules/@dvmkit/sdk/dist/chunk-FFRTAQUW.js
32044
+ // node_modules/@dvmkit/sdk/dist/chunk-P5KQKLWL.js
32045
32045
  import { createHash as createHash5 } from "crypto";
32046
32046
  var DEFAULT_TABLE_NAME = "mpp_tempo_charge_replays";
32047
32047
  var DEFAULT_RETENTION_MS = 60 * 60 * 1e3;
@@ -32396,7 +32396,7 @@ function isUniqueViolation(err) {
32396
32396
  return typeof err === "object" && err !== null && err.code === "23505";
32397
32397
  }
32398
32398
 
32399
- // node_modules/@dvmkit/sdk/dist/chunk-A2YESDQM.js
32399
+ // node_modules/@dvmkit/sdk/dist/chunk-LM6E4YHQ.js
32400
32400
  import { randomUUID as randomUUID3 } from "crypto";
32401
32401
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
32402
32402
  import { isDeepStrictEqual } from "util";
@@ -36792,7 +36792,7 @@ function expiryReleaseReport(dvmId, row) {
36792
36792
  };
36793
36793
  }
36794
36794
 
36795
- // node_modules/@dvmkit/sdk/dist/chunk-TKJBUFYY.js
36795
+ // node_modules/@dvmkit/sdk/dist/chunk-33J3NQDZ.js
36796
36796
  import { randomUUID as randomUUID4 } from "crypto";
36797
36797
  var MemoryCreditLedger = class _MemoryCreditLedger {
36798
36798
  /**
@@ -38225,7 +38225,7 @@ function assertAmount2(amountMicro, opts) {
38225
38225
  }
38226
38226
  }
38227
38227
 
38228
- // node_modules/@dvmkit/sdk/dist/chunk-AFV77S4C.js
38228
+ // node_modules/@dvmkit/sdk/dist/chunk-KVKJ7R5V.js
38229
38229
  import { randomUUID as randomUUID5 } from "crypto";
38230
38230
  function toJobRecord(job) {
38231
38231
  return {
@@ -38250,6 +38250,7 @@ function toJobRecord(job) {
38250
38250
  awaitingInputAtMs: job.awaitingInputAtMs,
38251
38251
  messages: job.messages,
38252
38252
  seq: job.seq,
38253
+ upfrontPayment: job.upfrontPayment,
38253
38254
  paidMsats: job.paidMsats,
38254
38255
  paymentMint: job.paymentMint,
38255
38256
  paymentRail: job.paymentRail,
@@ -38301,6 +38302,7 @@ function fromJobRecord(record2) {
38301
38302
  awaitingInputAtMs: record2.awaitingInputAtMs,
38302
38303
  messages: [...record2.messages],
38303
38304
  seq: record2.seq,
38305
+ upfrontPayment: record2.upfrontPayment,
38304
38306
  paidMsats: record2.paidMsats,
38305
38307
  paymentMint: record2.paymentMint,
38306
38308
  paymentRail: record2.paymentRail,
@@ -38362,6 +38364,9 @@ function providerMessage(job, type, content) {
38362
38364
  job.replayProviderSkip--;
38363
38365
  return;
38364
38366
  }
38367
+ if (type === "prompt" || type === "payment-request") {
38368
+ content = { ...content, expires_at_ms: Date.now() + (job.idleTimeoutMs ?? 36e5) };
38369
+ }
38365
38370
  const msg = localMessage(job, "provider", type, content);
38366
38371
  if (type === "payment-request") {
38367
38372
  const paymentRequest = content;
@@ -38384,7 +38389,51 @@ function providerMessage(job, type, content) {
38384
38389
  }
38385
38390
  job.messageAppender?.(msg, type === "prompt" ? { awaitingInput: job.status === "awaiting-input" } : void 0);
38386
38391
  }
38392
+ var historyHolds = /* @__PURE__ */ new WeakMap();
38393
+ var heldNotifications = /* @__PURE__ */ new WeakMap();
38394
+ function holdJobHistory(job, seq) {
38395
+ let holds = historyHolds.get(job);
38396
+ if (!holds) {
38397
+ holds = /* @__PURE__ */ new Set();
38398
+ historyHolds.set(job, holds);
38399
+ }
38400
+ holds.add(seq);
38401
+ }
38402
+ function visibleJobMessages(job) {
38403
+ const holds = historyHolds.get(job);
38404
+ if (!holds?.size) return job.messages;
38405
+ const boundary = Math.min(...holds);
38406
+ return job.messages.filter((message) => message.seq < boundary);
38407
+ }
38408
+ function releaseJobHistory(job, seq, accepted) {
38409
+ const holds = historyHolds.get(job);
38410
+ const wasPending = holds?.delete(seq);
38411
+ if (accepted && wasPending) {
38412
+ const next = job.messages.findIndex((existing) => existing.seq > accepted.seq);
38413
+ job.messages.splice(next < 0 ? job.messages.length : next, 0, accepted);
38414
+ const queued = heldNotifications.get(job) ?? [];
38415
+ queued.push(accepted);
38416
+ heldNotifications.set(job, queued);
38417
+ }
38418
+ flushJobHistory(job);
38419
+ }
38420
+ function flushJobHistory(job) {
38421
+ const holds = historyHolds.get(job);
38422
+ const boundary = holds?.size ? Math.min(...holds) : Infinity;
38423
+ const queued = heldNotifications.get(job) ?? [];
38424
+ queued.sort((a, b2) => a.seq - b2.seq);
38425
+ heldNotifications.set(job, queued.filter((message) => message.seq >= boundary));
38426
+ for (const message of queued) {
38427
+ if (message.seq < boundary) {
38428
+ for (const listener of job.listeners) listener(message);
38429
+ }
38430
+ }
38431
+ }
38387
38432
  function localMessage(job, from, type, content) {
38433
+ if (type === "cancel" || type === "complete") {
38434
+ historyHolds.get(job)?.clear();
38435
+ flushJobHistory(job);
38436
+ }
38388
38437
  job.seq++;
38389
38438
  const msg = {
38390
38439
  seq: job.seq,
@@ -38394,8 +38443,13 @@ function localMessage(job, from, type, content) {
38394
38443
  content
38395
38444
  };
38396
38445
  job.messages.push(msg);
38397
- for (const listener of job.listeners) {
38398
- listener(msg);
38446
+ const holds = historyHolds.get(job);
38447
+ if (holds?.size && msg.seq >= Math.min(...holds)) {
38448
+ const queued = heldNotifications.get(job) ?? [];
38449
+ queued.push(msg);
38450
+ heldNotifications.set(job, queued);
38451
+ } else {
38452
+ for (const listener of job.listeners) listener(msg);
38399
38453
  }
38400
38454
  return msg;
38401
38455
  }
@@ -38405,6 +38459,26 @@ function isTerminal(status) {
38405
38459
  function isYieldMessage(msg) {
38406
38460
  return msg.type === "prompt" || msg.type === "payment-request" || msg.type === "working" || msg.type === "complete" || msg.type === "cancel";
38407
38461
  }
38462
+ function callerDeadline(job, legacyTimeoutMs) {
38463
+ if (isTerminal(job.status)) return void 0;
38464
+ const prompts = /* @__PURE__ */ new Map();
38465
+ let payment;
38466
+ for (const message of job.messages) {
38467
+ if (message.from === "provider" && message.type === "prompt") prompts.set(message.content.id, message);
38468
+ if (message.from === "provider" && message.type === "payment-request") payment = message;
38469
+ if (message.from === "requester" && message.type === "response") prompts.delete(message.content.prompt_id);
38470
+ }
38471
+ const asks = [...prompts.values(), ...payment && (job.pendingPaymentMsats ?? 0) > 0 ? [payment] : []];
38472
+ const deadlines = asks.map((ask) => ask.content.expires_at_ms).filter((stamp) => Number.isSafeInteger(stamp));
38473
+ if (deadlines.length > 0) return Math.min(...deadlines);
38474
+ if (job.status === "awaiting-input" && legacyTimeoutMs !== void 0 && (asks.length > 0 || job.messages.length === 0)) {
38475
+ return (job.awaitingInputAtMs ?? job.lastActivityAt) + legacyTimeoutMs;
38476
+ }
38477
+ return void 0;
38478
+ }
38479
+ function hasCallerDeadline(messages) {
38480
+ return messages.some((message) => message.from === "provider" && (message.type === "prompt" || message.type === "payment-request") && Number.isSafeInteger(message.content.expires_at_ms));
38481
+ }
38408
38482
  var ContentHoldError = class extends Error {
38409
38483
  constructor(code) {
38410
38484
  super(code);
@@ -38462,7 +38536,7 @@ function applyContentHoldMutation(job, history, mutation) {
38462
38536
  return result;
38463
38537
  }
38464
38538
 
38465
- // node_modules/@dvmkit/sdk/dist/chunk-TWKQFIOW.js
38539
+ // node_modules/@dvmkit/sdk/dist/chunk-YMMCRQ2H.js
38466
38540
  import { createHash as createHash6 } from "crypto";
38467
38541
  var DEFAULT_BACKOFF_MS = [1e3, 4e3, 15e3, 3e4];
38468
38542
  var ListenChannel = class {
@@ -38710,6 +38784,7 @@ var PostgresJobStore = class {
38710
38784
  -- with a fund-and-draw response. INSERT-only for replay stability.
38711
38785
  ALTER TABLE jobs ADD COLUMN IF NOT EXISTS funding_receipt JSONB;
38712
38786
  ALTER TABLE jobs ADD COLUMN IF NOT EXISTS funding_credit JSONB;
38787
+ ALTER TABLE jobs ADD COLUMN IF NOT EXISTS upfront_payment JSONB;
38713
38788
  -- the outstanding mid-job ask, denominated in fiat micro at the
38714
38789
  -- instant it was emitted. The top-up's ledger leg funds and grows the
38715
38790
  -- draw in this figure, so it must not move with the BTC/USD rate between
@@ -38939,6 +39014,18 @@ var PostgresJobStore = class {
38939
39014
  }
38940
39015
  held.client.release();
38941
39016
  }
39017
+ async saveStep(jobId, record2) {
39018
+ const result = await this.pool.query(
39019
+ `UPDATE jobs SET step_cache = CASE
39020
+ WHEN EXISTS (SELECT 1 FROM jsonb_array_elements(step_cache) AS step
39021
+ WHERE step->>'id' = $2::jsonb->>'id') THEN step_cache
39022
+ ELSE step_cache || jsonb_build_array($2::jsonb) END
39023
+ WHERE id = $1 AND status NOT IN ('completed', 'failed', 'cancelled')
39024
+ AND redacted_at IS NULL`,
39025
+ [jobId, JSON.stringify(record2)]
39026
+ );
39027
+ if (result.rowCount !== 1) throw new Error("Step persistence requires a live job");
39028
+ }
38942
39029
  async save(record2) {
38943
39030
  const dvmId = record2[JOB_DVM_ID];
38944
39031
  for (let attempt = 0; ; attempt++) {
@@ -38985,8 +39072,8 @@ var PostgresJobStore = class {
38985
39072
  last_activity_at, next_seq, requester_token_hash, requester_token,
38986
39073
  request_fingerprint, requester_pubkey, request_id, credit_id, draw_id,
38987
39074
  pending_payment_fiat_micro, pending_payment_fiat_currency, auth_request_path,
38988
- funding_receipt, funding_credit, dvm_id, terminal_at_ms, caller_wait_ms, awaiting_input_at_ms, ended_by, timing_known
38989
- ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$51)
39075
+ funding_receipt, funding_credit, dvm_id, terminal_at_ms, caller_wait_ms, awaiting_input_at_ms, ended_by, timing_known, upfront_payment
39076
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$51,$52)
38990
39077
  ON CONFLICT (id) DO UPDATE SET
38991
39078
  terminal_at_ms = COALESCE(jobs.terminal_at_ms, EXCLUDED.terminal_at_ms),
38992
39079
  ended_by = CASE WHEN jobs.status IN ('completed', 'failed', 'cancelled') THEN jobs.ended_by ELSE EXCLUDED.ended_by END,
@@ -39037,7 +39124,17 @@ var PostgresJobStore = class {
39037
39124
  pending_x402_nonce = EXCLUDED.pending_x402_nonce,
39038
39125
  pending_x402_amount_usdc_micro = EXCLUDED.pending_x402_amount_usdc_micro,
39039
39126
  required_msats = EXCLUDED.required_msats,
39040
- step_cache = EXCLUDED.step_cache,
39127
+ -- A stale snapshot must not erase a step committed by saveStep.
39128
+ -- First stored result wins for each id, matching cached replay.
39129
+ step_cache = (
39130
+ SELECT COALESCE(jsonb_agg(entry ORDER BY position), '[]'::jsonb)
39131
+ FROM (
39132
+ SELECT DISTINCT ON (entry->>'id') entry, position
39133
+ FROM jsonb_array_elements(jobs.step_cache || EXCLUDED.step_cache)
39134
+ WITH ORDINALITY AS steps(entry, position)
39135
+ ORDER BY entry->>'id', position
39136
+ ) AS merged_steps
39137
+ ),
39041
39138
  state = EXCLUDED.state,
39042
39139
  last_activity_at = CASE WHEN jobs.status IN ('completed', 'failed', 'cancelled') THEN jobs.last_activity_at ELSE EXCLUDED.last_activity_at END
39043
39140
  -- terminal is terminal. On a multi-machine DVM a DELETE can
@@ -39115,7 +39212,8 @@ var PostgresJobStore = class {
39115
39212
  record2.status === "awaiting-input" ? record2.awaitingInputAtMs ?? now : null,
39116
39213
  isTerminalStatus(record2.status) && record2.status !== "completed" ? record2.endedBy ?? "provider" : null,
39117
39214
  now,
39118
- record2.timingKnown ?? true
39215
+ record2.timingKnown ?? true,
39216
+ record2.upfrontPayment ? JSON.stringify(record2.upfrontPayment) : null
39119
39217
  ]
39120
39218
  );
39121
39219
  let rowCount;
@@ -39154,6 +39252,7 @@ var PostgresJobStore = class {
39154
39252
  return;
39155
39253
  }
39156
39254
  if (record2.status === "completed" || record2.status === "failed" || record2.status === "cancelled") {
39255
+ await this.pool.query("SELECT pg_notify('job_messages', $1)", [record2.id]).catch(() => void 0);
39157
39256
  await this.deleteResolvedMessages(record2.id).catch(() => void 0);
39158
39257
  }
39159
39258
  }
@@ -39622,7 +39721,11 @@ var PostgresJobStore = class {
39622
39721
  }
39623
39722
  async markInboundFailed(jobId, seq, _reason) {
39624
39723
  await this.pool.query(
39625
- "UPDATE job_messages SET status='failed-verify' WHERE job_id = $1 AND seq = $2 AND status = 'pending-verification'",
39724
+ `WITH failed AS (
39725
+ UPDATE job_messages SET status='failed-verify'
39726
+ WHERE job_id = $1 AND seq = $2 AND status = 'pending-verification'
39727
+ RETURNING job_id
39728
+ ) SELECT pg_notify('job_messages', job_id) FROM failed`,
39626
39729
  [jobId, seq]
39627
39730
  );
39628
39731
  }
@@ -39741,10 +39844,24 @@ var PostgresJobStore = class {
39741
39844
  if (subSet.size === 0) this.notifySubscribers.delete(jobId);
39742
39845
  });
39743
39846
  }
39744
- async getMessages(jobId, afterSeq) {
39847
+ async getMessages(jobId, afterSeq, options) {
39745
39848
  const { rows: rows2 } = await this.pool.query(
39746
- "SELECT data FROM job_messages WHERE job_id = $1 AND seq > $2 AND status = 'verified' ORDER BY seq",
39747
- [jobId, afterSeq]
39849
+ `WITH terminal AS (
39850
+ SELECT messages FROM jobs WHERE id = $1 AND status IN ('completed', 'failed', 'cancelled')
39851
+ ), history AS (
39852
+ SELECT seq, data, 0 AS origin FROM job_messages
39853
+ WHERE job_id = $1 AND seq > $2 AND status = 'verified'
39854
+ AND ($3::boolean OR EXISTS (SELECT 1 FROM terminal)
39855
+ OR EXISTS (SELECT 1 FROM job_messages WHERE job_id = $1 AND status = 'verified'
39856
+ AND data->>'from' = 'provider' AND data->>'type' IN ('complete', 'cancel'))
39857
+ OR seq < COALESCE((SELECT MIN(seq) FROM job_messages
39858
+ WHERE job_id = $1 AND status = 'pending-verification' AND data->>'type' = 'payment'), 9223372036854775807))
39859
+ UNION ALL
39860
+ SELECT (message->>'seq')::bigint, message, 1 AS origin
39861
+ FROM terminal CROSS JOIN LATERAL jsonb_array_elements(terminal.messages) AS snapshot(message)
39862
+ WHERE (message->>'seq')::bigint > $2
39863
+ ) SELECT DISTINCT ON (seq) data FROM history ORDER BY seq, origin`,
39864
+ [jobId, afterSeq, options?.includeHeld ?? false]
39748
39865
  );
39749
39866
  return rows2.map((r) => typeof r.data === "string" ? JSON.parse(r.data) : r.data);
39750
39867
  }
@@ -39822,7 +39939,7 @@ var PostgresJobStore = class {
39822
39939
  try {
39823
39940
  await client.query("BEGIN");
39824
39941
  const { rows: rows2 } = await client.query(
39825
- `SELECT next_seq FROM jobs
39942
+ `SELECT * FROM jobs
39826
39943
  WHERE id = $1
39827
39944
  AND status IN ('processing', 'working', 'awaiting-input')
39828
39945
  ${staleOnly ? "AND last_activity_at <= $2" : ""}
@@ -39833,6 +39950,22 @@ var PostgresJobStore = class {
39833
39950
  await client.query("ROLLBACK");
39834
39951
  return false;
39835
39952
  }
39953
+ let terminalMessages;
39954
+ if (staleOnly) {
39955
+ const record2 = rowToRecord(rows2[0]);
39956
+ const { rows: messages } = await client.query(
39957
+ "SELECT data FROM job_messages WHERE job_id=$1 AND status='verified' ORDER BY seq",
39958
+ [jobId]
39959
+ );
39960
+ const history = messages.length ? messages.map((row) => row.data) : record2.messages;
39961
+ terminalMessages = history;
39962
+ const deadline = callerDeadline({ ...record2, messages: history });
39963
+ const awaiting = deadline !== void 0 || record2.status === "awaiting-input" && !hasCallerDeadline(history);
39964
+ if (terminalStatus === "cancelled" !== awaiting || deadline !== void 0 && Date.now() < deadline) {
39965
+ await client.query("ROLLBACK");
39966
+ return false;
39967
+ }
39968
+ }
39836
39969
  const nextSeq = rows2[0].next_seq;
39837
39970
  const now = Date.now();
39838
39971
  const cancelMsg = {
@@ -39855,12 +39988,20 @@ var PostgresJobStore = class {
39855
39988
  awaiting_input_at_ms = NULL,
39856
39989
  status = $6,
39857
39990
  summary = COALESCE(summary, $2),
39858
- messages = COALESCE(messages, '[]'::jsonb) || $3::jsonb,
39991
+ messages = ${staleOnly ? "$3::jsonb" : "COALESCE(messages, '[]'::jsonb) || $3::jsonb"},
39859
39992
  seq = $4,
39860
39993
  next_seq = $4 + 1,
39861
39994
  last_activity_at = $5
39862
39995
  WHERE id = $1`,
39863
- [jobId, reason, JSON.stringify([cancelMsg]), nextSeq, now, terminalStatus, endedBy]
39996
+ [
39997
+ jobId,
39998
+ reason,
39999
+ JSON.stringify([...terminalMessages ?? [], cancelMsg]),
40000
+ nextSeq,
40001
+ now,
40002
+ terminalStatus,
40003
+ staleOnly ? terminalStatus === "cancelled" ? "caller" : "provider" : endedBy
40004
+ ]
39864
40005
  );
39865
40006
  await client.query("SELECT pg_notify('job_messages', $1)", [jobId]);
39866
40007
  await client.query("COMMIT");
@@ -39948,6 +40089,7 @@ function rowToRecord(row) {
39948
40089
  summary: row.summary,
39949
40090
  messages: row.messages,
39950
40091
  seq: row.seq,
40092
+ upfrontPayment: row.upfront_payment ?? void 0,
39951
40093
  paidMsats: Number(row.paid_msats),
39952
40094
  paymentMint: row.payment_mint,
39953
40095
  paymentRail: row.payment_rail ?? void 0,
@@ -39986,7 +40128,7 @@ function isTerminalStatus(status) {
39986
40128
  return status === "completed" || status === "failed" || status === "cancelled";
39987
40129
  }
39988
40130
 
39989
- // node_modules/@dvmkit/sdk/dist/chunk-HULU2UVM.js
40131
+ // node_modules/@dvmkit/sdk/dist/chunk-ZO2ZAPG3.js
39990
40132
  function humanizeZodError(err, opts) {
39991
40133
  return humanizeZodIssues(err.issues, opts);
39992
40134
  }
@@ -40139,7 +40281,7 @@ function createDefaultReplayStore() {
40139
40281
  }
40140
40282
  var SATURATION_WARN_INTERVAL_SECONDS = 60;
40141
40283
 
40142
- // node_modules/@dvmkit/sdk/dist/chunk-KJZVTWMX.js
40284
+ // node_modules/@dvmkit/sdk/dist/chunk-PKLNMMKF.js
40143
40285
  function accumulateAskedTopUp(prior, ask) {
40144
40286
  const poisoned = (reason) => ({
40145
40287
  micro: UNCAPPABLE_ASK_TOTAL,
@@ -40241,7 +40383,10 @@ var MemoryJobStore = class {
40241
40383
  return Promise.resolve();
40242
40384
  }
40243
40385
  const snapshot = structuredClone(record2);
40244
- if (existing) snapshot.createdAt = existing.createdAt;
40386
+ if (existing) {
40387
+ snapshot.createdAt = existing.createdAt;
40388
+ snapshot.upfrontPayment = structuredClone(existing.upfrontPayment);
40389
+ }
40245
40390
  if (existing && isTerminal(existing.status)) snapshot.lastActivityAt = existing.lastActivityAt;
40246
40391
  if (existing?.receipt) snapshot.receipt = existing.receipt;
40247
40392
  snapshot.timingKnown = existing ? existing.timingKnown ?? false : record2.timingKnown ?? true;
@@ -40250,6 +40395,7 @@ var MemoryJobStore = class {
40250
40395
  const cur = this.nextSeq.get(record2.id) ?? 1;
40251
40396
  this.nextSeq.set(record2.id, Math.max(cur, record2.seq + 1));
40252
40397
  if (isTerminal(record2.status)) {
40398
+ this.notify(record2.id);
40253
40399
  this.messages.delete(record2.id);
40254
40400
  }
40255
40401
  return Promise.resolve();
@@ -40361,7 +40507,7 @@ var MemoryJobStore = class {
40361
40507
  }
40362
40508
  if (!isTerminal(record2.status)) record2.lastActivityAt = Date.now();
40363
40509
  if (seq > record2.seq) record2.seq = seq;
40364
- this.notify(jobId, fullMessage);
40510
+ this.notify(jobId);
40365
40511
  return Promise.resolve(seq);
40366
40512
  }
40367
40513
  recordInbound(jobId, message) {
@@ -40422,7 +40568,7 @@ var MemoryJobStore = class {
40422
40568
  }
40423
40569
  }
40424
40570
  if (!isTerminal(record2.status)) record2.lastActivityAt = Date.now();
40425
- this.notify(jobId, stored.message);
40571
+ this.notify(jobId);
40426
40572
  return Promise.resolve({
40427
40573
  counters: snapshotCounters(record2),
40428
40574
  alreadyVerified: false,
@@ -40443,6 +40589,7 @@ var MemoryJobStore = class {
40443
40589
  const stored = this.messagesFor(jobId).find((m) => m.message.seq === seq);
40444
40590
  if (stored?.status === "pending-verification") {
40445
40591
  stored.status = "failed-verify";
40592
+ this.notify(jobId);
40446
40593
  }
40447
40594
  return Promise.resolve();
40448
40595
  }
@@ -40533,11 +40680,8 @@ var MemoryJobStore = class {
40533
40680
  if (subSet.size === 0) this.notifySubscribers.delete(jobId);
40534
40681
  });
40535
40682
  }
40536
- getMessages(jobId, afterSeq) {
40537
- const stored = this.messagesFor(jobId);
40538
- return Promise.resolve(
40539
- stored.filter((m) => m.status === "verified" && m.message.seq > afterSeq).map((m) => m.message)
40540
- );
40683
+ getMessages(jobId, afterSeq, options) {
40684
+ return Promise.resolve(this.visibleMessages(jobId, afterSeq, options?.includeHeld));
40541
40685
  }
40542
40686
  initStreaming() {
40543
40687
  return Promise.resolve();
@@ -40558,6 +40702,15 @@ var MemoryJobStore = class {
40558
40702
  if (!record2) return Promise.resolve(false);
40559
40703
  const eligible = (record2.status === "processing" || record2.status === "working" || record2.status === "awaiting-input") && (expectedActivityBefore === null || record2.lastActivityAt <= expectedActivityBefore);
40560
40704
  if (!eligible) return Promise.resolve(false);
40705
+ let terminalMessages = record2.messages;
40706
+ if (expectedActivityBefore !== null) {
40707
+ const messages = this.messagesFor(jobId).filter((entry) => entry.status === "verified").map((entry) => entry.message);
40708
+ const history = messages.length ? messages : record2.messages;
40709
+ terminalMessages = history;
40710
+ const deadline = callerDeadline({ ...record2, messages: history });
40711
+ const awaiting = deadline !== void 0 || record2.status === "awaiting-input" && !hasCallerDeadline(history);
40712
+ if (terminalStatus === "cancelled" !== awaiting || deadline !== void 0 && Date.now() < deadline) return Promise.resolve(false);
40713
+ }
40561
40714
  const seq = this.allocateSeq(jobId);
40562
40715
  const cancelMsg = {
40563
40716
  seq,
@@ -40567,14 +40720,14 @@ var MemoryJobStore = class {
40567
40720
  content: { reason }
40568
40721
  };
40569
40722
  this.messagesFor(jobId).push({ message: cancelMsg, status: "verified" });
40570
- record2.endedBy = expectedActivityBefore === null || record2.status === "awaiting-input" ? "caller" : "provider";
40723
+ record2.endedBy = expectedActivityBefore === null || terminalStatus === "cancelled" ? "caller" : "provider";
40571
40724
  applyTiming(record2, structuredClone(record2), Date.now(), terminalStatus);
40572
40725
  record2.status = terminalStatus;
40573
40726
  record2.summary = record2.summary ?? reason;
40574
- record2.messages = [...record2.messages, cancelMsg];
40727
+ record2.messages = [...terminalMessages, cancelMsg];
40575
40728
  record2.seq = seq;
40576
40729
  record2.lastActivityAt = Date.now();
40577
- this.notify(jobId, cancelMsg);
40730
+ this.notify(jobId);
40578
40731
  this.messages.delete(jobId);
40579
40732
  return Promise.resolve(true);
40580
40733
  }
@@ -40591,11 +40744,35 @@ var MemoryJobStore = class {
40591
40744
  }
40592
40745
  return list;
40593
40746
  }
40594
- notify(jobId, message) {
40747
+ visibleMessages(jobId, afterSeq, includeHeld = false) {
40748
+ const stored = this.messagesFor(jobId);
40749
+ const record2 = this.data.get(jobId);
40750
+ const terminal = record2 && isTerminal(record2.status);
40751
+ const terminalMessage = stored.some((entry) => entry.status === "verified" && entry.message.from === "provider" && (entry.message.type === "complete" || entry.message.type === "cancel"));
40752
+ let boundary = Infinity;
40753
+ if (!includeHeld && !terminal && !terminalMessage) {
40754
+ for (const entry of stored) {
40755
+ if (entry.status === "pending-verification" && entry.message.type === "payment") {
40756
+ boundary = Math.min(boundary, entry.message.seq);
40757
+ }
40758
+ }
40759
+ }
40760
+ const messages = /* @__PURE__ */ new Map();
40761
+ if (terminal) {
40762
+ for (const message of record2.messages) if (message.seq > afterSeq) messages.set(message.seq, message);
40763
+ }
40764
+ for (const entry of stored) {
40765
+ if (entry.status === "verified" && entry.message.seq > afterSeq && entry.message.seq < boundary) {
40766
+ messages.set(entry.message.seq, entry.message);
40767
+ }
40768
+ }
40769
+ return [...messages.values()].sort((a, b2) => a.seq - b2.seq);
40770
+ }
40771
+ notify(jobId) {
40595
40772
  const subs = this.messageSubscribers.get(jobId);
40596
40773
  if (subs) {
40597
40774
  for (const sub of subs) {
40598
- if (message.seq > sub.afterSeq) {
40775
+ for (const message of this.visibleMessages(jobId, sub.afterSeq)) {
40599
40776
  sub.afterSeq = message.seq;
40600
40777
  sub.cb(message);
40601
40778
  }
@@ -40666,7 +40843,7 @@ function mergeSignals(a, b2) {
40666
40843
  return AbortSignal.any([a, b2]);
40667
40844
  }
40668
40845
 
40669
- // node_modules/@dvmkit/sdk/dist/chunk-JLT2YIBS.js
40846
+ // node_modules/@dvmkit/sdk/dist/chunk-GB2N4NG5.js
40670
40847
  import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
40671
40848
  var TEMPO_SETTLEMENT_BALANCE_INTERVAL_MS = 5 * 60 * 1e3;
40672
40849
  function isTempoInsufficientFundsError(error) {
@@ -42017,7 +42194,7 @@ function isTempoCloseTransaction(reference) {
42017
42194
  return typeof reference === "string" && /^0x[0-9a-fA-F]{64}$/.test(reference);
42018
42195
  }
42019
42196
 
42020
- // node_modules/@dvmkit/sdk/dist/chunk-JFH34P3M.js
42197
+ // node_modules/@dvmkit/sdk/dist/chunk-ZJRGORJ3.js
42021
42198
  import { createHash as createHash8, randomUUID as randomUUID7 } from "crypto";
42022
42199
  import { createHash as createHash23 } from "crypto";
42023
42200
  import { createHash as createHash33 } from "crypto";
@@ -45475,7 +45652,7 @@ var BatchSettlementEvmScheme3 = class {
45475
45652
  }
45476
45653
  };
45477
45654
 
45478
- // node_modules/@dvmkit/sdk/dist/chunk-JFH34P3M.js
45655
+ // node_modules/@dvmkit/sdk/dist/chunk-ZJRGORJ3.js
45479
45656
  import { createHash as createHash42, randomBytes as randomBytes8, randomUUID as randomUUID22 } from "crypto";
45480
45657
  import { randomBytes as randomBytes22 } from "crypto";
45481
45658
 
@@ -47846,7 +48023,7 @@ function date3(params) {
47846
48023
  // node_modules/zod/v4/classic/external.js
47847
48024
  config(en_default());
47848
48025
 
47849
- // node_modules/@dvmkit/sdk/dist/chunk-JFH34P3M.js
48026
+ // node_modules/@dvmkit/sdk/dist/chunk-ZJRGORJ3.js
47850
48027
  import { createHash as createHash52 } from "crypto";
47851
48028
  import { createHash as createHash62, randomUUID as randomUUID32 } from "crypto";
47852
48029
  import { isDeepStrictEqual as isDeepStrictEqual22 } from "util";
@@ -50239,7 +50416,7 @@ var streamSSE = (c, cb, onError) => {
50239
50416
  return c.newResponse(stream2.responseReadable);
50240
50417
  };
50241
50418
 
50242
- // node_modules/@dvmkit/sdk/dist/chunk-JFH34P3M.js
50419
+ // node_modules/@dvmkit/sdk/dist/chunk-ZJRGORJ3.js
50243
50420
  import { createHash as createHash10 } from "crypto";
50244
50421
  async function initLockPubkeyTable(db) {
50245
50422
  await withSdkInitLock(db, () => createLockPubkeyTable(db));
@@ -53103,6 +53280,24 @@ async function restoreRevokedVoucher(storage2, channelId, pendingId, before) {
53103
53280
  function isRecord5(value) {
53104
53281
  return !!value && typeof value === "object" && !Array.isArray(value);
53105
53282
  }
53283
+ function upfrontPaymentFromDraw(draw) {
53284
+ const value = draw.railValue;
53285
+ const rail = value.rail;
53286
+ return {
53287
+ amount_msats: value.drawMsats,
53288
+ ...value.creditCurrency !== null && {
53289
+ amount_micro: draw.amountMicro,
53290
+ currency: value.creditCurrency
53291
+ },
53292
+ ...rail === "cashu" || rail === "x402" || rail === "tempo" || rail === "lightning" ? { rail } : {},
53293
+ ...value.drawNative !== null && value.nativeAsset !== null && {
53294
+ native_amount: value.drawNative,
53295
+ native_asset: value.nativeAsset
53296
+ },
53297
+ credit_id: draw.creditId,
53298
+ draw_id: draw.drawId
53299
+ };
53300
+ }
53106
53301
  function paymentFailureFields(error) {
53107
53302
  let category = "unknown";
53108
53303
  try {
@@ -53458,7 +53653,18 @@ async function issueUpfrontChallenges(mpp, requiredMsats, resourcePath, btcUsdRa
53458
53653
  );
53459
53654
  }
53460
53655
  async function verifyUpfrontPayment(opts) {
53461
- return withPaymentDiagnostics(() => verifyUpfrontPaymentInScope(opts));
53656
+ const result = await withPaymentDiagnostics(() => verifyUpfrontPaymentInScope(opts));
53657
+ if (!result.error && !result.replayedDraw && !result.upfrontPayment && !opts.fundOnly) {
53658
+ result.upfrontPayment = {
53659
+ amount_msats: result.paidMsats,
53660
+ ...result.paymentRail && { rail: result.paymentRail },
53661
+ ...result.nativeAmount !== void 0 && result.nativeAsset !== void 0 && {
53662
+ native_amount: result.nativeAmount,
53663
+ native_asset: result.nativeAsset
53664
+ }
53665
+ };
53666
+ }
53667
+ return result;
53462
53668
  }
53463
53669
  async function verifyUpfrontPaymentInScope(opts) {
53464
53670
  const {
@@ -53790,7 +53996,7 @@ async function verifyUpfrontPaymentInScope(opts) {
53790
53996
  x402Requirements
53791
53997
  });
53792
53998
  }
53793
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-RUJ4LUKF-ZB7JM22B.js");
53999
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-AY6P5KV4-SIZF7YNW.js");
53794
54000
  const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
53795
54001
  x402Payment,
53796
54002
  x402Config,
@@ -54226,7 +54432,8 @@ async function verifyUpfrontPaymentInScope(opts) {
54226
54432
  creditId: draw.creditId,
54227
54433
  drawId: draw.drawId,
54228
54434
  drawAmountMicro: draw.amountMicro,
54229
- creditCurrency: ledgerCtx.priceFiat.currency
54435
+ creditCurrency: ledgerCtx.priceFiat.currency,
54436
+ upfrontPayment: upfrontPaymentFromDraw(draw)
54230
54437
  };
54231
54438
  } catch (err) {
54232
54439
  if (err instanceof CreditLedgerError) return creditLedgerErrorResult(err, x402Requirements);
@@ -54814,7 +55021,7 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
54814
55021
  snapshot
54815
55022
  });
54816
55023
  }
54817
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-RUJ4LUKF-ZB7JM22B.js");
55024
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-AY6P5KV4-SIZF7YNW.js");
54818
55025
  const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
54819
55026
  body.content.x402_payment,
54820
55027
  opts.x402Config,
@@ -55053,7 +55260,9 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
55053
55260
  };
55054
55261
  }
55055
55262
  }
55056
- return {};
55263
+ return { error: { status: 402, body: paymentErrorBody("payment_invalid", {
55264
+ message: "Payment method is not configured"
55265
+ }) } };
55057
55266
  }
55058
55267
  function midJobFundedMsats(snapshot, railMsats) {
55059
55268
  const pending = snapshot.pendingPaymentMsats ?? 0;
@@ -55263,7 +55472,7 @@ async function processIncomingPaymentInScope(job, body, opts) {
55263
55472
  try {
55264
55473
  const requiredMsats = job.pendingPaymentMsats ?? 0;
55265
55474
  const requiredUsdcMicro = job.pendingX402AmountUsdcMicro !== void 0 ? BigInt(job.pendingX402AmountUsdcMicro) : BigInt(msatsToUsdc(requiredMsats, rate));
55266
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-RUJ4LUKF-ZB7JM22B.js");
55475
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-AY6P5KV4-SIZF7YNW.js");
55267
55476
  const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
55268
55477
  body.content.x402_payment,
55269
55478
  opts.x402Config,
@@ -55862,7 +56071,8 @@ function withDrawBasis(info, ctx, committed) {
55862
56071
  const withDraw = {
55863
56072
  ...base22,
55864
56073
  drawId,
55865
- drawAmountMicro: draw.amountMicro
56074
+ drawAmountMicro: draw.amountMicro,
56075
+ ...!ctx.midJob && !ctx.fundOnly && { upfrontPayment: upfrontPaymentFromDraw(draw) }
55866
56076
  };
55867
56077
  if (!ctx.drawBasis) return withDraw;
55868
56078
  const { drawMsats, drawNative } = committed.added ?? draw.railValue;
@@ -62330,6 +62540,12 @@ function buildContext(job, opts) {
62330
62540
  log.error("Terminal handling failed", { error: String(err) });
62331
62541
  });
62332
62542
  };
62543
+ let replayPrompts;
62544
+ const captureReplayPrompts = () => {
62545
+ if (replayPrompts === void 0 && job.replayHighSeq !== null) {
62546
+ replayPrompts = job.messages.filter((m) => m.from === "provider" && m.type === "prompt" && m.seq <= job.replayHighSeq);
62547
+ }
62548
+ };
62333
62549
  let creditedToHandlerMsats = 0;
62334
62550
  let creditedToHandlerMicro = 0;
62335
62551
  let poolBasis = false;
@@ -62337,6 +62553,7 @@ function buildContext(job, opts) {
62337
62553
  let declaredCostCurrency;
62338
62554
  let declaredCostRevision = 0;
62339
62555
  let costPoisoned = false;
62556
+ const stepWrites = /* @__PURE__ */ new Map();
62340
62557
  const stepCostOwner = {};
62341
62558
  const declareCost = (declared) => {
62342
62559
  if (terminated("cost")) return;
@@ -62392,29 +62609,41 @@ function buildContext(job, opts) {
62392
62609
  },
62393
62610
  sendMessage: (type, content) => {
62394
62611
  if (terminated("sendMessage")) return;
62612
+ if (type === "payment-request" && typeof content.amount_msats === "number") job.pendingPaymentMsats = content.amount_msats;
62395
62613
  providerMessage(job, type, content);
62614
+ if ((type === "prompt" || type === "payment-request") && opts.onYield) {
62615
+ void opts.onYield().catch((err) => {
62616
+ log.error("Failed to persist event-driven wait", { error: String(err) });
62617
+ });
62618
+ }
62396
62619
  },
62397
62620
  prompt: (id, text, promptOpts) => {
62398
62621
  if (terminated("prompt")) {
62399
62622
  return Promise.reject(new JobCancelledError(`Job already ${job.status}`));
62400
62623
  }
62401
62624
  job.status = "awaiting-input";
62402
- providerMessage(job, "prompt", {
62403
- id,
62404
- text,
62405
- ...promptOpts?.options && { options: promptOpts.options },
62406
- ...promptOpts?.schema && { schema: promptOpts.schema }
62407
- });
62408
- if (job.replayHighSeq !== null) {
62625
+ captureReplayPrompts();
62626
+ const originalIndex = replayPrompts?.findIndex((m) => m.type === "prompt" && m.content.id === id) ?? -1;
62627
+ const original = originalIndex < 0 ? void 0 : replayPrompts.splice(originalIndex, 1)[0];
62628
+ if (original) {
62629
+ if (job.replayProviderSkip > 0) job.replayProviderSkip--;
62409
62630
  const response = job.messages.find(
62410
- (m) => m.type === "response" && m.from === "requester" && m.content.prompt_id === id
62631
+ (m) => m.type === "response" && m.from === "requester" && m.content.prompt_id === id && m.seq > original.seq
62411
62632
  );
62412
62633
  if (response) {
62413
- job.status = "processing";
62634
+ job.status = job.pendingPrompts.size > 0 || job.pendingPayment ? "awaiting-input" : "processing";
62635
+ opts.onCallerResume?.();
62414
62636
  return Promise.resolve(response.content);
62415
62637
  }
62638
+ } else {
62416
62639
  job.replayHighSeq = null;
62417
62640
  job.replayProviderSkip = 0;
62641
+ providerMessage(job, "prompt", {
62642
+ id,
62643
+ text,
62644
+ ...promptOpts?.options && { options: promptOpts.options },
62645
+ ...promptOpts?.schema && { schema: promptOpts.schema }
62646
+ });
62418
62647
  }
62419
62648
  const p = new Promise((resolve, reject) => {
62420
62649
  job.pendingPrompts.set(id, { resolve, reject });
@@ -62427,6 +62656,7 @@ function buildContext(job, opts) {
62427
62656
  return p;
62428
62657
  },
62429
62658
  requestPayment: async (amount, reason, payOpts) => {
62659
+ captureReplayPrompts();
62430
62660
  if (terminated("requestPayment")) {
62431
62661
  throw new JobCancelledError(`Job already ${job.status}`);
62432
62662
  }
@@ -62535,135 +62765,153 @@ function buildContext(job, opts) {
62535
62765
  poolRemainingMicro: pool.amountMicro - creditedToHandlerMicro
62536
62766
  } : { poolRemaining: job.paidMsats - creditedToHandlerMsats }
62537
62767
  });
62768
+ if (job.replayHighSeq !== null) {
62769
+ job.status = job.pendingPrompts.size > 0 ? "awaiting-input" : "processing";
62770
+ opts.onCallerResume?.();
62771
+ }
62538
62772
  advanceReplayPaymentIndex(job);
62539
62773
  return { amount_msats: amountMsats };
62540
62774
  }
62541
- const pendingFiat = await pinAsk();
62775
+ const replayedPaymentRequest = job.replayHighSeq !== null && job.replayPaymentIndex >= job.messages.filter((m) => m.from === "requester" && m.type === "payment").length ? job.messages.findLast((m) => m.from === "provider" && m.type === "payment-request" && m.seq <= job.replayHighSeq && m.seq > (job.messages.findLast((message) => message.from === "requester" && message.type === "payment")?.seq ?? -1)) : void 0;
62776
+ const originalAsk = replayedPaymentRequest?.type === "payment-request" ? replayedPaymentRequest.content : void 0;
62777
+ if (originalAsk) amountMsats = originalAsk.amount_msats;
62778
+ const pendingFiat = originalAsk ? originalAsk.credit ? { amountMicro: originalAsk.credit.amount_micro, currency: originalAsk.credit.currency } : void 0 : await pinAsk();
62542
62779
  job.pendingPaymentMsats = amountMsats;
62543
62780
  job.pendingPaymentFiatMicro = pendingFiat?.amountMicro;
62544
62781
  job.pendingPaymentFiatCurrency = pendingFiat?.currency;
62545
- const paymentRequestContent = {
62546
- amount_msats: amountMsats,
62547
- reason,
62548
- ...pendingFiat && { credit: { amount_micro: pendingFiat.amountMicro, currency: pendingFiat.currency } },
62549
- ...fiatAmount && { fiat_amount: fiatAmount },
62550
- ...payOpts?.mints && { mints: payOpts.mints },
62551
- ...payOpts?.minLocktimeSeconds && { min_locktime_seconds: payOpts.minLocktimeSeconds },
62552
- ...!payOpts?.mints && opts.mints && { mints: opts.mints }
62553
- };
62554
- let paymentRate;
62555
- let x402Nonce;
62556
- let x402AmountUsdcMicro;
62557
- const hasExplicitX402 = Boolean(payOpts?.x402);
62558
- if ((opts.pricingCurrency ?? "usd") === "usd") {
62559
- if (payOpts?.x402) {
62560
- paymentRequestContent.x402 = payOpts.x402;
62561
- } else if (opts.paymentMethods?.includes("x402") && opts.x402 && (opts.x402FacilitatorHealth?.support().available ?? true)) {
62562
- paymentRequestContent.x402 = {
62563
- pay_to: opts.x402.payTo,
62564
- network: opts.x402.network,
62565
- asset: opts.x402.asset ?? "USDC",
62566
- ...opts.x402.facilitator && { facilitator: opts.x402.facilitator }
62567
- };
62568
- }
62569
- }
62570
- if (paymentRequestContent.x402) {
62571
- paymentRate = (await resolveServerBtcUsdRate(opts.fxFetcher)).rate;
62572
- x402Nonce = `0x${randomBytes32(32).toString("hex")}`;
62573
- x402AmountUsdcMicro = msatsToUsdc(amountMsats, paymentRate).toString();
62574
- const x402Request = paymentRequestContent.x402;
62575
- const challengeConfig = {
62576
- payTo: x402Request.pay_to,
62577
- network: x402Request.network,
62578
- ...x402Request.asset ? { asset: x402Request.asset } : {},
62579
- ...x402Request.facilitator ? { facilitator: x402Request.facilitator } : {}
62782
+ let paymentRequestContent;
62783
+ if (originalAsk) {
62784
+ paymentRequestContent = { ...originalAsk };
62785
+ job.pendingX402Nonce = originalAsk.x402?.nonce;
62786
+ job.pendingX402AmountUsdcMicro = originalAsk.x402?.required_usdc_micro;
62787
+ job.pendingMppChallengeIds = originalAsk.tempo?.challenges.map((challenge2) => challenge2.id);
62788
+ } else {
62789
+ paymentRequestContent = {
62790
+ amount_msats: amountMsats,
62791
+ reason,
62792
+ ...pendingFiat && { credit: { amount_micro: pendingFiat.amountMicro, currency: pendingFiat.currency } },
62793
+ ...fiatAmount && { fiat_amount: fiatAmount },
62794
+ ...payOpts?.mints && { mints: payOpts.mints },
62795
+ ...payOpts?.minLocktimeSeconds && { min_locktime_seconds: payOpts.minLocktimeSeconds },
62796
+ ...!payOpts?.mints && opts.mints && { mints: opts.mints }
62580
62797
  };
62581
- Object.assign(x402Request, {
62582
- nonce: x402Nonce,
62583
- required_usdc_micro: x402AmountUsdcMicro,
62584
- ...hasExplicitX402 || (opts.x402FacilitatorHealth?.support().exact.v2 ?? true) ? {
62585
- payment_required: buildPaymentRequiredV2({
62586
- x402Config: challengeConfig,
62587
- requiredUsdcMicro: BigInt(x402AmountUsdcMicro),
62588
- resource: `/v1/job/${job.id}/messages`,
62589
- description: reason
62590
- })
62591
- } : {}
62592
- });
62593
- }
62594
- job.pendingX402Nonce = x402Nonce;
62595
- job.pendingX402AmountUsdcMicro = x402AmountUsdcMicro;
62596
- let mppChallengeIds;
62597
- if (payOpts?.mpp) {
62598
- const challenges = payOpts.mpp.challenges.filter((c) => c.intent !== "session");
62599
- if (challenges.length > 0) {
62600
- paymentRequestContent.tempo = { challenges };
62601
- mppChallengeIds = challenges.map((c) => c.id);
62798
+ let paymentRate;
62799
+ let x402Nonce;
62800
+ let x402AmountUsdcMicro;
62801
+ const hasExplicitX402 = Boolean(payOpts?.x402);
62802
+ if ((opts.pricingCurrency ?? "usd") === "usd") {
62803
+ if (payOpts?.x402) {
62804
+ paymentRequestContent.x402 = payOpts.x402;
62805
+ } else if (opts.paymentMethods?.includes("x402") && opts.x402 && (opts.x402FacilitatorHealth?.support().available ?? true)) {
62806
+ paymentRequestContent.x402 = {
62807
+ pay_to: opts.x402.payTo,
62808
+ network: opts.x402.network,
62809
+ asset: opts.x402.asset ?? "USDC",
62810
+ ...opts.x402.facilitator && { facilitator: opts.x402.facilitator }
62811
+ };
62812
+ }
62602
62813
  }
62603
- } else if (opts.paymentMethods?.includes("tempo") && opts.mpp) {
62604
- const rate = paymentRate ?? (await resolveServerBtcUsdRate(opts.fxFetcher)).rate;
62605
- const challenges = [];
62606
- for (const m of opts.mpp.methods) {
62607
- const meta3 = m;
62608
- if (meta3.intent === "session") continue;
62609
- const amount2 = pendingFiat?.currency === "usd" ? fiatMicroToMethodAmount(pendingFiat.amountMicro, meta3.name) : msatsToMethodAmount(amountMsats, meta3.name, rate);
62610
- const ch = await opts.mpp.issueChallenge(meta3.name, meta3.intent, {
62611
- amount: amount2,
62612
- description: reason
62814
+ if (paymentRequestContent.x402) {
62815
+ paymentRate = (await resolveServerBtcUsdRate(opts.fxFetcher)).rate;
62816
+ x402Nonce = `0x${randomBytes32(32).toString("hex")}`;
62817
+ x402AmountUsdcMicro = msatsToUsdc(amountMsats, paymentRate).toString();
62818
+ const x402Request = paymentRequestContent.x402;
62819
+ const challengeConfig = {
62820
+ payTo: x402Request.pay_to,
62821
+ network: x402Request.network,
62822
+ ...x402Request.asset ? { asset: x402Request.asset } : {},
62823
+ ...x402Request.facilitator ? { facilitator: x402Request.facilitator } : {}
62824
+ };
62825
+ Object.assign(x402Request, {
62826
+ nonce: x402Nonce,
62827
+ required_usdc_micro: x402AmountUsdcMicro,
62828
+ ...hasExplicitX402 || (opts.x402FacilitatorHealth?.support().exact.v2 ?? true) ? {
62829
+ payment_required: buildPaymentRequiredV2({
62830
+ x402Config: challengeConfig,
62831
+ requiredUsdcMicro: BigInt(x402AmountUsdcMicro),
62832
+ resource: `/v1/job/${job.id}/messages`,
62833
+ description: reason
62834
+ })
62835
+ } : {}
62613
62836
  });
62614
- challenges.push(ch);
62615
62837
  }
62616
- if (challenges.length > 0) {
62617
- paymentRequestContent.tempo = { challenges };
62618
- mppChallengeIds = challenges.map((c) => c.id);
62838
+ job.pendingX402Nonce = x402Nonce;
62839
+ job.pendingX402AmountUsdcMicro = x402AmountUsdcMicro;
62840
+ let mppChallengeIds;
62841
+ if (payOpts?.mpp) {
62842
+ const challenges = payOpts.mpp.challenges.filter((c) => c.intent !== "session");
62843
+ if (challenges.length > 0) {
62844
+ paymentRequestContent.tempo = { challenges };
62845
+ mppChallengeIds = challenges.map((c) => c.id);
62846
+ }
62847
+ } else if (opts.paymentMethods?.includes("tempo") && opts.mpp) {
62848
+ const rate = paymentRate ?? (await resolveServerBtcUsdRate(opts.fxFetcher)).rate;
62849
+ const challenges = [];
62850
+ for (const m of opts.mpp.methods) {
62851
+ const meta3 = m;
62852
+ if (meta3.intent === "session") continue;
62853
+ const amount2 = pendingFiat?.currency === "usd" ? fiatMicroToMethodAmount(pendingFiat.amountMicro, meta3.name) : msatsToMethodAmount(amountMsats, meta3.name, rate);
62854
+ const ch = await opts.mpp.issueChallenge(meta3.name, meta3.intent, {
62855
+ amount: amount2,
62856
+ description: reason
62857
+ });
62858
+ challenges.push(ch);
62859
+ }
62860
+ if (challenges.length > 0) {
62861
+ paymentRequestContent.tempo = { challenges };
62862
+ mppChallengeIds = challenges.map((c) => c.id);
62863
+ }
62619
62864
  }
62865
+ job.pendingMppChallengeIds = mppChallengeIds;
62620
62866
  }
62621
- job.pendingMppChallengeIds = mppChallengeIds;
62622
62867
  if (job.replayHighSeq !== null) {
62623
- const payments = job.messages.filter((m) => m.type === "payment" && m.from === "requester");
62868
+ const payments = job.messages.filter((m) => m.type === "payment" && m.from === "requester" && m.seq <= job.replayHighSeq);
62624
62869
  if (job.replayPaymentIndex < payments.length) {
62625
62870
  const payment = payments[job.replayPaymentIndex];
62626
62871
  job.replayPaymentIndex++;
62627
62872
  const balance = payment.content.credit;
62628
62873
  const accepted = balance ? await opts.acceptedBalancePayment?.(payment.seq, pendingFiat?.amountMicro, pendingFiat?.currency) : job.reactivationPaymentApplied === true;
62629
62874
  if (!accepted) throw new Error("[internal_error] payment replay reached without credit");
62630
- if (balance) {
62631
- job.pendingPaymentMsats = void 0;
62632
- job.pendingPaymentFiatMicro = void 0;
62633
- job.pendingPaymentFiatCurrency = void 0;
62634
- job.pendingMppChallengeIds = void 0;
62635
- job.pendingX402Nonce = void 0;
62636
- job.pendingX402AmountUsdcMicro = void 0;
62637
- }
62638
- job.status = "processing";
62875
+ job.pendingPaymentMsats = void 0;
62876
+ job.pendingPaymentFiatMicro = void 0;
62877
+ job.pendingPaymentFiatCurrency = void 0;
62878
+ job.pendingMppChallengeIds = void 0;
62879
+ job.pendingX402Nonce = void 0;
62880
+ job.pendingX402AmountUsdcMicro = void 0;
62881
+ job.status = job.pendingPrompts.size > 0 ? "awaiting-input" : "processing";
62882
+ opts.onCallerResume?.();
62639
62883
  creditedToHandlerMsats += amountMsats;
62640
62884
  creditedToHandlerMicro += pendingFiat?.amountMicro ?? 0;
62641
62885
  return payment.content;
62642
62886
  }
62643
- job.replayHighSeq = null;
62644
- job.replayProviderSkip = 0;
62887
+ if (!originalAsk) {
62888
+ job.replayHighSeq = null;
62889
+ job.replayProviderSkip = 0;
62890
+ }
62645
62891
  }
62646
- const askedTotal = accumulateAskedTopUp(
62647
- {
62648
- micro: job.askedTopUpMicro,
62649
- currency: job.askedTopUpCurrency,
62650
- reason: job.topUpCapUnenforcedReason
62651
- },
62652
- { micro: pendingFiat?.amountMicro, currency: pendingFiat?.currency }
62653
- );
62654
- job.askedTopUpMicro = askedTotal.micro;
62655
- job.askedTopUpCurrency = askedTotal.currency;
62656
- if (askedTotal.reason && !job.topUpCapUnenforcedReason) {
62657
- job.topUpCapUnenforcedReason = askedTotal.reason;
62658
- loggers.isolate.warn("dvm.topup_cap_unenforceable", {
62659
- job_id: job.id,
62660
- reason: askedTotal.reason,
62661
- ask_currency: askCurrency,
62662
- ask_msats: amountMsats
62663
- });
62892
+ if (!originalAsk) {
62893
+ const askedTotal = accumulateAskedTopUp(
62894
+ {
62895
+ micro: job.askedTopUpMicro,
62896
+ currency: job.askedTopUpCurrency,
62897
+ reason: job.topUpCapUnenforcedReason
62898
+ },
62899
+ { micro: pendingFiat?.amountMicro, currency: pendingFiat?.currency }
62900
+ );
62901
+ job.askedTopUpMicro = askedTotal.micro;
62902
+ job.askedTopUpCurrency = askedTotal.currency;
62903
+ if (askedTotal.reason && !job.topUpCapUnenforcedReason) {
62904
+ job.topUpCapUnenforcedReason = askedTotal.reason;
62905
+ loggers.isolate.warn("dvm.topup_cap_unenforceable", {
62906
+ job_id: job.id,
62907
+ reason: askedTotal.reason,
62908
+ ask_currency: askCurrency,
62909
+ ask_msats: amountMsats
62910
+ });
62911
+ }
62664
62912
  }
62665
62913
  job.status = "awaiting-input";
62666
- providerMessage(job, "payment-request", paymentRequestContent);
62914
+ if (!originalAsk) providerMessage(job, "payment-request", paymentRequestContent);
62667
62915
  const paidMsatsAtYield = job.paidMsats;
62668
62916
  const p = new Promise((resolve, reject) => {
62669
62917
  let resolved = false;
@@ -62681,6 +62929,9 @@ function buildContext(job, opts) {
62681
62929
  if (resolved) return;
62682
62930
  job.pendingPayment = null;
62683
62931
  }
62932
+ job.replayHighSeq = null;
62933
+ job.replayProviderSkip = 0;
62934
+ opts.onCallerResume?.();
62684
62935
  resolved = true;
62685
62936
  cleanup();
62686
62937
  creditedToHandlerMsats += amountMsats;
@@ -62786,6 +63037,7 @@ function buildContext(job, opts) {
62786
63037
  cost: declareCost,
62787
63038
  step: async (id, fn2) => {
62788
63039
  if (job.stepCache.has(id)) {
63040
+ await stepWrites.get(id);
62789
63041
  const record2 = job.stepCache.getRecord(id);
62790
63042
  for (const declared of record2.costs ?? []) declareCost(declared);
62791
63043
  return record2.value;
@@ -62798,6 +63050,15 @@ function buildContext(job, opts) {
62798
63050
  fn2
62799
63051
  );
62800
63052
  job.stepCache.set(id, result, costs);
63053
+ if (opts.onStep) {
63054
+ const persistence = opts.onStep(job.stepCache.getRecord(id));
63055
+ stepWrites.set(id, persistence);
63056
+ try {
63057
+ await persistence;
63058
+ } finally {
63059
+ stepWrites.delete(id);
63060
+ }
63061
+ }
62801
63062
  return result;
62802
63063
  },
62803
63064
  state: job.state,
@@ -62824,7 +63085,7 @@ function warnPinLost(jobId, currency, amountMsats, reason, detail) {
62824
63085
  }
62825
63086
  function advanceReplayPaymentIndex(job) {
62826
63087
  if (job.replayHighSeq === null) return;
62827
- const payments = job.messages.filter((m) => m.type === "payment" && m.from === "requester");
63088
+ const payments = job.messages.filter((m) => m.type === "payment" && m.from === "requester" && m.seq <= job.replayHighSeq);
62828
63089
  if (job.replayPaymentIndex < payments.length) {
62829
63090
  job.replayPaymentIndex++;
62830
63091
  }
@@ -63229,6 +63490,7 @@ var JobManager = class {
63229
63490
  // Bind live resolvers and recovery scaffolds to the store-allocated ask identity.
63230
63491
  paymentAskSeqs = /* @__PURE__ */ new WeakMap();
63231
63492
  reactivationAskSeqs = /* @__PURE__ */ new WeakMap();
63493
+ pendingPaymentMessages = /* @__PURE__ */ new WeakMap();
63232
63494
  // Every local input resume holds this queue through its durable wait update.
63233
63495
  // A prompt response and a payment NOTIFY must not mistake each other for a
63234
63496
  // different machine's successful claim.
@@ -63554,6 +63816,7 @@ var JobManager = class {
63554
63816
  status: "processing",
63555
63817
  messages: [],
63556
63818
  seq: 0,
63819
+ upfrontPayment: payment.upfrontPayment ? structuredClone(payment.upfrontPayment) : void 0,
63557
63820
  paidMsats: payment.paidMsats,
63558
63821
  paymentMint: payment.paymentMint,
63559
63822
  paymentRail: payment.paymentRail,
@@ -63737,8 +64000,10 @@ var JobManager = class {
63737
64000
  job.pendingPrompts.delete(rc.prompt_id);
63738
64001
  job.status = job.pendingPrompts.size > 0 || job.pendingPayment ? "awaiting-input" : "processing";
63739
64002
  if (job.status === "awaiting-input") await this.persistJob(job);
64003
+ this.startIdleTimer(job);
63740
64004
  pending.resolve(rc);
63741
64005
  } else if (cap?.onResponse && ctx) {
64006
+ this.startIdleTimer(job);
63742
64007
  await cap.onResponse(ctx, rc);
63743
64008
  }
63744
64009
  } else if (type === "payment") {
@@ -63758,6 +64023,7 @@ var JobManager = class {
63758
64023
  await pp.resolve(pc);
63759
64024
  });
63760
64025
  } else if (cap?.onPayment && ctx) {
64026
+ this.startIdleTimer(job);
63761
64027
  await cap.onPayment(ctx, pc);
63762
64028
  }
63763
64029
  } else if (type === "approval" && cap?.onApproval && ctx) {
@@ -63802,7 +64068,7 @@ var JobManager = class {
63802
64068
  if (await this.adoptDurableTerminal(job)) return;
63803
64069
  const record2 = toJobRecord(job);
63804
64070
  if (isTerminal(job.status) && isStreamableJobStore(this.jobStore)) {
63805
- const durable = await this.jobStore.getMessages(job.id, 0);
64071
+ const durable = await this.jobStore.getMessages(job.id, 0, { includeHeld: true });
63806
64072
  if (durable.length >= record2.messages.length) {
63807
64073
  record2.messages = durable;
63808
64074
  const highSeq = durable.length ? durable[durable.length - 1].seq : record2.seq;
@@ -64106,9 +64372,10 @@ var JobManager = class {
64106
64372
  job.messageAppenderTail = next;
64107
64373
  };
64108
64374
  }
64109
- startIdleTimer(job) {
64375
+ startIdleTimer(job, deadline = callerDeadline(job, this.descriptor.idleTimeout * 1e3)) {
64110
64376
  this.clearIdleTimer(job.id);
64111
- const timeoutMs = this.descriptor.idleTimeout * 1e3;
64377
+ if (deadline === void 0) return;
64378
+ const timeoutMs = Math.min(2147483647, Math.max(0, deadline - Date.now()));
64112
64379
  const timer = setTimeout(() => {
64113
64380
  void this.cancelJobIdle(job).catch(() => void 0);
64114
64381
  }, timeoutMs);
@@ -64124,7 +64391,7 @@ var JobManager = class {
64124
64391
  /** Cancel a job due to idle timeout. Exposed for the reactivation path's idle-expiry guard. */
64125
64392
  async cancelJobIdle(job) {
64126
64393
  if (isTerminal(job.status)) return;
64127
- const current = await this.jobStore.get(job.id).catch(() => void 0);
64394
+ const current = await this.jobStore.get(job.id);
64128
64395
  if (current && isTerminal(current.status)) {
64129
64396
  const reason = `Job reached terminal status "${current.status}" elsewhere`;
64130
64397
  for (const [, p] of job.pendingPrompts) p.reject(new Error(reason));
@@ -64136,11 +64403,32 @@ var JobManager = class {
64136
64403
  this.scheduleCleanup(job);
64137
64404
  return;
64138
64405
  }
64406
+ const waiting = current ?? job;
64407
+ if (current && isStreamableJobStore(this.jobStore)) {
64408
+ const messages = await this.jobStore.getMessages(job.id, 0);
64409
+ if (messages.length) waiting.messages = messages;
64410
+ }
64411
+ const deadline = callerDeadline(waiting, this.descriptor.idleTimeout * 1e3);
64412
+ if (deadline === void 0) {
64413
+ this.clearIdleTimer(job.id);
64414
+ return;
64415
+ }
64416
+ if (Date.now() < deadline) {
64417
+ this.startIdleTimer(job, deadline);
64418
+ return;
64419
+ }
64420
+ if (current && isStreamableJobStore(this.jobStore)) {
64421
+ const claimed = await this.jobStore.cancelStaleJob(job.id, current.lastActivityAt, "Job timed out (idle)", "cancelled");
64422
+ if (claimed) await this.finalizeStoredTerminal(job.id);
64423
+ await this.adoptDurableTerminal(job);
64424
+ if (!claimed && !isTerminal(job.status)) this.startIdleTimer(job, Date.now() + 1);
64425
+ return;
64426
+ }
64139
64427
  for (const [, p] of job.pendingPrompts) p.reject(new Error("Job timed out (idle)"));
64140
64428
  if (job.pendingPayment) job.pendingPayment.reject(new Error("Job timed out (idle)"));
64141
64429
  job.pendingPrompts.clear();
64142
64430
  job.pendingPayment = null;
64143
- job.endedBy = (current?.status ?? job.status) === "awaiting-input" ? "caller" : "provider";
64431
+ job.endedBy = "caller";
64144
64432
  job.status = "cancelled";
64145
64433
  abortJob(job, "Job timed out (idle)");
64146
64434
  providerMessage(job, "cancel", { reason: "Job timed out (idle)" });
@@ -64153,8 +64441,11 @@ var JobManager = class {
64153
64441
  * • `awaiting-input` past `staleJobTimeoutMs` → `cancelled`
64154
64442
  * (`stale_no_terminal_status`) — the caller never paid / responded.
64155
64443
  * • `processing`/`working` past `processingWatchdogMs` → `failed`
64156
- * (`worker_died_mid_job`) — the worker died mid-job. The heartbeat keeps
64157
- * live workers fresh, so a stale row here means a dead process.
64444
+ * (`worker_died_mid_job`) — the worker died mid-job. Before claiming a
64445
+ * processing row, skip and heartbeat it if this manager still holds a live
64446
+ * `processing`/`working` job. After a process pause, the sweep may run before
64447
+ * the heartbeat timer; stale activity alone does not prove a local worker
64448
+ * died. Superseded handlers leave `_activeJobs` and receive no protection.
64158
64449
  *
64159
64450
  * Fires on a timer (wired in the constructor) and also callable on demand
64160
64451
  * (tests, ops). The CAS in `cancelStaleJob` makes this safe to run
@@ -64162,6 +64453,8 @@ var JobManager = class {
64162
64453
  * JobManager owns so multi-mount hosts don't steal stuck rows from sibling
64163
64454
  * descriptors — the local activeJobs teardown only makes sense on the
64164
64455
  * JobManager that actually hosted the zombie handler.
64456
+ * Local liveness prevents this manager's claim; the activity CAS continues
64457
+ * to protect against other machines claiming a row refreshed after find.
64165
64458
  *
64166
64459
  * **Both cutoffs float off the wall clock.** Each is one
64167
64460
  * `Date.now()` sample compared against `last_activity_at`, stamped from a
@@ -64226,10 +64519,25 @@ var JobManager = class {
64226
64519
  );
64227
64520
  let swept = 0;
64228
64521
  for (const record2 of stale) {
64229
- const awaiting = record2.status === "awaiting-input";
64522
+ const messages = await this.jobStore.getMessages(record2.id, 0);
64523
+ const history = messages.length ? messages : record2.messages;
64524
+ const deadline = callerDeadline({ ...record2, messages: history });
64525
+ if (deadline !== void 0 && now < deadline) continue;
64526
+ const orphanedInput = record2.status === "awaiting-input" && deadline === void 0 && hasCallerDeadline(history);
64527
+ const awaiting = deadline !== void 0 || record2.status === "awaiting-input" && !orphanedInput;
64230
64528
  const terminalStatus = awaiting ? "cancelled" : "failed";
64231
64529
  const reason = awaiting ? "stale_no_terminal_status" : "worker_died_mid_job";
64232
- const expectedActivityBefore = awaiting ? awaitingThreshold : processingThreshold;
64530
+ const expectedActivityBefore = awaiting && record2.status === "awaiting-input" ? awaitingThreshold : processingThreshold;
64531
+ if (expectedActivityBefore < 0 || record2.lastActivityAt > expectedActivityBefore) continue;
64532
+ const local = this._activeJobs.get(record2.id);
64533
+ if ((record2.status === "processing" || record2.status === "working") && local && (local.status === "processing" || local.status === "working")) {
64534
+ await this.jobStore.heartbeatActiveJobs([record2.id], Date.now());
64535
+ diagnosticConsole.warn({
64536
+ level: "stale_job_local_live_skipped",
64537
+ ageMs: monoNow - record2.lastActivityAt
64538
+ });
64539
+ continue;
64540
+ }
64233
64541
  const claimed = await this.jobStore.cancelStaleJob(
64234
64542
  record2.id,
64235
64543
  expectedActivityBefore,
@@ -64849,8 +65157,9 @@ var JobManager = class {
64849
65157
  }
64850
65158
  }
64851
65159
  /**
64852
- * Record an inbound client message durably via Tx B and append
64853
- * it to the in-memory `job.messages` array. Returns the DB-allocated seq
65160
+ * Record an inbound client message durably via Tx B. Payments stay outside
65161
+ * visible history until processPayment accepts them; other messages append
65162
+ * to `job.messages` immediately. Returns the DB-allocated seq
64854
65163
  * (`null` when the store isn't streamable — non-Postgres test fallback).
64855
65164
  *
64856
65165
  * Status starts as `pending-verification`; a follow-up Tx C call
@@ -64869,13 +65178,24 @@ var JobManager = class {
64869
65178
  });
64870
65179
  }
64871
65180
  job.seq++;
64872
- job.messages.push({
65181
+ const message = {
64873
65182
  seq: job.seq,
64874
65183
  from: "requester",
64875
65184
  timestamp,
64876
65185
  type: msgType,
64877
65186
  content: msgContent
64878
- });
65187
+ };
65188
+ if (msgType === "payment") {
65189
+ let pending = this.pendingPaymentMessages.get(job);
65190
+ if (!pending) {
65191
+ pending = /* @__PURE__ */ new Map();
65192
+ this.pendingPaymentMessages.set(job, pending);
65193
+ }
65194
+ pending.set(txSeq ?? msgContent, message);
65195
+ holdJobHistory(job, message.seq);
65196
+ } else {
65197
+ job.messages.push(message);
65198
+ }
64879
65199
  job.lastActivityAt = Date.now();
64880
65200
  return txSeq;
64881
65201
  }
@@ -64984,6 +65304,22 @@ var JobManager = class {
64984
65304
  * 500. See `creditInbound`.
64985
65305
  */
64986
65306
  async processPayment(job, body, inboundSeq, extra) {
65307
+ const pending = this.pendingPaymentMessages.get(job);
65308
+ const key = inboundSeq ?? body.content;
65309
+ const message = pending?.get(key);
65310
+ let accepted;
65311
+ try {
65312
+ const outcome = await this.processPaymentAndCredit(job, body, inboundSeq, extra);
65313
+ if (!outcome.error && message && pending?.get(key) === message) {
65314
+ accepted = message;
65315
+ }
65316
+ return outcome;
65317
+ } finally {
65318
+ pending?.delete(key);
65319
+ if (message) releaseJobHistory(job, message.seq, accepted);
65320
+ }
65321
+ }
65322
+ async processPaymentAndCredit(job, body, inboundSeq, extra) {
64987
65323
  if (body.type !== "payment") return {};
64988
65324
  const devAuto = this.opts.devMode === true && body.content.dev_auto === true && !hasPaymentProof(body.content);
64989
65325
  if (devAuto || devModeSkipsPaymentVerification(this.opts)) {
@@ -65068,7 +65404,7 @@ var JobManager = class {
65068
65404
  };
65069
65405
  }
65070
65406
  const info = verifyResult.verified;
65071
- if (!info) return {};
65407
+ if (!info) return { error: { status: 402, body: { error: "payment_invalid", message: "Payment was not accepted" } } };
65072
65408
  const drawFundingReceipt = await this.drawFundingReceiptFor(info.drawFunding, info.funding?.currency);
65073
65409
  let unappliedCredit;
65074
65410
  const fullyUnapplied = info.unappliedMicro !== void 0 && info.funding !== void 0 && info.unappliedMicro >= info.funding.amountMicro;
@@ -65442,6 +65778,7 @@ var JobManager = class {
65442
65778
  */
65443
65779
  buildContextOpts(job) {
65444
65780
  const jobStore = this.jobStore;
65781
+ job.idleTimeoutMs = this.descriptor.idleTimeout * 1e3;
65445
65782
  return {
65446
65783
  mints: this.opts.mints,
65447
65784
  store: this.opts.store,
@@ -65452,7 +65789,25 @@ var JobManager = class {
65452
65789
  mpp: this.opts.mpp,
65453
65790
  fxFetcher: this.opts.fxFetcher,
65454
65791
  onTerminal: () => this.handleJobTerminal(job),
65455
- onYield: () => this.persistJob(job),
65792
+ onYield: () => {
65793
+ this.startIdleTimer(job);
65794
+ return this.persistJob(job);
65795
+ },
65796
+ onCallerResume: () => this.startIdleTimer(job),
65797
+ onStep: jobStore.saveStep ? async (record2) => {
65798
+ for (let attempt = 0; ; attempt++) {
65799
+ try {
65800
+ await jobStore.saveStep(job.id, record2);
65801
+ return;
65802
+ } catch {
65803
+ if (attempt >= 2) {
65804
+ diagnosticConsole.warn({ event: "step_persist_failed" });
65805
+ return;
65806
+ }
65807
+ await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
65808
+ }
65809
+ }
65810
+ } : void 0,
65456
65811
  onPaymentResume: () => retryJobSnapshot(() => this.persistJob(job)),
65457
65812
  subscribeNotifications: isStreamableJobStore(jobStore) ? (cb) => jobStore.subscribeNotifications(job.id, cb) : void 0,
65458
65813
  acceptedBalancePayment: this.opts.db && jobStore instanceof PostgresJobStore ? async (seq, amountMicro, currency) => {
@@ -70440,7 +70795,7 @@ async function createDVMServer(descriptor, opts) {
70440
70795
  }
70441
70796
  }
70442
70797
  if (!opts.onJobCompleted && platformToken && platformUrl && dvmId && opts.db) {
70443
- const { RevenueReporter: RevenueReporter2 } = await import("./revenue-reporter-HD4GMXGD-LAZU45ZA.js");
70798
+ const { RevenueReporter: RevenueReporter2 } = await import("./revenue-reporter-RIEHBKRA-75BDPVVX.js");
70444
70799
  const reporter = new RevenueReporter2(
70445
70800
  opts.db,
70446
70801
  platformUrl,
@@ -70450,7 +70805,7 @@ async function createDVMServer(descriptor, opts) {
70450
70805
  revenueReporter = reporter;
70451
70806
  await reporter.init();
70452
70807
  reporter.startRetryLoop();
70453
- const { MemoryX402BatchStore, PayoutReporter: PayoutReporter2 } = await import("./payout-reporter-NXWQVKXW-KHVN6C4Z.js");
70808
+ const { MemoryX402BatchStore, PayoutReporter: PayoutReporter2 } = await import("./payout-reporter-DDQ7FGRC-OKICJCC2.js");
70454
70809
  payoutReporter = new PayoutReporter2({
70455
70810
  dvmId,
70456
70811
  db: opts.db,
@@ -72761,7 +73116,6 @@ var DVMServer = class {
72761
73116
  );
72762
73117
  }
72763
73118
  const sdkCtx = jm.buildAndAttachContext(job, parsedInput);
72764
- jm.startIdleTimer(job);
72765
73119
  jm.runHandler(job, sdkCtx);
72766
73120
  await new Promise((resolve) => {
72767
73121
  setTimeout(resolve, 0);
@@ -73105,14 +73459,21 @@ var DVMServer = class {
73105
73459
  const job = this.jobManager.activeJobs.get(id);
73106
73460
  const after = Number(c.req.query("after") ?? "0");
73107
73461
  const accept = c.req.header("Accept") ?? "";
73108
- if (!job) {
73109
- const store = this.jobManager.store;
73462
+ const store = this.jobManager.store;
73463
+ if (job && !isJobOwner(c, job)) return c.json({ error: "Job not found" }, 404);
73464
+ if (!job || isStreamableJobStore(store)) {
73465
+ if (job) await job.messageAppenderTail;
73110
73466
  const record2 = await store.get(id);
73111
73467
  if (!record2) return c.json({ error: "Job not found" }, 404);
73112
73468
  if (!isJobOwner(c, record2)) return c.json({ error: "Job not found" }, 404);
73113
- const filtered = record2.messages.filter((m) => m.seq > after);
73469
+ const terminal = isTerminal(record2.status) || job !== void 0 && isTerminal(job.status);
73470
+ let filtered = record2.messages.filter((m) => m.seq > after);
73471
+ if (isStreamableJobStore(store)) {
73472
+ const durable = await store.getMessages(id, after, { includeHeld: terminal });
73473
+ if (durable.length > 0 || !terminal) filtered = durable;
73474
+ }
73114
73475
  if (accept.includes("text/event-stream")) {
73115
- if (isStreamableJobStore(store) && !isTerminal(record2.status)) {
73476
+ if (isStreamableJobStore(store) && !terminal) {
73116
73477
  return streamSSE(c, async (stream2) => {
73117
73478
  let unsubFn;
73118
73479
  await new Promise((resolve) => {
@@ -73175,10 +73536,6 @@ var DVMServer = class {
73175
73536
  }
73176
73537
  });
73177
73538
  }
73178
- if (isStreamableJobStore(store) && !isTerminal(record2.status)) {
73179
- const msgs = await store.getMessages(id, after);
73180
- if (msgs.length > 0) return c.json(await this.messageFields(record2, msgs));
73181
- }
73182
73539
  return c.json(await this.messageFields(record2, filtered));
73183
73540
  }
73184
73541
  if (!isJobOwner(c, job)) return c.json({ error: "Job not found" }, 404);
@@ -73186,7 +73543,7 @@ var DVMServer = class {
73186
73543
  const fields = await this.contentFields(job);
73187
73544
  return streamSSE(c, async (stream2) => {
73188
73545
  if (fields.content_available === false) return;
73189
- const existing = job.messages.filter((m) => m.seq > after);
73546
+ const existing = visibleJobMessages(job).filter((m) => m.seq > after);
73190
73547
  let yielded = false;
73191
73548
  for (const msg of existing) {
73192
73549
  await stream2.writeSSE({ data: JSON.stringify(msg), event: "message" });
@@ -73214,7 +73571,7 @@ var DVMServer = class {
73214
73571
  });
73215
73572
  });
73216
73573
  }
73217
- return c.json(await this.messageFields(job, job.messages.filter((m) => m.seq > after)));
73574
+ return c.json(await this.messageFields(job, visibleJobMessages(job).filter((m) => m.seq > after)));
73218
73575
  }
73219
73576
  jobNotActiveResponse(c) {
73220
73577
  return c.json(
@@ -73308,7 +73665,6 @@ var DVMServer = class {
73308
73665
  } else {
73309
73666
  await jm.markInboundVerified(activeJob.id, inboundSeq2);
73310
73667
  }
73311
- jm.startIdleTimer(activeJob);
73312
73668
  try {
73313
73669
  await jm.dispatchMessage(activeJob, body2.type, body2.content);
73314
73670
  await this.persistMessageSnapshot(jm, activeJob, body2.type);
@@ -73405,11 +73761,13 @@ var DVMServer = class {
73405
73761
  ...unappliedCredit && { credit: unappliedCredit },
73406
73762
  ...drawFundingReceipt && { draw_funding_receipt: drawFundingReceipt }
73407
73763
  };
73408
- const elapsed = Date.now() - record2.lastActivityAt;
73409
- if (elapsed >= this.descriptor.idleTimeout * 1e3) {
73764
+ const deadline = callerDeadline(record2, this.descriptor.idleTimeout * 1e3);
73765
+ if (deadline !== void 0 && Date.now() >= deadline) {
73410
73766
  await jm.cancelJobIdle(job);
73411
- const lastMsg2 = job.messages[job.messages.length - 1];
73412
- return c.json({ seq: lastMsg2.seq, ...creditBlock }, 201);
73767
+ if (isTerminal(job.status)) {
73768
+ const lastMsg2 = job.messages[job.messages.length - 1];
73769
+ return c.json({ seq: lastMsg2.seq, ...creditBlock }, 201);
73770
+ }
73413
73771
  }
73414
73772
  jm.startIdleTimer(job);
73415
73773
  try {
@@ -73589,6 +73947,7 @@ function recordedDrawPayment(draw, opts) {
73589
73947
  ...rail === "cashu" ? { cashuFlow: "p2pk_accumulator" } : {},
73590
73948
  creditId: draw.creditId,
73591
73949
  drawId: draw.drawId,
73950
+ upfrontPayment: upfrontPaymentFromDraw(draw),
73592
73951
  drawAmountMicro: draw.amountMicro,
73593
73952
  ...draw.railValue.creditCurrency ? { creditCurrency: draw.railValue.creditCurrency } : {}
73594
73953
  };
@@ -73674,6 +74033,7 @@ function removeUnavailableContent(fields) {
73674
74033
  }
73675
74034
  function terminalResponseFields(job) {
73676
74035
  const fields = {};
74036
+ if (job.upfrontPayment !== void 0) fields.upfront_payment = job.upfrontPayment;
73677
74037
  if (job.status === "completed") {
73678
74038
  if (job.summary !== void 0) fields.summary = job.summary;
73679
74039
  const artifactCount = job.messages.filter((m) => m.type === "artifact").length;