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.
Files changed (206) hide show
  1. package/README.md +23 -15
  2. package/dist/main.js +549 -552
  3. package/package.json +4 -2
  4. package/src/agent/Agent.ts +903 -0
  5. package/src/agent/SimpleAgent.ts +48 -0
  6. package/src/agent/index.ts +54 -0
  7. package/src/agent/orchestrator/AppBuilder.ts +443 -0
  8. package/src/agent/orchestrator/CouncilAgent.ts +310 -0
  9. package/src/agent/orchestrator/DiscussionRoom.ts +462 -0
  10. package/src/agent/orchestrator/OrchestratorAgent.ts +637 -0
  11. package/src/agent/orchestrator/index.ts +38 -0
  12. package/src/agent/orchestrator/utils.ts +397 -0
  13. package/src/agent/pricing.ts +115 -0
  14. package/src/agent/router.ts +74 -0
  15. package/src/agent/routerStats.ts +121 -0
  16. package/src/agent/types.ts +318 -0
  17. package/src/auth/login.ts +383 -0
  18. package/src/cli/config.ts +189 -0
  19. package/src/cli/index.ts +17 -0
  20. package/src/cli/middleware.ts +119 -0
  21. package/src/cli/types.ts +75 -0
  22. package/src/config/ConfigManager.ts +587 -0
  23. package/src/config/index.ts +7 -0
  24. package/src/config/types.ts +584 -0
  25. package/src/context/CompactionService.ts +300 -0
  26. package/src/context/ContextManager.ts +450 -0
  27. package/src/context/FileAnalyzer.ts +267 -0
  28. package/src/context/TokenCounter.ts +265 -0
  29. package/src/context/index.ts +27 -0
  30. package/src/context/storage/CacheStore.ts +176 -0
  31. package/src/context/storage/JSONLStore.ts +201 -0
  32. package/src/context/storage/MemoryStore.ts +205 -0
  33. package/src/context/storage/PersistentStore.ts +327 -0
  34. package/src/context/storage/index.ts +9 -0
  35. package/src/context/storage/pathUtils.ts +114 -0
  36. package/src/context/test.ts +309 -0
  37. package/src/context/types.ts +268 -0
  38. package/src/hooks/HookExecutor.ts +434 -0
  39. package/src/hooks/HookManager.ts +596 -0
  40. package/src/hooks/HookService.ts +269 -0
  41. package/src/hooks/Matcher.ts +157 -0
  42. package/src/hooks/index.ts +63 -0
  43. package/src/hooks/types.ts +424 -0
  44. package/src/main.tsx +596 -0
  45. package/src/mcp/HealthMonitor.ts +150 -0
  46. package/src/mcp/McpClient.ts +491 -0
  47. package/src/mcp/McpRegistry.ts +321 -0
  48. package/src/mcp/createMcpTool.ts +251 -0
  49. package/src/mcp/index.ts +15 -0
  50. package/src/mcp/server.ts +334 -0
  51. package/src/mcp/test-server.ts +88 -0
  52. package/src/mcp/test.ts +372 -0
  53. package/src/mcp/types.ts +247 -0
  54. package/src/memory/AgentMemoryBus.ts +432 -0
  55. package/src/memory/CloudSync.ts +99 -0
  56. package/src/memory/DriveSync.ts +106 -0
  57. package/src/memory/SharedMemory.ts +951 -0
  58. package/src/memory/index.ts +14 -0
  59. package/src/memory/machineFingerprint.ts +40 -0
  60. package/src/orchestrator/SubAgentMetadata.ts +136 -0
  61. package/src/prompts/builder.ts +213 -0
  62. package/src/prompts/default.ts +144 -0
  63. package/src/prompts/index.ts +16 -0
  64. package/src/prompts/plan.ts +64 -0
  65. package/src/prompts/test.ts +78 -0
  66. package/src/services/AnthropicChatService.ts +341 -0
  67. package/src/services/ChatService.ts +347 -0
  68. package/src/services/ClaudeCliChatService.ts +256 -0
  69. package/src/services/CloudSync.ts +168 -0
  70. package/src/services/CostLedger.ts +211 -0
  71. package/src/services/Heartbeat.ts +135 -0
  72. package/src/services/LearningCollector.ts +291 -0
  73. package/src/services/OllamaInstaller.ts +342 -0
  74. package/src/services/VersionChecker.ts +445 -0
  75. package/src/services/index.ts +57 -0
  76. package/src/services/streaming/OpenAIEventAdapter.ts +126 -0
  77. package/src/services/streaming/RenderingProfile.ts +90 -0
  78. package/src/services/streaming/StreamEventParser.ts +181 -0
  79. package/src/services/streaming/ThrottledRenderer.ts +139 -0
  80. package/src/services/streaming/TranscriptBuffer.ts +574 -0
  81. package/src/services/streaming/eventStatusMap.ts +52 -0
  82. package/src/services/streaming/index.ts +46 -0
  83. package/src/services/streaming/renderFormatting.ts +79 -0
  84. package/src/services/streaming/types.ts +234 -0
  85. package/src/skills/SkillLoader.ts +126 -0
  86. package/src/skills/SkillRegistry.ts +366 -0
  87. package/src/skills/index.ts +48 -0
  88. package/src/skills/types.ts +146 -0
  89. package/src/slash-commands/billing.ts +70 -0
  90. package/src/slash-commands/build.ts +413 -0
  91. package/src/slash-commands/builtinCommands.ts +2733 -0
  92. package/src/slash-commands/clone.ts +242 -0
  93. package/src/slash-commands/council.ts +125 -0
  94. package/src/slash-commands/custom/CustomCommandExecutor.ts +143 -0
  95. package/src/slash-commands/custom/CustomCommandLoader.ts +251 -0
  96. package/src/slash-commands/custom/CustomCommandRegistry.ts +144 -0
  97. package/src/slash-commands/custom/index.ts +7 -0
  98. package/src/slash-commands/debate.ts +254 -0
  99. package/src/slash-commands/gmail.ts +105 -0
  100. package/src/slash-commands/index.ts +388 -0
  101. package/src/slash-commands/mcpCommand.ts +205 -0
  102. package/src/slash-commands/types.ts +201 -0
  103. package/src/store/index.ts +76 -0
  104. package/src/store/selectors.ts +246 -0
  105. package/src/store/slices/appSlice.ts +205 -0
  106. package/src/store/slices/commandSlice.ts +115 -0
  107. package/src/store/slices/configSlice.ts +46 -0
  108. package/src/store/slices/focusSlice.ts +64 -0
  109. package/src/store/slices/index.ts +9 -0
  110. package/src/store/slices/sessionSlice.ts +424 -0
  111. package/src/store/streaming-buffer.ts +425 -0
  112. package/src/store/test.ts +296 -0
  113. package/src/store/types.ts +274 -0
  114. package/src/store/vanilla.ts +186 -0
  115. package/src/tools/builtin/bash.ts +236 -0
  116. package/src/tools/builtin/council.ts +105 -0
  117. package/src/tools/builtin/edit.ts +213 -0
  118. package/src/tools/builtin/glob.ts +136 -0
  119. package/src/tools/builtin/grep.ts +263 -0
  120. package/src/tools/builtin/index.ts +61 -0
  121. package/src/tools/builtin/memory.ts +66 -0
  122. package/src/tools/builtin/read.ts +168 -0
  123. package/src/tools/builtin/skill.ts +97 -0
  124. package/src/tools/builtin/snapshot.ts +40 -0
  125. package/src/tools/builtin/task.ts +106 -0
  126. package/src/tools/builtin/write.ts +134 -0
  127. package/src/tools/createTool.ts +221 -0
  128. package/src/tools/execution/ExecutionPipeline.ts +263 -0
  129. package/src/tools/execution/index.ts +40 -0
  130. package/src/tools/execution/stages/CacheStage.ts +131 -0
  131. package/src/tools/execution/stages/ConfirmationStage.ts +203 -0
  132. package/src/tools/execution/stages/DiscoveryStage.ts +46 -0
  133. package/src/tools/execution/stages/ExecutionStage.ts +48 -0
  134. package/src/tools/execution/stages/FormattingStage.ts +44 -0
  135. package/src/tools/execution/stages/HookStage.ts +72 -0
  136. package/src/tools/execution/stages/PermissionStage.ts +287 -0
  137. package/src/tools/execution/stages/PostHookStage.ts +71 -0
  138. package/src/tools/execution/stages/index.ts +12 -0
  139. package/src/tools/execution/test.ts +266 -0
  140. package/src/tools/execution/types.ts +273 -0
  141. package/src/tools/index.ts +81 -0
  142. package/src/tools/registry.ts +304 -0
  143. package/src/tools/schemas.ts +109 -0
  144. package/src/tools/test.ts +220 -0
  145. package/src/tools/types.ts +175 -0
  146. package/src/tools/validation/PermissionChecker.ts +242 -0
  147. package/src/tools/validation/SensitiveFileDetector.ts +210 -0
  148. package/src/tools/validation/index.ts +11 -0
  149. package/src/ui/App.tsx +166 -0
  150. package/src/ui/components/AegisInterface.tsx +484 -0
  151. package/src/ui/components/common/ChatSearch.tsx +150 -0
  152. package/src/ui/components/common/ErrorBoundary.tsx +82 -0
  153. package/src/ui/components/common/ExitMessage.tsx +120 -0
  154. package/src/ui/components/common/LoadingIndicator.tsx +49 -0
  155. package/src/ui/components/common/index.ts +6 -0
  156. package/src/ui/components/dialog/ConfirmationPrompt.tsx +208 -0
  157. package/src/ui/components/dialog/InteractiveSelector.tsx +149 -0
  158. package/src/ui/components/dialog/SetupWizard.tsx +297 -0
  159. package/src/ui/components/dialog/UpdatePrompt.tsx +155 -0
  160. package/src/ui/components/dialog/index.ts +8 -0
  161. package/src/ui/components/index.ts +28 -0
  162. package/src/ui/components/input/CommandSuggestions.tsx +139 -0
  163. package/src/ui/components/input/CustomTextInput.tsx +220 -0
  164. package/src/ui/components/input/InputArea.tsx +361 -0
  165. package/src/ui/components/input/PromptSuggestions.tsx +66 -0
  166. package/src/ui/components/input/index.ts +6 -0
  167. package/src/ui/components/layout/ChatStatusBar.tsx +90 -0
  168. package/src/ui/components/layout/ContextBar.tsx +79 -0
  169. package/src/ui/components/layout/MessageArea.tsx +96 -0
  170. package/src/ui/components/layout/MessageList.tsx +647 -0
  171. package/src/ui/components/layout/MessageSeparator.tsx +26 -0
  172. package/src/ui/components/layout/WelcomeMessage.tsx +93 -0
  173. package/src/ui/components/layout/index.ts +7 -0
  174. package/src/ui/components/markdown/CodeHighlighter.tsx +292 -0
  175. package/src/ui/components/markdown/MessageRenderer.tsx +1211 -0
  176. package/src/ui/components/markdown/index.ts +8 -0
  177. package/src/ui/components/markdown/parser.ts +336 -0
  178. package/src/ui/components/markdown/types.ts +66 -0
  179. package/src/ui/focus/FocusManager.ts +137 -0
  180. package/src/ui/focus/index.ts +13 -0
  181. package/src/ui/focus/types.ts +54 -0
  182. package/src/ui/focus/useFocus.ts +75 -0
  183. package/src/ui/hooks/index.ts +11 -0
  184. package/src/ui/hooks/useAgent.ts +284 -0
  185. package/src/ui/hooks/useCommandHistory.ts +87 -0
  186. package/src/ui/hooks/useCommandProcessor.ts +443 -0
  187. package/src/ui/hooks/useConfirmation.ts +99 -0
  188. package/src/ui/hooks/useCtrlCHandler.ts +100 -0
  189. package/src/ui/hooks/useInputBuffer.ts +122 -0
  190. package/src/ui/hooks/useTerminalSize.ts +68 -0
  191. package/src/ui/hooks/useTerminalWidth.ts +5 -0
  192. package/src/ui/hooks/useWindowedList.ts +118 -0
  193. package/src/ui/render-debugger.ts +621 -0
  194. package/src/ui/test.ts +189 -0
  195. package/src/ui/themes/ThemeManager.ts +332 -0
  196. package/src/ui/themes/aegisTheme.ts +87 -0
  197. package/src/ui/themes/darkTheme.ts +87 -0
  198. package/src/ui/themes/defaultTheme.ts +85 -0
  199. package/src/ui/themes/index.ts +10 -0
  200. package/src/ui/themes/lightTheme.ts +89 -0
  201. package/src/ui/themes/popularThemes.ts +187 -0
  202. package/src/ui/themes/types.ts +130 -0
  203. package/src/utils/clipboard.ts +48 -0
  204. package/src/utils/debug.ts +43 -0
  205. package/src/utils/environment.ts +68 -0
  206. package/src/utils/index.ts +10 -0
@@ -0,0 +1,242 @@
1
+ /**
2
+ * /clone — Clone any website via DeepSeek API
3
+ *
4
+ * Fetches a URL's HTML, sends it to DeepSeek for analysis,
5
+ * and recreates it as a local project you can customize.
6
+ *
7
+ * Usage:
8
+ * /clone https://example.com
9
+ * /clone https://example.com --name my-project
10
+ */
11
+
12
+ import type { SlashCommand, SlashCommandResult, SlashCommandContext } from './types.js';
13
+ import { createChatService } from '../services/ChatService.js';
14
+
15
+ const C = {
16
+ cyan: '\x1b[38;2;0;229;192m',
17
+ purple: '\x1b[38;2;124;111;212m',
18
+ green: '\x1b[38;2;34;197;94m',
19
+ red: '\x1b[38;2;239;68;68m',
20
+ muted: '\x1b[38;2;68;64;90m',
21
+ bold: '\x1b[1m',
22
+ reset: '\x1b[0m',
23
+ };
24
+
25
+ interface CloneOptions {
26
+ url: string;
27
+ name?: string;
28
+ }
29
+
30
+ function parseArgs(args: string): CloneOptions {
31
+ const parts = args.trim().split(/\s+/);
32
+ let url = '';
33
+ let name = '';
34
+
35
+ for (let i = 0; i < parts.length; i++) {
36
+ if (parts[i] === '--name' && i + 1 < parts.length) {
37
+ name = parts[++i];
38
+ } else if (!url) {
39
+ url = parts[i];
40
+ }
41
+ }
42
+
43
+ return { url, name };
44
+ }
45
+
46
+ async function fetchHtml(url: string): Promise<string> {
47
+ const { execSync } = await import('node:child_process');
48
+
49
+ // Use curl with a realistic User-Agent to get the actual page content
50
+ const cmd = [
51
+ 'curl',
52
+ '-s', // silent
53
+ '-L', // follow redirects
54
+ '--max-time', '15', // timeout after 15s
55
+ '--connect-timeout', '10',
56
+ '-H', `'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'`,
57
+ '-H', `'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'`,
58
+ `'${url}'`,
59
+ ].join(' ');
60
+
61
+ try {
62
+ const html = execSync(cmd, { encoding: 'utf-8', maxBuffer: 5 * 1024 * 1024 });
63
+ // Truncate very large pages to avoid token limits
64
+ return html.length > 80000 ? html.slice(0, 80000) + '\n<!-- [truncated] -->' : html;
65
+ } catch (e: any) {
66
+ throw new Error(`Failed to fetch ${url}: ${e.stderr?.toString() || e.message}`);
67
+ }
68
+ }
69
+
70
+ function pickDeepSeekModel(): { apiKey: string; baseURL: string; model: string } | null {
71
+ if (process.env.DEEPSEEK_API_KEY) {
72
+ return {
73
+ apiKey: process.env.DEEPSEEK_API_KEY,
74
+ baseURL: 'https://api.deepseek.com/v1',
75
+ model: 'deepseek-chat',
76
+ };
77
+ }
78
+ return null;
79
+ }
80
+
81
+ const CLONE_SYSTEM_PROMPT = `You are a senior web developer. Your job is to analyze HTML from a reference website and recreate it as a customizable local project.
82
+
83
+ Rules:
84
+ 1. Create a complete, self-contained HTML page that captures the visual structure, layout, and design of the reference
85
+ 2. Replace all brand-specific content with placeholder text (change company name, use "My Site" / "Your Brand")
86
+ 3. Replace all external URLs (images, links, APIs) with relative paths or placeholders
87
+ 4. Inline all CSS in a <style> tag — no external stylesheets
88
+ 5. Make the page responsive (mobile-friendly)
89
+ 6. Add a comment at the top showing the original source URL
90
+ 7. Output ONLY valid HTML — no explanations, no markdown
91
+
92
+ The output must be a single HTML file that works when opened in a browser.`;
93
+
94
+ async function cloneSite(opts: CloneOptions, output: (s: string) => void): Promise<string> {
95
+ const html = await fetchHtml(opts.url);
96
+
97
+ const ds = pickDeepSeekModel();
98
+ if (!ds) {
99
+ throw new Error(
100
+ 'DeepSeek API key not found.\n' +
101
+ 'Set DEEPSEEK_API_KEY in ~/.aegiscode/.env or as an environment variable.\n' +
102
+ 'Get a key at: https://platform.deepseek.com/'
103
+ );
104
+ }
105
+
106
+ const chat = createChatService({
107
+ apiKey: ds.apiKey,
108
+ baseURL: ds.baseURL,
109
+ model: ds.model,
110
+ timeout: 120_000,
111
+ });
112
+
113
+ output(`${C.muted} Analyzing ${opts.url} (${(html.length / 1024).toFixed(1)}KB HTML)${C.reset}\n`);
114
+ output(`${C.muted} Using DeepSeek to recreate…${C.reset}\n`);
115
+
116
+ const response = await chat.chat([
117
+ { role: 'system', content: CLONE_SYSTEM_PROMPT },
118
+ { role: 'user', content: `Here is the HTML of the reference website from ${opts.url}:\n\n\`\`\`html\n${html}\n\`\`\`\n\nRecreate this page as described. Output ONLY the HTML.` },
119
+ ]);
120
+
121
+ // Extract HTML from response (strip markdown fences if any)
122
+ let resultHtml = response.content.trim();
123
+ resultHtml = resultHtml.replace(/^```(?:html)?\n?/i, '').replace(/\n?```$/i, '').trim();
124
+
125
+ if (!resultHtml) {
126
+ throw new Error('DeepSeek returned empty response');
127
+ }
128
+
129
+ return resultHtml;
130
+ }
131
+
132
+ export const cloneCommand: SlashCommand = {
133
+ name: 'clone',
134
+ aliases: ['fetch-site', 'websnap'],
135
+ description: 'Clone any website using DeepSeek — /clone <url> [--name <project>]',
136
+ category: 'skills',
137
+ usage: '/clone <url> [--name <project-name>]',
138
+ examples: [
139
+ '/clone https://example.com',
140
+ '/clone https://example.com --name my-landing',
141
+ '/clone https://tailwindcss.com --name tailwind-clone',
142
+ ],
143
+ fullDescription: `Website cloner powered by DeepSeek.
144
+
145
+ Fetches a URL's HTML, sends it to DeepSeek for analysis,
146
+ and recreates it as a local HTML file you can customize.
147
+
148
+ The cloned page:
149
+ - Replaces brand content with placeholders
150
+ - Inlines all CSS
151
+ - Makes it responsive
152
+ - Works standalone in a browser
153
+
154
+ Requires DEEPSEEK_API_KEY in your environment.`,
155
+
156
+ async handler(args: string, context: SlashCommandContext): Promise<SlashCommandResult> {
157
+ const opts = parseArgs(args);
158
+ if (!opts.url) {
159
+ return {
160
+ success: false,
161
+ type: 'error',
162
+ error: 'Usage: /clone <url> [--name <project-name>]\n' +
163
+ 'Example: /clone https://example.com --name my-landing',
164
+ };
165
+ }
166
+
167
+ // Validate URL
168
+ try {
169
+ new URL(opts.url);
170
+ } catch {
171
+ return { success: false, type: 'error', error: `Invalid URL: ${opts.url}` };
172
+ }
173
+
174
+ const cwd = context.cwd || process.cwd();
175
+ const projectName = opts.name || opts.url.replace(/https?:\/\//, '').replace(/\/$/, '').replace(/[^a-zA-Z0-9_-]/g, '-');
176
+ const outputDir = `${cwd}/${projectName}`;
177
+
178
+ const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, '');
179
+ const log = (s: string) => {
180
+ if (context.onContentDelta) {
181
+ context.onContentDelta(stripAnsi(s) + '\n');
182
+ } else {
183
+ process.stdout.write(s + '\n');
184
+ }
185
+ };
186
+
187
+ log(`\n${C.cyan}${C.bold}⬡ CLONE${C.reset}`);
188
+ log(`${C.muted} Source: ${opts.url}${C.reset}`);
189
+ log(`${C.muted} Output: ${projectName}/${C.reset}\n`);
190
+
191
+ try {
192
+ const fs = await import('node:fs');
193
+ const path = await import('node:path');
194
+
195
+ // Create output directory
196
+ fs.mkdirSync(outputDir, { recursive: true });
197
+
198
+ // Clone the site
199
+ const html = await cloneSite(opts, log);
200
+
201
+ // Write the HTML file
202
+ const outputFile = path.join(outputDir, 'index.html');
203
+ fs.writeFileSync(outputFile, html, 'utf-8');
204
+
205
+ // Write a simple README
206
+ const readme = `# ${projectName}
207
+
208
+ Website cloned from [${opts.url}](${opts.url}) using AEGIS Code + DeepSeek.
209
+
210
+ ## Files
211
+
212
+ - \`index.html\` — Cloned website (standalone, open in browser)
213
+
214
+ ## Customize
215
+
216
+ Edit \`index.html\` to replace placeholder content with your own.
217
+ `;
218
+ fs.writeFileSync(path.join(outputDir, 'README.md'), readme, 'utf-8');
219
+
220
+ const filesize = (html.length / 1024).toFixed(1);
221
+
222
+ log(`\n${C.green}✓${C.reset} Created ${C.cyan}${projectName}/index.html${C.reset} (${filesize}KB)`);
223
+ log(`${C.muted} ${outputFile}${C.reset}`);
224
+ log(`\n${C.bold}Done!${C.reset} Open index.html in your browser or edit it to make it yours.`);
225
+
226
+ // Save a session note
227
+ const note = `[clone] Created ${projectName}/ — cloned from ${opts.url}`;
228
+ try {
229
+ const sessionFile = path.join(outputDir, '.aegis-clone');
230
+ fs.writeFileSync(sessionFile, JSON.stringify({ source: opts.url, clonedAt: new Date().toISOString(), project: projectName }, null, 2), 'utf-8');
231
+ } catch {}
232
+
233
+ return { success: true, type: 'silent' };
234
+ } catch (error: any) {
235
+ return {
236
+ success: false,
237
+ type: 'error',
238
+ error: `Clone failed: ${error.message}`,
239
+ };
240
+ }
241
+ },
242
+ };
@@ -0,0 +1,125 @@
1
+ /**
2
+ * /council — AEGIS Council Vote
3
+ * Three AI agents deliberate and vote via API directly
4
+ */
5
+
6
+ const C = {
7
+ teal: '\x1b[38;2;0;229;192m',
8
+ purple: '\x1b[38;2;124;111;212m',
9
+ pink: '\x1b[38;2;244;114;182m',
10
+ orange: '\x1b[38;2;249;115;22m',
11
+ green: '\x1b[38;2;34;197;94m',
12
+ red: '\x1b[38;2;239;68;68m',
13
+ muted: '\x1b[38;2;68;64;90m',
14
+ bold: '\x1b[1m',
15
+ reset: '\x1b[0m',
16
+ };
17
+
18
+ interface Agent {
19
+ name: string;
20
+ role: string;
21
+ color: string;
22
+ call: (question: string) => Promise<{ vote: string; analysis: string }>;
23
+ }
24
+
25
+ async function callOpenAICompatible(baseUrl: string, apiKey: string, model: string, question: string, persona: string): Promise<{ vote: string; analysis: string }> {
26
+ const res = await fetch(`${baseUrl}/chat/completions`, {
27
+ method: 'POST',
28
+ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
29
+ body: JSON.stringify({
30
+ model,
31
+ max_tokens: 300,
32
+ messages: [{
33
+ role: 'user',
34
+ content: `You are ${persona} in the AEGIS Council. The question is:\n\n"${question}"\n\nRespond with:\nVOTE: JA or NEJ\nANALYSIS: 1-2 sentences explaining your reasoning.`,
35
+ }],
36
+ }),
37
+ });
38
+ const data = await res.json() as any;
39
+ const text = data.choices?.[0]?.message?.content || '';
40
+ const vote = text.includes('VOTE: JA') ? 'JA' : text.includes('VOTE: NEJ') ? 'NEJ' : 'AVSTÅR';
41
+ const analysis = text.split('ANALYSIS:')[1]?.trim().slice(0, 200) || text.slice(0, 200);
42
+ return { vote, analysis };
43
+ }
44
+
45
+ function pickProvider(): { baseUrl: string; apiKey: string; model: string } {
46
+ if (process.env.OPENAI_API_KEY && process.env.OPENAI_BASE_URL)
47
+ return { baseUrl: process.env.OPENAI_BASE_URL, apiKey: process.env.OPENAI_API_KEY, model: process.env.OPENAI_MODEL || 'gpt-4o' };
48
+ if (process.env.DEEPSEEK_API_KEY)
49
+ return { baseUrl: 'https://api.deepseek.com/v1', apiKey: process.env.DEEPSEEK_API_KEY, model: 'deepseek-chat' };
50
+ if (process.env.GROQ_API_KEY)
51
+ return { baseUrl: 'https://api.groq.com/openai/v1', apiKey: process.env.GROQ_API_KEY, model: 'llama-3.3-70b-versatile' };
52
+ if (process.env.OPENAI_API_KEY)
53
+ return { baseUrl: 'https://api.openai.com/v1', apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o' };
54
+ throw new Error('No API key configured. Set OPENAI_API_KEY, DEEPSEEK_API_KEY, or GROQ_API_KEY in ~/.aegiscode/.env');
55
+ }
56
+
57
+ let _provider: ReturnType<typeof pickProvider> | null = null;
58
+ function callPrimary(q: string, p: string) { if (!_provider) _provider = pickProvider(); return callOpenAICompatible(_provider.baseUrl, _provider.apiKey, _provider.model, q, p); }
59
+ function callDeepSeek(q: string, p: string) { return callOpenAICompatible('https://api.deepseek.com/v1', process.env.DEEPSEEK_API_KEY || '', 'deepseek-chat', q, p); }
60
+ function callGroq(q: string, p: string) { return callOpenAICompatible('https://api.groq.com/openai/v1', process.env.GROQ_API_KEY || '', 'llama-3.3-70b-versatile', q, p); }
61
+
62
+ const AGENTS: Agent[] = [
63
+ {
64
+ name: 'Claude',
65
+ role: 'Strategic Analyst',
66
+ color: C.teal,
67
+ call: (q) => callPrimary(q, 'a strategic analyst focused on long-term impact and human values'),
68
+ },
69
+ {
70
+ name: 'DeepSeek',
71
+ role: 'Technical Architect',
72
+ color: C.purple,
73
+ call: (q) => callDeepSeek(q, 'a technical architect focused on feasibility and system design'),
74
+ },
75
+ {
76
+ name: 'Llama',
77
+ role: 'Ethics Officer',
78
+ color: C.orange,
79
+ call: (q) => callGroq(q, 'an ethics officer focused on safety, fairness, and societal impact'),
80
+ },
81
+ ];
82
+
83
+ export async function runCouncil(question: string): Promise<string> {
84
+ const results: { name: string; role: string; color: string; vote: string; analysis: string }[] = [];
85
+ const lines: string[] = [];
86
+
87
+ lines.push('## ⬡ AEGIS COUNCIL');
88
+ lines.push(`**Question:** ${question}`);
89
+ lines.push('');
90
+ lines.push('*Agents deliberating...*');
91
+ lines.push('');
92
+
93
+ await Promise.all(AGENTS.map(async (agent) => {
94
+ try {
95
+ const result = await agent.call(question);
96
+ results.push({ name: agent.name, role: agent.role, color: agent.color, ...result });
97
+ } catch (e: any) {
98
+ results.push({ name: agent.name, role: agent.role, color: agent.color, vote: 'OFFLINE', analysis: e.message });
99
+ }
100
+ }));
101
+
102
+ // Rebuild lines with results
103
+ lines.length = 0;
104
+ lines.push('## ⬡ AEGIS COUNCIL');
105
+ lines.push(`**Question:** ${question}`);
106
+ lines.push('');
107
+
108
+ for (const r of results) {
109
+ const voteEmoji = r.vote === 'JA' ? '✅' : r.vote === 'NEJ' ? '❌' : '⚫';
110
+ lines.push(`**${r.name}** · ${r.role}`);
111
+ lines.push(`${voteEmoji} **${r.vote}** — ${r.analysis}`);
112
+ lines.push('');
113
+ }
114
+
115
+ const ja = results.filter(r => r.vote === 'JA').length;
116
+ const nej = results.filter(r => r.vote === 'NEJ').length;
117
+ const approved = ja > nej;
118
+ const verdict = approved ? '✅ GODKÄNT' : '❌ AVSLAGET';
119
+ const summary = `${ja} JA · ${nej} NEJ · ${results.length - ja - nej} AVSTÅR`;
120
+
121
+ lines.push('---');
122
+ lines.push(`${verdict} · ${summary}`);
123
+
124
+ return lines.join('\n');
125
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * CustomCommandExecutor - 自定义命令执行器
3
+ *
4
+ *
5
+ * - 参数插值 ($ARGUMENTS, $1, $2, ...)
6
+ * - Bash 命令嵌入 (!`command`)
7
+ * - 文件引用 (@path/to/file)
8
+ */
9
+
10
+ import { execSync } from 'child_process';
11
+ import * as fs from 'fs';
12
+ import * as path from 'path';
13
+ import type { CustomCommand, CustomCommandExecutionContext } from '../types.js';
14
+
15
+ /**
16
+ *
17
+ */
18
+ export class CustomCommandExecutor {
19
+ /**
20
+ *
21
+ *
22
+ *
23
+ * 1. 参数插值
24
+ * 2. Bash 命令嵌入执行
25
+ * 3. 文件引用替换
26
+ */
27
+ async execute(
28
+ command: CustomCommand,
29
+ context: CustomCommandExecutionContext
30
+ ): Promise<string> {
31
+ let content = command.content;
32
+
33
+ // 1. 参数插
34
+ content = this.interpolateArgs(content, context.args);
35
+
36
+ // 2. Bash 嵌入执
37
+ content = await this.executeBashEmbeds(content, context);
38
+
39
+ // 3. 文件引用替
40
+ content = await this.resolveFileReferences(content, context.workspaceRoot);
41
+
42
+ return content;
43
+ }
44
+
45
+ /**
46
+ *
47
+ *
48
+ *
49
+ * - $ARGUMENTS - 全部参数(空格连接)
50
+ * - $1, $2, ..., $9 - 位置参数
51
+ */
52
+ private interpolateArgs(content: string, args: string[]): string {
53
+ // 替
54
+ content = content.replace(/\$ARGUMENTS/g, args.join(' '));
55
+
56
+ // 替换 $1, $2, ... $9(从大到小避免 $1 匹配 $10 的问
57
+ for (let i = 9; i >= 1; i--) {
58
+ content = content.split(`$${i}`).join(args[i - 1] ?? '');
59
+ }
60
+
61
+ return content;
62
+ }
63
+
64
+ /**
65
+ *
66
+ *
67
+ *
68
+ * - 命令在工作目录执行
69
+ * - 30 秒超时
70
+ * - 失败时显示错误信息
71
+ */
72
+ private async executeBashEmbeds(
73
+ content: string,
74
+ context: CustomCommandExecutionContext
75
+ ): Promise<string> {
76
+ const regex = /!`([^`]+)`/g;
77
+ let result = content;
78
+
79
+ for (const match of content.matchAll(regex)) {
80
+ const command = match[1];
81
+
82
+ try {
83
+ // 检查中断信
84
+ if (context.signal?.aborted) {
85
+ result = result.replace(match[0], '[Aborted]');
86
+ continue;
87
+ }
88
+
89
+ const output = execSync(command, {
90
+ cwd: context.workspaceRoot,
91
+ encoding: 'utf-8',
92
+ timeout: 30000, // 30 秒超
93
+ maxBuffer: 1024 * 1024, // 1MB 输出限
94
+ }).trim();
95
+
96
+ result = result.replace(match[0], output);
97
+ } catch (error) {
98
+ const errorMessage = error instanceof Error ? error.message : String(error);
99
+ result = result.replace(match[0], `[Error: ${errorMessage}]`);
100
+ }
101
+ }
102
+
103
+ return result;
104
+ }
105
+
106
+ /**
107
+ *
108
+ *
109
+ *
110
+ * - 路径相对于工作目录
111
+ * - 自动用代码块包裹文件内容
112
+ * - 文件不存在时保留原文
113
+ */
114
+ private async resolveFileReferences(
115
+ content: string,
116
+ workspaceRoot: string
117
+ ): Promise<string> {
118
+ // 匹
119
+ const regex = /@([\w./-]+(?:\/[\w./-]+|\.[\w]+))/g;
120
+ let result = content;
121
+
122
+ for (const match of content.matchAll(regex)) {
123
+ const relativePath = match[1];
124
+ const filePath = path.resolve(workspaceRoot, relativePath);
125
+
126
+ try {
127
+ const stat = fs.statSync(filePath);
128
+ if (stat.isFile()) {
129
+ const fileContent = fs.readFileSync(filePath, 'utf-8');
130
+ const ext = path.extname(relativePath).slice(1) || 'text';
131
+
132
+ // 用代码块包
133
+ const codeBlock = `\`\`\`${ext}\n${fileContent}\n\`\`\``;
134
+ result = result.replace(match[0], codeBlock);
135
+ }
136
+ } catch {
137
+ // 文件不存在,保留原
138
+ }
139
+ }
140
+
141
+ return result;
142
+ }
143
+ }