aegiscode 3.1.10 → 3.4.2

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 (209) hide show
  1. package/bin/aegis.js +165 -0
  2. package/package.json +18 -86
  3. package/LICENSE +0 -21
  4. package/README.md +0 -394
  5. package/dist/main.js +0 -2171
  6. package/gui/run-gui.cjs +0 -13
  7. package/src/agent/Agent.ts +0 -903
  8. package/src/agent/SimpleAgent.ts +0 -48
  9. package/src/agent/index.ts +0 -54
  10. package/src/agent/orchestrator/AppBuilder.ts +0 -443
  11. package/src/agent/orchestrator/CouncilAgent.ts +0 -310
  12. package/src/agent/orchestrator/DiscussionRoom.ts +0 -462
  13. package/src/agent/orchestrator/OrchestratorAgent.ts +0 -637
  14. package/src/agent/orchestrator/index.ts +0 -38
  15. package/src/agent/orchestrator/utils.ts +0 -397
  16. package/src/agent/pricing.ts +0 -115
  17. package/src/agent/router.ts +0 -74
  18. package/src/agent/routerStats.ts +0 -121
  19. package/src/agent/types.ts +0 -318
  20. package/src/auth/login.ts +0 -383
  21. package/src/cli/config.ts +0 -189
  22. package/src/cli/index.ts +0 -17
  23. package/src/cli/middleware.ts +0 -119
  24. package/src/cli/types.ts +0 -75
  25. package/src/config/ConfigManager.ts +0 -587
  26. package/src/config/index.ts +0 -7
  27. package/src/config/types.ts +0 -584
  28. package/src/context/CompactionService.ts +0 -300
  29. package/src/context/ContextManager.ts +0 -450
  30. package/src/context/FileAnalyzer.ts +0 -267
  31. package/src/context/TokenCounter.ts +0 -265
  32. package/src/context/index.ts +0 -27
  33. package/src/context/storage/CacheStore.ts +0 -176
  34. package/src/context/storage/JSONLStore.ts +0 -201
  35. package/src/context/storage/MemoryStore.ts +0 -205
  36. package/src/context/storage/PersistentStore.ts +0 -327
  37. package/src/context/storage/index.ts +0 -9
  38. package/src/context/storage/pathUtils.ts +0 -114
  39. package/src/context/test.ts +0 -309
  40. package/src/context/types.ts +0 -268
  41. package/src/hooks/HookExecutor.ts +0 -434
  42. package/src/hooks/HookManager.ts +0 -596
  43. package/src/hooks/HookService.ts +0 -269
  44. package/src/hooks/Matcher.ts +0 -157
  45. package/src/hooks/index.ts +0 -63
  46. package/src/hooks/types.ts +0 -424
  47. package/src/main.tsx +0 -596
  48. package/src/mcp/HealthMonitor.ts +0 -150
  49. package/src/mcp/McpClient.ts +0 -491
  50. package/src/mcp/McpRegistry.ts +0 -321
  51. package/src/mcp/createMcpTool.ts +0 -251
  52. package/src/mcp/index.ts +0 -15
  53. package/src/mcp/server.ts +0 -334
  54. package/src/mcp/test-server.ts +0 -88
  55. package/src/mcp/test.ts +0 -372
  56. package/src/mcp/types.ts +0 -247
  57. package/src/memory/AgentMemoryBus.ts +0 -432
  58. package/src/memory/CloudSync.ts +0 -99
  59. package/src/memory/DriveSync.ts +0 -106
  60. package/src/memory/SharedMemory.ts +0 -951
  61. package/src/memory/index.ts +0 -14
  62. package/src/memory/machineFingerprint.ts +0 -40
  63. package/src/orchestrator/SubAgentMetadata.ts +0 -136
  64. package/src/prompts/builder.ts +0 -213
  65. package/src/prompts/default.ts +0 -144
  66. package/src/prompts/index.ts +0 -16
  67. package/src/prompts/plan.ts +0 -64
  68. package/src/prompts/test.ts +0 -78
  69. package/src/services/AnthropicChatService.ts +0 -341
  70. package/src/services/ChatService.ts +0 -347
  71. package/src/services/ClaudeCliChatService.ts +0 -256
  72. package/src/services/CloudSync.ts +0 -168
  73. package/src/services/CostLedger.ts +0 -211
  74. package/src/services/Heartbeat.ts +0 -135
  75. package/src/services/LearningCollector.ts +0 -291
  76. package/src/services/OllamaInstaller.ts +0 -342
  77. package/src/services/VersionChecker.ts +0 -445
  78. package/src/services/index.ts +0 -57
  79. package/src/services/streaming/OpenAIEventAdapter.ts +0 -126
  80. package/src/services/streaming/RenderingProfile.ts +0 -90
  81. package/src/services/streaming/StreamEventParser.ts +0 -181
  82. package/src/services/streaming/ThrottledRenderer.ts +0 -139
  83. package/src/services/streaming/TranscriptBuffer.ts +0 -574
  84. package/src/services/streaming/eventStatusMap.ts +0 -52
  85. package/src/services/streaming/index.ts +0 -46
  86. package/src/services/streaming/renderFormatting.ts +0 -79
  87. package/src/services/streaming/types.ts +0 -234
  88. package/src/skills/SkillLoader.ts +0 -126
  89. package/src/skills/SkillRegistry.ts +0 -366
  90. package/src/skills/index.ts +0 -48
  91. package/src/skills/types.ts +0 -146
  92. package/src/slash-commands/billing.ts +0 -70
  93. package/src/slash-commands/build.ts +0 -413
  94. package/src/slash-commands/builtinCommands.ts +0 -2733
  95. package/src/slash-commands/clone.ts +0 -242
  96. package/src/slash-commands/council.ts +0 -125
  97. package/src/slash-commands/custom/CustomCommandExecutor.ts +0 -143
  98. package/src/slash-commands/custom/CustomCommandLoader.ts +0 -251
  99. package/src/slash-commands/custom/CustomCommandRegistry.ts +0 -144
  100. package/src/slash-commands/custom/index.ts +0 -7
  101. package/src/slash-commands/debate.ts +0 -254
  102. package/src/slash-commands/gmail.ts +0 -105
  103. package/src/slash-commands/index.ts +0 -388
  104. package/src/slash-commands/mcpCommand.ts +0 -205
  105. package/src/slash-commands/types.ts +0 -201
  106. package/src/store/index.ts +0 -76
  107. package/src/store/selectors.ts +0 -246
  108. package/src/store/slices/appSlice.ts +0 -205
  109. package/src/store/slices/commandSlice.ts +0 -115
  110. package/src/store/slices/configSlice.ts +0 -46
  111. package/src/store/slices/focusSlice.ts +0 -64
  112. package/src/store/slices/index.ts +0 -9
  113. package/src/store/slices/sessionSlice.ts +0 -424
  114. package/src/store/streaming-buffer.ts +0 -425
  115. package/src/store/test.ts +0 -296
  116. package/src/store/types.ts +0 -274
  117. package/src/store/vanilla.ts +0 -186
  118. package/src/tools/builtin/bash.ts +0 -236
  119. package/src/tools/builtin/council.ts +0 -105
  120. package/src/tools/builtin/edit.ts +0 -213
  121. package/src/tools/builtin/glob.ts +0 -136
  122. package/src/tools/builtin/grep.ts +0 -263
  123. package/src/tools/builtin/index.ts +0 -61
  124. package/src/tools/builtin/memory.ts +0 -66
  125. package/src/tools/builtin/read.ts +0 -168
  126. package/src/tools/builtin/skill.ts +0 -97
  127. package/src/tools/builtin/snapshot.ts +0 -40
  128. package/src/tools/builtin/task.ts +0 -106
  129. package/src/tools/builtin/write.ts +0 -134
  130. package/src/tools/createTool.ts +0 -221
  131. package/src/tools/execution/ExecutionPipeline.ts +0 -263
  132. package/src/tools/execution/index.ts +0 -40
  133. package/src/tools/execution/stages/CacheStage.ts +0 -131
  134. package/src/tools/execution/stages/ConfirmationStage.ts +0 -203
  135. package/src/tools/execution/stages/DiscoveryStage.ts +0 -46
  136. package/src/tools/execution/stages/ExecutionStage.ts +0 -48
  137. package/src/tools/execution/stages/FormattingStage.ts +0 -44
  138. package/src/tools/execution/stages/HookStage.ts +0 -72
  139. package/src/tools/execution/stages/PermissionStage.ts +0 -287
  140. package/src/tools/execution/stages/PostHookStage.ts +0 -71
  141. package/src/tools/execution/stages/index.ts +0 -12
  142. package/src/tools/execution/test.ts +0 -266
  143. package/src/tools/execution/types.ts +0 -273
  144. package/src/tools/index.ts +0 -81
  145. package/src/tools/registry.ts +0 -304
  146. package/src/tools/schemas.ts +0 -109
  147. package/src/tools/test.ts +0 -220
  148. package/src/tools/types.ts +0 -175
  149. package/src/tools/validation/PermissionChecker.ts +0 -242
  150. package/src/tools/validation/SensitiveFileDetector.ts +0 -210
  151. package/src/tools/validation/index.ts +0 -11
  152. package/src/ui/App.tsx +0 -166
  153. package/src/ui/components/AegisInterface.tsx +0 -484
  154. package/src/ui/components/common/ChatSearch.tsx +0 -150
  155. package/src/ui/components/common/ErrorBoundary.tsx +0 -82
  156. package/src/ui/components/common/ExitMessage.tsx +0 -120
  157. package/src/ui/components/common/LoadingIndicator.tsx +0 -49
  158. package/src/ui/components/common/index.ts +0 -6
  159. package/src/ui/components/dialog/ConfirmationPrompt.tsx +0 -208
  160. package/src/ui/components/dialog/InteractiveSelector.tsx +0 -149
  161. package/src/ui/components/dialog/SetupWizard.tsx +0 -297
  162. package/src/ui/components/dialog/UpdatePrompt.tsx +0 -155
  163. package/src/ui/components/dialog/index.ts +0 -8
  164. package/src/ui/components/index.ts +0 -28
  165. package/src/ui/components/input/CommandSuggestions.tsx +0 -139
  166. package/src/ui/components/input/CustomTextInput.tsx +0 -220
  167. package/src/ui/components/input/InputArea.tsx +0 -361
  168. package/src/ui/components/input/PromptSuggestions.tsx +0 -66
  169. package/src/ui/components/input/index.ts +0 -6
  170. package/src/ui/components/layout/ChatStatusBar.tsx +0 -90
  171. package/src/ui/components/layout/ContextBar.tsx +0 -79
  172. package/src/ui/components/layout/MessageArea.tsx +0 -96
  173. package/src/ui/components/layout/MessageList.tsx +0 -647
  174. package/src/ui/components/layout/MessageSeparator.tsx +0 -26
  175. package/src/ui/components/layout/WelcomeMessage.tsx +0 -93
  176. package/src/ui/components/layout/index.ts +0 -7
  177. package/src/ui/components/markdown/CodeHighlighter.tsx +0 -292
  178. package/src/ui/components/markdown/MessageRenderer.tsx +0 -1211
  179. package/src/ui/components/markdown/index.ts +0 -8
  180. package/src/ui/components/markdown/parser.ts +0 -336
  181. package/src/ui/components/markdown/types.ts +0 -66
  182. package/src/ui/focus/FocusManager.ts +0 -137
  183. package/src/ui/focus/index.ts +0 -13
  184. package/src/ui/focus/types.ts +0 -54
  185. package/src/ui/focus/useFocus.ts +0 -75
  186. package/src/ui/hooks/index.ts +0 -11
  187. package/src/ui/hooks/useAgent.ts +0 -284
  188. package/src/ui/hooks/useCommandHistory.ts +0 -87
  189. package/src/ui/hooks/useCommandProcessor.ts +0 -443
  190. package/src/ui/hooks/useConfirmation.ts +0 -99
  191. package/src/ui/hooks/useCtrlCHandler.ts +0 -100
  192. package/src/ui/hooks/useInputBuffer.ts +0 -122
  193. package/src/ui/hooks/useTerminalSize.ts +0 -68
  194. package/src/ui/hooks/useTerminalWidth.ts +0 -5
  195. package/src/ui/hooks/useWindowedList.ts +0 -118
  196. package/src/ui/render-debugger.ts +0 -621
  197. package/src/ui/test.ts +0 -189
  198. package/src/ui/themes/ThemeManager.ts +0 -332
  199. package/src/ui/themes/aegisTheme.ts +0 -87
  200. package/src/ui/themes/darkTheme.ts +0 -87
  201. package/src/ui/themes/defaultTheme.ts +0 -85
  202. package/src/ui/themes/index.ts +0 -10
  203. package/src/ui/themes/lightTheme.ts +0 -89
  204. package/src/ui/themes/popularThemes.ts +0 -187
  205. package/src/ui/themes/types.ts +0 -130
  206. package/src/utils/clipboard.ts +0 -48
  207. package/src/utils/debug.ts +0 -43
  208. package/src/utils/environment.ts +0 -68
  209. package/src/utils/index.ts +0 -10
@@ -1,347 +0,0 @@
1
- /**
2
- * ChatService - LLM 通信服务
3
- */
4
-
5
- import OpenAI from 'openai';
6
- import type {
7
- Message,
8
- ToolDefinition,
9
- ChatResponse,
10
- IChatService,
11
- ToolCall,
12
- StreamCallbacks,
13
- } from '../agent/types.js';
14
- import { OpenAIEventAdapter } from './streaming/OpenAIEventAdapter.js';
15
- import { ClaudeCliChatService } from './ClaudeCliChatService.js';
16
- import { AnthropicChatService } from './AnthropicChatService.js';
17
-
18
- // For local Ollama models, only include tools when the query looks like a coding task.
19
- // This avoids sending 350+ tokens of tool schemas on every conversational message,
20
- // which would add 25-30s of prefill time on CPU.
21
- function ollamaQueryNeedsTools(messages: Message[]): boolean {
22
- const last = messages.filter(m => m.role === 'user').at(-1)?.content ?? '';
23
- return /\b(read|edit|write|create|delete|run|execute|bash|file|folder|dir|list|search|grep|find|install|build|test|fix|debug|refactor|rename|move|copy|open|show|cat|ls|pwd|cd|git|npm|pip|python|node)\b/i.test(last);
24
- }
25
-
26
- export interface ChatServiceConfig {
27
- apiKey: string;
28
- baseURL?: string;
29
- model?: string;
30
- maxRetries?: number;
31
- timeout?: number;
32
- /** aegiscode's own permission mode; only consulted for OAuth (claude CLI) transport. */
33
- permissionMode?: string;
34
- /** Extended-thinking budget tier — only honored on the native Anthropic transport. */
35
- thinkingBudget?: 'off' | 'low' | 'medium' | 'high' | 'max';
36
- maxOutputTokens?: number;
37
- }
38
-
39
- export class OpenAIChatService implements IChatService {
40
- private client: OpenAI;
41
- private model: string;
42
-
43
- constructor(config: ChatServiceConfig) {
44
- const isAnthropic = config.baseURL?.includes('anthropic.com') ?? false;
45
- this.client = new OpenAI({
46
- apiKey: config.apiKey,
47
- baseURL: config.baseURL,
48
- maxRetries: config.maxRetries ?? 2,
49
- timeout: config.timeout ?? 60000,
50
- defaultHeaders: isAnthropic ? {
51
- 'anthropic-version': '2023-06-01',
52
- 'anthropic-beta': 'messages-2023-12-15',
53
- } : undefined,
54
- });
55
- this.model = config.model || 'claude-sonnet-4-6';
56
- }
57
-
58
- async chat(
59
- messages: Message[],
60
- tools?: ToolDefinition[],
61
- signal?: AbortSignal,
62
- streamCallbacks?: StreamCallbacks,
63
- attempt = 0
64
- ): Promise<ChatResponse> {
65
- const isGroq = (this.client as any).baseURL?.includes('groq.com') || false;
66
- const isOllama = (this.client as any).baseURL?.includes('11434') || false;
67
- let content = '';
68
- let reasoningContent = '';
69
- let usage: ChatResponse['usage'] | undefined;
70
-
71
- try {
72
- // Strip zero-width characters and control characters that cause JSON parse errors
73
- const cleanContent = (s: string) => s.replace(/[\u200b-\u200f\u2028-\u202f\ufeff]/g, '');
74
- const openaiMessages = messages.map(msg => {
75
- const converted = this.convertMessage(msg);
76
- if (typeof converted.content === 'string') {
77
- converted.content = cleanContent(converted.content);
78
- }
79
- return converted;
80
- });
81
-
82
- // For small local Ollama models, inject a guardrail into the system message
83
- // so they don't hallucinate tool calls for casual/conversational input.
84
- if (isOllama) {
85
- const sysIdx = openaiMessages.findIndex(m => m.role === 'system');
86
- const guardrail = '\n\nIMPORTANT: Only call tools when the user explicitly asks you to work with files, run commands, or perform a coding task. For greetings and conversational messages respond with plain text only — do NOT call any tool.';
87
- if (sysIdx >= 0) {
88
- const existing = openaiMessages[sysIdx];
89
- openaiMessages[sysIdx] = {
90
- ...existing,
91
- content: (typeof existing.content === 'string' ? existing.content : '') + guardrail,
92
- };
93
- }
94
- }
95
-
96
- const requestParams: OpenAI.ChatCompletionCreateParams & { keep_alive?: number } = {
97
- model: this.model,
98
- messages: openaiMessages,
99
- stream: true,
100
- };
101
-
102
- // Keep Ollama models loaded in memory between requests — eliminates cold-start latency
103
- if (isOllama) {
104
- (requestParams as any).keep_alive = -1;
105
- }
106
-
107
- const includeTools = tools && tools.length > 0 && !isGroq &&
108
- (!isOllama || ollamaQueryNeedsTools(messages));
109
-
110
- if (includeTools) {
111
- requestParams.tools = tools!.map(tool => ({
112
- type: 'function' as const,
113
- function: tool.function,
114
- }));
115
- }
116
-
117
- const stream = await this.client.chat.completions.create(
118
- requestParams,
119
- { signal }
120
- );
121
-
122
- const toolCalls: Map<number, { id: string; name: string; arguments: string }> = new Map();
123
- const adapter = streamCallbacks?.onStreamEvent ? new OpenAIEventAdapter() : null;
124
- let inOllamaThinkBlock = false;
125
-
126
- for await (const chunk of stream) {
127
- const delta = chunk.choices[0]?.delta;
128
- if (!delta) continue;
129
-
130
- // For ollama: extract <think>…</think> from delta.content before adapter/callbacks.
131
- // Ollama embeds thinking in content as tags rather than a separate reasoning_content field.
132
- let adaptDelta = delta as Parameters<typeof OpenAIEventAdapter.prototype.adapt>[0];
133
- if (isOllama && delta.content) {
134
- let remaining = delta.content;
135
- let plainContent = '';
136
- let thinkContent = '';
137
-
138
- while (remaining.length > 0) {
139
- if (inOllamaThinkBlock) {
140
- const closeIdx = remaining.indexOf('</think>');
141
- if (closeIdx === -1) {
142
- thinkContent += remaining;
143
- remaining = '';
144
- } else {
145
- thinkContent += remaining.slice(0, closeIdx);
146
- remaining = remaining.slice(closeIdx + 8);
147
- inOllamaThinkBlock = false;
148
- }
149
- } else {
150
- const openIdx = remaining.indexOf('<think>');
151
- if (openIdx === -1) {
152
- plainContent += remaining;
153
- remaining = '';
154
- } else {
155
- plainContent += remaining.slice(0, openIdx);
156
- remaining = remaining.slice(openIdx + 7);
157
- inOllamaThinkBlock = true;
158
- }
159
- }
160
- }
161
-
162
- adaptDelta = {
163
- ...delta,
164
- content: plainContent || null,
165
- reasoning_content: thinkContent || null,
166
- } as Parameters<typeof OpenAIEventAdapter.prototype.adapt>[0];
167
- }
168
-
169
- // Unified event path: convert chunk to AnthropicStreamEvents and emit
170
- if (adapter && streamCallbacks?.onStreamEvent) {
171
- const events = adapter.adapt(adaptDelta);
172
- for (const event of events) {
173
- streamCallbacks.onStreamEvent(event);
174
- }
175
- }
176
-
177
- // Legacy individual callbacks (still called for backward compat)
178
- if (adaptDelta.content) {
179
- content += adaptDelta.content;
180
- streamCallbacks?.onContentDelta?.(adaptDelta.content);
181
- }
182
-
183
- const reasoning = (adaptDelta as Record<string, unknown>).reasoning_content
184
- || (adaptDelta as Record<string, unknown>).thinking
185
- || (adaptDelta as Record<string, unknown>).reasoning;
186
- if (reasoning && typeof reasoning === 'string') {
187
- reasoningContent += reasoning;
188
- streamCallbacks?.onThinkingDelta?.(reasoning);
189
- }
190
-
191
- if (delta.tool_calls) {
192
- for (const tc of delta.tool_calls) {
193
- const index = tc.index;
194
- if (!toolCalls.has(index)) {
195
- toolCalls.set(index, {
196
- id: tc.id || '',
197
- name: tc.function?.name || '',
198
- arguments: tc.function?.arguments || '',
199
- });
200
- if (tc.id && tc.function?.name) {
201
- streamCallbacks?.onToolCallStart?.({
202
- id: tc.id,
203
- type: 'function',
204
- function: { name: tc.function.name, arguments: '' },
205
- });
206
- }
207
- } else {
208
- const existing = toolCalls.get(index)!;
209
- if (tc.id) existing.id = tc.id;
210
- if (tc.function?.name) existing.name = tc.function.name;
211
- if (tc.function?.arguments) {
212
- existing.arguments += tc.function.arguments;
213
- streamCallbacks?.onToolCallDelta?.(existing.id, tc.function.arguments);
214
- }
215
- }
216
- }
217
- }
218
-
219
- try {
220
- if (chunk.usage) {
221
- usage = {
222
- promptTokens: chunk.usage.prompt_tokens || 0,
223
- completionTokens: chunk.usage.completion_tokens || 0,
224
- totalTokens: chunk.usage.total_tokens || 0,
225
- };
226
- }
227
- } catch {}
228
- }
229
-
230
- // Emit finalize events (content_block_stop + message_stop)
231
- if (adapter && streamCallbacks?.onStreamEvent) {
232
- const stopReason = (stream as any).finalMessage?.stop_reason;
233
- for (const event of adapter.finalize(stopReason)) {
234
- streamCallbacks.onStreamEvent(event);
235
- }
236
- }
237
-
238
- const result: ChatResponse = {
239
- content,
240
- reasoningContent: reasoningContent || undefined,
241
- usage,
242
- };
243
-
244
- if (toolCalls.size > 0) {
245
- result.toolCalls = Array.from(toolCalls.values()).map(tc => ({
246
- id: tc.id,
247
- type: 'function' as const,
248
- function: { name: tc.name, arguments: tc.arguments },
249
- }));
250
- }
251
-
252
- return result;
253
- } catch (error) {
254
- if (error instanceof Error && error.name === 'AbortError') throw error;
255
-
256
- // Exponential backoff for transient errors (429, 500, 503)
257
- const isTransient = (
258
- error instanceof OpenAI.APIError && [429, 500, 502, 503, 504].includes(error.status)
259
- ) || (
260
- error instanceof Error && (
261
- error.message.includes('Connection error') ||
262
- error.message.includes('ECONNRESET') ||
263
- error.message.includes('timeout')
264
- )
265
- );
266
-
267
- if (isTransient) {
268
- // Don't retry if content was already streaming: the UI buffer has partial
269
- // content and a retry with the same streamCallbacks would double it.
270
- if (content.length > 0) {
271
- return { content, reasoningContent: reasoningContent || undefined, usage };
272
- }
273
-
274
- const MAX_RETRIES = 5;
275
- if (attempt >= MAX_RETRIES) {
276
- const status = error instanceof OpenAI.APIError ? error.status : undefined;
277
- const reason = status === 429 ? 'Rate limited' : `Server error (${status ?? 'transient'})`;
278
- throw new Error(
279
- `${reason} — gave up after ${MAX_RETRIES} retries.\n` +
280
- (status === 429
281
- ? `The API is rate-limiting this key. Wait a few minutes or check usage.\n`
282
- : (error as Error).message)
283
- );
284
- }
285
-
286
- const delay = Math.min(1000 * 2 ** attempt, 16000);
287
- process.stderr.write(`[RETRY] attempt ${attempt + 1}/${MAX_RETRIES} after ${delay}ms\n`);
288
- await new Promise(r => setTimeout(r, delay));
289
- return this.chat(messages, tools, signal, streamCallbacks, attempt + 1);
290
- }
291
-
292
- if (error instanceof OpenAI.APIError) {
293
- if (isOllama && error.status === 400 && error.message.includes('does not support tools')) {
294
- throw new Error(
295
- `Model "${this.model}" does not support tools.\n\n` +
296
- `Switch to a tool-capable model:\n` +
297
- ` aegis --model llama3.2\n` +
298
- ` aegis --model mistral-nemo\n` +
299
- ` aegis --model qwen2.5-coder\n\n` +
300
- `Or run: ollama pull llama3.2`
301
- );
302
- }
303
- throw new Error(`LLM API Error: ${error.message}`);
304
- }
305
- throw error;
306
- }
307
- }
308
-
309
- private convertMessage(msg: Message): OpenAI.ChatCompletionMessageParam {
310
- switch (msg.role) {
311
- case 'system':
312
- return { role: 'system', content: msg.content };
313
- case 'user':
314
- return { role: 'user', content: msg.content };
315
- case 'assistant':
316
- const assistantMsg: any = { role: 'assistant', content: msg.content };
317
- if ((msg as any).reasoning_content) assistantMsg.reasoning_content = (msg as any).reasoning_content;
318
- if (msg.tool_calls) {
319
- assistantMsg.tool_calls = msg.tool_calls.map(tc => ({
320
- id: tc.id,
321
- type: 'function' as const,
322
- function: { name: tc.function.name, arguments: tc.function.arguments },
323
- }));
324
- }
325
- return assistantMsg;
326
- case 'tool':
327
- return { role: 'tool', tool_call_id: msg.tool_call_id || '', content: msg.content };
328
- default:
329
- throw new Error(`Unknown message role: ${msg.role}`);
330
- }
331
- }
332
- }
333
-
334
- export function createChatService(config: ChatServiceConfig): IChatService {
335
- // Claude Code Pro/Max OAuth tokens (sk-ant-oat...) only work through the
336
- // real `claude` binary — Anthropic rejects direct API calls using them
337
- // from anything else. Same model selection, different transport.
338
- if (config.apiKey?.startsWith('sk-ant-oat')) {
339
- return new ClaudeCliChatService({ model: config.model, permissionMode: config.permissionMode });
340
- }
341
- // Native Anthropic transport — required for cache_control, thinking, and
342
- // citations, none of which the OpenAI-compatible shim below can carry.
343
- if (config.baseURL?.includes('anthropic.com')) {
344
- return new AnthropicChatService(config);
345
- }
346
- return new OpenAIChatService(config);
347
- }
@@ -1,256 +0,0 @@
1
- /**
2
- * ClaudeCliChatService — backs chat completions with the real `claude` binary
3
- * as a subprocess, for Claude Code Pro/Max subscription auth.
4
- *
5
- * Anthropic gates OAuth subscription tokens (sk-ant-oat...) to the official
6
- * Claude Code client — direct API calls with that token get rejected, even
7
- * with the right beta headers, unless the request actually comes from the
8
- * claude binary. So instead of impersonating that client, this shells out to
9
- * the genuine `claude` CLI, which is the only sanctioned way to spend a
10
- * subscription on chat completions.
11
- *
12
- * `claude --print` doesn't emit OpenAI-style tool-call JSON aegiscode's own
13
- * Read/Write/Bash loop could intercept, so instead the spawned claude binary
14
- * runs its own tools directly against this directory. There's no stdin
15
- * channel for the subprocess to ask the user a permission question (it's
16
- * spawned headless), so it always runs with bypassPermissions regardless of
17
- * aegiscode's own permission mode — except 'plan', which is read-only by
18
- * design and passed through as-is.
19
- *
20
- * Each `claude --print` call exits after one response, so a fresh process
21
- * has no memory of tool calls the previous turn started. We capture the
22
- * `session_id` from the first reply and pass it back via `--resume` on
23
- * later turns so the CLI continues the same session instead of replaying
24
- * the whole transcript as flat text into a brand-new one (which left tool
25
- * calls half-finished and re-described as text on every "continue").
26
- */
27
-
28
- import { spawn } from 'node:child_process';
29
- import { existsSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';
30
- import { join } from 'node:path';
31
- import { homedir, tmpdir } from 'node:os';
32
- import type {
33
- Message,
34
- ToolDefinition,
35
- ChatResponse,
36
- IChatService,
37
- StreamCallbacks,
38
- } from '../agent/types.js';
39
- import { getPermissionMode as getStorePermissionMode } from '../store/vanilla.js';
40
-
41
- export interface ClaudeCliChatServiceConfig {
42
- model?: string;
43
- /** aegiscode permission mode ('default' | 'autoEdit' | 'yolo' | 'plan'); mapped to claude CLI's --permission-mode. */
44
- permissionMode?: string;
45
- /** Kill the subprocess and reject if no reply within this many ms (default 600000). */
46
- timeout?: number;
47
- }
48
-
49
- // spawn('claude', ...) relies on process.env.PATH, which is fine in an interactive
50
- // shell but NOT when aegiscode is launched from a GUI app (Electron's main process
51
- // inherits whatever minimal PATH the desktop session/launcher set, often missing
52
- // ~/.local/bin) — this is exactly where Claude Code's own installer puts the
53
- // binary. Resolve an absolute path so Pro/Max chat doesn't ENOENT in that case.
54
- let cachedClaudeBin: string | null | undefined;
55
- function resolveClaudeBin(): string {
56
- if (cachedClaudeBin !== undefined) return cachedClaudeBin ?? 'claude';
57
-
58
- const home = homedir();
59
- const candidates = [
60
- ...(process.env.PATH || '').split(':').map(dir => join(dir, 'claude')),
61
- join(home, '.local', 'bin', 'claude'),
62
- join(home, '.npm-global', 'bin', 'claude'),
63
- '/usr/local/bin/claude',
64
- '/opt/homebrew/bin/claude',
65
- ];
66
-
67
- cachedClaudeBin = candidates.find(p => p && existsSync(p)) ?? null;
68
- return cachedClaudeBin ?? 'claude';
69
- }
70
-
71
- // Anything other than 'bypassPermissions' makes the CLI block on an interactive
72
- // tool-permission prompt — but this subprocess is spawned headless (stdin
73
- // 'ignore'), so there's no channel to ever answer that prompt. It just hangs
74
- // until ClaudeCliChatService's own timeout kills it. So regardless of
75
- // aegiscode's own permission mode, the subprocess always runs with
76
- // bypassPermissions; 'plan' is the only mode kept distinct since it's
77
- // read-only by design and doesn't need permission prompts at all.
78
- const PERMISSION_MODE_MAP: Record<string, string> = {
79
- default: 'bypassPermissions',
80
- autoEdit: 'bypassPermissions',
81
- yolo: 'bypassPermissions',
82
- plan: 'plan',
83
- };
84
-
85
- // Pushed onto every call's system prompt — aegiscode already resolved relevant
86
- // memory/project context into that prompt; re-discovering it via the subprocess's
87
- // own Read/Grep/Bash tools wastes turns and can miss what aegiscode already knew.
88
- const ASK_DONT_DIG_INSTRUCTION =
89
- 'The system prompt above includes aegiscode\'s own project and memory context for ' +
90
- 'this turn. Prefer that context over re-deriving it yourself. If something relevant ' +
91
- 'is missing or ambiguous, ask the user directly rather than spending turns exploring ' +
92
- 'files, git history, or memory on your own.';
93
-
94
- function transcriptFor(messages: Message[]): { systemPrompt: string; prompt: string } {
95
- const systemParts = messages.filter(m => m.role === 'system').map(m => m.content);
96
- const turns = messages.filter(m => m.role === 'user' || m.role === 'assistant');
97
-
98
- // claude --print answers one prompt at a time; fold prior turns into the
99
- // prompt text itself so multi-turn context survives across calls (mirrors
100
- // how OpenAIChatService is called — aegiscode always resends full history).
101
- const lines: string[] = [];
102
- for (const m of turns) {
103
- lines.push(`${m.role === 'user' ? 'Human' : 'Assistant'}: ${m.content}`);
104
- }
105
-
106
- return { systemPrompt: systemParts.join('\n\n'), prompt: lines.join('\n\n') };
107
- }
108
-
109
- export class ClaudeCliChatService implements IChatService {
110
- /** Set once the first reply gives us a session_id; reused via --resume on later turns. */
111
- private sessionId: string | undefined;
112
-
113
- constructor(private config: ClaudeCliChatServiceConfig) {}
114
-
115
- async chat(
116
- messages: Message[],
117
- tools?: ToolDefinition[],
118
- signal?: AbortSignal,
119
- streamCallbacks?: StreamCallbacks
120
- ): Promise<ChatResponse> {
121
- const args = ['--print', '--output-format', 'stream-json', '--include-partial-messages', '--verbose'];
122
- const currentMode = this.config.permissionMode || getStorePermissionMode() || 'default';
123
- const cliPermissionMode = PERMISSION_MODE_MAP[currentMode] ?? 'default';
124
- args.push('--permission-mode', cliPermissionMode);
125
- if (this.config.model) args.push('--model', this.config.model);
126
-
127
- // Always carry the current system message (Agent.ts rebuilds it fresh every
128
- // call with that turn's memory/project context) — even on --resume turns,
129
- // where it would otherwise be silently dropped, leaving the resumed session
130
- // to re-derive context itself via its own tools instead of using what
131
- // aegiscode already resolved.
132
- const { systemPrompt, prompt: fullPrompt } = transcriptFor(messages);
133
- const appendedSystem = [systemPrompt, ASK_DONT_DIG_INSTRUCTION].filter(Boolean).join('\n\n');
134
-
135
- // Large system/memory context plus a full resent transcript can blow past
136
- // the OS argv size limit (ARG_MAX) when passed as CLI arguments, killing
137
- // spawn() with E2BIG. Write the system prompt to a temp file and send the
138
- // prompt over stdin instead — neither touches argv, so there's no size cap.
139
- let systemPromptFile: string | undefined;
140
- let systemPromptDir: string | undefined;
141
- if (appendedSystem) {
142
- systemPromptDir = mkdtempSync(join(tmpdir(), 'aegis-sysprompt-'));
143
- systemPromptFile = join(systemPromptDir, 'system-prompt.txt');
144
- writeFileSync(systemPromptFile, appendedSystem);
145
- args.push('--append-system-prompt-file', systemPromptFile);
146
- }
147
-
148
- let prompt: string;
149
- if (this.sessionId) {
150
- // Resuming: the CLI already has the prior turns (and any tool calls it
151
- // started) in its own session — just send the newest user message.
152
- args.push('--resume', this.sessionId);
153
- prompt = messages.filter(m => m.role === 'user').at(-1)?.content ?? '';
154
- } else {
155
- prompt = fullPrompt;
156
- }
157
-
158
- const cleanupSystemPromptFile = () => {
159
- if (systemPromptDir) { try { rmSync(systemPromptDir, { recursive: true, force: true }); } catch { /* best effort */ } }
160
- };
161
-
162
- const result = await new Promise<{ content: string; usage?: ChatResponse['usage'] }>((resolve, reject) => {
163
- // Strip ANTHROPIC_API_KEY so the child claude binary uses its own
164
- // OAuth subscription login instead of our (possibly out-of-credit) key.
165
- const { ANTHROPIC_API_KEY, ...env } = process.env;
166
- const child = spawn(resolveClaudeBin(), args, { stdio: ['pipe', 'pipe', 'pipe'], env });
167
- child.stdin.write(prompt);
168
- child.stdin.end();
169
-
170
- const timeoutMs = this.config.timeout ?? 600000;
171
- const timeoutTimer = setTimeout(() => {
172
- child.kill('SIGTERM');
173
- reject(new Error(
174
- `claude CLI timed out after ${Math.round(timeoutMs / 1000)}s with no response ` +
175
- `(likely blocked waiting on a tool-permission prompt that nothing can answer in this context)`
176
- ));
177
- }, timeoutMs);
178
-
179
- let stderr = '';
180
- let stdoutBuffer = '';
181
- let finalResult: { result?: string; usage?: { input_tokens?: number; output_tokens?: number }; is_error?: boolean } | null = null;
182
-
183
- const handleLine = (line: string) => {
184
- if (!line.trim()) return;
185
- let parsed: any;
186
- try {
187
- parsed = JSON.parse(line);
188
- } catch {
189
- return;
190
- }
191
-
192
- if (parsed.session_id) this.sessionId = parsed.session_id;
193
-
194
- if (parsed.type === 'stream_event' && parsed.event) {
195
- // Wire format is identical to AnthropicChatService's SSE events —
196
- // forward as-is so the UI streams incrementally instead of one block.
197
- streamCallbacks?.onStreamEvent?.(parsed.event);
198
- } else if (parsed.type === 'result') {
199
- finalResult = parsed;
200
- }
201
- };
202
-
203
- child.stdout.on('data', d => {
204
- stdoutBuffer += d;
205
- let idx: number;
206
- while ((idx = stdoutBuffer.indexOf('\n')) !== -1) {
207
- handleLine(stdoutBuffer.slice(0, idx));
208
- stdoutBuffer = stdoutBuffer.slice(idx + 1);
209
- }
210
- });
211
- child.stderr.on('data', d => { stderr += d; });
212
-
213
- const onAbort = () => child.kill('SIGTERM');
214
- signal?.addEventListener('abort', onAbort);
215
-
216
- child.on('error', err => {
217
- clearTimeout(timeoutTimer);
218
- signal?.removeEventListener('abort', onAbort);
219
- cleanupSystemPromptFile();
220
- reject(new Error(
221
- `Failed to launch the claude CLI (${err.message}). Install it with: ` +
222
- `npm install -g @anthropic-ai/claude-code — then run "claude setup-token" ` +
223
- `and "/login --claude-pro" in aegiscode to connect your subscription.`
224
- ));
225
- });
226
-
227
- child.on('close', code => {
228
- clearTimeout(timeoutTimer);
229
- signal?.removeEventListener('abort', onAbort);
230
- cleanupSystemPromptFile();
231
- if (stdoutBuffer.trim()) handleLine(stdoutBuffer);
232
- if (signal?.aborted) {
233
- const err = new Error('Aborted');
234
- err.name = 'AbortError';
235
- reject(err);
236
- return;
237
- }
238
- if (code !== 0 || !finalResult || finalResult.is_error) {
239
- reject(new Error(finalResult?.result || stderr.trim() || `claude CLI exited with code ${code}`));
240
- return;
241
- }
242
- const usage = finalResult.usage;
243
- resolve({
244
- content: finalResult.result ?? '',
245
- usage: usage && {
246
- promptTokens: usage.input_tokens ?? 0,
247
- completionTokens: usage.output_tokens ?? 0,
248
- totalTokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0),
249
- },
250
- });
251
- });
252
- });
253
-
254
- return { content: result.content, usage: result.usage };
255
- }
256
- }