@blockrun/llm 2.3.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -785,6 +785,24 @@ interface PriceClientOptions {
785
785
  /** If false, construction succeeds without a wallet (free endpoints only). */
786
786
  requireWallet?: boolean;
787
787
  }
788
+ interface SurfClientOptions {
789
+ privateKey?: `0x${string}` | string;
790
+ apiUrl?: string;
791
+ timeout?: number;
792
+ }
793
+ interface BlockrunClientOptions {
794
+ privateKey?: `0x${string}` | string;
795
+ apiUrl?: string;
796
+ /** Per-HTTP-call timeout in ms (default 60000). For long-running poll() jobs,
797
+ * set budgetMs in PollOptions instead — this only bounds individual fetches. */
798
+ timeout?: number;
799
+ }
800
+ interface PollOptions {
801
+ /** Total wall-clock budget for the entire submit + poll loop (default 300000 = 5 min). */
802
+ budgetMs?: number;
803
+ /** Sleep between poll attempts (default 5000 = 5 s). */
804
+ intervalMs?: number;
805
+ }
788
806
  declare class BlockrunError extends Error {
789
807
  constructor(message: string);
790
808
  }
@@ -1713,6 +1731,198 @@ declare class PriceClient {
1713
1731
  private fetchWithTimeout;
1714
1732
  }
1715
1733
 
1734
+ /**
1735
+ * BlockRun Surf Client — pay-per-call crypto data via x402 micropayments.
1736
+ *
1737
+ * Surf aggregates 84+ endpoints across CEX/DEX market data, on-chain SQL,
1738
+ * wallet intelligence, prediction markets, social analytics, and news under
1739
+ * a single OpenAPI surface mounted at `/api/v1/surf/*`.
1740
+ *
1741
+ * Pricing tiers (flat per-call, USDC on Base):
1742
+ * Tier 1 — $0.001/call (prices, rankings, lists, news, simple reads)
1743
+ * Tier 2 — $0.005/call (order books, candles, search, wallet details)
1744
+ * Tier 3 — $0.020/call (on-chain SQL, schema introspection, chat)
1745
+ *
1746
+ * Because the catalog is large and evolving, this client deliberately
1747
+ * exposes a thin `get` / `post` pair instead of 84 typed wrappers. Pass the
1748
+ * path (with or without the `/v1/surf` prefix) and either query params or a
1749
+ * JSON body. The full endpoint inventory lives at
1750
+ * https://blockrun.ai/marketplace/surf.
1751
+ *
1752
+ * Usage:
1753
+ * import { SurfClient } from "@blockrun/llm";
1754
+ *
1755
+ * const surf = new SurfClient({ privateKey: "0x..." });
1756
+ *
1757
+ * // Tier 1 — token price ($0.001)
1758
+ * const btc = await surf.get("/market/price", { symbol: "BTC" });
1759
+ *
1760
+ * // Tier 2 — order book ($0.005)
1761
+ * const book = await surf.get("/exchange/depth", {
1762
+ * exchange: "binance",
1763
+ * symbol: "BTC-USDT",
1764
+ * });
1765
+ *
1766
+ * // Tier 3 — raw on-chain SQL ($0.020)
1767
+ * const rows = await surf.post("/onchain/sql", {
1768
+ * query: "SELECT block_number FROM ethereum.blocks ORDER BY block_number DESC LIMIT 5",
1769
+ * });
1770
+ *
1771
+ * // Typed responses via generic
1772
+ * type Price = { symbol: string; price: number; timestamp: string };
1773
+ * const typed = await surf.get<Price>("/market/price", { symbol: "ETH" });
1774
+ */
1775
+
1776
+ type QueryValue$1 = string | number | boolean | null | undefined;
1777
+ type QueryParams$1 = Record<string, QueryValue$1 | QueryValue$1[]>;
1778
+ declare class SurfClient {
1779
+ private account;
1780
+ private privateKey;
1781
+ private apiUrl;
1782
+ private timeout;
1783
+ constructor(options?: SurfClientOptions);
1784
+ /**
1785
+ * GET a Surf endpoint. `path` is everything after `/v1/surf` (a leading
1786
+ * `/v1/surf` is tolerated and stripped). Query params are URL-encoded;
1787
+ * arrays become repeated keys (`?a=1&a=2`).
1788
+ */
1789
+ get<T = unknown>(path: string, params?: QueryParams$1): Promise<T>;
1790
+ /**
1791
+ * POST a Surf endpoint with a JSON body. Same path normalization as `get`.
1792
+ */
1793
+ post<T = unknown>(path: string, body?: Record<string, unknown>): Promise<T>;
1794
+ private buildUrl;
1795
+ private requestWithPayment;
1796
+ private handlePaymentAndRetry;
1797
+ private throwApiError;
1798
+ private fetchWithTimeout;
1799
+ getWalletAddress(): string;
1800
+ }
1801
+
1802
+ /**
1803
+ * BlockrunClient — the x402-paying HTTP primitive for the BlockRun gateway.
1804
+ *
1805
+ * This is the **primitive** that every BlockRun API surface composes on top of:
1806
+ * a wallet, an x402 401-sign-replay handler, and four call shapes (get, post,
1807
+ * poll, stream). Per-API classes (LLMClient, ImageClient, SurfClient, …) are
1808
+ * being collapsed into Claude Code skills that drive this client directly.
1809
+ *
1810
+ * Why one primitive instead of one client per API surface:
1811
+ * - Every BlockRun endpoint pays the same way (USDC via x402 on Base/Solana)
1812
+ * - ~30-40 % of each existing client class is identical boilerplate
1813
+ * - New API surfaces should ship as a skill (markdown) + path, not as a
1814
+ * new TypeScript class + npm release
1815
+ *
1816
+ * Four call shapes:
1817
+ * client.get<T>(path, params?) — sync GET, e.g. /v1/surf/market/price
1818
+ * client.post<T>(path, body?) — sync POST, e.g. /v1/surf/onchain/sql
1819
+ * client.poll<T>(path, body?, { budgetMs }) — submit + poll, e.g. /v1/videos/generations
1820
+ * client.stream<T>(path, body?) — SSE iterator, e.g. /v1/chat/completions
1821
+ *
1822
+ * Usage:
1823
+ * import { BlockrunClient } from "@blockrun/llm";
1824
+ *
1825
+ * const br = new BlockrunClient({ privateKey: "0x..." });
1826
+ *
1827
+ * // Surf endpoint (Tier 1, $0.001)
1828
+ * const btc = await br.get("/v1/surf/market/price", { symbol: "BTC" });
1829
+ *
1830
+ * // Raw on-chain SQL (Tier 3, $0.020)
1831
+ * const rows = await br.post("/v1/surf/onchain/sql", {
1832
+ * query: "SELECT block_number FROM ethereum.blocks ORDER BY block_number DESC LIMIT 1",
1833
+ * });
1834
+ *
1835
+ * // Long-running video generation (submit + poll, paid on success)
1836
+ * const video = await br.poll("/v1/videos/generations", {
1837
+ * model: "xai/grok-imagine-video",
1838
+ * prompt: "a red apple spinning",
1839
+ * });
1840
+ *
1841
+ * // Streaming chat
1842
+ * for await (const chunk of br.stream("/v1/chat/completions", {
1843
+ * model: "anthropic/claude-sonnet-4-6",
1844
+ * messages: [{ role: "user", content: "Hi" }],
1845
+ * stream: true,
1846
+ * })) {
1847
+ * process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
1848
+ * }
1849
+ */
1850
+
1851
+ type QueryValue = string | number | boolean | null | undefined;
1852
+ type QueryParams = Record<string, QueryValue | QueryValue[]>;
1853
+ /**
1854
+ * The x402-paying HTTP primitive for the BlockRun gateway.
1855
+ *
1856
+ * One instance, one wallet, all endpoints. The four call shapes (get, post,
1857
+ * poll, stream) cover every endpoint type the gateway exposes.
1858
+ */
1859
+ declare class BlockrunClient {
1860
+ private account;
1861
+ private privateKey;
1862
+ private apiUrl;
1863
+ private timeout;
1864
+ private sessionTotalUsd;
1865
+ private sessionCalls;
1866
+ constructor(options?: BlockrunClientOptions);
1867
+ /**
1868
+ * GET a BlockRun endpoint. `path` is everything after `/api` (a leading
1869
+ * `/api` is tolerated and stripped). Query params are URL-encoded; arrays
1870
+ * become repeated keys (`?a=1&a=2`); undefined/null are dropped.
1871
+ */
1872
+ get<T = unknown>(path: string, params?: QueryParams): Promise<T>;
1873
+ /**
1874
+ * POST a BlockRun endpoint with a JSON body.
1875
+ */
1876
+ post<T = unknown>(path: string, body?: Record<string, unknown>): Promise<T>;
1877
+ /**
1878
+ * Submit a long-running job and poll until it completes.
1879
+ *
1880
+ * Pattern: submit → 402 → sign → 202 `{ id, poll_url, status }` → loop GET
1881
+ * the poll_url with the SAME `PAYMENT-SIGNATURE` until status=completed (or
1882
+ * deadline exceeded). Settlement happens only when upstream returns 200 +
1883
+ * completed — upstream failure or caller giving up = no charge.
1884
+ *
1885
+ * If the gateway returns 200 directly on submit (no async surface), this
1886
+ * short-circuits and returns the body. Most long-running endpoints (image,
1887
+ * video, music, voice) return 202 with a poll_url.
1888
+ */
1889
+ poll<T = unknown>(path: string, body?: Record<string, unknown>, options?: PollOptions): Promise<T>;
1890
+ /**
1891
+ * Stream a Server-Sent Events endpoint.
1892
+ *
1893
+ * Yields each `data: …` line parsed as JSON. Stops when the upstream emits
1894
+ * `data: [DONE]` or closes the connection. Caller is responsible for typing
1895
+ * the chunk shape; pass a generic for typed yields.
1896
+ *
1897
+ * Example — streaming chat:
1898
+ * for await (const chunk of br.stream<ChatChunk>("/v1/chat/completions", {
1899
+ * model: "anthropic/claude-sonnet-4-6",
1900
+ * messages: [{ role: "user", content: "Hi" }],
1901
+ * stream: true,
1902
+ * })) {
1903
+ * process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
1904
+ * }
1905
+ */
1906
+ stream<T = unknown>(path: string, body?: Record<string, unknown>): AsyncGenerator<T, void, undefined>;
1907
+ private buildUrl;
1908
+ private absolute;
1909
+ private requestWithPayment;
1910
+ private handlePaymentAndRetry;
1911
+ /**
1912
+ * Read a 402 response's payment requirements (header or body), then sign and
1913
+ * return the base64 PAYMENT-SIGNATURE payload. Also records the cost-to-be
1914
+ * onto the response context (settled on `recordSpending`).
1915
+ */
1916
+ private signFrom402;
1917
+ /** Accumulates the most-recent pending cost; settled by recordSpending. */
1918
+ private pendingCostUsd;
1919
+ private recordSpending;
1920
+ private throwApiError;
1921
+ private fetchWithTimeout;
1922
+ getWalletAddress(): string;
1923
+ getSpending(): Spending;
1924
+ }
1925
+
1716
1926
  /**
1717
1927
  * x402 Payment Protocol v2 Implementation for BlockRun.
1718
1928
  *
@@ -2356,4 +2566,4 @@ declare function validateTemperature(temperature?: number): void;
2356
2566
  */
2357
2567
  declare function validateTopP(topP?: number): void;
2358
2568
 
2359
- export { APIError, AnthropicClient, type AudioModel, type AudioTrack, BASE_CHAIN_ID, type BarResolution, type BlockRunAnthropicOptions, 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, 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, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PaymentError, type PaymentLinks, type PriceBar, type PriceCategory, PriceClient, type PriceClientOptions, type PriceHistoryResponse, type PriceOptions, type PricePoint, type RoutingDecision, type RoutingProfile, type RoutingTier, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, SearchClient, type SearchClientOptions, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type SmartChatOptions, type SmartChatResponse, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type Spending, type SpendingReport, type StockMarket, type SymbolListResponse, type Tool, type ToolCall, type ToolChoice, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, VideoClient, type VideoClientOptions, type VideoClip, type VideoGenerateOptions, type VideoModel, type VideoResponse, VoiceClient, type VoiceClientOptions, type VoicePreset, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletInfo, type WebSearchSource, type XArticlesRisingResponse, type XAuthorAnalyticsResponse, XClient, type XClientOptions, type XCompareAuthorsResponse, type XFollower, type XFollowersResponse, type XFollowingsResponse, type XMentionsOptions, type XMentionsResponse, type XSearchOptions, type XSearchResponse, type XSearchSource, type XTrendingResponse, type XTweet, type XTweetLookupResponse, type XTweetRepliesOptions, type XTweetRepliesResponse, type XTweetThreadResponse, type XTweetsResponse, type XUser, type XUserInfoResponse, type XUserLookupResponse, type XUserTweetsOptions, type XVerifiedFollowersResponse, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatWalletCreatedMessage, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, validateMaxTokens, validateModel, validateTemperature, validateTopP };
2569
+ export { APIError, AnthropicClient, type AudioModel, type AudioTrack, BASE_CHAIN_ID, type BarResolution, 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, 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, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PaymentError, type PaymentLinks, type PollOptions, type PriceBar, type PriceCategory, PriceClient, type PriceClientOptions, type PriceHistoryResponse, type PriceOptions, type PricePoint, type RoutingDecision, type RoutingProfile, type RoutingTier, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, SearchClient, type SearchClientOptions, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type SmartChatOptions, type SmartChatResponse, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type Spending, type SpendingReport, type StockMarket, SurfClient, type SurfClientOptions, type SymbolListResponse, type Tool, type ToolCall, type ToolChoice, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, VideoClient, type VideoClientOptions, type VideoClip, type VideoGenerateOptions, type VideoModel, type VideoResponse, VoiceClient, type VoiceClientOptions, type VoicePreset, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletInfo, type WebSearchSource, type XArticlesRisingResponse, type XAuthorAnalyticsResponse, XClient, type XClientOptions, type XCompareAuthorsResponse, type XFollower, type XFollowersResponse, type XFollowingsResponse, type XMentionsOptions, type XMentionsResponse, type XSearchOptions, type XSearchResponse, type XSearchSource, type XTrendingResponse, type XTweet, type XTweetLookupResponse, type XTweetRepliesOptions, type XTweetRepliesResponse, type XTweetThreadResponse, type XTweetsResponse, type XUser, type XUserInfoResponse, type XUserLookupResponse, type XUserTweetsOptions, type XVerifiedFollowersResponse, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatWalletCreatedMessage, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, validateMaxTokens, validateModel, validateTemperature, validateTopP };
package/dist/index.d.ts CHANGED
@@ -785,6 +785,24 @@ interface PriceClientOptions {
785
785
  /** If false, construction succeeds without a wallet (free endpoints only). */
786
786
  requireWallet?: boolean;
787
787
  }
788
+ interface SurfClientOptions {
789
+ privateKey?: `0x${string}` | string;
790
+ apiUrl?: string;
791
+ timeout?: number;
792
+ }
793
+ interface BlockrunClientOptions {
794
+ privateKey?: `0x${string}` | string;
795
+ apiUrl?: string;
796
+ /** Per-HTTP-call timeout in ms (default 60000). For long-running poll() jobs,
797
+ * set budgetMs in PollOptions instead — this only bounds individual fetches. */
798
+ timeout?: number;
799
+ }
800
+ interface PollOptions {
801
+ /** Total wall-clock budget for the entire submit + poll loop (default 300000 = 5 min). */
802
+ budgetMs?: number;
803
+ /** Sleep between poll attempts (default 5000 = 5 s). */
804
+ intervalMs?: number;
805
+ }
788
806
  declare class BlockrunError extends Error {
789
807
  constructor(message: string);
790
808
  }
@@ -1713,6 +1731,198 @@ declare class PriceClient {
1713
1731
  private fetchWithTimeout;
1714
1732
  }
1715
1733
 
1734
+ /**
1735
+ * BlockRun Surf Client — pay-per-call crypto data via x402 micropayments.
1736
+ *
1737
+ * Surf aggregates 84+ endpoints across CEX/DEX market data, on-chain SQL,
1738
+ * wallet intelligence, prediction markets, social analytics, and news under
1739
+ * a single OpenAPI surface mounted at `/api/v1/surf/*`.
1740
+ *
1741
+ * Pricing tiers (flat per-call, USDC on Base):
1742
+ * Tier 1 — $0.001/call (prices, rankings, lists, news, simple reads)
1743
+ * Tier 2 — $0.005/call (order books, candles, search, wallet details)
1744
+ * Tier 3 — $0.020/call (on-chain SQL, schema introspection, chat)
1745
+ *
1746
+ * Because the catalog is large and evolving, this client deliberately
1747
+ * exposes a thin `get` / `post` pair instead of 84 typed wrappers. Pass the
1748
+ * path (with or without the `/v1/surf` prefix) and either query params or a
1749
+ * JSON body. The full endpoint inventory lives at
1750
+ * https://blockrun.ai/marketplace/surf.
1751
+ *
1752
+ * Usage:
1753
+ * import { SurfClient } from "@blockrun/llm";
1754
+ *
1755
+ * const surf = new SurfClient({ privateKey: "0x..." });
1756
+ *
1757
+ * // Tier 1 — token price ($0.001)
1758
+ * const btc = await surf.get("/market/price", { symbol: "BTC" });
1759
+ *
1760
+ * // Tier 2 — order book ($0.005)
1761
+ * const book = await surf.get("/exchange/depth", {
1762
+ * exchange: "binance",
1763
+ * symbol: "BTC-USDT",
1764
+ * });
1765
+ *
1766
+ * // Tier 3 — raw on-chain SQL ($0.020)
1767
+ * const rows = await surf.post("/onchain/sql", {
1768
+ * query: "SELECT block_number FROM ethereum.blocks ORDER BY block_number DESC LIMIT 5",
1769
+ * });
1770
+ *
1771
+ * // Typed responses via generic
1772
+ * type Price = { symbol: string; price: number; timestamp: string };
1773
+ * const typed = await surf.get<Price>("/market/price", { symbol: "ETH" });
1774
+ */
1775
+
1776
+ type QueryValue$1 = string | number | boolean | null | undefined;
1777
+ type QueryParams$1 = Record<string, QueryValue$1 | QueryValue$1[]>;
1778
+ declare class SurfClient {
1779
+ private account;
1780
+ private privateKey;
1781
+ private apiUrl;
1782
+ private timeout;
1783
+ constructor(options?: SurfClientOptions);
1784
+ /**
1785
+ * GET a Surf endpoint. `path` is everything after `/v1/surf` (a leading
1786
+ * `/v1/surf` is tolerated and stripped). Query params are URL-encoded;
1787
+ * arrays become repeated keys (`?a=1&a=2`).
1788
+ */
1789
+ get<T = unknown>(path: string, params?: QueryParams$1): Promise<T>;
1790
+ /**
1791
+ * POST a Surf endpoint with a JSON body. Same path normalization as `get`.
1792
+ */
1793
+ post<T = unknown>(path: string, body?: Record<string, unknown>): Promise<T>;
1794
+ private buildUrl;
1795
+ private requestWithPayment;
1796
+ private handlePaymentAndRetry;
1797
+ private throwApiError;
1798
+ private fetchWithTimeout;
1799
+ getWalletAddress(): string;
1800
+ }
1801
+
1802
+ /**
1803
+ * BlockrunClient — the x402-paying HTTP primitive for the BlockRun gateway.
1804
+ *
1805
+ * This is the **primitive** that every BlockRun API surface composes on top of:
1806
+ * a wallet, an x402 401-sign-replay handler, and four call shapes (get, post,
1807
+ * poll, stream). Per-API classes (LLMClient, ImageClient, SurfClient, …) are
1808
+ * being collapsed into Claude Code skills that drive this client directly.
1809
+ *
1810
+ * Why one primitive instead of one client per API surface:
1811
+ * - Every BlockRun endpoint pays the same way (USDC via x402 on Base/Solana)
1812
+ * - ~30-40 % of each existing client class is identical boilerplate
1813
+ * - New API surfaces should ship as a skill (markdown) + path, not as a
1814
+ * new TypeScript class + npm release
1815
+ *
1816
+ * Four call shapes:
1817
+ * client.get<T>(path, params?) — sync GET, e.g. /v1/surf/market/price
1818
+ * client.post<T>(path, body?) — sync POST, e.g. /v1/surf/onchain/sql
1819
+ * client.poll<T>(path, body?, { budgetMs }) — submit + poll, e.g. /v1/videos/generations
1820
+ * client.stream<T>(path, body?) — SSE iterator, e.g. /v1/chat/completions
1821
+ *
1822
+ * Usage:
1823
+ * import { BlockrunClient } from "@blockrun/llm";
1824
+ *
1825
+ * const br = new BlockrunClient({ privateKey: "0x..." });
1826
+ *
1827
+ * // Surf endpoint (Tier 1, $0.001)
1828
+ * const btc = await br.get("/v1/surf/market/price", { symbol: "BTC" });
1829
+ *
1830
+ * // Raw on-chain SQL (Tier 3, $0.020)
1831
+ * const rows = await br.post("/v1/surf/onchain/sql", {
1832
+ * query: "SELECT block_number FROM ethereum.blocks ORDER BY block_number DESC LIMIT 1",
1833
+ * });
1834
+ *
1835
+ * // Long-running video generation (submit + poll, paid on success)
1836
+ * const video = await br.poll("/v1/videos/generations", {
1837
+ * model: "xai/grok-imagine-video",
1838
+ * prompt: "a red apple spinning",
1839
+ * });
1840
+ *
1841
+ * // Streaming chat
1842
+ * for await (const chunk of br.stream("/v1/chat/completions", {
1843
+ * model: "anthropic/claude-sonnet-4-6",
1844
+ * messages: [{ role: "user", content: "Hi" }],
1845
+ * stream: true,
1846
+ * })) {
1847
+ * process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
1848
+ * }
1849
+ */
1850
+
1851
+ type QueryValue = string | number | boolean | null | undefined;
1852
+ type QueryParams = Record<string, QueryValue | QueryValue[]>;
1853
+ /**
1854
+ * The x402-paying HTTP primitive for the BlockRun gateway.
1855
+ *
1856
+ * One instance, one wallet, all endpoints. The four call shapes (get, post,
1857
+ * poll, stream) cover every endpoint type the gateway exposes.
1858
+ */
1859
+ declare class BlockrunClient {
1860
+ private account;
1861
+ private privateKey;
1862
+ private apiUrl;
1863
+ private timeout;
1864
+ private sessionTotalUsd;
1865
+ private sessionCalls;
1866
+ constructor(options?: BlockrunClientOptions);
1867
+ /**
1868
+ * GET a BlockRun endpoint. `path` is everything after `/api` (a leading
1869
+ * `/api` is tolerated and stripped). Query params are URL-encoded; arrays
1870
+ * become repeated keys (`?a=1&a=2`); undefined/null are dropped.
1871
+ */
1872
+ get<T = unknown>(path: string, params?: QueryParams): Promise<T>;
1873
+ /**
1874
+ * POST a BlockRun endpoint with a JSON body.
1875
+ */
1876
+ post<T = unknown>(path: string, body?: Record<string, unknown>): Promise<T>;
1877
+ /**
1878
+ * Submit a long-running job and poll until it completes.
1879
+ *
1880
+ * Pattern: submit → 402 → sign → 202 `{ id, poll_url, status }` → loop GET
1881
+ * the poll_url with the SAME `PAYMENT-SIGNATURE` until status=completed (or
1882
+ * deadline exceeded). Settlement happens only when upstream returns 200 +
1883
+ * completed — upstream failure or caller giving up = no charge.
1884
+ *
1885
+ * If the gateway returns 200 directly on submit (no async surface), this
1886
+ * short-circuits and returns the body. Most long-running endpoints (image,
1887
+ * video, music, voice) return 202 with a poll_url.
1888
+ */
1889
+ poll<T = unknown>(path: string, body?: Record<string, unknown>, options?: PollOptions): Promise<T>;
1890
+ /**
1891
+ * Stream a Server-Sent Events endpoint.
1892
+ *
1893
+ * Yields each `data: …` line parsed as JSON. Stops when the upstream emits
1894
+ * `data: [DONE]` or closes the connection. Caller is responsible for typing
1895
+ * the chunk shape; pass a generic for typed yields.
1896
+ *
1897
+ * Example — streaming chat:
1898
+ * for await (const chunk of br.stream<ChatChunk>("/v1/chat/completions", {
1899
+ * model: "anthropic/claude-sonnet-4-6",
1900
+ * messages: [{ role: "user", content: "Hi" }],
1901
+ * stream: true,
1902
+ * })) {
1903
+ * process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
1904
+ * }
1905
+ */
1906
+ stream<T = unknown>(path: string, body?: Record<string, unknown>): AsyncGenerator<T, void, undefined>;
1907
+ private buildUrl;
1908
+ private absolute;
1909
+ private requestWithPayment;
1910
+ private handlePaymentAndRetry;
1911
+ /**
1912
+ * Read a 402 response's payment requirements (header or body), then sign and
1913
+ * return the base64 PAYMENT-SIGNATURE payload. Also records the cost-to-be
1914
+ * onto the response context (settled on `recordSpending`).
1915
+ */
1916
+ private signFrom402;
1917
+ /** Accumulates the most-recent pending cost; settled by recordSpending. */
1918
+ private pendingCostUsd;
1919
+ private recordSpending;
1920
+ private throwApiError;
1921
+ private fetchWithTimeout;
1922
+ getWalletAddress(): string;
1923
+ getSpending(): Spending;
1924
+ }
1925
+
1716
1926
  /**
1717
1927
  * x402 Payment Protocol v2 Implementation for BlockRun.
1718
1928
  *
@@ -2356,4 +2566,4 @@ declare function validateTemperature(temperature?: number): void;
2356
2566
  */
2357
2567
  declare function validateTopP(topP?: number): void;
2358
2568
 
2359
- export { APIError, AnthropicClient, type AudioModel, type AudioTrack, BASE_CHAIN_ID, type BarResolution, type BlockRunAnthropicOptions, 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, 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, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PaymentError, type PaymentLinks, type PriceBar, type PriceCategory, PriceClient, type PriceClientOptions, type PriceHistoryResponse, type PriceOptions, type PricePoint, type RoutingDecision, type RoutingProfile, type RoutingTier, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, SearchClient, type SearchClientOptions, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type SmartChatOptions, type SmartChatResponse, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type Spending, type SpendingReport, type StockMarket, type SymbolListResponse, type Tool, type ToolCall, type ToolChoice, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, VideoClient, type VideoClientOptions, type VideoClip, type VideoGenerateOptions, type VideoModel, type VideoResponse, VoiceClient, type VoiceClientOptions, type VoicePreset, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletInfo, type WebSearchSource, type XArticlesRisingResponse, type XAuthorAnalyticsResponse, XClient, type XClientOptions, type XCompareAuthorsResponse, type XFollower, type XFollowersResponse, type XFollowingsResponse, type XMentionsOptions, type XMentionsResponse, type XSearchOptions, type XSearchResponse, type XSearchSource, type XTrendingResponse, type XTweet, type XTweetLookupResponse, type XTweetRepliesOptions, type XTweetRepliesResponse, type XTweetThreadResponse, type XTweetsResponse, type XUser, type XUserInfoResponse, type XUserLookupResponse, type XUserTweetsOptions, type XVerifiedFollowersResponse, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatWalletCreatedMessage, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, validateMaxTokens, validateModel, validateTemperature, validateTopP };
2569
+ export { APIError, AnthropicClient, type AudioModel, type AudioTrack, BASE_CHAIN_ID, type BarResolution, 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, 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, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PaymentError, type PaymentLinks, type PollOptions, type PriceBar, type PriceCategory, PriceClient, type PriceClientOptions, type PriceHistoryResponse, type PriceOptions, type PricePoint, type RoutingDecision, type RoutingProfile, type RoutingTier, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, SearchClient, type SearchClientOptions, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type SmartChatOptions, type SmartChatResponse, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type Spending, type SpendingReport, type StockMarket, SurfClient, type SurfClientOptions, type SymbolListResponse, type Tool, type ToolCall, type ToolChoice, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, VideoClient, type VideoClientOptions, type VideoClip, type VideoGenerateOptions, type VideoModel, type VideoResponse, VoiceClient, type VoiceClientOptions, type VoicePreset, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletInfo, type WebSearchSource, type XArticlesRisingResponse, type XAuthorAnalyticsResponse, XClient, type XClientOptions, type XCompareAuthorsResponse, type XFollower, type XFollowersResponse, type XFollowingsResponse, type XMentionsOptions, type XMentionsResponse, type XSearchOptions, type XSearchResponse, type XSearchSource, type XTrendingResponse, type XTweet, type XTweetLookupResponse, type XTweetRepliesOptions, type XTweetRepliesResponse, type XTweetThreadResponse, type XTweetsResponse, type XUser, type XUserInfoResponse, type XUserLookupResponse, type XUserTweetsOptions, type XVerifiedFollowersResponse, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatWalletCreatedMessage, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, validateMaxTokens, validateModel, validateTemperature, validateTopP };