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,397 +0,0 @@
1
- /**
2
- * Orchestrator shared utilities
3
- *
4
- * Centralises model resolution, tool setup, and config construction
5
- * so that every slash-command (/multi, /research, …) does not repeat
6
- * the same boilerplate.
7
- */
8
-
9
- import * as fs from 'fs';
10
- import * as path from 'path';
11
- import { execSync } from 'child_process';
12
- import { createChatService } from '../../services/ChatService.js';
13
- import { createToolRegistry, getBuiltinTools, ExecutionPipeline, PermissionMode } from '../../tools/index.js';
14
- import { configManager } from '../../config/ConfigManager.js';
15
-
16
- // ─── Types ────────────────────────────────────────────────────────
17
-
18
- export interface ResolvedModelConfig {
19
- model: string;
20
- baseURL?: string;
21
- apiKey: string;
22
- timeout: number;
23
- }
24
-
25
- export interface SubAgentOptions {
26
- model: string;
27
- baseURL?: string;
28
- apiKey: string;
29
- timeout?: number;
30
- }
31
-
32
- // ─── Defaults ──────────────────────────────────────────────────────
33
-
34
- const DEFAULT_TIMEOUT = 180_000; // 3 min – sub-agents need more time
35
-
36
- // ─── Model Resolution ──────────────────────────────────────────────
37
-
38
- /**
39
- * Resolve model config from the store, config-manager, and env-vars.
40
- * Falls back through: store → configManager → env → ''
41
- *
42
- * This is the single source of truth used by every multi-agent command.
43
- */
44
- export function resolveModelConfig(): ResolvedModelConfig {
45
- // Try store first
46
- let model: string | undefined;
47
- let baseURL: string | undefined;
48
- let apiKey: string | undefined;
49
-
50
- try {
51
- // Dynamic import to avoid circular deps at module level
52
- const store = require('../../store/index.js');
53
- const currentModel = store.getCurrentModel();
54
- if (currentModel) {
55
- model = (currentModel as any).model || (currentModel as any).id;
56
- baseURL = (currentModel as any).baseURL || (currentModel as any).baseUrl;
57
- apiKey = (currentModel as any).apiKey;
58
- }
59
- } catch { /* store not ready */ }
60
-
61
- // Fallback: configManager
62
- if (!apiKey) {
63
- try {
64
- const def = configManager.getDefaultModel() as any;
65
- if (def) {
66
- model = model || def.model || def.id;
67
- baseURL = baseURL || def.baseURL || def.baseUrl;
68
- apiKey = apiKey || def.apiKey;
69
- }
70
- } catch { /* config not ready */ }
71
- }
72
-
73
- // Fallback: env vars
74
- model = model || process.env.OPENAI_MODEL || '';
75
- baseURL = baseURL || process.env.OPENAI_BASE_URL || '';
76
- apiKey = apiKey || resolveApiKeyFromEnv(baseURL || '');
77
-
78
- return { model: model || '', baseURL: baseURL || undefined, apiKey: apiKey || '', timeout: DEFAULT_TIMEOUT };
79
- }
80
-
81
- /**
82
- * Pick the matching API key from env based on base URL.
83
- */
84
- export function resolveApiKeyFromEnv(baseURL: string): string {
85
- const bu = baseURL.toLowerCase();
86
- if (bu.includes('anthropic')) return process.env.ANTHROPIC_API_KEY || '';
87
- if (bu.includes('deepseek')) return process.env.DEEPSEEK_API_KEY || '';
88
- if (bu.includes('groq')) return process.env.GROQ_API_KEY || '';
89
- if (bu.includes('openai')) return process.env.OPENAI_API_KEY || '';
90
- // Wildcard fallback
91
- return process.env.DEEPSEEK_API_KEY
92
- || process.env.OPENAI_API_KEY
93
- || process.env.GROQ_API_KEY
94
- || process.env.ANTHROPIC_API_KEY
95
- || '';
96
- }
97
-
98
- /**
99
- * Build a safe ModelConfig object (throws if apiKey is missing).
100
- */
101
- export function requireModelConfig(): ResolvedModelConfig {
102
- const cfg = resolveModelConfig();
103
- if (!cfg.apiKey) {
104
- throw new Error(
105
- 'No API key configured. Set DEEPSEEK_API_KEY, OPENAI_API_KEY, ' +
106
- 'GROQ_API_KEY, or ANTHROPIC_API_KEY in ~/.aegiscode/.env'
107
- );
108
- }
109
- return cfg;
110
- }
111
-
112
- // ─── Tool Setup Helpers ────────────────────────────────────────────
113
-
114
- /**
115
- * Create a lightweight tool registry + execution pipeline for sub-agents.
116
- *
117
- * When `allowAllBuiltins` is true the agent gets Read/Edit/Write/Grep/Glob/Bash.
118
- * Otherwise you can pass a list of tool names.
119
- */
120
- export function createSubAgentToolkit(allowedTools?: string[], options?: { permissionMode?: PermissionMode }) {
121
- const registry = createToolRegistry();
122
- const builtins = getBuiltinTools();
123
-
124
- const names = allowedTools || ['Read', 'Grep', 'Glob', 'Edit', 'Write', 'Bash'];
125
- for (const tool of builtins) {
126
- if (names.includes(tool.name)) {
127
- registry.register(tool);
128
- }
129
- }
130
-
131
- const mode = options?.permissionMode || resolveDefaultPermissionMode();
132
- const pipeline = new ExecutionPipeline(registry, {
133
- defaultMode: mode,
134
- });
135
-
136
- return { registry, pipeline };
137
- }
138
-
139
- /**
140
- * Read the user's configured permission mode, falling back to DEFAULT (ask for confirmation).
141
- */
142
- function resolveDefaultPermissionMode(): PermissionMode {
143
- try {
144
- const mode = configManager.getDefaultPermissionMode();
145
- switch (mode) {
146
- case 'autoEdit': return PermissionMode.AUTO_EDIT;
147
- case 'yolo': return PermissionMode.YOLO;
148
- case 'plan': return PermissionMode.PLAN;
149
- default: return PermissionMode.DEFAULT;
150
- }
151
- } catch {
152
- return PermissionMode.DEFAULT;
153
- }
154
- }
155
-
156
- /**
157
- * Make a lightweight chat service from a resolved model config.
158
- */
159
- export function createSubAgentChatService(cfg: ResolvedModelConfig) {
160
- return createChatService({
161
- apiKey: cfg.apiKey,
162
- baseURL: cfg.baseURL,
163
- model: cfg.model,
164
- timeout: cfg.timeout,
165
- });
166
- }
167
-
168
- // ─── Workspace Source Context ─────────────────────────────────────
169
-
170
- const IGNORE_DIRS = new Set([
171
- 'node_modules', '.git', 'dist', 'build', '.next', '.turbo',
172
- 'coverage', '.nyc_output', '__pycache__', '.cache', 'target',
173
- 'vendor', '.venv', 'venv', '.aegiscode', '.claude',
174
- ]);
175
-
176
- const SOURCE_EXTENSIONS = new Set([
177
- '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',
178
- '.py', '.rs', '.go', '.java', '.rb', '.php',
179
- '.vue', '.svelte', '.css', '.scss', '.html',
180
- '.json', '.yaml', '.yml', '.toml', '.prisma',
181
- ]);
182
-
183
- // Config files that are always included (even if they'd exceed maxFiles)
184
- const ALWAYS_INCLUDE = new Set([
185
- 'package.json', 'tsconfig.json', 'tsconfig.tsbuildinfo',
186
- '.env.example', 'docker-compose.yml', 'Dockerfile',
187
- 'Makefile', 'Cargo.toml', 'go.mod', 'Gemfile',
188
- 'requirements.txt', 'Pipfile', 'pyproject.toml',
189
- 'wrangler.jsonc', 'wrangler.toml', '.eslintrc.js', '.prettierrc',
190
- ]);
191
-
192
- /** Extract structural summary (exports / classes / functions / interfaces) from source */
193
- function extractStructure(content: string): string {
194
- const lines = content.split('\n');
195
- const sigs: string[] = [];
196
- for (const line of lines) {
197
- const trimmed = line.trim();
198
- // Exports
199
- if (/^export\s+(default\s+)?(function|class|interface|type|enum|const|let|var|async\s+function)/.test(trimmed)) {
200
- sigs.push(trimmed.replace(/^export\s+default\s+/, 'export default ').replace(/^export\s+/, ''));
201
- }
202
- // Top-level function/class defs (non-exported)
203
- else if (/^(function|class|interface|type|enum|async\s+function)\s+\w+/.test(trimmed)) {
204
- sigs.push(trimmed);
205
- }
206
- // Module-level const/let that looks like a binding (e.g., "const foo = ...")
207
- else if (/^(const|let|var)\s+\w+\s*[:=]/.test(trimmed) && !trimmed.includes(';') && !trimmed.endsWith(')')) {
208
- const name = trimmed.match(/^(const|let|var)\s+(\w+)/);
209
- if (name) sigs.push(`${name[1]} ${name[2]} = ...`);
210
- }
211
- if (sigs.length >= 30) break;
212
- }
213
- return sigs.join('\n');
214
- }
215
-
216
- /** Try to load a JSON config file and return pretty-printed key fields */
217
- function loadConfigSummary(cwd: string, name: string): string | null {
218
- try {
219
- const raw = fs.readFileSync(path.join(cwd, name), 'utf8');
220
- const parsed = JSON.parse(raw) as Record<string, unknown>;
221
- if (name === 'package.json') {
222
- const deps = parsed.dependencies as Record<string, string> | undefined;
223
- const devDeps = parsed.devDependencies as Record<string, string> | undefined;
224
- const scripts = parsed.scripts as Record<string, string> | undefined;
225
- const entries = [`name: ${parsed.name || '(unnamed)'}`];
226
- if (parsed.type) entries.push(`type: ${parsed.type}`);
227
- if (scripts) entries.push(`scripts: ${Object.keys(scripts).join(', ')}`);
228
- if (deps) entries.push(`deps[${Object.keys(deps).length}]: ${Object.keys(deps).slice(0, 20).join(', ')}`);
229
- if (devDeps) entries.push(`devDeps[${Object.keys(devDeps).length}]: ${Object.keys(devDeps).slice(0, 15).join(', ')}`);
230
- return entries.join('\n');
231
- }
232
- if (name === 'tsconfig.json') {
233
- const compiler = (parsed.compilerOptions as Record<string, unknown>) || {};
234
- const entries: string[] = [];
235
- if (compiler.target) entries.push(`target: ${compiler.target}`);
236
- if (compiler.module) entries.push(`module: ${compiler.module}`);
237
- if (compiler.outDir) entries.push(`outDir: ${compiler.outDir}`);
238
- if (compiler.rootDir) entries.push(`rootDir: ${compiler.rootDir}`);
239
- if (compiler.paths) entries.push(`paths: ${JSON.stringify(compiler.paths)}`);
240
- return entries.length ? entries.join('\n') : null;
241
- }
242
- return null;
243
- } catch {
244
- return null;
245
- }
246
- }
247
-
248
- /** Get list of recently changed files from git (last N commits) */
249
- function getRecentGitChanges(cwd: string, max = 10): string[] {
250
- try {
251
- const out = execSync('git diff --name-only HEAD~5..HEAD 2>/dev/null || git diff --name-only HEAD~3..HEAD 2>/dev/null || true', {
252
- cwd,
253
- encoding: 'utf8',
254
- timeout: 2000,
255
- });
256
- const files = out.split('\n').filter(Boolean).slice(0, max);
257
- // Only keep source files that actually exist
258
- return files.filter(f => {
259
- const ext = path.extname(f).toLowerCase();
260
- return SOURCE_EXTENSIONS.has(ext) && fs.existsSync(path.join(cwd, f));
261
- });
262
- } catch {
263
- return [];
264
- }
265
- }
266
-
267
- /** Sort source files: recently modified first, then alphabetical */
268
- function prioritizeFiles(files: string[], cwd: string, recentGit: string[]): string[] {
269
- const recentSet = new Set(recentGit.map(f => path.resolve(cwd, f)));
270
- const isConfig = (f: string) => ALWAYS_INCLUDE.has(path.basename(f));
271
-
272
- return [...files].sort((a, b) => {
273
- // Config files always first
274
- if (isConfig(a) && !isConfig(b)) return -1;
275
- if (!isConfig(a) && isConfig(b)) return 1;
276
- // Recently git-changed files next
277
- const aRecent = recentSet.has(a) ? 1 : 0;
278
- const bRecent = recentSet.has(b) ? 1 : 0;
279
- if (aRecent !== bRecent) return bRecent - aRecent;
280
- // Then by modification time (newest first)
281
- try {
282
- return fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs;
283
- } catch {
284
- return a.localeCompare(b);
285
- }
286
- });
287
- }
288
-
289
- /**
290
- * Build a rich source-code context string for a workspace directory.
291
- *
292
- * Scans the workspace and provides:
293
- * - Project metadata (package.json scripts/deps, tsconfig)
294
- * - Recently changed files (git)
295
- * - Prioritized file tree (configs & recent changes first)
296
- * - Structural summaries (exports, classes, functions) for each file
297
- *
298
- * Injected into sub-agent system prompts so they know what exists
299
- * and can target their Read / Grep / Glob calls effectively.
300
- */
301
- export function buildSourceContext(
302
- cwd: string,
303
- maxFiles = 50,
304
- maxTotalChars = 12000,
305
- ): string {
306
- try {
307
- const lines: string[] = [];
308
- let budget = maxTotalChars;
309
- const append = (s: string) => {
310
- if (s.length + 2 <= budget) {
311
- lines.push(s);
312
- budget -= s.length + 1;
313
- }
314
- };
315
-
316
- // ── Project Metadata ──
317
- const pkg = loadConfigSummary(cwd, 'package.json');
318
- const tsConfig = loadConfigSummary(cwd, 'tsconfig.json');
319
- if (pkg || tsConfig) {
320
- append('--- PROJECT ---');
321
- if (pkg) append(pkg);
322
- if (tsConfig) append(tsConfig);
323
- append('');
324
- }
325
-
326
- // ── Git Context ──
327
- const recentGit = getRecentGitChanges(cwd);
328
- if (recentGit.length > 0) {
329
- append('--- RECENTLY CHANGED (git) ---');
330
- for (const f of recentGit) append(` ${f}`);
331
- append('');
332
- }
333
-
334
- // ── File scan + prioritization ──
335
- const allFiles = listSourceFiles(cwd, maxFiles);
336
- if (allFiles.length === 0) return lines.join('\n').trim();
337
-
338
- const prioritized = prioritizeFiles(allFiles, cwd, recentGit);
339
-
340
- append('--- SOURCE FILES ---');
341
- append(`Directory: ${cwd}`);
342
- append('');
343
- for (const f of prioritized) {
344
- const display = path.relative(cwd, f);
345
- if (budget <= 50) { append(` ... and ${allFiles.length - prioritized.indexOf(f)} more files`); break; }
346
- append(` ${display}`);
347
- }
348
- append('');
349
-
350
- // ── Structural summaries for top files ──
351
- const summaryCount = Math.min(prioritized.length, 15);
352
- for (let i = 0; i < summaryCount && budget > 300; i++) {
353
- const f = prioritized[i];
354
- try {
355
- const content = fs.readFileSync(f, 'utf8');
356
- const rel = path.relative(cwd, f);
357
- const structure = extractStructure(content);
358
- if (structure) {
359
- const header = `--- ${rel} ---`;
360
- const block = `\n${header}\n${structure}\n`;
361
- if (block.length < budget - 100) {
362
- append(block);
363
- }
364
- }
365
- } catch { /* skip unreadable */ }
366
- }
367
-
368
- // ── Footer ──
369
- const footer = '--- END WORKSPACE SOURCE ---';
370
- if (footer.length <= budget) append(footer);
371
-
372
- return lines.join('\n');
373
- } catch {
374
- return '';
375
- }
376
- }
377
-
378
- function listSourceFiles(dir: string, max: number): string[] {
379
- const result: string[] = [];
380
- try {
381
- const entries = fs.readdirSync(dir, { withFileTypes: true });
382
- for (const e of entries) {
383
- if (result.length >= max) break;
384
- if (e.name.startsWith('.') || IGNORE_DIRS.has(e.name)) continue;
385
- const full = path.join(dir, e.name);
386
- if (e.isDirectory()) {
387
- result.push(...listSourceFiles(full, max - result.length));
388
- } else if (e.isFile()) {
389
- const ext = path.extname(e.name).toLowerCase();
390
- if (SOURCE_EXTENSIONS.has(ext)) {
391
- result.push(full);
392
- }
393
- }
394
- }
395
- } catch { /* skip inaccessible */ }
396
- return result;
397
- }
@@ -1,115 +0,0 @@
1
- /**
2
- * Pricing database — per-model costs in $/1M tokens (input, output).
3
- *
4
- * These are the raw provider costs before the AEGIS margin is applied.
5
- * Auto-router uses cheapest-first ordering; billing uses actual token
6
- * counts from each API call to compute the dollar cost and the 3× margin.
7
- */
8
- export type ModelCost = { input: number; output: number };
9
-
10
- /**
11
- * Price table keyed by model-id (the id field in config/models[]).
12
- * Falls back to partial name matching, then to a sensible default.
13
- */
14
- const MODEL_COST_TABLE: Record<string, ModelCost> = {
15
- // ── Anthropic ──
16
- 'claude-opus-4': { input: 15, output: 75 },
17
- 'claude-sonnet-4': { input: 3, output: 15 },
18
- 'claude-haiku-4': { input: 0.8, output: 4 },
19
- 'claude-fable-5': { input: 5, output: 25 },
20
-
21
- // ── OpenAI ──
22
- 'openai-gpt-4o': { input: 2.5, output: 10 },
23
- 'openai-o3': { input: 10, output: 40 },
24
- 'openai-gpt-5.5': { input: 10, output: 40 },
25
- 'chatgpt': { input: 2.5, output: 10 },
26
-
27
- // ── DeepSeek ──
28
- 'deepseek-chat': { input: 0.14, output: 0.28 },
29
- 'deepseek-reasoner': { input: 0.55, output: 2.19 },
30
-
31
- // ── Groq ──
32
- 'groq-llama': { input: 0.06, output: 0.06 },
33
- 'groq-deepseek': { input: 0.06, output: 0.06 },
34
-
35
- // ── Google ──
36
- 'gemini-2.5-pro': { input: 1.25, output: 10 },
37
- 'gemini-2.5-flash': { input: 0.15, output: 0.60 },
38
-
39
- // ── Local ──
40
- 'ollama-local': { input: 0, output: 0 },
41
- };
42
-
43
- /**
44
- * Look up a model's raw provider cost by its model-id.
45
- * Falls back to partial name matching when no exact key exists.
46
- * Returns a sensible default ($1/$3 per MTok) when unknown.
47
- */
48
- export function costForModel(modelIdOrName: string): ModelCost {
49
- const exact = MODEL_COST_TABLE[modelIdOrName];
50
- if (exact) return exact;
51
-
52
- const key = modelIdOrName.toLowerCase();
53
- for (const [id, cost] of Object.entries(MODEL_COST_TABLE)) {
54
- if (key.includes(id) || id.includes(key)) return cost;
55
- }
56
- return { input: 1, output: 3 }; // fallback
57
- }
58
-
59
- /**
60
- * Compute the raw dollar cost for a single API call.
61
- *
62
- * @param modelId Model identifier (used for price lookup)
63
- * @param promptTokens Tokens in the prompt/input
64
- * @param completionTokens Tokens in the completion/output
65
- * @returns Raw provider cost in dollars
66
- */
67
- export function computeRawCost(
68
- modelId: string,
69
- promptTokens: number,
70
- completionTokens: number,
71
- ): number {
72
- const { input, output } = costForModel(modelId);
73
- return (promptTokens * input + completionTokens * output) / 1_000_000;
74
- }
75
-
76
- /** Margin multiplier applied to raw provider cost. */
77
- export const MARGIN_MULTIPLIER = 3;
78
-
79
- /**
80
- * Compute the billed (user-facing) cost including the AEGIS margin.
81
- * Billed cost = raw cost × MARGIN_MULTIPLIER.
82
- * The difference (billed − raw) is the AEGIS margin.
83
- */
84
- export function computeBilledCost(rawCost: number): number {
85
- return rawCost * MARGIN_MULTIPLIER;
86
- }
87
-
88
- /**
89
- * Convenience — returns both raw and billed cost in one call.
90
- *
91
- * @returns { rawCost, billedCost, marginAmount }
92
- */
93
- export function computeCosts(
94
- modelId: string,
95
- promptTokens: number,
96
- completionTokens: number,
97
- ): { rawCost: number; billedCost: number; marginAmount: number } {
98
- const rawCost = computeRawCost(modelId, promptTokens, completionTokens);
99
- const billedCost = computeBilledCost(rawCost);
100
- return {
101
- rawCost,
102
- billedCost,
103
- marginAmount: billedCost - rawCost,
104
- };
105
- }
106
-
107
- /** Format a dollar value to a readable string (short, no trailing zeros). */
108
- export function formatCost(usd: number): string {
109
- if (usd === 0) return '$0';
110
- if (usd < 0.00001) return '<$0.00001';
111
- if (usd < 0.01) return `$${usd.toFixed(5)}`;
112
- if (usd < 1) return `$${usd.toFixed(4)}`;
113
- if (usd < 100) return `$${usd.toFixed(3)}`;
114
- return `$${usd.toFixed(2)}`;
115
- }
@@ -1,74 +0,0 @@
1
- /**
2
- * Auto-router — classifies a task's complexity with cheap heuristics (no LLM
3
- * call) and resolves which configured model should handle it, so a quick
4
- * lookup doesn't pay for an expensive model and a hard refactor doesn't get
5
- * shortchanged by a weak one.
6
- */
7
-
8
- import type { ModelConfig } from '../config/types.js';
9
- import { pickByOutcomes } from './routerStats.js';
10
-
11
- export type ComplexityTier = 'simple' | 'medium' | 'complex';
12
-
13
- const COMPLEX_KEYWORDS = [
14
- 'architecture', 'refactor', 'security', 'design', 'rewrite', 'migrate',
15
- 'migration', 'performance', 'race condition', 'concurrency', 'scalability',
16
- 'vulnerability', 'audit', 'distributed', 'consensus', 'deadlock',
17
- ];
18
-
19
- const SIMPLE_LEAD_WORDS = new Set([
20
- 'what', 'why', 'how', 'when', 'where', 'who', 'is', 'are', 'does', 'do',
21
- 'can', 'explain', 'list', 'show', 'define',
22
- ]);
23
-
24
- /** Cheap heuristics, no LLM call — classify before picking a model. */
25
- export function classifyComplexity(message: string): ComplexityTier {
26
- const text = message.trim();
27
- const lower = text.toLowerCase();
28
- const wordCount = text.split(/\s+/).filter(Boolean).length;
29
-
30
- if (COMPLEX_KEYWORDS.some(kw => lower.includes(kw)) || wordCount > 80) {
31
- return 'complex';
32
- }
33
-
34
- const firstWord = lower.split(/\s+/)[0]?.replace(/[^a-z]/g, '') || '';
35
- const looksLikeQuestion = SIMPLE_LEAD_WORDS.has(firstWord) || text.endsWith('?');
36
- const mentionsManyFiles =
37
- (text.match(/\b[\w./-]+\.(ts|tsx|js|jsx|py|go|rs|java|json|md)\b/gi) || []).length > 2;
38
-
39
- if (looksLikeQuestion && wordCount <= 25 && !mentionsManyFiles) {
40
- return 'simple';
41
- }
42
-
43
- return 'medium';
44
- }
45
-
46
- /** Cheapest → strongest known model ids per tier, used when no explicit tier is set. */
47
- const TIER_FALLBACKS: Record<ComplexityTier, string[]> = {
48
- simple: ['groq-llama', 'deepseek-chat', 'claude-haiku-4', 'gemini-2.5-flash', 'chatgpt'],
49
- medium: ['deepseek-chat', 'claude-sonnet-4', 'gemini-2.5-pro', 'openai-gpt-4o', 'chatgpt'],
50
- complex: ['claude-opus-4', 'openai-o3', 'claude-sonnet-4', 'gemini-2.5-pro', 'chatgpt'],
51
- };
52
-
53
- /**
54
- * Resolve which configured model should handle this tier. Prefers an
55
- * explicit tier->modelId mapping; falls back to the first usable
56
- * (non-empty apiKey) model from a fixed cost-ordered list. Returns
57
- * undefined if nothing usable is found — caller should keep using
58
- * whatever model is already active.
59
- */
60
- export function resolveModelForTier(
61
- tier: ComplexityTier,
62
- models: ModelConfig[],
63
- explicitTiers?: Partial<Record<ComplexityTier, string>>,
64
- ): ModelConfig | undefined {
65
- const usable = (id?: string): ModelConfig | undefined =>
66
- id ? models.find(m => m.id === id && m.apiKey) : undefined;
67
-
68
- const explicit = usable(explicitTiers?.[tier]);
69
- if (explicit) return explicit;
70
-
71
- const usableIds = TIER_FALLBACKS[tier].filter(id => usable(id));
72
- const picked = pickByOutcomes(tier, usableIds);
73
- return usable(picked);
74
- }