@bridgenode/llm 0.1.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.
@@ -0,0 +1,3210 @@
1
+ import * as _anthropic_ai_sdk from '@anthropic-ai/sdk';
2
+
3
+ /**
4
+ * Type definitions for BlockRun LLM SDK
5
+ */
6
+ interface FunctionDefinition {
7
+ name: string;
8
+ description?: string;
9
+ parameters?: Record<string, unknown>;
10
+ strict?: boolean;
11
+ }
12
+ interface Tool {
13
+ type: "function";
14
+ function: FunctionDefinition;
15
+ }
16
+ interface FunctionCall {
17
+ name: string;
18
+ arguments: string;
19
+ }
20
+ interface ToolCall {
21
+ id: string;
22
+ type: "function";
23
+ function: FunctionCall;
24
+ }
25
+ type ToolChoice = "none" | "auto" | "required" | {
26
+ type: "function";
27
+ function: {
28
+ name: string;
29
+ };
30
+ };
31
+ interface ChatMessage {
32
+ role: "system" | "user" | "assistant" | "tool";
33
+ content?: string | null;
34
+ name?: string;
35
+ tool_call_id?: string;
36
+ tool_calls?: ToolCall[];
37
+ reasoning_content?: string;
38
+ thinking?: string;
39
+ }
40
+ interface ChatChoice {
41
+ index: number;
42
+ message: ChatMessage;
43
+ finish_reason?: "stop" | "length" | "content_filter" | "tool_calls";
44
+ }
45
+ interface ChatUsage {
46
+ prompt_tokens: number;
47
+ completion_tokens: number;
48
+ total_tokens: number;
49
+ num_sources_used?: number;
50
+ cache_read_input_tokens?: number;
51
+ cache_creation_input_tokens?: number;
52
+ }
53
+ interface ChatResponse {
54
+ id: string;
55
+ object: string;
56
+ created: number;
57
+ model: string;
58
+ choices: ChatChoice[];
59
+ usage?: ChatUsage;
60
+ citations?: string[];
61
+ /**
62
+ * Populated when the gateway transparently substituted a different
63
+ * model for the one the caller asked for — typically because the
64
+ * requested model errored and the gateway routed to a free fallback
65
+ * to fulfil the request. When `used` is true:
66
+ * - `model` is the model that actually answered (vs `ChatResponse.model`
67
+ * which historically reflected the requested model id).
68
+ * - `settlementSkipped` is `true` when the gateway also skipped the
69
+ * on-chain settle — i.e. the user was not charged for this call
70
+ * because a free fallback served it.
71
+ * Surfaced from the gateway's `X-Fallback-Used / X-Fallback-Model /
72
+ * X-Settlement-Skipped` response headers. Absent when the headers
73
+ * aren't present (most calls).
74
+ */
75
+ fallback?: {
76
+ used: true;
77
+ model?: string;
78
+ settlementSkipped?: boolean;
79
+ };
80
+ }
81
+ interface Model {
82
+ id: string;
83
+ name: string;
84
+ provider: string;
85
+ description: string;
86
+ /** Per 1M tokens. 0 when billingMode !== "paid". */
87
+ inputPrice: number;
88
+ /** Per 1M tokens. 0 when billingMode !== "paid". */
89
+ outputPrice: number;
90
+ contextWindow: number;
91
+ maxOutput: number;
92
+ categories: string[];
93
+ available: boolean;
94
+ type?: "llm" | "image";
95
+ /** One of "paid" (per-token), "flat" (flatPrice per request) or "free". */
96
+ billingMode?: "paid" | "flat" | "free";
97
+ /** Flat per-request price when billingMode === "flat". */
98
+ flatPrice?: number;
99
+ /** True for deprecated/superseded models that remain routable. */
100
+ hidden?: boolean;
101
+ }
102
+ interface ImageData {
103
+ url: string;
104
+ /** Original upstream URL (e.g. imgen.x.ai). Omitted for data URIs. */
105
+ source_url?: string;
106
+ /** True when the gateway mirrored the image to its GCS bucket. Omitted for data URIs. */
107
+ backed_up?: boolean;
108
+ revised_prompt?: string;
109
+ b64_json?: string;
110
+ }
111
+ interface ImageResponse {
112
+ created: number;
113
+ data: ImageData[];
114
+ }
115
+ interface ImageModel {
116
+ id: string;
117
+ name: string;
118
+ provider: string;
119
+ description: string;
120
+ pricePerImage: number;
121
+ supportedSizes?: string[];
122
+ maxPromptLength?: number;
123
+ available: boolean;
124
+ type?: "llm" | "image";
125
+ }
126
+ interface ImageClientOptions {
127
+ /** EVM wallet private key (hex string starting with 0x) */
128
+ privateKey?: `0x${string}` | string;
129
+ /** API endpoint URL (default: https://bridgenode.cc/api) */
130
+ apiUrl?: string;
131
+ /** Request timeout in milliseconds (default: 120000 for images) */
132
+ timeout?: number;
133
+ }
134
+ interface ImageGenerateOptions {
135
+ /** Model ID (default: "google/nano-banana") */
136
+ model?: string;
137
+ /** Image size (default: "1024x1024") */
138
+ size?: string;
139
+ /** Number of images to generate (default: 1) */
140
+ n?: number;
141
+ /** Image quality (for supported models) */
142
+ quality?: "standard" | "hd";
143
+ }
144
+ interface WebSearchSource {
145
+ type: "web";
146
+ country?: string;
147
+ excludedWebsites?: string[];
148
+ allowedWebsites?: string[];
149
+ safeSearch?: boolean;
150
+ }
151
+ interface XSearchSource {
152
+ type: "x";
153
+ includedXHandles?: string[];
154
+ excludedXHandles?: string[];
155
+ postFavoriteCount?: number;
156
+ postViewCount?: number;
157
+ }
158
+ interface NewsSearchSource {
159
+ type: "news";
160
+ country?: string;
161
+ excludedWebsites?: string[];
162
+ allowedWebsites?: string[];
163
+ safeSearch?: boolean;
164
+ }
165
+ interface RssSearchSource {
166
+ type: "rss";
167
+ links: string[];
168
+ }
169
+ type SearchSource = WebSearchSource | XSearchSource | NewsSearchSource | RssSearchSource;
170
+ interface SearchParameters {
171
+ mode?: "off" | "auto" | "on";
172
+ sources?: SearchSource[];
173
+ returnCitations?: boolean;
174
+ fromDate?: string;
175
+ toDate?: string;
176
+ maxSearchResults?: number;
177
+ }
178
+ /** Usage info for Live Search sources */
179
+ interface SearchUsage {
180
+ /** Number of search sources used in the response */
181
+ numSourcesUsed?: number;
182
+ }
183
+ interface Spending {
184
+ totalUsd: number;
185
+ calls: number;
186
+ }
187
+ /** Pre-request cost estimate for a chat call */
188
+ interface CostEstimate {
189
+ /** Model ID used for the estimate */
190
+ model: string;
191
+ /** Estimated input token count */
192
+ estimatedInputTokens: number;
193
+ /** Estimated output token count */
194
+ estimatedOutputTokens: number;
195
+ /** Estimated cost in USD */
196
+ estimatedCostUsd: number;
197
+ }
198
+ /** Per-call spending report with running session totals */
199
+ interface SpendingReport {
200
+ /** Model ID used */
201
+ model: string;
202
+ /** Input tokens consumed */
203
+ inputTokens: number;
204
+ /** Output tokens consumed */
205
+ outputTokens: number;
206
+ /** Cost of this call in USD */
207
+ costUsd: number;
208
+ /** Cumulative session spend in USD */
209
+ sessionTotalUsd: number;
210
+ /** Total number of calls in this session */
211
+ sessionCalls: number;
212
+ }
213
+ /** Chat response bundled with its spending report */
214
+ interface ChatResponseWithCost {
215
+ /** The chat completion response */
216
+ response: ChatResponse;
217
+ /** Spending report for this call */
218
+ spendingReport: SpendingReport;
219
+ }
220
+ interface ResourceInfo {
221
+ url: string;
222
+ description?: string;
223
+ mimeType?: string;
224
+ }
225
+ interface PaymentRequirement {
226
+ scheme: string;
227
+ network: string;
228
+ asset: string;
229
+ amount?: string;
230
+ maxAmountRequired?: string;
231
+ payTo: string;
232
+ maxTimeoutSeconds?: number;
233
+ extra?: {
234
+ name?: string;
235
+ version?: string;
236
+ };
237
+ }
238
+ interface PaymentRequired {
239
+ x402Version: number;
240
+ accepts: PaymentRequirement[];
241
+ resource?: ResourceInfo;
242
+ }
243
+ interface LLMClientOptions {
244
+ /** EVM wallet private key (hex string starting with 0x). Optional if BASE_CHAIN_WALLET_KEY env var is set. */
245
+ privateKey?: `0x${string}` | string;
246
+ /** API endpoint URL (default: https://bridgenode.cc/api) */
247
+ apiUrl?: string;
248
+ /** Request timeout in milliseconds (default: 600000 / 600s; override via BRIDGENODE_CHAT_TIMEOUT env, in seconds) */
249
+ timeout?: number;
250
+ }
251
+ /**
252
+ * OpenAI-compatible response format. `{ type: "json_object" }` enables JSON
253
+ * mode — honored across all providers by the gateway (native for OpenAI/Azure,
254
+ * emulated via a raw-JSON system instruction for Anthropic/Bedrock).
255
+ */
256
+ type ResponseFormat = {
257
+ type: "text";
258
+ } | {
259
+ type: "json_object";
260
+ } | {
261
+ type: "json_schema";
262
+ json_schema: Record<string, unknown>;
263
+ };
264
+ interface ChatOptions {
265
+ /** System prompt */
266
+ system?: string;
267
+ /** Max tokens to generate */
268
+ maxTokens?: number;
269
+ /** Sampling temperature */
270
+ temperature?: number;
271
+ /** Nucleus sampling parameter */
272
+ topP?: number;
273
+ /** Enable Live Search (shortcut for searchParameters.mode = "on") */
274
+ search?: boolean;
275
+ /** Full Live Search configuration (for search-enabled models) */
276
+ searchParameters?: SearchParameters;
277
+ /** Response format, e.g. { type: "json_object" } for JSON mode */
278
+ responseFormat?: ResponseFormat;
279
+ /** Up to 4 stop sequences (forwarded natively / mapped to stop_sequences) */
280
+ stop?: string | string[];
281
+ /**
282
+ * Models to try in order if the primary returns a transient error
283
+ * (timeout, network, 5xx). 4xx and PaymentError still propagate
284
+ * immediately. `smartChat` populates this from the routing tier's
285
+ * fallback chain automatically.
286
+ */
287
+ fallbackModels?: string[];
288
+ }
289
+ interface ChatCompletionOptions {
290
+ /** Max tokens to generate */
291
+ maxTokens?: number;
292
+ /** Sampling temperature */
293
+ temperature?: number;
294
+ /** Nucleus sampling parameter */
295
+ topP?: number;
296
+ /** Enable Live Search (shortcut for searchParameters.mode = "on") */
297
+ search?: boolean;
298
+ /** Full Live Search configuration (for search-enabled models) */
299
+ searchParameters?: SearchParameters;
300
+ /** Tool definitions for function calling */
301
+ tools?: Tool[];
302
+ /** Tool selection strategy */
303
+ toolChoice?: ToolChoice;
304
+ /** Response format, e.g. { type: "json_object" } for JSON mode */
305
+ responseFormat?: ResponseFormat;
306
+ /** Up to 4 stop sequences (forwarded natively / mapped to stop_sequences) */
307
+ stop?: string | string[];
308
+ /**
309
+ * Models to try in order if the primary returns a transient error
310
+ * (timeout, network, 5xx). 4xx and PaymentError still propagate
311
+ * immediately.
312
+ */
313
+ fallbackModels?: string[];
314
+ }
315
+ type RoutingProfile = "eco" | "auto" | "premium";
316
+ type RoutingTier = "SIMPLE" | "MEDIUM" | "COMPLEX" | "REASONING";
317
+ interface RoutingDecision {
318
+ model: string;
319
+ tier: RoutingTier;
320
+ confidence: number;
321
+ method: "rules" | "llm";
322
+ reasoning: string;
323
+ costEstimate: number;
324
+ baselineCost: number;
325
+ savings: number;
326
+ /** Routing profile applied by clawrouter (may include "agentic" on gateway responses). */
327
+ profile?: RoutingProfile | "agentic";
328
+ /** Score used when agentic routing is active. */
329
+ agenticScore?: number;
330
+ /**
331
+ * Remaining tier models with known pricing, in fallback order. `chat()`
332
+ * walks this list when the primary model hits a transient error
333
+ * (timeout, network, 5xx). Excludes the primary itself.
334
+ */
335
+ fallbacks?: string[];
336
+ }
337
+ interface SmartChatOptions extends ChatOptions {
338
+ /** Routing profile: eco (budget), auto (balanced), premium (best quality) */
339
+ routingProfile?: RoutingProfile;
340
+ /** Maximum output tokens (used for cost estimation) */
341
+ maxOutputTokens?: number;
342
+ }
343
+ interface SmartChatResponse {
344
+ /** The AI response text */
345
+ response: string;
346
+ /** Which model was selected by smart routing */
347
+ model: string;
348
+ /** Routing decision metadata */
349
+ routing: RoutingDecision;
350
+ }
351
+ interface SearchResult {
352
+ query: string;
353
+ summary: string;
354
+ citations?: Array<Record<string, string>>;
355
+ sources_used?: number;
356
+ model?: string;
357
+ }
358
+ interface ImageEditOptions {
359
+ /** Model ID (default: "openai/gpt-image-2") */
360
+ model?: string;
361
+ /** Optional base64-encoded mask image */
362
+ mask?: string;
363
+ /** Image size (default: "1024x1024") */
364
+ size?: string;
365
+ /** Number of images to generate (default: 1) */
366
+ n?: number;
367
+ }
368
+ interface AudioTrack {
369
+ url: string;
370
+ duration_seconds?: number;
371
+ lyrics?: string;
372
+ }
373
+ interface MusicResponse {
374
+ created: number;
375
+ model: string;
376
+ data: AudioTrack[];
377
+ txHash?: string;
378
+ }
379
+ interface AudioModel {
380
+ id: string;
381
+ name: string;
382
+ provider: string;
383
+ description: string;
384
+ pricePerTrack: number;
385
+ maxDurationSeconds: number;
386
+ supportsLyrics: boolean;
387
+ supportsInstrumental: boolean;
388
+ available: boolean;
389
+ type: "audio";
390
+ }
391
+ interface MusicClientOptions {
392
+ /** EVM wallet private key (hex string starting with 0x) */
393
+ privateKey?: `0x${string}` | string;
394
+ /** API endpoint URL (default: https://bridgenode.cc/api) */
395
+ apiUrl?: string;
396
+ /** Request timeout in milliseconds (default: 210000 — music gen takes 1-3 min) */
397
+ timeout?: number;
398
+ }
399
+ interface MusicGenerateOptions {
400
+ /** Model ID (default: "minimax/music-2.5+") */
401
+ model?: "minimax/music-2.5+" | "minimax/music-2.5";
402
+ /** Generate without vocals (default: true) */
403
+ instrumental?: boolean;
404
+ /** Custom lyrics — cannot be used with instrumental: true */
405
+ lyrics?: string;
406
+ }
407
+ /** A single synthesized audio clip. */
408
+ interface SpeechAudio {
409
+ url: string;
410
+ format?: string;
411
+ characters?: number;
412
+ credits?: number;
413
+ }
414
+ /** Response from speech synthesis or sound-effect generation. */
415
+ interface SpeechResponse {
416
+ created: number;
417
+ model: string;
418
+ data: SpeechAudio[];
419
+ txHash?: string;
420
+ }
421
+ interface SpeechClientOptions {
422
+ /** EVM wallet private key (hex string starting with 0x) */
423
+ privateKey?: `0x${string}` | string;
424
+ /** API endpoint URL (default: https://bridgenode.cc/api) */
425
+ apiUrl?: string;
426
+ /** Request timeout in milliseconds (default: 120000 — synthesis is synchronous) */
427
+ timeout?: number;
428
+ }
429
+ /** TTS model IDs (price per 1k chars: flash/turbo $0.05, multilingual-v2/v3 $0.10). */
430
+ type SpeechModel = "elevenlabs/flash-v2.5" | "elevenlabs/turbo-v2.5" | "elevenlabs/multilingual-v2" | "elevenlabs/v3";
431
+ /** Friendly voice aliases (raw ElevenLabs voice_ids also accepted). */
432
+ type SpeechVoice = "sarah" | "george" | "laura" | "charlie" | "river" | "roger" | "callum" | "harry" | (string & {});
433
+ interface SpeechGenerateOptions {
434
+ /** Speech model ID (default: "elevenlabs/flash-v2.5") */
435
+ model?: SpeechModel | (string & {});
436
+ /** Voice alias or raw ElevenLabs voice_id (default: "sarah") */
437
+ voice?: SpeechVoice;
438
+ /** Audio format (default: "mp3") */
439
+ responseFormat?: "mp3" | "opus" | "pcm" | "wav";
440
+ /** Playback speed 0.7-1.2 */
441
+ speed?: number;
442
+ }
443
+ interface SoundEffectOptions {
444
+ /** Model ID (default: "elevenlabs/sound-effects") */
445
+ model?: string;
446
+ /** Target duration 0.5-22s (auto if unset) */
447
+ durationSeconds?: number;
448
+ /** 0-1, higher follows the prompt more literally */
449
+ promptInfluence?: number;
450
+ /** Audio format (default: "mp3") */
451
+ responseFormat?: "mp3" | "opus" | "pcm" | "wav";
452
+ }
453
+ /** A voice entry returned by GET /v1/audio/voices. */
454
+ interface VoiceInfo {
455
+ voice_id: string;
456
+ name?: string;
457
+ alias?: string;
458
+ category?: string;
459
+ labels?: Record<string, string>;
460
+ preview_url?: string;
461
+ [key: string]: unknown;
462
+ }
463
+ interface RpcClientOptions {
464
+ /** EVM wallet private key (hex string starting with 0x) */
465
+ privateKey?: `0x${string}` | string;
466
+ /** API endpoint URL (default: https://bridgenode.cc/api) */
467
+ apiUrl?: string;
468
+ /** Request timeout in milliseconds (default: 60000 — upstream gateway timeout is 20s) */
469
+ timeout?: number;
470
+ }
471
+ /** A JSON-RPC 2.0 error object. */
472
+ interface RpcError {
473
+ code?: number;
474
+ message?: string;
475
+ data?: unknown;
476
+ }
477
+ /**
478
+ * Response from a multi-chain JSON-RPC call.
479
+ *
480
+ * Standard JSON-RPC 2.0 envelope plus BlockRun gateway metadata pulled
481
+ * from response headers (PAYMENT-RESPONSE / X-Network / X-Cache).
482
+ */
483
+ interface RpcResponse<T = unknown> {
484
+ jsonrpc?: string;
485
+ id?: string | number | null;
486
+ result?: T;
487
+ error?: RpcError;
488
+ /** Canonical network key, e.g. "ethereum" (from X-Network) */
489
+ network?: string;
490
+ /** Served from the gateway's method-aware cache (from X-Cache) */
491
+ cacheHit?: boolean;
492
+ /** x402 settlement tx hash (single calls) */
493
+ txHash?: string;
494
+ }
495
+ /** A single request in a JSON-RPC batch (jsonrpc/id auto-filled if omitted). */
496
+ interface RpcBatchRequest {
497
+ method: string;
498
+ params?: unknown[];
499
+ id?: string | number;
500
+ jsonrpc?: string;
501
+ }
502
+ /** Built-in Bland.ai voice presets. Any string is accepted (custom voice IDs work too). */
503
+ type VoicePreset = "nat" | "josh" | "maya" | "june" | "paige" | "derek" | "florian";
504
+ /** Bland.ai conversation model tier. */
505
+ type CallModel = "base" | "enhanced" | "turbo";
506
+ interface VoiceClientOptions {
507
+ /** EVM wallet private key (hex string starting with 0x) */
508
+ privateKey?: `0x${string}` | string;
509
+ /** API endpoint URL (default: https://bridgenode.cc/api) */
510
+ apiUrl?: string;
511
+ /** Request timeout in milliseconds (default: 60000 — initiation only) */
512
+ timeout?: number;
513
+ }
514
+ interface CallOptions {
515
+ /** Destination phone number in E.164 format (e.g. "+14155552671"). US + Canada. */
516
+ to: string;
517
+ /** What the AI agent should do on the call. 10–4000 chars. */
518
+ task: string;
519
+ /** Your provisioned BlockRun caller-ID number (E.164). Must be wallet-owned. */
520
+ from?: string;
521
+ /** Voice preset or any Bland.ai voice ID. */
522
+ voice?: VoicePreset | string;
523
+ /** Maximum call length in minutes (1–30, default 5). */
524
+ max_duration?: number;
525
+ /** BCP-47 language code for STT/TTS (default "en-US"). */
526
+ language?: string;
527
+ /** Optional opening line spoken by the agent. */
528
+ first_sentence?: string;
529
+ /** If true, wait for the recipient to speak first. */
530
+ wait_for_greeting?: boolean;
531
+ /** Sensitivity for detecting recipient interruption (50–500 ms). */
532
+ interruption_threshold?: number;
533
+ /** Conversation model. */
534
+ model?: CallModel;
535
+ }
536
+ interface CallInitiatedResponse {
537
+ call_id: string;
538
+ status: string;
539
+ poll_url: string;
540
+ message?: string;
541
+ /** On-chain payment receipt (Base tx hash). */
542
+ txHash?: string;
543
+ }
544
+ /**
545
+ * Bland.ai call status payload. Returned from getStatus.
546
+ * Most fields are populated only after the call ends.
547
+ */
548
+ interface CallStatusResponse {
549
+ call_id?: string;
550
+ status?: string;
551
+ to?: string;
552
+ from?: string;
553
+ /** ISO timestamp call started, or null while queued. */
554
+ started_at?: string | null;
555
+ /** ISO timestamp call ended, or null while in progress. */
556
+ ended_at?: string | null;
557
+ /** Total call length in seconds, once completed. */
558
+ call_length?: number;
559
+ /** URL to the call recording (mp3/wav). */
560
+ recording_url?: string | null;
561
+ /** Full text transcript of the call. */
562
+ concatenated_transcript?: string | null;
563
+ /** Per-turn transcript array. Shape comes from Bland.ai. */
564
+ transcripts?: Array<Record<string, unknown>>;
565
+ /** Why the call ended ("user_hangup", "agent_hangup", "timeout", …). */
566
+ ended_reason?: string | null;
567
+ /** Pass-through for anything Bland.ai adds. */
568
+ [key: string]: unknown;
569
+ }
570
+ interface VideoClip {
571
+ /** Permanent blockrun-hosted URL (falls back to upstream if backup fails) */
572
+ url: string;
573
+ /** Original upstream URL (e.g. vidgen.x.ai) */
574
+ source_url?: string;
575
+ /** Duration of the generated video */
576
+ duration_seconds?: number;
577
+ /** Upstream provider's request id (xAI) */
578
+ request_id?: string;
579
+ /** True when the gateway mirrored the video to its GCS bucket */
580
+ backed_up?: boolean;
581
+ }
582
+ interface VideoResponse {
583
+ created: number;
584
+ model: string;
585
+ data: VideoClip[];
586
+ txHash?: string;
587
+ }
588
+ interface VideoModel {
589
+ id: string;
590
+ name: string;
591
+ provider: string;
592
+ description: string;
593
+ pricePerSecond: number;
594
+ defaultDurationSeconds: number;
595
+ maxDurationSeconds: number;
596
+ supportsImageInput: boolean;
597
+ available: boolean;
598
+ type: "video";
599
+ }
600
+ interface VideoClientOptions {
601
+ /** EVM wallet private key (hex string starting with 0x) */
602
+ privateKey?: `0x${string}` | string;
603
+ /** API endpoint URL (default: https://bridgenode.cc/api) */
604
+ apiUrl?: string;
605
+ /** Request timeout in milliseconds (default: 300000 — video gen + polling up to 3 min) */
606
+ timeout?: number;
607
+ }
608
+ interface VideoGenerateOptions {
609
+ /** Model ID (default: "xai/grok-imagine-video") */
610
+ model?: "xai/grok-imagine-video" | string;
611
+ /** Optional seed image URL for image-to-video */
612
+ imageUrl?: string;
613
+ /**
614
+ * Virtual Portrait asset ID (`ta_xxxxxx`) — keeps the same AI character
615
+ * across multiple Seedance videos. Enroll via `POST /v1/portrait/enroll`
616
+ * ($0.01 USDC promo, no KYC). **Seedance 2.0 fast/pro only.** Mutually exclusive
617
+ * with `imageUrl`. Real-person likeness is not supported on BlockRun.
618
+ */
619
+ realFaceAssetId?: string;
620
+ /**
621
+ * First-and-last-frame interpolation: a second image that seeds the FINAL
622
+ * frame so the model tweens from `imageUrl` → `lastFrameUrl`. Requires
623
+ * `imageUrl` (the first frame) and a Seedance model
624
+ * (bytedance/seedance-1.5-pro, seedance-2.0, or seedance-2.0-fast).
625
+ * Priced identically to image-to-video. Mutually exclusive with
626
+ * `realFaceAssetId`.
627
+ */
628
+ lastFrameUrl?: string;
629
+ /**
630
+ * Omni / multi-reference: up to 9 reference image URLs for character/style
631
+ * consistency (**Seedance 2.0 only**). Cite them as "image 1", "image 2"
632
+ * in the prompt. Mutually exclusive with `imageUrl` / `lastFrameUrl` /
633
+ * `realFaceAssetId`.
634
+ */
635
+ referenceImageUrls?: string[];
636
+ /** Duration to bill for (defaults to model's default duration) */
637
+ durationSeconds?: number;
638
+ /** Output aspect ratio. Token360 / Seedance only — silently ignored by xAI Grok. */
639
+ aspectRatio?: "adaptive" | "16:9" | "9:16" | "1:1" | "4:3" | "3:4" | "21:9" | "9:21";
640
+ /** Output resolution. Token360 / Seedance only. */
641
+ resolution?: "360p" | "480p" | "540p" | "720p" | "1080p" | "1K" | "2K" | "4K";
642
+ /**
643
+ * Whether the model should produce a synced audio track. Token360 / Seedance
644
+ * only — silently ignored by xAI Grok. When omitted, the gateway defaults to
645
+ * `true` for text-to-video and `false` for image- or face-conditioned
646
+ * generation (the t2v / i2v split that matches Token360's quality profile).
647
+ * Pass an explicit boolean to override. Audio generation may be a paid
648
+ * surcharge upstream, so callers should expose this as a visible toggle.
649
+ */
650
+ generateAudio?: boolean;
651
+ /** Reproducibility seed when supported by the model. */
652
+ seed?: number;
653
+ /** Embed the upstream watermark on the output. Defaults to false at the gateway. */
654
+ watermark?: boolean;
655
+ /** Return the last frame as an image alongside the clip — useful for chaining. */
656
+ returnLastFrame?: boolean;
657
+ }
658
+ interface SearchOptions {
659
+ /** Source types to search (e.g. ["web", "x", "news"]) */
660
+ sources?: string[];
661
+ /** Maximum number of results (default: 10) */
662
+ maxResults?: number;
663
+ /** Start date filter (YYYY-MM-DD) */
664
+ fromDate?: string;
665
+ /** End date filter (YYYY-MM-DD) */
666
+ toDate?: string;
667
+ }
668
+ interface ExaSearchOptions {
669
+ /** Number of results to return (default: 10, max: 100) */
670
+ numResults?: number;
671
+ /** Restrict to a content category */
672
+ category?: "github" | "news" | "research paper" | "linkedin profile" | "personal site" | "tweet" | "financial report" | "pdf" | "company";
673
+ /** Only include pages published after this date (ISO 8601) */
674
+ startPublishedDate?: string;
675
+ /** Only include pages published before this date (ISO 8601) */
676
+ endPublishedDate?: string;
677
+ /** Only search within these domains */
678
+ includeDomains?: string[];
679
+ /** Exclude these domains from results */
680
+ excludeDomains?: string[];
681
+ }
682
+ interface ExaSearchItem {
683
+ id: string;
684
+ url: string;
685
+ title: string;
686
+ publishedDate?: string;
687
+ author?: string;
688
+ score?: number;
689
+ }
690
+ interface ExaSearchResponse {
691
+ requestId: string;
692
+ resolvedSearchType: string;
693
+ results: ExaSearchItem[];
694
+ searchTime: number;
695
+ costDollars: {
696
+ total: number;
697
+ };
698
+ }
699
+ interface ExaAnswerCitation {
700
+ id: string;
701
+ title: string;
702
+ url: string;
703
+ publishedDate?: string;
704
+ favicon?: string;
705
+ }
706
+ interface ExaAnswerResponse {
707
+ requestId: string;
708
+ answer: string;
709
+ citations: ExaAnswerCitation[];
710
+ }
711
+ interface ExaContentItem {
712
+ id: string;
713
+ url: string;
714
+ title: string;
715
+ text: string;
716
+ author?: string | null;
717
+ }
718
+ interface ExaContentsResponse {
719
+ results: ExaContentItem[];
720
+ costDollars: {
721
+ total: number;
722
+ };
723
+ }
724
+ interface ExaFindSimilarOptions {
725
+ /** Number of results to return (default: 10, max: 100) */
726
+ numResults?: number;
727
+ /** Exclude pages from the same domain as the reference URL */
728
+ excludeSourceDomain?: boolean;
729
+ }
730
+ interface OnrampResult {
731
+ /** One-time https://pay.coinbase.com/... URL prefilled for this wallet. */
732
+ url: string;
733
+ }
734
+ type PriceCategory = "crypto" | "fx" | "commodity" | "usstock" | "stocks";
735
+ type StockMarket = "us" | "hk" | "jp" | "kr" | "gb" | "de" | "fr" | "nl" | "ie" | "lu" | "cn" | "ca";
736
+ type BarResolution = "1" | "5" | "15" | "60" | "240" | "D" | "W" | "M";
737
+ type MarketSession = "pre" | "post" | "on";
738
+ interface PricePoint {
739
+ symbol: string;
740
+ price: number;
741
+ publishTime?: number;
742
+ confidence?: number;
743
+ feedId?: string;
744
+ timestamp?: string;
745
+ assetType?: string;
746
+ category?: string;
747
+ source?: string;
748
+ free?: boolean;
749
+ }
750
+ interface PriceBar {
751
+ t?: number;
752
+ o?: number;
753
+ h?: number;
754
+ l?: number;
755
+ c?: number;
756
+ v?: number;
757
+ }
758
+ interface PriceHistoryResponse {
759
+ symbol: string;
760
+ resolution?: string;
761
+ from?: number;
762
+ to?: number;
763
+ bars: PriceBar[];
764
+ source?: string;
765
+ category?: string;
766
+ }
767
+ interface SymbolListResponse {
768
+ symbols: Array<Record<string, unknown>>;
769
+ count?: number;
770
+ }
771
+ interface PriceOptions {
772
+ /** Required when category === "stocks". */
773
+ market?: StockMarket;
774
+ /** Optional US-equity session hint; ignored for non-equity. */
775
+ session?: MarketSession;
776
+ }
777
+ interface HistoryOptions extends PriceOptions {
778
+ /** TradingView-style bar resolution. Defaults to "D". */
779
+ resolution?: BarResolution;
780
+ /** Window start, unix seconds (required). */
781
+ from: number;
782
+ /** Window end, unix seconds. Defaults to now on the backend. */
783
+ to?: number;
784
+ }
785
+ interface ListOptions extends PriceOptions {
786
+ /** Free-text filter (maps to ?q=). */
787
+ query?: string;
788
+ /** Page size, capped at 2000. Defaults to 100. */
789
+ limit?: number;
790
+ }
791
+ interface SearchClientOptions {
792
+ privateKey?: `0x${string}` | string;
793
+ apiUrl?: string;
794
+ timeout?: number;
795
+ }
796
+ interface PriceClientOptions {
797
+ privateKey?: `0x${string}` | string;
798
+ apiUrl?: string;
799
+ timeout?: number;
800
+ /** If false, construction succeeds without a wallet (free endpoints only). */
801
+ requireWallet?: boolean;
802
+ }
803
+ interface SurfClientOptions {
804
+ privateKey?: `0x${string}` | string;
805
+ apiUrl?: string;
806
+ timeout?: number;
807
+ }
808
+ interface PhoneClientOptions {
809
+ /** EVM wallet private key (hex string starting with 0x) */
810
+ privateKey?: `0x${string}` | string;
811
+ /** API endpoint URL (default: https://bridgenode.cc/api) */
812
+ apiUrl?: string;
813
+ /** Request timeout in milliseconds (default: 600000 / 600s; override via BRIDGENODE_CHAT_TIMEOUT env, in seconds) */
814
+ timeout?: number;
815
+ }
816
+ /**
817
+ * Twilio Lookup passthrough — shape comes from upstream and varies by feature
818
+ * (basic vs `line_type_intelligence`, `sim_swap`, `call_forwarding`).
819
+ * Typed as a permissive record so future Twilio fields don't require an SDK release.
820
+ */
821
+ interface PhoneLookupResponse {
822
+ phone_number?: string;
823
+ country_code?: string;
824
+ national_format?: string;
825
+ caller_name?: Record<string, unknown> | null;
826
+ carrier?: Record<string, unknown> | null;
827
+ line_type_intelligence?: Record<string, unknown> | null;
828
+ sim_swap?: Record<string, unknown> | null;
829
+ call_forwarding?: Record<string, unknown> | null;
830
+ /** Pass-through for anything Twilio adds. */
831
+ [key: string]: unknown;
832
+ }
833
+ interface PhoneBuyOptions {
834
+ /** ISO country code, "US" or "CA" (default "US"). */
835
+ country?: "US" | "CA";
836
+ /**
837
+ * Optional 3-digit area-code hint. Availability is not guaranteed — the
838
+ * backend falls back to any number in the country if the area code
839
+ * can't be matched.
840
+ */
841
+ areaCode?: string;
842
+ }
843
+ interface PhoneBuyResponse {
844
+ /** The E.164 number now bound to your wallet. */
845
+ phone_number: string;
846
+ /** ISO-8601 expiry (30 days out from purchase). */
847
+ expires_at: string;
848
+ /** "base" | "solana" — settlement chain. */
849
+ chain: string;
850
+ /** Human-readable note. */
851
+ message?: string;
852
+ /** On-chain payment receipt (tx hash). */
853
+ txHash?: string;
854
+ }
855
+ interface PhoneRenewResponse {
856
+ phone_number: string;
857
+ /** Extended expiry (30 days from previous expiry). */
858
+ expires_at: string;
859
+ txHash?: string;
860
+ }
861
+ interface PhoneNumberRecord {
862
+ phone_number: string;
863
+ chain: string;
864
+ expires_at: string;
865
+ active: boolean;
866
+ }
867
+ interface PhoneListResponse {
868
+ numbers: PhoneNumberRecord[];
869
+ count: number;
870
+ txHash?: string;
871
+ }
872
+ interface PhoneReleaseResponse {
873
+ released: true;
874
+ phone_number: string;
875
+ txHash?: string;
876
+ }
877
+ interface PortraitClientOptions {
878
+ /** EVM wallet private key (hex string starting with 0x) */
879
+ privateKey?: `0x${string}` | string;
880
+ /** API endpoint URL (default: https://bridgenode.cc/api) */
881
+ apiUrl?: string;
882
+ /** Request timeout in milliseconds (default: 600000 / 600s; override via BRIDGENODE_CHAT_TIMEOUT env, in seconds) */
883
+ timeout?: number;
884
+ }
885
+ interface PortraitEnrollOptions {
886
+ /** Display name for the portrait (1–64 chars). */
887
+ name: string;
888
+ /**
889
+ * Public HTTPS URL to a JPG/PNG/WEBP face image (≤10 MB). The gateway fetches
890
+ * it server-side and forwards it to Token360 as multipart — only the URL is sent.
891
+ */
892
+ imageUrl: string;
893
+ }
894
+ /**
895
+ * Response from `POST /v1/portrait/enroll`. The `asset_id` (`ta_xxxxxx`) is what
896
+ * you pass as `realFaceAssetId` on a Seedance 2.0 video generation to keep the
897
+ * same AI character across clips.
898
+ */
899
+ interface PortraitEnrollResponse {
900
+ object: "virtual_portrait";
901
+ /** Token360 asset id (`ta_xxxxxx`) — pass as `realFaceAssetId` in VideoGenerateOptions. */
902
+ asset_id: string;
903
+ /** Token360 asset-group id (internal/debugging). */
904
+ group_id: string;
905
+ name: string;
906
+ /**
907
+ * Persisted thumbnail URL. The gateway mirrors your source image to its own
908
+ * storage when possible (so the listing thumbnail survives a dead source
909
+ * host); falls back to the original URL if mirroring fails. See `mirrored`.
910
+ */
911
+ image_url: string;
912
+ /** The original URL you supplied (before any mirroring). */
913
+ source_image_url?: string;
914
+ /** Whether `image_url` is the gateway-mirrored copy (true) or your original (false). */
915
+ mirrored?: boolean;
916
+ /** ISO-8601 creation timestamp. */
917
+ created_at: string;
918
+ usage: {
919
+ compatible_models: string[];
920
+ how_to_use: string;
921
+ };
922
+ price: {
923
+ amount: string;
924
+ currency: string;
925
+ };
926
+ settlement: {
927
+ success: boolean;
928
+ tx_hash: string | null;
929
+ network: string;
930
+ };
931
+ /** On-chain payment receipt (tx hash), surfaced from the response header. */
932
+ txHash?: string;
933
+ }
934
+ interface BridgeNodeClientOptions {
935
+ privateKey?: `0x${string}` | string;
936
+ apiUrl?: string;
937
+ /** Per-HTTP-call timeout in ms (default 60000). For long-running poll() jobs,
938
+ * set budgetMs in PollOptions instead — this only bounds individual fetches. */
939
+ timeout?: number;
940
+ }
941
+ interface PollOptions {
942
+ /** Total wall-clock budget for the entire submit + poll loop (default 300000 = 5 min). */
943
+ budgetMs?: number;
944
+ /** Sleep between poll attempts (default 5000 = 5 s). */
945
+ intervalMs?: number;
946
+ }
947
+ declare class BridgeNodeError extends Error {
948
+ constructor(message: string);
949
+ }
950
+ declare class PaymentError extends BridgeNodeError {
951
+ constructor(message: string);
952
+ }
953
+ declare class APIError extends BridgeNodeError {
954
+ statusCode: number;
955
+ response?: unknown;
956
+ constructor(message: string, statusCode: number, response?: unknown);
957
+ }
958
+
959
+ /**
960
+ * BlockRun LLM Client - Main SDK entry point.
961
+ *
962
+ * Usage:
963
+ * import { LLMClient } from '@blockrun/llm';
964
+ *
965
+ * // Option 1: Use BASE_CHAIN_WALLET_KEY env var
966
+ * const client = new LLMClient();
967
+ *
968
+ * // Option 2: Pass private key directly
969
+ * const client = new LLMClient({ privateKey: '0x...' });
970
+ *
971
+ * const response = await client.chat('openai/gpt-5.2', 'Hello!');
972
+ * console.log(response);
973
+ */
974
+
975
+ /**
976
+ * BlockRun LLM Gateway Client.
977
+ *
978
+ * Provides access to multiple LLM providers (OpenAI, Anthropic, Google, etc.)
979
+ * with automatic x402 micropayments on Base chain (Mainnet, Chain ID 8453).
980
+ * API base: https://bridgenode.cc/api
981
+ */
982
+ declare class LLMClient {
983
+ static readonly DEFAULT_API_URL = "https://bridgenode.cc/api";
984
+ private account;
985
+ private privateKey;
986
+ private apiUrl;
987
+ private timeout;
988
+ private sessionTotalUsd;
989
+ private sessionCalls;
990
+ private modelPricingCache;
991
+ private modelPricingPromise;
992
+ private preAuthCache;
993
+ private static readonly PRE_AUTH_TTL_MS;
994
+ /**
995
+ * Initialize the BlockRun LLM client.
996
+ *
997
+ * @param options - Client configuration options (optional if BASE_CHAIN_WALLET_KEY env var is set)
998
+ */
999
+ constructor(options?: LLMClientOptions);
1000
+ /**
1001
+ * Simple 1-line chat interface.
1002
+ *
1003
+ * @param model - Model ID (e.g., 'openai/gpt-5.2', 'anthropic/claude-sonnet-4.6')
1004
+ * @param prompt - User message
1005
+ * @param options - Optional chat parameters
1006
+ * @returns Assistant's response text
1007
+ *
1008
+ * @example
1009
+ * const response = await client.chat('gpt-5.2', 'What is the capital of France?');
1010
+ * console.log(response); // 'The capital of France is Paris.'
1011
+ */
1012
+ chat(model: string, prompt: string, options?: ChatOptions): Promise<string>;
1013
+ /**
1014
+ * Smart chat with automatic model routing.
1015
+ *
1016
+ * Uses ClawRouter's 14-dimension rule-based scoring algorithm (<1ms, 100% local)
1017
+ * to select the cheapest model that can handle your request.
1018
+ *
1019
+ * @param prompt - User message
1020
+ * @param options - Optional chat and routing parameters
1021
+ * @returns SmartChatResponse with response text, selected model, and routing metadata
1022
+ *
1023
+ * @example Simple usage (auto profile)
1024
+ * ```ts
1025
+ * const result = await client.smartChat('What is 2+2?');
1026
+ * console.log(result.response); // '4'
1027
+ * console.log(result.model); // 'google/gemini-2.5-flash-lite'
1028
+ * console.log(result.routing.savings); // 0.78 (78% savings)
1029
+ * ```
1030
+ *
1031
+ * @example With routing profile
1032
+ * ```ts
1033
+ * // Eco mode (budget optimized)
1034
+ * const result = await client.smartChat('Explain quantum computing', { routingProfile: 'eco' });
1035
+ *
1036
+ * // Premium mode (best quality)
1037
+ * const result = await client.smartChat('Write a business plan', { routingProfile: 'premium' });
1038
+ * ```
1039
+ */
1040
+ smartChat(prompt: string, options?: SmartChatOptions): Promise<SmartChatResponse>;
1041
+ /**
1042
+ * Get model pricing map (cached).
1043
+ * Fetches from API on first call, then returns cached result.
1044
+ */
1045
+ private getModelPricing;
1046
+ /**
1047
+ * Fetch model pricing from API.
1048
+ *
1049
+ * For flat-billed models (e.g. ZAI GLM-5 family at $0.001/call) the
1050
+ * router still expects per-token rates, so we synthesise an equivalent
1051
+ * per-token price assuming ~1500 total tokens per call. Without this,
1052
+ * flat models would resolve to inputPrice=outputPrice=0 and the router
1053
+ * would treat them as free, biasing routing decisions and reporting
1054
+ * inflated savings %.
1055
+ */
1056
+ private fetchModelPricing;
1057
+ /**
1058
+ * Full chat completion interface (OpenAI-compatible).
1059
+ *
1060
+ * When `fallbackModels` is set, transient failures (timeouts, network
1061
+ * errors, 5xx) on the primary model trigger a retry against the next
1062
+ * model in the list before raising. 4xx errors and PaymentError
1063
+ * propagate immediately — those aren't "swap upstream and retry"
1064
+ * situations. Each fallback hop logs one stderr line.
1065
+ *
1066
+ * @param model - Primary model ID
1067
+ * @param messages - Array of messages with role and content
1068
+ * @param options - Optional completion parameters
1069
+ * @returns ChatResponse object with choices and usage
1070
+ */
1071
+ chatCompletion(model: string, messages: ChatMessage[], options?: ChatCompletionOptions): Promise<ChatResponse>;
1072
+ /**
1073
+ * Write a canonical cost_log entry after a settled x402 payment.
1074
+ * Best-effort: failures here must never break a successful API call.
1075
+ * Mirrors what Franklin's AgentClient writes via src/agent/llm.ts so
1076
+ * cost_log.jsonl is a single source of truth regardless of caller.
1077
+ */
1078
+ private recordCost;
1079
+ /**
1080
+ * Parse the chat response JSON and attach `fallback` metadata when the
1081
+ * gateway signalled a transparent free-fallback substitution. The
1082
+ * gateway sets X-Fallback-Used / X-Fallback-Model / X-Settlement-Skipped
1083
+ * on the response when it served a paid request from a free model
1084
+ * (route.ts createPaymentResponseHeader path). Without surfacing these
1085
+ * to the caller, the user gets a different model than requested with
1086
+ * no visibility — silent quality drop and no clue why the on-chain
1087
+ * balance didn't change.
1088
+ */
1089
+ private parseChatResponse;
1090
+ /**
1091
+ * Make a request with automatic x402 payment handling.
1092
+ */
1093
+ private requestWithPayment;
1094
+ /**
1095
+ * Handle 402 response: parse requirements, sign payment, retry.
1096
+ */
1097
+ private handlePaymentAndRetry;
1098
+ /**
1099
+ * Sign a payment header and return the PAYMENT-SIGNATURE value.
1100
+ * Extracted to share logic between streaming and non-streaming flows.
1101
+ */
1102
+ private signPayment;
1103
+ /**
1104
+ * Streaming chat completion with automatic x402 payment.
1105
+ *
1106
+ * Uses a pre-auth cache so repeat calls to the same model skip the 402
1107
+ * round-trip (~200ms savings). Falls back to the normal 402 flow on cache
1108
+ * miss or if the pre-signed payment is rejected.
1109
+ *
1110
+ * @returns Raw fetch Response with a streaming SSE body.
1111
+ */
1112
+ chatCompletionStream(model: string, messages: ChatMessage[], options?: ChatCompletionOptions): Promise<Response>;
1113
+ /**
1114
+ * Make a request with automatic x402 payment handling, returning raw JSON.
1115
+ * Used for non-ChatResponse endpoints (X/Twitter, search, image edit, etc.).
1116
+ */
1117
+ private requestWithPaymentRaw;
1118
+ /**
1119
+ * Handle 402 response for raw endpoints: parse requirements, sign payment, retry.
1120
+ */
1121
+ private handlePaymentAndRetryRaw;
1122
+ /**
1123
+ * GET with automatic x402 payment handling, returning raw JSON.
1124
+ * Used for Predexon prediction market endpoints that use GET + query params.
1125
+ */
1126
+ private getWithPaymentRaw;
1127
+ /**
1128
+ * Handle 402 response for GET endpoints: parse requirements, sign payment, retry with GET.
1129
+ */
1130
+ private handleGetPaymentAndRetryRaw;
1131
+ /**
1132
+ * Fetch with timeout.
1133
+ */
1134
+ private fetchWithTimeout;
1135
+ /**
1136
+ * List available models with pricing.
1137
+ *
1138
+ * Returns the full `/v1/models` unified catalog (chat + image + music).
1139
+ * The shape preserves backwards compatibility — image/music rows have
1140
+ * `inputPrice = outputPrice = 0` since those fields don't apply, and
1141
+ * their per-call price surfaces via `flatPrice`.
1142
+ */
1143
+ listModels(): Promise<Model[]>;
1144
+ /**
1145
+ * List available image generation models with pricing.
1146
+ *
1147
+ * The dedicated `/v1/images/models` endpoint was deprecated server-side;
1148
+ * image models live in the unified `/v1/models` catalog under
1149
+ * `categories: ["image", ...]`. This method filters that catalog so
1150
+ * existing callers keep working.
1151
+ */
1152
+ listImageModels(): Promise<ImageModel[]>;
1153
+ /**
1154
+ * List all available models (chat, image, music, etc.) with pricing.
1155
+ *
1156
+ * @returns Array of all models with `type` field set from category
1157
+ * (`llm` for chat, `image` / `music` for media). Backwards-compat:
1158
+ * chat models always report `type: "llm"`.
1159
+ */
1160
+ listAllModels(): Promise<(Model | ImageModel)[]>;
1161
+ /**
1162
+ * Internal: fetch the raw `/v1/models` catalog without normalising shape.
1163
+ * Used by listImageModels / listAllModels so each can pick category-
1164
+ * specific fields.
1165
+ */
1166
+ private fetchRawModels;
1167
+ /**
1168
+ * Edit an image using img2img, optionally fusing multiple source images.
1169
+ *
1170
+ * @param prompt - Text description of the desired edit
1171
+ * @param image - A base64 `data:image/...` URI, or an array of 2–4 such URIs
1172
+ * to fuse (image fusion). Caps: `openai/*` up to 4, `google/*` up to 3.
1173
+ * A `mask` cannot be combined with multiple source images.
1174
+ * @param options - Optional edit parameters
1175
+ * @returns ImageResponse with edited image URLs
1176
+ */
1177
+ imageEdit(prompt: string, image: string | string[], options?: ImageEditOptions): Promise<ImageResponse>;
1178
+ /**
1179
+ * Standalone search (web, X/Twitter, news).
1180
+ *
1181
+ * @param query - Search query
1182
+ * @param options - Optional search parameters
1183
+ * @returns SearchResult with summary and citations
1184
+ */
1185
+ search(query: string, options?: SearchOptions): Promise<SearchResult>;
1186
+ /**
1187
+ * Generic Exa endpoint proxy (POST). Useful when you need an Exa API
1188
+ * surface that the typed wrappers below don't expose.
1189
+ *
1190
+ * @param path - Exa endpoint segment: "search" | "find-similar" | "contents" | "answer"
1191
+ * @param body - Request body (see Exa API docs)
1192
+ *
1193
+ * @example
1194
+ * const results = await client.exa("search", { query: "latest AI research", numResults: 5 });
1195
+ */
1196
+ exa(path: string, body: Record<string, unknown>): Promise<Record<string, unknown>>;
1197
+ /**
1198
+ * Neural web search via Exa. Returns semantically relevant URLs and metadata.
1199
+ * Understands meaning, not just keywords. $0.01/call.
1200
+ *
1201
+ * @param query - Natural language search query
1202
+ * @param options - Optional filters (numResults, category, date range, domains)
1203
+ */
1204
+ exaSearch(query: string, options?: ExaSearchOptions): Promise<ExaSearchResponse>;
1205
+ /**
1206
+ * Ask a question and get a cited, synthesized answer grounded in real web sources.
1207
+ * No hallucinations — every claim is backed by a citation. $0.01/call.
1208
+ *
1209
+ * @param query - The question to answer
1210
+ */
1211
+ exaAnswer(query: string): Promise<ExaAnswerResponse>;
1212
+ /**
1213
+ * Fetch full Markdown text content from a list of URLs. $0.002 per URL.
1214
+ * Returns clean text ready to feed into an LLM context window.
1215
+ *
1216
+ * @param urls - Array of URLs to fetch (up to 100)
1217
+ */
1218
+ exaContents(urls: string[]): Promise<ExaContentsResponse>;
1219
+ /**
1220
+ * Find pages semantically similar to a given URL. $0.01/call.
1221
+ * Useful for discovering competitors, alternatives, and related resources.
1222
+ *
1223
+ * @param url - Reference URL
1224
+ * @param options - Optional filters (numResults, excludeSourceDomain)
1225
+ */
1226
+ exaFindSimilar(url: string, options?: ExaFindSimilarOptions): Promise<ExaSearchResponse>;
1227
+ /**
1228
+ * Mint a one-time Coinbase Onramp link to fund this wallet with USDC on Base.
1229
+ *
1230
+ * FREE — the x402 signature only authenticates the wallet (no payment is
1231
+ * charged). Because the funding address must equal the signing wallet, this
1232
+ * mints a `pay.coinbase.com` link prefilled for `address` so a card/bank can
1233
+ * top it up (60+ fiat currencies → Base USDC). Base / USDC only.
1234
+ *
1235
+ * The returned URL is single-use and expires in ~5 minutes — mint it at click
1236
+ * time and never cache it. The funding `address` must match the signing wallet.
1237
+ *
1238
+ * @param address - Destination Base wallet address (0x + 40 hex chars). Must
1239
+ * equal the signing wallet that funds it.
1240
+ * @returns `{ url }` — a one-time https://pay.coinbase.com/... link.
1241
+ *
1242
+ * @example
1243
+ * const { url } = await client.onramp(client.getWalletAddress());
1244
+ * console.log(`Fund your wallet: ${url}`);
1245
+ */
1246
+ onramp(address: string): Promise<OnrampResult>;
1247
+ /**
1248
+ * Get USDC balance on Base mainnet.
1249
+ *
1250
+ * @returns USDC balance as a float (6 decimal places normalized)
1251
+ *
1252
+ * @example
1253
+ * const balance = await client.getBalance();
1254
+ * console.log(`Balance: $${balance.toFixed(2)} USDC`);
1255
+ */
1256
+ getBalance(): Promise<number>;
1257
+ /**
1258
+ * Query Predexon prediction market data (GET endpoints).
1259
+ *
1260
+ * Access real-time data from Polymarket, Kalshi, dFlow, and Binance Futures.
1261
+ * Powered by Predexon. $0.001 per request.
1262
+ *
1263
+ * @param path - Endpoint path, e.g. "polymarket/events", "kalshi/markets/12345"
1264
+ * @param params - Query parameters passed to the endpoint
1265
+ *
1266
+ * @example
1267
+ * const events = await client.pm("polymarket/events");
1268
+ * const market = await client.pm("kalshi/markets/KXBTC-25MAR14");
1269
+ * const results = await client.pm("polymarket/search", { q: "bitcoin" });
1270
+ */
1271
+ pm(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>;
1272
+ /**
1273
+ * Structured query for Predexon prediction market data (POST endpoints).
1274
+ *
1275
+ * For endpoints that require a JSON body, e.g. bulk wallet identity lookup.
1276
+ * Tier 1 = $0.001/call, Tier 2 = $0.005/call.
1277
+ *
1278
+ * @param path - Endpoint path, e.g. "polymarket/wallet/identities"
1279
+ * @param query - JSON body for the structured query
1280
+ *
1281
+ * @example
1282
+ * const batch = await client.pmQuery("polymarket/wallet/identities", {
1283
+ * addresses: ["0xabc...", "0xdef..."],
1284
+ * });
1285
+ */
1286
+ pmQuery(path: string, query: Record<string, unknown>): Promise<Record<string, unknown>>;
1287
+ /** List canonical cross-venue markets (Predexon v2). Tier 1 ($0.001/call).
1288
+ * Filter with venue, status, category, league, event_id, pagination_key. */
1289
+ pmMarkets(params?: Record<string, string>): Promise<Record<string, unknown>>;
1290
+ /** List venue-native executable listings flattened across canonical markets
1291
+ * (Predexon v2). Tier 1 ($0.001/call). */
1292
+ pmListings(params?: Record<string, string>): Promise<Record<string, unknown>>;
1293
+ /** Resolve a canonical Predexon outcome ID to its market context and venue
1294
+ * listings. Tier 1 ($0.001/call). */
1295
+ pmOutcome(predexonId: string): Promise<Record<string, unknown>>;
1296
+ /** Polymarket markets with cursor-based keyset pagination (use pagination_key).
1297
+ * Tier 1 ($0.001/call). */
1298
+ pmPolymarketMarketsKeyset(params?: Record<string, string>): Promise<Record<string, unknown>>;
1299
+ /** Polymarket events with cursor-based keyset pagination (use pagination_key).
1300
+ * Tier 1 ($0.001/call). */
1301
+ pmPolymarketEventsKeyset(params?: Record<string, string>): Promise<Record<string, unknown>>;
1302
+ /** List available sports categories. Tier 1 ($0.001/call). */
1303
+ pmSportsCategories(): Promise<Record<string, unknown>>;
1304
+ /** List sports markets grouped by game. Filter with league, sport_type,
1305
+ * status, venue. Tier 1 ($0.001/call). */
1306
+ pmSportsMarkets(params?: Record<string, string>): Promise<Record<string, unknown>>;
1307
+ /** Fetch identity + profile metadata for one wallet (ENS, Twitter, portfolio,
1308
+ * etc.). Tier 2 ($0.005/call). */
1309
+ pmWalletIdentity(wallet: string): Promise<Record<string, unknown>>;
1310
+ /** Bulk identity lookup for up to 200 wallet addresses (POST). Tier 2 ($0.005/call). */
1311
+ pmWalletIdentities(addresses: string[]): Promise<Record<string, unknown>>;
1312
+ /** Discover wallets connected to a seed address via on-chain transfers and
1313
+ * identity proofs. Tier 2 ($0.005/call). */
1314
+ pmWalletCluster(address: string): Promise<Record<string, unknown>>;
1315
+ /**
1316
+ * Query DefiLlama DeFi data (GET passthrough). Powered by DefiLlama.
1317
+ * $0.005/call for protocols / protocol/{slug} / chains / yields;
1318
+ * $0.001/call for prices/{coins}.
1319
+ *
1320
+ * @param path - e.g. "protocols", "protocol/aave", "chains", "yields",
1321
+ * "prices/coingecko:bitcoin,base:0x..."
1322
+ * @param params - Query parameters passed through to DefiLlama
1323
+ */
1324
+ defi(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>;
1325
+ /** All DeFi protocols with TVL ($0.005/call). */
1326
+ defiProtocols(): Promise<Record<string, unknown>>;
1327
+ /** Single protocol details + historical TVL ($0.005/call). */
1328
+ defiProtocol(slug: string): Promise<Record<string, unknown>>;
1329
+ /** Current TVL of every chain ($0.005/call). */
1330
+ defiChains(): Promise<Record<string, unknown>>;
1331
+ /** Yield pools with APY/TVL ($0.005/call). */
1332
+ defiYields(params?: Record<string, string>): Promise<Record<string, unknown>>;
1333
+ /** Token price lookup ($0.001/call). Coins like "coingecko:bitcoin" or "{chain}:{address}". */
1334
+ defiPrices(coins: string | string[]): Promise<Record<string, unknown>>;
1335
+ /**
1336
+ * Query the 0x Swap / Gasless APIs (free — no x402 payment; BlockRun
1337
+ * takes an on-chain affiliate fee on executed swaps instead).
1338
+ *
1339
+ * @param path - "price", "quote", "gasless/price", "gasless/quote",
1340
+ * "gasless/submit" (POST), "gasless/status/{hash}",
1341
+ * "gasless/approval-tokens", "gasless/chains", "swap/chains"
1342
+ * @param params - Query params (chainId, sellToken, buyToken, sellAmount, taker, ...)
1343
+ * @param body - JSON body — pass to switch to POST (gasless/submit only)
1344
+ */
1345
+ dex(path: string, params?: Record<string, string>, body?: Record<string, unknown>): Promise<Record<string, unknown>>;
1346
+ /** Indicative Permit2 swap price — no commitment (free). */
1347
+ dexPrice(params: Record<string, string>): Promise<Record<string, unknown>>;
1348
+ /** Firm Permit2 swap quote with permit2.eip712 + tx data (free). */
1349
+ dexQuote(params: Record<string, string>): Promise<Record<string, unknown>>;
1350
+ /** Gasless indicative price quote (free). */
1351
+ dexGaslessPrice(params: Record<string, string>): Promise<Record<string, unknown>>;
1352
+ /** Gasless firm quote — returns trade.eip712 to sign (free). */
1353
+ dexGaslessQuote(params: Record<string, string>): Promise<Record<string, unknown>>;
1354
+ /** Submit a signed gasless trade; the 0x relayer pays gas (free). */
1355
+ dexGaslessSubmit(body: Record<string, unknown>): Promise<Record<string, unknown>>;
1356
+ /** Poll a gasless trade's status by tradeHash (free). */
1357
+ dexGaslessStatus(tradeHash: string): Promise<Record<string, unknown>>;
1358
+ /** Chains where the Swap API is supported (free). */
1359
+ dexChains(): Promise<Record<string, unknown>>;
1360
+ /** Chains where the Gasless API is supported (free). */
1361
+ dexGaslessChains(): Promise<Record<string, unknown>>;
1362
+ /**
1363
+ * Call the Modal sandbox compute API (POST passthrough).
1364
+ *
1365
+ * @param path - "sandbox/create" ($0.01 CPU / $0.05 GPU), "sandbox/exec",
1366
+ * "sandbox/status", "sandbox/terminate" ($0.001 each)
1367
+ * @param body - JSON body for the endpoint
1368
+ */
1369
+ modal(path: string, body?: Record<string, unknown>): Promise<Record<string, unknown>>;
1370
+ /** Create a sandboxed compute environment ($0.01 CPU / $0.05 GPU). */
1371
+ modalSandboxCreate(body?: Record<string, unknown>): Promise<Record<string, unknown>>;
1372
+ /** Execute a command in a sandbox; returns stdout/stderr ($0.001). */
1373
+ modalSandboxExec(sandboxId: string, command: string[], extra?: Record<string, unknown>): Promise<Record<string, unknown>>;
1374
+ /** Check a sandbox's status ($0.001). */
1375
+ modalSandboxStatus(sandboxId: string): Promise<Record<string, unknown>>;
1376
+ /** Terminate a sandbox ($0.001). */
1377
+ modalSandboxTerminate(sandboxId: string): Promise<Record<string, unknown>>;
1378
+ /**
1379
+ * Get current session spending.
1380
+ *
1381
+ * @returns Object with totalUsd and calls count
1382
+ *
1383
+ * @example
1384
+ * const spending = client.getSpending();
1385
+ * console.log(`Spent $${spending.totalUsd.toFixed(4)} across ${spending.calls} calls`);
1386
+ */
1387
+ getSpending(): Spending;
1388
+ /**
1389
+ * Get the wallet address being used for payments.
1390
+ */
1391
+ getWalletAddress(): string;
1392
+ }
1393
+
1394
+ /**
1395
+ * BlockRun Image Client - Generate images via x402 micropayments.
1396
+ *
1397
+ * SECURITY NOTE - Private Key Handling:
1398
+ * Your private key NEVER leaves your machine. Here's what happens:
1399
+ * 1. Key stays local - only used to sign an EIP-712 typed data message
1400
+ * 2. Only the SIGNATURE is sent in the PAYMENT-SIGNATURE header
1401
+ * 3. BlockRun verifies the signature on-chain via Coinbase CDP facilitator
1402
+ *
1403
+ * Usage:
1404
+ * import { ImageClient } from '@blockrun/llm';
1405
+ *
1406
+ * const client = new ImageClient({ privateKey: '0x...' });
1407
+ * const result = await client.generate('A cute cat in space');
1408
+ * console.log(result.data[0].url);
1409
+ */
1410
+
1411
+ /**
1412
+ * BlockRun Image Generation Client.
1413
+ *
1414
+ * Generate images using Nano Banana (Google Gemini), DALL-E 3, GPT Image,
1415
+ * or CogView-4 (Zhipu AI) with automatic x402 micropayments on Base chain.
1416
+ */
1417
+ declare class ImageClient {
1418
+ private account;
1419
+ private privateKey;
1420
+ private apiUrl;
1421
+ private timeout;
1422
+ private sessionTotalUsd;
1423
+ private sessionCalls;
1424
+ /**
1425
+ * Initialize the BlockRun Image client.
1426
+ *
1427
+ * @param options - Client configuration options
1428
+ */
1429
+ constructor(options?: ImageClientOptions);
1430
+ /**
1431
+ * Generate an image from a text prompt.
1432
+ *
1433
+ * @param prompt - Text description of the image to generate
1434
+ * @param options - Optional generation parameters
1435
+ * @returns ImageResponse with generated image URLs
1436
+ *
1437
+ * @example
1438
+ * const result = await client.generate('A sunset over mountains');
1439
+ * console.log(result.data[0].url);
1440
+ */
1441
+ generate(prompt: string, options?: ImageGenerateOptions): Promise<ImageResponse>;
1442
+ /**
1443
+ * Edit an image using img2img, optionally fusing multiple source images.
1444
+ *
1445
+ * Pass a single `data:image/...` base64 data URI to edit one image, or an
1446
+ * array of 2–4 data URIs to fuse them (image fusion) — e.g. a reference photo
1447
+ * plus a brand logo. The server caps fusion per provider: `openai/*` accepts
1448
+ * up to 4 source images, `google/*` (Nano Banana) up to 3. A `mask` cannot be
1449
+ * combined with multiple source images.
1450
+ *
1451
+ * Edit-capable models: `openai/gpt-image-1`, `openai/gpt-image-2`,
1452
+ * `google/nano-banana`, `google/nano-banana-pro`.
1453
+ *
1454
+ * @param prompt - Text description of the desired edit
1455
+ * @param image - A base64 `data:image/...` URI, or an array of 2–4 such URIs to fuse
1456
+ * @param options - Optional edit parameters
1457
+ * @returns ImageResponse with edited image URLs
1458
+ *
1459
+ * @example
1460
+ * // Single-image edit
1461
+ * const result = await client.edit('Make it a painting', imageDataUri);
1462
+ *
1463
+ * @example
1464
+ * // Multi-image fusion (Nano Banana): blend a subject with a brand logo
1465
+ * const fused = await client.edit(
1466
+ * 'Place the logo on the t-shirt',
1467
+ * [subjectDataUri, logoDataUri],
1468
+ * { model: 'google/nano-banana' }
1469
+ * );
1470
+ */
1471
+ edit(prompt: string, image: string | string[], options?: ImageEditOptions): Promise<ImageResponse>;
1472
+ /**
1473
+ * List available image generation models with pricing.
1474
+ *
1475
+ * The dedicated `/v1/images/models` endpoint was deprecated server-side;
1476
+ * image models live in the unified `/v1/models` catalog under
1477
+ * `categories: ["image", ...]`. This method filters that catalog so
1478
+ * existing callers keep working.
1479
+ */
1480
+ listImageModels(): Promise<ImageModel[]>;
1481
+ /**
1482
+ * Make a request with automatic x402 payment handling.
1483
+ */
1484
+ private requestWithPayment;
1485
+ /**
1486
+ * Handle 402 response: parse requirements, sign payment, retry.
1487
+ */
1488
+ private handlePaymentAndRetry;
1489
+ /**
1490
+ * Poll the async image generation endpoint until the job reaches a terminal
1491
+ * state (completed/failed). Used when the POST returns 202 + poll_url for
1492
+ * slow models that exceeded the server's inline window.
1493
+ *
1494
+ * Sends the SAME payment header on every poll — the server binds the payer
1495
+ * to the job id and re-verifies on each call. Settlement happens server-side
1496
+ * on the first poll where status=completed.
1497
+ */
1498
+ private pollImageJob;
1499
+ /**
1500
+ * Fetch with timeout.
1501
+ */
1502
+ private fetchWithTimeout;
1503
+ /**
1504
+ * Get the wallet address being used for payments.
1505
+ */
1506
+ getWalletAddress(): string;
1507
+ /**
1508
+ * Get session spending information.
1509
+ */
1510
+ getSpending(): Spending;
1511
+ }
1512
+
1513
+ /**
1514
+ * BlockRun Music Client - Generate music tracks via x402 micropayments.
1515
+ *
1516
+ * SECURITY NOTE - Private Key Handling:
1517
+ * Your private key NEVER leaves your machine. Here's what happens:
1518
+ * 1. Key stays local - only used to sign an EIP-712 typed data message
1519
+ * 2. Only the SIGNATURE is sent in the PAYMENT-SIGNATURE header
1520
+ * 3. BlockRun verifies the signature on-chain via Coinbase CDP facilitator
1521
+ *
1522
+ * Usage:
1523
+ * import { MusicClient } from '@blockrun/llm';
1524
+ *
1525
+ * const client = new MusicClient({ privateKey: '0x...' });
1526
+ * const result = await client.generate('upbeat synthwave with neon pads');
1527
+ * console.log(result.data[0].url); // CDN URL — download within 24h
1528
+ */
1529
+
1530
+ /**
1531
+ * BlockRun Music Generation Client.
1532
+ *
1533
+ * Generate full-length ~3 minute music tracks using MiniMax Music 2.5+
1534
+ * with automatic x402 micropayments on Base chain.
1535
+ *
1536
+ * Pricing: $0.1575/track
1537
+ * Note: Generated URLs expire in ~24h — download immediately if needed.
1538
+ */
1539
+ declare class MusicClient {
1540
+ private account;
1541
+ private privateKey;
1542
+ private apiUrl;
1543
+ private timeout;
1544
+ private sessionTotalUsd;
1545
+ private sessionCalls;
1546
+ constructor(options?: MusicClientOptions);
1547
+ /**
1548
+ * Generate a music track from a text prompt.
1549
+ *
1550
+ * Takes 1-3 minutes. Returns a CDN URL valid for ~24h.
1551
+ *
1552
+ * @param prompt - Music style, mood, or description
1553
+ * @param options - Optional generation parameters
1554
+ * @returns MusicResponse with track URL and metadata
1555
+ *
1556
+ * @example
1557
+ * const result = await client.generate('chill lo-fi beats with piano');
1558
+ * console.log(result.data[0].url); // Download this URL — expires in 24h
1559
+ *
1560
+ * @example With lyrics
1561
+ * const result = await client.generate('upbeat pop song', {
1562
+ * instrumental: false,
1563
+ * lyrics: 'Hello world, this is my song...'
1564
+ * });
1565
+ */
1566
+ generate(prompt: string, options?: MusicGenerateOptions): Promise<MusicResponse>;
1567
+ private requestWithPayment;
1568
+ private handlePaymentAndRetry;
1569
+ private fetchWithTimeout;
1570
+ getWalletAddress(): string;
1571
+ getSpending(): Spending;
1572
+ }
1573
+
1574
+ /**
1575
+ * BlockRun Speech Client - Text-to-speech and sound effects (ElevenLabs) via x402 micropayments.
1576
+ *
1577
+ * SECURITY NOTE - Private Key Handling:
1578
+ * Your private key NEVER leaves your machine. Here's what happens:
1579
+ * 1. Key stays local - only used to sign an EIP-712 typed data message
1580
+ * 2. Only the SIGNATURE is sent in the PAYMENT-SIGNATURE header
1581
+ * 3. BlockRun verifies the signature on-chain via Coinbase CDP facilitator
1582
+ *
1583
+ * Usage:
1584
+ * import { SpeechClient } from '@blockrun/llm';
1585
+ *
1586
+ * const client = new SpeechClient({ privateKey: '0x...' });
1587
+ *
1588
+ * // Text-to-speech (price scales with character count)
1589
+ * const result = await client.generate('Hello from BlockRun!', { voice: 'sarah' });
1590
+ * console.log(result.data[0].url);
1591
+ *
1592
+ * // Sound effects (flat $0.05/generation)
1593
+ * const fx = await client.soundEffect('rain on a tin roof, distant thunder');
1594
+ *
1595
+ * // List voices (free, rate-limited)
1596
+ * const voices = await client.listVoices();
1597
+ *
1598
+ * Models & pricing:
1599
+ * elevenlabs/flash-v2.5 $0.05/1k chars ~75ms latency, 32 languages (default)
1600
+ * elevenlabs/turbo-v2.5 $0.05/1k chars ~250ms latency, 32 languages
1601
+ * elevenlabs/multilingual-v2 $0.10/1k chars long-form narration, 29 languages
1602
+ * elevenlabs/v3 $0.10/1k chars max expressiveness, 70+ languages
1603
+ * elevenlabs/sound-effects $0.05/generation (up to 22s)
1604
+ *
1605
+ * Price = (characters / 1000) x model rate, minimum $0.001/request.
1606
+ */
1607
+
1608
+ /**
1609
+ * BlockRun Speech Client (BlockRun Voice).
1610
+ *
1611
+ * Text-to-speech and sound-effect generation using ElevenLabs models
1612
+ * with automatic x402 micropayments on Base chain.
1613
+ *
1614
+ * TTS pricing scales with input characters; sound effects are flat
1615
+ * $0.05/generation.
1616
+ */
1617
+ declare class SpeechClient {
1618
+ private account;
1619
+ private privateKey;
1620
+ private apiUrl;
1621
+ private timeout;
1622
+ private sessionTotalUsd;
1623
+ private sessionCalls;
1624
+ constructor(options?: SpeechClientOptions);
1625
+ /**
1626
+ * Synthesize speech from text (OpenAI-compatible TTS).
1627
+ *
1628
+ * Price scales with character count: (chars / 1000) x model rate,
1629
+ * minimum $0.001/request. Synthesis is synchronous.
1630
+ *
1631
+ * @param input - Text to synthesize. Per-model character caps apply
1632
+ * (flash/turbo 40k, multilingual-v2 10k, v3 5k).
1633
+ * @param options - Optional model / voice / format / speed
1634
+ * @returns SpeechResponse with audio URL, format, and character count
1635
+ *
1636
+ * @example
1637
+ * const result = await client.generate('Welcome to BlockRun.', { voice: 'george' });
1638
+ * console.log(result.data[0].url); // audio URL (mp3 by default)
1639
+ */
1640
+ generate(input: string, options?: SpeechGenerateOptions): Promise<SpeechResponse>;
1641
+ /** OpenAI-style alias for {@link generate}. */
1642
+ speak(input: string, options?: SpeechGenerateOptions): Promise<SpeechResponse>;
1643
+ /**
1644
+ * Generate a cinematic sound effect from a text prompt.
1645
+ *
1646
+ * Flat $0.05/generation, up to 22 seconds of audio.
1647
+ *
1648
+ * @param text - Sound effect description (max 1000 chars).
1649
+ * E.g. 'rain on a tin roof', 'sci-fi door whoosh'
1650
+ * @param options - Optional duration / prompt influence / format
1651
+ * @returns SpeechResponse with audio URL and format
1652
+ *
1653
+ * @example
1654
+ * const fx = await client.soundEffect('crackling campfire at night');
1655
+ * console.log(fx.data[0].url);
1656
+ */
1657
+ soundEffect(text: string, options?: SoundEffectOptions): Promise<SpeechResponse>;
1658
+ /**
1659
+ * List available voices for TTS (free, rate-limited 60 req/min/IP).
1660
+ *
1661
+ * Pass a voice's `alias` (if present) or `voice_id` as the `voice`
1662
+ * option to {@link generate}.
1663
+ */
1664
+ listVoices(): Promise<VoiceInfo[]>;
1665
+ private requestWithPayment;
1666
+ private handlePaymentAndRetry;
1667
+ private fetchWithTimeout;
1668
+ getWalletAddress(): string;
1669
+ getSpending(): Spending;
1670
+ }
1671
+
1672
+ /**
1673
+ * BlockRun Video Client - Generate short AI videos via x402 micropayments.
1674
+ *
1675
+ * SECURITY NOTE - Private Key Handling:
1676
+ * Your private key NEVER leaves your machine. Here's what happens:
1677
+ * 1. Key stays local - only used to sign an EIP-712 typed data message
1678
+ * 2. Only the SIGNATURE is sent in the PAYMENT-SIGNATURE header
1679
+ * 3. BlockRun verifies the signature on-chain via Coinbase CDP facilitator
1680
+ *
1681
+ * Async flow (client-polled):
1682
+ * POST /v1/videos/generations -> 402 -> sign -> 202 { id, poll_url }
1683
+ * GET /v1/videos/generations/{id} -> loop until status=completed
1684
+ *
1685
+ * The client signs once and replays the same PAYMENT-SIGNATURE on every poll,
1686
+ * re-signing automatically if the 600s authorization window lapses mid-poll.
1687
+ * Settlement happens only on the first completed poll, so upstream failure or
1688
+ * the caller giving up = zero charge.
1689
+ *
1690
+ * Usage:
1691
+ * import { VideoClient } from '@blockrun/llm';
1692
+ *
1693
+ * const client = new VideoClient({ privateKey: '0x...' });
1694
+ * const result = await client.generate('a red apple slowly spinning on a wooden table');
1695
+ * console.log(result.data[0].url); // permanent MP4 URL
1696
+ * console.log(result.data[0].duration_seconds);
1697
+ */
1698
+
1699
+ /**
1700
+ * BlockRun Video Generation Client.
1701
+ *
1702
+ * Supports xAI Grok Imagine Video and ByteDance Seedance (1.5 Pro /
1703
+ * 2.0 Fast / 2.0 Pro) with automatic x402 micropayments on Base.
1704
+ */
1705
+ declare class VideoClient {
1706
+ private account;
1707
+ private privateKey;
1708
+ private apiUrl;
1709
+ private timeout;
1710
+ private sessionTotalUsd;
1711
+ private sessionCalls;
1712
+ constructor(options?: VideoClientOptions);
1713
+ /**
1714
+ * Generate a short video clip from a text prompt (or text + image).
1715
+ *
1716
+ * Submits an async job, then polls until the video is ready. Typical total
1717
+ * wall-time is 60-180s, but upstream status can lag several minutes behind
1718
+ * actual completion. If upstream runs past the budget (default 15min),
1719
+ * throws without charging — the job stays claimable ~48h via poll_url.
1720
+ *
1721
+ * @param prompt - Text description of the video
1722
+ * @param options - Optional generation parameters
1723
+ */
1724
+ generate(prompt: string, options?: VideoGenerateOptions & {
1725
+ budgetMs?: number;
1726
+ }): Promise<VideoResponse>;
1727
+ /**
1728
+ * Generate a video from a standard Seedance `content[]` body.
1729
+ *
1730
+ * Targets the gateway's `POST /v1/videos` endpoint, which accepts the
1731
+ * mainstream multimodal `content` array (text + a single reference image)
1732
+ * used by other Seedance APIs — so callers already holding a
1733
+ * `content[]`-shaped request can submit it unchanged. The gateway validates
1734
+ * unsupported inputs *before* charging, then delegates to the same x402
1735
+ * submit+poll pipeline as {@link generate}.
1736
+ *
1737
+ * Most SDK users should prefer {@link generate} (structured options like
1738
+ * `imageUrl` / `lastFrameUrl`) — this exists for migrating existing
1739
+ * `content[]` payloads with no reshaping.
1740
+ *
1741
+ * @param content - The Seedance `content` array, e.g.
1742
+ * `[{ type: "text", text: "a red apple spinning" }]` or a text item plus
1743
+ * `{ type: "image_url", image_url: { url: "https://..." } }`.
1744
+ * @param options - `model`, `budgetMs`, plus the same camelCase render options
1745
+ * as {@link generate} (`durationSeconds`, `aspectRatio`, `resolution`,
1746
+ * `generateAudio`, `seed`, `watermark`, `returnLastFrame`). These are mapped
1747
+ * to the gateway's snake_case fields for you. Any other keys you pass are
1748
+ * forwarded verbatim (use snake_case for those, since the gateway reads
1749
+ * snake_case only).
1750
+ */
1751
+ generateFromContent(content: Array<Record<string, unknown>>, options?: {
1752
+ model?: string;
1753
+ budgetMs?: number;
1754
+ durationSeconds?: number;
1755
+ aspectRatio?: string;
1756
+ resolution?: string;
1757
+ generateAudio?: boolean;
1758
+ seed?: number;
1759
+ watermark?: boolean;
1760
+ returnLastFrame?: boolean;
1761
+ } & Record<string, unknown>): Promise<VideoResponse>;
1762
+ private submitAndPoll;
1763
+ /**
1764
+ * Parse an x402 challenge response and sign a payment payload for it.
1765
+ * Used for the initial submit AND for mid-poll re-signing after the 600s
1766
+ * authorization window lapses on long polls.
1767
+ */
1768
+ private signFromChallenge;
1769
+ private absolute;
1770
+ private extractPaymentRequired;
1771
+ private throwApiError;
1772
+ private fetchWithTimeout;
1773
+ getWalletAddress(): string;
1774
+ getSpending(): Spending;
1775
+ }
1776
+
1777
+ /**
1778
+ * BlockRun Voice Call Client - AI-powered outbound phone calls via x402 micropayments.
1779
+ *
1780
+ * The AI agent calls a phone number (E.164) and conducts a real-time conversation
1781
+ * based on your 'task' instructions. STT, LLM, and TTS are handled upstream by
1782
+ * Bland.ai; BlockRun handles billing through x402.
1783
+ *
1784
+ * SECURITY NOTE - Private Key Handling:
1785
+ * Your private key NEVER leaves your machine. Here's what happens:
1786
+ * 1. Key stays local - only used to sign an EIP-712 typed data message
1787
+ * 2. Only the SIGNATURE is sent in the PAYMENT-SIGNATURE header
1788
+ * 3. BlockRun verifies the signature on-chain via Coinbase CDP facilitator
1789
+ *
1790
+ * Usage:
1791
+ * import { VoiceClient } from '@blockrun/llm';
1792
+ *
1793
+ * const client = new VoiceClient({ privateKey: '0x...' });
1794
+ *
1795
+ * // Initiate a call (paid, $0.54)
1796
+ * const result = await client.call({
1797
+ * to: '+14155552671',
1798
+ * task: 'You are a friendly assistant calling to confirm a 3pm dentist appointment.',
1799
+ * max_duration: 5,
1800
+ * });
1801
+ * console.log(result.call_id);
1802
+ *
1803
+ * // Poll status, transcript, recording (free)
1804
+ * const status = await client.getStatus(result.call_id);
1805
+ * console.log(status);
1806
+ */
1807
+
1808
+ /**
1809
+ * BlockRun Voice Call Client.
1810
+ *
1811
+ * Initiates AI-powered outbound phone calls with automatic x402 micropayments
1812
+ * on Base chain.
1813
+ *
1814
+ * Pricing: $0.54 per call (regardless of duration up to max_duration).
1815
+ * Status polling is free.
1816
+ */
1817
+ declare class VoiceClient {
1818
+ private account;
1819
+ private privateKey;
1820
+ private apiUrl;
1821
+ private timeout;
1822
+ private sessionTotalUsd;
1823
+ private sessionCalls;
1824
+ constructor(options?: VoiceClientOptions);
1825
+ /**
1826
+ * Initiate an AI-powered outbound phone call.
1827
+ *
1828
+ * Pricing: $0.54 per call. Returns immediately once the call is queued —
1829
+ * poll getStatus() for transcript and recording.
1830
+ *
1831
+ * @example
1832
+ * const r = await client.call({
1833
+ * to: '+14155552671',
1834
+ * task: 'Confirm the user wants to reschedule to Tuesday 2pm.',
1835
+ * voice: 'maya',
1836
+ * max_duration: 3,
1837
+ * });
1838
+ */
1839
+ call(options: CallOptions): Promise<CallInitiatedResponse>;
1840
+ /**
1841
+ * Poll the status of an in-progress or completed call. Free — no payment.
1842
+ *
1843
+ * Returns Bland.ai's full call record: status, transcript, recording URL, etc.
1844
+ * Most fields populate only once the call ends.
1845
+ */
1846
+ getStatus(callId: string): Promise<CallStatusResponse>;
1847
+ private requestWithPayment;
1848
+ private handlePaymentAndRetry;
1849
+ private fetchWithTimeout;
1850
+ getWalletAddress(): string;
1851
+ getSpending(): Spending;
1852
+ }
1853
+
1854
+ /**
1855
+ * BlockRun Phone Client — Twilio-backed phone lookup + number provisioning via x402.
1856
+ *
1857
+ * Endpoints (all under /v1/phone/...):
1858
+ * POST /lookup $0.01 Carrier + line-type lookup
1859
+ * POST /lookup/fraud $0.05 Carrier + SIM-swap / call-forwarding signals
1860
+ * POST /numbers/buy $5.00 Provision a US/CA number (30-day lease, bound to wallet)
1861
+ * POST /numbers/renew $5.00 Extend an existing number by 30 days
1862
+ * POST /numbers/list $0.001 List the wallet's active numbers
1863
+ * POST /numbers/release free Release a provisioned number (still flows through x402
1864
+ * so the backend can verify wallet identity)
1865
+ *
1866
+ * After buying a number you can use it as the `from` caller ID in VoiceClient.call().
1867
+ *
1868
+ * SECURITY NOTE — your private key never leaves your machine. Only EIP-712
1869
+ * signatures are sent in the PAYMENT-SIGNATURE header.
1870
+ *
1871
+ * @example
1872
+ * import { PhoneClient } from '@blockrun/llm';
1873
+ *
1874
+ * const client = new PhoneClient({ privateKey: '0x...' });
1875
+ *
1876
+ * // Lookup a number
1877
+ * const info = await client.lookup('+14155552671');
1878
+ *
1879
+ * // Buy a number (US, optional area code)
1880
+ * const bought = await client.buyNumber({ country: 'US', areaCode: '415' });
1881
+ * console.log(bought.phone_number, bought.expires_at);
1882
+ *
1883
+ * // List your active numbers
1884
+ * console.log(await client.listNumbers());
1885
+ *
1886
+ * // Renew / release
1887
+ * await client.renewNumber(bought.phone_number);
1888
+ * await client.releaseNumber(bought.phone_number);
1889
+ */
1890
+
1891
+ /** Per-endpoint price in USD — mirrors the backend's `PHONE_PRICES`. */
1892
+ declare const PHONE_PRICES: Readonly<Record<string, number>>;
1893
+ /**
1894
+ * BlockRun Phone Client.
1895
+ *
1896
+ * Wraps the `/v1/phone/*` x402 endpoints — phone-number lookup (carrier + fraud)
1897
+ * and provisioning of the caller-ID numbers required by VoiceClient.call().
1898
+ */
1899
+ declare class PhoneClient {
1900
+ private account;
1901
+ private privateKey;
1902
+ private apiUrl;
1903
+ private timeout;
1904
+ private sessionTotalUsd;
1905
+ private sessionCalls;
1906
+ constructor(options?: PhoneClientOptions);
1907
+ /** EVM wallet address used for payments. */
1908
+ getWalletAddress(): string;
1909
+ /** Session-cumulative USD spend + call count across this client instance. */
1910
+ getSpending(): Spending;
1911
+ /**
1912
+ * Carrier + line-type lookup. ~$0.01.
1913
+ *
1914
+ * @param phoneNumber E.164 number (e.g. "+14155552671").
1915
+ */
1916
+ lookup(phoneNumber: string): Promise<PhoneLookupResponse>;
1917
+ /**
1918
+ * Lookup + fraud signals (SIM swap, call forwarding). ~$0.05.
1919
+ *
1920
+ * @param phoneNumber E.164 number.
1921
+ */
1922
+ lookupFraud(phoneNumber: string): Promise<PhoneLookupResponse>;
1923
+ /**
1924
+ * Provision a dedicated phone number for 30 days. $5.00.
1925
+ *
1926
+ * Payment is settled only after Twilio confirms the purchase, so failed
1927
+ * buys never charge your wallet.
1928
+ *
1929
+ * @param options.country ISO country code, "US" or "CA" (default "US").
1930
+ * @param options.areaCode Optional 3-digit area-code hint. Availability is
1931
+ * not guaranteed — the backend falls back to any number in the country if
1932
+ * the area code can't be matched.
1933
+ */
1934
+ buyNumber(options?: PhoneBuyOptions): Promise<PhoneBuyResponse>;
1935
+ /**
1936
+ * Extend an existing provisioned number by 30 days. $5.00.
1937
+ *
1938
+ * @throws {APIError} 403 when the wallet doesn't own the number or it has expired.
1939
+ */
1940
+ renewNumber(phoneNumber: string): Promise<PhoneRenewResponse>;
1941
+ /** List the wallet's active phone numbers. ~$0.001. */
1942
+ listNumbers(): Promise<PhoneListResponse>;
1943
+ /**
1944
+ * Release a provisioned number back to the Twilio pool. Free, but still
1945
+ * flows through x402 so the backend can verify ownership.
1946
+ */
1947
+ releaseNumber(phoneNumber: string): Promise<PhoneReleaseResponse>;
1948
+ private request;
1949
+ private handlePaymentAndRetry;
1950
+ private unwrap;
1951
+ private fetchWithTimeout;
1952
+ }
1953
+
1954
+ /**
1955
+ * BlockRun Portrait Client — enroll a Virtual Portrait via x402.
1956
+ *
1957
+ * Wraps `POST /v1/portrait/enroll` ($0.01 USDC promo, no KYC). You upload a face image
1958
+ * by URL and get back a Token360 asset id (`ta_xxxxxx`). Pass that id as
1959
+ * `realFaceAssetId` on a Seedance 2.0 video generation (VideoClient.generate)
1960
+ * to keep the same AI character across clips.
1961
+ *
1962
+ * SECURITY NOTE — your private key never leaves your machine. Only EIP-712
1963
+ * signatures are sent in the PAYMENT-SIGNATURE header.
1964
+ *
1965
+ * @example
1966
+ * import { PortraitClient, VideoClient } from '@blockrun/llm';
1967
+ *
1968
+ * const portraits = new PortraitClient({ privateKey: '0x...' });
1969
+ * const { asset_id } = await portraits.enroll({
1970
+ * name: 'Spokesperson',
1971
+ * imageUrl: 'https://example.com/face.jpg',
1972
+ * });
1973
+ *
1974
+ * const video = new VideoClient({ privateKey: '0x...' });
1975
+ * const clip = await video.generate('she waves and smiles', {
1976
+ * model: 'bytedance/seedance-2.0-fast',
1977
+ * realFaceAssetId: asset_id,
1978
+ * });
1979
+ */
1980
+
1981
+ /**
1982
+ * Flat enrollment price in USD — mirrors the backend's `ENROLLMENT_PRICE_USD`.
1983
+ * Currently $0.01 (promotional, parity with RealFace). The authoritative price
1984
+ * is whatever the gateway quotes in the 402; this constant is informational.
1985
+ */
1986
+ declare const PORTRAIT_ENROLLMENT_PRICE_USD = 0.01;
1987
+ /**
1988
+ * BlockRun Portrait Client.
1989
+ *
1990
+ * Enrolls a Virtual Portrait from a face image URL and returns the `ta_xxxxxx`
1991
+ * asset id consumed by Seedance 2.0 video generation. Real-person likeness is
1992
+ * not supported on BlockRun — enrolled portraits are AI characters.
1993
+ */
1994
+ declare class PortraitClient {
1995
+ private account;
1996
+ private privateKey;
1997
+ private apiUrl;
1998
+ private timeout;
1999
+ private sessionTotalUsd;
2000
+ private sessionCalls;
2001
+ constructor(options?: PortraitClientOptions);
2002
+ /** EVM wallet address used for payments. */
2003
+ getWalletAddress(): string;
2004
+ /** Session-cumulative USD spend + call count across this client instance. */
2005
+ getSpending(): Spending;
2006
+ /**
2007
+ * Enroll a Virtual Portrait from a face image URL. $0.01 (promo).
2008
+ *
2009
+ * Payment is settled only after Token360 confirms the enrollment, so failed
2010
+ * enrollments never charge your wallet.
2011
+ *
2012
+ * @param options.name Display name (1–64 chars).
2013
+ * @param options.imageUrl Public HTTPS URL to a JPG/PNG/WEBP image (≤10 MB).
2014
+ * @returns The enrollment record, including `asset_id` (`ta_xxxxxx`).
2015
+ */
2016
+ enroll(options: PortraitEnrollOptions): Promise<PortraitEnrollResponse>;
2017
+ private request;
2018
+ private handlePaymentAndRetry;
2019
+ private unwrap;
2020
+ private fetchWithTimeout;
2021
+ }
2022
+
2023
+ /**
2024
+ * BlockRun Search Client - Standalone Grok Live Search via x402 micropayments.
2025
+ *
2026
+ * Backend endpoint: POST /api/v1/search
2027
+ * Pricing: $0.025/source + margin (default 10 sources ≈ $0.26).
2028
+ *
2029
+ * Usage:
2030
+ * import { SearchClient } from "@bridgenode/llm";
2031
+ *
2032
+ * const client = new SearchClient({ privateKey: "0x..." });
2033
+ * const result = await client.search("Latest news on x402 adoption", {
2034
+ * sources: ["x", "web"],
2035
+ * });
2036
+ * console.log(result.summary);
2037
+ */
2038
+
2039
+ declare class SearchClient {
2040
+ private account;
2041
+ private privateKey;
2042
+ private apiUrl;
2043
+ private timeout;
2044
+ constructor(options?: SearchClientOptions);
2045
+ search(query: string, options?: SearchOptions): Promise<SearchResult>;
2046
+ private requestWithPayment;
2047
+ private handlePaymentAndRetry;
2048
+ private fetchWithTimeout;
2049
+ getWalletAddress(): string;
2050
+ }
2051
+
2052
+ /**
2053
+ * BlockRun Price Client - Pyth-backed market data via x402.
2054
+ *
2055
+ * Payment gating mirrors CategoryConfig.paid in the backend:
2056
+ * crypto, fx, commodity → FREE across price + history + list
2057
+ * usstock, stocks/{market} → PAID for price + history; list always free
2058
+ *
2059
+ * Usage:
2060
+ * import { PriceClient } from "@bridgenode/llm";
2061
+ *
2062
+ * const p = new PriceClient({ privateKey: "0x..." });
2063
+ * const btc = await p.price("crypto", "BTC-USD");
2064
+ * const aapl = await p.price("stocks", "AAPL", { market: "us" });
2065
+ * const bars = await p.history("stocks", "AAPL", { market: "us",
2066
+ * from: 1700000000, to: 1710000000 });
2067
+ * const symbols = await p.listSymbols("crypto", { query: "sol" });
2068
+ */
2069
+
2070
+ declare class PriceClient {
2071
+ private account;
2072
+ private privateKey;
2073
+ private apiUrl;
2074
+ private timeout;
2075
+ constructor(options?: PriceClientOptions);
2076
+ price(category: PriceCategory, symbol: string, options?: PriceOptions): Promise<PricePoint>;
2077
+ history(category: PriceCategory, symbol: string, options: HistoryOptions): Promise<PriceHistoryResponse>;
2078
+ listSymbols(category: PriceCategory, options?: ListOptions): Promise<SymbolListResponse>;
2079
+ getWalletAddress(): string | null;
2080
+ private getWithPayment;
2081
+ private payAndRetry;
2082
+ private fetchWithTimeout;
2083
+ }
2084
+
2085
+ /**
2086
+ * BlockRun Surf Client — pay-per-call crypto data via x402 micropayments.
2087
+ *
2088
+ * Surf aggregates 84+ endpoints across CEX/DEX market data, on-chain SQL,
2089
+ * wallet intelligence, prediction markets, social analytics, and news under
2090
+ * a single OpenAPI surface mounted at `/api/v1/surf/*`.
2091
+ *
2092
+ * Pricing tiers (flat per-call, USDC on Base):
2093
+ * Tier 1 — $0.001/call (prices, rankings, lists, news, simple reads)
2094
+ * Tier 2 — $0.005/call (order books, candles, search, wallet details)
2095
+ * Tier 3 — $0.020/call (on-chain SQL, schema introspection, chat)
2096
+ *
2097
+ * Because the catalog is large and evolving, this client deliberately
2098
+ * exposes a thin `get` / `post` pair instead of 84 typed wrappers. Pass the
2099
+ * path (with or without the `/v1/surf` prefix) and either query params or a
2100
+ * JSON body. The full endpoint inventory lives at
2101
+ * https://bridgenode.cc/marketplace/surf.
2102
+ *
2103
+ * Usage:
2104
+ * import { SurfClient } from "@bridgenode/llm";
2105
+ *
2106
+ * const surf = new SurfClient({ privateKey: "0x..." });
2107
+ *
2108
+ * // Tier 1 — token price ($0.001)
2109
+ * const btc = await surf.get("/market/price", { symbol: "BTC" });
2110
+ *
2111
+ * // Tier 2 — order book ($0.005)
2112
+ * const book = await surf.get("/exchange/depth", {
2113
+ * exchange: "binance",
2114
+ * symbol: "BTC-USDT",
2115
+ * });
2116
+ *
2117
+ * // Tier 3 — raw on-chain SQL ($0.020)
2118
+ * const rows = await surf.post("/onchain/sql", {
2119
+ * query: "SELECT block_number FROM ethereum.blocks ORDER BY block_number DESC LIMIT 5",
2120
+ * });
2121
+ *
2122
+ * // Typed responses via generic
2123
+ * type Price = { symbol: string; price: number; timestamp: string };
2124
+ * const typed = await surf.get<Price>("/market/price", { symbol: "ETH" });
2125
+ */
2126
+
2127
+ type QueryValue$1 = string | number | boolean | null | undefined;
2128
+ type QueryParams$1 = Record<string, QueryValue$1 | QueryValue$1[]>;
2129
+ declare class SurfClient {
2130
+ private account;
2131
+ private privateKey;
2132
+ private apiUrl;
2133
+ private timeout;
2134
+ constructor(options?: SurfClientOptions);
2135
+ /**
2136
+ * GET a Surf endpoint. `path` is everything after `/v1/surf` (a leading
2137
+ * `/v1/surf` is tolerated and stripped). Query params are URL-encoded;
2138
+ * arrays become repeated keys (`?a=1&a=2`).
2139
+ */
2140
+ get<T = unknown>(path: string, params?: QueryParams$1): Promise<T>;
2141
+ /**
2142
+ * POST a Surf endpoint with a JSON body. Same path normalization as `get`.
2143
+ */
2144
+ post<T = unknown>(path: string, body?: Record<string, unknown>): Promise<T>;
2145
+ private buildUrl;
2146
+ private requestWithPayment;
2147
+ private handlePaymentAndRetry;
2148
+ private throwApiError;
2149
+ private fetchWithTimeout;
2150
+ getWalletAddress(): string;
2151
+ }
2152
+
2153
+ /**
2154
+ * BlockRun RPC Client - Multi-chain JSON-RPC (Tatum gateway) via x402 micropayments.
2155
+ *
2156
+ * One endpoint, 40+ chains: Ethereum, Base, Solana, Polygon, BSC, Arbitrum,
2157
+ * Optimism, Avalanche, Bitcoin, Sui, and more. Standard JSON-RPC 2.0
2158
+ * passthrough — no API key, pay-per-call in USDC.
2159
+ *
2160
+ * SECURITY NOTE - Private Key Handling:
2161
+ * Your private key NEVER leaves your machine. Here's what happens:
2162
+ * 1. Key stays local - only used to sign an EIP-712 typed data message
2163
+ * 2. Only the SIGNATURE is sent in the PAYMENT-SIGNATURE header
2164
+ * 3. BlockRun verifies the signature on-chain via Coinbase CDP facilitator
2165
+ *
2166
+ * Usage:
2167
+ * import { RpcClient } from '@blockrun/llm';
2168
+ *
2169
+ * const client = new RpcClient({ privateKey: '0x...' });
2170
+ *
2171
+ * // EVM chains speak eth_* JSON-RPC
2172
+ * const block = await client.call('ethereum', 'eth_blockNumber');
2173
+ * console.log(block.result); // e.g. "0x1499f7c"
2174
+ *
2175
+ * const balance = await client.call('base', 'eth_getBalance', [
2176
+ * '0x4200000000000000000000000000000000000006',
2177
+ * 'latest',
2178
+ * ]);
2179
+ *
2180
+ * // Non-EVM chains speak their native JSON-RPC
2181
+ * const slot = await client.call('solana', 'getSlot');
2182
+ *
2183
+ * // Batch: one payment, per-element pricing ($0.002 x N)
2184
+ * const out = await client.batch('polygon', [
2185
+ * { method: 'eth_blockNumber' },
2186
+ * { method: 'eth_gasPrice' },
2187
+ * ]);
2188
+ *
2189
+ * Pricing:
2190
+ * Flat $0.002 per JSON-RPC call; a batch charges per element.
2191
+ *
2192
+ * Networks:
2193
+ * 40 curated chains (see SUPPORTED_NETWORKS) plus common aliases
2194
+ * (eth, arb, op, matic, bnb, avax, sol, btc, xrp, dot, ...). Unknown but
2195
+ * well-formed slugs fall through to a generic `{slug}-mainnet` gateway
2196
+ * attempt, so new Tatum chains work without an SDK update.
2197
+ */
2198
+
2199
+ /**
2200
+ * Flat price per JSON-RPC call (batch = N x this). Informational only —
2201
+ * the actual quote always comes from the 402 challenge.
2202
+ */
2203
+ declare const RPC_PRICE_USD = 0.002;
2204
+ /**
2205
+ * Curated chains accepted by /v1/rpc/{network}. Mirrors the backend chain
2206
+ * registry (verified live 2026-06-07). EVM chains use eth_* JSON-RPC;
2207
+ * non-EVM (Solana / UTXO / NEAR / Sui / XRP Ledger / Polkadot) speak their
2208
+ * own JSON-RPC dialect.
2209
+ */
2210
+ declare const SUPPORTED_NETWORKS: readonly ["ethereum", "base", "arbitrum", "arbitrum-nova", "optimism", "polygon", "bsc", "avalanche", "fantom", "cronos", "celo", "gnosis", "zksync", "berachain", "unichain", "monad", "chiliz", "moonbeam", "aurora", "flare", "oasis", "kaia", "sonic", "xdc", "abstract", "hyperevm", "plume", "ronin", "rootstock", "solana", "bitcoin", "litecoin", "dogecoin", "bitcoin-cash", "near", "sui", "ripple", "polkadot", "kusama", "zcash"];
2211
+ type RpcNetwork = (typeof SUPPORTED_NETWORKS)[number] | (string & {});
2212
+ /** Common short names the gateway also accepts (resolved server-side). */
2213
+ declare const NETWORK_ALIASES: Record<string, string>;
2214
+ /**
2215
+ * BlockRun Multi-chain RPC Client.
2216
+ *
2217
+ * Standard JSON-RPC 2.0 access to 40+ chains through BlockRun's Tatum
2218
+ * gateway with automatic x402 micropayments on Base chain.
2219
+ *
2220
+ * Flat $0.002 per call; a JSON-RPC batch charges per element.
2221
+ */
2222
+ declare class RpcClient {
2223
+ private account;
2224
+ private privateKey;
2225
+ private apiUrl;
2226
+ private timeout;
2227
+ private sessionTotalUsd;
2228
+ private sessionCalls;
2229
+ constructor(options?: RpcClientOptions);
2230
+ /**
2231
+ * Make a single JSON-RPC 2.0 call. Flat $0.002.
2232
+ *
2233
+ * @param network - Chain name (e.g. "ethereum", "base", "solana") or a
2234
+ * common alias ("eth", "sol", "matic", ...). See
2235
+ * SUPPORTED_NETWORKS / NETWORK_ALIASES.
2236
+ * @param method - Chain RPC method, e.g. "eth_blockNumber", "eth_call",
2237
+ * "eth_getBalance" (EVM) or "getSlot", "getAccountInfo"
2238
+ * (Solana).
2239
+ * @param params - Method-specific params array (optional).
2240
+ * @returns RpcResponse with `result` (or JSON-RPC `error`), plus
2241
+ * `network`, `cacheHit` and `txHash` metadata.
2242
+ *
2243
+ * @example
2244
+ * const block = await client.call('ethereum', 'eth_blockNumber');
2245
+ * console.log(parseInt(block.result as string, 16));
2246
+ */
2247
+ call<T = unknown>(network: RpcNetwork, method: string, params?: unknown[]): Promise<RpcResponse<T>>;
2248
+ /**
2249
+ * Make a JSON-RPC 2.0 batch call. Priced per element ($0.002 x N).
2250
+ *
2251
+ * @param network - Chain name or alias (see {@link call}).
2252
+ * @param requests - Requests, each with a `method` and optional
2253
+ * `params` / `id`. `jsonrpc` and missing ids are
2254
+ * filled in automatically.
2255
+ * @returns Array of RpcResponse, in upstream order.
2256
+ *
2257
+ * @example
2258
+ * const out = await client.batch('base', [
2259
+ * { method: 'eth_blockNumber' },
2260
+ * { method: 'eth_gasPrice' },
2261
+ * ]);
2262
+ */
2263
+ batch(network: RpcNetwork, requests: RpcBatchRequest[]): Promise<RpcResponse[]>;
2264
+ private toResponse;
2265
+ private requestWithPayment;
2266
+ private handlePaymentAndRetry;
2267
+ private fetchWithTimeout;
2268
+ getWalletAddress(): string;
2269
+ getSpending(): Spending;
2270
+ }
2271
+
2272
+ /**
2273
+ * BlockrunClient — the x402-paying HTTP primitive for the BridgeNode gateway.
2274
+ *
2275
+ * This is the **primitive** that every BlockRun API surface composes on top of:
2276
+ * a wallet, an x402 401-sign-replay handler, and four call shapes (get, post,
2277
+ * poll, stream). Per-API classes (LLMClient, ImageClient, SurfClient, …) are
2278
+ * being collapsed into Claude Code skills that drive this client directly.
2279
+ *
2280
+ * Why one primitive instead of one client per API surface:
2281
+ * - Every BlockRun endpoint pays the same way (USDC via x402 on Base/Solana)
2282
+ * - ~30-40 % of each existing client class is identical boilerplate
2283
+ * - New API surfaces should ship as a skill (markdown) + path, not as a
2284
+ * new TypeScript class + npm release
2285
+ *
2286
+ * Four call shapes:
2287
+ * client.get<T>(path, params?) — sync GET, e.g. /v1/surf/market/price
2288
+ * client.post<T>(path, body?) — sync POST, e.g. /v1/surf/onchain/sql
2289
+ * client.poll<T>(path, body?, { budgetMs }) — submit + poll, e.g. /v1/videos/generations
2290
+ * client.stream<T>(path, body?) — SSE iterator, e.g. /v1/chat/completions
2291
+ *
2292
+ * Usage:
2293
+ * import { BlockrunClient } from "@bridgenode/llm";
2294
+ *
2295
+ * const br = new BlockrunClient({ privateKey: "0x..." });
2296
+ *
2297
+ * // Surf endpoint (Tier 1, $0.001)
2298
+ * const btc = await br.get("/v1/surf/market/price", { symbol: "BTC" });
2299
+ *
2300
+ * // Raw on-chain SQL (Tier 3, $0.020)
2301
+ * const rows = await br.post("/v1/surf/onchain/sql", {
2302
+ * query: "SELECT block_number FROM ethereum.blocks ORDER BY block_number DESC LIMIT 1",
2303
+ * });
2304
+ *
2305
+ * // Long-running video generation (submit + poll, paid on success)
2306
+ * const video = await br.poll("/v1/videos/generations", {
2307
+ * model: "xai/grok-imagine-video",
2308
+ * prompt: "a red apple spinning",
2309
+ * });
2310
+ *
2311
+ * // Streaming chat
2312
+ * for await (const chunk of br.stream("/v1/chat/completions", {
2313
+ * model: "anthropic/claude-sonnet-4-6",
2314
+ * messages: [{ role: "user", content: "Hi" }],
2315
+ * stream: true,
2316
+ * })) {
2317
+ * process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
2318
+ * }
2319
+ */
2320
+
2321
+ type QueryValue = string | number | boolean | null | undefined;
2322
+ type QueryParams = Record<string, QueryValue | QueryValue[]>;
2323
+ /**
2324
+ * The x402-paying HTTP primitive for the BridgeNode gateway.
2325
+ *
2326
+ * One instance, one wallet, all endpoints. The four call shapes (get, post,
2327
+ * poll, stream) cover every endpoint type the gateway exposes.
2328
+ */
2329
+ declare class BlockrunClient {
2330
+ private account;
2331
+ private privateKey;
2332
+ private apiUrl;
2333
+ private timeout;
2334
+ private sessionTotalUsd;
2335
+ private sessionCalls;
2336
+ constructor(options?: BridgeNodeClientOptions);
2337
+ /**
2338
+ * GET a BlockRun endpoint. `path` is everything after `/api` (a leading
2339
+ * `/api` is tolerated and stripped). Query params are URL-encoded; arrays
2340
+ * become repeated keys (`?a=1&a=2`); undefined/null are dropped.
2341
+ */
2342
+ get<T = unknown>(path: string, params?: QueryParams): Promise<T>;
2343
+ /**
2344
+ * POST a BlockRun endpoint with a JSON body.
2345
+ */
2346
+ post<T = unknown>(path: string, body?: Record<string, unknown>): Promise<T>;
2347
+ /**
2348
+ * Submit a long-running job and poll until it completes.
2349
+ *
2350
+ * Pattern: submit → 402 → sign → 202 `{ id, poll_url, status }` → loop GET
2351
+ * the poll_url with the SAME `PAYMENT-SIGNATURE` until status=completed (or
2352
+ * deadline exceeded). Settlement happens only when upstream returns 200 +
2353
+ * completed — upstream failure or caller giving up = no charge.
2354
+ *
2355
+ * If the gateway returns 200 directly on submit (no async surface), this
2356
+ * short-circuits and returns the body. Most long-running endpoints (image,
2357
+ * video, music, voice) return 202 with a poll_url.
2358
+ */
2359
+ poll<T = unknown>(path: string, body?: Record<string, unknown>, options?: PollOptions): Promise<T>;
2360
+ /**
2361
+ * Stream a Server-Sent Events endpoint.
2362
+ *
2363
+ * Yields each `data: …` line parsed as JSON. Stops when the upstream emits
2364
+ * `data: [DONE]` or closes the connection. Caller is responsible for typing
2365
+ * the chunk shape; pass a generic for typed yields.
2366
+ *
2367
+ * Example — streaming chat:
2368
+ * for await (const chunk of br.stream<ChatChunk>("/v1/chat/completions", {
2369
+ * model: "anthropic/claude-sonnet-4-6",
2370
+ * messages: [{ role: "user", content: "Hi" }],
2371
+ * stream: true,
2372
+ * })) {
2373
+ * process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
2374
+ * }
2375
+ */
2376
+ stream<T = unknown>(path: string, body?: Record<string, unknown>): AsyncGenerator<T, void, undefined>;
2377
+ private buildUrl;
2378
+ private absolute;
2379
+ private requestWithPayment;
2380
+ private handlePaymentAndRetry;
2381
+ /**
2382
+ * Read a 402 response's payment requirements (header or body), then sign and
2383
+ * return the base64 PAYMENT-SIGNATURE payload. Also records the cost-to-be
2384
+ * onto the response context (settled on `recordSpending`).
2385
+ */
2386
+ private signFrom402;
2387
+ /** Accumulates the most-recent pending cost; settled by recordSpending. */
2388
+ private pendingCostUsd;
2389
+ private recordSpending;
2390
+ private throwApiError;
2391
+ private fetchWithTimeout;
2392
+ getWalletAddress(): string;
2393
+ getSpending(): Spending;
2394
+ }
2395
+
2396
+ /**
2397
+ * x402 Payment Protocol v2 Implementation for BlockRun.
2398
+ *
2399
+ * This module handles creating signed payment payloads for the x402 v2 protocol.
2400
+ * The private key is used ONLY for local signing and NEVER leaves the client.
2401
+ */
2402
+
2403
+ declare const BASE_CHAIN_ID = 8453;
2404
+ declare const USDC_BASE: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
2405
+ declare const SOLANA_NETWORK = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
2406
+ declare const USDC_SOLANA = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
2407
+ interface CreatePaymentOptions {
2408
+ resourceUrl?: string;
2409
+ resourceDescription?: string;
2410
+ maxTimeoutSeconds?: number;
2411
+ extra?: {
2412
+ name?: string;
2413
+ version?: string;
2414
+ };
2415
+ extensions?: Record<string, unknown>;
2416
+ }
2417
+ /**
2418
+ * Create a signed x402 v2 payment payload.
2419
+ *
2420
+ * @param privateKey - Hex-encoded private key
2421
+ * @param fromAddress - Sender wallet address
2422
+ * @param recipient - Payment recipient address
2423
+ * @param amount - Amount in micro USDC (6 decimals)
2424
+ * @param network - Network identifier (default: eip155:8453)
2425
+ * @param options - Additional options for resource info
2426
+ * @returns Base64-encoded signed payment payload
2427
+ */
2428
+ declare function createPaymentPayload(privateKey: `0x${string}`, fromAddress: string, recipient: string, amount: string, network?: string, options?: CreatePaymentOptions): Promise<string>;
2429
+ interface CreateSolanaPaymentOptions {
2430
+ resourceUrl?: string;
2431
+ resourceDescription?: string;
2432
+ maxTimeoutSeconds?: number;
2433
+ extra?: Record<string, unknown>;
2434
+ extensions?: Record<string, unknown>;
2435
+ rpcUrl?: string;
2436
+ /**
2437
+ * Optional HTTP headers forwarded to the Solana RPC endpoint
2438
+ * (e.g. `{ "x-api-key": "..." }` for Tatum / header-auth gateways).
2439
+ */
2440
+ rpcHeaders?: Record<string, string>;
2441
+ }
2442
+ /**
2443
+ * Create a signed Solana x402 v2 payment payload.
2444
+ *
2445
+ * This creates an SPL TransferChecked transaction for USDC payment
2446
+ * that the CDP facilitator can verify and settle.
2447
+ *
2448
+ * Requires @solana/web3.js and @solana/spl-token dependencies.
2449
+ *
2450
+ * @param secretKey - Solana secret key (Uint8Array, 64 bytes)
2451
+ * @param fromAddress - Sender wallet address (base58)
2452
+ * @param recipient - Payment recipient address (base58)
2453
+ * @param amount - Amount in micro USDC (6 decimals)
2454
+ * @param feePayer - CDP facilitator fee payer address (base58)
2455
+ * @param options - Additional options
2456
+ * @returns Base64-encoded signed payment payload
2457
+ */
2458
+ declare function createSolanaPaymentPayload(secretKey: Uint8Array, fromAddress: string, recipient: string, amount: string, feePayer: string, options?: CreateSolanaPaymentOptions): Promise<string>;
2459
+ /**
2460
+ * Parse the PAYMENT-REQUIRED header from a 402 response.
2461
+ *
2462
+ * @param headerValue - Base64-encoded payment required header
2463
+ * @returns Parsed payment required object
2464
+ * @throws {Error} If the header cannot be parsed or has invalid structure
2465
+ */
2466
+ declare function parsePaymentRequired(headerValue: string): PaymentRequired;
2467
+ /**
2468
+ * Extract payment details from parsed payment required response.
2469
+ * Supports both v1 and v2 formats, with optional network preference.
2470
+ *
2471
+ * @param paymentRequired - Parsed payment required object
2472
+ * @param preferredNetwork - Optional network preference. If specified, will try
2473
+ * to use matching network option. Defaults to first option (Base).
2474
+ * Examples:
2475
+ * - "eip155:8453" for Base
2476
+ * - "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" for Solana
2477
+ */
2478
+ declare function extractPaymentDetails(paymentRequired: PaymentRequired, preferredNetwork?: string): {
2479
+ amount: string;
2480
+ recipient: string;
2481
+ network: string;
2482
+ asset: string;
2483
+ scheme: string;
2484
+ maxTimeoutSeconds: number;
2485
+ extra?: {
2486
+ name?: string;
2487
+ version?: string;
2488
+ feePayer?: string;
2489
+ };
2490
+ resource?: ResourceInfo;
2491
+ };
2492
+
2493
+ /**
2494
+ * BlockRun Wallet Management - Auto-create and manage wallets.
2495
+ *
2496
+ * Provides frictionless wallet setup for new users:
2497
+ * - Auto-creates wallet if none exists
2498
+ * - Stores key securely at ~/.bridgenode/.session
2499
+ * - Generates EIP-681 URIs for easy MetaMask funding
2500
+ */
2501
+ declare const USDC_BASE_CONTRACT = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
2502
+ interface WalletInfo {
2503
+ privateKey: string;
2504
+ address: string;
2505
+ isNew: boolean;
2506
+ }
2507
+ interface PaymentLinks {
2508
+ basescan: string;
2509
+ walletLink: string;
2510
+ ethereum: string;
2511
+ bridgenode: string;
2512
+ }
2513
+ /**
2514
+ * Create a new Ethereum wallet.
2515
+ *
2516
+ * @returns Object with address and privateKey
2517
+ */
2518
+ declare function createWallet(): {
2519
+ address: string;
2520
+ privateKey: string;
2521
+ };
2522
+ /**
2523
+ * Save wallet private key to ~/.bridgenode/.session
2524
+ *
2525
+ * @param privateKey - Private key string (with 0x prefix)
2526
+ * @returns Path to saved wallet file
2527
+ */
2528
+ declare function saveWallet(privateKey: string): string;
2529
+ /**
2530
+ * Discover ~/.<dir>/wallet.json files from other providers.
2531
+ *
2532
+ * Each file should contain JSON with "privateKey" and "address" fields.
2533
+ * Results are sorted by modification time (most recent first). Discovery is
2534
+ * intentionally opt-in: a provider wallet must never replace the canonical
2535
+ * BlockRun wallet merely because it was written more recently.
2536
+ *
2537
+ * @returns Array of wallet objects with privateKey and address
2538
+ */
2539
+ declare function scanWallets(): Array<{
2540
+ privateKey: string;
2541
+ address: string;
2542
+ source: string;
2543
+ }>;
2544
+ /**
2545
+ * List wallets from other applications, safe to show to a user.
2546
+ *
2547
+ * Unlike `scanWallets()`, no private key is returned and the address is derived
2548
+ * from the key rather than read from the file, so a wallet file cannot claim an
2549
+ * address it has no key for.
2550
+ *
2551
+ * Nothing here is active. Adopt one deliberately with `importWallet()`.
2552
+ *
2553
+ * @returns Discovered wallets as `{ address, source }`, most recent first
2554
+ */
2555
+ declare function listDiscoveredWallets(): Array<{
2556
+ address: string;
2557
+ source: string;
2558
+ }>;
2559
+ /**
2560
+ * Adopt a discovered wallet by address, making it the active BlockRun wallet.
2561
+ *
2562
+ * This is the deliberate migration path: automatic selection never adopts a
2563
+ * discovered wallet, but you can choose one whose funds you want to spend.
2564
+ * Matching is done against the address *derived from each discovered key*, so a
2565
+ * wallet file claiming someone else's address can never be selected by it.
2566
+ *
2567
+ * The current `~/.bridgenode/.session` is backed up beside itself before being
2568
+ * overwritten, so adopting a wallet can't strand the funds in the old one.
2569
+ *
2570
+ * @param address Address to adopt, as shown by `listDiscoveredWallets()`
2571
+ * @returns The adopted address
2572
+ * @throws If no discovered wallet derives to that address
2573
+ */
2574
+ declare function importWallet(address: string): string;
2575
+ /**
2576
+ * Load wallet private key from file.
2577
+ *
2578
+ * Priority:
2579
+ * 1. ~/.bridgenode/.session
2580
+ * 2. ~/.bridgenode/wallet.key (legacy)
2581
+ *
2582
+ * @returns Private key string or null if not found
2583
+ */
2584
+ declare function loadWallet(): string | null;
2585
+ /**
2586
+ * Warn when a new wallet was created while other provider wallets exist.
2587
+ *
2588
+ * Automatic selection deliberately ignores wallets discovered in other
2589
+ * applications' directories, so a user who previously relied on that discovery
2590
+ * would otherwise land on an empty wallet with no explanation of where their
2591
+ * funds went. This notice names the discovered addresses and tells them how to
2592
+ * import one on purpose.
2593
+ *
2594
+ * Addresses are derived from the discovered private key rather than read from
2595
+ * the file's "address" field, so a file claiming an address it cannot sign for
2596
+ * cannot trick the user into importing it.
2597
+ *
2598
+ * @param newAddress Address of the wallet that was just created
2599
+ * @returns Formatted notice, or null if nothing was discovered
2600
+ */
2601
+ declare function formatWalletMigrationNotice(newAddress: string): string | null;
2602
+ /**
2603
+ * Get existing wallet or create new one.
2604
+ *
2605
+ * Priority:
2606
+ * 1. BRIDGENODE_WALLET_KEY environment variable
2607
+ * 2. ~/.bridgenode/.session file
2608
+ * 3. ~/.bridgenode/wallet.key file - legacy
2609
+ * 4. Create new wallet
2610
+ *
2611
+ * @returns WalletInfo with address, privateKey, and isNew flag
2612
+ */
2613
+ declare function getOrCreateWallet(): WalletInfo;
2614
+ /**
2615
+ * Get wallet address without exposing private key.
2616
+ *
2617
+ * @returns Wallet address or null if no wallet configured
2618
+ */
2619
+ declare function getWalletAddress(): string | null;
2620
+ /**
2621
+ * Generate EIP-681 URI for USDC transfer on Base.
2622
+ *
2623
+ * @param address - Recipient Ethereum address
2624
+ * @param amountUsdc - Amount in USDC (default 1.0)
2625
+ * @returns EIP-681 URI string for MetaMask/wallet scanning
2626
+ */
2627
+ declare function getEip681Uri(address: string, amountUsdc?: number): string;
2628
+ /**
2629
+ * Generate payment links for the wallet address.
2630
+ *
2631
+ * @param address - Ethereum address
2632
+ * @returns Object with various payment links
2633
+ */
2634
+ declare function getPaymentLinks(address: string): PaymentLinks;
2635
+ /**
2636
+ * Format the message shown when a new wallet is created.
2637
+ *
2638
+ * @param address - New wallet address
2639
+ * @returns Formatted message string
2640
+ */
2641
+ declare function formatWalletCreatedMessage(address: string): string;
2642
+ /**
2643
+ * Format the message shown when wallet needs more funds.
2644
+ *
2645
+ * @param address - Wallet address
2646
+ * @returns Formatted message string
2647
+ */
2648
+ declare function formatNeedsFundingMessage(address: string): string;
2649
+ /**
2650
+ * Compact funding message (no QR) for repeated displays.
2651
+ *
2652
+ * @param address - Wallet address
2653
+ * @returns Short formatted message string
2654
+ */
2655
+ declare function formatFundingMessageCompact(address: string): string;
2656
+ declare const WALLET_FILE_PATH: string;
2657
+ declare const WALLET_DIR_PATH: string;
2658
+
2659
+ /**
2660
+ * BlockRun Solana LLM Client.
2661
+ *
2662
+ * Usage:
2663
+ * import { SolanaLLMClient } from '@blockrun/llm';
2664
+ *
2665
+ * // SOLANA_WALLET_KEY env var (bs58-encoded Solana secret key)
2666
+ * const client = new SolanaLLMClient();
2667
+ *
2668
+ * // Or pass key directly
2669
+ * const client = new SolanaLLMClient({ privateKey: 'your-bs58-key' });
2670
+ *
2671
+ * const response = await client.chat('openai/gpt-5.2', 'gm Solana');
2672
+ */
2673
+
2674
+ interface SolanaLLMClientOptions {
2675
+ /** bs58-encoded Solana secret key (64 bytes). Optional if SOLANA_WALLET_KEY env var is set. */
2676
+ privateKey?: string;
2677
+ /** API endpoint URL (default: https://sol.bridgenode.cc/api) */
2678
+ apiUrl?: string;
2679
+ /**
2680
+ * Solana JSON-RPC URL. Defaults to BlockRun's own Tatum-backed proxy
2681
+ * (`https://sol.bridgenode.cc/api/v1/solana/rpc`), free for SDK users.
2682
+ * Override to point at your own Helius / Tatum / QuickNode account, or
2683
+ * fall back to the env vars `SOLANA_RPC_URL` /
2684
+ * `SOLANA_RPC_API_KEY` / `SOLANA_RPC_HEADERS`.
2685
+ */
2686
+ rpcUrl?: string;
2687
+ /**
2688
+ * Optional headers forwarded to the Solana RPC endpoint. Use this for
2689
+ * header-auth gateways (Tatum's `x-api-key`, some Triton tiers). Falls
2690
+ * back to `SOLANA_RPC_HEADERS` (JSON dict) or `SOLANA_RPC_API_KEY`
2691
+ * (shortcut for `{ "x-api-key": "..." }`) env vars when omitted.
2692
+ */
2693
+ rpcHeaders?: Record<string, string>;
2694
+ /** Request timeout in milliseconds (default: 60000) */
2695
+ timeout?: number;
2696
+ }
2697
+ declare class SolanaLLMClient {
2698
+ static readonly SOLANA_API_URL = "https://sol.bridgenode.cc/api";
2699
+ private privateKey;
2700
+ private apiUrl;
2701
+ private rpcUrl;
2702
+ private rpcHeaders?;
2703
+ private timeout;
2704
+ private sessionTotalUsd;
2705
+ private sessionCalls;
2706
+ private addressCache;
2707
+ constructor(options?: SolanaLLMClientOptions);
2708
+ /** Get Solana wallet address (public key in base58). */
2709
+ getWalletAddress(): Promise<string>;
2710
+ /** Simple 1-line chat. */
2711
+ chat(model: string, prompt: string, options?: ChatOptions): Promise<string>;
2712
+ /** Full chat completion (OpenAI-compatible). */
2713
+ chatCompletion(model: string, messages: ChatMessage[], options?: ChatCompletionOptions): Promise<ChatResponse>;
2714
+ /** List available models. */
2715
+ listModels(): Promise<Model[]>;
2716
+ /**
2717
+ * Get Solana USDC balance.
2718
+ *
2719
+ * @returns USDC balance as a float
2720
+ */
2721
+ getBalance(): Promise<number>;
2722
+ /** Edit an image using img2img (Solana payment). */
2723
+ imageEdit(prompt: string, image: string | string[], options?: ImageEditOptions): Promise<ImageResponse>;
2724
+ /** Standalone search (Solana payment). */
2725
+ search(query: string, options?: SearchOptions): Promise<SearchResult>;
2726
+ pm(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>;
2727
+ pmQuery(path: string, query: Record<string, unknown>): Promise<Record<string, unknown>>;
2728
+ /**
2729
+ * Generic Exa endpoint proxy (POST, Solana payment). Powered by Exa.
2730
+ *
2731
+ * @param path - Exa endpoint: "search" | "find-similar" | "contents" | "answer"
2732
+ * @param body - Request body (see Exa API docs)
2733
+ *
2734
+ * @example
2735
+ * const results = await client.exa("search", { query: "latest AI research", numResults: 5 });
2736
+ */
2737
+ exa(path: string, body: Record<string, unknown>): Promise<Record<string, unknown>>;
2738
+ /**
2739
+ * Neural and keyword web search via Exa (Solana payment, $0.01/request).
2740
+ *
2741
+ * @example
2742
+ * const results = await client.exaSearch("latest AI papers", { numResults: 5 });
2743
+ */
2744
+ exaSearch(query: string, options?: Record<string, unknown>): Promise<Record<string, unknown>>;
2745
+ /**
2746
+ * Find pages semantically similar to a given URL via Exa (Solana payment, $0.01/request).
2747
+ *
2748
+ * @example
2749
+ * const results = await client.exaFindSimilar("https://openai.com/research/gpt-4", { numResults: 5 });
2750
+ */
2751
+ exaFindSimilar(url: string, options?: Record<string, unknown>): Promise<Record<string, unknown>>;
2752
+ /**
2753
+ * Extract full text content from URLs via Exa (Solana payment, $0.002/URL).
2754
+ *
2755
+ * @example
2756
+ * const data = await client.exaContents(["https://arxiv.org/abs/2303.08774"]);
2757
+ */
2758
+ exaContents(urls: string[], options?: Record<string, unknown>): Promise<Record<string, unknown>>;
2759
+ /**
2760
+ * AI-generated answer grounded in live web search via Exa (Solana payment, $0.01/request).
2761
+ *
2762
+ * @example
2763
+ * const answer = await client.exaAnswer("What is the current state of AI safety research?");
2764
+ */
2765
+ exaAnswer(query: string, options?: Record<string, unknown>): Promise<Record<string, unknown>>;
2766
+ /**
2767
+ * Query DefiLlama DeFi data (GET passthrough). Powered by DefiLlama.
2768
+ * $0.005/call for protocols / protocol/{slug} / chains / yields;
2769
+ * $0.001/call for prices/{coins}.
2770
+ *
2771
+ * @param path - e.g. "protocols", "protocol/aave", "chains", "yields",
2772
+ * "prices/coingecko:bitcoin,base:0x..."
2773
+ * @param params - Query parameters passed through to DefiLlama
2774
+ */
2775
+ defi(path: string, params?: Record<string, string>): Promise<Record<string, unknown>>;
2776
+ /** All DeFi protocols with TVL ($0.005/call). */
2777
+ defiProtocols(): Promise<Record<string, unknown>>;
2778
+ /** Single protocol details + historical TVL ($0.005/call). */
2779
+ defiProtocol(slug: string): Promise<Record<string, unknown>>;
2780
+ /** Current TVL of every chain ($0.005/call). */
2781
+ defiChains(): Promise<Record<string, unknown>>;
2782
+ /** Yield pools with APY/TVL ($0.005/call). */
2783
+ defiYields(params?: Record<string, string>): Promise<Record<string, unknown>>;
2784
+ /** Token price lookup ($0.001/call). Coins like "coingecko:bitcoin" or "{chain}:{address}". */
2785
+ defiPrices(coins: string | string[]): Promise<Record<string, unknown>>;
2786
+ /**
2787
+ * Query the 0x Swap / Gasless APIs (free — no x402 payment; BlockRun
2788
+ * takes an on-chain affiliate fee on executed swaps instead).
2789
+ *
2790
+ * @param path - "price", "quote", "gasless/price", "gasless/quote",
2791
+ * "gasless/submit" (POST), "gasless/status/{hash}",
2792
+ * "gasless/approval-tokens", "gasless/chains", "swap/chains"
2793
+ * @param params - Query params (chainId, sellToken, buyToken, sellAmount, taker, ...)
2794
+ * @param body - JSON body — pass to switch to POST (gasless/submit only)
2795
+ */
2796
+ dex(path: string, params?: Record<string, string>, body?: Record<string, unknown>): Promise<Record<string, unknown>>;
2797
+ /** Indicative Permit2 swap price — no commitment (free). */
2798
+ dexPrice(params: Record<string, string>): Promise<Record<string, unknown>>;
2799
+ /** Firm Permit2 swap quote with permit2.eip712 + tx data (free). */
2800
+ dexQuote(params: Record<string, string>): Promise<Record<string, unknown>>;
2801
+ /** Gasless indicative price quote (free). */
2802
+ dexGaslessPrice(params: Record<string, string>): Promise<Record<string, unknown>>;
2803
+ /** Gasless firm quote — returns trade.eip712 to sign (free). */
2804
+ dexGaslessQuote(params: Record<string, string>): Promise<Record<string, unknown>>;
2805
+ /** Submit a signed gasless trade; the 0x relayer pays gas (free). */
2806
+ dexGaslessSubmit(body: Record<string, unknown>): Promise<Record<string, unknown>>;
2807
+ /** Poll a gasless trade's status by tradeHash (free). */
2808
+ dexGaslessStatus(tradeHash: string): Promise<Record<string, unknown>>;
2809
+ /** Chains where the Swap API is supported (free). */
2810
+ dexChains(): Promise<Record<string, unknown>>;
2811
+ /** Chains where the Gasless API is supported (free). */
2812
+ dexGaslessChains(): Promise<Record<string, unknown>>;
2813
+ /**
2814
+ * Call the Modal sandbox compute API (POST passthrough).
2815
+ *
2816
+ * @param path - "sandbox/create" ($0.01 CPU / $0.05 GPU), "sandbox/exec",
2817
+ * "sandbox/status", "sandbox/terminate" ($0.001 each)
2818
+ * @param body - JSON body for the endpoint
2819
+ */
2820
+ modal(path: string, body?: Record<string, unknown>): Promise<Record<string, unknown>>;
2821
+ /** Create a sandboxed compute environment ($0.01 CPU / $0.05 GPU). */
2822
+ modalSandboxCreate(body?: Record<string, unknown>): Promise<Record<string, unknown>>;
2823
+ /** Execute a command in a sandbox; returns stdout/stderr ($0.001). */
2824
+ modalSandboxExec(sandboxId: string, command: string[], extra?: Record<string, unknown>): Promise<Record<string, unknown>>;
2825
+ /** Check a sandbox's status ($0.001). */
2826
+ modalSandboxStatus(sandboxId: string): Promise<Record<string, unknown>>;
2827
+ /** Terminate a sandbox ($0.001). */
2828
+ modalSandboxTerminate(sandboxId: string): Promise<Record<string, unknown>>;
2829
+ /** Get session spending. */
2830
+ getSpending(): Spending;
2831
+ /** True if using sol.bridgenode.cc. */
2832
+ isSolana(): boolean;
2833
+ private requestWithPayment;
2834
+ private handlePaymentAndRetry;
2835
+ private requestWithPaymentRaw;
2836
+ private handlePaymentAndRetryRaw;
2837
+ private getWithPaymentRaw;
2838
+ private handleGetPaymentAndRetryRaw;
2839
+ private fetchWithTimeout;
2840
+ }
2841
+ /**
2842
+ * Convenience function: create SolanaLLMClient for sol.bridgenode.cc.
2843
+ */
2844
+ declare function solanaClient(options?: SolanaLLMClientOptions): SolanaLLMClient;
2845
+
2846
+ declare const SOLANA_WALLET_FILE: string;
2847
+ interface SolanaWalletInfo {
2848
+ privateKey: string;
2849
+ address: string;
2850
+ isNew: boolean;
2851
+ }
2852
+ /**
2853
+ * Create a new Solana wallet.
2854
+ * Requires @solana/web3.js (optional dep) — loaded lazily via dynamic
2855
+ * import so callers that never touch Solana don't pay the resolution cost
2856
+ * and ESM consumers don't trip over esbuild's __require shim.
2857
+ */
2858
+ declare function createSolanaWallet(): Promise<{
2859
+ address: string;
2860
+ privateKey: string;
2861
+ }>;
2862
+ /**
2863
+ * Convert a bs58 private key string to Uint8Array (64 bytes).
2864
+ * Accepts: bs58-encoded 64-byte key (standard Solana format).
2865
+ */
2866
+ declare function solanaKeyToBytes(privateKey: string): Promise<Uint8Array>;
2867
+ /**
2868
+ * Get Solana public key (address) from bs58 private key.
2869
+ */
2870
+ declare function solanaPublicKey(privateKey: string): Promise<string>;
2871
+ declare function saveSolanaWallet(privateKey: string): string;
2872
+ /**
2873
+ * Discover ~/.<dir>/solana-wallet.json files from other providers.
2874
+ *
2875
+ * Each file should contain JSON with "privateKey" and "address" fields.
2876
+ * Also checks ~/.brcc/wallet.json for BRCC wallets.
2877
+ * Results are sorted by modification time (most recent first). Discovery is
2878
+ * opt-in and never changes the active BlockRun wallet automatically.
2879
+ *
2880
+ * @returns Array of wallet objects with secretKey and publicKey
2881
+ */
2882
+ declare function scanSolanaWallets(): Array<{
2883
+ secretKey: string;
2884
+ publicKey: string;
2885
+ source: string;
2886
+ }>;
2887
+ declare function loadSolanaWallet(): string | null;
2888
+ /**
2889
+ * List Solana wallets from other applications, safe to show to a user.
2890
+ *
2891
+ * Solana counterpart of `listDiscoveredWallets()`: no secret key is returned
2892
+ * and the address is derived from the key rather than trusted from the file.
2893
+ * Nothing here is active — adopt one with `importSolanaWallet()`.
2894
+ *
2895
+ * @returns Discovered wallets as `{ address, source }`, most recent first
2896
+ */
2897
+ declare function listDiscoveredSolanaWallets(): Promise<Array<{
2898
+ address: string;
2899
+ source: string;
2900
+ }>>;
2901
+ /**
2902
+ * Adopt a discovered Solana wallet, making it the active BlockRun wallet.
2903
+ *
2904
+ * Solana counterpart of `importWallet()`. Matching is done against the address
2905
+ * derived from each discovered key, and the current
2906
+ * `~/.bridgenode/.solana-session` is backed up before being overwritten.
2907
+ *
2908
+ * @param address Address to adopt, as shown by `listDiscoveredSolanaWallets()`
2909
+ * @returns The adopted address
2910
+ * @throws If no discovered wallet derives to that address
2911
+ */
2912
+ declare function importSolanaWallet(address: string): Promise<string>;
2913
+ /**
2914
+ * Warn when a new Solana wallet was created while provider wallets exist.
2915
+ *
2916
+ * Solana counterpart of `formatWalletMigrationNotice`. Addresses are derived
2917
+ * from the discovered secret key rather than trusted from the file's "address"
2918
+ * field.
2919
+ *
2920
+ * @param newAddress Address of the wallet that was just created
2921
+ * @returns Formatted notice, or null if nothing was discovered
2922
+ */
2923
+ declare function formatSolanaWalletMigrationNotice(newAddress: string): Promise<string | null>;
2924
+ declare function getOrCreateSolanaWallet(): Promise<SolanaWalletInfo>;
2925
+
2926
+ declare function getCached(key: string): unknown | null;
2927
+ declare function getCachedByRequest(endpoint: string, body: Record<string, unknown>): unknown | null;
2928
+ declare function setCache(key: string, data: unknown, ttlMs: number): void;
2929
+ declare function saveToCache(endpoint: string, body: Record<string, unknown>, response: unknown, costUsd?: number): void;
2930
+ declare function clearCache(): number;
2931
+ declare function getCostLogSummary(): {
2932
+ totalUsd: number;
2933
+ calls: number;
2934
+ byEndpoint: Record<string, number>;
2935
+ };
2936
+
2937
+ /**
2938
+ * Agent wallet setup utilities.
2939
+ *
2940
+ * Convenience functions for agent runtimes (Claude Code skills, etc.)
2941
+ * that auto-create wallets and return configured clients.
2942
+ */
2943
+
2944
+ declare function setupAgentWallet(options?: {
2945
+ silent?: boolean;
2946
+ }): LLMClient;
2947
+ declare function setupAgentSolanaWallet(options?: {
2948
+ silent?: boolean;
2949
+ }): Promise<SolanaLLMClient>;
2950
+ declare function status(): Promise<{
2951
+ address: string;
2952
+ balance: number;
2953
+ }>;
2954
+
2955
+ /** Canonical on-wire schema for cost_log.jsonl entries. */
2956
+ interface CostEntry {
2957
+ /** Unix epoch seconds (float, millisecond precision). */
2958
+ ts: number;
2959
+ /** API endpoint path, e.g. "/v1/chat/completions". */
2960
+ endpoint: string;
2961
+ /** Settled USDC amount (USD, 6-decimal precision). */
2962
+ cost_usd: number;
2963
+ /** Model id when known, e.g. "zai/glm-5-turbo". Optional for non-LLM endpoints. */
2964
+ model?: string;
2965
+ /** Payer wallet address (EVM 0x... or Solana base58). */
2966
+ wallet?: string;
2967
+ /** Network identifier — "eip155:8453" for Base mainnet, "solana-mainnet", etc. */
2968
+ network?: string;
2969
+ /** Caller kind for analytics — "LLMClient", "ImageClient", "AgentClient", ... */
2970
+ client_kind?: string;
2971
+ }
2972
+ declare function logCost(entry: CostEntry): void;
2973
+ declare function getCostSummary(): {
2974
+ totalUsd: number;
2975
+ calls: number;
2976
+ byModel: Record<string, number>;
2977
+ byEndpoint: Record<string, number>;
2978
+ };
2979
+
2980
+ /**
2981
+ * OpenAI-compatible API wrapper for BlockRun LLM SDK.
2982
+ *
2983
+ * Drop-in replacement for OpenAI SDK - just change the import and use walletKey instead of apiKey.
2984
+ *
2985
+ * @example
2986
+ * // Before (OpenAI)
2987
+ * import OpenAI from 'openai';
2988
+ * const client = new OpenAI({ apiKey: 'sk-...' });
2989
+ *
2990
+ * // After (BlockRun)
2991
+ * import { OpenAI } from '@blockrun/llm';
2992
+ * const client = new OpenAI({ walletKey: '0x...' });
2993
+ *
2994
+ * // Rest of your code stays exactly the same!
2995
+ * const response = await client.chat.completions.create({
2996
+ * model: 'gpt-5.2',
2997
+ * messages: [{ role: 'user', content: 'Hello!' }]
2998
+ * });
2999
+ */
3000
+
3001
+ interface OpenAIClientOptions {
3002
+ /** EVM wallet private key (replaces apiKey) */
3003
+ walletKey?: `0x${string}` | string;
3004
+ /** Alternative: use privateKey like LLMClient */
3005
+ privateKey?: `0x${string}` | string;
3006
+ /** API endpoint URL (default: https://bridgenode.cc/api) */
3007
+ baseURL?: string;
3008
+ /** Request timeout in milliseconds */
3009
+ timeout?: number;
3010
+ }
3011
+ interface OpenAIChatCompletionParams {
3012
+ model: string;
3013
+ messages: Array<{
3014
+ role: "system" | "user" | "assistant" | "tool";
3015
+ content?: string | null;
3016
+ name?: string;
3017
+ tool_call_id?: string;
3018
+ tool_calls?: ToolCall[];
3019
+ }>;
3020
+ max_tokens?: number;
3021
+ temperature?: number;
3022
+ response_format?: ResponseFormat;
3023
+ top_p?: number;
3024
+ stream?: boolean;
3025
+ n?: number;
3026
+ stop?: string | string[];
3027
+ presence_penalty?: number;
3028
+ frequency_penalty?: number;
3029
+ user?: string;
3030
+ tools?: Tool[];
3031
+ tool_choice?: ToolChoice;
3032
+ }
3033
+ interface OpenAIChatCompletionChoice {
3034
+ index: number;
3035
+ message: {
3036
+ role: "assistant";
3037
+ content?: string | null;
3038
+ tool_calls?: ToolCall[];
3039
+ };
3040
+ finish_reason: "stop" | "length" | "content_filter" | "tool_calls" | null;
3041
+ }
3042
+ interface OpenAIChatCompletionResponse {
3043
+ id: string;
3044
+ object: "chat.completion";
3045
+ created: number;
3046
+ model: string;
3047
+ choices: OpenAIChatCompletionChoice[];
3048
+ usage?: {
3049
+ prompt_tokens: number;
3050
+ completion_tokens: number;
3051
+ total_tokens: number;
3052
+ };
3053
+ }
3054
+ interface OpenAIChatCompletionChunk {
3055
+ id: string;
3056
+ object: "chat.completion.chunk";
3057
+ created: number;
3058
+ model: string;
3059
+ choices: Array<{
3060
+ index: number;
3061
+ delta: {
3062
+ role?: "assistant";
3063
+ content?: string;
3064
+ };
3065
+ finish_reason: string | null;
3066
+ }>;
3067
+ }
3068
+ /**
3069
+ * Chat completions API (OpenAI-compatible)
3070
+ */
3071
+ declare class ChatCompletions {
3072
+ private client;
3073
+ private apiUrl;
3074
+ private timeout;
3075
+ constructor(client: LLMClient, apiUrl: string, timeout: number);
3076
+ /**
3077
+ * Create a chat completion (OpenAI-compatible).
3078
+ */
3079
+ create(params: OpenAIChatCompletionParams): Promise<OpenAIChatCompletionResponse>;
3080
+ create(params: OpenAIChatCompletionParams & {
3081
+ stream: true;
3082
+ }): Promise<AsyncIterable<OpenAIChatCompletionChunk>>;
3083
+ private createStream;
3084
+ private transformResponse;
3085
+ }
3086
+ /**
3087
+ * Chat API namespace
3088
+ */
3089
+ declare class Chat {
3090
+ completions: ChatCompletions;
3091
+ constructor(client: LLMClient, apiUrl: string, timeout: number);
3092
+ }
3093
+ /**
3094
+ * OpenAI-compatible client for BlockRun.
3095
+ *
3096
+ * Drop-in replacement for the OpenAI SDK.
3097
+ *
3098
+ * @example
3099
+ * import { OpenAI } from '@blockrun/llm';
3100
+ *
3101
+ * const client = new OpenAI({ walletKey: '0x...' });
3102
+ *
3103
+ * const response = await client.chat.completions.create({
3104
+ * model: 'gpt-5.2',
3105
+ * messages: [{ role: 'user', content: 'Hello!' }]
3106
+ * });
3107
+ *
3108
+ * console.log(response.choices[0].message.content);
3109
+ */
3110
+ declare class OpenAI {
3111
+ chat: Chat;
3112
+ private client;
3113
+ constructor(options?: OpenAIClientOptions);
3114
+ /**
3115
+ * Get the wallet address being used for payments.
3116
+ */
3117
+ getWalletAddress(): string;
3118
+ }
3119
+
3120
+ interface BridgeNodeAnthropicOptions {
3121
+ privateKey?: `0x${string}` | string;
3122
+ apiUrl?: string;
3123
+ timeout?: number;
3124
+ }
3125
+ declare class AnthropicClient {
3126
+ private _client;
3127
+ private _clientPromise;
3128
+ private _privateKey;
3129
+ private _account;
3130
+ private _apiUrl;
3131
+ private _timeout;
3132
+ constructor(options?: BridgeNodeAnthropicOptions);
3133
+ private _getClient;
3134
+ private _x402Fetch;
3135
+ get messages(): _anthropic_ai_sdk.default['messages'];
3136
+ getWalletAddress(): string;
3137
+ }
3138
+
3139
+ /**
3140
+ * Input validation and security utilities for BlockRun LLM SDK.
3141
+ *
3142
+ * This module provides validation functions to ensure:
3143
+ * - Private keys are properly formatted
3144
+ * - API URLs use HTTPS
3145
+ * - Server responses don't leak sensitive information
3146
+ * - Resource URLs match expected domains
3147
+ */
3148
+
3149
+ /**
3150
+ * Known LLM providers (for optional validation).
3151
+ */
3152
+ declare const KNOWN_PROVIDERS: Set<string>;
3153
+ /**
3154
+ * Validates that a model ID is a non-empty string.
3155
+ *
3156
+ * @param model - The model ID (e.g., "openai/gpt-5.2", "anthropic/claude-sonnet-4.5")
3157
+ * @throws {Error} If the model is invalid
3158
+ *
3159
+ * @example
3160
+ * validateModel("openai/gpt-5.2");
3161
+ */
3162
+ declare function validateModel(model: string): void;
3163
+ /**
3164
+ * Mirrors the gateway's own contract for `max_tokens`, which is exactly
3165
+ * `z.number().int().min(1).optional()` — an integer, at least 1, and
3166
+ * deliberately **no upper bound**.
3167
+ *
3168
+ * There is no ceiling here on purpose. The gateway clamps every request with
3169
+ * `min(requested, model.maxOutput, contextHeadroom)` and then quotes only a
3170
+ * fraction of the clamped value, so an oversized `maxTokens` cannot inflate a
3171
+ * payment: 1e9 and 1_000_000 produce a byte-identical quote, because both land
3172
+ * on the same `model.maxOutput`. A client-side ceiling could therefore only
3173
+ * ever reject a request the gateway would have accepted and handled correctly.
3174
+ *
3175
+ * Earlier versions of this file did carry one, justified in a comment as
3176
+ * stopping a stray 1e9 from "becoming a payment quote". That was never true —
3177
+ * it was asserted here without being checked against the route handler, which
3178
+ * is the same mistake as the old `"maxTokens too large (maximum: 100000)"`
3179
+ * message that got recorded downstream as an upstream model ceiling. Verify
3180
+ * against the gateway before reintroducing any number in this file.
3181
+ *
3182
+ * @param maxTokens - Maximum number of tokens to generate
3183
+ * @throws {Error} If maxTokens is not a positive integer
3184
+ *
3185
+ * @example
3186
+ * validateMaxTokens(1000);
3187
+ */
3188
+ declare function validateMaxTokens(maxTokens?: number): void;
3189
+ /**
3190
+ * Validates that temperature is a number between 0 and 2.
3191
+ *
3192
+ * @param temperature - Sampling temperature (0-2)
3193
+ * @throws {Error} If temperature is invalid
3194
+ *
3195
+ * @example
3196
+ * validateTemperature(0.7);
3197
+ */
3198
+ declare function validateTemperature(temperature?: number): void;
3199
+ /**
3200
+ * Validates that top_p is a number between 0 and 1.
3201
+ *
3202
+ * @param topP - Top-p sampling parameter (0-1)
3203
+ * @throws {Error} If topP is invalid
3204
+ *
3205
+ * @example
3206
+ * validateTopP(0.9);
3207
+ */
3208
+ declare function validateTopP(topP?: number): void;
3209
+
3210
+ export { APIError, AnthropicClient, type AudioModel, type AudioTrack, BASE_CHAIN_ID, type BarResolution, type BridgeNodeAnthropicOptions, BlockrunClient as BridgeNodeClient, type BridgeNodeClientOptions, BridgeNodeError, 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, NETWORK_ALIASES, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PHONE_PRICES, PORTRAIT_ENROLLMENT_PRICE_USD, PaymentError, type PaymentLinks, 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 ResponseFormat, type RoutingDecision, type RoutingProfile, type RoutingTier, 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 SmartChatOptions, type SmartChatResponse, 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_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, 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 WalletInfo, type WebSearchSource, type XSearchSource, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatSolanaWalletMigrationNotice, formatWalletCreatedMessage, formatWalletMigrationNotice, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, importSolanaWallet, importWallet, listDiscoveredSolanaWallets, listDiscoveredWallets, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, validateMaxTokens, validateModel, validateTemperature, validateTopP };