genesis-ai-cli 7.4.5

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 (227) hide show
  1. package/.env.example +78 -0
  2. package/README.md +282 -0
  3. package/dist/src/active-inference/actions.d.ts +75 -0
  4. package/dist/src/active-inference/actions.js +250 -0
  5. package/dist/src/active-inference/autonomous-loop.d.ts +103 -0
  6. package/dist/src/active-inference/autonomous-loop.js +289 -0
  7. package/dist/src/active-inference/core.d.ts +85 -0
  8. package/dist/src/active-inference/core.js +555 -0
  9. package/dist/src/active-inference/demo-autonomous-loop.d.ts +8 -0
  10. package/dist/src/active-inference/demo-autonomous-loop.js +338 -0
  11. package/dist/src/active-inference/demo-value-integration.d.ts +8 -0
  12. package/dist/src/active-inference/demo-value-integration.js +174 -0
  13. package/dist/src/active-inference/index.d.ts +32 -0
  14. package/dist/src/active-inference/index.js +88 -0
  15. package/dist/src/active-inference/integration.d.ts +114 -0
  16. package/dist/src/active-inference/integration.js +698 -0
  17. package/dist/src/active-inference/memory-integration.d.ts +51 -0
  18. package/dist/src/active-inference/memory-integration.js +232 -0
  19. package/dist/src/active-inference/observations.d.ts +67 -0
  20. package/dist/src/active-inference/observations.js +147 -0
  21. package/dist/src/active-inference/test-active-inference.d.ts +8 -0
  22. package/dist/src/active-inference/test-active-inference.js +320 -0
  23. package/dist/src/active-inference/test-value-integration.d.ts +6 -0
  24. package/dist/src/active-inference/test-value-integration.js +168 -0
  25. package/dist/src/active-inference/types.d.ts +150 -0
  26. package/dist/src/active-inference/types.js +59 -0
  27. package/dist/src/active-inference/value-integration.d.ts +164 -0
  28. package/dist/src/active-inference/value-integration.js +459 -0
  29. package/dist/src/agents/base-agent.d.ts +53 -0
  30. package/dist/src/agents/base-agent.js +178 -0
  31. package/dist/src/agents/builder.d.ts +67 -0
  32. package/dist/src/agents/builder.js +537 -0
  33. package/dist/src/agents/critic.d.ts +35 -0
  34. package/dist/src/agents/critic.js +322 -0
  35. package/dist/src/agents/ethicist.d.ts +54 -0
  36. package/dist/src/agents/ethicist.js +393 -0
  37. package/dist/src/agents/explorer.d.ts +26 -0
  38. package/dist/src/agents/explorer.js +216 -0
  39. package/dist/src/agents/feeling.d.ts +41 -0
  40. package/dist/src/agents/feeling.js +320 -0
  41. package/dist/src/agents/index.d.ts +111 -0
  42. package/dist/src/agents/index.js +222 -0
  43. package/dist/src/agents/memory.d.ts +69 -0
  44. package/dist/src/agents/memory.js +404 -0
  45. package/dist/src/agents/message-bus.d.ts +88 -0
  46. package/dist/src/agents/message-bus.js +267 -0
  47. package/dist/src/agents/narrator.d.ts +90 -0
  48. package/dist/src/agents/narrator.js +473 -0
  49. package/dist/src/agents/planner.d.ts +38 -0
  50. package/dist/src/agents/planner.js +341 -0
  51. package/dist/src/agents/predictor.d.ts +73 -0
  52. package/dist/src/agents/predictor.js +506 -0
  53. package/dist/src/agents/sensor.d.ts +88 -0
  54. package/dist/src/agents/sensor.js +377 -0
  55. package/dist/src/agents/test-agents.d.ts +6 -0
  56. package/dist/src/agents/test-agents.js +73 -0
  57. package/dist/src/agents/types.d.ts +194 -0
  58. package/dist/src/agents/types.js +7 -0
  59. package/dist/src/brain/index.d.ts +185 -0
  60. package/dist/src/brain/index.js +843 -0
  61. package/dist/src/brain/trace.d.ts +91 -0
  62. package/dist/src/brain/trace.js +327 -0
  63. package/dist/src/brain/types.d.ts +165 -0
  64. package/dist/src/brain/types.js +51 -0
  65. package/dist/src/cli/chat.d.ts +237 -0
  66. package/dist/src/cli/chat.js +1959 -0
  67. package/dist/src/cli/dispatcher.d.ts +182 -0
  68. package/dist/src/cli/dispatcher.js +718 -0
  69. package/dist/src/cli/human-loop.d.ts +170 -0
  70. package/dist/src/cli/human-loop.js +543 -0
  71. package/dist/src/cli/index.d.ts +12 -0
  72. package/dist/src/cli/index.js +28 -0
  73. package/dist/src/cli/interactive.d.ts +141 -0
  74. package/dist/src/cli/interactive.js +757 -0
  75. package/dist/src/cli/ui.d.ts +205 -0
  76. package/dist/src/cli/ui.js +632 -0
  77. package/dist/src/consciousness/attention-schema.d.ts +154 -0
  78. package/dist/src/consciousness/attention-schema.js +432 -0
  79. package/dist/src/consciousness/global-workspace.d.ts +149 -0
  80. package/dist/src/consciousness/global-workspace.js +422 -0
  81. package/dist/src/consciousness/index.d.ts +186 -0
  82. package/dist/src/consciousness/index.js +476 -0
  83. package/dist/src/consciousness/phi-calculator.d.ts +119 -0
  84. package/dist/src/consciousness/phi-calculator.js +445 -0
  85. package/dist/src/consciousness/phi-decisions.d.ts +169 -0
  86. package/dist/src/consciousness/phi-decisions.js +383 -0
  87. package/dist/src/consciousness/phi-monitor.d.ts +153 -0
  88. package/dist/src/consciousness/phi-monitor.js +465 -0
  89. package/dist/src/consciousness/types.d.ts +260 -0
  90. package/dist/src/consciousness/types.js +44 -0
  91. package/dist/src/daemon/dream-mode.d.ts +115 -0
  92. package/dist/src/daemon/dream-mode.js +470 -0
  93. package/dist/src/daemon/index.d.ts +162 -0
  94. package/dist/src/daemon/index.js +542 -0
  95. package/dist/src/daemon/maintenance.d.ts +139 -0
  96. package/dist/src/daemon/maintenance.js +549 -0
  97. package/dist/src/daemon/process.d.ts +82 -0
  98. package/dist/src/daemon/process.js +442 -0
  99. package/dist/src/daemon/scheduler.d.ts +90 -0
  100. package/dist/src/daemon/scheduler.js +494 -0
  101. package/dist/src/daemon/types.d.ts +213 -0
  102. package/dist/src/daemon/types.js +50 -0
  103. package/dist/src/epistemic/index.d.ts +74 -0
  104. package/dist/src/epistemic/index.js +225 -0
  105. package/dist/src/grounding/epistemic-stack.d.ts +100 -0
  106. package/dist/src/grounding/epistemic-stack.js +408 -0
  107. package/dist/src/grounding/feedback.d.ts +98 -0
  108. package/dist/src/grounding/feedback.js +276 -0
  109. package/dist/src/grounding/index.d.ts +123 -0
  110. package/dist/src/grounding/index.js +224 -0
  111. package/dist/src/grounding/verifier.d.ts +149 -0
  112. package/dist/src/grounding/verifier.js +484 -0
  113. package/dist/src/healing/detector.d.ts +110 -0
  114. package/dist/src/healing/detector.js +436 -0
  115. package/dist/src/healing/fixer.d.ts +138 -0
  116. package/dist/src/healing/fixer.js +572 -0
  117. package/dist/src/healing/index.d.ts +23 -0
  118. package/dist/src/healing/index.js +43 -0
  119. package/dist/src/hooks/index.d.ts +135 -0
  120. package/dist/src/hooks/index.js +317 -0
  121. package/dist/src/index.d.ts +23 -0
  122. package/dist/src/index.js +1266 -0
  123. package/dist/src/kernel/index.d.ts +155 -0
  124. package/dist/src/kernel/index.js +795 -0
  125. package/dist/src/kernel/invariants.d.ts +153 -0
  126. package/dist/src/kernel/invariants.js +355 -0
  127. package/dist/src/kernel/test-kernel.d.ts +6 -0
  128. package/dist/src/kernel/test-kernel.js +108 -0
  129. package/dist/src/kernel/test-real-mcp.d.ts +10 -0
  130. package/dist/src/kernel/test-real-mcp.js +295 -0
  131. package/dist/src/llm/index.d.ts +146 -0
  132. package/dist/src/llm/index.js +428 -0
  133. package/dist/src/llm/router.d.ts +136 -0
  134. package/dist/src/llm/router.js +510 -0
  135. package/dist/src/mcp/index.d.ts +85 -0
  136. package/dist/src/mcp/index.js +657 -0
  137. package/dist/src/mcp/resilient.d.ts +139 -0
  138. package/dist/src/mcp/resilient.js +417 -0
  139. package/dist/src/memory/cache.d.ts +118 -0
  140. package/dist/src/memory/cache.js +356 -0
  141. package/dist/src/memory/cognitive-workspace.d.ts +231 -0
  142. package/dist/src/memory/cognitive-workspace.js +521 -0
  143. package/dist/src/memory/consolidation.d.ts +99 -0
  144. package/dist/src/memory/consolidation.js +443 -0
  145. package/dist/src/memory/episodic.d.ts +114 -0
  146. package/dist/src/memory/episodic.js +394 -0
  147. package/dist/src/memory/forgetting.d.ts +134 -0
  148. package/dist/src/memory/forgetting.js +324 -0
  149. package/dist/src/memory/index.d.ts +211 -0
  150. package/dist/src/memory/index.js +367 -0
  151. package/dist/src/memory/indexer.d.ts +123 -0
  152. package/dist/src/memory/indexer.js +479 -0
  153. package/dist/src/memory/procedural.d.ts +136 -0
  154. package/dist/src/memory/procedural.js +479 -0
  155. package/dist/src/memory/semantic.d.ts +132 -0
  156. package/dist/src/memory/semantic.js +497 -0
  157. package/dist/src/memory/types.d.ts +193 -0
  158. package/dist/src/memory/types.js +15 -0
  159. package/dist/src/orchestrator.d.ts +65 -0
  160. package/dist/src/orchestrator.js +317 -0
  161. package/dist/src/persistence/index.d.ts +257 -0
  162. package/dist/src/persistence/index.js +763 -0
  163. package/dist/src/pipeline/executor.d.ts +51 -0
  164. package/dist/src/pipeline/executor.js +695 -0
  165. package/dist/src/pipeline/index.d.ts +7 -0
  166. package/dist/src/pipeline/index.js +11 -0
  167. package/dist/src/self-production.d.ts +67 -0
  168. package/dist/src/self-production.js +205 -0
  169. package/dist/src/subagents/executor.d.ts +58 -0
  170. package/dist/src/subagents/executor.js +283 -0
  171. package/dist/src/subagents/index.d.ts +37 -0
  172. package/dist/src/subagents/index.js +53 -0
  173. package/dist/src/subagents/registry.d.ts +23 -0
  174. package/dist/src/subagents/registry.js +167 -0
  175. package/dist/src/subagents/types.d.ts +79 -0
  176. package/dist/src/subagents/types.js +14 -0
  177. package/dist/src/tools/bash.d.ts +139 -0
  178. package/dist/src/tools/bash.js +583 -0
  179. package/dist/src/tools/edit.d.ts +125 -0
  180. package/dist/src/tools/edit.js +424 -0
  181. package/dist/src/tools/git.d.ts +179 -0
  182. package/dist/src/tools/git.js +504 -0
  183. package/dist/src/tools/index.d.ts +21 -0
  184. package/dist/src/tools/index.js +163 -0
  185. package/dist/src/types.d.ts +145 -0
  186. package/dist/src/types.js +7 -0
  187. package/dist/src/world-model/decoder.d.ts +163 -0
  188. package/dist/src/world-model/decoder.js +517 -0
  189. package/dist/src/world-model/digital-twin.d.ts +219 -0
  190. package/dist/src/world-model/digital-twin.js +695 -0
  191. package/dist/src/world-model/encoder.d.ts +141 -0
  192. package/dist/src/world-model/encoder.js +564 -0
  193. package/dist/src/world-model/index.d.ts +221 -0
  194. package/dist/src/world-model/index.js +772 -0
  195. package/dist/src/world-model/predictor.d.ts +161 -0
  196. package/dist/src/world-model/predictor.js +681 -0
  197. package/dist/src/world-model/test-value-jepa.d.ts +8 -0
  198. package/dist/src/world-model/test-value-jepa.js +430 -0
  199. package/dist/src/world-model/types.d.ts +341 -0
  200. package/dist/src/world-model/types.js +69 -0
  201. package/dist/src/world-model/value-jepa.d.ts +247 -0
  202. package/dist/src/world-model/value-jepa.js +622 -0
  203. package/dist/test/brain.test.d.ts +11 -0
  204. package/dist/test/brain.test.js +358 -0
  205. package/dist/test/cli/dispatcher.test.d.ts +4 -0
  206. package/dist/test/cli/dispatcher.test.js +332 -0
  207. package/dist/test/cli/human-loop.test.d.ts +4 -0
  208. package/dist/test/cli/human-loop.test.js +270 -0
  209. package/dist/test/grounding/feedback.test.d.ts +4 -0
  210. package/dist/test/grounding/feedback.test.js +462 -0
  211. package/dist/test/grounding/verifier.test.d.ts +4 -0
  212. package/dist/test/grounding/verifier.test.js +442 -0
  213. package/dist/test/grounding.test.d.ts +6 -0
  214. package/dist/test/grounding.test.js +246 -0
  215. package/dist/test/healing/detector.test.d.ts +4 -0
  216. package/dist/test/healing/detector.test.js +266 -0
  217. package/dist/test/healing/fixer.test.d.ts +4 -0
  218. package/dist/test/healing/fixer.test.js +369 -0
  219. package/dist/test/integration.test.d.ts +5 -0
  220. package/dist/test/integration.test.js +290 -0
  221. package/dist/test/tools/bash.test.d.ts +4 -0
  222. package/dist/test/tools/bash.test.js +348 -0
  223. package/dist/test/tools/edit.test.d.ts +4 -0
  224. package/dist/test/tools/edit.test.js +350 -0
  225. package/dist/test/tools/git.test.d.ts +4 -0
  226. package/dist/test/tools/git.test.js +350 -0
  227. package/package.json +60 -0
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 6.0 - Pipeline Module
4
+ *
5
+ * Exports pipeline execution functionality.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.createPipelineExecutor = exports.PipelineExecutor = void 0;
9
+ var executor_js_1 = require("./executor.js");
10
+ Object.defineProperty(exports, "PipelineExecutor", { enumerable: true, get: function () { return executor_js_1.PipelineExecutor; } });
11
+ Object.defineProperty(exports, "createPipelineExecutor", { enumerable: true, get: function () { return executor_js_1.createPipelineExecutor; } });
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Genesis - Self-Production Module
3
+ *
4
+ * Enables Genesis to create improved versions of itself.
5
+ * This is the core of the autopoietic capability.
6
+ *
7
+ * Self-Production Rules:
8
+ * 1. Triggered upon detection of critical performance improvements
9
+ * 2. Uses existing pipeline to design new versions
10
+ * 3. All new versions validated against invariants
11
+ * 4. System upgrade events generated once verified
12
+ */
13
+ import { SystemSpec } from './types.js';
14
+ export interface SelfProductionSpec {
15
+ currentVersion: string;
16
+ targetVersion: string;
17
+ improvements: Improvement[];
18
+ preserveInvariants: string[];
19
+ }
20
+ export interface Improvement {
21
+ id: string;
22
+ type: 'performance' | 'capability' | 'reliability' | 'efficiency';
23
+ description: string;
24
+ priority: 'critical' | 'high' | 'medium' | 'low';
25
+ estimatedImpact: number;
26
+ }
27
+ export interface ProductionResult {
28
+ success: boolean;
29
+ newVersion?: string;
30
+ changes: string[];
31
+ validationPassed: boolean;
32
+ rollbackAvailable: boolean;
33
+ }
34
+ export declare class SelfProductionEngine {
35
+ private currentVersion;
36
+ private productionHistory;
37
+ private readonly coreInvariants;
38
+ constructor(version?: string);
39
+ /**
40
+ * Analyze system metrics to identify potential improvements
41
+ */
42
+ analyzeForImprovements(metrics: SystemMetrics): Improvement[];
43
+ /**
44
+ * Create a new version of Genesis with specified improvements
45
+ */
46
+ produce(spec: SelfProductionSpec): Promise<ProductionResult>;
47
+ private validateAgainstInvariants;
48
+ private generateImprovement;
49
+ private validateNewVersion;
50
+ /**
51
+ * Generate a SystemSpec for creating an improved Genesis
52
+ */
53
+ generateSelfImprovementSpec(): SystemSpec;
54
+ private incrementVersion;
55
+ getVersion(): string;
56
+ getHistory(): ProductionResult[];
57
+ getInvariants(): string[];
58
+ }
59
+ interface SystemMetrics {
60
+ avgPipelineDuration: number;
61
+ errorRate: number;
62
+ systemsCreated: number;
63
+ cacheHitRate: number;
64
+ hasAdvancedTemplates: boolean;
65
+ }
66
+ export declare function createSelfProductionEngine(version?: string): SelfProductionEngine;
67
+ export {};
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis - Self-Production Module
4
+ *
5
+ * Enables Genesis to create improved versions of itself.
6
+ * This is the core of the autopoietic capability.
7
+ *
8
+ * Self-Production Rules:
9
+ * 1. Triggered upon detection of critical performance improvements
10
+ * 2. Uses existing pipeline to design new versions
11
+ * 3. All new versions validated against invariants
12
+ * 4. System upgrade events generated once verified
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.SelfProductionEngine = void 0;
16
+ exports.createSelfProductionEngine = createSelfProductionEngine;
17
+ // ============================================================================
18
+ // Self-Production Engine
19
+ // ============================================================================
20
+ class SelfProductionEngine {
21
+ currentVersion;
22
+ productionHistory = [];
23
+ // Core invariants that must be preserved during self-production
24
+ coreInvariants = [
25
+ 'Pipeline stages execute sequentially',
26
+ 'MCP orchestration maintains connections',
27
+ 'State machine transitions are valid',
28
+ 'Generated code passes validation',
29
+ 'Self-production preserves all invariants',
30
+ ];
31
+ constructor(version = '1.0.0') {
32
+ this.currentVersion = version;
33
+ }
34
+ // ============================================================================
35
+ // Analysis
36
+ // ============================================================================
37
+ /**
38
+ * Analyze system metrics to identify potential improvements
39
+ */
40
+ analyzeForImprovements(metrics) {
41
+ const improvements = [];
42
+ // Performance improvements
43
+ if (metrics.avgPipelineDuration > 30000) {
44
+ improvements.push({
45
+ id: 'perf-001',
46
+ type: 'performance',
47
+ description: 'Parallelize independent MCP calls',
48
+ priority: 'high',
49
+ estimatedImpact: 0.4,
50
+ });
51
+ }
52
+ // Reliability improvements
53
+ if (metrics.errorRate > 0.05) {
54
+ improvements.push({
55
+ id: 'rel-001',
56
+ type: 'reliability',
57
+ description: 'Add retry logic with exponential backoff',
58
+ priority: 'critical',
59
+ estimatedImpact: 0.3,
60
+ });
61
+ }
62
+ // Capability improvements
63
+ if (metrics.systemsCreated > 10 && !metrics.hasAdvancedTemplates) {
64
+ improvements.push({
65
+ id: 'cap-001',
66
+ type: 'capability',
67
+ description: 'Generate advanced system templates from history',
68
+ priority: 'medium',
69
+ estimatedImpact: 0.2,
70
+ });
71
+ }
72
+ // Efficiency improvements
73
+ if (metrics.cacheHitRate < 0.5) {
74
+ improvements.push({
75
+ id: 'eff-001',
76
+ type: 'efficiency',
77
+ description: 'Implement semantic caching for research results',
78
+ priority: 'medium',
79
+ estimatedImpact: 0.25,
80
+ });
81
+ }
82
+ return improvements;
83
+ }
84
+ // ============================================================================
85
+ // Production
86
+ // ============================================================================
87
+ /**
88
+ * Create a new version of Genesis with specified improvements
89
+ */
90
+ async produce(spec) {
91
+ console.log(`[SelfProduction] Starting production: ${spec.currentVersion} → ${spec.targetVersion}`);
92
+ // Step 1: Validate improvements don't violate invariants
93
+ const invariantCheck = this.validateAgainstInvariants(spec.improvements);
94
+ if (!invariantCheck.valid) {
95
+ return {
96
+ success: false,
97
+ changes: [],
98
+ validationPassed: false,
99
+ rollbackAvailable: false,
100
+ };
101
+ }
102
+ // Step 2: Generate improvement code
103
+ const changes = [];
104
+ for (const improvement of spec.improvements) {
105
+ const change = await this.generateImprovement(improvement);
106
+ changes.push(change);
107
+ }
108
+ // Step 3: Validate new version
109
+ const validationPassed = await this.validateNewVersion(changes);
110
+ if (validationPassed) {
111
+ this.currentVersion = spec.targetVersion;
112
+ const result = {
113
+ success: true,
114
+ newVersion: spec.targetVersion,
115
+ changes,
116
+ validationPassed: true,
117
+ rollbackAvailable: true,
118
+ };
119
+ this.productionHistory.push(result);
120
+ return result;
121
+ }
122
+ return {
123
+ success: false,
124
+ changes,
125
+ validationPassed: false,
126
+ rollbackAvailable: true,
127
+ };
128
+ }
129
+ validateAgainstInvariants(improvements) {
130
+ const violations = [];
131
+ // Check each improvement doesn't break invariants
132
+ for (const improvement of improvements) {
133
+ // In a real system, this would analyze the code changes
134
+ // For now, we assume all improvements preserve invariants
135
+ }
136
+ return { valid: violations.length === 0, violations };
137
+ }
138
+ async generateImprovement(improvement) {
139
+ // This would use OpenAI MCP to generate actual code improvements
140
+ return `// Improvement: ${improvement.id}\n// ${improvement.description}`;
141
+ }
142
+ async validateNewVersion(changes) {
143
+ // Run tests, check invariants, verify functionality
144
+ // In a real system, this would be comprehensive
145
+ return true;
146
+ }
147
+ // ============================================================================
148
+ // Templates
149
+ // ============================================================================
150
+ /**
151
+ * Generate a SystemSpec for creating an improved Genesis
152
+ */
153
+ generateSelfImprovementSpec() {
154
+ const nextVersion = this.incrementVersion(this.currentVersion);
155
+ return {
156
+ name: `genesis-${nextVersion}`,
157
+ description: 'Self-improved version of Genesis System Creator',
158
+ type: 'autopoietic',
159
+ features: [
160
+ 'state-machine',
161
+ 'events',
162
+ 'mcp-orchestration',
163
+ 'self-production',
164
+ 'invariant-checking',
165
+ ],
166
+ inspirations: [
167
+ 'autopoiesis theory',
168
+ 'maturana-varela',
169
+ 'free energy principle',
170
+ ],
171
+ };
172
+ }
173
+ incrementVersion(version) {
174
+ const parts = version.split('.').map(Number);
175
+ parts[2]++; // Increment patch
176
+ if (parts[2] >= 10) {
177
+ parts[2] = 0;
178
+ parts[1]++;
179
+ }
180
+ if (parts[1] >= 10) {
181
+ parts[1] = 0;
182
+ parts[0]++;
183
+ }
184
+ return parts.join('.');
185
+ }
186
+ // ============================================================================
187
+ // Status
188
+ // ============================================================================
189
+ getVersion() {
190
+ return this.currentVersion;
191
+ }
192
+ getHistory() {
193
+ return [...this.productionHistory];
194
+ }
195
+ getInvariants() {
196
+ return [...this.coreInvariants];
197
+ }
198
+ }
199
+ exports.SelfProductionEngine = SelfProductionEngine;
200
+ // ============================================================================
201
+ // Export
202
+ // ============================================================================
203
+ function createSelfProductionEngine(version) {
204
+ return new SelfProductionEngine(version);
205
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Genesis v7.4 - Subagent Executor
3
+ *
4
+ * Executes subagents in isolated contexts with tool restrictions.
5
+ */
6
+ import { TaskRequest, TaskResult, BackgroundTask, SubagentEventHandler, SubagentConfig } from './types.js';
7
+ import { ToolDispatcher } from '../cli/dispatcher.js';
8
+ export declare class SubagentExecutor {
9
+ private config;
10
+ private runningTasks;
11
+ private eventHandlers;
12
+ private dispatcher;
13
+ constructor(config?: Partial<SubagentConfig>);
14
+ /**
15
+ * Set the tool dispatcher for subagents
16
+ */
17
+ setDispatcher(dispatcher: ToolDispatcher): void;
18
+ /**
19
+ * Execute a task synchronously
20
+ */
21
+ execute(request: TaskRequest): Promise<TaskResult>;
22
+ /**
23
+ * Execute a task in background
24
+ */
25
+ executeBackground(request: TaskRequest): Promise<string>;
26
+ /**
27
+ * Get background task status
28
+ */
29
+ getTask(taskId: string): BackgroundTask | undefined;
30
+ /**
31
+ * Get all tasks
32
+ */
33
+ getTasks(): BackgroundTask[];
34
+ /**
35
+ * Get running tasks
36
+ */
37
+ getRunningTasks(): BackgroundTask[];
38
+ /**
39
+ * Wait for a background task to complete
40
+ */
41
+ waitForTask(taskId: string, timeout?: number): Promise<TaskResult>;
42
+ /**
43
+ * Cancel a background task
44
+ */
45
+ cancelTask(taskId: string): boolean;
46
+ /**
47
+ * Subscribe to events
48
+ */
49
+ on(handler: SubagentEventHandler): () => void;
50
+ private runBackgroundTask;
51
+ private createSubagentLLM;
52
+ private buildSystemPrompt;
53
+ private runSubagent;
54
+ private timeoutPromise;
55
+ private emit;
56
+ }
57
+ export declare function getSubagentExecutor(): SubagentExecutor;
58
+ export declare function resetSubagentExecutor(): void;
@@ -0,0 +1,283 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis v7.4 - Subagent Executor
4
+ *
5
+ * Executes subagents in isolated contexts with tool restrictions.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.SubagentExecutor = void 0;
9
+ exports.getSubagentExecutor = getSubagentExecutor;
10
+ exports.resetSubagentExecutor = resetSubagentExecutor;
11
+ const crypto_1 = require("crypto");
12
+ const types_js_1 = require("./types.js");
13
+ const registry_js_1 = require("./registry.js");
14
+ const index_js_1 = require("../llm/index.js");
15
+ // ============================================================================
16
+ // Subagent Executor
17
+ // ============================================================================
18
+ class SubagentExecutor {
19
+ config;
20
+ runningTasks = new Map();
21
+ eventHandlers = new Set();
22
+ dispatcher = null;
23
+ constructor(config = {}) {
24
+ this.config = { ...types_js_1.DEFAULT_SUBAGENT_CONFIG, ...config };
25
+ }
26
+ /**
27
+ * Set the tool dispatcher for subagents
28
+ */
29
+ setDispatcher(dispatcher) {
30
+ this.dispatcher = dispatcher;
31
+ }
32
+ /**
33
+ * Execute a task synchronously
34
+ */
35
+ async execute(request) {
36
+ const taskId = (0, crypto_1.randomUUID)().slice(0, 8);
37
+ const startTime = Date.now();
38
+ // Get subagent definition
39
+ const subagent = (0, registry_js_1.getSubagent)(request.subagentType);
40
+ if (!subagent) {
41
+ return {
42
+ taskId,
43
+ subagentType: request.subagentType,
44
+ success: false,
45
+ error: `Unknown subagent type: ${request.subagentType}. Available: ${Object.keys(registry_js_1.BUILTIN_SUBAGENTS).join(', ')}`,
46
+ duration: Date.now() - startTime,
47
+ };
48
+ }
49
+ this.emit({
50
+ type: 'task_start',
51
+ taskId,
52
+ timestamp: new Date(),
53
+ data: { description: request.description, subagentType: request.subagentType },
54
+ });
55
+ try {
56
+ // Create isolated LLM bridge for subagent
57
+ const llm = this.createSubagentLLM(request.model || subagent.model);
58
+ // Build system prompt with tool restrictions
59
+ const systemPrompt = this.buildSystemPrompt(subagent.systemPrompt, subagent.tools);
60
+ // Execute with timeout
61
+ const timeout = subagent.timeout || this.config.defaultTimeout;
62
+ const result = await Promise.race([
63
+ this.runSubagent(llm, systemPrompt, request.prompt, subagent.tools, taskId),
64
+ this.timeoutPromise(timeout, taskId),
65
+ ]);
66
+ this.emit({
67
+ type: 'task_complete',
68
+ taskId,
69
+ timestamp: new Date(),
70
+ data: { success: true },
71
+ });
72
+ return {
73
+ taskId,
74
+ subagentType: request.subagentType,
75
+ success: true,
76
+ result,
77
+ duration: Date.now() - startTime,
78
+ };
79
+ }
80
+ catch (error) {
81
+ const errorMessage = error instanceof Error ? error.message : String(error);
82
+ this.emit({
83
+ type: 'task_error',
84
+ taskId,
85
+ timestamp: new Date(),
86
+ data: { error: errorMessage },
87
+ });
88
+ return {
89
+ taskId,
90
+ subagentType: request.subagentType,
91
+ success: false,
92
+ error: errorMessage,
93
+ duration: Date.now() - startTime,
94
+ };
95
+ }
96
+ }
97
+ /**
98
+ * Execute a task in background
99
+ */
100
+ async executeBackground(request) {
101
+ const taskId = (0, crypto_1.randomUUID)().slice(0, 8);
102
+ // Check concurrent limit
103
+ const runningCount = Array.from(this.runningTasks.values())
104
+ .filter(t => t.status === 'running').length;
105
+ if (runningCount >= this.config.maxConcurrent) {
106
+ throw new Error(`Max concurrent tasks (${this.config.maxConcurrent}) reached`);
107
+ }
108
+ // Create background task entry
109
+ const task = {
110
+ taskId,
111
+ description: request.description,
112
+ subagentType: request.subagentType,
113
+ status: 'pending',
114
+ startTime: Date.now(),
115
+ output: [],
116
+ };
117
+ this.runningTasks.set(taskId, task);
118
+ // Start execution in background
119
+ this.runBackgroundTask(taskId, request).catch(error => {
120
+ const t = this.runningTasks.get(taskId);
121
+ if (t) {
122
+ t.status = 'failed';
123
+ t.endTime = Date.now();
124
+ t.result = {
125
+ taskId,
126
+ subagentType: request.subagentType,
127
+ success: false,
128
+ error: error instanceof Error ? error.message : String(error),
129
+ duration: Date.now() - t.startTime,
130
+ };
131
+ }
132
+ });
133
+ return taskId;
134
+ }
135
+ /**
136
+ * Get background task status
137
+ */
138
+ getTask(taskId) {
139
+ return this.runningTasks.get(taskId);
140
+ }
141
+ /**
142
+ * Get all tasks
143
+ */
144
+ getTasks() {
145
+ return Array.from(this.runningTasks.values());
146
+ }
147
+ /**
148
+ * Get running tasks
149
+ */
150
+ getRunningTasks() {
151
+ return this.getTasks().filter(t => t.status === 'running');
152
+ }
153
+ /**
154
+ * Wait for a background task to complete
155
+ */
156
+ async waitForTask(taskId, timeout) {
157
+ const task = this.runningTasks.get(taskId);
158
+ if (!task) {
159
+ throw new Error(`Task not found: ${taskId}`);
160
+ }
161
+ const maxWait = timeout || this.config.defaultTimeout;
162
+ const startWait = Date.now();
163
+ while (task.status === 'pending' || task.status === 'running') {
164
+ if (Date.now() - startWait > maxWait) {
165
+ throw new Error(`Timeout waiting for task ${taskId}`);
166
+ }
167
+ await new Promise(resolve => setTimeout(resolve, 100));
168
+ }
169
+ if (!task.result) {
170
+ throw new Error(`Task ${taskId} completed without result`);
171
+ }
172
+ return task.result;
173
+ }
174
+ /**
175
+ * Cancel a background task
176
+ */
177
+ cancelTask(taskId) {
178
+ const task = this.runningTasks.get(taskId);
179
+ if (!task || task.status !== 'running') {
180
+ return false;
181
+ }
182
+ task.status = 'cancelled';
183
+ task.endTime = Date.now();
184
+ this.emit({
185
+ type: 'task_cancelled',
186
+ taskId,
187
+ timestamp: new Date(),
188
+ });
189
+ return true;
190
+ }
191
+ /**
192
+ * Subscribe to events
193
+ */
194
+ on(handler) {
195
+ this.eventHandlers.add(handler);
196
+ return () => this.eventHandlers.delete(handler);
197
+ }
198
+ // ============================================================================
199
+ // Private Methods
200
+ // ============================================================================
201
+ async runBackgroundTask(taskId, request) {
202
+ const task = this.runningTasks.get(taskId);
203
+ if (!task)
204
+ return;
205
+ task.status = 'running';
206
+ const result = await this.execute(request);
207
+ task.status = result.success ? 'completed' : 'failed';
208
+ task.endTime = Date.now();
209
+ task.result = result;
210
+ }
211
+ createSubagentLLM(modelTier) {
212
+ // Map tier to actual model
213
+ const modelMap = {
214
+ fast: 'qwen2.5-coder', // Local, fast
215
+ balanced: 'mistral', // Local, balanced
216
+ powerful: 'gpt-4o', // Cloud, powerful
217
+ };
218
+ const model = modelMap[modelTier || 'balanced'];
219
+ // Use Ollama for fast/balanced, OpenAI for powerful
220
+ if (modelTier === 'powerful' && process.env.OPENAI_API_KEY) {
221
+ return (0, index_js_1.createLLMBridge)({ provider: 'openai', model });
222
+ }
223
+ return (0, index_js_1.createLLMBridge)({ provider: 'ollama', model });
224
+ }
225
+ buildSystemPrompt(basePrompt, allowedTools) {
226
+ const toolsSection = allowedTools.includes('*')
227
+ ? 'You have access to ALL tools.'
228
+ : `You have access to these tools ONLY: ${allowedTools.join(', ')}`;
229
+ return `${basePrompt}
230
+
231
+ ## Tool Access
232
+ ${toolsSection}
233
+
234
+ ## Response Format
235
+ After completing your task, provide a clear summary of:
236
+ 1. What you found/did
237
+ 2. Key results with file:line references where applicable
238
+ 3. Any issues or warnings`;
239
+ }
240
+ async runSubagent(llm, systemPrompt, userPrompt, _allowedTools, taskId) {
241
+ // Simple single-turn execution for now
242
+ // TODO: Multi-turn with tool execution loop
243
+ const response = await llm.chat(userPrompt, systemPrompt);
244
+ this.emit({
245
+ type: 'task_progress',
246
+ taskId,
247
+ timestamp: new Date(),
248
+ data: { tokensUsed: response.usage },
249
+ });
250
+ return response.content;
251
+ }
252
+ timeoutPromise(ms, taskId) {
253
+ return new Promise((_, reject) => {
254
+ setTimeout(() => {
255
+ reject(new Error(`Task ${taskId} timed out after ${ms}ms`));
256
+ }, ms);
257
+ });
258
+ }
259
+ emit(event) {
260
+ for (const handler of this.eventHandlers) {
261
+ try {
262
+ handler(event);
263
+ }
264
+ catch {
265
+ // Ignore handler errors
266
+ }
267
+ }
268
+ }
269
+ }
270
+ exports.SubagentExecutor = SubagentExecutor;
271
+ // ============================================================================
272
+ // Singleton
273
+ // ============================================================================
274
+ let executorInstance = null;
275
+ function getSubagentExecutor() {
276
+ if (!executorInstance) {
277
+ executorInstance = new SubagentExecutor();
278
+ }
279
+ return executorInstance;
280
+ }
281
+ function resetSubagentExecutor() {
282
+ executorInstance = null;
283
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Genesis v7.4 - Subagent System
3
+ *
4
+ * Parallel subprocess execution for complex tasks.
5
+ * Equivalent to Claude Code's Task tool.
6
+ *
7
+ * Usage:
8
+ * ```typescript
9
+ * import { getSubagentExecutor, TaskRequest } from './subagents/index.js';
10
+ *
11
+ * const executor = getSubagentExecutor();
12
+ *
13
+ * // Synchronous execution
14
+ * const result = await executor.execute({
15
+ * description: 'Find auth handlers',
16
+ * prompt: 'Search for authentication handling code',
17
+ * subagentType: 'explore',
18
+ * });
19
+ *
20
+ * // Background execution
21
+ * const taskId = await executor.executeBackground({
22
+ * description: 'Research OAuth patterns',
23
+ * prompt: 'Find best practices for OAuth2 implementation',
24
+ * subagentType: 'research',
25
+ * runInBackground: true,
26
+ * });
27
+ *
28
+ * // Check status
29
+ * const task = executor.getTask(taskId);
30
+ *
31
+ * // Wait for completion
32
+ * const result = await executor.waitForTask(taskId);
33
+ * ```
34
+ */
35
+ export * from './types.js';
36
+ export * from './registry.js';
37
+ export * from './executor.js';