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,164 @@
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.importChatGPT = importChatGPT;
11
+ exports.importOpenClaw = importOpenClaw;
12
+ // core/importers.ts — Import conversation history from ChatGPT
13
+ // (conversations.json export) and OpenClaw (memory.md files)
14
+ // into Aiden's Knowledge Base and workspace memory.
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const path_1 = __importDefault(require("path"));
17
+ const knowledgeBase_1 = require("./knowledgeBase");
18
+ const WORKSPACE_ROOT = process.env.AIDEN_USER_DATA || process.cwd();
19
+ const MEMORY_DIR = path_1.default.join(WORKSPACE_ROOT, 'workspace', 'memory');
20
+ // ── ChatGPT importer ──────────────────────────────────────────
21
+ // Parses the conversations.json from a ChatGPT data export.
22
+ //
23
+ // Export format:
24
+ // Array<{ title: string, mapping: Record<id, { message: {
25
+ // author: { role: 'user'|'assistant' },
26
+ // content: { parts: string[] }
27
+ // }}> }>
28
+ async function importChatGPT(filePath) {
29
+ const result = {
30
+ source: 'chatgpt',
31
+ conversationsImported: 0,
32
+ memoriesExtracted: 0,
33
+ errors: [],
34
+ };
35
+ try {
36
+ const raw = fs_1.default.readFileSync(filePath, 'utf8');
37
+ const conversations = JSON.parse(raw);
38
+ if (!Array.isArray(conversations)) {
39
+ result.errors.push('Invalid format: expected array of conversations');
40
+ return result;
41
+ }
42
+ for (const convo of conversations) {
43
+ try {
44
+ const messages = [];
45
+ if (convo.mapping && typeof convo.mapping === 'object') {
46
+ for (const entry of Object.values(convo.mapping)) {
47
+ const msg = entry?.message;
48
+ if (!msg)
49
+ continue;
50
+ const parts = msg?.content?.parts;
51
+ if (!Array.isArray(parts) || typeof parts[0] !== 'string')
52
+ continue;
53
+ const text = parts[0].trim();
54
+ if (text.length <= 10)
55
+ continue;
56
+ const role = msg.author?.role || 'unknown';
57
+ messages.push(`${role}: ${text}`);
58
+ }
59
+ }
60
+ if (messages.length === 0)
61
+ continue;
62
+ const content = messages.join('\n\n').substring(0, 50000);
63
+ const title = String(convo.title || 'ChatGPT Import').replace(/[^a-zA-Z0-9._\- ]/g, '_').slice(0, 80);
64
+ const filename = `chatgpt_${title}.txt`;
65
+ const ingestResult = knowledgeBase_1.knowledgeBase.ingestText(content, filename, 'conversation', ['chatgpt', 'imported', 'conversation'], 'public');
66
+ if (ingestResult.success) {
67
+ result.conversationsImported++;
68
+ }
69
+ else {
70
+ result.errors.push(`Ingestion failed for: ${title}`);
71
+ }
72
+ }
73
+ catch (err) {
74
+ result.errors.push(`Failed to import: ${String(convo.title || 'unknown')}`);
75
+ }
76
+ }
77
+ console.log(`[Import] ChatGPT: ${result.conversationsImported} conversations imported`);
78
+ }
79
+ catch (err) {
80
+ result.errors.push(`Parse error: ${String(err)}`);
81
+ }
82
+ return result;
83
+ }
84
+ // ── OpenClaw importer ─────────────────────────────────────────
85
+ // Walks an OpenClaw workspace directory, ingests every .md file
86
+ // into the Knowledge Base, and copies memory/lessons files into
87
+ // workspace/memory/ so Aiden can surface them during planning.
88
+ function findMdFiles(dir) {
89
+ const files = [];
90
+ try {
91
+ const entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
92
+ for (const entry of entries) {
93
+ const fullPath = path_1.default.join(dir, entry.name);
94
+ if (entry.isDirectory() && !entry.name.startsWith('.')) {
95
+ files.push(...findMdFiles(fullPath));
96
+ }
97
+ else if (entry.name.endsWith('.md')) {
98
+ files.push(fullPath);
99
+ }
100
+ }
101
+ }
102
+ catch { }
103
+ return files;
104
+ }
105
+ async function importOpenClaw(directoryPath) {
106
+ const result = {
107
+ source: 'openclaw',
108
+ conversationsImported: 0,
109
+ memoriesExtracted: 0,
110
+ errors: [],
111
+ };
112
+ if (!fs_1.default.existsSync(directoryPath)) {
113
+ result.errors.push(`Directory not found: ${directoryPath}`);
114
+ return result;
115
+ }
116
+ const mdFiles = findMdFiles(directoryPath);
117
+ for (const file of mdFiles) {
118
+ try {
119
+ const content = fs_1.default.readFileSync(file, 'utf8');
120
+ if (content.trim().length < 50)
121
+ continue; // skip empty/trivial files
122
+ const basename = path_1.default.basename(file, '.md');
123
+ const lower = file.toLowerCase();
124
+ const isMemory = lower.includes('memory');
125
+ const isLesson = lower.includes('lesson');
126
+ const isDaily = /\d{4}[-_]\d{2}[-_]\d{2}/.test(basename);
127
+ const category = isMemory ? 'memory'
128
+ : isLesson ? 'lessons'
129
+ : isDaily ? 'daily-log'
130
+ : 'document';
131
+ const filename = `openclaw_${basename.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 60)}.md`;
132
+ const ingestResult = knowledgeBase_1.knowledgeBase.ingestText(content.substring(0, 50000), filename, category, ['openclaw', 'imported', category], 'public');
133
+ if (ingestResult.success) {
134
+ result.conversationsImported++;
135
+ }
136
+ else {
137
+ result.errors.push(`Ingestion failed: ${basename}`);
138
+ }
139
+ // Copy memory and lesson files into workspace/memory/ so the
140
+ // memory recall system can surface them during planning
141
+ if (isMemory || isLesson) {
142
+ try {
143
+ fs_1.default.mkdirSync(MEMORY_DIR, { recursive: true });
144
+ const destName = `imported_${basename.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 60)}.md`;
145
+ const destPath = path_1.default.join(MEMORY_DIR, destName);
146
+ // Only write if not already present (avoid duplicate on re-import)
147
+ if (!fs_1.default.existsSync(destPath)) {
148
+ fs_1.default.writeFileSync(destPath, `<!-- source: openclaw_import | confidence: 0.7 -->\n${content}`, 'utf8');
149
+ result.memoriesExtracted++;
150
+ }
151
+ }
152
+ catch (memErr) {
153
+ result.errors.push(`Memory copy failed: ${basename} — ${String(memErr)}`);
154
+ }
155
+ }
156
+ }
157
+ catch (err) {
158
+ result.errors.push(`Failed: ${path_1.default.basename(file)}`);
159
+ }
160
+ }
161
+ console.log(`[Import] OpenClaw: ${result.conversationsImported} files ingested, ` +
162
+ `${result.memoriesExtracted} memories extracted`);
163
+ return result;
164
+ }
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // DevOS — Autonomous AI Execution System
4
+ // Copyright (c) 2026 Shiva Deore. All rights reserved.
5
+ // ============================================================
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.instinctSystem = void 0;
41
+ exports.initInstinctSystem = initInstinctSystem;
42
+ // core/instinctSystem.ts — Micro-pattern instinct layer.
43
+ // Sits BELOW skills. Instincts are atomic "when X do Y" patterns
44
+ // with confidence scores. When 3+ related instincts cluster with
45
+ // enough total confidence, they evolve into a full SKILL.md.
46
+ const fs_1 = require("fs");
47
+ const path_1 = require("path");
48
+ // ── Thresholds ─────────────────────────────────────────────────
49
+ const CONFIDENCE_GAIN = 0.1;
50
+ const CONFIDENCE_LOSS = 0.2;
51
+ const DEPRECATION_THRESHOLD = 0.2;
52
+ const EVOLUTION_MIN_COUNT = 3;
53
+ const EVOLUTION_MIN_CONFIDENCE = 2.0; // sum of confidences across group
54
+ // ── InstinctSystem ─────────────────────────────────────────────
55
+ function tokenize(text) {
56
+ return text.toLowerCase().split(/\W+/).filter(w => w.length > 3);
57
+ }
58
+ class InstinctSystem {
59
+ constructor(workspaceDir) {
60
+ this.instincts = [];
61
+ this._saveTimer = null;
62
+ // CRITICAL: instincts are workspace-scoped.
63
+ // Trading instincts don't leak into DevOS work.
64
+ this.savePath = (0, path_1.join)(workspaceDir, 'instincts.json');
65
+ this.learnedDir = (0, path_1.join)(workspaceDir, 'skills', 'learned');
66
+ this.load();
67
+ }
68
+ // ── Observe a tool call ───────────────────────────────────────
69
+ observe(toolName, args, success, sessionId) {
70
+ const argSnippet = JSON.stringify(args).slice(0, 80);
71
+ const action = success
72
+ ? `Use ${toolName} with args like ${argSnippet}`
73
+ : `Avoid ${toolName} when args like ${argSnippet} — fails`;
74
+ const words = tokenize(action);
75
+ const existing = this.findSimilar(words);
76
+ if (existing) {
77
+ if (success) {
78
+ existing.confidence = Math.min(0.95, existing.confidence + CONFIDENCE_GAIN);
79
+ if (!existing.evidence.includes(sessionId)) {
80
+ existing.evidence.push(sessionId);
81
+ }
82
+ }
83
+ else {
84
+ existing.confidence -= CONFIDENCE_LOSS;
85
+ existing.contradictions++;
86
+ if (existing.confidence < DEPRECATION_THRESHOLD) {
87
+ existing.status = 'deprecated';
88
+ console.log(`[Instinct] Deprecated: "${existing.action.slice(0, 60)}"`);
89
+ }
90
+ }
91
+ existing.lastSeen = new Date().toISOString();
92
+ }
93
+ else if (success) {
94
+ this.instincts.push({
95
+ id: `inst_${Date.now()}`,
96
+ action,
97
+ words,
98
+ evidence: [sessionId],
99
+ confidence: 0.3,
100
+ category: 'tool_pattern',
101
+ created: new Date().toISOString(),
102
+ lastSeen: new Date().toISOString(),
103
+ contradictions: 0,
104
+ status: 'active',
105
+ });
106
+ }
107
+ this.checkEvolution();
108
+ this.save();
109
+ }
110
+ // ── Word-overlap similarity — 3+ shared words = same instinct ─
111
+ // Accepts pre-tokenized words to avoid re-tokenizing the incoming action.
112
+ // Uses inst.words cache so each stored instinct is tokenized only once.
113
+ findSimilar(incomingWords) {
114
+ const wordSet = new Set(incomingWords);
115
+ return this.instincts.find(inst => {
116
+ if (inst.status !== 'active')
117
+ return false;
118
+ // inst.words may be absent on instincts loaded from disk before this field existed
119
+ const instWords = inst.words ?? (inst.words = tokenize(inst.action));
120
+ return instWords.filter(w => wordSet.has(w)).length >= 3;
121
+ });
122
+ }
123
+ // ── Evolution check — cluster 3+ high-confidence instincts ────
124
+ checkEvolution() {
125
+ // Skip when too few active instincts to possibly meet EVOLUTION_MIN_COUNT
126
+ const activeCount = this.instincts.filter(i => i.status === 'active').length;
127
+ if (activeCount < EVOLUTION_MIN_COUNT)
128
+ return;
129
+ const byCategory = new Map();
130
+ for (const inst of this.instincts) {
131
+ if (inst.status !== 'active')
132
+ continue;
133
+ const group = byCategory.get(inst.category) ?? [];
134
+ group.push(inst);
135
+ byCategory.set(inst.category, group);
136
+ }
137
+ for (const [, group] of byCategory) {
138
+ if (group.length < EVOLUTION_MIN_COUNT)
139
+ continue;
140
+ const totalConfidence = group.reduce((sum, i) => sum + i.confidence, 0);
141
+ if (totalConfidence < EVOLUTION_MIN_CONFIDENCE)
142
+ continue;
143
+ const skillName = `evolved_${group[0].category}_${Date.now()}`;
144
+ console.log(`[Instinct] Evolving ${group.length} instincts into skill: ${skillName}`);
145
+ for (const inst of group) {
146
+ inst.status = 'evolved_into';
147
+ inst.evolvedInto = skillName;
148
+ }
149
+ this.notifyEvolution(skillName, group);
150
+ }
151
+ }
152
+ // ── Write a SKILL.md directory for SkillLoader to pick up ─────
153
+ // SkillLoader expects: skills/learned/{name}/SKILL.md
154
+ // A flat .md file would be skipped (isDirectory() check).
155
+ notifyEvolution(skillName, instincts) {
156
+ const skillDir = (0, path_1.join)(this.learnedDir, skillName);
157
+ const skillFile = (0, path_1.join)(skillDir, 'SKILL.md');
158
+ const content = [
159
+ `---`,
160
+ `name: ${skillName}`,
161
+ `description: Evolved from ${instincts.length} observed tool patterns`,
162
+ `version: 1.0.0`,
163
+ `confidence: low`,
164
+ `tags: ${instincts[0].category}, evolved, auto-generated`,
165
+ `---`,
166
+ ``,
167
+ `## Source Instincts`,
168
+ ...instincts.map(i => `- ${i.action} (confidence: ${(i.confidence * 100).toFixed(0)}%)`),
169
+ ``,
170
+ `## Summary`,
171
+ `This skill evolved from ${instincts.length} observed patterns in category "${instincts[0].category}".`,
172
+ ].join('\n');
173
+ try {
174
+ (0, fs_1.mkdirSync)(skillDir, { recursive: true });
175
+ (0, fs_1.writeFileSync)(skillFile, content);
176
+ console.log(`[Instinct] Wrote evolved skill: ${skillFile}`);
177
+ // Invalidate skillLoader cache so new skill is picked up
178
+ Promise.resolve().then(() => __importStar(require('./skillLoader'))).then(m => m.skillLoader.refresh()).catch(() => { });
179
+ }
180
+ catch (e) {
181
+ console.warn(`[Instinct] Failed to write evolved skill: ${e.message}`);
182
+ }
183
+ }
184
+ // ── Retrieve top instincts relevant to current context ────────
185
+ getRelevantInstincts(context) {
186
+ const active = this.instincts
187
+ .filter(i => i.status === 'active' && i.confidence > 0.5)
188
+ .sort((a, b) => b.confidence - a.confidence)
189
+ .slice(0, 5);
190
+ if (active.length === 0)
191
+ return '';
192
+ return ('Learned patterns:\n' +
193
+ active
194
+ .map(i => `- ${i.action} (confidence: ${(i.confidence * 100).toFixed(0)}%)`)
195
+ .join('\n'));
196
+ }
197
+ // ── Persistence ───────────────────────────────────────────────
198
+ load() {
199
+ try {
200
+ this.instincts = JSON.parse((0, fs_1.readFileSync)(this.savePath, 'utf8'));
201
+ }
202
+ catch {
203
+ this.instincts = [];
204
+ }
205
+ }
206
+ // Debounced — coalesces rapid bursts of tool calls into one disk write
207
+ save() {
208
+ if (this._saveTimer)
209
+ return;
210
+ this._saveTimer = setTimeout(() => {
211
+ this._saveTimer = null;
212
+ try {
213
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(this.savePath), { recursive: true });
214
+ (0, fs_1.writeFileSync)(this.savePath, JSON.stringify(this.instincts, null, 2));
215
+ }
216
+ catch { }
217
+ }, 2000);
218
+ }
219
+ }
220
+ function initInstinctSystem(workspaceDir) {
221
+ exports.instinctSystem = new InstinctSystem(workspaceDir);
222
+ console.log('[Instinct] System initialized');
223
+ }