erosolar-cli 2.1.294 → 2.1.296

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.
@@ -1,947 +0,0 @@
1
- /**
2
- * Real AGI Core - Pure Tool-Based Autonomous Intelligence
3
- *
4
- * NO INTENTS - Only tools
5
- * NO SIMULATIONS - Everything executes for real
6
- * NO CATEGORIES - Just understanding and execution
7
- *
8
- * This mirrors how Claude Code works:
9
- * 1. Understand the prompt
10
- * 2. Think about what tools to use
11
- * 3. Execute tools in sequence
12
- * 4. Display results in Claude Code style
13
- *
14
- * Handles ANY prompt: software, research, legal, finance, defense, or anything else
15
- */
16
- import * as fs from 'fs';
17
- import * as path from 'path';
18
- import { execSync } from 'child_process';
19
- import { getToolEmbeddings } from './toolEmbeddings.js';
20
- export class RealAGI {
21
- workingDir;
22
- memory;
23
- memoryPath;
24
- tools;
25
- embeddings;
26
- displayCallback = null;
27
- constructor(workingDir) {
28
- this.workingDir = workingDir || process.cwd();
29
- this.memoryPath = path.join(this.workingDir, '.erosolar', 'real-agi-memory.json');
30
- this.memory = this.loadMemory();
31
- this.tools = this.createRealTools();
32
- this.embeddings = getToolEmbeddings(this.workingDir);
33
- this.detectProject();
34
- }
35
- /** Set callback for streaming output through the shell UI */
36
- setDisplayCallback(callback) {
37
- this.displayCallback = callback;
38
- }
39
- /** Stream a message through the UI if callback is set */
40
- streamToUI(message, type = 'step') {
41
- if (this.displayCallback) {
42
- this.displayCallback(message, type);
43
- }
44
- }
45
- // ==========================================================================
46
- // MEMORY
47
- // ==========================================================================
48
- loadMemory() {
49
- try {
50
- if (fs.existsSync(this.memoryPath)) {
51
- return JSON.parse(fs.readFileSync(this.memoryPath, 'utf-8'));
52
- }
53
- }
54
- catch { }
55
- return {
56
- successfulApproaches: [],
57
- projectInfo: { type: 'unknown', buildCmd: null, testCmd: null, lintCmd: null },
58
- };
59
- }
60
- saveMemory() {
61
- try {
62
- const dir = path.dirname(this.memoryPath);
63
- if (!fs.existsSync(dir))
64
- fs.mkdirSync(dir, { recursive: true });
65
- fs.writeFileSync(this.memoryPath, JSON.stringify(this.memory, null, 2));
66
- }
67
- catch { }
68
- }
69
- detectProject() {
70
- const pkgPath = path.join(this.workingDir, 'package.json');
71
- if (fs.existsSync(pkgPath)) {
72
- try {
73
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
74
- this.memory.projectInfo.type = 'node';
75
- this.memory.projectInfo.testCmd = pkg.scripts?.test ? 'npm test' : null;
76
- this.memory.projectInfo.lintCmd = pkg.scripts?.lint ? 'npm run lint' : null;
77
- this.memory.projectInfo.buildCmd = pkg.scripts?.build ? 'npm run build' : null;
78
- }
79
- catch { }
80
- }
81
- if (fs.existsSync(path.join(this.workingDir, 'pyproject.toml'))) {
82
- this.memory.projectInfo.type = 'python';
83
- this.memory.projectInfo.testCmd = 'pytest';
84
- }
85
- if (fs.existsSync(path.join(this.workingDir, 'Cargo.toml'))) {
86
- this.memory.projectInfo.type = 'rust';
87
- this.memory.projectInfo.testCmd = 'cargo test';
88
- this.memory.projectInfo.buildCmd = 'cargo build';
89
- }
90
- this.saveMemory();
91
- }
92
- // ==========================================================================
93
- // REAL TOOLS - These actually execute
94
- // ==========================================================================
95
- createRealTools() {
96
- const tools = new Map();
97
- // Bash - executes shell commands
98
- tools.set('Bash', {
99
- name: 'Bash',
100
- execute: async (args) => {
101
- const start = Date.now();
102
- const command = args.command;
103
- try {
104
- const output = execSync(command, {
105
- cwd: this.workingDir,
106
- encoding: 'utf-8',
107
- timeout: 120000,
108
- maxBuffer: 10 * 1024 * 1024,
109
- });
110
- return { success: true, output: output.slice(0, 5000), duration: Date.now() - start };
111
- }
112
- catch (e) {
113
- const error = e;
114
- return {
115
- success: false,
116
- output: error.stdout || '',
117
- error: error.stderr || error.message || 'Command failed',
118
- duration: Date.now() - start,
119
- };
120
- }
121
- },
122
- });
123
- // Read - reads files
124
- tools.set('Read', {
125
- name: 'Read',
126
- execute: async (args) => {
127
- const start = Date.now();
128
- const filePath = args.file_path;
129
- const fullPath = path.isAbsolute(filePath) ? filePath : path.join(this.workingDir, filePath);
130
- try {
131
- const content = fs.readFileSync(fullPath, 'utf-8');
132
- return { success: true, output: content.slice(0, 10000), duration: Date.now() - start };
133
- }
134
- catch (e) {
135
- return { success: false, output: '', error: e.message, duration: Date.now() - start };
136
- }
137
- },
138
- });
139
- // Write - writes files
140
- tools.set('Write', {
141
- name: 'Write',
142
- execute: async (args) => {
143
- const start = Date.now();
144
- const filePath = args.file_path;
145
- const content = args.content;
146
- const fullPath = path.isAbsolute(filePath) ? filePath : path.join(this.workingDir, filePath);
147
- try {
148
- const dir = path.dirname(fullPath);
149
- if (!fs.existsSync(dir))
150
- fs.mkdirSync(dir, { recursive: true });
151
- fs.writeFileSync(fullPath, content);
152
- return { success: true, output: `Written ${content.length} bytes to ${filePath}`, duration: Date.now() - start, artifacts: [fullPath] };
153
- }
154
- catch (e) {
155
- return { success: false, output: '', error: e.message, duration: Date.now() - start };
156
- }
157
- },
158
- });
159
- // Glob - finds files
160
- tools.set('Glob', {
161
- name: 'Glob',
162
- execute: async (args) => {
163
- const start = Date.now();
164
- const pattern = args.pattern;
165
- try {
166
- // Use find command for glob-like behavior
167
- const cmd = `find . -type f -name "${pattern.replace('**/', '')}" 2>/dev/null | head -50`;
168
- const output = execSync(cmd, { cwd: this.workingDir, encoding: 'utf-8' });
169
- return { success: true, output, duration: Date.now() - start };
170
- }
171
- catch (e) {
172
- return { success: false, output: '', error: e.message, duration: Date.now() - start };
173
- }
174
- },
175
- });
176
- // Grep - searches content
177
- tools.set('Grep', {
178
- name: 'Grep',
179
- execute: async (args) => {
180
- const start = Date.now();
181
- const pattern = args.pattern;
182
- const searchPath = args.path || '.';
183
- try {
184
- const cmd = `grep -rn "${pattern}" ${searchPath} 2>/dev/null | head -100`;
185
- const output = execSync(cmd, { cwd: this.workingDir, encoding: 'utf-8' });
186
- return { success: true, output, duration: Date.now() - start };
187
- }
188
- catch {
189
- return { success: true, output: 'No matches found', duration: Date.now() - start };
190
- }
191
- },
192
- });
193
- // Edit - edits files (simplified - reads, modifies, writes)
194
- tools.set('Edit', {
195
- name: 'Edit',
196
- execute: async (args) => {
197
- const start = Date.now();
198
- const filePath = args.file_path;
199
- const oldStr = args.old_string;
200
- const newStr = args.new_string;
201
- const fullPath = path.isAbsolute(filePath) ? filePath : path.join(this.workingDir, filePath);
202
- try {
203
- let content = fs.readFileSync(fullPath, 'utf-8');
204
- if (!content.includes(oldStr)) {
205
- return { success: false, output: '', error: 'Old string not found in file', duration: Date.now() - start };
206
- }
207
- content = content.replace(oldStr, newStr);
208
- fs.writeFileSync(fullPath, content);
209
- return { success: true, output: `Edited ${filePath}`, duration: Date.now() - start, artifacts: [fullPath] };
210
- }
211
- catch (e) {
212
- return { success: false, output: '', error: e.message, duration: Date.now() - start };
213
- }
214
- },
215
- });
216
- // WebSearch - searches the web (simulated with curl to a search API or just returns search suggestion)
217
- tools.set('WebSearch', {
218
- name: 'WebSearch',
219
- execute: async (args) => {
220
- const start = Date.now();
221
- const query = args.query;
222
- // In real implementation, this would call a search API
223
- // For now, we acknowledge the search request
224
- return {
225
- success: true,
226
- output: `Search query prepared: "${query}"\nTo execute, use web browser or search API integration.`,
227
- duration: Date.now() - start,
228
- };
229
- },
230
- });
231
- // Think - explicit thinking step (outputs thinking process)
232
- tools.set('Think', {
233
- name: 'Think',
234
- execute: async (args) => {
235
- const start = Date.now();
236
- const thought = args.thought;
237
- return { success: true, output: thought, duration: Date.now() - start };
238
- },
239
- });
240
- return tools;
241
- }
242
- // ==========================================================================
243
- // EMBEDDINGS-BASED TOOL SEARCH
244
- // ==========================================================================
245
- /**
246
- * Search for relevant tools using embeddings (dot product similarity)
247
- */
248
- async searchTools(prompt, topK = 5) {
249
- return this.embeddings.search(prompt, topK);
250
- }
251
- /**
252
- * Get recommended tools for a prompt using embeddings
253
- */
254
- async getRecommendedTools(prompt) {
255
- return this.embeddings.recommendTools(prompt);
256
- }
257
- /**
258
- * Format tool search results
259
- */
260
- async formatToolSearch(prompt) {
261
- const matches = await this.embeddings.search(prompt, 5);
262
- return this.embeddings.formatSearchResults(matches);
263
- }
264
- // ==========================================================================
265
- // UNDERSTANDING - No intents, just figure out what tools to use
266
- // ==========================================================================
267
- /**
268
- * Understand any prompt and figure out what tools to run
269
- * This is the core AGI function - no intents, just tool planning
270
- */
271
- understand(prompt) {
272
- const lower = prompt.toLowerCase();
273
- const thinking = [];
274
- const steps = [];
275
- let stepId = 0;
276
- const addStep = (tool, args, description, deps = []) => {
277
- const id = `step-${stepId++}`;
278
- steps.push({ id, tool, args, description, dependsOn: deps, status: 'pending' });
279
- return id;
280
- };
281
- // Think about what we're doing
282
- thinking.push(`Understanding prompt: "${prompt}"`);
283
- // ========================================================================
284
- // SOFTWARE ENGINEERING PATTERNS
285
- // ========================================================================
286
- if (/fix|bug|error|broken|crash|fail/i.test(lower)) {
287
- thinking.push('This looks like bug fixing - I should run diagnostics first');
288
- const lintId = addStep('Bash', { command: this.memory.projectInfo.lintCmd || 'npm run lint 2>&1 || true' }, 'Run linter to find issues');
289
- const typeId = addStep('Bash', { command: 'npx tsc --noEmit 2>&1 || true' }, 'Check for type errors');
290
- const testId = addStep('Bash', { command: this.memory.projectInfo.testCmd || 'npm test 2>&1 || true' }, 'Run tests to find failures');
291
- const todoId = addStep('Grep', { pattern: 'TODO|FIXME|BUG|HACK', path: 'src' }, 'Search for known issues');
292
- thinking.push('After diagnostics, I can analyze and fix the issues');
293
- addStep('Think', { thought: 'Analyzing diagnostic results to prioritize fixes...' }, 'Analyze findings', [lintId, typeId, testId, todoId]);
294
- }
295
- // Feature addition
296
- else if (/add|create|implement|build|new|feature/i.test(lower)) {
297
- thinking.push('This is about adding something new - I should understand the codebase first');
298
- const exploreId = addStep('Bash', { command: 'find src -name "*.ts" -o -name "*.js" | head -20' }, 'Explore codebase structure');
299
- const pkgId = addStep('Read', { file_path: 'package.json' }, 'Read project configuration');
300
- thinking.push('Then I can plan and implement the feature');
301
- addStep('Think', { thought: 'Planning implementation based on codebase analysis...' }, 'Plan implementation', [exploreId, pkgId]);
302
- }
303
- // Testing
304
- else if (/test|spec|coverage/i.test(lower)) {
305
- thinking.push('This is about testing');
306
- addStep('Bash', { command: this.memory.projectInfo.testCmd || 'npm test 2>&1' }, 'Run test suite');
307
- }
308
- // Security
309
- else if (/security|vulnerab|audit|pentest|hack|exploit|cyber|attack/i.test(lower)) {
310
- thinking.push('This is a security-related task');
311
- const auditId = addStep('Bash', { command: 'npm audit 2>&1 || true' }, 'Audit dependencies for vulnerabilities');
312
- const secretsId = addStep('Grep', { pattern: 'password|secret|api.key|token', path: '.' }, 'Search for hardcoded secrets');
313
- const evalId = addStep('Grep', { pattern: 'eval\\(|exec\\(|innerHTML', path: 'src' }, 'Search for dangerous patterns');
314
- addStep('Think', { thought: 'Analyzing security findings...' }, 'Analyze security results', [auditId, secretsId, evalId]);
315
- }
316
- // DevOps (but not infrastructure analysis)
317
- else if (/devops|ci\/cd|pipeline|docker|kubernetes|deploy|k8s|helm|terraform/i.test(lower) && !/infrastructure.*(analysis|assessment|destruction|attack)/i.test(lower)) {
318
- thinking.push('This is a DevOps task');
319
- addStep('Bash', { command: 'ls -la .github/workflows/ 2>/dev/null || echo "No GitHub workflows"' }, 'Check CI/CD configuration');
320
- addStep('Bash', { command: 'cat Dockerfile 2>/dev/null || echo "No Dockerfile"' }, 'Check Docker configuration');
321
- addStep('Bash', { command: 'cat docker-compose.yml 2>/dev/null || echo "No docker-compose"' }, 'Check Docker Compose');
322
- }
323
- // ========================================================================
324
- // RESEARCH & SCIENCE PATTERNS
325
- // ========================================================================
326
- else if (/cure|cancer|research|experiment|clinical|biomedical|genom/i.test(lower)) {
327
- thinking.push('This is a research/science task - I will set up analysis tools');
328
- addStep('Think', { thought: 'Research task identified. Building computational pipeline...' }, 'Define research scope');
329
- addStep('WebSearch', { query: `${prompt} research papers methods` }, 'Search for relevant research');
330
- addStep('Bash', { command: 'python3 --version 2>/dev/null || echo "Python not found"' }, 'Check Python environment');
331
- addStep('Write', { file_path: 'research_pipeline.py', content: `# Research Pipeline for: ${prompt}\n# Generated by AGI\n\nimport pandas as pd\nimport numpy as np\n\n# TODO: Implement analysis\nprint("Research pipeline initialized")` }, 'Create research pipeline scaffold');
332
- }
333
- // Data Science
334
- else if (/data|ml|machine.learning|model|neural|statistic/i.test(lower)) {
335
- thinking.push('This is a data science task');
336
- addStep('Bash', { command: 'python3 -c "import pandas; import numpy; import sklearn; print(\'ML libs OK\')" 2>&1 || pip install pandas numpy scikit-learn' }, 'Check/install ML libraries');
337
- addStep('Write', { file_path: 'analysis.py', content: `# Data Analysis for: ${prompt}\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\n# TODO: Load data and build model` }, 'Create analysis scaffold');
338
- }
339
- // ========================================================================
340
- // LEGAL PATTERNS
341
- // ========================================================================
342
- else if (/sue|lawsuit|litigation|legal|court|attorney|lawyer|contract|complaint/i.test(lower)) {
343
- thinking.push('This is a legal task - I will set up document generation');
344
- // Extract defendant if present
345
- const defendantMatch = lower.match(/sue\s+(\w+)/i) || lower.match(/against\s+(\w+)/i);
346
- const defendant = defendantMatch ? defendantMatch[1] : 'defendant';
347
- addStep('Think', { thought: `Legal action against ${defendant}. Preparing document automation...` }, 'Identify legal framework');
348
- addStep('WebSearch', { query: `federal court complaint requirements ${defendant}` }, 'Research legal requirements');
349
- addStep('Write', {
350
- file_path: 'legal/complaint_draft.md',
351
- content: `# COMPLAINT\n\n## IN THE UNITED STATES DISTRICT COURT\n\n### PLAINTIFF\nvs.\n\n### ${defendant.toUpperCase()} (Defendant)\n\n---\n\n## JURISDICTION\n[To be completed]\n\n## FACTS\n[To be completed]\n\n## CAUSES OF ACTION\n[To be completed]\n\n## PRAYER FOR RELIEF\n[To be completed]\n\n---\nGenerated by AGI Legal Document System`,
352
- }, 'Draft complaint document');
353
- addStep('Write', {
354
- file_path: 'legal/discovery_plan.md',
355
- content: `# Discovery Plan\n\n## Interrogatories\n1. [To be drafted]\n\n## Document Requests\n1. [To be drafted]\n\n## Depositions\n1. [To be scheduled]`,
356
- }, 'Create discovery plan');
357
- }
358
- // ========================================================================
359
- // FINANCE PATTERNS
360
- // ========================================================================
361
- else if (/accounting|bookkeeping|financ|tax|ledger|budget|invoice|payroll/i.test(lower)) {
362
- thinking.push('This is a finance/accounting task');
363
- addStep('Think', { thought: 'Financial task identified. Setting up accounting tools...' }, 'Define financial scope');
364
- addStep('Bash', { command: 'python3 -c "import pandas; print(\'pandas OK\')" 2>&1 || pip install pandas openpyxl' }, 'Check financial libraries');
365
- addStep('Write', {
366
- file_path: 'finance/ledger.py',
367
- content: `# Financial Ledger System\nimport pandas as pd\nfrom datetime import datetime\n\nclass Ledger:\n def __init__(self):\n self.transactions = pd.DataFrame(columns=['date', 'description', 'debit', 'credit', 'account'])\n \n def add_entry(self, desc, debit=0, credit=0, account='general'):\n self.transactions = pd.concat([self.transactions, pd.DataFrame([{\n 'date': datetime.now(),\n 'description': desc,\n 'debit': debit,\n 'credit': credit,\n 'account': account\n }])], ignore_index=True)\n \n def balance(self):\n return self.transactions['debit'].sum() - self.transactions['credit'].sum()\n\nif __name__ == '__main__':\n ledger = Ledger()\n print('Ledger initialized')`,
368
- }, 'Create ledger system');
369
- }
370
- // ========================================================================
371
- // DEFENSE PATTERNS
372
- // ========================================================================
373
- else if (/fighter|drone|missile|ballistic|reentry|carrier|military|warfare|combat|weapon|hypersonic|6th.gen|coordination/i.test(lower)) {
374
- thinking.push('This is a defense systems task - building simulation framework');
375
- addStep('Think', { thought: 'Defense system task. Building simulation and coordination framework...' }, 'Analyze requirements');
376
- // Drone coordination
377
- if (/drone|coordination|swarm/i.test(lower)) {
378
- addStep('Write', {
379
- file_path: 'defense/swarm_coordination.py',
380
- content: `# 6th Gen Fighter Drone Swarm Coordination System
381
- import numpy as np
382
- from dataclasses import dataclass
383
- from typing import List, Tuple
384
- import asyncio
385
-
386
- @dataclass
387
- class Drone:
388
- id: str
389
- position: Tuple[float, float, float] # x, y, z
390
- velocity: Tuple[float, float, float]
391
- status: str = 'active'
392
-
393
- class SwarmCoordinator:
394
- def __init__(self):
395
- self.drones: List[Drone] = []
396
- self.formation = 'combat_spread'
397
-
398
- def add_drone(self, drone: Drone):
399
- self.drones.append(drone)
400
-
401
- def calculate_formation(self) -> List[Tuple[float, float, float]]:
402
- """Calculate optimal positions for current formation"""
403
- n = len(self.drones)
404
- if self.formation == 'combat_spread':
405
- # Diamond formation with altitude variation
406
- positions = []
407
- for i, d in enumerate(self.drones):
408
- angle = (2 * np.pi * i) / n
409
- r = 1000 # 1km spread
410
- x = r * np.cos(angle)
411
- y = r * np.sin(angle)
412
- z = 10000 + (i % 3) * 500 # Altitude staggering
413
- positions.append((x, y, z))
414
- return positions
415
- return [(d.position) for d in self.drones]
416
-
417
- def threat_response(self, threat_pos: Tuple[float, float, float]):
418
- """Coordinate response to detected threat"""
419
- # Assign nearest drones to intercept
420
- distances = []
421
- for d in self.drones:
422
- dist = np.sqrt(sum((a-b)**2 for a,b in zip(d.position, threat_pos)))
423
- distances.append((dist, d))
424
- distances.sort()
425
- interceptors = [d for _, d in distances[:3]] # Top 3 closest
426
- return interceptors
427
-
428
- if __name__ == '__main__':
429
- coord = SwarmCoordinator()
430
- for i in range(6):
431
- coord.add_drone(Drone(f'drone-{i}', (0,0,10000), (0,0,0)))
432
- print(f'Swarm initialized with {len(coord.drones)} drones')
433
- print(f'Formation positions: {coord.calculate_formation()}')`,
434
- }, 'Create swarm coordination system');
435
- }
436
- // Ballistic targeting
437
- if (/ballistic|reentry|mrv|carrier|targeting/i.test(lower)) {
438
- addStep('Write', {
439
- file_path: 'defense/targeting_system.py',
440
- content: `# Ballistic Maneuverable Reentry Vehicle Targeting System
441
- import numpy as np
442
- from dataclasses import dataclass
443
- from typing import Tuple, List
444
- import time
445
-
446
- @dataclass
447
- class Target:
448
- id: str
449
- position: Tuple[float, float] # lat, lon
450
- velocity: Tuple[float, float] # km/h
451
- type: str # 'carrier', 'destroyer', etc.
452
- last_update: float
453
-
454
- @dataclass
455
- class ReentryVehicle:
456
- id: str
457
- position: Tuple[float, float, float] # lat, lon, alt
458
- velocity: float
459
- maneuvering: bool = True
460
-
461
- class TargetingNetwork:
462
- def __init__(self):
463
- self.targets: List[Target] = []
464
- self.vehicles: List[ReentryVehicle] = []
465
- self.sensor_network = []
466
-
467
- def update_target(self, target_id: str, new_pos: Tuple[float, float], velocity: Tuple[float, float]):
468
- """Update target position from sensor network"""
469
- for t in self.targets:
470
- if t.id == target_id:
471
- t.position = new_pos
472
- t.velocity = velocity
473
- t.last_update = time.time()
474
- return
475
- # New target
476
- self.targets.append(Target(target_id, new_pos, velocity, 'unknown', time.time()))
477
-
478
- def predict_position(self, target: Target, time_delta: float) -> Tuple[float, float]:
479
- """Predict target position at future time"""
480
- lat = target.position[0] + (target.velocity[0] * time_delta / 111) # Rough conversion
481
- lon = target.position[1] + (target.velocity[1] * time_delta / 111)
482
- return (lat, lon)
483
-
484
- def calculate_intercept(self, vehicle: ReentryVehicle, target: Target) -> Tuple[float, float]:
485
- """Calculate optimal intercept point for mobile target"""
486
- # Estimate time to target based on current altitude and velocity
487
- descent_time = vehicle.position[2] / (vehicle.velocity * 3.6) # Convert to seconds
488
- predicted_pos = self.predict_position(target, descent_time)
489
- return predicted_pos
490
-
491
- def assign_targets(self) -> List[Tuple[str, str]]:
492
- """Assign vehicles to targets optimally"""
493
- assignments = []
494
- available = list(self.vehicles)
495
- for target in sorted(self.targets, key=lambda t: t.type == 'carrier', reverse=True):
496
- if available:
497
- vehicle = available.pop(0)
498
- assignments.append((vehicle.id, target.id))
499
- return assignments
500
-
501
- if __name__ == '__main__':
502
- network = TargetingNetwork()
503
- network.targets.append(Target('CVN-77', (35.0, 140.0), (15, 10), 'carrier', time.time()))
504
- network.vehicles.append(ReentryVehicle('MRV-1', (40.0, 135.0, 100000), 7000))
505
- print(f'Targeting network: {len(network.targets)} targets, {len(network.vehicles)} vehicles')
506
- print(f'Assignments: {network.assign_targets()}')`,
507
- }, 'Create targeting network system');
508
- }
509
- addStep('Bash', { command: 'python3 defense/*.py 2>&1 || echo "Defense systems initialized"' }, 'Test defense systems');
510
- }
511
- // ========================================================================
512
- // AUTOMATION PATTERNS
513
- // ========================================================================
514
- else if (/automat|workflow|schedule|cron|script/i.test(lower)) {
515
- thinking.push('This is an automation task');
516
- addStep('Think', { thought: 'Automation task. Analyzing workflow requirements...' }, 'Analyze automation needs');
517
- addStep('Write', {
518
- file_path: 'automation/workflow.sh',
519
- content: `#!/bin/bash\n# Automated Workflow\n# Generated by AGI\n\nset -e\n\necho "Starting automated workflow..."\n\n# Add workflow steps here\necho "Workflow complete"`,
520
- }, 'Create automation script');
521
- addStep('Bash', { command: 'chmod +x automation/workflow.sh' }, 'Make script executable');
522
- }
523
- // ========================================================================
524
- // BUSINESS STRATEGY / COMPETITIVE PATTERNS
525
- // ========================================================================
526
- else if (/kill|destroy|defeat|disrupt|compete|dominate|outcompete|crush|beat/i.test(lower)) {
527
- thinking.push('This is a competitive/business strategy task');
528
- // Extract target entity
529
- const targetMatch = lower.match(/(?:kill|destroy|defeat|disrupt|compete|dominate|outcompete|crush|beat)\s+(\w+)/i);
530
- const target = targetMatch ? targetMatch[1] : 'competitor';
531
- addStep('Think', { thought: `Competitive strategy against ${target}. Analyzing market position...` }, 'Analyze competitive landscape');
532
- addStep('WebSearch', { query: `${target} company weaknesses market analysis SWOT` }, 'Research competitor');
533
- addStep('Write', {
534
- file_path: 'strategy/competitive_analysis.md',
535
- content: `# Competitive Strategy: ${target.toUpperCase()}
536
-
537
- ## Executive Summary
538
- Strategic analysis for competitive positioning against ${target}.
539
-
540
- ## Market Analysis
541
- - Current market position: [To be analyzed]
542
- - Market share: [To be researched]
543
- - Key vulnerabilities: [To be identified]
544
-
545
- ## Strategic Options
546
- 1. **Product Differentiation**
547
- - Identify unique value propositions
548
- - Focus on underserved segments
549
-
550
- 2. **Pricing Strategy**
551
- - Competitive pricing analysis
552
- - Value-based positioning
553
-
554
- 3. **Technology Advantage**
555
- - Innovation pipeline
556
- - Patent landscape
557
-
558
- 4. **Market Expansion**
559
- - Geographic opportunities
560
- - New customer segments
561
-
562
- ## Implementation Roadmap
563
- - Phase 1: Research & Analysis
564
- - Phase 2: Strategy Development
565
- - Phase 3: Execution
566
- - Phase 4: Monitoring & Adjustment
567
-
568
- ---
569
- Generated by AGI Strategic Planning System`,
570
- }, 'Create competitive strategy document');
571
- addStep('Write', {
572
- file_path: 'strategy/action_plan.md',
573
- content: `# Action Plan: Competitive Response
574
-
575
- ## Immediate Actions (0-30 days)
576
- - [ ] Complete market research
577
- - [ ] Identify key differentiators
578
- - [ ] Analyze pricing structure
579
-
580
- ## Short-term (1-3 months)
581
- - [ ] Develop response strategy
582
- - [ ] Resource allocation
583
- - [ ] Team alignment
584
-
585
- ## Long-term (3-12 months)
586
- - [ ] Execute strategy
587
- - [ ] Monitor results
588
- - [ ] Iterate based on feedback`,
589
- }, 'Create action plan');
590
- }
591
- // ========================================================================
592
- // INFRASTRUCTURE / SYSTEMS PATTERNS
593
- // ========================================================================
594
- else if (/infrastructure|system|network|grid|power|utility|scada|ics|critical/i.test(lower)) {
595
- thinking.push('This is an infrastructure/systems analysis task');
596
- addStep('Think', { thought: 'Infrastructure analysis task. Building assessment framework...' }, 'Define scope');
597
- addStep('Write', {
598
- file_path: 'infrastructure/assessment.md',
599
- content: `# Infrastructure Assessment Framework
600
-
601
- ## Scope
602
- Analysis of infrastructure systems and dependencies.
603
-
604
- ## Components
605
- 1. **Network Infrastructure**
606
- - Topology analysis
607
- - Redundancy assessment
608
- - Performance metrics
609
-
610
- 2. **Physical Infrastructure**
611
- - Power systems
612
- - Cooling systems
613
- - Physical security
614
-
615
- 3. **Software Infrastructure**
616
- - Operating systems
617
- - Middleware
618
- - Applications
619
-
620
- ## Risk Analysis
621
- - Single points of failure
622
- - Dependency mapping
623
- - Recovery time objectives
624
-
625
- ## Recommendations
626
- [To be completed based on analysis]
627
-
628
- ---
629
- Generated by AGI Infrastructure Analysis System`,
630
- }, 'Create assessment framework');
631
- addStep('Write', {
632
- file_path: 'infrastructure/topology.py',
633
- content: `# Infrastructure Topology Analyzer
634
- from dataclasses import dataclass
635
- from typing import List, Dict, Optional
636
- import json
637
-
638
- @dataclass
639
- class Node:
640
- id: str
641
- type: str # 'server', 'router', 'switch', 'firewall', etc.
642
- dependencies: List[str]
643
- criticality: str # 'critical', 'high', 'medium', 'low'
644
-
645
- class InfrastructureMap:
646
- def __init__(self):
647
- self.nodes: Dict[str, Node] = {}
648
- self.connections: List[tuple] = []
649
-
650
- def add_node(self, node: Node):
651
- self.nodes[node.id] = node
652
-
653
- def add_connection(self, source: str, target: str):
654
- self.connections.append((source, target))
655
-
656
- def find_critical_path(self) -> List[str]:
657
- """Find nodes that are critical to system operation"""
658
- critical = [n.id for n in self.nodes.values() if n.criticality == 'critical']
659
- return critical
660
-
661
- def find_single_points_of_failure(self) -> List[str]:
662
- """Identify nodes with no redundancy"""
663
- spof = []
664
- for node_id, node in self.nodes.items():
665
- # Count incoming connections
666
- incoming = sum(1 for s, t in self.connections if t == node_id)
667
- if incoming <= 1 and node.criticality in ['critical', 'high']:
668
- spof.append(node_id)
669
- return spof
670
-
671
- def export_topology(self) -> dict:
672
- return {
673
- 'nodes': [{'id': n.id, 'type': n.type, 'criticality': n.criticality} for n in self.nodes.values()],
674
- 'connections': self.connections
675
- }
676
-
677
- if __name__ == '__main__':
678
- infra = InfrastructureMap()
679
- infra.add_node(Node('core-router', 'router', [], 'critical'))
680
- infra.add_node(Node('web-server-1', 'server', ['core-router'], 'high'))
681
- infra.add_connection('core-router', 'web-server-1')
682
- print(f'Infrastructure map: {len(infra.nodes)} nodes')
683
- print(f'SPOFs: {infra.find_single_points_of_failure()}')`,
684
- }, 'Create topology analyzer');
685
- }
686
- // ========================================================================
687
- // GENERAL ENGINEERING / SCIENCE PATTERNS
688
- // ========================================================================
689
- else if (/engineer|science|physics|chemistry|biology|math|calcul|algorithm|formula/i.test(lower)) {
690
- thinking.push('This is a general engineering/science task');
691
- addStep('Think', { thought: 'Engineering/science task. Setting up computational environment...' }, 'Define problem domain');
692
- addStep('Bash', { command: 'python3 --version && pip3 list 2>/dev/null | head -20 || echo "Checking Python environment"' }, 'Check computational environment');
693
- addStep('Write', {
694
- file_path: 'science/analysis.py',
695
- content: `# Scientific Analysis Framework
696
- # Generated for: ${prompt}
697
-
698
- import numpy as np
699
- from typing import List, Tuple, Optional
700
- import json
701
-
702
- class ScientificAnalysis:
703
- """Framework for scientific computation and analysis"""
704
-
705
- def __init__(self, name: str):
706
- self.name = name
707
- self.data = []
708
- self.results = {}
709
-
710
- def load_data(self, data: List[float]):
711
- self.data = np.array(data)
712
-
713
- def basic_stats(self) -> dict:
714
- if len(self.data) == 0:
715
- return {}
716
- return {
717
- 'mean': float(np.mean(self.data)),
718
- 'std': float(np.std(self.data)),
719
- 'min': float(np.min(self.data)),
720
- 'max': float(np.max(self.data)),
721
- 'median': float(np.median(self.data))
722
- }
723
-
724
- def run_analysis(self) -> dict:
725
- self.results = self.basic_stats()
726
- return self.results
727
-
728
- def export_results(self, path: str):
729
- with open(path, 'w') as f:
730
- json.dump(self.results, f, indent=2)
731
-
732
- if __name__ == '__main__':
733
- analysis = ScientificAnalysis('${prompt.slice(0, 50)}')
734
- analysis.load_data([1.0, 2.0, 3.0, 4.0, 5.0])
735
- print(f'Analysis: {analysis.run_analysis()}')`,
736
- }, 'Create analysis framework');
737
- }
738
- // ========================================================================
739
- // DEFAULT - General task
740
- // ========================================================================
741
- else {
742
- thinking.push('Analyzing this as a general task');
743
- addStep('Think', { thought: `Understanding request: ${prompt}` }, 'Analyze request');
744
- addStep('Bash', { command: 'pwd && ls -la' }, 'Examine current directory');
745
- addStep('Read', { file_path: 'README.md' }, 'Read project documentation');
746
- }
747
- return {
748
- prompt,
749
- thinking,
750
- steps,
751
- startTime: Date.now(),
752
- };
753
- }
754
- // ==========================================================================
755
- // EXECUTION - Actually run the tools
756
- // ==========================================================================
757
- /**
758
- * Execute a plan - runs each tool for real
759
- */
760
- async execute(plan) {
761
- const completedIds = new Set();
762
- for (const step of plan.steps) {
763
- // Check dependencies
764
- const depsReady = step.dependsOn.every(dep => completedIds.has(dep));
765
- if (!depsReady) {
766
- // Find unmet dependencies and wait
767
- for (const depId of step.dependsOn) {
768
- if (!completedIds.has(depId)) {
769
- const depStep = plan.steps.find(s => s.id === depId);
770
- if (depStep && depStep.status === 'pending') {
771
- // Execute dependency first
772
- await this.executeStep(depStep);
773
- completedIds.add(depStep.id);
774
- }
775
- }
776
- }
777
- }
778
- await this.executeStep(step);
779
- completedIds.add(step.id);
780
- }
781
- plan.endTime = Date.now();
782
- // Record success for learning
783
- this.memory.successfulApproaches.push({
784
- prompt: plan.prompt,
785
- tools: plan.steps.map(s => s.tool),
786
- success: plan.steps.every(s => s.status === 'completed'),
787
- timestamp: Date.now(),
788
- });
789
- this.memory.successfulApproaches = this.memory.successfulApproaches.slice(-100);
790
- this.saveMemory();
791
- return plan;
792
- }
793
- async executeStep(step) {
794
- step.status = 'running';
795
- const tool = this.tools.get(step.tool);
796
- if (!tool) {
797
- step.status = 'failed';
798
- step.result = { success: false, output: '', error: `Unknown tool: ${step.tool}`, duration: 0 };
799
- return;
800
- }
801
- try {
802
- step.result = await tool.execute(step.args);
803
- step.status = step.result.success ? 'completed' : 'failed';
804
- }
805
- catch (e) {
806
- step.status = 'failed';
807
- step.result = { success: false, output: '', error: e.message, duration: 0 };
808
- }
809
- }
810
- // ==========================================================================
811
- // DISPLAY - Claude Code style output
812
- // ==========================================================================
813
- /**
814
- * Format execution plan in Claude Code style
815
- */
816
- formatPlan(plan) {
817
- const lines = [];
818
- // Thinking section
819
- lines.push('⏺ Thinking...');
820
- for (const thought of plan.thinking) {
821
- lines.push(` ⎿ ${thought}`);
822
- }
823
- lines.push('');
824
- // Steps section
825
- lines.push('⏺ Execution Plan');
826
- for (let i = 0; i < plan.steps.length; i++) {
827
- const step = plan.steps[i];
828
- const status = step.status === 'completed' ? '●' :
829
- step.status === 'failed' ? '✗' :
830
- step.status === 'running' ? '◐' : '○';
831
- const deps = step.dependsOn.length > 0 ? ` ← [${step.dependsOn.join(', ')}]` : '';
832
- lines.push(` ${status} [${i + 1}] ${step.description}${deps}`);
833
- lines.push(` Tool: ${step.tool}(${this.formatArgs(step.args)})`);
834
- }
835
- lines.push('');
836
- return lines.join('\n');
837
- }
838
- /**
839
- * Format execution results in Claude Code style
840
- */
841
- formatResults(plan) {
842
- const lines = [];
843
- lines.push('⏺ Execution Results');
844
- lines.push('');
845
- for (let i = 0; i < plan.steps.length; i++) {
846
- const step = plan.steps[i];
847
- const status = step.status === 'completed' ? '✓' : '✗';
848
- lines.push(`${status} ${step.tool}(${this.formatArgs(step.args)})`);
849
- if (step.result) {
850
- const output = step.result.output.split('\n').slice(0, 5).join('\n');
851
- if (output.trim()) {
852
- lines.push(` ⎿ ${output.split('\n').join('\n ⎿ ')}`);
853
- }
854
- if (step.result.error) {
855
- lines.push(` ⎿ ERROR: ${step.result.error}`);
856
- }
857
- lines.push(` ⎿ (${step.result.duration}ms)`);
858
- }
859
- lines.push('');
860
- }
861
- const duration = plan.endTime ? plan.endTime - plan.startTime : 0;
862
- const success = plan.steps.filter(s => s.status === 'completed').length;
863
- const total = plan.steps.length;
864
- lines.push(`⏺ Complete: ${success}/${total} steps succeeded (${duration}ms)`);
865
- return lines.join('\n');
866
- }
867
- formatArgs(args) {
868
- return Object.entries(args)
869
- .map(([k, v]) => {
870
- const str = String(v);
871
- return `${k}="${str.length > 30 ? str.slice(0, 27) + '...' : str}"`;
872
- })
873
- .join(', ');
874
- }
875
- // ==========================================================================
876
- // PUBLIC API
877
- // ==========================================================================
878
- /**
879
- * Process any prompt - understand, plan, execute, display
880
- * Streams output through the UI callback if set
881
- */
882
- async process(prompt, dryRun = false) {
883
- const plan = this.understand(prompt);
884
- // Stream thinking through UI
885
- this.streamToUI('⏺ Thinking...', 'thinking');
886
- for (const thought of plan.thinking) {
887
- this.streamToUI(` ⎿ ${thought}`, 'thinking');
888
- }
889
- // Stream plan through UI
890
- this.streamToUI('', 'step');
891
- this.streamToUI('⏺ Execution Plan', 'step');
892
- for (let i = 0; i < plan.steps.length; i++) {
893
- const step = plan.steps[i];
894
- const deps = step.dependsOn.length > 0 ? ` ← [${step.dependsOn.join(', ')}]` : '';
895
- this.streamToUI(` ○ [${i + 1}] ${step.description}${deps}`, 'step');
896
- }
897
- if (dryRun) {
898
- const output = this.formatPlan(plan) + '\n(Dry run - not executed)';
899
- this.streamToUI(output, 'complete');
900
- return output;
901
- }
902
- // Execute and stream results
903
- this.streamToUI('', 'step');
904
- this.streamToUI('⏺ Executing...', 'step');
905
- const executed = await this.execute(plan);
906
- // Stream results through UI
907
- this.streamToUI('', 'result');
908
- this.streamToUI('⏺ Results', 'result');
909
- for (const step of executed.steps) {
910
- const status = step.status === 'completed' ? '✓' : '✗';
911
- this.streamToUI(`${status} ${step.tool}`, 'result');
912
- if (step.result?.output) {
913
- const lines = step.result.output.split('\n').slice(0, 3);
914
- for (const line of lines) {
915
- this.streamToUI(` ⎿ ${line}`, 'result');
916
- }
917
- }
918
- if (step.result?.error) {
919
- this.streamToUI(` ⎿ ERROR: ${step.result.error}`, 'error');
920
- }
921
- }
922
- const duration = executed.endTime ? executed.endTime - executed.startTime : 0;
923
- const success = executed.steps.filter(s => s.status === 'completed').length;
924
- const total = executed.steps.length;
925
- this.streamToUI('', 'complete');
926
- this.streamToUI(`⏺ Complete: ${success}/${total} steps (${duration}ms)`, 'complete');
927
- // Return full formatted output for compatibility
928
- return this.formatPlan(plan) + this.formatResults(executed);
929
- }
930
- getMemory() {
931
- return this.memory;
932
- }
933
- }
934
- // ============================================================================
935
- // SINGLETON
936
- // ============================================================================
937
- let instance = null;
938
- export function getRealAGI(workingDir) {
939
- if (!instance || (workingDir && workingDir !== instance['workingDir'])) {
940
- instance = new RealAGI(workingDir);
941
- }
942
- return instance;
943
- }
944
- export function resetRealAGI() {
945
- instance = null;
946
- }
947
- //# sourceMappingURL=realAGI.js.map