-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.d.ts
More file actions
1809 lines (1776 loc) · 60.7 KB
/
Copy pathindex.d.ts
File metadata and controls
1809 lines (1776 loc) · 60.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* OpenClaw Plugin Types (locally defined)
*
* OpenClaw's plugin SDK uses duck typing — these match the shapes
* expected by registerProvider() and the plugin system.
* Defined locally to avoid depending on internal OpenClaw paths.
*/
type ModelApi = "openai-completions" | "openai-responses" | "anthropic-messages" | "google-generative-ai" | "github-copilot" | "bedrock-converse-stream";
type ModelDefinitionConfig = {
id: string;
name: string;
api?: ModelApi;
reasoning: boolean;
input: Array<"text" | "image">;
cost: {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
};
contextWindow: number;
maxTokens: number;
headers?: Record<string, string>;
};
type ModelProviderConfig = {
baseUrl: string;
apiKey?: string;
api?: ModelApi;
headers?: Record<string, string>;
authHeader?: boolean;
models: ModelDefinitionConfig[];
};
type OpenClawConfig = Record<string, unknown> & {
models?: {
providers?: Record<string, ModelProviderConfig>;
};
agents?: Record<string, unknown>;
mcp?: {
servers?: Record<string, unknown>;
};
tools?: {
web?: {
search?: Record<string, unknown> & {
provider?: string;
enabled?: boolean;
};
};
};
};
type AuthProfileCredential = {
apiKey?: string;
type?: string;
[key: string]: unknown;
};
type ProviderAuthResult = {
profiles: Array<{
profileId: string;
credential: AuthProfileCredential;
}>;
configPatch?: Record<string, unknown>;
defaultModel?: string;
notes?: string[];
};
type WizardPrompter = {
text: (opts: {
message: string;
validate?: (value: string) => string | undefined;
}) => Promise<string | symbol>;
note: (message: string) => void;
progress: (message: string) => {
stop: (message?: string) => void;
};
};
type ProviderAuthContext = {
config: Record<string, unknown>;
agentDir?: string;
workspaceDir?: string;
prompter: WizardPrompter;
runtime: {
log: (message: string) => void;
};
isRemote: boolean;
openUrl: (url: string) => Promise<void>;
};
type ProviderAuthMethod = {
id: string;
label: string;
hint?: string;
kind: "oauth" | "api_key" | "token" | "device_code" | "custom";
run: (ctx: ProviderAuthContext) => Promise<ProviderAuthResult>;
};
type ProviderPlugin = {
id: string;
label: string;
docsPath?: string;
aliases?: string[];
envVars?: string[];
models?: ModelProviderConfig;
auth: ProviderAuthMethod[];
formatApiKey?: (cred: AuthProfileCredential) => string;
};
type PluginLogger = {
debug?: (message: string) => void;
info: (message: string) => void;
warn: (message: string) => void;
error: (message: string) => void;
};
type OpenClawPluginService = {
id: string;
start: () => void | Promise<void>;
stop?: () => void | Promise<void>;
};
type ImageGenerationResolution = "1K" | "2K" | "4K";
type GeneratedImageAsset = {
buffer: Buffer;
mimeType: string;
fileName?: string;
revisedPrompt?: string;
metadata?: Record<string, unknown>;
};
type ImageGenerationSourceImage = {
buffer: Buffer;
mimeType: string;
fileName?: string;
metadata?: Record<string, unknown>;
};
type ImageGenerationRequest = {
provider: string;
model: string;
prompt: string;
cfg: Record<string, unknown>;
agentDir?: string;
timeoutMs?: number;
count?: number;
size?: string;
aspectRatio?: string;
resolution?: ImageGenerationResolution;
inputImages?: ImageGenerationSourceImage[];
};
type ImageGenerationResult = {
images: GeneratedImageAsset[];
model?: string;
metadata?: Record<string, unknown>;
};
type ImageGenerationProviderCapabilities = {
generate: {
maxCount?: number;
supportsSize?: boolean;
supportsAspectRatio?: boolean;
supportsResolution?: boolean;
};
edit: {
enabled: boolean;
maxInputImages?: number;
maxCount?: number;
supportsSize?: boolean;
};
geometry?: {
sizes?: string[];
resolutions?: ImageGenerationResolution[];
};
};
type ImageGenerationProviderPlugin = {
id: string;
aliases?: string[];
label?: string;
defaultModel?: string;
models?: string[];
capabilities: ImageGenerationProviderCapabilities;
isConfigured?: (ctx: {
cfg?: Record<string, unknown>;
}) => boolean;
generateImage: (req: ImageGenerationRequest) => Promise<ImageGenerationResult>;
};
type MusicGenerationOutputFormat = "mp3" | "wav";
type GeneratedMusicAsset = {
buffer: Buffer;
mimeType: string;
fileName?: string;
metadata?: Record<string, unknown>;
};
type MusicGenerationRequest = {
provider: string;
model: string;
prompt: string;
cfg: Record<string, unknown>;
agentDir?: string;
timeoutMs?: number;
lyrics?: string;
instrumental?: boolean;
durationSeconds?: number;
format?: MusicGenerationOutputFormat;
};
type MusicGenerationResult = {
tracks: GeneratedMusicAsset[];
model?: string;
lyrics?: string[];
metadata?: Record<string, unknown>;
};
type MusicGenerationProviderCapabilities = {
maxTracks?: number;
maxDurationSeconds?: number;
supportsLyrics?: boolean;
supportsInstrumental?: boolean;
supportsDuration?: boolean;
supportsFormat?: boolean;
supportedFormats?: readonly MusicGenerationOutputFormat[];
};
type MusicGenerationProviderPlugin = {
id: string;
aliases?: string[];
label?: string;
defaultModel?: string;
models?: string[];
capabilities: MusicGenerationProviderCapabilities;
isConfigured?: (ctx: {
cfg?: Record<string, unknown>;
}) => boolean;
generateMusic: (req: MusicGenerationRequest) => Promise<MusicGenerationResult>;
};
type VideoGenerationResolution = "480P" | "720P" | "768P" | "1080P";
type GeneratedVideoAsset = {
buffer: Buffer;
mimeType: string;
fileName?: string;
metadata?: Record<string, unknown>;
};
type VideoGenerationSourceAsset = {
url?: string;
buffer?: Buffer;
mimeType?: string;
fileName?: string;
metadata?: Record<string, unknown>;
};
type VideoGenerationRequest = {
provider: string;
model: string;
prompt: string;
cfg: Record<string, unknown>;
agentDir?: string;
timeoutMs?: number;
size?: string;
aspectRatio?: string;
resolution?: VideoGenerationResolution;
durationSeconds?: number;
audio?: boolean;
watermark?: boolean;
inputImages?: VideoGenerationSourceAsset[];
inputVideos?: VideoGenerationSourceAsset[];
};
type VideoGenerationResult = {
videos: GeneratedVideoAsset[];
model?: string;
metadata?: Record<string, unknown>;
};
type VideoGenerationModeCapabilities = {
maxVideos?: number;
maxInputImages?: number;
maxInputVideos?: number;
maxDurationSeconds?: number;
supportedDurationSeconds?: readonly number[];
supportsSize?: boolean;
supportsAspectRatio?: boolean;
supportsResolution?: boolean;
supportsAudio?: boolean;
supportsWatermark?: boolean;
};
type VideoGenerationTransformCapabilities = VideoGenerationModeCapabilities & {
enabled: boolean;
};
type VideoGenerationProviderCapabilities = VideoGenerationModeCapabilities & {
generate?: VideoGenerationModeCapabilities;
imageToVideo?: VideoGenerationTransformCapabilities;
videoToVideo?: VideoGenerationTransformCapabilities;
};
type VideoGenerationProviderPlugin = {
id: string;
aliases?: string[];
label?: string;
defaultModel?: string;
models?: string[];
capabilities: VideoGenerationProviderCapabilities;
isConfigured?: (ctx: {
cfg?: Record<string, unknown>;
}) => boolean;
generateVideo: (req: VideoGenerationRequest) => Promise<VideoGenerationResult>;
};
type WebSearchProviderToolDefinition = {
description: string;
parameters: unknown;
execute: (args: Record<string, unknown>) => Promise<unknown> | unknown;
};
type WebSearchProviderContext = {
config: OpenClawConfig;
searchConfig?: Record<string, unknown>;
runtimeMetadata?: Record<string, unknown>;
};
type WebSearchProviderPlugin = {
id: string;
label: string;
hint: string;
onboardingScopes?: Array<"text-inference">;
requiresCredential?: boolean;
credentialLabel?: string;
envVars: string[];
placeholder: string;
signupUrl: string;
docsUrl?: string;
autoDetectOrder?: number;
credentialPath: string;
inactiveSecretPaths?: string[];
getCredentialValue: (searchConfig?: Record<string, unknown>) => unknown;
setCredentialValue: (searchConfigTarget: Record<string, unknown>, value: unknown) => void;
getConfiguredCredentialValue?: (config?: OpenClawConfig) => unknown;
setConfiguredCredentialValue?: (configTarget: OpenClawConfig, value: unknown) => void;
applySelectionConfig?: (config: OpenClawConfig) => OpenClawConfig;
resolveRuntimeMetadata?: (ctx: Record<string, unknown>) => unknown;
createTool: (ctx: WebSearchProviderContext) => WebSearchProviderToolDefinition | null;
};
type OpenClawPluginApi = {
id: string;
name: string;
version?: string;
description?: string;
source: string;
config: OpenClawConfig;
pluginConfig?: Record<string, unknown>;
logger: PluginLogger;
registerProvider: (provider: ProviderPlugin) => void;
registerImageGenerationProvider: (provider: ImageGenerationProviderPlugin) => void;
registerMusicGenerationProvider: (provider: MusicGenerationProviderPlugin) => void;
registerVideoGenerationProvider?: (provider: VideoGenerationProviderPlugin) => void;
registerWebSearchProvider?: (provider: WebSearchProviderPlugin) => void;
registerTool: (tool: unknown, opts?: unknown) => void;
registerHook: (events: string | string[], handler: unknown, opts?: unknown) => void;
registerHttpRoute: (params: {
path: string;
handler: unknown;
}) => void;
registerService: (service: OpenClawPluginService) => void;
registerCommand: (command: unknown) => void;
resolvePath: (input: string) => string;
on: (hookName: string, handler: unknown, opts?: unknown) => void;
};
type OpenClawPluginDefinition = {
id?: string;
name?: string;
description?: string;
version?: string;
/**
* OpenClaw 2026.5.7+ capability contracts. The gateway's plugin loader
* validates that every tool/middleware/factory the plugin tries to
* register is declared here upfront; anything undeclared is silently
* dropped and a diagnostic is recorded (visible via
* `openclaw plugins doctor`). Keep `tools` in sync with the names
* passed to `api.registerTool()`.
*/
contracts?: {
tools?: string[];
embeddedExtensionFactories?: string[];
agentToolResultMiddleware?: string[];
};
register?: (api: OpenClawPluginApi) => void | Promise<void>;
activate?: (api: OpenClawPluginApi) => void | Promise<void>;
deactivate?: (api: OpenClawPluginApi) => void | Promise<void>;
reload?: {
noopPrefixes?: string[];
};
};
/**
* Tier → Model Selection
*
* Maps a classification tier to the cheapest capable model.
* Builds RoutingDecision metadata with cost estimates and savings.
*/
type ModelPricing = {
inputPrice: number;
outputPrice: number;
/** Active promo flat price per request (overrides token-based pricing when set) */
flatPrice?: number;
};
/**
* Get the ordered fallback chain for a tier: [primary, ...fallbacks].
*/
declare function getFallbackChain(tier: Tier, tierConfigs: Record<Tier, TierConfig>): string[];
declare function calculateModelCost(model: string, modelPricing: Map<string, ModelPricing>, estimatedInputTokens: number, maxOutputTokens: number, routingProfile?: "free" | "eco" | "auto" | "premium"): {
costEstimate: number;
baselineCost: number;
savings: number;
};
/**
* Get the fallback chain filtered by context length.
* Only returns models that can handle the estimated total context.
*
* @param tier - The tier to get fallback chain for
* @param tierConfigs - Tier configurations
* @param estimatedTotalTokens - Estimated total context (input + output)
* @param getContextWindow - Function to get context window for a model ID
* @returns Filtered list of models that can handle the context
*/
declare function getFallbackChainFiltered(tier: Tier, tierConfigs: Record<Tier, TierConfig>, estimatedTotalTokens: number, getContextWindow: (modelId: string) => number | undefined): string[];
/**
* Smart Router Types
*
* Four classification tiers — REASONING is distinct from COMPLEX because
* reasoning tasks need different models (o3, gemini-pro) than general
* complex tasks (gpt-4o, sonnet-4).
*
* Scoring uses weighted float dimensions with sigmoid confidence calibration.
*/
type Tier = "SIMPLE" | "MEDIUM" | "COMPLEX" | "REASONING";
type RoutingDecision = {
model: string;
tier: Tier;
confidence: number;
method: "rules" | "llm";
reasoning: string;
costEstimate: number;
baselineCost: number;
savings: number;
agenticScore?: number;
/** Which tier configs were used (auto/eco/premium/agentic) — avoids re-derivation in proxy */
tierConfigs?: Record<Tier, TierConfig>;
/** Which routing profile was applied */
profile?: "auto" | "eco" | "premium" | "agentic";
};
type RouterOptions = {
config: RoutingConfig;
modelPricing: Map<string, ModelPricing>;
routingProfile?: "eco" | "auto" | "premium";
hasTools?: boolean;
/** Override current time for promotion window checks (for testing). Default: new Date() */
now?: Date;
};
type TierConfig = {
primary: string;
fallback: string[];
};
type ScoringConfig = {
tokenCountThresholds: {
simple: number;
complex: number;
};
codeKeywords: string[];
reasoningKeywords: string[];
simpleKeywords: string[];
technicalKeywords: string[];
creativeKeywords: string[];
imperativeVerbs: string[];
constraintIndicators: string[];
outputFormatKeywords: string[];
referenceKeywords: string[];
negationKeywords: string[];
domainSpecificKeywords: string[];
agenticTaskKeywords: string[];
dimensionWeights: Record<string, number>;
tierBoundaries: {
simpleMedium: number;
mediumComplex: number;
complexReasoning: number;
};
confidenceSteepness: number;
confidenceThreshold: number;
};
type ClassifierConfig = {
llmModel: string;
llmMaxTokens: number;
llmTemperature: number;
promptTruncationChars: number;
cacheTtlMs: number;
};
type OverridesConfig = {
maxTokensForceComplex: number;
structuredOutputMinTier: Tier;
ambiguousDefaultTier: Tier;
/**
* When enabled, prefer models optimized for agentic workflows.
* Agentic models continue autonomously with multi-step tasks
* instead of stopping and waiting for user input.
*/
agenticMode?: boolean;
};
/**
* Time-windowed promotion that temporarily overrides tier routing.
* Active promotions are auto-applied; expired ones are ignored at runtime.
*/
type Promotion = {
/** Human-readable label (e.g. "GLM-5 Launch Promo") */
name: string;
/** ISO date string, promotion starts (inclusive). e.g. "2026-04-01" */
startDate: string;
/** ISO date string, promotion ends (exclusive). e.g. "2026-04-15" */
endDate: string;
/** Partial tier overrides — merged into the active tier configs (primary/fallback) */
tierOverrides: Partial<Record<Tier, Partial<TierConfig>>>;
/** Which profiles this applies to. Default: all profiles. */
profiles?: Array<"auto" | "eco" | "premium" | "agentic">;
};
type RoutingConfig = {
version: string;
classifier: ClassifierConfig;
scoring: ScoringConfig;
tiers: Record<Tier, TierConfig>;
/**
* Tier configs for agentic mode — models that excel at multi-step tasks.
* Set to `null` to disable agentic tier selection entirely (forces all
* requests through `tiers`, even when tools are present in the request).
*/
agenticTiers?: Record<Tier, TierConfig> | null;
/** Tier configs for eco profile — ultra cost-optimized (blockrun/eco). `null` falls back to `tiers`. */
ecoTiers?: Record<Tier, TierConfig> | null;
/** Tier configs for premium profile — best quality (blockrun/premium). `null` falls back to `tiers`. */
premiumTiers?: Record<Tier, TierConfig> | null;
/** Time-windowed promotions that temporarily override tier routing */
promotions?: Promotion[];
overrides: OverridesConfig;
};
/**
* Default Routing Config
*
* All routing parameters as a TypeScript constant.
* Operators override via openclaw.yaml plugin config.
*
* Scoring uses 14 weighted dimensions with sigmoid confidence calibration.
*/
declare const DEFAULT_ROUTING_CONFIG: RoutingConfig;
/**
* Smart Router Entry Point
*
* Classifies requests and routes to the cheapest capable model.
* Delegates to pluggable RouterStrategy (default: RulesStrategy, <1ms).
*/
/**
* Route a request to the cheapest capable model.
* Delegates to the registered "rules" strategy by default.
*/
declare function route(prompt: string, systemPrompt: string | undefined, maxOutputTokens: number, options: RouterOptions): RoutingDecision;
/**
* Response Cache for LLM Completions
*
* Caches LLM responses by request hash (model + messages + params).
* Inspired by LiteLLM's caching system. Returns cached responses for
* identical requests, saving both cost and latency.
*
* Features:
* - TTL-based expiration (default 10 minutes)
* - LRU eviction when cache is full
* - Size limits per item (1MB max)
* - Heap-based expiration tracking for efficient pruning
*/
type CachedLLMResponse = {
body: Buffer;
status: number;
headers: Record<string, string>;
model: string;
cachedAt: number;
expiresAt: number;
};
type ResponseCacheConfig = {
/** Maximum number of cached responses. Default: 200 */
maxSize?: number;
/** Default TTL in seconds. Default: 600 (10 minutes) */
defaultTTL?: number;
/** Maximum size per cached item in bytes. Default: 1MB */
maxItemSize?: number;
/** Enable/disable cache. Default: true */
enabled?: boolean;
};
declare class ResponseCache {
private cache;
private expirationHeap;
private config;
private stats;
constructor(config?: ResponseCacheConfig);
/**
* Generate cache key from request body.
* Hashes: model + messages + temperature + max_tokens + other params
*/
static generateKey(body: Buffer | string): string;
/**
* Check if caching is enabled for this request.
* Respects cache control headers and request params.
*/
shouldCache(body: Buffer | string, headers?: Record<string, string>): boolean;
/**
* Get cached response if available and not expired.
*/
get(key: string): CachedLLMResponse | undefined;
/**
* Cache a response with optional custom TTL.
*/
set(key: string, response: {
body: Buffer;
status: number;
headers: Record<string, string>;
model: string;
}, ttlSeconds?: number): void;
/**
* Evict expired and oldest entries to make room.
*/
private evict;
/**
* Get cache statistics.
*/
getStats(): {
size: number;
maxSize: number;
hits: number;
misses: number;
evictions: number;
hitRate: string;
};
/**
* Clear all cached entries.
*/
clear(): void;
/**
* Check if cache is enabled.
*/
isEnabled(): boolean;
}
/**
* Balance Monitor for XClawRouter
*
* Monitors USDC balance on Base network with intelligent caching.
* Provides pre-request balance checks to prevent failed payments.
*
* Caching Strategy:
* - TTL: 30 seconds (balance is cached to avoid excessive RPC calls)
* - Optimistic deduction: after successful payment, subtract estimated cost from cache
* - Invalidation: on payment failure, immediately refresh from RPC
*/
/** Balance thresholds in USDC smallest unit (6 decimals) */
declare const BALANCE_THRESHOLDS: {
/** Low balance warning threshold: $1.00 */
readonly LOW_BALANCE_MICROS: 1000000n;
/** Effectively zero threshold: $0.0001 (covers dust/rounding) */
readonly ZERO_THRESHOLD: 100n;
};
/** Balance information returned by checkBalance() */
type BalanceInfo = {
/** Raw balance in USDC smallest unit (6 decimals) */
balance: bigint;
/** Formatted balance as "$X.XX" */
balanceUSD: string;
/** True if balance < $1.00 */
isLow: boolean;
/** True if balance < $0.0001 (effectively zero) */
isEmpty: boolean;
/** Wallet address for funding instructions */
walletAddress: string;
};
/** Result from checkSufficient() */
type SufficiencyResult = {
/** True if balance >= estimated cost */
sufficient: boolean;
/** Current balance info */
info: BalanceInfo;
/** If insufficient, the shortfall as "$X.XX" */
shortfall?: string;
};
/**
* Monitors USDC balance on Base network.
*
* Usage:
* const monitor = new BalanceMonitor("0x...");
* const info = await monitor.checkBalance();
* if (info.isLow) console.warn("Low balance!");
*/
declare class BalanceMonitor {
private readonly client;
private readonly walletAddress;
/** Cached balance (null = not yet fetched) */
private cachedBalance;
/** Timestamp when cache was last updated */
private cachedAt;
constructor(walletAddress: string);
/**
* Check current USDC balance.
* Uses cache if valid, otherwise fetches from RPC.
*/
checkBalance(): Promise<BalanceInfo>;
/**
* Check if balance is sufficient for an estimated cost.
*
* @param estimatedCostMicros - Estimated cost in USDC smallest unit (6 decimals)
*/
checkSufficient(estimatedCostMicros: bigint): Promise<SufficiencyResult>;
/**
* Optimistically deduct estimated cost from cached balance.
* Call this after a successful payment to keep cache accurate.
*
* @param amountMicros - Amount to deduct in USDC smallest unit
*/
deductEstimated(amountMicros: bigint): void;
/**
* Invalidate cache, forcing next checkBalance() to fetch from RPC.
* Call this after a payment failure to get accurate balance.
*/
invalidate(): void;
/**
* Force refresh balance from RPC (ignores cache).
*/
refresh(): Promise<BalanceInfo>;
/**
* Format USDC amount (in micros) as "$X.XX".
*/
formatUSDC(amountMicros: bigint): string;
/**
* Get the wallet address being monitored.
*/
getWalletAddress(): string;
/** Fetch balance from RPC */
private fetchBalance;
/** Build BalanceInfo from raw balance */
private buildInfo;
}
/**
* Solana USDC Balance Monitor
*
* Checks USDC balance on Solana mainnet with caching.
* Absorbed from @blockrun/clawwallet's solana-adapter.ts (balance portion only).
*/
type SolanaBalanceInfo = {
balance: bigint;
balanceUSD: string;
isLow: boolean;
isEmpty: boolean;
walletAddress: string;
};
/** Result from checkSufficient() */
type SolanaSufficiencyResult = {
sufficient: boolean;
info: SolanaBalanceInfo;
shortfall?: string;
};
declare class SolanaBalanceMonitor {
private readonly rpc;
private readonly walletAddress;
private cachedBalance;
private cachedAt;
constructor(walletAddress: string, rpcUrl?: string);
checkBalance(): Promise<SolanaBalanceInfo>;
deductEstimated(amountMicros: bigint): void;
invalidate(): void;
refresh(): Promise<SolanaBalanceInfo>;
/**
* Check if balance is sufficient for an estimated cost.
*/
checkSufficient(estimatedCostMicros: bigint): Promise<SolanaSufficiencyResult>;
/**
* Format USDC amount (in micros) as "$X.XX".
*/
formatUSDC(amountMicros: bigint): string;
getWalletAddress(): string;
/**
* Check native SOL balance (in lamports). Useful for detecting users who
* funded with SOL instead of USDC.
*/
checkSolBalance(): Promise<bigint>;
private fetchBalance;
private fetchBalanceOnce;
private buildInfo;
}
/**
* OnchainOsAdapter — thin wrapper around OKX's `onchainos` CLI.
*
* The CLI owns wallet state (email login, key material, on-chain interaction).
* XClawRouter shells out to it for wallet identity and x402 payment signing
* so private keys never live in this process.
*
* CLI surface used here (verified against okxclawrouter sample):
* onchainos --version
* onchainos wallet status → { data: { loggedIn, evmAddress?, email? } }
* onchainos wallet addresses → { data: { evm?, xlayer?, solana? } }
* Each chain may be a string, an array
* of strings, or an array of objects
* with an `address` field — handled
* tolerantly by `addresses()`.
* onchainos wallet login <email> (interactive)
* onchainos wallet logout
* onchainos payment x402-pay --accepts <json>
* → { data: { signature, authorization, sessionCert? } }
*
* Some onchainos builds omit `evmAddress` from `wallet status` even when the
* user is logged in. Callers should fall back to `addresses()` to recover the
* Base/EVM address rather than treating "no evmAddress in status" as "no
* onchainos wallet".
*
* Raw EIP-712 / typed-data signing is NOT exposed by onchainos, so we use
* `payment x402-pay` for the entire signing step rather than the @x402/fetch
* signer plumbing. See proxy.ts for the call site.
*/
interface OnchainOsStatus {
loggedIn: boolean;
email?: string;
evmAddress?: `0x${string}`;
solanaAddress?: string;
}
interface OnchainOsAddresses {
/** Base / EVM address. */
evm?: `0x${string}`;
/** OKX X Layer address (EVM-compatible). */
xlayer?: `0x${string}`;
/** Solana base58 address. */
solana?: string;
}
interface OnchainOsX402Payment {
signature: string;
authorization: Record<string, unknown>;
sessionCert?: string;
}
interface OnchainOsAdapterOptions {
/** Override the CLI binary path. Defaults to env var, then PATH, then common installs. */
bin?: string;
/** Per-command timeout in ms. */
timeoutMs?: number;
}
declare class OnchainOsAdapter {
private readonly bin;
private readonly timeoutMs;
constructor(opts?: OnchainOsAdapterOptions);
/** Quick, synchronous probe — does the binary exist and respond to --version? */
isInstalled(): boolean;
status(): Promise<OnchainOsStatus>;
/**
* Fetch the wallet's addresses across chains. Use this as a fallback when
* `wallet status` doesn't include `evmAddress` — some onchainos builds omit
* the address from status but still expose it via `wallet addresses`.
*
* Tolerates the three shapes onchainos has shipped for each chain entry:
* - bare string: `"0xabc..."`
* - array of strings: `["0xabc...", "0xdef..."]`
* - array of objects: `[{ address: "0xabc...", chain: "base" }, ...]`
*/
addresses(): Promise<OnchainOsAddresses>;
login(email: string): Promise<void>;
logout(): Promise<void>;
/**
* Sign an x402 payment via onchainos. Pass through the full `accepts` array
* from the 402 response — onchainos picks the chain/scheme it can satisfy.
*/
signX402Payment(accepts: unknown[]): Promise<OnchainOsX402Payment>;
}
/**
* XClawRouter wallet resolution.
*
* Wallet identity is resolved in this order:
* 1. OKX onchainos CLI (if installed AND user is logged in) — preferred.
* Private keys never enter this process; signing happens via
* `onchainos payment x402-pay`. See onchainos-adapter.ts.
* 2. Saved wallet.key file (legacy BIP-39 path — preserved for existing users)
* 3. BLOCKRUN_WALLET_KEY env var (legacy)
* 4. Auto-generated BIP-39 wallet — **opt-in only**, gated behind
* `XCLAWROUTER_USE_LOCAL_WALLET=1`. On a fresh install with no OKX
* wallet, resolution throws `OnchainOsRequiredError` instead of silently
* generating a local key. This is the fix for "一装就生成本地 wallet"
* — users should be guided to install/login onchainos, not handed a
* local key they don't realize is in play.
*/
/**
* Result of attempting to use the OKX onchainos Agentic Wallet.
*
* Every non-`ok` variant must be distinguishable by the caller — otherwise
* users who half-installed onchainos, forgot to log in, or hit a transient CLI
* error get the same silent local-key fallback and never learn why their OKX
* wallet wasn't picked up.
*
* - `ok` — onchainos is installed, logged in, and we have a usable EVM address.
* - `no-binary` — onchainos CLI is not on PATH. Tip handled at the call site
* (companion onboarding-tip issue covers when/how to suggest installing).
* - `not-logged-in` — binary is installed but `wallet status` reports
* `loggedIn: false`. User just needs to run `onchainos login`.
* - `status-error` — `wallet status` exited non-zero, timed out, or returned
* malformed output. `reason` carries the underlying CLI error message.
* - `no-evm-address` — status is logged in but neither `wallet status` nor the
* `wallet addresses` fallback yielded an EVM address (e.g. a Solana-only
* account).
* - `addresses-error` — status was logged in without an `evmAddress`, but the
* `wallet addresses` fallback itself failed. `reason` carries the CLI error.
*/
type OnchainOsDetectionResult = {
kind: "ok";
address: `0x${string}`;
email?: string;
adapter: OnchainOsAdapter;
} | {
kind: "no-binary";
} | {
kind: "not-logged-in";
} | {
kind: "status-error";
reason: string;
} | {
kind: "no-evm-address";
} | {
kind: "addresses-error";
reason: string;
};
declare function savePaymentChain(chain: "base" | "solana"): Promise<void>;
declare function loadPaymentChain(): Promise<"base" | "solana">;
/**
* Resolve payment chain: env var → persisted file → default "base".
* Accepts both XCLAWROUTER_PAYMENT_CHAIN (preferred) and CLAWROUTER_PAYMENT_CHAIN
* (legacy, deprecated — will be removed after one release).
*/
declare function resolvePaymentChain(): Promise<"base" | "solana">;
/**
* Result of wallet resolution.
*
* - `source: "okx"` — OKX onchainos wallet is connected. `key` is undefined
* because signing is delegated to onchainos (no private key in this process).
* `onchainos` is the adapter the proxy uses to sign x402 payments.
* - `source: "saved" | "env" | "config" | "generated"` — local key path.
*/
type WalletResolution = {
key?: string;
address: string;
source: "saved" | "env" | "config" | "generated" | "okx";
mnemonic?: string;
solanaPrivateKeyBytes?: Uint8Array;
onchainos?: OnchainOsAdapter;
email?: string;
/**
* The outcome of OKX onchainos detection. Present whenever
* `resolveOrGenerateWalletKey` ran the detection — callers use this to
* decide which warning, if any, to show the user. `kind: "ok"` accompanies
* `source: "okx"`; any other kind means we fell back to a local key.
*/
onchainosDetection?: OnchainOsDetectionResult;
};
/** Set up Solana for an existing local-key wallet. Not used in OKX mode. */
declare function setupSolana(): Promise<{
mnemonic: string;
solanaPrivateKeyBytes: Uint8Array;
}>;
/**
* Session Persistence Store
*
* Tracks model selections per session to prevent model switching mid-task.
* When a session is active, the router will continue using the same model
* instead of re-routing each request.
*/
type SessionEntry = {
model: string;
tier: string;
createdAt: number;
lastUsedAt: number;
requestCount: number;
/**
* `true` when the user explicitly chose this model (e.g. /model command in
* OpenClaw or sending an explicit non-profile model in the request body).
* Explicit pins are sticky — they're NOT overridden by tier escalation when
* a future routing-profile request comes in. The user's intent wins.
*/
userExplicit?: boolean;
recentHashes: string[];
strikes: number;
escalated: boolean;
sessionCostMicros: bigint;
};
type SessionConfig = {
/** Enable session persistence (default: false) */
enabled: boolean;
/** Session timeout in ms (default: 30 minutes) */
timeoutMs: number;
/** Header name for session ID (default: X-Session-ID) */
headerName: string;
};
declare const DEFAULT_SESSION_CONFIG: SessionConfig;
/**
* Session persistence store for maintaining model selections.
*/
declare class SessionStore {
private sessions;
private config;
private cleanupInterval;
constructor(config?: Partial<SessionConfig>);
/**
* Get the pinned model for a session, if any.
*/
getSession(sessionId: string): SessionEntry | undefined;
/**
* Pin a model to a session.
*
* Pass `userExplicit: true` when the user explicitly chose this model