aegiscode 3.1.10 → 3.2.0

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-cli-linux-x64 +0 -0
  2. package/bin/cli.js +68 -0
  3. package/package.json +11 -48
  4. package/scripts/download-binary.mjs +155 -0
  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,291 +0,0 @@
1
- /**
2
- * LearningCollector — Collect + push daily AI learnings to aegiscloud.org
3
- *
4
- * Extracts high-value facts, decisions, and solutions from interactions and
5
- * memory entries, then pushes them to the cloud for the daily digest.
6
- *
7
- * The admin panel aggregates learnings from all AEGIS instances (CLI + GUI)
8
- * and produces a daily summary of what "all AEGIS instances learned today."
9
- *
10
- * Pro-tier (logged-in) users contribute to the collective pool.
11
- * Ultimate-tier users can also pull the daily digest.
12
- *
13
- * Fire-and-forget, never blocks. Silently swallows all errors.
14
- */
15
- import * as fs from 'node:fs';
16
- import * as path from 'node:path';
17
- import * as os from 'node:os';
18
- import * as https from 'node:https';
19
-
20
- const HOST = 'aegiscloud.org';
21
- const PUSH_URL = '/api/learnings/push';
22
- const DIGEST_URL = '/api/learnings/daily';
23
- const TIMEOUT_MS = 8000;
24
-
25
- const LAST_DIGEST_FILE = path.join(os.homedir(), '.aegiscode', 'memory', '.last-digest');
26
-
27
- // ── Config helpers ──────────────────────────────────────────────────────────
28
-
29
- function getConfig(): Record<string, any> {
30
- try {
31
- const cfgPath = path.join(os.homedir(), '.aegiscode', 'config.json');
32
- return JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
33
- } catch { return {}; }
34
- }
35
-
36
- function getApiKey(): string | null {
37
- return getConfig()?.aegiscloud?.api_key ?? null;
38
- }
39
-
40
- // ── Types ───────────────────────────────────────────────────────────────────
41
-
42
- export interface Learning {
43
- /** Unique id (uuid) */
44
- id: string;
45
- /** When the learning was extracted */
46
- timestamp: string;
47
- /** The learned fact, decision, or solution text */
48
- content: string;
49
- /** Category: 'fact' | 'decision' | 'solution' | 'insight' | 'pattern' */
50
- category: string;
51
- /** Source client: 'cli' | 'gui' */
52
- client: string;
53
- /** Version of the client that produced this */
54
- version: string;
55
- /** Topics extracted from the content */
56
- topics: string[];
57
- /** Entities (code patterns, file paths, function names, etc.) */
58
- entities: string[];
59
- /** How important 0–1 */
60
- importance: number;
61
- /** Session this came from */
62
- sessionId?: string;
63
- /** Model that was used when this learning was generated */
64
- model?: string;
65
- }
66
-
67
- // ── Category detection ──────────────────────────────────────────────────────
68
-
69
- function detectCategory(content: string): Learning['category'] {
70
- const lower = content.toLowerCase();
71
- if (/decided|decision|chose|elected|going with|pick/i.test(lower)) return 'decision';
72
- if (/solved|fixed|resolved|solution|workaround|patch|bug.*fix/i.test(lower)) return 'solution';
73
- if (/pattern|anti.?pattern|common|always|never|typically/i.test(lower)) return 'pattern';
74
- if (/insight|realized|understood|now know|important/i.test(lower)) return 'insight';
75
- return 'fact';
76
- }
77
-
78
- function extractTopics(content: string): string[] {
79
- const topicMap: Record<string, RegExp> = {
80
- 'coding': /```|function|class|const|let|import|export|interface/i,
81
- 'debugging': /bug|error|fix|issue|crash|broken|not working/i,
82
- 'deployment': /deploy|railway|docker|container|cloud/i,
83
- 'architecture': /architecture|design pattern|scalab|refactor/i,
84
- 'database': /sqlite|postgres|sql|query|mongo/i,
85
- 'frontend': /react|vue|css|html|component|ui|interface/i,
86
- 'backend': /api|endpoint|server|flask|express|route/i,
87
- 'security': /auth|token|password|encrypt|security|vulnerab/i,
88
- 'devops': /ci|cd|github|action|pipeline|monitoring/i,
89
- 'ai-ml': /model|train|embed|vector|llm|token|inference/i,
90
- };
91
- return Object.entries(topicMap)
92
- .filter(([_, re]) => re.test(content))
93
- .map(([topic]) => topic);
94
- }
95
-
96
- function extractEntities(content: string): string[] {
97
- const entities: string[] = [];
98
- const funcMatches = content.match(/(?:function|class|def|const)\s+(\w+)/g);
99
- if (funcMatches) entities.push(...funcMatches.map(m => m.split(/\s+/)[1]));
100
- const fileMatches = content.match(/(?:`[^`]+`)/g);
101
- if (fileMatches) entities.push(...fileMatches.map(m => m.replace(/`/g, '')));
102
- const pkgMatches = content.match(/(?:from\s+|require\s*\(\s*['"])['"]([^'"]+)['"]/g);
103
- if (pkgMatches) entities.push(...pkgMatches.map(m => {
104
- const inner = m.match(/['"]([^'"]+)['"]/);
105
- return inner ? inner[1] : '';
106
- }));
107
- const toolMatches = content.match(/(docker|npm|yarn|git|pip|node|python|react|flask|sqlite|postgres)/gi);
108
- if (toolMatches) entities.push(...toolMatches.map(m => m.toLowerCase()));
109
- return [...new Set(entities)].filter(Boolean).slice(0, 10);
110
- }
111
-
112
- // ── HTTP helper (fire-and-forget POST) ──────────────────────────────────────
113
-
114
- function postJson(path: string, payload: object): Promise<unknown> {
115
- return new Promise((resolve, reject) => {
116
- const body = JSON.stringify(payload);
117
- const req = https.request(
118
- {
119
- hostname: HOST,
120
- path,
121
- method: 'POST',
122
- headers: {
123
- 'Content-Type': 'application/json',
124
- 'Content-Length': Buffer.byteLength(body),
125
- },
126
- },
127
- (res) => {
128
- let data = '';
129
- res.on('data', (chunk: Buffer) => { data += chunk.toString(); });
130
- res.on('end', () => {
131
- try { resolve(JSON.parse(data)); }
132
- catch { resolve(data); }
133
- });
134
- },
135
- );
136
- req.on('error', reject);
137
- req.setTimeout(TIMEOUT_MS, () => { req.destroy(); reject(new Error('timeout')); });
138
- req.write(body);
139
- req.end();
140
- });
141
- }
142
-
143
- // ── Main API ────────────────────────────────────────────────────────────────
144
-
145
- /**
146
- * Extract a Learning from a piece of content (user message or assistant response).
147
- * Returns null if the content isn't important enough to be a "learning".
148
- */
149
- export function extractLearning(
150
- content: string,
151
- role: 'user' | 'assistant',
152
- sessionId?: string,
153
- model?: string,
154
- ): Learning | null {
155
- if (!content || content.length < 30) return null;
156
-
157
- // Only assistant responses with sufficient importance qualify as learnings
158
- // (user messages provide context but aren't learnings themselves)
159
- if (role !== 'assistant') return null;
160
-
161
- // Must contain substantive information
162
- const lower = content.toLowerCase();
163
- const hasSubstance =
164
- /```/g.test(content) || // Code
165
- /(?:is|are|was|were|should|must|can|will)\s+.{20,}/.test(lower) || // Statements
166
- /step[s]?\s+\d|first|second|finally|solution|fix|method|approach/.test(lower); // Process
167
-
168
- if (!hasSubstance) return null;
169
-
170
- // Detect importance heuristically
171
- let importance = 0.5;
172
- if (/\bimportant|key|crucial|critical|essential|must|never|always\b/i.test(content)) importance += 0.15;
173
- if (/\bdecision|conclusion|resolved|solved|fixed\b/i.test(content)) importance += 0.15;
174
- if (content.length > 300) importance += 0.1;
175
-
176
- if (importance < 0.6) return null; // Not interesting enough
177
-
178
- const { v4: uuid } = require('uuid');
179
-
180
- return {
181
- id: uuid(),
182
- timestamp: new Date().toISOString(),
183
- content: content.slice(0, 500),
184
- category: detectCategory(content),
185
- client: process.env.AEGIS_CLIENT_TYPE || 'cli',
186
- version: process.env.npm_package_version || 'unknown',
187
- topics: extractTopics(content),
188
- entities: extractEntities(content),
189
- importance: Math.min(1, importance),
190
- sessionId: sessionId || 'unknown',
191
- model,
192
- };
193
- }
194
-
195
- /**
196
- * Push a batch of learnings to the cloud. Fire-and-forget.
197
- * Returns how many the server accepted.
198
- */
199
- export async function pushLearnings(learnings: Learning[]): Promise<number> {
200
- const apiKey = getApiKey();
201
- if (!apiKey || learnings.length === 0) return 0;
202
-
203
- try {
204
- const result = await postJson(PUSH_URL, { learnings }) as any;
205
- return result?.saved ?? 0;
206
- } catch {
207
- return 0;
208
- }
209
- }
210
-
211
- /**
212
- * Push all learnings from local memory that are new, then mark them as pushed.
213
- * Designed to run at the end of a session or periodically.
214
- */
215
- export async function flushPendingLearnings(
216
- getSentinel: () => string,
217
- setSentinel: (ts: string) => void,
218
- ): Promise<{ total: number; pushed: number }> {
219
- // The caller provides access to its memory entries and passes a sentinel timestamp
220
- // so we only push learnings not yet seen by the cloud.
221
- return { total: 0, pushed: 0 }; // placeholder — real impl reads from SharedMemory
222
- }
223
-
224
- /**
225
- * Pull today's collective digest — what all AEGIS instances learned today.
226
- * Only available to Ultimate-tier users.
227
- *
228
- * Returns a formatted string suitable for display in the UI.
229
- */
230
- export async function fetchDailyDigest(): Promise<string | null> {
231
- const apiKey = getApiKey();
232
- if (!apiKey) return null;
233
-
234
- try {
235
- const result = await postJson(DIGEST_URL, {}) as any;
236
- if (!result?.entries || !Array.isArray(result.entries)) return null;
237
-
238
- const entries = result.entries as Learning[];
239
- if (entries.length === 0) return 'No new learnings today yet.';
240
-
241
- const byCategory: Record<string, Learning[]> = {};
242
- for (const e of entries) {
243
- if (!byCategory[e.category]) byCategory[e.category] = [];
244
- byCategory[e.category].push(e);
245
- }
246
-
247
- const lines: string[] = [
248
- `═══ AEGIS Daily Digest ═══`,
249
- `${entries.length} learnings from ${new Set(entries.map(e => e.sessionId)).size} sessions`,
250
- ``,
251
- ];
252
-
253
- for (const [cat, items] of Object.entries(byCategory)) {
254
- lines.push(`▸ ${cat.toUpperCase()} (${items.length})`);
255
- for (const item of items.slice(0, 5)) {
256
- lines.push(` • ${item.content.slice(0, 120)}`);
257
- if (item.topics.length > 0) lines.push(` [${item.topics.join(', ')}]`);
258
- }
259
- if (items.length > 5) lines.push(` … and ${items.length - 5} more`);
260
- lines.push('');
261
- }
262
-
263
- lines.push('═══ End Digest ═══');
264
- return lines.join('\n');
265
- } catch {
266
- return null;
267
- }
268
- }
269
-
270
- /**
271
- * Check if we've already fetched today's digest.
272
- */
273
- export function hasFetchedToday(): boolean {
274
- try {
275
- if (!fs.existsSync(LAST_DIGEST_FILE)) return false;
276
- const last = fs.readFileSync(LAST_DIGEST_FILE, 'utf8').trim();
277
- const today = new Date().toISOString().slice(0, 10);
278
- return last === today;
279
- } catch { return false; }
280
- }
281
-
282
- /**
283
- * Mark digest as fetched for today.
284
- */
285
- export function markDigestFetched(): void {
286
- try {
287
- const dir = path.dirname(LAST_DIGEST_FILE);
288
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
289
- fs.writeFileSync(LAST_DIGEST_FILE, new Date().toISOString().slice(0, 10));
290
- } catch {}
291
- }
@@ -1,342 +0,0 @@
1
- /**
2
- * OllamaInstaller — auto-install, start, and validate Ollama when a local
3
- * Ollama model is selected.
4
- *
5
- * Flow:
6
- * 1. Detect if baseURL points to a local Ollama instance
7
- * 2. Ensure server is running (install if missing)
8
- * 3. Ensure the requested model is pulled
9
- * 4. Check that the model supports tools — auto-swap to best installed capable model if not
10
- * 5. Return the final model name to use (may differ from the input)
11
- */
12
-
13
- import { execSync, spawn } from 'child_process';
14
- import { platform } from 'os';
15
-
16
- const POLL_INTERVAL_MS = 600;
17
- const START_TIMEOUT_MS = 15_000;
18
- const TOOLS_CAPABLE_FALLBACK = 'llama3.2';
19
-
20
- // Models confirmed to NOT support tools in Ollama.
21
- // llama3.1 / llama3.2 / llama3.3 DO support tools; bare "llama3" does not.
22
- const TOOL_INCAPABLE_PATTERNS = [
23
- /^llama3$/,
24
- /^llama3:latest$/,
25
- /^llama2(:|$)/,
26
- /^codellama(:|$)/,
27
- /^phi[23](:|$)/,
28
- /^gemma(:|$)/,
29
- /^gemma2(:|$)/,
30
- /^orca-mini(:|$)/,
31
- /^vicuna(:|$)/,
32
- ];
33
-
34
- // ── Types ─────────────────────────────────────────────────────────────────────
35
-
36
- export interface OllamaModelInfo {
37
- name: string;
38
- supportsTools: boolean;
39
- sizeGB?: number;
40
- isLoaded: boolean;
41
- }
42
-
43
- // ── Session cache ─────────────────────────────────────────────────────────────
44
- // Keyed by model name. isLoaded is always fetched fresh (changes at runtime);
45
- // supportsTools and sizeGB are stable per model and cached after first fetch.
46
-
47
- const detailsCache = new Map<string, { supportsTools: boolean; sizeGB?: number }>();
48
-
49
- // ── Helpers ──────────────────────────────────────────────────────────────────
50
-
51
- export function isLocalOllamaUrl(baseURL?: string): boolean {
52
- if (!baseURL) return false;
53
- return (
54
- baseURL.includes('localhost:11434') ||
55
- baseURL.includes('127.0.0.1:11434') ||
56
- baseURL.includes('0.0.0.0:11434')
57
- );
58
- }
59
-
60
- // Strip /v1 (OpenAI-compat path) to get the Ollama server root for management APIs
61
- function ollamaRoot(baseURL: string): string {
62
- return baseURL.replace(/\/v1\/?$/, '').replace(/\/+$/, '');
63
- }
64
-
65
- function log(msg: string): void {
66
- process.stderr.write(`\x1b[38;2;83;74;183m[Ollama]\x1b[0m ${msg}\n`);
67
- }
68
-
69
- function nameMatchesBare(installed: string, bare: string): boolean {
70
- return installed === bare || installed.startsWith(bare + ':') || installed === bare + ':latest';
71
- }
72
-
73
- async function isOllamaResponding(baseURL: string): Promise<boolean> {
74
- try {
75
- const ctrl = new AbortController();
76
- const timer = setTimeout(() => ctrl.abort(), 2000);
77
- const res = await fetch(ollamaRoot(baseURL) + '/api/tags', { signal: ctrl.signal });
78
- clearTimeout(timer);
79
- return res.ok;
80
- } catch {
81
- return false;
82
- }
83
- }
84
-
85
- function isBinaryInstalled(): boolean {
86
- try { execSync('which ollama', { stdio: 'ignore' }); return true; } catch {}
87
- try { execSync('ollama --version', { stdio: 'ignore' }); return true; } catch {}
88
- const paths = [
89
- '/usr/local/bin/ollama',
90
- '/usr/bin/ollama',
91
- `${process.env.HOME}/.local/bin/ollama`,
92
- `${process.env.HOME}/bin/ollama`,
93
- ];
94
- for (const p of paths) {
95
- try { execSync(`test -x "${p}"`, { stdio: 'ignore' }); return true; } catch {}
96
- }
97
- return false;
98
- }
99
-
100
- // ── Model info fetchers ───────────────────────────────────────────────────────
101
-
102
- // /api/show — capabilities + disk size. Results cached per model name.
103
- async function fetchModelDetails(base: string, model: string): Promise<{ supportsTools: boolean; sizeGB?: number }> {
104
- const cached = detailsCache.get(model);
105
- if (cached) return cached;
106
-
107
- try {
108
- const res = await fetch(base + '/api/show', {
109
- method: 'POST',
110
- headers: { 'Content-Type': 'application/json' },
111
- body: JSON.stringify({ name: model }),
112
- });
113
- if (res.ok) {
114
- const data = await res.json() as {
115
- capabilities?: string[];
116
- size?: number;
117
- };
118
-
119
- const supportsTools = Array.isArray(data.capabilities)
120
- ? data.capabilities.includes('tools')
121
- : !TOOL_INCAPABLE_PATTERNS.some(re => re.test(model.toLowerCase().replace(/^registry\.ollama\.ai\/library\//, '')));
122
-
123
- const sizeGB = typeof data.size === 'number' && data.size > 0
124
- ? Math.round(data.size / 1e8) / 10 // round to 1 decimal GB
125
- : undefined;
126
-
127
- const result = { supportsTools, sizeGB };
128
- detailsCache.set(model, result);
129
- return result;
130
- }
131
- } catch {}
132
-
133
- // Fallback: name heuristic only
134
- const tag = model.toLowerCase().replace(/^registry\.ollama\.ai\/library\//, '');
135
- const result = { supportsTools: !TOOL_INCAPABLE_PATTERNS.some(re => re.test(tag)) };
136
- detailsCache.set(model, result);
137
- return result;
138
- }
139
-
140
- // /api/tags — all installed models with their disk sizes
141
- async function getInstalledModels(base: string): Promise<{ name: string; size: number }[]> {
142
- try {
143
- const res = await fetch(base + '/api/tags');
144
- if (!res.ok) return [];
145
- const data = await res.json() as { models?: { name: string; size?: number }[] };
146
- return (data.models || []).map(m => ({ name: m.name, size: m.size ?? 0 }));
147
- } catch {
148
- return [];
149
- }
150
- }
151
-
152
- // /api/ps — models currently loaded in memory (respond instantly, no cold-start)
153
- async function getLoadedModels(base: string): Promise<string[]> {
154
- try {
155
- const res = await fetch(base + '/api/ps');
156
- if (!res.ok) return [];
157
- const data = await res.json() as { models?: { name: string }[] };
158
- return (data.models || []).map(m => m.name);
159
- } catch {
160
- return [];
161
- }
162
- }
163
-
164
- // ── Public: enriched model list ───────────────────────────────────────────────
165
-
166
- /**
167
- * Returns enriched info for every model installed in a local Ollama instance.
168
- * Used by the /model selector to show size, tool support, and loaded status.
169
- * Returns [] if baseURL is not a local Ollama URL or the server is not running.
170
- */
171
- export async function getOllamaModels(baseURL?: string): Promise<OllamaModelInfo[]> {
172
- if (!isLocalOllamaUrl(baseURL)) return [];
173
- const base = ollamaRoot(baseURL!);
174
-
175
- if (!await isOllamaResponding(base)) return [];
176
-
177
- const [installed, loadedNames] = await Promise.all([
178
- getInstalledModels(base),
179
- getLoadedModels(base),
180
- ]);
181
-
182
- const loadedSet = new Set(loadedNames.map(n => n.split(':')[0]));
183
-
184
- return Promise.all(
185
- installed.map(async ({ name, size }) => {
186
- const details = await fetchModelDetails(base, name);
187
- // Use size from /api/tags if /api/show didn't return it
188
- const sizeGB = details.sizeGB ?? (size > 0 ? Math.round(size / 1e8) / 10 : undefined);
189
- const isLoaded = loadedSet.has(name.split(':')[0]);
190
- return { name, supportsTools: details.supportsTools, sizeGB, isLoaded };
191
- })
192
- );
193
- }
194
-
195
- // ── Install ───────────────────────────────────────────────────────────────────
196
-
197
- async function installOllama(): Promise<boolean> {
198
- if (isBinaryInstalled()) {
199
- log('Ollama is already installed.');
200
- return true;
201
- }
202
-
203
- if (platform() === 'win32') {
204
- log('Auto-install not supported on Windows. Download from https://ollama.com/download');
205
- return false;
206
- }
207
-
208
- log('Installing Ollama...');
209
- return new Promise((resolve) => {
210
- const child = spawn('sh', ['-c', 'curl -fsSL https://ollama.com/install.sh | sh'], {
211
- stdio: ['ignore', 'inherit', 'inherit'],
212
- });
213
- child.on('close', (code) => {
214
- if (code === 0) { log('Ollama installed successfully.'); resolve(true); }
215
- else { log(`Install failed (exit ${code}). Try: curl -fsSL https://ollama.com/install.sh | sh`); resolve(false); }
216
- });
217
- child.on('error', (err) => { log(`Install error: ${err.message}`); resolve(false); });
218
- });
219
- }
220
-
221
- // ── Start server ─────────────────────────────────────────────────────────────
222
-
223
- async function startOllamaServer(): Promise<boolean> {
224
- log('Starting Ollama server...');
225
- try {
226
- spawn('ollama', ['serve'], { stdio: 'ignore', detached: true })
227
- .on('error', () => {})
228
- .unref();
229
- } catch { return false; }
230
-
231
- const deadline = Date.now() + START_TIMEOUT_MS;
232
- while (Date.now() < deadline) {
233
- await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));
234
- if (await isOllamaResponding('http://localhost:11434')) {
235
- log('Ollama server is up.');
236
- return true;
237
- }
238
- }
239
- log('Ollama server did not respond in time. Try: ollama serve');
240
- return false;
241
- }
242
-
243
- // ── Model pull ────────────────────────────────────────────────────────────────
244
-
245
- async function pullModel(modelName: string): Promise<void> {
246
- const tag = modelName.replace(/^registry\.ollama\.ai\/library\//, '').split('/').pop() || modelName;
247
- log(`Pulling model "${tag}" (this may take a few minutes)...`);
248
- await new Promise<void>((resolve) => {
249
- const child = spawn('ollama', ['pull', tag], { stdio: ['ignore', 'inherit', 'inherit'] });
250
- child.on('close', (code) => {
251
- if (code === 0) log(`Model "${tag}" ready.`);
252
- else log(`Pull exited ${code} — run manually: ollama pull ${tag}`);
253
- resolve();
254
- });
255
- child.on('error', () => resolve());
256
- });
257
- }
258
-
259
- // ── Public entry point ────────────────────────────────────────────────────────
260
-
261
- /**
262
- * Called by Agent.initialize() before the first API request.
263
- *
264
- * Returns the model name that should actually be used — this may differ from
265
- * the `model` argument when the requested model does not support tools and
266
- * has been swapped for a capable alternative.
267
- *
268
- * Returns undefined if baseURL is not a local Ollama endpoint (no-op).
269
- */
270
- export async function ensureOllama(baseURL?: string, model?: string): Promise<string | undefined> {
271
- if (!isLocalOllamaUrl(baseURL)) return undefined;
272
-
273
- const base = ollamaRoot(baseURL!) || 'http://localhost:11434';
274
-
275
- // ── Ensure server is up ───────────────────────────────────────────────────
276
- if (!await isOllamaResponding(base)) {
277
- if (isBinaryInstalled()) {
278
- log('Ollama is installed but not running.');
279
- if (!await startOllamaServer()) return model;
280
- } else {
281
- log('Ollama not found.');
282
- if (!await installOllama()) return model;
283
- if (!await startOllamaServer()) return model;
284
- }
285
- }
286
-
287
- // ── Ensure model is pulled ────────────────────────────────────────────────
288
- const installed = await getInstalledModels(base);
289
- const installedNames = installed.map(m => m.name);
290
- const requestedTag = (model || '').replace(/^registry\.ollama\.ai\/library\//, '');
291
-
292
- if (installedNames.length === 0) {
293
- await pullModel(requestedTag || TOOLS_CAPABLE_FALLBACK);
294
- } else if (requestedTag) {
295
- const bare = requestedTag.split(':')[0];
296
- const exists = installedNames.some(m => nameMatchesBare(m, bare) || m === requestedTag);
297
- if (!exists) await pullModel(requestedTag);
298
- }
299
-
300
- // ── Check tool support ────────────────────────────────────────────────────
301
- const effectiveModel = requestedTag || TOOLS_CAPABLE_FALLBACK;
302
- const { supportsTools } = await fetchModelDetails(base, effectiveModel);
303
-
304
- if (!supportsTools) {
305
- // Prefer an already-installed tool-capable model over pulling a new one
306
- const freshInstalled = await getInstalledModels(base);
307
- const capableFallback = await findBestInstalledCapableModel(base, freshInstalled.map(m => m.name));
308
-
309
- if (capableFallback) {
310
- log(`"${effectiveModel}" does not support tools. Switching to installed model "${capableFallback}".`);
311
- return capableFallback;
312
- }
313
-
314
- // Nothing capable installed — pull the default fallback
315
- log(`"${effectiveModel}" does not support tools. Pulling ${TOOLS_CAPABLE_FALLBACK}...`);
316
- await pullModel(TOOLS_CAPABLE_FALLBACK);
317
- return TOOLS_CAPABLE_FALLBACK;
318
- }
319
-
320
- return effectiveModel || model;
321
- }
322
-
323
- // Find the best already-installed model that supports tools.
324
- // Prefers loaded models, then prefers well-known capable models.
325
- async function findBestInstalledCapableModel(base: string, names: string[]): Promise<string | undefined> {
326
- const loadedNames = await getLoadedModels(base);
327
- const loadedSet = new Set(loadedNames.map(n => n.split(':')[0]));
328
-
329
- const capable: string[] = [];
330
- for (const name of names) {
331
- const { supportsTools } = await fetchModelDetails(base, name);
332
- if (supportsTools) capable.push(name);
333
- }
334
-
335
- if (capable.length === 0) return undefined;
336
-
337
- // Prefer a currently loaded model
338
- const loadedCapable = capable.find(n => loadedSet.has(n.split(':')[0]));
339
- if (loadedCapable) return loadedCapable;
340
-
341
- return capable[0];
342
- }