thatgfsj-code 0.2.1

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.
Files changed (179) hide show
  1. package/.patches/0001-fix-repl-replace-readline-with-inquirer-input-for-ke.patch +279 -0
  2. package/.patches/0002-fix-repl-stream-AI-output-directly-to-stdout-so-term.patch +564 -0
  3. package/.patches/0003-fix-session-break-the-hallucination-loop-in-assistan.patch +194 -0
  4. package/.patches/0004-chore-release-bump-version-to-0.2.1.patch +24 -0
  5. package/LICENSE +21 -0
  6. package/README.md +100 -0
  7. package/ROADMAP.md +107 -0
  8. package/dist/agent/core.d.ts +56 -0
  9. package/dist/agent/core.d.ts.map +1 -0
  10. package/dist/agent/core.js +142 -0
  11. package/dist/agent/core.js.map +1 -0
  12. package/dist/agent/index.d.ts +8 -0
  13. package/dist/agent/index.d.ts.map +1 -0
  14. package/dist/agent/index.js +8 -0
  15. package/dist/agent/index.js.map +1 -0
  16. package/dist/agent/intent.d.ts +36 -0
  17. package/dist/agent/intent.d.ts.map +1 -0
  18. package/dist/agent/intent.js +146 -0
  19. package/dist/agent/intent.js.map +1 -0
  20. package/dist/agent/streaming.d.ts +50 -0
  21. package/dist/agent/streaming.d.ts.map +1 -0
  22. package/dist/agent/streaming.js +110 -0
  23. package/dist/agent/streaming.js.map +1 -0
  24. package/dist/core/ai-engine.d.ts +59 -0
  25. package/dist/core/ai-engine.d.ts.map +1 -0
  26. package/dist/core/ai-engine.js +378 -0
  27. package/dist/core/ai-engine.js.map +1 -0
  28. package/dist/core/cli.d.ts +21 -0
  29. package/dist/core/cli.d.ts.map +1 -0
  30. package/dist/core/cli.js +143 -0
  31. package/dist/core/cli.js.map +1 -0
  32. package/dist/core/config.d.ts +38 -0
  33. package/dist/core/config.d.ts.map +1 -0
  34. package/dist/core/config.js +129 -0
  35. package/dist/core/config.js.map +1 -0
  36. package/dist/core/context-compactor.d.ts +54 -0
  37. package/dist/core/context-compactor.d.ts.map +1 -0
  38. package/dist/core/context-compactor.js +197 -0
  39. package/dist/core/context-compactor.js.map +1 -0
  40. package/dist/core/hooks.d.ts +75 -0
  41. package/dist/core/hooks.d.ts.map +1 -0
  42. package/dist/core/hooks.js +146 -0
  43. package/dist/core/hooks.js.map +1 -0
  44. package/dist/core/permissions.d.ts +52 -0
  45. package/dist/core/permissions.d.ts.map +1 -0
  46. package/dist/core/permissions.js +237 -0
  47. package/dist/core/permissions.js.map +1 -0
  48. package/dist/core/session.d.ts +54 -0
  49. package/dist/core/session.d.ts.map +1 -0
  50. package/dist/core/session.js +147 -0
  51. package/dist/core/session.js.map +1 -0
  52. package/dist/core/skills.d.ts +60 -0
  53. package/dist/core/skills.d.ts.map +1 -0
  54. package/dist/core/skills.js +175 -0
  55. package/dist/core/skills.js.map +1 -0
  56. package/dist/core/state.d.ts +60 -0
  57. package/dist/core/state.d.ts.map +1 -0
  58. package/dist/core/state.js +106 -0
  59. package/dist/core/state.js.map +1 -0
  60. package/dist/core/subagent.d.ts +68 -0
  61. package/dist/core/subagent.d.ts.map +1 -0
  62. package/dist/core/subagent.js +142 -0
  63. package/dist/core/subagent.js.map +1 -0
  64. package/dist/core/system-prompt.d.ts +40 -0
  65. package/dist/core/system-prompt.d.ts.map +1 -0
  66. package/dist/core/system-prompt.js +138 -0
  67. package/dist/core/system-prompt.js.map +1 -0
  68. package/dist/core/tool-registry.d.ts +53 -0
  69. package/dist/core/tool-registry.d.ts.map +1 -0
  70. package/dist/core/tool-registry.js +138 -0
  71. package/dist/core/tool-registry.js.map +1 -0
  72. package/dist/core/types.d.ts +206 -0
  73. package/dist/core/types.d.ts.map +1 -0
  74. package/dist/core/types.js +127 -0
  75. package/dist/core/types.js.map +1 -0
  76. package/dist/index.d.ts +7 -0
  77. package/dist/index.d.ts.map +1 -0
  78. package/dist/index.js +481 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/mcp/client.d.ts +83 -0
  81. package/dist/mcp/client.d.ts.map +1 -0
  82. package/dist/mcp/client.js +267 -0
  83. package/dist/mcp/client.js.map +1 -0
  84. package/dist/repl/index.d.ts +8 -0
  85. package/dist/repl/index.d.ts.map +1 -0
  86. package/dist/repl/index.js +8 -0
  87. package/dist/repl/index.js.map +1 -0
  88. package/dist/repl/input.d.ts +61 -0
  89. package/dist/repl/input.d.ts.map +1 -0
  90. package/dist/repl/input.js +127 -0
  91. package/dist/repl/input.js.map +1 -0
  92. package/dist/repl/loop.d.ts +53 -0
  93. package/dist/repl/loop.d.ts.map +1 -0
  94. package/dist/repl/loop.js +241 -0
  95. package/dist/repl/loop.js.map +1 -0
  96. package/dist/repl/output.d.ts +105 -0
  97. package/dist/repl/output.d.ts.map +1 -0
  98. package/dist/repl/output.js +197 -0
  99. package/dist/repl/output.js.map +1 -0
  100. package/dist/repl/welcome.d.ts +68 -0
  101. package/dist/repl/welcome.d.ts.map +1 -0
  102. package/dist/repl/welcome.js +249 -0
  103. package/dist/repl/welcome.js.map +1 -0
  104. package/dist/tools/file.d.ts +46 -0
  105. package/dist/tools/file.d.ts.map +1 -0
  106. package/dist/tools/file.js +100 -0
  107. package/dist/tools/file.js.map +1 -0
  108. package/dist/tools/git.d.ts +52 -0
  109. package/dist/tools/git.d.ts.map +1 -0
  110. package/dist/tools/git.js +112 -0
  111. package/dist/tools/git.js.map +1 -0
  112. package/dist/tools/index.d.ts +22 -0
  113. package/dist/tools/index.d.ts.map +1 -0
  114. package/dist/tools/index.js +43 -0
  115. package/dist/tools/index.js.map +1 -0
  116. package/dist/tools/search.d.ts +36 -0
  117. package/dist/tools/search.d.ts.map +1 -0
  118. package/dist/tools/search.js +223 -0
  119. package/dist/tools/search.js.map +1 -0
  120. package/dist/tools/shell.d.ts +57 -0
  121. package/dist/tools/shell.d.ts.map +1 -0
  122. package/dist/tools/shell.js +153 -0
  123. package/dist/tools/shell.js.map +1 -0
  124. package/dist/utils/diff-preview.d.ts +42 -0
  125. package/dist/utils/diff-preview.d.ts.map +1 -0
  126. package/dist/utils/diff-preview.js +174 -0
  127. package/dist/utils/diff-preview.js.map +1 -0
  128. package/dist/utils/index.d.ts +8 -0
  129. package/dist/utils/index.d.ts.map +1 -0
  130. package/dist/utils/index.js +8 -0
  131. package/dist/utils/index.js.map +1 -0
  132. package/dist/utils/memory.d.ts +81 -0
  133. package/dist/utils/memory.d.ts.map +1 -0
  134. package/dist/utils/memory.js +186 -0
  135. package/dist/utils/memory.js.map +1 -0
  136. package/dist/utils/project-context.d.ts +62 -0
  137. package/dist/utils/project-context.d.ts.map +1 -0
  138. package/dist/utils/project-context.js +197 -0
  139. package/dist/utils/project-context.js.map +1 -0
  140. package/docs/API_KEY_GUIDE.md +236 -0
  141. package/docs/FAQ.md +182 -0
  142. package/install.bat +63 -0
  143. package/install.ps1 +238 -0
  144. package/install.sh +113 -0
  145. package/package.json +36 -0
  146. package/src/agent/core.ts +179 -0
  147. package/src/agent/index.ts +8 -0
  148. package/src/agent/intent.ts +181 -0
  149. package/src/agent/streaming.ts +132 -0
  150. package/src/core/ai-engine.ts +437 -0
  151. package/src/core/cli.ts +171 -0
  152. package/src/core/config.ts +147 -0
  153. package/src/core/context-compactor.ts +245 -0
  154. package/src/core/hooks.ts +196 -0
  155. package/src/core/permissions.ts +308 -0
  156. package/src/core/session.ts +165 -0
  157. package/src/core/skills.ts +208 -0
  158. package/src/core/state.ts +120 -0
  159. package/src/core/subagent.ts +195 -0
  160. package/src/core/system-prompt.ts +163 -0
  161. package/src/core/tool-registry.ts +157 -0
  162. package/src/core/types.ts +280 -0
  163. package/src/index.ts +544 -0
  164. package/src/mcp/client.ts +330 -0
  165. package/src/repl/index.ts +8 -0
  166. package/src/repl/input.ts +139 -0
  167. package/src/repl/loop.ts +280 -0
  168. package/src/repl/output.ts +222 -0
  169. package/src/repl/welcome.ts +296 -0
  170. package/src/tools/file.ts +117 -0
  171. package/src/tools/git.ts +132 -0
  172. package/src/tools/index.ts +48 -0
  173. package/src/tools/search.ts +263 -0
  174. package/src/tools/shell.ts +181 -0
  175. package/src/utils/diff-preview.ts +202 -0
  176. package/src/utils/index.ts +8 -0
  177. package/src/utils/memory.ts +223 -0
  178. package/src/utils/project-context.ts +207 -0
  179. package/tsconfig.json +19 -0
@@ -0,0 +1,437 @@
1
+ /**
2
+ * AI Engine - Core AI interaction module
3
+ * Supports multiple providers: MiniMax, SiliconFlow, OpenAI, Anthropic
4
+ *
5
+ * Implements S01: Agent Loop pattern with async generator for streaming
6
+ * Core pattern: while(true) { response → execute tools → append results → repeat }
7
+ */
8
+
9
+ import chalk from 'chalk';
10
+ import { ChatMessage, AIResponse, AIConfig, Tool, ToolCall } from './types.js';
11
+
12
+ export { AIResponse, ChatMessage };
13
+
14
+ export class AIEngine {
15
+ private config: AIConfig;
16
+ private tools: Map<string, Tool> = new Map();
17
+
18
+ constructor(config: AIConfig) {
19
+ this.config = config;
20
+ }
21
+
22
+ /**
23
+ * Register tools for function calling
24
+ */
25
+ registerTool(tool: Tool) {
26
+ this.tools.set(tool.name, tool);
27
+ }
28
+
29
+ /**
30
+ * Unregister a tool
31
+ */
32
+ unregisterTool(name: string) {
33
+ this.tools.delete(name);
34
+ }
35
+
36
+ /**
37
+ * Get registered tools for API (S02: uses ToolRegistry if available)
38
+ */
39
+ private getToolsForAPI() {
40
+ // If registry is injected, use its getToolsForAPI
41
+ if (this.registry) {
42
+ return this.registry.getToolsForAPI();
43
+ }
44
+ // Fallback: build from tools map
45
+ return Array.from(this.tools.values()).map(tool => ({
46
+ type: 'function' as const,
47
+ function: {
48
+ name: tool.name,
49
+ description: tool.description,
50
+ parameters: {
51
+ type: 'object',
52
+ properties: tool.parameters.reduce((acc, p) => {
53
+ acc[p.name] = { type: p.type, description: p.description };
54
+ return acc;
55
+ }, {} as any),
56
+ required: tool.parameters.filter(p => p.required).map(p => p.name)
57
+ }
58
+ }
59
+ }));
60
+ }
61
+
62
+ // S02: Inject registry for enhanced tool management
63
+ setRegistry(registry: any) {
64
+ this.registry = registry;
65
+ }
66
+ private registry?: any;
67
+
68
+ // S08: Hook manager
69
+ setHooks(hooks: import('./hooks.js').HookManager) {
70
+ this.hooks = hooks;
71
+ }
72
+ private hooks?: import('./hooks.js').HookManager | null = null;
73
+
74
+ // ==================== S01: Async Generator Agent Loop ====================
75
+
76
+ async *chatStream(
77
+ messages: ChatMessage[],
78
+ maxIterations: number = 10
79
+ ): AsyncGenerator<string, AIResponse, unknown> {
80
+ let currentMessages = [...messages];
81
+ let iterations = 0;
82
+
83
+ while (iterations < maxIterations) {
84
+ iterations++;
85
+
86
+ // S08 Hook: beforeAgentLoop
87
+ if (this.hooks) {
88
+ await this.hooks.emit('beforeAgentLoop', { messages: currentMessages, iteration: iterations });
89
+ }
90
+
91
+ let fullResponse = '';
92
+
93
+ for await (const chunk of this.streamRequest(currentMessages)) {
94
+ fullResponse += chunk;
95
+ yield chunk;
96
+ }
97
+
98
+ const response = this.parseResponse(fullResponse);
99
+
100
+ if (response.tool_calls && response.tool_calls.length > 0) {
101
+ currentMessages.push({
102
+ role: 'assistant',
103
+ content: response.content,
104
+ tool_calls: response.tool_calls
105
+ });
106
+
107
+ // Execute each tool
108
+ for (const toolCall of response.tool_calls) {
109
+ // S08 Hook: beforeToolCall
110
+ if (this.hooks) {
111
+ await this.hooks.emit('beforeToolCall', {
112
+ toolName: toolCall.function.name,
113
+ toolParams: JSON.parse(toolCall.function.arguments || '{}'),
114
+ toolCallId: toolCall.id
115
+ });
116
+ }
117
+
118
+ const result = await this.executeToolCall(toolCall);
119
+
120
+ // S08 Hook: afterToolCall
121
+ if (this.hooks) {
122
+ await this.hooks.emit('afterToolCall', {
123
+ toolName: toolCall.function.name,
124
+ toolParams: JSON.parse(toolCall.function.arguments || '{}'),
125
+ toolResult: result,
126
+ toolCallId: toolCall.id
127
+ });
128
+ }
129
+
130
+ const toolResultMsg: ChatMessage = {
131
+ role: 'tool',
132
+ content: result.output || result.error || '',
133
+ tool_call_id: toolCall.id,
134
+ name: toolCall.function.name
135
+ };
136
+ currentMessages.push(toolResultMsg);
137
+
138
+ yield `\n${chalk.gray(`[tool: ${toolCall.function.name}]`)}`;
139
+ }
140
+
141
+ continue;
142
+ }
143
+
144
+ // No tool calls — exit loop
145
+ if (response.content) {
146
+ currentMessages.push({
147
+ role: 'assistant',
148
+ content: response.content
149
+ });
150
+ }
151
+
152
+ // S08 Hook: afterAgentLoop
153
+ if (this.hooks) {
154
+ await this.hooks.emit('afterAgentLoop', { messages: currentMessages, iteration: iterations });
155
+ }
156
+
157
+ return response;
158
+ }
159
+
160
+ // Max iterations reached
161
+ return {
162
+ content: '[Agent loop exceeded maximum iterations]',
163
+ role: 'assistant'
164
+ };
165
+ }
166
+
167
+ /**
168
+ * S01 Core: Stream request — yields chunks as they arrive
169
+ * Uses async generator for backpressure control and lazy evaluation
170
+ */
171
+ private async *streamRequest(
172
+ messages: ChatMessage[]
173
+ ): AsyncGenerator<string, void, unknown> {
174
+ const apiKey = this.config.apiKey || this.getApiKey();
175
+
176
+ if (!apiKey) {
177
+ // Mock streaming for demo
178
+ const mock = this.getMockResponse(messages);
179
+ for (const char of mock) {
180
+ await new Promise(r => setTimeout(r, 10));
181
+ yield char;
182
+ }
183
+ return;
184
+ }
185
+
186
+ const isAnthropicFormat = this.config.provider === 'anthropic' || this.config.provider === 'minimax';
187
+ const isGeminiFormat = this.config.provider === 'gemini';
188
+
189
+ let url: string;
190
+ let headers: Record<string, string> = {};
191
+ let body: any;
192
+
193
+ if (isGeminiFormat) {
194
+ url = `${this.config.baseUrl}/models/${this.config.model}:generateContent`;
195
+ headers = { 'Content-Type': 'application/json' };
196
+ body = this.buildGeminiRequest(messages);
197
+ } else if (isAnthropicFormat) {
198
+ url = `${this.config.baseUrl}/messages-stream`;
199
+ headers = {
200
+ 'Content-Type': 'application/json',
201
+ 'x-api-key': apiKey,
202
+ 'anthropic-version': '2023-06-01',
203
+ 'anthropic-dangerous-direct-browser-access': 'true'
204
+ };
205
+ body = this.buildAnthropicRequest(messages, true);
206
+ } else {
207
+ url = `${this.config.baseUrl}/chat/completions`;
208
+ headers = {
209
+ 'Content-Type': 'application/json',
210
+ 'Authorization': `Bearer ${apiKey}`
211
+ };
212
+ body = this.buildOpenAIRequest(messages, true);
213
+ }
214
+
215
+ const response = await fetch(url, {
216
+ method: 'POST',
217
+ headers,
218
+ body: JSON.stringify(body)
219
+ });
220
+
221
+ if (!response.ok || !response.body) {
222
+ yield `\n${chalk.red(`[API Error: ${response.status}]`)}`;
223
+ return;
224
+ }
225
+
226
+ const decoder = new TextDecoder();
227
+ const reader = response.body.getReader();
228
+
229
+ try {
230
+ while (true) {
231
+ const { done, value } = await reader.read();
232
+ if (done) break;
233
+
234
+ const chunk = decoder.decode(value, { stream: true });
235
+ const text = this.extractChunkText(chunk, isAnthropicFormat, isGeminiFormat);
236
+ if (text) {
237
+ yield text;
238
+ }
239
+ }
240
+ } finally {
241
+ reader.releaseLock();
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Extract text from streaming chunk based on provider format
247
+ */
248
+ private extractChunkText(
249
+ chunk: string,
250
+ isAnthropic: boolean,
251
+ isGemini: boolean
252
+ ): string {
253
+ if (isAnthropic) {
254
+ // Anthropic streaming format: data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"..."}}
255
+ const match = chunk.match(/"type"\s*:\s*"text_delta"\s*,\s*"text"\s*:\s*"([^"]*)"/);
256
+ return match ? match[1] : '';
257
+ } else if (isGemini) {
258
+ // Gemini format
259
+ const match = chunk.match(/"text"\s*:\s*"([^"]*)"/);
260
+ return match ? match[1] : '';
261
+ } else {
262
+ // OpenAI SSE format: data: {"choices":[{"delta":{"content":"..."}}]}
263
+ const lines = chunk.split('\n');
264
+ for (const line of lines) {
265
+ if (line.startsWith('data: ') && line !== 'data: [DONE]') {
266
+ try {
267
+ const data = JSON.parse(line.slice(6));
268
+ const content = data.choices?.[0]?.delta?.content;
269
+ if (content) return content;
270
+ } catch {
271
+ // Skip invalid JSON
272
+ }
273
+ }
274
+ }
275
+ return '';
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Parse full response text into structured AIResponse
281
+ */
282
+ private parseResponse(fullText: string): AIResponse {
283
+ // For now return content as-is; tool call parsing happens via content patterns
284
+ return {
285
+ content: fullText,
286
+ role: 'assistant',
287
+ tool_calls: this.extractToolCalls(fullText)
288
+ };
289
+ }
290
+
291
+ /**
292
+ * Extract tool calls from response content
293
+ */
294
+ private extractToolCalls(content: string): ToolCall[] | undefined {
295
+ // Simple pattern: look for tool_call blocks in response
296
+ // In real implementation this would be parsed from structured response
297
+ // For streaming, we check if content indicates a tool call
298
+ if (!content.includes('tool_use')) return undefined;
299
+ return undefined; // Placeholder — actual implementation depends on provider
300
+ }
301
+
302
+ // ==================== Legacy chat() — delegates to chatStream ====================
303
+
304
+ /**
305
+ * Original non-streaming chat — now implemented via chatStream
306
+ */
307
+ async chat(messages: ChatMessage[], maxIterations: number = 5): Promise<AIResponse> {
308
+ let fullContent = '';
309
+
310
+ for await (const chunk of this.chatStream(messages, maxIterations)) {
311
+ fullContent += chunk;
312
+ }
313
+
314
+ return {
315
+ content: fullContent,
316
+ role: 'assistant'
317
+ };
318
+ }
319
+
320
+ // ==================== Tool Execution ====================
321
+
322
+ private async executeToolCall(toolCall: ToolCall): Promise<{ output?: string; error?: string }> {
323
+ const { name, arguments: args } = toolCall.function;
324
+ const tool = this.tools.get(name);
325
+
326
+ if (!tool) {
327
+ return { error: `Tool "${name}" not found` };
328
+ }
329
+
330
+ try {
331
+ const params = JSON.parse(args);
332
+ const result = await tool.execute(params, {
333
+ confirmAction: async (msg: string): Promise<boolean> => {
334
+ console.log(chalk.yellow(`\n⚠️ Tool wants to execute: ${msg}`));
335
+ return false; // Default deny in CLI mode
336
+ }
337
+ });
338
+
339
+ return {
340
+ output: result.success ? (result.output || JSON.stringify(result.data)) : undefined,
341
+ error: result.error
342
+ };
343
+ } catch (error: any) {
344
+ return { error: `Tool execution failed: ${error.message}` };
345
+ }
346
+ }
347
+
348
+ // ==================== Request Builders ====================
349
+
350
+ private buildOpenAIRequest(messages: ChatMessage[], stream: boolean) {
351
+ const tools = this.getToolsForAPI();
352
+ return {
353
+ model: this.config.model || 'Qwen/Qwen2.5-7B-Instruct',
354
+ messages: messages.map(m => ({
355
+ role: m.role,
356
+ content: m.content,
357
+ name: m.name,
358
+ tool_call_id: m.tool_call_id,
359
+ tool_calls: m.tool_calls
360
+ })),
361
+ temperature: this.config.temperature || 0.7,
362
+ max_tokens: this.config.maxTokens || 4096,
363
+ stream,
364
+ ...(tools.length > 0 && { tools })
365
+ };
366
+ }
367
+
368
+ private buildAnthropicRequest(messages: ChatMessage[], stream: boolean) {
369
+ const anthropicMessages = messages
370
+ .filter(m => m.role !== 'system')
371
+ .map(m => ({
372
+ role: m.role === 'assistant' ? 'assistant' : 'user',
373
+ content: m.content
374
+ }));
375
+
376
+ return {
377
+ model: this.config.model || 'claude-3-haiku-20240307',
378
+ messages: anthropicMessages,
379
+ max_tokens: this.config.maxTokens || 4096,
380
+ temperature: this.config.temperature || 0.7,
381
+ stream
382
+ };
383
+ }
384
+
385
+ private buildGeminiRequest(messages: ChatMessage[]) {
386
+ const contents = messages
387
+ .filter(m => m.role !== 'system')
388
+ .map(m => ({
389
+ role: m.role === 'assistant' ? 'model' : 'user',
390
+ parts: [{ text: m.content }]
391
+ }));
392
+
393
+ return {
394
+ contents,
395
+ generationConfig: {
396
+ temperature: this.config.temperature || 0.7,
397
+ maxOutputTokens: this.config.maxTokens || 4096
398
+ }
399
+ };
400
+ }
401
+
402
+ private getApiKey(): string {
403
+ const provider = this.config.provider || 'siliconflow';
404
+
405
+ const envKeys: Record<string, string[]> = {
406
+ siliconflow: ['SILICONFLOW_API_KEY', 'OPENAI_API_KEY'],
407
+ minimax: ['MINIMAX_API_KEY', 'OPENAI_API_KEY'],
408
+ openai: ['OPENAI_API_KEY'],
409
+ anthropic: ['ANTHROPIC_API_KEY'],
410
+ ollama: [],
411
+ gemini: ['GEMINI_API_KEY'],
412
+ kimi: ['KIMI_API_KEY', 'MOONSHOT_API_KEY'],
413
+ deepseek: ['DEEPSEEK_API_KEY']
414
+ };
415
+
416
+ for (const key of envKeys[provider] || []) {
417
+ if (process.env[key]) return process.env[key];
418
+ }
419
+
420
+ return '';
421
+ }
422
+
423
+ private getMockResponse(messages: ChatMessage[]): string {
424
+ const lastMessage = messages[messages.length - 1]?.content || '';
425
+ let response = 'Hello! I am Thatgfsj Code.\n\n';
426
+
427
+ if (lastMessage.toLowerCase().includes('hello') || lastMessage.toLowerCase().includes('hi')) {
428
+ response = 'Hi there! How can I help you today?';
429
+ } else if (lastMessage.toLowerCase().includes('who are you')) {
430
+ response = 'I am Thatgfsj Code, an AI assistant built with Node.js.';
431
+ } else {
432
+ response = `I understand you said: "${lastMessage.slice(0, 50)}..."\n\nThis is a streaming demo. Enable an API key for full AI capabilities.`;
433
+ }
434
+
435
+ return response;
436
+ }
437
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * S12: CLI & Architecture
3
+ *
4
+ * Main entry point, CLI argument parsing, and module architecture overview.
5
+ */
6
+
7
+ import { readFileSync } from 'fs';
8
+ import { join } from 'path';
9
+ import { AIEngine } from './ai-engine.js';
10
+ import { ConfigManager } from './config.js';
11
+ import { REPLLoop } from '../repl/loop.js';
12
+ import { ToolRegistry } from './tool-registry.js';
13
+ import { ShellTool, FileTool, GitTool } from '../tools/index.js';
14
+ import { HookManager, auditLogHook, getHookManager } from './hooks.js';
15
+ import { getStateManager } from './state.js';
16
+ import { SystemPromptBuilder } from './system-prompt.js';
17
+ import { BUILT_IN_SKILLS } from './skills.js';
18
+
19
+ // ==================== CLI Argument Parsing ====================
20
+
21
+ export interface CLIOptions {
22
+ model?: string;
23
+ provider?: string;
24
+ prompt?: string;
25
+ noStream?: boolean;
26
+ verbose?: boolean;
27
+ hooks?: boolean;
28
+ permissionMode?: 'accept' | 'deny' | 'ask';
29
+ }
30
+
31
+ export function parseArgs(args: string[]): CLIOptions {
32
+ const options: CLIOptions = {};
33
+
34
+ for (let i = 0; i < args.length; i++) {
35
+ const arg = args[i];
36
+
37
+ switch (arg) {
38
+ case '--model':
39
+ case '-m':
40
+ options.model = args[++i];
41
+ break;
42
+ case '--provider':
43
+ case '-p':
44
+ options.provider = args[++i];
45
+ break;
46
+ case '--prompt':
47
+ case '-c':
48
+ options.prompt = args[++i];
49
+ break;
50
+ case '--no-stream':
51
+ options.noStream = true;
52
+ break;
53
+ case '--verbose':
54
+ case '-v':
55
+ options.verbose = true;
56
+ break;
57
+ case '--hooks':
58
+ options.hooks = true;
59
+ break;
60
+ case '--permission':
61
+ options.permissionMode = (args[++i] as 'accept' | 'deny' | 'ask') || 'ask';
62
+ break;
63
+ case '--help':
64
+ case '-h':
65
+ printHelp();
66
+ process.exit(0);
67
+ }
68
+ }
69
+
70
+ return options;
71
+ }
72
+
73
+ function printHelp(): void {
74
+ console.log(`
75
+ Thatgfsj Code - AI Coding Assistant
76
+
77
+ Usage: thatgfsj [options]
78
+
79
+ Options:
80
+ -m, --model <model> Set AI model
81
+ -p, --provider <provider> Set provider (siliconflow, minimax, openai, etc.)
82
+ -c, --prompt <text> Run single prompt and exit
83
+ --no-stream Disable streaming output
84
+ --hooks Enable built-in hooks (audit log, etc.)
85
+ --permission <mode> Set permission mode (accept, deny, ask)
86
+ -v, --verbose Verbose output
87
+ -h, --help Show this help
88
+
89
+ Examples:
90
+ thatgfsj Start REPL
91
+ thatgfsj -c "Hello" Run single prompt
92
+ thatgfsj --provider minimax --model MiniMax-M2.5 Use specific provider
93
+ thatgfsj --permission accept Accept all tool calls
94
+ `);
95
+ }
96
+
97
+ // ==================== Architecture ====================
98
+
99
+ /**
100
+ * S12: Print architecture overview
101
+ */
102
+ export function printArchitecture(): void {
103
+ console.log(`
104
+ Thatgfsj Code Architecture
105
+ ============================
106
+
107
+ Core:
108
+ AIEngine - Async generator agent loop (S01), multi-provider
109
+ ToolRegistry - Tool registration and execution (S02)
110
+ PermissionChecker - 6-stage permission pipeline (S03)
111
+ SystemPromptBuilder - Dynamic prompt construction (S04)
112
+ ContextCompactor - 3-tier context compression (S05)
113
+ SubagentManager - Parallel subagent execution (S06)
114
+ HookManager - Event-driven hooks (S08)
115
+ SkillsLoader - Skills discovery and catalog (S10)
116
+ StateManager - Ephemeral/Persistent/Session state (S11)
117
+
118
+ Tools:
119
+ ShellTool - Shell command execution
120
+ FileTool - File read/write/list/delete
121
+ GitTool - Git operations
122
+
123
+ Entry:
124
+ REPLLoop - Interactive REPL
125
+ CLI - Command-line mode
126
+ `);
127
+ }
128
+
129
+ // ==================== Main ====================
130
+
131
+ export async function main(argv: string[]): Promise<void> {
132
+ const options = parseArgs(argv.slice(2));
133
+
134
+ // Single prompt mode
135
+ if (options.prompt) {
136
+ const config = await ConfigManager.load();
137
+ if (options.provider) config.provider = options.provider as any;
138
+ if (options.model) config.model = options.model;
139
+
140
+ const ai = new AIEngine(config);
141
+ const tools = [new ShellTool(), new FileTool(), new GitTool()];
142
+ for (const tool of tools) ai.registerTool(tool);
143
+
144
+ if (options.hooks) {
145
+ const hooks = getHookManager();
146
+ hooks.register('afterToolCall', auditLogHook);
147
+ ai.setHooks(hooks);
148
+ }
149
+
150
+ const promptBuilder = new SystemPromptBuilder({ tools, permissionMode: options.permissionMode });
151
+ const messages = [
152
+ { role: 'system' as const, content: promptBuilder.build() },
153
+ { role: 'user' as const, content: options.prompt }
154
+ ];
155
+
156
+ if (options.noStream) {
157
+ const response = await ai.chat(messages);
158
+ console.log(response.content);
159
+ } else {
160
+ for await (const chunk of ai.chatStream(messages)) {
161
+ process.stdout.write(chunk);
162
+ }
163
+ console.log();
164
+ }
165
+ return;
166
+ }
167
+
168
+ // REPL mode
169
+ const repl = new REPLLoop();
170
+ await repl.start();
171
+ }