aegiscode 3.1.8 → 3.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -15
- package/dist/main.js +549 -552
- package/package.json +4 -2
- package/src/agent/Agent.ts +903 -0
- package/src/agent/SimpleAgent.ts +48 -0
- package/src/agent/index.ts +54 -0
- package/src/agent/orchestrator/AppBuilder.ts +443 -0
- package/src/agent/orchestrator/CouncilAgent.ts +310 -0
- package/src/agent/orchestrator/DiscussionRoom.ts +462 -0
- package/src/agent/orchestrator/OrchestratorAgent.ts +637 -0
- package/src/agent/orchestrator/index.ts +38 -0
- package/src/agent/orchestrator/utils.ts +397 -0
- package/src/agent/pricing.ts +115 -0
- package/src/agent/router.ts +74 -0
- package/src/agent/routerStats.ts +121 -0
- package/src/agent/types.ts +318 -0
- package/src/auth/login.ts +383 -0
- package/src/cli/config.ts +189 -0
- package/src/cli/index.ts +17 -0
- package/src/cli/middleware.ts +119 -0
- package/src/cli/types.ts +75 -0
- package/src/config/ConfigManager.ts +587 -0
- package/src/config/index.ts +7 -0
- package/src/config/types.ts +584 -0
- package/src/context/CompactionService.ts +300 -0
- package/src/context/ContextManager.ts +450 -0
- package/src/context/FileAnalyzer.ts +267 -0
- package/src/context/TokenCounter.ts +265 -0
- package/src/context/index.ts +27 -0
- package/src/context/storage/CacheStore.ts +176 -0
- package/src/context/storage/JSONLStore.ts +201 -0
- package/src/context/storage/MemoryStore.ts +205 -0
- package/src/context/storage/PersistentStore.ts +327 -0
- package/src/context/storage/index.ts +9 -0
- package/src/context/storage/pathUtils.ts +114 -0
- package/src/context/test.ts +309 -0
- package/src/context/types.ts +268 -0
- package/src/hooks/HookExecutor.ts +434 -0
- package/src/hooks/HookManager.ts +596 -0
- package/src/hooks/HookService.ts +269 -0
- package/src/hooks/Matcher.ts +157 -0
- package/src/hooks/index.ts +63 -0
- package/src/hooks/types.ts +424 -0
- package/src/main.tsx +596 -0
- package/src/mcp/HealthMonitor.ts +150 -0
- package/src/mcp/McpClient.ts +491 -0
- package/src/mcp/McpRegistry.ts +321 -0
- package/src/mcp/createMcpTool.ts +251 -0
- package/src/mcp/index.ts +15 -0
- package/src/mcp/server.ts +334 -0
- package/src/mcp/test-server.ts +88 -0
- package/src/mcp/test.ts +372 -0
- package/src/mcp/types.ts +247 -0
- package/src/memory/AgentMemoryBus.ts +432 -0
- package/src/memory/CloudSync.ts +99 -0
- package/src/memory/DriveSync.ts +106 -0
- package/src/memory/SharedMemory.ts +951 -0
- package/src/memory/index.ts +14 -0
- package/src/memory/machineFingerprint.ts +40 -0
- package/src/orchestrator/SubAgentMetadata.ts +136 -0
- package/src/prompts/builder.ts +213 -0
- package/src/prompts/default.ts +144 -0
- package/src/prompts/index.ts +16 -0
- package/src/prompts/plan.ts +64 -0
- package/src/prompts/test.ts +78 -0
- package/src/services/AnthropicChatService.ts +341 -0
- package/src/services/ChatService.ts +347 -0
- package/src/services/ClaudeCliChatService.ts +256 -0
- package/src/services/CloudSync.ts +168 -0
- package/src/services/CostLedger.ts +211 -0
- package/src/services/Heartbeat.ts +135 -0
- package/src/services/LearningCollector.ts +291 -0
- package/src/services/OllamaInstaller.ts +342 -0
- package/src/services/VersionChecker.ts +445 -0
- package/src/services/index.ts +57 -0
- package/src/services/streaming/OpenAIEventAdapter.ts +126 -0
- package/src/services/streaming/RenderingProfile.ts +90 -0
- package/src/services/streaming/StreamEventParser.ts +181 -0
- package/src/services/streaming/ThrottledRenderer.ts +139 -0
- package/src/services/streaming/TranscriptBuffer.ts +574 -0
- package/src/services/streaming/eventStatusMap.ts +52 -0
- package/src/services/streaming/index.ts +46 -0
- package/src/services/streaming/renderFormatting.ts +79 -0
- package/src/services/streaming/types.ts +234 -0
- package/src/skills/SkillLoader.ts +126 -0
- package/src/skills/SkillRegistry.ts +366 -0
- package/src/skills/index.ts +48 -0
- package/src/skills/types.ts +146 -0
- package/src/slash-commands/billing.ts +70 -0
- package/src/slash-commands/build.ts +413 -0
- package/src/slash-commands/builtinCommands.ts +2733 -0
- package/src/slash-commands/clone.ts +242 -0
- package/src/slash-commands/council.ts +125 -0
- package/src/slash-commands/custom/CustomCommandExecutor.ts +143 -0
- package/src/slash-commands/custom/CustomCommandLoader.ts +251 -0
- package/src/slash-commands/custom/CustomCommandRegistry.ts +144 -0
- package/src/slash-commands/custom/index.ts +7 -0
- package/src/slash-commands/debate.ts +254 -0
- package/src/slash-commands/gmail.ts +105 -0
- package/src/slash-commands/index.ts +388 -0
- package/src/slash-commands/mcpCommand.ts +205 -0
- package/src/slash-commands/types.ts +201 -0
- package/src/store/index.ts +76 -0
- package/src/store/selectors.ts +246 -0
- package/src/store/slices/appSlice.ts +205 -0
- package/src/store/slices/commandSlice.ts +115 -0
- package/src/store/slices/configSlice.ts +46 -0
- package/src/store/slices/focusSlice.ts +64 -0
- package/src/store/slices/index.ts +9 -0
- package/src/store/slices/sessionSlice.ts +424 -0
- package/src/store/streaming-buffer.ts +425 -0
- package/src/store/test.ts +296 -0
- package/src/store/types.ts +274 -0
- package/src/store/vanilla.ts +186 -0
- package/src/tools/builtin/bash.ts +236 -0
- package/src/tools/builtin/council.ts +105 -0
- package/src/tools/builtin/edit.ts +213 -0
- package/src/tools/builtin/glob.ts +136 -0
- package/src/tools/builtin/grep.ts +263 -0
- package/src/tools/builtin/index.ts +61 -0
- package/src/tools/builtin/memory.ts +66 -0
- package/src/tools/builtin/read.ts +168 -0
- package/src/tools/builtin/skill.ts +97 -0
- package/src/tools/builtin/snapshot.ts +40 -0
- package/src/tools/builtin/task.ts +106 -0
- package/src/tools/builtin/write.ts +134 -0
- package/src/tools/createTool.ts +221 -0
- package/src/tools/execution/ExecutionPipeline.ts +263 -0
- package/src/tools/execution/index.ts +40 -0
- package/src/tools/execution/stages/CacheStage.ts +131 -0
- package/src/tools/execution/stages/ConfirmationStage.ts +203 -0
- package/src/tools/execution/stages/DiscoveryStage.ts +46 -0
- package/src/tools/execution/stages/ExecutionStage.ts +48 -0
- package/src/tools/execution/stages/FormattingStage.ts +44 -0
- package/src/tools/execution/stages/HookStage.ts +72 -0
- package/src/tools/execution/stages/PermissionStage.ts +287 -0
- package/src/tools/execution/stages/PostHookStage.ts +71 -0
- package/src/tools/execution/stages/index.ts +12 -0
- package/src/tools/execution/test.ts +266 -0
- package/src/tools/execution/types.ts +273 -0
- package/src/tools/index.ts +81 -0
- package/src/tools/registry.ts +304 -0
- package/src/tools/schemas.ts +109 -0
- package/src/tools/test.ts +220 -0
- package/src/tools/types.ts +175 -0
- package/src/tools/validation/PermissionChecker.ts +242 -0
- package/src/tools/validation/SensitiveFileDetector.ts +210 -0
- package/src/tools/validation/index.ts +11 -0
- package/src/ui/App.tsx +166 -0
- package/src/ui/components/AegisInterface.tsx +484 -0
- package/src/ui/components/common/ChatSearch.tsx +150 -0
- package/src/ui/components/common/ErrorBoundary.tsx +82 -0
- package/src/ui/components/common/ExitMessage.tsx +120 -0
- package/src/ui/components/common/LoadingIndicator.tsx +49 -0
- package/src/ui/components/common/index.ts +6 -0
- package/src/ui/components/dialog/ConfirmationPrompt.tsx +208 -0
- package/src/ui/components/dialog/InteractiveSelector.tsx +149 -0
- package/src/ui/components/dialog/SetupWizard.tsx +297 -0
- package/src/ui/components/dialog/UpdatePrompt.tsx +155 -0
- package/src/ui/components/dialog/index.ts +8 -0
- package/src/ui/components/index.ts +28 -0
- package/src/ui/components/input/CommandSuggestions.tsx +139 -0
- package/src/ui/components/input/CustomTextInput.tsx +220 -0
- package/src/ui/components/input/InputArea.tsx +361 -0
- package/src/ui/components/input/PromptSuggestions.tsx +66 -0
- package/src/ui/components/input/index.ts +6 -0
- package/src/ui/components/layout/ChatStatusBar.tsx +90 -0
- package/src/ui/components/layout/ContextBar.tsx +79 -0
- package/src/ui/components/layout/MessageArea.tsx +96 -0
- package/src/ui/components/layout/MessageList.tsx +647 -0
- package/src/ui/components/layout/MessageSeparator.tsx +26 -0
- package/src/ui/components/layout/WelcomeMessage.tsx +93 -0
- package/src/ui/components/layout/index.ts +7 -0
- package/src/ui/components/markdown/CodeHighlighter.tsx +292 -0
- package/src/ui/components/markdown/MessageRenderer.tsx +1211 -0
- package/src/ui/components/markdown/index.ts +8 -0
- package/src/ui/components/markdown/parser.ts +336 -0
- package/src/ui/components/markdown/types.ts +66 -0
- package/src/ui/focus/FocusManager.ts +137 -0
- package/src/ui/focus/index.ts +13 -0
- package/src/ui/focus/types.ts +54 -0
- package/src/ui/focus/useFocus.ts +75 -0
- package/src/ui/hooks/index.ts +11 -0
- package/src/ui/hooks/useAgent.ts +284 -0
- package/src/ui/hooks/useCommandHistory.ts +87 -0
- package/src/ui/hooks/useCommandProcessor.ts +443 -0
- package/src/ui/hooks/useConfirmation.ts +99 -0
- package/src/ui/hooks/useCtrlCHandler.ts +100 -0
- package/src/ui/hooks/useInputBuffer.ts +122 -0
- package/src/ui/hooks/useTerminalSize.ts +68 -0
- package/src/ui/hooks/useTerminalWidth.ts +5 -0
- package/src/ui/hooks/useWindowedList.ts +118 -0
- package/src/ui/render-debugger.ts +621 -0
- package/src/ui/test.ts +189 -0
- package/src/ui/themes/ThemeManager.ts +332 -0
- package/src/ui/themes/aegisTheme.ts +87 -0
- package/src/ui/themes/darkTheme.ts +87 -0
- package/src/ui/themes/defaultTheme.ts +85 -0
- package/src/ui/themes/index.ts +10 -0
- package/src/ui/themes/lightTheme.ts +89 -0
- package/src/ui/themes/popularThemes.ts +187 -0
- package/src/ui/themes/types.ts +130 -0
- package/src/utils/clipboard.ts +48 -0
- package/src/utils/debug.ts +43 -0
- package/src/utils/environment.ts +68 -0
- package/src/utils/index.ts +10 -0
|
@@ -0,0 +1,397 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
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
|
+
}
|