@dvmkit/dvm-cli 0.9.2 → 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-5R3BLFVO.js → chunk-6EYBCGGD.js} +2 -2
  3. package/dist/{chunk-BCDMVIPI.js → chunk-7N3HQJKE.js} +4 -4
  4. package/dist/{chunk-C7ZNQONB.js → chunk-BPWZNIMS.js} +2 -2
  5. package/dist/{chunk-PMPHS3LS.js → chunk-GEZVSJDM.js} +3 -3
  6. package/dist/{chunk-GD25CUI4.js → chunk-GHNF2I5C.js} +4 -4
  7. package/dist/{chunk-XDYBVNFS.js → chunk-HWWW7JEM.js} +3 -3
  8. package/dist/{chunk-MVVKMKWR.js → chunk-JJBRTWWS.js} +984 -24
  9. package/dist/{chunk-HUBCGZJL.js → chunk-K562SFVD.js} +2 -2
  10. package/dist/{chunk-6XTWANVN.js → chunk-MBSCP52L.js} +1073 -252
  11. package/dist/{chunk-QDOY3JF2.js → chunk-MMXHV3KC.js} +2 -2
  12. package/dist/{chunk-IEWV3CM2.js → chunk-UVFFMKU4.js} +3 -1
  13. package/dist/{client-MMJYIMKJ.js → client-DS4QJ346.js} +6 -6
  14. package/dist/dvm.js +1379 -1171
  15. package/dist/{internal-LRW4XR3J.js → internal-ZZHCUKOM.js} +15 -5
  16. package/dist/{lifecycle-QE3KHIHQ.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-J3BME4O3.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-HJQYBOZR.js → tempo-lifecycle-LGGBDCKK.js} +8 -8
  21. package/dist/{tempo-wallet-XN72C2GK.js → tempo-wallet-PLFC443A.js} +7 -7
  22. package/dist/{wallet-UEQTGVJE.js → wallet-UJ7EJNQA.js} +7 -7
  23. package/dist/{x402-RUJ4LUKF-ZB7JM22B.js → x402-AY6P5KV4-SIZF7YNW.js} +2 -2
  24. package/package.json +6 -3
  25. package/skills/dvm/calling.md +17 -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";
@@ -4924,7 +4924,7 @@ function hexToBytes3(hex3) {
4924
4924
  return out;
4925
4925
  }
4926
4926
 
4927
- // node_modules/@dvmkit/sdk/dist/chunk-5H7P3ORL.js
4927
+ // node_modules/@dvmkit/sdk/dist/chunk-5UC7TOQC.js
4928
4928
  function computeResultHash(summary, artifactContents) {
4929
4929
  const artifactHashes = artifactContents.map(
4930
4930
  (content) => bytesToHex(sha256(canonicaliseForSigning(content)))
@@ -4982,6 +4982,25 @@ function verifyFundingReceipt(receipt) {
4982
4982
  return false;
4983
4983
  }
4984
4984
  }
4985
+ function signDrawFundingReceipt(unsigned2, secretHex) {
4986
+ const bytes = canonicaliseForSigning(unsigned2);
4987
+ const signature = bytesToHex(schnorr.sign(bytes, hexToBytes(secretHex)));
4988
+ return { ...unsigned2, signature };
4989
+ }
4990
+ function isDrawFundingReceipt(value) {
4991
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4992
+ const r = value;
4993
+ return r.v === 1 && r.kind === "credit_draw_funding" && typeof r.credit_id === "string" && typeof r.job_id === "string" && typeof r.draw_id === "string" && typeof r.fund_id === "string" && (r.payment_seq === void 0 || typeof r.payment_seq === "number") && typeof r.currency === "string" && typeof r.funded_micro === "number" && typeof r.balance_after_micro === "number" && typeof r.ledger_seq === "number" && typeof r.issued_at === "number" && typeof r.caller_pubkey === "string" && typeof r.dvm_id === "string" && typeof r.dvm === "string" && typeof r.receipt_pubkey === "string" && typeof r.signature === "string";
4994
+ }
4995
+ function verifyDrawFundingReceipt(receipt) {
4996
+ try {
4997
+ const { signature, ...unsigned2 } = receipt;
4998
+ const bytes = canonicaliseForSigning(unsigned2);
4999
+ return schnorr.verify(hexToBytes(signature), bytes, hexToBytes(receipt.receipt_pubkey));
5000
+ } catch {
5001
+ return false;
5002
+ }
5003
+ }
4985
5004
  function isDrainReceipt(value) {
4986
5005
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4987
5006
  const r = value;
@@ -4997,7 +5016,7 @@ function verifyDrainReceipt(receipt) {
4997
5016
  }
4998
5017
  }
4999
5018
 
5000
- // node_modules/@dvmkit/sdk/dist/chunk-RPUFWIT4.js
5019
+ // node_modules/@dvmkit/sdk/dist/chunk-LZFZGY7L.js
5001
5020
  import { homedir } from "os";
5002
5021
  import { join as join3 } from "path";
5003
5022
  import { chmodSync, mkdirSync, statSync } from "fs";
@@ -10240,7 +10259,7 @@ zero
10240
10259
  zone
10241
10260
  zoo`.split("\n");
10242
10261
 
10243
- // node_modules/@dvmkit/sdk/dist/chunk-RPUFWIT4.js
10262
+ // node_modules/@dvmkit/sdk/dist/chunk-LZFZGY7L.js
10244
10263
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
10245
10264
  import { existsSync as existsSync4, readFileSync as readFileSync4, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs";
10246
10265
 
@@ -20214,7 +20233,7 @@ function expand(hash4, prk, info, length = 32) {
20214
20233
  }
20215
20234
  var hkdf = (hash4, ikm, salt, info, length) => expand(hash4, extract(hash4, ikm, salt), info, length);
20216
20235
 
20217
- // node_modules/@dvmkit/sdk/dist/chunk-RPUFWIT4.js
20236
+ // node_modules/@dvmkit/sdk/dist/chunk-LZFZGY7L.js
20218
20237
  import { randomBytes as randomBytes6 } from "crypto";
20219
20238
  import {
20220
20239
  chmodSync as chmodSync4,
@@ -20241,7 +20260,7 @@ function toLockPubkey(raw2) {
20241
20260
  function isX402SettlementReconciliationReason(value) {
20242
20261
  return value === "settlement_not_on_chain" || value === "chain_unreachable" || value === "settlement_unbookmarked" || value === "facilitator_channel_state_unavailable";
20243
20262
  }
20244
- var IMPLICIT_CREDIT_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
20263
+ var IMPLICIT_CREDIT_TTL_MS = 90 * 24 * 60 * 60 * 1e3;
20245
20264
  var TEMPO_SESSION_UPDATED_REASON = "Tempo session updated; attach the next voucher to fund this credit.";
20246
20265
  var CONFIG_DIR = process.env.DVM_CONFIG_DIR ?? join3(homedir(), ".dvm");
20247
20266
  var CONFIG_FILE = join3(CONFIG_DIR, "config.json");
@@ -21810,6 +21829,53 @@ function verifyFundingReceiptChain(args) {
21810
21829
  receipt: named
21811
21830
  };
21812
21831
  }
21832
+ function verifyDrawFundingReceiptChain(args) {
21833
+ const named = isDrawFundingReceipt(args.receipt) ? args.receipt : void 0;
21834
+ const check2 = (actual, expected) => expected === void 0 ? "unchecked" : actual === expected ? "ok" : "mismatch";
21835
+ const checks = {
21836
+ credit_id: check2(named?.credit_id, args.expectedCreditId),
21837
+ job_id: check2(named?.job_id, args.expectedJobId),
21838
+ draw_id: check2(named?.draw_id, args.expectedDrawId),
21839
+ fund_id: check2(named?.fund_id, args.expectedFundId),
21840
+ currency: check2(named?.currency, args.expectedCurrency),
21841
+ funded_micro: check2(named?.funded_micro, args.expectedFundedMicro),
21842
+ ledger_seq: check2(named?.ledger_seq, args.expectedLedgerSeq),
21843
+ caller_pubkey: check2(named?.caller_pubkey, args.expectedCallerPubkey),
21844
+ signature: named !== void 0 && verifyDrawFundingReceipt(named),
21845
+ attestation: "absent"
21846
+ };
21847
+ const mismatch = [
21848
+ ["credit_id", "credit_id_mismatch"],
21849
+ ["job_id", "job_id_mismatch"],
21850
+ ["draw_id", "draw_id_mismatch"],
21851
+ ["fund_id", "fund_id_mismatch"],
21852
+ ["currency", "funding_currency_mismatch"],
21853
+ ["funded_micro", "funding_amount_mismatch"],
21854
+ ["ledger_seq", "funding_ledger_seq_mismatch"],
21855
+ ["caller_pubkey", "caller_pubkey_mismatch"]
21856
+ ];
21857
+ for (const [field, reason] of mismatch) {
21858
+ if (checks[field] === "mismatch") return { status: "invalid", checks, reason, receipt: named };
21859
+ }
21860
+ if (!named || !checks.signature) {
21861
+ return { status: "invalid", checks, reason: "signature_invalid", receipt: named };
21862
+ }
21863
+ checks.attestation = checkReceiptAttestation(named, args.builder);
21864
+ if (checks.attestation === "invalid") {
21865
+ return { status: "invalid", checks, reason: "attestation_invalid", receipt: named };
21866
+ }
21867
+ if (checks.attestation === "identity_mismatch") {
21868
+ return { status: "invalid", checks, reason: "dvm_identity_mismatch", receipt: named };
21869
+ }
21870
+ if (checks.attestation === "key_mismatch") {
21871
+ return { status: "invalid", checks, reason: "receipt_key_mismatch", receipt: named };
21872
+ }
21873
+ return {
21874
+ status: checks.attestation === "ok" ? "verified" : "verified_unattested",
21875
+ checks,
21876
+ receipt: named
21877
+ };
21878
+ }
21813
21879
  function weakestReceiptVerdict(statuses) {
21814
21880
  if (statuses.length === 0) return "absent";
21815
21881
  if (statuses.includes("invalid")) return "invalid";
@@ -21872,7 +21938,7 @@ function createMonotonicClock() {
21872
21938
  };
21873
21939
  }
21874
21940
 
21875
- // node_modules/@dvmkit/sdk/dist/chunk-HW2UCOOC.js
21941
+ // node_modules/@dvmkit/sdk/dist/chunk-SXL44PL5.js
21876
21942
  function isZodSchema(value) {
21877
21943
  return typeof value === "object" && value !== null && "_zod" in value && "parse" in value && "safeParse" in value;
21878
21944
  }
@@ -21881,7 +21947,7 @@ var RAIL_REFUNDABLE = {
21881
21947
  x402: false,
21882
21948
  tempo: false
21883
21949
  };
21884
- var DEFAULT_CREDIT_TTL_SECONDS = 30 * 24 * 60 * 60;
21950
+ var DEFAULT_CREDIT_TTL_SECONDS = 90 * 24 * 60 * 60;
21885
21951
  var SIGNED_REQUEST_AUTH_ID = "secp256k1-schnorr-v2";
21886
21952
  var SIGNED_REQUEST_STATEMENT_VERSION = 2;
21887
21953
  function normalizeSignedRequestDomain(domain) {
@@ -21919,7 +21985,7 @@ function canonicalRequestPath(pathOrUrl) {
21919
21985
  return parsed.pathname.startsWith("/") ? parsed.pathname : `/${parsed.pathname}`;
21920
21986
  }
21921
21987
 
21922
- // node_modules/@dvmkit/sdk/dist/chunk-7KQLPVV7.js
21988
+ // node_modules/@dvmkit/sdk/dist/chunk-7NZRJPEP.js
21923
21989
  function createConsoleLogger(_jobId) {
21924
21990
  return {
21925
21991
  debug(_message, data) {
@@ -21989,7 +22055,7 @@ var StepCache = class _StepCache {
21989
22055
  }
21990
22056
  };
21991
22057
 
21992
- // node_modules/@dvmkit/sdk/dist/chunk-LDKV4UHI.js
22058
+ // node_modules/@dvmkit/sdk/dist/chunk-CVT5LTAK.js
21993
22059
  var InvalidCurrencyError = class extends Error {
21994
22060
  code = "invalid_currency";
21995
22061
  raw;
@@ -22441,7 +22507,7 @@ function resolveFxSourceFromEnv(env) {
22441
22507
  return raw2;
22442
22508
  }
22443
22509
 
22444
- // node_modules/@dvmkit/sdk/dist/chunk-EP7OVWI5.js
22510
+ // node_modules/@dvmkit/sdk/dist/chunk-FOXGN4KQ.js
22445
22511
  import { AsyncLocalStorage } from "async_hooks";
22446
22512
  var postgresRecovery = new AsyncLocalStorage();
22447
22513
  function withPostgresRecoveryContext(context, operation) {
@@ -22598,7 +22664,7 @@ function truncateUtf8(value, maxBytes) {
22598
22664
  return result;
22599
22665
  }
22600
22666
 
22601
- // node_modules/@dvmkit/sdk/dist/chunk-HNXMWHLU.js
22667
+ // node_modules/@dvmkit/sdk/dist/chunk-R7FH7SHX.js
22602
22668
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
22603
22669
  import { randomBytes as randomBytes7, randomUUID } from "crypto";
22604
22670
  import { hostname } from "os";
@@ -26864,6 +26930,7 @@ function recordFundResponse(args) {
26864
26930
  record2.balanceMicro = args.credit.balance_micro;
26865
26931
  record2.remainingMicro = args.credit.remaining_micro;
26866
26932
  record2.ledgerSeq = Math.max(record2.ledgerSeq, args.credit.ledger_seq);
26933
+ pruneDrawFundings(record2, record2.ledgerSeq);
26867
26934
  record2.expiryMs = args.credit.expiry_ms;
26868
26935
  record2.targetMicro = args.targetMicro;
26869
26936
  record2.status = args.credit.status === "unbacked" ? "unbacked" : args.credit.expired ? "expired" : "active";
@@ -26946,15 +27013,42 @@ function applyReceiptCredit(args) {
26946
27013
  where: (c) => c.callerPubkey === args.callerPubkey && c.creditId === args.credit.credit_id
26947
27014
  });
26948
27015
  if (!record2) return {};
27016
+ let admitted = false;
27017
+ for (const evidence of args.drawFundings ?? []) {
27018
+ const verdict = admitDrawFunding(record2, {
27019
+ callerPubkey: args.callerPubkey,
27020
+ identity: args.identity,
27021
+ receipt: evidence.receipt,
27022
+ builder: evidence.builder,
27023
+ now
27024
+ });
27025
+ admitted ||= verdict.recorded;
27026
+ }
27027
+ if (args.credit.ledger_seq < record2.ledgerSeq) {
27028
+ if (admitted) {
27029
+ attachDvmLocation(record2, key, args.identity);
27030
+ record2.updatedAt = now;
27031
+ saveStore(store);
27032
+ }
27033
+ return { credit: record2 };
27034
+ }
26949
27035
  attachDvmLocation(record2, key, args.identity);
26950
27036
  let mismatch;
27037
+ let fundedMicro;
26951
27038
  const sequential = args.credit.ledger_seq === record2.ledgerSeq + 1;
26952
27039
  if (sequential && args.outcome === "completed" && record2.status === "active" && !record2.provisional && !record2.unsequencedBalance) {
26953
- const expected = record2.remainingMicro - args.credit.amount;
27040
+ const eligible = (record2.drawFundings ?? []).filter(
27041
+ (fact) => fact.drawId === args.credit.draw_id && fact.ledgerSeq === args.credit.ledger_seq
27042
+ );
27043
+ if (eligible.length > 0) {
27044
+ fundedMicro = eligible.reduce((sum, fact) => sum + fact.fundedMicro, 0);
27045
+ }
27046
+ const expected = record2.remainingMicro + (fundedMicro ?? 0) - args.credit.amount;
26954
27047
  if (args.credit.balance_after !== expected) {
26955
27048
  mismatch = {
26956
27049
  atMs: now,
26957
27050
  expectedMicro: expected,
27051
+ ...fundedMicro !== void 0 ? { fundedMicro } : {},
26958
27052
  reportedMicro: args.credit.balance_after,
26959
27053
  drawId: args.credit.draw_id,
26960
27054
  ledgerSeq: args.credit.ledger_seq,
@@ -26964,11 +27058,10 @@ function applyReceiptCredit(args) {
26964
27058
  record2.discrepancy = mismatch;
26965
27059
  }
26966
27060
  }
26967
- if (args.credit.ledger_seq >= record2.ledgerSeq) {
26968
- record2.remainingMicro = args.credit.balance_after;
26969
- record2.ledgerSeq = args.credit.ledger_seq;
26970
- delete record2.unsequencedBalance;
26971
- }
27061
+ record2.remainingMicro = args.credit.balance_after;
27062
+ record2.ledgerSeq = args.credit.ledger_seq;
27063
+ pruneDrawFundings(record2, record2.ledgerSeq, args.credit.draw_id);
27064
+ delete record2.unsequencedBalance;
26972
27065
  delete record2.provisional;
26973
27066
  if (args.outcome === "completed") record2.lastPriceMicro = args.credit.amount;
26974
27067
  if (!mismatch && record2.discrepancy && args.credit.ledger_seq > record2.discrepancy.ledgerSeq) {
@@ -26977,8 +27070,102 @@ function applyReceiptCredit(args) {
26977
27070
  record2.lastReceiptJobId = args.jobId;
26978
27071
  record2.updatedAt = now;
26979
27072
  saveStore(store);
26980
- return { credit: record2, ...mismatch ? { mismatch } : {} };
27073
+ return {
27074
+ credit: record2,
27075
+ ...mismatch ? { mismatch } : {},
27076
+ ...fundedMicro !== void 0 ? { fundedMicro } : {}
27077
+ };
27078
+ });
27079
+ }
27080
+ function recordDrawFunding(args) {
27081
+ const now = args.now ?? Date.now();
27082
+ return withCreditLock(() => {
27083
+ const store = loadStore();
27084
+ const key = normalizeCreditEndpoint(args.endpoint);
27085
+ if (!isDrawFundingReceipt(args.receipt)) {
27086
+ return { recorded: false, reason: "invalid", verifyReason: "signature_invalid" };
27087
+ }
27088
+ const named = args.receipt;
27089
+ const record2 = findDvmLocated(store.credits, {
27090
+ endpoint: key,
27091
+ ...args.identity ? { identity: args.identity } : {},
27092
+ where: (c) => c.callerPubkey === args.callerPubkey && c.creditId === named.credit_id
27093
+ });
27094
+ if (!record2) return { recorded: false, reason: "unknown_credit" };
27095
+ const verdict = admitDrawFunding(record2, {
27096
+ callerPubkey: args.callerPubkey,
27097
+ identity: args.identity,
27098
+ receipt: named,
27099
+ builder: args.builder,
27100
+ now
27101
+ });
27102
+ if (verdict.recorded) {
27103
+ attachDvmLocation(record2, key, args.identity);
27104
+ record2.updatedAt = now;
27105
+ saveStore(store);
27106
+ }
27107
+ return { credit: record2, ...verdict };
27108
+ });
27109
+ }
27110
+ function admitDrawFunding(record2, args) {
27111
+ const verdict = verifyDrawFundingReceiptChain({
27112
+ receipt: args.receipt,
27113
+ builder: args.builder,
27114
+ expectedCallerPubkey: args.callerPubkey,
27115
+ expectedCreditId: record2.creditId
27116
+ });
27117
+ const named = verdict.receipt;
27118
+ if (!named) return { recorded: false, reason: "invalid", verifyReason: "signature_invalid" };
27119
+ if (verdict.reason === "caller_pubkey_mismatch") return { recorded: false, reason: "caller_mismatch" };
27120
+ if (verdict.reason === "credit_id_mismatch") return { recorded: false, reason: "unknown_credit" };
27121
+ if (verdict.status === "invalid") {
27122
+ const provider = verdict.reason === "dvm_identity_mismatch" || verdict.reason === "receipt_key_mismatch" || verdict.reason === "attestation_invalid";
27123
+ return {
27124
+ recorded: false,
27125
+ reason: provider ? "provider_mismatch" : "invalid",
27126
+ ...verdict.reason ? { verifyReason: verdict.reason } : {}
27127
+ };
27128
+ }
27129
+ if (args.identity && named.dvm_id !== args.identity.dvmId) {
27130
+ return { recorded: false, reason: "provider_mismatch", verifyReason: "dvm_identity_mismatch" };
27131
+ }
27132
+ if (record2.dvmId !== void 0 && named.dvm_id !== record2.dvmId) {
27133
+ return { recorded: false, reason: "provider_mismatch", verifyReason: "dvm_identity_mismatch" };
27134
+ }
27135
+ const attested = dvmLocationIdentity(record2);
27136
+ if (attested) {
27137
+ const anchorPubkey = args.builder?.pubkey?.trim().toLowerCase();
27138
+ if (verdict.status !== "verified" || anchorPubkey !== attested.builderPubkey) {
27139
+ return { recorded: false, reason: "provider_mismatch", verifyReason: "receipt_key_mismatch" };
27140
+ }
27141
+ }
27142
+ if (named.currency !== record2.currency) return { recorded: false, reason: "currency_mismatch" };
27143
+ if (named.ledger_seq <= record2.ledgerSeq) return { recorded: false, reason: "already_reflected" };
27144
+ const held = record2.drawFundings ?? [];
27145
+ if (held.some((fact) => fact.fundId === named.fund_id)) {
27146
+ return { recorded: false, reason: "duplicate" };
27147
+ }
27148
+ held.push({
27149
+ fundId: named.fund_id,
27150
+ jobId: named.job_id,
27151
+ drawId: named.draw_id,
27152
+ fundedMicro: named.funded_micro,
27153
+ ledgerSeq: named.ledger_seq,
27154
+ balanceAfterMicro: named.balance_after_micro,
27155
+ recordedAt: args.now,
27156
+ receipt: named
26981
27157
  });
27158
+ held.sort((a, b2) => a.ledgerSeq - b2.ledgerSeq || a.recordedAt - b2.recordedAt);
27159
+ record2.drawFundings = held;
27160
+ return { recorded: true };
27161
+ }
27162
+ function pruneDrawFundings(record2, ledgerSeq, drawId) {
27163
+ if (!record2.drawFundings) return;
27164
+ const kept = record2.drawFundings.filter(
27165
+ (fact) => fact.ledgerSeq > ledgerSeq && (drawId === void 0 || fact.drawId !== drawId)
27166
+ );
27167
+ if (kept.length === 0) delete record2.drawFundings;
27168
+ else record2.drawFundings = kept;
26982
27169
  }
26983
27170
  function applyImplicitReceiptCredit(args) {
26984
27171
  if (!args.credit.credit_id.startsWith("imp:")) return {};
@@ -27336,6 +27523,7 @@ function adoptCreditId(record2, creditId) {
27336
27523
  delete record2.refillDrainNoticed;
27337
27524
  delete record2.discrepancy;
27338
27525
  delete record2.lastReceiptJobId;
27526
+ delete record2.drawFundings;
27339
27527
  }
27340
27528
  var MAX_SETTLED_DRAIN_EVIDENCE = 8;
27341
27529
  var MAX_LOST_IMPLICIT_CREDITS = 8;
@@ -31275,7 +31463,7 @@ function parseStoreValue(value) {
31275
31463
  return parsed;
31276
31464
  }
31277
31465
 
31278
- // node_modules/@dvmkit/sdk/dist/chunk-NS2OMIU7.js
31466
+ // node_modules/@dvmkit/sdk/dist/chunk-RQK7OFJO.js
31279
31467
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
31280
31468
  var PostgresTempoSessionStore = class {
31281
31469
  constructor(pool) {
@@ -31853,7 +32041,7 @@ function acceptanceVoucherAmount(acceptance, key, current, next) {
31853
32041
  return authorized !== void 0 && authorized >= acceptance.cumulativeAmount ? acceptance.cumulativeAmount : void 0;
31854
32042
  }
31855
32043
 
31856
- // node_modules/@dvmkit/sdk/dist/chunk-FFRTAQUW.js
32044
+ // node_modules/@dvmkit/sdk/dist/chunk-P5KQKLWL.js
31857
32045
  import { createHash as createHash5 } from "crypto";
31858
32046
  var DEFAULT_TABLE_NAME = "mpp_tempo_charge_replays";
31859
32047
  var DEFAULT_RETENTION_MS = 60 * 60 * 1e3;
@@ -32208,7 +32396,7 @@ function isUniqueViolation(err) {
32208
32396
  return typeof err === "object" && err !== null && err.code === "23505";
32209
32397
  }
32210
32398
 
32211
- // node_modules/@dvmkit/sdk/dist/chunk-2VGMZ7VF.js
32399
+ // node_modules/@dvmkit/sdk/dist/chunk-LM6E4YHQ.js
32212
32400
  import { randomUUID as randomUUID3 } from "crypto";
32213
32401
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
32214
32402
  import { isDeepStrictEqual } from "util";
@@ -33526,7 +33714,11 @@ var CreditLedger = class {
33526
33714
  "caller_pubkey TEXT",
33527
33715
  "balance_after_micro BIGINT",
33528
33716
  "ledger_seq BIGINT",
33529
- "receipt JSONB"
33717
+ "receipt JSONB",
33718
+ // Mid-job draw funding bindings; null on opening and `/v1/credit` fundings.
33719
+ "job_id TEXT",
33720
+ "draw_id TEXT",
33721
+ "payment_seq BIGINT"
33530
33722
  ]) {
33531
33723
  await this.pool.query(`ALTER TABLE credit_fundings ADD COLUMN IF NOT EXISTS ${column}`);
33532
33724
  }
@@ -33727,8 +33919,8 @@ var CreditLedger = class {
33727
33919
  );
33728
33920
  }
33729
33921
  /**
33730
- * Funding adds balance and overwrites expiry, reviving an expired credit. It is additive,
33731
- * not idempotent: the caller’s rail marker or funding record must prevent replay. Owner and
33922
+ * Funding adds balance and extends expiry without shortening it, reviving an expired credit.
33923
+ * It is additive, not idempotent: the caller’s rail marker or funding record must prevent replay. Owner and
33732
33924
  * currency must match; rail and reusable-channel bindings cannot be mixed with other
33733
33925
  * instruments. A legacy NULL rail adopts its first typed top-up.
33734
33926
  *
@@ -33797,7 +33989,7 @@ var CreditLedger = class {
33797
33989
  ON CONFLICT (credit_id) DO UPDATE
33798
33990
  SET balance_micro = credits.balance_micro + EXCLUDED.balance_micro,
33799
33991
  last_funding_ledger_seq = credits.last_ledger_seq,
33800
- expiry_ms = EXCLUDED.expiry_ms,
33992
+ expiry_ms = GREATEST(credits.expiry_ms, EXCLUDED.expiry_ms),
33801
33993
  rail = COALESCE(credits.rail, EXCLUDED.rail),
33802
33994
  native_asset = COALESCE(EXCLUDED.native_asset, credits.native_asset),
33803
33995
  mint = COALESCE(EXCLUDED.mint, credits.mint),
@@ -34648,11 +34840,21 @@ var CreditLedger = class {
34648
34840
  });
34649
34841
  const nowMs = args.nowMs ?? Date.now();
34650
34842
  const { rows: rows2 } = await q2.query(
34651
- `INSERT INTO credit_fundings (credit_id, fund_id, amount_micro, rail, created_at)
34652
- VALUES ($1, $2, $3, $4, $5)
34843
+ `INSERT INTO credit_fundings
34844
+ (credit_id, fund_id, amount_micro, rail, created_at, job_id, draw_id, payment_seq)
34845
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
34653
34846
  ON CONFLICT (credit_id, fund_id) DO NOTHING
34654
34847
  RETURNING *`,
34655
- [args.creditId, args.fundId, args.amountMicro, args.rail ?? null, nowMs]
34848
+ [
34849
+ args.creditId,
34850
+ args.fundId,
34851
+ args.amountMicro,
34852
+ args.rail ?? null,
34853
+ nowMs,
34854
+ args.jobId ?? null,
34855
+ args.drawId ?? null,
34856
+ args.paymentSeq ?? null
34857
+ ]
34656
34858
  );
34657
34859
  if (rows2.length === 0) {
34658
34860
  throw new CreditLedgerError(
@@ -34675,6 +34877,19 @@ var CreditLedger = class {
34675
34877
  );
34676
34878
  return rows2.length > 0 ? fundingRecordFromRow(rows2[0]) : void 0;
34677
34879
  }
34880
+ /**
34881
+ * Every funding accepted against one job's draw, oldest first. The order is
34882
+ * stable across reads so a job read lists the same evidence each time.
34883
+ */
34884
+ async listDrawFundings(args) {
34885
+ const { rows: rows2 } = await this.pool.query(
34886
+ `SELECT * FROM credit_fundings
34887
+ WHERE credit_id = $1 AND draw_id = $2
34888
+ ORDER BY created_at ASC, fund_id ASC`,
34889
+ [args.creditId, args.drawId]
34890
+ );
34891
+ return rows2.map(fundingRecordFromRow);
34892
+ }
34678
34893
  /** Fix the funding-time receipt tuple inside the rail's open transaction. */
34679
34894
  async completeFunding(args) {
34680
34895
  const q2 = args.tx ?? this.pool;
@@ -34874,7 +35089,10 @@ var CreditLedger = class {
34874
35089
  [args.creditId, args.fundId, settledAt]
34875
35090
  );
34876
35091
  if (args.depositOutbox) {
34877
- await args.depositOutbox.enqueue(client, args.depositOutbox.payload);
35092
+ await args.depositOutbox.enqueue(client, {
35093
+ ...args.depositOutbox.payload,
35094
+ expiryMs: credit.expiryMs
35095
+ });
34878
35096
  }
34879
35097
  await client.query("COMMIT");
34880
35098
  return {
@@ -35045,7 +35263,10 @@ var CreditLedger = class {
35045
35263
  ]
35046
35264
  );
35047
35265
  if (args.depositOutbox) {
35048
- await args.depositOutbox.enqueue(client, args.depositOutbox.payload);
35266
+ await args.depositOutbox.enqueue(client, {
35267
+ ...args.depositOutbox.payload,
35268
+ expiryMs: credit.expiryMs
35269
+ });
35049
35270
  }
35050
35271
  await client.query("COMMIT");
35051
35272
  return {
@@ -36511,7 +36732,10 @@ function fundingRecordFromRow(row) {
36511
36732
  callerPubkey: row.caller_pubkey,
36512
36733
  balanceAfterMicro: row.balance_after_micro === null ? null : toSafeInt(row.balance_after_micro),
36513
36734
  ledgerSeq: row.ledger_seq === null ? null : toSafeInt(row.ledger_seq),
36514
- receipt: row.receipt
36735
+ receipt: row.receipt,
36736
+ jobId: row.job_id ?? null,
36737
+ drawId: row.draw_id ?? null,
36738
+ paymentSeq: row.payment_seq === null || row.payment_seq === void 0 ? null : toSafeInt(row.payment_seq)
36515
36739
  };
36516
36740
  }
36517
36741
  function invoiceRecordFromRow(row) {
@@ -36568,7 +36792,7 @@ function expiryReleaseReport(dvmId, row) {
36568
36792
  };
36569
36793
  }
36570
36794
 
36571
- // node_modules/@dvmkit/sdk/dist/chunk-POYUX2NN.js
36795
+ // node_modules/@dvmkit/sdk/dist/chunk-33J3NQDZ.js
36572
36796
  import { randomUUID as randomUUID4 } from "crypto";
36573
36797
  var MemoryCreditLedger = class _MemoryCreditLedger {
36574
36798
  /**
@@ -36739,7 +36963,10 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
36739
36963
  callerPubkey: null,
36740
36964
  balanceAfterMicro: null,
36741
36965
  ledgerSeq: null,
36742
- receipt: null
36966
+ receipt: null,
36967
+ jobId: args.jobId ?? null,
36968
+ drawId: args.drawId ?? null,
36969
+ paymentSeq: args.paymentSeq ?? null
36743
36970
  };
36744
36971
  this.fundings.set(key, record2);
36745
36972
  return record2;
@@ -36748,6 +36975,11 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
36748
36975
  getFunding(args) {
36749
36976
  return run(() => this.fundings.get(fundingKey(args.creditId, args.fundId)));
36750
36977
  }
36978
+ listDrawFundings(args) {
36979
+ return run(
36980
+ () => [...this.fundings.values()].filter((funding) => funding.creditId === args.creditId && funding.drawId === args.drawId).sort((a, b2) => a.createdAt - b2.createdAt || a.fundId.localeCompare(b2.fundId))
36981
+ );
36982
+ }
36751
36983
  completeFunding(args) {
36752
36984
  return run(() => {
36753
36985
  const key = fundingKey(args.creditId, args.fundId);
@@ -37067,7 +37299,7 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
37067
37299
  }
37068
37300
  existing.lastFundingLedgerSeq = existing.lastLedgerSeq;
37069
37301
  existing.balanceMicro += args.amountMicro;
37070
- existing.expiryMs = args.expiryMs;
37302
+ existing.expiryMs = Math.max(existing.expiryMs, args.expiryMs);
37071
37303
  applyBasis(existing, b2);
37072
37304
  recordLot(existing, args.amountMicro, b2, nowMs);
37073
37305
  return this.snapshot(existing, nowMs);
@@ -37993,7 +38225,7 @@ function assertAmount2(amountMicro, opts) {
37993
38225
  }
37994
38226
  }
37995
38227
 
37996
- // node_modules/@dvmkit/sdk/dist/chunk-AFV77S4C.js
38228
+ // node_modules/@dvmkit/sdk/dist/chunk-KVKJ7R5V.js
37997
38229
  import { randomUUID as randomUUID5 } from "crypto";
37998
38230
  function toJobRecord(job) {
37999
38231
  return {
@@ -38018,6 +38250,7 @@ function toJobRecord(job) {
38018
38250
  awaitingInputAtMs: job.awaitingInputAtMs,
38019
38251
  messages: job.messages,
38020
38252
  seq: job.seq,
38253
+ upfrontPayment: job.upfrontPayment,
38021
38254
  paidMsats: job.paidMsats,
38022
38255
  paymentMint: job.paymentMint,
38023
38256
  paymentRail: job.paymentRail,
@@ -38069,6 +38302,7 @@ function fromJobRecord(record2) {
38069
38302
  awaitingInputAtMs: record2.awaitingInputAtMs,
38070
38303
  messages: [...record2.messages],
38071
38304
  seq: record2.seq,
38305
+ upfrontPayment: record2.upfrontPayment,
38072
38306
  paidMsats: record2.paidMsats,
38073
38307
  paymentMint: record2.paymentMint,
38074
38308
  paymentRail: record2.paymentRail,
@@ -38130,6 +38364,9 @@ function providerMessage(job, type, content) {
38130
38364
  job.replayProviderSkip--;
38131
38365
  return;
38132
38366
  }
38367
+ if (type === "prompt" || type === "payment-request") {
38368
+ content = { ...content, expires_at_ms: Date.now() + (job.idleTimeoutMs ?? 36e5) };
38369
+ }
38133
38370
  const msg = localMessage(job, "provider", type, content);
38134
38371
  if (type === "payment-request") {
38135
38372
  const paymentRequest = content;
@@ -38152,7 +38389,51 @@ function providerMessage(job, type, content) {
38152
38389
  }
38153
38390
  job.messageAppender?.(msg, type === "prompt" ? { awaitingInput: job.status === "awaiting-input" } : void 0);
38154
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
+ }
38155
38432
  function localMessage(job, from, type, content) {
38433
+ if (type === "cancel" || type === "complete") {
38434
+ historyHolds.get(job)?.clear();
38435
+ flushJobHistory(job);
38436
+ }
38156
38437
  job.seq++;
38157
38438
  const msg = {
38158
38439
  seq: job.seq,
@@ -38162,8 +38443,13 @@ function localMessage(job, from, type, content) {
38162
38443
  content
38163
38444
  };
38164
38445
  job.messages.push(msg);
38165
- for (const listener of job.listeners) {
38166
- 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);
38167
38453
  }
38168
38454
  return msg;
38169
38455
  }
@@ -38173,6 +38459,26 @@ function isTerminal(status) {
38173
38459
  function isYieldMessage(msg) {
38174
38460
  return msg.type === "prompt" || msg.type === "payment-request" || msg.type === "working" || msg.type === "complete" || msg.type === "cancel";
38175
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
+ }
38176
38482
  var ContentHoldError = class extends Error {
38177
38483
  constructor(code) {
38178
38484
  super(code);
@@ -38230,7 +38536,7 @@ function applyContentHoldMutation(job, history, mutation) {
38230
38536
  return result;
38231
38537
  }
38232
38538
 
38233
- // node_modules/@dvmkit/sdk/dist/chunk-TWKQFIOW.js
38539
+ // node_modules/@dvmkit/sdk/dist/chunk-YMMCRQ2H.js
38234
38540
  import { createHash as createHash6 } from "crypto";
38235
38541
  var DEFAULT_BACKOFF_MS = [1e3, 4e3, 15e3, 3e4];
38236
38542
  var ListenChannel = class {
@@ -38478,6 +38784,7 @@ var PostgresJobStore = class {
38478
38784
  -- with a fund-and-draw response. INSERT-only for replay stability.
38479
38785
  ALTER TABLE jobs ADD COLUMN IF NOT EXISTS funding_receipt JSONB;
38480
38786
  ALTER TABLE jobs ADD COLUMN IF NOT EXISTS funding_credit JSONB;
38787
+ ALTER TABLE jobs ADD COLUMN IF NOT EXISTS upfront_payment JSONB;
38481
38788
  -- the outstanding mid-job ask, denominated in fiat micro at the
38482
38789
  -- instant it was emitted. The top-up's ledger leg funds and grows the
38483
38790
  -- draw in this figure, so it must not move with the BTC/USD rate between
@@ -38707,6 +39014,18 @@ var PostgresJobStore = class {
38707
39014
  }
38708
39015
  held.client.release();
38709
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
+ }
38710
39029
  async save(record2) {
38711
39030
  const dvmId = record2[JOB_DVM_ID];
38712
39031
  for (let attempt = 0; ; attempt++) {
@@ -38753,8 +39072,8 @@ var PostgresJobStore = class {
38753
39072
  last_activity_at, next_seq, requester_token_hash, requester_token,
38754
39073
  request_fingerprint, requester_pubkey, request_id, credit_id, draw_id,
38755
39074
  pending_payment_fiat_micro, pending_payment_fiat_currency, auth_request_path,
38756
- funding_receipt, funding_credit, dvm_id, terminal_at_ms, caller_wait_ms, awaiting_input_at_ms, ended_by, timing_known
38757
- ) 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)
38758
39077
  ON CONFLICT (id) DO UPDATE SET
38759
39078
  terminal_at_ms = COALESCE(jobs.terminal_at_ms, EXCLUDED.terminal_at_ms),
38760
39079
  ended_by = CASE WHEN jobs.status IN ('completed', 'failed', 'cancelled') THEN jobs.ended_by ELSE EXCLUDED.ended_by END,
@@ -38805,7 +39124,17 @@ var PostgresJobStore = class {
38805
39124
  pending_x402_nonce = EXCLUDED.pending_x402_nonce,
38806
39125
  pending_x402_amount_usdc_micro = EXCLUDED.pending_x402_amount_usdc_micro,
38807
39126
  required_msats = EXCLUDED.required_msats,
38808
- 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
+ ),
38809
39138
  state = EXCLUDED.state,
38810
39139
  last_activity_at = CASE WHEN jobs.status IN ('completed', 'failed', 'cancelled') THEN jobs.last_activity_at ELSE EXCLUDED.last_activity_at END
38811
39140
  -- terminal is terminal. On a multi-machine DVM a DELETE can
@@ -38883,7 +39212,8 @@ var PostgresJobStore = class {
38883
39212
  record2.status === "awaiting-input" ? record2.awaitingInputAtMs ?? now : null,
38884
39213
  isTerminalStatus(record2.status) && record2.status !== "completed" ? record2.endedBy ?? "provider" : null,
38885
39214
  now,
38886
- record2.timingKnown ?? true
39215
+ record2.timingKnown ?? true,
39216
+ record2.upfrontPayment ? JSON.stringify(record2.upfrontPayment) : null
38887
39217
  ]
38888
39218
  );
38889
39219
  let rowCount;
@@ -38922,6 +39252,7 @@ var PostgresJobStore = class {
38922
39252
  return;
38923
39253
  }
38924
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);
38925
39256
  await this.deleteResolvedMessages(record2.id).catch(() => void 0);
38926
39257
  }
38927
39258
  }
@@ -39390,7 +39721,11 @@ var PostgresJobStore = class {
39390
39721
  }
39391
39722
  async markInboundFailed(jobId, seq, _reason) {
39392
39723
  await this.pool.query(
39393
- "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`,
39394
39729
  [jobId, seq]
39395
39730
  );
39396
39731
  }
@@ -39509,10 +39844,24 @@ var PostgresJobStore = class {
39509
39844
  if (subSet.size === 0) this.notifySubscribers.delete(jobId);
39510
39845
  });
39511
39846
  }
39512
- async getMessages(jobId, afterSeq) {
39847
+ async getMessages(jobId, afterSeq, options) {
39513
39848
  const { rows: rows2 } = await this.pool.query(
39514
- "SELECT data FROM job_messages WHERE job_id = $1 AND seq > $2 AND status = 'verified' ORDER BY seq",
39515
- [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]
39516
39865
  );
39517
39866
  return rows2.map((r) => typeof r.data === "string" ? JSON.parse(r.data) : r.data);
39518
39867
  }
@@ -39590,7 +39939,7 @@ var PostgresJobStore = class {
39590
39939
  try {
39591
39940
  await client.query("BEGIN");
39592
39941
  const { rows: rows2 } = await client.query(
39593
- `SELECT next_seq FROM jobs
39942
+ `SELECT * FROM jobs
39594
39943
  WHERE id = $1
39595
39944
  AND status IN ('processing', 'working', 'awaiting-input')
39596
39945
  ${staleOnly ? "AND last_activity_at <= $2" : ""}
@@ -39601,6 +39950,22 @@ var PostgresJobStore = class {
39601
39950
  await client.query("ROLLBACK");
39602
39951
  return false;
39603
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
+ }
39604
39969
  const nextSeq = rows2[0].next_seq;
39605
39970
  const now = Date.now();
39606
39971
  const cancelMsg = {
@@ -39623,12 +39988,20 @@ var PostgresJobStore = class {
39623
39988
  awaiting_input_at_ms = NULL,
39624
39989
  status = $6,
39625
39990
  summary = COALESCE(summary, $2),
39626
- messages = COALESCE(messages, '[]'::jsonb) || $3::jsonb,
39991
+ messages = ${staleOnly ? "$3::jsonb" : "COALESCE(messages, '[]'::jsonb) || $3::jsonb"},
39627
39992
  seq = $4,
39628
39993
  next_seq = $4 + 1,
39629
39994
  last_activity_at = $5
39630
39995
  WHERE id = $1`,
39631
- [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
+ ]
39632
40005
  );
39633
40006
  await client.query("SELECT pg_notify('job_messages', $1)", [jobId]);
39634
40007
  await client.query("COMMIT");
@@ -39716,6 +40089,7 @@ function rowToRecord(row) {
39716
40089
  summary: row.summary,
39717
40090
  messages: row.messages,
39718
40091
  seq: row.seq,
40092
+ upfrontPayment: row.upfront_payment ?? void 0,
39719
40093
  paidMsats: Number(row.paid_msats),
39720
40094
  paymentMint: row.payment_mint,
39721
40095
  paymentRail: row.payment_rail ?? void 0,
@@ -39754,7 +40128,7 @@ function isTerminalStatus(status) {
39754
40128
  return status === "completed" || status === "failed" || status === "cancelled";
39755
40129
  }
39756
40130
 
39757
- // node_modules/@dvmkit/sdk/dist/chunk-WFCVS6QB.js
40131
+ // node_modules/@dvmkit/sdk/dist/chunk-ZO2ZAPG3.js
39758
40132
  function humanizeZodError(err, opts) {
39759
40133
  return humanizeZodIssues(err.issues, opts);
39760
40134
  }
@@ -39907,7 +40281,7 @@ function createDefaultReplayStore() {
39907
40281
  }
39908
40282
  var SATURATION_WARN_INTERVAL_SECONDS = 60;
39909
40283
 
39910
- // node_modules/@dvmkit/sdk/dist/chunk-KJZVTWMX.js
40284
+ // node_modules/@dvmkit/sdk/dist/chunk-PKLNMMKF.js
39911
40285
  function accumulateAskedTopUp(prior, ask) {
39912
40286
  const poisoned = (reason) => ({
39913
40287
  micro: UNCAPPABLE_ASK_TOTAL,
@@ -40009,7 +40383,10 @@ var MemoryJobStore = class {
40009
40383
  return Promise.resolve();
40010
40384
  }
40011
40385
  const snapshot = structuredClone(record2);
40012
- if (existing) snapshot.createdAt = existing.createdAt;
40386
+ if (existing) {
40387
+ snapshot.createdAt = existing.createdAt;
40388
+ snapshot.upfrontPayment = structuredClone(existing.upfrontPayment);
40389
+ }
40013
40390
  if (existing && isTerminal(existing.status)) snapshot.lastActivityAt = existing.lastActivityAt;
40014
40391
  if (existing?.receipt) snapshot.receipt = existing.receipt;
40015
40392
  snapshot.timingKnown = existing ? existing.timingKnown ?? false : record2.timingKnown ?? true;
@@ -40018,6 +40395,7 @@ var MemoryJobStore = class {
40018
40395
  const cur = this.nextSeq.get(record2.id) ?? 1;
40019
40396
  this.nextSeq.set(record2.id, Math.max(cur, record2.seq + 1));
40020
40397
  if (isTerminal(record2.status)) {
40398
+ this.notify(record2.id);
40021
40399
  this.messages.delete(record2.id);
40022
40400
  }
40023
40401
  return Promise.resolve();
@@ -40129,7 +40507,7 @@ var MemoryJobStore = class {
40129
40507
  }
40130
40508
  if (!isTerminal(record2.status)) record2.lastActivityAt = Date.now();
40131
40509
  if (seq > record2.seq) record2.seq = seq;
40132
- this.notify(jobId, fullMessage);
40510
+ this.notify(jobId);
40133
40511
  return Promise.resolve(seq);
40134
40512
  }
40135
40513
  recordInbound(jobId, message) {
@@ -40190,7 +40568,7 @@ var MemoryJobStore = class {
40190
40568
  }
40191
40569
  }
40192
40570
  if (!isTerminal(record2.status)) record2.lastActivityAt = Date.now();
40193
- this.notify(jobId, stored.message);
40571
+ this.notify(jobId);
40194
40572
  return Promise.resolve({
40195
40573
  counters: snapshotCounters(record2),
40196
40574
  alreadyVerified: false,
@@ -40211,6 +40589,7 @@ var MemoryJobStore = class {
40211
40589
  const stored = this.messagesFor(jobId).find((m) => m.message.seq === seq);
40212
40590
  if (stored?.status === "pending-verification") {
40213
40591
  stored.status = "failed-verify";
40592
+ this.notify(jobId);
40214
40593
  }
40215
40594
  return Promise.resolve();
40216
40595
  }
@@ -40301,11 +40680,8 @@ var MemoryJobStore = class {
40301
40680
  if (subSet.size === 0) this.notifySubscribers.delete(jobId);
40302
40681
  });
40303
40682
  }
40304
- getMessages(jobId, afterSeq) {
40305
- const stored = this.messagesFor(jobId);
40306
- return Promise.resolve(
40307
- stored.filter((m) => m.status === "verified" && m.message.seq > afterSeq).map((m) => m.message)
40308
- );
40683
+ getMessages(jobId, afterSeq, options) {
40684
+ return Promise.resolve(this.visibleMessages(jobId, afterSeq, options?.includeHeld));
40309
40685
  }
40310
40686
  initStreaming() {
40311
40687
  return Promise.resolve();
@@ -40326,6 +40702,15 @@ var MemoryJobStore = class {
40326
40702
  if (!record2) return Promise.resolve(false);
40327
40703
  const eligible = (record2.status === "processing" || record2.status === "working" || record2.status === "awaiting-input") && (expectedActivityBefore === null || record2.lastActivityAt <= expectedActivityBefore);
40328
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
+ }
40329
40714
  const seq = this.allocateSeq(jobId);
40330
40715
  const cancelMsg = {
40331
40716
  seq,
@@ -40335,14 +40720,14 @@ var MemoryJobStore = class {
40335
40720
  content: { reason }
40336
40721
  };
40337
40722
  this.messagesFor(jobId).push({ message: cancelMsg, status: "verified" });
40338
- record2.endedBy = expectedActivityBefore === null || record2.status === "awaiting-input" ? "caller" : "provider";
40723
+ record2.endedBy = expectedActivityBefore === null || terminalStatus === "cancelled" ? "caller" : "provider";
40339
40724
  applyTiming(record2, structuredClone(record2), Date.now(), terminalStatus);
40340
40725
  record2.status = terminalStatus;
40341
40726
  record2.summary = record2.summary ?? reason;
40342
- record2.messages = [...record2.messages, cancelMsg];
40727
+ record2.messages = [...terminalMessages, cancelMsg];
40343
40728
  record2.seq = seq;
40344
40729
  record2.lastActivityAt = Date.now();
40345
- this.notify(jobId, cancelMsg);
40730
+ this.notify(jobId);
40346
40731
  this.messages.delete(jobId);
40347
40732
  return Promise.resolve(true);
40348
40733
  }
@@ -40359,11 +40744,35 @@ var MemoryJobStore = class {
40359
40744
  }
40360
40745
  return list;
40361
40746
  }
40362
- 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) {
40363
40772
  const subs = this.messageSubscribers.get(jobId);
40364
40773
  if (subs) {
40365
40774
  for (const sub of subs) {
40366
- if (message.seq > sub.afterSeq) {
40775
+ for (const message of this.visibleMessages(jobId, sub.afterSeq)) {
40367
40776
  sub.afterSeq = message.seq;
40368
40777
  sub.cb(message);
40369
40778
  }
@@ -40434,7 +40843,7 @@ function mergeSignals(a, b2) {
40434
40843
  return AbortSignal.any([a, b2]);
40435
40844
  }
40436
40845
 
40437
- // node_modules/@dvmkit/sdk/dist/chunk-JLT2YIBS.js
40846
+ // node_modules/@dvmkit/sdk/dist/chunk-GB2N4NG5.js
40438
40847
  import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
40439
40848
  var TEMPO_SETTLEMENT_BALANCE_INTERVAL_MS = 5 * 60 * 1e3;
40440
40849
  function isTempoInsufficientFundsError(error) {
@@ -41785,7 +42194,7 @@ function isTempoCloseTransaction(reference) {
41785
42194
  return typeof reference === "string" && /^0x[0-9a-fA-F]{64}$/.test(reference);
41786
42195
  }
41787
42196
 
41788
- // node_modules/@dvmkit/sdk/dist/chunk-S7PIFHE4.js
42197
+ // node_modules/@dvmkit/sdk/dist/chunk-ZJRGORJ3.js
41789
42198
  import { createHash as createHash8, randomUUID as randomUUID7 } from "crypto";
41790
42199
  import { createHash as createHash23 } from "crypto";
41791
42200
  import { createHash as createHash33 } from "crypto";
@@ -45243,7 +45652,7 @@ var BatchSettlementEvmScheme3 = class {
45243
45652
  }
45244
45653
  };
45245
45654
 
45246
- // node_modules/@dvmkit/sdk/dist/chunk-S7PIFHE4.js
45655
+ // node_modules/@dvmkit/sdk/dist/chunk-ZJRGORJ3.js
45247
45656
  import { createHash as createHash42, randomBytes as randomBytes8, randomUUID as randomUUID22 } from "crypto";
45248
45657
  import { randomBytes as randomBytes22 } from "crypto";
45249
45658
 
@@ -47614,7 +48023,7 @@ function date3(params) {
47614
48023
  // node_modules/zod/v4/classic/external.js
47615
48024
  config(en_default());
47616
48025
 
47617
- // node_modules/@dvmkit/sdk/dist/chunk-S7PIFHE4.js
48026
+ // node_modules/@dvmkit/sdk/dist/chunk-ZJRGORJ3.js
47618
48027
  import { createHash as createHash52 } from "crypto";
47619
48028
  import { createHash as createHash62, randomUUID as randomUUID32 } from "crypto";
47620
48029
  import { isDeepStrictEqual as isDeepStrictEqual22 } from "util";
@@ -50007,7 +50416,7 @@ var streamSSE = (c, cb, onError) => {
50007
50416
  return c.newResponse(stream2.responseReadable);
50008
50417
  };
50009
50418
 
50010
- // node_modules/@dvmkit/sdk/dist/chunk-S7PIFHE4.js
50419
+ // node_modules/@dvmkit/sdk/dist/chunk-ZJRGORJ3.js
50011
50420
  import { createHash as createHash10 } from "crypto";
50012
50421
  async function initLockPubkeyTable(db) {
50013
50422
  await withSdkInitLock(db, () => createLockPubkeyTable(db));
@@ -52871,6 +53280,24 @@ async function restoreRevokedVoucher(storage2, channelId, pendingId, before) {
52871
53280
  function isRecord5(value) {
52872
53281
  return !!value && typeof value === "object" && !Array.isArray(value);
52873
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
+ }
52874
53301
  function paymentFailureFields(error) {
52875
53302
  let category = "unknown";
52876
53303
  try {
@@ -53226,7 +53653,18 @@ async function issueUpfrontChallenges(mpp, requiredMsats, resourcePath, btcUsdRa
53226
53653
  );
53227
53654
  }
53228
53655
  async function verifyUpfrontPayment(opts) {
53229
- 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;
53230
53668
  }
53231
53669
  async function verifyUpfrontPaymentInScope(opts) {
53232
53670
  const {
@@ -53558,7 +53996,7 @@ async function verifyUpfrontPaymentInScope(opts) {
53558
53996
  x402Requirements
53559
53997
  });
53560
53998
  }
53561
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-RUJ4LUKF-ZB7JM22B.js");
53999
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-AY6P5KV4-SIZF7YNW.js");
53562
54000
  const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
53563
54001
  x402Payment,
53564
54002
  x402Config,
@@ -53994,7 +54432,8 @@ async function verifyUpfrontPaymentInScope(opts) {
53994
54432
  creditId: draw.creditId,
53995
54433
  drawId: draw.drawId,
53996
54434
  drawAmountMicro: draw.amountMicro,
53997
- creditCurrency: ledgerCtx.priceFiat.currency
54435
+ creditCurrency: ledgerCtx.priceFiat.currency,
54436
+ upfrontPayment: upfrontPaymentFromDraw(draw)
53998
54437
  };
53999
54438
  } catch (err) {
54000
54439
  if (err instanceof CreditLedgerError) return creditLedgerErrorResult(err, x402Requirements);
@@ -54582,7 +55021,7 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
54582
55021
  snapshot
54583
55022
  });
54584
55023
  }
54585
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-RUJ4LUKF-ZB7JM22B.js");
55024
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-AY6P5KV4-SIZF7YNW.js");
54586
55025
  const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
54587
55026
  body.content.x402_payment,
54588
55027
  opts.x402Config,
@@ -54640,7 +55079,13 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
54640
55079
  const mapped = mapLedgerCommitError(err, void 0, true);
54641
55080
  if (mapped?.error) {
54642
55081
  logCredentialRejected("x402", "mid-job", err);
54643
- return { error: { body: mapped.error.body, status: mapped.error.status } };
55082
+ return {
55083
+ error: {
55084
+ body: mapped.error.body,
55085
+ status: mapped.error.status,
55086
+ ...mapped.error.replayPaymentId && { replayPaymentId: mapped.error.replayPaymentId }
55087
+ }
55088
+ };
54644
55089
  }
54645
55090
  throw err;
54646
55091
  }
@@ -54764,7 +55209,13 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
54764
55209
  const mapped = mapLedgerCommitError(err, void 0, true);
54765
55210
  if (mapped?.error) {
54766
55211
  logCredentialRejected("tempo", "mid-job", err);
54767
- return { error: { body: mapped.error.body, status: mapped.error.status } };
55212
+ return {
55213
+ error: {
55214
+ body: mapped.error.body,
55215
+ status: mapped.error.status,
55216
+ ...mapped.error.replayPaymentId && { replayPaymentId: mapped.error.replayPaymentId }
55217
+ }
55218
+ };
54768
55219
  }
54769
55220
  throw err;
54770
55221
  }
@@ -54809,7 +55260,9 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
54809
55260
  };
54810
55261
  }
54811
55262
  }
54812
- return {};
55263
+ return { error: { status: 402, body: paymentErrorBody("payment_invalid", {
55264
+ message: "Payment method is not configured"
55265
+ }) } };
54813
55266
  }
54814
55267
  function midJobFundedMsats(snapshot, railMsats) {
54815
55268
  const pending = snapshot.pendingPaymentMsats ?? 0;
@@ -54903,8 +55356,13 @@ async function acceptDurableExactIncoming(args) {
54903
55356
  drawId: replayedDrawId
54904
55357
  }) !== void 0;
54905
55358
  }
55359
+ const replayedDrawFunding = accepted.replayed && ledgerCtx?.topUp && accepted.receipt.txHash ? await ledgerCtx.ledger.getFunding({
55360
+ creditId: ledgerCtx.topUp.creditId,
55361
+ fundId: accepted.receipt.txHash
55362
+ }) : void 0;
54906
55363
  const info = withDrawBasis(
54907
55364
  {
55365
+ ...replayedDrawFunding && { drawFunding: replayedDrawFunding },
54908
55366
  paidMsats: args.snapshot.pendingPaymentMsats ?? accepted.receipt.amountMsats,
54909
55367
  paymentRail: "x402",
54910
55368
  receivedProofs: [],
@@ -54933,7 +55391,8 @@ function topUpBinding(info, snapshot) {
54933
55391
  return {
54934
55392
  ...fresh && { creditId: info.creditId, drawId: info.drawId },
54935
55393
  ...info.funding && { funding: info.funding },
54936
- ...info.unappliedMicro !== void 0 && { unappliedMicro: info.unappliedMicro }
55394
+ ...info.unappliedMicro !== void 0 && { unappliedMicro: info.unappliedMicro },
55395
+ ...info.drawFunding && { drawFunding: info.drawFunding }
54937
55396
  };
54938
55397
  }
54939
55398
  function applyPaymentInfoToJob(job, info) {
@@ -55013,7 +55472,7 @@ async function processIncomingPaymentInScope(job, body, opts) {
55013
55472
  try {
55014
55473
  const requiredMsats = job.pendingPaymentMsats ?? 0;
55015
55474
  const requiredUsdcMicro = job.pendingX402AmountUsdcMicro !== void 0 ? BigInt(job.pendingX402AmountUsdcMicro) : BigInt(msatsToUsdc(requiredMsats, rate));
55016
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-RUJ4LUKF-ZB7JM22B.js");
55475
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-AY6P5KV4-SIZF7YNW.js");
55017
55476
  const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
55018
55477
  body.content.x402_payment,
55019
55478
  opts.x402Config,
@@ -55253,7 +55712,11 @@ async function verifyAccumulatorReceipt(opts, mints, requiredMsats, ledgerCtx) {
55253
55712
  receivedProofs: [],
55254
55713
  error: {
55255
55714
  body: paymentErrorBody(result.code, { message: result.message, extra: { mints } }),
55256
- status
55715
+ status,
55716
+ // The accumulator keys replay on the request id, which is also the
55717
+ // funding id a mid-job top-up committed under, so the route can hand
55718
+ // back the original draw funding evidence beside the 409.
55719
+ ...status === 409 && requestId && { replayPaymentId: requestId }
55257
55720
  }
55258
55721
  };
55259
55722
  }
@@ -55449,7 +55912,7 @@ async function resolveTopUpLedgerContext(opts, snapshot, binding) {
55449
55912
  });
55450
55913
  return void 0;
55451
55914
  }
55452
- topUp = { creditId: snapshot.creditId, drawId: snapshot.drawId };
55915
+ topUp = { creditId: snapshot.creditId, drawId: snapshot.drawId, ledgerSeq: draw.ledgerSeq };
55453
55916
  callerId = credit.callerPubkey;
55454
55917
  currency = credit.currency;
55455
55918
  drawBasis = snapshot.paymentTxHash === drawSettlementRef(dvmId, snapshot.creditId, snapshot.drawId);
@@ -55599,7 +56062,8 @@ function withDrawBasis(info, ctx, committed) {
55599
56062
  ...committed.fundingCredit ? { fundingCredit: committed.fundingCredit } : {},
55600
56063
  ...committed.unappliedMicro !== void 0 && {
55601
56064
  unappliedMicro: committed.unappliedMicro
55602
- }
56065
+ },
56066
+ ...committed.drawFunding && { drawFunding: committed.drawFunding }
55603
56067
  };
55604
56068
  const draw = committed.draw;
55605
56069
  if (!draw) return base22;
@@ -55607,7 +56071,8 @@ function withDrawBasis(info, ctx, committed) {
55607
56071
  const withDraw = {
55608
56072
  ...base22,
55609
56073
  drawId,
55610
- drawAmountMicro: draw.amountMicro
56074
+ drawAmountMicro: draw.amountMicro,
56075
+ ...!ctx.midJob && !ctx.fundOnly && { upfrontPayment: upfrontPaymentFromDraw(draw) }
55611
56076
  };
55612
56077
  if (!ctx.drawBasis) return withDraw;
55613
56078
  const { drawMsats, drawNative } = committed.added ?? draw.railValue;
@@ -55663,6 +56128,7 @@ async function fundAndDrawInScope(ctx, funding, tx) {
55663
56128
  const instrument = credit.rail ? storedCreditBinding(credit).instrument : void 0;
55664
56129
  const report = {
55665
56130
  ...deposit,
56131
+ expiryMs: credit.expiryMs,
55666
56132
  callerPubkey: credit.callerPubkey,
55667
56133
  ...instrument && { instrument }
55668
56134
  };
@@ -55705,6 +56171,19 @@ async function fundAndDrawInScope(ctx, funding, tx) {
55705
56171
  }
55706
56172
  if (ctx.topUp) {
55707
56173
  const { creditId: creditId2, drawId: drawId2 } = ctx.topUp;
56174
+ await ctx.ledger.recordFunding({
56175
+ creditId: creditId2,
56176
+ fundId: funding.paymentId,
56177
+ amountMicro: fundedMicro,
56178
+ rail: funding.rail,
56179
+ hostingAdmissionId: ctx.hostingAdmissionId,
56180
+ hostingJobId: ctx.jobId,
56181
+ hostingPaymentSeq: ctx.hostingPaymentSeq,
56182
+ jobId: ctx.jobId,
56183
+ drawId: drawId2,
56184
+ paymentSeq: ctx.hostingPaymentSeq,
56185
+ tx
56186
+ });
55708
56187
  const credit = await ctx.ledger.fund({
55709
56188
  creditId: creditId2,
55710
56189
  callerPubkey: ctx.callerId,
@@ -55717,10 +56196,23 @@ async function fundAndDrawInScope(ctx, funding, tx) {
55717
56196
  basis,
55718
56197
  tx
55719
56198
  });
56199
+ const drawLedgerSeq = async () => ctx.topUp?.ledgerSeq ?? (await ctx.ledger.getDraw({ creditId: creditId2, drawId: drawId2 }))?.ledgerSeq;
56200
+ const completeDrawFunding = async (balanceAfterMicro, ledgerSeq) => ledgerSeq === void 0 ? void 0 : ctx.ledger.completeFunding({
56201
+ creditId: creditId2,
56202
+ fundId: funding.paymentId,
56203
+ callerPubkey: credit.callerPubkey,
56204
+ balanceAfterMicro,
56205
+ ledgerSeq,
56206
+ tx
56207
+ });
55720
56208
  if (ctx.askSatisfied) {
55721
- return commitDeposit({ creditId: creditId2, unappliedMicro: fundedMicro }, credit);
56209
+ const drawFunding2 = await completeDrawFunding(credit.availableMicro, await drawLedgerSeq());
56210
+ return commitDeposit({ creditId: creditId2, unappliedMicro: fundedMicro, drawFunding: drawFunding2 }, credit);
56211
+ }
56212
+ if (shortMidJob) {
56213
+ const drawFunding2 = await completeDrawFunding(credit.availableMicro, await drawLedgerSeq());
56214
+ return commitDeposit({ creditId: creditId2, drawFunding: drawFunding2 }, credit);
55722
56215
  }
55723
- if (shortMidJob) return commitDeposit({ creditId: creditId2 }, credit);
55724
56216
  const grown = await ctx.ledger.growDraw({
55725
56217
  creditId: creditId2,
55726
56218
  drawId: drawId2,
@@ -55741,14 +56233,17 @@ async function fundAndDrawInScope(ctx, funding, tx) {
55741
56233
  tx
55742
56234
  });
55743
56235
  if (grown.addedAmountMicro <= 0) {
55744
- return commitDeposit({ creditId: creditId2, unappliedMicro: grown.cappedMicro }, credit);
56236
+ const drawFunding2 = await completeDrawFunding(credit.availableMicro, grown.ledgerSeq);
56237
+ return commitDeposit({ creditId: creditId2, unappliedMicro: grown.cappedMicro, drawFunding: drawFunding2 }, credit);
55745
56238
  }
56239
+ const drawFunding = await completeDrawFunding(grown.balanceAfterMicro, grown.ledgerSeq);
55746
56240
  return commitDeposit(
55747
56241
  {
55748
56242
  creditId: creditId2,
55749
56243
  draw: grown,
55750
56244
  added: { amountMicro: grown.addedAmountMicro, ...grown.addedRailValue },
55751
- ...grown.cappedMicro > 0 && { unappliedMicro: grown.cappedMicro }
56245
+ ...grown.cappedMicro > 0 && { unappliedMicro: grown.cappedMicro },
56246
+ drawFunding
55752
56247
  },
55753
56248
  credit
55754
56249
  );
@@ -56582,8 +57077,8 @@ function drainedAt(drain) {
56582
57077
  }
56583
57078
  async function fundingReceiptFor(ledger, issuer, funding) {
56584
57079
  if (!issuer) return void 0;
56585
- if (funding.receipt) return funding.receipt;
56586
- if (funding.callerPubkey === null || funding.balanceAfterMicro === null || funding.ledgerSeq === null) {
57080
+ if (funding.receipt) return isFundingReceipt(funding.receipt) ? funding.receipt : void 0;
57081
+ if (funding.callerPubkey === null || funding.balanceAfterMicro === null || funding.ledgerSeq === null || isDrawBound(funding)) {
56587
57082
  return void 0;
56588
57083
  }
56589
57084
  const receipt = issuer.issueFunding({
@@ -56595,11 +57090,43 @@ async function fundingReceiptFor(ledger, issuer, funding) {
56595
57090
  callerPubkey: funding.callerPubkey,
56596
57091
  issuedAt: Math.floor(funding.createdAt / 1e3)
56597
57092
  });
56598
- return ledger.saveFundingReceipt({
57093
+ const saved = await ledger.saveFundingReceipt({
57094
+ creditId: funding.creditId,
57095
+ fundId: funding.fundId,
57096
+ receipt
57097
+ });
57098
+ return isFundingReceipt(saved) ? saved : void 0;
57099
+ }
57100
+ function isDrawBound(funding) {
57101
+ return Boolean(funding.jobId) || Boolean(funding.drawId);
57102
+ }
57103
+ async function drawFundingReceiptFor(ledger, issuer, funding, currency) {
57104
+ if (!issuer) return void 0;
57105
+ if (funding.receipt) return isDrawFundingReceipt(funding.receipt) ? funding.receipt : void 0;
57106
+ if (funding.callerPubkey === null || funding.balanceAfterMicro === null || funding.ledgerSeq === null || !funding.jobId || !funding.drawId) {
57107
+ return void 0;
57108
+ }
57109
+ const receipt = issuer.issueDrawFunding({
57110
+ creditId: funding.creditId,
57111
+ jobId: funding.jobId,
57112
+ drawId: funding.drawId,
57113
+ fundId: funding.fundId,
57114
+ ...funding.paymentSeq !== null && funding.paymentSeq !== void 0 && {
57115
+ paymentSeq: funding.paymentSeq
57116
+ },
57117
+ currency,
57118
+ fundedMicro: funding.amountMicro,
57119
+ balanceAfterMicro: funding.balanceAfterMicro,
57120
+ ledgerSeq: funding.ledgerSeq,
57121
+ callerPubkey: funding.callerPubkey,
57122
+ issuedAt: Math.floor(funding.createdAt / 1e3)
57123
+ });
57124
+ const saved = await ledger.saveFundingReceipt({
56599
57125
  creditId: funding.creditId,
56600
57126
  fundId: funding.fundId,
56601
57127
  receipt
56602
57128
  });
57129
+ return isDrawFundingReceipt(saved) ? saved : void 0;
56603
57130
  }
56604
57131
  async function completeTempoChannelDrain(args) {
56605
57132
  if (!args.tx && args.refundedNative !== void 0 && /^\d{1,78}$/.test(String(args.refundedNative))) {
@@ -62013,6 +62540,12 @@ function buildContext(job, opts) {
62013
62540
  log.error("Terminal handling failed", { error: String(err) });
62014
62541
  });
62015
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
+ };
62016
62549
  let creditedToHandlerMsats = 0;
62017
62550
  let creditedToHandlerMicro = 0;
62018
62551
  let poolBasis = false;
@@ -62020,6 +62553,7 @@ function buildContext(job, opts) {
62020
62553
  let declaredCostCurrency;
62021
62554
  let declaredCostRevision = 0;
62022
62555
  let costPoisoned = false;
62556
+ const stepWrites = /* @__PURE__ */ new Map();
62023
62557
  const stepCostOwner = {};
62024
62558
  const declareCost = (declared) => {
62025
62559
  if (terminated("cost")) return;
@@ -62075,29 +62609,41 @@ function buildContext(job, opts) {
62075
62609
  },
62076
62610
  sendMessage: (type, content) => {
62077
62611
  if (terminated("sendMessage")) return;
62612
+ if (type === "payment-request" && typeof content.amount_msats === "number") job.pendingPaymentMsats = content.amount_msats;
62078
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
+ }
62079
62619
  },
62080
62620
  prompt: (id, text, promptOpts) => {
62081
62621
  if (terminated("prompt")) {
62082
62622
  return Promise.reject(new JobCancelledError(`Job already ${job.status}`));
62083
62623
  }
62084
62624
  job.status = "awaiting-input";
62085
- providerMessage(job, "prompt", {
62086
- id,
62087
- text,
62088
- ...promptOpts?.options && { options: promptOpts.options },
62089
- ...promptOpts?.schema && { schema: promptOpts.schema }
62090
- });
62091
- 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--;
62092
62630
  const response = job.messages.find(
62093
- (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
62094
62632
  );
62095
62633
  if (response) {
62096
- job.status = "processing";
62634
+ job.status = job.pendingPrompts.size > 0 || job.pendingPayment ? "awaiting-input" : "processing";
62635
+ opts.onCallerResume?.();
62097
62636
  return Promise.resolve(response.content);
62098
62637
  }
62638
+ } else {
62099
62639
  job.replayHighSeq = null;
62100
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
+ });
62101
62647
  }
62102
62648
  const p = new Promise((resolve, reject) => {
62103
62649
  job.pendingPrompts.set(id, { resolve, reject });
@@ -62110,6 +62656,7 @@ function buildContext(job, opts) {
62110
62656
  return p;
62111
62657
  },
62112
62658
  requestPayment: async (amount, reason, payOpts) => {
62659
+ captureReplayPrompts();
62113
62660
  if (terminated("requestPayment")) {
62114
62661
  throw new JobCancelledError(`Job already ${job.status}`);
62115
62662
  }
@@ -62218,135 +62765,153 @@ function buildContext(job, opts) {
62218
62765
  poolRemainingMicro: pool.amountMicro - creditedToHandlerMicro
62219
62766
  } : { poolRemaining: job.paidMsats - creditedToHandlerMsats }
62220
62767
  });
62768
+ if (job.replayHighSeq !== null) {
62769
+ job.status = job.pendingPrompts.size > 0 ? "awaiting-input" : "processing";
62770
+ opts.onCallerResume?.();
62771
+ }
62221
62772
  advanceReplayPaymentIndex(job);
62222
62773
  return { amount_msats: amountMsats };
62223
62774
  }
62224
- 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();
62225
62779
  job.pendingPaymentMsats = amountMsats;
62226
62780
  job.pendingPaymentFiatMicro = pendingFiat?.amountMicro;
62227
62781
  job.pendingPaymentFiatCurrency = pendingFiat?.currency;
62228
- const paymentRequestContent = {
62229
- amount_msats: amountMsats,
62230
- reason,
62231
- ...pendingFiat && { credit: { amount_micro: pendingFiat.amountMicro, currency: pendingFiat.currency } },
62232
- ...fiatAmount && { fiat_amount: fiatAmount },
62233
- ...payOpts?.mints && { mints: payOpts.mints },
62234
- ...payOpts?.minLocktimeSeconds && { min_locktime_seconds: payOpts.minLocktimeSeconds },
62235
- ...!payOpts?.mints && opts.mints && { mints: opts.mints }
62236
- };
62237
- let paymentRate;
62238
- let x402Nonce;
62239
- let x402AmountUsdcMicro;
62240
- const hasExplicitX402 = Boolean(payOpts?.x402);
62241
- if ((opts.pricingCurrency ?? "usd") === "usd") {
62242
- if (payOpts?.x402) {
62243
- paymentRequestContent.x402 = payOpts.x402;
62244
- } else if (opts.paymentMethods?.includes("x402") && opts.x402 && (opts.x402FacilitatorHealth?.support().available ?? true)) {
62245
- paymentRequestContent.x402 = {
62246
- pay_to: opts.x402.payTo,
62247
- network: opts.x402.network,
62248
- asset: opts.x402.asset ?? "USDC",
62249
- ...opts.x402.facilitator && { facilitator: opts.x402.facilitator }
62250
- };
62251
- }
62252
- }
62253
- if (paymentRequestContent.x402) {
62254
- paymentRate = (await resolveServerBtcUsdRate(opts.fxFetcher)).rate;
62255
- x402Nonce = `0x${randomBytes32(32).toString("hex")}`;
62256
- x402AmountUsdcMicro = msatsToUsdc(amountMsats, paymentRate).toString();
62257
- const x402Request = paymentRequestContent.x402;
62258
- const challengeConfig = {
62259
- payTo: x402Request.pay_to,
62260
- network: x402Request.network,
62261
- ...x402Request.asset ? { asset: x402Request.asset } : {},
62262
- ...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 }
62263
62797
  };
62264
- Object.assign(x402Request, {
62265
- nonce: x402Nonce,
62266
- required_usdc_micro: x402AmountUsdcMicro,
62267
- ...hasExplicitX402 || (opts.x402FacilitatorHealth?.support().exact.v2 ?? true) ? {
62268
- payment_required: buildPaymentRequiredV2({
62269
- x402Config: challengeConfig,
62270
- requiredUsdcMicro: BigInt(x402AmountUsdcMicro),
62271
- resource: `/v1/job/${job.id}/messages`,
62272
- description: reason
62273
- })
62274
- } : {}
62275
- });
62276
- }
62277
- job.pendingX402Nonce = x402Nonce;
62278
- job.pendingX402AmountUsdcMicro = x402AmountUsdcMicro;
62279
- let mppChallengeIds;
62280
- if (payOpts?.mpp) {
62281
- const challenges = payOpts.mpp.challenges.filter((c) => c.intent !== "session");
62282
- if (challenges.length > 0) {
62283
- paymentRequestContent.tempo = { challenges };
62284
- 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
+ }
62285
62813
  }
62286
- } else if (opts.paymentMethods?.includes("tempo") && opts.mpp) {
62287
- const rate = paymentRate ?? (await resolveServerBtcUsdRate(opts.fxFetcher)).rate;
62288
- const challenges = [];
62289
- for (const m of opts.mpp.methods) {
62290
- const meta3 = m;
62291
- if (meta3.intent === "session") continue;
62292
- const amount2 = pendingFiat?.currency === "usd" ? fiatMicroToMethodAmount(pendingFiat.amountMicro, meta3.name) : msatsToMethodAmount(amountMsats, meta3.name, rate);
62293
- const ch = await opts.mpp.issueChallenge(meta3.name, meta3.intent, {
62294
- amount: amount2,
62295
- 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
+ } : {}
62296
62836
  });
62297
- challenges.push(ch);
62298
62837
  }
62299
- if (challenges.length > 0) {
62300
- paymentRequestContent.tempo = { challenges };
62301
- 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
+ }
62302
62864
  }
62865
+ job.pendingMppChallengeIds = mppChallengeIds;
62303
62866
  }
62304
- job.pendingMppChallengeIds = mppChallengeIds;
62305
62867
  if (job.replayHighSeq !== null) {
62306
- 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);
62307
62869
  if (job.replayPaymentIndex < payments.length) {
62308
62870
  const payment = payments[job.replayPaymentIndex];
62309
62871
  job.replayPaymentIndex++;
62310
62872
  const balance = payment.content.credit;
62311
62873
  const accepted = balance ? await opts.acceptedBalancePayment?.(payment.seq, pendingFiat?.amountMicro, pendingFiat?.currency) : job.reactivationPaymentApplied === true;
62312
62874
  if (!accepted) throw new Error("[internal_error] payment replay reached without credit");
62313
- if (balance) {
62314
- job.pendingPaymentMsats = void 0;
62315
- job.pendingPaymentFiatMicro = void 0;
62316
- job.pendingPaymentFiatCurrency = void 0;
62317
- job.pendingMppChallengeIds = void 0;
62318
- job.pendingX402Nonce = void 0;
62319
- job.pendingX402AmountUsdcMicro = void 0;
62320
- }
62321
- 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?.();
62322
62883
  creditedToHandlerMsats += amountMsats;
62323
62884
  creditedToHandlerMicro += pendingFiat?.amountMicro ?? 0;
62324
62885
  return payment.content;
62325
62886
  }
62326
- job.replayHighSeq = null;
62327
- job.replayProviderSkip = 0;
62887
+ if (!originalAsk) {
62888
+ job.replayHighSeq = null;
62889
+ job.replayProviderSkip = 0;
62890
+ }
62328
62891
  }
62329
- const askedTotal = accumulateAskedTopUp(
62330
- {
62331
- micro: job.askedTopUpMicro,
62332
- currency: job.askedTopUpCurrency,
62333
- reason: job.topUpCapUnenforcedReason
62334
- },
62335
- { micro: pendingFiat?.amountMicro, currency: pendingFiat?.currency }
62336
- );
62337
- job.askedTopUpMicro = askedTotal.micro;
62338
- job.askedTopUpCurrency = askedTotal.currency;
62339
- if (askedTotal.reason && !job.topUpCapUnenforcedReason) {
62340
- job.topUpCapUnenforcedReason = askedTotal.reason;
62341
- loggers.isolate.warn("dvm.topup_cap_unenforceable", {
62342
- job_id: job.id,
62343
- reason: askedTotal.reason,
62344
- ask_currency: askCurrency,
62345
- ask_msats: amountMsats
62346
- });
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
+ }
62347
62912
  }
62348
62913
  job.status = "awaiting-input";
62349
- providerMessage(job, "payment-request", paymentRequestContent);
62914
+ if (!originalAsk) providerMessage(job, "payment-request", paymentRequestContent);
62350
62915
  const paidMsatsAtYield = job.paidMsats;
62351
62916
  const p = new Promise((resolve, reject) => {
62352
62917
  let resolved = false;
@@ -62364,6 +62929,9 @@ function buildContext(job, opts) {
62364
62929
  if (resolved) return;
62365
62930
  job.pendingPayment = null;
62366
62931
  }
62932
+ job.replayHighSeq = null;
62933
+ job.replayProviderSkip = 0;
62934
+ opts.onCallerResume?.();
62367
62935
  resolved = true;
62368
62936
  cleanup();
62369
62937
  creditedToHandlerMsats += amountMsats;
@@ -62469,6 +63037,7 @@ function buildContext(job, opts) {
62469
63037
  cost: declareCost,
62470
63038
  step: async (id, fn2) => {
62471
63039
  if (job.stepCache.has(id)) {
63040
+ await stepWrites.get(id);
62472
63041
  const record2 = job.stepCache.getRecord(id);
62473
63042
  for (const declared of record2.costs ?? []) declareCost(declared);
62474
63043
  return record2.value;
@@ -62481,6 +63050,15 @@ function buildContext(job, opts) {
62481
63050
  fn2
62482
63051
  );
62483
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
+ }
62484
63062
  return result;
62485
63063
  },
62486
63064
  state: job.state,
@@ -62507,7 +63085,7 @@ function warnPinLost(jobId, currency, amountMsats, reason, detail) {
62507
63085
  }
62508
63086
  function advanceReplayPaymentIndex(job) {
62509
63087
  if (job.replayHighSeq === null) return;
62510
- 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);
62511
63089
  if (job.replayPaymentIndex < payments.length) {
62512
63090
  job.replayPaymentIndex++;
62513
63091
  }
@@ -62611,6 +63189,34 @@ var ReceiptIssuer = class {
62611
63189
  this.secret
62612
63190
  );
62613
63191
  }
63192
+ /**
63193
+ * Countersign the immutable tuple captured when a mid-job payment funded a
63194
+ * job's credit against its pending draw. `ledgerSeq` is the draw's own
63195
+ * sequence so the artifact lines up with the terminal receipt's credit block.
63196
+ */
63197
+ issueDrawFunding(args) {
63198
+ return signDrawFundingReceipt(
63199
+ {
63200
+ v: 1,
63201
+ kind: "credit_draw_funding",
63202
+ credit_id: args.creditId,
63203
+ job_id: args.jobId,
63204
+ draw_id: args.drawId,
63205
+ fund_id: args.fundId,
63206
+ ...args.paymentSeq !== void 0 && { payment_seq: args.paymentSeq },
63207
+ currency: args.currency,
63208
+ funded_micro: args.fundedMicro,
63209
+ balance_after_micro: args.balanceAfterMicro,
63210
+ ledger_seq: args.ledgerSeq,
63211
+ issued_at: args.issuedAt ?? Math.floor(Date.now() / 1e3),
63212
+ caller_pubkey: args.callerPubkey,
63213
+ dvm_id: this.dvmId,
63214
+ dvm: this.dvm,
63215
+ receipt_pubkey: this.pubkey
63216
+ },
63217
+ this.secret
63218
+ );
63219
+ }
62614
63220
  };
62615
63221
  function isReceiptableStatus(status) {
62616
63222
  return status === "completed" || status === "failed" || status === "cancelled";
@@ -62884,6 +63490,7 @@ var JobManager = class {
62884
63490
  // Bind live resolvers and recovery scaffolds to the store-allocated ask identity.
62885
63491
  paymentAskSeqs = /* @__PURE__ */ new WeakMap();
62886
63492
  reactivationAskSeqs = /* @__PURE__ */ new WeakMap();
63493
+ pendingPaymentMessages = /* @__PURE__ */ new WeakMap();
62887
63494
  // Every local input resume holds this queue through its durable wait update.
62888
63495
  // A prompt response and a payment NOTIFY must not mistake each other for a
62889
63496
  // different machine's successful claim.
@@ -63209,6 +63816,7 @@ var JobManager = class {
63209
63816
  status: "processing",
63210
63817
  messages: [],
63211
63818
  seq: 0,
63819
+ upfrontPayment: payment.upfrontPayment ? structuredClone(payment.upfrontPayment) : void 0,
63212
63820
  paidMsats: payment.paidMsats,
63213
63821
  paymentMint: payment.paymentMint,
63214
63822
  paymentRail: payment.paymentRail,
@@ -63392,8 +64000,10 @@ var JobManager = class {
63392
64000
  job.pendingPrompts.delete(rc.prompt_id);
63393
64001
  job.status = job.pendingPrompts.size > 0 || job.pendingPayment ? "awaiting-input" : "processing";
63394
64002
  if (job.status === "awaiting-input") await this.persistJob(job);
64003
+ this.startIdleTimer(job);
63395
64004
  pending.resolve(rc);
63396
64005
  } else if (cap?.onResponse && ctx) {
64006
+ this.startIdleTimer(job);
63397
64007
  await cap.onResponse(ctx, rc);
63398
64008
  }
63399
64009
  } else if (type === "payment") {
@@ -63413,6 +64023,7 @@ var JobManager = class {
63413
64023
  await pp.resolve(pc);
63414
64024
  });
63415
64025
  } else if (cap?.onPayment && ctx) {
64026
+ this.startIdleTimer(job);
63416
64027
  await cap.onPayment(ctx, pc);
63417
64028
  }
63418
64029
  } else if (type === "approval" && cap?.onApproval && ctx) {
@@ -63457,7 +64068,7 @@ var JobManager = class {
63457
64068
  if (await this.adoptDurableTerminal(job)) return;
63458
64069
  const record2 = toJobRecord(job);
63459
64070
  if (isTerminal(job.status) && isStreamableJobStore(this.jobStore)) {
63460
- const durable = await this.jobStore.getMessages(job.id, 0);
64071
+ const durable = await this.jobStore.getMessages(job.id, 0, { includeHeld: true });
63461
64072
  if (durable.length >= record2.messages.length) {
63462
64073
  record2.messages = durable;
63463
64074
  const highSeq = durable.length ? durable[durable.length - 1].seq : record2.seq;
@@ -63761,9 +64372,10 @@ var JobManager = class {
63761
64372
  job.messageAppenderTail = next;
63762
64373
  };
63763
64374
  }
63764
- startIdleTimer(job) {
64375
+ startIdleTimer(job, deadline = callerDeadline(job, this.descriptor.idleTimeout * 1e3)) {
63765
64376
  this.clearIdleTimer(job.id);
63766
- const timeoutMs = this.descriptor.idleTimeout * 1e3;
64377
+ if (deadline === void 0) return;
64378
+ const timeoutMs = Math.min(2147483647, Math.max(0, deadline - Date.now()));
63767
64379
  const timer = setTimeout(() => {
63768
64380
  void this.cancelJobIdle(job).catch(() => void 0);
63769
64381
  }, timeoutMs);
@@ -63779,7 +64391,7 @@ var JobManager = class {
63779
64391
  /** Cancel a job due to idle timeout. Exposed for the reactivation path's idle-expiry guard. */
63780
64392
  async cancelJobIdle(job) {
63781
64393
  if (isTerminal(job.status)) return;
63782
- const current = await this.jobStore.get(job.id).catch(() => void 0);
64394
+ const current = await this.jobStore.get(job.id);
63783
64395
  if (current && isTerminal(current.status)) {
63784
64396
  const reason = `Job reached terminal status "${current.status}" elsewhere`;
63785
64397
  for (const [, p] of job.pendingPrompts) p.reject(new Error(reason));
@@ -63791,11 +64403,32 @@ var JobManager = class {
63791
64403
  this.scheduleCleanup(job);
63792
64404
  return;
63793
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
+ }
63794
64427
  for (const [, p] of job.pendingPrompts) p.reject(new Error("Job timed out (idle)"));
63795
64428
  if (job.pendingPayment) job.pendingPayment.reject(new Error("Job timed out (idle)"));
63796
64429
  job.pendingPrompts.clear();
63797
64430
  job.pendingPayment = null;
63798
- job.endedBy = (current?.status ?? job.status) === "awaiting-input" ? "caller" : "provider";
64431
+ job.endedBy = "caller";
63799
64432
  job.status = "cancelled";
63800
64433
  abortJob(job, "Job timed out (idle)");
63801
64434
  providerMessage(job, "cancel", { reason: "Job timed out (idle)" });
@@ -63808,8 +64441,11 @@ var JobManager = class {
63808
64441
  * • `awaiting-input` past `staleJobTimeoutMs` → `cancelled`
63809
64442
  * (`stale_no_terminal_status`) — the caller never paid / responded.
63810
64443
  * • `processing`/`working` past `processingWatchdogMs` → `failed`
63811
- * (`worker_died_mid_job`) — the worker died mid-job. The heartbeat keeps
63812
- * 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.
63813
64449
  *
63814
64450
  * Fires on a timer (wired in the constructor) and also callable on demand
63815
64451
  * (tests, ops). The CAS in `cancelStaleJob` makes this safe to run
@@ -63817,6 +64453,8 @@ var JobManager = class {
63817
64453
  * JobManager owns so multi-mount hosts don't steal stuck rows from sibling
63818
64454
  * descriptors — the local activeJobs teardown only makes sense on the
63819
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.
63820
64458
  *
63821
64459
  * **Both cutoffs float off the wall clock.** Each is one
63822
64460
  * `Date.now()` sample compared against `last_activity_at`, stamped from a
@@ -63881,10 +64519,25 @@ var JobManager = class {
63881
64519
  );
63882
64520
  let swept = 0;
63883
64521
  for (const record2 of stale) {
63884
- 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;
63885
64528
  const terminalStatus = awaiting ? "cancelled" : "failed";
63886
64529
  const reason = awaiting ? "stale_no_terminal_status" : "worker_died_mid_job";
63887
- 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
+ }
63888
64541
  const claimed = await this.jobStore.cancelStaleJob(
63889
64542
  record2.id,
63890
64543
  expectedActivityBefore,
@@ -64504,8 +65157,9 @@ var JobManager = class {
64504
65157
  }
64505
65158
  }
64506
65159
  /**
64507
- * Record an inbound client message durably via Tx B and append
64508
- * 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
64509
65163
  * (`null` when the store isn't streamable — non-Postgres test fallback).
64510
65164
  *
64511
65165
  * Status starts as `pending-verification`; a follow-up Tx C call
@@ -64524,13 +65178,24 @@ var JobManager = class {
64524
65178
  });
64525
65179
  }
64526
65180
  job.seq++;
64527
- job.messages.push({
65181
+ const message = {
64528
65182
  seq: job.seq,
64529
65183
  from: "requester",
64530
65184
  timestamp,
64531
65185
  type: msgType,
64532
65186
  content: msgContent
64533
- });
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
+ }
64534
65199
  job.lastActivityAt = Date.now();
64535
65200
  return txSeq;
64536
65201
  }
@@ -64639,6 +65304,22 @@ var JobManager = class {
64639
65304
  * 500. See `creditInbound`.
64640
65305
  */
64641
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) {
64642
65323
  if (body.type !== "payment") return {};
64643
65324
  const devAuto = this.opts.devMode === true && body.content.dev_auto === true && !hasPaymentProof(body.content);
64644
65325
  if (devAuto || devModeSkipsPaymentVerification(this.opts)) {
@@ -64652,14 +65333,14 @@ var JobManager = class {
64652
65333
  if (hadPendingPayment2 && delta > 0 && (counters.pendingPaymentMsats === void 0 || counters.pendingPaymentMsats === 0)) {
64653
65334
  job.reactivationPaymentApplied = true;
64654
65335
  }
64655
- if (counters.pendingPaymentMsats === void 0 && job.status === "awaiting-input") {
65336
+ if (counters.pendingPaymentMsats === void 0 && job.status === "awaiting-input" && job.pendingPrompts.size === 0) {
64656
65337
  job.status = "processing";
64657
65338
  }
64658
65339
  } else if (delta) {
64659
65340
  job.paidMsats += delta;
64660
65341
  job.pendingPaymentMsats = void 0;
64661
65342
  if (hadPendingPayment2) job.reactivationPaymentApplied = true;
64662
- if (job.status === "awaiting-input") job.status = "processing";
65343
+ if (job.status === "awaiting-input" && job.pendingPrompts.size === 0) job.status = "processing";
64663
65344
  }
64664
65345
  return {};
64665
65346
  }
@@ -64714,10 +65395,17 @@ var JobManager = class {
64714
65395
  await this.jobStore.markInboundFailed(job.id, inboundSeq, code).catch(() => void 0);
64715
65396
  }
64716
65397
  this.reportCreditDeposit(verifyResult.error.funding);
64717
- return { error: { body: verifyResult.error.body, status: verifyResult.error.status } };
65398
+ const replayed = await this.replayedDrawFundingReceipt(job, verifyResult.error.replayPaymentId);
65399
+ return {
65400
+ error: {
65401
+ body: { ...verifyResult.error.body, ...replayed && { draw_funding_receipt: replayed } },
65402
+ status: verifyResult.error.status
65403
+ }
65404
+ };
64718
65405
  }
64719
65406
  const info = verifyResult.verified;
64720
- if (!info) return {};
65407
+ if (!info) return { error: { status: 402, body: { error: "payment_invalid", message: "Payment was not accepted" } } };
65408
+ const drawFundingReceipt = await this.drawFundingReceiptFor(info.drawFunding, info.funding?.currency);
64721
65409
  let unappliedCredit;
64722
65410
  const fullyUnapplied = info.unappliedMicro !== void 0 && info.funding !== void 0 && info.unappliedMicro >= info.funding.amountMicro;
64723
65411
  const hadPendingPayment = job.pendingPaymentMsats !== void 0;
@@ -64743,7 +65431,13 @@ var JobManager = class {
64743
65431
  }
64744
65432
  );
64745
65433
  } catch (err) {
64746
- return { error: await this.reportUnappliedPayment(job, inboundSeq, info, err) };
65434
+ const unapplied = await this.reportUnappliedPayment(job, inboundSeq, info, err);
65435
+ return {
65436
+ error: {
65437
+ body: { ...unapplied.body, ...drawFundingReceipt && { draw_funding_receipt: drawFundingReceipt } },
65438
+ status: unapplied.status
65439
+ }
65440
+ };
64747
65441
  }
64748
65442
  const { counters } = result;
64749
65443
  job.paidMsats = counters.paidMsats;
@@ -64787,7 +65481,7 @@ var JobManager = class {
64787
65481
  job.pendingX402AmountUsdcMicro = void 0;
64788
65482
  }
64789
65483
  }
64790
- if (counters.pendingPaymentMsats === void 0 && job.status === "awaiting-input") {
65484
+ if (counters.pendingPaymentMsats === void 0 && job.status === "awaiting-input" && job.pendingPrompts.size === 0) {
64791
65485
  job.status = "processing";
64792
65486
  }
64793
65487
  } else {
@@ -64813,7 +65507,81 @@ var JobManager = class {
64813
65507
  );
64814
65508
  }
64815
65509
  this.reportCreditDeposit(info.funding);
64816
- return { ...unappliedCredit && { unappliedCredit } };
65510
+ return {
65511
+ ...unappliedCredit && { unappliedCredit },
65512
+ ...drawFundingReceipt && { drawFundingReceipt }
65513
+ };
65514
+ }
65515
+ /** Issue (or reuse) the signed draw funding receipt for a committed funding row; never throws. */
65516
+ async drawFundingReceiptFor(funding, currency) {
65517
+ const ledger = this.opts.creditLedger;
65518
+ if (!funding || !ledger || currency === void 0) return void 0;
65519
+ try {
65520
+ return await drawFundingReceiptFor(ledger, this.opts.receiptIssuer, funding, currency);
65521
+ } catch (err) {
65522
+ diagnosticConsole.error({
65523
+ level: "error",
65524
+ event: "draw_funding_receipt_unavailable",
65525
+ credit_id: funding.creditId,
65526
+ fund_id: funding.fundId,
65527
+ error: errText(err)
65528
+ });
65529
+ return void 0;
65530
+ }
65531
+ }
65532
+ /**
65533
+ * Every signed draw funding receipt for a job's draw, oldest first, reissuing
65534
+ * any the acknowledgement never carried. Empty when the ledger cannot list
65535
+ * draw fundings or the job holds no draw; a lookup failure is logged and
65536
+ * answered as empty rather than failing the read.
65537
+ */
65538
+ async drawFundingReceipts(job) {
65539
+ const ledger = this.opts.creditLedger;
65540
+ if (!ledger?.listDrawFundings || !this.opts.receiptIssuer || !job.creditId || !job.drawId) {
65541
+ return [];
65542
+ }
65543
+ try {
65544
+ const fundings = (await ledger.listDrawFundings({ creditId: job.creditId, drawId: job.drawId })).filter((funding) => funding.jobId === job.id);
65545
+ if (fundings.length === 0) return [];
65546
+ const credit = await ledger.get(job.creditId);
65547
+ if (!credit) return [];
65548
+ const receipts = [];
65549
+ for (const funding of fundings) {
65550
+ const receipt = await drawFundingReceiptFor(ledger, this.opts.receiptIssuer, funding, credit.currency);
65551
+ if (receipt) receipts.push(receipt);
65552
+ }
65553
+ return receipts;
65554
+ } catch (err) {
65555
+ diagnosticConsole.error({
65556
+ level: "error",
65557
+ event: "draw_funding_receipts_unavailable",
65558
+ job_id: job.id,
65559
+ error: errText(err)
65560
+ });
65561
+ return [];
65562
+ }
65563
+ }
65564
+ /** The stored evidence for a replayed mid-job payment, looked up by the payment id the marker collided on. */
65565
+ async replayedDrawFundingReceipt(job, replayPaymentId) {
65566
+ const ledger = this.opts.creditLedger;
65567
+ if (!replayPaymentId || !ledger || !job.creditId) return void 0;
65568
+ try {
65569
+ const [credit, funding] = await Promise.all([
65570
+ ledger.get(job.creditId),
65571
+ ledger.getFunding({ creditId: job.creditId, fundId: replayPaymentId })
65572
+ ]);
65573
+ if (!credit || !funding || funding.jobId !== job.id) return void 0;
65574
+ return await drawFundingReceiptFor(ledger, this.opts.receiptIssuer, funding, credit.currency);
65575
+ } catch (err) {
65576
+ diagnosticConsole.error({
65577
+ level: "error",
65578
+ event: "draw_funding_receipt_unavailable",
65579
+ job_id: job.id,
65580
+ fund_id: replayPaymentId,
65581
+ error: errText(err)
65582
+ });
65583
+ return void 0;
65584
+ }
64817
65585
  }
64818
65586
  /**
64819
65587
  * Tx C with a bounded retry.
@@ -65010,6 +65778,7 @@ var JobManager = class {
65010
65778
  */
65011
65779
  buildContextOpts(job) {
65012
65780
  const jobStore = this.jobStore;
65781
+ job.idleTimeoutMs = this.descriptor.idleTimeout * 1e3;
65013
65782
  return {
65014
65783
  mints: this.opts.mints,
65015
65784
  store: this.opts.store,
@@ -65020,7 +65789,25 @@ var JobManager = class {
65020
65789
  mpp: this.opts.mpp,
65021
65790
  fxFetcher: this.opts.fxFetcher,
65022
65791
  onTerminal: () => this.handleJobTerminal(job),
65023
- 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,
65024
65811
  onPaymentResume: () => retryJobSnapshot(() => this.persistJob(job)),
65025
65812
  subscribeNotifications: isStreamableJobStore(jobStore) ? (cb) => jobStore.subscribeNotifications(job.id, cb) : void 0,
65026
65813
  acceptedBalancePayment: this.opts.db && jobStore instanceof PostgresJobStore ? async (seq, amountMicro, currency) => {
@@ -70008,7 +70795,7 @@ async function createDVMServer(descriptor, opts) {
70008
70795
  }
70009
70796
  }
70010
70797
  if (!opts.onJobCompleted && platformToken && platformUrl && dvmId && opts.db) {
70011
- const { RevenueReporter: RevenueReporter2 } = await import("./revenue-reporter-HD4GMXGD-LAZU45ZA.js");
70798
+ const { RevenueReporter: RevenueReporter2 } = await import("./revenue-reporter-RIEHBKRA-75BDPVVX.js");
70012
70799
  const reporter = new RevenueReporter2(
70013
70800
  opts.db,
70014
70801
  platformUrl,
@@ -70018,7 +70805,7 @@ async function createDVMServer(descriptor, opts) {
70018
70805
  revenueReporter = reporter;
70019
70806
  await reporter.init();
70020
70807
  reporter.startRetryLoop();
70021
- const { MemoryX402BatchStore, PayoutReporter: PayoutReporter2 } = await import("./payout-reporter-NXWQVKXW-KHVN6C4Z.js");
70808
+ const { MemoryX402BatchStore, PayoutReporter: PayoutReporter2 } = await import("./payout-reporter-DDQ7FGRC-OKICJCC2.js");
70022
70809
  payoutReporter = new PayoutReporter2({
70023
70810
  dvmId,
70024
70811
  db: opts.db,
@@ -72329,7 +73116,6 @@ var DVMServer = class {
72329
73116
  );
72330
73117
  }
72331
73118
  const sdkCtx = jm.buildAndAttachContext(job, parsedInput);
72332
- jm.startIdleTimer(job);
72333
73119
  jm.runHandler(job, sdkCtx);
72334
73120
  await new Promise((resolve) => {
72335
73121
  setTimeout(resolve, 0);
@@ -72643,6 +73429,7 @@ var DVMServer = class {
72643
73429
  await this.jobManager.ensureReceipt(job);
72644
73430
  const res2 = { job_id: job.id, status: job.status };
72645
73431
  Object.assign(res2, terminalResponseFields(job), await this.contentFields(job));
73432
+ Object.assign(res2, await this.drawFundingFields(job));
72646
73433
  removeUnavailableContent(res2);
72647
73434
  return c.json(res2);
72648
73435
  }
@@ -72652,23 +73439,41 @@ var DVMServer = class {
72652
73439
  await this.jobManager.ensureReceipt(record2);
72653
73440
  const res = { job_id: record2.id, status: record2.status };
72654
73441
  Object.assign(res, terminalResponseFields(record2), await this.contentFields(record2));
73442
+ Object.assign(res, await this.drawFundingFields(record2));
72655
73443
  removeUnavailableContent(res);
72656
73444
  return c.json(res);
72657
73445
  }
73446
+ /**
73447
+ * Recoverable mid-job funding evidence for an authenticated job read: every
73448
+ * signed draw funding receipt the ledger holds for the job's draw, reissued
73449
+ * from the committed rows when an acknowledgement was lost or the process
73450
+ * restarted. Omitted entirely when the job holds no draw or none exist.
73451
+ */
73452
+ async drawFundingFields(job) {
73453
+ const receipts = await this.jobManager.drawFundingReceipts(job);
73454
+ return receipts.length > 0 ? { draw_funding_receipts: receipts } : {};
73455
+ }
72658
73456
  async handleGetMessages(c) {
72659
73457
  if (!jobCredential.presents(c.req)) return c.json(jobCredential.body(), 401);
72660
73458
  const id = c.req.param("id") ?? "";
72661
73459
  const job = this.jobManager.activeJobs.get(id);
72662
73460
  const after = Number(c.req.query("after") ?? "0");
72663
73461
  const accept = c.req.header("Accept") ?? "";
72664
- if (!job) {
72665
- 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;
72666
73466
  const record2 = await store.get(id);
72667
73467
  if (!record2) return c.json({ error: "Job not found" }, 404);
72668
73468
  if (!isJobOwner(c, record2)) return c.json({ error: "Job not found" }, 404);
72669
- 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
+ }
72670
73475
  if (accept.includes("text/event-stream")) {
72671
- if (isStreamableJobStore(store) && !isTerminal(record2.status)) {
73476
+ if (isStreamableJobStore(store) && !terminal) {
72672
73477
  return streamSSE(c, async (stream2) => {
72673
73478
  let unsubFn;
72674
73479
  await new Promise((resolve) => {
@@ -72731,10 +73536,6 @@ var DVMServer = class {
72731
73536
  }
72732
73537
  });
72733
73538
  }
72734
- if (isStreamableJobStore(store) && !isTerminal(record2.status)) {
72735
- const msgs = await store.getMessages(id, after);
72736
- if (msgs.length > 0) return c.json(await this.messageFields(record2, msgs));
72737
- }
72738
73539
  return c.json(await this.messageFields(record2, filtered));
72739
73540
  }
72740
73541
  if (!isJobOwner(c, job)) return c.json({ error: "Job not found" }, 404);
@@ -72742,7 +73543,7 @@ var DVMServer = class {
72742
73543
  const fields = await this.contentFields(job);
72743
73544
  return streamSSE(c, async (stream2) => {
72744
73545
  if (fields.content_available === false) return;
72745
- const existing = job.messages.filter((m) => m.seq > after);
73546
+ const existing = visibleJobMessages(job).filter((m) => m.seq > after);
72746
73547
  let yielded = false;
72747
73548
  for (const msg of existing) {
72748
73549
  await stream2.writeSSE({ data: JSON.stringify(msg), event: "message" });
@@ -72770,7 +73571,7 @@ var DVMServer = class {
72770
73571
  });
72771
73572
  });
72772
73573
  }
72773
- 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)));
72774
73575
  }
72775
73576
  jobNotActiveResponse(c) {
72776
73577
  return c.json(
@@ -72851,6 +73652,7 @@ var DVMServer = class {
72851
73652
  const inboundSeq2 = await jm.recordInboundPending(activeJob, body2.type, body2.content);
72852
73653
  const lockPubkeys2 = await this.resolveLockPubkeysForReceive();
72853
73654
  let unappliedCredit2;
73655
+ let drawFundingReceipt2;
72854
73656
  if (body2.type === "payment") {
72855
73657
  const outcome = await jm.processPayment(activeJob, body2, inboundSeq2, {
72856
73658
  lockPubkeys: lockPubkeys2,
@@ -72859,20 +73661,24 @@ var DVMServer = class {
72859
73661
  if (outcome.error)
72860
73662
  return c.json(outcome.error.body, outcome.error.status);
72861
73663
  unappliedCredit2 = outcome.unappliedCredit;
73664
+ drawFundingReceipt2 = outcome.drawFundingReceipt;
72862
73665
  } else {
72863
73666
  await jm.markInboundVerified(activeJob.id, inboundSeq2);
72864
73667
  }
72865
- jm.startIdleTimer(activeJob);
72866
73668
  try {
72867
73669
  await jm.dispatchMessage(activeJob, body2.type, body2.content);
72868
73670
  await this.persistMessageSnapshot(jm, activeJob, body2.type);
72869
73671
  } catch (error) {
72870
- const response = this.postPaymentSnapshotFailure(c, error, activeJob, body2.type, inboundSeq2, unappliedCredit2);
73672
+ const response = this.postPaymentSnapshotFailure(c, error, activeJob, body2.type, inboundSeq2, unappliedCredit2, drawFundingReceipt2);
72871
73673
  if (response) return response;
72872
73674
  throw error;
72873
73675
  }
72874
73676
  const lastMsg2 = activeJob.messages[activeJob.messages.length - 1];
72875
- return c.json({ seq: lastMsg2.seq, ...unappliedCredit2 && { credit: unappliedCredit2 } }, 201);
73677
+ return c.json({
73678
+ seq: lastMsg2.seq,
73679
+ ...unappliedCredit2 && { credit: unappliedCredit2 },
73680
+ ...drawFundingReceipt2 && { draw_funding_receipt: drawFundingReceipt2 }
73681
+ }, 201);
72876
73682
  }
72877
73683
  const record2 = await jm.store.get(id);
72878
73684
  if (!record2) return c.json({ error: "Job not found" }, 404);
@@ -72936,6 +73742,7 @@ var DVMServer = class {
72936
73742
  const inboundSeq = await jm.recordInboundPending(job, body.type, body.content);
72937
73743
  const lockPubkeys = await this.resolveLockPubkeysForReceive();
72938
73744
  let unappliedCredit;
73745
+ let drawFundingReceipt;
72939
73746
  if (body.type === "payment") {
72940
73747
  const outcome = await jm.processPayment(job, body, inboundSeq, {
72941
73748
  lockPubkeys,
@@ -72946,15 +73753,21 @@ var DVMServer = class {
72946
73753
  return c.json(outcome.error.body, outcome.error.status);
72947
73754
  }
72948
73755
  unappliedCredit = outcome.unappliedCredit;
73756
+ drawFundingReceipt = outcome.drawFundingReceipt;
72949
73757
  } else {
72950
73758
  await jm.markInboundVerified(job.id, inboundSeq);
72951
73759
  }
72952
- const creditBlock = unappliedCredit ? { credit: unappliedCredit } : {};
72953
- const elapsed = Date.now() - record2.lastActivityAt;
72954
- if (elapsed >= this.descriptor.idleTimeout * 1e3) {
73760
+ const creditBlock = {
73761
+ ...unappliedCredit && { credit: unappliedCredit },
73762
+ ...drawFundingReceipt && { draw_funding_receipt: drawFundingReceipt }
73763
+ };
73764
+ const deadline = callerDeadline(record2, this.descriptor.idleTimeout * 1e3);
73765
+ if (deadline !== void 0 && Date.now() >= deadline) {
72955
73766
  await jm.cancelJobIdle(job);
72956
- const lastMsg2 = job.messages[job.messages.length - 1];
72957
- 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
+ }
72958
73771
  }
72959
73772
  jm.startIdleTimer(job);
72960
73773
  try {
@@ -72970,7 +73783,7 @@ var DVMServer = class {
72970
73783
  await this.runReactivation(jm, job, body, record2.status);
72971
73784
  }
72972
73785
  } catch (error) {
72973
- const response = this.postPaymentSnapshotFailure(c, error, job, body.type, inboundSeq, unappliedCredit);
73786
+ const response = this.postPaymentSnapshotFailure(c, error, job, body.type, inboundSeq, unappliedCredit, drawFundingReceipt);
72974
73787
  if (response) return response;
72975
73788
  throw error;
72976
73789
  }
@@ -72984,7 +73797,7 @@ var DVMServer = class {
72984
73797
  await jm.persistJob(job);
72985
73798
  }
72986
73799
  }
72987
- postPaymentSnapshotFailure(c, error, job, type, inboundSeq, unappliedCredit) {
73800
+ postPaymentSnapshotFailure(c, error, job, type, inboundSeq, unappliedCredit, drawFundingReceipt) {
72988
73801
  if (!(error instanceof JobSnapshotPersistenceError) || type !== "payment" || inboundSeq === null || !isStreamableJobStore(this.jobManager.store)) return void 0;
72989
73802
  diagnosticConsole.error({ level: "job_snapshot_unavailable", job_id: job.id, seq: inboundSeq });
72990
73803
  return c.json({
@@ -72996,7 +73809,8 @@ var DVMServer = class {
72996
73809
  payment_status: "recorded",
72997
73810
  job_id: job.id,
72998
73811
  seq: inboundSeq,
72999
- ...unappliedCredit && { credit: unappliedCredit }
73812
+ ...unappliedCredit && { credit: unappliedCredit },
73813
+ ...drawFundingReceipt && { draw_funding_receipt: drawFundingReceipt }
73000
73814
  }, 503);
73001
73815
  }
73002
73816
  /**
@@ -73133,6 +73947,7 @@ function recordedDrawPayment(draw, opts) {
73133
73947
  ...rail === "cashu" ? { cashuFlow: "p2pk_accumulator" } : {},
73134
73948
  creditId: draw.creditId,
73135
73949
  drawId: draw.drawId,
73950
+ upfrontPayment: upfrontPaymentFromDraw(draw),
73136
73951
  drawAmountMicro: draw.amountMicro,
73137
73952
  ...draw.railValue.creditCurrency ? { creditCurrency: draw.railValue.creditCurrency } : {}
73138
73953
  };
@@ -73218,6 +74033,7 @@ function removeUnavailableContent(fields) {
73218
74033
  }
73219
74034
  function terminalResponseFields(job) {
73220
74035
  const fields = {};
74036
+ if (job.upfrontPayment !== void 0) fields.upfront_payment = job.upfrontPayment;
73221
74037
  if (job.status === "completed") {
73222
74038
  if (job.summary !== void 0) fields.summary = job.summary;
73223
74039
  const artifactCount = job.messages.filter((m) => m.type === "artifact").length;
@@ -73479,6 +74295,9 @@ export {
73479
74295
  signFundingReceipt,
73480
74296
  isFundingReceipt,
73481
74297
  verifyFundingReceipt,
74298
+ signDrawFundingReceipt,
74299
+ isDrawFundingReceipt,
74300
+ verifyDrawFundingReceipt,
73482
74301
  isDrainReceipt,
73483
74302
  verifyDrainReceipt,
73484
74303
  require_proper_lockfile,
@@ -73580,6 +74399,7 @@ export {
73580
74399
  checkReceiptAttestation,
73581
74400
  verifyDrainReceiptChain,
73582
74401
  verifyFundingReceiptChain,
74402
+ verifyDrawFundingReceiptChain,
73583
74403
  weakestReceiptVerdict,
73584
74404
  isPublicRequestId,
73585
74405
  parseTraceparent,
@@ -73676,6 +74496,7 @@ export {
73676
74496
  recordFundResponse,
73677
74497
  recordBalanceResponse,
73678
74498
  applyReceiptCredit,
74499
+ recordDrawFunding,
73679
74500
  applyImplicitReceiptCredit,
73680
74501
  ensureProvisionalCredit,
73681
74502
  markCredit,