-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.ts
More file actions
421 lines (363 loc) · 13.8 KB
/
router.ts
File metadata and controls
421 lines (363 loc) · 13.8 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
import { ClaudeCodeAdapter } from "../adapters/claude-code";
import { CursorAdapter } from "../adapters/cursor-cli";
import { GeminiCodeAdapter } from "../adapters/gemini-cli";
import { KiroAdapter } from "../adapters/kiro-cli";
import { OllamaClaudeCodeAdapter } from "../adapters/ollama-claude-code";
import { CodexAdapter } from "../adapters/openai-codex";
import { OpenCodeAdapter } from "../adapters/opencode";
import { processWithAnthropic } from "../providers/anthropic";
import { processWithGemini } from "../providers/gemini";
import { processWithHuggingFace } from "../providers/huggingface";
import { processWithMiniMax } from "../providers/minimax";
import { processWithMistral } from "../providers/mistral";
import { processWithMoonshot } from "../providers/moonshot";
import { processWithOpenAI } from "../providers/openai";
import { processWithOpenRouter } from "../providers/openrouter";
import { processWithXAI } from "../providers/xai";
import { logger } from "../shared/logger";
import { IDEAdapter, MCPServerEntry, ModelInfo } from "../shared/types";
import { CronTool } from "../tools/cron";
import { EnvTool } from "../tools/env";
import { GitTool } from "../tools/git";
import { HttpTool } from "../tools/http";
import { MCPBridge, MCPServerConfig } from "../tools/mcp-bridge";
import { NetworkTool } from "../tools/network";
import { ProcessTool } from "../tools/process";
import { ToolRegistry } from "../tools/registry";
import { SearchTool } from "../tools/search";
import { SysinfoTool } from "../tools/sysinfo";
import { TerminalTool } from "../tools/terminal";
import { loadMCPServersCatalog } from "../utils/mcp-catalog-loader";
import { ContextManager } from "./context-manager";
export const AVAILABLE_ADAPTERS = [
{ id: "claude-code", label: "Claude Code (Anthropic API)" },
{ id: "cursor", label: "Cursor CLI (Headless)" },
{ id: "gemini-code", label: "Gemini Code (Google AI API)" },
{ id: "codex", label: "OpenAI Codex (OpenAI API)" },
{ id: "ollama-claude-code", label: "Claude Code via Ollama (Local)" },
{ id: "kiro", label: "Kiro CLI (AWS)" },
];
export class Router {
private adapter: IDEAdapter;
private currentAdapterName: string;
private provider: string;
private apiKey: string;
private model: string;
private toolRegistry: ToolRegistry;
private contextManager: ContextManager;
private pendingHandoff: string | null = null;
private currentAbortController: AbortController | null = null;
private mcpBridge: MCPBridge;
constructor() {
this.provider = process.env.AI_PROVIDER || "anthropic";
this.apiKey = process.env.AI_API_KEY || "";
this.model = process.env.AI_MODEL || "";
this.toolRegistry = new ToolRegistry();
this.toolRegistry.register(new TerminalTool());
this.toolRegistry.register(new ProcessTool());
this.toolRegistry.register(new GitTool());
this.toolRegistry.register(new SearchTool());
this.toolRegistry.register(new HttpTool());
this.toolRegistry.register(new EnvTool());
this.toolRegistry.register(new NetworkTool());
this.toolRegistry.register(new CronTool());
this.toolRegistry.register(new SysinfoTool());
this.mcpBridge = new MCPBridge();
this.contextManager = new ContextManager();
const ideType = process.env.IDE_TYPE || "";
this.currentAdapterName = ideType;
this.contextManager.setCurrentAdapter(ideType);
this.adapter = this.createAdapter(ideType);
this.restoreAdapterModel(ideType);
}
async initMCP(): Promise<void> {
const mcpServers = this.loadMCPConfig();
if (!mcpServers || mcpServers.length === 0) {
return;
}
const catalog = loadMCPServersCatalog();
const catalogMap = new Map(catalog.servers.map((s) => [s.id, s]));
const results: string[] = [];
for (const entry of mcpServers) {
if (!entry.enabled) {
continue;
}
try {
const catalogEntry = catalogMap.get(entry.id);
const serverConfig = this.buildMCPServerConfig(entry, catalogEntry);
const tools = await this.mcpBridge.connect(serverConfig);
this.toolRegistry.registerMCPTools(tools);
results.push(`${entry.id}: ${tools.length} tools`);
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
logger.debug(`MCP server "${entry.id}" failed to connect: ${msg}`);
}
}
if (results.length > 0) {
logger.info(`MCP servers connected (${results.join(", ")})`);
logger.info(`Total tools: ${this.toolRegistry.getMCPToolCount()} MCP + built-in`);
}
}
private buildMCPServerConfig(
entry: MCPServerEntry,
catalogEntry?: {
keychainKey?: string;
tokenEnvKey?: string;
additionalTokens?: Array<{ keychainKey: string; tokenEnvKey: string }>;
},
): MCPServerConfig {
const config: MCPServerConfig = {
id: entry.id,
name: entry.id,
transport: entry.transport,
};
if (entry.transport === "stdio") {
config.command = entry.command;
const resolvedArgs = (entry.args || []).map((arg) => {
const keychainMatch = arg.match(/^__KEYCHAIN:(.+)__$/);
if (keychainMatch) {
return process.env[`MCP_TOKEN_${entry.id.toUpperCase().replace(/-/g, "_")}`] || arg;
}
return arg;
});
config.args = resolvedArgs;
const env: Record<string, string> = { ...entry.env };
if (catalogEntry?.tokenEnvKey) {
const envKey = `MCP_TOKEN_${entry.id.toUpperCase().replace(/-/g, "_")}`;
const token = process.env[envKey];
if (token) {
env[catalogEntry.tokenEnvKey] = token;
}
}
if (catalogEntry?.additionalTokens) {
for (const additional of catalogEntry.additionalTokens) {
const envKey = `MCP_TOKEN_${additional.keychainKey.toUpperCase().replace(/-/g, "_")}`;
const token = process.env[envKey];
if (token) {
env[additional.tokenEnvKey] = token;
}
}
}
config.env = env;
} else {
config.url = entry.url;
const tokenEnvKey = `MCP_TOKEN_${entry.id.toUpperCase().replace(/-/g, "_")}`;
const token = process.env[tokenEnvKey];
if (token) {
config.headers = { Authorization: `Bearer ${token}` };
}
}
return config;
}
private loadMCPConfig(): MCPServerEntry[] | null {
try {
const fs = require("fs");
const path = require("path");
const os = require("os");
const configPath = path.join(os.homedir(), ".txtcode", "config.json");
if (!fs.existsSync(configPath)) {
return null;
}
const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
return config.mcpServers || null;
} catch {
return null;
}
}
async shutdownMCP(): Promise<void> {
for (const serverId of this.mcpBridge.getConnectedServerIds()) {
this.toolRegistry.removeMCPTools(serverId);
}
await this.mcpBridge.disconnectAll();
}
private createAdapter(ideType: string): IDEAdapter {
switch (ideType) {
case "claude-code":
return new ClaudeCodeAdapter();
case "cursor":
return new CursorAdapter();
case "gemini-code":
return new GeminiCodeAdapter();
case "codex":
return new CodexAdapter();
case "ollama-claude-code":
return new OllamaClaudeCodeAdapter();
case "kiro":
return new KiroAdapter();
case "opencode":
return new OpenCodeAdapter();
default:
throw new Error(
`No coding adapter configured (IDE_TYPE="${ideType}"). Run: txtcode config`,
);
}
}
async switchAdapter(
newAdapterName: string,
): Promise<{ handoffGenerated: boolean; oldAdapter: string; entryCount: number }> {
const oldAdapter = this.currentAdapterName;
const entryCount = this.contextManager.getEntryCount();
const trackedFiles = this.adapter.getTrackedFiles();
const handoff = this.contextManager.handleSwitch(oldAdapter, newAdapterName, trackedFiles);
this.pendingHandoff = handoff;
try {
await this.adapter.disconnect();
} catch (error) {
logger.debug(`Error disconnecting old adapter: ${error}`);
}
this.adapter = this.createAdapter(newAdapterName);
this.currentAdapterName = newAdapterName;
this.restoreAdapterModel(newAdapterName);
logger.debug(`Switched adapter: ${oldAdapter} → ${newAdapterName}`);
return { handoffGenerated: handoff !== null, oldAdapter, entryCount };
}
async routeToChat(instruction: string): Promise<string> {
if (!this.apiKey) {
return "[WARN] AI API key not configured. Run: txtcode config";
}
if (!this.model) {
return "[WARN] AI model not configured. Run: txtcode config";
}
logger.debug(`[Router] Chat → provider=${this.provider}, model=${this.model}`);
const startTime = Date.now();
try {
const result = await this._routeToProvider(instruction);
logger.debug(
`[Router] Chat complete → provider=${this.provider}, time=${Date.now() - startTime}ms, response=${result.length} chars`,
);
return result;
} catch (error) {
logger.error(
`[Router] Chat failed → provider=${this.provider}, time=${Date.now() - startTime}ms`,
error,
);
throw error;
}
}
private async _routeToProvider(instruction: string): Promise<string> {
switch (this.provider) {
case "anthropic":
return await processWithAnthropic(instruction, this.apiKey, this.model, this.toolRegistry);
case "openai":
return await processWithOpenAI(instruction, this.apiKey, this.model, this.toolRegistry);
case "gemini":
return await processWithGemini(instruction, this.apiKey, this.model, this.toolRegistry);
case "openrouter":
return await processWithOpenRouter(instruction, this.apiKey, this.model, this.toolRegistry);
case "moonshot":
return await processWithMoonshot(instruction, this.apiKey, this.model, this.toolRegistry);
case "minimax":
return await processWithMiniMax(instruction, this.apiKey, this.model, this.toolRegistry);
case "huggingface":
return await processWithHuggingFace(
instruction,
this.apiKey,
this.model,
this.toolRegistry,
);
case "mistral":
return await processWithMistral(instruction, this.apiKey, this.model, this.toolRegistry);
case "xai":
return await processWithXAI(instruction, this.apiKey, this.model, this.toolRegistry);
default:
return `[ERROR] Unsupported AI provider: ${this.provider}. Run: txtcode config`;
}
}
async routeToCode(instruction: string, onProgress?: (chunk: string) => void): Promise<string> {
if (this.currentAbortController) {
logger.debug("Aborting previous command...");
this.currentAbortController.abort();
}
this.currentAbortController = new AbortController();
const signal = this.currentAbortController.signal;
logger.debug(`[Router] Code → adapter=${this.currentAdapterName}`);
const startTime = Date.now();
try {
this.contextManager.addEntry("user", instruction);
let conversationHistory: Array<{ role: "user" | "assistant"; content: string }> | undefined;
if (this.pendingHandoff) {
conversationHistory = [{ role: "user", content: this.pendingHandoff }];
this.pendingHandoff = null;
logger.debug("Injecting handoff context via conversationHistory parameter");
}
const result = await this.adapter.executeCommand(
instruction,
conversationHistory,
signal,
onProgress,
);
this.contextManager.addEntry("assistant", result);
logger.debug(
`[Router] Code complete → adapter=${this.currentAdapterName}, time=${Date.now() - startTime}ms, response=${result.length} chars`,
);
return result;
} finally {
this.currentAbortController = null;
}
}
abortCurrentCommand(): void {
if (this.currentAbortController) {
logger.debug("Aborting current command via Router...");
this.currentAbortController.abort();
this.currentAbortController = null;
if (this.adapter.abort) {
this.adapter.abort();
}
}
}
async getAdapterStatus(): Promise<string> {
return await this.adapter.getStatus();
}
getProviderName(): string {
return this.provider;
}
getCurrentModel(): string {
return this.model;
}
updateProvider(provider: string, apiKey: string, model: string): void {
this.provider = provider;
this.apiKey = apiKey;
this.model = model;
process.env.AI_PROVIDER = provider;
process.env.AI_API_KEY = apiKey;
process.env.AI_MODEL = model;
logger.debug(`Provider updated: ${provider} with model ${model}`);
}
getAdapterName(): string {
return this.currentAdapterName;
}
getAvailableAdapters(): typeof AVAILABLE_ADAPTERS {
return AVAILABLE_ADAPTERS;
}
getContextEntryCount(): number {
return this.contextManager.getEntryCount();
}
getAdapterModels(): ModelInfo[] {
return this.adapter.getAvailableModels();
}
getAdapterCurrentModel(): string {
return this.adapter.getCurrentModel();
}
setAdapterModel(modelId: string): void {
this.adapter.setModel(modelId);
}
private restoreAdapterModel(adapterName: string): void {
try {
const fs = require("fs");
const path = require("path");
const os = require("os");
const configPath = path.join(os.homedir(), ".txtcode", "config.json");
if (!fs.existsSync(configPath)) {
return;
}
const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
const savedModel = config.adapterModels?.[adapterName];
if (savedModel) {
this.adapter.setModel(savedModel);
logger.debug(`Restored model ${savedModel} for adapter ${adapterName}`);
}
} catch {
// ignore
}
}
}