erosolar-cli 2.1.269 → 2.1.271

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 (112) hide show
  1. package/dist/capabilities/index.d.ts +0 -1
  2. package/dist/capabilities/index.d.ts.map +1 -1
  3. package/dist/capabilities/index.js +1 -1
  4. package/dist/capabilities/index.js.map +1 -1
  5. package/dist/capabilities/orchestrationCapability.d.ts.map +1 -1
  6. package/dist/capabilities/orchestrationCapability.js +107 -62
  7. package/dist/capabilities/orchestrationCapability.js.map +1 -1
  8. package/dist/core/iMessageVerification.d.ts +1 -1
  9. package/dist/core/infrastructureTemplates.d.ts +1 -1
  10. package/dist/core/infrastructureTemplates.js +5 -5
  11. package/dist/core/infrastructureTemplates.js.map +1 -1
  12. package/dist/core/persistentObjectiveStore.d.ts +13 -1
  13. package/dist/core/persistentObjectiveStore.d.ts.map +1 -1
  14. package/dist/core/persistentObjectiveStore.js.map +1 -1
  15. package/dist/core/securityDeliverableGenerator.d.ts +1 -1
  16. package/dist/core/securityDeliverableGenerator.d.ts.map +1 -1
  17. package/dist/core/securityDeliverableGenerator.js +3 -3
  18. package/dist/core/securityDeliverableGenerator.js.map +1 -1
  19. package/dist/core/toolRuntime.d.ts.map +1 -1
  20. package/dist/core/toolRuntime.js +11 -5
  21. package/dist/core/toolRuntime.js.map +1 -1
  22. package/dist/core/types.js.map +1 -1
  23. package/dist/core/unifiedOrchestrator.d.ts +265 -77
  24. package/dist/core/unifiedOrchestrator.d.ts.map +1 -1
  25. package/dist/core/unifiedOrchestrator.js +915 -254
  26. package/dist/core/unifiedOrchestrator.js.map +1 -1
  27. package/dist/providers/anthropicProvider.d.ts +1 -1
  28. package/dist/shell/interactiveShell.d.ts +1 -1
  29. package/dist/shell/interactiveShell.d.ts.map +1 -1
  30. package/dist/shell/interactiveShell.js +188 -207
  31. package/dist/shell/interactiveShell.js.map +1 -1
  32. package/dist/tools/tao/rl.js +1 -1
  33. package/dist/tools/tao/rl.js.map +1 -1
  34. package/dist/tools/taoTools.js +5 -5
  35. package/dist/tools/taoTools.js.map +1 -1
  36. package/package.json +1 -1
  37. package/dist/capabilities/unifiedInvestigationCapability.d.ts +0 -22
  38. package/dist/capabilities/unifiedInvestigationCapability.d.ts.map +0 -1
  39. package/dist/capabilities/unifiedInvestigationCapability.js +0 -41
  40. package/dist/capabilities/unifiedInvestigationCapability.js.map +0 -1
  41. package/dist/core/agentOrchestrator.d.ts +0 -400
  42. package/dist/core/agentOrchestrator.d.ts.map +0 -1
  43. package/dist/core/agentOrchestrator.js +0 -2133
  44. package/dist/core/agentOrchestrator.js.map +0 -1
  45. package/dist/core/autoExecutionOrchestrator.d.ts +0 -172
  46. package/dist/core/autoExecutionOrchestrator.d.ts.map +0 -1
  47. package/dist/core/autoExecutionOrchestrator.js +0 -591
  48. package/dist/core/autoExecutionOrchestrator.js.map +0 -1
  49. package/dist/core/dualAgentOrchestrator.d.ts +0 -34
  50. package/dist/core/dualAgentOrchestrator.d.ts.map +0 -1
  51. package/dist/core/dualAgentOrchestrator.js +0 -94
  52. package/dist/core/dualAgentOrchestrator.js.map +0 -1
  53. package/dist/core/failureRecovery.d.ts +0 -26
  54. package/dist/core/failureRecovery.d.ts.map +0 -1
  55. package/dist/core/failureRecovery.js +0 -54
  56. package/dist/core/failureRecovery.js.map +0 -1
  57. package/dist/core/intelligentTestFlows.d.ts +0 -45
  58. package/dist/core/intelligentTestFlows.d.ts.map +0 -1
  59. package/dist/core/intelligentTestFlows.js +0 -25
  60. package/dist/core/intelligentTestFlows.js.map +0 -1
  61. package/dist/core/learningPersistence.d.ts +0 -58
  62. package/dist/core/learningPersistence.d.ts.map +0 -1
  63. package/dist/core/learningPersistence.js +0 -46
  64. package/dist/core/learningPersistence.js.map +0 -1
  65. package/dist/core/metricsTracker.d.ts +0 -40
  66. package/dist/core/metricsTracker.d.ts.map +0 -1
  67. package/dist/core/metricsTracker.js +0 -83
  68. package/dist/core/metricsTracker.js.map +0 -1
  69. package/dist/core/orchestration.d.ts +0 -534
  70. package/dist/core/orchestration.d.ts.map +0 -1
  71. package/dist/core/orchestration.js +0 -2009
  72. package/dist/core/orchestration.js.map +0 -1
  73. package/dist/core/performanceMonitor.d.ts +0 -30
  74. package/dist/core/performanceMonitor.d.ts.map +0 -1
  75. package/dist/core/performanceMonitor.js +0 -39
  76. package/dist/core/performanceMonitor.js.map +0 -1
  77. package/dist/core/selfEvolution.d.ts +0 -61
  78. package/dist/core/selfEvolution.d.ts.map +0 -1
  79. package/dist/core/selfEvolution.js +0 -38
  80. package/dist/core/selfEvolution.js.map +0 -1
  81. package/dist/core/selfImprovement.d.ts +0 -82
  82. package/dist/core/selfImprovement.d.ts.map +0 -1
  83. package/dist/core/selfImprovement.js +0 -25
  84. package/dist/core/selfImprovement.js.map +0 -1
  85. package/dist/core/unifiedFraudOrchestrator.d.ts +0 -738
  86. package/dist/core/unifiedFraudOrchestrator.d.ts.map +0 -1
  87. package/dist/core/unifiedFraudOrchestrator.js +0 -3312
  88. package/dist/core/unifiedFraudOrchestrator.js.map +0 -1
  89. package/dist/core/unifiedRealOrchestrator.d.ts +0 -126
  90. package/dist/core/unifiedRealOrchestrator.d.ts.map +0 -1
  91. package/dist/core/unifiedRealOrchestrator.js +0 -475
  92. package/dist/core/unifiedRealOrchestrator.js.map +0 -1
  93. package/dist/core/userDefenseOrchestrator.d.ts +0 -202
  94. package/dist/core/userDefenseOrchestrator.d.ts.map +0 -1
  95. package/dist/core/userDefenseOrchestrator.js +0 -1006
  96. package/dist/core/userDefenseOrchestrator.js.map +0 -1
  97. package/dist/plugins/tools/unifiedInvestigation/unifiedInvestigationPlugin.d.ts +0 -3
  98. package/dist/plugins/tools/unifiedInvestigation/unifiedInvestigationPlugin.d.ts.map +0 -1
  99. package/dist/plugins/tools/unifiedInvestigation/unifiedInvestigationPlugin.js +0 -14
  100. package/dist/plugins/tools/unifiedInvestigation/unifiedInvestigationPlugin.js.map +0 -1
  101. package/dist/tools/frontendTestingTools.d.ts +0 -9
  102. package/dist/tools/frontendTestingTools.d.ts.map +0 -1
  103. package/dist/tools/frontendTestingTools.js +0 -291
  104. package/dist/tools/frontendTestingTools.js.map +0 -1
  105. package/dist/tools/unifiedInvestigationTools.d.ts +0 -19
  106. package/dist/tools/unifiedInvestigationTools.d.ts.map +0 -1
  107. package/dist/tools/unifiedInvestigationTools.js +0 -1163
  108. package/dist/tools/unifiedInvestigationTools.js.map +0 -1
  109. package/scripts/human-verification.mjs +0 -380
  110. package/scripts/isolated-verification-runner.mjs +0 -364
  111. package/scripts/isolated-verification-wrapper.mjs +0 -276
  112. package/scripts/verify-task-completion.mjs +0 -143
@@ -1,284 +1,945 @@
1
1
  /**
2
- * Unified Orchestrator
2
+ * Unified Orchestrator - Comprehensive Real Tool Execution
3
3
  *
4
- * Lean orchestration combining RL and non-RL modes:
5
- * - Single pass: Standard execution
6
- * - Dual-RL: Self-improving with refinement
7
- * - Auto: Execute to completion
8
- * - APT: Full kill-chain execution
4
+ * REAL EXECUTION ONLY - NO SIMULATIONS
9
5
  *
10
- * Features:
11
- * - Mode-agnostic interface
12
- * - RL reward tracking
13
- * - Real technique execution via TAO
14
- * - Deliverable generation
6
+ * Provides comprehensive tools for AI to use naturally.
7
+ * AI decides what to do during confirmation/planning phase.
8
+ * All tools execute real commands - no mocks, no fakes.
9
+ *
10
+ * Tool Categories:
11
+ * - Execution: Run commands, scripts, processes
12
+ * - Engineering: Build, test, lint, typecheck, format, deps
13
+ * - Security: Audit, scan, recon, enumerate, analyze
14
+ * - Investigation: Files, processes, network, forensics
15
+ * - Analysis: Code quality, performance, patterns
16
+ * - Git: Status, commits, branches, diffs
15
17
  */
16
- import { AgentOrchestrator, } from './agentOrchestrator.js';
17
- import { scoreOutcome, recordDualOutcome, planAttackChain, selectNextTechnique, executeTechniqueInChain, getChainStats, getRLState, parseNaturalLanguageIntent, } from '../tools/tao/index.js';
18
+ import { execSync, spawn } from 'child_process';
19
+ import * as fs from 'fs';
20
+ import * as path from 'path';
21
+ import * as crypto from 'crypto';
22
+ import * as os from 'os';
18
23
  // ============================================================================
19
- // UNIFIED ORCHESTRATOR
24
+ // UNIFIED ORCHESTRATOR - Comprehensive Tool Set
20
25
  // ============================================================================
21
26
  export class UnifiedOrchestrator {
22
- agent;
23
- baseOrchestrator;
24
- constructor(agent) {
25
- this.agent = agent;
26
- this.baseOrchestrator = new AgentOrchestrator(agent);
27
+ workingDir;
28
+ results = [];
29
+ findings = [];
30
+ backgroundProcesses = new Map();
31
+ constructor(workingDir) {
32
+ this.workingDir = workingDir || process.cwd();
27
33
  }
28
- /**
29
- * Run orchestration with specified mode
30
- */
31
- async run(objective, options = {}) {
32
- const mode = options.mode ?? 'single';
33
- const startTime = Date.now();
34
- switch (mode) {
35
- case 'dual-rl':
36
- return this.runDualRL(objective, options, startTime);
37
- case 'auto':
38
- return this.runAuto(objective, options, startTime);
39
- case 'apt':
40
- return this.runAPT(objective, options, startTime);
41
- case 'security':
42
- return this.runSecurity(objective, options, startTime);
43
- case 'single':
44
- default:
45
- return this.runSingle(objective, options, startTime);
34
+ // ==========================================================================
35
+ // CORE EXECUTION TOOLS
36
+ // ==========================================================================
37
+ /** Execute a shell command */
38
+ exec(command, timeout = 60000) {
39
+ const start = Date.now();
40
+ try {
41
+ const output = execSync(command, {
42
+ cwd: this.workingDir,
43
+ encoding: 'utf-8',
44
+ timeout,
45
+ maxBuffer: 50 * 1024 * 1024,
46
+ stdio: ['pipe', 'pipe', 'pipe'],
47
+ });
48
+ const result = { success: true, output: output || '', duration: Date.now() - start, command, exitCode: 0 };
49
+ this.results.push(result);
50
+ return result;
51
+ }
52
+ catch (e) {
53
+ const err = e;
54
+ const output = (err.stdout || err.stderr || err.message || '');
55
+ const result = { success: false, output, error: err.message, duration: Date.now() - start, command, exitCode: err.status };
56
+ this.results.push(result);
57
+ return result;
46
58
  }
47
59
  }
48
- /**
49
- * Single-pass orchestration
50
- */
51
- async runSingle(objective, options, startTime) {
52
- const orchestratorOpts = this.toOrchestratorOptions(options);
53
- const result = await this.baseOrchestrator.runToCompletion(objective, orchestratorOpts);
54
- const reward = scoreOutcome(result);
55
- return {
56
- ...result,
57
- mode: 'single',
58
- rl: {
59
- primaryReward: reward,
60
- chosenAction: 'primary',
61
- snapshot: { avgReward: reward, primaryReward: reward, refineReward: reward, chosen: 'primary', historySize: 1 },
62
- },
63
- stats: {
64
- duration: Date.now() - startTime,
65
- cycles: 1,
66
- toolCalls: result.toolsUsed.length,
67
- },
68
- };
60
+ /** Execute multiple commands sequentially */
61
+ execMany(commands, timeout) {
62
+ return commands.map(cmd => this.exec(cmd, timeout));
69
63
  }
70
- /**
71
- * Dual-agent RL orchestration
72
- */
73
- async runDualRL(objective, options, startTime) {
74
- const orchestratorOpts = this.toOrchestratorOptions(options);
75
- // Primary pass
76
- const primary = await this.baseOrchestrator.runToCompletion(objective, orchestratorOpts);
77
- const primaryReward = scoreOutcome(primary);
78
- options.onProgress?.('primary', 0.5);
79
- // Refinement pass
80
- const refinementPrompt = this.buildRefinementPrompt(objective, primary);
81
- const refinement = await this.baseOrchestrator.runToCompletion(refinementPrompt, {
82
- ...orchestratorOpts,
83
- singlePassFocus: true,
84
- });
85
- const refinementReward = scoreOutcome(refinement);
86
- // Choose best result
87
- const chosenAction = refinementReward > primaryReward ? 'refine' : 'primary';
88
- const chosen = chosenAction === 'refine' ? refinement : primary;
89
- const snapshot = recordDualOutcome(primaryReward, refinementReward, chosenAction);
90
- options.onProgress?.('complete', 1.0);
91
- return {
92
- ...chosen,
93
- mode: 'dual-rl',
94
- statusSummary: `${chosen.statusSummary || ''} | RL: primary=${primaryReward.toFixed(2)}, refine=${refinementReward.toFixed(2)}, chosen=${chosenAction}`,
95
- rl: {
96
- primaryReward,
97
- refinementReward,
98
- chosenAction,
99
- snapshot,
100
- },
101
- stats: {
102
- duration: Date.now() - startTime,
103
- cycles: 2,
104
- toolCalls: primary.toolsUsed.length + refinement.toolsUsed.length,
105
- },
64
+ /** Execute multiple commands in parallel */
65
+ async execParallel(commands, timeout) {
66
+ return Promise.all(commands.map(cmd => Promise.resolve(this.exec(cmd, timeout))));
67
+ }
68
+ /** Start a background process */
69
+ execBackground(command, id) {
70
+ const processId = id || `bg-${Date.now()}`;
71
+ const [cmd, ...args] = command.split(' ');
72
+ const proc = spawn(cmd, args, { cwd: this.workingDir, detached: true, stdio: 'pipe' });
73
+ this.backgroundProcesses.set(processId, proc);
74
+ return processId;
75
+ }
76
+ /** Kill a background process */
77
+ killProcess(id) {
78
+ const proc = this.backgroundProcesses.get(id);
79
+ if (proc) {
80
+ proc.kill();
81
+ this.backgroundProcesses.delete(id);
82
+ return true;
83
+ }
84
+ return false;
85
+ }
86
+ // ==========================================================================
87
+ // SOFTWARE ENGINEERING TOOLS
88
+ // ==========================================================================
89
+ /** Run npm/yarn build */
90
+ build() {
91
+ return this.exec('npm run build 2>&1', 300000);
92
+ }
93
+ /** Run tests */
94
+ test(pattern) {
95
+ const cmd = pattern ? `npm test -- --grep "${pattern}" 2>&1` : 'npm test 2>&1';
96
+ return this.exec(cmd, 300000);
97
+ }
98
+ /** Run linter */
99
+ lint(fix = false) {
100
+ const cmd = fix ? 'npm run lint -- --fix 2>&1 || npx eslint . --fix 2>&1' : 'npm run lint 2>&1 || npx eslint . 2>&1';
101
+ return this.exec(cmd, 120000);
102
+ }
103
+ /** TypeScript type checking */
104
+ typecheck() {
105
+ return this.exec('npx tsc --noEmit 2>&1', 120000);
106
+ }
107
+ /** Format code */
108
+ format(check = false) {
109
+ const cmd = check ? 'npx prettier --check . 2>&1' : 'npx prettier --write . 2>&1';
110
+ return this.exec(cmd, 60000);
111
+ }
112
+ /** Dependency operations */
113
+ deps(action = 'audit') {
114
+ const cmds = {
115
+ install: 'npm install 2>&1',
116
+ update: 'npm update 2>&1',
117
+ audit: 'npm audit 2>&1',
118
+ outdated: 'npm outdated 2>&1',
119
+ dedupe: 'npm dedupe 2>&1',
106
120
  };
121
+ return this.exec(cmds[action] || cmds.audit, 180000);
107
122
  }
108
- /**
109
- * Auto-execute to completion
110
- */
111
- async runAuto(objective, options, startTime) {
112
- const maxCycles = options.maxCycles ?? (options.depth === 'deep' ? 10 : options.depth === 'quick' ? 3 : 5);
113
- const orchestratorOpts = this.toOrchestratorOptions(options);
114
- let cycle = 0;
115
- let lastResult = null;
116
- let totalToolCalls = 0;
117
- while (cycle < maxCycles) {
118
- cycle++;
119
- options.onProgress?.(`cycle-${cycle}`, cycle / maxCycles);
120
- const prompt = cycle === 1 ? objective : this.buildContinuationPrompt(objective, lastResult);
121
- const result = await this.baseOrchestrator.runToCompletion(prompt, orchestratorOpts);
122
- totalToolCalls += result.toolsUsed.length;
123
- lastResult = result;
124
- // Check completion
125
- if (result.finalResponse?.includes('TASK_FULLY_COMPLETE')) {
126
- break;
123
+ /** Clean build artifacts */
124
+ clean() {
125
+ return this.exec('rm -rf node_modules dist .tsbuildinfo .eslintcache coverage 2>&1; echo "Cleaned"', 30000);
126
+ }
127
+ /** Run full CI pipeline */
128
+ ci() {
129
+ return [
130
+ this.lint(),
131
+ this.typecheck(),
132
+ this.test(),
133
+ this.build(),
134
+ ];
135
+ }
136
+ // ==========================================================================
137
+ // SECURITY TOOLS
138
+ // ==========================================================================
139
+ /** Security audit */
140
+ securityAudit() {
141
+ return this.execMany([
142
+ 'npm audit 2>&1 | head -50',
143
+ 'grep -rn "password\\|secret\\|api.key\\|token" --include="*.ts" --include="*.js" --include="*.json" . 2>/dev/null | grep -v node_modules | head -30 || echo "No secrets"',
144
+ 'find . -name ".env*" -o -name "*.pem" -o -name "*.key" 2>/dev/null | grep -v node_modules | head -20',
145
+ ]);
146
+ }
147
+ /** Scan for vulnerabilities in code */
148
+ vulnerabilityScan() {
149
+ return this.execMany([
150
+ 'grep -rn "eval\\|exec\\|execSync\\|spawn" --include="*.ts" --include="*.js" . 2>/dev/null | grep -v node_modules | head -30 || echo "No dangerous patterns"',
151
+ 'grep -rn "innerHTML\\|dangerouslySetInnerHTML" --include="*.ts" --include="*.tsx" . 2>/dev/null | grep -v node_modules | head -20 || echo "No XSS patterns"',
152
+ 'grep -rn "SELECT.*\\$\\|INSERT.*\\$\\|UPDATE.*\\$" --include="*.ts" --include="*.js" . 2>/dev/null | grep -v node_modules | head -20 || echo "No SQL injection patterns"',
153
+ ]);
154
+ }
155
+ /** Network reconnaissance */
156
+ recon(target) {
157
+ const cmds = [
158
+ 'ifconfig 2>/dev/null || ip addr 2>/dev/null',
159
+ 'netstat -an 2>/dev/null | head -30 || ss -an 2>/dev/null | head -30',
160
+ 'lsof -i -P -n 2>/dev/null | head -30',
161
+ 'arp -a 2>/dev/null | head -20',
162
+ ];
163
+ if (target) {
164
+ cmds.push(`dig +short ${target} A 2>/dev/null; dig +short ${target} MX 2>/dev/null`);
165
+ cmds.push(`whois ${target} 2>/dev/null | head -50`);
166
+ }
167
+ return this.execMany(cmds);
168
+ }
169
+ /** System enumeration */
170
+ enumerate() {
171
+ return this.execMany([
172
+ 'whoami; id; groups 2>/dev/null',
173
+ 'uname -a',
174
+ 'ps aux | head -30',
175
+ 'env | grep -iE "path|home|user|shell" | head -20',
176
+ 'cat /etc/passwd 2>/dev/null | head -20 || dscl . list /Users 2>/dev/null | head -20',
177
+ 'sudo -l 2>/dev/null || echo "Sudo not available"',
178
+ 'find /usr -perm -4000 -type f 2>/dev/null | head -20',
179
+ ]);
180
+ }
181
+ /** Check for persistence mechanisms */
182
+ persistenceCheck() {
183
+ return this.execMany([
184
+ 'crontab -l 2>/dev/null || echo "No crontab"',
185
+ 'ls -la ~/.ssh 2>/dev/null',
186
+ 'cat ~/.ssh/authorized_keys 2>/dev/null | head -10 || echo "No authorized_keys"',
187
+ 'ls -la /Library/LaunchDaemons 2>/dev/null | head -20',
188
+ 'ls -la ~/Library/LaunchAgents 2>/dev/null | head -20',
189
+ 'grep -l "curl\\|wget\\|python\\|bash" ~/.bashrc ~/.zshrc ~/.bash_profile 2>/dev/null || echo "No suspicious profile entries"',
190
+ ]);
191
+ }
192
+ /** Defensive security checks */
193
+ defenseCheck() {
194
+ return this.execMany([
195
+ '/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null || echo "Firewall check unavailable"',
196
+ 'csrutil status 2>/dev/null || echo "SIP check unavailable"',
197
+ 'fdesetup status 2>/dev/null || echo "FileVault check unavailable"',
198
+ 'spctl --status 2>/dev/null || echo "Gatekeeper check unavailable"',
199
+ 'system_profiler SPFirewallDataType 2>/dev/null | head -20 || echo "Firewall data unavailable"',
200
+ ]);
201
+ }
202
+ // ==========================================================================
203
+ // OFFENSIVE SECURITY TOOLS
204
+ // ==========================================================================
205
+ /** Target reconnaissance and OSINT */
206
+ targetRecon(target) {
207
+ const cmds = [
208
+ `host ${target} 2>/dev/null || dig +short ${target} 2>/dev/null`,
209
+ `dig ${target} ANY 2>/dev/null | head -50`,
210
+ `dig ${target} MX 2>/dev/null | head -20`,
211
+ `dig ${target} TXT 2>/dev/null | head -20`,
212
+ `dig ${target} NS 2>/dev/null | head -20`,
213
+ `whois ${target} 2>/dev/null | head -100`,
214
+ `curl -sI "https://${target}" 2>/dev/null | head -30 || echo "HTTPS unavailable"`,
215
+ `curl -sI "http://${target}" 2>/dev/null | head -30 || echo "HTTP unavailable"`,
216
+ ];
217
+ return this.execMany(cmds, 30000);
218
+ }
219
+ /** Subdomain enumeration */
220
+ subdomainEnum(domain) {
221
+ return this.execMany([
222
+ `dig ${domain} ANY 2>/dev/null | grep -v "^;" | head -50`,
223
+ `curl -s "https://crt.sh/?q=%25.${domain}&output=json" 2>/dev/null | grep -oE '"name_value":"[^"]*"' | cut -d'"' -f4 | sort -u | head -50 || echo "crt.sh unavailable"`,
224
+ `host -t NS ${domain} 2>/dev/null`,
225
+ `host -t MX ${domain} 2>/dev/null`,
226
+ ], 60000);
227
+ }
228
+ /** Port scanning (local/network) */
229
+ portScan(target, ports = '22,80,443,8080,8443,3000,5000') {
230
+ return this.exec(`nc -zvw3 ${target} ${ports.split(',').join(' ')} 2>&1 | head -50 || echo "Scan complete"`, 60000);
231
+ }
232
+ /** Service detection */
233
+ serviceDetect(target) {
234
+ return this.execMany([
235
+ `curl -sI "https://${target}" 2>/dev/null | grep -iE "server:|x-powered-by:|x-aspnet|x-drupal|x-generator" || echo "No server headers"`,
236
+ `curl -s "https://${target}/robots.txt" 2>/dev/null | head -30 || echo "No robots.txt"`,
237
+ `curl -s "https://${target}/.well-known/security.txt" 2>/dev/null | head -30 || echo "No security.txt"`,
238
+ `curl -s "https://${target}/sitemap.xml" 2>/dev/null | head -30 || echo "No sitemap"`,
239
+ ], 30000);
240
+ }
241
+ /** Web technology fingerprinting */
242
+ webFingerprint(url) {
243
+ return this.execMany([
244
+ `curl -sI "${url}" 2>/dev/null | head -30`,
245
+ `curl -s "${url}" 2>/dev/null | grep -oE '<meta[^>]*>' | head -20 || echo "No meta tags"`,
246
+ `curl -s "${url}" 2>/dev/null | grep -oE 'src="[^"]*\\.js"' | head -20 || echo "No JS files"`,
247
+ `curl -s "${url}" 2>/dev/null | grep -oE 'href="[^"]*\\.css"' | head -20 || echo "No CSS files"`,
248
+ ], 30000);
249
+ }
250
+ /** Directory/path enumeration */
251
+ pathEnum(baseUrl) {
252
+ const commonPaths = [
253
+ 'admin', 'login', 'api', 'dashboard', 'config', 'backup', '.git', '.env',
254
+ 'wp-admin', 'wp-login.php', 'administrator', 'phpmyadmin', 'console',
255
+ ];
256
+ const cmds = commonPaths.map(p => `curl -sI "${baseUrl}/${p}" 2>/dev/null | head -1 | grep -q "200\\|301\\|302" && echo "Found: ${p}" || true`);
257
+ return this.execMany(cmds, 60000);
258
+ }
259
+ /** SSL/TLS analysis */
260
+ sslAnalyze(host) {
261
+ return this.execMany([
262
+ `echo | openssl s_client -connect ${host}:443 -servername ${host} 2>/dev/null | openssl x509 -noout -dates -subject -issuer 2>/dev/null || echo "SSL unavailable"`,
263
+ `echo | openssl s_client -connect ${host}:443 -servername ${host} 2>/dev/null | grep -E "Protocol|Cipher" | head -10 || echo "Cipher info unavailable"`,
264
+ `curl -sI "https://${host}" 2>/dev/null | grep -iE "strict-transport|content-security|x-frame|x-content-type|x-xss" || echo "No security headers"`,
265
+ ], 30000);
266
+ }
267
+ /** Cloud service detection */
268
+ cloudDetect(target) {
269
+ return this.execMany([
270
+ `dig ${target} 2>/dev/null | grep -iE "amazonaws|azure|cloudflare|fastly|akamai|google" || echo "No cloud indicators in DNS"`,
271
+ `curl -sI "https://${target}" 2>/dev/null | grep -iE "cloudflare|cloudfront|azure|x-amz|google" || echo "No cloud headers"`,
272
+ `whois ${target} 2>/dev/null | grep -iE "amazon|microsoft|google|cloudflare" | head -10 || echo "No cloud in whois"`,
273
+ ], 30000);
274
+ }
275
+ /** Local privilege escalation checks */
276
+ privescCheck() {
277
+ return this.execMany([
278
+ 'sudo -l 2>/dev/null || echo "sudo list unavailable"',
279
+ 'find / -perm -4000 -type f 2>/dev/null | head -30',
280
+ 'find / -perm -2000 -type f 2>/dev/null | head -30',
281
+ 'cat /etc/sudoers 2>/dev/null | grep -v "^#" | head -20 || echo "sudoers unreadable"',
282
+ 'ls -la /etc/passwd /etc/shadow 2>/dev/null',
283
+ 'getcap -r / 2>/dev/null | head -20 || echo "capabilities unavailable"',
284
+ 'cat /etc/crontab 2>/dev/null | head -20 || echo "crontab unreadable"',
285
+ 'ls -la /var/spool/cron/crontabs 2>/dev/null || ls -la /etc/cron.d 2>/dev/null | head -20',
286
+ ]);
287
+ }
288
+ /** macOS-specific offensive checks */
289
+ macosOffensive() {
290
+ return this.execMany([
291
+ 'security find-identity -v -p codesigning 2>/dev/null | head -20 || echo "No signing identities"',
292
+ 'security list-keychains 2>/dev/null',
293
+ 'sqlite3 ~/Library/Keychains/login.keychain-db ".tables" 2>/dev/null || echo "Keychain query unavailable"',
294
+ 'sqlite3 ~/Library/Messages/chat.db "SELECT COUNT(*) FROM message" 2>/dev/null || echo "iMessage db unavailable"',
295
+ 'sqlite3 ~/Library/Application\\ Support/Google/Chrome/Default/Login\\ Data ".tables" 2>/dev/null || echo "Chrome data unavailable"',
296
+ 'plutil -p ~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist 2>/dev/null | head -30 || echo "Launch services unavailable"',
297
+ 'sqlite3 ~/Library/Safari/History.db "SELECT url FROM history_items LIMIT 20" 2>/dev/null || echo "Safari history unavailable"',
298
+ 'ls -la ~/Library/Application\\ Support/com.apple.TCC/TCC.db 2>/dev/null || echo "TCC db path"',
299
+ ]);
300
+ }
301
+ /** Credential hunting */
302
+ credentialHunt() {
303
+ return this.execMany([
304
+ 'grep -rn "password\\|passwd\\|secret\\|api.key\\|apikey\\|token\\|credential" --include="*.json" --include="*.yml" --include="*.yaml" --include="*.conf" --include="*.config" --include="*.env" . 2>/dev/null | grep -v node_modules | head -30 || echo "No credentials in config files"',
305
+ 'find ~ -name ".env" -o -name ".env.*" -o -name "*.pem" -o -name "*.key" 2>/dev/null | head -20',
306
+ 'find ~ -name "id_rsa" -o -name "id_ed25519" -o -name "*.ppk" 2>/dev/null | head -10',
307
+ 'ls -la ~/.aws/credentials 2>/dev/null; cat ~/.aws/credentials 2>/dev/null | head -10 || echo "No AWS credentials"',
308
+ 'ls -la ~/.ssh 2>/dev/null',
309
+ 'cat ~/.gitconfig 2>/dev/null | head -20',
310
+ 'cat ~/.netrc 2>/dev/null || echo "No .netrc"',
311
+ ]);
312
+ }
313
+ /** Network attack surface mapping */
314
+ networkMap() {
315
+ return this.execMany([
316
+ 'ifconfig 2>/dev/null || ip addr 2>/dev/null',
317
+ 'route -n 2>/dev/null || netstat -rn 2>/dev/null',
318
+ 'arp -a 2>/dev/null',
319
+ 'netstat -tulpn 2>/dev/null | head -30 || lsof -i -P -n 2>/dev/null | head -30',
320
+ 'cat /etc/hosts',
321
+ 'cat /etc/resolv.conf 2>/dev/null',
322
+ ]);
323
+ }
324
+ /** Container/Docker enumeration */
325
+ containerEnum() {
326
+ return this.execMany([
327
+ 'docker ps -a 2>/dev/null | head -20 || echo "Docker not available"',
328
+ 'docker images 2>/dev/null | head -20 || echo "No docker images"',
329
+ 'docker network ls 2>/dev/null || echo "No docker networks"',
330
+ 'cat /.dockerenv 2>/dev/null && echo "Running in container" || echo "Not in container"',
331
+ 'cat /proc/1/cgroup 2>/dev/null | head -10 || echo "cgroup info unavailable"',
332
+ ]);
333
+ }
334
+ /** Full offensive assessment */
335
+ fullOffensive(target) {
336
+ const results = [];
337
+ results.push(...this.enumerate());
338
+ results.push(...this.networkMap());
339
+ results.push(...this.privescCheck());
340
+ results.push(...this.credentialHunt());
341
+ results.push(...this.persistenceCheck());
342
+ if (os.platform() === 'darwin') {
343
+ results.push(...this.macosOffensive());
344
+ }
345
+ if (target) {
346
+ results.push(...this.targetRecon(target));
347
+ results.push(...this.serviceDetect(target));
348
+ }
349
+ return results;
350
+ }
351
+ /** Attack chain execution */
352
+ attackChain(target, depth = 'medium') {
353
+ const results = [];
354
+ // Phase 1: Recon
355
+ results.push(...this.targetRecon(target));
356
+ // Phase 2: Enumeration
357
+ results.push(...this.subdomainEnum(target));
358
+ if (depth !== 'light') {
359
+ // Phase 3: Service detection
360
+ results.push(...this.serviceDetect(target));
361
+ results.push(...this.sslAnalyze(target));
362
+ }
363
+ if (depth === 'deep') {
364
+ // Phase 4: Deep analysis
365
+ results.push(...this.webFingerprint(`https://${target}`));
366
+ results.push(...this.pathEnum(`https://${target}`));
367
+ results.push(...this.cloudDetect(target));
368
+ }
369
+ return results;
370
+ }
371
+ // ==========================================================================
372
+ // INVESTIGATION & FORENSICS TOOLS
373
+ // ==========================================================================
374
+ /** File system investigation */
375
+ investigateFiles(pattern, days = 7) {
376
+ const cmds = [
377
+ `find . -type f -mtime -${days} 2>/dev/null | head -50`,
378
+ `find ~ -type f -mtime -${days} 2>/dev/null | grep -v "Library/Caches" | head -30`,
379
+ 'ls -lt ~/Downloads 2>/dev/null | head -20',
380
+ 'ls -la ~/.Trash 2>/dev/null | head -20',
381
+ ];
382
+ if (pattern) {
383
+ cmds.push(`find . -name "${pattern}" 2>/dev/null | head -30`);
384
+ }
385
+ return this.execMany(cmds);
386
+ }
387
+ /** Process investigation */
388
+ investigateProcesses() {
389
+ return this.execMany([
390
+ 'ps aux --sort=-%mem | head -20',
391
+ 'ps aux --sort=-%cpu | head -20',
392
+ 'lsof -i -P -n 2>/dev/null | grep ESTABLISHED | head -20',
393
+ 'top -l 1 -n 10 2>/dev/null || top -bn1 | head -20 2>/dev/null',
394
+ ]);
395
+ }
396
+ /** Network investigation */
397
+ investigateNetwork() {
398
+ return this.execMany([
399
+ 'netstat -an | grep ESTABLISHED | head -20',
400
+ 'lsof -i -P -n 2>/dev/null | head -30',
401
+ 'cat /etc/hosts',
402
+ 'cat /etc/resolv.conf 2>/dev/null',
403
+ 'scutil --dns 2>/dev/null | head -30',
404
+ ]);
405
+ }
406
+ /** Browser history investigation */
407
+ investigateBrowser() {
408
+ return this.execMany([
409
+ 'sqlite3 ~/Library/Application\\ Support/Google/Chrome/Default/History "SELECT url FROM urls ORDER BY last_visit_time DESC LIMIT 20" 2>/dev/null || echo "Chrome unavailable"',
410
+ 'sqlite3 ~/Library/Safari/History.db "SELECT url FROM history_items ORDER BY visit_count DESC LIMIT 20" 2>/dev/null || echo "Safari unavailable"',
411
+ 'ls ~/Library/Application\\ Support/Google/Chrome/Default/Extensions 2>/dev/null | head -10',
412
+ ]);
413
+ }
414
+ /** Email investigation */
415
+ investigateEmail() {
416
+ return this.execMany([
417
+ 'ls -la ~/Library/Mail/V*/MailData/*.db 2>/dev/null | head -10 || echo "No Mail database"',
418
+ 'find ~/Library/Mail -name "*.pdf" -o -name "*.docx" 2>/dev/null | head -20',
419
+ 'mdfind "kMDItemContentType == \'com.apple.mail.emlx\'" 2>/dev/null | head -20',
420
+ ]);
421
+ }
422
+ /** iMessage investigation */
423
+ investigateIMessage() {
424
+ return this.execMany([
425
+ 'ls -la ~/Library/Messages/chat.db 2>/dev/null || echo "No iMessage database"',
426
+ 'sqlite3 ~/Library/Messages/chat.db "SELECT COUNT(*) FROM message" 2>/dev/null || echo "Count unavailable"',
427
+ 'find ~/Library/Messages/Attachments -type f -mtime -7 2>/dev/null | wc -l',
428
+ ]);
429
+ }
430
+ // ==========================================================================
431
+ // CODE ANALYSIS TOOLS
432
+ // ==========================================================================
433
+ /** Analyze code quality */
434
+ analyzeQuality() {
435
+ return this.execMany([
436
+ 'npx tsc --noEmit 2>&1 | grep -c "error" || echo "0"',
437
+ 'npm run lint 2>&1 | grep -cE "error|warning" || echo "0"',
438
+ 'grep -rn "TODO\\|FIXME\\|HACK\\|XXX\\|BUG" src/ --include="*.ts" 2>/dev/null | head -30 || echo "No markers"',
439
+ 'grep -rn "console\\.log\\|console\\.error\\|console\\.warn" src/ --include="*.ts" 2>/dev/null | grep -v node_modules | head -20 || echo "No console statements"',
440
+ ]);
441
+ }
442
+ /** Find code patterns */
443
+ findPatterns(pattern, fileTypes = '*.ts') {
444
+ return this.exec(`grep -rn "${pattern}" --include="${fileTypes}" . 2>/dev/null | grep -v node_modules | head -50 || echo "No matches"`);
445
+ }
446
+ /** Analyze code complexity */
447
+ analyzeComplexity() {
448
+ return this.execMany([
449
+ 'find src -name "*.ts" | xargs wc -l 2>/dev/null | tail -10',
450
+ 'find src -type f | wc -l',
451
+ 'find src -name "*.ts" -size +50k 2>/dev/null | head -10 || echo "No large files"',
452
+ 'find src -type d -empty 2>/dev/null | head -10 || echo "No empty directories"',
453
+ ]);
454
+ }
455
+ /** Find unused/dead code patterns */
456
+ findDeadCode() {
457
+ return this.execMany([
458
+ 'grep -rn "@ts-ignore\\|@ts-expect-error\\|eslint-disable" src/ --include="*.ts" 2>/dev/null | head -20 || echo "No suppressions"',
459
+ 'grep -rn "// TODO.*remove\\|// DEPRECATED\\|// LEGACY" src/ --include="*.ts" 2>/dev/null | head -20 || echo "No legacy markers"',
460
+ 'npx ts-unused-exports tsconfig.json 2>&1 | head -30 || echo "ts-unused-exports not available"',
461
+ ]);
462
+ }
463
+ /** Find simulation/mock patterns for removal */
464
+ findSimulation() {
465
+ return this.exec('grep -rn "simulat\\|mock\\|fake\\|stub" src/ --include="*.ts" 2>/dev/null | grep -v node_modules | head -50 || echo "No simulation patterns"');
466
+ }
467
+ // ==========================================================================
468
+ // GIT TOOLS
469
+ // ==========================================================================
470
+ /** Git status */
471
+ gitStatus() {
472
+ return this.exec('git status 2>&1');
473
+ }
474
+ /** Git log */
475
+ gitLog(count = 10) {
476
+ return this.exec(`git log --oneline -${count} 2>&1`);
477
+ }
478
+ /** Git diff */
479
+ gitDiff(staged = false) {
480
+ const cmd = staged ? 'git diff --staged 2>&1' : 'git diff 2>&1';
481
+ return this.exec(cmd);
482
+ }
483
+ /** Git branches */
484
+ gitBranches() {
485
+ return this.exec('git branch -a 2>&1');
486
+ }
487
+ /** Git stash */
488
+ gitStash(action = 'list') {
489
+ return this.exec(`git stash ${action} 2>&1`);
490
+ }
491
+ // ==========================================================================
492
+ // FILE SYSTEM TOOLS
493
+ // ==========================================================================
494
+ /** Read file contents */
495
+ readFile(filePath) {
496
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(this.workingDir, filePath);
497
+ return fs.readFileSync(fullPath, 'utf-8');
498
+ }
499
+ /** Write file contents */
500
+ writeFile(filePath, content) {
501
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(this.workingDir, filePath);
502
+ fs.writeFileSync(fullPath, content, 'utf-8');
503
+ }
504
+ /** Check if file exists */
505
+ fileExists(filePath) {
506
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(this.workingDir, filePath);
507
+ return fs.existsSync(fullPath);
508
+ }
509
+ /** List directory */
510
+ listDir(dirPath = '.', recursive = false) {
511
+ const fullPath = path.isAbsolute(dirPath) ? dirPath : path.join(this.workingDir, dirPath);
512
+ if (recursive) {
513
+ const result = this.exec(`find "${fullPath}" -type f 2>/dev/null | head -100`);
514
+ return result.output.split('\n').filter(Boolean);
515
+ }
516
+ return fs.readdirSync(fullPath);
517
+ }
518
+ /** Get file stats */
519
+ fileStats(filePath) {
520
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(this.workingDir, filePath);
521
+ try {
522
+ return fs.statSync(fullPath);
523
+ }
524
+ catch {
525
+ return null;
526
+ }
527
+ }
528
+ /** Delete file or directory */
529
+ delete(targetPath, recursive = false) {
530
+ const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(this.workingDir, targetPath);
531
+ try {
532
+ if (recursive) {
533
+ fs.rmSync(fullPath, { recursive: true, force: true });
534
+ }
535
+ else {
536
+ fs.unlinkSync(fullPath);
127
537
  }
538
+ return true;
128
539
  }
129
- const reward = scoreOutcome(lastResult);
540
+ catch {
541
+ return false;
542
+ }
543
+ }
544
+ // ==========================================================================
545
+ // SYSTEM INFO TOOLS
546
+ // ==========================================================================
547
+ /** Get system information */
548
+ systemInfo() {
130
549
  return {
131
- ...lastResult,
132
- mode: 'auto',
133
- rl: {
134
- primaryReward: reward,
135
- chosenAction: 'primary',
136
- snapshot: { avgReward: reward, primaryReward: reward, refineReward: reward, chosen: 'primary', historySize: cycle },
137
- },
138
- stats: {
139
- duration: Date.now() - startTime,
140
- cycles: cycle,
141
- toolCalls: totalToolCalls,
550
+ platform: os.platform(),
551
+ arch: os.arch(),
552
+ hostname: os.hostname(),
553
+ cpus: os.cpus().length,
554
+ memory: {
555
+ total: Math.round(os.totalmem() / 1024 / 1024 / 1024) + 'GB',
556
+ free: Math.round(os.freemem() / 1024 / 1024 / 1024) + 'GB',
142
557
  },
558
+ uptime: Math.round(os.uptime() / 3600) + ' hours',
559
+ user: os.userInfo().username,
560
+ home: os.homedir(),
561
+ cwd: this.workingDir,
143
562
  };
144
563
  }
145
- /**
146
- * APT kill-chain orchestration
147
- */
148
- async runAPT(objective, options, startTime) {
149
- const target = options.targets?.[0] ?? 'target';
150
- const goal = options.goal ?? 'all';
151
- // Parse intent and plan attack chain
152
- const intent = parseNaturalLanguageIntent(`${goal} attack on ${target}: ${objective}`);
153
- const chain = planAttackChain(intent, objective);
154
- const techniques = [];
155
- // Execute techniques in chain
156
- let phaseIndex = 0;
157
- const totalPhases = chain.phases.length;
158
- while (chain.currentPhase < totalPhases) {
159
- options.onProgress?.(`phase-${phaseIndex}`, phaseIndex / totalPhases);
160
- const action = selectNextTechnique(chain);
161
- if (!action) {
162
- chain.currentPhase++;
163
- phaseIndex++;
164
- continue;
165
- }
166
- const params = {
167
- target,
168
- depth: options.depth ?? 'standard',
169
- stealth: options.stealthMode ?? false,
170
- timeout: 30000,
171
- context: {},
172
- };
173
- try {
174
- const executionResult = await executeTechniqueInChain(chain, action, params);
175
- techniques.push(executionResult.result);
176
- options.onTechnique?.(action.id, executionResult.result);
177
- if (!executionResult.result.success && phaseIndex <= 3) {
178
- // Critical phase failed (recon through exploitation)
179
- break;
180
- }
181
- }
182
- catch {
183
- // Technique failed, move to next phase
184
- }
185
- chain.currentPhase++;
186
- phaseIndex++;
187
- }
188
- // Generate summary via agent
189
- const orchestratorOpts = this.toOrchestratorOptions(options);
190
- const summaryPrompt = `Summarize APT operation results:\nChain: ${chain.id}\nPhases: ${phaseIndex}/${totalPhases}\nTechniques: ${techniques.length}\nGoal: ${goal}`;
191
- const agentResult = await this.baseOrchestrator.runToCompletion(summaryPrompt, { ...orchestratorOpts, maxAttempts: 1 });
192
- const reward = scoreOutcome(agentResult);
193
- const goalAchieved = techniques.filter(t => t.success).length >= totalPhases * 0.7;
564
+ /** Get environment variables */
565
+ getEnv(key) {
566
+ if (key)
567
+ return process.env[key] || '';
568
+ return process.env;
569
+ }
570
+ // ==========================================================================
571
+ // ANALYSIS & FINDINGS
572
+ // ==========================================================================
573
+ /** Analyze output and extract findings */
574
+ analyze(output, context) {
575
+ const findings = [];
576
+ const lower = output.toLowerCase();
577
+ // TypeScript errors
578
+ const tsMatches = output.match(/error TS\d+:/g);
579
+ if (tsMatches) {
580
+ findings.push({
581
+ severity: 'high',
582
+ category: 'TypeScript',
583
+ title: `${tsMatches.length} TypeScript error(s)`,
584
+ description: 'Compilation errors found',
585
+ evidence: output.slice(0, 500),
586
+ recommendation: 'Fix type errors before proceeding',
587
+ });
588
+ }
589
+ // Security vulnerabilities
590
+ if (lower.includes('vulnerabilit') && (lower.includes('high') || lower.includes('critical'))) {
591
+ findings.push({
592
+ severity: 'critical',
593
+ category: 'Security',
594
+ title: 'Security vulnerabilities detected',
595
+ description: 'High/critical vulnerabilities in dependencies',
596
+ evidence: output.slice(0, 500),
597
+ recommendation: 'Run npm audit fix or update packages',
598
+ });
599
+ }
600
+ // Secrets exposure
601
+ if ((lower.includes('password') || lower.includes('secret') || lower.includes('api_key') || lower.includes('token')) &&
602
+ !lower.includes('no secret') && !lower.includes('no password') && output.includes(':')) {
603
+ findings.push({
604
+ severity: 'critical',
605
+ category: 'Security',
606
+ title: 'Potential secrets in code',
607
+ description: 'Credentials or secrets may be exposed',
608
+ evidence: output.slice(0, 300),
609
+ recommendation: 'Remove secrets, use environment variables',
610
+ });
611
+ }
612
+ // Test failures
613
+ if (lower.includes('fail') && (lower.includes('test') || lower.includes('spec') || lower.includes('assert'))) {
614
+ findings.push({
615
+ severity: 'high',
616
+ category: 'Testing',
617
+ title: 'Test failures',
618
+ description: 'One or more tests failed',
619
+ evidence: output.slice(0, 500),
620
+ recommendation: 'Fix failing tests',
621
+ });
622
+ }
623
+ // ESLint errors
624
+ const eslintErrors = output.match(/\d+ error/);
625
+ if (eslintErrors) {
626
+ findings.push({
627
+ severity: 'medium',
628
+ category: 'Code Quality',
629
+ title: 'Linting errors',
630
+ description: `ESLint found issues: ${eslintErrors[0]}`,
631
+ evidence: output.slice(0, 500),
632
+ recommendation: 'Run lint with --fix or address manually',
633
+ });
634
+ }
635
+ this.findings.push(...findings);
636
+ return findings;
637
+ }
638
+ /** Add a custom finding */
639
+ addFinding(finding) {
640
+ this.findings.push(finding);
641
+ }
642
+ /** Get all findings */
643
+ getFindings() {
644
+ return this.findings;
645
+ }
646
+ /** Get all results */
647
+ getResults() {
648
+ return this.results;
649
+ }
650
+ /** Reset state */
651
+ reset() {
652
+ this.results = [];
653
+ this.findings = [];
654
+ }
655
+ // ==========================================================================
656
+ // REPORT GENERATION
657
+ // ==========================================================================
658
+ /** Generate comprehensive report */
659
+ generateReport(objective = 'Operation') {
660
+ const successCount = this.results.filter(r => r.success).length;
661
+ const totalDuration = this.results.reduce((sum, r) => sum + r.duration, 0);
662
+ const criticalFindings = this.findings.filter(f => f.severity === 'critical').length;
663
+ const isSuccess = successCount === this.results.length && criticalFindings === 0;
194
664
  return {
195
- ...agentResult,
196
- mode: 'apt',
197
- rl: {
198
- primaryReward: reward,
199
- chosenAction: 'primary',
200
- snapshot: { avgReward: reward, primaryReward: reward, refineReward: reward, chosen: 'primary', historySize: techniques.length },
201
- },
202
- apt: {
203
- chain,
204
- techniques,
205
- goalAchieved,
206
- },
207
- stats: {
208
- duration: Date.now() - startTime,
209
- cycles: techniques.length,
210
- toolCalls: agentResult.toolsUsed.length,
211
- },
665
+ id: `OP-${Date.now()}-${crypto.randomBytes(4).toString('hex').toUpperCase()}`,
666
+ objective,
667
+ startTime: Date.now() - totalDuration,
668
+ endTime: Date.now(),
669
+ duration: totalDuration,
670
+ results: this.results,
671
+ findings: this.findings,
672
+ summary: `${successCount}/${this.results.length} succeeded, ${this.findings.length} findings (${criticalFindings} critical)`,
673
+ success: isSuccess,
674
+ mode: objective,
675
+ phasesCompleted: [...new Set(this.results.filter(r => r.success).map(r => (r.command || '').split(' ')[0]))],
676
+ recommendations: this.findings.filter(f => f.recommendation).map(f => f.recommendation),
677
+ limitations: [],
678
+ toolsUsed: [...new Set(this.results.map(r => (r.command || '').split(' ')[0]))],
679
+ exitReason: isSuccess ? 'complete' : 'incomplete',
680
+ statusSummary: `${successCount}/${this.results.length} commands succeeded`,
681
+ finalResponse: this.results.slice(-3).map(r => r.output).join('\n').slice(0, 2000),
682
+ completed: isSuccess,
683
+ evidence: [],
212
684
  };
213
685
  }
686
+ // ==========================================================================
687
+ // INTELLIGENT EXECUTION - AI Flow Integration
688
+ // ==========================================================================
214
689
  /**
215
- * Security assessment orchestration
690
+ * Execute operations based on objective analysis.
691
+ * Automatically selects and runs appropriate tools based on the objective.
216
692
  */
217
- async runSecurity(objective, options, startTime) {
218
- const securityPrompt = `Security Assessment Objective: ${objective}
219
-
220
- Execute a thorough security assessment:
221
- 1. Reconnaissance - gather target information
222
- 2. Vulnerability scanning - identify weaknesses
223
- 3. Exploitation testing - verify vulnerabilities
224
- 4. Documentation - produce findings report
225
-
226
- Targets: ${options.targets?.join(', ') ?? 'as specified'}
227
- Stealth mode: ${options.stealthMode ? 'enabled' : 'disabled'}
228
-
229
- Provide concrete findings with severity ratings.`;
230
- // Run with RL if enabled
231
- if (options.useRL) {
232
- return this.runDualRL(securityPrompt, { ...options, mode: 'dual-rl' }, startTime);
233
- }
234
- return this.runAuto(securityPrompt, { ...options, mode: 'auto', depth: 'deep' }, startTime);
235
- }
236
- // ============================================================================
237
- // HELPERS
238
- // ============================================================================
239
- toOrchestratorOptions(options) {
240
- return {
241
- streaming: options.streaming,
242
- enforceActions: options.enforceActions,
243
- maxAttempts: options.maxAttempts,
244
- };
693
+ async execute(config) {
694
+ this.reset();
695
+ const objective = (config.objective || config.mode || 'operation').toLowerCase();
696
+ const target = config.target;
697
+ // Analyze objective and execute appropriate tools
698
+ if (this.matchesIntent(objective, ['build', 'compile', 'typescript', 'tsc'])) {
699
+ this.typecheck();
700
+ this.build();
701
+ }
702
+ if (this.matchesIntent(objective, ['test', 'spec', 'jest', 'mocha'])) {
703
+ this.test();
704
+ }
705
+ if (this.matchesIntent(objective, ['lint', 'eslint', 'format', 'prettier'])) {
706
+ this.lint();
707
+ this.format(true);
708
+ }
709
+ if (this.matchesIntent(objective, ['security', 'audit', 'vulnerab', 'scan'])) {
710
+ this.securityAudit();
711
+ this.vulnerabilityScan();
712
+ }
713
+ if (this.matchesIntent(objective, ['attack', 'offensive', 'pentest', 'red team', 'recon'])) {
714
+ if (target) {
715
+ this.targetRecon(target);
716
+ this.serviceDetect(target);
717
+ this.sslAnalyze(target);
718
+ }
719
+ this.enumerate();
720
+ this.credentialHunt();
721
+ this.persistenceCheck();
722
+ }
723
+ if (this.matchesIntent(objective, ['defense', 'blue team', 'harden', 'protect'])) {
724
+ this.defenseCheck();
725
+ this.securityAudit();
726
+ this.persistenceCheck();
727
+ }
728
+ if (this.matchesIntent(objective, ['investigate', 'forensic', 'analyze'])) {
729
+ this.investigateFiles();
730
+ this.investigateProcesses();
731
+ this.investigateNetwork();
732
+ }
733
+ if (this.matchesIntent(objective, ['bug', 'fix', 'error', 'issue', 'problem'])) {
734
+ this.typecheck();
735
+ this.lint();
736
+ this.analyzeQuality();
737
+ this.findDeadCode();
738
+ }
739
+ if (this.matchesIntent(objective, ['ci', 'pipeline', 'full', 'complete', 'all'])) {
740
+ this.ci();
741
+ this.securityAudit();
742
+ this.analyzeQuality();
743
+ }
744
+ if (this.matchesIntent(objective, ['git', 'status', 'commit', 'branch'])) {
745
+ this.gitStatus();
746
+ this.gitLog(10);
747
+ this.gitDiff();
748
+ }
749
+ if (this.matchesIntent(objective, ['clean', 'remove', 'delete', 'clear'])) {
750
+ this.clean();
751
+ }
752
+ if (this.matchesIntent(objective, ['health', 'check', 'status'])) {
753
+ this.gitStatus();
754
+ this.typecheck();
755
+ this.deps('audit');
756
+ }
757
+ // Analyze all results for findings
758
+ for (const result of this.results) {
759
+ this.analyze(result.output, objective);
760
+ }
761
+ const report = this.generateReport(config.objective || 'Operation');
762
+ report.finalResponse = this.generateFinalResponse(report);
763
+ return report;
245
764
  }
246
- buildRefinementPrompt(objective, primary) {
247
- return `You are refining another agent's work.
248
-
249
- Original objective: ${objective}
250
-
251
- Primary output:
252
- ${primary.finalResponse}
253
-
254
- ${primary.limitations.length ? `Limitations: ${primary.limitations.join(', ')}` : ''}
255
- ${primary.recommendations.length ? `Recommendations: ${primary.recommendations.join(', ')}` : ''}
256
-
257
- Your task:
258
- - Verify the output is correct
259
- - Fix any gaps or errors
260
- - Run minimal tools to validate
261
- - End with TASK_FULLY_COMPLETE if verified`;
262
- }
263
- buildContinuationPrompt(objective, previous) {
264
- return `Continue working on: ${objective}
265
-
266
- Previous progress:
267
- ${previous.statusSummary || previous.finalResponse}
268
-
269
- ${previous.limitations.length ? `Remaining issues: ${previous.limitations.join(', ')}` : ''}
270
-
271
- Continue until complete. End with TASK_FULLY_COMPLETE when done.`;
765
+ /** Check if objective matches any of the intent keywords */
766
+ matchesIntent(objective, keywords) {
767
+ return keywords.some(kw => objective.includes(kw));
768
+ }
769
+ /** Generate a human-readable final response from the report */
770
+ generateFinalResponse(report) {
771
+ const lines = [];
772
+ lines.push(`## ${report.objective}`);
773
+ lines.push('');
774
+ lines.push(`**Status:** ${report.success ? ' Success' : '⚠ Issues Found'}`);
775
+ lines.push(`**Duration:** ${report.duration}ms`);
776
+ lines.push(`**Commands Executed:** ${report.results.length}`);
777
+ lines.push('');
778
+ if (report.findings.length > 0) {
779
+ lines.push('### Findings');
780
+ report.findings.forEach(f => {
781
+ lines.push(`- **${f.severity.toUpperCase()}**: ${f.title}`);
782
+ if (f.recommendation)
783
+ lines.push(` - Recommendation: ${f.recommendation}`);
784
+ });
785
+ lines.push('');
786
+ }
787
+ const failed = report.results.filter(r => !r.success);
788
+ if (failed.length > 0) {
789
+ lines.push('### Failed Commands');
790
+ failed.slice(0, 5).forEach(r => {
791
+ lines.push(`- \`${r.command}\`: ${r.error || 'Unknown error'}`);
792
+ });
793
+ lines.push('');
794
+ }
795
+ lines.push(`### Summary`);
796
+ lines.push(report.summary);
797
+ return lines.join('\n');
798
+ }
799
+ async runUnified(objective, options) {
800
+ return this.execute({ objective, ...options });
801
+ }
802
+ async runToCompletion(objective, options) {
803
+ return this.execute({ objective, ...options });
804
+ }
805
+ // ==========================================================================
806
+ // STATIC METHODS
807
+ // ==========================================================================
808
+ static run(command, workingDir) {
809
+ return new UnifiedOrchestrator(workingDir).exec(command);
810
+ }
811
+ static runMany(commands, workingDir) {
812
+ return new UnifiedOrchestrator(workingDir).execMany(commands);
272
813
  }
273
814
  }
274
815
  // ============================================================================
275
- // FACTORY
276
- // ============================================================================
277
- export function createUnifiedOrchestrator(agent) {
278
- return new UnifiedOrchestrator(agent);
279
- }
280
- // ============================================================================
281
- // UTILITY EXPORTS
816
+ // CONVENIENCE EXPORTS
282
817
  // ============================================================================
283
- export { getChainStats, getRLState };
818
+ export const orchestrator = new UnifiedOrchestrator();
819
+ // Direct execution
820
+ export const exec = (cmd, dir) => UnifiedOrchestrator.run(cmd, dir);
821
+ export const execMany = (cmds, dir) => UnifiedOrchestrator.runMany(cmds, dir);
822
+ // Engineering
823
+ export const build = (dir) => new UnifiedOrchestrator(dir).build();
824
+ export const test = (dir) => new UnifiedOrchestrator(dir).test();
825
+ export const lint = (dir) => new UnifiedOrchestrator(dir).lint();
826
+ export const typecheck = (dir) => new UnifiedOrchestrator(dir).typecheck();
827
+ export const format = (dir) => new UnifiedOrchestrator(dir).format();
828
+ export const ci = (dir) => new UnifiedOrchestrator(dir).ci();
829
+ // Security
830
+ export const securityAudit = (dir) => new UnifiedOrchestrator(dir).securityAudit();
831
+ export const vulnerabilityScan = (dir) => new UnifiedOrchestrator(dir).vulnerabilityScan();
832
+ export const recon = (target, dir) => new UnifiedOrchestrator(dir).recon(target);
833
+ export const enumerate = (dir) => new UnifiedOrchestrator(dir).enumerate();
834
+ // Analysis
835
+ export const analyzeQuality = (dir) => new UnifiedOrchestrator(dir).analyzeQuality();
836
+ export const findPatterns = (pattern, dir) => new UnifiedOrchestrator(dir).findPatterns(pattern);
837
+ export const findSimulation = (dir) => new UnifiedOrchestrator(dir).findSimulation();
838
+ export const findDeadCode = (dir) => new UnifiedOrchestrator(dir).findDeadCode();
839
+ // Investigation
840
+ export const investigateFiles = (dir) => new UnifiedOrchestrator(dir).investigateFiles();
841
+ export const investigateProcesses = (dir) => new UnifiedOrchestrator(dir).investigateProcesses();
842
+ export const investigateNetwork = (dir) => new UnifiedOrchestrator(dir).investigateNetwork();
843
+ // Git
844
+ export const gitStatus = (dir) => new UnifiedOrchestrator(dir).gitStatus();
845
+ export const gitLog = (dir) => new UnifiedOrchestrator(dir).gitLog();
846
+ export const gitDiff = (dir) => new UnifiedOrchestrator(dir).gitDiff();
847
+ // Offensive Security
848
+ export const targetRecon = (target, dir) => new UnifiedOrchestrator(dir).targetRecon(target);
849
+ export const subdomainEnum = (domain, dir) => new UnifiedOrchestrator(dir).subdomainEnum(domain);
850
+ export const portScan = (target, ports, dir) => new UnifiedOrchestrator(dir).portScan(target, ports);
851
+ export const serviceDetect = (target, dir) => new UnifiedOrchestrator(dir).serviceDetect(target);
852
+ export const webFingerprint = (url, dir) => new UnifiedOrchestrator(dir).webFingerprint(url);
853
+ export const pathEnum = (baseUrl, dir) => new UnifiedOrchestrator(dir).pathEnum(baseUrl);
854
+ export const sslAnalyze = (host, dir) => new UnifiedOrchestrator(dir).sslAnalyze(host);
855
+ export const cloudDetect = (target, dir) => new UnifiedOrchestrator(dir).cloudDetect(target);
856
+ export const privescCheck = (dir) => new UnifiedOrchestrator(dir).privescCheck();
857
+ export const macosOffensive = (dir) => new UnifiedOrchestrator(dir).macosOffensive();
858
+ export const credentialHunt = (dir) => new UnifiedOrchestrator(dir).credentialHunt();
859
+ export const networkMap = (dir) => new UnifiedOrchestrator(dir).networkMap();
860
+ export const containerEnum = (dir) => new UnifiedOrchestrator(dir).containerEnum();
861
+ export const fullOffensive = (target, dir) => new UnifiedOrchestrator(dir).fullOffensive(target);
862
+ export const attackChain = (target, depth, dir) => new UnifiedOrchestrator(dir).attackChain(target, depth);
863
+ // Composite Operations - Full Pipelines
864
+ export const fullEngineering = (dir) => {
865
+ const o = new UnifiedOrchestrator(dir);
866
+ o.exec('npm run clean 2>&1 || true');
867
+ o.deps('install');
868
+ o.ci();
869
+ o.analyzeQuality();
870
+ for (const r of o.getResults())
871
+ o.analyze(r.output, 'engineering');
872
+ return o.generateReport('Full Engineering');
873
+ };
874
+ export const fullSecurity = (dir) => {
875
+ const o = new UnifiedOrchestrator(dir);
876
+ o.securityAudit();
877
+ o.vulnerabilityScan();
878
+ o.defenseCheck();
879
+ o.persistenceCheck();
880
+ for (const r of o.getResults())
881
+ o.analyze(r.output, 'security');
882
+ return o.generateReport('Full Security');
883
+ };
884
+ export const fullDefensive = (dir) => {
885
+ const o = new UnifiedOrchestrator(dir);
886
+ o.defenseCheck();
887
+ o.persistenceCheck();
888
+ o.securityAudit();
889
+ for (const r of o.getResults())
890
+ o.analyze(r.output, 'defensive');
891
+ return o.generateReport('Full Defensive');
892
+ };
893
+ export const fullInvestigation = (dir) => {
894
+ const o = new UnifiedOrchestrator(dir);
895
+ o.investigateFiles();
896
+ o.investigateProcesses();
897
+ o.investigateNetwork();
898
+ o.investigateBrowser();
899
+ o.investigateEmail();
900
+ o.investigateIMessage();
901
+ for (const r of o.getResults())
902
+ o.analyze(r.output, 'investigation');
903
+ return o.generateReport('Full Investigation');
904
+ };
905
+ export const redTeam = (target, dir) => {
906
+ const o = new UnifiedOrchestrator(dir);
907
+ if (target)
908
+ o.targetRecon(target);
909
+ o.enumerate();
910
+ o.vulnerabilityScan();
911
+ o.persistenceCheck();
912
+ o.credentialHunt();
913
+ o.networkMap();
914
+ if (os.platform() === 'darwin')
915
+ o.macosOffensive();
916
+ for (const r of o.getResults())
917
+ o.analyze(r.output, 'redteam');
918
+ return o.generateReport('Red Team Operation');
919
+ };
920
+ export const blueTeam = (dir) => {
921
+ const o = new UnifiedOrchestrator(dir);
922
+ o.defenseCheck();
923
+ o.securityAudit();
924
+ o.persistenceCheck();
925
+ o.investigateProcesses();
926
+ o.investigateNetwork();
927
+ for (const r of o.getResults())
928
+ o.analyze(r.output, 'blueteam');
929
+ return o.generateReport('Blue Team Operation');
930
+ };
931
+ export const intelligence = (target, dir) => {
932
+ const o = new UnifiedOrchestrator(dir);
933
+ o.recon(target);
934
+ if (target)
935
+ o.targetRecon(target);
936
+ o.enumerate();
937
+ o.investigateNetwork();
938
+ for (const r of o.getResults())
939
+ o.analyze(r.output, 'intelligence');
940
+ return o.generateReport('Intelligence Collection');
941
+ };
942
+ // Legacy compatibility
943
+ export const run = (objective, options) => new UnifiedOrchestrator(options?.target).execute({ objective, ...options });
944
+ export const healthCheck = (dir) => new UnifiedOrchestrator(dir).execute({ objective: 'health' });
284
945
  //# sourceMappingURL=unifiedOrchestrator.js.map