@blockrun/llm 4.3.0 → 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 -->91<!-- /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 -->91<!-- /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) |
@@ -1405,11 +1405,15 @@ const { answers, costUsd } = await client.decisions({
1405
1405
  { type: 'predicate', name: 'urgent', instructions: 'Does this need a reply today?' },
1406
1406
  {
1407
1407
  type: 'choice', name: 'team', instructions: 'Which team owns this?',
1408
- choices: [{ value: 'billing' }, { value: 'shipping' }, { value: 'none', description: 'fits no team' }],
1408
+ choices: [
1409
+ { value: 'billing', description: 'payments and refunds' },
1410
+ { value: 'shipping', description: 'delivery' },
1411
+ { value: 'none', description: 'fits no team' },
1412
+ ],
1409
1413
  },
1410
1414
  {
1411
1415
  type: 'score', name: 'anger', instructions: 'How upset is the writer?',
1412
- levels: [{ label: 'calm' }, { label: 'annoyed' }, { label: 'furious' }], // lowest first
1416
+ levels: [{ label: 'calm', description: '' }, { label: 'annoyed', description: '' }, { label: 'furious', description: '' }], // lowest first
1413
1417
  },
1414
1418
  ],
1415
1419
  });
@@ -1418,6 +1422,12 @@ const { answers, costUsd } = await client.decisions({
1418
1422
  // { type: 'score', name: 'anger', score: 1, probabilities: [...], confidence: 1 }]
1419
1423
  ```
1420
1424
 
1425
+ A `score` answer is the probability-weighted position on the rubric (0 = the
1426
+ first level), so it can be fractional: Gemini answered this example with 1.43
1427
+ (2% calm, 53% annoyed, 45% furious) where luna, all on "annoyed", gave 1. For a
1428
+ single level, take the entry in `probabilities` with the highest probability,
1429
+ or round.
1430
+
1421
1431
  Only input tokens are billed. A wallet call pays the 402's quote: an
1422
1432
  upper-bound estimate of the input tokens plus the $0.001 transaction fee. Under
1423
1433
  Solana [batch settlement](#batch-settlement-optional-metered-billing) it pays
@@ -1432,6 +1442,12 @@ refuses an over-limit request with a 400 before any payment. A `choice` always
1432
1442
  picks one of your values, so give it a `none` value for inputs that fit
1433
1443
  nothing.
1434
1444
 
1445
+ Pass `model: 'gemini-decision-1'` to use Google's Gemini Decision 1 (same price,
1446
+ up to 1,000 questions). It needs a `description` string on every choice and every
1447
+ score level; an empty string is fine. The SDK throws before sending when one is
1448
+ missing. `gpt-6-luna` accepts descriptions too, so the example above works on
1449
+ both models.
1450
+
1435
1451
  ### Standalone Search
1436
1452
 
1437
1453
  `SearchClient` wraps `POST /v1/search` — Grok Live Search over `web` and
@@ -1896,7 +1912,7 @@ to pick up security fixes.
1896
1912
  ## Frequently Asked Questions
1897
1913
 
1898
1914
  ### What is @blockrun/llm?
1899
- 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 -->91<!-- /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.
1900
1916
 
1901
1917
  ### What is smart routing?
1902
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,
@@ -737,6 +739,10 @@ function withCost(body, response, bookedUsd, scheme) {
737
739
  // src/decisions.ts
738
740
  var DECISIONS_DEFAULT_MODEL = "gpt-6-luna";
739
741
  var QUESTION_TYPES = /* @__PURE__ */ new Set(["predicate", "choice", "score"]);
742
+ var GEMINI_DECISIONS_MODEL = "gemini-decision-1";
743
+ function isGemini(model) {
744
+ return typeof model === "string" && model.trim().replace(/^google\//, "") === GEMINI_DECISIONS_MODEL;
745
+ }
740
746
  function invalid(message) {
741
747
  throw withDisposition(new Error(`decisions: ${message}`), "unpaid");
742
748
  }
@@ -762,6 +768,15 @@ function buildDecisionsBody(request) {
762
768
  if (q.type === "score" && (!Array.isArray(q.levels) || q.levels.length === 0)) {
763
769
  invalid(`questions[${i}] (score) needs a non-empty levels array, lowest first`);
764
770
  }
771
+ if (isGemini(request.model) && (q.type === "choice" || q.type === "score")) {
772
+ const key = q.type === "choice" ? "choices" : "levels";
773
+ const items = (q.type === "choice" ? q.choices : q.levels) ?? [];
774
+ items.forEach((item, j) => {
775
+ if (!item || typeof item !== "object" || typeof item.description !== "string") {
776
+ invalid(`questions[${i}].${key}[${j}].description must be a string for ${GEMINI_DECISIONS_MODEL} (it may be empty: "")`);
777
+ }
778
+ });
779
+ }
765
780
  });
766
781
  return { ...request, model: request.model ?? DECISIONS_DEFAULT_MODEL };
767
782
  }
@@ -4803,6 +4818,22 @@ var AUTO_ROUTING_PROFILES = {
4803
4818
  };
4804
4819
  var BASE_MINIMUM_PAYMENT_USD = 2e-3;
4805
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
+ }
4806
4837
  function isTransientError(err) {
4807
4838
  if (retryDisposition(err) !== "unpaid") return false;
4808
4839
  if (err instanceof PaymentError) return false;
@@ -4931,7 +4962,9 @@ function routeWithCatalog(prompt, systemPrompt, maxOutputTokens, modelPricing, o
4931
4962
  const minimumPaymentUsd = options.minimumPaymentUsd ?? SOLANA_MINIMUM_PAYMENT_USD;
4932
4963
  const entry = modelPricing.get(model);
4933
4964
  const isFree = entry !== void 0 && entry.inputPrice === 0 && entry.outputPrice === 0 && !entry.flatPrice;
4934
- 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);
4935
4968
  const savings = options.routingProfile === "premium" || costs.baselineCost <= 0 ? 0 : entry !== void 0 ? Math.max(0, (costs.baselineCost - costEstimate) / costs.baselineCost) : decision.savings;
4936
4969
  return {
4937
4970
  ...decision,
@@ -5352,7 +5385,7 @@ function getCostSummary() {
5352
5385
  }
5353
5386
 
5354
5387
  // src/version.ts
5355
- var SDK_VERSION = "4.3.0";
5388
+ var SDK_VERSION = "4.4.0";
5356
5389
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5357
5390
 
5358
5391
  // src/client.ts
@@ -5370,6 +5403,7 @@ function mapRawToModel(m) {
5370
5403
  available: true,
5371
5404
  billingMode: m.billingMode ?? m.billing_mode,
5372
5405
  flatPrice: m.flatPrice ?? m.flat_price ?? m.pricing?.flat,
5406
+ platformFeePercent: platformFeePercentOf(m),
5373
5407
  hidden: m.hidden
5374
5408
  };
5375
5409
  }
@@ -5630,7 +5664,12 @@ var LLMClient = class _LLMClient {
5630
5664
  if (model.billingMode === "flat" && Number.isFinite(model.flatPrice) && model.flatPrice > 0) {
5631
5665
  pricing.set(model.id, { inputPrice, outputPrice, flatPrice: model.flatPrice });
5632
5666
  } else {
5633
- 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
+ });
5634
5673
  }
5635
5674
  }
5636
5675
  registerSearchModels(pricing, models);
@@ -6591,7 +6630,9 @@ var LLMClient = class _LLMClient {
6591
6630
  * questions: [
6592
6631
  * { type: 'predicate', name: 'urgent', instructions: 'Does this need a reply today?' },
6593
6632
  * { type: 'choice', name: 'team', instructions: 'Which team owns this?',
6594
- * choices: [{ value: 'billing' }, { value: 'shipping' }, { value: 'none' }] },
6633
+ * choices: [{ value: 'billing', description: 'payments and refunds' },
6634
+ * { value: 'shipping', description: 'delivery' },
6635
+ * { value: 'none', description: 'fits no team' }] },
6595
6636
  * ],
6596
6637
  * });
6597
6638
  */
@@ -6868,6 +6909,18 @@ var LLMClient = class _LLMClient {
6868
6909
  async defi(path7, params) {
6869
6910
  return this.getWithPaymentRaw(`/v1/defillama/${path7}`, params);
6870
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
+ }
6871
6924
  /** All DeFi protocols with TVL. */
6872
6925
  async defiProtocols() {
6873
6926
  return this.defi("protocols");
@@ -8981,6 +9034,9 @@ var PriceClient = class {
8981
9034
  if (options?.session) query.session = options.session;
8982
9035
  const data = await this.getWithPayment(path7, query);
8983
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,
8984
9040
  symbol: data.symbol ?? symbol.toUpperCase(),
8985
9041
  price: data.price,
8986
9042
  publishTime: data.publishTime,
@@ -13627,10 +13683,13 @@ var SolanaLLMClient = class {
13627
13683
  const inputPrice = num(model.inputPrice ?? raw.input_price ?? raw.pricing?.input);
13628
13684
  const outputPrice = num(model.outputPrice ?? raw.output_price ?? raw.pricing?.output);
13629
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);
13630
13688
  pricing.set(model.id, {
13631
13689
  inputPrice,
13632
13690
  outputPrice,
13633
- ...(model.billingMode ?? raw.billing_mode) === "flat" && flatPrice > 0 ? { flatPrice } : {}
13691
+ ...isFlat ? { flatPrice } : {},
13692
+ ...platformFeePercent > 0 ? { platformFeePercent } : {}
13634
13693
  });
13635
13694
  }
13636
13695
  registerSearchModels(pricing, models);
@@ -14119,6 +14178,18 @@ var SolanaLLMClient = class {
14119
14178
  async defi(path7, params) {
14120
14179
  return this.getWithPaymentRaw(`/v1/defillama/${path7}`, params);
14121
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
+ }
14122
14193
  /** All DeFi protocols with TVL. */
14123
14194
  async defiProtocols() {
14124
14195
  return this.defi("protocols");
@@ -15441,6 +15512,7 @@ var AnthropicClient = class {
15441
15512
  createSolanaPaymentPayload,
15442
15513
  createSolanaWallet,
15443
15514
  createWallet,
15515
+ estimateChatCostUsd,
15444
15516
  evmNetwork,
15445
15517
  extractPaymentDetails,
15446
15518
  formatFundingMessageCompact,
@@ -15467,6 +15539,7 @@ var AnthropicClient = class {
15467
15539
  logCost,
15468
15540
  parsePaymentRequired,
15469
15541
  paymentRejectedErrorFromBody,
15542
+ platformFeePercentOf,
15470
15543
  readSettlement,
15471
15544
  retryDisposition,
15472
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;
@@ -1798,7 +1886,9 @@ declare class LLMClient {
1798
1886
  * questions: [
1799
1887
  * { type: 'predicate', name: 'urgent', instructions: 'Does this need a reply today?' },
1800
1888
  * { type: 'choice', name: 'team', instructions: 'Which team owns this?',
1801
- * choices: [{ value: 'billing' }, { value: 'shipping' }, { value: 'none' }] },
1889
+ * choices: [{ value: 'billing', description: 'payments and refunds' },
1890
+ * { value: 'shipping', description: 'delivery' },
1891
+ * { value: 'none', description: 'fits no team' }] },
1802
1892
  * ],
1803
1893
  * });
1804
1894
  */
@@ -1960,6 +2050,15 @@ declare class LLMClient {
1960
2050
  * @param params - Query parameters passed through to DefiLlama
1961
2051
  */
1962
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>;
1963
2062
  /** All DeFi protocols with TVL. */
1964
2063
  defiProtocols(): Promise<Record<string, unknown>>;
1965
2064
  /** Single protocol details + historical TVL. */
@@ -2550,7 +2649,7 @@ declare class PriceClient {
2550
2649
  private apiUrl;
2551
2650
  private timeout;
2552
2651
  constructor(options?: PriceClientOptions);
2553
- price(category: PriceCategory, symbol: string, options?: PriceOptions): Promise<PricePoint>;
2652
+ price(category: PriceCategory, symbol: string, options?: PriceOptions): Promise<PricePointWithExtras>;
2554
2653
  history(category: PriceCategory, symbol: string, options: HistoryOptions): Promise<PriceHistoryResponse>;
2555
2654
  listSymbols(category: PriceCategory, options?: ListOptions): Promise<SymbolListResponse>;
2556
2655
  getWalletAddress(): string | null;
@@ -2764,6 +2863,49 @@ declare class BlockrunClient {
2764
2863
  getSpending(): Spending;
2765
2864
  }
2766
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
+
2767
2909
  /**
2768
2910
  * x402 Payment Protocol v2 Implementation for BlockRun.
2769
2911
  *
@@ -4263,6 +4405,15 @@ declare class SolanaLLMClient {
4263
4405
  * @param params - Query parameters passed through to DefiLlama
4264
4406
  */
4265
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>;
4266
4417
  /** All DeFi protocols with TVL. */
4267
4418
  defiProtocols(): Promise<Record<string, unknown>>;
4268
4419
  /** Single protocol details + historical TVL. */
@@ -4913,4 +5064,4 @@ declare function readSettlement(response: Response, quotedUsd: number, scheme: S
4913
5064
  /** The model OpenAI serves Decisions from; the gateway also accepts our catalog ids. */
4914
5065
  declare const DECISIONS_DEFAULT_MODEL = "gpt-6-luna";
4915
5066
 
4916
- 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;
@@ -1798,7 +1886,9 @@ declare class LLMClient {
1798
1886
  * questions: [
1799
1887
  * { type: 'predicate', name: 'urgent', instructions: 'Does this need a reply today?' },
1800
1888
  * { type: 'choice', name: 'team', instructions: 'Which team owns this?',
1801
- * choices: [{ value: 'billing' }, { value: 'shipping' }, { value: 'none' }] },
1889
+ * choices: [{ value: 'billing', description: 'payments and refunds' },
1890
+ * { value: 'shipping', description: 'delivery' },
1891
+ * { value: 'none', description: 'fits no team' }] },
1802
1892
  * ],
1803
1893
  * });
1804
1894
  */
@@ -1960,6 +2050,15 @@ declare class LLMClient {
1960
2050
  * @param params - Query parameters passed through to DefiLlama
1961
2051
  */
1962
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>;
1963
2062
  /** All DeFi protocols with TVL. */
1964
2063
  defiProtocols(): Promise<Record<string, unknown>>;
1965
2064
  /** Single protocol details + historical TVL. */
@@ -2550,7 +2649,7 @@ declare class PriceClient {
2550
2649
  private apiUrl;
2551
2650
  private timeout;
2552
2651
  constructor(options?: PriceClientOptions);
2553
- price(category: PriceCategory, symbol: string, options?: PriceOptions): Promise<PricePoint>;
2652
+ price(category: PriceCategory, symbol: string, options?: PriceOptions): Promise<PricePointWithExtras>;
2554
2653
  history(category: PriceCategory, symbol: string, options: HistoryOptions): Promise<PriceHistoryResponse>;
2555
2654
  listSymbols(category: PriceCategory, options?: ListOptions): Promise<SymbolListResponse>;
2556
2655
  getWalletAddress(): string | null;
@@ -2764,6 +2863,49 @@ declare class BlockrunClient {
2764
2863
  getSpending(): Spending;
2765
2864
  }
2766
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
+
2767
2909
  /**
2768
2910
  * x402 Payment Protocol v2 Implementation for BlockRun.
2769
2911
  *
@@ -4263,6 +4405,15 @@ declare class SolanaLLMClient {
4263
4405
  * @param params - Query parameters passed through to DefiLlama
4264
4406
  */
4265
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>;
4266
4417
  /** All DeFi protocols with TVL. */
4267
4418
  defiProtocols(): Promise<Record<string, unknown>>;
4268
4419
  /** Single protocol details + historical TVL. */
@@ -4913,4 +5064,4 @@ declare function readSettlement(response: Response, quotedUsd: number, scheme: S
4913
5064
  /** The model OpenAI serves Decisions from; the gateway also accepts our catalog ids. */
4914
5065
  declare const DECISIONS_DEFAULT_MODEL = "gpt-6-luna";
4915
5066
 
4916
- 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
@@ -596,6 +596,10 @@ function withCost(body, response, bookedUsd, scheme) {
596
596
  // src/decisions.ts
597
597
  var DECISIONS_DEFAULT_MODEL = "gpt-6-luna";
598
598
  var QUESTION_TYPES = /* @__PURE__ */ new Set(["predicate", "choice", "score"]);
599
+ var GEMINI_DECISIONS_MODEL = "gemini-decision-1";
600
+ function isGemini(model) {
601
+ return typeof model === "string" && model.trim().replace(/^google\//, "") === GEMINI_DECISIONS_MODEL;
602
+ }
599
603
  function invalid(message) {
600
604
  throw withDisposition(new Error(`decisions: ${message}`), "unpaid");
601
605
  }
@@ -621,6 +625,15 @@ function buildDecisionsBody(request) {
621
625
  if (q.type === "score" && (!Array.isArray(q.levels) || q.levels.length === 0)) {
622
626
  invalid(`questions[${i}] (score) needs a non-empty levels array, lowest first`);
623
627
  }
628
+ if (isGemini(request.model) && (q.type === "choice" || q.type === "score")) {
629
+ const key = q.type === "choice" ? "choices" : "levels";
630
+ const items = (q.type === "choice" ? q.choices : q.levels) ?? [];
631
+ items.forEach((item, j) => {
632
+ if (!item || typeof item !== "object" || typeof item.description !== "string") {
633
+ invalid(`questions[${i}].${key}[${j}].description must be a string for ${GEMINI_DECISIONS_MODEL} (it may be empty: "")`);
634
+ }
635
+ });
636
+ }
624
637
  });
625
638
  return { ...request, model: request.model ?? DECISIONS_DEFAULT_MODEL };
626
639
  }
@@ -4662,6 +4675,22 @@ var AUTO_ROUTING_PROFILES = {
4662
4675
  };
4663
4676
  var BASE_MINIMUM_PAYMENT_USD = 2e-3;
4664
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
+ }
4665
4694
  function isTransientError(err) {
4666
4695
  if (retryDisposition(err) !== "unpaid") return false;
4667
4696
  if (err instanceof PaymentError) return false;
@@ -4790,7 +4819,9 @@ function routeWithCatalog(prompt, systemPrompt, maxOutputTokens, modelPricing, o
4790
4819
  const minimumPaymentUsd = options.minimumPaymentUsd ?? SOLANA_MINIMUM_PAYMENT_USD;
4791
4820
  const entry = modelPricing.get(model);
4792
4821
  const isFree = entry !== void 0 && entry.inputPrice === 0 && entry.outputPrice === 0 && !entry.flatPrice;
4793
- 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);
4794
4825
  const savings = options.routingProfile === "premium" || costs.baselineCost <= 0 ? 0 : entry !== void 0 ? Math.max(0, (costs.baselineCost - costEstimate) / costs.baselineCost) : decision.savings;
4795
4826
  return {
4796
4827
  ...decision,
@@ -5211,7 +5242,7 @@ function getCostSummary() {
5211
5242
  }
5212
5243
 
5213
5244
  // src/version.ts
5214
- var SDK_VERSION = "4.3.0";
5245
+ var SDK_VERSION = "4.4.0";
5215
5246
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5216
5247
 
5217
5248
  // src/client.ts
@@ -5229,6 +5260,7 @@ function mapRawToModel(m) {
5229
5260
  available: true,
5230
5261
  billingMode: m.billingMode ?? m.billing_mode,
5231
5262
  flatPrice: m.flatPrice ?? m.flat_price ?? m.pricing?.flat,
5263
+ platformFeePercent: platformFeePercentOf(m),
5232
5264
  hidden: m.hidden
5233
5265
  };
5234
5266
  }
@@ -5489,7 +5521,12 @@ var LLMClient = class _LLMClient {
5489
5521
  if (model.billingMode === "flat" && Number.isFinite(model.flatPrice) && model.flatPrice > 0) {
5490
5522
  pricing.set(model.id, { inputPrice, outputPrice, flatPrice: model.flatPrice });
5491
5523
  } else {
5492
- 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
+ });
5493
5530
  }
5494
5531
  }
5495
5532
  registerSearchModels(pricing, models);
@@ -6450,7 +6487,9 @@ var LLMClient = class _LLMClient {
6450
6487
  * questions: [
6451
6488
  * { type: 'predicate', name: 'urgent', instructions: 'Does this need a reply today?' },
6452
6489
  * { type: 'choice', name: 'team', instructions: 'Which team owns this?',
6453
- * choices: [{ value: 'billing' }, { value: 'shipping' }, { value: 'none' }] },
6490
+ * choices: [{ value: 'billing', description: 'payments and refunds' },
6491
+ * { value: 'shipping', description: 'delivery' },
6492
+ * { value: 'none', description: 'fits no team' }] },
6454
6493
  * ],
6455
6494
  * });
6456
6495
  */
@@ -6727,6 +6766,18 @@ var LLMClient = class _LLMClient {
6727
6766
  async defi(path7, params) {
6728
6767
  return this.getWithPaymentRaw(`/v1/defillama/${path7}`, params);
6729
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
+ }
6730
6781
  /** All DeFi protocols with TVL. */
6731
6782
  async defiProtocols() {
6732
6783
  return this.defi("protocols");
@@ -8840,6 +8891,9 @@ var PriceClient = class {
8840
8891
  if (options?.session) query.session = options.session;
8841
8892
  const data = await this.getWithPayment(path7, query);
8842
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,
8843
8897
  symbol: data.symbol ?? symbol.toUpperCase(),
8844
8898
  price: data.price,
8845
8899
  publishTime: data.publishTime,
@@ -13486,10 +13540,13 @@ var SolanaLLMClient = class {
13486
13540
  const inputPrice = num(model.inputPrice ?? raw.input_price ?? raw.pricing?.input);
13487
13541
  const outputPrice = num(model.outputPrice ?? raw.output_price ?? raw.pricing?.output);
13488
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);
13489
13545
  pricing.set(model.id, {
13490
13546
  inputPrice,
13491
13547
  outputPrice,
13492
- ...(model.billingMode ?? raw.billing_mode) === "flat" && flatPrice > 0 ? { flatPrice } : {}
13548
+ ...isFlat ? { flatPrice } : {},
13549
+ ...platformFeePercent > 0 ? { platformFeePercent } : {}
13493
13550
  });
13494
13551
  }
13495
13552
  registerSearchModels(pricing, models);
@@ -13978,6 +14035,18 @@ var SolanaLLMClient = class {
13978
14035
  async defi(path7, params) {
13979
14036
  return this.getWithPaymentRaw(`/v1/defillama/${path7}`, params);
13980
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
+ }
13981
14050
  /** All DeFi protocols with TVL. */
13982
14051
  async defiProtocols() {
13983
14052
  return this.defi("protocols");
@@ -15300,6 +15369,7 @@ export {
15300
15369
  createSolanaWallet,
15301
15370
  createWallet,
15302
15371
  client_default as default,
15372
+ estimateChatCostUsd,
15303
15373
  evmNetwork,
15304
15374
  extractPaymentDetails,
15305
15375
  formatFundingMessageCompact,
@@ -15326,6 +15396,7 @@ export {
15326
15396
  logCost,
15327
15397
  parsePaymentRequired,
15328
15398
  paymentRejectedErrorFromBody,
15399
+ platformFeePercentOf,
15329
15400
  readSettlement,
15330
15401
  retryDisposition,
15331
15402
  saveSolanaWallet,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/llm",
3
- "version": "4.3.0",
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",