aegiscode 3.1.7 → 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 +555 -556
  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,291 @@
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
+ }
@@ -0,0 +1,342 @@
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
+ }