erosolar-cli 2.1.270 → 2.1.272

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 +56 -108
  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 +911 -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 -558
  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,2009 +0,0 @@
1
- /**
2
- * Unified Orchestration Module
3
- *
4
- * Single entry point for ALL orchestration modes:
5
- * - Single-pass: Standard task completion
6
- * - Dual-RL: Self-improving with refinement agent
7
- * - Auto-execution: Full objective completion with deliverables
8
- * - Security: Specialized for security assessments
9
- * - APT-Chain: Full adversary simulation with kill-chain phases
10
- * - Infrastructure: Full stack deployment and management
11
- * - Government: Law enforcement and compliance procedures
12
- *
13
- * Features:
14
- * - REAL execution: DNS queries, port scans, HTTP probes - not simulations
15
- * - Concrete execution producing actual documents and procedures
16
- * - Actionable results: training modules, incident response, security controls
17
- * - Full offensive stack: recon, exploitation, persistence, exfiltration
18
- * - Auto-execution to completion for all modes
19
- * - RL-guided technique selection with real feedback loops
20
- *
21
- * Usage:
22
- * ```typescript
23
- * import { createOrchestrator, OrchestrationMode } from './orchestration.js';
24
- *
25
- * const orchestrator = createOrchestrator(agent, 'apt-chain');
26
- * const result = await orchestrator.run(objective, options);
27
- * ```
28
- */
29
- import { AgentOrchestrator, } from './agentOrchestrator.js';
30
- import { DualAgentOrchestrator, } from './dualAgentOrchestrator.js';
31
- import { AutoExecutionOrchestrator, } from './autoExecutionOrchestrator.js';
32
- import { SecurityDeliverableGenerator, exportToMarkdown, exportToJSON, exportToHTML, } from './securityDeliverableGenerator.js';
33
- // Direct TAO imports for real execution
34
- import { techniqueRegistry, planAttackChain, selectNextTechnique, executeTechniqueInChain, listActiveChains, getChainStats, getRLState, } from '../tools/tao/index.js';
35
- import { parseNaturalLanguageIntent } from '../tools/tao/intentParser.js';
36
- import { getApplicableLegalFrameworks, } from './governmentProcedures.js';
37
- import { getInfrastructureStack, generateDeploymentScript, generateTeardownScript, generateOpsecChecklist, } from './infrastructureTemplates.js';
38
- // ═══════════════════════════════════════════════════════════════════════════════
39
- // UNIFIED ORCHESTRATOR
40
- // ═══════════════════════════════════════════════════════════════════════════════
41
- export class UnifiedOrchestrator {
42
- agent;
43
- workingDir;
44
- singleOrchestrator;
45
- dualOrchestrator;
46
- autoOrchestrator;
47
- deliverableGenerator;
48
- constructor(agent, workingDir = process.cwd()) {
49
- this.agent = agent;
50
- this.workingDir = workingDir;
51
- this.singleOrchestrator = new AgentOrchestrator(agent);
52
- this.dualOrchestrator = new DualAgentOrchestrator(agent);
53
- this.autoOrchestrator = new AutoExecutionOrchestrator(agent, workingDir);
54
- this.deliverableGenerator = new SecurityDeliverableGenerator();
55
- }
56
- /**
57
- * Run orchestration with unified interface
58
- */
59
- async run(request, options = {}) {
60
- const mode = options.mode || 'single';
61
- const startTime = Date.now();
62
- switch (mode) {
63
- case 'single':
64
- return this.runSingle(request, options, startTime);
65
- case 'dual-rl':
66
- return this.runDualRL(request, options, startTime);
67
- case 'auto':
68
- return this.runAuto(request, options, startTime);
69
- case 'auto-security':
70
- return this.runAutoSecurity(request, options, startTime);
71
- case 'security-only':
72
- return this.runSecurityOnly(request, options, startTime);
73
- case 'apt-chain':
74
- return this.runAPTChain(request, options, startTime);
75
- case 'infrastructure':
76
- return this.runInfrastructure(request, options, startTime);
77
- case 'incident-response':
78
- return this.runIncidentResponse(request, options, startTime);
79
- case 'training':
80
- return this.runTraining(request, options, startTime);
81
- case 'compliance':
82
- return this.runCompliance(request, options, startTime);
83
- case 'red-team':
84
- return this.runRedTeam(request, options, startTime);
85
- case 'a2ad':
86
- return this.runA2AD(request, options, startTime);
87
- case 'direct-apt':
88
- return this.runDirectAPT(request, options, startTime);
89
- case 'persistent-access':
90
- return this.runPersistentAccess(request, options, startTime);
91
- case 'intel-collection':
92
- return this.runIntelCollection(request, options, startTime);
93
- case 'impact':
94
- return this.runImpact(request, options, startTime);
95
- default:
96
- // Check if goal-oriented execution is requested
97
- if (options.goal || options.goals) {
98
- return this.runGoalOriented(request, options, startTime);
99
- }
100
- return this.runSingle(request, options, startTime);
101
- }
102
- }
103
- /**
104
- * Run single-pass orchestration
105
- */
106
- async runSingle(request, options, startTime) {
107
- const orchestratorOptions = {
108
- streaming: options.streaming ?? true,
109
- enforceActions: options.enforceActions ?? true,
110
- maxAttempts: options.maxAttempts ?? 6,
111
- };
112
- const result = await this.singleOrchestrator.runToCompletion(request, orchestratorOptions);
113
- let deliverable;
114
- let deliverablePaths;
115
- if (options.generateDeliverable) {
116
- deliverable = await this.deliverableGenerator.generate(options.deliverableType || 'pentest-report', result, this.agent.getHistory(), {});
117
- if (options.outputDir && options.exportFormats) {
118
- deliverablePaths = await this.exportDeliverable(deliverable, options.outputDir, options.exportFormats);
119
- }
120
- if (options.onDeliverable) {
121
- options.onDeliverable(deliverable);
122
- }
123
- }
124
- return {
125
- mode: 'single',
126
- success: result.exitReason === 'complete',
127
- finalResponse: result.finalResponse,
128
- toolsUsed: result.toolsUsed,
129
- orchestratorResult: result,
130
- deliverable,
131
- deliverablePaths,
132
- summary: result.statusSummary || 'Task completed',
133
- duration: Date.now() - startTime,
134
- };
135
- }
136
- /**
137
- * Run dual-RL orchestration with refinement
138
- */
139
- async runDualRL(request, options, startTime) {
140
- const dualOptions = {
141
- mode: 'dual-rl',
142
- streaming: options.streaming ?? true,
143
- enforceActions: options.enforceActions ?? true,
144
- maxAttempts: options.maxAttempts ?? 6,
145
- };
146
- const result = await this.dualOrchestrator.runToCompletion(request, dualOptions);
147
- let deliverable;
148
- let deliverablePaths;
149
- if (options.generateDeliverable) {
150
- deliverable = await this.deliverableGenerator.generate(options.deliverableType || 'pentest-report', result, this.agent.getHistory(), {});
151
- if (options.outputDir && options.exportFormats) {
152
- deliverablePaths = await this.exportDeliverable(deliverable, options.outputDir, options.exportFormats);
153
- }
154
- if (options.onDeliverable) {
155
- options.onDeliverable(deliverable);
156
- }
157
- }
158
- return {
159
- mode: 'dual-rl',
160
- success: result.exitReason === 'complete',
161
- finalResponse: result.finalResponse,
162
- toolsUsed: result.toolsUsed,
163
- dualResult: result,
164
- deliverable,
165
- deliverablePaths,
166
- summary: result.statusSummary || `Dual-RL: ${result.chosenAction || 'primary'} chosen`,
167
- duration: Date.now() - startTime,
168
- };
169
- }
170
- /**
171
- * Run auto-execution to completion
172
- */
173
- async runAuto(request, options, startTime) {
174
- const autoConfig = {
175
- maxExecutionTime: options.maxExecutionTime,
176
- maxCycles: options.maxCycles,
177
- depth: options.depth,
178
- stealthMode: options.stealthMode,
179
- generateDeliverable: options.generateDeliverable ?? false,
180
- deliverableType: options.deliverableType,
181
- outputDir: options.outputDir,
182
- exportFormats: options.exportFormats,
183
- onProgress: options.onProgress,
184
- onDeliverable: options.onDeliverable,
185
- };
186
- const result = await this.autoOrchestrator.execute(request, autoConfig);
187
- return {
188
- mode: 'auto',
189
- success: result.success,
190
- finalResponse: result.summary,
191
- toolsUsed: result.metrics.toolsUsed,
192
- autoResult: result,
193
- deliverable: result.deliverable,
194
- deliverablePaths: result.deliverablePaths,
195
- summary: result.summary,
196
- duration: Date.now() - startTime,
197
- };
198
- }
199
- /**
200
- * Run auto-execution with security deliverables
201
- */
202
- async runAutoSecurity(request, options, startTime) {
203
- const autoConfig = {
204
- maxExecutionTime: options.maxExecutionTime ?? 30 * 60 * 1000,
205
- maxCycles: options.maxCycles ?? 10,
206
- depth: options.depth ?? 'standard',
207
- stealthMode: options.stealthMode ?? false,
208
- generateDeliverable: true,
209
- deliverableType: options.deliverableType ?? 'pentest-report',
210
- outputDir: options.outputDir ?? `${this.workingDir}/deliverables`,
211
- exportFormats: options.exportFormats ?? ['markdown', 'json', 'html'],
212
- onProgress: options.onProgress,
213
- onDeliverable: options.onDeliverable,
214
- };
215
- const result = await this.autoOrchestrator.execute(request, autoConfig);
216
- return {
217
- mode: 'auto-security',
218
- success: result.success,
219
- finalResponse: result.summary,
220
- toolsUsed: result.metrics.toolsUsed,
221
- autoResult: result,
222
- deliverable: result.deliverable,
223
- deliverablePaths: result.deliverablePaths,
224
- summary: result.summary,
225
- duration: Date.now() - startTime,
226
- };
227
- }
228
- /**
229
- * Generate security deliverable from current conversation
230
- */
231
- async runSecurityOnly(request, options, startTime) {
232
- // Create a minimal orchestrator result from current state
233
- const minimalResult = {
234
- finalResponse: request,
235
- toolsUsed: [],
236
- planOnly: false,
237
- tookAction: false,
238
- completion: {
239
- isComplete: true,
240
- confidence: 1,
241
- signals: {
242
- hasExplicitCompletionStatement: true,
243
- hasIncompleteWorkIndicators: false,
244
- hasPendingActionIndicators: false,
245
- hasErrorIndicators: false,
246
- hasFollowUpQuestions: false,
247
- toolsUsedInLastResponse: 0,
248
- lastToolWasReadOnly: false,
249
- consecutiveResponsesWithoutTools: 0,
250
- hasRecentFileWrites: false,
251
- hasRecentCommits: false,
252
- todoItemsPending: 0,
253
- todoItemsCompleted: 0,
254
- mentionsFutureWork: false,
255
- completionConfidence: 1,
256
- },
257
- reason: 'Security deliverable generation',
258
- shouldVerify: false,
259
- },
260
- exitReason: 'complete',
261
- statusSummary: 'Deliverable generated',
262
- limitations: [],
263
- recommendations: [],
264
- };
265
- const generatorOptions = {
266
- customTitle: request,
267
- };
268
- const deliverable = await this.deliverableGenerator.generate(options.deliverableType || 'pentest-report', minimalResult, this.agent.getHistory(), generatorOptions);
269
- let deliverablePaths;
270
- if (options.outputDir && options.exportFormats) {
271
- deliverablePaths = await this.exportDeliverable(deliverable, options.outputDir, options.exportFormats);
272
- }
273
- if (options.onDeliverable) {
274
- options.onDeliverable(deliverable);
275
- }
276
- return {
277
- mode: 'security-only',
278
- success: true,
279
- finalResponse: `Generated ${deliverable.type} deliverable: ${deliverable.id}`,
280
- toolsUsed: [],
281
- deliverable,
282
- deliverablePaths,
283
- summary: `Deliverable generated with ${deliverable.findings.length} findings`,
284
- duration: Date.now() - startTime,
285
- };
286
- }
287
- /**
288
- * Run full APT kill-chain simulation with REAL execution
289
- * Executes complete adversary simulation with all kill-chain phases
290
- * using actual network operations (DNS, TCP, HTTP)
291
- */
292
- async runAPTChain(request, options, startTime) {
293
- const region = options.region || 'us';
294
- const stack = getInfrastructureStack(region);
295
- // Parse intent for real execution parameters
296
- const intent = parseNaturalLanguageIntent(request);
297
- const targets = options.targets ?? intent.targets;
298
- const stealth = options.stealthMode ?? intent.constraints.includes('stealth');
299
- const depth = this.normalizeDepth(options.depth ?? intent.depth);
300
- // Track all real executions
301
- const realExecutions = [];
302
- const completedPhases = [];
303
- // Execute REAL techniques for each target
304
- for (const target of targets) {
305
- // Create attack chain with RL planning
306
- const chain = planAttackChain(intent, `APT simulation against ${target}`);
307
- options.onChainProgress?.(chain, 0);
308
- // Execute each phase with real network operations
309
- while (chain.state === 'planning' || chain.state === 'executing') {
310
- const action = selectNextTechnique(chain);
311
- if (!action)
312
- break;
313
- const technique = techniqueRegistry.get(action.id);
314
- if (!technique)
315
- continue;
316
- // Notify start
317
- options.onTechniqueStart?.(action.id, target);
318
- // Build technique params
319
- const params = {
320
- target,
321
- depth,
322
- stealth,
323
- timeout: depth === 'quick' ? 5000 : depth === 'deep' ? 30000 : 15000,
324
- context: {},
325
- };
326
- // EXECUTE REAL TECHNIQUE
327
- const { result, reward } = await executeTechniqueInChain(chain, action, params);
328
- // Record execution
329
- const execResult = {
330
- techniqueId: action.id,
331
- techniqueName: technique.name,
332
- phase: technique.phase,
333
- success: result.success,
334
- duration: result.duration,
335
- artifacts: result.artifacts,
336
- detectionRisk: result.detectionRisk,
337
- nextTechniques: result.nextTechniques,
338
- };
339
- realExecutions.push(execResult);
340
- // Notify completion
341
- options.onTechniqueComplete?.(execResult);
342
- // Track phase completion
343
- if (result.success && !completedPhases.includes(technique.phase)) {
344
- completedPhases.push(technique.phase);
345
- }
346
- // Update chain progress
347
- options.onChainProgress?.(chain, chain.currentPhase);
348
- // Short delay between techniques for stealth
349
- if (stealth) {
350
- await new Promise(r => setTimeout(r, 500 + Math.random() * 1000));
351
- }
352
- }
353
- }
354
- // Compute real execution metrics
355
- const rlState = getRLState();
356
- const realMetrics = {
357
- totalTechniquesExecuted: realExecutions.length,
358
- successfulTechniques: realExecutions.filter(e => e.success).length,
359
- failedTechniques: realExecutions.filter(e => !e.success).length,
360
- totalDuration: realExecutions.reduce((sum, e) => sum + e.duration, 0),
361
- averageDetectionRisk: realExecutions.length > 0
362
- ? realExecutions.reduce((sum, e) => sum + e.detectionRisk, 0) / realExecutions.length
363
- : 0,
364
- phasesCompleted: completedPhases,
365
- artifactsCollected: realExecutions.reduce((sum, e) => sum + e.artifacts.length, 0),
366
- rlRewardAverage: rlState.avgReward,
367
- };
368
- // Now run the auto-orchestrator for comprehensive analysis and deliverable
369
- const autoConfig = {
370
- maxExecutionTime: options.maxExecutionTime ?? 60 * 60 * 1000,
371
- maxCycles: options.maxCycles ?? 20,
372
- depth,
373
- stealthMode: stealth,
374
- generateDeliverable: true,
375
- deliverableType: 'apt-analysis',
376
- outputDir: options.outputDir ?? `${this.workingDir}/deliverables`,
377
- exportFormats: ['markdown', 'json', 'html'],
378
- onProgress: options.onProgress,
379
- onDeliverable: options.onDeliverable,
380
- };
381
- // Build summary from real executions for the AI orchestrator
382
- const realExecutionSummary = this.buildRealExecutionSummary(realExecutions, realMetrics);
383
- const result = await this.autoOrchestrator.execute(`APT SIMULATION ANALYSIS: ${request}\n\n` +
384
- `REAL EXECUTION RESULTS:\n${realExecutionSummary}\n\n` +
385
- `Analyze the real execution results and provide:\n` +
386
- `1. Tactical analysis of what was discovered\n` +
387
- `2. Risk assessment based on actual findings\n` +
388
- `3. Recommendations for defensive improvements\n` +
389
- `4. Evidence preservation notes\n\n` +
390
- `Targets: ${targets.join(', ')}\n` +
391
- `Constraints: ${options.constraints?.join(', ') || intent.constraints.join(', ') || 'standard ROE'}`, autoConfig);
392
- // Get all active chains for reporting
393
- const activeChains = listActiveChains();
394
- const chainStats = getChainStats();
395
- return {
396
- mode: 'apt-chain',
397
- success: result.success && realMetrics.successfulTechniques > 0,
398
- finalResponse: result.summary,
399
- toolsUsed: [...result.metrics.toolsUsed, ...realExecutions.map(e => `tao:${e.techniqueId}`)],
400
- autoResult: result,
401
- deliverable: result.deliverable,
402
- deliverablePaths: result.deliverablePaths,
403
- infrastructureStack: stack,
404
- attackChainPhases: completedPhases.map(p => p),
405
- persistenceMechanisms: stack?.persistence,
406
- // Real execution data
407
- realExecutions,
408
- realMetrics,
409
- attackChains: activeChains,
410
- summary: `APT simulation: ${realMetrics.successfulTechniques}/${realMetrics.totalTechniquesExecuted} techniques, ${realMetrics.artifactsCollected} artifacts`,
411
- duration: Date.now() - startTime,
412
- };
413
- }
414
- /**
415
- * Build human-readable summary of real technique executions
416
- */
417
- buildRealExecutionSummary(executions, metrics) {
418
- const lines = [];
419
- lines.push(`## Execution Metrics`);
420
- lines.push(`- Total techniques: ${metrics.totalTechniquesExecuted}`);
421
- lines.push(`- Successful: ${metrics.successfulTechniques}`);
422
- lines.push(`- Failed: ${metrics.failedTechniques}`);
423
- lines.push(`- Total duration: ${(metrics.totalDuration / 1000).toFixed(1)}s`);
424
- lines.push(`- Average detection risk: ${(metrics.averageDetectionRisk * 100).toFixed(1)}%`);
425
- lines.push(`- Artifacts collected: ${metrics.artifactsCollected}`);
426
- lines.push(`- Phases completed: ${metrics.phasesCompleted.join(', ') || 'none'}`);
427
- lines.push('');
428
- lines.push(`## Technique Execution Details`);
429
- for (const exec of executions) {
430
- const status = exec.success ? '✓' : '✗';
431
- lines.push(`### ${status} ${exec.techniqueName} (${exec.techniqueId})`);
432
- lines.push(`- Phase: ${exec.phase}`);
433
- lines.push(`- Duration: ${exec.duration}ms`);
434
- lines.push(`- Detection risk: ${(exec.detectionRisk * 100).toFixed(1)}%`);
435
- if (exec.artifacts.length > 0) {
436
- lines.push(`- Artifacts:`);
437
- for (const artifact of exec.artifacts.slice(0, 10)) {
438
- lines.push(` - [${artifact.type}] ${artifact.data.slice(0, 100)}${artifact.data.length > 100 ? '...' : ''}`);
439
- }
440
- }
441
- if (exec.nextTechniques.length > 0) {
442
- lines.push(`- Suggested next: ${exec.nextTechniques.join(', ')}`);
443
- }
444
- lines.push('');
445
- }
446
- return lines.join('\n');
447
- }
448
- /**
449
- * Run infrastructure deployment mode
450
- * Deploys full stack infrastructure for operations
451
- */
452
- async runInfrastructure(request, options, startTime) {
453
- const region = options.region || 'us';
454
- const stack = getInfrastructureStack(region);
455
- if (!stack) {
456
- return {
457
- mode: 'infrastructure',
458
- success: false,
459
- finalResponse: `No infrastructure stack available for region: ${region}`,
460
- toolsUsed: [],
461
- summary: 'Infrastructure deployment failed - no stack',
462
- duration: Date.now() - startTime,
463
- };
464
- }
465
- const deployScript = generateDeploymentScript(stack);
466
- const teardownScript = generateTeardownScript(stack);
467
- const opsecList = generateOpsecChecklist(stack);
468
- // Notify callback if provided
469
- if (options.onInfrastructure) {
470
- options.onInfrastructure(stack);
471
- }
472
- // Generate infrastructure assessment deliverable
473
- const deliverable = await this.deliverableGenerator.generate('infrastructure-assessment', {
474
- finalResponse: `Infrastructure stack deployed: ${stack.name}`,
475
- toolsUsed: ['infrastructure-deploy'],
476
- planOnly: false,
477
- tookAction: true,
478
- completion: {
479
- isComplete: true,
480
- confidence: 1,
481
- signals: {
482
- hasExplicitCompletionStatement: true,
483
- hasIncompleteWorkIndicators: false,
484
- hasPendingActionIndicators: false,
485
- hasErrorIndicators: false,
486
- hasFollowUpQuestions: false,
487
- toolsUsedInLastResponse: 1,
488
- lastToolWasReadOnly: false,
489
- consecutiveResponsesWithoutTools: 0,
490
- hasRecentFileWrites: false,
491
- hasRecentCommits: false,
492
- todoItemsPending: 0,
493
- todoItemsCompleted: 1,
494
- mentionsFutureWork: false,
495
- completionConfidence: 1,
496
- },
497
- reason: 'Infrastructure deployment',
498
- shouldVerify: false,
499
- },
500
- exitReason: 'complete',
501
- statusSummary: 'Infrastructure deployed',
502
- limitations: [],
503
- recommendations: ['Review OPSEC checklist', 'Test all components'],
504
- }, this.agent.getHistory(), { customTitle: `Infrastructure: ${stack.name}` });
505
- let deliverablePaths;
506
- if (options.outputDir && options.exportFormats) {
507
- deliverablePaths = await this.exportDeliverable(deliverable, options.outputDir, options.exportFormats);
508
- }
509
- return {
510
- mode: 'infrastructure',
511
- success: true,
512
- finalResponse: `Infrastructure stack ready: ${stack.name}\n\nComponents: ${stack.components.length}\nPersistence mechanisms: ${stack.persistence.length}\nCost estimate: $${stack.costEstimate.monthly}/month`,
513
- toolsUsed: ['infrastructure-deploy', 'script-generator'],
514
- infrastructureStack: stack,
515
- deploymentScript: deployScript,
516
- teardownScript: teardownScript,
517
- opsecChecklist: opsecList,
518
- deliverable,
519
- deliverablePaths,
520
- persistenceMechanisms: stack.persistence,
521
- summary: `${region.toUpperCase()} infrastructure: ${stack.components.length} components, ${stack.persistence.length} persistence mechanisms`,
522
- duration: Date.now() - startTime,
523
- };
524
- }
525
- /**
526
- * Run incident response procedure generation
527
- */
528
- async runIncidentResponse(request, options, startTime) {
529
- const deliverable = await this.deliverableGenerator.generate('incident-response', {
530
- finalResponse: request,
531
- toolsUsed: [],
532
- planOnly: false,
533
- tookAction: false,
534
- completion: {
535
- isComplete: true,
536
- confidence: 1,
537
- signals: {
538
- hasExplicitCompletionStatement: true,
539
- hasIncompleteWorkIndicators: false,
540
- hasPendingActionIndicators: false,
541
- hasErrorIndicators: false,
542
- hasFollowUpQuestions: false,
543
- toolsUsedInLastResponse: 0,
544
- lastToolWasReadOnly: false,
545
- consecutiveResponsesWithoutTools: 0,
546
- hasRecentFileWrites: false,
547
- hasRecentCommits: false,
548
- todoItemsPending: 0,
549
- todoItemsCompleted: 0,
550
- mentionsFutureWork: false,
551
- completionConfidence: 1,
552
- },
553
- reason: 'Incident response generation',
554
- shouldVerify: false,
555
- },
556
- exitReason: 'complete',
557
- statusSummary: 'Incident response procedures generated',
558
- limitations: [],
559
- recommendations: [],
560
- }, this.agent.getHistory(), { customTitle: `Incident Response: ${request}` });
561
- let deliverablePaths;
562
- if (options.outputDir && options.exportFormats) {
563
- deliverablePaths = await this.exportDeliverable(deliverable, options.outputDir, options.exportFormats);
564
- }
565
- return {
566
- mode: 'incident-response',
567
- success: true,
568
- finalResponse: `Generated incident response procedures with ${deliverable.procedures?.length || 0} procedures`,
569
- toolsUsed: [],
570
- deliverable,
571
- deliverablePaths,
572
- summary: `IR procedures: ${deliverable.procedures?.length || 0} procedures generated`,
573
- duration: Date.now() - startTime,
574
- };
575
- }
576
- /**
577
- * Run security training module generation
578
- */
579
- async runTraining(request, options, startTime) {
580
- const deliverable = await this.deliverableGenerator.generate('training-module', {
581
- finalResponse: request,
582
- toolsUsed: [],
583
- planOnly: false,
584
- tookAction: false,
585
- completion: {
586
- isComplete: true,
587
- confidence: 1,
588
- signals: {
589
- hasExplicitCompletionStatement: true,
590
- hasIncompleteWorkIndicators: false,
591
- hasPendingActionIndicators: false,
592
- hasErrorIndicators: false,
593
- hasFollowUpQuestions: false,
594
- toolsUsedInLastResponse: 0,
595
- lastToolWasReadOnly: false,
596
- consecutiveResponsesWithoutTools: 0,
597
- hasRecentFileWrites: false,
598
- hasRecentCommits: false,
599
- todoItemsPending: 0,
600
- todoItemsCompleted: 0,
601
- mentionsFutureWork: false,
602
- completionConfidence: 1,
603
- },
604
- reason: 'Training module generation',
605
- shouldVerify: false,
606
- },
607
- exitReason: 'complete',
608
- statusSummary: 'Training modules generated',
609
- limitations: [],
610
- recommendations: [],
611
- }, this.agent.getHistory(), { customTitle: `Security Training: ${request}` });
612
- let deliverablePaths;
613
- if (options.outputDir && options.exportFormats) {
614
- deliverablePaths = await this.exportDeliverable(deliverable, options.outputDir, options.exportFormats);
615
- }
616
- return {
617
- mode: 'training',
618
- success: true,
619
- finalResponse: `Generated ${deliverable.training?.length || 0} training modules`,
620
- toolsUsed: [],
621
- deliverable,
622
- deliverablePaths,
623
- summary: `Training: ${deliverable.training?.length || 0} modules generated`,
624
- duration: Date.now() - startTime,
625
- };
626
- }
627
- /**
628
- * Run compliance audit mode
629
- */
630
- async runCompliance(request, options, startTime) {
631
- const agencyTypes = options.agencyTypes || ['federal-le', 'regulatory'];
632
- const frameworks = getApplicableLegalFrameworks(agencyTypes);
633
- const deliverable = await this.deliverableGenerator.generate('compliance-audit', {
634
- finalResponse: `Compliance audit: ${frameworks.map(f => f.name).join(', ')}`,
635
- toolsUsed: [],
636
- planOnly: false,
637
- tookAction: false,
638
- completion: {
639
- isComplete: true,
640
- confidence: 1,
641
- signals: {
642
- hasExplicitCompletionStatement: true,
643
- hasIncompleteWorkIndicators: false,
644
- hasPendingActionIndicators: false,
645
- hasErrorIndicators: false,
646
- hasFollowUpQuestions: false,
647
- toolsUsedInLastResponse: 0,
648
- lastToolWasReadOnly: false,
649
- consecutiveResponsesWithoutTools: 0,
650
- hasRecentFileWrites: false,
651
- hasRecentCommits: false,
652
- todoItemsPending: 0,
653
- todoItemsCompleted: 0,
654
- mentionsFutureWork: false,
655
- completionConfidence: 1,
656
- },
657
- reason: 'Compliance audit',
658
- shouldVerify: false,
659
- },
660
- exitReason: 'complete',
661
- statusSummary: 'Compliance audit completed',
662
- limitations: [],
663
- recommendations: frameworks.flatMap(f => f.requirements.map(r => r.requirement)),
664
- }, this.agent.getHistory(), { customTitle: `Compliance Audit: ${request}` });
665
- let deliverablePaths;
666
- if (options.outputDir && options.exportFormats) {
667
- deliverablePaths = await this.exportDeliverable(deliverable, options.outputDir, options.exportFormats);
668
- }
669
- return {
670
- mode: 'compliance',
671
- success: true,
672
- finalResponse: `Compliance audit completed against ${frameworks.length} frameworks`,
673
- toolsUsed: [],
674
- deliverable,
675
- deliverablePaths,
676
- summary: `Compliance: ${frameworks.length} frameworks, ${deliverable.controls?.length || 0} controls assessed`,
677
- duration: Date.now() - startTime,
678
- };
679
- }
680
- /**
681
- * Run full red team playbook mode
682
- * Combines APT chain with infrastructure and deliverables
683
- */
684
- async runRedTeam(request, options, startTime) {
685
- const region = options.region || 'us';
686
- const stack = getInfrastructureStack(region);
687
- // Execute red team operations
688
- const autoConfig = {
689
- maxExecutionTime: options.maxExecutionTime ?? 90 * 60 * 1000, // 90 minutes
690
- maxCycles: options.maxCycles ?? 25,
691
- depth: options.depth ?? 'deep',
692
- stealthMode: options.stealthMode ?? true,
693
- generateDeliverable: true,
694
- deliverableType: 'red-team-playbook',
695
- outputDir: options.outputDir ?? `${this.workingDir}/deliverables`,
696
- exportFormats: ['markdown', 'json', 'html'],
697
- onProgress: options.onProgress,
698
- onDeliverable: options.onDeliverable,
699
- };
700
- const result = await this.autoOrchestrator.execute(`RED TEAM OPERATION: ${request}\n\n` +
701
- `Infrastructure: ${stack?.name || 'standard'}\n` +
702
- `Execute full red team playbook:\n` +
703
- `1. Infrastructure deployment and verification\n` +
704
- `2. Reconnaissance (OSINT, active scanning)\n` +
705
- `3. Initial access (phishing, exploitation)\n` +
706
- `4. Privilege escalation\n` +
707
- `5. Persistence establishment\n` +
708
- `6. Lateral movement\n` +
709
- `7. Data discovery and exfiltration\n` +
710
- `8. Cleanup and reporting\n\n` +
711
- `Targets: ${options.targets?.join(', ') || 'as specified'}\n` +
712
- `Stealth priority: ${options.stealthMode ? 'HIGH' : 'STANDARD'}`, autoConfig);
713
- return {
714
- mode: 'red-team',
715
- success: result.success,
716
- finalResponse: result.summary,
717
- toolsUsed: result.metrics.toolsUsed,
718
- autoResult: result,
719
- deliverable: result.deliverable,
720
- deliverablePaths: result.deliverablePaths,
721
- infrastructureStack: stack,
722
- deploymentScript: stack ? generateDeploymentScript(stack) : undefined,
723
- teardownScript: stack ? generateTeardownScript(stack) : undefined,
724
- opsecChecklist: stack ? generateOpsecChecklist(stack) : undefined,
725
- attackChainPhases: ['recon', 'initial-access', 'privesc', 'persistence', 'lateral', 'exfil', 'cleanup'],
726
- persistenceMechanisms: stack?.persistence,
727
- summary: `Red team: ${result.metrics.techniquesSucceeded}/${result.metrics.techniquesExecuted} techniques, ${result.metrics.chainsCompleted} chains`,
728
- duration: Date.now() - startTime,
729
- };
730
- }
731
- /**
732
- * Run A2AD (Anti-Access/Area Denial) mode - REAL EXECUTION
733
- * Full offensive APT against defense systems, contractors, any stack
734
- * Uses direct TAO technique execution - actual DNS, ports, HTTP, commands
735
- */
736
- async runA2AD(request, options, startTime) {
737
- const targets = options.targets || [];
738
- const depth = this.normalizeDepth(options.depth ?? 'deep');
739
- const stealth = options.stealthMode ?? true;
740
- const realExecutions = [];
741
- const attackChains = [];
742
- // A2AD phases - full kill-chain with cloud/SaaS techniques for maximum coverage
743
- const a2adPhases = [
744
- {
745
- phase: 'reconnaissance',
746
- techniques: [
747
- // DNS & Network
748
- 'dns_enum', 'whois_recon', 'asn_lookup', 'dns_zone_transfer', 'subdomain_enum',
749
- // SSL/TLS & Certificates
750
- 'ssl_analysis', 'ct_search',
751
- // Web & Technology
752
- 'web_fingerprint', 'tech_fingerprint', 'email_security',
753
- // Cloud Provider Detection
754
- 'cloud_detect', 's3_enum', 'gcs_enum', 'azure_enum',
755
- ],
756
- },
757
- {
758
- phase: 'weaponization',
759
- techniques: [
760
- // Port & Service Scanning
761
- 'port_scan', 'full_port_scan', 'service_enum',
762
- // Protocol Enumeration
763
- 'ssh_enum', 'smb_enum',
764
- // Web Enumeration
765
- 'dir_enum', 'api_discovery', 'vuln_scan',
766
- ],
767
- },
768
- {
769
- phase: 'delivery',
770
- techniques: ['credential_spray'],
771
- },
772
- {
773
- phase: 'exploitation',
774
- techniques: ['exploit_attempt', 'cloud_metadata'],
775
- },
776
- {
777
- phase: 'installation',
778
- techniques: ['privesc', 'process_enum', 'persistence', 'sched_persist', 'ssh_persist'],
779
- },
780
- {
781
- phase: 'command-control',
782
- techniques: ['c2_beacon', 'network_discovery', 'lateral_move'],
783
- },
784
- {
785
- phase: 'actions-on-objectives',
786
- techniques: ['file_discovery', 'credential_harvest', 'memory_dump', 'exfil', 'cleanup'],
787
- },
788
- ];
789
- // REAL EXECUTION - Direct technique calls
790
- for (const target of targets) {
791
- const intent = parseNaturalLanguageIntent(`A2AD against ${target}: ${request}`);
792
- const chain = planAttackChain(intent, `A2AD_${target}`);
793
- attackChains.push(chain);
794
- for (const { phase, techniques } of a2adPhases) {
795
- const limit = depth === 'quick' ? 2 : depth === 'standard' ? 4 : techniques.length;
796
- for (const techniqueId of techniques.slice(0, limit)) {
797
- const technique = techniqueRegistry.get(techniqueId);
798
- if (!technique)
799
- continue;
800
- if (stealth && technique.stealthRating < 0.3)
801
- continue;
802
- options.onTechniqueStart?.(techniqueId, target);
803
- try {
804
- // REAL execution - actual network ops, DNS, TCP, HTTP, commands
805
- const result = await technique.execute({
806
- target,
807
- depth,
808
- stealth,
809
- timeout: 60000,
810
- context: {},
811
- });
812
- const execResult = {
813
- techniqueId: technique.id,
814
- techniqueName: technique.name,
815
- phase,
816
- success: result.success,
817
- duration: result.duration,
818
- artifacts: result.artifacts,
819
- detectionRisk: result.detectionRisk,
820
- nextTechniques: result.nextTechniques,
821
- };
822
- realExecutions.push(execResult);
823
- options.onTechniqueComplete?.(execResult);
824
- if (stealth && result.detectionRisk > 0.7)
825
- break;
826
- }
827
- catch {
828
- realExecutions.push({
829
- techniqueId: technique.id,
830
- techniqueName: technique.name,
831
- phase,
832
- success: false,
833
- duration: 0,
834
- artifacts: [],
835
- detectionRisk: 0.5,
836
- nextTechniques: [],
837
- });
838
- }
839
- }
840
- }
841
- }
842
- // Metrics
843
- const successCount = realExecutions.filter(r => r.success).length;
844
- const realMetrics = {
845
- totalTechniquesExecuted: realExecutions.length,
846
- successfulTechniques: successCount,
847
- failedTechniques: realExecutions.length - successCount,
848
- totalDuration: Date.now() - startTime,
849
- averageDetectionRisk: realExecutions.length > 0
850
- ? realExecutions.reduce((s, r) => s + r.detectionRisk, 0) / realExecutions.length : 0,
851
- phasesCompleted: [...new Set(realExecutions.filter(r => r.success).map(r => r.phase))],
852
- artifactsCollected: realExecutions.reduce((s, r) => s + r.artifacts.length, 0),
853
- rlRewardAverage: getRLState().avgReward,
854
- };
855
- // Generate deliverable
856
- let deliverable;
857
- let deliverablePaths;
858
- if (options.generateDeliverable !== false) {
859
- deliverable = await this.deliverableGenerator.generate('apt-analysis', {
860
- finalResponse: `A2/AD: ${successCount}/${realExecutions.length} techniques`,
861
- toolsUsed: realExecutions.map(r => r.techniqueId),
862
- planOnly: false,
863
- tookAction: true,
864
- completion: {
865
- isComplete: true,
866
- confidence: successCount / Math.max(realExecutions.length, 1),
867
- signals: {
868
- hasExplicitCompletionStatement: true,
869
- hasIncompleteWorkIndicators: false,
870
- hasPendingActionIndicators: false,
871
- hasErrorIndicators: false,
872
- hasFollowUpQuestions: false,
873
- toolsUsedInLastResponse: realExecutions.length,
874
- lastToolWasReadOnly: false,
875
- consecutiveResponsesWithoutTools: 0,
876
- hasRecentFileWrites: false,
877
- hasRecentCommits: false,
878
- todoItemsPending: 0,
879
- todoItemsCompleted: realExecutions.length,
880
- mentionsFutureWork: false,
881
- completionConfidence: successCount / Math.max(realExecutions.length, 1),
882
- },
883
- reason: 'A2/AD complete',
884
- shouldVerify: false,
885
- },
886
- exitReason: 'complete',
887
- statusSummary: 'A2/AD operation completed',
888
- limitations: [],
889
- recommendations: realExecutions.flatMap(r => r.nextTechniques),
890
- }, this.agent.getHistory(), { customTitle: `A2/AD: ${request}`, targets });
891
- if (options.outputDir && options.exportFormats) {
892
- deliverablePaths = await this.exportDeliverable(deliverable, options.outputDir, options.exportFormats);
893
- }
894
- }
895
- const region = options.region || 'us';
896
- const stack = getInfrastructureStack(region);
897
- return {
898
- mode: 'a2ad',
899
- success: successCount > 0,
900
- finalResponse: `A2/AD REAL EXECUTION: ${successCount}/${realExecutions.length} techniques against ${targets.length} targets`,
901
- toolsUsed: realExecutions.map(r => r.techniqueId),
902
- infrastructureStack: stack,
903
- deploymentScript: stack ? generateDeploymentScript(stack) : undefined,
904
- teardownScript: stack ? generateTeardownScript(stack) : undefined,
905
- opsecChecklist: stack ? generateOpsecChecklist(stack) : undefined,
906
- attackChainPhases: a2adPhases.map(p => p.phase),
907
- persistenceMechanisms: stack?.persistence,
908
- realExecutions,
909
- realMetrics,
910
- attackChains,
911
- deliverable,
912
- deliverablePaths,
913
- summary: `A2/AD: ${successCount}/${realExecutions.length} real techniques, ${realMetrics.artifactsCollected} artifacts`,
914
- duration: Date.now() - startTime,
915
- };
916
- }
917
- /**
918
- * Run Direct APT mode - real execution without AI orchestration overhead
919
- * Pure TAO technique execution with RL guidance
920
- */
921
- async runDirectAPT(request, options, startTime) {
922
- const intent = parseNaturalLanguageIntent(request);
923
- const targets = options.targets ?? intent.targets;
924
- const stealth = options.stealthMode ?? intent.constraints.includes('stealth');
925
- const depth = this.normalizeDepth(options.depth ?? intent.depth);
926
- const realExecutions = [];
927
- const completedPhases = [];
928
- // Execute REAL techniques directly without AI orchestration
929
- for (const target of targets) {
930
- const chain = planAttackChain(intent, `Direct APT: ${target}`);
931
- options.onChainProgress?.(chain, 0);
932
- while (chain.state === 'planning' || chain.state === 'executing') {
933
- const action = selectNextTechnique(chain);
934
- if (!action)
935
- break;
936
- const technique = techniqueRegistry.get(action.id);
937
- if (!technique)
938
- continue;
939
- options.onTechniqueStart?.(action.id, target);
940
- const params = {
941
- target,
942
- depth,
943
- stealth,
944
- timeout: depth === 'quick' ? 5000 : depth === 'deep' ? 30000 : 15000,
945
- context: {},
946
- };
947
- const { result } = await executeTechniqueInChain(chain, action, params);
948
- const execResult = {
949
- techniqueId: action.id,
950
- techniqueName: technique.name,
951
- phase: technique.phase,
952
- success: result.success,
953
- duration: result.duration,
954
- artifacts: result.artifacts,
955
- detectionRisk: result.detectionRisk,
956
- nextTechniques: result.nextTechniques,
957
- };
958
- realExecutions.push(execResult);
959
- options.onTechniqueComplete?.(execResult);
960
- if (result.success && !completedPhases.includes(technique.phase)) {
961
- completedPhases.push(technique.phase);
962
- }
963
- options.onChainProgress?.(chain, chain.currentPhase);
964
- if (stealth) {
965
- await new Promise(r => setTimeout(r, 300 + Math.random() * 700));
966
- }
967
- }
968
- }
969
- const rlState = getRLState();
970
- const realMetrics = {
971
- totalTechniquesExecuted: realExecutions.length,
972
- successfulTechniques: realExecutions.filter(e => e.success).length,
973
- failedTechniques: realExecutions.filter(e => !e.success).length,
974
- totalDuration: realExecutions.reduce((sum, e) => sum + e.duration, 0),
975
- averageDetectionRisk: realExecutions.length > 0
976
- ? realExecutions.reduce((sum, e) => sum + e.detectionRisk, 0) / realExecutions.length
977
- : 0,
978
- phasesCompleted: completedPhases,
979
- artifactsCollected: realExecutions.reduce((sum, e) => sum + e.artifacts.length, 0),
980
- rlRewardAverage: rlState.avgReward,
981
- };
982
- const activeChains = listActiveChains();
983
- return {
984
- mode: 'direct-apt',
985
- success: realMetrics.successfulTechniques > 0,
986
- finalResponse: this.buildRealExecutionSummary(realExecutions, realMetrics),
987
- toolsUsed: realExecutions.map(e => `tao:${e.techniqueId}`),
988
- realExecutions,
989
- realMetrics,
990
- attackChains: activeChains,
991
- attackChainPhases: completedPhases.map(p => p),
992
- summary: `Direct APT: ${realMetrics.successfulTechniques}/${realMetrics.totalTechniquesExecuted} techniques, ${realMetrics.artifactsCollected} artifacts`,
993
- duration: Date.now() - startTime,
994
- };
995
- }
996
- /**
997
- * Normalize depth value to valid type
998
- */
999
- normalizeDepth(depth) {
1000
- if (depth === 'quick' || depth === 'standard' || depth === 'deep') {
1001
- return depth;
1002
- }
1003
- return 'standard';
1004
- }
1005
- // ═══════════════════════════════════════════════════════════════════════════════
1006
- // GOAL-ORIENTED APT EXECUTION
1007
- // ═══════════════════════════════════════════════════════════════════════════════
1008
- /** Technique mappings for each APT goal */
1009
- goalTechniques = {
1010
- reconnaissance: [
1011
- // DNS & Network Intelligence
1012
- 'dns_enum', 'whois_recon', 'asn_lookup', 'subdomain_enum', 'dns_zone_transfer',
1013
- 'domain_intel', 'network_mapping', 'port_scan', 'service_enum',
1014
- // Cryptographic Mapping & SSL/TLS Analysis
1015
- 'crypto_map', 'ssl_analysis', 'ct_search',
1016
- // Stack & Technology Fingerprinting
1017
- 'stack_fingerprint', 'tech_fingerprint', 'web_fingerprint',
1018
- // Cloud Provider Enumeration
1019
- 'cloud_detect', 's3_enum', 'gcs_enum', 'azure_enum', 'cloud_metadata',
1020
- // Corporate Infrastructure Discovery
1021
- 'corp_enum', 'business_sw_enum', 'saas_enum', 'email_security',
1022
- // Product & API Surface Mapping
1023
- 'product_enum', 'api_surface_map', 'api_discovery', 'git_analysis',
1024
- ],
1025
- access: [
1026
- 'credential_spray', 'exploit_attempt', 'cloud_metadata', 'container_escape',
1027
- ],
1028
- persistence: [
1029
- 'persistence', 'sched_persist', 'ssh_persist', 'c2_beacon',
1030
- ],
1031
- privilege: [
1032
- 'privesc', 'credential_harvest', 'memory_dump', 'cloud_creds',
1033
- ],
1034
- lateral: [
1035
- 'lateral_move', 'network_discovery', 'smb_enum', 'ssh_enum',
1036
- ],
1037
- collection: [
1038
- // Discovery & Enumeration
1039
- 'file_discovery', 'data_discovery', 'process_enum', 'cloud_enum',
1040
- // Credential & Code Collection
1041
- 'credential_harvest', 'git_analysis', 'supply_chain_enum',
1042
- // Enterprise Stack Collection
1043
- 'stack_fingerprint', 'product_enum', 'business_sw_enum', 'saas_enum',
1044
- 'corp_enum', 'domain_intel', 'api_surface_map',
1045
- ],
1046
- exfiltration: [
1047
- 'data_staging', 'exfil', 'c2_beacon',
1048
- ],
1049
- impact: [
1050
- 'service_disruption', 'resource_exhaustion', 'cleanup',
1051
- ],
1052
- stealth: [
1053
- 'cleanup', 'process_enum', 'network_discovery',
1054
- ],
1055
- all: [], // Populated dynamically with all techniques
1056
- };
1057
- /**
1058
- * Run goal-oriented APT execution
1059
- * Selects techniques based on specified goals for maximum effectiveness
1060
- */
1061
- async runGoalOriented(request, options, startTime) {
1062
- const targets = options.targets || [];
1063
- const goals = options.goals || (options.goal ? [options.goal] : ['all']);
1064
- const depth = this.normalizeDepth(options.depth ?? 'deep');
1065
- const stealth = options.stealthMode ?? options.minimizeFootprint ?? false;
1066
- const realExecutions = [];
1067
- const achievedGoals = [];
1068
- const allArtifacts = [];
1069
- // Build technique list based on goals
1070
- let techniques = [];
1071
- for (const goal of goals) {
1072
- if (goal === 'all') {
1073
- // Get all registered techniques
1074
- techniques = techniqueRegistry.list().map(t => t.id);
1075
- break;
1076
- }
1077
- techniques.push(...(this.goalTechniques[goal] || []));
1078
- }
1079
- techniques = [...new Set(techniques)]; // Deduplicate
1080
- // Execute techniques for each target
1081
- for (const target of targets) {
1082
- const intent = parseNaturalLanguageIntent(`Goal-oriented APT: ${goals.join(', ')} against ${target}`);
1083
- const chain = planAttackChain(intent, `Goal_${goals.join('_')}_${target}`);
1084
- for (const techniqueId of techniques) {
1085
- const technique = techniqueRegistry.get(techniqueId);
1086
- if (!technique)
1087
- continue;
1088
- if (stealth && technique.stealthRating < 0.3)
1089
- continue;
1090
- options.onTechniqueStart?.(techniqueId, target);
1091
- try {
1092
- const result = await technique.execute({
1093
- target,
1094
- depth,
1095
- stealth,
1096
- timeout: 60000,
1097
- context: {},
1098
- });
1099
- const execResult = {
1100
- techniqueId: technique.id,
1101
- techniqueName: technique.name,
1102
- phase: technique.phase,
1103
- success: result.success,
1104
- duration: result.duration,
1105
- artifacts: result.artifacts,
1106
- detectionRisk: result.detectionRisk,
1107
- nextTechniques: result.nextTechniques,
1108
- };
1109
- realExecutions.push(execResult);
1110
- allArtifacts.push(...result.artifacts);
1111
- options.onTechniqueComplete?.(execResult);
1112
- // Check if any goals were achieved
1113
- for (const goal of goals) {
1114
- if (!achievedGoals.includes(goal)) {
1115
- const goalTechs = this.goalTechniques[goal] || [];
1116
- if (goalTechs.includes(techniqueId) && result.success) {
1117
- achievedGoals.push(goal);
1118
- options.onGoalAchieved?.(goal, result.artifacts);
1119
- }
1120
- }
1121
- }
1122
- if (stealth && result.detectionRisk > 0.7)
1123
- break;
1124
- }
1125
- catch {
1126
- realExecutions.push({
1127
- techniqueId: technique.id,
1128
- techniqueName: technique.name,
1129
- phase: technique.phase,
1130
- success: false,
1131
- duration: 0,
1132
- artifacts: [],
1133
- detectionRisk: 0.5,
1134
- nextTechniques: [],
1135
- });
1136
- }
1137
- }
1138
- // Maintain access if requested
1139
- if (options.maintainAccess) {
1140
- for (const persistTech of ['persistence', 'sched_persist', 'ssh_persist']) {
1141
- const technique = techniqueRegistry.get(persistTech);
1142
- if (technique) {
1143
- try {
1144
- await technique.execute({ target, depth, stealth, timeout: 30000, context: {} });
1145
- }
1146
- catch { /* ignore */ }
1147
- }
1148
- }
1149
- }
1150
- }
1151
- const successCount = realExecutions.filter(r => r.success).length;
1152
- const realMetrics = {
1153
- totalTechniquesExecuted: realExecutions.length,
1154
- successfulTechniques: successCount,
1155
- failedTechniques: realExecutions.length - successCount,
1156
- totalDuration: Date.now() - startTime,
1157
- averageDetectionRisk: realExecutions.length > 0
1158
- ? realExecutions.reduce((s, r) => s + r.detectionRisk, 0) / realExecutions.length : 0,
1159
- phasesCompleted: [...new Set(realExecutions.filter(r => r.success).map(r => r.phase))],
1160
- artifactsCollected: allArtifacts.length,
1161
- rlRewardAverage: getRLState().avgReward,
1162
- };
1163
- return {
1164
- mode: options.mode || 'direct-apt',
1165
- success: successCount > 0,
1166
- finalResponse: `Goal-oriented APT: ${achievedGoals.length}/${goals.length} goals achieved, ${successCount}/${realExecutions.length} techniques`,
1167
- toolsUsed: realExecutions.map(r => r.techniqueId),
1168
- realExecutions,
1169
- realMetrics,
1170
- attackChains: listActiveChains(),
1171
- attackChainPhases: [...new Set(realExecutions.map(r => r.phase))],
1172
- summary: `Goals: ${achievedGoals.join(', ')} | ${allArtifacts.length} artifacts collected`,
1173
- duration: Date.now() - startTime,
1174
- };
1175
- }
1176
- /**
1177
- * Run persistent access mode - establish and maintain long-term presence
1178
- */
1179
- async runPersistentAccess(request, options, startTime) {
1180
- return this.runGoalOriented(request, {
1181
- ...options,
1182
- goals: ['access', 'persistence', 'stealth'],
1183
- maintainAccess: true,
1184
- minimizeFootprint: true,
1185
- }, startTime);
1186
- }
1187
- /**
1188
- * Run intelligence collection mode - gather all available data
1189
- */
1190
- async runIntelCollection(request, options, startTime) {
1191
- return this.runGoalOriented(request, {
1192
- ...options,
1193
- goals: ['reconnaissance', 'collection', 'exfiltration'],
1194
- collectIntel: true,
1195
- }, startTime);
1196
- }
1197
- /**
1198
- * Run impact mode - disrupt/destroy/manipulate target infrastructure
1199
- */
1200
- async runImpact(request, options, startTime) {
1201
- return this.runGoalOriented(request, {
1202
- ...options,
1203
- goals: ['access', 'privilege', 'impact'],
1204
- stealthMode: false, // Impact operations are inherently noisy
1205
- }, startTime);
1206
- }
1207
- // ═══════════════════════════════════════════════════════════════════════════════
1208
- // REAL TECHNIQUE EXECUTION - Direct access to TAO execution
1209
- // ═══════════════════════════════════════════════════════════════════════════════
1210
- /**
1211
- * Execute a specific technique against a target with real network operations
1212
- * Can be called directly for granular control
1213
- */
1214
- async executeRealTechnique(techniqueId, target, options = {}) {
1215
- const technique = techniqueRegistry.get(techniqueId);
1216
- if (!technique) {
1217
- throw new Error(`Unknown technique: ${techniqueId}`);
1218
- }
1219
- // Notify start
1220
- options.onStart?.(techniqueId, target);
1221
- const params = {
1222
- target,
1223
- depth: options.depth ?? 'standard',
1224
- stealth: options.stealth ?? false,
1225
- timeout: options.timeout ?? 15000,
1226
- context: options.context ?? {},
1227
- };
1228
- // Create a simple chain for single technique execution
1229
- const intent = parseNaturalLanguageIntent(`execute ${techniqueId} against ${target}`);
1230
- const chain = planAttackChain(intent, `Direct ${techniqueId} execution`);
1231
- const action = { id: techniqueId, params: {}, confidence: 1.0 };
1232
- const { result } = await executeTechniqueInChain(chain, action, params);
1233
- const execResult = {
1234
- techniqueId,
1235
- techniqueName: technique.name,
1236
- phase: technique.phase,
1237
- success: result.success,
1238
- duration: result.duration,
1239
- artifacts: result.artifacts,
1240
- detectionRisk: result.detectionRisk,
1241
- nextTechniques: result.nextTechniques,
1242
- };
1243
- // Notify completion
1244
- options.onComplete?.(execResult);
1245
- return execResult;
1246
- }
1247
- /**
1248
- * Execute reconnaissance techniques against a target
1249
- * Returns structured intel from real DNS/TCP/HTTP operations
1250
- */
1251
- async executeRecon(target, options = {}) {
1252
- const depth = options.depth ?? 'standard';
1253
- const reconTechniques = options.techniques ?? [
1254
- 'dns_enum',
1255
- 'subdomain_enum',
1256
- 'port_scan',
1257
- 'service_enum',
1258
- 'web_fingerprint',
1259
- ];
1260
- // Filter to quick techniques if depth is quick
1261
- const techniques = depth === 'quick'
1262
- ? reconTechniques.slice(0, 3)
1263
- : reconTechniques;
1264
- const results = [];
1265
- const completedPhases = [];
1266
- for (let i = 0; i < techniques.length; i++) {
1267
- const techId = techniques[i];
1268
- if (!techId)
1269
- continue;
1270
- options.onProgress?.(techId, i, techniques.length);
1271
- try {
1272
- const result = await this.executeRealTechnique(techId, target, {
1273
- depth,
1274
- stealth: false,
1275
- timeout: depth === 'deep' ? 30000 : 15000,
1276
- });
1277
- results.push(result);
1278
- if (result.success && !completedPhases.includes(result.phase)) {
1279
- completedPhases.push(result.phase);
1280
- }
1281
- }
1282
- catch {
1283
- // Continue with other techniques on failure
1284
- }
1285
- }
1286
- const rlState = getRLState();
1287
- const metrics = {
1288
- totalTechniquesExecuted: results.length,
1289
- successfulTechniques: results.filter(r => r.success).length,
1290
- failedTechniques: results.filter(r => !r.success).length,
1291
- totalDuration: results.reduce((sum, r) => sum + r.duration, 0),
1292
- averageDetectionRisk: results.length > 0
1293
- ? results.reduce((sum, r) => sum + r.detectionRisk, 0) / results.length
1294
- : 0,
1295
- phasesCompleted: completedPhases,
1296
- artifactsCollected: results.reduce((sum, r) => sum + r.artifacts.length, 0),
1297
- rlRewardAverage: rlState.avgReward,
1298
- };
1299
- options.onProgress?.('complete', techniques.length, techniques.length);
1300
- return {
1301
- target,
1302
- results,
1303
- metrics,
1304
- summary: this.buildRealExecutionSummary(results, metrics),
1305
- };
1306
- }
1307
- /**
1308
- * Get available techniques for a category or phase
1309
- */
1310
- getAvailableTechniques(filter) {
1311
- let techniques = techniqueRegistry.list();
1312
- if (filter?.phase) {
1313
- techniques = techniqueRegistry.getByPhase(filter.phase);
1314
- }
1315
- return techniques.map(t => ({
1316
- id: t.id,
1317
- name: t.name,
1318
- category: t.category,
1319
- phase: t.phase,
1320
- stealthRating: t.stealthRating,
1321
- }));
1322
- }
1323
- /**
1324
- * Get current RL state and statistics
1325
- */
1326
- getRLStats() {
1327
- const rlState = getRLState();
1328
- const chainStats = getChainStats();
1329
- const techniques = techniqueRegistry.list().map(t => ({
1330
- id: t.id,
1331
- successRate: techniqueRegistry.getSuccessRate(t.id),
1332
- }));
1333
- return {
1334
- episode: rlState.episode,
1335
- steps: rlState.steps,
1336
- avgReward: rlState.avgReward,
1337
- chainStats,
1338
- techniques,
1339
- };
1340
- }
1341
- /**
1342
- * Export deliverable to files
1343
- */
1344
- async exportDeliverable(deliverable, outputDir, formats) {
1345
- const fs = await import('node:fs/promises');
1346
- const path = await import('node:path');
1347
- await fs.mkdir(outputDir, { recursive: true });
1348
- const baseName = `${deliverable.type}-${new Date().toISOString().slice(0, 10)}`;
1349
- const paths = {};
1350
- for (const format of formats) {
1351
- let content;
1352
- let extension;
1353
- switch (format) {
1354
- case 'markdown':
1355
- content = exportToMarkdown(deliverable);
1356
- extension = 'md';
1357
- break;
1358
- case 'json':
1359
- content = exportToJSON(deliverable);
1360
- extension = 'json';
1361
- break;
1362
- case 'html':
1363
- content = exportToHTML(deliverable);
1364
- extension = 'html';
1365
- break;
1366
- default:
1367
- continue;
1368
- }
1369
- const filePath = path.join(outputDir, `${baseName}.${extension}`);
1370
- await fs.writeFile(filePath, content, 'utf-8');
1371
- paths[format] = filePath;
1372
- }
1373
- return paths;
1374
- }
1375
- }
1376
- // ═══════════════════════════════════════════════════════════════════════════════
1377
- // FACTORY FUNCTIONS
1378
- // ═══════════════════════════════════════════════════════════════════════════════
1379
- /**
1380
- * Create an orchestrator for the specified mode
1381
- */
1382
- export function createOrchestrator(agent, mode = 'single', workingDir = process.cwd()) {
1383
- return new UnifiedOrchestrator(agent, workingDir);
1384
- }
1385
- /**
1386
- * Quick function to run a task with the appropriate orchestrator
1387
- */
1388
- export async function runTask(agent, request, options = {}) {
1389
- const orchestrator = new UnifiedOrchestrator(agent);
1390
- return orchestrator.run(request, options);
1391
- }
1392
- /**
1393
- * Run security assessment with deliverables
1394
- */
1395
- export async function runSecurityAssessment(agent, objective, options = {}) {
1396
- const orchestrator = new UnifiedOrchestrator(agent);
1397
- return orchestrator.run(objective, {
1398
- mode: 'auto-security',
1399
- deliverableType: options.deliverableType || 'pentest-report',
1400
- depth: options.depth || 'standard',
1401
- stealthMode: options.stealth || false,
1402
- outputDir: options.outputDir || './deliverables',
1403
- exportFormats: ['markdown', 'json', 'html'],
1404
- generateDeliverable: true,
1405
- });
1406
- }
1407
- /**
1408
- * Generate deliverable from current conversation
1409
- */
1410
- export async function generateDeliverable(agent, type, options = {}) {
1411
- const generator = new SecurityDeliverableGenerator();
1412
- const minimalResult = {
1413
- finalResponse: '',
1414
- toolsUsed: [],
1415
- planOnly: false,
1416
- tookAction: false,
1417
- completion: {
1418
- isComplete: true,
1419
- confidence: 1,
1420
- signals: {
1421
- hasExplicitCompletionStatement: true,
1422
- hasIncompleteWorkIndicators: false,
1423
- hasPendingActionIndicators: false,
1424
- hasErrorIndicators: false,
1425
- hasFollowUpQuestions: false,
1426
- toolsUsedInLastResponse: 0,
1427
- lastToolWasReadOnly: false,
1428
- consecutiveResponsesWithoutTools: 0,
1429
- hasRecentFileWrites: false,
1430
- hasRecentCommits: false,
1431
- todoItemsPending: 0,
1432
- todoItemsCompleted: 0,
1433
- mentionsFutureWork: false,
1434
- completionConfidence: 1,
1435
- },
1436
- reason: 'Deliverable generation',
1437
- shouldVerify: false,
1438
- },
1439
- exitReason: 'complete',
1440
- statusSummary: null,
1441
- limitations: [],
1442
- recommendations: [],
1443
- };
1444
- return generator.generate(type, minimalResult, agent.getHistory(), options);
1445
- }
1446
- /**
1447
- * Run APT simulation with full kill-chain
1448
- */
1449
- export async function runAPTSimulation(agent, objective, options = {}) {
1450
- const orchestrator = new UnifiedOrchestrator(agent);
1451
- return orchestrator.run(objective, {
1452
- mode: 'apt-chain',
1453
- targets: options.targets,
1454
- constraints: options.constraints,
1455
- region: options.region || 'us',
1456
- depth: options.depth || 'deep',
1457
- stealthMode: options.stealth ?? true,
1458
- outputDir: options.outputDir || './deliverables',
1459
- exportFormats: ['markdown', 'json', 'html'],
1460
- generateDeliverable: true,
1461
- });
1462
- }
1463
- /**
1464
- * Run red team operation with full playbook
1465
- */
1466
- export async function runRedTeamOperation(agent, objective, options = {}) {
1467
- const orchestrator = new UnifiedOrchestrator(agent);
1468
- return orchestrator.run(objective, {
1469
- mode: 'red-team',
1470
- targets: options.targets,
1471
- region: options.region || 'us',
1472
- stealthMode: options.stealth ?? true,
1473
- outputDir: options.outputDir || './deliverables',
1474
- exportFormats: ['markdown', 'json', 'html'],
1475
- generateDeliverable: true,
1476
- });
1477
- }
1478
- /**
1479
- * Deploy operational infrastructure
1480
- */
1481
- export async function deployInfrastructure(agent, region, options = {}) {
1482
- const orchestrator = new UnifiedOrchestrator(agent);
1483
- return orchestrator.run(`Deploy ${region} infrastructure`, {
1484
- mode: 'infrastructure',
1485
- region,
1486
- outputDir: options.outputDir || './deliverables',
1487
- exportFormats: ['markdown', 'json'],
1488
- generateDeliverable: true,
1489
- });
1490
- }
1491
- /**
1492
- * Generate incident response procedures
1493
- */
1494
- export async function generateIncidentResponse(agent, scenario, options = {}) {
1495
- const orchestrator = new UnifiedOrchestrator(agent);
1496
- return orchestrator.run(scenario, {
1497
- mode: 'incident-response',
1498
- outputDir: options.outputDir || './deliverables',
1499
- exportFormats: ['markdown', 'json', 'html'],
1500
- generateDeliverable: true,
1501
- });
1502
- }
1503
- /**
1504
- * Generate security training module
1505
- */
1506
- export async function generateTrainingModule(agent, topic, options = {}) {
1507
- const orchestrator = new UnifiedOrchestrator(agent);
1508
- return orchestrator.run(topic, {
1509
- mode: 'training',
1510
- outputDir: options.outputDir || './deliverables',
1511
- exportFormats: ['markdown', 'json', 'html'],
1512
- generateDeliverable: true,
1513
- });
1514
- }
1515
- /**
1516
- * Run compliance audit
1517
- */
1518
- export async function runComplianceAudit(agent, scope, options = {}) {
1519
- const orchestrator = new UnifiedOrchestrator(agent);
1520
- return orchestrator.run(scope, {
1521
- mode: 'compliance',
1522
- agencyTypes: options.agencyTypes || ['federal-le', 'regulatory'],
1523
- outputDir: options.outputDir || './deliverables',
1524
- exportFormats: ['markdown', 'json', 'html'],
1525
- generateDeliverable: true,
1526
- });
1527
- }
1528
- /**
1529
- * Run A2/AD operation with REAL technique execution
1530
- * Full offensive APT against defense systems, contractors, any stack (Google, AWS, etc)
1531
- */
1532
- export async function runA2AD(agent, objective, options) {
1533
- const orchestrator = new UnifiedOrchestrator(agent);
1534
- return orchestrator.run(objective, {
1535
- mode: 'a2ad',
1536
- targets: options.targets,
1537
- region: options.region || 'us',
1538
- depth: options.depth || 'deep',
1539
- stealthMode: options.stealth ?? true,
1540
- outputDir: options.outputDir || './deliverables',
1541
- exportFormats: ['markdown', 'json', 'html'],
1542
- generateDeliverable: true,
1543
- onTechniqueStart: options.onTechniqueStart,
1544
- onTechniqueComplete: options.onTechniqueComplete,
1545
- });
1546
- }
1547
- /**
1548
- * Run Direct APT with NO agent overhead - pure real technique execution
1549
- * Maximum speed, direct TAO chains, actual network operations
1550
- */
1551
- export async function runDirectAPT(agent, objective, options) {
1552
- const orchestrator = new UnifiedOrchestrator(agent);
1553
- return orchestrator.run(objective, {
1554
- mode: 'direct-apt',
1555
- targets: options.targets,
1556
- depth: options.depth || 'deep',
1557
- stealthMode: options.stealth ?? false,
1558
- onTechniqueStart: options.onTechniqueStart,
1559
- onTechniqueComplete: options.onTechniqueComplete,
1560
- });
1561
- }
1562
- /**
1563
- * Run goal-oriented APT - specify what you want to achieve
1564
- * Automatically selects appropriate techniques
1565
- */
1566
- export async function runGoalAPT(agent, objective, options) {
1567
- const orchestrator = new UnifiedOrchestrator(agent);
1568
- return orchestrator.run(objective, {
1569
- targets: options.targets,
1570
- goal: options.goal,
1571
- goals: options.goals,
1572
- depth: options.depth || 'deep',
1573
- stealthMode: options.stealth ?? false,
1574
- maintainAccess: options.maintainAccess ?? false,
1575
- onTechniqueComplete: options.onTechniqueComplete,
1576
- onGoalAchieved: options.onGoalAchieved,
1577
- });
1578
- }
1579
- /**
1580
- * Run persistent access mode - establish long-term presence
1581
- */
1582
- export async function runPersistentAccess(agent, objective, options) {
1583
- const orchestrator = new UnifiedOrchestrator(agent);
1584
- return orchestrator.run(objective, {
1585
- mode: 'persistent-access',
1586
- targets: options.targets,
1587
- stealthMode: options.stealth ?? true,
1588
- maintainAccess: true,
1589
- minimizeFootprint: true,
1590
- onTechniqueComplete: options.onTechniqueComplete,
1591
- });
1592
- }
1593
- /**
1594
- * Run intelligence collection - gather all available data
1595
- */
1596
- export async function runIntelCollection(agent, objective, options) {
1597
- const orchestrator = new UnifiedOrchestrator(agent);
1598
- return orchestrator.run(objective, {
1599
- mode: 'intel-collection',
1600
- targets: options.targets,
1601
- depth: options.depth || 'deep',
1602
- collectIntel: true,
1603
- onTechniqueComplete: options.onTechniqueComplete,
1604
- });
1605
- }
1606
- /**
1607
- * Run impact operations - disrupt/destroy/manipulate
1608
- */
1609
- export async function runImpactOps(agent, objective, options) {
1610
- const orchestrator = new UnifiedOrchestrator(agent);
1611
- return orchestrator.run(objective, {
1612
- mode: 'impact',
1613
- targets: options.targets,
1614
- stealthMode: false,
1615
- onTechniqueComplete: options.onTechniqueComplete,
1616
- });
1617
- }
1618
- // ═══════════════════════════════════════════════════════════════════════════════
1619
- // REAL EXECUTION HELPERS - Direct TAO technique execution
1620
- // ═══════════════════════════════════════════════════════════════════════════════
1621
- /**
1622
- * Execute real reconnaissance against a target without agent context
1623
- * Uses actual network operations (DNS, TCP, HTTP)
1624
- */
1625
- export async function executeRealRecon(target, options = {}) {
1626
- const depth = options.depth ?? 'standard';
1627
- const reconTechniques = options.techniques ?? [
1628
- 'dns_enum',
1629
- 'subdomain_enum',
1630
- 'port_scan',
1631
- 'service_enum',
1632
- 'web_fingerprint',
1633
- ];
1634
- const techniques = depth === 'quick'
1635
- ? reconTechniques.slice(0, 3)
1636
- : reconTechniques;
1637
- const results = [];
1638
- const completedPhases = [];
1639
- const intent = parseNaturalLanguageIntent(`recon ${target}`);
1640
- for (let i = 0; i < techniques.length; i++) {
1641
- const techId = techniques[i];
1642
- if (!techId)
1643
- continue;
1644
- const technique = techniqueRegistry.get(techId);
1645
- if (!technique)
1646
- continue;
1647
- options.onProgress?.(techId, i, techniques.length);
1648
- const chain = planAttackChain(intent, `Recon against ${target}`);
1649
- const action = { id: techId, params: {}, confidence: 1.0 };
1650
- const params = {
1651
- target,
1652
- depth,
1653
- stealth: false,
1654
- timeout: depth === 'deep' ? 30000 : 15000,
1655
- context: {},
1656
- };
1657
- try {
1658
- const { result } = await executeTechniqueInChain(chain, action, params);
1659
- const execResult = {
1660
- techniqueId: techId,
1661
- techniqueName: technique.name,
1662
- phase: technique.phase,
1663
- success: result.success,
1664
- duration: result.duration,
1665
- artifacts: result.artifacts,
1666
- detectionRisk: result.detectionRisk,
1667
- nextTechniques: result.nextTechniques,
1668
- };
1669
- results.push(execResult);
1670
- // Notify artifacts
1671
- for (const artifact of result.artifacts) {
1672
- options.onArtifact?.(artifact);
1673
- }
1674
- if (result.success && !completedPhases.includes(technique.phase)) {
1675
- completedPhases.push(technique.phase);
1676
- }
1677
- }
1678
- catch {
1679
- // Continue with other techniques
1680
- }
1681
- }
1682
- const rlState = getRLState();
1683
- const metrics = {
1684
- totalTechniquesExecuted: results.length,
1685
- successfulTechniques: results.filter(r => r.success).length,
1686
- failedTechniques: results.filter(r => !r.success).length,
1687
- totalDuration: results.reduce((sum, r) => sum + r.duration, 0),
1688
- averageDetectionRisk: results.length > 0
1689
- ? results.reduce((sum, r) => sum + r.detectionRisk, 0) / results.length
1690
- : 0,
1691
- phasesCompleted: completedPhases,
1692
- artifactsCollected: results.reduce((sum, r) => sum + r.artifacts.length, 0),
1693
- rlRewardAverage: rlState.avgReward,
1694
- };
1695
- options.onProgress?.('complete', techniques.length, techniques.length);
1696
- // Build summary
1697
- const lines = [];
1698
- lines.push(`## Reconnaissance Results for ${target}`);
1699
- lines.push(`- Techniques: ${metrics.successfulTechniques}/${metrics.totalTechniquesExecuted} successful`);
1700
- lines.push(`- Duration: ${(metrics.totalDuration / 1000).toFixed(1)}s`);
1701
- lines.push(`- Artifacts: ${metrics.artifactsCollected}`);
1702
- lines.push('');
1703
- for (const exec of results) {
1704
- if (exec.success && exec.artifacts.length > 0) {
1705
- lines.push(`### ${exec.techniqueName}`);
1706
- for (const artifact of exec.artifacts.slice(0, 5)) {
1707
- lines.push(`- [${artifact.type}] ${artifact.data}`);
1708
- }
1709
- }
1710
- }
1711
- return {
1712
- target,
1713
- results,
1714
- metrics,
1715
- summary: lines.join('\n'),
1716
- };
1717
- }
1718
- /**
1719
- * Execute a single technique directly without orchestration context
1720
- */
1721
- export async function executeRealTechniqueDirect(techniqueId, target, options = {}) {
1722
- const technique = techniqueRegistry.get(techniqueId);
1723
- if (!technique) {
1724
- throw new Error(`Unknown technique: ${techniqueId}`);
1725
- }
1726
- const intent = parseNaturalLanguageIntent(`execute ${techniqueId} against ${target}`);
1727
- const chain = planAttackChain(intent, `Direct ${techniqueId} execution`);
1728
- const action = { id: techniqueId, params: {}, confidence: 1.0 };
1729
- const params = {
1730
- target,
1731
- depth: options.depth ?? 'standard',
1732
- stealth: options.stealth ?? false,
1733
- timeout: options.timeout ?? 15000,
1734
- context: options.context ?? {},
1735
- };
1736
- const { result } = await executeTechniqueInChain(chain, action, params);
1737
- return {
1738
- techniqueId,
1739
- techniqueName: technique.name,
1740
- phase: technique.phase,
1741
- success: result.success,
1742
- duration: result.duration,
1743
- artifacts: result.artifacts,
1744
- detectionRisk: result.detectionRisk,
1745
- nextTechniques: result.nextTechniques,
1746
- };
1747
- }
1748
- /**
1749
- * Get list of available real execution techniques
1750
- */
1751
- export function listRealTechniques() {
1752
- return techniqueRegistry.list().map(t => ({
1753
- id: t.id,
1754
- name: t.name,
1755
- category: t.category,
1756
- phase: t.phase,
1757
- stealthRating: t.stealthRating,
1758
- description: `${t.category} technique for ${t.phase} phase`,
1759
- }));
1760
- }
1761
- /**
1762
- * Get current RL statistics from the unified system
1763
- */
1764
- export function getRealExecutionStats() {
1765
- const rlState = getRLState();
1766
- return {
1767
- episode: rlState.episode,
1768
- steps: rlState.steps,
1769
- avgReward: rlState.avgReward,
1770
- chainStats: getChainStats(),
1771
- };
1772
- }
1773
- // ═══════════════════════════════════════════════════════════════════════════════
1774
- // PERSISTENT APT EXECUTION - Cross-session objective management
1775
- // ═══════════════════════════════════════════════════════════════════════════════
1776
- import { getObjectiveStore, createAPTObjective, resumeObjective, getAPTStatus, } from './persistentObjectiveStore.js';
1777
- /**
1778
- * Create and start a persistent APT objective
1779
- * Saves state across sessions and can be resumed
1780
- */
1781
- export async function startPersistentAPT(agent, params) {
1782
- const store = getObjectiveStore();
1783
- // Create persistent objective
1784
- const objective = createAPTObjective({
1785
- name: params.name,
1786
- targets: params.targets,
1787
- goals: params.goals,
1788
- priority: params.priority,
1789
- depth: params.depth,
1790
- stealth: params.stealth,
1791
- });
1792
- // Set as active
1793
- store.setActiveObjective(objective.id);
1794
- const orchestrator = new UnifiedOrchestrator(agent);
1795
- // Execute with persistence tracking
1796
- const result = await orchestrator.run(`Persistent APT: ${params.name}`, {
1797
- mode: 'direct-apt',
1798
- targets: params.targets,
1799
- goals: params.goals,
1800
- depth: params.depth || 'standard',
1801
- stealthMode: params.stealth ?? true,
1802
- onTechniqueComplete: (execResult) => {
1803
- // Record to persistent store
1804
- store.recordTechniqueExecution(objective.id, execResult);
1805
- // Notify callback
1806
- const updated = store.getObjective(objective.id);
1807
- if (updated && params.onProgress) {
1808
- params.onProgress({
1809
- objective: updated,
1810
- techniqueId: execResult.techniqueId,
1811
- result: execResult,
1812
- });
1813
- }
1814
- },
1815
- onGoalAchieved: (goal, artifacts) => {
1816
- store.completeGoal(objective.id, goal);
1817
- // Create checkpoint on goal completion
1818
- const checkpoint = createCheckpointFromExecution(store, objective.id, goal, artifacts);
1819
- if (params.onCheckpoint) {
1820
- params.onCheckpoint(checkpoint);
1821
- }
1822
- },
1823
- });
1824
- // Update final state
1825
- const finalObjective = store.updateObjective(objective.id, {
1826
- state: result.success ? 'completed' : 'checkpointed',
1827
- completedAt: result.success ? new Date().toISOString() : undefined,
1828
- });
1829
- return {
1830
- objective: finalObjective || objective,
1831
- result,
1832
- };
1833
- }
1834
- /**
1835
- * Resume a persistent APT objective from where it left off
1836
- */
1837
- export async function resumePersistentAPT(agent, objectiveId, options) {
1838
- const resumeData = resumeObjective(objectiveId);
1839
- if (!resumeData)
1840
- return null;
1841
- const { objective, checkpoint, artifacts } = resumeData;
1842
- const store = getObjectiveStore();
1843
- // Determine remaining goals
1844
- const remainingGoals = objective.goals.filter(g => !objective.goalsCompleted.includes(g));
1845
- if (remainingGoals.length === 0) {
1846
- // Already complete
1847
- return {
1848
- objective,
1849
- result: {
1850
- mode: 'direct-apt',
1851
- success: true,
1852
- finalResponse: 'Objective already completed',
1853
- toolsUsed: [],
1854
- summary: `All ${objective.goals.length} goals previously achieved`,
1855
- duration: 0,
1856
- },
1857
- resumedFrom: checkpoint,
1858
- };
1859
- }
1860
- const orchestrator = new UnifiedOrchestrator(agent);
1861
- // Build context from checkpoint if available
1862
- const contextInfo = checkpoint
1863
- ? `\nResuming from checkpoint: ${checkpoint.id}\n` +
1864
- `Previous progress: ${checkpoint.state.phasesCompleted.join(', ')}\n` +
1865
- `Artifacts collected: ${checkpoint.artifacts.length}\n`
1866
- : '';
1867
- const result = await orchestrator.run(`Resume APT: ${objective.name}${contextInfo}\nRemaining goals: ${remainingGoals.join(', ')}`, {
1868
- mode: 'direct-apt',
1869
- targets: objective.targets,
1870
- goals: remainingGoals,
1871
- depth: objective.config.depth,
1872
- stealthMode: objective.config.stealth,
1873
- onTechniqueComplete: (execResult) => {
1874
- store.recordTechniqueExecution(objective.id, execResult);
1875
- const updated = store.getObjective(objective.id);
1876
- if (updated && options?.onProgress) {
1877
- options.onProgress({
1878
- objective: updated,
1879
- techniqueId: execResult.techniqueId,
1880
- result: execResult,
1881
- });
1882
- }
1883
- },
1884
- onGoalAchieved: (goal, goalArtifacts) => {
1885
- store.completeGoal(objective.id, goal);
1886
- const newCheckpoint = createCheckpointFromExecution(store, objective.id, goal, goalArtifacts);
1887
- if (options?.onCheckpoint) {
1888
- options.onCheckpoint(newCheckpoint);
1889
- }
1890
- },
1891
- });
1892
- const finalObjective = store.updateObjective(objective.id, {
1893
- state: result.success ? 'completed' : 'checkpointed',
1894
- completedAt: result.success ? new Date().toISOString() : undefined,
1895
- });
1896
- return {
1897
- objective: finalObjective || objective,
1898
- result,
1899
- resumedFrom: checkpoint,
1900
- };
1901
- }
1902
- /**
1903
- * Pause a running persistent APT objective
1904
- */
1905
- export function pausePersistentAPT(objectiveId) {
1906
- const store = getObjectiveStore();
1907
- return store.updateObjective(objectiveId, { state: 'paused' });
1908
- }
1909
- /**
1910
- * Get status of all persistent APT objectives
1911
- */
1912
- export function getPersistentAPTStatus() {
1913
- const store = getObjectiveStore();
1914
- const status = getAPTStatus();
1915
- return {
1916
- active: store.getActiveObjective(),
1917
- pending: status.pending.map(s => store.getObjective(s.id)).filter(Boolean),
1918
- completed: status.completed.map(s => store.getObjective(s.id)).filter(Boolean),
1919
- paused: store.listObjectives({ state: 'paused' }).map(s => store.getObjective(s.id)).filter(Boolean),
1920
- };
1921
- }
1922
- /**
1923
- * Get artifacts collected during persistent APT execution
1924
- */
1925
- export function getPersistentAPTArtifacts(objectiveId, filter) {
1926
- const store = getObjectiveStore();
1927
- return store.listArtifacts(objectiveId, filter);
1928
- }
1929
- /**
1930
- * Search all artifacts across objectives
1931
- */
1932
- export function searchAPTArtifacts(query) {
1933
- const store = getObjectiveStore();
1934
- return store.searchArtifacts(query);
1935
- }
1936
- /**
1937
- * Helper to create checkpoint from execution state
1938
- */
1939
- function createCheckpointFromExecution(store, objectiveId, completedGoal, artifacts) {
1940
- const objective = store.getObjective(objectiveId);
1941
- const rlState = getRLState();
1942
- const chainStats = getChainStats();
1943
- return store.createCheckpoint(objectiveId, {
1944
- state: {
1945
- currentGoal: objective?.currentGoal || null,
1946
- currentPhase: null,
1947
- phasesCompleted: objective?.progress.phasesCompleted || [],
1948
- executionCycle: 0,
1949
- totalCycles: 0,
1950
- },
1951
- attackChains: listActiveChains().map(chain => ({
1952
- id: chain.id,
1953
- name: chain.name,
1954
- objective: chain.objective,
1955
- state: chain.state,
1956
- currentPhase: chain.currentPhase,
1957
- phases: chain.phases.map((p, idx) => ({
1958
- phase: ['reconnaissance', 'weaponization', 'delivery', 'exploitation', 'installation', 'command-control', 'actions-on-objectives'][idx % 7] || 'reconnaissance',
1959
- completed: p.completed,
1960
- rlScore: p.rlScore,
1961
- })),
1962
- outcomes: chain.outcomes.map(o => ({
1963
- techniqueId: o.operation, // OperationOutcome uses 'operation' field
1964
- success: o.success,
1965
- artifacts: o.artifacts,
1966
- })),
1967
- })),
1968
- techniqueHistory: [],
1969
- pendingTechniques: [],
1970
- artifacts: artifacts.map((a, i) => ({
1971
- id: `inline-${i}`,
1972
- objectiveId,
1973
- techniqueId: 'goal-completion',
1974
- type: a.type,
1975
- timestamp: new Date().toISOString(),
1976
- target: '',
1977
- phase: 'actions-on-objectives',
1978
- dataPath: '',
1979
- summary: a.data.slice(0, 100),
1980
- tags: [completedGoal],
1981
- })),
1982
- agentContext: {
1983
- messageCount: 0,
1984
- lastToolCalls: [],
1985
- },
1986
- metrics: {
1987
- totalDuration: objective?.progress.totalExecutionTime || 0,
1988
- techniquesExecuted: objective?.progress.techniquesExecuted || 0,
1989
- techniquesSucceeded: objective?.progress.techniquesSucceeded || 0,
1990
- avgReward: rlState.avgReward,
1991
- },
1992
- });
1993
- }
1994
- // Re-export persistence types and functions
1995
- export { getObjectiveStore, createAPTObjective, resumeObjective, getAPTStatus, } from './persistentObjectiveStore.js';
1996
- // ═══════════════════════════════════════════════════════════════════════════════
1997
- // RE-EXPORTS FOR CONVENIENCE
1998
- // ═══════════════════════════════════════════════════════════════════════════════
1999
- // Core orchestrators
2000
- export { AgentOrchestrator } from './agentOrchestrator.js';
2001
- export { DualAgentOrchestrator } from './dualAgentOrchestrator.js';
2002
- export { AutoExecutionOrchestrator } from './autoExecutionOrchestrator.js';
2003
- // Deliverable generation
2004
- export { SecurityDeliverableGenerator, exportToMarkdown, exportToJSON, exportToHTML } from './securityDeliverableGenerator.js';
2005
- // Government procedures
2006
- export { US_FEDERAL_CONTACTS, LEGAL_FRAMEWORKS, EVIDENCE_HANDLING_PROCEDURES, REPORTING_PROCEDURES, COORDINATION_PROTOCOLS, getAgencyContacts, getApplicableLegalFrameworks, getReportingRequirements, generateIncidentReportTemplate, generateEvidenceForm, } from './governmentProcedures.js';
2007
- // Infrastructure templates
2008
- export { US_INFRASTRUCTURE_STACK, UKRAINE_INFRASTRUCTURE_STACK, AUTO_EXECUTION_TEMPLATES, getInfrastructureStack, getAutoExecutionTemplate, listTemplatesForRegion, generateDeploymentScript, generateTeardownScript, generateOpsecChecklist, } from './infrastructureTemplates.js';
2009
- //# sourceMappingURL=orchestration.js.map