@dvmkit/dvm-cli 0.18.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +8 -0
  2. package/dist/{chunk-ESQ6DCS3.js → chunk-3NXAIRFF.js} +2 -2
  3. package/dist/{chunk-RYFCHR6Z.js → chunk-7HJ5ZR3D.js} +9 -4
  4. package/dist/{chunk-REIUNZQX.js → chunk-B5KW2TPR.js} +2 -2
  5. package/dist/{chunk-DGA5EFKU.js → chunk-DF2OWCRY.js} +6 -6
  6. package/dist/{chunk-OEWENVJ7.js → chunk-MM646MFM.js} +4 -4
  7. package/dist/{chunk-VSOIBYBF.js → chunk-NCX4JVLU.js} +345 -49
  8. package/dist/{chunk-VLD7OKSH.js → chunk-NKD4NEUF.js} +3 -3
  9. package/dist/{chunk-ZGBCVQF2.js → chunk-OCVRCWBL.js} +3 -3
  10. package/dist/{chunk-IK7RI645.js → chunk-W4ADV3HW.js} +449 -5
  11. package/dist/{chunk-UFMAHF6T.js → chunk-WCX4PNEF.js} +127 -40
  12. package/dist/{chunk-THTPKBZX.js → chunk-X6BETQ7V.js} +1252 -737
  13. package/dist/{chunk-A2B7QDMS.js → chunk-ZZCYSYXR.js} +2 -2
  14. package/dist/{client-PVRLAMI3.js → client-PY4T2DOA.js} +6 -6
  15. package/dist/dvm.js +396 -74
  16. package/dist/{internal-L362ZUWL.js → internal-WAQ3LZN4.js} +10 -8
  17. package/dist/{lifecycle-BH4OA5I3.js → lifecycle-NOK3MKL4.js} +6 -6
  18. package/dist/{payout-reporter-F5LFV5W4-EJ7E5ALO.js → payout-reporter-5PH53T44-7IA4NGIN.js} +2 -2
  19. package/dist/{pocket-refill-6UL6CHD5.js → pocket-refill-U4VK5WGO.js} +10 -10
  20. package/dist/{revenue-reporter-2U55YH2I-EUB6PBRN.js → revenue-reporter-4XV3OO5O-RYHS3M34.js} +2 -2
  21. package/dist/{tempo-lifecycle-WGTX6MJR.js → tempo-lifecycle-QGJ4JEHN.js} +8 -8
  22. package/dist/{tempo-wallet-OTB2YSWE.js → tempo-wallet-GDDZZP5S.js} +7 -7
  23. package/dist/{wallet-73EJBUSO.js → wallet-2M3H75UP.js} +7 -7
  24. package/dist/{x402-G6C4N2BN-TAJEBQGU.js → x402-FHHB3V4V-CM6OMLHE.js} +2 -2
  25. package/package.json +2 -2
  26. package/skills/dvm/calling.md +3 -1
  27. package/skills/dvm/credit.md +4 -0
  28. package/skills/dvm/recovery.md +4 -0
  29. package/skills/dvm/wallets.md +3 -1
@@ -89,10 +89,21 @@ import {
89
89
  x402ResourceServer,
90
90
  x402SupportedNetworksHint,
91
91
  x402Version
92
- } from "./chunk-DGA5EFKU.js";
92
+ } from "./chunk-DF2OWCRY.js";
93
93
  import {
94
- x402EarnedCeiling
95
- } from "./chunk-IK7RI645.js";
94
+ applyRetryToPool,
95
+ connectForX402ShutdownClaim,
96
+ isTransportError,
97
+ poolForX402ShutdownClaim,
98
+ postgresErrorCode,
99
+ waitForX402ShutdownClaim,
100
+ withPostgresRecoveryContext,
101
+ withPostgresTransactionRecovery,
102
+ withX402ShutdownClaimBudget,
103
+ x402EarnedCeiling,
104
+ x402ShutdownClaimEnvironment,
105
+ x402ShutdownClaimSignal
106
+ } from "./chunk-W4ADV3HW.js";
96
107
  import {
97
108
  withSdkInitLock
98
109
  } from "./chunk-R2DSAZBO.js";
@@ -105,7 +116,7 @@ import {
105
116
  extendDiagnosticIdentityAuthority,
106
117
  projectDiagnosticFields,
107
118
  projectSpanRow
108
- } from "./chunk-UFMAHF6T.js";
119
+ } from "./chunk-WCX4PNEF.js";
109
120
  import {
110
121
  privateKeyToAccount
111
122
  } from "./chunk-EVQERRCP.js";
@@ -1754,7 +1765,7 @@ var require_proper_lockfile = __commonJS({
1754
1765
  // node_modules/@dvmkit/sdk/dist/chunk-A262WVYX.js
1755
1766
  var CAPABILITY_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
1756
1767
 
1757
- // node_modules/@dvmkit/sdk/dist/chunk-6VZ44JDJ.js
1768
+ // node_modules/@dvmkit/sdk/dist/chunk-Z5IRFJBH.js
1758
1769
  import { createHash } from "crypto";
1759
1770
 
1760
1771
  // node_modules/@noble/ciphers/utils.js
@@ -3891,7 +3902,7 @@ var getPublicKey2 = i2.getPublicKey;
3891
3902
  var finalizeEvent2 = i2.finalizeEvent;
3892
3903
  var verifyEvent2 = i2.verifyEvent;
3893
3904
 
3894
- // node_modules/@dvmkit/sdk/dist/chunk-6VZ44JDJ.js
3905
+ // node_modules/@dvmkit/sdk/dist/chunk-Z5IRFJBH.js
3895
3906
  var X402_SELF_RELAY_KEY = "DVMKIT_X402_SELF_RELAY_KEY";
3896
3907
  var X402_RECEIVER_AUTHORIZER_KEY = "DVMKIT_X402_RECEIVER_AUTHORIZER_KEY";
3897
3908
  var X402_BATCH_SETTLEMENT_KEY = "DVMKIT_X402_BATCH_SETTLEMENT";
@@ -4999,7 +5010,7 @@ function verifyDrainReceipt(receipt) {
4999
5010
  }
5000
5011
  }
5001
5012
 
5002
- // node_modules/@dvmkit/sdk/dist/chunk-4MX2IZBN.js
5013
+ // node_modules/@dvmkit/sdk/dist/chunk-6GZTO2G2.js
5003
5014
  import { homedir } from "os";
5004
5015
  import { join as join3 } from "path";
5005
5016
  import { chmodSync, mkdirSync, statSync } from "fs";
@@ -10242,7 +10253,7 @@ zero
10242
10253
  zone
10243
10254
  zoo`.split("\n");
10244
10255
 
10245
- // node_modules/@dvmkit/sdk/dist/chunk-4MX2IZBN.js
10256
+ // node_modules/@dvmkit/sdk/dist/chunk-6GZTO2G2.js
10246
10257
  var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
10247
10258
  import { existsSync as existsSync4, readFileSync as readFileSync4, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs";
10248
10259
 
@@ -20797,7 +20808,7 @@ function expand(hash4, prk, info, length = 32) {
20797
20808
  }
20798
20809
  var hkdf = (hash4, ikm, salt, info, length) => expand(hash4, extract(hash4, ikm, salt), info, length);
20799
20810
 
20800
- // node_modules/@dvmkit/sdk/dist/chunk-4MX2IZBN.js
20811
+ // node_modules/@dvmkit/sdk/dist/chunk-6GZTO2G2.js
20801
20812
  import { randomBytes as randomBytes6 } from "crypto";
20802
20813
  import {
20803
20814
  chmodSync as chmodSync4,
@@ -20821,10 +20832,6 @@ import {
20821
20832
  function toLockPubkey(raw2) {
20822
20833
  return raw2.trim().toLowerCase();
20823
20834
  }
20824
- function isX402SettlementReconciliationReason(value) {
20825
- return value === "settlement_not_on_chain" || value === "chain_unreachable" || value === "settlement_unbookmarked" || value === "facilitator_channel_state_unavailable";
20826
- }
20827
- var IMPLICIT_CREDIT_TTL_MS = 90 * 24 * 60 * 60 * 1e3;
20828
20835
  var TEMPO_SESSION_UPDATED_REASON = "Tempo session updated; attach the next voucher to fund this credit.";
20829
20836
  var CONFIG_DIR = process.env.DVM_CONFIG_DIR ?? join3(homedir(), ".dvm");
20830
20837
  var CONFIG_FILE = join3(CONFIG_DIR, "config.json");
@@ -21047,6 +21054,7 @@ async function fetchFromApi() {
21047
21054
  }
21048
21055
  return rate;
21049
21056
  }
21057
+ var IMPLICIT_CREDIT_TTL_MS = 90 * 24 * 60 * 60 * 1e3;
21050
21058
  function backupSecretFile(file2, nextContent) {
21051
21059
  const content = existsSync2(file2) ? readFileSync2(file2) : null;
21052
21060
  if (content === null) return null;
@@ -21306,11 +21314,11 @@ function effectiveFundingMint(mints) {
21306
21314
  }
21307
21315
  function migrateV1ToV4(parsed) {
21308
21316
  const proofs = Array.isArray(parsed.proofs) ? parsed.proofs : [];
21309
- const pending = Array.isArray(parsed.pending_mints) ? parsed.pending_mints : [];
21310
- if (proofs.length > 0 || pending.length > 0) {
21317
+ const pending2 = Array.isArray(parsed.pending_mints) ? parsed.pending_mints : [];
21318
+ if (proofs.length > 0 || pending2.length > 0) {
21311
21319
  throw new DvmError(
21312
21320
  "wallet_unknown_version",
21313
- `Cannot migrate v1 wallet at ${WALLET_FILE}: contains ${proofs.length} proofs and ${pending.length} pending mints under the legacy schema.`,
21321
+ `Cannot migrate v1 wallet at ${WALLET_FILE}: contains ${proofs.length} proofs and ${pending2.length} pending mints under the legacy schema.`,
21314
21322
  "v1 wallets predate the fund flow and are expected to be empty. If this wallet was somehow populated, restore a backup or run: dvm wallet init --force"
21315
21323
  );
21316
21324
  }
@@ -21586,8 +21594,8 @@ async function checkMintHealth(mintUrl, opts) {
21586
21594
  let lastLatency = 0;
21587
21595
  for (let attempt = 0; attempt < retries; attempt++) {
21588
21596
  if (attempt > 0) {
21589
- const delay2 = backoff[Math.min(attempt - 1, backoff.length - 1)];
21590
- await sleep(delay2);
21597
+ const delay3 = backoff[Math.min(attempt - 1, backoff.length - 1)];
21598
+ await sleep(delay3);
21591
21599
  }
21592
21600
  const startedAt = Date.now();
21593
21601
  try {
@@ -21934,6 +21942,9 @@ var X402_BATCH_CHANNEL_ABI = [
21934
21942
  ]
21935
21943
  }
21936
21944
  ];
21945
+ function isX402SettlementReconciliationReason(value) {
21946
+ return value === "settlement_not_on_chain" || value === "chain_unreachable" || value === "settlement_unbookmarked" || value === "facilitator_channel_state_unavailable";
21947
+ }
21937
21948
  var RECEIPT_KDF_SALT = "dvmkit/receipt/v1";
21938
21949
  function deriveReceiptSecret(builderSecretHex, dvmId) {
21939
21950
  const ikm = hexToBytes(builderSecretHex);
@@ -22363,7 +22374,7 @@ function verifyFundingReceiptChain(args) {
22363
22374
  signature: named !== void 0 && verifyFundingReceipt(named),
22364
22375
  attestation: "absent"
22365
22376
  };
22366
- const mismatch = [
22377
+ const mismatch2 = [
22367
22378
  ["credit_id", "credit_id_mismatch"],
22368
22379
  ["fund_id", "fund_id_mismatch"],
22369
22380
  ["funded_micro", "funding_amount_mismatch"],
@@ -22371,7 +22382,7 @@ function verifyFundingReceiptChain(args) {
22371
22382
  ["ledger_seq", "funding_ledger_seq_mismatch"],
22372
22383
  ["caller_pubkey", "caller_pubkey_mismatch"]
22373
22384
  ];
22374
- for (const [field, reason] of mismatch) {
22385
+ for (const [field, reason] of mismatch2) {
22375
22386
  if (checks[field] === "mismatch") return { status: "invalid", checks, reason, receipt: named };
22376
22387
  }
22377
22388
  if (!named || !checks.signature) {
@@ -22408,7 +22419,7 @@ function verifyDrawFundingReceiptChain(args) {
22408
22419
  signature: named !== void 0 && verifyDrawFundingReceipt(named),
22409
22420
  attestation: "absent"
22410
22421
  };
22411
- const mismatch = [
22422
+ const mismatch2 = [
22412
22423
  ["credit_id", "credit_id_mismatch"],
22413
22424
  ["job_id", "job_id_mismatch"],
22414
22425
  ["draw_id", "draw_id_mismatch"],
@@ -22418,7 +22429,7 @@ function verifyDrawFundingReceiptChain(args) {
22418
22429
  ["ledger_seq", "funding_ledger_seq_mismatch"],
22419
22430
  ["caller_pubkey", "caller_pubkey_mismatch"]
22420
22431
  ];
22421
- for (const [field, reason] of mismatch) {
22432
+ for (const [field, reason] of mismatch2) {
22422
22433
  if (checks[field] === "mismatch") return { status: "invalid", checks, reason, receipt: named };
22423
22434
  }
22424
22435
  if (!named || !checks.signature) {
@@ -22549,7 +22560,7 @@ function canonicalRequestPath(pathOrUrl) {
22549
22560
  return parsed.pathname.startsWith("/") ? parsed.pathname : `/${parsed.pathname}`;
22550
22561
  }
22551
22562
 
22552
- // node_modules/@dvmkit/sdk/dist/chunk-JO4V5KJ2.js
22563
+ // node_modules/@dvmkit/sdk/dist/chunk-WRAQQQO4.js
22553
22564
  function createConsoleLogger(_jobId) {
22554
22565
  return {
22555
22566
  debug(_message, data) {
@@ -22619,7 +22630,7 @@ var StepCache = class _StepCache {
22619
22630
  }
22620
22631
  };
22621
22632
 
22622
- // node_modules/@dvmkit/sdk/dist/chunk-NX6ABQDY.js
22633
+ // node_modules/@dvmkit/sdk/dist/chunk-BJJOXCOB.js
22623
22634
  var InvalidCurrencyError = class extends Error {
22624
22635
  code = "invalid_currency";
22625
22636
  raw;
@@ -22992,7 +23003,7 @@ function collectRates(source, raw2, currencies) {
22992
23003
  }
22993
23004
  function carryForward(fresh, previous, currencies) {
22994
23005
  const carried = [];
22995
- const unavailable = [];
23006
+ const unavailable2 = [];
22996
23007
  const rates = { ...fresh.rates };
22997
23008
  for (const currency of currencies) {
22998
23009
  if (Object.prototype.hasOwnProperty.call(fresh.rates, currency)) continue;
@@ -23002,21 +23013,21 @@ function carryForward(fresh, previous, currencies) {
23002
23013
  carried.push(currency);
23003
23014
  continue;
23004
23015
  }
23005
- unavailable.push(currency);
23016
+ unavailable2.push(currency);
23006
23017
  }
23007
- if (carried.length === 0 && unavailable.length === 0) return fresh;
23018
+ if (carried.length === 0 && unavailable2.length === 0) return fresh;
23008
23019
  return {
23009
23020
  rates,
23010
23021
  as_of: fresh.as_of,
23011
23022
  ...carried.length > 0 && { carried_forward: carried },
23012
- ...unavailable.length > 0 && { unavailable }
23023
+ ...unavailable2.length > 0 && { unavailable: unavailable2 }
23013
23024
  };
23014
23025
  }
23015
23026
  function warnPartialRates(source, snapshot, episode) {
23016
23027
  const carried = snapshot.carried_forward ?? [];
23017
- const unavailable = snapshot.unavailable ?? [];
23018
- if (carried.length === 0 && unavailable.length === 0) return null;
23019
- const key = `${carried.join(",")}|${unavailable.join(",")}`;
23028
+ const unavailable2 = snapshot.unavailable ?? [];
23029
+ if (carried.length === 0 && unavailable2.length === 0) return null;
23030
+ const key = `${carried.join(",")}|${unavailable2.join(",")}`;
23020
23031
  if (key === episode) return episode;
23021
23032
  diagnosticConsole.warn(
23022
23033
  {
@@ -23024,7 +23035,7 @@ function warnPartialRates(source, snapshot, episode) {
23024
23035
  event: "fx_rates_partial",
23025
23036
  source,
23026
23037
  ...carried.length > 0 && { carried_forward: carried },
23027
- ...unavailable.length > 0 && { unavailable }
23038
+ ...unavailable2.length > 0 && { unavailable: unavailable2 }
23028
23039
  }
23029
23040
  );
23030
23041
  return key;
@@ -23071,195 +23082,11 @@ function resolveFxSourceFromEnv(env) {
23071
23082
  return raw2;
23072
23083
  }
23073
23084
 
23074
- // node_modules/@dvmkit/sdk/dist/chunk-5PAP7G6G.js
23085
+ // node_modules/@dvmkit/sdk/dist/chunk-CX5VPF4G.js
23075
23086
  import { AsyncLocalStorage } from "async_hooks";
23076
- var postgresRecovery = new AsyncLocalStorage();
23077
- var queryingPool = new AsyncLocalStorage();
23078
- function withPostgresRecoveryContext(context, operation) {
23079
- return postgresRecovery.run(context, operation);
23080
- }
23081
- function isTransportError(err) {
23082
- if (err === null || typeof err !== "object") return false;
23083
- const code = err.code;
23084
- const msg = err.message;
23085
- if (typeof code === "string" && /^[0-9A-Z]{5}$/.test(code)) return false;
23086
- return typeof msg === "string" && msg.includes("Connection terminated") || code === "ECONNRESET" || code === "ENOTFOUND";
23087
- }
23088
- async function withInitRetry(fn2, label, delays = [1e3, 4e3, 15e3]) {
23089
- for (let attempt = 0; ; attempt++) {
23090
- try {
23091
- await fn2();
23092
- return;
23093
- } catch (err) {
23094
- if (!isTransportError(err) || attempt >= delays.length) throw err;
23095
- const wait = delays[attempt];
23096
- diagnosticConsole.warn();
23097
- await new Promise((resolve) => setTimeout(resolve, wait));
23098
- }
23099
- }
23100
- }
23101
- var POSTGRES_APPLICATION_NAME_MAX_BYTES = 63;
23102
- function formatPostgresApplicationName(label, machineId = process.env.FLY_MACHINE_ID) {
23103
- const machineSuffix = machineId ? `@${machineId}` : "";
23104
- const boundedMachineSuffix = truncateUtf8(machineSuffix, POSTGRES_APPLICATION_NAME_MAX_BYTES);
23105
- const labelBudget = POSTGRES_APPLICATION_NAME_MAX_BYTES - Buffer.byteLength(boundedMachineSuffix, "utf8");
23106
- return `${truncateUtf8(label, labelBudget)}${boundedMachineSuffix}`;
23107
- }
23108
- var patchedPools = /* @__PURE__ */ new WeakSet();
23109
- var guardedClients = /* @__PURE__ */ new WeakSet();
23110
- function applyRetryToPool(pool, label = "pg-pool") {
23111
- if (patchedPools.has(pool)) return;
23112
- patchedPools.add(pool);
23113
- pool.options.application_name = formatPostgresApplicationName(label);
23114
- pool.on("error", (_err) => {
23115
- diagnosticConsole.error();
23116
- });
23117
- const p = pool;
23118
- const origQuery = p.query.bind(pool);
23119
- p.query = (...args) => withTransportRecovery(
23120
- pool,
23121
- label,
23122
- "pool.query",
23123
- () => queryingPool.run(pool, () => origQuery(...args))
23124
- );
23125
- const origConnect = pool.connect.bind(pool);
23126
- pool.connect = ((callback) => {
23127
- if (queryingPool.getStore() === pool) {
23128
- return queryingPool.exit(() => callback ? origConnect(callback) : origConnect());
23129
- }
23130
- const pending = withTransportRecovery(pool, label, "pool.connect", async () => {
23131
- const client = await origConnect();
23132
- guardCheckedOutClient(client, label);
23133
- const remainingMs = (postgresRecovery.getStore()?.deadlineMs ?? Infinity) - Date.now();
23134
- const probe = {
23135
- text: "SELECT 1",
23136
- query_timeout: Math.max(1, Math.min(connectionTimeoutMs(pool), remainingMs))
23137
- };
23138
- try {
23139
- await client.query(probe);
23140
- return client;
23141
- } catch (error62) {
23142
- client.release(asError(error62));
23143
- throw error62;
23144
- }
23145
- });
23146
- if (!callback) return pending;
23147
- void pending.then(
23148
- (client) => callback(void 0, client, client.release),
23149
- (error62) => callback(asError(error62), void 0, () => void 0)
23150
- );
23151
- });
23152
- }
23153
- function withPostgresTransactionRecovery(pool, label, operation, callback) {
23154
- return withTransportRecovery(pool, label, operation, async () => {
23155
- const client = await pool.connect();
23156
- let releaseError;
23157
- try {
23158
- await client.query("BEGIN");
23159
- const value = await callback(client);
23160
- await client.query("COMMIT");
23161
- return value;
23162
- } catch (error62) {
23163
- await client.query("ROLLBACK").catch(() => void 0);
23164
- if (isTransportError(error62)) releaseError = asError(error62);
23165
- throw error62;
23166
- } finally {
23167
- client.release(releaseError);
23168
- }
23169
- });
23170
- }
23171
- async function withTransportRecovery(pool, label, operation, callback) {
23172
- const context = postgresRecovery.getStore();
23173
- const maxAttempts = context?.drainPool === false ? 2 : hostPoolSize(pool) + 1;
23174
- const startedAt = Date.now();
23175
- const deadlineMs = context?.deadlineMs ?? startedAt + connectionTimeoutMs(pool);
23176
- let firstError;
23177
- for (let attempt = 1; ; attempt += 1) {
23178
- try {
23179
- const value = await callback();
23180
- if (firstError) {
23181
- logTransportRecovery({
23182
- context,
23183
- label,
23184
- operation,
23185
- attempts: attempt,
23186
- elapsedMs: Date.now() - startedAt,
23187
- outcome: "recovered",
23188
- error: firstError.message
23189
- });
23190
- }
23191
- return value;
23192
- } catch (error62) {
23193
- if (!isTransportError(error62)) throw error62;
23194
- firstError ??= asError(error62);
23195
- const elapsedMs = Date.now() - startedAt;
23196
- if (attempt >= maxAttempts || Date.now() >= deadlineMs) {
23197
- logTransportRecovery({
23198
- context,
23199
- label,
23200
- operation,
23201
- attempts: attempt,
23202
- elapsedMs,
23203
- outcome: "exhausted",
23204
- error: asError(error62).message
23205
- });
23206
- throw error62;
23207
- }
23208
- }
23209
- }
23210
- }
23211
- function connectionTimeoutMs(pool) {
23212
- const configured = pool.options.connectionTimeoutMillis;
23213
- return typeof configured === "number" && Number.isFinite(configured) && configured > 0 ? configured : 1e4;
23214
- }
23215
- function hostPoolSize(pool) {
23216
- const configured = pool.options.max;
23217
- return typeof configured === "number" && Number.isSafeInteger(configured) && configured > 0 ? configured : 10;
23218
- }
23219
- function logTransportRecovery(args) {
23220
- diagnosticConsole.warn(
23221
- {
23222
- level: "postgres_transport_recovery",
23223
- label: args.label,
23224
- route: args.context?.route,
23225
- channel_id: args.context?.channelId,
23226
- operation: args.operation,
23227
- attempts: args.attempts,
23228
- elapsed_ms: args.elapsedMs,
23229
- outcome: args.outcome,
23230
- error: void 0
23231
- }
23232
- );
23233
- }
23234
- function asError(error62) {
23235
- return error62 instanceof Error ? error62 : new Error(String(error62));
23236
- }
23237
- function guardCheckedOutClient(client, _label) {
23238
- if (client === null || typeof client !== "object") return;
23239
- const emitter2 = client;
23240
- if (typeof emitter2.on !== "function" || guardedClients.has(client)) return;
23241
- guardedClients.add(client);
23242
- emitter2.on("error", (_err) => {
23243
- diagnosticConsole.error();
23244
- });
23245
- }
23246
- function truncateUtf8(value, maxBytes) {
23247
- if (maxBytes <= 0) return "";
23248
- if (Buffer.byteLength(value, "utf8") <= maxBytes) return value;
23249
- let result = "";
23250
- for (const character of value) {
23251
- const next = result + character;
23252
- if (Buffer.byteLength(next, "utf8") > maxBytes) break;
23253
- result = next;
23254
- }
23255
- return result;
23256
- }
23257
-
23258
- // node_modules/@dvmkit/sdk/dist/chunk-ATHNJU6K.js
23259
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
23260
23087
  import { randomBytes as randomBytes7, randomUUID } from "crypto";
23261
23088
  import { hostname } from "os";
23262
- var storage = new AsyncLocalStorage2();
23089
+ var storage = new AsyncLocalStorage();
23263
23090
  var defaultService = "unknown";
23264
23091
  function setDefaultService(service) {
23265
23092
  defaultService = service;
@@ -23674,7 +23501,7 @@ import {
23674
23501
  writeSync,
23675
23502
  ftruncateSync
23676
23503
  } from "fs";
23677
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
23504
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
23678
23505
  import { randomUUID as randomUUID2 } from "crypto";
23679
23506
  import { existsSync as existsSync42, readFileSync as readFileSync52, renameSync as renameSync42, writeFileSync as writeFileSync42 } from "fs";
23680
23507
  var import_proper_lockfile4 = __toESM(require_proper_lockfile(), 1);
@@ -24797,14 +24624,14 @@ var x402Client = class _x402Client {
24797
24624
  const clientRecord = clientValue;
24798
24625
  const additiveFields = ADDITIVE_ARRAY_INFO_FIELDS[key];
24799
24626
  const extensionValue = { ...serverRecord };
24800
- const pending = [{ target: extensionValue, source: clientRecord }];
24801
- for (const item of pending) {
24627
+ const pending2 = [{ target: extensionValue, source: clientRecord }];
24628
+ for (const item of pending2) {
24802
24629
  for (const [fieldKey, clientFieldValue] of Object.entries(item.source)) {
24803
24630
  const serverFieldValue = item.target[fieldKey];
24804
24631
  if (serverFieldValue !== null && typeof serverFieldValue === "object" && !Array.isArray(serverFieldValue) && clientFieldValue !== null && typeof clientFieldValue === "object" && !Array.isArray(clientFieldValue)) {
24805
24632
  const nestedValue = { ...serverFieldValue };
24806
24633
  item.target[fieldKey] = nestedValue;
24807
- pending.push({
24634
+ pending2.push({
24808
24635
  target: nestedValue,
24809
24636
  source: clientFieldValue
24810
24637
  });
@@ -27184,9 +27011,14 @@ function parseCreditMenu(raw2) {
27184
27011
  function parseCreditStripeTerms(raw2) {
27185
27012
  if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return void 0;
27186
27013
  const block = raw2;
27187
- if (typeof block.network_id !== "string" || typeof block.min_micro !== "number" || !Number.isSafeInteger(block.min_micro) || block.min_micro <= 0 || block.currency !== "usd")
27014
+ if (typeof block.network_id !== "string" || typeof block.min_micro !== "number" || !Number.isSafeInteger(block.min_micro) || block.min_micro <= 0 || block.checkout !== void 0 && block.checkout !== true || block.currency !== "usd")
27188
27015
  return void 0;
27189
- return { network_id: block.network_id, min_micro: block.min_micro, currency: "usd" };
27016
+ return {
27017
+ network_id: block.network_id,
27018
+ min_micro: block.min_micro,
27019
+ currency: "usd",
27020
+ ...block.checkout === true && { checkout: true }
27021
+ };
27190
27022
  }
27191
27023
  function parseCreditTempoTerms(raw2) {
27192
27024
  if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return void 0;
@@ -27635,7 +27467,7 @@ function applyReceiptCredit(args) {
27635
27467
  return { credit: record2 };
27636
27468
  }
27637
27469
  attachDvmLocation(record2, key, args.identity);
27638
- let mismatch;
27470
+ let mismatch2;
27639
27471
  let fundedMicro;
27640
27472
  const sequential = args.credit.ledger_seq === record2.ledgerSeq + 1;
27641
27473
  const charged = args.settlement ? args.settlement.charged : args.credit.amount;
@@ -27650,7 +27482,7 @@ function applyReceiptCredit(args) {
27650
27482
  const paidMicro = record2.remainingMicro + (fundedMicro ?? 0);
27651
27483
  const expected = paidMicro - charged;
27652
27484
  if (args.credit.balance_after !== expected || charged > paidMicro) {
27653
- mismatch = {
27485
+ mismatch2 = {
27654
27486
  atMs: now,
27655
27487
  expectedMicro: expected,
27656
27488
  ...fundedMicro !== void 0 ? { fundedMicro } : {},
@@ -27660,7 +27492,7 @@ function applyReceiptCredit(args) {
27660
27492
  ...record2.lastReceiptJobId ? { priorJobId: record2.lastReceiptJobId } : {},
27661
27493
  jobId: args.jobId
27662
27494
  };
27663
- record2.discrepancy = mismatch;
27495
+ record2.discrepancy = mismatch2;
27664
27496
  }
27665
27497
  }
27666
27498
  record2.remainingMicro = args.credit.balance_after;
@@ -27669,7 +27501,7 @@ function applyReceiptCredit(args) {
27669
27501
  delete record2.unsequencedBalance;
27670
27502
  delete record2.provisional;
27671
27503
  if (args.outcome === "completed") record2.lastPriceMicro = args.credit.amount;
27672
- if (!mismatch && record2.discrepancy && args.credit.ledger_seq > record2.discrepancy.ledgerSeq) {
27504
+ if (!mismatch2 && record2.discrepancy && args.credit.ledger_seq > record2.discrepancy.ledgerSeq) {
27673
27505
  delete record2.discrepancy;
27674
27506
  }
27675
27507
  record2.lastReceiptJobId = args.jobId;
@@ -27677,7 +27509,7 @@ function applyReceiptCredit(args) {
27677
27509
  saveStore(store);
27678
27510
  return {
27679
27511
  credit: record2,
27680
- ...mismatch ? { mismatch } : {},
27512
+ ...mismatch2 ? { mismatch: mismatch2 } : {},
27681
27513
  ...fundedMicro !== void 0 ? { fundedMicro } : {}
27682
27514
  };
27683
27515
  });
@@ -27813,12 +27645,12 @@ function applyImplicitReceiptCredit(args) {
27813
27645
  if (locationChanged) saveStore(store);
27814
27646
  return { credit: record2 };
27815
27647
  }
27816
- let mismatch;
27648
+ let mismatch2;
27817
27649
  const sequential = args.credit.ledger_seq === record2.ledgerSeq + 1;
27818
27650
  if (sequential && args.outcome === "completed" && record2.status === "active") {
27819
27651
  const expected = record2.remainingMicro - args.credit.amount;
27820
27652
  if (args.credit.balance_after !== expected) {
27821
- mismatch = {
27653
+ mismatch2 = {
27822
27654
  atMs: now,
27823
27655
  expectedMicro: expected,
27824
27656
  reportedMicro: args.credit.balance_after,
@@ -27827,14 +27659,14 @@ function applyImplicitReceiptCredit(args) {
27827
27659
  ...record2.lastReceiptJobId ? { priorJobId: record2.lastReceiptJobId } : {},
27828
27660
  jobId: args.jobId
27829
27661
  };
27830
- record2.discrepancy = mismatch;
27662
+ record2.discrepancy = mismatch2;
27831
27663
  }
27832
27664
  }
27833
27665
  if (args.credit.ledger_seq >= record2.ledgerSeq) {
27834
27666
  record2.remainingMicro = args.credit.balance_after;
27835
27667
  record2.ledgerSeq = args.credit.ledger_seq;
27836
27668
  }
27837
- if (!mismatch && record2.discrepancy && args.credit.ledger_seq > record2.discrepancy.ledgerSeq) {
27669
+ if (!mismatch2 && record2.discrepancy && args.credit.ledger_seq > record2.discrepancy.ledgerSeq) {
27838
27670
  delete record2.discrepancy;
27839
27671
  }
27840
27672
  record2.currency = args.currency;
@@ -27843,7 +27675,7 @@ function applyImplicitReceiptCredit(args) {
27843
27675
  if (record2.remainingMicro <= 0) {
27844
27676
  store.implicitCredits = store.implicitCredits.filter((candidate) => candidate !== record2);
27845
27677
  saveStore(store);
27846
- return { ...mismatch ? { mismatch } : {}, pruned: true };
27678
+ return { ...mismatch2 ? { mismatch: mismatch2 } : {}, pruned: true };
27847
27679
  }
27848
27680
  if (record2.expiryMs <= now) record2.status = "lost";
27849
27681
  const capped = capLostImplicitCredits(store.implicitCredits);
@@ -27851,7 +27683,7 @@ function applyImplicitReceiptCredit(args) {
27851
27683
  saveStore(store);
27852
27684
  return {
27853
27685
  ...store.implicitCredits.includes(record2) ? { credit: record2 } : {},
27854
- ...mismatch ? { mismatch } : {}
27686
+ ...mismatch2 ? { mismatch: mismatch2 } : {}
27855
27687
  };
27856
27688
  });
27857
27689
  }
@@ -28924,7 +28756,7 @@ function isWorkingMessage(msg) {
28924
28756
  var X402_EXACT_AUTHORIZATION_TTL_SECONDS = 600;
28925
28757
  var X402_REFUSAL_TRANSACTION_DISCOVERY_WINDOW_MS = 15 * 6e4;
28926
28758
  var TEMPO_CHARGE_PENDING_STALE_MS = 24 * 60 * 60 * 1e3;
28927
- var tempoLockOwner = new AsyncLocalStorage3();
28759
+ var tempoLockOwner = new AsyncLocalStorage2();
28928
28760
  async function withTempoChannelLock(operation) {
28929
28761
  if (tempoLockOwner.getStore()?.active) return operation();
28930
28762
  ensureTempoChannelFile();
@@ -29099,15 +28931,15 @@ async function retireTempoChannelScope(association) {
29099
28931
  operator: association.operator
29100
28932
  }).delete(association.channelKey);
29101
28933
  }
29102
- function tempoChargeFundingStale(pending, now = Date.now()) {
29103
- return now - pending.requestedAt >= TEMPO_CHARGE_PENDING_STALE_MS;
28934
+ function tempoChargeFundingStale(pending2, now = Date.now()) {
28935
+ return now - pending2.requestedAt >= TEMPO_CHARGE_PENDING_STALE_MS;
29104
28936
  }
29105
- function tempoChargeCredentialSettleable(pending, now = Date.now()) {
29106
- return pending.credentialValidBefore !== void 0 && now < pending.credentialValidBefore * 1e3;
28937
+ function tempoChargeCredentialSettleable(pending2, now = Date.now()) {
28938
+ return pending2.credentialValidBefore !== void 0 && now < pending2.credentialValidBefore * 1e3;
29107
28939
  }
29108
- function recordPendingTempoChargeFunding(pending) {
28940
+ function recordPendingTempoChargeFunding(pending2) {
29109
28941
  const { file: file2, credits } = loadChargeFile();
29110
- const entry = { ...pending, endpoint: normalizeCreditEndpoint(pending.endpoint) };
28942
+ const entry = { ...pending2, endpoint: normalizeCreditEndpoint(pending2.endpoint) };
29111
28943
  file2.charges = [
29112
28944
  ...file2.charges.filter((candidate) => !sameChargeCredit(candidate, entry, credits)),
29113
28945
  entry
@@ -29132,11 +28964,11 @@ function listResumableTempoChargeFundings(filter = {}) {
29132
28964
  (entry) => (!endpoint || fundingReachableAt(entry, endpoint, credits)) && (!filter.callerPubkey || entry.callerPubkey === filter.callerPubkey) && !tempoChargeFundingStale(entry, filter.now)
29133
28965
  ).sort((a, b2) => a.requestedAt - b2.requestedAt);
29134
28966
  }
29135
- function clearPendingTempoChargeFunding(pending) {
28967
+ function clearPendingTempoChargeFunding(pending2) {
29136
28968
  const { file: file2, credits } = loadChargeFile();
29137
- const key = { ...pending, endpoint: normalizeCreditEndpoint(pending.endpoint) };
28969
+ const key = { ...pending2, endpoint: normalizeCreditEndpoint(pending2.endpoint) };
29138
28970
  const remaining = file2.charges.filter(
29139
- (entry) => !sameChargeCredit(entry, key, credits) || entry.fundId !== pending.fundId
28971
+ (entry) => !sameChargeCredit(entry, key, credits) || entry.fundId !== pending2.fundId
29140
28972
  );
29141
28973
  if (remaining.length === file2.charges.length) return;
29142
28974
  file2.charges = remaining;
@@ -30778,21 +30610,21 @@ function resolveX402ChannelRpc(channelNetwork, configuredNetwork, bundled) {
30778
30610
  };
30779
30611
  }
30780
30612
  var X402_PENDING_STALE_MS = 24 * 60 * 60 * 1e3;
30781
- function x402PendingStale(pending, now = Date.now()) {
30782
- return now - pending.requestedAt >= X402_PENDING_STALE_MS;
30613
+ function x402PendingStale(pending2, now = Date.now()) {
30614
+ return now - pending2.requestedAt >= X402_PENDING_STALE_MS;
30783
30615
  }
30784
- function x402PendingRetired(pending) {
30785
- return pending.refusedAt !== void 0 || pending.supersededAt !== void 0;
30616
+ function x402PendingRetired(pending2) {
30617
+ return pending2.refusedAt !== void 0 || pending2.supersededAt !== void 0;
30786
30618
  }
30787
- function x402PendingBlockExpiresAt(pending) {
30788
- return x402PendingDepositExpiresAt(pending) ?? pending.requestedAt + X402_PENDING_STALE_MS;
30619
+ function x402PendingBlockExpiresAt(pending2) {
30620
+ return x402PendingDepositExpiresAt(pending2) ?? pending2.requestedAt + X402_PENDING_STALE_MS;
30789
30621
  }
30790
- function x402PendingDepositExpiresAt(pending) {
30791
- const seconds = pending.authorizationValidBefore ? Number(pending.authorizationValidBefore) : NaN;
30622
+ function x402PendingDepositExpiresAt(pending2) {
30623
+ const seconds = pending2.authorizationValidBefore ? Number(pending2.authorizationValidBefore) : NaN;
30792
30624
  return Number.isFinite(seconds) ? seconds * 1e3 : void 0;
30793
30625
  }
30794
- function x402PendingUnsettled(pending, now = Date.now()) {
30795
- return !x402PendingRetired(pending) || now <= x402PendingBlockExpiresAt(pending);
30626
+ function x402PendingUnsettled(pending2, now = Date.now()) {
30627
+ return !x402PendingRetired(pending2) || now <= x402PendingBlockExpiresAt(pending2);
30796
30628
  }
30797
30629
  function x402VoucherPendingState(blocking) {
30798
30630
  const depositExpiresAt = x402PendingDepositExpiresAt(blocking);
@@ -30807,20 +30639,20 @@ function x402VoucherPendingState(blocking) {
30807
30639
  ...depositExpiresAt === void 0 ? {} : { depositExpiresAt }
30808
30640
  };
30809
30641
  }
30810
- function assertNoRivalX402Voucher(channelId, creditId, pending, now) {
30811
- const blocking = pending.filter((entry) => x402PendingUnsettled(entry, now));
30642
+ function assertNoRivalX402Voucher(channelId, creditId, pending2, now) {
30643
+ const blocking = pending2.filter((entry) => x402PendingUnsettled(entry, now));
30812
30644
  const rival = blocking.find((entry) => entry.creditId !== creditId && !x402PendingRetired(entry)) ?? blocking.find((entry) => entry.creditId !== creditId || x402PendingRetired(entry));
30813
30645
  if (rival) throw { ...x402VoucherPendingState(rival), channelId };
30814
30646
  }
30815
- function x402ExactFundingDead(pending, now = Date.now()) {
30816
- const seconds = pending.authorizationValidBefore ? Number(pending.authorizationValidBefore) : NaN;
30817
- return Number.isFinite(seconds) ? now >= seconds * 1e3 : now >= pending.requestedAt + X402_EXACT_AUTHORIZATION_TTL_SECONDS * 1e3;
30647
+ function x402ExactFundingDead(pending2, now = Date.now()) {
30648
+ const seconds = pending2.authorizationValidBefore ? Number(pending2.authorizationValidBefore) : NaN;
30649
+ return Number.isFinite(seconds) ? now >= seconds * 1e3 : now >= pending2.requestedAt + X402_EXACT_AUTHORIZATION_TTL_SECONDS * 1e3;
30818
30650
  }
30819
- function recordPendingX402ExactFunding(pending) {
30651
+ function recordPendingX402ExactFunding(pending2) {
30820
30652
  const { file: file2, credits } = loadFundingFile();
30821
30653
  file2.exact = [
30822
- ...file2.exact.filter((entry) => !sameFundingCredit(entry, pending, credits)),
30823
- pending
30654
+ ...file2.exact.filter((entry) => !sameFundingCredit(entry, pending2, credits)),
30655
+ pending2
30824
30656
  ];
30825
30657
  saveFile2(file2);
30826
30658
  }
@@ -30837,11 +30669,11 @@ function listResumableX402ExactFundings(filter = {}) {
30837
30669
  (entry) => (!endpoint || fundingReachableAt(entry, endpoint, credits)) && (!filter.callerPubkey || entry.callerPubkey === filter.callerPubkey) && !x402ExactFundingDead(entry, filter.now)
30838
30670
  );
30839
30671
  }
30840
- function clearPendingX402ExactFunding(pending) {
30672
+ function clearPendingX402ExactFunding(pending2) {
30841
30673
  const { file: file2 } = loadFundingFile();
30842
- const key = pendingKey(pending);
30674
+ const key = pendingKey(pending2);
30843
30675
  file2.exact = file2.exact.filter(
30844
- (entry) => pendingKey(entry) !== key || entry.fundId !== pending.fundId
30676
+ (entry) => pendingKey(entry) !== key || entry.fundId !== pending2.fundId
30845
30677
  );
30846
30678
  saveFile2(file2);
30847
30679
  }
@@ -31054,16 +30886,16 @@ function findX402Channel(args) {
31054
30886
  function x402ChannelBalanceUnreconciledAt(channelId) {
31055
30887
  return loadFile2().channels[canonicalChannelId(channelId)]?.unreconciledBalanceAt;
31056
30888
  }
31057
- function recordPendingX402Funding(pending) {
30889
+ function recordPendingX402Funding(pending2) {
31058
30890
  const { file: file2, credits } = loadFundingFile();
31059
- const pendingOrigin = normalizeEndpoint(pending.endpoint);
30891
+ const pendingOrigin = normalizeEndpoint(pending2.endpoint);
31060
30892
  file2.pending = [
31061
30893
  ...file2.pending.flatMap((entry) => {
31062
- if (!sameFundingCredit(entry, pending, credits) || x402PendingRetired(entry)) return [entry];
30894
+ if (!sameFundingCredit(entry, pending2, credits) || x402PendingRetired(entry)) return [entry];
31063
30895
  if (normalizeEndpoint(entry.endpoint) === pendingOrigin) return [];
31064
- return [{ ...entry, supersededAt: pending.requestedAt }];
30896
+ return [{ ...entry, supersededAt: pending2.requestedAt }];
31065
30897
  }),
31066
- pending
30898
+ pending2
31067
30899
  ];
31068
30900
  saveFile2(file2);
31069
30901
  }
@@ -31089,9 +30921,9 @@ function listPendingX402FundingsForChannel(channelId) {
31089
30921
  (entry) => canonicalChannelId(entry.channelId) === canonical
31090
30922
  );
31091
30923
  }
31092
- function retirePendingX402Funding(pending) {
30924
+ function retirePendingX402Funding(pending2) {
31093
30925
  const { file: file2 } = loadFundingFile();
31094
- const key = pendingKey(pending);
30926
+ const key = pendingKey(pending2);
31095
30927
  const target = file2.pending.find(
31096
30928
  (entry) => pendingKey(entry) === key && !x402PendingRetired(entry)
31097
30929
  );
@@ -31100,9 +30932,9 @@ function retirePendingX402Funding(pending) {
31100
30932
  file2.pending = file2.pending.map((entry) => entry === target ? { ...entry, refusedAt } : entry);
31101
30933
  saveFile2(file2);
31102
30934
  }
31103
- function clearPendingX402Funding(pending) {
30935
+ function clearPendingX402Funding(pending2) {
31104
30936
  const { file: file2 } = loadFundingFile();
31105
- const next = file2.pending.filter((entry) => !sameJournalEntry(entry, pending));
30937
+ const next = file2.pending.filter((entry) => !sameJournalEntry(entry, pending2));
31106
30938
  if (next.length === file2.pending.length) return;
31107
30939
  file2.pending = next;
31108
30940
  saveFile2(file2);
@@ -31148,11 +30980,11 @@ function loadFundingFile() {
31148
30980
  function collapseFundingFile() {
31149
30981
  const file2 = loadFile2();
31150
30982
  const credits = listCredits();
31151
- const pending = dedupeX402FundingCredits(file2.pending, credits);
30983
+ const pending2 = dedupeX402FundingCredits(file2.pending, credits);
31152
30984
  const exact = dedupeFundingCredits(file2.exact, credits);
31153
- if (pending.changed) file2.pending = pending.entries;
30985
+ if (pending2.changed) file2.pending = pending2.entries;
31154
30986
  if (exact.changed) file2.exact = exact.entries;
31155
- return { file: file2, credits, changed: pending.changed || exact.changed };
30987
+ return { file: file2, credits, changed: pending2.changed || exact.changed };
31156
30988
  }
31157
30989
  function dedupeX402FundingCredits(entries, credits) {
31158
30990
  const kept = [];
@@ -31406,9 +31238,9 @@ async function resolveChannelRead(channel, configuredNetwork, clients, posture)
31406
31238
  async function readChannelState(channel, configuredNetwork, clients, posture) {
31407
31239
  const read = await resolveChannelRead(channel, configuredNetwork, clients, posture);
31408
31240
  let onchain;
31409
- let pending;
31241
+ let pending2;
31410
31242
  try {
31411
- [onchain, pending] = await Promise.all([
31243
+ [onchain, pending2] = await Promise.all([
31412
31244
  read.client.readContract({
31413
31245
  address: BATCH_SETTLEMENT_ADDRESS,
31414
31246
  abi: X402_BATCH_CHANNEL_ABI,
@@ -31432,7 +31264,7 @@ async function readChannelState(channel, configuredNetwork, clients, posture) {
31432
31264
  return {
31433
31265
  balance: onchain[0],
31434
31266
  totalClaimed: BigInt(onchain[1]),
31435
- pendingWithdrawal: pending[0]
31267
+ pendingWithdrawal: pending2[0]
31436
31268
  };
31437
31269
  }
31438
31270
  async function readChannelRefundNonce(channel, configuredNetwork, clients) {
@@ -31484,8 +31316,8 @@ function x402ReservationRelease(journalled) {
31484
31316
  const retriable = journalled.filter((entry) => !x402PendingRetired(entry));
31485
31317
  return retriable.length > 0 ? { entry: retriable[0], retriable: true } : { entry: journalled[0], retriable: false };
31486
31318
  }
31487
- function x402VoucherCap(pending) {
31488
- const recorded = pending.maxClaimableMicro ?? x402VoucherFacts(pending.paymentHeader)?.maxClaimableMicro;
31319
+ function x402VoucherCap(pending2) {
31320
+ const recorded = pending2.maxClaimableMicro ?? x402VoucherFacts(pending2.paymentHeader)?.maxClaimableMicro;
31489
31321
  if (recorded === void 0) return X402_MAX_UINT128;
31490
31322
  try {
31491
31323
  return BigInt(recorded);
@@ -31923,12 +31755,12 @@ function channelChainReader(network, walletNetwork) {
31923
31755
  });
31924
31756
  }
31925
31757
  async function reconcileLapsedRefusals(wallet, channelId) {
31926
- const pending = listPendingX402FundingsForChannel(channelId);
31927
- if (!pending.some((entry) => x402PendingRetired(entry) && entry.depositMicro !== void 0)) {
31758
+ const pending2 = listPendingX402FundingsForChannel(channelId);
31759
+ if (!pending2.some((entry) => x402PendingRetired(entry) && entry.depositMicro !== void 0)) {
31928
31760
  return;
31929
31761
  }
31930
31762
  try {
31931
- await reconcileRefusedX402Deposits({ wallet, channelId, pending });
31763
+ await reconcileRefusedX402Deposits({ wallet, channelId, pending: pending2 });
31932
31764
  } catch {
31933
31765
  }
31934
31766
  }
@@ -31977,9 +31809,9 @@ function x402RefundError(err, chain4) {
31977
31809
  );
31978
31810
  }
31979
31811
  function assertNoRivalVoucher(channelId, creditId) {
31980
- const pending = listPendingX402FundingsForChannel(channelId);
31812
+ const pending2 = listPendingX402FundingsForChannel(channelId);
31981
31813
  try {
31982
- assertNoRivalX402Voucher(channelId, creditId, pending);
31814
+ assertNoRivalX402Voucher(channelId, creditId, pending2);
31983
31815
  } catch (state) {
31984
31816
  if (typeof state !== "object" || state === null || !("code" in state) || state.code !== "x402_voucher_pending" || !("creditId" in state) || typeof state.creditId !== "string" || !("fundId" in state) || typeof state.fundId !== "string" || !("channelId" in state) || typeof state.channelId !== "string" || !("endpoint" in state) || typeof state.endpoint !== "string" || !("retired" in state) || typeof state.retired !== "boolean" || !("blockedUntil" in state) || typeof state.blockedUntil !== "number") {
31985
31817
  throw state;
@@ -32089,8 +31921,8 @@ function parseStoreValue(value) {
32089
31921
  return parsed;
32090
31922
  }
32091
31923
 
32092
- // node_modules/@dvmkit/sdk/dist/chunk-P5VP6ZPW.js
32093
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
31924
+ // node_modules/@dvmkit/sdk/dist/chunk-GQIVNV77.js
31925
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
32094
31926
  var PostgresTempoSessionStore = class {
32095
31927
  constructor(pool) {
32096
31928
  this.pool = pool;
@@ -32101,7 +31933,7 @@ var PostgresTempoSessionStore = class {
32101
31933
  useHostingCleanupFence(fence) {
32102
31934
  this.hostingCleanupFence = fence;
32103
31935
  }
32104
- acceptance = new AsyncLocalStorage4();
31936
+ acceptance = new AsyncLocalStorage3();
32105
31937
  async init() {
32106
31938
  await withSdkInitLock(this.pool, async () => {
32107
31939
  const before = await this.pool.query(
@@ -32209,10 +32041,10 @@ var PostgresTempoSessionStore = class {
32209
32041
  await context.client?.query("ROLLBACK").catch(() => void 0);
32210
32042
  throw error62;
32211
32043
  } finally {
32212
- const pending = context.pendingClient;
32044
+ const pending2 = context.pendingClient;
32213
32045
  context.client = void 0;
32214
32046
  context.pendingClient = void 0;
32215
- (await pending?.catch(() => void 0))?.release();
32047
+ (await pending2?.catch(() => void 0))?.release();
32216
32048
  }
32217
32049
  }
32218
32050
  /**
@@ -32667,7 +32499,7 @@ function acceptanceVoucherAmount(acceptance, key, current, next) {
32667
32499
  return authorized !== void 0 && authorized >= acceptance.cumulativeAmount ? acceptance.cumulativeAmount : void 0;
32668
32500
  }
32669
32501
 
32670
- // node_modules/@dvmkit/sdk/dist/chunk-W3URQBLA.js
32502
+ // node_modules/@dvmkit/sdk/dist/chunk-FO3KFX2H.js
32671
32503
  import { createHash as createHash5 } from "crypto";
32672
32504
  var DEFAULT_TABLE_NAME = "mpp_tempo_charge_replays";
32673
32505
  var DEFAULT_RETENTION_MS = 60 * 60 * 1e3;
@@ -32826,7 +32658,7 @@ var PostgresTempoChargeStore = class {
32826
32658
  const now = this.now();
32827
32659
  if (change.op === "set") {
32828
32660
  if (this.hostingCleanupFence) {
32829
- const pending = await client.query(
32661
+ const pending2 = await client.query(
32830
32662
  `SELECT EXISTS (
32831
32663
  SELECT 1 FROM sdk_hosted_tempo_charge_intents i
32832
32664
  LEFT JOIN sdk_hosting_admissions a ON a.id=i.admission_id
@@ -32836,7 +32668,7 @@ var PostgresTempoChargeStore = class {
32836
32668
  ) AS reserved`,
32837
32669
  [this.hostingCleanupFence.dvmId, this.hostingCleanupFence.scope, key]
32838
32670
  );
32839
- if (!pending.rows[0]?.reserved) {
32671
+ if (!pending2.rows[0]?.reserved) {
32840
32672
  await this.hostingCleanupFence.assertNewIntent(client);
32841
32673
  }
32842
32674
  }
@@ -33022,9 +32854,9 @@ function isUniqueViolation(err) {
33022
32854
  return typeof err === "object" && err !== null && err.code === "23505";
33023
32855
  }
33024
32856
 
33025
- // node_modules/@dvmkit/sdk/dist/chunk-6JPH553R.js
32857
+ // node_modules/@dvmkit/sdk/dist/chunk-5J6L47RB.js
33026
32858
  import { randomUUID as randomUUID3 } from "crypto";
33027
- import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
32859
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
33028
32860
  import { isDeepStrictEqual } from "util";
33029
32861
  var NON_CHANNEL_BITCOIN_RAILS = [
33030
32862
  "cashu",
@@ -33193,9 +33025,9 @@ var PostgresX402ChannelStorage = class {
33193
33025
  fundingCommitment: reservation.commitment
33194
33026
  }, (tx) => this.hostingCleanupFence.assertFundingReservation(tx, reservation));
33195
33027
  }
33196
- transaction = new AsyncLocalStorage5();
33028
+ transaction = new AsyncLocalStorage4();
33197
33029
  hostedFunding = /* @__PURE__ */ new WeakMap();
33198
- refundBase = new AsyncLocalStorage5();
33030
+ refundBase = new AsyncLocalStorage4();
33199
33031
  settlementPool;
33200
33032
  fleetLock = Promise.resolve();
33201
33033
  fleetLockQueueDepth = 0;
@@ -33341,7 +33173,7 @@ var PostgresX402ChannelStorage = class {
33341
33173
  return rows2[0]?.pending_settle ?? false;
33342
33174
  }
33343
33175
  /** Record whether a claim's funds still need a `settle(receiver, token)` transfer. */
33344
- async setSettlePending(scope, pending) {
33176
+ async setSettlePending(scope, pending2) {
33345
33177
  const writer = await this.settlementWriter();
33346
33178
  await writer.query(
33347
33179
  `INSERT INTO x402_batch_settlement_state (scope, pending_settle, updated_at)
@@ -33349,7 +33181,7 @@ var PostgresX402ChannelStorage = class {
33349
33181
  ON CONFLICT (scope) DO UPDATE
33350
33182
  SET pending_settle = EXCLUDED.pending_settle,
33351
33183
  updated_at = EXCLUDED.updated_at`,
33352
- [scope, pending, Date.now()]
33184
+ [scope, pending2, Date.now()]
33353
33185
  );
33354
33186
  }
33355
33187
  /**
@@ -33687,7 +33519,7 @@ var PostgresX402ChannelStorage = class {
33687
33519
  }
33688
33520
  }
33689
33521
  async get(channelId) {
33690
- const q2 = this.transaction.getStore() ?? this.pool;
33522
+ const q2 = this.transaction.getStore() ?? poolForX402ShutdownClaim(this.pool);
33691
33523
  const { rows: rows2 } = await q2.query(
33692
33524
  `SELECT * FROM x402_batch_channels WHERE channel_id = $1`,
33693
33525
  [normalizeChannelId2(channelId)]
@@ -33696,7 +33528,7 @@ var PostgresX402ChannelStorage = class {
33696
33528
  }
33697
33529
  /** List all channel snapshots in stable channel-id order. */
33698
33530
  async list() {
33699
- const q2 = this.transaction.getStore() ?? this.pool;
33531
+ const q2 = this.transaction.getStore() ?? poolForX402ShutdownClaim(this.pool);
33700
33532
  const { rows: rows2 } = await q2.query(
33701
33533
  `SELECT * FROM x402_batch_channels ORDER BY channel_id`
33702
33534
  );
@@ -33706,7 +33538,7 @@ var PostgresX402ChannelStorage = class {
33706
33538
  async updateChannel(channelId, update) {
33707
33539
  const active = this.transaction.getStore();
33708
33540
  if (active) return this.updateInTransaction(active, channelId, update, true);
33709
- const client = await this.pool.connect();
33541
+ const client = await connectForX402ShutdownClaim(this.pool);
33710
33542
  try {
33711
33543
  await client.query("BEGIN");
33712
33544
  const result = await this.updateInTransaction(client, channelId, update, false);
@@ -33762,10 +33594,10 @@ var PostgresX402ChannelStorage = class {
33762
33594
  }
33763
33595
  /** Durable effect bookkeeping reached while a caller already holds a host-pool client. */
33764
33596
  async withSettlementTransaction(operation) {
33765
- const client = await (await this.settlementPoolRef()).connect();
33597
+ const client = await connectForX402ShutdownClaim(await this.settlementPoolRef());
33766
33598
  try {
33767
33599
  await client.query("BEGIN");
33768
- const result = await operation(client);
33600
+ const result = await waitForX402ShutdownClaim(() => operation(client));
33769
33601
  await client.query("COMMIT");
33770
33602
  return result;
33771
33603
  } catch (error62) {
@@ -33828,7 +33660,7 @@ var PostgresX402ChannelStorage = class {
33828
33660
  */
33829
33661
  async withRelaySubmissionLock(key, operation) {
33830
33662
  const pool = await this.settlementPoolRef();
33831
- const client = await pool.connect();
33663
+ const client = await connectForX402ShutdownClaim(pool);
33832
33664
  let locked = false;
33833
33665
  let destroyClient = false;
33834
33666
  try {
@@ -33844,7 +33676,7 @@ var PostgresX402ChannelStorage = class {
33844
33676
  await relayLockHolder(client, key)
33845
33677
  );
33846
33678
  }
33847
- return await operation();
33679
+ return await waitForX402ShutdownClaim(operation);
33848
33680
  } finally {
33849
33681
  if (locked) {
33850
33682
  await client.query(RELAY_UNLOCK_SQL, [key]).catch(() => {
@@ -33864,14 +33696,14 @@ var PostgresX402ChannelStorage = class {
33864
33696
  if (settlement) await (await settlement).end();
33865
33697
  }
33866
33698
  async settlementWriter() {
33867
- return this.settlementPoolRef();
33699
+ return poolForX402ShutdownClaim(await this.settlementPoolRef());
33868
33700
  }
33869
33701
  async settlementPoolRef() {
33870
33702
  this.settlementPool ??= createSettlementPool(this.pool);
33871
33703
  return this.settlementPool;
33872
33704
  }
33873
33705
  async runUnderFleetLock(operation, wait) {
33874
- const client = await this.pool.connect();
33706
+ const client = await connectForX402ShutdownClaim(this.pool);
33875
33707
  let locked = false;
33876
33708
  let timeoutSet = false;
33877
33709
  try {
@@ -33893,7 +33725,7 @@ var PostgresX402ChannelStorage = class {
33893
33725
  locked = rows2[0]?.locked ?? false;
33894
33726
  }
33895
33727
  if (!locked) return false;
33896
- await operation();
33728
+ await waitForX402ShutdownClaim(operation);
33897
33729
  return true;
33898
33730
  } finally {
33899
33731
  let destroyClient = false;
@@ -34880,8 +34712,8 @@ var CreditLedger = class {
34880
34712
  if (expiryMs > nowMs || balanceMicro <= 0 || credit.status !== "active") return void 0;
34881
34713
  if (credit.tempo_channel_id !== null || credit.rail === "tempo") return void 0;
34882
34714
  if (isCardFundedRail(credit.rail)) return void 0;
34883
- const pending = await this.pendingSums(client, credit.credit_id);
34884
- if (pending.micro > 0) return void 0;
34715
+ const pending2 = await this.pendingSums(client, credit.credit_id);
34716
+ if (pending2.micro > 0) return void 0;
34885
34717
  const { rows: open2 } = await client.query(
34886
34718
  `SELECT 1 AS one FROM credit_expiry_releases
34887
34719
  WHERE credit_id = $1 AND reversed_at IS NULL`,
@@ -34997,8 +34829,8 @@ var CreditLedger = class {
34997
34829
  balanceMicro
34998
34830
  });
34999
34831
  }
35000
- const pending = await this.pendingSums(client, args.creditId);
35001
- const available = balanceMicro - pending.micro;
34832
+ const pending2 = await this.pendingSums(client, args.creditId);
34833
+ const available = balanceMicro - pending2.micro;
35002
34834
  if (args.amountMicro > available) {
35003
34835
  throw new CreditLedgerError(
35004
34836
  "insufficient_credit",
@@ -35010,8 +34842,8 @@ var CreditLedger = class {
35010
34842
  const railValue2 = allocateDrawValue({
35011
34843
  amountMicro: args.amountMicro,
35012
34844
  availableMicro: available,
35013
- availableMsats: Math.max(0, toSafeInt(credit.msats_remaining) - pending.msats),
35014
- availableNative: nativeRemaining === null ? null : Math.max(0, nativeRemaining - pending.native)
34845
+ availableMsats: Math.max(0, toSafeInt(credit.msats_remaining) - pending2.msats),
34846
+ availableNative: nativeRemaining === null ? null : Math.max(0, nativeRemaining - pending2.native)
35015
34847
  });
35016
34848
  const ledgerSeq = toSafeInt(credit.last_ledger_seq) + 1;
35017
34849
  const balanceAfterMicro = available - args.amountMicro;
@@ -35135,8 +34967,8 @@ var CreditLedger = class {
35135
34967
  const headroom = args.capMicro === void 0 ? args.addAmountMicro : Math.max(0, args.capMicro - priorGrown);
35136
34968
  const grantMicro = Math.min(args.addAmountMicro, headroom);
35137
34969
  const balanceMicro = toSafeInt(credit.balance_micro);
35138
- const pending = await this.pendingSums(client, args.creditId);
35139
- const available = balanceMicro - pending.micro;
34970
+ const pending2 = await this.pendingSums(client, args.creditId);
34971
+ const available = balanceMicro - pending2.micro;
35140
34972
  if (grantMicro <= 0) {
35141
34973
  return {
35142
34974
  creditId: args.creditId,
@@ -35171,8 +35003,8 @@ var CreditLedger = class {
35171
35003
  earmark: clipEarmark(args.addRailValue, grantMicro, args.addAmountMicro),
35172
35004
  amountMicro: grantMicro,
35173
35005
  availableMicro: available,
35174
- availableMsats: Math.max(0, toSafeInt(credit.msats_remaining) - pending.msats),
35175
- availableNative: nativeRemaining === null ? null : Math.max(0, nativeRemaining - pending.native)
35006
+ availableMsats: Math.max(0, toSafeInt(credit.msats_remaining) - pending2.msats),
35007
+ availableNative: nativeRemaining === null ? null : Math.max(0, nativeRemaining - pending2.native)
35176
35008
  });
35177
35009
  const amountMicro = toSafeInt(existing.amount_micro) + grantMicro;
35178
35010
  const balanceAfterMicro = available - grantMicro;
@@ -35299,7 +35131,7 @@ var CreditLedger = class {
35299
35131
  "SELECT dvm_id FROM reported_job_terminals WHERE job_id = $1",
35300
35132
  [draw.job_id]
35301
35133
  );
35302
- for (const terminal of terminals.rows) owners.add(terminal.dvm_id);
35134
+ for (const terminal2 of terminals.rows) owners.add(terminal2.dvm_id);
35303
35135
  }
35304
35136
  if (owners.size !== 1 || !owners.has(args.outbox.dvmId)) {
35305
35137
  throw new CreditLedgerError("draw_not_found", "No draw with proven ownership matches this DVM.");
@@ -36091,7 +35923,7 @@ var CreditLedger = class {
36091
35923
  * distinct from earned zero, so settlement cannot guess a claim limit.
36092
35924
  */
36093
35925
  async earnedNativeForX402Channel(channelId) {
36094
- const { rows: rows2 } = await this.pool.query(
35926
+ const { rows: rows2 } = await poolForX402ShutdownClaim(this.pool).query(
36095
35927
  `SELECT COALESCE(
36096
35928
  (SELECT SUM(d.draw_native)
36097
35929
  FROM credit_draws d
@@ -36338,9 +36170,9 @@ var CreditLedger = class {
36338
36170
  throw x402SettlementPending(args.creditId, blocking);
36339
36171
  }
36340
36172
  const balanceMicro = toSafeInt(credit.balance_micro);
36341
- const pending = await this.pendingSums(client, args.creditId);
36342
- const availableMicro = balanceMicro - pending.micro;
36343
- if (args.requireNoPending && pending.micro > 0) {
36173
+ const pending2 = await this.pendingSums(client, args.creditId);
36174
+ const availableMicro = balanceMicro - pending2.micro;
36175
+ if (args.requireNoPending && pending2.micro > 0) {
36344
36176
  throw new CreditLedgerError(
36345
36177
  "drain_conflict",
36346
36178
  `credit ${args.creditId} has pending draws that must finish before it can drain`,
@@ -36364,8 +36196,8 @@ var CreditLedger = class {
36364
36196
  }
36365
36197
  const ledgerSeq = toSafeInt(credit.last_ledger_seq) + 1;
36366
36198
  const balanceAfter = balanceMicro - availableMicro;
36367
- const drainedMsats = Math.max(0, toSafeInt(credit.msats_remaining) - pending.msats);
36368
- const drainedNative = credit.native_remaining === null ? null : Math.max(0, toSafeInt(credit.native_remaining) - pending.native);
36199
+ const drainedMsats = Math.max(0, toSafeInt(credit.msats_remaining) - pending2.msats);
36200
+ const drainedNative = credit.native_remaining === null ? null : Math.max(0, toSafeInt(credit.native_remaining) - pending2.native);
36369
36201
  await client.query(
36370
36202
  `UPDATE credits
36371
36203
  SET balance_micro = $2,
@@ -36374,7 +36206,7 @@ var CreditLedger = class {
36374
36206
  native_remaining = CASE WHEN native_remaining IS NULL THEN NULL
36375
36207
  ELSE LEAST(native_remaining, $5) END
36376
36208
  WHERE credit_id = $1`,
36377
- [args.creditId, balanceAfter, ledgerSeq, pending.msats, pending.native]
36209
+ [args.creditId, balanceAfter, ledgerSeq, pending2.msats, pending2.native]
36378
36210
  );
36379
36211
  const { rows: rows2 } = await client.query(
36380
36212
  `INSERT INTO credit_drains
@@ -37375,15 +37207,15 @@ var CreditLedger = class {
37375
37207
  async snapshotFromRow(row, q2, nowMs) {
37376
37208
  const balanceMicro = toSafeInt(row.balance_micro);
37377
37209
  const expiryMs = toSafeInt(row.expiry_ms);
37378
- const pending = await this.pendingSums(q2, row.credit_id);
37210
+ const pending2 = await this.pendingSums(q2, row.credit_id);
37379
37211
  const live = row.status === "active";
37380
37212
  return {
37381
37213
  creditId: row.credit_id,
37382
37214
  callerPubkey: row.caller_pubkey,
37383
37215
  currency: row.currency,
37384
37216
  balanceMicro,
37385
- availableMicro: live ? balanceMicro - pending.micro : 0,
37386
- nativeAvailable: row.native_remaining === null ? null : live ? Math.max(0, toSafeInt(row.native_remaining) - pending.native) : 0,
37217
+ availableMicro: live ? balanceMicro - pending2.micro : 0,
37218
+ nativeAvailable: row.native_remaining === null ? null : live ? Math.max(0, toSafeInt(row.native_remaining) - pending2.native) : 0,
37387
37219
  expiryMs,
37388
37220
  expired: expiryMs <= nowMs,
37389
37221
  status: creditStatusOf(row.status),
@@ -37777,7 +37609,7 @@ function expiryReleaseReport(dvmId, row) {
37777
37609
  };
37778
37610
  }
37779
37611
 
37780
- // node_modules/@dvmkit/sdk/dist/chunk-JMR4C55F.js
37612
+ // node_modules/@dvmkit/sdk/dist/chunk-NESUY5TM.js
37781
37613
  import { randomUUID as randomUUID4 } from "crypto";
37782
37614
  var MemoryCreditLedger = class _MemoryCreditLedger {
37783
37615
  /**
@@ -38366,8 +38198,8 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
38366
38198
  balanceMicro: credit.balanceMicro
38367
38199
  });
38368
38200
  }
38369
- const pending = pendingSums(credit);
38370
- const available = credit.balanceMicro - pending.micro;
38201
+ const pending2 = pendingSums(credit);
38202
+ const available = credit.balanceMicro - pending2.micro;
38371
38203
  if (args.amountMicro > available) {
38372
38204
  throw new CreditLedgerError(
38373
38205
  "insufficient_credit",
@@ -38382,8 +38214,8 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
38382
38214
  const alloc = allocateDrawValue({
38383
38215
  amountMicro: args.amountMicro,
38384
38216
  availableMicro: available,
38385
- availableMsats: Math.max(0, credit.msatsRemaining - pending.msats),
38386
- availableNative: credit.nativeRemaining === null ? null : Math.max(0, credit.nativeRemaining - pending.native)
38217
+ availableMsats: Math.max(0, credit.msatsRemaining - pending2.msats),
38218
+ availableNative: credit.nativeRemaining === null ? null : Math.max(0, credit.nativeRemaining - pending2.native)
38387
38219
  });
38388
38220
  const ledgerSeq = credit.lastLedgerSeq + 1;
38389
38221
  credit.lastLedgerSeq = ledgerSeq;
@@ -38439,8 +38271,8 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
38439
38271
  if (x402Refund) throw x402SettlementPending(args.creditId, x402Refund);
38440
38272
  if (credit.tempoChannelId) throw new CreditLedgerError("tempo_channel_closing", "Tempo balance growth requires a durable channel lifecycle");
38441
38273
  }
38442
- const pending = pendingSums(credit);
38443
- const available = credit.balanceMicro - pending.micro;
38274
+ const pending2 = pendingSums(credit);
38275
+ const available = credit.balanceMicro - pending2.micro;
38444
38276
  const headroom = args.capMicro === void 0 ? args.addAmountMicro : Math.max(0, args.capMicro - draw.grownMicro);
38445
38277
  const grantMicro = Math.min(args.addAmountMicro, headroom);
38446
38278
  if (grantMicro <= 0) {
@@ -38467,8 +38299,8 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
38467
38299
  earmark: clipEarmark(args.addRailValue, grantMicro, args.addAmountMicro),
38468
38300
  amountMicro: grantMicro,
38469
38301
  availableMicro: available,
38470
- availableMsats: Math.max(0, credit.msatsRemaining - pending.msats),
38471
- availableNative: credit.nativeRemaining === null ? null : Math.max(0, credit.nativeRemaining - pending.native)
38302
+ availableMsats: Math.max(0, credit.msatsRemaining - pending2.msats),
38303
+ availableNative: credit.nativeRemaining === null ? null : Math.max(0, credit.nativeRemaining - pending2.native)
38472
38304
  });
38473
38305
  draw.amountMicro += grantMicro;
38474
38306
  draw.grownMicro += grantMicro;
@@ -38679,9 +38511,9 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
38679
38511
  if (blocking) throw cardRefundPendingConflict(args.creditId, blocking.drainId);
38680
38512
  }
38681
38513
  if (x402Refund) throw x402SettlementPending(args.creditId, x402Refund);
38682
- const pending = pendingSums(credit);
38683
- const availableMicro = credit.balanceMicro - pending.micro;
38684
- if (args.requireNoPending && pending.micro > 0) {
38514
+ const pending2 = pendingSums(credit);
38515
+ const availableMicro = credit.balanceMicro - pending2.micro;
38516
+ if (args.requireNoPending && pending2.micro > 0) {
38685
38517
  throw new CreditLedgerError(
38686
38518
  "drain_conflict",
38687
38519
  `credit ${args.creditId} has pending draws that must finish before it can drain`,
@@ -38707,13 +38539,13 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
38707
38539
  );
38708
38540
  }
38709
38541
  const ledgerSeq = credit.lastLedgerSeq + 1;
38710
- const drainedMsats = Math.max(0, credit.msatsRemaining - pending.msats);
38711
- const drainedNative = credit.nativeRemaining === null ? null : Math.max(0, credit.nativeRemaining - pending.native);
38542
+ const drainedMsats = Math.max(0, credit.msatsRemaining - pending2.msats);
38543
+ const drainedNative = credit.nativeRemaining === null ? null : Math.max(0, credit.nativeRemaining - pending2.native);
38712
38544
  credit.lastLedgerSeq = ledgerSeq;
38713
38545
  credit.balanceMicro -= availableMicro;
38714
- credit.msatsRemaining = Math.min(credit.msatsRemaining, pending.msats);
38546
+ credit.msatsRemaining = Math.min(credit.msatsRemaining, pending2.msats);
38715
38547
  if (credit.nativeRemaining !== null) {
38716
- credit.nativeRemaining = Math.min(credit.nativeRemaining, pending.native);
38548
+ credit.nativeRemaining = Math.min(credit.nativeRemaining, pending2.native);
38717
38549
  }
38718
38550
  const drain = {
38719
38551
  drainId: args.drainId,
@@ -39105,15 +38937,15 @@ var MemoryCreditLedger = class _MemoryCreditLedger {
39105
38937
  return credit;
39106
38938
  }
39107
38939
  snapshot(credit, nowMs) {
39108
- const pending = pendingSums(credit);
38940
+ const pending2 = pendingSums(credit);
39109
38941
  const live = credit.status === "active";
39110
38942
  return {
39111
38943
  creditId: credit.creditId,
39112
38944
  callerPubkey: credit.callerPubkey,
39113
38945
  currency: credit.currency,
39114
38946
  balanceMicro: credit.balanceMicro,
39115
- availableMicro: live ? credit.balanceMicro - pending.micro : 0,
39116
- nativeAvailable: credit.nativeRemaining === null ? null : live ? Math.max(0, credit.nativeRemaining - pending.native) : 0,
38947
+ availableMicro: live ? credit.balanceMicro - pending2.micro : 0,
38948
+ nativeAvailable: credit.nativeRemaining === null ? null : live ? Math.max(0, credit.nativeRemaining - pending2.native) : 0,
39117
38949
  expiryMs: credit.expiryMs,
39118
38950
  expired: credit.expiryMs <= nowMs,
39119
38951
  status: credit.status,
@@ -39805,14 +39637,25 @@ async function waitBeforeRetry(delayMs, started, maxWaitMs, open2) {
39805
39637
  await new Promise((resolve) => setTimeout(resolve, delayMs));
39806
39638
  }
39807
39639
 
39808
- // node_modules/@dvmkit/sdk/dist/chunk-ADPAHY5W.js
39640
+ // node_modules/@dvmkit/sdk/dist/chunk-XBT2F4F4.js
39809
39641
  import { createHash as createHash6 } from "crypto";
39810
39642
  var DEFAULT_BACKOFF_MS = [1e3, 4e3, 15e3, 3e4];
39643
+ var DEFAULT_HEARTBEAT_MS = 5 * 6e4;
39811
39644
  var ListenChannel = class {
39812
39645
  constructor(pool, opts) {
39813
39646
  this.pool = pool;
39814
39647
  this.opts = opts;
39815
39648
  this.backoffMs = opts.backoffMs ?? DEFAULT_BACKOFF_MS;
39649
+ const heartbeat = opts.heartbeat;
39650
+ if (!heartbeat) {
39651
+ this.heartbeatMs = null;
39652
+ } else {
39653
+ const intervalMs = heartbeat === true ? void 0 : heartbeat.intervalMs;
39654
+ this.heartbeatMs = intervalMs ?? DEFAULT_HEARTBEAT_MS;
39655
+ if (!Number.isFinite(this.heartbeatMs) || this.heartbeatMs <= 0) {
39656
+ throw new RangeError("ListenChannel heartbeat intervalMs must be a positive number");
39657
+ }
39658
+ }
39816
39659
  }
39817
39660
  pool;
39818
39661
  opts;
@@ -39820,7 +39663,10 @@ var ListenChannel = class {
39820
39663
  stopped = false;
39821
39664
  reconnectTimer = null;
39822
39665
  reconnectAttempt = 0;
39666
+ disconnectedAt = null;
39667
+ heartbeatTimer = null;
39823
39668
  backoffMs;
39669
+ heartbeatMs;
39824
39670
  /**
39825
39671
  * Open the LISTEN connection. Resolves once the initial connect attempt
39826
39672
  * has either succeeded or scheduled a retry — never rejects, so callers
@@ -39833,10 +39679,13 @@ var ListenChannel = class {
39833
39679
  /** Release the LISTEN client and cancel any pending reconnect. */
39834
39680
  async stop() {
39835
39681
  this.stopped = true;
39682
+ this.disconnectedAt = null;
39683
+ this.reconnectAttempt = 0;
39836
39684
  if (this.reconnectTimer) {
39837
39685
  clearTimeout(this.reconnectTimer);
39838
39686
  this.reconnectTimer = null;
39839
39687
  }
39688
+ this.clearHeartbeat();
39840
39689
  const client = this.client;
39841
39690
  this.client = null;
39842
39691
  if (client) {
@@ -39864,7 +39713,10 @@ var ListenChannel = class {
39864
39713
  const onLost = (err) => {
39865
39714
  if (lost || this.stopped) return;
39866
39715
  lost = true;
39867
- if (this.client === client) this.client = null;
39716
+ if (this.client === client) {
39717
+ this.clearHeartbeat();
39718
+ this.client = null;
39719
+ }
39868
39720
  this.opts.onLost?.(err);
39869
39721
  try {
39870
39722
  client.release(err ?? new Error("listen connection lost"));
@@ -39910,17 +39762,53 @@ var ListenChannel = class {
39910
39762
  if (notification.channel !== this.opts.channel) return;
39911
39763
  this.opts.onNotification(notification.payload);
39912
39764
  });
39765
+ this.scheduleHeartbeat(client, onLost);
39766
+ if (this.disconnectedAt !== null) {
39767
+ const downtimeMs = Math.max(0, Date.now() - this.disconnectedAt);
39768
+ this.disconnectedAt = null;
39769
+ this.opts.onRestored?.(downtimeMs);
39770
+ }
39771
+ }
39772
+ clearHeartbeat() {
39773
+ if (this.heartbeatTimer) {
39774
+ clearTimeout(this.heartbeatTimer);
39775
+ this.heartbeatTimer = null;
39776
+ }
39777
+ }
39778
+ /**
39779
+ * Queue the next heartbeat for `client`. The following beat is scheduled
39780
+ * only after this one's query settles, so beats never overlap. Each step
39781
+ * re-checks that `client` is still the live connection: a result arriving
39782
+ * late from a replaced or stopped client must not tear down its successor
39783
+ * or revive a stopped listener.
39784
+ */
39785
+ scheduleHeartbeat(client, onLost) {
39786
+ if (this.heartbeatMs === null) return;
39787
+ const live = () => !this.stopped && this.client === client;
39788
+ this.heartbeatTimer = setTimeout(() => {
39789
+ this.heartbeatTimer = null;
39790
+ if (!live()) return;
39791
+ client.query("SELECT 1").then(
39792
+ () => {
39793
+ if (live()) this.scheduleHeartbeat(client, onLost);
39794
+ },
39795
+ (err) => {
39796
+ if (live()) onLost(err instanceof Error ? err : new Error(String(err)));
39797
+ }
39798
+ );
39799
+ }, this.heartbeatMs);
39913
39800
  }
39914
39801
  scheduleReconnect() {
39915
39802
  if (this.stopped) return;
39803
+ this.disconnectedAt ??= Date.now();
39916
39804
  if (this.reconnectTimer) return;
39917
39805
  const idx = Math.min(this.reconnectAttempt, this.backoffMs.length - 1);
39918
- const delay2 = this.backoffMs[idx];
39806
+ const delay3 = this.backoffMs[idx];
39919
39807
  this.reconnectAttempt++;
39920
39808
  this.reconnectTimer = setTimeout(() => {
39921
39809
  this.reconnectTimer = null;
39922
39810
  void this.connect();
39923
- }, delay2);
39811
+ }, delay3);
39924
39812
  }
39925
39813
  };
39926
39814
  var JOB_MESSAGES_CHANNEL = "job_messages";
@@ -41373,6 +41261,9 @@ var PostgresJobStore = class {
41373
41261
  });
41374
41262
  }
41375
41263
  async getMessages(jobId, afterSeq, options) {
41264
+ if (options?.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1)) {
41265
+ throw new RangeError("Message limit must be a positive safe integer");
41266
+ }
41376
41267
  const { rows: rows2 } = await this.pool.query(
41377
41268
  `WITH terminal AS (
41378
41269
  SELECT messages FROM jobs WHERE id = $1 AND status IN ('completed', 'failed', 'cancelled')
@@ -41388,33 +41279,39 @@ var PostgresJobStore = class {
41388
41279
  SELECT (message->>'seq')::bigint, message, 1 AS origin
41389
41280
  FROM terminal CROSS JOIN LATERAL jsonb_array_elements(terminal.messages) AS snapshot(message)
41390
41281
  WHERE (message->>'seq')::bigint > $2
41391
- ) SELECT DISTINCT ON (seq) data FROM history ORDER BY seq, origin`,
41392
- [jobId, afterSeq, options?.includeHeld ?? false]
41282
+ ) SELECT DISTINCT ON (seq) data FROM history ORDER BY seq, origin LIMIT $4`,
41283
+ [jobId, afterSeq, options?.includeHeld ?? false, options?.limit ?? null]
41393
41284
  );
41394
41285
  return rows2.map((r) => typeof r.data === "string" ? JSON.parse(r.data) : r.data);
41395
41286
  }
41396
41287
  async initStreaming() {
41397
41288
  this.listenChannel = new ListenChannel(this.pool, {
41398
41289
  channel: JOB_MESSAGES_CHANNEL,
41290
+ heartbeat: true,
41399
41291
  onNotification: (payload) => {
41400
41292
  this.dispatch(payload);
41401
41293
  },
41402
- onLost: (_err) => {
41294
+ onLost: (err) => {
41403
41295
  diagnosticConsole.warn(
41404
41296
  {
41405
41297
  level: "job_messages_listen_lost",
41406
- error: void 0
41298
+ error_code: postgresErrorCode(err)
41407
41299
  }
41408
41300
  );
41409
41301
  },
41410
- onReconnectFailed: (attempt, _err) => {
41302
+ onReconnectFailed: (attempt, err) => {
41411
41303
  diagnosticConsole.warn(
41412
41304
  {
41413
41305
  level: "job_messages_listen_connect_failed",
41414
41306
  attempt,
41415
- error: void 0
41307
+ error_code: postgresErrorCode(err)
41416
41308
  }
41417
41309
  );
41310
+ },
41311
+ onRestored: (downtimeMs) => {
41312
+ diagnosticConsole.info({ event: "job_messages_listen_restored", elapsed_ms: downtimeMs });
41313
+ const jobIds = /* @__PURE__ */ new Set([...this.messageSubscribers.keys(), ...this.notifySubscribers.keys()]);
41314
+ for (const jobId of jobIds) this.dispatch(jobId);
41418
41315
  }
41419
41316
  });
41420
41317
  await this.listenChannel.start();
@@ -43311,9 +43208,9 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
43311
43208
  let i3 = 0;
43312
43209
  while (i3 < fullpath.length) {
43313
43210
  const el = fullpath[i3];
43314
- const terminal = i3 === fullpath.length - 1;
43211
+ const terminal2 = i3 === fullpath.length - 1;
43315
43212
  if (el === "_errors") {
43316
- if (terminal)
43213
+ if (terminal2)
43317
43214
  curr._errors.push(mapper(issue2));
43318
43215
  i3++;
43319
43216
  continue;
@@ -43327,7 +43224,7 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
43327
43224
  });
43328
43225
  }
43329
43226
  const node2 = curr[el];
43330
- if (terminal) {
43227
+ if (terminal2) {
43331
43228
  node2._errors.push(mapper(issue2));
43332
43229
  }
43333
43230
  curr = node2;
@@ -43361,7 +43258,7 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
43361
43258
  let i3 = 0;
43362
43259
  while (i3 < fullpath.length) {
43363
43260
  const el = fullpath[i3];
43364
- const terminal = i3 === fullpath.length - 1;
43261
+ const terminal2 = i3 === fullpath.length - 1;
43365
43262
  if (typeof el === "string") {
43366
43263
  curr.properties ?? (curr.properties = {});
43367
43264
  if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {
@@ -43378,7 +43275,7 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
43378
43275
  (_a4 = curr.items)[el] ?? (_a4[el] = { errors: [] });
43379
43276
  curr = curr.items[el];
43380
43277
  }
43381
- if (terminal) {
43278
+ if (terminal2) {
43382
43279
  curr.errors.push(mapper(issue2));
43383
43280
  }
43384
43281
  i3++;
@@ -58361,13 +58258,13 @@ var recordProcessor = (schema, ctx, _json, params) => {
58361
58258
  ...params,
58362
58259
  path: [...params.path, "propertyNames"]
58363
58260
  });
58364
- let pending = pendingRecords.get(ctx);
58365
- if (!pending) {
58366
- pending = [];
58367
- pendingRecords.set(ctx, pending);
58261
+ let pending2 = pendingRecords.get(ctx);
58262
+ if (!pending2) {
58263
+ pending2 = [];
58264
+ pendingRecords.set(ctx, pending2);
58368
58265
  ctx.deferred.push(() => rewriteKeyNames(ctx));
58369
58266
  }
58370
- pending.push(schema);
58267
+ pending2.push(schema);
58371
58268
  }
58372
58269
  json2.additionalProperties = processSchema(def.valueType, ctx, {
58373
58270
  ...params,
@@ -61385,7 +61282,7 @@ function date4(params) {
61385
61282
  return _coercedDate(ZodDate, params);
61386
61283
  }
61387
61284
 
61388
- // node_modules/@dvmkit/sdk/dist/chunk-M76A6UGG.js
61285
+ // node_modules/@dvmkit/sdk/dist/chunk-X2YIIJFB.js
61389
61286
  function humanizeZodError(err, opts) {
61390
61287
  return humanizeZodIssues(err.issues, opts);
61391
61288
  }
@@ -61743,8 +61640,8 @@ function shortestCashuLockWindowSeconds(cashu, servesUnsigned) {
61743
61640
  return servesUnsigned ? Math.min(signed, unsignedCashuLockWindowSeconds(cashu)) : signed;
61744
61641
  }
61745
61642
 
61746
- // node_modules/@dvmkit/sdk/dist/chunk-GSENU5XC.js
61747
- import { AsyncLocalStorage as AsyncLocalStorage6 } from "async_hooks";
61643
+ // node_modules/@dvmkit/sdk/dist/chunk-ZOTXYYRJ.js
61644
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
61748
61645
  var MemoryJobStore = class {
61749
61646
  contentHolds = /* @__PURE__ */ new Map();
61750
61647
  paymentIntents = /* @__PURE__ */ new Map();
@@ -62183,8 +62080,11 @@ var MemoryJobStore = class {
62183
62080
  if (subSet.size === 0) this.notifySubscribers.delete(jobId);
62184
62081
  });
62185
62082
  }
62186
- getMessages(jobId, afterSeq, options) {
62187
- return Promise.resolve(this.visibleMessages(jobId, afterSeq, options?.includeHeld));
62083
+ async getMessages(jobId, afterSeq, options) {
62084
+ if (options?.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1)) {
62085
+ throw new RangeError("Message limit must be a positive safe integer");
62086
+ }
62087
+ return this.visibleMessages(jobId, afterSeq, options?.includeHeld, options?.limit);
62188
62088
  }
62189
62089
  initStreaming() {
62190
62090
  return Promise.resolve();
@@ -62251,8 +62151,8 @@ var MemoryJobStore = class {
62251
62151
  * verified keeps its row, so its outcome can still be recorded.
62252
62152
  */
62253
62153
  deleteResolvedMessages(jobId) {
62254
- const pending = this.messagesFor(jobId).filter((entry) => entry.status === "pending-verification" && entry.message.type === "payment");
62255
- if (pending.length) this.messages.set(jobId, pending);
62154
+ const pending2 = this.messagesFor(jobId).filter((entry) => entry.status === "pending-verification" && entry.message.type === "payment");
62155
+ if (pending2.length) this.messages.set(jobId, pending2);
62256
62156
  else this.messages.delete(jobId);
62257
62157
  }
62258
62158
  resolveIntent(jobId, seq) {
@@ -62272,13 +62172,13 @@ var MemoryJobStore = class {
62272
62172
  }
62273
62173
  return list;
62274
62174
  }
62275
- visibleMessages(jobId, afterSeq, includeHeld = false) {
62175
+ visibleMessages(jobId, afterSeq, includeHeld = false, limit) {
62276
62176
  const stored = this.messagesFor(jobId);
62277
62177
  const record2 = this.data.get(jobId);
62278
- const terminal = record2 && isTerminal(record2.status);
62178
+ const terminal2 = record2 && isTerminal(record2.status);
62279
62179
  const terminalMessage = stored.some((entry) => entry.status === "verified" && entry.message.from === "provider" && (entry.message.type === "complete" || entry.message.type === "cancel"));
62280
62180
  let boundary = Infinity;
62281
- if (!includeHeld && !terminal && !terminalMessage) {
62181
+ if (!includeHeld && !terminal2 && !terminalMessage) {
62282
62182
  for (const entry of stored) {
62283
62183
  if (entry.status === "pending-verification" && entry.message.type === "payment") {
62284
62184
  boundary = Math.min(boundary, entry.message.seq);
@@ -62286,12 +62186,20 @@ var MemoryJobStore = class {
62286
62186
  }
62287
62187
  }
62288
62188
  const messages = /* @__PURE__ */ new Map();
62289
- if (terminal) {
62290
- for (const message of record2.messages) if (message.seq > afterSeq) messages.set(message.seq, message);
62189
+ const retain = (message) => {
62190
+ messages.set(message.seq, message);
62191
+ if (limit !== void 0 && messages.size > limit) {
62192
+ let lastSeq = -Infinity;
62193
+ for (const seq of messages.keys()) lastSeq = Math.max(lastSeq, seq);
62194
+ messages.delete(lastSeq);
62195
+ }
62196
+ };
62197
+ if (terminal2) {
62198
+ for (const message of record2.messages) if (message.seq > afterSeq) retain(message);
62291
62199
  }
62292
62200
  for (const entry of stored) {
62293
62201
  if (entry.status === "verified" && entry.message.seq > afterSeq && entry.message.seq < boundary) {
62294
- messages.set(entry.message.seq, entry.message);
62202
+ retain(entry.message);
62295
62203
  }
62296
62204
  }
62297
62205
  return [...messages.values()].sort((a, b2) => a.seq - b2.seq);
@@ -62371,7 +62279,7 @@ function mergeSignals(a, b2) {
62371
62279
  if (!b2) return a;
62372
62280
  return AbortSignal.any([a, b2]);
62373
62281
  }
62374
- var stepCostScope = new AsyncLocalStorage6();
62282
+ var stepCostScope = new AsyncLocalStorage5();
62375
62283
  function createStepRunner(cache, declareCost, onStep) {
62376
62284
  const owner = {};
62377
62285
  const writes = /* @__PURE__ */ new Map();
@@ -62411,7 +62319,7 @@ function createStepRunner(cache, declareCost, onStep) {
62411
62319
  };
62412
62320
  }
62413
62321
 
62414
- // node_modules/@dvmkit/sdk/dist/chunk-HUPNS7JD.js
62322
+ // node_modules/@dvmkit/sdk/dist/chunk-TIKAMYMQ.js
62415
62323
  import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
62416
62324
  var TEMPO_SETTLEMENT_BALANCE_INTERVAL_MS = 5 * 60 * 1e3;
62417
62325
  function isTempoInsufficientFundsError(error62) {
@@ -62817,10 +62725,10 @@ function attachTempoSessionRuntime(mppx, config2, chainOpOverrides = {}) {
62817
62725
  const key = channel.channelId.toLowerCase();
62818
62726
  const intent = await store.getClose?.(key);
62819
62727
  if (isTempoCloseTransaction(intent?.reference)) return false;
62820
- const pending = await obligations.findPendingTempo(key, "close");
62821
- if (pending?.state !== "unmatched" || isTempoCloseTransaction(pending.tx_hash) || pending.rail !== "tempo" || pending.operation !== "close" || pending.channel_id.toLowerCase() !== key || pending.network !== `eip155:${channel.chainId}` || pending.contract.toLowerCase() !== channel.escrowContract.toLowerCase() || typeof pending.original.drainId !== "string" || !pending.original.drainId) return false;
62822
- if (intent && intent.drainId !== pending.original.drainId) return false;
62823
- return !isTempoCloseTransaction(await obligations.tempoCloseTransaction(key, pending.original.drainId));
62728
+ const pending2 = await obligations.findPendingTempo(key, "close");
62729
+ if (pending2?.state !== "unmatched" || isTempoCloseTransaction(pending2.tx_hash) || pending2.rail !== "tempo" || pending2.operation !== "close" || pending2.channel_id.toLowerCase() !== key || pending2.network !== `eip155:${channel.chainId}` || pending2.contract.toLowerCase() !== channel.escrowContract.toLowerCase() || typeof pending2.original.drainId !== "string" || !pending2.original.drainId) return false;
62730
+ if (intent && intent.drainId !== pending2.original.drainId) return false;
62731
+ return !isTempoCloseTransaction(await obligations.tempoCloseTransaction(key, pending2.original.drainId));
62824
62732
  };
62825
62733
  const terminalizeLostBacking = async (channel, chainState, proof) => {
62826
62734
  if (chainState.deposit !== 0n || !creditLedger) return;
@@ -62866,7 +62774,7 @@ function attachTempoSessionRuntime(mppx, config2, chainOpOverrides = {}) {
62866
62774
  });
62867
62775
  }
62868
62776
  }
62869
- const pending = !resolved && headroom > 0n;
62777
+ const pending2 = !resolved && headroom > 0n;
62870
62778
  let drainProof;
62871
62779
  try {
62872
62780
  if (resolved) drainProof = await resolveChannelDrainProof(channel, chainState, resolved);
@@ -62874,7 +62782,7 @@ function attachTempoSessionRuntime(mppx, config2, chainOpOverrides = {}) {
62874
62782
  await protectFinalizedBacking(channel, chainState, drainProof);
62875
62783
  }
62876
62784
  if (drainProof) await retainRefundEvidence(drainProof.drain, drainProof.refundedNative, drainProof.payerExit);
62877
- if (pending) return;
62785
+ if (pending2) return;
62878
62786
  const refundedNative = resolved?.outcome === "ours" ? resolved.receipt.refundedToPayer : 0n;
62879
62787
  const retire = async (lifecycle, tx) => {
62880
62788
  const settledOnChainNative = maxBigInt(
@@ -63291,12 +63199,12 @@ function attachTempoSessionRuntime(mppx, config2, chainOpOverrides = {}) {
63291
63199
  }
63292
63200
  if (!finalized2) return null;
63293
63201
  if (current.finalized) await terminalizeLostBacking(current, { deposit: 0n, settled: current.settledOnChain });
63294
- const pending = await config2.hostedObligations?.pendingTempoClose(channelId, drainId);
63202
+ const pending2 = await config2.hostedObligations?.pendingTempoClose(channelId, drainId);
63295
63203
  const selfHostedReport = !config2.hostedObligations && !!config2.onSessionSettlement && !!store.claimCloseReference && !!store.getCloseRecovery;
63296
- let reference = pending?.txHash ?? void 0;
63297
- if (pending && pending.state !== "unmatched" && !reference || selfHostedReport) {
63204
+ let reference = pending2?.txHash ?? void 0;
63205
+ if (pending2 && pending2.state !== "unmatched" && !reference || selfHostedReport) {
63298
63206
  const recovery = await store.getCloseRecovery?.(channelId);
63299
- const notBeforeMs = pending?.reservedAtMs ?? recovery?.updatedAtMs;
63207
+ const notBeforeMs = pending2?.reservedAtMs ?? recovery?.updatedAtMs;
63300
63208
  if (notBeforeMs === void 0) throw new Error(`Tempo session close intent ${channelId} not found`);
63301
63209
  const obligations = config2.hostedObligations;
63302
63210
  const found = await findFinalizedClose(
@@ -63304,18 +63212,18 @@ function attachTempoSessionRuntime(mppx, config2, chainOpOverrides = {}) {
63304
63212
  stored,
63305
63213
  drainId,
63306
63214
  notBeforeMs,
63307
- pending ? {
63308
- from: pending.searchBefore,
63309
- obligationId: pending.id,
63310
- save: (resumeAt) => obligations.recordTempoCloseSearch(pending.id, resumeAt)
63215
+ pending2 ? {
63216
+ from: pending2.searchBefore,
63217
+ obligationId: pending2.id,
63218
+ save: (resumeAt) => obligations.recordTempoCloseSearch(pending2.id, resumeAt)
63311
63219
  } : {
63312
63220
  from: recovery?.searchBefore ?? null,
63313
63221
  save: (resumeAt) => store.recordCloseSearch?.(channelId, drainId, resumeAt)
63314
63222
  },
63315
63223
  TEMPO_CLOSE_POLL_SEARCH_BUDGET_MS
63316
63224
  );
63317
- if (pending) {
63318
- reference = await settleUnsubmittedClose(current.channelId, drainId, pending.id, found);
63225
+ if (pending2) {
63226
+ reference = await settleUnsubmittedClose(current.channelId, drainId, pending2.id, found);
63319
63227
  } else if (found.outcome === "ours") {
63320
63228
  const client = await getClient({ chainId: current.chainId });
63321
63229
  const { settledToPayee } = await chainOps.readChannelClose(client, current.channelId, found.txHash);
@@ -63478,32 +63386,32 @@ function attachTempoSessionRuntime(mppx, config2, chainOpOverrides = {}) {
63478
63386
  if (!current) throw new Error("Channel history is unavailable");
63479
63387
  const client = await getClient({ chainId: current.chainId });
63480
63388
  const recovery = await store.getCloseRecovery?.(drain.channelId);
63481
- const pending = await config2.hostedObligations?.pendingTempoClose(drain.channelId, drain.drainId);
63389
+ const pending2 = await config2.hostedObligations?.pendingTempoClose(drain.channelId, drain.drainId);
63482
63390
  const intent = await store.getClose?.(drain.channelId);
63483
63391
  const recorded = intent?.drainId === drain.drainId && isTempoCloseTransaction(intent.reference) ? intent.reference : await config2.hostedObligations?.tempoCloseTransaction(drain.channelId, drain.drainId);
63484
- const txHash = recorded ?? pending?.txHash;
63392
+ const txHash = recorded ?? pending2?.txHash;
63485
63393
  let receipt = isTempoCloseTransaction(txHash) ? await chainOps.readChannelClose(client, current.channelId, txHash) : void 0;
63486
63394
  const chainState = receipt ? { deposit: 0n, settled: receipt.settledToPayee, closeRequestedAt: 0 } : (await chainOps.getChannelStatesBatch(client, [current.channelId], current.escrowContract))[0];
63487
63395
  if (!chainState || chainState.deposit !== 0n) return { outcome: "open" };
63488
63396
  await protectFinalizedBacking(current, chainState, receipt ? { drain, refundedNative: receipt.refundedToPayer } : void 0, receipt !== void 0);
63489
63397
  let found = receipt && isTempoCloseTransaction(txHash) ? { outcome: "ours", txHash } : void 0;
63490
- if (found?.outcome === "ours" && pending) {
63491
- await config2.hostedObligations.recordSubmitted(pending.id, found.txHash);
63398
+ if (found?.outcome === "ours" && pending2) {
63399
+ await config2.hostedObligations.recordSubmitted(pending2.id, found.txHash);
63492
63400
  }
63493
- if (!found && pending && !pending.txHash) {
63494
- if (pending.state === "unmatched") throw new TempoDrainRefundUnprovenError("close_history_unmatched", "Close history requires an operator retry");
63401
+ if (!found && pending2 && !pending2.txHash) {
63402
+ if (pending2.state === "unmatched") throw new TempoDrainRefundUnprovenError("close_history_unmatched", "Close history requires an operator retry");
63495
63403
  if (!recoverPending) return { outcome: "open" };
63496
- found = await findFinalizedClose(current, stored, drain.drainId, pending.reservedAtMs, {
63497
- from: pending.searchBefore,
63498
- obligationId: pending.id,
63499
- save: (resumeAt) => config2.hostedObligations.recordTempoCloseSearch(pending.id, resumeAt)
63404
+ found = await findFinalizedClose(current, stored, drain.drainId, pending2.reservedAtMs, {
63405
+ from: pending2.searchBefore,
63406
+ obligationId: pending2.id,
63407
+ save: (resumeAt) => config2.hostedObligations.recordTempoCloseSearch(pending2.id, resumeAt)
63500
63408
  }, searchBudgetMs);
63501
- await settleUnsubmittedClose(current.channelId, drain.drainId, pending.id, found);
63409
+ await settleUnsubmittedClose(current.channelId, drain.drainId, pending2.id, found);
63502
63410
  if (found.outcome === "none" && found.terminal) {
63503
63411
  throw new TempoDrainRefundUnprovenError("close_history_unmatched", "Close history requires an operator retry");
63504
63412
  }
63505
63413
  }
63506
- found ??= pending?.txHash ? { outcome: "ours", txHash: pending.txHash } : await findFinalizedClose(current, stored, drain.drainId, drain.createdAt, {
63414
+ found ??= pending2?.txHash ? { outcome: "ours", txHash: pending2.txHash } : await findFinalizedClose(current, stored, drain.drainId, drain.createdAt, {
63507
63415
  from: recovery?.searchBefore ?? null,
63508
63416
  save: (resumeAt) => store.recordCloseSearch?.(drain.channelId, drain.drainId, resumeAt)
63509
63417
  }, searchBudgetMs);
@@ -63762,7 +63670,7 @@ function isTempoCloseTransaction(reference) {
63762
63670
  return typeof reference === "string" && /^0x[0-9a-fA-F]{64}$/.test(reference);
63763
63671
  }
63764
63672
 
63765
- // node_modules/@dvmkit/sdk/dist/chunk-XLOH5DKI.js
63673
+ // node_modules/@dvmkit/sdk/dist/chunk-64EXC7TE.js
63766
63674
  import { createHash as createHash8, randomUUID as randomUUID7 } from "crypto";
63767
63675
  import { createHash as createHash23 } from "crypto";
63768
63676
  import { createHash as createHash33 } from "crypto";
@@ -64612,8 +64520,8 @@ function pendingExpiresAt(maxTimeoutSeconds, now) {
64612
64520
  const ttlMs = Math.min(MAX_PENDING_TTL_MS, Math.max(MIN_PENDING_TTL_MS, requestedMs));
64613
64521
  return now + ttlMs;
64614
64522
  }
64615
- function isPendingLive(pending, now) {
64616
- return pending !== void 0 && pending.expiresAt > now;
64523
+ function isPendingLive(pending2, now) {
64524
+ return pending2 !== void 0 && pending2.expiresAt > now;
64617
64525
  }
64618
64526
  function verificationStateUnavailable() {
64619
64527
  return {
@@ -67220,22 +67128,24 @@ var BatchSettlementEvmScheme3 = class {
67220
67128
  }
67221
67129
  };
67222
67130
 
67223
- // node_modules/@dvmkit/sdk/dist/chunk-XLOH5DKI.js
67131
+ // node_modules/@dvmkit/sdk/dist/chunk-64EXC7TE.js
67224
67132
  import { randomUUID as randomUUID22 } from "crypto";
67225
67133
  import { createHash as createHash42 } from "crypto";
67226
67134
  import { createHash as createHash62, randomBytes as randomBytes8, randomUUID as randomUUID32 } from "crypto";
67227
67135
  import { createHash as createHash52 } from "crypto";
67136
+ import { randomUUID as randomUUID42 } from "crypto";
67137
+ import { setTimeout as delay2 } from "timers/promises";
67228
67138
  import { randomBytes as randomBytes22 } from "crypto";
67229
- import { createHash as createHash72 } from "crypto";
67230
- import { createHash as createHash82, randomUUID as randomUUID42 } from "crypto";
67139
+ import { createHash as createHash82 } from "crypto";
67140
+ import { createHash as createHash9, randomUUID as randomUUID52 } from "crypto";
67231
67141
  import { isDeepStrictEqual as isDeepStrictEqual22 } from "util";
67232
- import { createHmac as createHmac2, randomUUID as randomUUID52, timingSafeEqual as timingSafeEqual2 } from "crypto";
67233
- import { createHash as createHash9 } from "crypto";
67142
+ import { createHmac as createHmac2, randomUUID as randomUUID62, timingSafeEqual as timingSafeEqual2 } from "crypto";
67143
+ import { createHash as createHash10 } from "crypto";
67234
67144
  import { randomBytes as randomBytes42 } from "crypto";
67235
67145
  import { randomBytes as randomBytes32 } from "crypto";
67236
- import { createHash as createHash10 } from "crypto";
67237
67146
  import { createHash as createHash11 } from "crypto";
67238
- import { createHash as createHash13, randomBytes as randomBytes52, randomUUID as randomUUID62 } from "crypto";
67147
+ import { createHash as createHash12 } from "crypto";
67148
+ import { createHash as createHash14, randomBytes as randomBytes52, randomUUID as randomUUID8 } from "crypto";
67239
67149
 
67240
67150
  // node_modules/hono/dist/request/constants.js
67241
67151
  var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
@@ -69286,8 +69196,9 @@ var streamSSE = (c, cb, onError) => {
69286
69196
  return c.newResponse(stream2.responseReadable);
69287
69197
  };
69288
69198
 
69289
- // node_modules/@dvmkit/sdk/dist/chunk-XLOH5DKI.js
69290
- import { createHash as createHash12 } from "crypto";
69199
+ // node_modules/@dvmkit/sdk/dist/chunk-64EXC7TE.js
69200
+ import { randomUUID as randomUUID72 } from "crypto";
69201
+ import { createHash as createHash13 } from "crypto";
69291
69202
  async function initLockPubkeyTable(db) {
69292
69203
  await withSdkInitLock(db, () => createLockPubkeyTable(db));
69293
69204
  }
@@ -69991,6 +69902,7 @@ async function buildCreditMenu(args) {
69991
69902
  ...funding.includes("stripe") && args.stripeNetworkId !== void 0 && {
69992
69903
  stripe: {
69993
69904
  network_id: args.stripeNetworkId,
69905
+ ...args.stripeCheckout && { checkout: true },
69994
69906
  min_micro: Math.min(
69995
69907
  Math.max(
69996
69908
  args.stripeMinMicro ?? STRIPE_CREDIT_DEFAULT_MIN_MICRO,
@@ -70122,6 +70034,112 @@ function warnOnce(event, message) {
70122
70034
  warned.add(event);
70123
70035
  diagnosticConsole.warn({ level: "warn", event, message });
70124
70036
  }
70037
+ var STALE_RATE_COOLDOWN_MS = 6e4;
70038
+ async function resolveServerBtcUsdRate(fetcher) {
70039
+ const fx = fetcher ?? lazyFxFetcher();
70040
+ if (Date.now() < cooldownUntil) {
70041
+ const cached2 = usableCachedRate(fx);
70042
+ if (cached2) {
70043
+ warnStaleRate(cached2.cachedAt);
70044
+ return { rate: cached2.rate, stale: true, cachedAt: cached2.cachedAt };
70045
+ }
70046
+ }
70047
+ try {
70048
+ const snapshot = await fx.fetch();
70049
+ const rate = fxRateFor(snapshot, "usd");
70050
+ if (!Number.isFinite(rate) || rate <= 0) throw new Error("implausible usd rate from fx source");
70051
+ staleEpisode = false;
70052
+ staleRefusalEpisode = false;
70053
+ cooldownUntil = 0;
70054
+ return { rate, stale: false };
70055
+ } catch (err) {
70056
+ if (err instanceof FxRateUnavailableError && err.knownStale) {
70057
+ warnKnownStaleRefusal(err.knownStale);
70058
+ throw rateStaleRefused(err.knownStale);
70059
+ }
70060
+ const cached2 = usableCachedRate(fx);
70061
+ if (cached2) {
70062
+ cooldownUntil = Date.now() + STALE_RATE_COOLDOWN_MS;
70063
+ warnStaleRate(cached2.cachedAt);
70064
+ return { rate: cached2.rate, stale: true, cachedAt: cached2.cachedAt };
70065
+ }
70066
+ throw rateUnavailable();
70067
+ }
70068
+ }
70069
+ function rateUnavailablePaymentError() {
70070
+ const err = rateUnavailable();
70071
+ return {
70072
+ body: {
70073
+ error: err.code,
70074
+ message: err.message,
70075
+ hint: err.hint,
70076
+ display: err.display,
70077
+ retryable: true
70078
+ },
70079
+ status: 503
70080
+ };
70081
+ }
70082
+ var staleEpisode = false;
70083
+ var staleRefusalEpisode = false;
70084
+ var cooldownUntil = 0;
70085
+ var _lazyFxFetcher = null;
70086
+ function lazyFxFetcher() {
70087
+ _lazyFxFetcher ??= createFxFetcher({ currencies: ["usd"] });
70088
+ return _lazyFxFetcher;
70089
+ }
70090
+ function usableCachedRate(fx) {
70091
+ const cached2 = fx.lastKnown?.();
70092
+ if (!cached2) return null;
70093
+ const rate = cached2.snapshot.rates.usd;
70094
+ if (typeof rate === "number" && Number.isFinite(rate) && rate > 0) {
70095
+ return { rate, cachedAt: cached2.cachedAt };
70096
+ }
70097
+ return null;
70098
+ }
70099
+ function warnStaleRate(cachedAt) {
70100
+ if (staleEpisode) return;
70101
+ staleEpisode = true;
70102
+ diagnosticConsole.warn(
70103
+ {
70104
+ level: "btc_rate_stale_fallback",
70105
+ message: void 0,
70106
+ cached_at: new Date(cachedAt).toISOString(),
70107
+ age: formatStaleness(cachedAt)
70108
+ }
70109
+ );
70110
+ }
70111
+ function warnKnownStaleRefusal(knownStale) {
70112
+ if (staleRefusalEpisode) return;
70113
+ staleRefusalEpisode = true;
70114
+ diagnosticConsole.warn(
70115
+ {
70116
+ level: "btc_rate_stale_refused",
70117
+ message: void 0,
70118
+ stale_days: knownStale.staleDays,
70119
+ stale_source: knownStale.staleSource,
70120
+ threshold_days: knownStale.thresholdDays
70121
+ }
70122
+ );
70123
+ }
70124
+ function rateStaleRefused(knownStale) {
70125
+ return new FxRateUnavailableError(
70126
+ `Could not price this payment: the platform refused its BTC/USD snapshot as ${knownStale.staleDays.toString()}d stale.`,
70127
+ {
70128
+ display: "BTC/USD rate is stale \u2014 the platform refused to price this payment, so nothing was charged.",
70129
+ hint: `The platform's FX snapshot is ${knownStale.staleDays.toString()} days stale (its refresh is stalled). Retry once rates refresh.`
70130
+ },
70131
+ knownStale
70132
+ );
70133
+ }
70134
+ function rateUnavailable() {
70135
+ return new FxRateUnavailableError(
70136
+ "Could not price this payment: the BTC/USD rate provider is unreachable and this DVM has no cached rate.",
70137
+ {
70138
+ display: "BTC/USD rate unavailable \u2014 the payment could not be priced, so nothing was charged.",
70139
+ hint: "The rate provider (CoinGecko) is rate-limiting or down and this DVM has never cached a rate. Retry in a minute."
70140
+ }
70141
+ );
70142
+ }
70125
70143
  function resolvePriceFiat(args) {
70126
70144
  if (!args.priceMsats) return void 0;
70127
70145
  return priceFiatMicro(args);
@@ -70269,112 +70287,6 @@ ${creditId}
70269
70287
  ${drawId}`, "utf8").digest("hex");
70270
70288
  return `draw:${digest}`;
70271
70289
  }
70272
- var STALE_RATE_COOLDOWN_MS = 6e4;
70273
- async function resolveServerBtcUsdRate(fetcher) {
70274
- const fx = fetcher ?? lazyFxFetcher();
70275
- if (Date.now() < cooldownUntil) {
70276
- const cached2 = usableCachedRate(fx);
70277
- if (cached2) {
70278
- warnStaleRate(cached2.cachedAt);
70279
- return { rate: cached2.rate, stale: true, cachedAt: cached2.cachedAt };
70280
- }
70281
- }
70282
- try {
70283
- const snapshot = await fx.fetch();
70284
- const rate = fxRateFor(snapshot, "usd");
70285
- if (!Number.isFinite(rate) || rate <= 0) throw new Error("implausible usd rate from fx source");
70286
- staleEpisode = false;
70287
- staleRefusalEpisode = false;
70288
- cooldownUntil = 0;
70289
- return { rate, stale: false };
70290
- } catch (err) {
70291
- if (err instanceof FxRateUnavailableError && err.knownStale) {
70292
- warnKnownStaleRefusal(err.knownStale);
70293
- throw rateStaleRefused(err.knownStale);
70294
- }
70295
- const cached2 = usableCachedRate(fx);
70296
- if (cached2) {
70297
- cooldownUntil = Date.now() + STALE_RATE_COOLDOWN_MS;
70298
- warnStaleRate(cached2.cachedAt);
70299
- return { rate: cached2.rate, stale: true, cachedAt: cached2.cachedAt };
70300
- }
70301
- throw rateUnavailable();
70302
- }
70303
- }
70304
- function rateUnavailablePaymentError() {
70305
- const err = rateUnavailable();
70306
- return {
70307
- body: {
70308
- error: err.code,
70309
- message: err.message,
70310
- hint: err.hint,
70311
- display: err.display,
70312
- retryable: true
70313
- },
70314
- status: 503
70315
- };
70316
- }
70317
- var staleEpisode = false;
70318
- var staleRefusalEpisode = false;
70319
- var cooldownUntil = 0;
70320
- var _lazyFxFetcher = null;
70321
- function lazyFxFetcher() {
70322
- _lazyFxFetcher ??= createFxFetcher({ currencies: ["usd"] });
70323
- return _lazyFxFetcher;
70324
- }
70325
- function usableCachedRate(fx) {
70326
- const cached2 = fx.lastKnown?.();
70327
- if (!cached2) return null;
70328
- const rate = cached2.snapshot.rates.usd;
70329
- if (typeof rate === "number" && Number.isFinite(rate) && rate > 0) {
70330
- return { rate, cachedAt: cached2.cachedAt };
70331
- }
70332
- return null;
70333
- }
70334
- function warnStaleRate(cachedAt) {
70335
- if (staleEpisode) return;
70336
- staleEpisode = true;
70337
- diagnosticConsole.warn(
70338
- {
70339
- level: "btc_rate_stale_fallback",
70340
- message: void 0,
70341
- cached_at: new Date(cachedAt).toISOString(),
70342
- age: formatStaleness(cachedAt)
70343
- }
70344
- );
70345
- }
70346
- function warnKnownStaleRefusal(knownStale) {
70347
- if (staleRefusalEpisode) return;
70348
- staleRefusalEpisode = true;
70349
- diagnosticConsole.warn(
70350
- {
70351
- level: "btc_rate_stale_refused",
70352
- message: void 0,
70353
- stale_days: knownStale.staleDays,
70354
- stale_source: knownStale.staleSource,
70355
- threshold_days: knownStale.thresholdDays
70356
- }
70357
- );
70358
- }
70359
- function rateStaleRefused(knownStale) {
70360
- return new FxRateUnavailableError(
70361
- `Could not price this payment: the platform refused its BTC/USD snapshot as ${knownStale.staleDays.toString()}d stale.`,
70362
- {
70363
- display: "BTC/USD rate is stale \u2014 the platform refused to price this payment, so nothing was charged.",
70364
- hint: `The platform's FX snapshot is ${knownStale.staleDays.toString()} days stale (its refresh is stalled). Retry once rates refresh.`
70365
- },
70366
- knownStale
70367
- );
70368
- }
70369
- function rateUnavailable() {
70370
- return new FxRateUnavailableError(
70371
- "Could not price this payment: the BTC/USD rate provider is unreachable and this DVM has no cached rate.",
70372
- {
70373
- display: "BTC/USD rate unavailable \u2014 the payment could not be priced, so nothing was charged.",
70374
- hint: "The rate provider (CoinGecko) is rate-limiting or down and this DVM has never cached a rate. Retry in a minute."
70375
- }
70376
- );
70377
- }
70378
70290
  var X402_SELF_RELAY_DEFAULT_LOW_BALANCE_WEI = 1000000000000000n;
70379
70291
  var X402_SELF_RELAY_BALANCE_INTERVAL_MS = 5 * 60 * 1e3;
70380
70292
  function createX402SelfRelay(opts) {
@@ -70387,7 +70299,15 @@ function createX402SelfRelay(opts) {
70387
70299
  }
70388
70300
  const chain4 = relayChain(opts.network);
70389
70301
  const account = privateKeyToAccount(opts.config.privateKey);
70390
- const transport = http(opts.config.rpcUrl);
70302
+ const transport = http(opts.config.rpcUrl, {
70303
+ fetchFn: (input2, init) => {
70304
+ const signal = x402ShutdownClaimSignal.getStore();
70305
+ return fetch(input2, signal ? {
70306
+ ...init,
70307
+ signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal
70308
+ } : init);
70309
+ }
70310
+ });
70391
70311
  const publicClient = createPublicClient({ chain: chain4, transport });
70392
70312
  const walletClient = createWalletClient({ account, chain: chain4, transport });
70393
70313
  const observeRpcFailure = async (operation) => {
@@ -70512,11 +70432,12 @@ function createSubmissionLock(lock, network, address) {
70512
70432
  tail = new Promise((resolve) => {
70513
70433
  releaseLocal = resolve;
70514
70434
  });
70515
- await prior;
70516
70435
  try {
70517
- if (!lock) return await operation();
70436
+ await waitForX402ShutdownClaim(() => prior);
70437
+ const submit = () => waitForX402ShutdownClaim(operation);
70438
+ if (!lock) return await submit();
70518
70439
  if (lastRefusal && lastRefusal !== refusalAtEntry) throw lastRefusal;
70519
- return await lock.withRelaySubmissionLock(key, operation);
70440
+ return await lock.withRelaySubmissionLock(key, submit);
70520
70441
  } catch (error62) {
70521
70442
  if (error62 instanceof X402RelaySubmissionLockError && error62 !== lastRefusal) {
70522
70443
  lastRefusal = error62;
@@ -70619,6 +70540,38 @@ function numericField(value, field) {
70619
70540
  function stringField(value, field) {
70620
70541
  return typeof value[field] === "string" ? value[field] : void 0;
70621
70542
  }
70543
+ function withX402ClaimBatches(manager) {
70544
+ const claim2 = async (opts = {}) => {
70545
+ const size = opts.maxClaimsPerBatch ?? 100;
70546
+ if (!Number.isSafeInteger(size) || size <= 0) {
70547
+ throw new Error("x402 maxClaimsPerBatch must be a positive safe integer");
70548
+ }
70549
+ let targets;
70550
+ let offset = 0;
70551
+ const results = [];
70552
+ do {
70553
+ const batch = await manager.claim({
70554
+ ...opts,
70555
+ maxClaimsPerBatch: size,
70556
+ selectClaimChannels: async (channels, context) => {
70557
+ targets ??= opts.selectClaimChannels ? await opts.selectClaimChannels(channels, context) : channels;
70558
+ const selected = targets.slice(offset, offset + size);
70559
+ offset += size;
70560
+ return selected;
70561
+ }
70562
+ });
70563
+ results.push(...batch);
70564
+ } while (targets && offset < targets.length);
70565
+ return results;
70566
+ };
70567
+ return new Proxy(manager, {
70568
+ get(target, property, receiver) {
70569
+ if (property === "claim") return claim2;
70570
+ const value = Reflect.get(target, property, receiver);
70571
+ return typeof value === "function" ? value.bind(target) : value;
70572
+ }
70573
+ });
70574
+ }
70622
70575
  var AUTHORIZATION_USED_EVENT = parseAbiItem(
70623
70576
  "event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)"
70624
70577
  );
@@ -70975,6 +70928,7 @@ function hostedSettlementFacilitator(facilitator, obligations, network) {
70975
70928
  throw new Error("Hosted x402 claim has no selected vouchers");
70976
70929
  }
70977
70930
  for (const raw2 of payload.claims) {
70931
+ x402ShutdownClaimSignal.getStore()?.throwIfAborted();
70978
70932
  const claim2 = raw2;
70979
70933
  if (!claim2.voucher?.channel || !claim2.signature || !claim2.totalClaimed) {
70980
70934
  throw new Error("Hosted x402 claim lacks original voucher identity");
@@ -71020,7 +70974,7 @@ function hostedSettlementFacilitator(facilitator, obligations, network) {
71020
70974
  if (reservation.replayed) throw new Error("Hosted x402 settle already has an original effect attempt");
71021
70975
  reservations.push(reservation);
71022
70976
  }
71023
- const response = await target.settle(payment, requirements);
70977
+ const response = await waitForX402ShutdownClaim(() => target.settle(payment, requirements));
71024
70978
  if (response.success && reservations.length) {
71025
70979
  for (const reservation of reservations) {
71026
70980
  await obligations.recordSubmitted(reservation.id, response.transaction);
@@ -71032,6 +70986,11 @@ function hostedSettlementFacilitator(facilitator, obligations, network) {
71032
70986
  });
71033
70987
  }
71034
70988
  async function createX402BatchSettlementServer(opts) {
70989
+ const rawShutdownClaimMs = (x402ShutdownClaimEnvironment.getStore() ?? process.env).DVMKIT_X402_SHUTDOWN_CLAIM_MS;
70990
+ const shutdownClaimMs = rawShutdownClaimMs === void 0 ? 3e3 : Number(rawShutdownClaimMs);
70991
+ if (!/^[1-9]\d*$/.test(rawShutdownClaimMs ?? "3000") || !Number.isSafeInteger(shutdownClaimMs) || shutdownClaimMs > 2147483647) {
70992
+ throw new Error("DVMKIT_X402_SHUTDOWN_CLAIM_MS must be a positive integer number of milliseconds, at most 2147483647");
70993
+ }
71035
70994
  const selfRelayEnabled = !!opts.config.selfRelay;
71036
70995
  if (selfRelayEnabled && opts.network !== X402_BATCH_SETTLEMENT_MAINNET_NETWORK) {
71037
70996
  throw new Error(`x402 selfRelay is Base mainnet-only; got ${opts.network}`);
@@ -71079,6 +71038,7 @@ async function createX402BatchSettlementServer(opts) {
71079
71038
  }
71080
71039
  storage2 = new InMemoryChannelStorage();
71081
71040
  }
71041
+ storage2 = withX402ShutdownClaimBudget(storage2);
71082
71042
  if (postgres && opts.hostedObligations) {
71083
71043
  opts.hostedObligations.attachX402SettlementStore(postgres);
71084
71044
  }
@@ -71104,7 +71064,23 @@ async function createX402BatchSettlementServer(opts) {
71104
71064
  ...opts.facilitatorAuth ? { facilitatorAuth: opts.facilitatorAuth } : {}
71105
71065
  });
71106
71066
  const facilitator = opts.supportedResponse && !selfRelayEnabled ? withCachedSupportedResponse(rawFacilitator, opts.supportedResponse) : rawFacilitator;
71107
- const settlementFacilitator = opts.hostedObligations ? hostedSettlementFacilitator(facilitator, opts.hostedObligations, opts.network) : facilitator;
71067
+ const accountingFacilitator = opts.hostedObligations ? hostedSettlementFacilitator(facilitator, opts.hostedObligations, opts.network) : facilitator;
71068
+ let remaining;
71069
+ const settlementFacilitator = withX402ShutdownClaimBudget({
71070
+ verify: accountingFacilitator.verify.bind(accountingFacilitator),
71071
+ getSupported: accountingFacilitator.getSupported.bind(accountingFacilitator),
71072
+ async settle(payload, requirements) {
71073
+ const response = await waitForX402ShutdownClaim(() => accountingFacilitator.settle(payload, requirements));
71074
+ if (response.success && payload.payload.type === "claim") {
71075
+ const claims = payload.payload.claims;
71076
+ for (const claim2 of claims) {
71077
+ remaining?.delete(computeChannelId(claim2.voucher.channel, opts.network).toLowerCase());
71078
+ }
71079
+ await marker.write(true);
71080
+ }
71081
+ return response;
71082
+ }
71083
+ });
71108
71084
  const rpcUrl = opts.rpcUrl ?? opts.config.rpcUrl;
71109
71085
  const settlementEvidence = opts.settlementEvidenceReader ?? await createX402SettlementEvidenceReader({
71110
71086
  network: opts.network,
@@ -71139,7 +71115,7 @@ async function createX402BatchSettlementServer(opts) {
71139
71115
  ...X402_BATCH_AUTO_SETTLEMENT,
71140
71116
  ...opts.config.autoSettlement === false ? {} : opts.config.autoSettlement,
71141
71117
  // Every claim this fleet builds is capped at earned draws — the claim
71142
- // timer, `claimAndSettle()`, and the withdraw-race rush claim all route
71118
+ // timer, `claimAndSettle()`, withdraw-race rush and shutdown claim all route
71143
71119
  // through this selector. A builder-supplied
71144
71120
  // `autoSettlement.selectClaimChannels` cannot override it: the ceiling is
71145
71121
  // a money invariant, not a policy knob. Upstream's refund job builds its
@@ -71148,10 +71124,16 @@ async function createX402BatchSettlementServer(opts) {
71148
71124
  selectClaimChannels: claimCeiling
71149
71125
  };
71150
71126
  const settleScope = `${opts.network}|${opts.payTo.toLowerCase()}|${token.toLowerCase()}`;
71127
+ let pendingSettle = false;
71151
71128
  const marker = postgres ? {
71152
71129
  read: () => postgres.isSettlePending(settleScope),
71153
- write: (pending) => postgres.setSettlePending(settleScope, pending)
71154
- } : void 0;
71130
+ write: (pending2) => postgres.setSettlePending(settleScope, pending2)
71131
+ } : {
71132
+ read: async () => pendingSettle,
71133
+ write: async (pending2) => {
71134
+ pendingSettle = pending2;
71135
+ }
71136
+ };
71155
71137
  opts.payout?.attach({
71156
71138
  scope: settleScope,
71157
71139
  payTo: opts.payTo,
@@ -71161,20 +71143,20 @@ async function createX402BatchSettlementServer(opts) {
71161
71143
  settleIntervalMs: (settlementConfig.settleIntervalSecs ?? X402_BATCH_AUTO_SETTLEMENT.settleIntervalSecs ?? 300) * 1e3,
71162
71144
  ...postgres ? { listWedgedRefunds: () => listWedgedRefunds(postgres) } : {}
71163
71145
  });
71164
- const tracked = opts.payout ? opts.payout.trackManager(manager) : manager;
71146
+ const tracked = withX402ClaimBatches(opts.payout ? opts.payout.trackManager(manager) : manager);
71165
71147
  let scheduler;
71166
71148
  if (opts.config.autoSettlement !== false) {
71167
- if (postgres && marker) {
71168
- scheduler = createX402FleetSettlementScheduler({
71169
- manager: tracked,
71170
- storage: storage2,
71171
- config: settlementConfig,
71172
- withLock: (operation) => postgres.withFleetSettlementLock(operation),
71173
- marker
71174
- });
71175
- } else {
71176
- manager.start(settlementConfig);
71177
- }
71149
+ scheduler = createX402FleetSettlementScheduler({
71150
+ manager: tracked,
71151
+ storage: storage2,
71152
+ config: settlementConfig,
71153
+ withLock: async (operation) => {
71154
+ if (postgres) return postgres.withFleetSettlementLock(operation);
71155
+ await operation();
71156
+ return true;
71157
+ },
71158
+ marker
71159
+ });
71178
71160
  }
71179
71161
  const buildRequirements = async (amount) => {
71180
71162
  const requirements = await resource.buildPaymentRequirementsFromOptions(
@@ -71199,6 +71181,7 @@ async function createX402BatchSettlementServer(opts) {
71199
71181
  );
71200
71182
  return requirements;
71201
71183
  };
71184
+ let stopPromise;
71202
71185
  selfRelay?.start();
71203
71186
  return {
71204
71187
  buildRequirements,
@@ -71524,7 +71507,7 @@ async function createX402BatchSettlementServer(opts) {
71524
71507
  context
71525
71508
  )
71526
71509
  });
71527
- if (results.length > 0) await marker?.write(true);
71510
+ if (results.length > 0) await marker.write(true);
71528
71511
  };
71529
71512
  if (postgres) await postgres.withFleetSettlementLock(claim2);
71530
71513
  else await claim2();
@@ -71577,8 +71560,8 @@ async function createX402BatchSettlementServer(opts) {
71577
71560
  maxClaimsPerBatch: 100,
71578
71561
  selectClaimChannels: claimCeiling
71579
71562
  });
71580
- if (claims.length > 0) await marker?.write(true);
71581
- if (claims.length === 0 && !await marker?.read()) return;
71563
+ if (claims.length > 0) await marker.write(true);
71564
+ if (claims.length === 0 && !await marker.read()) return;
71582
71565
  try {
71583
71566
  const settled = await settleOutstandingClaims(manager);
71584
71567
  await opts.payout?.recordSettle(settled.transaction);
@@ -71586,17 +71569,66 @@ async function createX402BatchSettlementServer(opts) {
71586
71569
  await opts.payout?.recordSettleFailure(error62);
71587
71570
  throw error62;
71588
71571
  }
71589
- await marker?.write(false);
71572
+ await marker.write(false);
71590
71573
  };
71591
71574
  if (postgres) await postgres.withFleetSettlementLock(operation, true);
71592
71575
  else await operation();
71593
71576
  },
71594
- async stop() {
71595
- selfRelay?.stop();
71596
- scheduler?.stop();
71597
- await manager.stop();
71598
- await postgres?.close();
71599
- if (relayLockOwner !== postgres) await relayLockOwner?.close();
71577
+ stop() {
71578
+ return stopPromise ??= (async () => {
71579
+ selfRelay?.stop();
71580
+ scheduler?.stop();
71581
+ await manager.stop();
71582
+ const controller = new AbortController();
71583
+ const timer = setTimeout(() => controller.abort(new Error("x402 shutdown claim deadline")), shutdownClaimMs);
71584
+ let reason;
71585
+ try {
71586
+ await x402ShutdownClaimSignal.run(controller.signal, () => waitForX402ShutdownClaim(async () => {
71587
+ const selectRemaining = async (channels, context) => {
71588
+ const selected = await claimCeiling(channels, context);
71589
+ remaining = new Map(selected.map((channel) => [
71590
+ channel.channelId.toLowerCase(),
71591
+ BigInt(channel.chargedCumulativeAmount) - BigInt(channel.totalClaimed)
71592
+ ]));
71593
+ return selected;
71594
+ };
71595
+ const claim2 = async () => {
71596
+ const claims = await tracked.claim({
71597
+ maxClaimsPerBatch: settlementConfig.maxClaimsPerBatch ?? 100,
71598
+ selectClaimChannels: selectRemaining
71599
+ });
71600
+ if (claims.length > 0) await marker.write(true);
71601
+ };
71602
+ if (postgres) {
71603
+ if (!await postgres.withFleetSettlementLock(claim2)) {
71604
+ reason = "lock_unavailable";
71605
+ await selectRemaining(await storage2.list(), {
71606
+ now: Date.now(),
71607
+ lastClaimTime: 0,
71608
+ lastSettleTime: 0,
71609
+ pendingSettle: false
71610
+ });
71611
+ }
71612
+ } else await claim2();
71613
+ }));
71614
+ } catch {
71615
+ reason = controller.signal.aborted ? "timeout" : "failed";
71616
+ } finally {
71617
+ clearTimeout(timer);
71618
+ controller.abort(new Error("x402 shutdown claim finished"));
71619
+ }
71620
+ if (reason) {
71621
+ diagnosticConsole.warn({
71622
+ event: "x402_shutdown_claim_incomplete",
71623
+ reason,
71624
+ timeout_ms: shutdownClaimMs,
71625
+ unclaimed_channels: remaining?.size ?? null,
71626
+ unclaimed_amount_native: remaining ? [...remaining.values()].reduce((total, amount) => total + amount, 0n).toString() : null
71627
+ });
71628
+ }
71629
+ await postgres?.close();
71630
+ if (relayLockOwner !== postgres) await relayLockOwner?.close();
71631
+ })();
71600
71632
  }
71601
71633
  };
71602
71634
  }
@@ -71909,6 +71941,7 @@ function claimCeilingSelector(earnedNative) {
71909
71941
  return async (channels) => {
71910
71942
  const selected = [];
71911
71943
  for (const channel of channels) {
71944
+ x402ShutdownClaimSignal.getStore()?.throwIfAborted();
71912
71945
  const charged = BigInt(channel.chargedCumulativeAmount);
71913
71946
  const claimed = BigInt(channel.totalClaimed);
71914
71947
  if (charged <= claimed) continue;
@@ -73388,6 +73421,7 @@ function methodNativeAmountToDecimal(amount, methodName) {
73388
73421
  return `${nativeAmount2 / scale}.${(nativeAmount2 % scale).toString().padStart(decimals, "0")}`;
73389
73422
  }
73390
73423
  function cashuPaymentRequest(args) {
73424
+ const tags = args.lockWindowSeconds === void 0 ? [] : [["refund_delay", String(args.lockWindowSeconds + REFUND_DELAY_TOLERANCE_SECONDS)]];
73391
73425
  return new yi(
73392
73426
  void 0,
73393
73427
  void 0,
@@ -73396,7 +73430,7 @@ function cashuPaymentRequest(args) {
73396
73430
  args.mints,
73397
73431
  void 0,
73398
73432
  false,
73399
- { kind: "P2PK", data: args.lockPubkey, tags: [] }
73433
+ { kind: "P2PK", data: args.lockPubkey, tags }
73400
73434
  ).toEncodedCreqA();
73401
73435
  }
73402
73436
  function proofSetRequestId(secrets) {
@@ -73440,6 +73474,7 @@ function sameRates(a, b2) {
73440
73474
  return true;
73441
73475
  }
73442
73476
  var FX_HOLD_WINDOW_MS = 10 * 6e4;
73477
+ var REFUND_DELAY_TOLERANCE_SECONDS = FX_HOLD_WINDOW_MS / 1e3;
73443
73478
  function isTestMintUrl(url2) {
73444
73479
  let host;
73445
73480
  try {
@@ -73468,9 +73503,17 @@ function valueCashuFunding(wallet, proofs) {
73468
73503
  netMsats: netSats.multiplyBy(1e3).toNumber()
73469
73504
  };
73470
73505
  }
73471
- var P2PK_TAG_KEYS = /* @__PURE__ */ new Set(["locktime", "refund", "pubkeys", "n_sigs", "sigflag", "n_sigs_refund"]);
73472
- var SINGLE_VALUE_TAG_KEYS = /* @__PURE__ */ new Set(["locktime", "n_sigs", "sigflag", "n_sigs_refund"]);
73506
+ var MAX_CASHU_SECRET_LENGTH = 1024;
73507
+ var P2PK_TAG_KEYS = /* @__PURE__ */ new Set(["locktime", "refund", "pubkeys", "n_sigs", "sigflag", "n_sigs_refund", "refund_delay"]);
73508
+ var SINGLE_VALUE_TAG_KEYS = /* @__PURE__ */ new Set(["locktime", "n_sigs", "sigflag", "n_sigs_refund", "refund_delay"]);
73473
73509
  function assessCashuLock(secret, lockPubkeys, nowSec, floorSec = nowSec + DEFAULT_CASHU_LOCK_WINDOW_SECONDS) {
73510
+ if (secret.length > MAX_CASHU_SECRET_LENGTH) {
73511
+ return {
73512
+ kind: "rejected",
73513
+ code: "lock_not_exclusive",
73514
+ message: `Proof secret is ${secret.length} characters; the mint redeems at most ${MAX_CASHU_SECRET_LENGTH}.`
73515
+ };
73516
+ }
73474
73517
  try {
73475
73518
  I(secret);
73476
73519
  if (ln(secret) !== "P2PK") throw new Error("not P2PK");
@@ -74399,7 +74442,7 @@ async function verifyUpfrontPaymentInScope(opts) {
74399
74442
  x402Requirements
74400
74443
  });
74401
74444
  }
74402
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-G6C4N2BN-TAJEBQGU.js");
74445
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-FHHB3V4V-CM6OMLHE.js");
74403
74446
  const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
74404
74447
  x402Payment,
74405
74448
  x402Config,
@@ -74846,7 +74889,12 @@ async function verifyUpfrontPaymentInScope(opts) {
74846
74889
  opts.priceFiat
74847
74890
  ) : void 0;
74848
74891
  const lockPubkey = opts.lockPubkeys?.[0];
74849
- const cashuRequest = opts.nut24 && opts.nut24.mints.length > 0 && !opts.fundOnly && cashuAccumulatorReady(opts) && lockPubkey ? cashuPaymentRequest({ requiredMsats, mints: opts.nut24.mints, lockPubkey }) : void 0;
74892
+ const cashuRequest = opts.nut24 && opts.nut24.mints.length > 0 && !opts.fundOnly && cashuAccumulatorReady(opts) && lockPubkey ? cashuPaymentRequest({
74893
+ requiredMsats,
74894
+ mints: opts.nut24.mints,
74895
+ lockPubkey,
74896
+ ...opts.nut24.refundDelay && { lockWindowSeconds: lockWindowOrDefault(opts.cashuLockWindowSeconds) }
74897
+ }) : void 0;
74850
74898
  return {
74851
74899
  paidMsats: 0,
74852
74900
  receivedProofs: [],
@@ -74985,7 +75033,7 @@ async function verifyTempoSessionManagementCredential(args) {
74985
75033
  }
74986
75034
  };
74987
75035
  }
74988
- var LOCK_SHAPE_HINT = "Lock a fresh token with data set to cashu.lock_pubkeys[0] from /v1/info as a 33-byte compressed hex key. Use only the locktime, refund, pubkeys, n_sigs, sigflag and n_sigs_refund tags, each once and with a value: pubkeys may list only other cashu.lock_pubkeys entries, n_sigs must be 1, sigflag SIG_INPUTS, refund keys compressed and distinct, n_sigs_refund at most the number of refund keys";
75036
+ var LOCK_SHAPE_HINT = "Lock a fresh token with data set to cashu.lock_pubkeys[0] from /v1/info as a 33-byte compressed hex key, in a secret of at most 1024 characters. Use only the locktime, refund, pubkeys, n_sigs, sigflag, n_sigs_refund and refund_delay tags, each once and with a value: pubkeys may list only other cashu.lock_pubkeys entries, n_sigs must be 1, sigflag SIG_INPUTS, refund keys compressed and distinct, n_sigs_refund at most the number of refund keys";
74989
75037
  var UNSIGNED_LOCK_REFUSAL_HINT = `${LOCK_SHAPE_HINT}, and any locktime at least cashu.unsigned_min_locktime seconds in the future.`;
74990
75038
  var PAYMENT_ERROR_COPY = {
74991
75039
  payment_invalid: {
@@ -75480,7 +75528,7 @@ async function verifyIncomingPaymentInScope(body, opts, snapshot) {
75480
75528
  };
75481
75529
  }
75482
75530
  }
75483
- const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-G6C4N2BN-TAJEBQGU.js");
75531
+ const { verifyX402Payment: verifyX402Payment2 } = await import("./x402-FHHB3V4V-CM6OMLHE.js");
75484
75532
  const receipt = await withPaymentStage("verifier_broadcast", () => verifyX402Payment2(
75485
75533
  body.content.x402_payment,
75486
75534
  opts.x402Config,
@@ -75703,8 +75751,8 @@ function x402FundingId(txHash, paymentHeader) {
75703
75751
  return `eip3009:${from.toLowerCase()}:${nonce.toLowerCase()}`;
75704
75752
  }
75705
75753
  function midJobFundedMsats(snapshot, railMsats) {
75706
- const pending = snapshot.pendingPaymentMsats ?? 0;
75707
- return pending > 0 ? pending : railMsats;
75754
+ const pending2 = snapshot.pendingPaymentMsats ?? 0;
75755
+ return pending2 > 0 ? pending2 : railMsats;
75708
75756
  }
75709
75757
  async function acceptDurableExactIncoming(args) {
75710
75758
  const authorization = exactEvmAuthorization(decodePayment(args.paymentHeader));
@@ -77397,6 +77445,239 @@ function logCredentialRejected(rail, phase, err) {
77397
77445
  }
77398
77446
  );
77399
77447
  }
77448
+ async function bookCheckoutFunding(opts, tx) {
77449
+ if (!opts.creditLedger) throw new Error("Checkout requires a credit ledger");
77450
+ const committed = await commitMarkedFunding({
77451
+ ledger: opts.creditLedger,
77452
+ processedPayments: opts.processedPayments,
77453
+ enqueueCreditDeposit: opts.enqueueCreditDeposit,
77454
+ priceFiat: { currency: "usd", amountMicro: opts.amountMicro },
77455
+ requiredMsats: 0,
77456
+ callerId: opts.callerPubkey,
77457
+ hostingAdmissionId: opts.hostingAdmissionId,
77458
+ hostingPaymentArtifactHash: opts.hostingPaymentArtifactHash,
77459
+ dvmId: opts.dvmId ?? "",
77460
+ fundOnly: { creditId: opts.creditId, fundId: opts.fundId, commitment: "" },
77461
+ drawBasis: false,
77462
+ ttlMs: opts.creditTtlMs ?? IMPLICIT_CREDIT_TTL_MS
77463
+ }, {
77464
+ rail: "stripe",
77465
+ paymentId: opts.paymentIntentId,
77466
+ paidMsats: 0,
77467
+ fundedMicro: opts.amountMicro,
77468
+ nativeAmount: opts.amountMicro / 1e4,
77469
+ nativeAsset: "usd-cents"
77470
+ }, tx);
77471
+ return committed.deposit;
77472
+ }
77473
+ var CHECKOUT_LIFETIME_MS = 60 * 60 * 1e3;
77474
+ function checkoutMetadata(record2) {
77475
+ return {
77476
+ fund_id: record2.fundId,
77477
+ credit_id: record2.creditId,
77478
+ caller_pubkey: record2.callerPubkey,
77479
+ dvmkit_dvm_id: record2.dvmId,
77480
+ dvmkit_checkout_store: record2.storeNamespace
77481
+ };
77482
+ }
77483
+ function checkoutMatches(session, record2) {
77484
+ const metadata = checkoutMetadata(record2);
77485
+ return session.client_reference_id === record2.fundId && Object.entries(metadata).every(([key, value]) => session.metadata?.[key] === value);
77486
+ }
77487
+ function paidCheckoutMatches(session, record2) {
77488
+ const pi2 = session.payment_intent;
77489
+ return checkoutMatches(session, record2) && session.payment_status === "paid" && session.status === "complete" && !!pi2?.id && pi2.status === "succeeded" && pi2.amount === record2.amountMicro / 1e4 && pi2.currency === "usd" && Object.entries(checkoutMetadata(record2)).every(([key, value]) => pi2.metadata?.[key] === value);
77490
+ }
77491
+ var StripeCheckoutError = class extends Error {
77492
+ constructor(status, code) {
77493
+ super("Stripe Checkout request failed");
77494
+ this.status = status;
77495
+ this.retryable = status >= 500 || status === 409 || status === 429;
77496
+ this.causeCode = status === 403 ? "permission_denied" : code && /^[a-z0-9_]{1,80}$/.test(code) ? code : "stripe_request_failed";
77497
+ }
77498
+ status;
77499
+ retryable;
77500
+ causeCode;
77501
+ };
77502
+ async function withCheckoutInternalLock(store, fundId, run3) {
77503
+ const deadline = Date.now() + 1e3;
77504
+ for (; ; ) {
77505
+ try {
77506
+ return await store.withRecord(fundId, run3);
77507
+ } catch (error62) {
77508
+ if (error62?.code !== "55P03" || Date.now() >= deadline) throw error62;
77509
+ await delay2(10);
77510
+ }
77511
+ }
77512
+ }
77513
+ var CHECKOUT_CREATE_WINDOW_MS = 30 * 60 * 1e3;
77514
+ var CHECKOUT_LEASE_MS = 3e4;
77515
+ function checkoutExpired(refunded = false, disputeLost = false) {
77516
+ return Response.json({
77517
+ error: "checkout_expired",
77518
+ message: "This Checkout top-up has expired; no credit can be booked.",
77519
+ hint: disputeLost ? "The card dispute was lost; no additional refund is due. Start a new top-up with a new fund_id." : refunded ? "What was still owed on the charge was refunded to the card. Start a new top-up with a new fund_id." : "Start a new top-up with a new fund_id. Any abandoned payment is automatically refunded to the card.",
77520
+ retryable: false
77521
+ }, { status: 409 });
77522
+ }
77523
+ function mismatch() {
77524
+ return Response.json({
77525
+ error: "payment_invalid",
77526
+ message: "The Checkout session does not match this signed top-up. No credit was booked.",
77527
+ retryable: false
77528
+ }, { status: 409 });
77529
+ }
77530
+ function unavailable(error62) {
77531
+ const stripe = error62 instanceof StripeCheckoutError ? error62 : void 0;
77532
+ const retryable = stripe?.retryable ?? true;
77533
+ return { funded: false, response: Response.json({
77534
+ error: "checkout_unavailable",
77535
+ message: stripe?.causeCode === "permission_denied" ? "Stripe denied Checkout access. The operator must grant the key Checkout Sessions permission." : "The service could not confirm this Checkout top-up's state.",
77536
+ hint: retryable ? "Retry the same fund_id and signed amount; do not start another payment." : "Ask the operator to resolve the Stripe request failure before starting another top-up.",
77537
+ retryable,
77538
+ ...stripe && { cause: stripe.causeCode, stripe_status: stripe.status }
77539
+ }, { status: retryable ? 503 : 502 }) };
77540
+ }
77541
+ function terminal(record2) {
77542
+ if (record2.state === "booked") return { funded: true, replayed: true };
77543
+ if (["expired", "refunding", "refunded"].includes(record2.state)) {
77544
+ return { funded: false, response: checkoutExpired(record2.state === "refunded", record2.terminalReason === "dispute_lost") };
77545
+ }
77546
+ }
77547
+ async function expireUnshownCheckout(rail, fundId, nowMs) {
77548
+ await withCheckoutInternalLock(rail.store, fundId, async (locked) => {
77549
+ const record2 = locked.record;
77550
+ if (record2.state === "creating" && !record2.sessionId && (record2.leaseUntil ?? 0) <= nowMs) {
77551
+ await locked.transition("creating", "expired", void 0, { leaseToken: void 0, leaseUntil: void 0 });
77552
+ }
77553
+ });
77554
+ }
77555
+ async function createSession(rail, snapshot, nowMs) {
77556
+ if (nowMs >= snapshot.createdAt + CHECKOUT_CREATE_WINDOW_MS) {
77557
+ await expireUnshownCheckout(rail, snapshot.fundId, nowMs);
77558
+ const current = await rail.store.get(snapshot.fundId);
77559
+ return current ? terminal(current) ?? unavailable() : unavailable();
77560
+ }
77561
+ const token = randomUUID42();
77562
+ const claimed = await withCheckoutInternalLock(rail.store, snapshot.fundId, async (locked) => {
77563
+ if (locked.record.state !== "creating" || (locked.record.leaseUntil ?? 0) > nowMs) return false;
77564
+ await locked.transition("creating", "creating", void 0, { leaseToken: token, leaseUntil: nowMs + CHECKOUT_LEASE_MS });
77565
+ return true;
77566
+ });
77567
+ if (!claimed) return unavailable();
77568
+ let session;
77569
+ try {
77570
+ session = await rail.api.create(snapshot);
77571
+ if (!session.id || !checkoutMatches(session, snapshot)) throw new Error("Checkout create binding mismatch");
77572
+ } catch (error62) {
77573
+ await withCheckoutInternalLock(rail.store, snapshot.fundId, async (locked) => {
77574
+ if (locked.record.state !== "creating" || locked.record.leaseToken !== token) return;
77575
+ await locked.transition(
77576
+ "creating",
77577
+ error62 instanceof StripeCheckoutError && !error62.retryable ? "expired" : "creating",
77578
+ void 0,
77579
+ { leaseToken: void 0, leaseUntil: void 0 }
77580
+ );
77581
+ });
77582
+ return unavailable(error62);
77583
+ }
77584
+ try {
77585
+ return await withCheckoutInternalLock(rail.store, snapshot.fundId, async (locked) => {
77586
+ if (locked.record.state !== "creating" || locked.record.leaseToken !== token) return unavailable();
77587
+ await locked.transition("creating", "open", session.id, { leaseToken: void 0, leaseUntil: void 0 });
77588
+ return pending(session, locked.record);
77589
+ });
77590
+ } catch (error62) {
77591
+ await withCheckoutInternalLock(rail.store, snapshot.fundId, async (locked) => {
77592
+ if (locked.record.state === "creating" && locked.record.leaseToken === token) {
77593
+ await locked.transition("creating", "creating", void 0, { leaseToken: void 0, leaseUntil: void 0 });
77594
+ }
77595
+ });
77596
+ throw error62;
77597
+ }
77598
+ }
77599
+ function pending(session, record2) {
77600
+ if (session.status !== "open" || !session.url || !Number.isSafeInteger(session.expires_at)) return unavailable();
77601
+ return { funded: false, response: Response.json({
77602
+ status: "pending",
77603
+ fund_id: record2.fundId,
77604
+ credit_id: record2.creditId,
77605
+ checkout: { url: session.url, expires_at: session.expires_at }
77606
+ }, { status: 202 }) };
77607
+ }
77608
+ async function fundStripeCheckout(args) {
77609
+ const { rail } = args;
77610
+ const nowMs = args.nowMs ?? Date.now();
77611
+ const dvmId = args.opts.canonicalDvmId ?? args.opts.dvmId ?? rail.store.namespace;
77612
+ if (args.fundId.length > 200 || !Number.isSafeInteger(args.amountMicro) || args.amountMicro <= 0 || args.amountMicro % 1e4 !== 0) {
77613
+ return { funded: false, response: Response.json({
77614
+ error: "invalid_request",
77615
+ message: "Checkout requires fund_id of at most 200 characters and a positive whole number of USD cents.",
77616
+ retryable: false
77617
+ }, { status: 400 }) };
77618
+ }
77619
+ try {
77620
+ let snapshot = await rail.store.get(args.fundId);
77621
+ if (!snapshot || snapshot.state === "creating") {
77622
+ const refused = await args.preflight();
77623
+ if (refused) return { funded: false, response: refused };
77624
+ if (await args.opts.creditLedger?.getFunding({ creditId: args.creditId, fundId: args.fundId })) return { funded: false, response: mismatch() };
77625
+ if (!snapshot) {
77626
+ await rail.store.create({
77627
+ storeNamespace: rail.store.namespace,
77628
+ dvmId,
77629
+ hostingDvmId: args.opts.dvmId,
77630
+ fundId: args.fundId,
77631
+ creditId: args.creditId,
77632
+ callerPubkey: args.callerPubkey,
77633
+ amountMicro: args.amountMicro,
77634
+ createdAt: nowMs,
77635
+ expiresAt: nowMs + CHECKOUT_LIFETIME_MS,
77636
+ successUrl: rail.successUrl,
77637
+ productName: args.productName,
77638
+ state: "creating"
77639
+ });
77640
+ snapshot = await rail.store.get(args.fundId);
77641
+ }
77642
+ }
77643
+ if (!snapshot) return unavailable();
77644
+ if (snapshot.fundId !== args.fundId || snapshot.creditId !== args.creditId || snapshot.callerPubkey !== args.callerPubkey || snapshot.amountMicro !== args.amountMicro || snapshot.storeNamespace !== rail.store.namespace || snapshot.dvmId !== dvmId) {
77645
+ return { funded: false, response: mismatch() };
77646
+ }
77647
+ const resolved = terminal(snapshot);
77648
+ if (resolved) return resolved;
77649
+ if (snapshot.state === "creating") return await createSession(rail, snapshot, nowMs);
77650
+ if (!snapshot.sessionId) return unavailable();
77651
+ const session = await rail.api.retrieve(snapshot.sessionId);
77652
+ if (session.id !== snapshot.sessionId || !checkoutMatches(session, snapshot)) return { funded: false, response: mismatch() };
77653
+ return await rail.store.withRecord(args.fundId, async (locked) => {
77654
+ const record2 = locked.record;
77655
+ const finished = terminal(record2);
77656
+ if (finished) return finished;
77657
+ if (record2.state !== "open" || record2.sessionId !== session.id) return unavailable();
77658
+ if (session.payment_status === "paid") {
77659
+ if (!paidCheckoutMatches(session, record2)) return { funded: false, response: mismatch() };
77660
+ const deposit = await bookCheckoutFunding({
77661
+ ...args.opts,
77662
+ creditId: record2.creditId,
77663
+ fundId: record2.fundId,
77664
+ callerPubkey: record2.callerPubkey,
77665
+ amountMicro: record2.amountMicro,
77666
+ paymentIntentId: session.payment_intent.id
77667
+ }, locked.tx);
77668
+ await locked.transition("open", "booked");
77669
+ return { funded: true, replayed: false, deposit };
77670
+ }
77671
+ if (session.status === "expired") {
77672
+ await locked.transition("open", "expired");
77673
+ return { funded: false, response: checkoutExpired() };
77674
+ }
77675
+ return pending(session, record2);
77676
+ });
77677
+ } catch (error62) {
77678
+ return unavailable(error62);
77679
+ }
77680
+ }
77400
77681
  function authErrorBody(err, opts = {}) {
77401
77682
  const schemaUrl = opts.schemaUrl ?? "/v1/info";
77402
77683
  const inputIssues = err.sub_reason === "schema_invalid" ? callerInputIssues(err.issues) : [];
@@ -77435,8 +77716,8 @@ function authErrorBody(err, opts = {}) {
77435
77716
  hint: subReason === "signature_required" ? "Run `npx @dvmkit/dvm-cli init`, then use `dvm request` to sign and send the request, or implement secp256k1+BIP-340 Schnorr signing with the domain-bound envelope described at https://dvmkit.com/docs/protocol." : "Regenerate the request with the current timestamp + a fresh nonce; sign with secp256k1+BIP-340 Schnorr over the canonical JSON form of the input."
77436
77717
  };
77437
77718
  }
77438
- function infoSchemaUrl(requestUrl, publicOrigin) {
77439
- return `${publicOrigin ?? new URL(requestUrl).origin}/v1/info`;
77719
+ function infoSchemaUrl(requestUrl, mountPrefix2, publicOrigin) {
77720
+ return `${publicOrigin ?? new URL(requestUrl).origin}${mountPrefix2}/v1/info`;
77440
77721
  }
77441
77722
  function callerInputIssues(issues) {
77442
77723
  if (!issues) return [];
@@ -77663,8 +77944,8 @@ async function runLocked(deps, drain) {
77663
77944
  if (stored) plan = stored;
77664
77945
  if (!refundsFinished(plan)) {
77665
77946
  const fresh = await reread(deps, drain);
77666
- const terminal = plan.entries.find((entry) => entry.lastError && isTerminalFailure(entry.lastError));
77667
- return { drain: terminal ? await blockDrain(deps, fresh, terminal.lastError) : fresh, completed: false };
77947
+ const terminal2 = plan.entries.find((entry) => entry.lastError && isTerminalFailure(entry.lastError));
77948
+ return { drain: terminal2 ? await blockDrain(deps, fresh, terminal2.lastError) : fresh, completed: false };
77668
77949
  }
77669
77950
  const transition = (tx) => deps.ledger.markDrainSent({
77670
77951
  creditId: drain.creditId,
@@ -77851,7 +78132,7 @@ function refundsFinished(plan) {
77851
78132
  function refundIdempotencyKey(drain, entry) {
77852
78133
  const fields = [drain.creditId, drain.drainId, entry.lotId, String(entry.attempt)];
77853
78134
  if (entry.revision) fields.push(String(entry.revision));
77854
- const digest = createHash72("sha256").update(fields.join("\0")).digest("hex");
78135
+ const digest = createHash82("sha256").update(fields.join("\0")).digest("hex");
77855
78136
  return `dvmkit-card-refund-${digest}`;
77856
78137
  }
77857
78138
  function cardRefundSentRef(plan) {
@@ -77883,7 +78164,7 @@ function failureCode(err) {
77883
78164
  function refundDrainTag(drain) {
77884
78165
  const tag = `${drain.creditId}:${drain.drainId}`;
77885
78166
  if (tag.length <= 200) return tag;
77886
- return `sha256:${createHash72("sha256").update(tag).digest("hex")}`;
78167
+ return `sha256:${createHash82("sha256").update(tag).digest("hex")}`;
77887
78168
  }
77888
78169
  function logPending(drain, fields) {
77889
78170
  diagnosticConsole.warn({
@@ -78159,6 +78440,7 @@ var CREDIT_REQUEST_SCHEMA = external_exports.object({
78159
78440
  * a card top-up: its MPP `method="stripe"` challenge is issued only here.
78160
78441
  */
78161
78442
  method: external_exports.enum(["lightning", "tempo", "stripe"]).optional(),
78443
+ via: external_exports.string().optional(),
78162
78444
  /** Required with `method: "tempo"`; invalid on every other funding rail. */
78163
78445
  intent: external_exports.enum(["charge", "session"]).optional()
78164
78446
  }).optional(),
@@ -78236,12 +78518,13 @@ async function handleCreditRequest(c, deps) {
78236
78518
  case "fund":
78237
78519
  if (deps.withFundingAdmission && body.fund) {
78238
78520
  const creditId = body.credit_id ?? derivedFundCreditId(callerPubkey, body.fund.fund_id);
78239
- const [prior, invoice] = await Promise.all([
78521
+ const [prior, invoice, checkout] = await Promise.all([
78240
78522
  deps.ledger.getFunding({ creditId, fundId: body.fund.fund_id }),
78241
- body.fund.method === "lightning" ? deps.ledger.getInvoice({ creditId, fundId: body.fund.fund_id }) : Promise.resolve(void 0)
78523
+ body.fund.method === "lightning" ? deps.ledger.getInvoice({ creditId, fundId: body.fund.fund_id }) : Promise.resolve(void 0),
78524
+ body.fund.via === "checkout" ? deps.stripeCredit?.checkout?.store.get(body.fund.fund_id) : Promise.resolve(void 0)
78242
78525
  ]);
78243
78526
  const priorCredit = prior ? await deps.ledger.get(creditId) : void 0;
78244
- if (priorCredit?.callerPubkey === callerPubkey || invoice?.callerPubkey === callerPubkey) {
78527
+ if (priorCredit?.callerPubkey === callerPubkey || invoice?.callerPubkey === callerPubkey || checkout?.callerPubkey === callerPubkey && checkout.state !== "creating") {
78245
78528
  return handleFund(c, deps, { callerPubkey, body, envelope, menu });
78246
78529
  }
78247
78530
  return deps.withFundingAdmission(c, body, () => handleFund(c, deps, { callerPubkey, body, envelope, menu }));
@@ -78718,20 +79001,20 @@ var HOSTED_TEMPO_CLOSE_IN_FLIGHT = "Hosted Tempo close already has an original e
78718
79001
  var HostedTempoCloseAttemptsExhaustedError = class extends Error {
78719
79002
  };
78720
79003
  async function reserveHostedTempoClose(reports, mpp, record2, channelId, ledger) {
78721
- const pending = await reports.pendingTempoClose(channelId, record2.drainId);
78722
- if (!pending) {
79004
+ const pending2 = await reports.pendingTempoClose(channelId, record2.drainId);
79005
+ if (!pending2) {
78723
79006
  const reserved = await reports.reserveTempo(channelId, "close", record2.drainId);
78724
79007
  if (reserved.replayed) throw new Error(HOSTED_TEMPO_CLOSE_IN_FLIGHT);
78725
79008
  return reserved.id;
78726
79009
  }
78727
- if (pending.state === "exhausted") throw new HostedTempoCloseAttemptsExhaustedError();
78728
- if (pending.state === "unmatched") throw new Error("Hosted Tempo close report requires an operator retry");
78729
- if (pending.txHash || !mpp.getTempoSessionDrainState) throw new Error(HOSTED_TEMPO_CLOSE_IN_FLIGHT);
79010
+ if (pending2.state === "exhausted") throw new HostedTempoCloseAttemptsExhaustedError();
79011
+ if (pending2.state === "unmatched") throw new Error("Hosted Tempo close report requires an operator retry");
79012
+ if (pending2.txHash || !mpp.getTempoSessionDrainState) throw new Error(HOSTED_TEMPO_CLOSE_IN_FLIGHT);
78730
79013
  const state = await mpp.getTempoSessionDrainState(channelId);
78731
79014
  if (state.finalized || state.deposit === 0n || state.closeRequestedAt !== 0n) {
78732
79015
  throw new Error(HOSTED_TEMPO_CLOSE_IN_FLIGHT);
78733
79016
  }
78734
- const result = await reports.releaseStaleTempoClose(pending.id, channelId, record2.drainId, {
79017
+ const result = await reports.releaseStaleTempoClose(pending2.id, channelId, record2.drainId, {
78735
79018
  staleAfterMs: HOSTED_TEMPO_CLOSE_STALE_MS,
78736
79019
  maxReleases: HOSTED_TEMPO_CLOSE_MAX_RELEASES,
78737
79020
  onExhausted: async (tx) => {
@@ -78744,9 +79027,9 @@ async function reserveHostedTempoClose(reports, mpp, record2, channelId, ledger)
78744
79027
  credit_id: record2.creditId,
78745
79028
  drain_id: record2.drainId,
78746
79029
  channel_id: channelId,
78747
- obligation_id: pending.id,
79030
+ obligation_id: pending2.id,
78748
79031
  attempt: result.releases + 1,
78749
- amount_at_stake_native: await reports.tempoCloseAmountAtStake(pending.id)
79032
+ amount_at_stake_native: await reports.tempoCloseAmountAtStake(pending2.id)
78750
79033
  });
78751
79034
  throw new HostedTempoCloseAttemptsExhaustedError(
78752
79035
  `Tempo drain ${record2.drainId} exhausted its cooperative close attempts`
@@ -78756,17 +79039,17 @@ async function reserveHostedTempoClose(reports, mpp, record2, channelId, ledger)
78756
79039
  credit_id: record2.creditId,
78757
79040
  drain_id: record2.drainId,
78758
79041
  channel_id: channelId,
78759
- obligation_id: pending.id,
79042
+ obligation_id: pending2.id,
78760
79043
  attempt: result.releases + 1
78761
79044
  });
78762
79045
  return result.id;
78763
79046
  }
78764
79047
  function tempoExitRequiredResponse(record2) {
78765
- const terminal = record2.status === "exit_required";
79048
+ const terminal2 = record2.status === "exit_required";
78766
79049
  return jsonPaymentError("tempo_channel_exit_required", 409, {
78767
- message: terminal ? `Tempo drain ${record2.drainId} cannot cooperatively close this channel.` : `This Tempo close credential cannot complete drain ${record2.drainId}.`,
79050
+ message: terminal2 ? `Tempo drain ${record2.drainId} cannot cooperatively close this channel.` : `This Tempo close credential cannot complete drain ${record2.drainId}.`,
78768
79051
  display: "Your funds remain in the channel. Use the timed on-chain exit to recover them.",
78769
- hint: terminal ? "Start the channel's timed on-chain exit. A corrected close credential does not reopen this drain or debit it again." : "This drain remains pending. Use the channel's timed on-chain exit, or retry the same drain with a valid close credential if cooperative attempts remain. Retrying does not debit it again.",
79052
+ hint: terminal2 ? "Start the channel's timed on-chain exit. A corrected close credential does not reopen this drain or debit it again." : "This drain remains pending. Use the channel's timed on-chain exit, or retry the same drain with a valid close credential if cooperative attempts remain. Retrying does not debit it again.",
78770
79053
  extra: {
78771
79054
  drain_registered: true,
78772
79055
  drain_id: record2.drainId,
@@ -78995,14 +79278,14 @@ async function handleX402ChannelDrain(c, deps, args) {
78995
79278
  if (blocking && blocking.effectId !== `${args.credit.creditId}:${args.drainId}`) {
78996
79279
  const rejected2 = await burnNonce(c, deps, args.envelope);
78997
79280
  if (rejected2) return rejected2;
78998
- const pending = x402SettlementPending(args.credit.creditId, blocking);
79281
+ const pending2 = x402SettlementPending(args.credit.creditId, blocking);
78999
79282
  return x402SettlementPendingRefusal({
79000
79283
  door: "drain",
79001
- message: pending.message,
79284
+ message: pending2.message,
79002
79285
  drainId: args.drainId,
79003
79286
  settlementId: blocking.settlementId,
79004
79287
  settlementStatus: blocking.status,
79005
- ...pending.details.blockingDrainId ? { blockingDrainId: pending.details.blockingDrainId } : {}
79288
+ ...pending2.details.blockingDrainId ? { blockingDrainId: pending2.details.blockingDrainId } : {}
79006
79289
  });
79007
79290
  }
79008
79291
  if (!rail.x402Payment) {
@@ -79070,7 +79353,7 @@ async function handleX402ChannelDrain(c, deps, args) {
79070
79353
  return requested;
79071
79354
  },
79072
79355
  complete: async (settlement, requested, tx) => {
79073
- const terminal = await completeX402ChannelDrain({
79356
+ const terminal2 = await completeX402ChannelDrain({
79074
79357
  deps,
79075
79358
  creditId: args.credit.creditId,
79076
79359
  drainId: args.drainId,
@@ -79080,8 +79363,8 @@ async function handleX402ChannelDrain(c, deps, args) {
79080
79363
  transaction: settlement.transaction,
79081
79364
  tx
79082
79365
  });
79083
- terminalReplayed = terminal.replayed;
79084
- return { ...requested, drain: terminal.drain };
79366
+ terminalReplayed = terminal2.replayed;
79367
+ return { ...requested, drain: terminal2.drain };
79085
79368
  }
79086
79369
  });
79087
79370
  if (!accepted.ok && accepted.corrective === false) {
@@ -79142,10 +79425,10 @@ function isX402RefundBoundFailureReason(reason) {
79142
79425
  return reason === "refund_bound_unavailable" || reason === "refund_exceeds_channel_escrow";
79143
79426
  }
79144
79427
  function x402RefundBoundFailureResponse(creditId, reason) {
79145
- const unavailable = reason === "refund_bound_unavailable";
79428
+ const unavailable2 = reason === "refund_bound_unavailable";
79146
79429
  return jsonPaymentError("drain_conflict", 409, {
79147
- message: unavailable ? `credit ${creditId} records no usable x402 token basis to size a cooperative refund.` : `credit ${creditId} cannot be refunded cooperatively because its channel no longer has enough unclaimed escrow.`,
79148
- display: unavailable ? "The service can't safely calculate this cooperative refund. Your x402 channel still has a timed on-chain exit." : "The service can't return this whole balance cooperatively because the x402 channel no longer holds enough unclaimed funds. The timed on-chain exit can still recover whatever remains.",
79430
+ message: unavailable2 ? `credit ${creditId} records no usable x402 token basis to size a cooperative refund.` : `credit ${creditId} cannot be refunded cooperatively because its channel no longer has enough unclaimed escrow.`,
79431
+ display: unavailable2 ? "The service can't safely calculate this cooperative refund. Your x402 channel still has a timed on-chain exit." : "The service can't return this whole balance cooperatively because the x402 channel no longer holds enough unclaimed funds. The timed on-chain exit can still recover whatever remains.",
79149
79432
  hint: "Run 'dvm wallet x402-withdraw-initiate <dvm>' to start the timed on-chain exit. It closes the whole channel position and reports the guaranteed and likely recovery."
79150
79433
  });
79151
79434
  }
@@ -79480,8 +79763,17 @@ async function handleFund(c, deps, args) {
79480
79763
  400
79481
79764
  );
79482
79765
  }
79766
+ if (fund.via !== void 0 && (fund.via !== "checkout" || fund.method !== "stripe")) {
79767
+ return c.json({ error: "invalid_request", message: 'fund.via only accepts "checkout" with method "stripe".' }, 400);
79768
+ }
79769
+ if (fund.via === "checkout" && fund.fund_id.length > 200) {
79770
+ return c.json({ error: "invalid_request", message: "Checkout fund_id must be at most 200 characters.", retryable: false }, 400);
79771
+ }
79772
+ if (fund.via === "checkout" && (fund.commitment !== void 0 || fund.intent !== void 0)) {
79773
+ return c.json({ error: "invalid_request", message: "Checkout carries no commitment or intent; omit both." }, 400);
79774
+ }
79483
79775
  let commitment = "";
79484
- if (fund.method === "lightning") {
79776
+ if (fund.method === "lightning" || fund.via === "checkout") {
79485
79777
  if (fund.commitment !== void 0) {
79486
79778
  return c.json(
79487
79779
  {
@@ -79536,7 +79828,7 @@ async function handleFund(c, deps, args) {
79536
79828
  commitment = fund.commitment;
79537
79829
  }
79538
79830
  const creditId = body.credit_id ?? derivedFundCreditId(args.callerPubkey, fund.fund_id);
79539
- const replayed = await replayedFunding(c, deps, {
79831
+ const replayed = fund.via === "checkout" ? void 0 : await replayedFunding(c, deps, {
79540
79832
  creditId,
79541
79833
  fundId: fund.fund_id,
79542
79834
  callerPubkey: args.callerPubkey,
@@ -79554,7 +79846,7 @@ async function handleFund(c, deps, args) {
79554
79846
  });
79555
79847
  if (outstanding) return outstanding;
79556
79848
  }
79557
- const sizing = await checkSizing(deps, {
79849
+ const sizingCheck = () => checkSizing(deps, {
79558
79850
  callerPubkey: args.callerPubkey,
79559
79851
  creditId,
79560
79852
  named: body.credit_id !== void 0,
@@ -79564,6 +79856,38 @@ async function handleFund(c, deps, args) {
79564
79856
  rail: fund.method,
79565
79857
  tempoIntent: fund.method === "tempo" ? fund.intent : void 0
79566
79858
  });
79859
+ if (fund.via === "checkout") {
79860
+ const rail = deps.stripeCredit?.checkout;
79861
+ if (!rail || !menu.stripe?.checkout) {
79862
+ return c.json({
79863
+ error: "checkout_not_supported",
79864
+ message: "This DVM does not offer hosted card Checkout.",
79865
+ hint: "Use the token path: omit fund.via and attach the shared payment token credential when challenged.",
79866
+ retryable: false
79867
+ }, 409);
79868
+ }
79869
+ const result = await fundStripeCheckout({
79870
+ rail,
79871
+ opts: await deps.railOpts(c),
79872
+ creditId,
79873
+ fundId: fund.fund_id,
79874
+ callerPubkey: args.callerPubkey,
79875
+ amountMicro: fund.amount_micro,
79876
+ productName: deps.checkoutProductName ?? "DVM prepaid credit",
79877
+ preflight: sizingCheck
79878
+ });
79879
+ if (!result.funded) return result.response;
79880
+ if (result.deposit) deps.onDeposit(result.deposit);
79881
+ const rejected2 = await burnNonce(c, deps, args.envelope);
79882
+ if (rejected2) return rejected2;
79883
+ return await replayedFunding(c, deps, {
79884
+ creditId,
79885
+ fundId: fund.fund_id,
79886
+ callerPubkey: args.callerPubkey,
79887
+ replayed: result.replayed
79888
+ }) ?? creditFundingUnrecorded(c, { creditId, fundId: fund.fund_id, requestedMicro: fund.amount_micro });
79889
+ }
79890
+ const sizing = await sizingCheck();
79567
79891
  if (sizing) return sizing;
79568
79892
  if (fund.method === "stripe" && (!menu.stripe || !deps.stripeCredit)) {
79569
79893
  return jsonPaymentError("payment_invalid", 409, {
@@ -79733,12 +80057,12 @@ async function lightningPoll(c, deps, args) {
79733
80057
  });
79734
80058
  }
79735
80059
  if (invoice?.status !== "pending") {
79736
- const terminal = invoice ?? existing;
80060
+ const terminal2 = invoice ?? existing;
79737
80061
  return creditFundingUnrecorded(c, {
79738
80062
  creditId: args.creditId,
79739
80063
  fundId: args.fundId,
79740
- requestedMicro: terminal.amountMicro,
79741
- invoiceStatus: terminal.status
80064
+ requestedMicro: terminal2.amountMicro,
80065
+ invoiceStatus: terminal2.status
79742
80066
  });
79743
80067
  }
79744
80068
  return c.json(
@@ -79996,13 +80320,13 @@ async function checkTargetCredit(deps, args) {
79996
80320
  X402_SPEND_BLOCKING_SETTLEMENT_STATUSES
79997
80321
  );
79998
80322
  if (wedged) {
79999
- const pending = x402SettlementPending(args.creditId, wedged);
80323
+ const pending2 = x402SettlementPending(args.creditId, wedged);
80000
80324
  return x402SettlementPendingRefusal({
80001
80325
  door: "top_up",
80002
- message: pending.message,
80326
+ message: pending2.message,
80003
80327
  settlementId: wedged.settlementId,
80004
80328
  settlementStatus: wedged.status,
80005
- ...pending.details.blockingDrainId ? { blockingDrainId: pending.details.blockingDrainId } : {}
80329
+ ...pending2.details.blockingDrainId ? { blockingDrainId: pending2.details.blockingDrainId } : {}
80006
80330
  });
80007
80331
  }
80008
80332
  if (args.rail === "tempo" && args.tempoIntent) {
@@ -80056,7 +80380,7 @@ async function replayedFunding(c, deps, args) {
80056
80380
  return c.json({
80057
80381
  op: "fund",
80058
80382
  funded_micro: prior.amountMicro,
80059
- replayed: true,
80383
+ replayed: args.replayed ?? true,
80060
80384
  credit: creditBody(credit),
80061
80385
  ...fundingReceipt && { funding_receipt: fundingReceipt }
80062
80386
  });
@@ -80733,7 +81057,7 @@ var TEMPO_CLOSED_EVENT = session_exports.Precompile.escrowAbi.find(
80733
81057
  (item) => item.type === "event" && item.name === "ChannelClosed"
80734
81058
  );
80735
81059
  function hash22(value) {
80736
- return createHash82("sha256").update(JSON.stringify(value)).digest("hex");
81060
+ return createHash9("sha256").update(JSON.stringify(value)).digest("hex");
80737
81061
  }
80738
81062
  function hex3(value, bytes) {
80739
81063
  return typeof value === "string" && new RegExp(`^0x[0-9a-fA-F]{${bytes * 2}}$`).test(value);
@@ -81309,7 +81633,7 @@ var HostedSettlementReportObligations = class {
81309
81633
  }
81310
81634
  async submittedIds(rail, operation, txHash, batchId) {
81311
81635
  if (!hex3(txHash, 32)) throw new Error("Hosted effect has no exact transaction hash");
81312
- const result = await this.pool.query(
81636
+ const result = await poolForX402ShutdownClaim(this.pool).query(
81313
81637
  `SELECT id,original FROM sdk_hosted_settlement_report_obligations
81314
81638
  WHERE dvm_id=$1 AND scope=$2 AND rail=$3 AND operation=$4 AND tx_hash=$5
81315
81639
  ORDER BY source_key`,
@@ -81405,7 +81729,7 @@ var HostedSettlementReportObligations = class {
81405
81729
  FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint)
81406
81730
  ON CONFLICT (scope) DO UPDATE SET scope=EXCLUDED.scope
81407
81731
  RETURNING batch_id`,
81408
- [scope, randomUUID42()]
81732
+ [scope, randomUUID52()]
81409
81733
  );
81410
81734
  return result.rows[0].batch_id;
81411
81735
  }
@@ -81660,13 +81984,13 @@ var HostedSettlementReportObligations = class {
81660
81984
  }
81661
81985
  }
81662
81986
  async acknowledgeDelivered(reportId, tx, requireLinked = true) {
81663
- const pending = await tx.query(
81987
+ const pending2 = await tx.query(
81664
81988
  "SELECT payload FROM pending_dvm_reports WHERE id=$1 AND kind='payout' FOR UPDATE",
81665
81989
  [reportId]
81666
81990
  );
81667
- if (!pending.rows[0]) throw new Error("Hosted payout acknowledgement has no durable outbox row");
81668
- if (pending.rows[0].payload.rail === "x402" || pending.rows[0].payload.rail === "tempo") {
81669
- await this.assertReportReady(reportId, pending.rows[0].payload, tx);
81991
+ if (!pending2.rows[0]) throw new Error("Hosted payout acknowledgement has no durable outbox row");
81992
+ if (pending2.rows[0].payload.rail === "x402" || pending2.rows[0].payload.rail === "tempo") {
81993
+ await this.assertReportReady(reportId, pending2.rows[0].payload, tx);
81670
81994
  }
81671
81995
  const rows2 = await tx.query(
81672
81996
  `UPDATE sdk_hosted_settlement_report_obligations
@@ -81904,7 +82228,7 @@ var HostedSettlementReportObligations = class {
81904
82228
  if (competing.rows.some((row2) => row2.source_key !== sourceKey)) {
81905
82229
  throw new Error("Hosted settlement has another unresolved original effect");
81906
82230
  }
81907
- const id = randomUUID42();
82231
+ const id = randomUUID52();
81908
82232
  const result = await tx.query(
81909
82233
  `INSERT INTO sdk_hosted_settlement_report_obligations
81910
82234
  (id,source_key,dvm_id,scope,instance_id,boot_epoch,rail,operation,network,
@@ -82150,7 +82474,7 @@ async function readHostedChannelSnapshot(query) {
82150
82474
  };
82151
82475
  const x402HistoryComplete = await history(names[6]);
82152
82476
  const tempoHistoryComplete = await history(names[7]);
82153
- const digest = createHash9("sha256").update(JSON.stringify({
82477
+ const digest = createHash10("sha256").update(JSON.stringify({
82154
82478
  present: [...exists].sort(),
82155
82479
  x402,
82156
82480
  x402Tombstones,
@@ -82303,8 +82627,8 @@ var HostedChannelEvidenceReader = class _HostedChannelEvidenceReader {
82303
82627
  for (const row of [...snapshot.x402, ...snapshot.x402Tombstones]) {
82304
82628
  if (!hex22(row.channel_id, 32)) throw new Error("invalid channel");
82305
82629
  if (row.pending_request !== null) {
82306
- const pending2 = row.pending_request;
82307
- const pendingId = pending2 && typeof pending2 === "object" && !Array.isArray(pending2) ? pending2.pendingId : void 0;
82630
+ const pending3 = row.pending_request;
82631
+ const pendingId = pending3 && typeof pending3 === "object" && !Array.isArray(pending3) ? pending3.pendingId : void 0;
82308
82632
  if (!snapshot.x402Tombstones.includes(row) || typeof pendingId !== "string" || !snapshot.x402Settlements.some((settlement) => settlement.channel_id === row.channel_id && settlement.pending_id === pendingId && settlement.status === "complete")) throw new Error("x402 request remains pending");
82309
82633
  }
82310
82634
  const binding = row.hosting_binding;
@@ -82385,8 +82709,8 @@ var HostedChannelEvidenceReader = class _HostedChannelEvidenceReader {
82385
82709
  })
82386
82710
  ]);
82387
82711
  const [balance, claimed] = state;
82388
- const [pending, initiatedAt] = withdrawal;
82389
- if (balance !== claimed || BigInt(pending) !== 0n || initiatedAt !== 0 || claimed !== covered || localNonce > BigInt(refundNonces.length) || nonce !== BigInt(refundNonces.length)) {
82712
+ const [pending2, initiatedAt] = withdrawal;
82713
+ if (balance !== claimed || BigInt(pending2) !== 0n || initiatedAt !== 0 || claimed !== covered || localNonce > BigInt(refundNonces.length) || nonce !== BigInt(refundNonces.length)) {
82390
82714
  throw new Error("x402 balance, original claims, or refunds remain unresolved");
82391
82715
  }
82392
82716
  channels.push(row.channel_id);
@@ -82593,7 +82917,7 @@ var HostingControl = class {
82593
82917
  `UPDATE sdk_hosting_control
82594
82918
  SET instance_id=COALESCE(instance_id,$3), boot_epoch=boot_epoch+1
82595
82919
  WHERE dvm_id=$1 AND scope=$2 RETURNING boot_epoch`,
82596
- [this.dvmId, this.config.scope, randomUUID52()]
82920
+ [this.dvmId, this.config.scope, randomUUID62()]
82597
82921
  );
82598
82922
  if (!boot.rows[0]) throw new Error("Hosting control identity was not initialized");
82599
82923
  this.bootEpoch = Number(boot.rows[0].boot_epoch);
@@ -82737,7 +83061,8 @@ var HostingControl = class {
82737
83061
  "mpp_tempo_charge_replays",
82738
83062
  "sdk_hosted_tempo_charge_intents",
82739
83063
  "sdk_hosted_settlement_report_history",
82740
- "sdk_hosted_settlement_report_obligations"
83064
+ "sdk_hosted_settlement_report_obligations",
83065
+ "stripe_checkout_sessions"
82741
83066
  ];
82742
83067
  const present = await client.query(
82743
83068
  `SELECT name, to_regclass(name) IS NOT NULL AS exists FROM unnest($1::text[]) AS name`,
@@ -82779,13 +83104,21 @@ var HostingControl = class {
82779
83104
  "dvm_id<>$1 OR scope<>$2",
82780
83105
  [this.dvmId, this.config.scope]
82781
83106
  )) reasons.push("historical_admission_owner_unknown");
83107
+ if (await count("stripe_checkout_sessions", "state IN ('creating','open','refunding')")) {
83108
+ reasons.push("checkout_sessions_unresolved");
83109
+ }
82782
83110
  if (exists.has("sdk_hosting_admissions") && exists.has("credit_fundings")) {
82783
83111
  const unbooked = await client.query(
82784
83112
  `SELECT COUNT(*)::text AS n FROM sdk_hosting_admissions a
82785
83113
  WHERE a.dvm_id=$1 AND a.scope=$2 AND a.outcome='accepted'
82786
83114
  AND a.credit_id IS NOT NULL AND a.fund_id IS NOT NULL
82787
83115
  AND NOT EXISTS (SELECT 1 FROM credit_fundings f
82788
- WHERE f.credit_id=a.credit_id AND f.fund_id=a.fund_id)`,
83116
+ WHERE f.credit_id=a.credit_id AND f.fund_id=a.fund_id)
83117
+ ${exists.has("stripe_checkout_sessions") ? `AND NOT EXISTS (
83118
+ SELECT 1 FROM stripe_checkout_sessions s WHERE s.fund_id=a.fund_id
83119
+ AND COALESCE(s.record->>'hostingDvmId',s.record->>'dvmId')=a.dvm_id
83120
+ AND s.record->>'creditId'=a.credit_id AND s.record->>'callerPubkey'=a.caller_pubkey
83121
+ AND s.state IN ('expired','refunded'))` : ""}`,
82789
83122
  [this.dvmId, this.config.scope]
82790
83123
  );
82791
83124
  if (Number(unbooked.rows[0].n)) reasons.push("funding_intents_unbooked");
@@ -83204,7 +83537,7 @@ var HostingControl = class {
83204
83537
  ORDER BY j.id`,
83205
83538
  [this.dvmId]
83206
83539
  );
83207
- const pending = await this.pool.query(
83540
+ const pending2 = await this.pool.query(
83208
83541
  `SELECT COUNT(*) FILTER (WHERE outcome='pending')::text AS pending,
83209
83542
  COUNT(*) FILTER (WHERE outcome='unresolved')::text AS unresolved
83210
83543
  FROM sdk_hosting_admissions WHERE dvm_id=$1 AND scope=$2`,
@@ -83227,9 +83560,9 @@ var HostingControl = class {
83227
83560
  leaseExpiresAtMs: rows2[0].lease_expires_at_ms === null ? null : Number(rows2[0].lease_expires_at_ms),
83228
83561
  activeJobIds: active.rows.map((row) => row.id),
83229
83562
  unownedActiveJobIds: unowned.rows.map((row) => row.id),
83230
- pendingAdmissionCount: Number(pending.rows[0].pending),
83563
+ pendingAdmissionCount: Number(pending2.rows[0].pending),
83231
83564
  pendingAdmissions: inFlight.rows.map((row) => ({ admissionId: row.id, workId: row.job_id })),
83232
- unresolvedAdmissionCount: Number(pending.rows[0].unresolved),
83565
+ unresolvedAdmissionCount: Number(pending2.rows[0].unresolved),
83233
83566
  unresolvedAdmissions: unresolved.rows.map((row) => ({ admissionId: row.id, jobId: row.job_id })),
83234
83567
  jobIdentityHeader: "v1"
83235
83568
  };
@@ -83347,7 +83680,7 @@ function capabilityForChannel(descriptor, name, channel) {
83347
83680
  return map2[name];
83348
83681
  }
83349
83682
  function hashKey(key) {
83350
- return createHash10("sha256").update(key).digest("hex").slice(0, 16);
83683
+ return createHash11("sha256").update(key).digest("hex").slice(0, 16);
83351
83684
  }
83352
83685
  function instrumentKVStore(inner) {
83353
83686
  return {
@@ -83429,7 +83762,7 @@ function buildContext(job, opts) {
83429
83762
  };
83430
83763
  let askInFlight = false;
83431
83764
  const withdrawAsk = () => {
83432
- const pending = job.pendingPayment;
83765
+ const pending2 = job.pendingPayment;
83433
83766
  job.pendingPayment = null;
83434
83767
  job.pendingPaymentMsats = void 0;
83435
83768
  job.pendingPaymentFiatMicro = void 0;
@@ -83437,7 +83770,7 @@ function buildContext(job, opts) {
83437
83770
  job.pendingMppChallengeIds = void 0;
83438
83771
  job.pendingX402Nonce = void 0;
83439
83772
  job.pendingX402AmountUsdcMicro = void 0;
83440
- pending?.reject(new JobCancelledError("The job completed; its open payment request was withdrawn"));
83773
+ pending2?.reject(new JobCancelledError("The job completed; its open payment request was withdrawn"));
83441
83774
  };
83442
83775
  let declaredCostAmount = 0;
83443
83776
  let declaredCostCurrency;
@@ -83902,18 +84235,15 @@ function buildContext(job, opts) {
83902
84235
  providerMessage(job, "complete", { summary });
83903
84236
  runTerminal();
83904
84237
  },
83905
- // `failOpts.refund` is a caller-fault annotation and nothing more
83906
- // No rail hands value backwards: a failed job's debit is the
83907
- // credit draw the terminal funnel releases, and the caller reclaims that
83908
- // balance through the `drain` op. The Cashu branch that used to
83909
- // send proofs back here was dead — `job.receivedProofs` has been empty on
83910
- // every path since the accumulator became the commit boundary for inbound
83911
- // proofs — and the accumulator-debit rewrite that would
83912
- // have revived it, was cancelled as superseded by the ledger.
83913
- fail: (error62) => {
84238
+ // Neither option moves money. No rail hands value backwards: a failed job's
84239
+ // debit is the credit draw the terminal funnel releases, and the caller
84240
+ // reclaims that balance through the `drain` op. `caller_fault` rides the
84241
+ // durable cancel message so a route answering from the stored record, on
84242
+ // any machine, can read it.
84243
+ fail: (error62, failOpts) => {
83914
84244
  if (terminated("fail")) return;
83915
84245
  job.status = "failed";
83916
- providerMessage(job, "cancel", { reason: error62 });
84246
+ providerMessage(job, "cancel", { reason: error62, ...failOpts?.callerFault === true && { caller_fault: true } });
83917
84247
  runTerminal();
83918
84248
  },
83919
84249
  cost: declareCost,
@@ -84938,10 +85268,10 @@ var JobManager = class {
84938
85268
  if (type !== "response" && type !== "payment") {
84939
85269
  return this.dispatchMessageNow(job, type, content);
84940
85270
  }
84941
- const pending = type === "payment" ? job.pendingPayment : job.pendingPrompts.get(content.prompt_id);
85271
+ const pending2 = type === "payment" ? job.pendingPayment : job.pendingPrompts.get(content.prompt_id);
84942
85272
  await this.queueInputResume(job, async () => {
84943
85273
  const current = type === "payment" ? job.pendingPayment : job.pendingPrompts.get(content.prompt_id);
84944
- if (pending && current !== pending) return;
85274
+ if (pending2 && current !== pending2) return;
84945
85275
  return this.dispatchMessageNow(job, type, content);
84946
85276
  });
84947
85277
  }
@@ -84995,9 +85325,9 @@ var JobManager = class {
84995
85325
  tx.release();
84996
85326
  }
84997
85327
  }
84998
- async adoptPaymentMetadata(job, pending) {
85328
+ async adoptPaymentMetadata(job, pending2) {
84999
85329
  const record2 = await this.jobStore.get(job.id);
85000
- if (!record2 || job.pendingPayment !== pending || isTerminal(job.status) || isTerminal(record2.status)) return false;
85330
+ if (!record2 || job.pendingPayment !== pending2 || isTerminal(job.status) || isTerminal(record2.status)) return false;
85001
85331
  job.paidMsats = record2.paidMsats;
85002
85332
  job.pendingPaymentMsats = record2.pendingPaymentMsats;
85003
85333
  job.creditId = record2.creditId;
@@ -85033,18 +85363,18 @@ var JobManager = class {
85033
85363
  const cap = this.getCapability(job.capability, job.channel);
85034
85364
  if (type === "response") {
85035
85365
  const rc = content;
85036
- const pending = job.pendingPrompts.get(rc.prompt_id);
85037
- if (pending) {
85366
+ const pending2 = job.pendingPrompts.get(rc.prompt_id);
85367
+ if (pending2) {
85038
85368
  if (!await this.claimLocalInput(job)) {
85039
85369
  await this.adoptDurableTerminal(job);
85040
85370
  return;
85041
85371
  }
85042
- if (job.pendingPrompts.get(rc.prompt_id) !== pending || isTerminal(job.status)) return;
85372
+ if (job.pendingPrompts.get(rc.prompt_id) !== pending2 || isTerminal(job.status)) return;
85043
85373
  job.pendingPrompts.delete(rc.prompt_id);
85044
85374
  job.status = job.pendingPrompts.size > 0 || job.pendingPayment ? "awaiting-input" : "processing";
85045
85375
  if (job.status === "awaiting-input") await this.persistJob(job);
85046
85376
  this.startIdleTimer(job);
85047
- pending.resolve(rc);
85377
+ pending2.resolve(rc);
85048
85378
  } else if (cap?.onResponse && ctx) {
85049
85379
  this.startIdleTimer(job);
85050
85380
  await cap.onResponse(ctx, rc);
@@ -85486,7 +85816,7 @@ var JobManager = class {
85486
85816
  while (queue?.length) {
85487
85817
  const entry = queue[0];
85488
85818
  if (entry.pending === void 0) entry.pending = job.pendingPayment;
85489
- const { msg, opts, pending } = entry;
85819
+ const { msg, opts, pending: pending2 } = entry;
85490
85820
  let stored;
85491
85821
  try {
85492
85822
  stored = await store.appendOutgoing(job.id, {
@@ -85501,8 +85831,8 @@ var JobManager = class {
85501
85831
  await this.adoptDurableTerminal(job);
85502
85832
  return;
85503
85833
  }
85504
- if (msg.type === "payment-request" && pending && job.pendingPayment === pending) {
85505
- this.paymentAskSeqs.set(pending, stored);
85834
+ if (msg.type === "payment-request" && pending2 && job.pendingPayment === pending2) {
85835
+ this.paymentAskSeqs.set(pending2, stored);
85506
85836
  }
85507
85837
  queue.shift();
85508
85838
  }
@@ -86347,12 +86677,12 @@ var JobManager = class {
86347
86677
  content: msgContent
86348
86678
  };
86349
86679
  if (msgType === "payment") {
86350
- let pending = this.pendingPaymentMessages.get(job);
86351
- if (!pending) {
86352
- pending = /* @__PURE__ */ new Map();
86353
- this.pendingPaymentMessages.set(job, pending);
86680
+ let pending2 = this.pendingPaymentMessages.get(job);
86681
+ if (!pending2) {
86682
+ pending2 = /* @__PURE__ */ new Map();
86683
+ this.pendingPaymentMessages.set(job, pending2);
86354
86684
  }
86355
- pending.set(txSeq ?? msgContent, message);
86685
+ pending2.set(txSeq ?? msgContent, message);
86356
86686
  if (disposition) {
86357
86687
  let dispositions = this.paymentDispositions.get(job);
86358
86688
  if (!dispositions) this.paymentDispositions.set(job, dispositions = /* @__PURE__ */ new Map());
@@ -86471,9 +86801,9 @@ var JobManager = class {
86471
86801
  * 500. See `creditInbound`.
86472
86802
  */
86473
86803
  async processPayment(job, body, inboundSeq, extra) {
86474
- const pending = this.pendingPaymentMessages.get(job);
86804
+ const pending2 = this.pendingPaymentMessages.get(job);
86475
86805
  const key = inboundSeq ?? body.content;
86476
- const message = pending?.get(key);
86806
+ const message = pending2?.get(key);
86477
86807
  const disposition = this.paymentDispositions.get(job)?.get(key) ?? decidePaymentDisposition({
86478
86808
  status: job.status,
86479
86809
  pendingPaymentMsats: job.pendingPaymentMsats,
@@ -86483,7 +86813,7 @@ var JobManager = class {
86483
86813
  let accepted;
86484
86814
  try {
86485
86815
  const outcome = await this.processPaymentAndCredit(job, body, inboundSeq, disposition, extra);
86486
- if (!outcome.error && !outcome.landedAsBalance && message && pending?.get(key) === message) {
86816
+ if (!outcome.error && !outcome.landedAsBalance && message && pending2?.get(key) === message) {
86487
86817
  accepted = message;
86488
86818
  }
86489
86819
  return outcome;
@@ -86493,7 +86823,7 @@ var JobManager = class {
86493
86823
  }
86494
86824
  throw error62;
86495
86825
  } finally {
86496
- pending?.delete(key);
86826
+ pending2?.delete(key);
86497
86827
  if (message) releaseJobHistory(job, message.seq, accepted);
86498
86828
  }
86499
86829
  }
@@ -87021,14 +87351,14 @@ var JobManager = class {
87021
87351
  creditRail: this.opts.creditLedger ? () => this.payableCreditRail(job) : void 0,
87022
87352
  pricingCurrency: this.pricingCurrency,
87023
87353
  claimForProcessing: isStreamableJobStore(jobStore) ? (resume) => {
87024
- const pending = job.pendingPayment;
87354
+ const pending2 = job.pendingPayment;
87025
87355
  return this.queueInputResume(job, async () => {
87026
- if (!pending || job.pendingPayment !== pending || isTerminal(job.status)) return false;
87356
+ if (!pending2 || job.pendingPayment !== pending2 || isTerminal(job.status)) return false;
87027
87357
  if (!await this.claimLocalInput(job)) return false;
87028
- if (job.pendingPayment !== pending || isTerminal(job.status)) return false;
87358
+ if (job.pendingPayment !== pending2 || isTerminal(job.status)) return false;
87029
87359
  let resumed = false;
87030
87360
  await this.resumeClaimedPayment(job, async () => {
87031
- if (!await this.adoptPaymentMetadata(job, pending)) return;
87361
+ if (!await this.adoptPaymentMetadata(job, pending2)) return;
87032
87362
  await resume?.();
87033
87363
  resumed = true;
87034
87364
  });
@@ -88646,18 +88976,38 @@ function waitForInlineResult(store, jobId, localJob, seconds, signal) {
88646
88976
  });
88647
88977
  }
88648
88978
  var INLINE_RESULT_MESSAGES_MAX_BYTES = 1048576;
88979
+ var INLINE_RESULT_MESSAGES_PAGE_SIZE = 16;
88649
88980
  async function inlineResultMessages(store, job) {
88650
88981
  if (!job.messages.some((message) => message.type === "artifact")) return void 0;
88651
88982
  return boundedResultMessages(store, job);
88652
88983
  }
88653
88984
  async function boundedResultMessages(store, job) {
88654
88985
  if (job.status !== "completed" || job.redactedAt !== void 0) return void 0;
88655
- let messages = job.messages.filter((message) => message.seq > 0);
88986
+ const messages = [];
88987
+ let bytes = 2;
88988
+ const append = (message) => {
88989
+ bytes += (messages.length > 0 ? 1 : 0) + Buffer.byteLength(JSON.stringify(message), "utf8");
88990
+ if (bytes > INLINE_RESULT_MESSAGES_MAX_BYTES) return false;
88991
+ messages.push(message);
88992
+ return true;
88993
+ };
88656
88994
  if (isStreamableJobStore(store)) {
88657
- const durable = await store.getMessages(job.id, 0, { includeHeld: true });
88658
- if (durable.length > 0) messages = durable;
88995
+ let afterSeq = 0;
88996
+ for (; ; ) {
88997
+ const page = await store.getMessages(job.id, afterSeq, {
88998
+ includeHeld: true,
88999
+ limit: INLINE_RESULT_MESSAGES_PAGE_SIZE
89000
+ });
89001
+ for (const message of page) if (!append(message)) return void 0;
89002
+ if (page.length < INLINE_RESULT_MESSAGES_PAGE_SIZE) break;
89003
+ afterSeq = page[page.length - 1].seq;
89004
+ }
89005
+ if (messages.length > 0) return messages;
89006
+ }
89007
+ for (const message of job.messages) {
89008
+ if (message.seq > 0 && !append(message)) return void 0;
88659
89009
  }
88660
- return Buffer.byteLength(JSON.stringify(messages), "utf8") <= INLINE_RESULT_MESSAGES_MAX_BYTES ? messages : void 0;
89010
+ return messages;
88661
89011
  }
88662
89012
  async function withJobReadAvailability(read) {
88663
89013
  try {
@@ -88722,7 +89072,7 @@ async function commitBalancePayment(args) {
88722
89072
  args.auth.recheckSignature(BALANCE_PAYMENT_SCHEMA, args.raw, args.domain);
88723
89073
  const auth = BALANCE_PAYMENT_SCHEMA.parse(args.raw);
88724
89074
  const { pubkey, credit_id, draw_id, payment_id, request_seq, amount_micro, currency } = auth;
88725
- const fingerprint = createHash11("sha256").update(JSON.stringify([
89075
+ const fingerprint = createHash12("sha256").update(JSON.stringify([
88726
89076
  args.domain,
88727
89077
  args.jobId,
88728
89078
  pubkey,
@@ -89092,8 +89442,8 @@ async function requireAuth(c, opts) {
89092
89442
  async function handlePendingDrains(c, opts) {
89093
89443
  const auth = await requireAuth(c, opts);
89094
89444
  if ("response" in auth) return auth.response;
89095
- const pending = await opts.ledger.listPendingDrains();
89096
- const needsRate = pending.some((d) => d.method === "cashu" && d.owedSats === null);
89445
+ const pending2 = await opts.ledger.listPendingDrains();
89446
+ const needsRate = pending2.some((d) => d.method === "cashu" && d.owedSats === null);
89097
89447
  let rateFor = () => 0;
89098
89448
  if (needsRate) {
89099
89449
  try {
@@ -89109,7 +89459,7 @@ async function handlePendingDrains(c, opts) {
89109
89459
  );
89110
89460
  }
89111
89461
  }
89112
- const drains = pending.map((d) => {
89462
+ const drains = pending2.map((d) => {
89113
89463
  const automatic = d.method === "cashu";
89114
89464
  const amountSats = !automatic ? null : d.owedSats ?? netOwedSats(fiatToSatsCeil(d.amountMicro / 1e6, rateFor(d.currency)));
89115
89465
  const settlement = automatic ? "automatic" : d.method === "stripe" ? "card" : d.channelId === null ? "manual" : "channel";
@@ -89136,7 +89486,7 @@ async function handlePendingDrains(c, opts) {
89136
89486
  const liability = {
89137
89487
  cashu_sats: drains.filter((d) => d.method === "cashu").reduce((sum2, d) => sum2 + (d.amount_sats ?? 0), 0),
89138
89488
  by_method_micro: DRAIN_METHODS.reduce((acc, method) => {
89139
- acc[method] = pending.filter((d) => d.method === method).reduce((sum2, d) => sum2 + d.amountMicro, 0);
89489
+ acc[method] = pending2.filter((d) => d.method === method).reduce((sum2, d) => sum2 + d.amountMicro, 0);
89140
89490
  return acc;
89141
89491
  }, {}),
89142
89492
  manual_micro: drains.filter((d) => d.settlement === "manual").reduce((sum2, d) => sum2 + d.amount_micro, 0),
@@ -89149,8 +89499,8 @@ async function handleBitcoinLiability(c, opts) {
89149
89499
  const auth = await requireAuth(c, opts);
89150
89500
  if ("response" in auth) return auth.response;
89151
89501
  const deposit = await opts.ledger.bitcoinDepositLiability();
89152
- const pending = await opts.ledger.listPendingDrains();
89153
- const promised = pending.filter((d) => d.method === "cashu" && d.status === "pending");
89502
+ const pending2 = await opts.ledger.listPendingDrains();
89503
+ const promised = pending2.filter((d) => d.method === "cashu" && d.status === "pending");
89154
89504
  const drainSats = promised.reduce((sum2, d) => sum2 + (d.owedSats ?? 0), 0);
89155
89505
  const drainsUnpriced = promised.filter((d) => d.owedSats === null).length;
89156
89506
  return c.json({
@@ -89828,7 +90178,7 @@ async function handleReconcileX402(c, opts) {
89828
90178
  return requested;
89829
90179
  },
89830
90180
  complete: async (evidence, requested, tx) => {
89831
- const terminal = await completeX402ChannelDrain({
90181
+ const terminal2 = await completeX402ChannelDrain({
89832
90182
  deps: {
89833
90183
  ledger: opts.ledger,
89834
90184
  drainReport: {
@@ -89846,7 +90196,7 @@ async function handleReconcileX402(c, opts) {
89846
90196
  repaired: true,
89847
90197
  tx
89848
90198
  });
89849
- return { ...requested, drain: terminal.drain };
90199
+ return { ...requested, drain: terminal2.drain };
89850
90200
  }
89851
90201
  });
89852
90202
  } catch (err) {
@@ -91022,6 +91372,127 @@ function callerFacingRequestUrl(requestUrl, publicOrigin) {
91022
91372
  const request = new URL(requestUrl);
91023
91373
  return `${publicOrigin}${request.pathname}${request.search}`;
91024
91374
  }
91375
+ var CHECKOUT_ABANDONED_AFTER_MS = 24 * 60 * 60 * 1e3;
91376
+ var CHECKOUT_RECOVERY_BACKOFF_MS = 60 * 60 * 1e3;
91377
+ async function refundAbandonedCheckouts(rail, stripe, nowMs, limit) {
91378
+ const refunded = [];
91379
+ for (const fundId of await rail.store.listRecoverable(nowMs, limit)) {
91380
+ let token;
91381
+ let sessionId;
91382
+ try {
91383
+ const snapshot = await rail.store.get(fundId);
91384
+ if (!snapshot || ["booked", "expired", "refunded"].includes(snapshot.state)) continue;
91385
+ if (snapshot.state === "creating" && !snapshot.sessionId) {
91386
+ if (nowMs >= snapshot.createdAt + CHECKOUT_CREATE_WINDOW_MS) await expireUnshownCheckout(rail, fundId, nowMs);
91387
+ continue;
91388
+ }
91389
+ if (!snapshot.sessionId) throw new Error("Checkout session id missing");
91390
+ sessionId = snapshot.sessionId;
91391
+ const session = await rail.api.retrieve(sessionId);
91392
+ if (session.id !== snapshot.sessionId || !checkoutMatches(session, snapshot)) throw new Error("Checkout recovery binding mismatch");
91393
+ const claimToken = randomUUID72();
91394
+ const claim2 = await withCheckoutInternalLock(rail.store, fundId, async (locked) => {
91395
+ const record2 = locked.record;
91396
+ if (!["open", "refunding"].includes(record2.state) || (record2.leaseUntil ?? 0) > nowMs) return;
91397
+ if (record2.sessionId !== session.id) throw new Error("Checkout recovery session mismatch");
91398
+ const nextRecoveryAt = Math.max(nowMs + CHECKOUT_RECOVERY_BACKOFF_MS, record2.createdAt + CHECKOUT_ABANDONED_AFTER_MS);
91399
+ if (session.payment_status !== "paid") {
91400
+ await locked.transition(
91401
+ record2.state,
91402
+ session.status === "expired" && record2.state === "open" ? "expired" : record2.state,
91403
+ void 0,
91404
+ { nextRecoveryAt: nowMs + CHECKOUT_RECOVERY_BACKOFF_MS }
91405
+ );
91406
+ return;
91407
+ }
91408
+ if (!paidCheckoutMatches(session, record2)) throw new Error("Checkout recovery payment mismatch");
91409
+ if (nowMs < record2.createdAt + CHECKOUT_ABANDONED_AFTER_MS) {
91410
+ await locked.transition(record2.state, record2.state, void 0, { nextRecoveryAt });
91411
+ return;
91412
+ }
91413
+ await locked.transition(record2.state, "refunding", void 0, {
91414
+ leaseToken: claimToken,
91415
+ leaseUntil: nowMs + CHECKOUT_LEASE_MS,
91416
+ nextRecoveryAt
91417
+ });
91418
+ return { id: session.payment_intent.id, amount: record2.amountMicro / 1e4 };
91419
+ });
91420
+ if (!claim2) continue;
91421
+ token = claimToken;
91422
+ const charge = await stripe.retrieveCharge(claim2.id);
91423
+ if (charge.amount !== claim2.amount || charge.currency !== "usd" || charge.status !== "succeeded") {
91424
+ throw new Error("Checkout refund charge mismatch");
91425
+ }
91426
+ let lostDisputeAmount = 0;
91427
+ if (charge.disputed) {
91428
+ const page = await stripe.listDisputesForPaymentIntent(claim2.id);
91429
+ if (page.hasMore || !page.disputes.length || page.disputes.some((d) => d.paymentIntentId !== claim2.id)) {
91430
+ throw new Error("Checkout dispute evidence incomplete");
91431
+ }
91432
+ if (!page.disputes.every((d) => d.status === "lost" || ["won", "warning_closed", "prevented"].includes(d.status))) {
91433
+ throw new Error("Checkout dispute remains open");
91434
+ }
91435
+ for (const dispute of page.disputes.filter((d) => d.status === "lost")) {
91436
+ if (dispute.amount === void 0 || !Number.isSafeInteger(dispute.amount) || dispute.amount < 0) {
91437
+ throw new Error("Checkout lost dispute amount missing");
91438
+ }
91439
+ lostDisputeAmount += dispute.amount;
91440
+ }
91441
+ if (!Number.isSafeInteger(lostDisputeAmount)) throw new Error("Checkout lost dispute amount overflow");
91442
+ }
91443
+ const owed = claim2.amount - charge.amountRefunded - lostDisputeAmount;
91444
+ if (lostDisputeAmount >= claim2.amount) {
91445
+ if (await finishRecovery(rail, fundId, token, "dispute_lost")) {
91446
+ diagnosticConsole.warn({ event: "card_checkout_dispute_lost", session_id: sessionId, payment_intent: claim2.id });
91447
+ }
91448
+ continue;
91449
+ }
91450
+ if (owed > 0) {
91451
+ const refunds = (await stripe.listRefunds(claim2.id)).filter((r) => r.metadata.dvmkit_checkout_fund_id === fundId);
91452
+ if (refunds.some((r) => r.status !== "succeeded" && r.status !== "failed" && r.status !== "canceled")) continue;
91453
+ const refund = await stripe.createRefund({
91454
+ paymentIntentId: claim2.id,
91455
+ amount: owed,
91456
+ idempotencyKey: `dvmkit-checkout-refund-${claim2.id}`,
91457
+ metadata: { dvmkit_checkout_fund_id: fundId }
91458
+ });
91459
+ if (refund.status !== "succeeded" || refund.amount !== owed || refund.paymentIntentId !== claim2.id) continue;
91460
+ }
91461
+ const completed = await finishRecovery(rail, fundId, token, "refunded");
91462
+ if (completed) refunded.push(claim2.id);
91463
+ } catch (error62) {
91464
+ if (error62?.code !== "55P03") {
91465
+ await withCheckoutInternalLock(rail.store, fundId, async (locked) => {
91466
+ if (!["open", "refunding"].includes(locked.record.state)) return;
91467
+ if (locked.record.leaseToken && locked.record.leaseToken !== token) return;
91468
+ await locked.transition(locked.record.state, locked.record.state, void 0, { nextRecoveryAt: nowMs + CHECKOUT_RECOVERY_BACKOFF_MS });
91469
+ }).catch(() => {
91470
+ });
91471
+ const event = error62 instanceof StripeCheckoutError && error62.status === 403 ? "card_checkout_session_permission_denied" : error62 instanceof StripeCheckoutError && error62.status === 404 ? "card_checkout_session_missing" : "card_checkout_recovery_deferred";
91472
+ diagnosticConsole.warn({ event, session_id: sessionId, retry_after_ms: CHECKOUT_RECOVERY_BACKOFF_MS });
91473
+ }
91474
+ } finally {
91475
+ if (token) await withCheckoutInternalLock(rail.store, fundId, async (locked) => {
91476
+ if (locked.record.state === "refunding" && locked.record.leaseToken === token) {
91477
+ await locked.transition("refunding", "refunding", void 0, { leaseToken: void 0, leaseUntil: void 0 });
91478
+ }
91479
+ }).catch(() => {
91480
+ });
91481
+ }
91482
+ }
91483
+ return refunded;
91484
+ }
91485
+ async function finishRecovery(rail, fundId, token, outcome) {
91486
+ return withCheckoutInternalLock(rail.store, fundId, async (locked) => {
91487
+ if (locked.record.state !== "refunding" || locked.record.leaseToken !== token) return false;
91488
+ await locked.transition("refunding", outcome === "dispute_lost" ? "expired" : "refunded", void 0, {
91489
+ leaseToken: void 0,
91490
+ leaseUntil: void 0,
91491
+ terminalReason: outcome === "dispute_lost" ? "dispute_lost" : void 0
91492
+ });
91493
+ return true;
91494
+ });
91495
+ }
91025
91496
  var DISPUTE_LOOKBACK_MS = 180 * 24 * 60 * 60 * 1e3;
91026
91497
  var MAX_DISPUTE_PAGES = 10;
91027
91498
  var DISPUTE_SETTLED_FOR_MERCHANT = /* @__PURE__ */ new Set(["won", "warning_closed"]);
@@ -91070,10 +91541,10 @@ async function runCardRefundSweep(deps, opts = {}) {
91070
91541
  });
91071
91542
  }
91072
91543
  await step("retry", async () => {
91073
- const pending = (await deps.ledger.listPendingDrains()).filter(
91544
+ const pending2 = (await deps.ledger.listPendingDrains()).filter(
91074
91545
  (drain) => drain.method === "stripe" && drain.status === "pending"
91075
91546
  );
91076
- for (const drain of pending.slice(0, limit)) {
91547
+ for (const drain of pending2.slice(0, limit)) {
91077
91548
  try {
91078
91549
  const { drain: after } = await runStripeDrain(legDeps, drain);
91079
91550
  (after.status === "sent" ? result.completed : after.status === "refund_blocked" ? result.blocked : result.pending).push(
@@ -91090,6 +91561,11 @@ async function runCardRefundSweep(deps, opts = {}) {
91090
91561
  result.strandedRefunds = await refundStranded(deps, journal2, nowMs, limit);
91091
91562
  });
91092
91563
  }
91564
+ if (deps.checkout) {
91565
+ await step("checkout", async () => {
91566
+ result.strandedRefunds.push(...await refundAbandonedCheckouts(deps.checkout, deps.stripe, nowMs, limit));
91567
+ });
91568
+ }
91093
91569
  return result;
91094
91570
  }
91095
91571
  function startCardRefundSweep(deps, opts = {}) {
@@ -92226,7 +92702,7 @@ function requestFingerprint(req, opts) {
92226
92702
  params: req.params ?? {},
92227
92703
  data: opts.stripAuthEnvelope ? stripEnvelope(req.data) : req.data
92228
92704
  });
92229
- return createHash12("sha256").update(canonical).digest("hex");
92705
+ return createHash13("sha256").update(canonical).digest("hex");
92230
92706
  }
92231
92707
  var ENVELOPE_KEYS = /* @__PURE__ */ new Set(["pubkey", "signature", "timestamp", "nonce", "auth_statement"]);
92232
92708
  function stripEnvelope(data) {
@@ -92245,22 +92721,25 @@ function assertX402RoutesServable(descriptor, server) {
92245
92721
  if (!first) return;
92246
92722
  const at2 = `createDVMServer: capability "${first.name}" is offered on x402`;
92247
92723
  const { x402Config, paymentMethods } = server;
92248
- if (!x402Config) {
92249
- throw new Error(`${at2} but the server has no x402 configuration; set DVMConfig.x402 or the host's x402 option`);
92250
- }
92251
92724
  if (paymentMethods !== void 0 && !paymentMethods.includes("x402")) {
92252
92725
  throw new Error(
92253
92726
  `${at2} but paymentMethods (${JSON.stringify(paymentMethods)}) leaves out "x402"; add "x402" to paymentMethods or stop offering the capability on x402`
92254
92727
  );
92255
92728
  }
92729
+ if (!x402Config && descriptor.x402) {
92730
+ throw new Error(
92731
+ `${at2} and DVMConfig.x402 is set, but the server was given no x402 configuration; pass the x402 option to createDVMServer, or mount the DVM on createDVMHost, which passes it through`
92732
+ );
92733
+ }
92256
92734
  if (!server.publicOrigin && !server.devMode) {
92257
92735
  throw new Error(
92258
92736
  `${at2} but DVMKIT_PUBLIC_URL is unset or not an http or https URL; set it to the origin callers reach this DVM at, such as https://dvm.example.com, since each x402 payment names that address as its resource`
92259
92737
  );
92260
92738
  }
92261
92739
  if (server.responseLimitMs !== void 0) {
92262
- assertX402DeadlinesFit(definitions, x402Config, server.responseLimitMs, server.devMode);
92740
+ assertX402DeadlinesFit(definitions, x402Config?.facilitatorTimeoutMs, server.responseLimitMs, server.devMode);
92263
92741
  }
92742
+ if (!x402Config) return;
92264
92743
  for (const def of definitions) {
92265
92744
  const price = typeof def.price === "string" ? priceFiatMicro({ price: def.price }) : void 0;
92266
92745
  const required2 = x402ChannelPaymentRequired({
@@ -92294,8 +92773,8 @@ function parseX402ResponseLimitMs(value) {
92294
92773
  }
92295
92774
  return limit;
92296
92775
  }
92297
- function assertX402DeadlinesFit(definitions, x402Config, limitMs, devMode) {
92298
- const facilitatorTimeoutMs = x402Config.facilitatorTimeoutMs ?? X402_DEFAULT_FACILITATOR_TIMEOUT_MS;
92776
+ function assertX402DeadlinesFit(definitions, configuredTimeoutMs, limitMs, devMode) {
92777
+ const facilitatorTimeoutMs = configuredTimeoutMs ?? X402_DEFAULT_FACILITATOR_TIMEOUT_MS;
92299
92778
  for (const def of definitions) {
92300
92779
  if (def.maxRuntimeSeconds === void 0) continue;
92301
92780
  const deadlineMs = def.maxRuntimeSeconds * 1e3 + facilitatorTimeoutMs;
@@ -92369,6 +92848,12 @@ function classifyX402RouteOutcome(args) {
92369
92848
  return "unknown";
92370
92849
  }
92371
92850
  }
92851
+ function x402FailedJobAnswer(messages) {
92852
+ const cancel = messages.findLast((message) => message.type === "cancel");
92853
+ if (cancel?.type !== "cancel") return { status: 500 };
92854
+ const callerFault = cancel.from === "provider" && cancel.content.caller_fault === true;
92855
+ return { reason: cancel.content.reason, status: callerFault ? 422 : 500 };
92856
+ }
92372
92857
  function chargedSettleResponse(intent) {
92373
92858
  const stored = callerSettleResponse(intent.settleResponse);
92374
92859
  return {
@@ -92521,7 +93006,7 @@ async function createDVMServer(descriptor, opts) {
92521
93006
  }
92522
93007
  }
92523
93008
  if (!opts.onJobCompleted && platformToken && platformUrl && dvmId && opts.db) {
92524
- const { RevenueReporter: RevenueReporter2 } = await import("./revenue-reporter-2U55YH2I-EUB6PBRN.js");
93009
+ const { RevenueReporter: RevenueReporter2 } = await import("./revenue-reporter-4XV3OO5O-RYHS3M34.js");
92525
93010
  const reporter = new RevenueReporter2(
92526
93011
  opts.db,
92527
93012
  platformUrl,
@@ -92531,7 +93016,7 @@ async function createDVMServer(descriptor, opts) {
92531
93016
  revenueReporter = reporter;
92532
93017
  await reporter.init();
92533
93018
  reporter.startRetryLoop();
92534
- const { MemoryX402BatchStore, PayoutReporter: PayoutReporter2 } = await import("./payout-reporter-F5LFV5W4-EJ7E5ALO.js");
93019
+ const { MemoryX402BatchStore, PayoutReporter: PayoutReporter2 } = await import("./payout-reporter-5PH53T44-7IA4NGIN.js");
92535
93020
  payoutReporter = new PayoutReporter2({
92536
93021
  dvmId,
92537
93022
  db: opts.db,
@@ -92636,7 +93121,7 @@ async function createDVMServer(descriptor, opts) {
92636
93121
  await x402ChannelStorage.init();
92637
93122
  creditLedger.useX402SettlementGate?.(x402ChannelStorage);
92638
93123
  }
92639
- const x402BatchSettlementFactory = x402Config && effectiveX402BatchConfig ? () => createX402BatchSettlementServer({
93124
+ const x402BatchSettlementFactory = x402Config && effectiveX402BatchConfig ? () => x402ShutdownClaimEnvironment.run(opts.env, () => createX402BatchSettlementServer({
92640
93125
  channelStorage: x402ChannelStorage,
92641
93126
  network: x402Config.network,
92642
93127
  payTo: x402Config.payTo,
@@ -92649,7 +93134,7 @@ async function createDVMServer(descriptor, opts) {
92649
93134
  supportedResponse: selfRelayEnabled ? void 0 : opts.x402FacilitatorHealth?.supportedResponse?.(),
92650
93135
  payout: payoutReporter?.x402Observer(),
92651
93136
  hostedObligations: hostedSettlementReports
92652
- }) : void 0;
93137
+ })) : void 0;
92653
93138
  x402BatchSettlement = x402BatchSettlementFactory && (bootX402Support?.batchSettlement || selfRelayEnabled) ? await x402BatchSettlementFactory() : void 0;
92654
93139
  const x402ExactStore = x402Config && opts.db && typeof opts.db.connect === "function" ? new PostgresX402ExactSettlementStore(opts.db) : void 0;
92655
93140
  await x402ExactStore?.init();
@@ -92744,7 +93229,8 @@ async function createDVMServer(descriptor, opts) {
92744
93229
  stripe: opts.stripeCredit.refunds,
92745
93230
  drainReport: { db: opts.db, dvmId, enqueueCreditDrain },
92746
93231
  ...server.drainReceiptIssuer && { receiptIssuer: server.drainReceiptIssuer },
92747
- ...opts.stripeCredit.chargeJournal && { journal: opts.stripeCredit.chargeJournal }
93232
+ ...opts.stripeCredit.chargeJournal && { journal: opts.stripeCredit.chargeJournal },
93233
+ checkout: opts.stripeCredit.checkout
92748
93234
  },
92749
93235
  opts.creditExpirySweep
92750
93236
  );
@@ -92816,6 +93302,14 @@ var DVMServer = class {
92816
93302
  undeclareSessionCapability;
92817
93303
  hostingSweepTimer;
92818
93304
  diagnosticCapabilityAuthority;
93305
+ /**
93306
+ * Capabilities are offered on x402 but no rail reached this server, as when
93307
+ * the account routes no payouts to the x402 network. The server still
93308
+ * starts: an optional payment channel must not take the DVM's other
93309
+ * capabilities and rails down with it, so the x402 routes refuse and
93310
+ * `/v1/info` leaves them out.
93311
+ */
93312
+ x402RailMissing;
92819
93313
  constructor(descriptor, opts) {
92820
93314
  this.descriptor = descriptor;
92821
93315
  this.diagnosticCapabilityAuthority = createDiagnosticCapabilityAuthority([
@@ -92842,6 +93336,8 @@ var DVMServer = class {
92842
93336
  );
92843
93337
  }
92844
93338
  assertCapabilityRates(descriptor.capabilities);
93339
+ const x402Names = Object.keys(descriptor.x402Capabilities ?? {});
93340
+ this.x402RailMissing = x402Names.length > 0 && !opts.x402;
92845
93341
  assertX402RoutesServable(descriptor, {
92846
93342
  x402Config: opts.x402,
92847
93343
  paymentMethods: opts.paymentMethods,
@@ -92850,7 +93346,7 @@ var DVMServer = class {
92850
93346
  devMode: opts.devMode,
92851
93347
  responseLimitMs: parseX402ResponseLimitMs(opts.env.DVMKIT_X402_RESPONSE_LIMIT_MS)
92852
93348
  });
92853
- if (!this.publicOrigin && Object.keys(descriptor.x402Capabilities ?? {}).length > 0) {
93349
+ if (!this.publicOrigin && x402Names.length > 0 && !this.x402RailMissing) {
92854
93350
  diagnosticConsole.warn({ level: "warn", event: "x402_route_origin_from_request" });
92855
93351
  }
92856
93352
  if (opts.mintHealthTracker) {
@@ -92926,9 +93422,17 @@ var DVMServer = class {
92926
93422
  pricingCurrency: this.pricingCurrency,
92927
93423
  dualServe: opts.x402?.dualServe ?? true
92928
93424
  })) {
93425
+ if (this.x402RailMissing && reason.event !== "x402_route_currency_unsupported") continue;
92929
93426
  if (!opts.devMode) throw new Error(reason.message);
92930
93427
  diagnosticConsole.warn({ level: "warn", event: reason.event });
92931
93428
  }
93429
+ if (this.x402RailMissing) {
93430
+ diagnosticConsole.warn(bindDiagnosticCapabilityAuthority({
93431
+ level: "warn",
93432
+ event: "x402_rail_missing",
93433
+ capabilities: x402Names
93434
+ }, this.diagnosticCapabilityAuthority));
93435
+ }
92932
93436
  this.jobManager = new JobManager(descriptor, {
92933
93437
  deferredX402: this.deferredX402,
92934
93438
  receiptIssuer: this.receiptIssuer,
@@ -93113,7 +93617,7 @@ var DVMServer = class {
93113
93617
  const raw2 = c.req.header("traceparent");
93114
93618
  const parsed = raw2 ? parseTraceparent(raw2) : null;
93115
93619
  const traceCtx = {
93116
- traceId: parsed ? parsed.traceId : randomUUID62().replace(/-/g, ""),
93620
+ traceId: parsed ? parsed.traceId : randomUUID8().replace(/-/g, ""),
93117
93621
  spanId: parsed ? parsed.parentSpanId : null,
93118
93622
  dimensions: {},
93119
93623
  service: `isolate-${dvmSlug}`,
@@ -93128,8 +93632,8 @@ var DVMServer = class {
93128
93632
  });
93129
93633
  this.app.use("*", clientCompatibilityMiddleware());
93130
93634
  this.app.use("*", async (c, next) => {
93131
- if (c.req.path === "/health" || c.req.path === "/healthz" || c.req.path.startsWith("/_"))
93132
- return next();
93635
+ const route = c.req.path.slice(mountPrefix(c).length) || "/";
93636
+ if (route === "/health" || route === "/healthz" || route.startsWith("/_")) return next();
93133
93637
  let statusCode = 200;
93134
93638
  let errorCode;
93135
93639
  let errorMsg;
@@ -93140,7 +93644,7 @@ var DVMServer = class {
93140
93644
  name: "dvm.request",
93141
93645
  attrs: {
93142
93646
  "http.method": c.req.method,
93143
- "http.route": c.req.path,
93647
+ "http.route": route,
93144
93648
  ...clientCompatibilityAttributes(
93145
93649
  c.get("clientCompatibility") ?? {
93146
93650
  capabilities: [],
@@ -93158,7 +93662,9 @@ var DVMServer = class {
93158
93662
  status: "error",
93159
93663
  errorMessage: errorMsg ?? `HTTP ${statusCode}`,
93160
93664
  attrs,
93161
- ...probe ? { level: "warn" } : {}
93665
+ // A DVM with no x402 rail refusing its x402 route is expected
93666
+ // configuration, not a fault.
93667
+ ...probe || this.x402RailMissing && errorCode === "x402_not_offered" ? { level: "warn" } : {}
93162
93668
  };
93163
93669
  }
93164
93670
  return { attrs };
@@ -93528,7 +94034,7 @@ var DVMServer = class {
93528
94034
  const dvmId = this.opts.dvmId ?? `dev:${this.descriptor.name}`;
93529
94035
  return {
93530
94036
  dvm_id: dvmId,
93531
- builder_pubkey: createHash13("sha256").update(`dvmkit-dev:${dvmId}`).digest("hex")
94037
+ builder_pubkey: createHash14("sha256").update(`dvmkit-dev:${dvmId}`).digest("hex")
93532
94038
  };
93533
94039
  }
93534
94040
  throw new AuthAudienceError();
@@ -93606,7 +94112,9 @@ var DVMServer = class {
93606
94112
  const currencyFiltered = configured.filter(
93607
94113
  (method) => method !== "x402" || this.x402CurrencySupported()
93608
94114
  );
93609
- if (!this.opts.x402) return currencyFiltered;
94115
+ if (!this.opts.x402) {
94116
+ return this.x402RailMissing ? currencyFiltered.filter((method) => method !== "x402") : currencyFiltered;
94117
+ }
93610
94118
  const x402Available = this.x402CurrencySupported() && (this.x402Support()?.available ?? false);
93611
94119
  return currencyFiltered.filter((method) => method !== "x402" || x402Available);
93612
94120
  }
@@ -93845,6 +94353,7 @@ var DVMServer = class {
93845
94353
  lightningFundingMinSats: this.opts.lightningReceive?.fundingMinSats,
93846
94354
  stripeNetworkId: this.opts.stripeCredit?.networkId,
93847
94355
  stripeMinMicro: this.opts.stripeCredit?.minMicro,
94356
+ stripeCheckout: !!this.opts.stripeCredit?.checkout,
93848
94357
  // Configured, not advertised: `advertisedMints()` is health
93849
94358
  // filtered, and a rail that comes and goes with a mint's uptime is worse
93850
94359
  // product than one that is honestly absent.
@@ -93864,6 +94373,7 @@ var DVMServer = class {
93864
94373
  let hostingFundingArtifactHash;
93865
94374
  this.maybeSweepTempoSessions();
93866
94375
  return handleCreditRequest(c, {
94376
+ checkoutProductName: `${this.descriptor.name} prepaid credit`,
93867
94377
  hostedSettlementReports: this.opts.hostedSettlementReports,
93868
94378
  menu: () => this.creditMenu(this.creditCurrency()),
93869
94379
  creditConfig: this.descriptor.credit,
@@ -93889,14 +94399,14 @@ var DVMServer = class {
93889
94399
  settleLightning: (callerPubkey, creditId) => this.settleLightningFunding(callerPubkey, creditId),
93890
94400
  withFundingAdmission: this.opts.hostingControlInstance ? async (ctx, body, run3) => {
93891
94401
  const control = this.opts.hostingControlInstance;
93892
- let admissionId = randomUUID62();
94402
+ let admissionId = randomUUID8();
93893
94403
  const fundId = body.fund?.fund_id ?? admissionId;
93894
94404
  const creditId = body.credit_id ?? derivedFundCreditId(body.pubkey, fundId);
93895
94405
  const workId = `credit-fund:${creditId}:${fundId}`;
93896
94406
  const paymentAuthorization = ctx.req.header("Authorization");
93897
94407
  const mppArtifact = paymentAuthorization ? (await import("./dist-23E7OOCA.js")).Credential.extractPaymentScheme(paymentAuthorization) : void 0;
93898
94408
  const attachedPayment = ctx.req.header("X-Cashu") ?? ctx.req.header("PAYMENT-SIGNATURE") ?? ctx.req.header("X-PAYMENT") ?? mppArtifact;
93899
- const paymentArtifactHash = attachedPayment ? createHash13("sha256").update(attachedPayment).digest("hex") : void 0;
94409
+ const paymentArtifactHash = attachedPayment ? createHash14("sha256").update(attachedPayment).digest("hex") : void 0;
93900
94410
  hostingFundingArtifactHash = paymentArtifactHash;
93901
94411
  if (!await control.admit(admissionId, workId, {
93902
94412
  creditId,
@@ -94089,7 +94599,7 @@ var DVMServer = class {
94089
94599
  */
94090
94600
  renderX402Capabilities(c) {
94091
94601
  const caps = Object.entries(this.descriptor.x402Capabilities ?? {});
94092
- if (caps.length === 0) return void 0;
94602
+ if (caps.length === 0 || this.x402RailMissing) return void 0;
94093
94603
  const origin = this.publicOrigin ?? new URL(c.req.url).origin;
94094
94604
  const prefix = mountPrefix(c);
94095
94605
  return Object.fromEntries(
@@ -94223,7 +94733,7 @@ var DVMServer = class {
94223
94733
  { onError: () => ({ "error.code": "invalid_quote_data" }) }
94224
94734
  );
94225
94735
  } catch (err) {
94226
- const schemaUrl = infoSchemaUrl(c.req.url, this.publicOrigin);
94736
+ const schemaUrl = infoSchemaUrl(c.req.url, mountPrefix(c), this.publicOrigin);
94227
94737
  const { message, hint } = err instanceof external_exports.ZodError ? humanizeZodError(err, { schemaUrl }) : {
94228
94738
  message: "Quote-input validation failed",
94229
94739
  hint: `Inspect ${schemaUrl} for the expected input schema.`
@@ -94326,7 +94836,7 @@ var DVMServer = class {
94326
94836
  */
94327
94837
  requireCapabilityFromBody(c, capability) {
94328
94838
  const known = Object.keys(this.descriptor.capabilities);
94329
- const infoUrl = infoSchemaUrl(c.req.url, this.publicOrigin);
94839
+ const infoUrl = infoSchemaUrl(c.req.url, mountPrefix(c), this.publicOrigin);
94330
94840
  const x402Only = known.length === 0 ? `This DVM offers its capabilities to x402 clients only: send the request to POST ${mountPrefix(c)}${X402_CHANNEL_PATH_PREFIX}<capability>. See ${infoUrl}.` : void 0;
94331
94841
  if (typeof capability !== "string" || capability.length === 0) {
94332
94842
  return {
@@ -94368,7 +94878,7 @@ var DVMServer = class {
94368
94878
  try {
94369
94879
  return { body: await c.req.json() };
94370
94880
  } catch {
94371
- const infoUrl = infoSchemaUrl(c.req.url, this.publicOrigin);
94881
+ const infoUrl = infoSchemaUrl(c.req.url, mountPrefix(c), this.publicOrigin);
94372
94882
  return {
94373
94883
  error: c.json(
94374
94884
  {
@@ -94387,7 +94897,7 @@ var DVMServer = class {
94387
94897
  * and `message` carry the same relayable explanation.
94388
94898
  */
94389
94899
  invalidInputResponse(c, err) {
94390
- const schemaUrl = infoSchemaUrl(c.req.url, this.publicOrigin);
94900
+ const schemaUrl = infoSchemaUrl(c.req.url, mountPrefix(c), this.publicOrigin);
94391
94901
  const issues = zodIssuesOf(err);
94392
94902
  if (issues) {
94393
94903
  const inputIssues = callerInputIssues(issues);
@@ -94647,7 +95157,7 @@ var DVMServer = class {
94647
95157
  pinDimension("capability", name);
94648
95158
  pinDimension("channel", "x402");
94649
95159
  }
94650
- const schemaUrl = `${this.publicOrigin ?? new URL(c.req.url).origin}${prefix}/v1/info`;
95160
+ const schemaUrl = infoSchemaUrl(c.req.url, prefix, this.publicOrigin);
94651
95161
  if (!cap) {
94652
95162
  return c.json(
94653
95163
  {
@@ -94658,6 +95168,18 @@ var DVMServer = class {
94658
95168
  404
94659
95169
  );
94660
95170
  }
95171
+ if (this.x402RailMissing) {
95172
+ return c.json(
95173
+ {
95174
+ error: "x402_not_offered",
95175
+ retryable: false,
95176
+ message: "x402 payment is not configured for this DVM.",
95177
+ display: "This service does not take x402 payment. Nothing was charged.",
95178
+ hint: `x402 is not configured for this DVM. See ${schemaUrl} for the capabilities and payment methods it offers.`
95179
+ },
95180
+ 503
95181
+ );
95182
+ }
94661
95183
  const authorization = c.req.header("Authorization");
94662
95184
  const mppCredential = authorization ? (await import("./dist-23E7OOCA.js")).Credential.extractPaymentScheme(authorization) : void 0;
94663
95185
  if (c.req.header("X-Cashu") || mppCredential) {
@@ -94923,7 +95445,7 @@ var DVMServer = class {
94923
95445
  const authorization = c.req.header("Authorization");
94924
95446
  const mppArtifact = authorization ? (await import("./dist-23E7OOCA.js")).Credential.extractPaymentScheme(authorization) : void 0;
94925
95447
  const attachedPayment = c.req.header("X-Cashu") ?? c.req.header("PAYMENT-SIGNATURE") ?? c.req.header("X-PAYMENT") ?? mppArtifact;
94926
- const hostingPaymentArtifactHash = attachedPayment ? createHash13("sha256").update(attachedPayment).digest("hex") : void 0;
95448
+ const hostingPaymentArtifactHash = attachedPayment ? createHash14("sha256").update(attachedPayment).digest("hex") : void 0;
94927
95449
  if (!resumeOnly && !route && this.opts.hostingControlInstance && hostingPaymentArtifactHash) {
94928
95450
  const priorId = await this.opts.hostingControlInstance.acceptedJobByPaymentArtifactHash(
94929
95451
  hostingPaymentArtifactHash
@@ -94977,7 +95499,7 @@ var DVMServer = class {
94977
95499
  }
94978
95500
  let jobId = publicRequestClaimResult?.jobId ?? this.jobManager.allocateJobId();
94979
95501
  if (!resumeOnly && this.opts.hostingControlInstance) {
94980
- hostingAdmissionId = randomUUID62();
95502
+ hostingAdmissionId = randomUUID8();
94981
95503
  if (!await this.opts.hostingControlInstance.admit(hostingAdmissionId, jobId, {
94982
95504
  paymentArtifactHash: hostingPaymentArtifactHash
94983
95505
  })) {
@@ -95084,7 +95606,8 @@ var DVMServer = class {
95084
95606
  if (!route && (!this.descriptor.auth || unsignedPaid && this.unsignedCashuOffered())) {
95085
95607
  railOpts.nut24 = {
95086
95608
  mints: this.advertisedMints(),
95087
- previousRequiredMsats: this.previousPriceMsats(cap, dynamicUpfront, pricedAt)
95609
+ previousRequiredMsats: this.previousPriceMsats(cap, dynamicUpfront, pricedAt),
95610
+ refundDelay: this.descriptor.cashu?.advertiseRefundDelay ?? false
95088
95611
  };
95089
95612
  if (!railOpts.requestId) {
95090
95613
  railOpts.cashuLockWindowSeconds = unsignedCashuLockWindowSeconds(this.descriptor.cashu);
@@ -95269,7 +95792,7 @@ var DVMServer = class {
95269
95792
  }
95270
95793
  const isAnonymous = requesterId === "anonymous" || requesterId === "dev-anonymous";
95271
95794
  const jobToken = isAnonymous ? randomBytes52(32).toString("hex") : void 0;
95272
- const requesterTokenHash = jobToken ? createHash13("sha256").update(jobToken).digest("hex") : void 0;
95795
+ const requesterTokenHash = jobToken ? createHash14("sha256").update(jobToken).digest("hex") : void 0;
95273
95796
  const job = jm.createJob(
95274
95797
  normalisedBody,
95275
95798
  requesterId,
@@ -95298,8 +95821,8 @@ var DVMServer = class {
95298
95821
  if (store instanceof PostgresJobStore && await store.cancelJobForHosting(jobId, "Hosting drain deadline reached")) {
95299
95822
  await jm.finalizeStoredTerminal(jobId);
95300
95823
  }
95301
- const terminal = await store.get(jobId);
95302
- if (terminal) return await respond(terminal, jobToken);
95824
+ const terminal2 = await store.get(jobId);
95825
+ if (terminal2) return await respond(terminal2, jobToken);
95303
95826
  }
95304
95827
  if (exactAdmission) {
95305
95828
  await this.x402ExactSettlement?.completeAdmission(
@@ -95683,10 +96206,11 @@ var DVMServer = class {
95683
96206
  }
95684
96207
  if (row === "handler_failed" || row === "runtime_bound") {
95685
96208
  const copy = record2.status === "completed" ? X402_ROUTE_COPY.settle_window_closed : X402_ROUTE_COPY[row];
95686
- const reason = record2.status === "completed" ? SETTLE_WINDOW_CLOSED_REASON : lastCancelReason(record2.messages) ?? copy.display;
96209
+ const failure2 = record2.status === "completed" ? void 0 : x402FailedJobAnswer(record2.messages);
96210
+ const reason = record2.status === "completed" ? SETTLE_WINDOW_CLOSED_REASON : failure2?.reason ?? copy.display;
95687
96211
  return c.json(
95688
96212
  { job_id: record2.id, status: "failed", reason, ...copy, charge_outcome: "not_charged" },
95689
- row === "handler_failed" ? 500 : 503,
96213
+ row === "runtime_bound" ? 503 : failure2?.status ?? 500,
95690
96214
  identity
95691
96215
  );
95692
96216
  }
@@ -95803,14 +96327,14 @@ var DVMServer = class {
95803
96327
  const record2 = await store.get(id);
95804
96328
  if (!record2) return c.json({ error: "Job not found" }, 404);
95805
96329
  if (!isJobOwner(c, record2)) return c.json({ error: "Job not found" }, 404);
95806
- const terminal = isTerminal(record2.status) || job !== void 0 && isTerminal(job.status);
96330
+ const terminal2 = isTerminal(record2.status) || job !== void 0 && isTerminal(job.status);
95807
96331
  let filtered = record2.messages.filter((m) => m.seq > after);
95808
96332
  if (isStreamableJobStore(store)) {
95809
- const durable = await store.getMessages(id, after, { includeHeld: terminal });
95810
- if (durable.length > 0 || !terminal) filtered = durable;
96333
+ const durable = await store.getMessages(id, after, { includeHeld: terminal2 });
96334
+ if (durable.length > 0 || !terminal2) filtered = durable;
95811
96335
  }
95812
96336
  if (accept.includes("text/event-stream")) {
95813
- if (isStreamableJobStore(store) && !terminal) {
96337
+ if (isStreamableJobStore(store) && !terminal2) {
95814
96338
  if ((await this.contentFields(record2)).content_available === false) {
95815
96339
  return streamSSE(c, async () => void 0);
95816
96340
  }
@@ -96122,7 +96646,7 @@ var DVMServer = class {
96122
96646
  if (open2) return this.paymentInProgressResponse(c);
96123
96647
  throw error62;
96124
96648
  }
96125
- const infoUrl = infoSchemaUrl(c.req.url, this.publicOrigin);
96649
+ const infoUrl = infoSchemaUrl(c.req.url, mountPrefix(c), this.publicOrigin);
96126
96650
  return c.json(
96127
96651
  {
96128
96652
  error: "unknown_capability",
@@ -96379,7 +96903,7 @@ function isJobOwner(c, job) {
96379
96903
  if (job.requesterTokenHash) {
96380
96904
  const token = c.req.header("X-Job-Token");
96381
96905
  if (!token) return false;
96382
- const provided = createHash13("sha256").update(token).digest("hex");
96906
+ const provided = createHash14("sha256").update(token).digest("hex");
96383
96907
  return timingSafeEqualHex(provided, job.requesterTokenHash);
96384
96908
  }
96385
96909
  return c.get("requesterId") === job.requesterId;
@@ -96564,13 +97088,6 @@ async function settlesWithin(work, ms) {
96564
97088
  clearTimeout(timer);
96565
97089
  }
96566
97090
  }
96567
- function lastCancelReason(messages) {
96568
- for (let i3 = messages.length - 1; i3 >= 0; i3--) {
96569
- const message = messages[i3];
96570
- if (message.type === "cancel") return message.content.reason;
96571
- }
96572
- return void 0;
96573
- }
96574
97091
  function mountPrefix(c) {
96575
97092
  return x402MountPrefix(baseRoutePath(c));
96576
97093
  }
@@ -96723,7 +97240,7 @@ var PaymentValidationError = class extends Error {
96723
97240
  detail;
96724
97241
  };
96725
97242
  function buildAuthErrorResponse(c, err, publicOrigin) {
96726
- return c.json(authErrorBody(err, { schemaUrl: infoSchemaUrl(c.req.url, publicOrigin) }), 401);
97243
+ return c.json(authErrorBody(err, { schemaUrl: infoSchemaUrl(c.req.url, mountPrefix(c), publicOrigin) }), 401);
96727
97244
  }
96728
97245
  function validateMessageContent(type, content, devMode) {
96729
97246
  if (type === "response") {
@@ -96977,8 +97494,6 @@ export {
96977
97494
  createFxFetcher,
96978
97495
  warmFxSnapshot,
96979
97496
  fxRateFor,
96980
- withInitRetry,
96981
- applyRetryToPool,
96982
97497
  randomTraceId,
96983
97498
  withTraceContext,
96984
97499
  currentContext,
@@ -97261,6 +97776,7 @@ export {
97261
97776
  clearAccumulatorForDvm,
97262
97777
  hashLockKey,
97263
97778
  toCreditTerms,
97779
+ rateUnavailablePaymentError,
97264
97780
  resolvePriceFiat,
97265
97781
  priceFiatMicro,
97266
97782
  resolveFxSnapshot,
@@ -97272,7 +97788,6 @@ export {
97272
97788
  implicitCreditId,
97273
97789
  isDerivedCreditId,
97274
97790
  derivedFundCreditId,
97275
- rateUnavailablePaymentError,
97276
97791
  X402_BATCH_SETTLEMENT_MAINNET_NETWORK,
97277
97792
  devModeSkipsPaymentVerification,
97278
97793
  PAYMENT_PROOF_KEYS,