aiden-runtime 3.16.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 (159) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +465 -0
  3. package/config/devos.config.json +186 -0
  4. package/config/hardware.json +9 -0
  5. package/config/model-selection.json +7 -0
  6. package/config/setup-complete.json +20 -0
  7. package/dist/api/routes/computerUse.js +112 -0
  8. package/dist/api/server.js +6870 -0
  9. package/dist/bin/npx-init.js +71 -0
  10. package/dist/coordination/commandGate.js +115 -0
  11. package/dist/coordination/livePulse.js +127 -0
  12. package/dist/core/agentLoop.js +2718 -0
  13. package/dist/core/agentShield.js +231 -0
  14. package/dist/core/aidenIdentity.js +215 -0
  15. package/dist/core/aidenPersonality.js +166 -0
  16. package/dist/core/aidenSdk.js +374 -0
  17. package/dist/core/asyncTasks.js +82 -0
  18. package/dist/core/auditTrail.js +61 -0
  19. package/dist/core/auxiliaryClient.js +114 -0
  20. package/dist/core/bgLLM.js +108 -0
  21. package/dist/core/bm25.js +68 -0
  22. package/dist/core/callbackSystem.js +64 -0
  23. package/dist/core/channels/adapter.js +6 -0
  24. package/dist/core/channels/discord.js +173 -0
  25. package/dist/core/channels/email.js +253 -0
  26. package/dist/core/channels/imessage.js +164 -0
  27. package/dist/core/channels/manager.js +96 -0
  28. package/dist/core/channels/signal.js +140 -0
  29. package/dist/core/channels/slack.js +139 -0
  30. package/dist/core/channels/twilio.js +144 -0
  31. package/dist/core/channels/webhook.js +186 -0
  32. package/dist/core/channels/whatsapp.js +185 -0
  33. package/dist/core/clarifyBus.js +75 -0
  34. package/dist/core/codeInterpreter.js +82 -0
  35. package/dist/core/computerControl.js +439 -0
  36. package/dist/core/conversationMemory.js +334 -0
  37. package/dist/core/costTracker.js +221 -0
  38. package/dist/core/cronManager.js +217 -0
  39. package/dist/core/deepKB.js +77 -0
  40. package/dist/core/doctor.js +279 -0
  41. package/dist/core/dreamEngine.js +334 -0
  42. package/dist/core/entityGraph.js +169 -0
  43. package/dist/core/eventBus.js +16 -0
  44. package/dist/core/evolutionAnalyzer.js +153 -0
  45. package/dist/core/executionLoop.js +309 -0
  46. package/dist/core/executor.js +224 -0
  47. package/dist/core/failureAnalyzer.js +166 -0
  48. package/dist/core/fastPathExpansion.js +82 -0
  49. package/dist/core/faultEngine.js +106 -0
  50. package/dist/core/featureGates.js +70 -0
  51. package/dist/core/fileIngestion.js +113 -0
  52. package/dist/core/gateway.js +97 -0
  53. package/dist/core/goalTracker.js +75 -0
  54. package/dist/core/growthEngine.js +168 -0
  55. package/dist/core/hardwareDetector.js +98 -0
  56. package/dist/core/hooks.js +45 -0
  57. package/dist/core/httpKeepalive.js +46 -0
  58. package/dist/core/hybridSearch.js +101 -0
  59. package/dist/core/importers.js +164 -0
  60. package/dist/core/instinctSystem.js +223 -0
  61. package/dist/core/knowledgeBase.js +351 -0
  62. package/dist/core/learningMemory.js +121 -0
  63. package/dist/core/lessonsBrowser.js +125 -0
  64. package/dist/core/licenseManager.js +399 -0
  65. package/dist/core/logBuffer.js +85 -0
  66. package/dist/core/machineId.js +87 -0
  67. package/dist/core/mcpClient.js +442 -0
  68. package/dist/core/memoryDistiller.js +165 -0
  69. package/dist/core/memoryExtractor.js +212 -0
  70. package/dist/core/memoryIds.js +213 -0
  71. package/dist/core/memoryPreamble.js +113 -0
  72. package/dist/core/memoryQuery.js +136 -0
  73. package/dist/core/memoryRecall.js +140 -0
  74. package/dist/core/memoryStrategy.js +201 -0
  75. package/dist/core/messageValidator.js +85 -0
  76. package/dist/core/modelDiscovery.js +108 -0
  77. package/dist/core/modelRouter.js +118 -0
  78. package/dist/core/morningBriefing.js +203 -0
  79. package/dist/core/multiGoalValidator.js +51 -0
  80. package/dist/core/parallelExecutor.js +43 -0
  81. package/dist/core/passiveSkillObserver.js +204 -0
  82. package/dist/core/paths.js +57 -0
  83. package/dist/core/patternDetector.js +83 -0
  84. package/dist/core/planResponseRepair.js +64 -0
  85. package/dist/core/planTool.js +111 -0
  86. package/dist/core/playwrightBridge.js +356 -0
  87. package/dist/core/pluginSystem.js +121 -0
  88. package/dist/core/privateMode.js +85 -0
  89. package/dist/core/reactLoop.js +156 -0
  90. package/dist/core/recipeEngine.js +166 -0
  91. package/dist/core/responseCache.js +128 -0
  92. package/dist/core/runSandbox.js +132 -0
  93. package/dist/core/sandboxRunner.js +200 -0
  94. package/dist/core/scheduler.js +543 -0
  95. package/dist/core/secretScanner.js +49 -0
  96. package/dist/core/semanticMemory.js +223 -0
  97. package/dist/core/sessionMemory.js +259 -0
  98. package/dist/core/sessionRouter.js +91 -0
  99. package/dist/core/sessionSearch.js +163 -0
  100. package/dist/core/setupWizard.js +225 -0
  101. package/dist/core/skillImporter.js +303 -0
  102. package/dist/core/skillLibrary.js +144 -0
  103. package/dist/core/skillLoader.js +471 -0
  104. package/dist/core/skillTeacher.js +352 -0
  105. package/dist/core/skillValidator.js +210 -0
  106. package/dist/core/skillWriter.js +384 -0
  107. package/dist/core/slashAsTool.js +226 -0
  108. package/dist/core/spawnManager.js +197 -0
  109. package/dist/core/statusVerbs.js +43 -0
  110. package/dist/core/swarmManager.js +109 -0
  111. package/dist/core/taskQueue.js +119 -0
  112. package/dist/core/taskRecovery.js +128 -0
  113. package/dist/core/taskState.js +168 -0
  114. package/dist/core/telegramBot.js +152 -0
  115. package/dist/core/todoManager.js +70 -0
  116. package/dist/core/toolNameRepair.js +71 -0
  117. package/dist/core/toolRegistry.js +2730 -0
  118. package/dist/core/tools/calendarTool.js +98 -0
  119. package/dist/core/tools/companyFilingsTool.js +98 -0
  120. package/dist/core/tools/gmailTool.js +87 -0
  121. package/dist/core/tools/marketDataTool.js +135 -0
  122. package/dist/core/tools/socialResearchTool.js +121 -0
  123. package/dist/core/truthCheck.js +57 -0
  124. package/dist/core/updateChecker.js +74 -0
  125. package/dist/core/userCognitionProfile.js +238 -0
  126. package/dist/core/userProfile.js +341 -0
  127. package/dist/core/version.js +5 -0
  128. package/dist/core/visionAnalyze.js +161 -0
  129. package/dist/core/voice/audio.js +187 -0
  130. package/dist/core/voice/stt.js +226 -0
  131. package/dist/core/voice/tts.js +310 -0
  132. package/dist/core/voiceInput.js +118 -0
  133. package/dist/core/voiceOutput.js +130 -0
  134. package/dist/core/webSearch.js +326 -0
  135. package/dist/core/workflowTracker.js +72 -0
  136. package/dist/core/workspaceMemory.js +54 -0
  137. package/dist/core/youtubeTranscript.js +224 -0
  138. package/dist/integrations/computerUse/apiRegistry.js +113 -0
  139. package/dist/integrations/computerUse/screenAgent.js +203 -0
  140. package/dist/integrations/computerUse/visionLoop.js +296 -0
  141. package/dist/memory/memoryLayers.js +143 -0
  142. package/dist/providers/boa.js +93 -0
  143. package/dist/providers/cerebras.js +70 -0
  144. package/dist/providers/custom.js +89 -0
  145. package/dist/providers/gemini.js +82 -0
  146. package/dist/providers/groq.js +92 -0
  147. package/dist/providers/index.js +149 -0
  148. package/dist/providers/nvidia.js +70 -0
  149. package/dist/providers/ollama.js +99 -0
  150. package/dist/providers/openrouter.js +74 -0
  151. package/dist/providers/router.js +497 -0
  152. package/dist/providers/types.js +6 -0
  153. package/dist/security/browserVault.js +129 -0
  154. package/dist/security/dataGuard.js +89 -0
  155. package/dist/tools/eonetTool.js +72 -0
  156. package/dist/types/computerUse.js +2 -0
  157. package/dist/types/executor.js +2 -0
  158. package/dist-bundle/cli.js +357859 -0
  159. package/package.json +256 -0
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // DevOS — Autonomous AI Execution System
4
+ // Copyright (c) 2026 Shiva Deore. All rights reserved.
5
+ // ============================================================
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.loadGoals = loadGoals;
8
+ exports.saveGoals = saveGoals;
9
+ exports.getActiveGoalsSummary = getActiveGoalsSummary;
10
+ // core/goalTracker.ts — Reads/writes workspace/GOALS.md,
11
+ // exposes active goal summaries for planner injection.
12
+ const fs_1 = require("fs");
13
+ const path_1 = require("path");
14
+ const GOALS_PATH = (0, path_1.join)(process.cwd(), 'workspace', 'GOALS.md');
15
+ // ── Parser ────────────────────────────────────────────────────
16
+ function parseGoalSection(section) {
17
+ const lines = section.split('\n');
18
+ const title = lines[0].trim();
19
+ const goal = {
20
+ id: Date.now().toString(),
21
+ title,
22
+ status: 'not_started',
23
+ lastUpdated: new Date().toISOString().split('T')[0],
24
+ };
25
+ for (const line of lines.slice(1)) {
26
+ const t = line.trim();
27
+ if (t.startsWith('- Status:'))
28
+ goal.status = t.replace('- Status:', '').trim();
29
+ else if (t.startsWith('- Target:'))
30
+ goal.target = t.replace('- Target:', '').trim();
31
+ else if (t.startsWith('- Next action:'))
32
+ goal.nextAction = t.replace('- Next action:', '').trim();
33
+ else if (t.startsWith('- Note:')) {
34
+ if (!goal.notes)
35
+ goal.notes = [];
36
+ goal.notes.push(t.replace('- Note:', '').trim());
37
+ }
38
+ }
39
+ return goal;
40
+ }
41
+ // ── Public API ────────────────────────────────────────────────
42
+ function loadGoals() {
43
+ if (!(0, fs_1.existsSync)(GOALS_PATH))
44
+ return [];
45
+ try {
46
+ return (0, fs_1.readFileSync)(GOALS_PATH, 'utf8')
47
+ .split(/^## /m)
48
+ .slice(1)
49
+ .map(parseGoalSection);
50
+ }
51
+ catch {
52
+ return [];
53
+ }
54
+ }
55
+ function saveGoals(goals) {
56
+ const today = new Date().toISOString().split('T')[0];
57
+ const md = '# Active Goals\n\n' +
58
+ goals.map(g => `## ${g.title}\n` +
59
+ `- Status: ${g.status}\n` +
60
+ (g.target ? `- Target: ${g.target}\n` : '') +
61
+ (g.nextAction ? `- Next action: ${g.nextAction}\n` : '') +
62
+ `- Last updated: ${today}\n` +
63
+ (g.notes?.map(n => `- Note: ${n}\n`).join('') ?? '')).join('\n');
64
+ try {
65
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(GOALS_PATH), { recursive: true });
66
+ (0, fs_1.writeFileSync)(GOALS_PATH, md);
67
+ }
68
+ catch { }
69
+ }
70
+ function getActiveGoalsSummary() {
71
+ const active = loadGoals().filter(g => g.status !== 'done');
72
+ if (active.length === 0)
73
+ return '';
74
+ return 'Active goals:\n' + active.map(g => `- ${g.title} [${g.status}]: ${g.nextAction || 'No next action'}`).join('\n');
75
+ }
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // DevOS — Autonomous AI Execution System
4
+ // Copyright (c) 2026 Shiva Deore. All rights reserved.
5
+ // ============================================================
6
+ var __importDefault = (this && this.__importDefault) || function (mod) {
7
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.growthEngine = exports.GrowthEngine = void 0;
11
+ // core/growthEngine.ts — Self-improvement through failure analysis.
12
+ //
13
+ // Appends every failure as a JSONL line to workspace/growth/failure-log.jsonl.
14
+ // On analyze(), clusters failures by (capability, error-class) context hash,
15
+ // surfaces opportunities with count >= 3, and writes a weekly markdown report.
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const path_1 = __importDefault(require("path"));
18
+ // ── Paths ──────────────────────────────────────────────────────
19
+ const GROWTH_DIR = path_1.default.join(process.cwd(), 'workspace', 'growth');
20
+ const FAILURE_LOG = path_1.default.join(GROWTH_DIR, 'failure-log.jsonl');
21
+ const OPPORTUNITIES_PATH = path_1.default.join(GROWTH_DIR, 'skill-opportunities.json');
22
+ const REPORT_PATH = path_1.default.join(GROWTH_DIR, 'weekly-report.md');
23
+ // ── GrowthEngine ───────────────────────────────────────────────
24
+ class GrowthEngine {
25
+ constructor() {
26
+ try {
27
+ fs_1.default.mkdirSync(GROWTH_DIR, { recursive: true });
28
+ }
29
+ catch { }
30
+ }
31
+ // ── Record a failure ──────────────────────────────────────────
32
+ logFailure(task, error, toolsAttempted) {
33
+ const capability = toolsAttempted[toolsAttempted.length - 1] || 'unknown';
34
+ const contextHash = this.hashContext(error, capability);
35
+ const entry = {
36
+ timestamp: Date.now(),
37
+ task,
38
+ error: error.slice(0, 200),
39
+ capability,
40
+ contextHash,
41
+ };
42
+ try {
43
+ fs_1.default.appendFileSync(FAILURE_LOG, JSON.stringify(entry) + '\n', 'utf-8');
44
+ }
45
+ catch { }
46
+ console.log(`[GrowthEngine] Failure logged: ${contextHash} — "${task.slice(0, 60)}"`);
47
+ }
48
+ // ── Record a success ──────────────────────────────────────────
49
+ // Tracked for confidence scoring — future use
50
+ logSuccess(_task, _tools) {
51
+ // No-op for now; confidence scoring uses failure ratio
52
+ }
53
+ // ── Analyse failure log and surface opportunities ─────────────
54
+ analyze() {
55
+ if (!fs_1.default.existsSync(FAILURE_LOG))
56
+ return [];
57
+ let lines;
58
+ try {
59
+ lines = fs_1.default.readFileSync(FAILURE_LOG, 'utf-8').trim().split('\n').filter(Boolean);
60
+ }
61
+ catch {
62
+ return [];
63
+ }
64
+ const totalFailures = lines.length;
65
+ if (totalFailures === 0)
66
+ return [];
67
+ const map = new Map();
68
+ for (const line of lines) {
69
+ try {
70
+ const f = JSON.parse(line);
71
+ if (!map.has(f.contextHash)) {
72
+ map.set(f.contextHash, {
73
+ contextHash: f.contextHash,
74
+ count: 0,
75
+ suggestedSkill: this.inferSkill(f),
76
+ lastSeen: f.timestamp,
77
+ confidence: 0,
78
+ });
79
+ }
80
+ const entry = map.get(f.contextHash);
81
+ entry.count++;
82
+ entry.lastSeen = Math.max(entry.lastSeen, f.timestamp);
83
+ entry.confidence = entry.count / totalFailures;
84
+ }
85
+ catch { }
86
+ }
87
+ const opportunities = Array.from(map.values())
88
+ .filter(o => o.count >= 3 && o.confidence > 0.1)
89
+ .sort((a, b) => b.count - a.count);
90
+ try {
91
+ fs_1.default.writeFileSync(OPPORTUNITIES_PATH, JSON.stringify(opportunities, null, 2), 'utf-8');
92
+ }
93
+ catch { }
94
+ return opportunities;
95
+ }
96
+ // ── Weekly report ─────────────────────────────────────────────
97
+ getWeeklyReport() {
98
+ const opportunities = this.analyze();
99
+ let failedCount = 0;
100
+ try {
101
+ if (fs_1.default.existsSync(FAILURE_LOG)) {
102
+ failedCount = fs_1.default.readFileSync(FAILURE_LOG, 'utf-8')
103
+ .trim().split('\n').filter(Boolean).length;
104
+ }
105
+ }
106
+ catch { }
107
+ const report = {
108
+ learned: 0,
109
+ failed: failedCount,
110
+ gaps: opportunities.map(o => o.contextHash),
111
+ proposals: opportunities.map(o => o.suggestedSkill),
112
+ };
113
+ // Write markdown report
114
+ try {
115
+ const lines = [
116
+ `# DevOS Weekly Growth Report`,
117
+ ``,
118
+ `**Failed tasks:** ${report.failed}`,
119
+ `**Gaps detected:** ${report.gaps.length}`,
120
+ ``,
121
+ opportunities.length === 0
122
+ ? '_No recurring failure patterns detected._'
123
+ : opportunities
124
+ .map(o => `- \`${o.contextHash}\` → \`${o.suggestedSkill}\` ` +
125
+ `(${o.count} failures, confidence: ${(o.confidence * 100).toFixed(0)}%)`)
126
+ .join('\n'),
127
+ ];
128
+ fs_1.default.writeFileSync(REPORT_PATH, lines.join('\n'), 'utf-8');
129
+ }
130
+ catch { }
131
+ return report;
132
+ }
133
+ // ── Context hash: (capability, error-class) pair ─────────────
134
+ hashContext(error, capability) {
135
+ const lower = error.toLowerCase();
136
+ const errClass = lower.includes('timeout') ? 'timeout'
137
+ : lower.includes('selector') ? 'selector'
138
+ : lower.includes('403') || lower.includes('401') ? 'auth'
139
+ : lower.includes('rate') || lower.includes('429') ? 'ratelimit'
140
+ : lower.includes('not found') || lower.includes('enoent') ? 'notfound'
141
+ : lower.includes('parse') || lower.includes('json') ? 'parse'
142
+ : lower.includes('network') || lower.includes('fetch') ? 'network'
143
+ : 'general';
144
+ return `${capability}_${errClass}`;
145
+ }
146
+ // ── Infer a skill name from a failure ─────────────────────────
147
+ inferSkill(f) {
148
+ const lower = f.error.toLowerCase();
149
+ if (lower.includes('selector'))
150
+ return 'web.extractor.robust';
151
+ if (lower.includes('timeout'))
152
+ return 'retry.backoff';
153
+ if (f.capability.includes('file'))
154
+ return 'file.recovery';
155
+ if (lower.includes('rate') || lower.includes('429'))
156
+ return 'provider.rotation';
157
+ if (lower.includes('403') || lower.includes('401'))
158
+ return 'auth.refresh';
159
+ if (lower.includes('parse') || lower.includes('json'))
160
+ return 'output.parser';
161
+ if (lower.includes('network') || lower.includes('fetch'))
162
+ return 'network.resilience';
163
+ return 'general.improvement';
164
+ }
165
+ }
166
+ exports.GrowthEngine = GrowthEngine;
167
+ // ── Singleton ─────────────────────────────────────────────────
168
+ exports.growthEngine = new GrowthEngine();
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // DevOS — Autonomous AI Execution System
4
+ // Copyright (c) 2026 Shiva Deore. All rights reserved.
5
+ // ============================================================
6
+ var __importDefault = (this && this.__importDefault) || function (mod) {
7
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.detectHardware = detectHardware;
11
+ exports.redetectHardware = redetectHardware;
12
+ // core/hardwareDetector.ts — Cross-platform GPU/RAM detection.
13
+ // Caches result to config/hardware.json for 24 hours.
14
+ const os_1 = __importDefault(require("os"));
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const path_1 = __importDefault(require("path"));
17
+ const child_process_1 = require("child_process");
18
+ const CONFIG_PATH = path_1.default.join(process.cwd(), 'config', 'hardware.json');
19
+ function safeExec(cmd) {
20
+ try {
21
+ return (0, child_process_1.execSync)(cmd, { timeout: 5000 }).toString().trim();
22
+ }
23
+ catch {
24
+ return '';
25
+ }
26
+ }
27
+ function detectHardware() {
28
+ // Return cached if exists and less than 24 hours old
29
+ if (fs_1.default.existsSync(CONFIG_PATH)) {
30
+ try {
31
+ const cached = JSON.parse(fs_1.default.readFileSync(CONFIG_PATH, 'utf-8'));
32
+ const age = Date.now() - new Date(cached.detectedAt).getTime();
33
+ if (age < 24 * 60 * 60 * 1000)
34
+ return cached;
35
+ }
36
+ catch { }
37
+ }
38
+ const platformRaw = os_1.default.platform();
39
+ const platform = platformRaw === 'win32' ? 'windows' : platformRaw === 'darwin' ? 'macos' : 'linux';
40
+ const appleSilicon = platform === 'macos' && os_1.default.arch() === 'arm64';
41
+ let gpu = 'Unknown GPU';
42
+ let vramGB = 4;
43
+ let cudaAvailable = false;
44
+ // NVIDIA — works on Windows, Linux, macOS eGPU
45
+ const nvidiaSmiName = safeExec('nvidia-smi --query-gpu=name --format=csv,noheader');
46
+ const nvidiaSmiMem = safeExec('nvidia-smi --query-gpu=memory.total --format=csv,noheader,nounits');
47
+ if (nvidiaSmiName && nvidiaSmiMem) {
48
+ gpu = nvidiaSmiName.split('\n')[0].trim();
49
+ vramGB = Math.round(parseInt(nvidiaSmiMem) / 1024);
50
+ cudaAvailable = true;
51
+ }
52
+ // Apple Silicon — use hw.gpu.unified_mem for actual GPU memory
53
+ if (appleSilicon && gpu === 'Unknown GPU') {
54
+ const unifiedMem = safeExec('sysctl -n hw.gpu.unified_mem'); // actual GPU VRAM
55
+ const chipType = safeExec('sysctl -n machdep.cpu.brand_string');
56
+ if (unifiedMem)
57
+ vramGB = Math.round(parseInt(unifiedMem) / (1024 ** 3));
58
+ else
59
+ vramGB = Math.round(os_1.default.totalmem() / (1024 ** 3) / 2); // fallback: half of RAM
60
+ gpu = chipType || 'Apple Silicon GPU';
61
+ }
62
+ // Windows fallback — integrated/AMD via WMI
63
+ if (platform === 'windows' && gpu === 'Unknown GPU') {
64
+ const wmicOut = safeExec('wmic path Win32_VideoController get Name,AdapterRAM /format:csv');
65
+ const lines = wmicOut.split('\n').filter(l => l.includes(','));
66
+ if (lines[1]) {
67
+ const parts = lines[1].split(',');
68
+ const bytes = parseInt(parts[1] || '0');
69
+ if (bytes > 0)
70
+ vramGB = Math.round(bytes / (1024 ** 3));
71
+ gpu = parts[2]?.trim() || 'Windows GPU';
72
+ }
73
+ }
74
+ // Linux AMD
75
+ if (platform === 'linux' && gpu === 'Unknown GPU') {
76
+ try {
77
+ const mem = fs_1.default.readFileSync('/sys/class/drm/card0/device/mem_info_vram_total', 'utf-8').trim();
78
+ vramGB = Math.round(parseInt(mem) / (1024 ** 3));
79
+ gpu = 'AMD GPU';
80
+ }
81
+ catch { }
82
+ }
83
+ const profile = {
84
+ gpu, vramGB: Math.max(vramGB, 2),
85
+ ramGB: Math.round(os_1.default.totalmem() / (1024 ** 3)),
86
+ platform, cudaAvailable, appleSilicon,
87
+ detectedAt: new Date().toISOString()
88
+ };
89
+ fs_1.default.mkdirSync(path_1.default.dirname(CONFIG_PATH), { recursive: true });
90
+ fs_1.default.writeFileSync(CONFIG_PATH, JSON.stringify(profile, null, 2));
91
+ return profile;
92
+ }
93
+ // Force re-detect (ignores cache)
94
+ function redetectHardware() {
95
+ if (fs_1.default.existsSync(CONFIG_PATH))
96
+ fs_1.default.unlinkSync(CONFIG_PATH);
97
+ return detectHardware();
98
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // DevOS — Autonomous AI Execution System
4
+ // Copyright (c) 2026 Shiva Deore. All rights reserved.
5
+ // ============================================================
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.registerHook = registerHook;
8
+ exports.getHookCount = getHookCount;
9
+ exports.fireHook = fireHook;
10
+ exports.registerExternalHook = registerExternalHook;
11
+ // ── Registry ───────────────────────────────────────────────────
12
+ const registry = new Map();
13
+ function registerHook(event, handler) {
14
+ const handlers = registry.get(event) ?? [];
15
+ handlers.push(handler);
16
+ registry.set(event, handlers);
17
+ }
18
+ function getHookCount(event) {
19
+ return registry.get(event)?.length ?? 0;
20
+ }
21
+ async function fireHook(event, payload) {
22
+ const handlers = registry.get(event);
23
+ if (!handlers || handlers.length === 0)
24
+ return;
25
+ console.log(`[Hooks] Firing "${event}" (${handlers.length} handler(s))`);
26
+ for (const handler of handlers) {
27
+ try {
28
+ await handler(payload);
29
+ }
30
+ catch (e) {
31
+ console.error(`[Hooks] Handler error for "${event}": ${e.message}`);
32
+ }
33
+ }
34
+ }
35
+ // ── Plugin hook registration ───────────────────────────────────
36
+ // Validates the event is a known HookEvent before delegating to registerHook.
37
+ const VALID_HOOK_EVENTS = ['pre_compact', 'session_stop', 'after_tool_call'];
38
+ function registerExternalHook(event, handler, source) {
39
+ if (!VALID_HOOK_EVENTS.includes(event)) {
40
+ console.warn(`[Hooks] Plugin "${source}" tried unknown event "${event}" — valid: ${VALID_HOOK_EVENTS.join(', ')}`);
41
+ return;
42
+ }
43
+ registerHook(event, handler);
44
+ console.log(`[Hooks] Plugin "${source}" registered hook for "${event}"`);
45
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // DevOS — Autonomous AI Execution System
4
+ // Copyright (c) 2026 Shiva Deore. All rights reserved.
5
+ // ============================================================
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.setupHttpKeepalive = setupHttpKeepalive;
8
+ // core/httpKeepalive.ts — Phase 7 of Prompt 10.
9
+ //
10
+ // Sets a global undici Agent with TCP keepalive enabled.
11
+ // All providers use Node.js global fetch(), which is backed by undici in
12
+ // Node 18+. A single call to setupHttpKeepalive() at server startup
13
+ // eliminates the cold-connect TCP handshake on every LLM request.
14
+ //
15
+ // Keepalive settings:
16
+ // keepAliveTimeout 60 s — hold idle connections this long
17
+ // keepAliveMaxTimeout 300 s — server-driven max (Groq allows ~5 min)
18
+ // connections 50 — max concurrent sockets per origin
19
+ // pipelining 1 — one request per connection (safe for HTTP/1.1)
20
+ //
21
+ // Call once at startup:
22
+ // import { setupHttpKeepalive } from '../core/httpKeepalive'
23
+ // setupHttpKeepalive()
24
+ const undici_1 = require("undici");
25
+ let installed = false;
26
+ /**
27
+ * Install a keepalive-enabled undici Agent as the global fetch dispatcher.
28
+ * Idempotent — safe to call multiple times.
29
+ */
30
+ function setupHttpKeepalive() {
31
+ if (installed)
32
+ return;
33
+ const agent = new undici_1.Agent({
34
+ connect: {
35
+ keepAlive: true,
36
+ keepAliveInitialDelay: 0,
37
+ },
38
+ keepAliveTimeout: 60000, // 60 s idle before closing
39
+ keepAliveMaxTimeout: 300000, // 5 min hard cap
40
+ connections: 50, // sockets per origin
41
+ pipelining: 1, // no pipelining — safer with AI APIs
42
+ });
43
+ (0, undici_1.setGlobalDispatcher)(agent);
44
+ installed = true;
45
+ console.log('[HttpKeepalive] Global undici Agent installed — TCP keepalive active');
46
+ }
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // DevOS — Autonomous AI Execution System
4
+ // Copyright (c) 2026 Shiva Deore. All rights reserved.
5
+ // ============================================================
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.hybridSearch = hybridSearch;
8
+ // core/hybridSearch.ts — Weighted hybrid: semantic memory (0.6) + FTS (0.4).
9
+ //
10
+ // Combines:
11
+ // 1. semanticMemory.search() — BM25 + vector, workspace/memory/*.md store
12
+ // 2. sessionSearch.searchSessions() — BM25 over workspace/sessions/*.md
13
+ //
14
+ // Scores are normalised to [0, 1] then merged with the weights above.
15
+ // Deduplication: if a result appears in both sources, the max normalised
16
+ // score is used (avoids double-counting).
17
+ const semanticMemory_1 = require("./semanticMemory");
18
+ const sessionSearch_1 = require("./sessionSearch");
19
+ // ── Normalise an array of scores to [0, 1] ────────────────────
20
+ function normalise(scores) {
21
+ const max = Math.max(...scores, 1e-9);
22
+ return scores.map(s => s / max);
23
+ }
24
+ // ── Simple snippet extractor ──────────────────────────────────
25
+ function snippet(text, maxLen = 200) {
26
+ const s = text.replace(/\s+/g, ' ').trim();
27
+ return s.length <= maxLen ? s : s.slice(0, maxLen) + '…';
28
+ }
29
+ // ── Main hybrid search ────────────────────────────────────────
30
+ /**
31
+ * Hybrid search combining semantic memory and BM25 session search.
32
+ *
33
+ * @param query Natural-language query
34
+ * @param opts Optional weight overrides and topK
35
+ */
36
+ function hybridSearch(query, opts = {}) {
37
+ const topK = opts.topK ?? 5;
38
+ const wSem = opts.semanticWeight ?? 0.6;
39
+ const wFts = opts.ftsWeight ?? 0.4;
40
+ const fetch = topK * 3; // oversample before merging
41
+ // ── 1. Semantic memory results ────────────────────────────────
42
+ let semTexts = [];
43
+ try {
44
+ semTexts = semanticMemory_1.semanticMemory.searchText(query, fetch);
45
+ }
46
+ catch { /* ok */ }
47
+ const semHits = new Map();
48
+ const semScores = semTexts.map((_, i) => Math.max(0, 1 - i / fetch));
49
+ const normSem = normalise(semScores);
50
+ semTexts.forEach((text, i) => {
51
+ const id = `sem:${simpleHash(text)}`;
52
+ semHits.set(id, {
53
+ title: snippet(text, 60),
54
+ snippet: snippet(text),
55
+ rawScore: normSem[i] * wSem,
56
+ source: 'semantic',
57
+ });
58
+ });
59
+ // ── 2. Session FTS results ────────────────────────────────────
60
+ let ftsHits = [];
61
+ try {
62
+ ftsHits = (0, sessionSearch_1.searchSessions)(query, fetch);
63
+ }
64
+ catch { /* ok */ }
65
+ const ftsScores = ftsHits.map(h => h.score);
66
+ const normFts = normalise(ftsScores);
67
+ const ftsMap = new Map();
68
+ ftsHits.forEach((h, i) => {
69
+ ftsMap.set(`fts:${h.doc.id}`, {
70
+ title: h.doc.title,
71
+ snippet: snippet(h.doc.content),
72
+ rawScore: normFts[i] * wFts,
73
+ });
74
+ });
75
+ // ── 3. Merge ──────────────────────────────────────────────────
76
+ const merged = new Map();
77
+ for (const [id, h] of semHits) {
78
+ merged.set(id, { id, title: h.title, snippet: h.snippet, score: h.rawScore, source: 'semantic' });
79
+ }
80
+ for (const [id, h] of ftsMap) {
81
+ if (merged.has(id)) {
82
+ const existing = merged.get(id);
83
+ existing.score = Math.max(existing.score, h.rawScore);
84
+ existing.source = 'both';
85
+ }
86
+ else {
87
+ merged.set(id, { id, title: h.title, snippet: h.snippet, score: h.rawScore, source: 'session' });
88
+ }
89
+ }
90
+ return Array.from(merged.values())
91
+ .sort((a, b) => b.score - a.score)
92
+ .slice(0, topK);
93
+ }
94
+ // ── Simple string hash for dedup ──────────────────────────────
95
+ function simpleHash(s) {
96
+ let h = 0;
97
+ for (let i = 0; i < Math.min(s.length, 64); i++) {
98
+ h = Math.imul(31, h) + s.charCodeAt(i) | 0;
99
+ }
100
+ return (h >>> 0).toString(36);
101
+ }