@blockrun/clawrouter 0.12.304 → 0.12.306

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +420 -97
  2. package/dist/index.js +420 -97
  3. package/package.json +4 -2
package/dist/cli.js CHANGED
@@ -107337,11 +107337,13 @@ __export(dist_exports, {
107337
107337
  AnthropicClient: () => AnthropicClient,
107338
107338
  BASE_CHAIN_ID: () => BASE_CHAIN_ID,
107339
107339
  BLOCKRUN_SOL_OPERATOR: () => BLOCKRUN_SOL_OPERATOR,
107340
+ BatchChannelLockedError: () => BatchChannelLockedError,
107340
107341
  BatchCloseDeferredError: () => BatchCloseDeferredError,
107341
107342
  BatchPaymentUnresolvedError: () => BatchPaymentUnresolvedError,
107342
107343
  BlockrunClient: () => BlockrunClient,
107343
107344
  BlockrunError: () => BlockrunError,
107344
107345
  DEFAULT_BATCH_IN_DOUBT: () => DEFAULT_BATCH_IN_DOUBT,
107346
+ DEFAULT_BATCH_LOCK_WAIT_MS: () => DEFAULT_BATCH_LOCK_WAIT_MS,
107345
107347
  DEFAULT_BATCH_RATE_LIMIT: () => DEFAULT_BATCH_RATE_LIMIT,
107346
107348
  EVM_NETWORKS: () => EVM_NETWORKS,
107347
107349
  ImageClient: () => ImageClient,
@@ -107722,13 +107724,43 @@ function readSettlement(response, quotedUsd, scheme) {
107722
107724
  };
107723
107725
  return { costUsd, settlement };
107724
107726
  }
107727
+ function settlementSkipReason(response) {
107728
+ const headers = response.headers;
107729
+ if (typeof headers?.get !== "function") return void 0;
107730
+ const reason = [headers.get("X-Settlement-Skipped"), headers.get("X-Payment-Waived")].map((value) => value?.trim()).find((value) => !!value && !NOT_A_SKIP.test(value));
107731
+ if (reason === void 0) return void 0;
107732
+ const evidence = settlementEvidence(response);
107733
+ if (evidence !== void 0) {
107734
+ console.error(
107735
+ `[@blockrun/llm] settlement: the gateway named a skipped settlement (${JSON.stringify(reason)}) on a response that also carries ${evidence}; booked as charged`
107736
+ );
107737
+ return void 0;
107738
+ }
107739
+ return reason;
107740
+ }
107741
+ function settlementEvidence(response) {
107742
+ const header = response.headers.get("PAYMENT-RESPONSE") ?? response.headers.get("X-PAYMENT-RESPONSE");
107743
+ const receipt = header ? decode4(header) : void 0;
107744
+ if (receipt && receipt.success !== false) {
107745
+ if (typeof receipt.transaction === "string" && receipt.transaction) return "a settlement receipt with a transaction";
107746
+ const extra = receipt.extra;
107747
+ const charged = receiptChargedUsd({
107748
+ amount: receipt.amount,
107749
+ extra: extra && typeof extra === "object" ? extra : void 0
107750
+ });
107751
+ if (charged !== void 0 && charged > 0) return "a settlement receipt with a charge";
107752
+ }
107753
+ if (response.headers.get("X-Payment-Receipt")?.trim()) return "an X-Payment-Receipt transaction";
107754
+ return void 0;
107755
+ }
107725
107756
  function settlementSkipped(response) {
107726
- return response.headers.get("X-Settlement-Skipped") === "free-fallback";
107757
+ return settlementSkipReason(response) !== void 0;
107727
107758
  }
107728
107759
  function withCost(body, response, bookedUsd, scheme) {
107729
- if (settlementSkipped(response)) {
107760
+ const skipped = settlementSkipReason(response);
107761
+ if (skipped !== void 0) {
107730
107762
  body.costUsd = 0;
107731
- body.settlement = { ...readSettlement(response, bookedUsd, scheme).settlement, skipped: "free-fallback" };
107763
+ body.settlement = { ...readSettlement(response, bookedUsd, scheme).settlement, skipped };
107732
107764
  return body;
107733
107765
  }
107734
107766
  body.costUsd = bookedUsd;
@@ -108750,10 +108782,10 @@ function isEligible2(modelId, features, maxOutputTokens, options) {
108750
108782
  return model.contextWindow >= (features.estimatedInputTokens + maxOutputTokens) * 1.1;
108751
108783
  }
108752
108784
  function estimatedCost2(modelId, options, inputTokens, outputTokens) {
108753
- const price = options.modelPricing.get(modelId);
108754
- if (!price) return Number.POSITIVE_INFINITY;
108755
- if (price.flatPrice !== void 0) return price.flatPrice;
108756
- return (inputTokens * price.inputPrice + outputTokens * price.outputPrice) / 1e6;
108785
+ const price2 = options.modelPricing.get(modelId);
108786
+ if (!price2) return Number.POSITIVE_INFINITY;
108787
+ if (price2.flatPrice !== void 0) return price2.flatPrice;
108788
+ return (inputTokens * price2.inputPrice + outputTokens * price2.outputPrice) / 1e6;
108757
108789
  }
108758
108790
  function profileScore2(modelId, options, now2) {
108759
108791
  const profile = options.modelPerformance?.[modelId] ?? LIVE_MODEL_PROFILES2[modelId] ?? HISTORICAL_MODEL_PROFILES2[modelId];
@@ -110049,7 +110081,7 @@ function decodeChannelAccount(owner, data) {
110049
110081
  }
110050
110082
  async function readChannelAccount(rpcUrl, channelId, rpcHeaders, options = {}) {
110051
110083
  await checkChannelLayout();
110052
- const config2 = { encoding: "base64", commitment: "finalized" };
110084
+ const config2 = { encoding: "base64", commitment: options.commitment ?? "finalized" };
110053
110085
  if (options.minContextSlot !== void 0) config2.minContextSlot = options.minContextSlot;
110054
110086
  const response = await fetch(rpcUrl, {
110055
110087
  method: "POST",
@@ -110111,6 +110143,10 @@ function checkChannelLayout() {
110111
110143
  });
110112
110144
  return layoutChecked;
110113
110145
  }
110146
+ function savedReclaimAnchor(record2) {
110147
+ const saved = record2.reclaimAnchorHeight;
110148
+ return typeof saved === "number" && Number.isSafeInteger(saved) && saved > 0 ? saved : void 0;
110149
+ }
110114
110150
  function maxOf(a, b) {
110115
110151
  if (a === void 0) return b;
110116
110152
  if (b === void 0) return a;
@@ -110135,6 +110171,35 @@ function withoutClientSignedBatch(paymentRequired) {
110135
110171
  const accepts = paymentRequired.accepts ?? [];
110136
110172
  return accepts.some(clientSignedBatch) ? { ...paymentRequired, accepts: accepts.filter((accept) => !clientSignedBatch(accept)) } : paymentRequired;
110137
110173
  }
110174
+ async function finalizedBlockhash(rpcUrl, rpcHeaders) {
110175
+ const cached2 = depositBlockhashes.get(rpcUrl);
110176
+ if (cached2 && Date.now() - cached2.fetchedAt < DEPOSIT_BLOCKHASH_TTL_MS) return cached2;
110177
+ const result = await rpcRequest(rpcUrl, "getLatestBlockhash", [{ commitment: "finalized" }], rpcHeaders);
110178
+ const blockhash2 = result.value?.blockhash;
110179
+ if (typeof blockhash2 !== "string" || !blockhash2) throw new Error("getLatestBlockhash returned no blockhash");
110180
+ const entry = {
110181
+ blockhash: blockhash2,
110182
+ lastValidBlockHeight: rpcInteger(result.value?.lastValidBlockHeight, "getLatestBlockhash lastValidBlockHeight"),
110183
+ fetchedAt: Date.now()
110184
+ };
110185
+ depositBlockhashes.delete(rpcUrl);
110186
+ depositBlockhashes.set(rpcUrl, entry);
110187
+ while (depositBlockhashes.size > MAX_DEPOSIT_BLOCKHASH_ENDPOINTS) {
110188
+ depositBlockhashes.delete(depositBlockhashes.keys().next().value);
110189
+ }
110190
+ return entry;
110191
+ }
110192
+ function withDepositBlockhash(paymentRequired, blockhash2) {
110193
+ const accepts = paymentRequired.accepts ?? [];
110194
+ const lacking = (accept) => accept.scheme === BATCH_SCHEME && !accept.extra?.recentBlockhash;
110195
+ if (!accepts.some(lacking)) return paymentRequired;
110196
+ return {
110197
+ ...paymentRequired,
110198
+ accepts: accepts.map(
110199
+ (accept) => lacking(accept) ? { ...accept, extra: { ...accept.extra, recentBlockhash: blockhash2.blockhash, lastValidBlockHeight: blockhash2.lastValidBlockHeight } } : accept
110200
+ )
110201
+ };
110202
+ }
110138
110203
  function withPaymentIdentifier(paymentRequired) {
110139
110204
  const declared = paymentRequired.extensions?.[PAYMENT_IDENTIFIER];
110140
110205
  if (typeof declared?.info?.required !== "boolean") return paymentRequired;
@@ -110795,7 +110860,7 @@ async function setupAgentClient(options = {}) {
110795
110860
  chain3 ??= !loadSolanaWallet() && loadWallet() ? "base" : "solana";
110796
110861
  return chain3 === "solana" ? setupAgentSolanaWallet(options) : setupAgentWallet(options);
110797
110862
  }
110798
- var RETRY_DISPOSITION, BlockrunError, RetiredEndpointError, PaymentError, APIError, LOCALHOST_DOMAINS, KNOWN_PROVIDERS, TRANSIENT_STATUS, TRANSIENT_RETRIES, TRANSIENT_BACKOFF_MS, API_KEY_URL, PORTAL_URL2, ApiKeyAuth, UNSEGMENTED_SCRIPT2, WORD_CHAR2, ASCII_PHRASE2, SEGMENTED_WORD_CHAR2, BOUNDARY_BEFORE2, BOUNDARY_AFTER2, BOUNDED_LAST_WORD_LENGTH2, SHORT_SUFFIXES2, SIBILANT_PLURAL2, MID_SUFFIXES2, DROPPED_E_SUFFIXES2, DOUBLED_CONSONANT_SUFFIXES2, matcherCache2, BASELINE_MODEL_ID2, BASELINE_INPUT_PRICE2, BASELINE_OUTPUT_PRICE2, SERVER_MARGIN_PERCENT2, MIN_PAYMENT_USD2, CJK_CHARS2, RulesStrategy2, registry3, DEFAULT_MODEL_CAPABILITIES2, model_profiles_generated_default2, LIVE_MODEL_PROFILES2, HISTORICAL_MODEL_PROFILES2, DEFAULT_PORTFOLIO_WEIGHTS2, VERIFIED_TOOL_FALLBACKS2, PortfolioStrategy2, DEFAULT_ROUTING_CONFIG2, AUTO_ROUTING_PROFILES, BASE_MINIMUM_PAYMENT_USD, SOLANA_MINIMUM_PAYMENT_USD, searchModelsByCatalog, INSTALL_HINT, BASE_CHAIN_ID, USDC_BASE2, ARC_CHAIN_ID, USDC_ARC, EVM_NETWORKS, SOLANA_NETWORK, USDC_SOLANA, SOLANA_USDC_DECIMALS, DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS2, DEFAULT_COMPUTE_UNIT_LIMIT2, BLOCKHASH_TTL_MS, MAX_FEE_NONCE_STEPS, MAX_TRACKED_BLOCKHASHES, MAX_TRACKED_ENDPOINTS, blockhashCache, issuedByBlockhash, TRANSFER_TYPES, BLOCKRUN_SERVICE_CODE2, BLOCKRUN_DIR, COST_LOG_FILE, SDK_VERSION, USER_AGENT2, DEFAULT_API_URL, DEFAULT_MAX_TOKENS2, DEFAULT_TIMEOUT, LLMClient, client_default, DEFAULT_API_URL2, DEFAULT_MODEL, DEFAULT_SIZE, DEFAULT_TIMEOUT2, POLL_INTERVAL_MS, POLL_MAX_DURATION_MS, ImageClient, DEFAULT_API_URL3, DEFAULT_MODEL2, DEFAULT_TIMEOUT3, MusicClient, DEFAULT_API_URL4, DEFAULT_MODEL3, DEFAULT_SOUNDFX_MODEL, DEFAULT_TIMEOUT4, SpeechClient, DEFAULT_API_URL5, DEFAULT_MODEL4, DEFAULT_TIMEOUT5, POLL_INTERVAL_MS2, DEFAULT_GENERATE_BUDGET_MS, MAX_TIMEOUT_SECONDS, MAX_POLL_RESIGNS, VideoClient, DEFAULT_API_URL6, DEFAULT_TIMEOUT6, CALL_PRICE_USD, VALID_MODELS, VoiceClient, DEFAULT_API_URL7, DEFAULT_TIMEOUT7, PHONE_PRICES, PhoneClient, DEFAULT_API_URL8, DEFAULT_TIMEOUT8, PORTRAIT_ENROLLMENT_PRICE_USD, PortraitClient, DEFAULT_API_URL9, DEFAULT_TIMEOUT9, SearchClient, DEFAULT_API_URL10, DEFAULT_TIMEOUT10, PriceClient, DEFAULT_API_URL11, DEFAULT_TIMEOUT11, SURF_PREFIX, warnedRetired, SurfClient, DEFAULT_API_URL12, DEFAULT_TIMEOUT12, RPC_PRICE_USD, SUPPORTED_NETWORKS, NETWORK_ALIASES, RpcClient, DEFAULT_API_URL13, DEFAULT_TIMEOUT13, DEFAULT_POLL_INTERVAL_MS, DEFAULT_POLL_BUDGET_MS, MAX_SIGNED_AUTH_SECONDS, BlockrunClient, USDC_BASE_CONTRACT, BASE_CHAIN_ID2, WALLET_FILE_PATH, WALLET_DIR_PATH, WALLET_DIR3, SOLANA_WALLET_FILE, POLL_AUTH_HEADERS, ED25519_PKCS8_PREFIX, BATCH_SCHEME, BLOCKRUN_SOL_OPERATOR, DEFAULT_BATCH_RATE_LIMIT, DEFAULT_BATCH_IN_DOUBT, BatchPaymentUnresolvedError, BatchCloseDeferredError, INSTALL_HINT2, FileChannelStorage, MemoryChannelStorage, FileIntentJournal, MemoryIntentJournal, BATCH_REGISTRY, registryHost, registry22, lockIds, ChannelResyncRequiredError, ChannelBook, PAYMENT_CHANNELS_PROGRAM_ID2, CHANNEL, ChannelUnreadableError, ChannelLayoutError, layoutChecked, LANDING_MARGIN_BLOCKS, ResyncError, PAYMENT_IDENTIFIER, IN_DOUBT_MIN_WAIT_MS, IN_DOUBT_MAX_WAIT_MS, BATCH_REFUSALS, PRE_REQUEST_REFUSALS, MAX_RETRY_AFTER_MS, NOT_BROADCAST_REFUSALS, CONFIG_REFUSALS, REFUSAL_COOLDOWN_MS, CONFIG_REFUSAL_COOLDOWN_MS, REFUSAL_COOLDOWN_MAX_MS, realSleep, sleep2, warnedNoSizer, payScope, RPC_SCOPE_STORE, RPC_HEADER_HOOK, sharedGlobal, rpcScope, SolanaBatchPayer, SOLANA_API_URL, DEFAULT_MAX_TOKENS22, DEFAULT_TIMEOUT14, STALE_BLOCKHASH_RETRY_BACKOFFS_MS, MAX_PAYMENT_FAILURE_BYTES, DEFAULT_VIDEO_MODEL, DEFAULT_MUSIC_MODEL, DEFAULT_VIDEO_BUDGET_MS, DEFAULT_MUSIC_BUDGET_MS, VIDEO_POLL_INTERVAL_MS, MAX_PAID_POLL_REFUSALS, MAX_RETRY_AFTER_MS2, MEDIA_SUBMIT_TIMEOUT_MS, SafeStaleBlockhashError, DEFAULT_SOLANA_RPC_URL, SolanaLLMClient, CACHE_DIR, DATA_DIR, COST_LOG_FILE2, DEFAULT_TTL, StreamingResponse, ChatCompletions, Chat, OpenAI, AnthropicClient;
110863
+ var RETRY_DISPOSITION, BlockrunError, RetiredEndpointError, PaymentError, APIError, LOCALHOST_DOMAINS, KNOWN_PROVIDERS, TRANSIENT_STATUS, TRANSIENT_RETRIES, TRANSIENT_BACKOFF_MS, API_KEY_URL, PORTAL_URL2, ApiKeyAuth, NOT_A_SKIP, UNSEGMENTED_SCRIPT2, WORD_CHAR2, ASCII_PHRASE2, SEGMENTED_WORD_CHAR2, BOUNDARY_BEFORE2, BOUNDARY_AFTER2, BOUNDED_LAST_WORD_LENGTH2, SHORT_SUFFIXES2, SIBILANT_PLURAL2, MID_SUFFIXES2, DROPPED_E_SUFFIXES2, DOUBLED_CONSONANT_SUFFIXES2, matcherCache2, BASELINE_MODEL_ID2, BASELINE_INPUT_PRICE2, BASELINE_OUTPUT_PRICE2, SERVER_MARGIN_PERCENT2, MIN_PAYMENT_USD2, CJK_CHARS2, RulesStrategy2, registry3, DEFAULT_MODEL_CAPABILITIES2, model_profiles_generated_default2, LIVE_MODEL_PROFILES2, HISTORICAL_MODEL_PROFILES2, DEFAULT_PORTFOLIO_WEIGHTS2, VERIFIED_TOOL_FALLBACKS2, PortfolioStrategy2, DEFAULT_ROUTING_CONFIG2, AUTO_ROUTING_PROFILES, BASE_MINIMUM_PAYMENT_USD, SOLANA_MINIMUM_PAYMENT_USD, searchModelsByCatalog, INSTALL_HINT, BASE_CHAIN_ID, USDC_BASE2, ARC_CHAIN_ID, USDC_ARC, EVM_NETWORKS, SOLANA_NETWORK, USDC_SOLANA, SOLANA_USDC_DECIMALS, DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS2, DEFAULT_COMPUTE_UNIT_LIMIT2, BLOCKHASH_TTL_MS, MAX_FEE_NONCE_STEPS, MAX_TRACKED_BLOCKHASHES, MAX_TRACKED_ENDPOINTS, blockhashCache, issuedByBlockhash, TRANSFER_TYPES, BLOCKRUN_SERVICE_CODE2, BLOCKRUN_DIR, COST_LOG_FILE, SDK_VERSION, USER_AGENT2, DEFAULT_API_URL, DEFAULT_MAX_TOKENS2, DEFAULT_TIMEOUT, LLMClient, client_default, DEFAULT_API_URL2, DEFAULT_MODEL, DEFAULT_SIZE, DEFAULT_TIMEOUT2, POLL_INTERVAL_MS, POLL_MAX_DURATION_MS, ImageClient, DEFAULT_API_URL3, DEFAULT_MODEL2, DEFAULT_TIMEOUT3, MusicClient, DEFAULT_API_URL4, DEFAULT_MODEL3, DEFAULT_SOUNDFX_MODEL, DEFAULT_TIMEOUT4, SpeechClient, DEFAULT_API_URL5, DEFAULT_MODEL4, DEFAULT_TIMEOUT5, POLL_INTERVAL_MS2, DEFAULT_GENERATE_BUDGET_MS, MAX_TIMEOUT_SECONDS, MAX_POLL_RESIGNS, VideoClient, DEFAULT_API_URL6, DEFAULT_TIMEOUT6, CALL_PRICE_USD, VALID_MODELS, VoiceClient, DEFAULT_API_URL7, DEFAULT_TIMEOUT7, PHONE_PRICES, PhoneClient, DEFAULT_API_URL8, DEFAULT_TIMEOUT8, PORTRAIT_ENROLLMENT_PRICE_USD, PortraitClient, DEFAULT_API_URL9, DEFAULT_TIMEOUT9, SearchClient, DEFAULT_API_URL10, DEFAULT_TIMEOUT10, PriceClient, DEFAULT_API_URL11, DEFAULT_TIMEOUT11, SURF_PREFIX, warnedRetired, SurfClient, DEFAULT_API_URL12, DEFAULT_TIMEOUT12, RPC_PRICE_USD, SUPPORTED_NETWORKS, NETWORK_ALIASES, RpcClient, DEFAULT_API_URL13, DEFAULT_TIMEOUT13, DEFAULT_POLL_INTERVAL_MS, DEFAULT_POLL_BUDGET_MS, MAX_SIGNED_AUTH_SECONDS, BlockrunClient, USDC_BASE_CONTRACT, BASE_CHAIN_ID2, WALLET_FILE_PATH, WALLET_DIR_PATH, WALLET_DIR3, SOLANA_WALLET_FILE, POLL_AUTH_HEADERS, ED25519_PKCS8_PREFIX, BATCH_SCHEME, BLOCKRUN_SOL_OPERATOR, DEFAULT_BATCH_RATE_LIMIT, DEFAULT_BATCH_IN_DOUBT, DEFAULT_BATCH_LOCK_WAIT_MS, LOCK_POLL_MS, BatchPaymentUnresolvedError, BatchCloseDeferredError, BatchChannelLockedError, INSTALL_HINT2, FileChannelStorage, MemoryChannelStorage, FileIntentJournal, MemoryIntentJournal, BATCH_REGISTRY, registryHost, registry22, lockIds, ChannelResyncRequiredError, ChannelBook, PAYMENT_CHANNELS_PROGRAM_ID2, CHANNEL, ChannelUnreadableError, ChannelLayoutError, layoutChecked, LANDING_MARGIN_BLOCKS, ResyncError, DEPOSIT_BLOCKHASH_TTL_MS, MAX_DEPOSIT_BLOCKHASH_ENDPOINTS, depositBlockhashes, PAYMENT_IDENTIFIER, IN_DOUBT_MIN_WAIT_MS, IN_DOUBT_MAX_WAIT_MS, BATCH_REFUSALS, PRE_REQUEST_REFUSALS, MAX_RETRY_AFTER_MS, NOT_BROADCAST_REFUSALS, CONFIG_REFUSALS, REFUSAL_COOLDOWN_MS, CONFIG_REFUSAL_COOLDOWN_MS, REFUSAL_COOLDOWN_MAX_MS, realSleep, sleep2, warnedNoSizer, payScope, RPC_SCOPE_STORE, RPC_HEADER_HOOK, sharedGlobal, rpcScope, SolanaBatchPayer, SOLANA_API_URL, DEFAULT_MAX_TOKENS22, STALE_BLOCKHASH_RETRY_BACKOFFS_MS, MAX_PAYMENT_FAILURE_BYTES, DEFAULT_VIDEO_MODEL, DEFAULT_MUSIC_MODEL, DEFAULT_VIDEO_BUDGET_MS, DEFAULT_MUSIC_BUDGET_MS, VIDEO_POLL_INTERVAL_MS, MAX_PAID_POLL_REFUSALS, MAX_RETRY_AFTER_MS2, MEDIA_SUBMIT_TIMEOUT_MS, SafeStaleBlockhashError, DEFAULT_SOLANA_RPC_URL, SolanaLLMClient, CACHE_DIR, DATA_DIR, COST_LOG_FILE2, DEFAULT_TTL, StreamingResponse, ChatCompletions, Chat, OpenAI, AnthropicClient;
110799
110864
  var init_dist2 = __esm({
110800
110865
  "node_modules/@blockrun/llm/dist/index.js"() {
110801
110866
  "use strict";
@@ -110963,6 +111028,7 @@ var init_dist2 = __esm({
110963
111028
  throw new APIError("Account API job polling timed out; check the job before submitting again.", 504, { poll_url: url3 });
110964
111029
  }
110965
111030
  };
111031
+ NOT_A_SKIP = /^(false|0|no|none)$/i;
110966
111032
  UNSEGMENTED_SCRIPT2 = /[؀-ۿ -ヿ㐀-䶿一-鿿가-힯豈-﫿＀-￯]/;
110967
111033
  WORD_CHAR2 = /[\p{L}\p{N}]/u;
110968
111034
  ASCII_PHRASE2 = /^[a-z0-9' -]+$/;
@@ -113970,7 +114036,7 @@ var init_dist2 = __esm({
113970
114036
  BLOCKRUN_SERVICE_CODE2 = "blockrun";
113971
114037
  BLOCKRUN_DIR = path2.join(os.homedir(), ".blockrun");
113972
114038
  COST_LOG_FILE = path2.join(BLOCKRUN_DIR, "cost_log.jsonl");
113973
- SDK_VERSION = "3.24.4";
114039
+ SDK_VERSION = "3.25.0";
113974
114040
  USER_AGENT2 = `blockrun-ts/${SDK_VERSION}`;
113975
114041
  DEFAULT_API_URL = "https://blockrun.ai/api";
113976
114042
  DEFAULT_MAX_TOKENS2 = 1024;
@@ -113997,8 +114063,15 @@ var init_dist2 = __esm({
113997
114063
  modelPricingCache = null;
113998
114064
  modelPricingPromise = null;
113999
114065
  // Pre-auth cache: avoids the 402 round-trip on repeat requests to the same model.
114000
- // Key = "endpoint:model", value = cached payment header + timestamp.
114066
+ // Key = "endpoint:model", value = cached payment header + timestamp + the
114067
+ // length of the request body it was quoted for.
114001
114068
  // TTL: 1 hour — pre-auth quotes are stable server-side on that horizon.
114069
+ //
114070
+ // A quote prices ONE request (input size + max_tokens), and exact settles
114071
+ // the whole signed amount, so reusing it for a smaller request overpaid and
114072
+ // for a larger one underpaid. The gateway refuses both with a 402 (an
114073
+ // over-signed payment since blockrun#874), so a reuse is only attempted for
114074
+ // a body the same size as the one that was quoted.
114002
114075
  preAuthCache = /* @__PURE__ */ new Map();
114003
114076
  static PRE_AUTH_TTL_MS = 36e5;
114004
114077
  /**
@@ -114518,9 +114591,9 @@ var init_dist2 = __esm({
114518
114591
  return this.bookPaid(url3, body, details, retryResponse);
114519
114592
  }
114520
114593
  /**
114521
- * Book a served, paid chat call and attach its cost. A response the gateway
114522
- * served from a free fallback with settlement skipped
114523
- * (`X-Settlement-Skipped: free-fallback`) moved nothing on chain, so it is
114594
+ * Book a served, paid chat call and attach its cost. A response whose
114595
+ * settlement the gateway skipped ({@link settlementSkipped}: e.g.
114596
+ * `X-Settlement-Skipped: free-fallback`) moved nothing on chain, so it is
114524
114597
  * not added to `getSpending()` or the cost log, and reports `costUsd: 0`.
114525
114598
  */
114526
114599
  async bookPaid(url3, body, details, response) {
@@ -114532,6 +114605,21 @@ var init_dist2 = __esm({
114532
114605
  }
114533
114606
  return withCost(await this.parseChatResponse(response), response, costUsd, "exact");
114534
114607
  }
114608
+ /**
114609
+ * Book a served, paid raw (non-chat) call: the signed amount goes to
114610
+ * `getSpending()` and the cost log, unless the gateway skipped settlement
114611
+ * ({@link settlementSkipped}: e.g. `X-Settlement-Skipped: empty-result` on an
114612
+ * empty prediction-market search, `unexecuted` on a JSON-RPC call that never
114613
+ * ran, or `X-Payment-Waived`), in which case nothing moved and nothing is
114614
+ * booked. `X-Payment-Settled: false` alone is still booked: it is owed.
114615
+ */
114616
+ bookPaidRaw(url3, details, response, body) {
114617
+ if (settlementSkipped(response)) return;
114618
+ const costUsd = parseFloat(details.amount) / 1e6;
114619
+ this.sessionCalls += 1;
114620
+ this.sessionTotalUsd += costUsd;
114621
+ this.recordCost(url3, costUsd, body ? { body, network: details.network } : { network: details.network });
114622
+ }
114535
114623
  /**
114536
114624
  * Sign a payment header and return the PAYMENT-SIGNATURE value.
114537
114625
  * Extracted to share logic between streaming and non-streaming flows.
@@ -114605,9 +114693,10 @@ var init_dist2 = __esm({
114605
114693
  if (options?.responseFormat !== void 0) body.response_format = options.responseFormat;
114606
114694
  if (options?.stop !== void 0) body.stop = options.stop;
114607
114695
  const cacheKey22 = `/v1/chat/completions:${requestModel}`;
114696
+ const requestBody = JSON.stringify(body);
114608
114697
  const cached2 = this.preAuthCache.get(cacheKey22);
114609
114698
  const now2 = Date.now();
114610
- if (cached2 && now2 - cached2.cachedAt < _LLMClient.PRE_AUTH_TTL_MS) {
114699
+ if (cached2 && now2 - cached2.cachedAt < _LLMClient.PRE_AUTH_TTL_MS && cached2.bodyLength === requestBody.length) {
114611
114700
  let signed2;
114612
114701
  try {
114613
114702
  signed2 = await this.signPayment(cached2.paymentHeader);
@@ -114631,8 +114720,10 @@ var init_dist2 = __esm({
114631
114720
  throw withDisposition(err, "paid-or-in-doubt");
114632
114721
  }
114633
114722
  if (preAuthResp.ok) {
114634
- this.sessionCalls += 1;
114635
- this.sessionTotalUsd += signed2.costUsd;
114723
+ if (!settlementSkipped(preAuthResp)) {
114724
+ this.sessionCalls += 1;
114725
+ this.sessionTotalUsd += signed2.costUsd;
114726
+ }
114636
114727
  return preAuthResp;
114637
114728
  }
114638
114729
  this.preAuthCache.delete(cacheKey22);
@@ -114676,7 +114767,7 @@ var init_dist2 = __esm({
114676
114767
  }
114677
114768
  }
114678
114769
  if (!paymentHeader) throw new PaymentError("402 response but no payment requirements found");
114679
- this.preAuthCache.set(cacheKey22, { paymentHeader, cachedAt: now2 });
114770
+ this.preAuthCache.set(cacheKey22, { paymentHeader, cachedAt: now2, bodyLength: requestBody.length });
114680
114771
  const { paymentPayload, costUsd } = await this.signPayment(paymentHeader);
114681
114772
  const streamResp = await this.fetchWithTimeout(url3, {
114682
114773
  method: "POST",
@@ -114697,8 +114788,10 @@ var init_dist2 = __esm({
114697
114788
  }
114698
114789
  throw new APIError(`API error after payment: ${streamResp.status}`, streamResp.status, sanitizeErrorResponse(errorBody));
114699
114790
  }
114700
- this.sessionCalls += 1;
114701
- this.sessionTotalUsd += costUsd;
114791
+ if (!settlementSkipped(streamResp)) {
114792
+ this.sessionCalls += 1;
114793
+ this.sessionTotalUsd += costUsd;
114794
+ }
114702
114795
  return streamResp;
114703
114796
  }
114704
114797
  /**
@@ -114822,10 +114915,7 @@ var init_dist2 = __esm({
114822
114915
  }
114823
114916
  throw new APIError(`API error after payment: ${retryResp2.status}`, retryResp2.status, sanitizeErrorResponse(errorBody));
114824
114917
  }
114825
- const costUsd2 = parseFloat(details.amount) / 1e6;
114826
- this.sessionCalls += 1;
114827
- this.sessionTotalUsd += costUsd2;
114828
- this.recordCost(url3, costUsd2, { body, network: details.network });
114918
+ this.bookPaidRaw(url3, details, retryResp2, body);
114829
114919
  return retryResp2.json();
114830
114920
  }
114831
114921
  }
@@ -114845,10 +114935,7 @@ var init_dist2 = __esm({
114845
114935
  sanitizeErrorResponse(errorBody)
114846
114936
  );
114847
114937
  }
114848
- const costUsd = parseFloat(details.amount) / 1e6;
114849
- this.sessionCalls += 1;
114850
- this.sessionTotalUsd += costUsd;
114851
- this.recordCost(url3, costUsd, { body, network: details.network });
114938
+ this.bookPaidRaw(url3, details, retryResponse, body);
114852
114939
  return retryResponse.json();
114853
114940
  }
114854
114941
  /**
@@ -114968,10 +115055,7 @@ var init_dist2 = __esm({
114968
115055
  }
114969
115056
  throw new APIError(`API error after payment: ${retryResp2.status}`, retryResp2.status, sanitizeErrorResponse(errorBody));
114970
115057
  }
114971
- const costUsd2 = parseFloat(details.amount) / 1e6;
114972
- this.sessionCalls += 1;
114973
- this.sessionTotalUsd += costUsd2;
114974
- this.recordCost(url3, costUsd2, { network: details.network });
115058
+ this.bookPaidRaw(url3, details, retryResp2);
114975
115059
  return retryResp2.json();
114976
115060
  }
114977
115061
  }
@@ -114991,10 +115075,7 @@ var init_dist2 = __esm({
114991
115075
  sanitizeErrorResponse(errorBody)
114992
115076
  );
114993
115077
  }
114994
- const costUsd = parseFloat(details.amount) / 1e6;
114995
- this.sessionCalls += 1;
114996
- this.sessionTotalUsd += costUsd;
114997
- this.recordCost(url3, costUsd, { network: details.network });
115078
+ this.bookPaidRaw(url3, details, retryResponse);
114998
115079
  return retryResponse.json();
114999
115080
  }
115000
115081
  /**
@@ -116001,8 +116082,10 @@ var init_dist2 = __esm({
116001
116082
  throw new APIError(`API error after payment: ${retryResponse.status}`, retryResponse.status, sanitizeErrorResponse(errorBody));
116002
116083
  }
116003
116084
  const data = await retryResponse.json();
116004
- this.sessionCalls++;
116005
- this.sessionTotalUsd += 0.1575;
116085
+ if (!settlementSkipped(retryResponse)) {
116086
+ this.sessionCalls++;
116087
+ this.sessionTotalUsd += 0.1575;
116088
+ }
116006
116089
  const txHash = retryResponse.headers.get("x-payment-receipt") || retryResponse.headers.get("X-Payment-Receipt");
116007
116090
  if (txHash) data.txHash = txHash;
116008
116091
  return data;
@@ -116211,9 +116294,11 @@ var init_dist2 = __esm({
116211
116294
  throw new APIError(`API error after payment: ${retryResponse.status}`, retryResponse.status, sanitizeErrorResponse(errorBody));
116212
116295
  }
116213
116296
  const data = await retryResponse.json();
116214
- this.sessionCalls++;
116215
- const paidUsd = Number(details.amount) / 1e6;
116216
- if (Number.isFinite(paidUsd)) this.sessionTotalUsd += paidUsd;
116297
+ if (!settlementSkipped(retryResponse)) {
116298
+ this.sessionCalls++;
116299
+ const paidUsd = Number(details.amount) / 1e6;
116300
+ if (Number.isFinite(paidUsd)) this.sessionTotalUsd += paidUsd;
116301
+ }
116217
116302
  const txHash = retryResponse.headers.get("x-payment-receipt") || retryResponse.headers.get("X-Payment-Receipt");
116218
116303
  if (txHash) data.txHash = txHash;
116219
116304
  return data;
@@ -116507,8 +116592,10 @@ var init_dist2 = __esm({
116507
116592
  }
116508
116593
  if (lastStatus === "completed") {
116509
116594
  const data = pollData;
116510
- this.sessionCalls++;
116511
- this.sessionTotalUsd += Number(details.amount) / 1e6;
116595
+ if (!settlementSkipped(pollResp)) {
116596
+ this.sessionCalls++;
116597
+ this.sessionTotalUsd += Number(details.amount) / 1e6;
116598
+ }
116512
116599
  const txHash = pollResp.headers.get("x-payment-receipt") || pollResp.headers.get("X-Payment-Receipt");
116513
116600
  if (txHash) data.txHash = txHash;
116514
116601
  return data;
@@ -116800,8 +116887,10 @@ var init_dist2 = __esm({
116800
116887
  throw new APIError(`API error after payment: ${retryResponse.status}`, retryResponse.status, sanitizeErrorResponse(errorBody));
116801
116888
  }
116802
116889
  const data = await retryResponse.json();
116803
- this.sessionCalls++;
116804
- this.sessionTotalUsd += CALL_PRICE_USD;
116890
+ if (!settlementSkipped(retryResponse)) {
116891
+ this.sessionCalls++;
116892
+ this.sessionTotalUsd += CALL_PRICE_USD;
116893
+ }
116805
116894
  const txHash = retryResponse.headers.get("x-payment-receipt") || retryResponse.headers.get("X-Payment-Receipt");
116806
116895
  if (txHash) data.txHash = txHash;
116807
116896
  return data;
@@ -117006,9 +117095,10 @@ var init_dist2 = __esm({
117006
117095
  throw new PaymentError("Payment was rejected. Check your wallet balance.");
117007
117096
  }
117008
117097
  const data = await this.unwrap(retry, true);
117009
- const costUsd = Number.parseFloat(details.amount) / 1e6;
117010
- this.sessionCalls += 1;
117011
- this.sessionTotalUsd += costUsd;
117098
+ if (!settlementSkipped(retry)) {
117099
+ this.sessionCalls += 1;
117100
+ this.sessionTotalUsd += Number.parseFloat(details.amount) / 1e6;
117101
+ }
117012
117102
  const txHash = retry.headers.get("x-payment-receipt") || retry.headers.get("X-Payment-Receipt");
117013
117103
  if (txHash && data && typeof data === "object" && !("txHash" in data)) {
117014
117104
  data.txHash = txHash;
@@ -117170,9 +117260,10 @@ var init_dist2 = __esm({
117170
117260
  throw new PaymentError("Payment was rejected. Check your wallet balance.");
117171
117261
  }
117172
117262
  const data = await this.unwrap(retry, true);
117173
- const costUsd = Number.parseFloat(details.amount) / 1e6;
117174
- this.sessionCalls += 1;
117175
- this.sessionTotalUsd += costUsd;
117263
+ if (!settlementSkipped(retry)) {
117264
+ this.sessionCalls += 1;
117265
+ this.sessionTotalUsd += Number.parseFloat(details.amount) / 1e6;
117266
+ }
117176
117267
  if (data && typeof data === "object" && !("txHash" in data)) {
117177
117268
  const settlement = data.settlement;
117178
117269
  if (settlement?.tx_hash) {
@@ -117956,9 +118047,11 @@ var init_dist2 = __esm({
117956
118047
  }
117957
118048
  throw new APIError(`API error after payment: ${retryResponse.status}`, retryResponse.status, sanitizeErrorResponse(errorBody));
117958
118049
  }
117959
- this.sessionCalls++;
117960
- const paidUsd = Number(details.amount) / 1e6;
117961
- if (Number.isFinite(paidUsd)) this.sessionTotalUsd += paidUsd;
118050
+ if (!settlementSkipped(retryResponse)) {
118051
+ this.sessionCalls++;
118052
+ const paidUsd = Number(details.amount) / 1e6;
118053
+ if (Number.isFinite(paidUsd)) this.sessionTotalUsd += paidUsd;
118054
+ }
117962
118055
  return { data: await retryResponse.json(), headers: retryResponse.headers };
117963
118056
  }
117964
118057
  async fetchWithTimeout(url3, options) {
@@ -118073,7 +118166,7 @@ var init_dist2 = __esm({
118073
118166
  if (resp402.status !== 402) {
118074
118167
  await this.throwApiError(resp402, `poll submit failed (${submitUrl})`);
118075
118168
  }
118076
- const paymentPayload = await this.signFrom402(resp402, submitUrl, {
118169
+ const { paymentPayload, costUsd } = await this.signFrom402(resp402, submitUrl, {
118077
118170
  description: "BlockRun async job",
118078
118171
  maxTimeoutSeconds: MAX_SIGNED_AUTH_SECONDS
118079
118172
  });
@@ -118092,7 +118185,7 @@ var init_dist2 = __esm({
118092
118185
  await this.throwApiError(submitResp, `poll submit failed (${submitUrl})`);
118093
118186
  }
118094
118187
  if (submitResp.status === 200) {
118095
- this.recordSpending();
118188
+ this.recordSpending(submitResp, costUsd);
118096
118189
  return submitResp.json();
118097
118190
  }
118098
118191
  const submitData = await submitResp.json();
@@ -118129,7 +118222,7 @@ var init_dist2 = __esm({
118129
118222
  );
118130
118223
  }
118131
118224
  if (pollResp.status === 200 && lastStatus === "completed") {
118132
- this.recordSpending();
118225
+ this.recordSpending(pollResp, costUsd);
118133
118226
  return pollData;
118134
118227
  }
118135
118228
  if (pollResp.status !== 200 && pollResp.status !== 202 && pollResp.status !== 504) {
@@ -118170,7 +118263,7 @@ var init_dist2 = __esm({
118170
118263
  if (resp402.status === 200) {
118171
118264
  streamResp = resp402;
118172
118265
  } else if (resp402.status === 402) {
118173
- const paymentPayload = await this.signFrom402(resp402, url3, {
118266
+ const { paymentPayload, costUsd } = await this.signFrom402(resp402, url3, {
118174
118267
  description: "BlockRun stream"
118175
118268
  });
118176
118269
  streamResp = await this.fetchWithTimeout(url3, {
@@ -118189,7 +118282,7 @@ var init_dist2 = __esm({
118189
118282
  if (!streamResp.ok) {
118190
118283
  await this.throwApiError(streamResp, `stream failed after payment (${url3})`);
118191
118284
  }
118192
- this.recordSpending();
118285
+ this.recordSpending(streamResp, costUsd);
118193
118286
  } else {
118194
118287
  await this.throwApiError(resp402, `stream failed (${url3})`);
118195
118288
  return;
@@ -118245,7 +118338,7 @@ var init_dist2 = __esm({
118245
118338
  return response.json();
118246
118339
  }
118247
118340
  async handlePaymentAndRetry(url3, method, body, response) {
118248
- const paymentPayload = await this.signFrom402(response, url3, {
118341
+ const { paymentPayload, costUsd } = await this.signFrom402(response, url3, {
118249
118342
  description: "BlockRun"
118250
118343
  });
118251
118344
  const retryInit = {
@@ -118268,13 +118361,14 @@ var init_dist2 = __esm({
118268
118361
  if (!retry.ok) {
118269
118362
  await this.throwApiError(retry, `${method} ${url3} failed after payment`);
118270
118363
  }
118271
- this.recordSpending();
118364
+ this.recordSpending(retry, costUsd);
118272
118365
  return retry.json();
118273
118366
  }
118274
118367
  /**
118275
118368
  * Read a 402 response's payment requirements (header or body), then sign and
118276
- * return the base64 PAYMENT-SIGNATURE payload. Also records the cost-to-be
118277
- * onto the response context (settled on `recordSpending`).
118369
+ * return the base64 PAYMENT-SIGNATURE payload with what it pays, in USD.
118370
+ * The cost stays with the call that signed it (booked by `recordSpending`):
118371
+ * concurrent calls on one client never share it.
118278
118372
  */
118279
118373
  async signFrom402(response, url3, opts) {
118280
118374
  let paymentHeader = response.headers.get("payment-required");
@@ -118292,8 +118386,8 @@ var init_dist2 = __esm({
118292
118386
  }
118293
118387
  const paymentRequired = parsePaymentRequired(paymentHeader);
118294
118388
  const details = extractPaymentDetails(paymentRequired);
118295
- this.pendingCostUsd = parseFloat(details.amount) / 1e6;
118296
- return createPaymentPayload(
118389
+ const costUsd = parseFloat(details.amount) / 1e6;
118390
+ const paymentPayload = await createPaymentPayload(
118297
118391
  this.privateKey,
118298
118392
  this.account.address,
118299
118393
  details.recipient,
@@ -118310,14 +118404,20 @@ var init_dist2 = __esm({
118310
118404
  asset: details.asset
118311
118405
  }
118312
118406
  );
118407
+ return { paymentPayload, costUsd };
118313
118408
  }
118314
- /** Accumulates the most-recent pending cost; settled by recordSpending. */
118315
- pendingCostUsd = 0;
118316
- recordSpending() {
118317
- if (this.pendingCostUsd > 0) {
118409
+ /**
118410
+ * Book `costUsd`, what the call that `response` answered signed. A response
118411
+ * whose settlement the gateway skipped ({@link settlementSkipped}:
118412
+ * `X-Settlement-Skipped: <reason>` or `X-Payment-Waived`) moved nothing, so
118413
+ * nothing is booked. `X-Payment-Settled: false` alone is still booked: the
118414
+ * payment is owed.
118415
+ */
118416
+ recordSpending(response, costUsd) {
118417
+ if (settlementSkipped(response)) return;
118418
+ if (costUsd > 0) {
118318
118419
  this.sessionCalls += 1;
118319
- this.sessionTotalUsd += this.pendingCostUsd;
118320
- this.pendingCostUsd = 0;
118420
+ this.sessionTotalUsd += costUsd;
118321
118421
  }
118322
118422
  }
118323
118423
  async throwApiError(resp, prefix) {
@@ -118369,6 +118469,8 @@ var init_dist2 = __esm({
118369
118469
  BLOCKRUN_SOL_OPERATOR = "5YKPQUFjw5WQqhSUkEGKNNfYYVqnRRNbpYyL71qQ1vm3";
118370
118470
  DEFAULT_BATCH_RATE_LIMIT = { maxAttempts: 3, maxWaitMs: 6e4 };
118371
118471
  DEFAULT_BATCH_IN_DOUBT = { maxWaitMs: 3e5 };
118472
+ DEFAULT_BATCH_LOCK_WAIT_MS = 6e4;
118473
+ LOCK_POLL_MS = 500;
118372
118474
  BatchPaymentUnresolvedError = class extends PaymentError {
118373
118475
  /** The {@link SolanaBatchEvent.reason} of the `unresolved` event reported with it. */
118374
118476
  reason;
@@ -118414,6 +118516,22 @@ var init_dist2 = __esm({
118414
118516
  this.channelIds = init2.channelIds ?? [];
118415
118517
  }
118416
118518
  };
118519
+ BatchChannelLockedError = class extends BlockrunError {
118520
+ /** The paying wallet's address. */
118521
+ wallet;
118522
+ /** The live owner's pid, when the SDK knows it. */
118523
+ ownerPid;
118524
+ /** How long this call waited for the lock, in ms (0 unless `onLocked` is `"wait"`). */
118525
+ waitedMs;
118526
+ constructor(init2) {
118527
+ super(`batch-settlement unavailable for wallet ${init2.wallet}: ${init2.detail}`);
118528
+ this.name = "BatchChannelLockedError";
118529
+ this.wallet = init2.wallet;
118530
+ if (init2.ownerPid !== void 0) this.ownerPid = init2.ownerPid;
118531
+ this.waitedMs = init2.waitedMs;
118532
+ withDisposition(this, "unpaid");
118533
+ }
118534
+ };
118417
118535
  INSTALL_HINT2 = "npm install @x402/core@~2.28.0 @x402/svm@~2.28.0 @solana/kit";
118418
118536
  FileChannelStorage = class {
118419
118537
  constructor(file2) {
@@ -118735,6 +118853,9 @@ var init_dist2 = __esm({
118735
118853
  }
118736
118854
  reason;
118737
118855
  };
118856
+ DEPOSIT_BLOCKHASH_TTL_MS = 1e4;
118857
+ MAX_DEPOSIT_BLOCKHASH_ENDPOINTS = 8;
118858
+ depositBlockhashes = /* @__PURE__ */ new Map();
118738
118859
  PAYMENT_IDENTIFIER = "payment-identifier";
118739
118860
  IN_DOUBT_MIN_WAIT_MS = 1e3;
118740
118861
  IN_DOUBT_MAX_WAIT_MS = 3e4;
@@ -118818,12 +118939,22 @@ var init_dist2 = __esm({
118818
118939
  if (!Number.isFinite(this.inDoubtMaxWaitMs) || this.inDoubtMaxWaitMs < 0) {
118819
118940
  throw new Error("batch.inDoubt.maxWaitMs must be a finite number of ms >= 0");
118820
118941
  }
118942
+ this.onLocked = init2.options.onLocked ?? "exact";
118943
+ if (this.onLocked !== "exact" && this.onLocked !== "wait" && this.onLocked !== "throw") {
118944
+ throw new Error('batch.onLocked must be "exact", "wait" or "throw"');
118945
+ }
118946
+ this.lockWaitMs = init2.options.lockWaitMs ?? DEFAULT_BATCH_LOCK_WAIT_MS;
118947
+ if (!Number.isFinite(this.lockWaitMs) || this.lockWaitMs < 0) {
118948
+ throw new Error("batch.lockWaitMs must be a finite number of ms >= 0");
118949
+ }
118821
118950
  }
118822
118951
  init;
118823
118952
  state;
118824
118953
  maxAttempts;
118825
118954
  maxWaitMs;
118826
118955
  inDoubtMaxWaitMs;
118956
+ onLocked;
118957
+ lockWaitMs;
118827
118958
  counters = {
118828
118959
  fallbacks: 0,
118829
118960
  fallbacksByReason: {},
@@ -118872,6 +119003,7 @@ var init_dist2 = __esm({
118872
119003
  if (owner !== void 0) {
118873
119004
  return {
118874
119005
  reason: "channel_store_locked",
119006
+ ownerPid: owner,
118875
119007
  detail: owner === process.pid ? `channel store ${file2} is in use by another copy of @blockrun/llm in this process (or by a process that had this pid and died: remove ${file2}.lock if nothing uses it)` : `channel store ${file2} is in use by process ${owner}`
118876
119008
  };
118877
119009
  }
@@ -119217,12 +119349,23 @@ var init_dist2 = __esm({
119217
119349
  const unavailable = batchUnavailable(paymentRequired);
119218
119350
  if (unavailable) return this.fallback(unavailable);
119219
119351
  let wallet;
119352
+ let waitedMs = 0;
119220
119353
  try {
119221
119354
  wallet = await this.wallet();
119355
+ if ("reason" in wallet && wallet.reason === "channel_store_locked" && this.onLocked === "wait") {
119356
+ const started = Date.now();
119357
+ wallet = await this.waitForLock(wallet);
119358
+ waitedMs = Date.now() - started;
119359
+ }
119222
119360
  } catch (err) {
119223
119361
  return this.fallback(creationFailure(err));
119224
119362
  }
119225
- if ("reason" in wallet) return this.fallback({ reason: wallet.reason, detail: wallet.detail });
119363
+ if ("reason" in wallet) {
119364
+ if (wallet.reason === "channel_store_locked" && this.onLocked !== "exact") {
119365
+ return this.lockedOut(wallet.detail, wallet.ownerPid, waitedMs);
119366
+ }
119367
+ return this.fallback({ reason: wallet.reason, detail: wallet.detail });
119368
+ }
119226
119369
  if (closesAtStart !== void 0 && wallet.closes !== closesAtStart) {
119227
119370
  return this.fallback({
119228
119371
  reason: "closed_during_call",
@@ -119239,6 +119382,40 @@ var init_dist2 = __esm({
119239
119382
  wallet.active -= 1;
119240
119383
  }
119241
119384
  }
119385
+ /**
119386
+ * `onLocked: "wait"`: try the wallet's channel store again every
119387
+ * {@link LOCK_POLL_MS} until its owner lets go of it or `lockWaitMs` runs
119388
+ * out. Reported once as a `backoff` event (`channel_store_locked`).
119389
+ */
119390
+ async waitForLock(refusal) {
119391
+ const deadline = Date.now() + this.lockWaitMs;
119392
+ let current = refusal;
119393
+ if (this.lockWaitMs > 0) {
119394
+ await this.report({
119395
+ type: "backoff",
119396
+ reason: "channel_store_locked",
119397
+ retryAfterMs: this.lockWaitMs,
119398
+ detail: refusal.detail
119399
+ });
119400
+ }
119401
+ while ("reason" in current && current.reason === "channel_store_locked") {
119402
+ const left = deadline - Date.now();
119403
+ if (left <= 0) break;
119404
+ await sleep2(Math.min(LOCK_POLL_MS, left));
119405
+ current = await this.wallet();
119406
+ }
119407
+ return current;
119408
+ }
119409
+ /** `onLocked` other than `"exact"`: the call's `"unpaid"` error, nothing signed. */
119410
+ async lockedOut(detail, ownerPid, waitedMs) {
119411
+ const error62 = new BatchChannelLockedError({
119412
+ wallet: await this.init.address(),
119413
+ detail,
119414
+ waitedMs,
119415
+ ...ownerPid !== void 0 ? { ownerPid } : {}
119416
+ });
119417
+ return { kind: "failed", error: error62 };
119418
+ }
119242
119419
  /**
119243
119420
  * The close fence for a call about to send its first request: how many
119244
119421
  * closes this wallet has completed so far, to hand to {@link pay}.
@@ -119329,11 +119506,9 @@ var init_dist2 = __esm({
119329
119506
  }
119330
119507
  if (wallet.busy) return fallback2({ reason: "channel_busy", attempt: budget.attempt });
119331
119508
  if (wallet.file && !holdsChannelFile(wallet.file)) {
119332
- return fallback2({
119333
- reason: "channel_store_locked",
119334
- attempt: budget.attempt,
119335
- detail: `this process no longer holds the lock on ${wallet.file}; another owner may be paying into its channels`
119336
- });
119509
+ const detail = `this process no longer holds the lock on ${wallet.file}; another owner may be paying into its channels`;
119510
+ if (this.onLocked !== "exact") return this.lockedOut(detail, void 0, 0);
119511
+ return fallback2({ reason: "channel_store_locked", attempt: budget.attempt, detail });
119337
119512
  }
119338
119513
  wallet.busy = true;
119339
119514
  holding = true;
@@ -119378,6 +119553,8 @@ var init_dist2 = __esm({
119378
119553
  wallet.refusedFor = outcome.errorReason;
119379
119554
  }
119380
119555
  }
119556
+ } else if (built.key && outcome.reason === "payment_required" && outcome.refusedForMs === void 0) {
119557
+ await this.recheckRefusedChannel(wallet, built.key, built.reclaimAnchor);
119381
119558
  }
119382
119559
  sent = void 0;
119383
119560
  release();
@@ -119645,6 +119822,13 @@ var init_dist2 = __esm({
119645
119822
  }
119646
119823
  /** Build a new batch payment for a 402: the payload, its headers and its kind. */
119647
119824
  async buildPayment(wallet, paymentRequired) {
119825
+ const acceptKey = channelKeyOf(trustedBatchAccept(paymentRequired, this.init.options.operators));
119826
+ let reclaimAnchor;
119827
+ try {
119828
+ const stored = acceptKey ? await wallet.book.base.get(acceptKey) : void 0;
119829
+ reclaimAnchor = stored ? savedReclaimAnchor(stored) : void 0;
119830
+ } catch {
119831
+ }
119648
119832
  const { http: http5, payload } = await this.createPayload(wallet, paymentRequired);
119649
119833
  const scope = payScope.getStore();
119650
119834
  if (scope?.afterError) {
@@ -119666,7 +119850,16 @@ var init_dist2 = __esm({
119666
119850
  const record2 = known?.record;
119667
119851
  kind = record2 && (record2.pending === void 0 || record2.hasConfirmedState) ? "top-up" : "open";
119668
119852
  }
119669
- return { http: http5, payload, headers, kind, key: known?.key, sentAt: Date.now(), sends: 0 };
119853
+ return {
119854
+ http: http5,
119855
+ payload,
119856
+ headers,
119857
+ kind,
119858
+ key: known?.key,
119859
+ ...reclaimAnchor !== void 0 && known?.key === acceptKey ? { reclaimAnchor } : {},
119860
+ sentAt: Date.now(),
119861
+ sends: 0
119862
+ };
119670
119863
  }
119671
119864
  /**
119672
119865
  * Write a deposit's intent to the wallet's journal before it is sent
@@ -119892,7 +120085,8 @@ var init_dist2 = __esm({
119892
120085
  const http5 = (await this.build(wallet)).http;
119893
120086
  try {
119894
120087
  await this.prepareTopUp(wallet, paymentRequired);
119895
- return { http: http5, payload: await http5.createPaymentPayload(withPaymentIdentifier(withoutClientSignedBatch(paymentRequired))) };
120088
+ const required2 = await this.withDepositBlockhash(wallet, withoutClientSignedBatch(paymentRequired));
120089
+ return { http: http5, payload: await http5.createPaymentPayload(withPaymentIdentifier(required2)) };
119896
120090
  } catch (err) {
119897
120091
  if (pass > 0 || !isResyncRequired(err) || wallet.resyncs.size === 0) throw err;
119898
120092
  } finally {
@@ -119900,6 +120094,112 @@ var init_dist2 = __esm({
119900
120094
  }
119901
120095
  }
119902
120096
  }
120097
+ /**
120098
+ * The 402 to build this payment from: with a finalized blockhash
120099
+ * ({@link withDepositBlockhash}) when the payment will likely carry a
120100
+ * deposit (no usable record for the trusted accept's channel, so an open,
120101
+ * or a top-up {@link prepareTopUp} just sized). An authorization signs no
120102
+ * transaction and costs no RPC read. Best effort: a failed read leaves the
120103
+ * 402 as it is, and `@x402/svm` fetches its own blockhash.
120104
+ */
120105
+ async withDepositBlockhash(wallet, paymentRequired) {
120106
+ const accept = trustedBatchAccept(paymentRequired, this.init.options.operators);
120107
+ const key3 = accept ? channelKeyOf(accept) : void 0;
120108
+ if (!accept || accept.extra?.recentBlockhash) return paymentRequired;
120109
+ let deposit = wallet.topUp !== void 0;
120110
+ if (!deposit) {
120111
+ try {
120112
+ const record2 = key3 ? await wallet.book.base.get(key3) : void 0;
120113
+ deposit = !record2 || typeof record2.channelId !== "string" || record2.pending !== void 0;
120114
+ } catch {
120115
+ deposit = true;
120116
+ }
120117
+ }
120118
+ if (!deposit) return paymentRequired;
120119
+ try {
120120
+ return withDepositBlockhash(paymentRequired, await finalizedBlockhash(this.init.rpcUrl, this.init.rpcHeaders));
120121
+ } catch {
120122
+ return paymentRequired;
120123
+ }
120124
+ }
120125
+ /**
120126
+ * Queue a re-read of a stored channel whose account is gone at finalized
120127
+ * and at confirmed commitment (closed, its account reclaimed), anchored at
120128
+ * the SDK's own `getBlockHeight` at confirmed. The anchor is saved in the
120129
+ * record (`reclaimAnchorHeight`), so a short-lived process finishes the
120130
+ * wait instead of starting it over; a failed read leaves resync to take it,
120131
+ * and a failed save only costs that. resync pays exact until finality is
120132
+ * LANDING_MARGIN_BLOCKS past the anchor, then drops the record if the
120133
+ * finalized chain still has no account (a lagging read finds the channel
120134
+ * and rewrites the record, without the anchor).
120135
+ */
120136
+ async queueReclaimed(wallet, key3, record2, channelId, savedAnchor) {
120137
+ let anchorHeight = savedReclaimAnchor(record2) ?? savedAnchor;
120138
+ if (anchorHeight === void 0) {
120139
+ try {
120140
+ anchorHeight = rpcInteger(
120141
+ await rpcRequest(this.init.rpcUrl, "getBlockHeight", [{ commitment: "confirmed" }], this.init.rpcHeaders),
120142
+ "getBlockHeight"
120143
+ );
120144
+ } catch {
120145
+ }
120146
+ }
120147
+ if (anchorHeight !== void 0 && savedReclaimAnchor(record2) !== anchorHeight) {
120148
+ try {
120149
+ await wallet.book.set(key3, { ...record2, reclaimAnchorHeight: anchorHeight });
120150
+ } catch {
120151
+ }
120152
+ }
120153
+ addResyncTarget(wallet, {
120154
+ key: key3,
120155
+ channelId,
120156
+ channelConfig: record2.channelConfig,
120157
+ cumulative: parseAtomic(record2.chargedCumulativeAmount),
120158
+ knownDeposit: parseAtomic(record2.deposit),
120159
+ ...anchorHeight !== void 0 ? { anchorHeight } : {},
120160
+ reason: "channel_unusable"
120161
+ });
120162
+ }
120163
+ /**
120164
+ * After the gateway refused an authorization with a plain 402 (no receipt,
120165
+ * not an admission refusal), check the channel it paid into. That is how
120166
+ * the gateway answers an authorization into a channel the facilitator
120167
+ * closed (its verify rejects it), and a channel with deposit to spare is
120168
+ * otherwise never read again: every call would sign another authorization
120169
+ * into it and pay exact. A channel the finalized chain shows closing,
120170
+ * closed or not this wallet's is re-read through resync (record dropped,
120171
+ * or kept and paid exact); one gone at every commitment is queued as
120172
+ * {@link queueReclaimed}; an open one of this wallet's, or one only at
120173
+ * confirmed (not finalized yet), is left as it is. A queued re-read is run
120174
+ * at once. Best effort: a failed read changes nothing, and the next
120175
+ * refusal checks again.
120176
+ */
120177
+ async recheckRefusedChannel(wallet, key3, savedAnchor) {
120178
+ try {
120179
+ const record2 = await wallet.book.get(key3);
120180
+ if (!record2 || record2.pending || typeof record2.channelId !== "string" || wallet.resyncs.has(key3)) return;
120181
+ const channelId = record2.channelId;
120182
+ const channel = await readChannelAccount(this.init.rpcUrl, channelId, this.init.rpcHeaders);
120183
+ if (channel !== void 0) {
120184
+ if (channel.open && channel.payer === await this.init.address() && channel.authorizedSigner === record2.channelConfig.payerAuthorizer && channel.mint === record2.channelConfig.token) {
120185
+ return;
120186
+ }
120187
+ addResyncTarget(wallet, {
120188
+ key: key3,
120189
+ channelId,
120190
+ channelConfig: record2.channelConfig,
120191
+ cumulative: parseAtomic(record2.chargedCumulativeAmount),
120192
+ knownDeposit: parseAtomic(record2.deposit),
120193
+ reason: "channel_unusable"
120194
+ });
120195
+ } else {
120196
+ if (await readChannelAccount(this.init.rpcUrl, channelId, this.init.rpcHeaders, { commitment: "confirmed" }) !== void 0) return;
120197
+ await this.queueReclaimed(wallet, key3, record2, channelId, savedAnchor);
120198
+ }
120199
+ await this.resync(wallet);
120200
+ } catch {
120201
+ }
120202
+ }
119903
120203
  /**
119904
120204
  * When this payment will top up the wallet's channel, read how much of its
119905
120205
  * deposit is already settled on-chain (at `finalized` commitment, so never
@@ -119917,7 +120217,11 @@ var init_dist2 = __esm({
119917
120217
  * pays exact (`channel_unreadable`), record kept. If
119918
120218
  * the finalized channel is closing or closed, or is not this wallet's for
119919
120219
  * the record's operator and mint, no top-up is sized from the record: it
119920
- * is re-read at once (`channel_unusable`), see {@link createPayload}.
120220
+ * is re-read at once (`channel_unusable`), see {@link createPayload}. So is
120221
+ * a channel with no account at finalized or at confirmed commitment (closed
120222
+ * and reclaimed); resync drops its record only once finality is past its
120223
+ * own anchor. One that shows only at confirmed is not finalized yet: the
120224
+ * lifetime cap applies.
119921
120225
  */
119922
120226
  async prepareTopUp(wallet, paymentRequired) {
119923
120227
  wallet.topUp = void 0;
@@ -119929,8 +120233,12 @@ var init_dist2 = __esm({
119929
120233
  const deposit = parseAtomic(record2.deposit);
119930
120234
  if (parseAtomic(record2.chargedCumulativeAmount) + parseAtomic(accept.amount) <= deposit) return;
119931
120235
  let channel;
120236
+ let unfinalized = false;
119932
120237
  try {
119933
120238
  channel = await readChannelAccount(this.init.rpcUrl, record2.channelId, this.init.rpcHeaders);
120239
+ if (channel === void 0) {
120240
+ unfinalized = await readChannelAccount(this.init.rpcUrl, record2.channelId, this.init.rpcHeaders, { commitment: "confirmed" }) !== void 0;
120241
+ }
119934
120242
  } catch (err) {
119935
120243
  if (err instanceof ChannelLayoutError) {
119936
120244
  throw new ResyncError("channel_unreadable", `channel ${record2.channelId}: ${err.message}; no top-up is sized from it`);
@@ -119943,7 +120251,11 @@ var init_dist2 = __esm({
119943
120251
  `could not read channel ${record2.channelId} before topping it up: ${err instanceof Error ? err.message : String(err)}`
119944
120252
  );
119945
120253
  }
119946
- if (channel === void 0) return;
120254
+ if (channel === void 0 && unfinalized) return;
120255
+ if (channel === void 0) {
120256
+ await this.queueReclaimed(wallet, key3, record2, record2.channelId);
120257
+ throw new ChannelResyncRequiredError(record2.channelId);
120258
+ }
119947
120259
  if (!channel.open || channel.payer !== await this.init.address() || channel.authorizedSigner !== record2.channelConfig.payerAuthorizer || channel.mint !== record2.channelConfig.token) {
119948
120260
  addResyncTarget(wallet, {
119949
120261
  key: key3,
@@ -120114,7 +120426,6 @@ var init_dist2 = __esm({
120114
120426
  };
120115
120427
  SOLANA_API_URL = "https://sol.blockrun.ai/api";
120116
120428
  DEFAULT_MAX_TOKENS22 = 1024;
120117
- DEFAULT_TIMEOUT14 = 6e4;
120118
120429
  STALE_BLOCKHASH_RETRY_BACKOFFS_MS = [500, 2e3];
120119
120430
  MAX_PAYMENT_FAILURE_BYTES = 64 * 1024;
120120
120431
  DEFAULT_VIDEO_MODEL = "xai/grok-imagine-video";
@@ -120170,7 +120481,7 @@ var init_dist2 = __esm({
120170
120481
  const rpc = resolveRpcConfig(options.rpcUrl, options.rpcHeaders);
120171
120482
  this.rpcUrl = rpc.url;
120172
120483
  this.rpcHeaders = rpc.headers;
120173
- this.timeout = options.timeout || DEFAULT_TIMEOUT14;
120484
+ this.timeout = options.timeout || DEFAULT_TIMEOUT;
120174
120485
  if (options.batch && !this.apiAuth) {
120175
120486
  this.batchPayer = new SolanaBatchPayer({
120176
120487
  options: options.batch,
@@ -120464,7 +120775,7 @@ var init_dist2 = __esm({
120464
120775
  body: requestBody
120465
120776
  });
120466
120777
  await this.assertPaid(paid);
120467
- this.recordSettlement(costUsd);
120778
+ this.recordSettlement(costUsd, paid);
120468
120779
  return paid;
120469
120780
  } catch (error62) {
120470
120781
  if (!(error62 instanceof SafeStaleBlockhashError) || staleRetries >= STALE_BLOCKHASH_RETRY_BACKOFFS_MS.length) throw error62;
@@ -120851,7 +121162,7 @@ var init_dist2 = __esm({
120851
121162
  closesAtStart
120852
121163
  );
120853
121164
  if (batch.kind === "paid") {
120854
- this.recordSettlement(batch.chargedUsd);
121165
+ this.recordSettlement(batch.chargedUsd, batch.response);
120855
121166
  const paid = await this.readPaidJson(batch.response);
120856
121167
  return withCost(paid, batch.response, batch.chargedUsd, "batch");
120857
121168
  }
@@ -120968,7 +121279,7 @@ var init_dist2 = __esm({
120968
121279
  };
120969
121280
  const deliver = (data, response) => {
120970
121281
  if (kind === "video") {
120971
- if (videoCostUsd !== void 0) this.recordSettlement(videoCostUsd);
121282
+ if (videoCostUsd !== void 0) this.recordSettlement(videoCostUsd, response);
120972
121283
  const txHash = response.headers.get("x-payment-receipt");
120973
121284
  if (txHash) data.txHash = txHash;
120974
121285
  }
@@ -121215,7 +121526,7 @@ var init_dist2 = __esm({
121215
121526
  throw withDisposition(error62, "paid-or-in-doubt");
121216
121527
  }
121217
121528
  await this.assertPaid(retryResponse);
121218
- if (!settlementSkipped(retryResponse)) this.recordSettlement(costUsd);
121529
+ this.recordSettlement(costUsd, retryResponse);
121219
121530
  const paid = await this.readPaidJson(retryResponse);
121220
121531
  return withCost(paid, retryResponse, costUsd, "exact");
121221
121532
  }
@@ -121275,11 +121586,11 @@ var init_dist2 = __esm({
121275
121586
  await this.assertPaid(retryResponse);
121276
121587
  if (retryResponse.status === 202) {
121277
121588
  const kind = pollKindFor(url3);
121278
- if (kind !== "video") this.recordSettlement(costUsd);
121589
+ if (kind !== "video") this.recordSettlement(costUsd, retryResponse);
121279
121590
  const submitted = await retryResponse.json();
121280
121591
  return this.followSolanaJob(submitted, media.pollBudgetMs ?? this.timeout, kind);
121281
121592
  }
121282
- this.recordSettlement(costUsd);
121593
+ this.recordSettlement(costUsd, retryResponse);
121283
121594
  return retryResponse.json();
121284
121595
  }
121285
121596
  async getWithPaymentRaw(endpoint, params) {
@@ -121323,7 +121634,7 @@ var init_dist2 = __esm({
121323
121634
  }
121324
121635
  });
121325
121636
  await this.assertPaid(retryResponse);
121326
- this.recordSettlement(costUsd);
121637
+ this.recordSettlement(costUsd, retryResponse);
121327
121638
  return retryResponse.json();
121328
121639
  }
121329
121640
  /**
@@ -121361,8 +121672,17 @@ var init_dist2 = __esm({
121361
121672
  );
121362
121673
  }
121363
121674
  }
121364
- /** Count one settled x402 payment against the session total. */
121365
- recordSettlement(costUsd) {
121675
+ /**
121676
+ * Count one settled x402 payment against the session total.
121677
+ *
121678
+ * Takes the paid response so no booking site can forget the check: a
121679
+ * response whose settlement the gateway skipped ({@link settlementSkipped}:
121680
+ * `X-Settlement-Skipped: free-fallback | empty-result | unexecuted | …`, or
121681
+ * `X-Payment-Waived`) moved nothing on chain and books nothing.
121682
+ * `X-Payment-Settled: false` alone is still booked: the payment is owed.
121683
+ */
121684
+ recordSettlement(costUsd, response) {
121685
+ if (settlementSkipped(response)) return;
121366
121686
  this.sessionCalls += 1;
121367
121687
  this.sessionTotalUsd += costUsd;
121368
121688
  }
@@ -176598,8 +176918,14 @@ var require_follow_redirects = __commonJS({
176598
176918
  RedirectableRequest.prototype._sanitizeOptions = function(options) {
176599
176919
  if (!options.headers) {
176600
176920
  options.headers = {};
176921
+ } else if (Array.isArray(options.headers)) {
176922
+ var headerList = options.headers;
176923
+ options.headers = {};
176924
+ for (var i = 0; i < headerList.length; i += 2) {
176925
+ options.headers[headerList[i]] = headerList[i + 1];
176926
+ }
176601
176927
  }
176602
- if (!isArray2(options.sensitiveHeaders)) {
176928
+ if (!Array.isArray(options.sensitiveHeaders)) {
176603
176929
  options.sensitiveHeaders = [];
176604
176930
  }
176605
176931
  if (options.host) {
@@ -176856,9 +177182,6 @@ var require_follow_redirects = __commonJS({
176856
177182
  var dot = subdomain.length - domain2.length - 1;
176857
177183
  return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain2);
176858
177184
  }
176859
- function isArray2(value) {
176860
- return value instanceof Array;
176861
- }
176862
177185
  function isString2(value) {
176863
177186
  return typeof value === "string" || value instanceof String;
176864
177187
  }
@@ -176872,7 +177195,7 @@ var require_follow_redirects = __commonJS({
176872
177195
  return URL3 && value instanceof URL3;
176873
177196
  }
176874
177197
  function escapeRegex4(regex) {
176875
- return regex.replace(/[\]\\/()*+?.$]/g, "\\$&");
177198
+ return regex.replace(/[[\]\\/()*+?.^$|]/g, "\\$&");
176876
177199
  }
176877
177200
  module.exports = wrap3({ http: http5, https: https2 });
176878
177201
  module.exports.wrap = wrap3;