@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 t2000
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,202 @@
1
+ # @t2000/engine
2
+
3
+ Agent engine for conversational finance — powers the **Audric** consumer product.
4
+
5
+ QueryEngine orchestrates LLM conversations, financial tools, user confirmations, and MCP integrations into a single async-generator loop.
6
+
7
+ ## Quick Start
8
+
9
+ ```typescript
10
+ import { QueryEngine, AnthropicProvider, getDefaultTools } from '@t2000/engine';
11
+ import { T2000 } from '@t2000/sdk';
12
+
13
+ const agent = await T2000.create({ pin: process.env.T2000_PIN });
14
+
15
+ const engine = new QueryEngine({
16
+ provider: new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY }),
17
+ agent,
18
+ tools: getDefaultTools(),
19
+ });
20
+
21
+ for await (const event of engine.submitMessage('What is my balance?')) {
22
+ switch (event.type) {
23
+ case 'text_delta':
24
+ process.stdout.write(event.text);
25
+ break;
26
+ case 'tool_start':
27
+ console.log(`\n[calling ${event.toolName}]`);
28
+ break;
29
+ case 'permission_request':
30
+ event.resolve(true); // auto-approve (or prompt the user)
31
+ break;
32
+ }
33
+ }
34
+ ```
35
+
36
+ ## Architecture
37
+
38
+ ```
39
+ User message
40
+
41
+
42
+ QueryEngine.submitMessage()
43
+
44
+ ├── LLM Provider (Anthropic Claude)
45
+ │ ├── text_delta events → streamed to client
46
+ │ └── tool_use → dispatched to tool system
47
+
48
+ ├── Tool Orchestration (runTools)
49
+ │ ├── Read-only tools → parallel (Promise.allSettled)
50
+ │ └── Write tools → serial (TxMutex)
51
+
52
+ ├── Permission Flow
53
+ │ └── confirm-level tools yield permission_request
54
+ │ → client resolves → tool executes or aborts
55
+
56
+ └── MCP Integration
57
+ ├── MCP Client (McpClientManager) → consume external MCPs
58
+ └── MCP Server (buildMcpTools) → expose tools to AI clients
59
+ ```
60
+
61
+ ## Modules
62
+
63
+ | Module | Export | Purpose |
64
+ |--------|--------|---------|
65
+ | `engine.ts` | `QueryEngine` | Stateful conversation loop with tool dispatch |
66
+ | `tool.ts` | `buildTool` | Typed tool factory with Zod validation |
67
+ | `orchestration.ts` | `runTools`, `TxMutex` | Parallel reads, serial writes |
68
+ | `streaming.ts` | `serializeSSE`, `parseSSE`, `PermissionBridge`, `engineToSSE` | SSE wire format + permission bridging |
69
+ | `session.ts` | `MemorySessionStore` | In-memory session store with TTL |
70
+ | `context.ts` | `estimateTokens`, `compactMessages` | Token estimation + message compaction |
71
+ | `cost.ts` | `CostTracker` | Token usage + USD cost tracking with budget limits |
72
+ | `mcp.ts` | `buildMcpTools`, `registerEngineTools` | Expose engine tools as MCP server |
73
+ | `mcp-client.ts` | `McpClientManager`, `McpResponseCache` | Multi-server MCP client with caching |
74
+ | `mcp-tool-adapter.ts` | `adaptMcpTool`, `adaptAllMcpTools` | Convert MCP tools into engine `Tool` objects |
75
+ | `navi-config.ts` | `NAVI_MCP_CONFIG`, `NaviTools` | NAVI MCP server configuration |
76
+ | `navi-transforms.ts` | `transformRates`, `transformBalance`, ... | Raw MCP response → engine types |
77
+ | `navi-reads.ts` | `fetchRates`, `fetchBalance`, ... | Composite MCP read functions |
78
+ | `prompt.ts` | `DEFAULT_SYSTEM_PROMPT` | Audric system prompt |
79
+ | `providers/anthropic.ts` | `AnthropicProvider` | Anthropic Claude LLM provider |
80
+
81
+ ## Built-in Tools
82
+
83
+ ### Read Tools (parallel, auto-approved)
84
+
85
+ | Tool | Description |
86
+ |------|-------------|
87
+ | `balance_check` | Available, savings, debt, rewards, gas reserve |
88
+ | `savings_info` | Positions, earnings, fund status |
89
+ | `health_check` | Health factor with risk assessment |
90
+ | `rates_info` | Current supply/borrow APYs |
91
+ | `transaction_history` | Recent transaction log |
92
+
93
+ ### Write Tools (serial, confirmation required)
94
+
95
+ | Tool | Description |
96
+ |------|-------------|
97
+ | `save_deposit` | Deposit USDC to savings |
98
+ | `withdraw` | Withdraw from savings |
99
+ | `send_transfer` | Send USDC to an address |
100
+ | `borrow` | Borrow USDC against collateral |
101
+ | `repay_debt` | Repay outstanding debt |
102
+ | `claim_rewards` | Claim pending yield rewards |
103
+ | `pay_api` | Pay for an API service via MPP |
104
+
105
+ ## Configuration
106
+
107
+ ```typescript
108
+ interface EngineConfig {
109
+ provider: LLMProvider; // Required — LLM provider instance
110
+ agent?: unknown; // T2000 SDK instance (for tool execution)
111
+ mcpManager?: unknown; // McpClientManager (MCP-first reads)
112
+ walletAddress?: string; // User's Sui address (for MCP reads)
113
+ tools?: Tool[]; // Custom tool set (defaults to getDefaultTools())
114
+ systemPrompt?: string; // Override default Audric prompt
115
+ model?: string; // LLM model override
116
+ maxTurns?: number; // Max conversation turns (default: 10)
117
+ maxTokens?: number; // Max tokens per response (default: 4096)
118
+ costTracker?: {
119
+ budgetLimitUsd?: number; // Kill switch at USD threshold
120
+ inputCostPerToken?: number;
121
+ outputCostPerToken?: number;
122
+ };
123
+ }
124
+ ```
125
+
126
+ ## Event Types
127
+
128
+ The `submitMessage()` async generator yields `EngineEvent`:
129
+
130
+ | Event | Fields | When |
131
+ |-------|--------|------|
132
+ | `text_delta` | `text` | LLM streams a text chunk |
133
+ | `tool_start` | `toolName`, `toolUseId`, `input` | Tool execution begins |
134
+ | `tool_result` | `toolName`, `toolUseId`, `result`, `isError` | Tool execution completes |
135
+ | `permission_request` | `toolName`, `toolUseId`, `input`, `description`, `resolve` | Write tool awaiting approval |
136
+ | `turn_complete` | `stopReason` | Conversation turn finished |
137
+ | `usage` | `inputTokens`, `outputTokens`, `cacheReadTokens?`, `cacheWriteTokens?` | Token usage report |
138
+ | `error` | `error` | Unrecoverable error |
139
+
140
+ ## MCP Client Integration
141
+
142
+ Connect to external MCP servers (e.g., NAVI Protocol) for data:
143
+
144
+ ```typescript
145
+ import { McpClientManager, NAVI_MCP_CONFIG } from '@t2000/engine';
146
+
147
+ const mcpManager = new McpClientManager();
148
+ await mcpManager.connect(NAVI_MCP_CONFIG);
149
+
150
+ const engine = new QueryEngine({
151
+ provider,
152
+ agent,
153
+ mcpManager,
154
+ walletAddress: '0x...',
155
+ tools: getDefaultTools(),
156
+ });
157
+ ```
158
+
159
+ Read tools automatically use MCP when available, falling back to the SDK.
160
+
161
+ ## MCP Server Adapter
162
+
163
+ Expose engine tools to Claude Desktop, Cursor, or any MCP client:
164
+
165
+ ```typescript
166
+ import { registerEngineTools } from '@t2000/engine';
167
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
168
+
169
+ const server = new McpServer({ name: 'audric', version: '0.1.0' });
170
+ registerEngineTools(server, getDefaultTools());
171
+ ```
172
+
173
+ ## Custom Tools
174
+
175
+ ```typescript
176
+ import { z } from 'zod';
177
+ import { buildTool } from '@t2000/engine';
178
+
179
+ const myTool = buildTool({
180
+ name: 'my_tool',
181
+ description: 'Does something useful',
182
+ inputSchema: z.object({ query: z.string() }),
183
+ isReadOnly: true,
184
+ permissionLevel: 'auto',
185
+ async call(input, context) {
186
+ return { data: { answer: 42 }, displayText: 'The answer is 42' };
187
+ },
188
+ });
189
+ ```
190
+
191
+ ## Development
192
+
193
+ ```bash
194
+ pnpm --filter @t2000/engine build # Build (tsup → ESM)
195
+ pnpm --filter @t2000/engine test # Run tests (vitest)
196
+ pnpm --filter @t2000/engine typecheck # TypeScript strict check
197
+ pnpm --filter @t2000/engine lint # ESLint
198
+ ```
199
+
200
+ ## License
201
+
202
+ MIT