@blockrun/llm 3.19.1 → 3.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,19 @@
1
1
  // src/types.ts
2
+ var RETRY_DISPOSITION = /* @__PURE__ */ Symbol.for("@blockrun/llm/retry-disposition/v1");
3
+ function retryDisposition(err) {
4
+ if (!err || typeof err !== "object" && typeof err !== "function") return void 0;
5
+ const value = err[RETRY_DISPOSITION];
6
+ return value === "unpaid" || value === "paid-or-in-doubt" ? value : void 0;
7
+ }
8
+ function withDisposition(err, disposition) {
9
+ if (!err || typeof err !== "object") return err;
10
+ if (retryDisposition(err) === "paid-or-in-doubt") return err;
11
+ try {
12
+ Object.defineProperty(err, RETRY_DISPOSITION, { value: disposition, configurable: true, writable: true, enumerable: false });
13
+ } catch {
14
+ }
15
+ return err;
16
+ }
2
17
  var BlockrunError = class extends Error {
3
18
  constructor(message) {
4
19
  super(message);
@@ -190,6 +205,15 @@ function resolveApiKeyAuth(options) {
190
205
  const base = options.apiUrl ?? (typeof process !== "undefined" ? process.env?.BLOCKRUN_API_BASE_URL : void 0) ?? API_KEY_URL;
191
206
  return new ApiKeyAuth(key.trim(), base);
192
207
  }
208
+ function accountErrorDisposition(err) {
209
+ if (!(err instanceof APIError)) return "paid-or-in-doubt";
210
+ if (err.statusCode >= 400 && err.statusCode < 500) return "unpaid";
211
+ if (err.statusCode >= 500 && hasGatewayErrorEnvelope(err.response)) return "unpaid";
212
+ return "paid-or-in-doubt";
213
+ }
214
+ function hasGatewayErrorEnvelope(response) {
215
+ return !!response && typeof response === "object" && typeof response.message === "string" && response.message.length > 0;
216
+ }
193
217
  function requireWallet(value) {
194
218
  if (value === void 0) throw new Error("This operation requires a wallet; the client uses API key account billing.");
195
219
  return value;
@@ -4056,6 +4080,7 @@ var AUTO_ROUTING_PROFILES = {
4056
4080
  var BASE_MINIMUM_PAYMENT_USD = 2e-3;
4057
4081
  var SOLANA_MINIMUM_PAYMENT_USD = 1e-3;
4058
4082
  function isTransientError(err) {
4083
+ if (retryDisposition(err) !== "unpaid") return false;
4059
4084
  if (err instanceof PaymentError) return false;
4060
4085
  if (err instanceof APIError) {
4061
4086
  return [429, 502, 503, 504, 522, 524].includes(err.statusCode);
@@ -4539,7 +4564,7 @@ function getCostSummary() {
4539
4564
  }
4540
4565
 
4541
4566
  // src/version.ts
4542
- var SDK_VERSION = "3.19.1";
4567
+ var SDK_VERSION = "3.20.1";
4543
4568
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
4544
4569
 
4545
4570
  // src/client.ts
@@ -4811,10 +4836,13 @@ var LLMClient = class _LLMClient {
4811
4836
  * Full chat completion interface (OpenAI-compatible).
4812
4837
  *
4813
4838
  * When `fallbackModels` is set, transient failures (timeouts, network
4814
- * errors, 5xx) on the primary model trigger a retry against the next
4815
- * model in the list before raising. 4xx errors and PaymentError
4816
- * propagate immediately — those aren't "swap upstream and retry"
4817
- * situations. Each fallback hop logs one stderr line.
4839
+ * errors, 429, 5xx) on the primary model trigger a retry against the next
4840
+ * model in the list before raising, but only while no payment has been
4841
+ * sent for it (the error's {@link RetryDisposition} is `"unpaid"`). Once a
4842
+ * payment was sent, any failure propagates: the next model would be a
4843
+ * second charge. 4xx errors and PaymentError also propagate immediately —
4844
+ * those aren't "swap upstream and retry" situations. Each fallback hop
4845
+ * logs one stderr line.
4818
4846
  *
4819
4847
  * @param model - Primary model ID
4820
4848
  * @param messages - Array of messages with role and content
@@ -4917,21 +4945,25 @@ var LLMClient = class _LLMClient {
4917
4945
  }
4918
4946
  /**
4919
4947
  * Make a request with automatic x402 payment handling.
4948
+ *
4949
+ * Every error it throws carries a {@link RetryDisposition}, which is what
4950
+ * {@link LLMClient.chatCompletion}'s fallback walk honours: errors of the
4951
+ * unpaid first request (and its one 502/503 retry), of the 402 challenge
4952
+ * and of signing are `"unpaid"`; anything after the signed payment was sent
4953
+ * is `"paid-or-in-doubt"`. With an API key the request itself is billed, so
4954
+ * only the account API's explicit 4xx refusal is `"unpaid"`.
4920
4955
  */
4921
4956
  async requestWithPayment(endpoint, body) {
4922
4957
  const url = `${this.apiUrl}${endpoint}`;
4923
- const response = await this.fetchWithTimeout(url, {
4958
+ const unpaid = {
4924
4959
  method: "POST",
4925
4960
  headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
4926
4961
  body: JSON.stringify(body)
4927
- });
4962
+ };
4963
+ const response = await this.sendUnpaid(url, unpaid);
4928
4964
  if (response.status === 502 || response.status === 503) {
4929
4965
  await new Promise((r) => setTimeout(r, 1e3));
4930
- const retryResp = await this.fetchWithTimeout(url, {
4931
- method: "POST",
4932
- headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
4933
- body: JSON.stringify(body)
4934
- });
4966
+ const retryResp = await this.sendUnpaid(url, unpaid);
4935
4967
  if (retryResp.status !== 502 && retryResp.status !== 503) {
4936
4968
  if (retryResp.status === 402) return this.handlePaymentAndRetry(url, body, retryResp);
4937
4969
  if (!retryResp.ok) {
@@ -4941,9 +4973,12 @@ var LLMClient = class _LLMClient {
4941
4973
  } catch {
4942
4974
  errorBody = { error: "Request failed" };
4943
4975
  }
4944
- throw new APIError(`API error: ${retryResp.status}`, retryResp.status, sanitizeErrorResponse(errorBody));
4976
+ throw withDisposition(
4977
+ new APIError(`API error: ${retryResp.status}`, retryResp.status, sanitizeErrorResponse(errorBody)),
4978
+ "unpaid"
4979
+ );
4945
4980
  }
4946
- return this.parseChatResponse(retryResp);
4981
+ return this.parseUnpaidChatResponse(retryResp);
4947
4982
  }
4948
4983
  }
4949
4984
  if (response.status === 402) {
@@ -4956,18 +4991,61 @@ var LLMClient = class _LLMClient {
4956
4991
  } catch {
4957
4992
  errorBody = { error: "Request failed" };
4958
4993
  }
4959
- throw new APIError(
4960
- `API error: ${response.status}`,
4961
- response.status,
4962
- sanitizeErrorResponse(errorBody)
4994
+ throw withDisposition(
4995
+ new APIError(
4996
+ `API error: ${response.status}`,
4997
+ response.status,
4998
+ sanitizeErrorResponse(errorBody)
4999
+ ),
5000
+ "unpaid"
4963
5001
  );
4964
5002
  }
4965
- return this.parseChatResponse(response);
5003
+ return this.parseUnpaidChatResponse(response);
5004
+ }
5005
+ /**
5006
+ * Send a request that carries no payment, marking what it throws with its
5007
+ * {@link RetryDisposition}: `"unpaid"` with a wallet; with an API key, see
5008
+ * {@link accountErrorDisposition} (the request itself is billed).
5009
+ */
5010
+ async sendUnpaid(url, init) {
5011
+ try {
5012
+ return await this.fetchWithTimeout(url, init);
5013
+ } catch (err) {
5014
+ throw withDisposition(err, this.apiAuth ? accountErrorDisposition(err) : "unpaid");
5015
+ }
5016
+ }
5017
+ /**
5018
+ * Parse a response to a request that carried no payment: the free tier,
5019
+ * or, with an API key, the billed request itself.
5020
+ */
5021
+ async parseUnpaidChatResponse(response) {
5022
+ try {
5023
+ return await this.parseChatResponse(response);
5024
+ } catch (err) {
5025
+ throw withDisposition(err, this.apiAuth ? "paid-or-in-doubt" : "unpaid");
5026
+ }
4966
5027
  }
4967
5028
  /**
4968
5029
  * Handle 402 response: parse requirements, sign payment, retry.
5030
+ *
5031
+ * Anything thrown before the signed payment is sent is `"unpaid"`; anything
5032
+ * after it, `"paid-or-in-doubt"` (see {@link RetryDisposition}).
4969
5033
  */
4970
5034
  async handlePaymentAndRetry(url, body, response) {
5035
+ let signed;
5036
+ try {
5037
+ signed = await this.signFrom402(url, response);
5038
+ } catch (err) {
5039
+ throw withDisposition(err, "unpaid");
5040
+ }
5041
+ try {
5042
+ return await this.sendPaid(url, body, signed.paymentPayload, signed.details);
5043
+ } catch (err) {
5044
+ throw withDisposition(err, "paid-or-in-doubt");
5045
+ }
5046
+ }
5047
+ /** Read a 402's requirements and sign the exact payment for them. Sends nothing. */
5048
+ async signFrom402(url, response) {
4971
5049
  let paymentHeader = response.headers.get("payment-required");
4972
5050
  if (!paymentHeader) {
4973
5051
  try {
@@ -5003,6 +5081,10 @@ var LLMClient = class _LLMClient {
5003
5081
  extensions
5004
5082
  }
5005
5083
  );
5084
+ return { paymentPayload, details };
5085
+ }
5086
+ /** Send the signed payment and read the answer. The payment may settle from here on. */
5087
+ async sendPaid(url, body, paymentPayload, details) {
5006
5088
  const retryResponse = await this.fetchWithTimeout(url, {
5007
5089
  method: "POST",
5008
5090
  headers: {
@@ -5139,25 +5221,46 @@ var LLMClient = class _LLMClient {
5139
5221
  const cached = this.preAuthCache.get(cacheKey2);
5140
5222
  const now = Date.now();
5141
5223
  if (cached && now - cached.cachedAt < _LLMClient.PRE_AUTH_TTL_MS) {
5224
+ let signed;
5142
5225
  try {
5143
- const { paymentPayload: paymentPayload2, costUsd: costUsd2 } = await this.signPayment(cached.paymentHeader);
5144
- const preAuthResp = await this.fetchWithTimeout(url, {
5145
- method: "POST",
5146
- headers: {
5147
- "Content-Type": "application/json",
5148
- "User-Agent": USER_AGENT,
5149
- "PAYMENT-SIGNATURE": paymentPayload2
5150
- },
5151
- body: JSON.stringify(body)
5152
- });
5153
- if (preAuthResp.status !== 402 && preAuthResp.ok) {
5226
+ signed = await this.signPayment(cached.paymentHeader);
5227
+ } catch {
5228
+ this.preAuthCache.delete(cacheKey2);
5229
+ }
5230
+ if (signed) {
5231
+ let preAuthResp;
5232
+ try {
5233
+ preAuthResp = await this.fetchWithTimeout(url, {
5234
+ method: "POST",
5235
+ headers: {
5236
+ "Content-Type": "application/json",
5237
+ "User-Agent": USER_AGENT,
5238
+ "PAYMENT-SIGNATURE": signed.paymentPayload
5239
+ },
5240
+ body: JSON.stringify(body)
5241
+ });
5242
+ } catch (err) {
5243
+ this.preAuthCache.delete(cacheKey2);
5244
+ throw withDisposition(err, "paid-or-in-doubt");
5245
+ }
5246
+ if (preAuthResp.ok) {
5154
5247
  this.sessionCalls += 1;
5155
- this.sessionTotalUsd += costUsd2;
5248
+ this.sessionTotalUsd += signed.costUsd;
5156
5249
  return preAuthResp;
5157
5250
  }
5158
5251
  this.preAuthCache.delete(cacheKey2);
5159
- } catch {
5160
- this.preAuthCache.delete(cacheKey2);
5252
+ if (preAuthResp.status !== 402) {
5253
+ let errorBody;
5254
+ try {
5255
+ errorBody = await preAuthResp.json();
5256
+ } catch {
5257
+ errorBody = { error: "Request failed" };
5258
+ }
5259
+ throw withDisposition(
5260
+ new APIError(`API error after payment: ${preAuthResp.status}`, preAuthResp.status, sanitizeErrorResponse(errorBody)),
5261
+ "paid-or-in-doubt"
5262
+ );
5263
+ }
5161
5264
  }
5162
5265
  }
5163
5266
  const firstResp = await this.fetchWithTimeout(url, {
@@ -9226,11 +9329,11 @@ var WALLET_DIR = path4.join(os3.homedir(), ".blockrun");
9226
9329
  var SOLANA_WALLET_FILE = path4.join(WALLET_DIR, ".solana-session");
9227
9330
  async function createSolanaWallet() {
9228
9331
  const { Keypair } = await loadSolanaWeb3("Solana wallet operations");
9229
- const bs58 = await import("bs58");
9332
+ const bs582 = await import("bs58");
9230
9333
  const keypair = Keypair.generate();
9231
9334
  return {
9232
9335
  address: keypair.publicKey.toBase58(),
9233
- privateKey: (bs58.default ?? bs58).encode(keypair.secretKey)
9336
+ privateKey: (bs582.default ?? bs582).encode(keypair.secretKey)
9234
9337
  };
9235
9338
  }
9236
9339
  async function solanaKeyToBytes(privateKey) {
@@ -9268,8 +9371,8 @@ async function solanaKeyToBytes(privateKey) {
9268
9371
  return bytes;
9269
9372
  }
9270
9373
  try {
9271
- const bs58 = await import("bs58");
9272
- const bytes = (bs58.default ?? bs58).decode(key);
9374
+ const bs582 = await import("bs58");
9375
+ const bytes = (bs582.default ?? bs582).decode(key);
9273
9376
  if (bytes.length !== 64) {
9274
9377
  throw new Error(`Invalid Solana key length: expected 64 bytes, got ${bytes.length}`);
9275
9378
  }
@@ -9449,10 +9552,59 @@ async function getOrCreateSolanaWallet() {
9449
9552
  }
9450
9553
 
9451
9554
  // src/solana-batch.ts
9555
+ import { AsyncLocalStorage } from "async_hooks";
9556
+ import { randomUUID } from "crypto";
9452
9557
  import * as fs6 from "fs";
9453
9558
  import * as path5 from "path";
9559
+ import bs58 from "bs58";
9454
9560
  var BATCH_SCHEME = "batch-settlement";
9455
9561
  var BLOCKRUN_SOL_OPERATOR = "5YKPQUFjw5WQqhSUkEGKNNfYYVqnRRNbpYyL71qQ1vm3";
9562
+ var DEFAULT_BATCH_RATE_LIMIT = { maxAttempts: 3, maxWaitMs: 6e4 };
9563
+ var BatchPaymentUnresolvedError = class extends PaymentError {
9564
+ /** The {@link SolanaBatchEvent.reason} of the `unresolved` event reported with it. */
9565
+ reason;
9566
+ /** The paying wallet's address. */
9567
+ wallet;
9568
+ /** The request id of the payment that may have been charged. */
9569
+ requestId;
9570
+ /** The channel it paid into. */
9571
+ channelId;
9572
+ /** What it carried. */
9573
+ payloadKind;
9574
+ /** HTTP status of the gateway's last answer to it, when there was one. */
9575
+ status;
9576
+ /** Whether it carried a deposit, which is now in doubt as well. */
9577
+ depositInDoubt;
9578
+ constructor(init) {
9579
+ super(
9580
+ `batch-settlement payment ${init.requestId ?? "<unknown>"} from wallet ${init.wallet} may have been charged and is not paid again${init.detail ? `: ${init.detail}` : ""}`
9581
+ );
9582
+ this.name = "BatchPaymentUnresolvedError";
9583
+ withDisposition(this, "paid-or-in-doubt");
9584
+ this.reason = init.reason;
9585
+ this.wallet = init.wallet;
9586
+ this.requestId = init.requestId;
9587
+ this.channelId = init.channelId;
9588
+ this.payloadKind = init.payloadKind;
9589
+ this.status = init.status;
9590
+ this.depositInDoubt = init.payloadKind === "open" || init.payloadKind === "top-up";
9591
+ if (init.cause !== void 0) this.cause = init.cause;
9592
+ }
9593
+ };
9594
+ var BatchCloseDeferredError = class extends BlockrunError {
9595
+ reason;
9596
+ /** The paying wallet's address. */
9597
+ wallet;
9598
+ /** The channels whose deposit is in doubt (`deposit_in_doubt`). */
9599
+ channelIds;
9600
+ constructor(init) {
9601
+ super(`batch-settlement channel close deferred for wallet ${init.wallet}: ${init.detail}`);
9602
+ this.name = "BatchCloseDeferredError";
9603
+ this.reason = init.reason;
9604
+ this.wallet = init.wallet;
9605
+ this.channelIds = init.channelIds ?? [];
9606
+ }
9607
+ };
9456
9608
  var INSTALL_HINT2 = "npm install @x402/core@~2.28.0 @x402/svm@~2.28.0 @solana/kit";
9457
9609
  async function load(pkg, importer) {
9458
9610
  try {
@@ -9502,6 +9654,10 @@ var FileChannelStorage = class {
9502
9654
  delete all[key];
9503
9655
  this.write(all);
9504
9656
  }
9657
+ /** The keys of every stored channel. */
9658
+ async keys() {
9659
+ return Object.keys(this.read());
9660
+ }
9505
9661
  /** Forget every channel in this file. */
9506
9662
  clear() {
9507
9663
  try {
@@ -9511,6 +9667,192 @@ var FileChannelStorage = class {
9511
9667
  }
9512
9668
  }
9513
9669
  };
9670
+ var MemoryChannelStorage = class {
9671
+ records = /* @__PURE__ */ new Map();
9672
+ async get(key) {
9673
+ const raw = this.records.get(key);
9674
+ return raw === void 0 ? void 0 : JSON.parse(raw);
9675
+ }
9676
+ async set(key, record) {
9677
+ this.records.set(key, JSON.stringify(record));
9678
+ }
9679
+ async delete(key) {
9680
+ this.records.delete(key);
9681
+ }
9682
+ async keys() {
9683
+ return [...this.records.keys()];
9684
+ }
9685
+ clear() {
9686
+ this.records.clear();
9687
+ }
9688
+ };
9689
+ function isPlainObject(value) {
9690
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9691
+ }
9692
+ function intentProblem(key, intent) {
9693
+ const atomic = (value) => typeof value === "string" && /^\d+$/.test(value);
9694
+ if (!isPlainObject(intent)) return "not an object";
9695
+ if (intent.key !== key || !key) return "key does not match its entry";
9696
+ if (typeof intent.channelId !== "string" || !intent.channelId) return "channelId missing";
9697
+ if (!isPlainObject(intent.channelConfig)) return "channelConfig missing";
9698
+ if (intent.kind !== "open" && intent.kind !== "top-up") return "kind is neither open nor top-up";
9699
+ if (!atomic(intent.cumulative)) return "cumulative is not an atomic amount";
9700
+ if (!atomic(intent.expectDeposit)) return "expectDeposit is not an atomic amount";
9701
+ if (intent.knownDeposit !== void 0 && !atomic(intent.knownDeposit)) return "knownDeposit is not an atomic amount";
9702
+ if (intent.requestId !== void 0 && typeof intent.requestId !== "string") return "requestId is not a string";
9703
+ if (intent.anchorHeight !== void 0 && (!Number.isSafeInteger(intent.anchorHeight) || intent.anchorHeight < 0)) {
9704
+ return "anchorHeight is not a block height";
9705
+ }
9706
+ if (typeof intent.at !== "number" || !Number.isFinite(intent.at)) return "at is not a time";
9707
+ return void 0;
9708
+ }
9709
+ function fsyncDirectory(dir) {
9710
+ let fd;
9711
+ try {
9712
+ fd = fs6.openSync(dir, "r");
9713
+ fs6.fsyncSync(fd);
9714
+ } catch (err) {
9715
+ const code = err.code;
9716
+ if (!["EISDIR", "EPERM", "EACCES", "EINVAL", "ENOTSUP", "EBADF"].includes(code ?? "")) throw err;
9717
+ } finally {
9718
+ if (fd !== void 0) fs6.closeSync(fd);
9719
+ }
9720
+ }
9721
+ var FileIntentJournal = class _FileIntentJournal {
9722
+ constructor(file) {
9723
+ this.file = file;
9724
+ }
9725
+ file;
9726
+ durable = true;
9727
+ /** The journal file for a channel store file: its full path plus `.deposit-intents`, one per store. */
9728
+ static beside(channelFile) {
9729
+ return new _FileIntentJournal(`${channelFile}.deposit-intents`);
9730
+ }
9731
+ /**
9732
+ * Where earlier builds kept a store's journal: the store's name without
9733
+ * `.json`, plus `.deposit-intents.json`. Two stores could share it
9734
+ * (`/x/channels` and `/x/channels.json`), so its intents are moved by payer
9735
+ * ({@link adoptLegacy}). No current journal path ever ends in `.json`, so
9736
+ * this never names one.
9737
+ */
9738
+ static legacyBeside(channelFile) {
9739
+ const base = path5.basename(channelFile).replace(/\.json$/i, "");
9740
+ return path5.join(path5.dirname(channelFile), `${base}.deposit-intents.json`);
9741
+ }
9742
+ /**
9743
+ * Move `payer`'s intents from a journal an earlier build wrote at
9744
+ * `legacyFile` into this one, before this one is used: written here first
9745
+ * (durably), then removed there (the file goes once empty). Intents of other
9746
+ * payers are left where they are, for the store they belong to. An intent
9747
+ * already here is kept (a migration interrupted between the two writes).
9748
+ *
9749
+ * @throws when the old journal cannot be read or is not valid, or holds an
9750
+ * intent naming no payer: the wallet then keeps batch off, as for an
9751
+ * unreadable journal, and nothing is dropped.
9752
+ */
9753
+ adoptLegacy(legacyFile, payer) {
9754
+ if (legacyFile === this.file) return;
9755
+ const legacy = new _FileIntentJournal(legacyFile);
9756
+ const found = legacy.read();
9757
+ const mine = [];
9758
+ const others = {};
9759
+ for (const [key, intent] of Object.entries(found)) {
9760
+ const owner = intent.channelConfig.payer;
9761
+ if (typeof owner !== "string") {
9762
+ throw new Error(`deposit-intent journal ${legacyFile} holds an intent naming no payer (${JSON.stringify(key)}); move it by hand`);
9763
+ }
9764
+ if (owner === payer) mine.push(intent);
9765
+ else others[key] = intent;
9766
+ }
9767
+ if (mine.length === 0) return;
9768
+ const intents = this.read();
9769
+ for (const intent of mine) intents[intent.key] ??= intent;
9770
+ this.write(intents);
9771
+ legacy.write(others);
9772
+ }
9773
+ /**
9774
+ * The journaled intents. Only a missing file is an empty journal: anything
9775
+ * else that is not a version-1 journal of well-formed intents throws, so a
9776
+ * deposit in doubt is never lost to a damaged or unknown file (the wallet
9777
+ * then keeps batch off, `deposit_journal_unreadable`).
9778
+ */
9779
+ read() {
9780
+ let text;
9781
+ try {
9782
+ text = fs6.readFileSync(this.file, "utf8");
9783
+ } catch (err) {
9784
+ if (err.code === "ENOENT") return {};
9785
+ throw err;
9786
+ }
9787
+ const invalid = (why) => new Error(`deposit-intent journal ${this.file} is not valid (${why})`);
9788
+ let parsed;
9789
+ try {
9790
+ parsed = JSON.parse(text);
9791
+ } catch (err) {
9792
+ throw invalid(err instanceof Error ? err.message : String(err));
9793
+ }
9794
+ if (!isPlainObject(parsed)) throw invalid("not a JSON object");
9795
+ if (parsed.version !== 1) throw invalid(`unsupported version ${JSON.stringify(parsed.version)}`);
9796
+ const { intents } = parsed;
9797
+ if (!isPlainObject(intents)) throw invalid("intents is not an object");
9798
+ for (const [key, intent] of Object.entries(intents)) {
9799
+ const why = intentProblem(key, intent);
9800
+ if (why) throw invalid(`intent ${JSON.stringify(key)}: ${why}`);
9801
+ }
9802
+ return intents;
9803
+ }
9804
+ write(intents) {
9805
+ const dir = path5.dirname(this.file);
9806
+ fs6.mkdirSync(dir, { recursive: true, mode: 448 });
9807
+ if (Object.keys(intents).length === 0) {
9808
+ try {
9809
+ fs6.unlinkSync(this.file);
9810
+ } catch (err) {
9811
+ if (err.code !== "ENOENT") throw err;
9812
+ return;
9813
+ }
9814
+ fsyncDirectory(dir);
9815
+ return;
9816
+ }
9817
+ const tmp = `${this.file}.${process.pid}.${randomUUID()}.tmp`;
9818
+ const fd = fs6.openSync(tmp, "w", 384);
9819
+ try {
9820
+ fs6.writeSync(fd, JSON.stringify({ version: 1, intents }, null, 2));
9821
+ fs6.fsyncSync(fd);
9822
+ } finally {
9823
+ fs6.closeSync(fd);
9824
+ }
9825
+ fs6.renameSync(tmp, this.file);
9826
+ fsyncDirectory(dir);
9827
+ }
9828
+ list() {
9829
+ return Object.values(this.read());
9830
+ }
9831
+ put(intent) {
9832
+ const intents = this.read();
9833
+ intents[intent.key] = intent;
9834
+ this.write(intents);
9835
+ }
9836
+ remove(key) {
9837
+ const intents = this.read();
9838
+ if (!(key in intents)) return;
9839
+ delete intents[key];
9840
+ this.write(intents);
9841
+ }
9842
+ };
9843
+ var MemoryIntentJournal = class {
9844
+ durable = false;
9845
+ intents = /* @__PURE__ */ new Map();
9846
+ list() {
9847
+ return [...this.intents.values()];
9848
+ }
9849
+ put(intent) {
9850
+ this.intents.set(intent.key, { ...intent });
9851
+ }
9852
+ remove(key) {
9853
+ this.intents.delete(key);
9854
+ }
9855
+ };
9514
9856
  function processAlive(pid) {
9515
9857
  try {
9516
9858
  process.kill(pid, 0);
@@ -9519,71 +9861,438 @@ function processAlive(pid) {
9519
9861
  return err.code === "EPERM";
9520
9862
  }
9521
9863
  }
9522
- var heldLocks = /* @__PURE__ */ new Set();
9523
- var exitHookInstalled = false;
9864
+ var BATCH_REGISTRY = /* @__PURE__ */ Symbol.for("@blockrun/llm/batch-registry/v1");
9865
+ var registryHost = globalThis;
9866
+ var registry2 = registryHost[BATCH_REGISTRY] ??= {
9867
+ wallets: /* @__PURE__ */ new Map(),
9868
+ locks: /* @__PURE__ */ new Map(),
9869
+ exitHook: false
9870
+ };
9871
+ var lockIds = registry2.lockIds ??= /* @__PURE__ */ new Map();
9872
+ function fileIdentity(file) {
9873
+ try {
9874
+ const stat = fs6.statSync(file);
9875
+ return `${stat.dev}:${stat.ino}:${stat.mtimeMs}`;
9876
+ } catch {
9877
+ return void 0;
9878
+ }
9879
+ }
9880
+ function lockPredatesProcess(lock) {
9881
+ try {
9882
+ return fs6.statSync(lock).mtimeMs < performance.timeOrigin;
9883
+ } catch {
9884
+ return false;
9885
+ }
9886
+ }
9887
+ function holdsChannelFile(file) {
9888
+ const token = registry2.locks.get(file);
9889
+ if (!token) return false;
9890
+ const lock = `${file}.lock`;
9891
+ if (!ownsLock(lock, token)) return false;
9892
+ const id = lockIds.get(file);
9893
+ return id === void 0 || fileIdentity(lock) === id;
9894
+ }
9895
+ function lockTokenFile(lock) {
9896
+ return `${lock}.owner`;
9897
+ }
9898
+ function readLockOwner(lock) {
9899
+ let raw;
9900
+ try {
9901
+ raw = fs6.readFileSync(lock, "utf8");
9902
+ } catch (err) {
9903
+ if (err.code === "ENOENT") return void 0;
9904
+ throw err;
9905
+ }
9906
+ let pid = Number(raw.trim());
9907
+ if (!Number.isInteger(pid)) {
9908
+ try {
9909
+ const parsed = JSON.parse(raw);
9910
+ pid = parsed && typeof parsed === "object" && Number.isInteger(parsed.pid) ? parsed.pid : 0;
9911
+ } catch {
9912
+ pid = 0;
9913
+ }
9914
+ }
9915
+ return { pid, raw };
9916
+ }
9917
+ function readLockToken(lock) {
9918
+ try {
9919
+ const parsed = JSON.parse(fs6.readFileSync(lockTokenFile(lock), "utf8"));
9920
+ return parsed && typeof parsed === "object" && typeof parsed.token === "string" ? parsed.token : void 0;
9921
+ } catch {
9922
+ return void 0;
9923
+ }
9924
+ }
9925
+ function ownsLock(lock, token) {
9926
+ return readLockOwner(lock)?.pid === process.pid && readLockToken(lock) === token;
9927
+ }
9928
+ function releaseHeldLocks() {
9929
+ for (const [file, token] of registry2.locks) {
9930
+ const lock = `${file}.lock`;
9931
+ try {
9932
+ if (!ownsLock(lock, token)) continue;
9933
+ fs6.unlinkSync(lockTokenFile(lock));
9934
+ fs6.unlinkSync(lock);
9935
+ } catch {
9936
+ }
9937
+ }
9938
+ }
9524
9939
  function lockChannelFile(file) {
9525
- if (heldLocks.has(file)) return void 0;
9940
+ if (registry2.locks.has(file)) return void 0;
9526
9941
  const lock = `${file}.lock`;
9527
9942
  fs6.mkdirSync(path5.dirname(lock), { recursive: true, mode: 448 });
9943
+ const token = randomUUID();
9528
9944
  for (let attempt = 0; attempt < 2; attempt += 1) {
9945
+ const tmp = `${lock}.${process.pid}.${token}.tmp`;
9529
9946
  try {
9530
- fs6.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
9531
- heldLocks.add(file);
9532
- if (!exitHookInstalled) {
9533
- exitHookInstalled = true;
9534
- process.once("exit", () => {
9535
- for (const held of heldLocks) {
9536
- try {
9537
- fs6.unlinkSync(`${held}.lock`);
9538
- } catch {
9539
- }
9540
- }
9541
- });
9947
+ fs6.writeFileSync(tmp, String(process.pid), { mode: 384 });
9948
+ try {
9949
+ fs6.linkSync(tmp, lock);
9950
+ } catch (err) {
9951
+ const code = err.code;
9952
+ if (code !== "EPERM" && code !== "ENOTSUP" && code !== "EXDEV" && code !== "EOPNOTSUPP") throw err;
9953
+ fs6.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
9954
+ }
9955
+ try {
9956
+ writeLockToken(lock, token);
9957
+ } catch (err) {
9958
+ try {
9959
+ fs6.unlinkSync(lock);
9960
+ } catch {
9961
+ }
9962
+ throw err;
9963
+ }
9964
+ registry2.locks.set(file, token);
9965
+ const id = fileIdentity(lock);
9966
+ if (id) lockIds.set(file, id);
9967
+ else lockIds.delete(file);
9968
+ if (!registry2.exitHook) {
9969
+ registry2.exitHook = true;
9970
+ process.once("exit", releaseHeldLocks);
9542
9971
  }
9543
9972
  return void 0;
9544
9973
  } catch (err) {
9545
9974
  if (err.code !== "EEXIST") throw err;
9975
+ } finally {
9976
+ try {
9977
+ fs6.unlinkSync(tmp);
9978
+ } catch {
9979
+ }
9980
+ }
9981
+ const owner = readLockOwner(lock);
9982
+ if (!owner) continue;
9983
+ if (owner.pid === process.pid) {
9984
+ if (!lockPredatesProcess(lock)) return process.pid;
9985
+ } else if (owner.pid > 0 && processAlive(owner.pid)) {
9986
+ return owner.pid;
9546
9987
  }
9547
- const owner = Number(fs6.readFileSync(lock, "utf8").trim());
9548
- if (Number.isInteger(owner) && owner > 0 && owner !== process.pid && processAlive(owner)) return owner;
9549
9988
  try {
9550
- fs6.unlinkSync(lock);
9989
+ if (readLockOwner(lock)?.raw === owner.raw) fs6.unlinkSync(lock);
9551
9990
  } catch {
9552
9991
  }
9553
9992
  }
9554
9993
  return -1;
9555
9994
  }
9995
+ function writeLockToken(lock, token) {
9996
+ const sidecar = lockTokenFile(lock);
9997
+ const tmp = `${sidecar}.${process.pid}.${token}.tmp`;
9998
+ try {
9999
+ fs6.writeFileSync(tmp, JSON.stringify({ pid: process.pid, token }), { mode: 384 });
10000
+ fs6.renameSync(tmp, sidecar);
10001
+ } finally {
10002
+ try {
10003
+ fs6.unlinkSync(tmp);
10004
+ } catch {
10005
+ }
10006
+ }
10007
+ }
9556
10008
  function pendingDeposit(pending) {
9557
10009
  const entries = Array.isArray(pending) ? pending : [pending];
9558
10010
  return entries.some(
9559
10011
  (entry) => entry?.payment?.payload?.type === "deposit"
9560
10012
  );
9561
10013
  }
9562
- function dropOrphanedPending(storage) {
9563
- return {
9564
- get: async (key) => {
9565
- const record = await storage.get(key);
9566
- if (!record?.pending || record.channelConfig?.voucherSigner !== "server") return record;
9567
- if (!record.hasConfirmedState || pendingDeposit(record.pending)) {
9568
- await storage.delete(key);
9569
- return void 0;
9570
- }
10014
+ var ChannelResyncRequiredError = class extends Error {
10015
+ constructor(channelId) {
10016
+ super(`batch-settlement channel ${channelId ?? "<unknown>"} needs a chain re-read before it is used`);
10017
+ this.channelId = channelId;
10018
+ this.name = "ChannelResyncRequiredError";
10019
+ }
10020
+ channelId;
10021
+ };
10022
+ function isResyncRequired(err) {
10023
+ return err instanceof Error && err.name === "ChannelResyncRequiredError";
10024
+ }
10025
+ function parseAtomic(value) {
10026
+ return typeof value === "string" && /^\d+$/.test(value) ? BigInt(value) : 0n;
10027
+ }
10028
+ function confirmedCumulative(record, channelId) {
10029
+ if (!record || record.channelId !== channelId) return 0n;
10030
+ return record.pending === void 0 || record.hasConfirmedState ? parseAtomic(record.chargedCumulativeAmount) : 0n;
10031
+ }
10032
+ var ChannelBook = class {
10033
+ constructor(base, onUnverified = () => {
10034
+ }) {
10035
+ this.base = base;
10036
+ this.onUnverified = onUnverified;
10037
+ }
10038
+ base;
10039
+ onUnverified;
10040
+ seen = /* @__PURE__ */ new Map();
10041
+ async get(key) {
10042
+ const record = await this.base.get(key);
10043
+ if (record) this.seen.set(key, record);
10044
+ if (!record?.pending || record.channelConfig?.voucherSigner !== "server") return record;
10045
+ if (record.hasConfirmedState && !pendingDeposit(record.pending)) {
9571
10046
  const { pending: _pending, hasConfirmedState: _confirmed, ...confirmed } = record;
9572
- await storage.set(key, confirmed);
10047
+ await this.set(key, confirmed);
9573
10048
  return confirmed;
9574
- },
9575
- set: (key, record) => storage.set(key, record),
9576
- delete: (key) => storage.delete(key)
10049
+ }
10050
+ if (typeof record.channelId === "string") {
10051
+ const pendingEntries = Array.isArray(record.pending) ? record.pending : [record.pending];
10052
+ const inDoubt = pendingEntries.find((entry) => entry?.payment?.payload?.type === "deposit");
10053
+ this.onUnverified({
10054
+ key,
10055
+ channelId: record.channelId,
10056
+ channelConfig: record.channelConfig,
10057
+ cumulative: record.hasConfirmedState ? parseAtomic(record.chargedCumulativeAmount) : 0n,
10058
+ ...record.hasConfirmedState ? { knownDeposit: parseAtomic(record.deposit) } : {},
10059
+ ...inDoubt ? { expectDeposit: parseAtomic(inDoubt.deposit) } : {},
10060
+ reason: "orphaned_deposit"
10061
+ });
10062
+ }
10063
+ throw new ChannelResyncRequiredError(record.channelId);
10064
+ }
10065
+ /**
10066
+ * Store a record, and only once it is stored remember it as the last one
10067
+ * seen. If storing fails (say, while the scheme saves a reconciled
10068
+ * receipt), the scheme reports the receipt unreconciled, and the SDK must
10069
+ * still see the state from before it: `distrust()` adds that call's charge
10070
+ * to it, and a remembered post-receipt cumulative would count it twice.
10071
+ */
10072
+ async set(key, record) {
10073
+ await this.base.set(key, record);
10074
+ this.seen.set(key, record);
10075
+ }
10076
+ async delete(key) {
10077
+ await this.base.delete(key);
10078
+ }
10079
+ /** The keys of every stored channel. */
10080
+ async keys() {
10081
+ return await this.base.keys?.() ?? [];
10082
+ }
10083
+ /** The last record seen for a channel, even one the scheme has deleted since. */
10084
+ find(channelId) {
10085
+ for (const [key, record] of this.seen) {
10086
+ if (record.channelId === channelId) return { key, record };
10087
+ }
10088
+ return void 0;
10089
+ }
10090
+ clear() {
10091
+ this.seen.clear();
10092
+ this.base.clear?.();
10093
+ }
10094
+ /** Forget one channel: its stored record and the last record seen for it. An emptied store is removed. */
10095
+ async forget(key) {
10096
+ this.seen.delete(key);
10097
+ await this.base.delete(key);
10098
+ if ((await this.keys()).length === 0) this.clear();
10099
+ }
10100
+ };
10101
+ var PAYMENT_CHANNELS_PROGRAM_ID = "CHNLxYvVA28MJP9PrFuDXccuoGXAx7jBacfLEkahyGsX";
10102
+ var CHANNEL = {
10103
+ size: 256,
10104
+ rentPayer: 216,
10105
+ discriminator: 1,
10106
+ status: 3,
10107
+ deposit: 12,
10108
+ settled: 20,
10109
+ closureStartedAt: 36,
10110
+ payer: 88,
10111
+ authorizedSigner: 152,
10112
+ mint: 184
10113
+ };
10114
+ function decodeChannelAccount(owner, data) {
10115
+ if (owner !== PAYMENT_CHANNELS_PROGRAM_ID || data.length < CHANNEL.size || data[0] !== CHANNEL.discriminator) {
10116
+ return void 0;
10117
+ }
10118
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
10119
+ const key = (offset) => bs58.encode(data.subarray(offset, offset + 32));
10120
+ return {
10121
+ deposit: view.getBigUint64(CHANNEL.deposit, true),
10122
+ settled: view.getBigUint64(CHANNEL.settled, true),
10123
+ open: data[CHANNEL.status] === 0 && view.getBigInt64(CHANNEL.closureStartedAt, true) === 0n,
10124
+ payer: key(CHANNEL.payer),
10125
+ authorizedSigner: key(CHANNEL.authorizedSigner),
10126
+ mint: key(CHANNEL.mint)
10127
+ };
10128
+ }
10129
+ var ChannelUnreadableError = class extends Error {
10130
+ constructor(channelId, why) {
10131
+ super(`account ${channelId} is on chain but is not a readable payment channel (${why})`);
10132
+ this.name = "ChannelUnreadableError";
10133
+ }
10134
+ };
10135
+ var ChannelLayoutError = class extends Error {
10136
+ constructor(message, options) {
10137
+ super(message, options);
10138
+ this.name = "ChannelLayoutError";
10139
+ }
10140
+ };
10141
+ async function readChannelAccount(rpcUrl, channelId, rpcHeaders, options = {}) {
10142
+ await checkChannelLayout();
10143
+ const config = { encoding: "base64", commitment: "finalized" };
10144
+ if (options.minContextSlot !== void 0) config.minContextSlot = options.minContextSlot;
10145
+ const response = await fetch(rpcUrl, {
10146
+ method: "POST",
10147
+ headers: { ...rpcHeaders, "Content-Type": "application/json" },
10148
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "getAccountInfo", params: [channelId, config] }),
10149
+ signal: AbortSignal.timeout(15e3),
10150
+ // rpcHeaders may carry an API key: never let a redirect take it elsewhere.
10151
+ redirect: "error"
10152
+ });
10153
+ if (!response.ok) throw new Error(`getAccountInfo answered HTTP ${response.status}`);
10154
+ const body = await response.json();
10155
+ if (body.error) throw new Error(`getAccountInfo failed: ${body.error.message ?? JSON.stringify(body.error)}`);
10156
+ if (!body.result || typeof body.result !== "object" || !("value" in body.result)) {
10157
+ throw new Error("getAccountInfo returned no result");
10158
+ }
10159
+ const value = body.result.value;
10160
+ if (value === null) return void 0;
10161
+ if (!value || typeof value !== "object") throw new ChannelUnreadableError(channelId, "malformed account value");
10162
+ if (!Array.isArray(value.data) || typeof value.data[0] !== "string" || value.data[1] !== "base64") {
10163
+ throw new ChannelUnreadableError(channelId, "unsupported data encoding");
10164
+ }
10165
+ const channel = decodeChannelAccount(value.owner, Buffer.from(value.data[0], "base64"));
10166
+ if (!channel) throw new ChannelUnreadableError(channelId, "wrong owner or layout");
10167
+ return channel;
10168
+ }
10169
+ async function rpcRequest(rpcUrl, method, params, rpcHeaders) {
10170
+ const response = await fetch(rpcUrl, {
10171
+ method: "POST",
10172
+ headers: { ...rpcHeaders, "Content-Type": "application/json" },
10173
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
10174
+ signal: AbortSignal.timeout(15e3),
10175
+ // rpcHeaders may carry an API key: never let a redirect take it elsewhere.
10176
+ redirect: "error"
10177
+ });
10178
+ if (!response.ok) throw new Error(`${method} answered HTTP ${response.status}`);
10179
+ const body = await response.json();
10180
+ if (body.error) throw new Error(`${method} failed: ${body.error.message ?? JSON.stringify(body.error)}`);
10181
+ if (body.result === void 0 || body.result === null) throw new Error(`${method} returned no result`);
10182
+ return body.result;
10183
+ }
10184
+ function rpcInteger(value, what) {
10185
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${what} is not a block height or slot`);
10186
+ return value;
10187
+ }
10188
+ var layoutChecked;
10189
+ function checkChannelLayout() {
10190
+ layoutChecked ??= (async () => {
10191
+ const svm = await load("@x402/svm", () => import("@x402/svm")).catch((err) => {
10192
+ throw new ChannelLayoutError(
10193
+ `cannot check the payment-channel account layout: ${err instanceof Error ? err.message : String(err)}`,
10194
+ { cause: err }
10195
+ );
10196
+ });
10197
+ if (svm.CHANNEL_ACCOUNT_SIZE !== BigInt(CHANNEL.size) || svm.CHANNEL_RENT_PAYER_OFFSET !== BigInt(CHANNEL.rentPayer)) {
10198
+ throw new ChannelLayoutError("@x402/svm changed the payment-channel account layout; this SDK cannot read channels from it");
10199
+ }
10200
+ })();
10201
+ layoutChecked.catch(() => {
10202
+ layoutChecked = void 0;
10203
+ });
10204
+ return layoutChecked;
10205
+ }
10206
+ var LANDING_MARGIN_BLOCKS = 300;
10207
+ function maxOf(a, b) {
10208
+ if (a === void 0) return b;
10209
+ if (b === void 0) return a;
10210
+ return a > b ? a : b;
10211
+ }
10212
+ var ResyncError = class extends Error {
10213
+ constructor(reason, message) {
10214
+ super(message);
10215
+ this.reason = reason;
10216
+ this.name = "ResyncError";
10217
+ }
10218
+ reason;
10219
+ };
10220
+ function payloadChannelId(payload) {
10221
+ return payload.payload?.authorization?.channelId ?? payload.payload?.voucher?.channelId;
10222
+ }
10223
+ function clientSignedBatch(accept) {
10224
+ return accept.scheme === BATCH_SCHEME && accept.extra?.voucherSigner !== "server";
10225
+ }
10226
+ function batchUnavailable(paymentRequired) {
10227
+ const batch = (paymentRequired.accepts ?? []).filter((accept) => accept.scheme === BATCH_SCHEME);
10228
+ if (batch.length === 0) return { reason: "not_offered" };
10229
+ if (!batch.every(clientSignedBatch)) return void 0;
10230
+ return {
10231
+ reason: "client_signed_not_supported",
10232
+ detail: "the 402 offers only client-signed batch-settlement accepts; this SDK pays batch only into server-signed (operator) channels"
9577
10233
  };
9578
10234
  }
9579
- function offersBatch(paymentRequired) {
9580
- return (paymentRequired.accepts ?? []).some((accept) => accept.scheme === BATCH_SCHEME);
10235
+ function withoutClientSignedBatch(paymentRequired) {
10236
+ const accepts = paymentRequired.accepts ?? [];
10237
+ return accepts.some(clientSignedBatch) ? { ...paymentRequired, accepts: accepts.filter((accept) => !clientSignedBatch(accept)) } : paymentRequired;
10238
+ }
10239
+ function trustedBatchAccepts(paymentRequired, operators) {
10240
+ return (paymentRequired.accepts ?? []).filter((candidate) => {
10241
+ const extra = candidate.extra;
10242
+ return candidate.scheme === BATCH_SCHEME && extra?.voucherSigner === "server" && operators.includes(extra.operator);
10243
+ });
10244
+ }
10245
+ function trustedBatchAccept(paymentRequired, operators) {
10246
+ return trustedBatchAccepts(paymentRequired, operators)[0];
9581
10247
  }
9582
10248
  function atomicToUsd(amount) {
9583
- return amount !== void 0 && /^\d+$/.test(amount) ? Number(amount) / 1e6 : void 0;
10249
+ return typeof amount === "string" && /^\d+$/.test(amount) ? Number(amount) / 1e6 : void 0;
9584
10250
  }
9585
- async function isBatchRefusal(response) {
9586
- if (response.status === 402) return "payment_required";
10251
+ function chargedUsd(getReceipt) {
10252
+ let receipt;
10253
+ try {
10254
+ receipt = getReceipt();
10255
+ } catch {
10256
+ return 0;
10257
+ }
10258
+ return atomicToUsd(receipt?.extra?.chargedAmount) ?? atomicToUsd(receipt?.amount) ?? 0;
10259
+ }
10260
+ function rebuiltCharge(settled, payload) {
10261
+ if (settled?.success !== true) return 0n;
10262
+ const charged = parseAtomic(typeof settled.extra?.chargedAmount === "string" ? settled.extra.chargedAmount : settled.amount);
10263
+ const ceiling = parseAtomic(payload.accepted?.amount);
10264
+ return charged > ceiling ? ceiling : charged;
10265
+ }
10266
+ function confirmedState(record) {
10267
+ if (!record || !(record.pending === void 0 || record.hasConfirmedState)) return void 0;
10268
+ return { cumulative: parseAtomic(record.chargedCumulativeAmount), deposit: parseAtomic(record.deposit) };
10269
+ }
10270
+ function recordAdvanced(before, after, payload, receipt) {
10271
+ const deposited = payload.payload?.type === "deposit" ? parseAtomic(payload.payload.deposit?.amount) : 0n;
10272
+ const charged = rebuiltCharge(receipt, payload);
10273
+ if (deposited === 0n && charged === 0n) return true;
10274
+ if (!after) return false;
10275
+ const prior = before ?? { cumulative: 0n, deposit: 0n };
10276
+ return after.deposit >= prior.deposit + deposited && after.cumulative >= prior.cumulative + charged;
10277
+ }
10278
+ var BATCH_REFUSALS = /* @__PURE__ */ new Set([
10279
+ "batch_payer_not_allowed",
10280
+ "batch_payer_not_admitted",
10281
+ "batch_admission_paused",
10282
+ "batch_server_signed_only",
10283
+ "batch_unavailable",
10284
+ "batch_channel_limit",
10285
+ "PAYMENT_VERIFICATION_UNAVAILABLE"
10286
+ ]);
10287
+ var PRE_REQUEST_REFUSALS = /* @__PURE__ */ new Set([
10288
+ "batch_payer_not_allowed",
10289
+ "batch_payer_not_admitted",
10290
+ "batch_admission_paused",
10291
+ "batch_server_signed_only",
10292
+ "batch_unavailable",
10293
+ "batch_channel_limit"
10294
+ ]);
10295
+ async function batchRefusal(response) {
9587
10296
  if (![400, 403, 409, 503].includes(response.status)) return void 0;
9588
10297
  let body;
9589
10298
  try {
@@ -9592,20 +10301,254 @@ async function isBatchRefusal(response) {
9592
10301
  return void 0;
9593
10302
  }
9594
10303
  const { error, code } = body ?? {};
9595
- if (code === "PAYMENT_VERIFICATION_UNAVAILABLE") return code;
9596
- return typeof error === "string" && error.startsWith("batch_") ? error : void 0;
10304
+ for (const value of [code, error]) {
10305
+ if (typeof value === "string" && BATCH_REFUSALS.has(value)) return value;
10306
+ }
10307
+ return void 0;
9597
10308
  }
9598
- var wallets = /* @__PURE__ */ new Map();
9599
- var SolanaBatchPayer = class {
9600
- constructor(init) {
9601
- this.init = init;
9602
- const { operators } = init.options;
9603
- if (!Array.isArray(operators) || operators.length === 0 || operators.some((o) => typeof o !== "string" || !o)) {
9604
- throw new Error("batch.operators must list at least one base58 operator public key");
10309
+ async function duplicateAnswer(response) {
10310
+ const codes = [];
10311
+ try {
10312
+ const body = await response.clone().json();
10313
+ if (body && typeof body === "object") codes.push(body.error, body.code, body.reason, body.invalidReason);
10314
+ } catch {
10315
+ }
10316
+ const header = response.headers.get("PAYMENT-REQUIRED");
10317
+ if (header) {
10318
+ try {
10319
+ const challenge = parsePaymentRequired(header);
10320
+ codes.push(challenge.error, challenge.invalidReason);
10321
+ } catch {
10322
+ }
10323
+ }
10324
+ for (const code of codes) {
10325
+ if (typeof code === "string" && /duplicate/i.test(code)) return code;
10326
+ }
10327
+ return void 0;
10328
+ }
10329
+ function cleanRefusalReceipt(receipt) {
10330
+ if (receipt === void 0) return true;
10331
+ return receipt.success === false && !receipt.transaction && receipt.errorReason !== "settlement_pending";
10332
+ }
10333
+ async function afterPaymentError(response) {
10334
+ let body;
10335
+ try {
10336
+ body = await response.clone().json();
10337
+ } catch {
10338
+ body = { error: "Request failed" };
10339
+ }
10340
+ return withDisposition(
10341
+ new APIError(`API error after payment: ${response.status}`, response.status, sanitizeErrorResponse(body)),
10342
+ "paid-or-in-doubt"
10343
+ );
10344
+ }
10345
+ function cancelledReceipt(receipt) {
10346
+ return receipt?.success === false && receipt.errorReason === "batch_cancelled" && !receipt.transaction;
10347
+ }
10348
+ async function cancelledError(response) {
10349
+ let body;
10350
+ try {
10351
+ body = await response.clone().json();
10352
+ } catch {
10353
+ body = { error: "Request failed" };
10354
+ }
10355
+ return withDisposition(new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(body)), "unpaid");
10356
+ }
10357
+ function describeReceipt(receipt) {
10358
+ if (!receipt) return "no receipt";
10359
+ const parts = [`success=${String(receipt.success)}`];
10360
+ if (receipt.errorReason) parts.push(`errorReason=${receipt.errorReason}`);
10361
+ if (receipt.transaction) parts.push(`transaction=${receipt.transaction}`);
10362
+ return `receipt ${parts.join(" ")}`;
10363
+ }
10364
+ var MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1e3;
10365
+ function parseRetryAfter(value, now = Date.now()) {
10366
+ const text = value?.trim();
10367
+ if (!text) return void 0;
10368
+ let ms;
10369
+ if (/^\d+(\.\d+)?$/.test(text)) {
10370
+ ms = Math.round(Number(text) * 1e3);
10371
+ } else {
10372
+ const at = Date.parse(text);
10373
+ if (Number.isNaN(at)) return void 0;
10374
+ ms = Math.max(0, at - now);
10375
+ }
10376
+ return Number.isFinite(ms) && ms <= MAX_RETRY_AFTER_MS ? ms : void 0;
10377
+ }
10378
+ var NOT_BROADCAST_429 = /* @__PURE__ */ new Set([
10379
+ "batch_account_channel_capacity_exhausted",
10380
+ "batch_channel_capacity_exhausted",
10381
+ "batch_deposit_rate_limited"
10382
+ ]);
10383
+ function provesNothingBroadcast(receipt) {
10384
+ return receipt?.success === false && !receipt.transaction && typeof receipt.errorReason === "string" && NOT_BROADCAST_429.has(receipt.errorReason);
10385
+ }
10386
+ function backoffDelay(attempt) {
10387
+ const base = 1e3 * 2 ** Math.max(0, attempt - 1);
10388
+ return Math.round(base * (0.75 + Math.random() * 0.5));
10389
+ }
10390
+ async function rateLimitReason(response, settled) {
10391
+ let body;
10392
+ try {
10393
+ body = await response.clone().json();
10394
+ } catch {
10395
+ body = void 0;
10396
+ }
10397
+ const fields = body ?? {};
10398
+ for (const value of [fields.errorReason, fields.error, fields.code, fields.reason, settled?.errorReason]) {
10399
+ if (typeof value === "string" && value) return value;
10400
+ }
10401
+ return void 0;
10402
+ }
10403
+ function creationFailure(err) {
10404
+ const detail = err instanceof Error ? err.message : String(err);
10405
+ if (err instanceof Error && err.name === "UntrustedOperatorError") return { reason: "untrusted_operator", detail };
10406
+ if (detail.includes("serverSignedChannelsPolicy maxDeposit")) return { reason: "deposit_over_cap", detail };
10407
+ if (detail.includes("has a pending request")) return { reason: "channel_pending", detail };
10408
+ if (detail.includes("requires the optional peer dependency")) return { reason: "peer_dependency_missing", detail };
10409
+ return { reason: "payment_creation_failed", detail };
10410
+ }
10411
+ function logValue(value) {
10412
+ const text = String(value);
10413
+ return /^[\w.:/@+-]+$/.test(text) ? text : JSON.stringify(text);
10414
+ }
10415
+ function formatEvent(event) {
10416
+ const fields = [
10417
+ ["event", event.type],
10418
+ ["reason", event.reason],
10419
+ ["status", event.status],
10420
+ ["errorReason", event.errorReason],
10421
+ ["retryAfterMs", event.retryAfterMs],
10422
+ ["attempt", event.attempt],
10423
+ ["wallet", event.wallet],
10424
+ ["next", event.type === "fallback" ? "exact" : event.type === "backoff" ? "retry" : event.type === "unresolved" ? "raise" : void 0],
10425
+ ["detail", event.detail]
10426
+ ];
10427
+ const parts = fields.filter(([, v]) => v !== void 0 && v !== "").map(([k, v]) => `${k}=${logValue(v)}`);
10428
+ return `[@blockrun/llm] batch-settlement ${parts.join(" ")}`;
10429
+ }
10430
+ var realSleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
10431
+ var sleep2 = realSleep;
10432
+ var warnedNoSizer = false;
10433
+ function channelKeyOf(requirements) {
10434
+ const accept = requirements;
10435
+ const extra = accept?.extra ?? {};
10436
+ if (typeof extra.feePayer !== "string" || typeof extra.withdrawDelay !== "number") return void 0;
10437
+ return [
10438
+ accept.network,
10439
+ accept.asset,
10440
+ accept.payTo,
10441
+ extra.feePayer,
10442
+ extra.withdrawDelay,
10443
+ extra.receiverAuthorizer ?? "",
10444
+ extra.voucherSigner ?? "client",
10445
+ extra.operator ?? ""
10446
+ ].join(":");
10447
+ }
10448
+ function capOutstandingEscrow(scheme, wallet) {
10449
+ const target = scheme;
10450
+ const original = target.resolveDepositAmount;
10451
+ if (typeof original !== "function") {
10452
+ if (!warnedNoSizer) {
10453
+ warnedNoSizer = true;
10454
+ console.error(
10455
+ "[@blockrun/llm] batch-settlement: this @x402/svm does not expose resolveDepositAmount; maxDeposit caps lifetime deposits"
10456
+ );
10457
+ }
10458
+ return;
10459
+ }
10460
+ target.resolveDepositAmount = function(requirements, requestAmount, needed, context, trust, existingDeposit) {
10461
+ const topUp = wallet.topUp;
10462
+ const widened = topUp && existingDeposit > 0n && existingDeposit === topUp.deposit && channelKeyOf(requirements) === topUp.key && typeof trust?.maxDeposit === "bigint" ? { ...trust, maxDeposit: trust.maxDeposit + topUp.settled } : trust;
10463
+ return original.call(this, requirements, requestAmount, needed, context, widened, existingDeposit);
10464
+ };
10465
+ }
10466
+ var RPC_SCOPE_STORE = /* @__PURE__ */ Symbol.for("@blockrun/llm/batch-rpc-scope/v1");
10467
+ var RPC_HEADER_HOOK = /* @__PURE__ */ Symbol.for("@blockrun/llm/batch-rpc-headers/v1");
10468
+ var sharedGlobal = globalThis;
10469
+ var rpcScope = sharedGlobal[RPC_SCOPE_STORE] ??= new AsyncLocalStorage();
10470
+ function requestUrl(input) {
10471
+ return typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
10472
+ }
10473
+ function installRpcHeaderHook() {
10474
+ const current = globalThis.fetch;
10475
+ if (current[RPC_HEADER_HOOK]) return;
10476
+ const hooked = (input, init) => {
10477
+ const scope = rpcScope.getStore();
10478
+ if (!scope || requestUrl(input) !== scope.url) return current(input, init);
10479
+ const headers = new Headers(input instanceof Request ? input.headers : void 0);
10480
+ new Headers(scope.headers).forEach((value, name) => headers.set(name, value));
10481
+ new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
10482
+ return current(input, { ...init, headers, redirect: "error" });
10483
+ };
10484
+ hooked[RPC_HEADER_HOOK] = true;
10485
+ globalThis.fetch = hooked;
10486
+ }
10487
+ function addResyncTarget(wallet, target) {
10488
+ const existing = wallet.resyncs.get(target.key);
10489
+ if (!existing) {
10490
+ wallet.resyncs.set(target.key, target);
10491
+ return;
10492
+ }
10493
+ wallet.resyncs.set(target.key, {
10494
+ ...existing,
10495
+ channelConfig: target.channelConfig,
10496
+ cumulative: maxOf(existing.cumulative, target.cumulative) ?? 0n,
10497
+ expectDeposit: maxOf(existing.expectDeposit, target.expectDeposit),
10498
+ knownDeposit: maxOf(existing.knownDeposit, target.knownDeposit),
10499
+ anchorHeight: existing.anchorHeight === void 0 || target.anchorHeight === void 0 ? existing.anchorHeight ?? target.anchorHeight : Math.max(existing.anchorHeight, target.anchorHeight)
10500
+ });
10501
+ }
10502
+ function intentTarget(intent) {
10503
+ return {
10504
+ key: intent.key,
10505
+ channelId: intent.channelId,
10506
+ channelConfig: intent.channelConfig,
10507
+ cumulative: parseAtomic(intent.cumulative),
10508
+ expectDeposit: parseAtomic(intent.expectDeposit),
10509
+ ...intent.knownDeposit !== void 0 ? { knownDeposit: parseAtomic(intent.knownDeposit) } : {},
10510
+ ...intent.anchorHeight !== void 0 ? { anchorHeight: intent.anchorHeight } : {},
10511
+ reason: "orphaned_deposit"
10512
+ };
10513
+ }
10514
+ var SolanaBatchPayer = class {
10515
+ constructor(init) {
10516
+ this.init = init;
10517
+ const { operators, rateLimit } = init.options;
10518
+ if (!Array.isArray(operators) || operators.length === 0 || operators.some((o) => typeof o !== "string" || !o)) {
10519
+ throw new Error("batch.operators must list at least one base58 operator public key");
10520
+ }
10521
+ this.maxAttempts = rateLimit?.maxAttempts ?? DEFAULT_BATCH_RATE_LIMIT.maxAttempts;
10522
+ this.maxWaitMs = rateLimit?.maxWaitMs ?? DEFAULT_BATCH_RATE_LIMIT.maxWaitMs;
10523
+ if (!Number.isInteger(this.maxAttempts) || this.maxAttempts < 1) {
10524
+ throw new Error("batch.rateLimit.maxAttempts must be an integer >= 1");
10525
+ }
10526
+ if (!Number.isFinite(this.maxWaitMs) || this.maxWaitMs < 0) {
10527
+ throw new Error("batch.rateLimit.maxWaitMs must be a finite number of ms >= 0");
9605
10528
  }
9606
10529
  }
9607
10530
  init;
9608
10531
  state;
10532
+ maxAttempts;
10533
+ maxWaitMs;
10534
+ counters = {
10535
+ fallbacks: 0,
10536
+ fallbacksByReason: {},
10537
+ backoffs: 0,
10538
+ retries: 0,
10539
+ recoveries: 0,
10540
+ resyncs: 0,
10541
+ unresolved: 0,
10542
+ unresolvedByReason: {}
10543
+ };
10544
+ /** A copy of this client's batch counters. */
10545
+ stats() {
10546
+ return {
10547
+ ...this.counters,
10548
+ fallbacksByReason: { ...this.counters.fallbacksByReason },
10549
+ unresolvedByReason: { ...this.counters.unresolvedByReason }
10550
+ };
10551
+ }
9609
10552
  async storeFile() {
9610
10553
  const { channelStore } = this.init.options;
9611
10554
  if (channelStore === false) return void 0;
@@ -9621,20 +10564,63 @@ var SolanaBatchPayer = class {
9621
10564
  const address = await this.init.address();
9622
10565
  const file = await this.storeFile();
9623
10566
  const { operators, maxDeposit } = this.init.options;
9624
- const config = JSON.stringify([[...operators].sort(), String(maxDeposit ?? ""), file ?? null, this.init.rpcUrl]);
9625
- const existing = wallets.get(address);
10567
+ const headers = Object.entries(this.init.rpcHeaders ?? {}).sort(([a], [b]) => a.localeCompare(b));
10568
+ const config = JSON.stringify([[...operators].sort(), String(maxDeposit ?? ""), file ?? null, this.init.rpcUrl, headers]);
10569
+ const existing = registry2.wallets.get(address);
9626
10570
  if (existing) {
9627
- return existing.config === config ? existing : "another client in this process uses this wallet with different batch options";
10571
+ return existing.config === config ? existing : {
10572
+ reason: "wallet_config_conflict",
10573
+ detail: "another client in this process uses this wallet with different batch options"
10574
+ };
9628
10575
  }
9629
10576
  if (file) {
9630
10577
  const owner = lockChannelFile(file);
9631
- if (owner !== void 0) return `channel store ${file} is in use by process ${owner}`;
10578
+ if (owner !== void 0) {
10579
+ return {
10580
+ reason: "channel_store_locked",
10581
+ detail: owner === process.pid ? `channel store ${file} is in use by another copy of @blockrun/llm in this process (or by a process that had this pid and died: remove ${file}.lock if nothing uses it)` : `channel store ${file} is in use by process ${owner}`
10582
+ };
10583
+ }
9632
10584
  }
9633
- const created = { config, busy: false, warned: /* @__PURE__ */ new Set() };
9634
- wallets.set(address, created);
10585
+ const resyncs = /* @__PURE__ */ new Map();
10586
+ const base = file ? new FileChannelStorage(file) : new MemoryChannelStorage();
10587
+ const book = new ChannelBook(base, (target) => addResyncTarget(created, target));
10588
+ const intents = file ? FileIntentJournal.beside(file) : new MemoryIntentJournal();
10589
+ let journaled;
10590
+ try {
10591
+ if (file) intents.adoptLegacy(FileIntentJournal.legacyBeside(file), address);
10592
+ journaled = intents.list();
10593
+ } catch (err) {
10594
+ return {
10595
+ reason: "deposit_journal_unreadable",
10596
+ detail: `cannot read ${intents.file}: ${err instanceof Error ? err.message : String(err)}`
10597
+ };
10598
+ }
10599
+ const created = {
10600
+ config,
10601
+ busy: false,
10602
+ cooldownUntil: 0,
10603
+ active: 0,
10604
+ ...file ? { file } : {},
10605
+ book,
10606
+ resyncs,
10607
+ intents,
10608
+ closes: 0
10609
+ };
10610
+ for (const intent of journaled) addResyncTarget(created, intentTarget(intent));
10611
+ registry2.wallets.set(address, created);
9635
10612
  return created;
9636
10613
  })();
9637
- return this.state;
10614
+ const state = this.state;
10615
+ state.then(
10616
+ (result) => {
10617
+ if ("reason" in result && result.reason !== "wallet_config_conflict" && this.state === state) this.state = void 0;
10618
+ },
10619
+ () => {
10620
+ if (this.state === state) this.state = void 0;
10621
+ }
10622
+ );
10623
+ return state;
9638
10624
  }
9639
10625
  build(wallet) {
9640
10626
  wallet.client ??= (async () => {
@@ -9644,21 +10630,33 @@ var SolanaBatchPayer = class {
9644
10630
  load("@solana/kit", () => import("@solana/kit"))
9645
10631
  ]);
9646
10632
  const signer = await kit.createKeyPairSignerFromBytes(await this.init.secretKey());
9647
- const file = await this.storeFile();
9648
- const storage = file ? dropOrphanedPending(new FileChannelStorage(file)) : void 0;
9649
10633
  const scheme = new svm.BatchSvmScheme(signer, {
9650
10634
  rpcUrl: this.init.rpcUrl,
9651
10635
  serverSignedChannelsPolicy: {
9652
10636
  allowedOperators: this.init.options.operators,
9653
10637
  maxDeposit: this.init.options.maxDeposit ?? svm.DEFAULT_SERVER_SIGNED_MAX_DEPOSIT
9654
10638
  },
9655
- ...storage ? { channelStorage: storage } : {}
10639
+ // Always a store, memory included: a record the SDK repairs from the
10640
+ // chain survives the scheme being rebuilt to pick it up.
10641
+ channelStorage: wallet.book
9656
10642
  });
10643
+ capOutstandingEscrow(scheme, wallet);
9657
10644
  const client = new core.x402Client().register("solana:*", scheme).registerPolicy(scheme.paymentPolicy);
9658
10645
  client.setSpendControls({ maxAmountPerPayment: false });
10646
+ const raw = new core.x402HTTPClient(client);
10647
+ const http = {
10648
+ getPaymentSettleResponse: (getHeader) => raw.getPaymentSettleResponse(getHeader),
10649
+ createPaymentPayload: (paymentRequired) => this.withRpcHeaders(() => raw.createPaymentPayload(paymentRequired)),
10650
+ encodePaymentSignatureHeader: (payload) => raw.encodePaymentSignatureHeader(payload),
10651
+ processPaymentResult: (payload, getHeader, status2) => this.withRpcHeaders(() => raw.processPaymentResult(payload, getHeader, status2))
10652
+ };
10653
+ const loader = scheme.loadChannel;
9659
10654
  return {
9660
- http: new core.x402HTTPClient(client),
9661
- refund: (url) => scheme.refund(url)
10655
+ http,
10656
+ refund: (url, requirements) => this.withRpcHeaders(() => scheme.refund(url, { requirements })),
10657
+ load: async (key) => {
10658
+ if (typeof loader === "function") await loader.call(scheme, key);
10659
+ }
9662
10660
  };
9663
10661
  })();
9664
10662
  wallet.client.catch(() => {
@@ -9666,73 +10664,863 @@ var SolanaBatchPayer = class {
9666
10664
  });
9667
10665
  return wallet.client;
9668
10666
  }
10667
+ /** Run a scheme call so its RPC requests carry this client's `rpcHeaders`. */
10668
+ withRpcHeaders(call) {
10669
+ const headers = this.init.rpcHeaders;
10670
+ if (!headers || Object.keys(headers).length === 0) return call();
10671
+ installRpcHeaderHook();
10672
+ return rpcScope.run({ url: this.init.rpcUrl, headers }, call);
10673
+ }
9669
10674
  /**
9670
- * Drop everything this wallet knows about its channel, on disk and in
9671
- * memory. The next call rebuilds the scheme, which reads the channel's real
9672
- * state (deposit, open or closed) from the chain.
10675
+ * Drop everything this wallet knows about one channel, on disk and in
10676
+ * memory, leaving its other channels' records alone. The scheme is rebuilt
10677
+ * on the next call, without the closed channel in its memory.
9673
10678
  */
9674
- async forget(wallet) {
10679
+ async forget(wallet, key) {
9675
10680
  wallet.client = void 0;
9676
- const file = await this.storeFile();
9677
- if (file) new FileChannelStorage(file).clear();
10681
+ wallet.resyncs.delete(key);
10682
+ await wallet.book.forget(key);
10683
+ this.forgetIntent(wallet, key);
9678
10684
  }
9679
- warn(wallet, reason) {
9680
- if (wallet?.warned.has(reason)) return;
9681
- wallet?.warned.add(reason);
9682
- console.error(`[@blockrun/llm] batch-settlement unavailable (${reason}); paying with exact`);
10685
+ /**
10686
+ * Stop trusting the record of the channel a payload paid into: the next
10687
+ * payment re-reads that channel from the chain first. The scheme has
10688
+ * already restored (or, for an open, dropped) its record; the book still
10689
+ * knows the channel and the cumulative it last confirmed.
10690
+ */
10691
+ distrust(wallet, sent, reason, charged = 0n) {
10692
+ const { payload } = sent;
10693
+ const channelId = payloadChannelId(payload);
10694
+ const known = channelId ? wallet.book.find(channelId) : void 0;
10695
+ if (!channelId || !known) {
10696
+ wallet.client = void 0;
10697
+ let intent;
10698
+ try {
10699
+ intent = sent.key ? wallet.intents.list().find((candidate) => candidate.key === sent.key) : void 0;
10700
+ } catch {
10701
+ intent = void 0;
10702
+ }
10703
+ if (intent) addResyncTarget(wallet, { ...intentTarget(intent), reason });
10704
+ return;
10705
+ }
10706
+ const { key, record } = known;
10707
+ const hasConfirmed = record.pending === void 0 || record.hasConfirmedState;
10708
+ const confirmed = hasConfirmed ? parseAtomic(record.chargedCumulativeAmount) : 0n;
10709
+ const expectDeposit = sent.expectDeposit ?? this.depositExpectation(wallet, payload).expectDeposit;
10710
+ addResyncTarget(wallet, {
10711
+ key,
10712
+ channelId,
10713
+ channelConfig: record.channelConfig,
10714
+ cumulative: confirmed + charged,
10715
+ ...hasConfirmed ? { knownDeposit: parseAtomic(record.deposit) } : {},
10716
+ ...expectDeposit !== void 0 ? { expectDeposit } : {},
10717
+ reason
10718
+ });
10719
+ }
10720
+ /**
10721
+ * The channel's total deposit if a deposit payload landed: the confirmed
10722
+ * deposit plus this one (for an open, nothing plus this one). Undefined for
10723
+ * a payment without a deposit, or a channel the SDK has no record of.
10724
+ */
10725
+ depositExpectation(wallet, payload) {
10726
+ if (payload.payload?.type !== "deposit") return {};
10727
+ const channelId = payloadChannelId(payload);
10728
+ const record = channelId ? wallet.book.find(channelId)?.record : void 0;
10729
+ if (!record) return {};
10730
+ const hasConfirmed = record.pending === void 0 || record.hasConfirmedState;
10731
+ return { expectDeposit: (hasConfirmed ? parseAtomic(record.deposit) : 0n) + parseAtomic(payload.payload.deposit?.amount) };
10732
+ }
10733
+ /**
10734
+ * Re-read every distrusted channel from the chain, at `finalized`
10735
+ * commitment, and rewrite its record: the on-chain deposit, and the highest
10736
+ * of the cumulative the SDK can vouch for, the cumulative the stored record
10737
+ * already confirmed, and the on-chain settled amount. A closing or closed
10738
+ * channel is dropped. The scheme is rebuilt to load the repaired record.
10739
+ *
10740
+ * The stored cumulative is never moved backwards. A deposit's intent can
10741
+ * outlive the receipt that reconciled it (the process died, or the journal
10742
+ * could not be cleared, after the scheme saved the new state), so its
10743
+ * cumulative may predate vouchers the scheme has since confirmed; and
10744
+ * vouchers are redeemed on-chain asynchronously, so `settled` can lag too.
10745
+ * Rewriting the record with either would leave every later voucher
10746
+ * unreconcilable.
10747
+ *
10748
+ * A deposit in doubt is settled by the chain alone:
10749
+ * - landed: the finalized channel holds at least the deposit it would
10750
+ * bring (and at least what the record already claimed);
10751
+ * - never landed: the finalized chain is {@link LANDING_MARGIN_BLOCKS}
10752
+ * past the target's anchor height, and a read at least that recent still
10753
+ * does not show it. An open's record is then dropped; a top-up's channel
10754
+ * is rewritten with the deposit it really has.
10755
+ * Until one of those holds, it is pending. This settles only the deposit:
10756
+ * whether the gateway charged the payment that carried it is never read
10757
+ * from the chain.
10758
+ *
10759
+ * @throws ResyncError when the chain cannot be read, or a deposit may still
10760
+ * land: the caller pays exact and the re-read is tried again next call.
10761
+ * Nothing opens or tops up a channel while any re-read is pending.
10762
+ */
10763
+ async resync(wallet) {
10764
+ for (const target of [...wallet.resyncs.values()]) {
10765
+ const failed = (err) => err instanceof ResyncError ? err : err instanceof ChannelUnreadableError ? new ResyncError("channel_unreadable", err.message) : err instanceof ChannelLayoutError ? new ResyncError("channel_unreadable", `channel ${target.channelId}: ${err.message}`) : new ResyncError(
10766
+ "channel_resync_failed",
10767
+ `could not read channel ${target.channelId} from the chain: ${err instanceof Error ? err.message : String(err)}`
10768
+ );
10769
+ let channel;
10770
+ let expired = false;
10771
+ let stored;
10772
+ try {
10773
+ channel = await this.readOwnChannel(target);
10774
+ const required = maxOf(target.expectDeposit, target.knownDeposit) ?? 0n;
10775
+ if (channel === void 0 || channel.open && channel.deposit < required) {
10776
+ if (target.anchorHeight === void 0) {
10777
+ target.anchorHeight = rpcInteger(
10778
+ await rpcRequest(this.init.rpcUrl, "getBlockHeight", [{ commitment: "confirmed" }], this.init.rpcHeaders),
10779
+ "getBlockHeight"
10780
+ );
10781
+ try {
10782
+ const intent = wallet.intents.list().find((candidate) => candidate.key === target.key);
10783
+ if (intent) wallet.intents.put({ ...intent, anchorHeight: target.anchorHeight });
10784
+ } catch {
10785
+ }
10786
+ }
10787
+ const epoch = await rpcRequest(this.init.rpcUrl, "getEpochInfo", [{ commitment: "finalized" }], this.init.rpcHeaders);
10788
+ const finalizedHeight = rpcInteger(epoch.blockHeight, "getEpochInfo blockHeight");
10789
+ const finalizedSlot = rpcInteger(epoch.absoluteSlot, "getEpochInfo absoluteSlot");
10790
+ if (finalizedHeight <= target.anchorHeight + LANDING_MARGIN_BLOCKS) {
10791
+ throw new ResyncError(
10792
+ "channel_resync_pending",
10793
+ channel === void 0 ? `channel ${target.channelId} is not finalized on chain, and its deposit may still land` : `channel ${target.channelId} holds ${channel.deposit} finalized, short of the ${required} it should hold, and a deposit may still land`
10794
+ );
10795
+ }
10796
+ channel = await this.readOwnChannel(target, finalizedSlot);
10797
+ expired = true;
10798
+ }
10799
+ stored = await wallet.book.base.get(target.key);
10800
+ } catch (err) {
10801
+ throw failed(err);
10802
+ }
10803
+ let outcome;
10804
+ if (typeof stored?.channelId === "string" && stored.channelId !== target.channelId) {
10805
+ outcome = `the record under its key now names channel ${stored.channelId}; left untouched`;
10806
+ } else if (channel === void 0) {
10807
+ await wallet.book.delete(target.key);
10808
+ outcome = "no such channel at finalized commitment, past its deposit's last valid block; record dropped";
10809
+ } else if (!channel.open) {
10810
+ await wallet.book.delete(target.key);
10811
+ outcome = "channel is closing or closed; record dropped";
10812
+ } else {
10813
+ const cumulative = maxOf(maxOf(target.cumulative, channel.settled), confirmedCumulative(stored, target.channelId)) ?? 0n;
10814
+ await wallet.book.set(target.key, {
10815
+ channelConfig: target.channelConfig,
10816
+ channelId: target.channelId,
10817
+ chargedCumulativeAmount: cumulative.toString(),
10818
+ deposit: channel.deposit.toString()
10819
+ });
10820
+ outcome = `record rewritten from finalized chain: deposit=${channel.deposit} settled=${channel.settled} cumulative=${cumulative}` + (expired ? " (the deposit in doubt never landed)" : "");
10821
+ }
10822
+ wallet.resyncs.delete(target.key);
10823
+ this.forgetIntent(wallet, target.key);
10824
+ wallet.client = void 0;
10825
+ await this.report({ type: "resync", reason: target.reason, detail: `channel ${target.channelId}: ${outcome}` });
10826
+ }
10827
+ }
10828
+ /**
10829
+ * A distrusted channel's account at `finalized` commitment, checked to be
10830
+ * this wallet's channel for the record's operator and mint.
10831
+ *
10832
+ * @throws ResyncError (`channel_unreadable`) for any other payment channel.
10833
+ */
10834
+ async readOwnChannel(target, minContextSlot) {
10835
+ const channel = await readChannelAccount(this.init.rpcUrl, target.channelId, this.init.rpcHeaders, { minContextSlot });
10836
+ if (channel !== void 0 && (channel.payer !== await this.init.address() || channel.authorizedSigner !== target.channelConfig.payerAuthorizer || channel.mint !== target.channelConfig.token)) {
10837
+ throw new ResyncError("channel_unreadable", `account ${target.channelId} is a payment channel for another payer, operator or mint`);
10838
+ }
10839
+ return channel;
10840
+ }
10841
+ /**
10842
+ * Make one event observable three ways: a stderr line (every time, never
10843
+ * deduplicated), this client's counters, and the caller's `onEvent`.
10844
+ */
10845
+ async report(event) {
10846
+ let wallet;
10847
+ try {
10848
+ wallet = await this.init.address();
10849
+ } catch {
10850
+ wallet = "unknown";
10851
+ }
10852
+ const full = { ...event, wallet, at: Date.now() };
10853
+ if (full.type === "fallback") {
10854
+ this.counters.fallbacks += 1;
10855
+ this.counters.fallbacksByReason[full.reason] = (this.counters.fallbacksByReason[full.reason] ?? 0) + 1;
10856
+ } else if (full.type === "backoff") {
10857
+ this.counters.backoffs += 1;
10858
+ } else if (full.type === "recovered") {
10859
+ this.counters.recoveries += 1;
10860
+ } else if (full.type === "unresolved") {
10861
+ this.counters.unresolved += 1;
10862
+ this.counters.unresolvedByReason[full.reason] = (this.counters.unresolvedByReason[full.reason] ?? 0) + 1;
10863
+ } else {
10864
+ this.counters.resyncs += 1;
10865
+ }
10866
+ console.error(formatEvent(full));
10867
+ const failed = (err) => console.error(
10868
+ `[@blockrun/llm] batch-settlement onEvent callback threw: ${JSON.stringify(err instanceof Error ? err.message : String(err))}`
10869
+ );
10870
+ try {
10871
+ const result = this.init.options.onEvent?.(full);
10872
+ if (result && typeof result.then === "function") {
10873
+ result.then(void 0, failed);
10874
+ }
10875
+ } catch (err) {
10876
+ failed(err);
10877
+ }
10878
+ }
10879
+ /** Report a fallback and tell the caller to pay exact. */
10880
+ async fallback(event) {
10881
+ await this.report({ type: "fallback", ...event });
10882
+ return { kind: "fallback", reason: event.reason };
9683
10883
  }
9684
10884
  /**
9685
10885
  * Pay one 402 with batch-settlement, or say why the caller should use exact.
9686
10886
  *
9687
- * `send` replays the original request with the payment headers. The
9688
- * returned response is 2xx; any other answer either becomes a fallback (the
9689
- * gateway charged nothing) or is returned to the caller's own error path.
10887
+ * `send` replays the original request with the payment headers. Every send
10888
+ * goes through {@link sendOnce}, the one place an answer is classified as
10889
+ * charged, not charged, or in doubt:
10890
+ *
10891
+ * - charged: the 2xx is returned (`paid`);
10892
+ * - not charged (the gateway's explicit answer to a first send): a 429
10893
+ * whose receipt proves nothing was broadcast is backed off
10894
+ * (`Retry-After`, else 1s, 2s, 4s with jitter) and paid again with a new
10895
+ * payment built from a fresh 402 (`rechallenge`: the original's
10896
+ * `recentBlockhash` / `recentSlot` can be stale by then), within
10897
+ * `rateLimit.maxAttempts` / `maxWaitMs`, then with exact; any other is
10898
+ * paid with exact (`fallback`). A fresh challenge served with a 2xx is
10899
+ * the call's result (`served`, nothing paid); one that fails otherwise
10900
+ * is the call's error (`failed`, `"unpaid"`), never an exact payment
10901
+ * against the stale challenge;
10902
+ * - in doubt: ends only with a definitive success receipt from the one
10903
+ * replay a receipt-less 429 is allowed ({@link resolveInDoubt}), or a
10904
+ * thrown {@link BatchPaymentUnresolvedError}. No new authorization, no
10905
+ * new deposit, no exact payment and no fallback model is ever paid for a
10906
+ * call in doubt.
10907
+ *
10908
+ * The wallet stays in cooldown after a 429, so its other calls wait
10909
+ * instead of sending opens of their own.
10910
+ *
10911
+ * @param closesAtStart - {@link closeFence}, taken before the call's first
10912
+ * (unpaid) request. If a close completed since, the call pays exact
10913
+ * (`closed_during_call`): it started before the close, so it must not
10914
+ * open a channel the caller believes is closed.
9690
10915
  */
9691
- async pay(paymentRequired, send) {
9692
- if (!offersBatch(paymentRequired)) return { kind: "fallback", reason: "not_offered" };
9693
- const wallet = await this.wallet();
9694
- if (typeof wallet === "string") {
9695
- this.warn(void 0, wallet);
9696
- return { kind: "fallback", reason: wallet };
10916
+ async pay(paymentRequired, send, rechallenge, closesAtStart) {
10917
+ const unavailable = batchUnavailable(paymentRequired);
10918
+ if (unavailable) return this.fallback(unavailable);
10919
+ let wallet;
10920
+ try {
10921
+ wallet = await this.wallet();
10922
+ } catch (err) {
10923
+ return this.fallback(creationFailure(err));
9697
10924
  }
9698
- if (wallet.busy) return { kind: "fallback", reason: "channel_busy" };
9699
- wallet.busy = true;
10925
+ if ("reason" in wallet) return this.fallback({ reason: wallet.reason, detail: wallet.detail });
10926
+ if (closesAtStart !== void 0 && wallet.closes !== closesAtStart) {
10927
+ return this.fallback({
10928
+ reason: "closed_during_call",
10929
+ detail: "closeBatchChannel() closed this wallet's channel after this call started; it opens no channel"
10930
+ });
10931
+ }
10932
+ wallet.active += 1;
9700
10933
  try {
9701
- let http;
9702
- let payload;
9703
- try {
9704
- http = (await this.build(wallet)).http;
9705
- payload = await http.createPaymentPayload(paymentRequired);
9706
- } catch (err) {
9707
- const reason = err instanceof Error ? err.message : String(err);
9708
- this.warn(wallet, reason);
9709
- return { kind: "fallback", reason };
10934
+ return await this.payWith(wallet, paymentRequired, send, rechallenge, closesAtStart ?? wallet.closes);
10935
+ } finally {
10936
+ wallet.active -= 1;
10937
+ }
10938
+ }
10939
+ /**
10940
+ * The close fence for a call about to send its first request: how many
10941
+ * closes this wallet has completed so far, to hand to {@link pay}.
10942
+ * `close()` refuses while a call is inside `pay()`, but a call still
10943
+ * waiting for its 402 is not there yet; the fence covers that window.
10944
+ * Undefined when the wallet cannot be named (no fence then; `pay()`
10945
+ * reports why batch is unavailable).
10946
+ */
10947
+ async closeFence() {
10948
+ try {
10949
+ return registry2.wallets.get(await this.init.address())?.closes ?? 0;
10950
+ } catch {
10951
+ return void 0;
10952
+ }
10953
+ }
10954
+ /** {@link pay}, for a wallet this client may use. */
10955
+ async payWith(wallet, paymentRequired, send, rechallenge, fence) {
10956
+ let current = paymentRequired;
10957
+ const fallback = async (event) => {
10958
+ const result = await this.fallback(event);
10959
+ return current === paymentRequired ? result : { ...result, paymentRequired: current };
10960
+ };
10961
+ const budget = { attempt: 1, waited: 0 };
10962
+ let waitedUntil = 0;
10963
+ let backedOff;
10964
+ let holding = false;
10965
+ let sent;
10966
+ const release = () => {
10967
+ if (holding) wallet.busy = false;
10968
+ holding = false;
10969
+ };
10970
+ try {
10971
+ for (; ; ) {
10972
+ const now = Date.now();
10973
+ if (wallet.cooldownUntil > now && wallet.cooldownUntil !== waitedUntil) {
10974
+ const wait = wallet.cooldownUntil - now;
10975
+ if (budget.waited + wait > this.maxWaitMs) {
10976
+ return fallback({
10977
+ reason: "rate_limited",
10978
+ retryAfterMs: wait,
10979
+ attempt: budget.attempt,
10980
+ detail: "wallet is in a 429 cooldown longer than batch.rateLimit.maxWaitMs allows"
10981
+ });
10982
+ }
10983
+ await this.report({ type: "backoff", reason: "cooldown", retryAfterMs: wait, attempt: budget.attempt });
10984
+ backedOff ??= "cooldown";
10985
+ waitedUntil = wallet.cooldownUntil;
10986
+ budget.waited += wait;
10987
+ await sleep2(wait);
10988
+ continue;
10989
+ }
10990
+ if (budget.attempt > 1 || budget.waited > 0) {
10991
+ let fresh;
10992
+ try {
10993
+ fresh = await rechallenge();
10994
+ } catch (err) {
10995
+ return { kind: "failed", error: withDisposition(err instanceof Error ? err : new Error(String(err)), "unpaid") };
10996
+ }
10997
+ if (fresh.kind === "served") {
10998
+ await this.report({
10999
+ type: "recovered",
11000
+ reason: "served_unpaid_on_rechallenge",
11001
+ status: fresh.response.status,
11002
+ attempt: budget.attempt,
11003
+ detail: "the fresh challenge after the wait was served without a payment; nothing was paid"
11004
+ });
11005
+ return { kind: "served", response: fresh.response };
11006
+ }
11007
+ current = fresh.paymentRequired;
11008
+ const unavailable = batchUnavailable(current);
11009
+ if (unavailable) return fallback({ ...unavailable, attempt: budget.attempt });
11010
+ }
11011
+ if (wallet.closes !== fence) {
11012
+ return fallback({
11013
+ reason: "closed_during_call",
11014
+ attempt: budget.attempt,
11015
+ detail: "closeBatchChannel() closed this wallet's channel after this call started; it opens no channel"
11016
+ });
11017
+ }
11018
+ if (wallet.busy) return fallback({ reason: "channel_busy", attempt: budget.attempt });
11019
+ if (wallet.file && !holdsChannelFile(wallet.file)) {
11020
+ return fallback({
11021
+ reason: "channel_store_locked",
11022
+ attempt: budget.attempt,
11023
+ detail: `this process no longer holds the lock on ${wallet.file}; another owner may be paying into its channels`
11024
+ });
11025
+ }
11026
+ wallet.busy = true;
11027
+ holding = true;
11028
+ let built;
11029
+ try {
11030
+ built = await this.buildPayment(wallet, current);
11031
+ } catch (err) {
11032
+ release();
11033
+ if (err instanceof ResyncError) return fallback({ reason: err.reason, detail: err.message, attempt: budget.attempt });
11034
+ return fallback({ ...creationFailure(err), attempt: budget.attempt });
11035
+ }
11036
+ if (built.kind !== "authorization") {
11037
+ try {
11038
+ this.journalDeposit(wallet, built);
11039
+ } catch (err) {
11040
+ await this.settle(built.http, built.payload, () => null, 0);
11041
+ release();
11042
+ return fallback({
11043
+ reason: "deposit_journal_failed",
11044
+ attempt: budget.attempt,
11045
+ detail: err instanceof Error ? err.message : String(err)
11046
+ });
11047
+ }
11048
+ }
11049
+ sent = built;
11050
+ const outcome = await this.sendOnce(wallet, built, send, backedOff === "rate_limited", false);
11051
+ if (outcome.kind === "charged") {
11052
+ if (built.kind !== "authorization" && !(built.key && wallet.resyncs.has(built.key))) this.forgetIntent(wallet, built.key);
11053
+ sent = void 0;
11054
+ release();
11055
+ if (backedOff) await this.report({ type: "recovered", reason: backedOff, attempt: budget.attempt });
11056
+ return { kind: "paid", response: outcome.response, chargedUsd: outcome.chargedUsd };
11057
+ }
11058
+ if (outcome.kind === "not_charged") {
11059
+ if (built.kind !== "authorization") {
11060
+ if (outcome.depositSafe) this.forgetIntent(wallet, built.key);
11061
+ else this.distrust(wallet, built, "deposit_refused");
11062
+ }
11063
+ sent = void 0;
11064
+ release();
11065
+ if (!outcome.rateLimited) {
11066
+ const { kind: _kind, rateLimited: _limited, depositSafe: _safe, ...event } = outcome;
11067
+ return fallback({ ...event, attempt: budget.attempt });
11068
+ }
11069
+ const wait = this.coolDown(wallet, outcome.rateLimited.retryAfterMs ?? backoffDelay(budget.attempt));
11070
+ if (budget.attempt >= this.maxAttempts || budget.waited + wait > this.maxWaitMs) {
11071
+ return fallback({
11072
+ reason: "rate_limited",
11073
+ status: 429,
11074
+ errorReason: outcome.errorReason,
11075
+ retryAfterMs: wait,
11076
+ attempt: budget.attempt,
11077
+ detail: budget.attempt >= this.maxAttempts ? "batch.rateLimit.maxAttempts reached" : "Retry-After exceeds what is left of batch.rateLimit.maxWaitMs"
11078
+ });
11079
+ }
11080
+ await this.report({
11081
+ type: "backoff",
11082
+ reason: "rate_limited",
11083
+ status: 429,
11084
+ errorReason: outcome.errorReason,
11085
+ retryAfterMs: wait,
11086
+ attempt: budget.attempt
11087
+ });
11088
+ backedOff = "rate_limited";
11089
+ waitedUntil = wallet.cooldownUntil;
11090
+ budget.waited += wait;
11091
+ await sleep2(wait);
11092
+ budget.attempt += 1;
11093
+ continue;
11094
+ }
11095
+ if (outcome.kind === "cancelled") {
11096
+ sent = void 0;
11097
+ release();
11098
+ await this.report({
11099
+ type: "recovered",
11100
+ reason: "batch_cancelled",
11101
+ status: outcome.status,
11102
+ errorReason: "batch_cancelled",
11103
+ attempt: budget.attempt,
11104
+ detail: "the gateway cancelled the payment: nothing was charged, and its error is raised unpaid"
11105
+ });
11106
+ return { kind: "failed", error: outcome.error };
11107
+ }
11108
+ const resolved = await this.resolveInDoubt(wallet, built, outcome, send, budget);
11109
+ if (resolved.kind === "charged") {
11110
+ if (built.kind !== "authorization" && !(built.key && wallet.resyncs.has(built.key))) this.forgetIntent(wallet, built.key);
11111
+ sent = void 0;
11112
+ release();
11113
+ await this.report({ type: "recovered", reason: "rate_limited", attempt: budget.attempt });
11114
+ return { kind: "paid", response: resolved.response, chargedUsd: resolved.chargedUsd };
11115
+ }
11116
+ return await this.raiseUnresolved(wallet, built, resolved, budget.attempt);
11117
+ }
11118
+ } catch (err) {
11119
+ if (err instanceof Error && err.name === "BatchPaymentUnresolvedError") throw err;
11120
+ if (sent) {
11121
+ try {
11122
+ return await this.raiseUnresolved(
11123
+ wallet,
11124
+ sent,
11125
+ {
11126
+ kind: "in_doubt",
11127
+ reason: "outcome_unknown",
11128
+ replayable: false,
11129
+ settled: false,
11130
+ detail: `an error after the payment was sent: ${err instanceof Error ? err.message : String(err)}`,
11131
+ cause: err
11132
+ },
11133
+ budget.attempt
11134
+ );
11135
+ } catch (raised) {
11136
+ throw withDisposition(raised, "paid-or-in-doubt");
11137
+ }
11138
+ }
11139
+ return fallback({ ...creationFailure(err), attempt: budget.attempt });
11140
+ } finally {
11141
+ release();
11142
+ }
11143
+ }
11144
+ /**
11145
+ * Put the wallet in a 429 cooldown for `delay` ms (`Retry-After`, or the
11146
+ * default backoff), and return how long this call would have to wait.
11147
+ *
11148
+ * The shared cooldown is capped at `rateLimit.maxWaitMs`, so one header,
11149
+ * however long, never keeps the wallet's calls off batch for longer than
11150
+ * the retry budget. This call still weighs the full delay: one it cannot
11151
+ * wait out within its budget is not waited at all, and the caller pays
11152
+ * exact (or raises a payment in doubt) at once.
11153
+ */
11154
+ coolDown(wallet, delay) {
11155
+ const limitedAt = Date.now();
11156
+ wallet.cooldownUntil = Math.max(wallet.cooldownUntil, limitedAt + Math.min(delay, this.maxWaitMs));
11157
+ return Math.max(delay, wallet.cooldownUntil - limitedAt);
11158
+ }
11159
+ /**
11160
+ * Try to end a payment in doubt with the gateway's own word.
11161
+ *
11162
+ * The one source of evidence this SDK accepts today is a definitive
11163
+ * success receipt on the single byte-identical replay a 429 without a
11164
+ * receipt is allowed, after its backoff (the owner's bounded safety
11165
+ * attempt). Any other answer to it (a 402 or `duplicate_settlement`, which
11166
+ * mean the original reached the gateway; another 429; a 5xx; a timeout)
11167
+ * leaves it in doubt. Every other in-doubt outcome is never replayed.
11168
+ *
11169
+ * Chain state is not evidence here: it can settle a deposit (see
11170
+ * `resync`), never whether the gateway charged. Gateway-side evidence (a
11171
+ * receipt on every response, a request-status endpoint with a fence)
11172
+ * plugs in here, before the caller raises.
11173
+ *
11174
+ * @returns the charged replay, or the doubt to raise.
11175
+ */
11176
+ async resolveInDoubt(wallet, sent, doubt, send, budget) {
11177
+ if (!doubt.replayable) return doubt;
11178
+ const wait = this.coolDown(wallet, doubt.retryAfterMs ?? backoffDelay(budget.attempt));
11179
+ if (budget.attempt >= this.maxAttempts || budget.waited + wait > this.maxWaitMs) {
11180
+ return {
11181
+ ...doubt,
11182
+ detail: `${doubt.detail}; batch.rateLimit leaves no room for its one replay`
11183
+ };
11184
+ }
11185
+ await this.report({
11186
+ type: "backoff",
11187
+ reason: "rate_limited",
11188
+ status: 429,
11189
+ errorReason: doubt.errorReason,
11190
+ retryAfterMs: wait,
11191
+ attempt: budget.attempt
11192
+ });
11193
+ budget.waited += wait;
11194
+ await sleep2(wait);
11195
+ budget.attempt += 1;
11196
+ const replayed = await this.sendOnce(wallet, sent, send, true, true);
11197
+ if (replayed.kind === "charged") return replayed;
11198
+ return replayed.kind === "in_doubt" ? replayed : { kind: "in_doubt", reason: "replay_unresolved", replayable: false, settled: true, detail: "the replay was refused" };
11199
+ }
11200
+ /**
11201
+ * Raise a payment in doubt: release the scheme's hold on it (the channel
11202
+ * goes back to its confirmed state), put a deposit's channel in doubt so
11203
+ * it is re-read from the chain before anything pays into it again, report
11204
+ * the `unresolved` event, and throw {@link BatchPaymentUnresolvedError}.
11205
+ */
11206
+ async raiseUnresolved(wallet, sent, doubt, attempt) {
11207
+ if (!doubt.settled) await this.settle(sent.http, sent.payload, () => null, 0);
11208
+ if (sent.kind !== "authorization") {
11209
+ this.distrust(
11210
+ wallet,
11211
+ sent,
11212
+ doubt.reason === "no_response" ? "deposit_unanswered" : doubt.reason === "replay_unresolved" ? "deposit_rate_limited" : "deposit_failed"
11213
+ );
11214
+ }
11215
+ await this.report({
11216
+ type: "unresolved",
11217
+ reason: doubt.reason,
11218
+ status: doubt.status,
11219
+ errorReason: doubt.errorReason,
11220
+ attempt,
11221
+ detail: `${doubt.detail}; it may have been charged, so it is not paid again`
11222
+ });
11223
+ throw new BatchPaymentUnresolvedError({
11224
+ reason: doubt.reason,
11225
+ wallet: await this.init.address(),
11226
+ requestId: sent.payload.payload?.authorization?.requestId,
11227
+ channelId: payloadChannelId(sent.payload),
11228
+ payloadKind: sent.kind,
11229
+ status: doubt.status,
11230
+ detail: doubt.detail,
11231
+ cause: doubt.cause
11232
+ });
11233
+ }
11234
+ /** Build a new batch payment for a 402: the payload, its headers and its kind. */
11235
+ async buildPayment(wallet, paymentRequired) {
11236
+ const { http, payload } = await this.createPayload(wallet, paymentRequired);
11237
+ const headers = http.encodePaymentSignatureHeader(payload);
11238
+ const channelId = payloadChannelId(payload);
11239
+ const known = channelId ? wallet.book.find(channelId) : void 0;
11240
+ let kind = "authorization";
11241
+ if (payload.payload?.type === "deposit") {
11242
+ const record = known?.record;
11243
+ kind = record && (record.pending === void 0 || record.hasConfirmedState) ? "top-up" : "open";
11244
+ }
11245
+ return { http, payload, headers, kind, key: known?.key, sentAt: Date.now(), sends: 0 };
11246
+ }
11247
+ /**
11248
+ * Write a deposit's intent to the wallet's journal before it is sent
11249
+ * (with the file store: the file and its directory fsynced).
11250
+ *
11251
+ * @throws when it cannot be recorded; the deposit must then not be sent.
11252
+ */
11253
+ journalDeposit(wallet, sent) {
11254
+ const channelId = payloadChannelId(sent.payload);
11255
+ const record = channelId ? wallet.book.find(channelId)?.record : void 0;
11256
+ const { expectDeposit } = this.depositExpectation(wallet, sent.payload);
11257
+ if (!sent.key || !channelId || !record || expectDeposit === void 0 || sent.kind === "authorization") {
11258
+ throw new Error("the deposit's channel record is missing");
11259
+ }
11260
+ const hasConfirmed = record.pending === void 0 || record.hasConfirmedState;
11261
+ sent.expectDeposit = expectDeposit;
11262
+ wallet.intents.put({
11263
+ key: sent.key,
11264
+ channelId,
11265
+ channelConfig: record.channelConfig,
11266
+ requestId: sent.payload.payload?.authorization?.requestId,
11267
+ kind: sent.kind,
11268
+ cumulative: hasConfirmed ? String(parseAtomic(record.chargedCumulativeAmount)) : "0",
11269
+ expectDeposit: expectDeposit.toString(),
11270
+ ...hasConfirmed ? { knownDeposit: String(parseAtomic(record.deposit)) } : {},
11271
+ at: Date.now()
11272
+ });
11273
+ }
11274
+ /**
11275
+ * Remove a deposit's intent once it is reconciled. A failure is logged,
11276
+ * not thrown: the intent then outlives its deposit, and after a restart
11277
+ * the chain re-read settles it again.
11278
+ */
11279
+ forgetIntent(wallet, key) {
11280
+ if (!key) return;
11281
+ try {
11282
+ wallet.intents.remove(key);
11283
+ } catch (err) {
11284
+ console.error(
11285
+ `[@blockrun/llm] batch-settlement could not clear a deposit intent: ${JSON.stringify(err instanceof Error ? err.message : String(err))}`
11286
+ );
11287
+ }
11288
+ }
11289
+ /**
11290
+ * THE choke point: send a batch payment once and classify the answer.
11291
+ *
11292
+ * The only caller of `send` for a batch payment, and the only place its
11293
+ * outcome is decided (see {@link SendOutcome}). Every exception once the
11294
+ * send has started is `in_doubt`, whatever its type or `cause.code`: the
11295
+ * request may have reached the gateway. "Not charged" is only ever minted
11296
+ * here, and only for a first send.
11297
+ *
11298
+ * @param retry - count this send in `retries` (it follows this call's own 429).
11299
+ * @param replay - this is the one replay of a receipt-less 429: only a 2xx
11300
+ * with a success receipt counts, everything else stays in doubt.
11301
+ */
11302
+ async sendOnce(wallet, sent, send, retry, replay) {
11303
+ if (retry) this.counters.retries += 1;
11304
+ sent.sends += 1;
11305
+ let response;
11306
+ try {
11307
+ response = await send(sent.headers);
11308
+ } catch (err) {
11309
+ return {
11310
+ kind: "in_doubt",
11311
+ reason: replay ? "replay_unresolved" : "no_response",
11312
+ replayable: false,
11313
+ settled: false,
11314
+ detail: `${replay ? "the replay" : "the payment"} got no answer (${err instanceof Error ? `${err.name}: ${err.message}` : String(err)})`,
11315
+ cause: err
11316
+ };
11317
+ }
11318
+ try {
11319
+ return await this.classify(wallet, sent, response, replay);
11320
+ } catch (err) {
11321
+ return {
11322
+ kind: "in_doubt",
11323
+ reason: replay ? "replay_unresolved" : "outcome_unknown",
11324
+ replayable: false,
11325
+ settled: false,
11326
+ status: response.status,
11327
+ detail: `the answer could not be classified (${err instanceof Error ? err.message : String(err)})`,
11328
+ cause: err
11329
+ };
11330
+ }
11331
+ }
11332
+ /** {@link sendOnce}'s classifier, for an HTTP answer. */
11333
+ async classify(wallet, sent, response, replay) {
11334
+ const { http, payload } = sent;
11335
+ const getHeader = (name) => response.headers.get(name);
11336
+ const receipted = Boolean(getHeader("PAYMENT-RESPONSE") || getHeader("X-PAYMENT-RESPONSE"));
11337
+ const status2 = response.status;
11338
+ if (status2 === 429 && !receipted) {
11339
+ return {
11340
+ kind: "in_doubt",
11341
+ reason: "replay_unresolved",
11342
+ replayable: !replay,
11343
+ settled: false,
11344
+ status: status2,
11345
+ retryAfterMs: parseRetryAfter(getHeader("retry-after")),
11346
+ errorReason: await rateLimitReason(response, void 0),
11347
+ detail: replay ? "the replay was answered 429 without a receipt" : "a 429 without a receipt"
11348
+ };
11349
+ }
11350
+ const channelId = payloadChannelId(payload);
11351
+ const before = channelId ? confirmedState(wallet.book.find(channelId)?.record) : void 0;
11352
+ const reconciled = await this.settle(http, payload, getHeader, status2);
11353
+ const receipt = reconciled.settleResponse;
11354
+ const definitive = receipt?.success === true && reconciled.ok && recordAdvanced(before, channelId ? confirmedState(wallet.book.find(channelId)?.record) : void 0, payload, receipt);
11355
+ if (!response.ok && !replay && sent.kind === "authorization" && cancelledReceipt(receipt)) {
11356
+ return { kind: "cancelled", status: status2, error: await cancelledError(response) };
11357
+ }
11358
+ if (response.ok && (!replay || definitive)) {
11359
+ if (!definitive) {
11360
+ this.distrust(wallet, sent, receipt ? "receipt_unreconciled" : "receipt_missing", rebuiltCharge(receipt, payload));
9710
11361
  }
9711
- const deposit = payload.payload?.type === "deposit";
9712
- let response;
11362
+ return { kind: "charged", response, chargedUsd: chargedUsd(() => http.getPaymentSettleResponse(getHeader)) };
11363
+ }
11364
+ if (replay) {
11365
+ return {
11366
+ kind: "in_doubt",
11367
+ reason: "replay_unresolved",
11368
+ replayable: false,
11369
+ settled: true,
11370
+ status: status2,
11371
+ errorReason: status2 === 429 ? await rateLimitReason(response, receipt) : receipt?.errorReason,
11372
+ detail: `the replay was answered ${status2} with ${describeReceipt(receipt)}`,
11373
+ cause: await afterPaymentError(response)
11374
+ };
11375
+ }
11376
+ if (status2 === 429) {
11377
+ if (provesNothingBroadcast(receipt)) {
11378
+ return {
11379
+ kind: "not_charged",
11380
+ reason: "rate_limited",
11381
+ status: status2,
11382
+ errorReason: await rateLimitReason(response, receipt),
11383
+ rateLimited: { retryAfterMs: parseRetryAfter(getHeader("retry-after")) },
11384
+ // The facilitator's explicit failed receipt names no transaction: the
11385
+ // deposit was never broadcast (see provesNothingBroadcast).
11386
+ depositSafe: true
11387
+ };
11388
+ }
11389
+ return {
11390
+ kind: "in_doubt",
11391
+ reason: "ambiguous_rate_limit",
11392
+ replayable: false,
11393
+ settled: true,
11394
+ status: status2,
11395
+ errorReason: await rateLimitReason(response, receipt),
11396
+ detail: `a 429 whose ${describeReceipt(receipt)} does not prove nothing was broadcast`,
11397
+ cause: await afterPaymentError(response)
11398
+ };
11399
+ }
11400
+ if (cleanRefusalReceipt(receipt)) {
11401
+ if (status2 === 402) {
11402
+ const duplicate = await duplicateAnswer(response);
11403
+ if (duplicate) {
11404
+ return {
11405
+ kind: "in_doubt",
11406
+ reason: "duplicate_settlement",
11407
+ replayable: false,
11408
+ settled: true,
11409
+ status: status2,
11410
+ errorReason: duplicate,
11411
+ detail: `the payment was answered 402 ${duplicate}: another copy of this request reached the gateway`,
11412
+ cause: await afterPaymentError(response)
11413
+ };
11414
+ }
11415
+ return { kind: "not_charged", reason: "payment_required", status: status2, errorReason: receipt?.errorReason, depositSafe: provesNothingBroadcast(receipt) };
11416
+ }
11417
+ const refusal = await batchRefusal(response);
11418
+ if (refusal) {
11419
+ return { kind: "not_charged", reason: refusal, status: status2, errorReason: refusal, depositSafe: PRE_REQUEST_REFUSALS.has(refusal) };
11420
+ }
11421
+ }
11422
+ return {
11423
+ kind: "in_doubt",
11424
+ reason: "outcome_unknown",
11425
+ replayable: false,
11426
+ settled: true,
11427
+ status: status2,
11428
+ errorReason: receipt?.errorReason,
11429
+ detail: `the payment was answered ${status2} with ${describeReceipt(receipt)}`,
11430
+ cause: await afterPaymentError(response)
11431
+ };
11432
+ }
11433
+ /**
11434
+ * Build the payment payload, re-reading any distrusted channel from the
11435
+ * chain first. A stored record the book refuses to hand over (a deposit a
11436
+ * dead process never heard back about), or one a top-up's read found
11437
+ * unusable ({@link prepareTopUp}), is re-read and the payload rebuilt
11438
+ * once.
11439
+ */
11440
+ async createPayload(wallet, paymentRequired) {
11441
+ for (let pass = 0; ; pass += 1) {
11442
+ await this.resync(wallet);
11443
+ const http = (await this.build(wallet)).http;
9713
11444
  try {
9714
- response = await send(http.encodePaymentSignatureHeader(payload));
11445
+ await this.prepareTopUp(wallet, paymentRequired);
11446
+ return { http, payload: await http.createPaymentPayload(withoutClientSignedBatch(paymentRequired)) };
9715
11447
  } catch (err) {
9716
- if (deposit) await this.forget(wallet);
9717
- else await this.settle(http, payload, () => null, 0);
9718
- throw err;
11448
+ if (pass > 0 || !isResyncRequired(err) || wallet.resyncs.size === 0) throw err;
11449
+ } finally {
11450
+ wallet.topUp = void 0;
9719
11451
  }
9720
- const getHeader = (name) => response.headers.get(name);
9721
- const settled = await this.settle(http, payload, getHeader, response.status);
9722
- if (deposit && !(response.ok && settled?.success === true)) await this.forget(wallet);
9723
- if (response.ok) {
9724
- const charged = atomicToUsd(settled?.amount) ?? atomicToUsd(payload.accepted?.amount) ?? 0;
9725
- return { kind: "paid", response, chargedUsd: charged };
11452
+ }
11453
+ }
11454
+ /**
11455
+ * When this payment will top up the wallet's channel, read how much of its
11456
+ * deposit is already settled on-chain (at `finalized` commitment, so never
11457
+ * more than will stay settled), so `maxDeposit` caps the escrow still at
11458
+ * stake rather than every deposit the channel ever took.
11459
+ *
11460
+ * Only a top-up costs this read (a channel's balance decides it, from the
11461
+ * stored record). If the read fails, nothing settled is assumed, which is
11462
+ * the stricter, lifetime cap. If the chain shows a larger deposit than the
11463
+ * record, the record is behind (a deposit it never heard about landed):
11464
+ * sizing a top-up from it could exceed `maxDeposit`, so this call pays
11465
+ * exact and the channel is re-read before the next payment. If
11466
+ * `@x402/svm`'s channel layout is not the one this SDK decodes, or the
11467
+ * account at the channel's address cannot be read as a channel, the call
11468
+ * pays exact (`channel_unreadable`), record kept. If
11469
+ * the finalized channel is closing or closed, or is not this wallet's for
11470
+ * the record's operator and mint, no top-up is sized from the record: it
11471
+ * is re-read at once (`channel_unusable`), see {@link createPayload}.
11472
+ */
11473
+ async prepareTopUp(wallet, paymentRequired) {
11474
+ wallet.topUp = void 0;
11475
+ const accept = trustedBatchAccept(paymentRequired, this.init.options.operators);
11476
+ if (!accept) return;
11477
+ const key = channelKeyOf(accept);
11478
+ const record = key ? await wallet.book.get(key) : void 0;
11479
+ if (!key || !record || record.pending || typeof record.channelId !== "string") return;
11480
+ const deposit = parseAtomic(record.deposit);
11481
+ if (parseAtomic(record.chargedCumulativeAmount) + parseAtomic(accept.amount) <= deposit) return;
11482
+ let channel;
11483
+ try {
11484
+ channel = await readChannelAccount(this.init.rpcUrl, record.channelId, this.init.rpcHeaders);
11485
+ } catch (err) {
11486
+ if (err instanceof ChannelLayoutError) {
11487
+ throw new ResyncError("channel_unreadable", `channel ${record.channelId}: ${err.message}; no top-up is sized from it`);
9726
11488
  }
9727
- const refusal = await isBatchRefusal(response);
9728
- if (refusal) {
9729
- this.warn(wallet, refusal);
9730
- return { kind: "fallback", reason: refusal };
11489
+ if (err instanceof ChannelUnreadableError) {
11490
+ throw new ResyncError("channel_unreadable", `${err.message}; no top-up is signed into it`);
9731
11491
  }
9732
- return { kind: "failed", response };
9733
- } finally {
9734
- wallet.busy = false;
11492
+ throw new ResyncError(
11493
+ "channel_resync_failed",
11494
+ `could not read channel ${record.channelId} before topping it up: ${err instanceof Error ? err.message : String(err)}`
11495
+ );
9735
11496
  }
11497
+ if (channel === void 0) return;
11498
+ if (!channel.open || channel.payer !== await this.init.address() || channel.authorizedSigner !== record.channelConfig.payerAuthorizer || channel.mint !== record.channelConfig.token) {
11499
+ addResyncTarget(wallet, {
11500
+ key,
11501
+ channelId: record.channelId,
11502
+ channelConfig: record.channelConfig,
11503
+ cumulative: parseAtomic(record.chargedCumulativeAmount),
11504
+ knownDeposit: deposit,
11505
+ reason: "channel_unusable"
11506
+ });
11507
+ throw new ChannelResyncRequiredError(record.channelId);
11508
+ }
11509
+ if (channel.deposit > deposit) {
11510
+ addResyncTarget(wallet, {
11511
+ key,
11512
+ channelId: record.channelId,
11513
+ channelConfig: record.channelConfig,
11514
+ cumulative: parseAtomic(record.chargedCumulativeAmount),
11515
+ knownDeposit: channel.deposit,
11516
+ reason: "deposit_unrecorded"
11517
+ });
11518
+ throw new ResyncError(
11519
+ "channel_resync_pending",
11520
+ `channel ${record.channelId} holds ${channel.deposit} on chain, more than the ${deposit} its record knows; it is re-read before any top-up`
11521
+ );
11522
+ }
11523
+ wallet.topUp = { key, deposit, settled: channel.settled };
9736
11524
  }
9737
11525
  /**
9738
11526
  * Hand the gateway's answer to the scheme, which verifies the operator's
@@ -9743,36 +11531,143 @@ var SolanaBatchPayer = class {
9743
11531
  */
9744
11532
  async settle(http, payload, getHeader, status2) {
9745
11533
  try {
9746
- return (await http.processPaymentResult(payload, getHeader, status2)).settleResponse;
11534
+ return { settleResponse: (await http.processPaymentResult(payload, getHeader, status2)).settleResponse, ok: true };
9747
11535
  } catch (err) {
9748
11536
  console.error(
9749
- `[@blockrun/llm] batch-settlement receipt not reconciled: ${err instanceof Error ? err.message : String(err)}`
11537
+ `[@blockrun/llm] batch-settlement receipt not reconciled: ${JSON.stringify(err instanceof Error ? err.message : String(err))}`
9750
11538
  );
9751
- return void 0;
11539
+ let settleResponse;
11540
+ try {
11541
+ settleResponse = http.getPaymentSettleResponse(getHeader);
11542
+ } catch {
11543
+ settleResponse = void 0;
11544
+ }
11545
+ return { settleResponse, ok: false };
9752
11546
  }
9753
11547
  }
9754
11548
  /**
9755
- * Close the channel and return its unused escrow to the wallet.
11549
+ * Close the channel the gateway's current challenge names and return its
11550
+ * unused escrow to the wallet.
9756
11551
  *
9757
11552
  * The scheme keeps a closed channel in its records, and would go on paying
9758
- * into it, so a successful close forgets the channel. The next batch call
9759
- * finds no open channel on-chain and opens a new one.
11553
+ * into it, so a successful close forgets that channel. The next batch call
11554
+ * finds no open channel on-chain and opens a new one. Any other channel
11555
+ * (say, one opened with an operator key that is being rotated out) keeps
11556
+ * its record, so it can still be closed without an on-chain scan. A
11557
+ * client-signed channel an earlier SDK version opened is closed too, once
11558
+ * the trusted server-signed one has no record (see {@link refundTarget}).
9760
11559
  *
9761
11560
  * @param url - any batch-enabled route on the gateway the channel was opened with.
11561
+ * @throws BatchCloseDeferredError while a batch call for the wallet is in
11562
+ * flight, or while any of its deposits is in doubt (until a finalized
11563
+ * chain read settles it). Nothing is refunded or forgotten then.
9762
11564
  */
9763
11565
  async close(url) {
9764
11566
  const wallet = await this.wallet();
9765
- if (typeof wallet === "string") throw new Error(`batch-settlement unavailable: ${wallet}`);
9766
- if (wallet.busy) throw new Error("batch-settlement channel has a request in flight; close it when the call returns");
11567
+ if ("reason" in wallet) throw new Error(`batch-settlement unavailable: ${wallet.detail}`);
11568
+ if (wallet.busy || wallet.active > 0) {
11569
+ throw new BatchCloseDeferredError({
11570
+ reason: "call_in_flight",
11571
+ wallet: await this.init.address(),
11572
+ detail: "a batch call is in flight (it may be waiting out a 429); close the channel when it returns"
11573
+ });
11574
+ }
9767
11575
  wallet.busy = true;
9768
11576
  try {
9769
- const result = await (await this.build(wallet)).refund(url);
9770
- await this.forget(wallet);
11577
+ await this.settleDoubtsForClose(wallet);
11578
+ const { accept, key } = await this.refundTarget(wallet, url);
11579
+ const result = await (await this.prepareClose(wallet, key)).refund(url, accept);
11580
+ wallet.closes += 1;
11581
+ await this.forget(wallet, key);
9771
11582
  return result;
9772
11583
  } finally {
9773
11584
  wallet.busy = false;
9774
11585
  }
9775
11586
  }
11587
+ /**
11588
+ * Re-read every distrusted channel before a close. A deposit still in
11589
+ * doubt defers the close: refunding (or forgetting) a channel a deposit
11590
+ * may yet land on could strand that deposit, and after a restart nothing
11591
+ * would remember it. A record re-read that only failed for another reason
11592
+ * (an RPC error on a channel with no deposit in doubt) does not.
11593
+ */
11594
+ async settleDoubtsForClose(wallet) {
11595
+ try {
11596
+ await this.resync(wallet);
11597
+ } catch (err) {
11598
+ if (!(err instanceof ResyncError)) throw err;
11599
+ const inDoubt = [...wallet.resyncs.values()].filter((target) => target.expectDeposit !== void 0);
11600
+ if (inDoubt.length > 0) {
11601
+ throw new BatchCloseDeferredError({
11602
+ reason: "deposit_in_doubt",
11603
+ wallet: await this.init.address(),
11604
+ channelIds: inDoubt.map((target) => target.channelId),
11605
+ detail: `a deposit on channel ${inDoubt.map((target) => target.channelId).join(", ")} is in doubt (${err.message}); close once a finalized chain read settles it`
11606
+ });
11607
+ }
11608
+ }
11609
+ }
11610
+ /**
11611
+ * The channel a close targets: the one the gateway's refund challenge
11612
+ * names, by the scheme's storage key for its trusted server-signed accept
11613
+ * (network, asset, receiver, fee payer, withdraw delay, receiver
11614
+ * authorizer, operator). Probed with an unpaid GET, as `@x402/svm`'s own
11615
+ * refund probes; that accept is then handed to the refund, so upstream
11616
+ * does not probe again and pick another accept.
11617
+ *
11618
+ * A legacy client-signed channel (opened by an earlier SDK version, which
11619
+ * could pay a client-signed accept; this one never opens one) must stay
11620
+ * refundable. When the trusted server-signed accept has no stored record,
11621
+ * or there is none, a client-signed accept in the challenge whose storage
11622
+ * key names a stored client-signed record is the target instead, and the
11623
+ * refund runs through `@x402/svm`'s client-signed path (a refund voucher
11624
+ * signed by the payer at its confirmed cumulative). The signer modes match:
11625
+ * a server-signed record is never refunded under a client-signed accept.
11626
+ */
11627
+ async refundTarget(wallet, url) {
11628
+ const probe = await fetch(url, { method: "GET" });
11629
+ const header = probe.status === 402 ? probe.headers.get("PAYMENT-REQUIRED") : null;
11630
+ if (!header) throw new Error(`refund probe expected a 402 with PAYMENT-REQUIRED from ${url}, got HTTP ${probe.status}`);
11631
+ const paymentRequired = parsePaymentRequired(header);
11632
+ const trustedAccepts = trustedBatchAccepts(paymentRequired, this.init.options.operators).map((accept) => ({ accept, key: channelKeyOf(accept) })).filter((candidate) => !!candidate.key);
11633
+ for (const candidate of trustedAccepts) {
11634
+ if (await wallet.book.base.get(candidate.key)) return candidate;
11635
+ }
11636
+ for (const accept of (paymentRequired.accepts ?? []).filter(clientSignedBatch)) {
11637
+ const key = channelKeyOf(accept);
11638
+ const record = key ? await wallet.book.base.get(key) : void 0;
11639
+ if (key && record && (record.channelConfig?.voucherSigner ?? "client") === "client") return { accept, key };
11640
+ }
11641
+ const first = trustedAccepts[0];
11642
+ if (!first) throw new Error(`${url} offers no batch-settlement accept with a trusted operator to close against`);
11643
+ return first;
11644
+ }
11645
+ /**
11646
+ * Get the stored channel `key` ready to refund.
11647
+ *
11648
+ * `@x402/svm` refunds a server-signed channel only from the scheme's memory,
11649
+ * or after an on-chain scan that many RPCs refuse; it never reads the
11650
+ * stored record. So the target channel is loaded into a freshly built
11651
+ * scheme, and only that one: upstream's refund falls back to the first
11652
+ * channel in memory for the same receiver and asset, whatever its operator.
11653
+ * A record in doubt (a deposit this process never confirmed, or a pending
11654
+ * deposit left by a process that died) is re-read from the chain before it
11655
+ * is loaded. If a re-read cannot settle a record, the refund is still
11656
+ * attempted and may find the channel by its scan.
11657
+ */
11658
+ async prepareClose(wallet, key) {
11659
+ for (let pass = 0; ; pass += 1) {
11660
+ await this.settleDoubtsForClose(wallet);
11661
+ wallet.client = void 0;
11662
+ const built = await this.build(wallet);
11663
+ try {
11664
+ await built.load(key);
11665
+ return built;
11666
+ } catch (err) {
11667
+ if (pass > 0 || !isResyncRequired(err)) return built;
11668
+ }
11669
+ }
11670
+ }
9776
11671
  };
9777
11672
 
9778
11673
  // src/solana-client.ts
@@ -9841,6 +11736,18 @@ async function waitForStaleRetry(attempt) {
9841
11736
  (resolve2) => setTimeout(resolve2, STALE_BLOCKHASH_RETRY_BACKOFFS_MS[attempt])
9842
11737
  );
9843
11738
  }
11739
+ async function unpaidApiError(response) {
11740
+ let errorBody;
11741
+ try {
11742
+ errorBody = await response.json();
11743
+ } catch {
11744
+ errorBody = { error: "Request failed" };
11745
+ }
11746
+ return withDisposition(
11747
+ new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(errorBody)),
11748
+ "unpaid"
11749
+ );
11750
+ }
9844
11751
  var DEFAULT_SOLANA_RPC_URL = "https://sol.blockrun.ai/api/v1/solana/rpc";
9845
11752
  function resolveRpcConfig(rpcUrl, rpcHeaders) {
9846
11753
  const env = typeof process !== "undefined" && process.env ? process.env : {};
@@ -9907,21 +11814,42 @@ var SolanaLLMClient = class {
9907
11814
  options: options.batch,
9908
11815
  secretKey: () => solanaKeyToBytes(this.privateKey),
9909
11816
  address: () => this.getWalletAddress(),
9910
- rpcUrl: this.rpcUrl
11817
+ rpcUrl: this.rpcUrl,
11818
+ rpcHeaders: this.rpcHeaders
9911
11819
  });
9912
11820
  }
9913
11821
  }
9914
11822
  /**
9915
11823
  * Close this wallet's batch-settlement channel and return its unused escrow.
9916
11824
  *
9917
- * The gateway closes it cooperatively when it can; otherwise this starts a
9918
- * payer-forced close and the escrow comes back after the channel's grace
9919
- * period. Only meaningful with the `batch` option.
11825
+ * Closes the channel for the operator the gateway's current 402 names; a
11826
+ * channel opened with another trusted operator key (during a key rotation)
11827
+ * keeps its record. The gateway closes it cooperatively when it can;
11828
+ * otherwise this starts a payer-forced close and the escrow comes back
11829
+ * after the channel's grace period. Only meaningful with the `batch`
11830
+ * option.
11831
+ *
11832
+ * @throws BatchCloseDeferredError, closing nothing, while a chat call for
11833
+ * this wallet is still in flight (including one waiting out a 429, so a
11834
+ * retry can never reopen a channel you just closed), or while one of its
11835
+ * deposits is in doubt (until a `finalized` chain read shows it landed or
11836
+ * that it no longer can, usually a few minutes after it was sent). Call
11837
+ * it again later.
9920
11838
  */
9921
11839
  async closeBatchChannel() {
9922
11840
  if (!this.batchPayer) throw new Error("closeBatchChannel() requires the `batch` option in wallet mode");
9923
11841
  return this.batchPayer.close(`${this.apiUrl}/v1/chat/completions`);
9924
11842
  }
11843
+ /**
11844
+ * This client's batch-settlement counters: calls that fell back to `exact`
11845
+ * (in total and by reason), 429 backoffs, batch retries, and recoveries.
11846
+ * Every one of those is also logged to stderr and passed to `batch.onEvent`.
11847
+ * Only meaningful with the `batch` option.
11848
+ */
11849
+ getBatchStats() {
11850
+ if (!this.batchPayer) throw new Error("getBatchStats() requires the `batch` option in wallet mode");
11851
+ return this.batchPayer.stats();
11852
+ }
9925
11853
  /** Get Solana wallet address (public key in base58). */
9926
11854
  async getWalletAddress() {
9927
11855
  if (!this.addressCache) {
@@ -10445,17 +12373,34 @@ var SolanaLLMClient = class {
10445
12373
  isSolana() {
10446
12374
  return this.apiUrl.includes("sol.blockrun.ai");
10447
12375
  }
12376
+ /**
12377
+ * Chat request with automatic x402 payment.
12378
+ *
12379
+ * Every error it throws carries a {@link RetryDisposition}, which is what
12380
+ * {@link SolanaLLMClient.chatCompletion}'s fallback walk honours: errors of
12381
+ * the unpaid first request, its 402 challenge and the signing step are
12382
+ * `"unpaid"`; anything after a payment was sent (exact or batch) is
12383
+ * `"paid-or-in-doubt"`, and so is any error with an API key once the billed
12384
+ * request was sent, except the account API's explicit 4xx refusal.
12385
+ */
10448
12386
  async requestWithPayment(endpoint, body) {
10449
12387
  const url = `${this.apiUrl}${endpoint}`;
12388
+ const closesAtStart = await this.batchPayer?.closeFence();
10450
12389
  for (let staleRetries = 0; ; ) {
10451
- const response = await this.fetchWithTimeout(url, {
12390
+ const response = await this.sendUnpaid(url, {
10452
12391
  method: "POST",
10453
12392
  headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
10454
12393
  body: JSON.stringify(body)
10455
12394
  });
10456
12395
  if (response.status === 402) {
10457
12396
  try {
10458
- const paymentRequired = await this.readPaymentRequired(response);
12397
+ let paymentRequired;
12398
+ try {
12399
+ paymentRequired = await this.readPaymentRequired(response);
12400
+ } catch (error) {
12401
+ throw withDisposition(error, "unpaid");
12402
+ }
12403
+ let exactRequired = paymentRequired;
10459
12404
  if (this.batchPayer && staleRetries === 0) {
10460
12405
  const batch = await this.batchPayer.pay(
10461
12406
  paymentRequired,
@@ -10463,39 +12408,75 @@ var SolanaLLMClient = class {
10463
12408
  method: "POST",
10464
12409
  headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT, ...paymentHeaders },
10465
12410
  body: JSON.stringify(body)
10466
- })
12411
+ }),
12412
+ // A fresh, unpaid challenge after a 429 wait: the request itself,
12413
+ // sent again without a payment. Every error it throws is unpaid.
12414
+ async () => {
12415
+ const challenge = await this.sendUnpaid(url, {
12416
+ method: "POST",
12417
+ headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
12418
+ body: JSON.stringify(body)
12419
+ });
12420
+ if (challenge.status === 402) {
12421
+ try {
12422
+ return { kind: "challenge", paymentRequired: await this.readPaymentRequired(challenge) };
12423
+ } catch (error) {
12424
+ throw withDisposition(error, "unpaid");
12425
+ }
12426
+ }
12427
+ if (challenge.ok) return { kind: "served", response: challenge };
12428
+ throw await unpaidApiError(challenge);
12429
+ },
12430
+ closesAtStart
10467
12431
  );
10468
12432
  if (batch.kind === "paid") {
10469
12433
  this.recordSettlement(batch.chargedUsd);
10470
- return batch.response.json();
10471
- }
10472
- if (batch.kind === "failed") {
10473
- let errorBody;
10474
- try {
10475
- errorBody = await batch.response.json();
10476
- } catch {
10477
- errorBody = { error: "Request failed" };
10478
- }
10479
- throw new APIError(`API error after payment: ${batch.response.status}`, batch.response.status, sanitizeErrorResponse(errorBody));
12434
+ return await this.readPaidJson(batch.response);
10480
12435
  }
12436
+ if (batch.kind === "served") return await this.readUnpaidJson(batch.response);
12437
+ if (batch.kind === "failed") throw batch.error;
12438
+ exactRequired = batch.paymentRequired ?? paymentRequired;
10481
12439
  }
10482
- return await this.handlePaymentAndRetry(url, body, paymentRequired, staleRetries > 0);
12440
+ return await this.handlePaymentAndRetry(url, body, exactRequired, staleRetries > 0);
10483
12441
  } catch (error) {
10484
12442
  if (!(error instanceof SafeStaleBlockhashError) || staleRetries >= STALE_BLOCKHASH_RETRY_BACKOFFS_MS.length) throw error;
10485
12443
  await waitForStaleRetry(staleRetries++);
10486
12444
  continue;
10487
12445
  }
10488
12446
  }
10489
- if (!response.ok) {
10490
- let errorBody;
10491
- try {
10492
- errorBody = await response.json();
10493
- } catch {
10494
- errorBody = { error: "Request failed" };
10495
- }
10496
- throw new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(errorBody));
10497
- }
10498
- return response.json();
12447
+ if (!response.ok) throw await unpaidApiError(response);
12448
+ return await this.readUnpaidJson(response);
12449
+ }
12450
+ }
12451
+ /**
12452
+ * Read the JSON body of a 2xx served without a payment: the free tier, or
12453
+ * with an API key, where this very request was the billed one.
12454
+ */
12455
+ async readUnpaidJson(response) {
12456
+ try {
12457
+ return await response.json();
12458
+ } catch (error) {
12459
+ throw withDisposition(error, this.apiAuth ? "paid-or-in-doubt" : "unpaid");
12460
+ }
12461
+ }
12462
+ /**
12463
+ * Send a request that carries no payment, marking what it throws with its
12464
+ * {@link RetryDisposition}: `"unpaid"` with a wallet; with an API key, see
12465
+ * {@link accountErrorDisposition} (the request itself is billed).
12466
+ */
12467
+ async sendUnpaid(url, init) {
12468
+ try {
12469
+ return await this.fetchWithTimeout(url, init);
12470
+ } catch (error) {
12471
+ throw withDisposition(error, this.apiAuth ? accountErrorDisposition(error) : "unpaid");
12472
+ }
12473
+ }
12474
+ /** Read a paid 2xx response's JSON body. The call was charged, so a failure here is never retried. */
12475
+ async readPaidJson(response) {
12476
+ try {
12477
+ return await response.json();
12478
+ } catch (error) {
12479
+ throw withDisposition(error, "paid-or-in-doubt");
10499
12480
  }
10500
12481
  }
10501
12482
  /**
@@ -10663,24 +12644,30 @@ var SolanaLLMClient = class {
10663
12644
  return { paymentPayload, costUsd: parseFloat(details.amount) / 1e6 };
10664
12645
  }
10665
12646
  async handlePaymentAndRetry(url, body, paymentRequired, forceFreshBlockhash = false) {
10666
- const { paymentPayload, costUsd } = await this.signExactPayment(
10667
- url,
10668
- paymentRequired,
10669
- forceFreshBlockhash,
10670
- `${this.apiUrl}/v1/chat/completions`
10671
- );
10672
- const retryResponse = await this.fetchWithTimeout(url, {
10673
- method: "POST",
10674
- headers: {
10675
- "Content-Type": "application/json",
10676
- "User-Agent": USER_AGENT,
10677
- "PAYMENT-SIGNATURE": paymentPayload
10678
- },
10679
- body: JSON.stringify(body)
10680
- });
12647
+ let signed;
12648
+ try {
12649
+ signed = await this.signExactPayment(url, paymentRequired, forceFreshBlockhash, `${this.apiUrl}/v1/chat/completions`);
12650
+ } catch (error) {
12651
+ throw withDisposition(error, "unpaid");
12652
+ }
12653
+ const { paymentPayload, costUsd } = signed;
12654
+ let retryResponse;
12655
+ try {
12656
+ retryResponse = await this.fetchWithTimeout(url, {
12657
+ method: "POST",
12658
+ headers: {
12659
+ "Content-Type": "application/json",
12660
+ "User-Agent": USER_AGENT,
12661
+ "PAYMENT-SIGNATURE": paymentPayload
12662
+ },
12663
+ body: JSON.stringify(body)
12664
+ });
12665
+ } catch (error) {
12666
+ throw withDisposition(error, "paid-or-in-doubt");
12667
+ }
10681
12668
  await this.assertPaid(retryResponse);
10682
12669
  this.recordSettlement(costUsd);
10683
- return retryResponse.json();
12670
+ return this.readPaidJson(retryResponse);
10684
12671
  }
10685
12672
  async requestWithPaymentRaw(endpoint, body) {
10686
12673
  const url = `${this.apiUrl}${endpoint}`;
@@ -10787,14 +12774,15 @@ var SolanaLLMClient = class {
10787
12774
  * lives.
10788
12775
  * @param response - the reply to the paid request.
10789
12776
  * @throws SafeStaleBlockhashError when the caller should re-sign, PaymentError
10790
- * when it should not, APIError for any other failure.
12777
+ * when it should not, APIError for any other failure. Every one but the
12778
+ * first is marked `"paid-or-in-doubt"`: the payment may have settled.
10791
12779
  */
10792
12780
  async assertPaid(response) {
10793
12781
  if (response.status === 402) {
10794
12782
  if (await isSafeStaleBlockhashResponse(response)) {
10795
- throw new SafeStaleBlockhashError();
12783
+ throw withDisposition(new SafeStaleBlockhashError(), "unpaid");
10796
12784
  }
10797
- throw new PaymentError("Payment was rejected. Check your Solana USDC balance.");
12785
+ throw withDisposition(new PaymentError("Payment was rejected. Check your Solana USDC balance."), "paid-or-in-doubt");
10798
12786
  }
10799
12787
  if (!response.ok) {
10800
12788
  let errorBody;
@@ -10803,7 +12791,11 @@ var SolanaLLMClient = class {
10803
12791
  } catch {
10804
12792
  errorBody = { error: "Request failed" };
10805
12793
  }
10806
- throw new APIError(`API error after payment: ${response.status}`, response.status, sanitizeErrorResponse(errorBody));
12794
+ const unverified = response.status === 503 && errorBody?.code === "PAYMENT_VERIFICATION_UNAVAILABLE";
12795
+ throw withDisposition(
12796
+ new APIError(`API error after payment: ${response.status}`, response.status, sanitizeErrorResponse(errorBody)),
12797
+ unverified ? "unpaid" : "paid-or-in-doubt"
12798
+ );
10807
12799
  }
10808
12800
  }
10809
12801
  /** Count one settled x402 payment against the session total. */
@@ -11274,8 +13266,12 @@ var AnthropicClient = class {
11274
13266
  baseURL: this._apiUrl,
11275
13267
  apiKey: "blockrun",
11276
13268
  fetch: this._x402Fetch.bind(this),
11277
- // Account POSTs may already be billed when an upstream error arrives.
11278
- ...this.apiAuth ? { maxRetries: 0 } : {}
13269
+ // Never let the Anthropic SDK retry. It retries 408/409/429/5xx and
13270
+ // connection errors by calling this fetch again, which in wallet mode
13271
+ // runs the whole x402 flow and signs a NEW payment each time (three
13272
+ // payments for one call at the default maxRetries of 2); in account
13273
+ // mode the POST itself may already be billed.
13274
+ maxRetries: 0
11279
13275
  });
11280
13276
  return this._client;
11281
13277
  })();
@@ -11369,8 +13365,11 @@ export {
11369
13365
  AnthropicClient,
11370
13366
  BASE_CHAIN_ID,
11371
13367
  BLOCKRUN_SOL_OPERATOR,
13368
+ BatchCloseDeferredError,
13369
+ BatchPaymentUnresolvedError,
11372
13370
  BlockrunClient,
11373
13371
  BlockrunError,
13372
+ DEFAULT_BATCH_RATE_LIMIT,
11374
13373
  EVM_NETWORKS,
11375
13374
  ImageClient,
11376
13375
  KNOWN_PROVIDERS,
@@ -11433,6 +13432,7 @@ export {
11433
13432
  loadWallet,
11434
13433
  logCost,
11435
13434
  parsePaymentRequired,
13435
+ retryDisposition,
11436
13436
  saveSolanaWallet,
11437
13437
  saveToCache,
11438
13438
  saveWallet,