thatgfsj-code 0.3.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 +21 -0
- package/README.md +136 -0
- package/ROADMAP.md +61 -0
- package/dist/app/agent.d.ts +31 -0
- package/dist/app/agent.d.ts.map +1 -0
- package/dist/app/agent.js +106 -0
- package/dist/app/agent.js.map +1 -0
- package/dist/app/index.d.ts +39 -0
- package/dist/app/index.d.ts.map +1 -0
- package/dist/app/index.js +80 -0
- package/dist/app/index.js.map +1 -0
- package/dist/cmd/index.d.ts +12 -0
- package/dist/cmd/index.d.ts.map +1 -0
- package/dist/cmd/index.js +85 -0
- package/dist/cmd/index.js.map +1 -0
- package/dist/config/index.d.ts +39 -0
- package/dist/config/index.d.ts.map +1 -0
- package/dist/config/index.js +110 -0
- package/dist/config/index.js.map +1 -0
- package/dist/config/providers.d.ts +23 -0
- package/dist/config/providers.d.ts.map +1 -0
- package/dist/config/providers.js +152 -0
- package/dist/config/providers.js.map +1 -0
- package/dist/config/types.d.ts +33 -0
- package/dist/config/types.d.ts.map +1 -0
- package/dist/config/types.js +5 -0
- package/dist/config/types.js.map +1 -0
- package/dist/hooks/index.d.ts +31 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +71 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/llm/anthropic.d.ts +17 -0
- package/dist/llm/anthropic.d.ts.map +1 -0
- package/dist/llm/anthropic.js +126 -0
- package/dist/llm/anthropic.js.map +1 -0
- package/dist/llm/gemini.d.ts +16 -0
- package/dist/llm/gemini.d.ts.map +1 -0
- package/dist/llm/gemini.js +107 -0
- package/dist/llm/gemini.js.map +1 -0
- package/dist/llm/index.d.ts +48 -0
- package/dist/llm/index.d.ts.map +1 -0
- package/dist/llm/index.js +174 -0
- package/dist/llm/index.js.map +1 -0
- package/dist/llm/openai.d.ts +17 -0
- package/dist/llm/openai.d.ts.map +1 -0
- package/dist/llm/openai.js +113 -0
- package/dist/llm/openai.js.map +1 -0
- package/dist/llm/provider.d.ts +33 -0
- package/dist/llm/provider.d.ts.map +1 -0
- package/dist/llm/provider.js +6 -0
- package/dist/llm/provider.js.map +1 -0
- package/dist/mcp/client.d.ts +83 -0
- package/dist/mcp/client.d.ts.map +1 -0
- package/dist/mcp/client.js +267 -0
- package/dist/mcp/client.js.map +1 -0
- package/dist/prompts/index.d.ts +27 -0
- package/dist/prompts/index.d.ts.map +1 -0
- package/dist/prompts/index.js +102 -0
- package/dist/prompts/index.js.map +1 -0
- package/dist/session/compactor.d.ts +48 -0
- package/dist/session/compactor.d.ts.map +1 -0
- package/dist/session/compactor.js +77 -0
- package/dist/session/compactor.js.map +1 -0
- package/dist/session/index.d.ts +48 -0
- package/dist/session/index.d.ts.map +1 -0
- package/dist/session/index.js +69 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/message.d.ts +26 -0
- package/dist/session/message.d.ts.map +1 -0
- package/dist/session/message.js +34 -0
- package/dist/session/message.js.map +1 -0
- package/dist/tools/file.d.ts +46 -0
- package/dist/tools/file.d.ts.map +1 -0
- package/dist/tools/file.js +100 -0
- package/dist/tools/file.js.map +1 -0
- package/dist/tools/git.d.ts +52 -0
- package/dist/tools/git.d.ts.map +1 -0
- package/dist/tools/git.js +112 -0
- package/dist/tools/git.js.map +1 -0
- package/dist/tools/index.d.ts +42 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +92 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/search.d.ts +36 -0
- package/dist/tools/search.d.ts.map +1 -0
- package/dist/tools/search.js +223 -0
- package/dist/tools/search.js.map +1 -0
- package/dist/tools/shell.d.ts +50 -0
- package/dist/tools/shell.d.ts.map +1 -0
- package/dist/tools/shell.js +117 -0
- package/dist/tools/shell.js.map +1 -0
- package/dist/tools/types.d.ts +68 -0
- package/dist/tools/types.d.ts.map +1 -0
- package/dist/tools/types.js +57 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/tui/index.d.ts +8 -0
- package/dist/tui/index.d.ts.map +1 -0
- package/dist/tui/index.js +8 -0
- package/dist/tui/index.js.map +1 -0
- package/dist/tui/input.d.ts +14 -0
- package/dist/tui/input.d.ts.map +1 -0
- package/dist/tui/input.js +50 -0
- package/dist/tui/input.js.map +1 -0
- package/dist/tui/output.d.ts +20 -0
- package/dist/tui/output.d.ts.map +1 -0
- package/dist/tui/output.js +70 -0
- package/dist/tui/output.js.map +1 -0
- package/dist/tui/repl.d.ts +25 -0
- package/dist/tui/repl.d.ts.map +1 -0
- package/dist/tui/repl.js +114 -0
- package/dist/tui/repl.js.map +1 -0
- package/dist/tui/welcome.d.ts +15 -0
- package/dist/tui/welcome.d.ts.map +1 -0
- package/dist/tui/welcome.js +86 -0
- package/dist/tui/welcome.js.map +1 -0
- package/dist/types.d.ts +38 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/diff.d.ts +22 -0
- package/dist/utils/diff.d.ts.map +1 -0
- package/dist/utils/diff.js +60 -0
- package/dist/utils/diff.js.map +1 -0
- package/dist/utils/project.d.ts +32 -0
- package/dist/utils/project.d.ts.map +1 -0
- package/dist/utils/project.js +89 -0
- package/dist/utils/project.js.map +1 -0
- package/docs/API_KEY_GUIDE.md +236 -0
- package/docs/FAQ.md +182 -0
- package/install.bat +63 -0
- package/install.ps1 +238 -0
- package/install.sh +113 -0
- package/package.json +36 -0
- package/src/app/agent.ts +140 -0
- package/src/app/index.ts +101 -0
- package/src/cmd/index.ts +96 -0
- package/src/config/index.ts +130 -0
- package/src/config/providers.ts +160 -0
- package/src/config/types.ts +46 -0
- package/src/hooks/index.ts +111 -0
- package/src/llm/anthropic.ts +146 -0
- package/src/llm/gemini.ts +127 -0
- package/src/llm/index.ts +209 -0
- package/src/llm/openai.ts +132 -0
- package/src/llm/provider.ts +38 -0
- package/src/mcp/client.ts +330 -0
- package/src/prompts/index.ts +123 -0
- package/src/session/compactor.ts +103 -0
- package/src/session/index.ts +81 -0
- package/src/session/message.ts +42 -0
- package/src/tools/file.ts +117 -0
- package/src/tools/git.ts +132 -0
- package/src/tools/index.ts +108 -0
- package/src/tools/search.ts +263 -0
- package/src/tools/shell.ts +136 -0
- package/src/tools/types.ts +122 -0
- package/src/tui/index.ts +8 -0
- package/src/tui/input.ts +56 -0
- package/src/tui/output.ts +83 -0
- package/src/tui/repl.ts +131 -0
- package/src/tui/welcome.ts +101 -0
- package/src/types.ts +42 -0
- package/src/utils/diff.ts +71 -0
- package/src/utils/project.ts +99 -0
- package/tsconfig.json +19 -0
package/src/llm/index.ts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LLM Service - Factory for creating providers
|
|
3
|
+
* Replaces the monolithic AIEngine with a clean provider abstraction
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import chalk from 'chalk';
|
|
7
|
+
import type { ChatMessage, ChatResponse, ChatOptions, ToolCall } from '../types.js';
|
|
8
|
+
import type { Tool } from '../tools/types.js';
|
|
9
|
+
import type { LLMProvider } from './provider.js';
|
|
10
|
+
import type { AIConfig, ProviderName } from '../config/types.js';
|
|
11
|
+
import { PROVIDERS } from '../config/providers.js';
|
|
12
|
+
import { OpenAIProvider } from './openai.js';
|
|
13
|
+
import { AnthropicProvider } from './anthropic.js';
|
|
14
|
+
import { GeminiProvider } from './gemini.js';
|
|
15
|
+
|
|
16
|
+
export class LLMService {
|
|
17
|
+
private provider: LLMProvider;
|
|
18
|
+
private tools: Map<string, Tool> = new Map();
|
|
19
|
+
|
|
20
|
+
constructor(provider: LLMProvider) {
|
|
21
|
+
this.provider = provider;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Create LLMService from AIConfig
|
|
26
|
+
*/
|
|
27
|
+
static fromConfig(config: AIConfig): LLMService {
|
|
28
|
+
const providerName = config.provider || 'siliconflow';
|
|
29
|
+
const providerConfig = PROVIDERS[providerName];
|
|
30
|
+
|
|
31
|
+
const providerCfg = {
|
|
32
|
+
apiKey: config.apiKey || '',
|
|
33
|
+
model: config.model || providerConfig.defaultModel,
|
|
34
|
+
baseUrl: config.baseUrl || providerConfig.baseUrl,
|
|
35
|
+
temperature: config.temperature ?? 0.7,
|
|
36
|
+
maxTokens: config.maxTokens ?? 4096,
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const format = providerConfig.format;
|
|
40
|
+
let provider: LLMProvider;
|
|
41
|
+
|
|
42
|
+
switch (format) {
|
|
43
|
+
case 'anthropic':
|
|
44
|
+
provider = new AnthropicProvider(providerCfg);
|
|
45
|
+
break;
|
|
46
|
+
case 'gemini':
|
|
47
|
+
provider = new GeminiProvider(providerCfg);
|
|
48
|
+
break;
|
|
49
|
+
default:
|
|
50
|
+
provider = new OpenAIProvider(providerCfg);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return new LLMService(provider);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Register tools for function calling
|
|
58
|
+
*/
|
|
59
|
+
registerTools(tools: Tool[]): void {
|
|
60
|
+
for (const tool of tools) {
|
|
61
|
+
this.tools.set(tool.name, tool);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Get provider name
|
|
67
|
+
*/
|
|
68
|
+
getProviderName(): string {
|
|
69
|
+
return this.provider.name;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Non-streaming chat
|
|
74
|
+
*/
|
|
75
|
+
async chat(messages: ChatMessage[], options?: ChatOptions): Promise<ChatResponse> {
|
|
76
|
+
if (!this.hasApiKey()) {
|
|
77
|
+
return this.getMockResponse(messages);
|
|
78
|
+
}
|
|
79
|
+
return this.provider.chat(messages, options);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Streaming chat with agent loop (tool call support)
|
|
84
|
+
*/
|
|
85
|
+
async *chatStream(
|
|
86
|
+
messages: ChatMessage[],
|
|
87
|
+
options?: ChatOptions & { maxIterations?: number }
|
|
88
|
+
): AsyncGenerator<string, ChatResponse> {
|
|
89
|
+
if (!this.hasApiKey()) {
|
|
90
|
+
const mock = this.getMockResponse(messages);
|
|
91
|
+
for (const char of mock.content) {
|
|
92
|
+
await new Promise(r => setTimeout(r, 10));
|
|
93
|
+
yield char;
|
|
94
|
+
}
|
|
95
|
+
return mock;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const maxIterations = options?.maxIterations ?? 10;
|
|
99
|
+
let currentMessages = [...messages];
|
|
100
|
+
let iterations = 0;
|
|
101
|
+
|
|
102
|
+
while (iterations < maxIterations) {
|
|
103
|
+
iterations++;
|
|
104
|
+
|
|
105
|
+
// Get tools in provider format
|
|
106
|
+
const toolsArray = [...this.tools.values()];
|
|
107
|
+
const providerTools = toolsArray.length > 0 ? this.provider.buildTools(toolsArray) : [];
|
|
108
|
+
|
|
109
|
+
// Stream the response
|
|
110
|
+
let fullContent = '';
|
|
111
|
+
const streamOptions = { ...options };
|
|
112
|
+
|
|
113
|
+
// Add tools to the request if available
|
|
114
|
+
if (providerTools.length > 0) {
|
|
115
|
+
// We need to pass tools differently depending on provider
|
|
116
|
+
// For now, inject into messages context
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
for await (const chunk of this.provider.chatStream(currentMessages, streamOptions)) {
|
|
120
|
+
fullContent += chunk;
|
|
121
|
+
yield chunk;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Check for tool calls in the response
|
|
125
|
+
const response = await this.provider.chat(currentMessages, { ...streamOptions, stream: false });
|
|
126
|
+
const toolCalls = response.tool_calls;
|
|
127
|
+
|
|
128
|
+
if (toolCalls && toolCalls.length > 0) {
|
|
129
|
+
// Append assistant message with tool calls
|
|
130
|
+
currentMessages.push({
|
|
131
|
+
role: 'assistant',
|
|
132
|
+
content: fullContent,
|
|
133
|
+
tool_calls: toolCalls,
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// Execute each tool
|
|
137
|
+
for (const toolCall of toolCalls) {
|
|
138
|
+
const tool = this.tools.get(toolCall.function.name);
|
|
139
|
+
if (!tool) {
|
|
140
|
+
currentMessages.push({
|
|
141
|
+
role: 'tool',
|
|
142
|
+
content: `Tool "${toolCall.function.name}" not found`,
|
|
143
|
+
tool_call_id: toolCall.id,
|
|
144
|
+
name: toolCall.function.name,
|
|
145
|
+
});
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
try {
|
|
150
|
+
const params = JSON.parse(toolCall.function.arguments || '{}');
|
|
151
|
+
const result = await tool.execute(params);
|
|
152
|
+
currentMessages.push({
|
|
153
|
+
role: 'tool',
|
|
154
|
+
content: result.success ? (result.output || JSON.stringify(result.data)) : (result.error || 'Tool failed'),
|
|
155
|
+
tool_call_id: toolCall.id,
|
|
156
|
+
name: toolCall.function.name,
|
|
157
|
+
});
|
|
158
|
+
yield `\n${chalk.gray(`[tool: ${toolCall.function.name}]`)}`;
|
|
159
|
+
} catch (error: any) {
|
|
160
|
+
currentMessages.push({
|
|
161
|
+
role: 'tool',
|
|
162
|
+
content: `Tool execution error: ${error.message}`,
|
|
163
|
+
tool_call_id: toolCall.id,
|
|
164
|
+
name: toolCall.function.name,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
continue; // Loop back for next iteration
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// No tool calls - we're done
|
|
173
|
+
return response;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return { content: '[Agent loop exceeded maximum iterations]', role: 'assistant' };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Check if API key is available
|
|
181
|
+
*/
|
|
182
|
+
private hasApiKey(): boolean {
|
|
183
|
+
return !!(this.provider as any).config?.apiKey;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Mock response when no API key is set
|
|
188
|
+
*/
|
|
189
|
+
private getMockResponse(messages: ChatMessage[]): ChatResponse {
|
|
190
|
+
const last = messages[messages.length - 1]?.content || '';
|
|
191
|
+
let content: string;
|
|
192
|
+
|
|
193
|
+
if (/^(hi|hello|hey)/i.test(last)) {
|
|
194
|
+
content = 'Hi there! How can I help you today?';
|
|
195
|
+
} else if (last.toLowerCase().includes('who are you')) {
|
|
196
|
+
content = 'I am Thatgfsj Code, an AI coding assistant.';
|
|
197
|
+
} else {
|
|
198
|
+
content = `I understand you said: "${last.slice(0, 50)}..."\n\nThis is a demo response. Configure an API key for full AI capabilities.\nRun: gfcode init`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return { content, role: 'assistant' };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Re-export provider types
|
|
206
|
+
export type { LLMProvider, ProviderConfig } from './provider.js';
|
|
207
|
+
export { OpenAIProvider } from './openai.js';
|
|
208
|
+
export { AnthropicProvider } from './anthropic.js';
|
|
209
|
+
export { GeminiProvider } from './gemini.js';
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI-compatible Provider
|
|
3
|
+
* Works with: OpenAI, SiliconFlow, MiniMax (OpenAI mode), DeepSeek, Kimi, ERNIE, Ollama
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { ChatMessage, ChatResponse, ChatOptions } from '../types.js';
|
|
7
|
+
import type { Tool } from '../tools/types.js';
|
|
8
|
+
import type { LLMProvider, ProviderConfig } from './provider.js';
|
|
9
|
+
|
|
10
|
+
export class OpenAIProvider implements LLMProvider {
|
|
11
|
+
readonly name = 'openai';
|
|
12
|
+
private config: ProviderConfig;
|
|
13
|
+
|
|
14
|
+
constructor(config: ProviderConfig) {
|
|
15
|
+
this.config = config;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
buildTools(tools: Tool[]): any[] {
|
|
19
|
+
return tools.map(tool => ({
|
|
20
|
+
type: 'function' as const,
|
|
21
|
+
function: {
|
|
22
|
+
name: tool.name,
|
|
23
|
+
description: tool.description,
|
|
24
|
+
parameters: tool.inputSchema || {
|
|
25
|
+
type: 'object',
|
|
26
|
+
properties: Object.fromEntries(
|
|
27
|
+
tool.parameters.map(p => [p.name, { type: p.type, description: p.description }])
|
|
28
|
+
),
|
|
29
|
+
required: tool.parameters.filter(p => p.required).map(p => p.name),
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
}));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async chat(messages: ChatMessage[], options?: ChatOptions): Promise<ChatResponse> {
|
|
36
|
+
const body = this.buildRequest(messages, false, options);
|
|
37
|
+
|
|
38
|
+
const response = await fetch(`${this.config.baseUrl}/chat/completions`, {
|
|
39
|
+
method: 'POST',
|
|
40
|
+
headers: {
|
|
41
|
+
'Content-Type': 'application/json',
|
|
42
|
+
'Authorization': `Bearer ${this.config.apiKey}`,
|
|
43
|
+
},
|
|
44
|
+
body: JSON.stringify(body),
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
if (!response.ok) {
|
|
48
|
+
const text = await response.text().catch(() => '');
|
|
49
|
+
throw new Error(`OpenAI API error ${response.status}: ${text}`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const data = await response.json();
|
|
53
|
+
const choice = data.choices?.[0];
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
content: choice?.message?.content || '',
|
|
57
|
+
role: 'assistant',
|
|
58
|
+
usage: data.usage,
|
|
59
|
+
tool_calls: choice?.message?.tool_calls,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async *chatStream(messages: ChatMessage[], options?: ChatOptions): AsyncGenerator<string, ChatResponse> {
|
|
64
|
+
const body = this.buildRequest(messages, true, options);
|
|
65
|
+
|
|
66
|
+
const response = await fetch(`${this.config.baseUrl}/chat/completions`, {
|
|
67
|
+
method: 'POST',
|
|
68
|
+
headers: {
|
|
69
|
+
'Content-Type': 'application/json',
|
|
70
|
+
'Authorization': `Bearer ${this.config.apiKey}`,
|
|
71
|
+
},
|
|
72
|
+
body: JSON.stringify(body),
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
if (!response.ok || !response.body) {
|
|
76
|
+
const text = await response.text().catch(() => '');
|
|
77
|
+
throw new Error(`OpenAI API error ${response.status}: ${text}`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const reader = response.body.getReader();
|
|
81
|
+
const decoder = new TextDecoder();
|
|
82
|
+
let fullContent = '';
|
|
83
|
+
let buffer = '';
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
while (true) {
|
|
87
|
+
const { done, value } = await reader.read();
|
|
88
|
+
if (done) break;
|
|
89
|
+
|
|
90
|
+
buffer += decoder.decode(value, { stream: true });
|
|
91
|
+
const lines = buffer.split('\n');
|
|
92
|
+
buffer = lines.pop() || '';
|
|
93
|
+
|
|
94
|
+
for (const line of lines) {
|
|
95
|
+
const trimmed = line.trim();
|
|
96
|
+
if (!trimmed || !trimmed.startsWith('data: ') || trimmed === 'data: [DONE]') continue;
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const data = JSON.parse(trimmed.slice(6));
|
|
100
|
+
const content = data.choices?.[0]?.delta?.content;
|
|
101
|
+
if (content) {
|
|
102
|
+
fullContent += content;
|
|
103
|
+
yield content;
|
|
104
|
+
}
|
|
105
|
+
} catch {
|
|
106
|
+
// Skip invalid JSON lines
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
} finally {
|
|
111
|
+
reader.releaseLock();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return { content: fullContent, role: 'assistant' };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
private buildRequest(messages: ChatMessage[], stream: boolean, options?: ChatOptions) {
|
|
118
|
+
return {
|
|
119
|
+
model: this.config.model,
|
|
120
|
+
messages: messages.map(m => ({
|
|
121
|
+
role: m.role,
|
|
122
|
+
content: m.content,
|
|
123
|
+
...(m.name && { name: m.name }),
|
|
124
|
+
...(m.tool_call_id && { tool_call_id: m.tool_call_id }),
|
|
125
|
+
...(m.tool_calls && { tool_calls: m.tool_calls }),
|
|
126
|
+
})),
|
|
127
|
+
temperature: options?.temperature ?? this.config.temperature,
|
|
128
|
+
max_tokens: options?.maxTokens ?? this.config.maxTokens,
|
|
129
|
+
stream,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Abstract LLM Provider interface
|
|
3
|
+
* All providers implement this interface
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { ChatMessage, ChatResponse, ChatOptions } from '../types.js';
|
|
7
|
+
import type { Tool } from '../tools/types.js';
|
|
8
|
+
|
|
9
|
+
export interface LLMProvider {
|
|
10
|
+
/** Provider name for logging */
|
|
11
|
+
readonly name: string;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Non-streaming chat completion
|
|
15
|
+
*/
|
|
16
|
+
chat(messages: ChatMessage[], options?: ChatOptions): Promise<ChatResponse>;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Streaming chat completion - yields text chunks
|
|
20
|
+
*/
|
|
21
|
+
chatStream(messages: ChatMessage[], options?: ChatOptions): AsyncGenerator<string, ChatResponse>;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Convert Tool[] to provider-specific format
|
|
25
|
+
*/
|
|
26
|
+
buildTools(tools: Tool[]): any[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Provider configuration passed to each provider
|
|
31
|
+
*/
|
|
32
|
+
export interface ProviderConfig {
|
|
33
|
+
apiKey: string;
|
|
34
|
+
model: string;
|
|
35
|
+
baseUrl: string;
|
|
36
|
+
temperature: number;
|
|
37
|
+
maxTokens: number;
|
|
38
|
+
}
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* S07: MCP Client (Model Context Protocol)
|
|
3
|
+
* Connect to MCP servers and expose their tools as agent tools
|
|
4
|
+
*
|
|
5
|
+
* MCP turns the agent from a closed system into an open platform.
|
|
6
|
+
* Any server can expose tools via the MCP JSON-RPC 2.0 protocol.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { spawn, ChildProcess } from 'child_process';
|
|
10
|
+
import type { Tool, ToolResult } from '../tools/types.js';
|
|
11
|
+
|
|
12
|
+
// ==================== MCP Types ====================
|
|
13
|
+
|
|
14
|
+
interface MCPJsonRPCRequest {
|
|
15
|
+
jsonrpc: '2.0';
|
|
16
|
+
id: number | string;
|
|
17
|
+
method: string;
|
|
18
|
+
params?: any;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface MCPJsonRPCResponse {
|
|
22
|
+
jsonrpc: '2.0';
|
|
23
|
+
id: number | string;
|
|
24
|
+
result?: any;
|
|
25
|
+
error?: { code: number; message: string; data?: any };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface MCPTool {
|
|
29
|
+
name: string;
|
|
30
|
+
description: string;
|
|
31
|
+
inputSchema: {
|
|
32
|
+
type: 'object';
|
|
33
|
+
properties: Record<string, any>;
|
|
34
|
+
required?: string[];
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// ==================== MCP Client ====================
|
|
39
|
+
|
|
40
|
+
export class MCPClient {
|
|
41
|
+
private process: ChildProcess | null = null;
|
|
42
|
+
private tools: Map<string, MCPTool> = new Map();
|
|
43
|
+
private requestId = 0;
|
|
44
|
+
private pendingRequests: Map<number | string, {
|
|
45
|
+
resolve: (value: any) => void;
|
|
46
|
+
reject: (reason: any) => void;
|
|
47
|
+
}> = new Map();
|
|
48
|
+
private name: string;
|
|
49
|
+
private connected = false;
|
|
50
|
+
|
|
51
|
+
constructor(name: string) {
|
|
52
|
+
this.name = name;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* S07: Connect to an MCP server
|
|
57
|
+
* @param command Command to run (e.g., 'npx', 'node')
|
|
58
|
+
* @param args Arguments (e.g., ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/dir'])
|
|
59
|
+
*/
|
|
60
|
+
async connect(command: string, args: string[]): Promise<void> {
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
this.process = spawn(command, args, {
|
|
63
|
+
stdio: ['pipe', 'pipe', 'pipe']
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
let buffer = '';
|
|
67
|
+
|
|
68
|
+
this.process.stdout?.on('data', (data: Buffer) => {
|
|
69
|
+
buffer += data.toString();
|
|
70
|
+
const lines = buffer.split('\n');
|
|
71
|
+
buffer = lines.pop() || '';
|
|
72
|
+
|
|
73
|
+
for (const line of lines) {
|
|
74
|
+
if (line.trim()) {
|
|
75
|
+
this.handleMessage(line);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
this.process.stderr?.on('data', (data: Buffer) => {
|
|
81
|
+
console.error(`[MCP ${this.name}] stderr:`, data.toString().trim());
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
this.process.on('error', (err) => {
|
|
85
|
+
reject(err);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
this.process.on('close', (code) => {
|
|
89
|
+
this.connected = false;
|
|
90
|
+
console.log(`[MCP ${this.name}] exited with code ${code}`);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// Initialize MCP connection
|
|
94
|
+
this.sendRequest('initialize', {
|
|
95
|
+
protocolVersion: '2024-11-05',
|
|
96
|
+
capabilities: { tools: {} },
|
|
97
|
+
clientInfo: { name: 'thatgfsj-code', version: '1.0.0' }
|
|
98
|
+
}).then(() => {
|
|
99
|
+
this.connected = true;
|
|
100
|
+
// Send initialized notification
|
|
101
|
+
this.sendNotification('initialized', {});
|
|
102
|
+
// List available tools
|
|
103
|
+
return this.listTools();
|
|
104
|
+
}).then(() => {
|
|
105
|
+
resolve();
|
|
106
|
+
}).catch(reject);
|
|
107
|
+
|
|
108
|
+
// Timeout
|
|
109
|
+
setTimeout(() => reject(new Error('MCP connection timeout')), 30000);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* S07: Handle incoming JSON-RPC message
|
|
115
|
+
*/
|
|
116
|
+
private handleMessage(raw: string): void {
|
|
117
|
+
try {
|
|
118
|
+
const msg: MCPJsonRPCResponse = JSON.parse(raw);
|
|
119
|
+
|
|
120
|
+
// Handle response
|
|
121
|
+
const pending = this.pendingRequests.get(msg.id);
|
|
122
|
+
if (pending) {
|
|
123
|
+
this.pendingRequests.delete(msg.id);
|
|
124
|
+
if (msg.error) {
|
|
125
|
+
pending.reject(new Error(msg.error.message));
|
|
126
|
+
} else {
|
|
127
|
+
pending.resolve(msg.result);
|
|
128
|
+
}
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
} catch {
|
|
132
|
+
// Not JSON, ignore
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* S07: Send a JSON-RPC request
|
|
138
|
+
*/
|
|
139
|
+
private sendRequest(method: string, params: any): Promise<any> {
|
|
140
|
+
return new Promise((resolve, reject) => {
|
|
141
|
+
if (!this.process?.connected) {
|
|
142
|
+
reject(new Error('MCP process not connected'));
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const id = ++this.requestId;
|
|
147
|
+
this.pendingRequests.set(id, { resolve, reject });
|
|
148
|
+
|
|
149
|
+
const request: MCPJsonRPCRequest = {
|
|
150
|
+
jsonrpc: '2.0',
|
|
151
|
+
id,
|
|
152
|
+
method,
|
|
153
|
+
params
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
this.process.stdin?.write(JSON.stringify(request) + '\n');
|
|
157
|
+
|
|
158
|
+
// Timeout
|
|
159
|
+
setTimeout(() => {
|
|
160
|
+
if (this.pendingRequests.has(id)) {
|
|
161
|
+
this.pendingRequests.delete(id);
|
|
162
|
+
reject(new Error('MCP request timeout: ' + method));
|
|
163
|
+
}
|
|
164
|
+
}, 30000);
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* S07: Send a notification (no response expected)
|
|
170
|
+
*/
|
|
171
|
+
private sendNotification(method: string, params: any): void {
|
|
172
|
+
if (!this.process?.connected) return;
|
|
173
|
+
|
|
174
|
+
const notification = {
|
|
175
|
+
jsonrpc: '2.0',
|
|
176
|
+
method,
|
|
177
|
+
params
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
this.process.stdin?.write(JSON.stringify(notification) + '\n');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* S07: Call an MCP tool
|
|
185
|
+
*/
|
|
186
|
+
async callTool(name: string, arguments_: Record<string, any>): Promise<ToolResult> {
|
|
187
|
+
try {
|
|
188
|
+
const result = await this.sendRequest('tools/call', {
|
|
189
|
+
name,
|
|
190
|
+
arguments: arguments_
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
success: true,
|
|
195
|
+
output: typeof result === 'string' ? result : JSON.stringify(result)
|
|
196
|
+
};
|
|
197
|
+
} catch (error: any) {
|
|
198
|
+
return {
|
|
199
|
+
success: false,
|
|
200
|
+
error: error.message
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* S07: List tools from MCP server
|
|
207
|
+
*/
|
|
208
|
+
private async listTools(): Promise<void> {
|
|
209
|
+
try {
|
|
210
|
+
const result = await this.sendRequest('tools/list', {});
|
|
211
|
+
const tools: MCPTool[] = result.tools || [];
|
|
212
|
+
|
|
213
|
+
this.tools.clear();
|
|
214
|
+
for (const tool of tools) {
|
|
215
|
+
this.tools.set(tool.name, tool);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
console.log(`[MCP ${this.name}] Loaded ${tools.length} tools:`, [...this.tools.keys()].join(', '));
|
|
219
|
+
} catch (error: any) {
|
|
220
|
+
console.error(`[MCP ${this.name}] Failed to list tools:`, error.message);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* S07: Get registered tools as agent Tool[]
|
|
226
|
+
*/
|
|
227
|
+
getTools(): Tool[] {
|
|
228
|
+
return [...this.tools.values()].map(mcpTool => ({
|
|
229
|
+
name: this.name + ':' + mcpTool.name,
|
|
230
|
+
description: mcpTool.description,
|
|
231
|
+
parameters: Object.entries(mcpTool.inputSchema.properties || {}).map(([name, schema]: [string, any]) => ({
|
|
232
|
+
name,
|
|
233
|
+
type: schema.type || 'string',
|
|
234
|
+
description: schema.description || '',
|
|
235
|
+
required: (mcpTool.inputSchema.required || []).includes(name)
|
|
236
|
+
})),
|
|
237
|
+
execute: async (params: Record<string, any>): Promise<ToolResult> => {
|
|
238
|
+
return this.callTool(mcpTool.name, params);
|
|
239
|
+
}
|
|
240
|
+
}));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* S07: Get tool names
|
|
245
|
+
*/
|
|
246
|
+
getToolNames(): string[] {
|
|
247
|
+
return [...this.tools.keys()];
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* S07: Check if connected
|
|
252
|
+
*/
|
|
253
|
+
isConnected(): boolean {
|
|
254
|
+
return this.connected;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* S07: Disconnect from MCP server
|
|
259
|
+
*/
|
|
260
|
+
disconnect(): void {
|
|
261
|
+
if (this.process) {
|
|
262
|
+
this.process.kill();
|
|
263
|
+
this.process = null;
|
|
264
|
+
}
|
|
265
|
+
this.connected = false;
|
|
266
|
+
this.tools.clear();
|
|
267
|
+
this.pendingRequests.clear();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ==================== MCP Server Manager ====================
|
|
272
|
+
|
|
273
|
+
export class MCPServerManager {
|
|
274
|
+
private clients: Map<string, MCPClient> = new Map();
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* S07: Add and connect an MCP server
|
|
278
|
+
*/
|
|
279
|
+
async addServer(name: string, command: string, args: string[]): Promise<void> {
|
|
280
|
+
const client = new MCPClient(name);
|
|
281
|
+
await client.connect(command, args);
|
|
282
|
+
this.clients.set(name, client);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* S07: Get all tools from all servers
|
|
287
|
+
*/
|
|
288
|
+
getAllTools(): Tool[] {
|
|
289
|
+
const allTools: Tool[] = [];
|
|
290
|
+
for (const client of this.clients.values()) {
|
|
291
|
+
allTools.push(...client.getTools());
|
|
292
|
+
}
|
|
293
|
+
return allTools;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* S07: Get tool names from all servers
|
|
298
|
+
*/
|
|
299
|
+
getAllToolNames(): string[] {
|
|
300
|
+
const names: string[] = [];
|
|
301
|
+
for (const [serverName, client] of this.clients) {
|
|
302
|
+
for (const toolName of client.getToolNames()) {
|
|
303
|
+
names.push(serverName + ':' + toolName);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return names;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* S07: Disconnect a server
|
|
311
|
+
*/
|
|
312
|
+
removeServer(name: string): void {
|
|
313
|
+
const client = this.clients.get(name);
|
|
314
|
+
if (client) {
|
|
315
|
+
client.disconnect();
|
|
316
|
+
this.clients.delete(name);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* S07: Get server status
|
|
322
|
+
*/
|
|
323
|
+
getStatus(): Record<string, boolean> {
|
|
324
|
+
const status: Record<string, boolean> = {};
|
|
325
|
+
for (const [name, client] of this.clients) {
|
|
326
|
+
status[name] = client.isConnected();
|
|
327
|
+
}
|
|
328
|
+
return status;
|
|
329
|
+
}
|
|
330
|
+
}
|