@blockrun/clawrouter 0.12.304 → 0.12.305

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 +412 -92
  2. package/dist/index.js +412 -92
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -83708,11 +83708,13 @@ __export(dist_exports, {
83708
83708
  AnthropicClient: () => AnthropicClient,
83709
83709
  BASE_CHAIN_ID: () => BASE_CHAIN_ID,
83710
83710
  BLOCKRUN_SOL_OPERATOR: () => BLOCKRUN_SOL_OPERATOR,
83711
+ BatchChannelLockedError: () => BatchChannelLockedError,
83711
83712
  BatchCloseDeferredError: () => BatchCloseDeferredError,
83712
83713
  BatchPaymentUnresolvedError: () => BatchPaymentUnresolvedError,
83713
83714
  BlockrunClient: () => BlockrunClient,
83714
83715
  BlockrunError: () => BlockrunError,
83715
83716
  DEFAULT_BATCH_IN_DOUBT: () => DEFAULT_BATCH_IN_DOUBT,
83717
+ DEFAULT_BATCH_LOCK_WAIT_MS: () => DEFAULT_BATCH_LOCK_WAIT_MS,
83716
83718
  DEFAULT_BATCH_RATE_LIMIT: () => DEFAULT_BATCH_RATE_LIMIT,
83717
83719
  EVM_NETWORKS: () => EVM_NETWORKS,
83718
83720
  ImageClient: () => ImageClient,
@@ -84093,13 +84095,43 @@ function readSettlement(response, quotedUsd, scheme) {
84093
84095
  };
84094
84096
  return { costUsd, settlement };
84095
84097
  }
84098
+ function settlementSkipReason(response) {
84099
+ const headers = response.headers;
84100
+ if (typeof headers?.get !== "function") return void 0;
84101
+ const reason = [headers.get("X-Settlement-Skipped"), headers.get("X-Payment-Waived")].map((value) => value?.trim()).find((value) => !!value && !NOT_A_SKIP.test(value));
84102
+ if (reason === void 0) return void 0;
84103
+ const evidence = settlementEvidence(response);
84104
+ if (evidence !== void 0) {
84105
+ console.error(
84106
+ `[@blockrun/llm] settlement: the gateway named a skipped settlement (${JSON.stringify(reason)}) on a response that also carries ${evidence}; booked as charged`
84107
+ );
84108
+ return void 0;
84109
+ }
84110
+ return reason;
84111
+ }
84112
+ function settlementEvidence(response) {
84113
+ const header = response.headers.get("PAYMENT-RESPONSE") ?? response.headers.get("X-PAYMENT-RESPONSE");
84114
+ const receipt = header ? decode4(header) : void 0;
84115
+ if (receipt && receipt.success !== false) {
84116
+ if (typeof receipt.transaction === "string" && receipt.transaction) return "a settlement receipt with a transaction";
84117
+ const extra = receipt.extra;
84118
+ const charged = receiptChargedUsd({
84119
+ amount: receipt.amount,
84120
+ extra: extra && typeof extra === "object" ? extra : void 0
84121
+ });
84122
+ if (charged !== void 0 && charged > 0) return "a settlement receipt with a charge";
84123
+ }
84124
+ if (response.headers.get("X-Payment-Receipt")?.trim()) return "an X-Payment-Receipt transaction";
84125
+ return void 0;
84126
+ }
84096
84127
  function settlementSkipped(response) {
84097
- return response.headers.get("X-Settlement-Skipped") === "free-fallback";
84128
+ return settlementSkipReason(response) !== void 0;
84098
84129
  }
84099
84130
  function withCost(body, response, bookedUsd, scheme) {
84100
- if (settlementSkipped(response)) {
84131
+ const skipped = settlementSkipReason(response);
84132
+ if (skipped !== void 0) {
84101
84133
  body.costUsd = 0;
84102
- body.settlement = { ...readSettlement(response, bookedUsd, scheme).settlement, skipped: "free-fallback" };
84134
+ body.settlement = { ...readSettlement(response, bookedUsd, scheme).settlement, skipped };
84103
84135
  return body;
84104
84136
  }
84105
84137
  body.costUsd = bookedUsd;
@@ -85121,10 +85153,10 @@ function isEligible2(modelId, features, maxOutputTokens, options) {
85121
85153
  return model.contextWindow >= (features.estimatedInputTokens + maxOutputTokens) * 1.1;
85122
85154
  }
85123
85155
  function estimatedCost2(modelId, options, inputTokens, outputTokens) {
85124
- const price = options.modelPricing.get(modelId);
85125
- if (!price) return Number.POSITIVE_INFINITY;
85126
- if (price.flatPrice !== void 0) return price.flatPrice;
85127
- return (inputTokens * price.inputPrice + outputTokens * price.outputPrice) / 1e6;
85156
+ const price2 = options.modelPricing.get(modelId);
85157
+ if (!price2) return Number.POSITIVE_INFINITY;
85158
+ if (price2.flatPrice !== void 0) return price2.flatPrice;
85159
+ return (inputTokens * price2.inputPrice + outputTokens * price2.outputPrice) / 1e6;
85128
85160
  }
85129
85161
  function profileScore2(modelId, options, now2) {
85130
85162
  const profile = options.modelPerformance?.[modelId] ?? LIVE_MODEL_PROFILES2[modelId] ?? HISTORICAL_MODEL_PROFILES2[modelId];
@@ -86420,7 +86452,7 @@ function decodeChannelAccount(owner, data) {
86420
86452
  }
86421
86453
  async function readChannelAccount(rpcUrl, channelId, rpcHeaders, options = {}) {
86422
86454
  await checkChannelLayout();
86423
- const config2 = { encoding: "base64", commitment: "finalized" };
86455
+ const config2 = { encoding: "base64", commitment: options.commitment ?? "finalized" };
86424
86456
  if (options.minContextSlot !== void 0) config2.minContextSlot = options.minContextSlot;
86425
86457
  const response = await fetch(rpcUrl, {
86426
86458
  method: "POST",
@@ -86482,6 +86514,10 @@ function checkChannelLayout() {
86482
86514
  });
86483
86515
  return layoutChecked;
86484
86516
  }
86517
+ function savedReclaimAnchor(record2) {
86518
+ const saved = record2.reclaimAnchorHeight;
86519
+ return typeof saved === "number" && Number.isSafeInteger(saved) && saved > 0 ? saved : void 0;
86520
+ }
86485
86521
  function maxOf(a, b) {
86486
86522
  if (a === void 0) return b;
86487
86523
  if (b === void 0) return a;
@@ -86506,6 +86542,35 @@ function withoutClientSignedBatch(paymentRequired) {
86506
86542
  const accepts = paymentRequired.accepts ?? [];
86507
86543
  return accepts.some(clientSignedBatch) ? { ...paymentRequired, accepts: accepts.filter((accept) => !clientSignedBatch(accept)) } : paymentRequired;
86508
86544
  }
86545
+ async function finalizedBlockhash(rpcUrl, rpcHeaders) {
86546
+ const cached2 = depositBlockhashes.get(rpcUrl);
86547
+ if (cached2 && Date.now() - cached2.fetchedAt < DEPOSIT_BLOCKHASH_TTL_MS) return cached2;
86548
+ const result = await rpcRequest(rpcUrl, "getLatestBlockhash", [{ commitment: "finalized" }], rpcHeaders);
86549
+ const blockhash2 = result.value?.blockhash;
86550
+ if (typeof blockhash2 !== "string" || !blockhash2) throw new Error("getLatestBlockhash returned no blockhash");
86551
+ const entry = {
86552
+ blockhash: blockhash2,
86553
+ lastValidBlockHeight: rpcInteger(result.value?.lastValidBlockHeight, "getLatestBlockhash lastValidBlockHeight"),
86554
+ fetchedAt: Date.now()
86555
+ };
86556
+ depositBlockhashes.delete(rpcUrl);
86557
+ depositBlockhashes.set(rpcUrl, entry);
86558
+ while (depositBlockhashes.size > MAX_DEPOSIT_BLOCKHASH_ENDPOINTS) {
86559
+ depositBlockhashes.delete(depositBlockhashes.keys().next().value);
86560
+ }
86561
+ return entry;
86562
+ }
86563
+ function withDepositBlockhash(paymentRequired, blockhash2) {
86564
+ const accepts = paymentRequired.accepts ?? [];
86565
+ const lacking = (accept) => accept.scheme === BATCH_SCHEME && !accept.extra?.recentBlockhash;
86566
+ if (!accepts.some(lacking)) return paymentRequired;
86567
+ return {
86568
+ ...paymentRequired,
86569
+ accepts: accepts.map(
86570
+ (accept) => lacking(accept) ? { ...accept, extra: { ...accept.extra, recentBlockhash: blockhash2.blockhash, lastValidBlockHeight: blockhash2.lastValidBlockHeight } } : accept
86571
+ )
86572
+ };
86573
+ }
86509
86574
  function withPaymentIdentifier(paymentRequired) {
86510
86575
  const declared = paymentRequired.extensions?.[PAYMENT_IDENTIFIER];
86511
86576
  if (typeof declared?.info?.required !== "boolean") return paymentRequired;
@@ -87166,7 +87231,7 @@ async function setupAgentClient(options = {}) {
87166
87231
  chain3 ??= !loadSolanaWallet() && loadWallet() ? "base" : "solana";
87167
87232
  return chain3 === "solana" ? setupAgentSolanaWallet(options) : setupAgentWallet(options);
87168
87233
  }
87169
- 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;
87234
+ 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;
87170
87235
  var init_dist = __esm({
87171
87236
  "node_modules/@blockrun/llm/dist/index.js"() {
87172
87237
  "use strict";
@@ -87334,6 +87399,7 @@ var init_dist = __esm({
87334
87399
  throw new APIError("Account API job polling timed out; check the job before submitting again.", 504, { poll_url: url3 });
87335
87400
  }
87336
87401
  };
87402
+ NOT_A_SKIP = /^(false|0|no|none)$/i;
87337
87403
  UNSEGMENTED_SCRIPT2 = /[؀-ۿ -ヿ㐀-䶿一-鿿가-힯豈-﫿＀-￯]/;
87338
87404
  WORD_CHAR2 = /[\p{L}\p{N}]/u;
87339
87405
  ASCII_PHRASE2 = /^[a-z0-9' -]+$/;
@@ -90341,7 +90407,7 @@ var init_dist = __esm({
90341
90407
  BLOCKRUN_SERVICE_CODE2 = "blockrun";
90342
90408
  BLOCKRUN_DIR = path2.join(os.homedir(), ".blockrun");
90343
90409
  COST_LOG_FILE = path2.join(BLOCKRUN_DIR, "cost_log.jsonl");
90344
- SDK_VERSION = "3.24.4";
90410
+ SDK_VERSION = "3.25.0";
90345
90411
  USER_AGENT2 = `blockrun-ts/${SDK_VERSION}`;
90346
90412
  DEFAULT_API_URL = "https://blockrun.ai/api";
90347
90413
  DEFAULT_MAX_TOKENS2 = 1024;
@@ -90368,8 +90434,15 @@ var init_dist = __esm({
90368
90434
  modelPricingCache = null;
90369
90435
  modelPricingPromise = null;
90370
90436
  // Pre-auth cache: avoids the 402 round-trip on repeat requests to the same model.
90371
- // Key = "endpoint:model", value = cached payment header + timestamp.
90437
+ // Key = "endpoint:model", value = cached payment header + timestamp + the
90438
+ // length of the request body it was quoted for.
90372
90439
  // TTL: 1 hour — pre-auth quotes are stable server-side on that horizon.
90440
+ //
90441
+ // A quote prices ONE request (input size + max_tokens), and exact settles
90442
+ // the whole signed amount, so reusing it for a smaller request overpaid and
90443
+ // for a larger one underpaid. The gateway refuses both with a 402 (an
90444
+ // over-signed payment since blockrun#874), so a reuse is only attempted for
90445
+ // a body the same size as the one that was quoted.
90373
90446
  preAuthCache = /* @__PURE__ */ new Map();
90374
90447
  static PRE_AUTH_TTL_MS = 36e5;
90375
90448
  /**
@@ -90889,9 +90962,9 @@ var init_dist = __esm({
90889
90962
  return this.bookPaid(url3, body, details, retryResponse);
90890
90963
  }
90891
90964
  /**
90892
- * Book a served, paid chat call and attach its cost. A response the gateway
90893
- * served from a free fallback with settlement skipped
90894
- * (`X-Settlement-Skipped: free-fallback`) moved nothing on chain, so it is
90965
+ * Book a served, paid chat call and attach its cost. A response whose
90966
+ * settlement the gateway skipped ({@link settlementSkipped}: e.g.
90967
+ * `X-Settlement-Skipped: free-fallback`) moved nothing on chain, so it is
90895
90968
  * not added to `getSpending()` or the cost log, and reports `costUsd: 0`.
90896
90969
  */
90897
90970
  async bookPaid(url3, body, details, response) {
@@ -90903,6 +90976,21 @@ var init_dist = __esm({
90903
90976
  }
90904
90977
  return withCost(await this.parseChatResponse(response), response, costUsd, "exact");
90905
90978
  }
90979
+ /**
90980
+ * Book a served, paid raw (non-chat) call: the signed amount goes to
90981
+ * `getSpending()` and the cost log, unless the gateway skipped settlement
90982
+ * ({@link settlementSkipped}: e.g. `X-Settlement-Skipped: empty-result` on an
90983
+ * empty prediction-market search, `unexecuted` on a JSON-RPC call that never
90984
+ * ran, or `X-Payment-Waived`), in which case nothing moved and nothing is
90985
+ * booked. `X-Payment-Settled: false` alone is still booked: it is owed.
90986
+ */
90987
+ bookPaidRaw(url3, details, response, body) {
90988
+ if (settlementSkipped(response)) return;
90989
+ const costUsd = parseFloat(details.amount) / 1e6;
90990
+ this.sessionCalls += 1;
90991
+ this.sessionTotalUsd += costUsd;
90992
+ this.recordCost(url3, costUsd, body ? { body, network: details.network } : { network: details.network });
90993
+ }
90906
90994
  /**
90907
90995
  * Sign a payment header and return the PAYMENT-SIGNATURE value.
90908
90996
  * Extracted to share logic between streaming and non-streaming flows.
@@ -90976,9 +91064,10 @@ var init_dist = __esm({
90976
91064
  if (options?.responseFormat !== void 0) body.response_format = options.responseFormat;
90977
91065
  if (options?.stop !== void 0) body.stop = options.stop;
90978
91066
  const cacheKey22 = `/v1/chat/completions:${requestModel}`;
91067
+ const requestBody = JSON.stringify(body);
90979
91068
  const cached2 = this.preAuthCache.get(cacheKey22);
90980
91069
  const now2 = Date.now();
90981
- if (cached2 && now2 - cached2.cachedAt < _LLMClient.PRE_AUTH_TTL_MS) {
91070
+ if (cached2 && now2 - cached2.cachedAt < _LLMClient.PRE_AUTH_TTL_MS && cached2.bodyLength === requestBody.length) {
90982
91071
  let signed2;
90983
91072
  try {
90984
91073
  signed2 = await this.signPayment(cached2.paymentHeader);
@@ -91002,8 +91091,10 @@ var init_dist = __esm({
91002
91091
  throw withDisposition(err, "paid-or-in-doubt");
91003
91092
  }
91004
91093
  if (preAuthResp.ok) {
91005
- this.sessionCalls += 1;
91006
- this.sessionTotalUsd += signed2.costUsd;
91094
+ if (!settlementSkipped(preAuthResp)) {
91095
+ this.sessionCalls += 1;
91096
+ this.sessionTotalUsd += signed2.costUsd;
91097
+ }
91007
91098
  return preAuthResp;
91008
91099
  }
91009
91100
  this.preAuthCache.delete(cacheKey22);
@@ -91047,7 +91138,7 @@ var init_dist = __esm({
91047
91138
  }
91048
91139
  }
91049
91140
  if (!paymentHeader) throw new PaymentError("402 response but no payment requirements found");
91050
- this.preAuthCache.set(cacheKey22, { paymentHeader, cachedAt: now2 });
91141
+ this.preAuthCache.set(cacheKey22, { paymentHeader, cachedAt: now2, bodyLength: requestBody.length });
91051
91142
  const { paymentPayload, costUsd } = await this.signPayment(paymentHeader);
91052
91143
  const streamResp = await this.fetchWithTimeout(url3, {
91053
91144
  method: "POST",
@@ -91068,8 +91159,10 @@ var init_dist = __esm({
91068
91159
  }
91069
91160
  throw new APIError(`API error after payment: ${streamResp.status}`, streamResp.status, sanitizeErrorResponse(errorBody));
91070
91161
  }
91071
- this.sessionCalls += 1;
91072
- this.sessionTotalUsd += costUsd;
91162
+ if (!settlementSkipped(streamResp)) {
91163
+ this.sessionCalls += 1;
91164
+ this.sessionTotalUsd += costUsd;
91165
+ }
91073
91166
  return streamResp;
91074
91167
  }
91075
91168
  /**
@@ -91193,10 +91286,7 @@ var init_dist = __esm({
91193
91286
  }
91194
91287
  throw new APIError(`API error after payment: ${retryResp2.status}`, retryResp2.status, sanitizeErrorResponse(errorBody));
91195
91288
  }
91196
- const costUsd2 = parseFloat(details.amount) / 1e6;
91197
- this.sessionCalls += 1;
91198
- this.sessionTotalUsd += costUsd2;
91199
- this.recordCost(url3, costUsd2, { body, network: details.network });
91289
+ this.bookPaidRaw(url3, details, retryResp2, body);
91200
91290
  return retryResp2.json();
91201
91291
  }
91202
91292
  }
@@ -91216,10 +91306,7 @@ var init_dist = __esm({
91216
91306
  sanitizeErrorResponse(errorBody)
91217
91307
  );
91218
91308
  }
91219
- const costUsd = parseFloat(details.amount) / 1e6;
91220
- this.sessionCalls += 1;
91221
- this.sessionTotalUsd += costUsd;
91222
- this.recordCost(url3, costUsd, { body, network: details.network });
91309
+ this.bookPaidRaw(url3, details, retryResponse, body);
91223
91310
  return retryResponse.json();
91224
91311
  }
91225
91312
  /**
@@ -91339,10 +91426,7 @@ var init_dist = __esm({
91339
91426
  }
91340
91427
  throw new APIError(`API error after payment: ${retryResp2.status}`, retryResp2.status, sanitizeErrorResponse(errorBody));
91341
91428
  }
91342
- const costUsd2 = parseFloat(details.amount) / 1e6;
91343
- this.sessionCalls += 1;
91344
- this.sessionTotalUsd += costUsd2;
91345
- this.recordCost(url3, costUsd2, { network: details.network });
91429
+ this.bookPaidRaw(url3, details, retryResp2);
91346
91430
  return retryResp2.json();
91347
91431
  }
91348
91432
  }
@@ -91362,10 +91446,7 @@ var init_dist = __esm({
91362
91446
  sanitizeErrorResponse(errorBody)
91363
91447
  );
91364
91448
  }
91365
- const costUsd = parseFloat(details.amount) / 1e6;
91366
- this.sessionCalls += 1;
91367
- this.sessionTotalUsd += costUsd;
91368
- this.recordCost(url3, costUsd, { network: details.network });
91449
+ this.bookPaidRaw(url3, details, retryResponse);
91369
91450
  return retryResponse.json();
91370
91451
  }
91371
91452
  /**
@@ -92372,8 +92453,10 @@ var init_dist = __esm({
92372
92453
  throw new APIError(`API error after payment: ${retryResponse.status}`, retryResponse.status, sanitizeErrorResponse(errorBody));
92373
92454
  }
92374
92455
  const data = await retryResponse.json();
92375
- this.sessionCalls++;
92376
- this.sessionTotalUsd += 0.1575;
92456
+ if (!settlementSkipped(retryResponse)) {
92457
+ this.sessionCalls++;
92458
+ this.sessionTotalUsd += 0.1575;
92459
+ }
92377
92460
  const txHash = retryResponse.headers.get("x-payment-receipt") || retryResponse.headers.get("X-Payment-Receipt");
92378
92461
  if (txHash) data.txHash = txHash;
92379
92462
  return data;
@@ -92582,9 +92665,11 @@ var init_dist = __esm({
92582
92665
  throw new APIError(`API error after payment: ${retryResponse.status}`, retryResponse.status, sanitizeErrorResponse(errorBody));
92583
92666
  }
92584
92667
  const data = await retryResponse.json();
92585
- this.sessionCalls++;
92586
- const paidUsd = Number(details.amount) / 1e6;
92587
- if (Number.isFinite(paidUsd)) this.sessionTotalUsd += paidUsd;
92668
+ if (!settlementSkipped(retryResponse)) {
92669
+ this.sessionCalls++;
92670
+ const paidUsd = Number(details.amount) / 1e6;
92671
+ if (Number.isFinite(paidUsd)) this.sessionTotalUsd += paidUsd;
92672
+ }
92588
92673
  const txHash = retryResponse.headers.get("x-payment-receipt") || retryResponse.headers.get("X-Payment-Receipt");
92589
92674
  if (txHash) data.txHash = txHash;
92590
92675
  return data;
@@ -92878,8 +92963,10 @@ var init_dist = __esm({
92878
92963
  }
92879
92964
  if (lastStatus === "completed") {
92880
92965
  const data = pollData;
92881
- this.sessionCalls++;
92882
- this.sessionTotalUsd += Number(details.amount) / 1e6;
92966
+ if (!settlementSkipped(pollResp)) {
92967
+ this.sessionCalls++;
92968
+ this.sessionTotalUsd += Number(details.amount) / 1e6;
92969
+ }
92883
92970
  const txHash = pollResp.headers.get("x-payment-receipt") || pollResp.headers.get("X-Payment-Receipt");
92884
92971
  if (txHash) data.txHash = txHash;
92885
92972
  return data;
@@ -93171,8 +93258,10 @@ var init_dist = __esm({
93171
93258
  throw new APIError(`API error after payment: ${retryResponse.status}`, retryResponse.status, sanitizeErrorResponse(errorBody));
93172
93259
  }
93173
93260
  const data = await retryResponse.json();
93174
- this.sessionCalls++;
93175
- this.sessionTotalUsd += CALL_PRICE_USD;
93261
+ if (!settlementSkipped(retryResponse)) {
93262
+ this.sessionCalls++;
93263
+ this.sessionTotalUsd += CALL_PRICE_USD;
93264
+ }
93176
93265
  const txHash = retryResponse.headers.get("x-payment-receipt") || retryResponse.headers.get("X-Payment-Receipt");
93177
93266
  if (txHash) data.txHash = txHash;
93178
93267
  return data;
@@ -93377,9 +93466,10 @@ var init_dist = __esm({
93377
93466
  throw new PaymentError("Payment was rejected. Check your wallet balance.");
93378
93467
  }
93379
93468
  const data = await this.unwrap(retry, true);
93380
- const costUsd = Number.parseFloat(details.amount) / 1e6;
93381
- this.sessionCalls += 1;
93382
- this.sessionTotalUsd += costUsd;
93469
+ if (!settlementSkipped(retry)) {
93470
+ this.sessionCalls += 1;
93471
+ this.sessionTotalUsd += Number.parseFloat(details.amount) / 1e6;
93472
+ }
93383
93473
  const txHash = retry.headers.get("x-payment-receipt") || retry.headers.get("X-Payment-Receipt");
93384
93474
  if (txHash && data && typeof data === "object" && !("txHash" in data)) {
93385
93475
  data.txHash = txHash;
@@ -93541,9 +93631,10 @@ var init_dist = __esm({
93541
93631
  throw new PaymentError("Payment was rejected. Check your wallet balance.");
93542
93632
  }
93543
93633
  const data = await this.unwrap(retry, true);
93544
- const costUsd = Number.parseFloat(details.amount) / 1e6;
93545
- this.sessionCalls += 1;
93546
- this.sessionTotalUsd += costUsd;
93634
+ if (!settlementSkipped(retry)) {
93635
+ this.sessionCalls += 1;
93636
+ this.sessionTotalUsd += Number.parseFloat(details.amount) / 1e6;
93637
+ }
93547
93638
  if (data && typeof data === "object" && !("txHash" in data)) {
93548
93639
  const settlement = data.settlement;
93549
93640
  if (settlement?.tx_hash) {
@@ -94327,9 +94418,11 @@ var init_dist = __esm({
94327
94418
  }
94328
94419
  throw new APIError(`API error after payment: ${retryResponse.status}`, retryResponse.status, sanitizeErrorResponse(errorBody));
94329
94420
  }
94330
- this.sessionCalls++;
94331
- const paidUsd = Number(details.amount) / 1e6;
94332
- if (Number.isFinite(paidUsd)) this.sessionTotalUsd += paidUsd;
94421
+ if (!settlementSkipped(retryResponse)) {
94422
+ this.sessionCalls++;
94423
+ const paidUsd = Number(details.amount) / 1e6;
94424
+ if (Number.isFinite(paidUsd)) this.sessionTotalUsd += paidUsd;
94425
+ }
94333
94426
  return { data: await retryResponse.json(), headers: retryResponse.headers };
94334
94427
  }
94335
94428
  async fetchWithTimeout(url3, options) {
@@ -94444,7 +94537,7 @@ var init_dist = __esm({
94444
94537
  if (resp402.status !== 402) {
94445
94538
  await this.throwApiError(resp402, `poll submit failed (${submitUrl})`);
94446
94539
  }
94447
- const paymentPayload = await this.signFrom402(resp402, submitUrl, {
94540
+ const { paymentPayload, costUsd } = await this.signFrom402(resp402, submitUrl, {
94448
94541
  description: "BlockRun async job",
94449
94542
  maxTimeoutSeconds: MAX_SIGNED_AUTH_SECONDS
94450
94543
  });
@@ -94463,7 +94556,7 @@ var init_dist = __esm({
94463
94556
  await this.throwApiError(submitResp, `poll submit failed (${submitUrl})`);
94464
94557
  }
94465
94558
  if (submitResp.status === 200) {
94466
- this.recordSpending();
94559
+ this.recordSpending(submitResp, costUsd);
94467
94560
  return submitResp.json();
94468
94561
  }
94469
94562
  const submitData = await submitResp.json();
@@ -94500,7 +94593,7 @@ var init_dist = __esm({
94500
94593
  );
94501
94594
  }
94502
94595
  if (pollResp.status === 200 && lastStatus === "completed") {
94503
- this.recordSpending();
94596
+ this.recordSpending(pollResp, costUsd);
94504
94597
  return pollData;
94505
94598
  }
94506
94599
  if (pollResp.status !== 200 && pollResp.status !== 202 && pollResp.status !== 504) {
@@ -94541,7 +94634,7 @@ var init_dist = __esm({
94541
94634
  if (resp402.status === 200) {
94542
94635
  streamResp = resp402;
94543
94636
  } else if (resp402.status === 402) {
94544
- const paymentPayload = await this.signFrom402(resp402, url3, {
94637
+ const { paymentPayload, costUsd } = await this.signFrom402(resp402, url3, {
94545
94638
  description: "BlockRun stream"
94546
94639
  });
94547
94640
  streamResp = await this.fetchWithTimeout(url3, {
@@ -94560,7 +94653,7 @@ var init_dist = __esm({
94560
94653
  if (!streamResp.ok) {
94561
94654
  await this.throwApiError(streamResp, `stream failed after payment (${url3})`);
94562
94655
  }
94563
- this.recordSpending();
94656
+ this.recordSpending(streamResp, costUsd);
94564
94657
  } else {
94565
94658
  await this.throwApiError(resp402, `stream failed (${url3})`);
94566
94659
  return;
@@ -94616,7 +94709,7 @@ var init_dist = __esm({
94616
94709
  return response.json();
94617
94710
  }
94618
94711
  async handlePaymentAndRetry(url3, method, body, response) {
94619
- const paymentPayload = await this.signFrom402(response, url3, {
94712
+ const { paymentPayload, costUsd } = await this.signFrom402(response, url3, {
94620
94713
  description: "BlockRun"
94621
94714
  });
94622
94715
  const retryInit = {
@@ -94639,13 +94732,14 @@ var init_dist = __esm({
94639
94732
  if (!retry.ok) {
94640
94733
  await this.throwApiError(retry, `${method} ${url3} failed after payment`);
94641
94734
  }
94642
- this.recordSpending();
94735
+ this.recordSpending(retry, costUsd);
94643
94736
  return retry.json();
94644
94737
  }
94645
94738
  /**
94646
94739
  * Read a 402 response's payment requirements (header or body), then sign and
94647
- * return the base64 PAYMENT-SIGNATURE payload. Also records the cost-to-be
94648
- * onto the response context (settled on `recordSpending`).
94740
+ * return the base64 PAYMENT-SIGNATURE payload with what it pays, in USD.
94741
+ * The cost stays with the call that signed it (booked by `recordSpending`):
94742
+ * concurrent calls on one client never share it.
94649
94743
  */
94650
94744
  async signFrom402(response, url3, opts) {
94651
94745
  let paymentHeader = response.headers.get("payment-required");
@@ -94663,8 +94757,8 @@ var init_dist = __esm({
94663
94757
  }
94664
94758
  const paymentRequired = parsePaymentRequired(paymentHeader);
94665
94759
  const details = extractPaymentDetails(paymentRequired);
94666
- this.pendingCostUsd = parseFloat(details.amount) / 1e6;
94667
- return createPaymentPayload(
94760
+ const costUsd = parseFloat(details.amount) / 1e6;
94761
+ const paymentPayload = await createPaymentPayload(
94668
94762
  this.privateKey,
94669
94763
  this.account.address,
94670
94764
  details.recipient,
@@ -94681,14 +94775,20 @@ var init_dist = __esm({
94681
94775
  asset: details.asset
94682
94776
  }
94683
94777
  );
94778
+ return { paymentPayload, costUsd };
94684
94779
  }
94685
- /** Accumulates the most-recent pending cost; settled by recordSpending. */
94686
- pendingCostUsd = 0;
94687
- recordSpending() {
94688
- if (this.pendingCostUsd > 0) {
94780
+ /**
94781
+ * Book `costUsd`, what the call that `response` answered signed. A response
94782
+ * whose settlement the gateway skipped ({@link settlementSkipped}:
94783
+ * `X-Settlement-Skipped: <reason>` or `X-Payment-Waived`) moved nothing, so
94784
+ * nothing is booked. `X-Payment-Settled: false` alone is still booked: the
94785
+ * payment is owed.
94786
+ */
94787
+ recordSpending(response, costUsd) {
94788
+ if (settlementSkipped(response)) return;
94789
+ if (costUsd > 0) {
94689
94790
  this.sessionCalls += 1;
94690
- this.sessionTotalUsd += this.pendingCostUsd;
94691
- this.pendingCostUsd = 0;
94791
+ this.sessionTotalUsd += costUsd;
94692
94792
  }
94693
94793
  }
94694
94794
  async throwApiError(resp, prefix) {
@@ -94740,6 +94840,8 @@ var init_dist = __esm({
94740
94840
  BLOCKRUN_SOL_OPERATOR = "5YKPQUFjw5WQqhSUkEGKNNfYYVqnRRNbpYyL71qQ1vm3";
94741
94841
  DEFAULT_BATCH_RATE_LIMIT = { maxAttempts: 3, maxWaitMs: 6e4 };
94742
94842
  DEFAULT_BATCH_IN_DOUBT = { maxWaitMs: 3e5 };
94843
+ DEFAULT_BATCH_LOCK_WAIT_MS = 6e4;
94844
+ LOCK_POLL_MS = 500;
94743
94845
  BatchPaymentUnresolvedError = class extends PaymentError {
94744
94846
  /** The {@link SolanaBatchEvent.reason} of the `unresolved` event reported with it. */
94745
94847
  reason;
@@ -94785,6 +94887,22 @@ var init_dist = __esm({
94785
94887
  this.channelIds = init2.channelIds ?? [];
94786
94888
  }
94787
94889
  };
94890
+ BatchChannelLockedError = class extends BlockrunError {
94891
+ /** The paying wallet's address. */
94892
+ wallet;
94893
+ /** The live owner's pid, when the SDK knows it. */
94894
+ ownerPid;
94895
+ /** How long this call waited for the lock, in ms (0 unless `onLocked` is `"wait"`). */
94896
+ waitedMs;
94897
+ constructor(init2) {
94898
+ super(`batch-settlement unavailable for wallet ${init2.wallet}: ${init2.detail}`);
94899
+ this.name = "BatchChannelLockedError";
94900
+ this.wallet = init2.wallet;
94901
+ if (init2.ownerPid !== void 0) this.ownerPid = init2.ownerPid;
94902
+ this.waitedMs = init2.waitedMs;
94903
+ withDisposition(this, "unpaid");
94904
+ }
94905
+ };
94788
94906
  INSTALL_HINT2 = "npm install @x402/core@~2.28.0 @x402/svm@~2.28.0 @solana/kit";
94789
94907
  FileChannelStorage = class {
94790
94908
  constructor(file2) {
@@ -95106,6 +95224,9 @@ var init_dist = __esm({
95106
95224
  }
95107
95225
  reason;
95108
95226
  };
95227
+ DEPOSIT_BLOCKHASH_TTL_MS = 1e4;
95228
+ MAX_DEPOSIT_BLOCKHASH_ENDPOINTS = 8;
95229
+ depositBlockhashes = /* @__PURE__ */ new Map();
95109
95230
  PAYMENT_IDENTIFIER = "payment-identifier";
95110
95231
  IN_DOUBT_MIN_WAIT_MS = 1e3;
95111
95232
  IN_DOUBT_MAX_WAIT_MS = 3e4;
@@ -95189,12 +95310,22 @@ var init_dist = __esm({
95189
95310
  if (!Number.isFinite(this.inDoubtMaxWaitMs) || this.inDoubtMaxWaitMs < 0) {
95190
95311
  throw new Error("batch.inDoubt.maxWaitMs must be a finite number of ms >= 0");
95191
95312
  }
95313
+ this.onLocked = init2.options.onLocked ?? "exact";
95314
+ if (this.onLocked !== "exact" && this.onLocked !== "wait" && this.onLocked !== "throw") {
95315
+ throw new Error('batch.onLocked must be "exact", "wait" or "throw"');
95316
+ }
95317
+ this.lockWaitMs = init2.options.lockWaitMs ?? DEFAULT_BATCH_LOCK_WAIT_MS;
95318
+ if (!Number.isFinite(this.lockWaitMs) || this.lockWaitMs < 0) {
95319
+ throw new Error("batch.lockWaitMs must be a finite number of ms >= 0");
95320
+ }
95192
95321
  }
95193
95322
  init;
95194
95323
  state;
95195
95324
  maxAttempts;
95196
95325
  maxWaitMs;
95197
95326
  inDoubtMaxWaitMs;
95327
+ onLocked;
95328
+ lockWaitMs;
95198
95329
  counters = {
95199
95330
  fallbacks: 0,
95200
95331
  fallbacksByReason: {},
@@ -95243,6 +95374,7 @@ var init_dist = __esm({
95243
95374
  if (owner !== void 0) {
95244
95375
  return {
95245
95376
  reason: "channel_store_locked",
95377
+ ownerPid: owner,
95246
95378
  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}`
95247
95379
  };
95248
95380
  }
@@ -95588,12 +95720,23 @@ var init_dist = __esm({
95588
95720
  const unavailable = batchUnavailable(paymentRequired);
95589
95721
  if (unavailable) return this.fallback(unavailable);
95590
95722
  let wallet;
95723
+ let waitedMs = 0;
95591
95724
  try {
95592
95725
  wallet = await this.wallet();
95726
+ if ("reason" in wallet && wallet.reason === "channel_store_locked" && this.onLocked === "wait") {
95727
+ const started = Date.now();
95728
+ wallet = await this.waitForLock(wallet);
95729
+ waitedMs = Date.now() - started;
95730
+ }
95593
95731
  } catch (err) {
95594
95732
  return this.fallback(creationFailure(err));
95595
95733
  }
95596
- if ("reason" in wallet) return this.fallback({ reason: wallet.reason, detail: wallet.detail });
95734
+ if ("reason" in wallet) {
95735
+ if (wallet.reason === "channel_store_locked" && this.onLocked !== "exact") {
95736
+ return this.lockedOut(wallet.detail, wallet.ownerPid, waitedMs);
95737
+ }
95738
+ return this.fallback({ reason: wallet.reason, detail: wallet.detail });
95739
+ }
95597
95740
  if (closesAtStart !== void 0 && wallet.closes !== closesAtStart) {
95598
95741
  return this.fallback({
95599
95742
  reason: "closed_during_call",
@@ -95610,6 +95753,40 @@ var init_dist = __esm({
95610
95753
  wallet.active -= 1;
95611
95754
  }
95612
95755
  }
95756
+ /**
95757
+ * `onLocked: "wait"`: try the wallet's channel store again every
95758
+ * {@link LOCK_POLL_MS} until its owner lets go of it or `lockWaitMs` runs
95759
+ * out. Reported once as a `backoff` event (`channel_store_locked`).
95760
+ */
95761
+ async waitForLock(refusal) {
95762
+ const deadline = Date.now() + this.lockWaitMs;
95763
+ let current = refusal;
95764
+ if (this.lockWaitMs > 0) {
95765
+ await this.report({
95766
+ type: "backoff",
95767
+ reason: "channel_store_locked",
95768
+ retryAfterMs: this.lockWaitMs,
95769
+ detail: refusal.detail
95770
+ });
95771
+ }
95772
+ while ("reason" in current && current.reason === "channel_store_locked") {
95773
+ const left = deadline - Date.now();
95774
+ if (left <= 0) break;
95775
+ await sleep2(Math.min(LOCK_POLL_MS, left));
95776
+ current = await this.wallet();
95777
+ }
95778
+ return current;
95779
+ }
95780
+ /** `onLocked` other than `"exact"`: the call's `"unpaid"` error, nothing signed. */
95781
+ async lockedOut(detail, ownerPid, waitedMs) {
95782
+ const error62 = new BatchChannelLockedError({
95783
+ wallet: await this.init.address(),
95784
+ detail,
95785
+ waitedMs,
95786
+ ...ownerPid !== void 0 ? { ownerPid } : {}
95787
+ });
95788
+ return { kind: "failed", error: error62 };
95789
+ }
95613
95790
  /**
95614
95791
  * The close fence for a call about to send its first request: how many
95615
95792
  * closes this wallet has completed so far, to hand to {@link pay}.
@@ -95700,11 +95877,9 @@ var init_dist = __esm({
95700
95877
  }
95701
95878
  if (wallet.busy) return fallback2({ reason: "channel_busy", attempt: budget.attempt });
95702
95879
  if (wallet.file && !holdsChannelFile(wallet.file)) {
95703
- return fallback2({
95704
- reason: "channel_store_locked",
95705
- attempt: budget.attempt,
95706
- detail: `this process no longer holds the lock on ${wallet.file}; another owner may be paying into its channels`
95707
- });
95880
+ const detail = `this process no longer holds the lock on ${wallet.file}; another owner may be paying into its channels`;
95881
+ if (this.onLocked !== "exact") return this.lockedOut(detail, void 0, 0);
95882
+ return fallback2({ reason: "channel_store_locked", attempt: budget.attempt, detail });
95708
95883
  }
95709
95884
  wallet.busy = true;
95710
95885
  holding = true;
@@ -95749,6 +95924,8 @@ var init_dist = __esm({
95749
95924
  wallet.refusedFor = outcome.errorReason;
95750
95925
  }
95751
95926
  }
95927
+ } else if (built.key && outcome.reason === "payment_required" && outcome.refusedForMs === void 0) {
95928
+ await this.recheckRefusedChannel(wallet, built.key, built.reclaimAnchor);
95752
95929
  }
95753
95930
  sent = void 0;
95754
95931
  release();
@@ -96016,6 +96193,13 @@ var init_dist = __esm({
96016
96193
  }
96017
96194
  /** Build a new batch payment for a 402: the payload, its headers and its kind. */
96018
96195
  async buildPayment(wallet, paymentRequired) {
96196
+ const acceptKey = channelKeyOf(trustedBatchAccept(paymentRequired, this.init.options.operators));
96197
+ let reclaimAnchor;
96198
+ try {
96199
+ const stored = acceptKey ? await wallet.book.base.get(acceptKey) : void 0;
96200
+ reclaimAnchor = stored ? savedReclaimAnchor(stored) : void 0;
96201
+ } catch {
96202
+ }
96019
96203
  const { http: http5, payload } = await this.createPayload(wallet, paymentRequired);
96020
96204
  const scope = payScope.getStore();
96021
96205
  if (scope?.afterError) {
@@ -96037,7 +96221,16 @@ var init_dist = __esm({
96037
96221
  const record2 = known?.record;
96038
96222
  kind = record2 && (record2.pending === void 0 || record2.hasConfirmedState) ? "top-up" : "open";
96039
96223
  }
96040
- return { http: http5, payload, headers, kind, key: known?.key, sentAt: Date.now(), sends: 0 };
96224
+ return {
96225
+ http: http5,
96226
+ payload,
96227
+ headers,
96228
+ kind,
96229
+ key: known?.key,
96230
+ ...reclaimAnchor !== void 0 && known?.key === acceptKey ? { reclaimAnchor } : {},
96231
+ sentAt: Date.now(),
96232
+ sends: 0
96233
+ };
96041
96234
  }
96042
96235
  /**
96043
96236
  * Write a deposit's intent to the wallet's journal before it is sent
@@ -96263,7 +96456,8 @@ var init_dist = __esm({
96263
96456
  const http5 = (await this.build(wallet)).http;
96264
96457
  try {
96265
96458
  await this.prepareTopUp(wallet, paymentRequired);
96266
- return { http: http5, payload: await http5.createPaymentPayload(withPaymentIdentifier(withoutClientSignedBatch(paymentRequired))) };
96459
+ const required2 = await this.withDepositBlockhash(wallet, withoutClientSignedBatch(paymentRequired));
96460
+ return { http: http5, payload: await http5.createPaymentPayload(withPaymentIdentifier(required2)) };
96267
96461
  } catch (err) {
96268
96462
  if (pass > 0 || !isResyncRequired(err) || wallet.resyncs.size === 0) throw err;
96269
96463
  } finally {
@@ -96271,6 +96465,112 @@ var init_dist = __esm({
96271
96465
  }
96272
96466
  }
96273
96467
  }
96468
+ /**
96469
+ * The 402 to build this payment from: with a finalized blockhash
96470
+ * ({@link withDepositBlockhash}) when the payment will likely carry a
96471
+ * deposit (no usable record for the trusted accept's channel, so an open,
96472
+ * or a top-up {@link prepareTopUp} just sized). An authorization signs no
96473
+ * transaction and costs no RPC read. Best effort: a failed read leaves the
96474
+ * 402 as it is, and `@x402/svm` fetches its own blockhash.
96475
+ */
96476
+ async withDepositBlockhash(wallet, paymentRequired) {
96477
+ const accept = trustedBatchAccept(paymentRequired, this.init.options.operators);
96478
+ const key3 = accept ? channelKeyOf(accept) : void 0;
96479
+ if (!accept || accept.extra?.recentBlockhash) return paymentRequired;
96480
+ let deposit = wallet.topUp !== void 0;
96481
+ if (!deposit) {
96482
+ try {
96483
+ const record2 = key3 ? await wallet.book.base.get(key3) : void 0;
96484
+ deposit = !record2 || typeof record2.channelId !== "string" || record2.pending !== void 0;
96485
+ } catch {
96486
+ deposit = true;
96487
+ }
96488
+ }
96489
+ if (!deposit) return paymentRequired;
96490
+ try {
96491
+ return withDepositBlockhash(paymentRequired, await finalizedBlockhash(this.init.rpcUrl, this.init.rpcHeaders));
96492
+ } catch {
96493
+ return paymentRequired;
96494
+ }
96495
+ }
96496
+ /**
96497
+ * Queue a re-read of a stored channel whose account is gone at finalized
96498
+ * and at confirmed commitment (closed, its account reclaimed), anchored at
96499
+ * the SDK's own `getBlockHeight` at confirmed. The anchor is saved in the
96500
+ * record (`reclaimAnchorHeight`), so a short-lived process finishes the
96501
+ * wait instead of starting it over; a failed read leaves resync to take it,
96502
+ * and a failed save only costs that. resync pays exact until finality is
96503
+ * LANDING_MARGIN_BLOCKS past the anchor, then drops the record if the
96504
+ * finalized chain still has no account (a lagging read finds the channel
96505
+ * and rewrites the record, without the anchor).
96506
+ */
96507
+ async queueReclaimed(wallet, key3, record2, channelId, savedAnchor) {
96508
+ let anchorHeight = savedReclaimAnchor(record2) ?? savedAnchor;
96509
+ if (anchorHeight === void 0) {
96510
+ try {
96511
+ anchorHeight = rpcInteger(
96512
+ await rpcRequest(this.init.rpcUrl, "getBlockHeight", [{ commitment: "confirmed" }], this.init.rpcHeaders),
96513
+ "getBlockHeight"
96514
+ );
96515
+ } catch {
96516
+ }
96517
+ }
96518
+ if (anchorHeight !== void 0 && savedReclaimAnchor(record2) !== anchorHeight) {
96519
+ try {
96520
+ await wallet.book.set(key3, { ...record2, reclaimAnchorHeight: anchorHeight });
96521
+ } catch {
96522
+ }
96523
+ }
96524
+ addResyncTarget(wallet, {
96525
+ key: key3,
96526
+ channelId,
96527
+ channelConfig: record2.channelConfig,
96528
+ cumulative: parseAtomic(record2.chargedCumulativeAmount),
96529
+ knownDeposit: parseAtomic(record2.deposit),
96530
+ ...anchorHeight !== void 0 ? { anchorHeight } : {},
96531
+ reason: "channel_unusable"
96532
+ });
96533
+ }
96534
+ /**
96535
+ * After the gateway refused an authorization with a plain 402 (no receipt,
96536
+ * not an admission refusal), check the channel it paid into. That is how
96537
+ * the gateway answers an authorization into a channel the facilitator
96538
+ * closed (its verify rejects it), and a channel with deposit to spare is
96539
+ * otherwise never read again: every call would sign another authorization
96540
+ * into it and pay exact. A channel the finalized chain shows closing,
96541
+ * closed or not this wallet's is re-read through resync (record dropped,
96542
+ * or kept and paid exact); one gone at every commitment is queued as
96543
+ * {@link queueReclaimed}; an open one of this wallet's, or one only at
96544
+ * confirmed (not finalized yet), is left as it is. A queued re-read is run
96545
+ * at once. Best effort: a failed read changes nothing, and the next
96546
+ * refusal checks again.
96547
+ */
96548
+ async recheckRefusedChannel(wallet, key3, savedAnchor) {
96549
+ try {
96550
+ const record2 = await wallet.book.get(key3);
96551
+ if (!record2 || record2.pending || typeof record2.channelId !== "string" || wallet.resyncs.has(key3)) return;
96552
+ const channelId = record2.channelId;
96553
+ const channel = await readChannelAccount(this.init.rpcUrl, channelId, this.init.rpcHeaders);
96554
+ if (channel !== void 0) {
96555
+ if (channel.open && channel.payer === await this.init.address() && channel.authorizedSigner === record2.channelConfig.payerAuthorizer && channel.mint === record2.channelConfig.token) {
96556
+ return;
96557
+ }
96558
+ addResyncTarget(wallet, {
96559
+ key: key3,
96560
+ channelId,
96561
+ channelConfig: record2.channelConfig,
96562
+ cumulative: parseAtomic(record2.chargedCumulativeAmount),
96563
+ knownDeposit: parseAtomic(record2.deposit),
96564
+ reason: "channel_unusable"
96565
+ });
96566
+ } else {
96567
+ if (await readChannelAccount(this.init.rpcUrl, channelId, this.init.rpcHeaders, { commitment: "confirmed" }) !== void 0) return;
96568
+ await this.queueReclaimed(wallet, key3, record2, channelId, savedAnchor);
96569
+ }
96570
+ await this.resync(wallet);
96571
+ } catch {
96572
+ }
96573
+ }
96274
96574
  /**
96275
96575
  * When this payment will top up the wallet's channel, read how much of its
96276
96576
  * deposit is already settled on-chain (at `finalized` commitment, so never
@@ -96288,7 +96588,11 @@ var init_dist = __esm({
96288
96588
  * pays exact (`channel_unreadable`), record kept. If
96289
96589
  * the finalized channel is closing or closed, or is not this wallet's for
96290
96590
  * the record's operator and mint, no top-up is sized from the record: it
96291
- * is re-read at once (`channel_unusable`), see {@link createPayload}.
96591
+ * is re-read at once (`channel_unusable`), see {@link createPayload}. So is
96592
+ * a channel with no account at finalized or at confirmed commitment (closed
96593
+ * and reclaimed); resync drops its record only once finality is past its
96594
+ * own anchor. One that shows only at confirmed is not finalized yet: the
96595
+ * lifetime cap applies.
96292
96596
  */
96293
96597
  async prepareTopUp(wallet, paymentRequired) {
96294
96598
  wallet.topUp = void 0;
@@ -96300,8 +96604,12 @@ var init_dist = __esm({
96300
96604
  const deposit = parseAtomic(record2.deposit);
96301
96605
  if (parseAtomic(record2.chargedCumulativeAmount) + parseAtomic(accept.amount) <= deposit) return;
96302
96606
  let channel;
96607
+ let unfinalized = false;
96303
96608
  try {
96304
96609
  channel = await readChannelAccount(this.init.rpcUrl, record2.channelId, this.init.rpcHeaders);
96610
+ if (channel === void 0) {
96611
+ unfinalized = await readChannelAccount(this.init.rpcUrl, record2.channelId, this.init.rpcHeaders, { commitment: "confirmed" }) !== void 0;
96612
+ }
96305
96613
  } catch (err) {
96306
96614
  if (err instanceof ChannelLayoutError) {
96307
96615
  throw new ResyncError("channel_unreadable", `channel ${record2.channelId}: ${err.message}; no top-up is sized from it`);
@@ -96314,7 +96622,11 @@ var init_dist = __esm({
96314
96622
  `could not read channel ${record2.channelId} before topping it up: ${err instanceof Error ? err.message : String(err)}`
96315
96623
  );
96316
96624
  }
96317
- if (channel === void 0) return;
96625
+ if (channel === void 0 && unfinalized) return;
96626
+ if (channel === void 0) {
96627
+ await this.queueReclaimed(wallet, key3, record2, record2.channelId);
96628
+ throw new ChannelResyncRequiredError(record2.channelId);
96629
+ }
96318
96630
  if (!channel.open || channel.payer !== await this.init.address() || channel.authorizedSigner !== record2.channelConfig.payerAuthorizer || channel.mint !== record2.channelConfig.token) {
96319
96631
  addResyncTarget(wallet, {
96320
96632
  key: key3,
@@ -96485,7 +96797,6 @@ var init_dist = __esm({
96485
96797
  };
96486
96798
  SOLANA_API_URL = "https://sol.blockrun.ai/api";
96487
96799
  DEFAULT_MAX_TOKENS22 = 1024;
96488
- DEFAULT_TIMEOUT14 = 6e4;
96489
96800
  STALE_BLOCKHASH_RETRY_BACKOFFS_MS = [500, 2e3];
96490
96801
  MAX_PAYMENT_FAILURE_BYTES = 64 * 1024;
96491
96802
  DEFAULT_VIDEO_MODEL = "xai/grok-imagine-video";
@@ -96541,7 +96852,7 @@ var init_dist = __esm({
96541
96852
  const rpc = resolveRpcConfig(options.rpcUrl, options.rpcHeaders);
96542
96853
  this.rpcUrl = rpc.url;
96543
96854
  this.rpcHeaders = rpc.headers;
96544
- this.timeout = options.timeout || DEFAULT_TIMEOUT14;
96855
+ this.timeout = options.timeout || DEFAULT_TIMEOUT;
96545
96856
  if (options.batch && !this.apiAuth) {
96546
96857
  this.batchPayer = new SolanaBatchPayer({
96547
96858
  options: options.batch,
@@ -96835,7 +97146,7 @@ var init_dist = __esm({
96835
97146
  body: requestBody
96836
97147
  });
96837
97148
  await this.assertPaid(paid);
96838
- this.recordSettlement(costUsd);
97149
+ this.recordSettlement(costUsd, paid);
96839
97150
  return paid;
96840
97151
  } catch (error62) {
96841
97152
  if (!(error62 instanceof SafeStaleBlockhashError) || staleRetries >= STALE_BLOCKHASH_RETRY_BACKOFFS_MS.length) throw error62;
@@ -97222,7 +97533,7 @@ var init_dist = __esm({
97222
97533
  closesAtStart
97223
97534
  );
97224
97535
  if (batch.kind === "paid") {
97225
- this.recordSettlement(batch.chargedUsd);
97536
+ this.recordSettlement(batch.chargedUsd, batch.response);
97226
97537
  const paid = await this.readPaidJson(batch.response);
97227
97538
  return withCost(paid, batch.response, batch.chargedUsd, "batch");
97228
97539
  }
@@ -97339,7 +97650,7 @@ var init_dist = __esm({
97339
97650
  };
97340
97651
  const deliver = (data, response) => {
97341
97652
  if (kind === "video") {
97342
- if (videoCostUsd !== void 0) this.recordSettlement(videoCostUsd);
97653
+ if (videoCostUsd !== void 0) this.recordSettlement(videoCostUsd, response);
97343
97654
  const txHash = response.headers.get("x-payment-receipt");
97344
97655
  if (txHash) data.txHash = txHash;
97345
97656
  }
@@ -97586,7 +97897,7 @@ var init_dist = __esm({
97586
97897
  throw withDisposition(error62, "paid-or-in-doubt");
97587
97898
  }
97588
97899
  await this.assertPaid(retryResponse);
97589
- if (!settlementSkipped(retryResponse)) this.recordSettlement(costUsd);
97900
+ this.recordSettlement(costUsd, retryResponse);
97590
97901
  const paid = await this.readPaidJson(retryResponse);
97591
97902
  return withCost(paid, retryResponse, costUsd, "exact");
97592
97903
  }
@@ -97646,11 +97957,11 @@ var init_dist = __esm({
97646
97957
  await this.assertPaid(retryResponse);
97647
97958
  if (retryResponse.status === 202) {
97648
97959
  const kind = pollKindFor(url3);
97649
- if (kind !== "video") this.recordSettlement(costUsd);
97960
+ if (kind !== "video") this.recordSettlement(costUsd, retryResponse);
97650
97961
  const submitted = await retryResponse.json();
97651
97962
  return this.followSolanaJob(submitted, media.pollBudgetMs ?? this.timeout, kind);
97652
97963
  }
97653
- this.recordSettlement(costUsd);
97964
+ this.recordSettlement(costUsd, retryResponse);
97654
97965
  return retryResponse.json();
97655
97966
  }
97656
97967
  async getWithPaymentRaw(endpoint, params) {
@@ -97694,7 +98005,7 @@ var init_dist = __esm({
97694
98005
  }
97695
98006
  });
97696
98007
  await this.assertPaid(retryResponse);
97697
- this.recordSettlement(costUsd);
98008
+ this.recordSettlement(costUsd, retryResponse);
97698
98009
  return retryResponse.json();
97699
98010
  }
97700
98011
  /**
@@ -97732,8 +98043,17 @@ var init_dist = __esm({
97732
98043
  );
97733
98044
  }
97734
98045
  }
97735
- /** Count one settled x402 payment against the session total. */
97736
- recordSettlement(costUsd) {
98046
+ /**
98047
+ * Count one settled x402 payment against the session total.
98048
+ *
98049
+ * Takes the paid response so no booking site can forget the check: a
98050
+ * response whose settlement the gateway skipped ({@link settlementSkipped}:
98051
+ * `X-Settlement-Skipped: free-fallback | empty-result | unexecuted | …`, or
98052
+ * `X-Payment-Waived`) moved nothing on chain and books nothing.
98053
+ * `X-Payment-Settled: false` alone is still booked: the payment is owed.
98054
+ */
98055
+ recordSettlement(costUsd, response) {
98056
+ if (settlementSkipped(response)) return;
97737
98057
  this.sessionCalls += 1;
97738
98058
  this.sessionTotalUsd += costUsd;
97739
98059
  }