@causyne/agent 1.11.0 → 1.12.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 (40) hide show
  1. package/docs/THIRD_PARTY_NOTICES.md +12 -0
  2. package/package.json +1 -1
  3. package/src/acp/protocol.js +1 -0
  4. package/src/acp/protocol.ts +22 -0
  5. package/src/acp/server.js +158 -21
  6. package/src/acp/server.ts +167 -21
  7. package/src/agentLoop.d.ts +22 -1
  8. package/src/agentLoop.js +15 -5
  9. package/src/approvalGrants.js +33 -0
  10. package/src/approvalGrants.ts +50 -0
  11. package/src/decisionPolicy.js +2 -0
  12. package/src/decisionPolicy.ts +1 -0
  13. package/src/engines/cad.js +113 -0
  14. package/src/engines/cad.ts +128 -0
  15. package/src/engines/film.js +108 -0
  16. package/src/engines/film.ts +104 -0
  17. package/src/engines/installer.js +226 -0
  18. package/src/engines/installer.ts +248 -0
  19. package/src/engines/photo.js +126 -0
  20. package/src/engines/photo.ts +137 -0
  21. package/src/engines/registry.js +186 -0
  22. package/src/engines/registry.ts +185 -0
  23. package/src/engines/sound.js +117 -0
  24. package/src/engines/sound.ts +130 -0
  25. package/src/engines/types.js +1 -0
  26. package/src/engines/types.ts +73 -0
  27. package/src/memoryManager.js +9 -3
  28. package/src/promptMentions.js +1 -1
  29. package/src/promptMentions.ts +1 -1
  30. package/src/sandbox.js +8 -0
  31. package/src/sessionJournal.js +12 -2
  32. package/src/sessionJournal.ts +12 -2
  33. package/src/toolPacks.js +15 -7
  34. package/src/tools/generateMediaViaApi.js +1 -1
  35. package/src/tools/nativeEngine.js +464 -0
  36. package/src/tools/nativeEngine.ts +433 -0
  37. package/src/tools/openSourceToolProvisioner.js +510 -0
  38. package/src/tools/openSourceToolProvisioner.ts +590 -0
  39. package/src/tools/registry.js +4 -1
  40. package/src/tui/completion.js +2 -2
@@ -0,0 +1,590 @@
1
+ import os from 'node:os';
2
+ import fs from 'node:fs';
3
+ import fsp from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { execFile } from 'node:child_process';
6
+ import util from 'node:util';
7
+ import { causyneHome, resolveUserPath } from '../utils/paths.js';
8
+
9
+ const execFilePromise = util.promisify(execFile);
10
+
11
+ export interface SystemSpecs {
12
+ platform: string;
13
+ architecture: string;
14
+ totalRamMB: number;
15
+ freeRamMB: number;
16
+ cpuCores: number;
17
+ cpuModel: string;
18
+ diskSpaceGB: number;
19
+ diskSpaceText: string;
20
+ accelerator: 'Apple Silicon Metal (Unified Memory)' | 'NVIDIA CUDA' | 'CPU';
21
+ }
22
+
23
+ export interface OpenSourceToolProfile {
24
+ id: string;
25
+ name: string;
26
+ category: 'voice' | 'audio' | 'vision' | 'llm' | 'utilities';
27
+ repo: string;
28
+ url: string;
29
+ license: string;
30
+ description: string;
31
+ minRamMB: number;
32
+ recommendedRamMB: number;
33
+ diskFootprintMB: number;
34
+ computeType: string;
35
+ supportedPlatforms?: string[];
36
+ installMethod: 'pip' | 'binary' | 'git';
37
+ pipPackages?: string[];
38
+ lightweightAlternativeId?: string;
39
+ }
40
+
41
+ export interface CompatibilityReport {
42
+ compatible: boolean;
43
+ status: 'READY_OPTIMAL' | 'READY_MARGINAL' | 'INSUFFICIENT_HARDWARE';
44
+ reason: string;
45
+ ramAssessment: string;
46
+ diskAssessment: string;
47
+ computeAssessment: string;
48
+ }
49
+
50
+ export const CURATED_OPEN_SOURCE_CATALOGUE: Record<string, OpenSourceToolProfile> = {
51
+ 'f5-tts': {
52
+ id: 'f5-tts',
53
+ name: 'F5-TTS (Fairytale-5 Voice Cloning)',
54
+ category: 'voice',
55
+ repo: 'SWivid/F5-TTS',
56
+ url: 'https://github.com/SWivid/F5-TTS',
57
+ license: 'MIT',
58
+ description: 'State-of-the-art non-autoregressive zero-shot voice cloning with Flow Matching. Natural prosody and high similarity from a 5-10s audio reference.',
59
+ minRamMB: 4096,
60
+ recommendedRamMB: 8192,
61
+ diskFootprintMB: 1800,
62
+ computeType: 'Apple Silicon Metal (MPS) / NVIDIA CUDA / CPU',
63
+ installMethod: 'pip',
64
+ pipPackages: ['f5-tts==0.2.2', 'soundfile>=0.12.1'],
65
+ lightweightAlternativeId: 'kokoro-82m'
66
+ },
67
+ 'kokoro-82m': {
68
+ id: 'kokoro-82m',
69
+ name: 'Kokoro-82M Ultra-Light TTS',
70
+ category: 'voice',
71
+ repo: 'hexgrad/Kokoro-82M',
72
+ url: 'https://github.com/hexgrad/Kokoro-82M',
73
+ license: 'Apache-2.0',
74
+ description: 'Ultra-compact 82M parameter speech synthesizer with studio-quality prosody. Runs smoothly on low RAM and pure CPU.',
75
+ minRamMB: 1024,
76
+ recommendedRamMB: 2048,
77
+ diskFootprintMB: 350,
78
+ computeType: 'CPU / Apple Silicon Metal / CUDA',
79
+ installMethod: 'pip',
80
+ pipPackages: ['kokoro>=0.8.4', 'soundfile>=0.12.1']
81
+ },
82
+ 'xtts-v2': {
83
+ id: 'xtts-v2',
84
+ name: 'Coqui XTTS-v2 Voice Cloner',
85
+ category: 'voice',
86
+ repo: 'coqui-ai/TTS',
87
+ url: 'https://github.com/coqui-ai/TTS',
88
+ license: 'CPML / Research',
89
+ description: 'Multilingual zero-shot voice cloning across 17+ languages using a 3-second audio sample.',
90
+ minRamMB: 6144,
91
+ recommendedRamMB: 12288,
92
+ diskFootprintMB: 3800,
93
+ computeType: 'NVIDIA CUDA / Apple Silicon MPS / Fast CPU',
94
+ installMethod: 'pip',
95
+ pipPackages: ['TTS>=0.22.0'],
96
+ lightweightAlternativeId: 'kokoro-82m'
97
+ },
98
+ 'chatterbox': {
99
+ id: 'chatterbox',
100
+ name: 'Chatterbox TTS & Voice Clone',
101
+ category: 'voice',
102
+ repo: 'resemble-ai/Chatterbox',
103
+ url: 'https://github.com/resemble-ai/Chatterbox',
104
+ license: 'MIT',
105
+ description: 'Open-source voice cloning toolkit with low latency and clean speech synthesis.',
106
+ minRamMB: 4096,
107
+ recommendedRamMB: 8192,
108
+ diskFootprintMB: 1500,
109
+ computeType: 'CPU / MPS / CUDA',
110
+ installMethod: 'pip',
111
+ pipPackages: ['chatterbox-tts>=0.1.0'],
112
+ lightweightAlternativeId: 'kokoro-82m'
113
+ },
114
+ 'whisper-cpp': {
115
+ id: 'whisper-cpp',
116
+ name: 'Whisper.cpp High-Speed Transcriber',
117
+ category: 'audio',
118
+ repo: 'ggerganov/whisper.cpp',
119
+ url: 'https://github.com/ggerganov/whisper.cpp',
120
+ license: 'MIT',
121
+ description: 'High-performance speech-to-text inference in pure C/C++ with zero dependencies. Optimized for Apple Silicon Metal & AVX2.',
122
+ minRamMB: 1024,
123
+ recommendedRamMB: 4096,
124
+ diskFootprintMB: 450,
125
+ computeType: 'Apple Silicon Metal / CPU / CUDA',
126
+ installMethod: 'binary',
127
+ lightweightAlternativeId: 'whisper-cpp'
128
+ },
129
+ 'faster-whisper': {
130
+ id: 'faster-whisper',
131
+ name: 'Faster-Whisper (CTranslate2)',
132
+ category: 'audio',
133
+ repo: 'SYSTRAN/faster-whisper',
134
+ url: 'https://github.com/SYSTRAN/faster-whisper',
135
+ license: 'MIT',
136
+ description: 'Reimplementation of Whisper using CTranslate2, up to 4x faster with lower memory consumption.',
137
+ minRamMB: 2048,
138
+ recommendedRamMB: 4096,
139
+ diskFootprintMB: 800,
140
+ computeType: 'CPU / CUDA / MPS',
141
+ installMethod: 'pip',
142
+ pipPackages: ['faster-whisper>=1.0.0']
143
+ },
144
+ 'realesrgan': {
145
+ id: 'realesrgan',
146
+ name: 'Real-ESRGAN Image & Video Upscaler',
147
+ category: 'vision',
148
+ repo: 'xinntao/Real-ESRGAN',
149
+ url: 'https://github.com/xinntao/Real-ESRGAN',
150
+ license: 'BSD-3-Clause',
151
+ description: 'Practical AI algorithms for general image restoration, super-resolution, and 4x upscaling.',
152
+ minRamMB: 4096,
153
+ recommendedRamMB: 8192,
154
+ diskFootprintMB: 600,
155
+ computeType: 'Apple Silicon Metal / CUDA / CPU',
156
+ installMethod: 'pip',
157
+ pipPackages: ['realesrgan>=0.3.0']
158
+ },
159
+ 'rembg': {
160
+ id: 'rembg',
161
+ name: 'Rembg (Background Removal)',
162
+ category: 'vision',
163
+ repo: 'danielgatis/rembg',
164
+ url: 'https://github.com/danielgatis/rembg',
165
+ license: 'MIT',
166
+ description: 'Tool to remove background from images using U^2-Net and ONNX runtime.',
167
+ minRamMB: 2048,
168
+ recommendedRamMB: 4096,
169
+ diskFootprintMB: 400,
170
+ computeType: 'CPU / ONNX / CUDA',
171
+ installMethod: 'pip',
172
+ pipPackages: ['rembg>=2.0.50']
173
+ },
174
+ 'ollama': {
175
+ id: 'ollama',
176
+ name: 'Ollama Sovereign Model Runner',
177
+ category: 'llm',
178
+ repo: 'ollama/ollama',
179
+ url: 'https://github.com/ollama/ollama',
180
+ license: 'MIT',
181
+ description: 'Run open-source LLMs and local embedding models directly on Apple Silicon Metal or CUDA.',
182
+ minRamMB: 4096,
183
+ recommendedRamMB: 16384,
184
+ diskFootprintMB: 3000,
185
+ computeType: 'Apple Silicon Metal / NVIDIA CUDA / CPU',
186
+ installMethod: 'binary'
187
+ }
188
+ };
189
+
190
+ export async function detectSystemSpecs(workspaceRoot?: string): Promise<SystemSpecs> {
191
+ const totalRamMB = Math.round(os.totalmem() / 1024 / 1024);
192
+ let freeRamMB = Math.round(os.freemem() / 1024 / 1024);
193
+ const platform = os.platform();
194
+ const architecture = os.arch();
195
+ const cpuCores = os.cpus().length;
196
+ const cpuModel = os.cpus()[0]?.model || 'Unknown CPU';
197
+
198
+ // macOS memory accounting: add inactive buffer estimate
199
+ if (platform === 'darwin') {
200
+ const usedApprox = totalRamMB - freeRamMB;
201
+ const inactiveApprox = usedApprox * 0.4;
202
+ freeRamMB = Math.round(freeRamMB + inactiveApprox);
203
+ }
204
+
205
+ // Disk space detection
206
+ let diskSpaceGB = 10;
207
+ let diskSpaceText = '10 GB available';
208
+ try {
209
+ const checkDir = workspaceRoot || process.cwd();
210
+ const stats = await fsp.statfs(checkDir);
211
+ const freeBytes = stats.bavail * stats.bsize;
212
+ diskSpaceGB = Math.round(freeBytes / 1024 / 1024 / 1024);
213
+ diskSpaceText = `${diskSpaceGB} GB available`;
214
+ } catch {
215
+ // Fallback on default assumption
216
+ }
217
+
218
+ // Accelerator detection
219
+ let accelerator: SystemSpecs['accelerator'] = 'CPU';
220
+ if (platform === 'darwin' && architecture === 'arm64') {
221
+ accelerator = 'Apple Silicon Metal (Unified Memory)';
222
+ } else if (process.env['CUDA_VISIBLE_DEVICES'] || fs.existsSync('/usr/local/cuda')) {
223
+ accelerator = 'NVIDIA CUDA';
224
+ }
225
+
226
+ return {
227
+ platform,
228
+ architecture,
229
+ totalRamMB,
230
+ freeRamMB,
231
+ cpuCores,
232
+ cpuModel,
233
+ diskSpaceGB,
234
+ diskSpaceText,
235
+ accelerator
236
+ };
237
+ }
238
+
239
+ export function evaluateHardwareCompatibility(
240
+ specs: SystemSpecs,
241
+ tool: OpenSourceToolProfile
242
+ ): CompatibilityReport {
243
+ const hasMinRam = specs.freeRamMB >= tool.minRamMB || specs.totalRamMB >= tool.minRamMB + 1024;
244
+ const hasComfortableRam = specs.freeRamMB >= tool.recommendedRamMB;
245
+ const diskNeededGB = Math.ceil(tool.diskFootprintMB / 1024);
246
+ const hasDisk = specs.diskSpaceGB >= diskNeededGB + 2; // Keep at least 2GB breathing room
247
+
248
+ let status: CompatibilityReport['status'] = 'READY_OPTIMAL';
249
+ let compatible = true;
250
+ let reason = 'Hardware specs meet or exceed recommended operational thresholds.';
251
+
252
+ if (!hasMinRam || !hasDisk) {
253
+ status = 'INSUFFICIENT_HARDWARE';
254
+ compatible = false;
255
+ reason = !hasMinRam
256
+ ? `Insufficient RAM: Needs minimum ${Math.round(tool.minRamMB / 1024)}GB, but only ~${Math.round(specs.freeRamMB / 1024)}GB is currently free.`
257
+ : `Insufficient Disk Space: Needs ~${diskNeededGB}GB, but only ${specs.diskSpaceGB}GB is available.`;
258
+ } else if (!hasComfortableRam) {
259
+ status = 'READY_MARGINAL';
260
+ reason = `System meets minimum RAM (${Math.round(tool.minRamMB / 1024)}GB) but is below recommended ${Math.round(tool.recommendedRamMB / 1024)}GB. Inference may be slower or share memory with other applications.`;
261
+ }
262
+
263
+ const ramAssessment = `RAM: ${Math.round(specs.freeRamMB / 1024)}GB free / ${Math.round(specs.totalRamMB / 1024)}GB total (Tool requires ${Math.round(tool.minRamMB / 1024)}GB min, ${Math.round(tool.recommendedRamMB / 1024)}GB recommended).`;
264
+ const diskAssessment = `Disk: ${specs.diskSpaceGB}GB free (Tool footprint ~${(tool.diskFootprintMB / 1024).toFixed(1)}GB).`;
265
+ const computeAssessment = `Compute: ${specs.accelerator} (${specs.cpuCores} cores, ${specs.cpuModel}).`;
266
+
267
+ return {
268
+ compatible,
269
+ status,
270
+ reason,
271
+ ramAssessment,
272
+ diskAssessment,
273
+ computeAssessment
274
+ };
275
+ }
276
+
277
+ export function searchCatalogue(intentOrQuery: string): OpenSourceToolProfile[] {
278
+ const q = (intentOrQuery || '').toLowerCase().trim();
279
+ const profiles = Object.values(CURATED_OPEN_SOURCE_CATALOGUE);
280
+ if (!q) return profiles;
281
+
282
+ return profiles.filter(p => {
283
+ return (
284
+ p.id.includes(q) ||
285
+ p.name.toLowerCase().includes(q) ||
286
+ p.category.toLowerCase().includes(q) ||
287
+ p.description.toLowerCase().includes(q) ||
288
+ (q.includes('voice') && (p.category === 'voice' || p.id.includes('tts'))) ||
289
+ (q.includes('clone') && p.category === 'voice') ||
290
+ (q.includes('speech') && (p.category === 'voice' || p.category === 'audio')) ||
291
+ (q.includes('audio') && (p.category === 'voice' || p.category === 'audio')) ||
292
+ (q.includes('upscale') && p.id === 'realesrgan') ||
293
+ (q.includes('background') && p.id === 'rembg') ||
294
+ (q.includes('transcribe') && p.category === 'audio')
295
+ );
296
+ });
297
+ }
298
+
299
+ export const openSourceToolProvisioner = {
300
+ schema: {
301
+ name: 'open_source_tool_provisioner',
302
+ description: 'Discover, evaluate compute/RAM hardware compatibility, and install sovereign open-source AI tools & models (voice cloning, TTS, speech-to-text, vision upscaling, local LLMs). Evaluates user hardware specs (RAM, CPU, GPU/MPS, disk) first and enforces Human-In-The-Loop (HITL) approval before any installation.',
303
+ parameters: {
304
+ type: 'object',
305
+ properties: {
306
+ action: {
307
+ type: 'string',
308
+ enum: ['discover', 'evaluate', 'install', 'list_installed'],
309
+ description: 'Action: discover (search tools matching user intent & evaluate hardware), evaluate (check hardware compatibility for a specific toolId), install (install approved open source tool with HITL confirm flag), or list_installed (view installed local tools).'
310
+ },
311
+ intent: {
312
+ type: 'string',
313
+ description: 'User intent or domain (e.g., "voice cloning", "clone my voice", "audio transcription", "image upscaling", "local llm").'
314
+ },
315
+ toolId: {
316
+ type: 'string',
317
+ description: 'Identifier of the open-source tool (e.g., "f5-tts", "kokoro-82m", "whisper-cpp", "xtts-v2", "realesrgan", "rembg", "ollama").'
318
+ },
319
+ confirm: {
320
+ type: 'boolean',
321
+ description: 'Mandatory Human-In-The-Loop (HITL) consent flag. Must be set to true only after obtaining explicit user agreement.'
322
+ },
323
+ forceAlternative: {
324
+ type: 'boolean',
325
+ description: 'If true, automatically select the lightweight low-RAM alternative if the primary tool is heavy.'
326
+ }
327
+ },
328
+ required: ['action']
329
+ }
330
+ },
331
+
332
+ async execute(args: Record<string, unknown>, sandbox: Record<string, unknown> = {}) {
333
+ const action = String(args['action'] || 'discover');
334
+ const intent = typeof args['intent'] === 'string' ? args['intent'] : '';
335
+ let toolId = typeof args['toolId'] === 'string' ? args['toolId'].toLowerCase().trim() : '';
336
+ const confirm = args['confirm'] === true;
337
+ const forceAlternative = args['forceAlternative'] === true;
338
+
339
+ const workspaceDir = (Array.isArray(sandbox['workspacePaths']) && sandbox['workspacePaths'][0])
340
+ ? String(sandbox['workspacePaths'][0])
341
+ : process.cwd();
342
+
343
+ const specs = await detectSystemSpecs(workspaceDir);
344
+
345
+ // ── ACTION: DISCOVER ──────────────────────────────────────────────────
346
+ if (action === 'discover') {
347
+ const matches = searchCatalogue(intent || toolId);
348
+ if (matches.length === 0) {
349
+ return {
350
+ success: true,
351
+ query: intent,
352
+ systemSpecs: specs,
353
+ message: `No exact local catalogue match for "${intent}". You may search GitHub directly via web_search or query another domain.`,
354
+ recommendations: []
355
+ };
356
+ }
357
+
358
+ const evaluations = matches.map(tool => {
359
+ const evalReport = evaluateHardwareCompatibility(specs, tool);
360
+ return {
361
+ id: tool.id,
362
+ name: tool.name,
363
+ category: tool.category,
364
+ repoUrl: tool.url,
365
+ license: tool.license,
366
+ description: tool.description,
367
+ diskSize: `~${(tool.diskFootprintMB / 1024).toFixed(1)} GB`,
368
+ ramRequired: `${Math.round(tool.minRamMB / 1024)}GB min, ${Math.round(tool.recommendedRamMB / 1024)}GB rec`,
369
+ compute: tool.computeType,
370
+ status: evalReport.status,
371
+ compatible: evalReport.compatible,
372
+ advice: evalReport.reason,
373
+ lightweightAlternative: tool.lightweightAlternativeId
374
+ };
375
+ });
376
+
377
+ // Sort optimal first
378
+ evaluations.sort((a, b) => {
379
+ const score = (s: string) => (s === 'READY_OPTIMAL' ? 2 : s === 'READY_MARGINAL' ? 1 : 0);
380
+ return score(b.status) - score(a.status);
381
+ });
382
+
383
+ return {
384
+ success: true,
385
+ intent: intent || 'general',
386
+ systemSpecs: {
387
+ platform: specs.platform,
388
+ architecture: specs.architecture,
389
+ cpu: `${specs.cpuCores} cores (${specs.cpuModel})`,
390
+ accelerator: specs.accelerator,
391
+ totalRamGB: Math.round(specs.totalRamMB / 1024),
392
+ freeRamGB: Math.round(specs.freeRamMB / 1024),
393
+ diskSpace: specs.diskSpaceText
394
+ },
395
+ recommendations: evaluations,
396
+ instruction: 'To install a candidate, review specs with the user, obtain HITL consent, and invoke with action: "install", toolId: "<id>", confirm: true.'
397
+ };
398
+ }
399
+
400
+ // ── ACTION: EVALUATE ──────────────────────────────────────────────────
401
+ if (action === 'evaluate') {
402
+ if (!toolId) {
403
+ return { success: false, error: 'Missing toolId for evaluate action.' };
404
+ }
405
+ const tool = CURATED_OPEN_SOURCE_CATALOGUE[toolId];
406
+ if (!tool) {
407
+ return { success: false, error: `Unknown toolId "${toolId}". Choose from: ${Object.keys(CURATED_OPEN_SOURCE_CATALOGUE).join(', ')}` };
408
+ }
409
+
410
+ const evalReport = evaluateHardwareCompatibility(specs, tool);
411
+ return {
412
+ success: true,
413
+ tool: {
414
+ id: tool.id,
415
+ name: tool.name,
416
+ repoUrl: tool.url,
417
+ license: tool.license,
418
+ diskSize: `~${(tool.diskFootprintMB / 1024).toFixed(1)} GB`,
419
+ minRam: `${Math.round(tool.minRamMB / 1024)} GB`,
420
+ recommendedRam: `${Math.round(tool.recommendedRamMB / 1024)} GB`,
421
+ compute: tool.computeType
422
+ },
423
+ systemSpecs: specs,
424
+ evaluation: evalReport
425
+ };
426
+ }
427
+
428
+ // ── ACTION: INSTALL (WITH MANDATORY HITL) ─────────────────────────────
429
+ if (action === 'install') {
430
+ if (!toolId) {
431
+ return { success: false, error: 'Missing toolId to install.' };
432
+ }
433
+
434
+ let tool = CURATED_OPEN_SOURCE_CATALOGUE[toolId];
435
+ if (!tool) {
436
+ return { success: false, error: `Tool "${toolId}" not found in catalogue.` };
437
+ }
438
+
439
+ let selectedTool: OpenSourceToolProfile = tool;
440
+ if (forceAlternative && tool.lightweightAlternativeId) {
441
+ const alt = CURATED_OPEN_SOURCE_CATALOGUE[tool.lightweightAlternativeId];
442
+ if (alt) {
443
+ selectedTool = alt;
444
+ toolId = alt.id;
445
+ }
446
+ }
447
+
448
+ const evalReport = evaluateHardwareCompatibility(specs, selectedTool);
449
+
450
+ // MANDATORY HITL GATE: If not confirmed, pause and formulate decision proposal
451
+ if (!confirm) {
452
+ const altProfile = selectedTool.lightweightAlternativeId
453
+ ? CURATED_OPEN_SOURCE_CATALOGUE[selectedTool.lightweightAlternativeId]
454
+ : undefined;
455
+
456
+ return {
457
+ success: true,
458
+ requiresConsent: true,
459
+ status: 'AWAITING_HITL_CONFIRMATION',
460
+ message: `Human-In-The-Loop confirmation required before installing ${selectedTool.name}.`,
461
+ tool: {
462
+ id: selectedTool.id,
463
+ name: selectedTool.name,
464
+ repository: selectedTool.url,
465
+ license: selectedTool.license,
466
+ diskSize: `~${(selectedTool.diskFootprintMB / 1024).toFixed(1)} GB`,
467
+ minRam: `${Math.round(selectedTool.minRamMB / 1024)} GB`,
468
+ recommendedRam: `${Math.round(selectedTool.recommendedRamMB / 1024)} GB`,
469
+ compute: selectedTool.computeType,
470
+ evaluation: evalReport
471
+ },
472
+ decisionRequest: {
473
+ kind: 'product',
474
+ header: `Install ${selectedTool.name}`,
475
+ question: `Do you authorize installing ${selectedTool.name} (~${(selectedTool.diskFootprintMB / 1024).toFixed(1)} GB disk, ${Math.round(selectedTool.minRamMB / 1024)} GB RAM)?`,
476
+ reason: `Sovereign open-source tool installation on your local machine requires explicit authorization.`,
477
+ options: [
478
+ {
479
+ id: 'install_authorized',
480
+ label: `Authorize & Install ${selectedTool.name}`,
481
+ description: `Proceed with installation into isolated .ai_tools workspace environment.`
482
+ },
483
+ ...(altProfile
484
+ ? [
485
+ {
486
+ id: 'install_lightweight',
487
+ label: `Use Lightweight Alternative (${altProfile.name})`,
488
+ description: `Requires much less RAM (<1-2GB) and smaller disk footprint.`
489
+ }
490
+ ]
491
+ : []),
492
+ {
493
+ id: 'cancel_install',
494
+ label: 'Cancel Installation',
495
+ description: 'Do not install local model; fall back to cloud API or procedural tools.'
496
+ }
497
+ ]
498
+ },
499
+ instruction: `Ask user for consent via request_decision or run 'open_source_tool_provisioner' with confirm: true after obtaining agreement.`
500
+ };
501
+ }
502
+
503
+ // User has explicitly confirmed! Proceed with sovereign isolated setup.
504
+ const aiToolsDir = path.join(workspaceDir, '.ai_tools');
505
+ const venvDir = path.join(aiToolsDir, 'venv');
506
+ await fsp.mkdir(aiToolsDir, { recursive: true });
507
+
508
+ // Ensure python venv exists
509
+ const isWin = process.platform === 'win32';
510
+ const pythonBin = isWin ? 'python.exe' : 'python3';
511
+ const venvPip = isWin ? path.join(venvDir, 'Scripts', 'pip.exe') : path.join(venvDir, 'bin', 'pip');
512
+ const venvPython = isWin ? path.join(venvDir, 'Scripts', 'python.exe') : path.join(venvDir, 'bin', 'python');
513
+
514
+ if (!fs.existsSync(venvPip)) {
515
+ try {
516
+ await execFilePromise(pythonBin, ['-m', 'venv', venvDir], { timeout: 120000 });
517
+ } catch (e: unknown) {
518
+ const errMsg = e instanceof Error ? e.message : String(e);
519
+ return { success: false, error: `Failed to create virtual environment: ${errMsg}` };
520
+ }
521
+ }
522
+
523
+ // Install packages if pip-based
524
+ if (selectedTool.installMethod === 'pip' && selectedTool.pipPackages && selectedTool.pipPackages.length > 0) {
525
+ try {
526
+ await execFilePromise(
527
+ venvPip,
528
+ ['install', '--disable-pip-version-check', '--no-input', ...selectedTool.pipPackages],
529
+ { timeout: 10 * 60 * 1000, maxBuffer: 10 * 1024 * 1024 }
530
+ );
531
+ } catch (pipErr: unknown) {
532
+ const errMsg = pipErr instanceof Error ? pipErr.message : String(pipErr);
533
+ return { success: false, error: `Package installation failed: ${errMsg}` };
534
+ }
535
+ }
536
+
537
+ // Record in installed_tools.json manifest
538
+ const manifestFile = path.join(aiToolsDir, 'installed_tools.json');
539
+ let installedMap: Record<string, unknown> = {};
540
+ try {
541
+ if (fs.existsSync(manifestFile)) {
542
+ installedMap = JSON.parse(await fsp.readFile(manifestFile, 'utf8'));
543
+ }
544
+ } catch {
545
+ installedMap = {};
546
+ }
547
+
548
+ installedMap[selectedTool.id] = {
549
+ name: selectedTool.name,
550
+ repo: selectedTool.repo,
551
+ installedAt: new Date().toISOString(),
552
+ pythonPath: venvPython,
553
+ compute: selectedTool.computeType,
554
+ diskSize: `~${(selectedTool.diskFootprintMB / 1024).toFixed(1)} GB`
555
+ };
556
+
557
+ await fsp.writeFile(manifestFile, JSON.stringify(installedMap, null, 2), 'utf8');
558
+
559
+ return {
560
+ success: true,
561
+ installed: true,
562
+ toolId: selectedTool.id,
563
+ name: selectedTool.name,
564
+ pythonPath: venvPython,
565
+ message: `Successfully provisioned ${selectedTool.name}. Dependencies installed in isolated workspace environment (.ai_tools/venv).`,
566
+ runCommand: `${venvPython} -m ${selectedTool.id.replace(/-/g, '_')}`,
567
+ systemSpecs: {
568
+ accelerator: specs.accelerator,
569
+ freeRamGB: Math.round(specs.freeRamMB / 1024)
570
+ }
571
+ };
572
+ }
573
+
574
+ // ── ACTION: LIST_INSTALLED ────────────────────────────────────────────
575
+ if (action === 'list_installed') {
576
+ const manifestFile = path.join(workspaceDir, '.ai_tools', 'installed_tools.json');
577
+ if (!fs.existsSync(manifestFile)) {
578
+ return { success: true, installedTools: [], message: 'No local open-source tools installed in .ai_tools.' };
579
+ }
580
+ try {
581
+ const data = JSON.parse(await fsp.readFile(manifestFile, 'utf8'));
582
+ return { success: true, installedTools: data };
583
+ } catch {
584
+ return { success: true, installedTools: [] };
585
+ }
586
+ }
587
+
588
+ return { success: false, error: `Unknown action: "${action}". Supported: discover, evaluate, install, list_installed.` };
589
+ }
590
+ };
@@ -2,7 +2,9 @@ import { creativeApps } from './creativeApps.js';
2
2
  import { computerUse } from './computerUse.js';
3
3
  import { uiForge } from './uiForge.js';
4
4
  import { documentForgeTool } from './documentForge.js';
5
+ import { nativeEngineTool } from './nativeEngine.js';
5
6
  import { peerAgentTool } from './peerAgent.js';
7
+ import { openSourceToolProvisioner } from './openSourceToolProvisioner.js';
6
8
  import { sysRun, sysRunBg } from './sysRun.js';
7
9
  import { fsRead } from './fsRead.js';
8
10
  import { fsWrite } from './fsWrite.js';
@@ -125,7 +127,8 @@ const TOOL_MODULES = [
125
127
  gameShaderForge, gameSceneBuilder, gameEntitySpawner,
126
128
  gameTilemapGenerator, gameUiHudBuilder, gameEconomyBalancer,
127
129
  gameDataForge, gameWebRuntimeInspector, gameCanvasAudit, readNativeSkill, createSkill, creativeApps,
128
- computerUse, uiForge, documentForgeTool, peerAgentTool
130
+ computerUse, uiForge, documentForgeTool, nativeEngineTool, peerAgentTool,
131
+ openSourceToolProvisioner
129
132
  ];
130
133
 
131
134
  // Base static definitions (backwards compatible). Order is preserved from the
@@ -236,13 +236,13 @@ export class FileIndex {
236
236
  if (entry.isDirectory()) {
237
237
  if (SKIP_DIRECTORIES.has(entry.name) || depth >= MAX_INDEX_DEPTH) continue;
238
238
  queue.push({ dir: full, depth: depth + 1 });
239
- const relDir = path.relative(this.root, full) + '/';
239
+ const relDir = path.relative(this.root, full).split(path.sep).join('/') + '/';
240
240
  if (isTerminalSafe(relDir)) found.push(relDir);
241
241
  continue;
242
242
  }
243
243
  if (!entry.isFile()) continue;
244
244
 
245
- const relative = path.relative(this.root, full);
245
+ const relative = path.relative(this.root, full).split(path.sep).join('/');
246
246
  if (!isTerminalSafe(relative)) continue;
247
247
  found.push(relative);
248
248
  if (found.length >= MAX_INDEX_ENTRIES) {