@blockrun/llm 4.3.1 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  ### Cut your LLM bill by <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->%. One line of TypeScript.
6
6
 
7
- The smart-routing SDK for <!-- br:models.chatVisible -->93<!-- /br:models.chatVisible --> models — every request goes to the cheapest model that can handle it,
7
+ The smart-routing SDK for <!-- br:models.chatVisible -->97<!-- /br:models.chatVisible --> models — every request goes to the cheapest model that can handle it,
8
8
  paid with an API key or per-request USDC on Solana, Base or Arc. No vendor lock-in.
9
9
 
10
10
  [![npm](https://img.shields.io/npm/v/@blockrun/llm.svg?style=flat-square)](https://www.npmjs.com/package/@blockrun/llm)
@@ -56,7 +56,7 @@ console.log(r.response); // the proof
56
56
  | | OpenAI SDK | OpenRouter | LiteLLM | **@blockrun/llm** |
57
57
  | ------------------ | -------------- | ----------------- | ---------------- | ----------------------------------------------------------------------- |
58
58
  | **Cost routing** | ✗ one vendor | Manual selection | Manual selection | **Automatic — <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->% cheaper** |
59
- | **Models** | GPT only | 200+ | 100+ (BYO keys) | **<!-- br:models.chatVisible -->93<!-- /br:models.chatVisible -->, one credential** |
59
+ | **Models** | GPT only | 200+ | 100+ (BYO keys) | **<!-- br:models.chatVisible -->97<!-- /br:models.chatVisible -->, one credential** |
60
60
  | **Free tier** | ✗ | Rate-limited | ✗ | **<!-- br:models.free -->9<!-- /br:models.free --> models, no signup** |
61
61
  | **Auth** | API key | Account + API key | Your API keys | **API key *or* wallet signature** |
62
62
  | **Payment** | Card + invoice | Credit card | BYO keys | **Account credit or USDC per-request** |
@@ -436,7 +436,7 @@ picked:
436
436
  | `candidateScores` | Per-candidate score breakdown (`quality` / `cost` / `speed` / `reliability`), ordered with `candidates` |
437
437
  | `fallbacks` | The chain `chat()` walks on transient errors before payment (timeout / network / 429 / 5xx) — `candidates` minus the primary, with ClawRouter's proxy-namespace `free/*` ids mapped to their `nvidia/*` gateway ids (SDK-computed) |
438
438
  | `savings` | 0–1 fraction saved vs the baseline model (`anthropic/claude-opus-4.7`, priced like Opus 5) |
439
- | `costEstimate` / `baselineCost` | Estimated cost of the pick vs that baseline, in USD |
439
+ | `costEstimate` / `baselineCost` | Estimated cost of the pick vs that baseline, in USD. `costEstimate` is the catalog's per-token list cost times `1 + platform_fee_percent / 100` (the fee each paid chat row of `/v1/models` publishes; 0 when the gateway omits it), a flat price as-is, $0 for free models, floored at the per-request minimum. The 402 quote is the real charge |
440
440
  | `confidence` | Sigmoid-calibrated classifier confidence, 0–1 |
441
441
  | `routerVersion` | `'v3-portfolio'` or `'v2-rules'` |
442
442
  | `profile` | Tier set the decision used: `'auto'`, `'eco'`, `'premium'`, or `'agentic'` (the router's own set for agentic requests; not a `routingProfile` you can pass) |
@@ -1912,7 +1912,7 @@ to pick up security fixes.
1912
1912
  ## Frequently Asked Questions
1913
1913
 
1914
1914
  ### What is @blockrun/llm?
1915
- A TypeScript SDK that cuts LLM costs by <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->% on a realistic workload with built-in smart routing: every request goes to the cheapest of <!-- br:models.chatVisible -->93<!-- /br:models.chatVisible --> models (OpenAI, Anthropic, Google, xAI, DeepSeek, Moonshot, and more) that can handle it, paid with an account API key or per-request USDC via x402 on Solana, Base or Arc.
1915
+ A TypeScript SDK that cuts LLM costs by <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->% on a realistic workload with built-in smart routing: every request goes to the cheapest of <!-- br:models.chatVisible -->97<!-- /br:models.chatVisible --> models (OpenAI, Anthropic, Google, xAI, DeepSeek, Moonshot, and more) that can handle it, paid with an account API key or per-request USDC via x402 on Solana, Base or Arc.
1916
1916
 
1917
1917
  ### What is smart routing?
1918
1918
  Router Core V3, bundled into the SDK: the same deterministic engine that powers ClawRouter. It analyzes each request across <!-- br:clawrouter.dimensions -->15<!-- /br:clawrouter.dimensions --> dimensions locally, in under 1ms, and picks the cheapest capable model. Use `smartChat()`, `smartChatCompletion()`, or the `blockrun/auto` model alias. See [Smart Routing](#smart-routing-router-core-v3).
package/dist/index.cjs CHANGED
@@ -89,6 +89,7 @@ __export(index_exports, {
89
89
  createSolanaWallet: () => createSolanaWallet,
90
90
  createWallet: () => createWallet,
91
91
  default: () => client_default,
92
+ estimateChatCostUsd: () => estimateChatCostUsd,
92
93
  evmNetwork: () => evmNetwork,
93
94
  extractPaymentDetails: () => extractPaymentDetails,
94
95
  formatFundingMessageCompact: () => formatFundingMessageCompact,
@@ -115,6 +116,7 @@ __export(index_exports, {
115
116
  logCost: () => logCost,
116
117
  parsePaymentRequired: () => parsePaymentRequired,
117
118
  paymentRejectedErrorFromBody: () => paymentRejectedErrorFromBody,
119
+ platformFeePercentOf: () => platformFeePercentOf,
118
120
  readSettlement: () => readSettlement,
119
121
  retryDisposition: () => retryDisposition,
120
122
  saveSolanaWallet: () => saveSolanaWallet,
@@ -4816,6 +4818,22 @@ var AUTO_ROUTING_PROFILES = {
4816
4818
  };
4817
4819
  var BASE_MINIMUM_PAYMENT_USD = 2e-3;
4818
4820
  var SOLANA_MINIMUM_PAYMENT_USD = 1e-3;
4821
+ function platformFeePercentOf(row) {
4822
+ if (!row) return 0;
4823
+ const mode = row.billingMode ?? row.billing_mode;
4824
+ if (mode !== void 0 && mode !== "paid") return 0;
4825
+ if (row.pricing?.flat !== void 0 && row.pricing.flat !== null) return 0;
4826
+ for (const value of [row.pricing?.platform_fee_percent, row.platform_fee_percent, row.platformFeePercent]) {
4827
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
4828
+ }
4829
+ return 0;
4830
+ }
4831
+ function estimateChatCostUsd(pricing, inputTokens, outputTokens) {
4832
+ if (pricing.flatPrice !== void 0) return pricing.flatPrice;
4833
+ const fee = pricing.platformFeePercent;
4834
+ const factor = typeof fee === "number" && Number.isFinite(fee) && fee >= 0 ? 1 + fee / 100 : 1;
4835
+ return (inputTokens / 1e6 * pricing.inputPrice + outputTokens / 1e6 * pricing.outputPrice) * factor;
4836
+ }
4819
4837
  function isTransientError(err) {
4820
4838
  if (retryDisposition(err) !== "unpaid") return false;
4821
4839
  if (err instanceof PaymentError) return false;
@@ -4944,7 +4962,9 @@ function routeWithCatalog(prompt, systemPrompt, maxOutputTokens, modelPricing, o
4944
4962
  const minimumPaymentUsd = options.minimumPaymentUsd ?? SOLANA_MINIMUM_PAYMENT_USD;
4945
4963
  const entry = modelPricing.get(model);
4946
4964
  const isFree = entry !== void 0 && entry.inputPrice === 0 && entry.outputPrice === 0 && !entry.flatPrice;
4947
- const costEstimate = isFree ? 0 : Math.max(costs.costEstimate, minimumPaymentUsd);
4965
+ const usable = entry !== void 0 && [entry.inputPrice, entry.outputPrice, entry.flatPrice ?? 0].every((v) => Number.isFinite(v) && v >= 0);
4966
+ const modelCost = usable ? estimateChatCostUsd(entry, estimatedInputTokens, maxOutputTokens) : costs.costEstimate;
4967
+ const costEstimate = isFree ? 0 : Math.max(modelCost, minimumPaymentUsd);
4948
4968
  const savings = options.routingProfile === "premium" || costs.baselineCost <= 0 ? 0 : entry !== void 0 ? Math.max(0, (costs.baselineCost - costEstimate) / costs.baselineCost) : decision.savings;
4949
4969
  return {
4950
4970
  ...decision,
@@ -5365,7 +5385,7 @@ function getCostSummary() {
5365
5385
  }
5366
5386
 
5367
5387
  // src/version.ts
5368
- var SDK_VERSION = "4.3.1";
5388
+ var SDK_VERSION = "4.4.0";
5369
5389
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5370
5390
 
5371
5391
  // src/client.ts
@@ -5383,6 +5403,7 @@ function mapRawToModel(m) {
5383
5403
  available: true,
5384
5404
  billingMode: m.billingMode ?? m.billing_mode,
5385
5405
  flatPrice: m.flatPrice ?? m.flat_price ?? m.pricing?.flat,
5406
+ platformFeePercent: platformFeePercentOf(m),
5386
5407
  hidden: m.hidden
5387
5408
  };
5388
5409
  }
@@ -5643,7 +5664,12 @@ var LLMClient = class _LLMClient {
5643
5664
  if (model.billingMode === "flat" && Number.isFinite(model.flatPrice) && model.flatPrice > 0) {
5644
5665
  pricing.set(model.id, { inputPrice, outputPrice, flatPrice: model.flatPrice });
5645
5666
  } else {
5646
- pricing.set(model.id, { inputPrice, outputPrice });
5667
+ const platformFeePercent = platformFeePercentOf(model);
5668
+ pricing.set(model.id, {
5669
+ inputPrice,
5670
+ outputPrice,
5671
+ ...platformFeePercent > 0 ? { platformFeePercent } : {}
5672
+ });
5647
5673
  }
5648
5674
  }
5649
5675
  registerSearchModels(pricing, models);
@@ -6883,6 +6909,18 @@ var LLMClient = class _LLMClient {
6883
6909
  async defi(path7, params) {
6884
6910
  return this.getWithPaymentRaw(`/v1/defillama/${path7}`, params);
6885
6911
  }
6912
+ /**
6913
+ * On-chain US stock price from tokenized-stock DEX pools, paid per call.
6914
+ * This client's chain decides the market: Base (blockrun.ai, Coinbase
6915
+ * Tokenized Stocks) or Solana (sol.blockrun.ai, xStocks). Returns the full
6916
+ * response: price, every pool, the dividend multiplier, the US session and
6917
+ * SEC company facts. A ticker with no market on this chain throws a 404
6918
+ * APIError before anything is signed.
6919
+ */
6920
+ async stockPrice(symbol) {
6921
+ if (!symbol) throw new Error("symbol is required");
6922
+ return await this.getWithPaymentRaw(`/v1/stocks/us/price/${encodeURIComponent(symbol)}`);
6923
+ }
6886
6924
  /** All DeFi protocols with TVL. */
6887
6925
  async defiProtocols() {
6888
6926
  return this.defi("protocols");
@@ -8996,6 +9034,9 @@ var PriceClient = class {
8996
9034
  if (options?.session) query.session = options.session;
8997
9035
  const data = await this.getWithPayment(path7, query);
8998
9036
  return {
9037
+ // Everything the gateway sent, then the typed fields: the on-chain stock
9038
+ // price carries chain, pools, multiplier, usMarket and asset this way.
9039
+ ...data,
8999
9040
  symbol: data.symbol ?? symbol.toUpperCase(),
9000
9041
  price: data.price,
9001
9042
  publishTime: data.publishTime,
@@ -13642,10 +13683,13 @@ var SolanaLLMClient = class {
13642
13683
  const inputPrice = num(model.inputPrice ?? raw.input_price ?? raw.pricing?.input);
13643
13684
  const outputPrice = num(model.outputPrice ?? raw.output_price ?? raw.pricing?.output);
13644
13685
  const flatPrice = num(model.flatPrice ?? raw.flat_price ?? raw.pricing?.flat);
13686
+ const isFlat = (model.billingMode ?? raw.billing_mode) === "flat" && flatPrice > 0;
13687
+ const platformFeePercent = isFlat ? 0 : platformFeePercentOf(raw);
13645
13688
  pricing.set(model.id, {
13646
13689
  inputPrice,
13647
13690
  outputPrice,
13648
- ...(model.billingMode ?? raw.billing_mode) === "flat" && flatPrice > 0 ? { flatPrice } : {}
13691
+ ...isFlat ? { flatPrice } : {},
13692
+ ...platformFeePercent > 0 ? { platformFeePercent } : {}
13649
13693
  });
13650
13694
  }
13651
13695
  registerSearchModels(pricing, models);
@@ -14134,6 +14178,18 @@ var SolanaLLMClient = class {
14134
14178
  async defi(path7, params) {
14135
14179
  return this.getWithPaymentRaw(`/v1/defillama/${path7}`, params);
14136
14180
  }
14181
+ /**
14182
+ * On-chain US stock price from tokenized-stock DEX pools, paid per call.
14183
+ * This client's chain decides the market: Base (blockrun.ai, Coinbase
14184
+ * Tokenized Stocks) or Solana (sol.blockrun.ai, xStocks). Returns the full
14185
+ * response: price, every pool, the dividend multiplier, the US session and
14186
+ * SEC company facts. A ticker with no market on this chain throws a 404
14187
+ * APIError before anything is signed.
14188
+ */
14189
+ async stockPrice(symbol) {
14190
+ if (!symbol) throw new Error("symbol is required");
14191
+ return await this.getWithPaymentRaw(`/v1/stocks/us/price/${encodeURIComponent(symbol)}`);
14192
+ }
14137
14193
  /** All DeFi protocols with TVL. */
14138
14194
  async defiProtocols() {
14139
14195
  return this.defi("protocols");
@@ -15456,6 +15512,7 @@ var AnthropicClient = class {
15456
15512
  createSolanaPaymentPayload,
15457
15513
  createSolanaWallet,
15458
15514
  createWallet,
15515
+ estimateChatCostUsd,
15459
15516
  evmNetwork,
15460
15517
  extractPaymentDetails,
15461
15518
  formatFundingMessageCompact,
@@ -15482,6 +15539,7 @@ var AnthropicClient = class {
15482
15539
  logCost,
15483
15540
  parsePaymentRequired,
15484
15541
  paymentRejectedErrorFromBody,
15542
+ platformFeePercentOf,
15485
15543
  readSettlement,
15486
15544
  retryDisposition,
15487
15545
  saveSolanaWallet,
package/dist/index.d.cts CHANGED
@@ -1,5 +1,19 @@
1
1
  import * as _anthropic_ai_sdk from '@anthropic-ai/sdk';
2
2
 
3
+ /**
4
+ * Tier → Model Selection
5
+ *
6
+ * Maps a classification tier to the cheapest capable model.
7
+ * Builds RoutingDecision metadata with cost estimates and savings.
8
+ */
9
+
10
+ type ModelPricing$1 = {
11
+ inputPrice: number;
12
+ outputPrice: number;
13
+ /** Active promo flat price per request (overrides token-based pricing when set) */
14
+ flatPrice?: number;
15
+ };
16
+
3
17
  /**
4
18
  * Smart Router Types
5
19
  *
@@ -347,6 +361,12 @@ interface Model {
347
361
  billingMode?: "paid" | "flat" | "free";
348
362
  /** Flat per-request price when billingMode === "flat". */
349
363
  flatPrice?: number;
364
+ /**
365
+ * Platform fee (percent) an x402 call pays on top of the per-token
366
+ * `inputPrice` / `outputPrice`: cost = token cost x (1 + this / 100).
367
+ * 0 for free, flat and media rows, and when the gateway does not publish it.
368
+ */
369
+ platformFeePercent?: number;
350
370
  /** True for deprecated/superseded models that remain routable. */
351
371
  hidden?: boolean;
352
372
  }
@@ -1200,6 +1220,74 @@ interface PricePoint {
1200
1220
  /** The gateway's note on the data, e.g. "Daily close, not realtime. ..." */
1201
1221
  note?: string;
1202
1222
  }
1223
+ /**
1224
+ * What PriceClient.price returns: the typed fields plus every other field the
1225
+ * gateway sent, kept as-is (the on-chain US stock price carries chain, pools,
1226
+ * multiplier, usMarket, asset this way). The index signature lives here, not on
1227
+ * PricePoint, so PricePoint itself stays strict for everyone else.
1228
+ */
1229
+ type PricePointWithExtras = PricePoint & Record<string, unknown>;
1230
+ /**
1231
+ * On-chain US stock price: GET /v1/stocks/us/price/{symbol}. blockrun.ai prices
1232
+ * Coinbase Tokenized Stocks on Base, sol.blockrun.ai prices xStocks on Solana;
1233
+ * each answers only for its own chain, and a ticker with no on-chain market
1234
+ * there is a 404 before any payment.
1235
+ */
1236
+ interface OnchainStockQuote {
1237
+ symbol: string;
1238
+ market: "us";
1239
+ chain: "base" | "solana";
1240
+ /** USD per share: liquidity-weighted mid of the on-chain pools, multiplier applied. */
1241
+ price: number;
1242
+ kind: "onchain_dex_mid";
1243
+ note: string;
1244
+ token: {
1245
+ symbol: string;
1246
+ issuer: string;
1247
+ address: string;
1248
+ standard: string;
1249
+ decimals: number;
1250
+ };
1251
+ multiplier: {
1252
+ value: number;
1253
+ next: {
1254
+ value: number;
1255
+ effectiveAt: string;
1256
+ } | null;
1257
+ };
1258
+ paused: boolean | null;
1259
+ pools: Array<{
1260
+ address: string;
1261
+ dex: string;
1262
+ quote: "USDC" | "SOL";
1263
+ price: number | null;
1264
+ quoteSideUsd: number;
1265
+ tvlUsd: number;
1266
+ weight: number;
1267
+ included: boolean;
1268
+ excludedReason: string | null;
1269
+ lastTxAt: string | null;
1270
+ ageSeconds: number | null;
1271
+ }>;
1272
+ quoteSideUsd: number;
1273
+ tvlUsd: number;
1274
+ poolSpreadBps: number;
1275
+ staleWarning?: string[];
1276
+ staleWarningText?: string;
1277
+ chainTime: string;
1278
+ readAt: string;
1279
+ usMarket: {
1280
+ session: "pre" | "regular" | "post" | "closed" | "unknown";
1281
+ nextOpen: string | null;
1282
+ };
1283
+ asset: Record<string, unknown>;
1284
+ otherChains: Array<{
1285
+ chain: "base" | "solana";
1286
+ covered: boolean;
1287
+ endpoint: string;
1288
+ }>;
1289
+ [key: string]: unknown;
1290
+ }
1203
1291
  interface PriceBar {
1204
1292
  t?: number;
1205
1293
  o?: number;
@@ -1962,6 +2050,15 @@ declare class LLMClient {
1962
2050
  * @param params - Query parameters passed through to DefiLlama
1963
2051
  */
1964
2052
  defi(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>;
2053
+ /**
2054
+ * On-chain US stock price from tokenized-stock DEX pools, paid per call.
2055
+ * This client's chain decides the market: Base (blockrun.ai, Coinbase
2056
+ * Tokenized Stocks) or Solana (sol.blockrun.ai, xStocks). Returns the full
2057
+ * response: price, every pool, the dividend multiplier, the US session and
2058
+ * SEC company facts. A ticker with no market on this chain throws a 404
2059
+ * APIError before anything is signed.
2060
+ */
2061
+ stockPrice(symbol: string): Promise<OnchainStockQuote>;
1965
2062
  /** All DeFi protocols with TVL. */
1966
2063
  defiProtocols(): Promise<Record<string, unknown>>;
1967
2064
  /** Single protocol details + historical TVL. */
@@ -2552,7 +2649,7 @@ declare class PriceClient {
2552
2649
  private apiUrl;
2553
2650
  private timeout;
2554
2651
  constructor(options?: PriceClientOptions);
2555
- price(category: PriceCategory, symbol: string, options?: PriceOptions): Promise<PricePoint>;
2652
+ price(category: PriceCategory, symbol: string, options?: PriceOptions): Promise<PricePointWithExtras>;
2556
2653
  history(category: PriceCategory, symbol: string, options: HistoryOptions): Promise<PriceHistoryResponse>;
2557
2654
  listSymbols(category: PriceCategory, options?: ListOptions): Promise<SymbolListResponse>;
2558
2655
  getWalletAddress(): string | null;
@@ -2766,6 +2863,49 @@ declare class BlockrunClient {
2766
2863
  getSpending(): Spending;
2767
2864
  }
2768
2865
 
2866
+ /**
2867
+ * A catalog pricing entry: the bundled router's pricing shape plus the
2868
+ * gateway's platform fee. `platformFeePercent` is set only on per-token paid
2869
+ * chat rows (see {@link platformFeePercentOf}); the router ignores it, and
2870
+ * {@link estimateChatCostUsd} applies it.
2871
+ */
2872
+ type ModelPricing = ModelPricing$1 & {
2873
+ platformFeePercent?: number;
2874
+ };
2875
+ /** A `/v1/models` row as either gateway emits it, or as the SDK maps it. */
2876
+ interface PlatformFeeRow {
2877
+ billing_mode?: string;
2878
+ billingMode?: string;
2879
+ platform_fee_percent?: unknown;
2880
+ platformFeePercent?: unknown;
2881
+ pricing?: {
2882
+ platform_fee_percent?: unknown;
2883
+ flat?: unknown;
2884
+ } | null;
2885
+ }
2886
+ /**
2887
+ * The platform fee, in percent, that an x402 call to this `/v1/models` row
2888
+ * pays on top of its per-token `pricing.input` / `pricing.output` (which stay
2889
+ * at the vendor's list price). Spec: BlockRunAI/blockrun
2890
+ * specs/2026-11-16-chat-platform-fee.md PF-8.
2891
+ *
2892
+ * Read from `pricing.platform_fee_percent` (sol.blockrun.ai and blockrun.ai),
2893
+ * then the row's top-level `platform_fee_percent` (blockrun.ai), then the
2894
+ * SDK-mapped `platformFeePercent`. The first finite, non-negative number wins.
2895
+ *
2896
+ * 0 when the field is absent (older gateways and enterprise, PF-9, do not
2897
+ * send it), and always 0 for a row that is not per-token paid chat: free,
2898
+ * flat (a flat price is final) and media rows never pay it.
2899
+ */
2900
+ declare function platformFeePercentOf(row: PlatformFeeRow | null | undefined): number;
2901
+ /**
2902
+ * Estimated USD cost of one chat call against a catalog pricing entry, before
2903
+ * any payment floor: a flat price as-is, otherwise the per-token list cost
2904
+ * times `(1 + platformFeePercent / 100)`. The real charge is always the
2905
+ * gateway's 402 quote; this is metadata for routing and budgeting.
2906
+ */
2907
+ declare function estimateChatCostUsd(pricing: ModelPricing, inputTokens: number, outputTokens: number): number;
2908
+
2769
2909
  /**
2770
2910
  * x402 Payment Protocol v2 Implementation for BlockRun.
2771
2911
  *
@@ -4265,6 +4405,15 @@ declare class SolanaLLMClient {
4265
4405
  * @param params - Query parameters passed through to DefiLlama
4266
4406
  */
4267
4407
  defi(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>;
4408
+ /**
4409
+ * On-chain US stock price from tokenized-stock DEX pools, paid per call.
4410
+ * This client's chain decides the market: Base (blockrun.ai, Coinbase
4411
+ * Tokenized Stocks) or Solana (sol.blockrun.ai, xStocks). Returns the full
4412
+ * response: price, every pool, the dividend multiplier, the US session and
4413
+ * SEC company facts. A ticker with no market on this chain throws a 404
4414
+ * APIError before anything is signed.
4415
+ */
4416
+ stockPrice(symbol: string): Promise<OnchainStockQuote>;
4268
4417
  /** All DeFi protocols with TVL. */
4269
4418
  defiProtocols(): Promise<Record<string, unknown>>;
4270
4419
  /** Single protocol details + historical TVL. */
@@ -4915,4 +5064,4 @@ declare function readSettlement(response: Response, quotedUsd: number, scheme: S
4915
5064
  /** The model OpenAI serves Decisions from; the gateway also accepts our catalog ids. */
4916
5065
  declare const DECISIONS_DEFAULT_MODEL = "gpt-6-luna";
4917
5066
 
4918
- export { APIError, API_KEY_URL, ARC_CHAIN_ID, AnthropicClient, type AnyTool, type ApiKeyOptions, type AudioModel, type AudioTrack, BASE_CHAIN_ID, BLOCKRUN_SOL_OPERATOR, type BarResolution, type BatchAttempt, BatchChannelBusyError, BatchChannelLockedError, BatchCloseDeferredError, type BatchPayloadKind, BatchPaymentUnresolvedError, type BatchUnresolvedReason, type BlockRunAnthropicOptions, BlockrunClient, type BlockrunClientOptions, BlockrunError, type CallInitiatedResponse, type CallModel, type CallOptions, type CallStatusResponse, type ChatChoice, type ChatCompletionOptions, type ChatMessage, type ChatOptions, type ChatResponse, type ChatResponseWithCost, type ChatUsage, type CostEntry, type CostEstimate, type CreatePaymentOptions, DECISIONS_DEFAULT_MODEL, DEFAULT_BATCH_BUSY_WAIT_MS, DEFAULT_BATCH_IN_DOUBT, DEFAULT_BATCH_LOCK_WAIT_MS, DEFAULT_BATCH_RATE_LIMIT, type DecisionAnswer, type DecisionChoice, type DecisionInputMessage, type DecisionLevel, type DecisionQuestion, type DecisionsRequest, type DecisionsResponse, EVM_NETWORKS, type EvmNetwork, type FunctionCall, type FunctionDefinition, type HistoryOptions, ImageClient, type ImageClientOptions, type ImageData, type ImageEditOptions, type ImageGenerateOptions, type ImageModel, type ImageResponse, KNOWN_PROVIDERS, LLMClient, type LLMClientOptions, type ListOptions, type MarketSession, type Model, MusicClient, type MusicClientOptions, type MusicGenerateOptions, type MusicResponse, NETWORK_ALIASES, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PAYMENT_REPLAY, PHONE_PRICES, PORTAL_URL, PORTRAIT_ENROLLMENT_PRICE_USD, PaymentError, type PaymentLinks, PaymentReplayError, type PhoneBuyOptions, type PhoneBuyResponse, PhoneClient, type PhoneClientOptions, type PhoneListResponse, type PhoneLookupResponse, type PhoneNumberRecord, type PhoneReleaseResponse, type PhoneRenewResponse, type PollOptions, PortraitClient, type PortraitClientOptions, type PortraitEnrollOptions, type PortraitEnrollResponse, type PriceBar, type PriceCategory, PriceClient, type PriceClientOptions, type PriceHistoryResponse, type PriceOptions, type PricePoint, RPC_PRICE_USD, type ReasoningEffort, type Rechallenge, type ResponseFormat, RetiredEndpointError, type RetryDisposition, type RoutingDecision, type RoutingProfile, type RoutingTaskType, type RoutingTier, type RoutingTierConfig, type RpcBatchRequest, RpcClient, type RpcClientOptions, type RpcError, type RpcNetwork, type RpcResponse, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, SUPPORTED_NETWORKS, SearchClient, type SearchClientOptions, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type Settlement, type SmartChatCompletionOptions, type SmartChatCompletionResponse, type SmartChatOptions, type SmartChatResponse, type SolanaBatchEvent, type SolanaBatchOptions, SolanaBatchPayer, type SolanaBatchPayerInit, type SolanaBatchStats, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type SoundEffectOptions, type SpeechAudio, SpeechClient, type SpeechClientOptions, type SpeechGenerateOptions, type SpeechModel, type SpeechResponse, type SpeechVoice, type Spending, type SpendingReport, type StockMarket, SurfClient, type SurfClientOptions, type SymbolListResponse, type Tool, type ToolCall, type ToolChoice, USDC_ARC, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, type UrlCitation, VideoClient, type VideoClientOptions, type VideoClip, type VideoGenerateOptions, type VideoModel, type VideoResponse, VoiceClient, type VoiceClientOptions, type VoiceInfo, type VoicePreset, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletAuthChallenge, type WalletInfo, type WebSearchSource, type WebSearchTool, type X402ClientLike, type X402HookContext, type XSearchSource, type XSearchTool, buildPaymentRejectedError, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, evmNetwork, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatSolanaWalletMigrationNotice, formatWalletCreatedMessage, formatWalletMigrationNotice, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, importSolanaWallet, importWallet, isPaymentReplay, listDiscoveredSolanaWallets, listDiscoveredWallets, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, paymentRejectedErrorFromBody, readSettlement, retryDisposition, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentClient, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, toWireSearchParameters, toWireTools, validateMaxTokens, validateModel, validateTemperature, validateTopP };
5067
+ export { APIError, API_KEY_URL, ARC_CHAIN_ID, AnthropicClient, type AnyTool, type ApiKeyOptions, type AudioModel, type AudioTrack, BASE_CHAIN_ID, BLOCKRUN_SOL_OPERATOR, type BarResolution, type BatchAttempt, BatchChannelBusyError, BatchChannelLockedError, BatchCloseDeferredError, type BatchPayloadKind, BatchPaymentUnresolvedError, type BatchUnresolvedReason, type BlockRunAnthropicOptions, BlockrunClient, type BlockrunClientOptions, BlockrunError, type CallInitiatedResponse, type CallModel, type CallOptions, type CallStatusResponse, type ChatChoice, type ChatCompletionOptions, type ChatMessage, type ChatOptions, type ChatResponse, type ChatResponseWithCost, type ChatUsage, type CostEntry, type CostEstimate, type CreatePaymentOptions, DECISIONS_DEFAULT_MODEL, DEFAULT_BATCH_BUSY_WAIT_MS, DEFAULT_BATCH_IN_DOUBT, DEFAULT_BATCH_LOCK_WAIT_MS, DEFAULT_BATCH_RATE_LIMIT, type DecisionAnswer, type DecisionChoice, type DecisionInputMessage, type DecisionLevel, type DecisionQuestion, type DecisionsRequest, type DecisionsResponse, EVM_NETWORKS, type EvmNetwork, type FunctionCall, type FunctionDefinition, type HistoryOptions, ImageClient, type ImageClientOptions, type ImageData, type ImageEditOptions, type ImageGenerateOptions, type ImageModel, type ImageResponse, KNOWN_PROVIDERS, LLMClient, type LLMClientOptions, type ListOptions, type MarketSession, type Model, MusicClient, type MusicClientOptions, type MusicGenerateOptions, type MusicResponse, NETWORK_ALIASES, type NewsSearchSource, type OnchainStockQuote, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PAYMENT_REPLAY, PHONE_PRICES, PORTAL_URL, PORTRAIT_ENROLLMENT_PRICE_USD, PaymentError, type PaymentLinks, PaymentReplayError, type PhoneBuyOptions, type PhoneBuyResponse, PhoneClient, type PhoneClientOptions, type PhoneListResponse, type PhoneLookupResponse, type PhoneNumberRecord, type PhoneReleaseResponse, type PhoneRenewResponse, type PlatformFeeRow, type PollOptions, PortraitClient, type PortraitClientOptions, type PortraitEnrollOptions, type PortraitEnrollResponse, type PriceBar, type PriceCategory, PriceClient, type PriceClientOptions, type PriceHistoryResponse, type PriceOptions, type PricePoint, type PricePointWithExtras, RPC_PRICE_USD, type ReasoningEffort, type Rechallenge, type ResponseFormat, RetiredEndpointError, type RetryDisposition, type RoutingDecision, type RoutingProfile, type RoutingTaskType, type RoutingTier, type RoutingTierConfig, type RpcBatchRequest, RpcClient, type RpcClientOptions, type RpcError, type RpcNetwork, type RpcResponse, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, SUPPORTED_NETWORKS, SearchClient, type SearchClientOptions, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type Settlement, type SmartChatCompletionOptions, type SmartChatCompletionResponse, type SmartChatOptions, type SmartChatResponse, type SolanaBatchEvent, type SolanaBatchOptions, SolanaBatchPayer, type SolanaBatchPayerInit, type SolanaBatchStats, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type SoundEffectOptions, type SpeechAudio, SpeechClient, type SpeechClientOptions, type SpeechGenerateOptions, type SpeechModel, type SpeechResponse, type SpeechVoice, type Spending, type SpendingReport, type StockMarket, SurfClient, type SurfClientOptions, type SymbolListResponse, type Tool, type ToolCall, type ToolChoice, USDC_ARC, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, type UrlCitation, VideoClient, type VideoClientOptions, type VideoClip, type VideoGenerateOptions, type VideoModel, type VideoResponse, VoiceClient, type VoiceClientOptions, type VoiceInfo, type VoicePreset, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletAuthChallenge, type WalletInfo, type WebSearchSource, type WebSearchTool, type X402ClientLike, type X402HookContext, type XSearchSource, type XSearchTool, buildPaymentRejectedError, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, estimateChatCostUsd, evmNetwork, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatSolanaWalletMigrationNotice, formatWalletCreatedMessage, formatWalletMigrationNotice, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, importSolanaWallet, importWallet, isPaymentReplay, listDiscoveredSolanaWallets, listDiscoveredWallets, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, paymentRejectedErrorFromBody, platformFeePercentOf, readSettlement, retryDisposition, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentClient, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, toWireSearchParameters, toWireTools, validateMaxTokens, validateModel, validateTemperature, validateTopP };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,19 @@
1
1
  import * as _anthropic_ai_sdk from '@anthropic-ai/sdk';
2
2
 
3
+ /**
4
+ * Tier → Model Selection
5
+ *
6
+ * Maps a classification tier to the cheapest capable model.
7
+ * Builds RoutingDecision metadata with cost estimates and savings.
8
+ */
9
+
10
+ type ModelPricing$1 = {
11
+ inputPrice: number;
12
+ outputPrice: number;
13
+ /** Active promo flat price per request (overrides token-based pricing when set) */
14
+ flatPrice?: number;
15
+ };
16
+
3
17
  /**
4
18
  * Smart Router Types
5
19
  *
@@ -347,6 +361,12 @@ interface Model {
347
361
  billingMode?: "paid" | "flat" | "free";
348
362
  /** Flat per-request price when billingMode === "flat". */
349
363
  flatPrice?: number;
364
+ /**
365
+ * Platform fee (percent) an x402 call pays on top of the per-token
366
+ * `inputPrice` / `outputPrice`: cost = token cost x (1 + this / 100).
367
+ * 0 for free, flat and media rows, and when the gateway does not publish it.
368
+ */
369
+ platformFeePercent?: number;
350
370
  /** True for deprecated/superseded models that remain routable. */
351
371
  hidden?: boolean;
352
372
  }
@@ -1200,6 +1220,74 @@ interface PricePoint {
1200
1220
  /** The gateway's note on the data, e.g. "Daily close, not realtime. ..." */
1201
1221
  note?: string;
1202
1222
  }
1223
+ /**
1224
+ * What PriceClient.price returns: the typed fields plus every other field the
1225
+ * gateway sent, kept as-is (the on-chain US stock price carries chain, pools,
1226
+ * multiplier, usMarket, asset this way). The index signature lives here, not on
1227
+ * PricePoint, so PricePoint itself stays strict for everyone else.
1228
+ */
1229
+ type PricePointWithExtras = PricePoint & Record<string, unknown>;
1230
+ /**
1231
+ * On-chain US stock price: GET /v1/stocks/us/price/{symbol}. blockrun.ai prices
1232
+ * Coinbase Tokenized Stocks on Base, sol.blockrun.ai prices xStocks on Solana;
1233
+ * each answers only for its own chain, and a ticker with no on-chain market
1234
+ * there is a 404 before any payment.
1235
+ */
1236
+ interface OnchainStockQuote {
1237
+ symbol: string;
1238
+ market: "us";
1239
+ chain: "base" | "solana";
1240
+ /** USD per share: liquidity-weighted mid of the on-chain pools, multiplier applied. */
1241
+ price: number;
1242
+ kind: "onchain_dex_mid";
1243
+ note: string;
1244
+ token: {
1245
+ symbol: string;
1246
+ issuer: string;
1247
+ address: string;
1248
+ standard: string;
1249
+ decimals: number;
1250
+ };
1251
+ multiplier: {
1252
+ value: number;
1253
+ next: {
1254
+ value: number;
1255
+ effectiveAt: string;
1256
+ } | null;
1257
+ };
1258
+ paused: boolean | null;
1259
+ pools: Array<{
1260
+ address: string;
1261
+ dex: string;
1262
+ quote: "USDC" | "SOL";
1263
+ price: number | null;
1264
+ quoteSideUsd: number;
1265
+ tvlUsd: number;
1266
+ weight: number;
1267
+ included: boolean;
1268
+ excludedReason: string | null;
1269
+ lastTxAt: string | null;
1270
+ ageSeconds: number | null;
1271
+ }>;
1272
+ quoteSideUsd: number;
1273
+ tvlUsd: number;
1274
+ poolSpreadBps: number;
1275
+ staleWarning?: string[];
1276
+ staleWarningText?: string;
1277
+ chainTime: string;
1278
+ readAt: string;
1279
+ usMarket: {
1280
+ session: "pre" | "regular" | "post" | "closed" | "unknown";
1281
+ nextOpen: string | null;
1282
+ };
1283
+ asset: Record<string, unknown>;
1284
+ otherChains: Array<{
1285
+ chain: "base" | "solana";
1286
+ covered: boolean;
1287
+ endpoint: string;
1288
+ }>;
1289
+ [key: string]: unknown;
1290
+ }
1203
1291
  interface PriceBar {
1204
1292
  t?: number;
1205
1293
  o?: number;
@@ -1962,6 +2050,15 @@ declare class LLMClient {
1962
2050
  * @param params - Query parameters passed through to DefiLlama
1963
2051
  */
1964
2052
  defi(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>;
2053
+ /**
2054
+ * On-chain US stock price from tokenized-stock DEX pools, paid per call.
2055
+ * This client's chain decides the market: Base (blockrun.ai, Coinbase
2056
+ * Tokenized Stocks) or Solana (sol.blockrun.ai, xStocks). Returns the full
2057
+ * response: price, every pool, the dividend multiplier, the US session and
2058
+ * SEC company facts. A ticker with no market on this chain throws a 404
2059
+ * APIError before anything is signed.
2060
+ */
2061
+ stockPrice(symbol: string): Promise<OnchainStockQuote>;
1965
2062
  /** All DeFi protocols with TVL. */
1966
2063
  defiProtocols(): Promise<Record<string, unknown>>;
1967
2064
  /** Single protocol details + historical TVL. */
@@ -2552,7 +2649,7 @@ declare class PriceClient {
2552
2649
  private apiUrl;
2553
2650
  private timeout;
2554
2651
  constructor(options?: PriceClientOptions);
2555
- price(category: PriceCategory, symbol: string, options?: PriceOptions): Promise<PricePoint>;
2652
+ price(category: PriceCategory, symbol: string, options?: PriceOptions): Promise<PricePointWithExtras>;
2556
2653
  history(category: PriceCategory, symbol: string, options: HistoryOptions): Promise<PriceHistoryResponse>;
2557
2654
  listSymbols(category: PriceCategory, options?: ListOptions): Promise<SymbolListResponse>;
2558
2655
  getWalletAddress(): string | null;
@@ -2766,6 +2863,49 @@ declare class BlockrunClient {
2766
2863
  getSpending(): Spending;
2767
2864
  }
2768
2865
 
2866
+ /**
2867
+ * A catalog pricing entry: the bundled router's pricing shape plus the
2868
+ * gateway's platform fee. `platformFeePercent` is set only on per-token paid
2869
+ * chat rows (see {@link platformFeePercentOf}); the router ignores it, and
2870
+ * {@link estimateChatCostUsd} applies it.
2871
+ */
2872
+ type ModelPricing = ModelPricing$1 & {
2873
+ platformFeePercent?: number;
2874
+ };
2875
+ /** A `/v1/models` row as either gateway emits it, or as the SDK maps it. */
2876
+ interface PlatformFeeRow {
2877
+ billing_mode?: string;
2878
+ billingMode?: string;
2879
+ platform_fee_percent?: unknown;
2880
+ platformFeePercent?: unknown;
2881
+ pricing?: {
2882
+ platform_fee_percent?: unknown;
2883
+ flat?: unknown;
2884
+ } | null;
2885
+ }
2886
+ /**
2887
+ * The platform fee, in percent, that an x402 call to this `/v1/models` row
2888
+ * pays on top of its per-token `pricing.input` / `pricing.output` (which stay
2889
+ * at the vendor's list price). Spec: BlockRunAI/blockrun
2890
+ * specs/2026-11-16-chat-platform-fee.md PF-8.
2891
+ *
2892
+ * Read from `pricing.platform_fee_percent` (sol.blockrun.ai and blockrun.ai),
2893
+ * then the row's top-level `platform_fee_percent` (blockrun.ai), then the
2894
+ * SDK-mapped `platformFeePercent`. The first finite, non-negative number wins.
2895
+ *
2896
+ * 0 when the field is absent (older gateways and enterprise, PF-9, do not
2897
+ * send it), and always 0 for a row that is not per-token paid chat: free,
2898
+ * flat (a flat price is final) and media rows never pay it.
2899
+ */
2900
+ declare function platformFeePercentOf(row: PlatformFeeRow | null | undefined): number;
2901
+ /**
2902
+ * Estimated USD cost of one chat call against a catalog pricing entry, before
2903
+ * any payment floor: a flat price as-is, otherwise the per-token list cost
2904
+ * times `(1 + platformFeePercent / 100)`. The real charge is always the
2905
+ * gateway's 402 quote; this is metadata for routing and budgeting.
2906
+ */
2907
+ declare function estimateChatCostUsd(pricing: ModelPricing, inputTokens: number, outputTokens: number): number;
2908
+
2769
2909
  /**
2770
2910
  * x402 Payment Protocol v2 Implementation for BlockRun.
2771
2911
  *
@@ -4265,6 +4405,15 @@ declare class SolanaLLMClient {
4265
4405
  * @param params - Query parameters passed through to DefiLlama
4266
4406
  */
4267
4407
  defi(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>;
4408
+ /**
4409
+ * On-chain US stock price from tokenized-stock DEX pools, paid per call.
4410
+ * This client's chain decides the market: Base (blockrun.ai, Coinbase
4411
+ * Tokenized Stocks) or Solana (sol.blockrun.ai, xStocks). Returns the full
4412
+ * response: price, every pool, the dividend multiplier, the US session and
4413
+ * SEC company facts. A ticker with no market on this chain throws a 404
4414
+ * APIError before anything is signed.
4415
+ */
4416
+ stockPrice(symbol: string): Promise<OnchainStockQuote>;
4268
4417
  /** All DeFi protocols with TVL. */
4269
4418
  defiProtocols(): Promise<Record<string, unknown>>;
4270
4419
  /** Single protocol details + historical TVL. */
@@ -4915,4 +5064,4 @@ declare function readSettlement(response: Response, quotedUsd: number, scheme: S
4915
5064
  /** The model OpenAI serves Decisions from; the gateway also accepts our catalog ids. */
4916
5065
  declare const DECISIONS_DEFAULT_MODEL = "gpt-6-luna";
4917
5066
 
4918
- export { APIError, API_KEY_URL, ARC_CHAIN_ID, AnthropicClient, type AnyTool, type ApiKeyOptions, type AudioModel, type AudioTrack, BASE_CHAIN_ID, BLOCKRUN_SOL_OPERATOR, type BarResolution, type BatchAttempt, BatchChannelBusyError, BatchChannelLockedError, BatchCloseDeferredError, type BatchPayloadKind, BatchPaymentUnresolvedError, type BatchUnresolvedReason, type BlockRunAnthropicOptions, BlockrunClient, type BlockrunClientOptions, BlockrunError, type CallInitiatedResponse, type CallModel, type CallOptions, type CallStatusResponse, type ChatChoice, type ChatCompletionOptions, type ChatMessage, type ChatOptions, type ChatResponse, type ChatResponseWithCost, type ChatUsage, type CostEntry, type CostEstimate, type CreatePaymentOptions, DECISIONS_DEFAULT_MODEL, DEFAULT_BATCH_BUSY_WAIT_MS, DEFAULT_BATCH_IN_DOUBT, DEFAULT_BATCH_LOCK_WAIT_MS, DEFAULT_BATCH_RATE_LIMIT, type DecisionAnswer, type DecisionChoice, type DecisionInputMessage, type DecisionLevel, type DecisionQuestion, type DecisionsRequest, type DecisionsResponse, EVM_NETWORKS, type EvmNetwork, type FunctionCall, type FunctionDefinition, type HistoryOptions, ImageClient, type ImageClientOptions, type ImageData, type ImageEditOptions, type ImageGenerateOptions, type ImageModel, type ImageResponse, KNOWN_PROVIDERS, LLMClient, type LLMClientOptions, type ListOptions, type MarketSession, type Model, MusicClient, type MusicClientOptions, type MusicGenerateOptions, type MusicResponse, NETWORK_ALIASES, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PAYMENT_REPLAY, PHONE_PRICES, PORTAL_URL, PORTRAIT_ENROLLMENT_PRICE_USD, PaymentError, type PaymentLinks, PaymentReplayError, type PhoneBuyOptions, type PhoneBuyResponse, PhoneClient, type PhoneClientOptions, type PhoneListResponse, type PhoneLookupResponse, type PhoneNumberRecord, type PhoneReleaseResponse, type PhoneRenewResponse, type PollOptions, PortraitClient, type PortraitClientOptions, type PortraitEnrollOptions, type PortraitEnrollResponse, type PriceBar, type PriceCategory, PriceClient, type PriceClientOptions, type PriceHistoryResponse, type PriceOptions, type PricePoint, RPC_PRICE_USD, type ReasoningEffort, type Rechallenge, type ResponseFormat, RetiredEndpointError, type RetryDisposition, type RoutingDecision, type RoutingProfile, type RoutingTaskType, type RoutingTier, type RoutingTierConfig, type RpcBatchRequest, RpcClient, type RpcClientOptions, type RpcError, type RpcNetwork, type RpcResponse, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, SUPPORTED_NETWORKS, SearchClient, type SearchClientOptions, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type Settlement, type SmartChatCompletionOptions, type SmartChatCompletionResponse, type SmartChatOptions, type SmartChatResponse, type SolanaBatchEvent, type SolanaBatchOptions, SolanaBatchPayer, type SolanaBatchPayerInit, type SolanaBatchStats, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type SoundEffectOptions, type SpeechAudio, SpeechClient, type SpeechClientOptions, type SpeechGenerateOptions, type SpeechModel, type SpeechResponse, type SpeechVoice, type Spending, type SpendingReport, type StockMarket, SurfClient, type SurfClientOptions, type SymbolListResponse, type Tool, type ToolCall, type ToolChoice, USDC_ARC, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, type UrlCitation, VideoClient, type VideoClientOptions, type VideoClip, type VideoGenerateOptions, type VideoModel, type VideoResponse, VoiceClient, type VoiceClientOptions, type VoiceInfo, type VoicePreset, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletAuthChallenge, type WalletInfo, type WebSearchSource, type WebSearchTool, type X402ClientLike, type X402HookContext, type XSearchSource, type XSearchTool, buildPaymentRejectedError, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, evmNetwork, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatSolanaWalletMigrationNotice, formatWalletCreatedMessage, formatWalletMigrationNotice, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, importSolanaWallet, importWallet, isPaymentReplay, listDiscoveredSolanaWallets, listDiscoveredWallets, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, paymentRejectedErrorFromBody, readSettlement, retryDisposition, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentClient, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, toWireSearchParameters, toWireTools, validateMaxTokens, validateModel, validateTemperature, validateTopP };
5067
+ export { APIError, API_KEY_URL, ARC_CHAIN_ID, AnthropicClient, type AnyTool, type ApiKeyOptions, type AudioModel, type AudioTrack, BASE_CHAIN_ID, BLOCKRUN_SOL_OPERATOR, type BarResolution, type BatchAttempt, BatchChannelBusyError, BatchChannelLockedError, BatchCloseDeferredError, type BatchPayloadKind, BatchPaymentUnresolvedError, type BatchUnresolvedReason, type BlockRunAnthropicOptions, BlockrunClient, type BlockrunClientOptions, BlockrunError, type CallInitiatedResponse, type CallModel, type CallOptions, type CallStatusResponse, type ChatChoice, type ChatCompletionOptions, type ChatMessage, type ChatOptions, type ChatResponse, type ChatResponseWithCost, type ChatUsage, type CostEntry, type CostEstimate, type CreatePaymentOptions, DECISIONS_DEFAULT_MODEL, DEFAULT_BATCH_BUSY_WAIT_MS, DEFAULT_BATCH_IN_DOUBT, DEFAULT_BATCH_LOCK_WAIT_MS, DEFAULT_BATCH_RATE_LIMIT, type DecisionAnswer, type DecisionChoice, type DecisionInputMessage, type DecisionLevel, type DecisionQuestion, type DecisionsRequest, type DecisionsResponse, EVM_NETWORKS, type EvmNetwork, type FunctionCall, type FunctionDefinition, type HistoryOptions, ImageClient, type ImageClientOptions, type ImageData, type ImageEditOptions, type ImageGenerateOptions, type ImageModel, type ImageResponse, KNOWN_PROVIDERS, LLMClient, type LLMClientOptions, type ListOptions, type MarketSession, type Model, MusicClient, type MusicClientOptions, type MusicGenerateOptions, type MusicResponse, NETWORK_ALIASES, type NewsSearchSource, type OnchainStockQuote, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PAYMENT_REPLAY, PHONE_PRICES, PORTAL_URL, PORTRAIT_ENROLLMENT_PRICE_USD, PaymentError, type PaymentLinks, PaymentReplayError, type PhoneBuyOptions, type PhoneBuyResponse, PhoneClient, type PhoneClientOptions, type PhoneListResponse, type PhoneLookupResponse, type PhoneNumberRecord, type PhoneReleaseResponse, type PhoneRenewResponse, type PlatformFeeRow, type PollOptions, PortraitClient, type PortraitClientOptions, type PortraitEnrollOptions, type PortraitEnrollResponse, type PriceBar, type PriceCategory, PriceClient, type PriceClientOptions, type PriceHistoryResponse, type PriceOptions, type PricePoint, type PricePointWithExtras, RPC_PRICE_USD, type ReasoningEffort, type Rechallenge, type ResponseFormat, RetiredEndpointError, type RetryDisposition, type RoutingDecision, type RoutingProfile, type RoutingTaskType, type RoutingTier, type RoutingTierConfig, type RpcBatchRequest, RpcClient, type RpcClientOptions, type RpcError, type RpcNetwork, type RpcResponse, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, SUPPORTED_NETWORKS, SearchClient, type SearchClientOptions, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type Settlement, type SmartChatCompletionOptions, type SmartChatCompletionResponse, type SmartChatOptions, type SmartChatResponse, type SolanaBatchEvent, type SolanaBatchOptions, SolanaBatchPayer, type SolanaBatchPayerInit, type SolanaBatchStats, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type SoundEffectOptions, type SpeechAudio, SpeechClient, type SpeechClientOptions, type SpeechGenerateOptions, type SpeechModel, type SpeechResponse, type SpeechVoice, type Spending, type SpendingReport, type StockMarket, SurfClient, type SurfClientOptions, type SymbolListResponse, type Tool, type ToolCall, type ToolChoice, USDC_ARC, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, type UrlCitation, VideoClient, type VideoClientOptions, type VideoClip, type VideoGenerateOptions, type VideoModel, type VideoResponse, VoiceClient, type VoiceClientOptions, type VoiceInfo, type VoicePreset, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletAuthChallenge, type WalletInfo, type WebSearchSource, type WebSearchTool, type X402ClientLike, type X402HookContext, type XSearchSource, type XSearchTool, buildPaymentRejectedError, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, estimateChatCostUsd, evmNetwork, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatSolanaWalletMigrationNotice, formatWalletCreatedMessage, formatWalletMigrationNotice, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, importSolanaWallet, importWallet, isPaymentReplay, listDiscoveredSolanaWallets, listDiscoveredWallets, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, paymentRejectedErrorFromBody, platformFeePercentOf, readSettlement, retryDisposition, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentClient, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, toWireSearchParameters, toWireTools, validateMaxTokens, validateModel, validateTemperature, validateTopP };
package/dist/index.js CHANGED
@@ -4675,6 +4675,22 @@ var AUTO_ROUTING_PROFILES = {
4675
4675
  };
4676
4676
  var BASE_MINIMUM_PAYMENT_USD = 2e-3;
4677
4677
  var SOLANA_MINIMUM_PAYMENT_USD = 1e-3;
4678
+ function platformFeePercentOf(row) {
4679
+ if (!row) return 0;
4680
+ const mode = row.billingMode ?? row.billing_mode;
4681
+ if (mode !== void 0 && mode !== "paid") return 0;
4682
+ if (row.pricing?.flat !== void 0 && row.pricing.flat !== null) return 0;
4683
+ for (const value of [row.pricing?.platform_fee_percent, row.platform_fee_percent, row.platformFeePercent]) {
4684
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
4685
+ }
4686
+ return 0;
4687
+ }
4688
+ function estimateChatCostUsd(pricing, inputTokens, outputTokens) {
4689
+ if (pricing.flatPrice !== void 0) return pricing.flatPrice;
4690
+ const fee = pricing.platformFeePercent;
4691
+ const factor = typeof fee === "number" && Number.isFinite(fee) && fee >= 0 ? 1 + fee / 100 : 1;
4692
+ return (inputTokens / 1e6 * pricing.inputPrice + outputTokens / 1e6 * pricing.outputPrice) * factor;
4693
+ }
4678
4694
  function isTransientError(err) {
4679
4695
  if (retryDisposition(err) !== "unpaid") return false;
4680
4696
  if (err instanceof PaymentError) return false;
@@ -4803,7 +4819,9 @@ function routeWithCatalog(prompt, systemPrompt, maxOutputTokens, modelPricing, o
4803
4819
  const minimumPaymentUsd = options.minimumPaymentUsd ?? SOLANA_MINIMUM_PAYMENT_USD;
4804
4820
  const entry = modelPricing.get(model);
4805
4821
  const isFree = entry !== void 0 && entry.inputPrice === 0 && entry.outputPrice === 0 && !entry.flatPrice;
4806
- const costEstimate = isFree ? 0 : Math.max(costs.costEstimate, minimumPaymentUsd);
4822
+ const usable = entry !== void 0 && [entry.inputPrice, entry.outputPrice, entry.flatPrice ?? 0].every((v) => Number.isFinite(v) && v >= 0);
4823
+ const modelCost = usable ? estimateChatCostUsd(entry, estimatedInputTokens, maxOutputTokens) : costs.costEstimate;
4824
+ const costEstimate = isFree ? 0 : Math.max(modelCost, minimumPaymentUsd);
4807
4825
  const savings = options.routingProfile === "premium" || costs.baselineCost <= 0 ? 0 : entry !== void 0 ? Math.max(0, (costs.baselineCost - costEstimate) / costs.baselineCost) : decision.savings;
4808
4826
  return {
4809
4827
  ...decision,
@@ -5224,7 +5242,7 @@ function getCostSummary() {
5224
5242
  }
5225
5243
 
5226
5244
  // src/version.ts
5227
- var SDK_VERSION = "4.3.1";
5245
+ var SDK_VERSION = "4.4.0";
5228
5246
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5229
5247
 
5230
5248
  // src/client.ts
@@ -5242,6 +5260,7 @@ function mapRawToModel(m) {
5242
5260
  available: true,
5243
5261
  billingMode: m.billingMode ?? m.billing_mode,
5244
5262
  flatPrice: m.flatPrice ?? m.flat_price ?? m.pricing?.flat,
5263
+ platformFeePercent: platformFeePercentOf(m),
5245
5264
  hidden: m.hidden
5246
5265
  };
5247
5266
  }
@@ -5502,7 +5521,12 @@ var LLMClient = class _LLMClient {
5502
5521
  if (model.billingMode === "flat" && Number.isFinite(model.flatPrice) && model.flatPrice > 0) {
5503
5522
  pricing.set(model.id, { inputPrice, outputPrice, flatPrice: model.flatPrice });
5504
5523
  } else {
5505
- pricing.set(model.id, { inputPrice, outputPrice });
5524
+ const platformFeePercent = platformFeePercentOf(model);
5525
+ pricing.set(model.id, {
5526
+ inputPrice,
5527
+ outputPrice,
5528
+ ...platformFeePercent > 0 ? { platformFeePercent } : {}
5529
+ });
5506
5530
  }
5507
5531
  }
5508
5532
  registerSearchModels(pricing, models);
@@ -6742,6 +6766,18 @@ var LLMClient = class _LLMClient {
6742
6766
  async defi(path7, params) {
6743
6767
  return this.getWithPaymentRaw(`/v1/defillama/${path7}`, params);
6744
6768
  }
6769
+ /**
6770
+ * On-chain US stock price from tokenized-stock DEX pools, paid per call.
6771
+ * This client's chain decides the market: Base (blockrun.ai, Coinbase
6772
+ * Tokenized Stocks) or Solana (sol.blockrun.ai, xStocks). Returns the full
6773
+ * response: price, every pool, the dividend multiplier, the US session and
6774
+ * SEC company facts. A ticker with no market on this chain throws a 404
6775
+ * APIError before anything is signed.
6776
+ */
6777
+ async stockPrice(symbol) {
6778
+ if (!symbol) throw new Error("symbol is required");
6779
+ return await this.getWithPaymentRaw(`/v1/stocks/us/price/${encodeURIComponent(symbol)}`);
6780
+ }
6745
6781
  /** All DeFi protocols with TVL. */
6746
6782
  async defiProtocols() {
6747
6783
  return this.defi("protocols");
@@ -8855,6 +8891,9 @@ var PriceClient = class {
8855
8891
  if (options?.session) query.session = options.session;
8856
8892
  const data = await this.getWithPayment(path7, query);
8857
8893
  return {
8894
+ // Everything the gateway sent, then the typed fields: the on-chain stock
8895
+ // price carries chain, pools, multiplier, usMarket and asset this way.
8896
+ ...data,
8858
8897
  symbol: data.symbol ?? symbol.toUpperCase(),
8859
8898
  price: data.price,
8860
8899
  publishTime: data.publishTime,
@@ -13501,10 +13540,13 @@ var SolanaLLMClient = class {
13501
13540
  const inputPrice = num(model.inputPrice ?? raw.input_price ?? raw.pricing?.input);
13502
13541
  const outputPrice = num(model.outputPrice ?? raw.output_price ?? raw.pricing?.output);
13503
13542
  const flatPrice = num(model.flatPrice ?? raw.flat_price ?? raw.pricing?.flat);
13543
+ const isFlat = (model.billingMode ?? raw.billing_mode) === "flat" && flatPrice > 0;
13544
+ const platformFeePercent = isFlat ? 0 : platformFeePercentOf(raw);
13504
13545
  pricing.set(model.id, {
13505
13546
  inputPrice,
13506
13547
  outputPrice,
13507
- ...(model.billingMode ?? raw.billing_mode) === "flat" && flatPrice > 0 ? { flatPrice } : {}
13548
+ ...isFlat ? { flatPrice } : {},
13549
+ ...platformFeePercent > 0 ? { platformFeePercent } : {}
13508
13550
  });
13509
13551
  }
13510
13552
  registerSearchModels(pricing, models);
@@ -13993,6 +14035,18 @@ var SolanaLLMClient = class {
13993
14035
  async defi(path7, params) {
13994
14036
  return this.getWithPaymentRaw(`/v1/defillama/${path7}`, params);
13995
14037
  }
14038
+ /**
14039
+ * On-chain US stock price from tokenized-stock DEX pools, paid per call.
14040
+ * This client's chain decides the market: Base (blockrun.ai, Coinbase
14041
+ * Tokenized Stocks) or Solana (sol.blockrun.ai, xStocks). Returns the full
14042
+ * response: price, every pool, the dividend multiplier, the US session and
14043
+ * SEC company facts. A ticker with no market on this chain throws a 404
14044
+ * APIError before anything is signed.
14045
+ */
14046
+ async stockPrice(symbol) {
14047
+ if (!symbol) throw new Error("symbol is required");
14048
+ return await this.getWithPaymentRaw(`/v1/stocks/us/price/${encodeURIComponent(symbol)}`);
14049
+ }
13996
14050
  /** All DeFi protocols with TVL. */
13997
14051
  async defiProtocols() {
13998
14052
  return this.defi("protocols");
@@ -15315,6 +15369,7 @@ export {
15315
15369
  createSolanaWallet,
15316
15370
  createWallet,
15317
15371
  client_default as default,
15372
+ estimateChatCostUsd,
15318
15373
  evmNetwork,
15319
15374
  extractPaymentDetails,
15320
15375
  formatFundingMessageCompact,
@@ -15341,6 +15396,7 @@ export {
15341
15396
  logCost,
15342
15397
  parsePaymentRequired,
15343
15398
  paymentRejectedErrorFromBody,
15399
+ platformFeePercentOf,
15344
15400
  readSettlement,
15345
15401
  retryDisposition,
15346
15402
  saveSolanaWallet,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/llm",
3
- "version": "4.3.1",
3
+ "version": "4.4.0",
4
4
  "type": "module",
5
5
  "description": "TypeScript SDK for BlockRun - every frontier model behind one OpenAI-compatible client. Pay with a BlockRun API key or per-call in USDC. Smart routing picks the cheapest capable model. No rate limits.",
6
6
  "main": "dist/index.cjs",