@t2000/engine 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,838 @@
1
+ import { z } from 'zod';
2
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
3
+ import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
4
+ import { Tool as Tool$1 } from '@modelcontextprotocol/sdk/types.js';
5
+ import * as _t2000_sdk from '@t2000/sdk';
6
+ import { T2000 } from '@t2000/sdk';
7
+
8
+ type ContentBlock = {
9
+ type: 'text';
10
+ text: string;
11
+ } | {
12
+ type: 'tool_use';
13
+ id: string;
14
+ name: string;
15
+ input: unknown;
16
+ } | {
17
+ type: 'tool_result';
18
+ toolUseId: string;
19
+ content: string;
20
+ isError?: boolean;
21
+ };
22
+ interface Message {
23
+ role: 'user' | 'assistant';
24
+ content: ContentBlock[];
25
+ }
26
+ type EngineEvent = {
27
+ type: 'text_delta';
28
+ text: string;
29
+ } | {
30
+ type: 'tool_start';
31
+ toolName: string;
32
+ toolUseId: string;
33
+ input: unknown;
34
+ } | {
35
+ type: 'tool_result';
36
+ toolName: string;
37
+ toolUseId: string;
38
+ result: unknown;
39
+ isError: boolean;
40
+ } | {
41
+ type: 'permission_request';
42
+ toolName: string;
43
+ toolUseId: string;
44
+ input: unknown;
45
+ description: string;
46
+ resolve: (approved: boolean) => void;
47
+ } | {
48
+ type: 'turn_complete';
49
+ stopReason: StopReason;
50
+ } | {
51
+ type: 'usage';
52
+ inputTokens: number;
53
+ outputTokens: number;
54
+ cacheReadTokens?: number;
55
+ cacheWriteTokens?: number;
56
+ } | {
57
+ type: 'error';
58
+ error: Error;
59
+ };
60
+ type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'max_turns' | 'error';
61
+ type PermissionLevel = 'auto' | 'confirm' | 'explicit';
62
+ interface ToolResult<T = unknown> {
63
+ data: T;
64
+ displayText?: string;
65
+ }
66
+ interface ToolContext {
67
+ agent?: unknown;
68
+ mcpManager?: unknown;
69
+ walletAddress?: string;
70
+ signal?: AbortSignal;
71
+ }
72
+ interface ToolJsonSchema {
73
+ type: 'object';
74
+ properties: Record<string, unknown>;
75
+ required?: string[];
76
+ }
77
+ interface Tool<TInput = unknown, TOutput = unknown> {
78
+ name: string;
79
+ description: string;
80
+ inputSchema: z.ZodType<TInput>;
81
+ jsonSchema: ToolJsonSchema;
82
+ call(input: TInput, context: ToolContext): Promise<ToolResult<TOutput>>;
83
+ isConcurrencySafe: boolean;
84
+ isReadOnly: boolean;
85
+ permissionLevel: PermissionLevel;
86
+ }
87
+ interface EngineConfig {
88
+ provider: LLMProvider;
89
+ agent?: unknown;
90
+ mcpManager?: unknown;
91
+ walletAddress?: string;
92
+ tools?: Tool[];
93
+ systemPrompt?: string;
94
+ model?: string;
95
+ maxTurns?: number;
96
+ maxTokens?: number;
97
+ costTracker?: {
98
+ budgetLimitUsd?: number;
99
+ inputCostPerToken?: number;
100
+ outputCostPerToken?: number;
101
+ };
102
+ }
103
+ interface LLMProvider {
104
+ chat(params: ChatParams): AsyncGenerator<ProviderEvent>;
105
+ }
106
+ interface ChatParams {
107
+ messages: Message[];
108
+ systemPrompt: string;
109
+ tools: ToolDefinition[];
110
+ model?: string;
111
+ maxTokens?: number;
112
+ signal?: AbortSignal;
113
+ }
114
+ interface ToolDefinition {
115
+ name: string;
116
+ description: string;
117
+ input_schema: ToolJsonSchema;
118
+ }
119
+ type ProviderEvent = {
120
+ type: 'text_delta';
121
+ text: string;
122
+ } | {
123
+ type: 'tool_use_start';
124
+ id: string;
125
+ name: string;
126
+ } | {
127
+ type: 'tool_use_delta';
128
+ id: string;
129
+ partialJson: string;
130
+ } | {
131
+ type: 'tool_use_done';
132
+ id: string;
133
+ name: string;
134
+ input: unknown;
135
+ } | {
136
+ type: 'message_start';
137
+ messageId: string;
138
+ model: string;
139
+ } | {
140
+ type: 'usage';
141
+ inputTokens: number;
142
+ outputTokens: number;
143
+ cacheReadTokens?: number;
144
+ cacheWriteTokens?: number;
145
+ } | {
146
+ type: 'stop';
147
+ reason: StopReason;
148
+ };
149
+
150
+ interface CostSnapshot {
151
+ inputTokens: number;
152
+ outputTokens: number;
153
+ cacheReadTokens: number;
154
+ cacheWriteTokens: number;
155
+ totalTokens: number;
156
+ estimatedCostUsd: number;
157
+ }
158
+ interface CostTrackerConfig {
159
+ budgetLimitUsd?: number;
160
+ inputCostPerToken?: number;
161
+ outputCostPerToken?: number;
162
+ }
163
+ declare class CostTracker {
164
+ private inputTokens;
165
+ private outputTokens;
166
+ private cacheReadTokens;
167
+ private cacheWriteTokens;
168
+ private readonly budgetLimitUsd;
169
+ private readonly inputCost;
170
+ private readonly outputCost;
171
+ constructor(config?: CostTrackerConfig);
172
+ track(inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): void;
173
+ getSnapshot(): CostSnapshot;
174
+ isOverBudget(): boolean;
175
+ getRemainingBudgetUsd(): number | null;
176
+ reset(): void;
177
+ }
178
+
179
+ declare class QueryEngine {
180
+ private readonly provider;
181
+ private readonly tools;
182
+ private readonly systemPrompt;
183
+ private readonly model;
184
+ private readonly maxTurns;
185
+ private readonly maxTokens;
186
+ private readonly agent;
187
+ private readonly mcpManager;
188
+ private readonly walletAddress;
189
+ private readonly txMutex;
190
+ private readonly costTracker;
191
+ private messages;
192
+ private abortController;
193
+ constructor(config: EngineConfig);
194
+ /**
195
+ * Submit a user message and receive a stream of engine events.
196
+ * Handles the full agent loop: LLM → permission check → tool execution → LLM → ...
197
+ */
198
+ submitMessage(prompt: string): AsyncGenerator<EngineEvent>;
199
+ interrupt(): void;
200
+ getMessages(): readonly Message[];
201
+ reset(): void;
202
+ loadMessages(messages: Message[]): void;
203
+ getUsage(): CostSnapshot;
204
+ private handleProviderEvent;
205
+ }
206
+
207
+ interface BuildToolOptions<TInput, TOutput> {
208
+ name: string;
209
+ description: string;
210
+ inputSchema: z.ZodType<TInput>;
211
+ jsonSchema: ToolJsonSchema;
212
+ call: (input: TInput, context: ToolContext) => Promise<ToolResult<TOutput>>;
213
+ isReadOnly?: boolean;
214
+ permissionLevel?: PermissionLevel;
215
+ }
216
+ declare function buildTool<TInput, TOutput>(opts: BuildToolOptions<TInput, TOutput>): Tool<TInput, TOutput>;
217
+ declare function toolsToDefinitions(tools: Tool[]): {
218
+ name: string;
219
+ description: string;
220
+ input_schema: ToolJsonSchema;
221
+ }[];
222
+ declare function findTool(tools: Tool[], name: string): Tool | undefined;
223
+
224
+ interface PendingToolCall {
225
+ id: string;
226
+ name: string;
227
+ input: unknown;
228
+ }
229
+ declare class TxMutex {
230
+ private queue;
231
+ private locked;
232
+ acquire(): Promise<void>;
233
+ release(): void;
234
+ }
235
+ declare function runTools(pending: PendingToolCall[], tools: Tool[], context: ToolContext, txMutex: TxMutex): AsyncGenerator<EngineEvent>;
236
+
237
+ /**
238
+ * Wire-safe representation of EngineEvent for SSE transport.
239
+ * `permission_request` replaces the `resolve` callback with a `permissionId`
240
+ * that the client sends back via a separate HTTP endpoint.
241
+ */
242
+ type SSEEvent = {
243
+ type: 'text_delta';
244
+ text: string;
245
+ } | {
246
+ type: 'tool_start';
247
+ toolName: string;
248
+ toolUseId: string;
249
+ input: unknown;
250
+ } | {
251
+ type: 'tool_result';
252
+ toolName: string;
253
+ toolUseId: string;
254
+ result: unknown;
255
+ isError: boolean;
256
+ } | {
257
+ type: 'permission_request';
258
+ permissionId: string;
259
+ toolName: string;
260
+ toolUseId: string;
261
+ input: unknown;
262
+ description: string;
263
+ } | {
264
+ type: 'turn_complete';
265
+ stopReason: StopReason;
266
+ } | {
267
+ type: 'usage';
268
+ inputTokens: number;
269
+ outputTokens: number;
270
+ cacheReadTokens?: number;
271
+ cacheWriteTokens?: number;
272
+ } | {
273
+ type: 'error';
274
+ message: string;
275
+ };
276
+ declare function serializeSSE(event: SSEEvent): string;
277
+ declare function parseSSE(raw: string): SSEEvent | null;
278
+ declare class PermissionBridge {
279
+ private pending;
280
+ private counter;
281
+ /**
282
+ * Register a permission_request resolve callback.
283
+ * Returns the permissionId to send to the client.
284
+ */
285
+ register(resolve: (approved: boolean) => void): string;
286
+ /**
287
+ * Resolve a pending permission request from the client.
288
+ * Returns false if the permissionId is unknown (expired or invalid).
289
+ */
290
+ resolve(permissionId: string, approved: boolean): boolean;
291
+ /** Number of pending (unresolved) permission requests. */
292
+ get size(): number;
293
+ /** Reject all pending permissions (e.g., on disconnect). */
294
+ rejectAll(): void;
295
+ }
296
+ /**
297
+ * Wraps a QueryEngine.submitMessage() generator, converting EngineEvents
298
+ * to SSE text. Permission requests are routed through the bridge.
299
+ */
300
+ declare function engineToSSE(events: AsyncGenerator<EngineEvent>, bridge: PermissionBridge): AsyncGenerator<string>;
301
+
302
+ interface SessionData {
303
+ id: string;
304
+ messages: Message[];
305
+ usage: CostSnapshot;
306
+ createdAt: number;
307
+ updatedAt: number;
308
+ metadata?: Record<string, unknown>;
309
+ }
310
+ interface SessionStore {
311
+ /** Load a session by ID. Returns null if not found or expired. */
312
+ get(sessionId: string): Promise<SessionData | null>;
313
+ /** Save or update a session. */
314
+ set(session: SessionData): Promise<void>;
315
+ /** Delete a session. */
316
+ delete(sessionId: string): Promise<void>;
317
+ /** Check if a session exists. */
318
+ exists(sessionId: string): Promise<boolean>;
319
+ }
320
+ declare class MemorySessionStore implements SessionStore {
321
+ private store;
322
+ private readonly ttlMs;
323
+ constructor(opts?: {
324
+ ttlMs?: number;
325
+ });
326
+ get(sessionId: string): Promise<SessionData | null>;
327
+ set(session: SessionData): Promise<void>;
328
+ delete(sessionId: string): Promise<void>;
329
+ exists(sessionId: string): Promise<boolean>;
330
+ /** For testing: number of active (non-expired) sessions. */
331
+ get size(): number;
332
+ private evictExpired;
333
+ }
334
+
335
+ /** Rough token count for a message array. */
336
+ declare function estimateTokens(messages: Message[]): number;
337
+ interface CompactOptions {
338
+ /** Max token budget for the conversation. Default 100_000. */
339
+ maxTokens?: number;
340
+ /** Number of recent messages to always keep uncompacted. Default 6. */
341
+ keepRecentCount?: number;
342
+ /** System prompt token estimate (subtracted from budget). Default 500. */
343
+ systemPromptTokens?: number;
344
+ }
345
+ /**
346
+ * Compact a conversation that exceeds the token budget.
347
+ *
348
+ * Strategy:
349
+ * 1. Always preserve the most recent `keepRecentCount` messages (the active context).
350
+ * 2. For older messages, summarise tool_result content to a brief one-liner.
351
+ * 3. If still over budget, drop the oldest messages (keeping the first user message
352
+ * for context continuity).
353
+ *
354
+ * Returns a new array — does not mutate the input.
355
+ */
356
+ declare function compactMessages(messages: readonly Message[], opts?: CompactOptions): Message[];
357
+
358
+ interface McpToolDescriptor {
359
+ name: string;
360
+ description: string;
361
+ inputSchema: Record<string, unknown>;
362
+ handler: (args: Record<string, unknown>) => Promise<{
363
+ content: Array<{
364
+ type: 'text';
365
+ text: string;
366
+ }>;
367
+ isError?: boolean;
368
+ }>;
369
+ }
370
+ /**
371
+ * Builds MCP-compatible tool descriptors from engine tools.
372
+ * Each tool's `call()` is wrapped to return the MCP response format.
373
+ *
374
+ * Usage with @modelcontextprotocol/sdk:
375
+ * ```
376
+ * const descriptors = buildMcpTools(context);
377
+ * for (const desc of descriptors) {
378
+ * server.tool(desc.name, desc.description, desc.inputSchema, desc.handler);
379
+ * }
380
+ * ```
381
+ */
382
+ declare function buildMcpTools(context: ToolContext, tools?: Tool[]): McpToolDescriptor[];
383
+ /**
384
+ * Register all engine tools with an MCP server instance.
385
+ * Convenience wrapper for the common pattern.
386
+ */
387
+ declare function registerEngineTools(server: {
388
+ tool: (name: string, description: string, schema: Record<string, unknown>, handler: (args: Record<string, unknown>) => Promise<unknown>) => void;
389
+ }, context: ToolContext, tools?: Tool[]): void;
390
+
391
+ interface McpServerConfig {
392
+ /** Human-readable server name, used as tool namespace prefix. */
393
+ name: string;
394
+ /** MCP server URL (Streamable HTTP or SSE endpoint). */
395
+ url: string;
396
+ /** Transport type. Defaults to 'streamable-http'. */
397
+ transport?: 'streamable-http' | 'sse';
398
+ /** Response cache TTL in ms. Default 30_000 (30s). */
399
+ cacheTtlMs?: number;
400
+ /** Whether all tools from this server are read-only. Default true. */
401
+ readOnly?: boolean;
402
+ }
403
+ interface McpServerConnection {
404
+ config: McpServerConfig;
405
+ client: Client;
406
+ transport: Transport;
407
+ tools: Tool$1[];
408
+ status: 'connected' | 'disconnected' | 'error';
409
+ lastError?: string;
410
+ }
411
+ interface McpCallResult {
412
+ content: Array<{
413
+ type: string;
414
+ text?: string;
415
+ [key: string]: unknown;
416
+ }>;
417
+ isError?: boolean;
418
+ }
419
+ declare class McpResponseCache {
420
+ private cache;
421
+ private readonly defaultTtlMs;
422
+ constructor(defaultTtlMs?: number);
423
+ private key;
424
+ get(serverName: string, toolName: string, args: unknown): McpCallResult | null;
425
+ set(serverName: string, toolName: string, args: unknown, result: McpCallResult, ttlMs?: number): void;
426
+ invalidate(serverName?: string): void;
427
+ get size(): number;
428
+ }
429
+ declare class McpClientManager {
430
+ private connections;
431
+ private readonly responseCache;
432
+ constructor(opts?: {
433
+ cacheTtlMs?: number;
434
+ });
435
+ /**
436
+ * Connect to an MCP server and discover its tools.
437
+ * If already connected to a server with this name, disconnects first.
438
+ */
439
+ connect(config: McpServerConfig): Promise<McpServerConnection>;
440
+ /** Disconnect from a server by name. */
441
+ disconnect(name: string): Promise<void>;
442
+ /** Disconnect from all servers. */
443
+ disconnectAll(): Promise<void>;
444
+ /** Get a connection by server name. */
445
+ getConnection(name: string): McpServerConnection | undefined;
446
+ /** Check if a server is connected. */
447
+ isConnected(name: string): boolean;
448
+ /** List all tool definitions across all connected servers. */
449
+ listAllTools(): Array<{
450
+ serverName: string;
451
+ tool: Tool$1;
452
+ }>;
453
+ /**
454
+ * Call a tool on a specific server.
455
+ * Uses response cache for read-only servers.
456
+ */
457
+ callTool(serverName: string, toolName: string, args?: Record<string, unknown>): Promise<McpCallResult>;
458
+ /** Get the response cache (for testing / manual invalidation). */
459
+ get cache(): McpResponseCache;
460
+ /** Number of connected servers. */
461
+ get serverCount(): number;
462
+ /** All server names. */
463
+ get serverNames(): string[];
464
+ }
465
+
466
+ interface McpToolAdapterConfig {
467
+ /** The McpClientManager to route calls through. */
468
+ manager: McpClientManager;
469
+ /** Server name this tool belongs to. */
470
+ serverName: string;
471
+ /** Override permission level for all tools from this server. */
472
+ permissionLevel?: PermissionLevel;
473
+ /** Override isReadOnly for all tools from this server. */
474
+ isReadOnly?: boolean;
475
+ /** Per-tool overrides keyed by MCP tool name. */
476
+ toolOverrides?: Record<string, {
477
+ permissionLevel?: PermissionLevel;
478
+ isReadOnly?: boolean;
479
+ description?: string;
480
+ }>;
481
+ }
482
+ /**
483
+ * Convert a single MCP tool definition into an engine Tool.
484
+ * The tool name is namespaced as `{serverName}_{mcpToolName}`.
485
+ */
486
+ declare function adaptMcpTool(mcpTool: Tool$1, config: McpToolAdapterConfig): Tool;
487
+ /**
488
+ * Convert all discovered tools from an MCP server into engine Tools.
489
+ * Call this after `manager.connect(config)` completes successfully.
490
+ */
491
+ declare function adaptAllMcpTools(config: McpToolAdapterConfig): Tool[];
492
+ /**
493
+ * Convenience: adapt tools from all connected servers.
494
+ * Returns a flat array of engine Tools, namespaced by server name.
495
+ */
496
+ declare function adaptAllServerTools(manager: McpClientManager, serverConfigs?: Record<string, Omit<McpToolAdapterConfig, 'manager' | 'serverName'>>): Tool[];
497
+
498
+ declare const NAVI_SERVER_NAME = "navi";
499
+ declare const NAVI_MCP_URL = "https://open-api.naviprotocol.io/api/mcp";
500
+ declare const NAVI_MCP_CONFIG: McpServerConfig;
501
+ declare const NaviTools: {
502
+ readonly GET_POOLS: "navi_get_pools";
503
+ readonly GET_POOL: "navi_get_pool";
504
+ readonly GET_PROTOCOL_STATS: "navi_get_protocol_stats";
505
+ readonly GET_HEALTH_FACTOR: "navi_get_health_factor";
506
+ readonly GET_BORROW_FEE: "navi_get_borrow_fee";
507
+ readonly GET_FEES: "navi_get_fees";
508
+ readonly GET_FLASH_LOAN_ASSETS: "navi_get_flash_loan_assets";
509
+ readonly GET_FLASH_LOAN_ASSET: "navi_get_flash_loan_asset";
510
+ readonly GET_LENDING_REWARDS: "navi_get_lending_rewards";
511
+ readonly GET_AVAILABLE_REWARDS: "navi_get_available_rewards";
512
+ readonly GET_PRICE_FEEDS: "navi_get_price_feeds";
513
+ readonly GET_SWAP_QUOTE: "navi_get_swap_quote";
514
+ readonly GET_BRIDGE_CHAINS: "navi_get_bridge_chains";
515
+ readonly SEARCH_BRIDGE_TOKENS: "navi_search_bridge_tokens";
516
+ readonly GET_BRIDGE_QUOTE: "navi_get_bridge_quote";
517
+ readonly GET_BRIDGE_TX_STATUS: "navi_get_bridge_tx_status";
518
+ readonly GET_BRIDGE_HISTORY: "navi_get_bridge_history";
519
+ readonly GET_DCA_ORDERS: "navi_get_dca_orders";
520
+ readonly GET_DCA_ORDER_DETAILS: "navi_get_dca_order_details";
521
+ readonly LIST_DCA_ORDERS: "navi_list_dca_orders";
522
+ readonly GET_COINS: "navi_get_coins";
523
+ readonly GET_MARKET_CONFIG: "navi_get_market_config";
524
+ readonly GET_POSITIONS: "get_positions";
525
+ readonly GET_TRANSACTION: "sui_get_transaction";
526
+ readonly EXPLAIN_TRANSACTION: "sui_explain_transaction";
527
+ readonly SEARCH_TOKENS: "navi_search_tokens";
528
+ };
529
+
530
+ interface NaviRawPool {
531
+ id: number;
532
+ symbol: string;
533
+ coinType: string;
534
+ price: string;
535
+ market: string;
536
+ ltv: number;
537
+ liquidation: {
538
+ bonus: string;
539
+ ratio: string;
540
+ threshold: string;
541
+ };
542
+ supply: string;
543
+ borrow: string;
544
+ supplyApy: string;
545
+ borrowApy: string;
546
+ }
547
+ interface NaviRawPosition {
548
+ id: string;
549
+ protocol: string;
550
+ type: string;
551
+ market: string;
552
+ tokenASymbol: string;
553
+ tokenAPrice: number;
554
+ amountA: string;
555
+ tokenBSymbol?: string | null;
556
+ tokenBPrice?: number | null;
557
+ amountB?: string | null;
558
+ valueUSD: string;
559
+ apr: string;
560
+ liquidationThreshold: string;
561
+ lowerPrice?: string | null;
562
+ upperPrice?: string | null;
563
+ currentPrice?: string | null;
564
+ claimableRewards?: string | null;
565
+ isActive?: boolean;
566
+ }
567
+ interface NaviRawPositionsResponse {
568
+ address: string;
569
+ positions: NaviRawPosition[];
570
+ }
571
+ interface NaviRawHealthFactor {
572
+ address: string;
573
+ healthFactor: number | null;
574
+ }
575
+ interface NaviRawCoin {
576
+ coinType: string;
577
+ totalBalance: string;
578
+ coinObjectCount: number;
579
+ symbol?: string;
580
+ decimals?: number;
581
+ }
582
+ interface NaviRawRewardsResponse {
583
+ address: string;
584
+ rewards: Array<{
585
+ pool?: string;
586
+ rewardType?: string;
587
+ amount?: string;
588
+ symbol?: string;
589
+ valueUsd?: number;
590
+ }>;
591
+ summary: Array<{
592
+ symbol: string;
593
+ totalAmount: string;
594
+ valueUSD?: string;
595
+ }>;
596
+ }
597
+ interface NaviRawProtocolStats {
598
+ tvl: number;
599
+ totalBorrowUsd: number;
600
+ averageUtilization: number;
601
+ maxApy: number;
602
+ userAmount: number;
603
+ interactionUserAmount: number;
604
+ borrowFee: number;
605
+ }
606
+ interface RatesResult {
607
+ [symbol: string]: {
608
+ saveApy: number;
609
+ borrowApy: number;
610
+ ltv: number;
611
+ price: number;
612
+ };
613
+ }
614
+ interface HealthFactorResult {
615
+ healthFactor: number;
616
+ supplied: number;
617
+ borrowed: number;
618
+ maxBorrow: number;
619
+ liquidationThreshold: number;
620
+ }
621
+ interface BalanceResult {
622
+ available: number;
623
+ savings: number;
624
+ debt: number;
625
+ pendingRewards: number;
626
+ gasReserve: number;
627
+ total: number;
628
+ stables: number;
629
+ }
630
+ interface PositionEntry {
631
+ protocol: string;
632
+ type: 'supply' | 'borrow';
633
+ symbol: string;
634
+ amount: number;
635
+ valueUsd: number;
636
+ apy: number;
637
+ liquidationThreshold: number;
638
+ }
639
+ interface SavingsResult {
640
+ positions: PositionEntry[];
641
+ earnings: {
642
+ totalYieldEarned: number;
643
+ currentApy: number;
644
+ dailyEarning: number;
645
+ supplied: number;
646
+ };
647
+ fundStatus: {
648
+ supplied: number;
649
+ apy: number;
650
+ earnedToday: number;
651
+ earnedAllTime: number;
652
+ projectedMonthly: number;
653
+ };
654
+ }
655
+ declare function transformRates(raw: unknown): RatesResult;
656
+ declare function transformPositions(raw: unknown): PositionEntry[];
657
+ declare function transformHealthFactor(rawHf: unknown, rawPositions?: unknown): HealthFactorResult;
658
+ interface PendingReward {
659
+ symbol: string;
660
+ totalAmount: number;
661
+ valueUsd: number;
662
+ }
663
+ declare function transformRewards(raw: unknown): PendingReward[];
664
+ interface BalancePrices {
665
+ [symbol: string]: number;
666
+ }
667
+ declare function transformBalance(rawCoins: unknown, rawPositions: unknown, rawRewards: unknown, prices?: BalancePrices): BalanceResult;
668
+ declare function transformSavings(rawPositions: unknown, rawPools: unknown): SavingsResult;
669
+ declare function extractMcpText(content: Array<{
670
+ type: string;
671
+ text?: string;
672
+ [key: string]: unknown;
673
+ }>): string;
674
+ declare function parseMcpJson<T = unknown>(content: Array<{
675
+ type: string;
676
+ text?: string;
677
+ [key: string]: unknown;
678
+ }>): T;
679
+
680
+ interface NaviReadOptions {
681
+ /** MCP server name override (default: 'navi'). */
682
+ serverName?: string;
683
+ }
684
+ declare function fetchRates(manager: McpClientManager, opts?: NaviReadOptions): Promise<RatesResult>;
685
+ declare function fetchHealthFactor(manager: McpClientManager, address: string, opts?: NaviReadOptions): Promise<HealthFactorResult>;
686
+ declare function fetchBalance(manager: McpClientManager, address: string, opts?: NaviReadOptions): Promise<BalanceResult>;
687
+ declare function fetchSavings(manager: McpClientManager, address: string, opts?: NaviReadOptions): Promise<SavingsResult>;
688
+ declare function fetchPositions(manager: McpClientManager, address: string, opts?: NaviReadOptions & {
689
+ protocols?: string;
690
+ }): Promise<PositionEntry[]>;
691
+ declare function fetchAvailableRewards(manager: McpClientManager, address: string, opts?: NaviReadOptions): Promise<PendingReward[]>;
692
+ interface ProtocolStats {
693
+ tvl: number;
694
+ totalBorrowUsd: number;
695
+ utilization: number;
696
+ maxApy: number;
697
+ totalUsers: number;
698
+ }
699
+ declare function fetchProtocolStats(manager: McpClientManager, opts?: NaviReadOptions): Promise<ProtocolStats>;
700
+
701
+ interface AnthropicProviderConfig {
702
+ apiKey: string;
703
+ defaultModel?: string;
704
+ defaultMaxTokens?: number;
705
+ }
706
+ declare class AnthropicProvider implements LLMProvider {
707
+ private client;
708
+ private defaultModel;
709
+ private defaultMaxTokens;
710
+ constructor(config: AnthropicProviderConfig);
711
+ chat(params: ChatParams): AsyncGenerator<ProviderEvent>;
712
+ }
713
+
714
+ declare const balanceCheckTool: Tool<{}, BalanceResult>;
715
+
716
+ declare const savingsInfoTool: Tool<{}, SavingsResult>;
717
+
718
+ declare const healthCheckTool: Tool<{}, {
719
+ status: string;
720
+ healthFactor: number;
721
+ supplied: number;
722
+ borrowed: number;
723
+ maxBorrow: number;
724
+ liquidationThreshold: number;
725
+ }>;
726
+
727
+ declare const ratesInfoTool: Tool<{}, _t2000_sdk.RatesResult>;
728
+
729
+ declare const transactionHistoryTool: Tool<{
730
+ limit?: number | undefined;
731
+ }, {
732
+ transactions: _t2000_sdk.TransactionRecord[];
733
+ count: number;
734
+ }>;
735
+
736
+ declare const saveDepositTool: Tool<{
737
+ amount: number | "all";
738
+ }, {
739
+ success: boolean;
740
+ tx: string;
741
+ amount: number;
742
+ apy: number;
743
+ fee: number;
744
+ gasCost: number;
745
+ savingsBalance: number;
746
+ }>;
747
+
748
+ declare const withdrawTool: Tool<{
749
+ amount: number | "all";
750
+ }, {
751
+ success: boolean;
752
+ tx: string;
753
+ amount: number;
754
+ gasCost: number;
755
+ }>;
756
+
757
+ declare const sendTransferTool: Tool<{
758
+ amount: number;
759
+ to: string;
760
+ }, {
761
+ success: boolean;
762
+ tx: string;
763
+ amount: number;
764
+ to: string;
765
+ contactName: string | undefined;
766
+ gasCost: number;
767
+ gasMethod: _t2000_sdk.GasMethod;
768
+ balance: _t2000_sdk.BalanceResponse;
769
+ }>;
770
+
771
+ declare const borrowTool: Tool<{
772
+ amount: number;
773
+ }, {
774
+ success: boolean;
775
+ tx: string;
776
+ amount: number;
777
+ fee: number;
778
+ healthFactor: number;
779
+ gasCost: number;
780
+ }>;
781
+
782
+ declare const repayDebtTool: Tool<{
783
+ amount: number | "all";
784
+ }, {
785
+ success: boolean;
786
+ tx: string;
787
+ amount: number;
788
+ remainingDebt: number;
789
+ gasCost: number;
790
+ }>;
791
+
792
+ declare const claimRewardsTool: Tool<{}, {
793
+ success: boolean;
794
+ tx: string | null;
795
+ rewards: _t2000_sdk.PendingReward[];
796
+ totalValueUsd: number;
797
+ gasCost: number;
798
+ }>;
799
+
800
+ declare const payApiTool: Tool<{
801
+ url: string;
802
+ method?: "GET" | "POST" | "PUT" | "DELETE" | undefined;
803
+ body?: string | undefined;
804
+ headers?: Record<string, string> | undefined;
805
+ maxPrice?: number | undefined;
806
+ }, {
807
+ status: number;
808
+ body: unknown;
809
+ paid: boolean;
810
+ cost: number | undefined;
811
+ receipt: {
812
+ reference: string;
813
+ timestamp: string;
814
+ } | undefined;
815
+ }>;
816
+
817
+ declare const READ_TOOLS: Tool[];
818
+ declare const WRITE_TOOLS: Tool[];
819
+ declare function getDefaultTools(): Tool[];
820
+
821
+ declare function requireAgent(context: ToolContext): T2000;
822
+ /**
823
+ * Check if context has an MCP manager with a connected NAVI server
824
+ * and a wallet address for address-dependent reads.
825
+ */
826
+ declare function hasNaviMcp(context: ToolContext): boolean;
827
+ /**
828
+ * Get the MCP client manager from context (assumes hasNaviMcp() is true).
829
+ */
830
+ declare function getMcpManager(context: ToolContext): McpClientManager;
831
+ /**
832
+ * Get the wallet address from context (assumes hasNaviMcp() is true).
833
+ */
834
+ declare function getWalletAddress(context: ToolContext): string;
835
+
836
+ declare const DEFAULT_SYSTEM_PROMPT = "You are Audric, a financial agent operating on the Sui blockchain. You help users manage their USDC through savings, payments, transfers, and credit.\n\n## Capabilities\n- Check balances, savings positions, health factors, and interest rates\n- Execute deposits, withdrawals, transfers, borrows, and repayments\n- Access API services via micropayments (MPP)\n- Track transaction history and earnings\n\n## Guidelines\n\n### Before Acting\n- Always check the user's balance before suggesting financial actions\n- Show real numbers from tool results \u2014 never fabricate rates, amounts, or balances\n- For transactions that move funds, explain what will happen and confirm intent\n\n### Tool Usage\n- Use multiple read-only tools in parallel when you need several data points\n- Present amounts as currency ($1,234.56) and rates as percentages (4.86% APY)\n- If a tool errors, explain the issue clearly and suggest alternatives\n\n### Communication Style\n- Be concise and direct \u2014 users want financial data, not filler\n- Lead with numbers and results, follow with context\n- Use short sentences. Avoid hedging language.\n- When presenting positions or balances, use a structured format\n\n### Safety\n- Never encourage risky financial behavior\n- Warn when health factor drops below 1.5\n- Remind users of gas costs for on-chain transactions\n- All amounts are in USDC unless explicitly stated otherwise";
837
+
838
+ export { AnthropicProvider, type AnthropicProviderConfig, type BalancePrices, type BalanceResult, type BuildToolOptions, type ChatParams, type CompactOptions, type ContentBlock, type CostSnapshot, CostTracker, type CostTrackerConfig, DEFAULT_SYSTEM_PROMPT, type EngineConfig, type EngineEvent, type HealthFactorResult, type LLMProvider, type McpCallResult, McpClientManager, McpResponseCache, type McpServerConfig, type McpServerConnection, type McpToolAdapterConfig, type McpToolDescriptor, MemorySessionStore, type Message, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_SERVER_NAME, type NaviRawCoin, type NaviRawHealthFactor, type NaviRawPool, type NaviRawPosition, type NaviRawPositionsResponse, type NaviRawProtocolStats, type NaviRawRewardsResponse, type NaviReadOptions, NaviTools, type PendingReward, type PendingToolCall, PermissionBridge, type PermissionLevel, type PositionEntry, type ProtocolStats, type ProviderEvent, QueryEngine, READ_TOOLS, type RatesResult, type SSEEvent, type SavingsResult, type SessionData, type SessionStore, type StopReason, type Tool, type ToolContext, type ToolDefinition, type ToolJsonSchema, type ToolResult, TxMutex, WRITE_TOOLS, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, balanceCheckTool, borrowTool, buildMcpTools, buildTool, claimRewardsTool, compactMessages, engineToSSE, estimateTokens, extractMcpText, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, findTool, getDefaultTools, getMcpManager, getWalletAddress, hasNaviMcp, healthCheckTool, parseMcpJson, parseSSE, payApiTool, ratesInfoTool, registerEngineTools, repayDebtTool, requireAgent, runTools, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, withdrawTool };