@blockrun/llm 3.19.1 → 3.20.0

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