UNPKG

@bear_ai/nexus-flow

Version:

Universal AI orchestrator - portal to any flow (claude-flow, qwen-flow, copilot-flow) with queen bee coordination system

327 lines (275 loc) 9.84 kB
import { EventEmitter } from 'events'; import { NexusConfig, Task, FlowInstance, NexusEvent, TruthVerificationResult } from '../types/index.js'; import { ConfigManager } from './config-manager.js'; import { FlowRegistry } from './flow-registry.js'; import { QueenBee } from './queen-bee.js'; import { Portal } from './portal.js'; import { FlowNexus, FlowNexusConfig } from './flow-nexus.js'; import { HooksSystem, HooksConfig } from './hooks-system.js'; import { Logger } from '../utils/logger.js'; export class NexusEngine extends EventEmitter { private config: ConfigManager; private flowRegistry: FlowRegistry; private queenBee?: QueenBee; private portal: Portal; private flowNexus?: FlowNexus; private hooksSystem?: HooksSystem; private logger: Logger; private initialized = false; constructor(configPath?: string) { super(); this.logger = new Logger('NexusEngine'); this.config = new ConfigManager(configPath); this.flowRegistry = new FlowRegistry(); this.portal = new Portal(this.flowRegistry); this.setupEventHandlers(); } private setupEventHandlers(): void { this.flowRegistry.on('flow-registered', (flow: FlowInstance) => { this.logger.info(`Flow registered: ${flow.name} (${flow.type})`); this.emit('flow-registered', flow); }); this.flowRegistry.on('flow-status-changed', (event) => { this.logger.debug(`Flow status changed: ${event.name} -> ${event.status}`); this.emit('flow-status-changed', event); }); this.portal.on('task-routed', (event) => { this.logger.info(`Task routed: ${event.taskId} -> ${event.targetFlow}`); this.emit('task-routed', event); }); if (this.queenBee) { this.queenBee.on('task-delegated', (event) => { this.logger.info(`Task delegated: ${event.taskId} -> ${event.targetFlow}`); this.emit('task-delegated', event); }); this.queenBee.on('coordination-decision', (event) => { this.logger.debug(`Coordination decision: ${event.decision}`); this.emit('coordination-decision', event); }); } } async initialize(): Promise<void> { if (this.initialized) return; try { this.logger.info('Initializing Nexus Engine...'); // Load configuration await this.config.load(); const nexusConfig = this.config.getConfig(); // Initialize hooks system const hooksConfig: HooksConfig = { enabled: true, defaultTimeout: 30000, maxConcurrent: 10, lifecycle: { 'pre-task': true, 'post-task': true, 'pre-flow': true, 'post-flow': true, 'pre-coordination': true, 'post-coordination': true, 'pre-verification': true, 'post-verification': true, 'pre-training': true, 'post-training': true } }; this.hooksSystem = new HooksSystem(hooksConfig); this.hooksSystem.createLifecycleHooks(); // Initialize Flow Nexus const flowNexusConfig: FlowNexusConfig = { enabled: true, sandboxes: [ { type: 'nodejs' }, { type: 'python' }, { type: 'react' }, { type: 'nextjs' } ], neuralTraining: { enabled: true, accuracyThreshold: 0.95, maxIterations: 1000, batchSize: 32 }, truthVerification: { enabled: true, accuracyThreshold: 0.95, mandatoryVerification: true }, mcpProtocol: { enabled: true, toolCount: 87, parallelCoordination: true } }; this.flowNexus = new FlowNexus(flowNexusConfig); await this.flowNexus.initialize(); // Initialize flow registry with configured flows await this.flowRegistry.initialize(nexusConfig.flows); // Enhance flows with MCP if Flow Nexus is enabled if (this.flowNexus) { const flows = this.flowRegistry.getAll(); const enhancedFlows = await this.flowNexus.enhanceWithMCP(flows); this.logger.info(`Enhanced ${enhancedFlows.length} flows with MCP protocol`); } // Initialize Queen Bee if enabled if (nexusConfig.queenBee?.enabled) { this.queenBee = new QueenBee( nexusConfig.queenBee, this.flowRegistry, this.logger ); await this.queenBee.initialize(); } // Initialize Portal await this.portal.initialize(nexusConfig.portal); this.initialized = true; this.logger.info('Nexus Engine initialized successfully with Flow Nexus and Hooks System'); this.emit('initialized'); } catch (error: any) { this.logger.error('Failed to initialize Nexus Engine:', error); this.emit('initialization-error', error); throw error; } } async executeTask(description: string, options: any = {}): Promise<string> { if (!this.initialized) { await this.initialize(); } const task: Task = { id: this.generateTaskId(), description, type: options.type || 'code-generation', priority: options.priority || 1, status: 'pending', createdAt: new Date(), updatedAt: new Date(), metadata: options.metadata || {} }; this.logger.info(`Executing task: ${task.id} - ${task.description}`); try { // Execute pre-task hooks let context = { task, timestamp: new Date() }; if (this.hooksSystem) { context = await this.hooksSystem.executeHooks('pre-task', context); } let result: string; if (this.queenBee?.isEnabled()) { // Execute pre-coordination hooks if (this.hooksSystem) { context = await this.hooksSystem.executeHooks('pre-coordination', context); } // Use Queen Bee for coordination result = await this.queenBee.delegateTask(context.task!); // Execute post-coordination hooks if (this.hooksSystem) { context = await this.hooksSystem.executeHooks('post-coordination', { ...context, result }); } } else { // Use Portal for direct routing result = await this.portal.routeTask(context.task!); } // Truth verification if Flow Nexus is enabled if (this.flowNexus) { // Execute pre-verification hooks if (this.hooksSystem) { context = await this.hooksSystem.executeHooks('pre-verification', { ...context, result }); } const verification = await this.flowNexus.verifyTruth(context.task!, result); this.logger.info(`Truth verification: ${verification.verified} (accuracy: ${verification.accuracy})`); // Execute post-verification hooks if (this.hooksSystem) { context = await this.hooksSystem.executeHooks('post-verification', { ...context, result, metadata: { verification } }); } } task.status = 'completed'; task.updatedAt = new Date(); // Execute post-task hooks if (this.hooksSystem) { await this.hooksSystem.executeHooks('post-task', { ...context, result }); } this.emit('task-completed', { taskId: task.id, result }); return result; } catch (error: any) { task.status = 'failed'; task.updatedAt = new Date(); this.logger.error(`Task failed: ${task.id} - ${error.message}`); this.emit('task-failed', { taskId: task.id, error: error.message }); throw error; } } async discoverFlows(): Promise<FlowInstance[]> { return await this.flowRegistry.discoverAvailableFlows(); } getAvailableFlows(): FlowInstance[] { return this.flowRegistry.getAll(); } getFlowStatus(flowName: string): FlowInstance | undefined { return this.flowRegistry.get(flowName); } async enableQueenBee(config?: any): Promise<void> { if (!this.queenBee) { const queenBeeConfig = config || this.config.getConfig().queenBee; this.queenBee = new QueenBee( queenBeeConfig, this.flowRegistry, this.logger ); await this.queenBee.initialize(); } } async disableQueenBee(): Promise<void> { if (this.queenBee) { await this.queenBee.shutdown(); this.queenBee = undefined; } } isQueenBeeEnabled(): boolean { return this.queenBee?.isEnabled() || false; } async getSystemStatus(): Promise<{ initialized: boolean; queenBeeEnabled: boolean; availableFlows: number; activeFlows: number; totalTasks: number; flowNexus?: any; hooksSystem?: any; }> { const flows = this.getAvailableFlows(); const activeFlows = flows.filter(f => f.status === 'available' || f.status === 'busy'); const status = { initialized: this.initialized, queenBeeEnabled: this.isQueenBeeEnabled(), availableFlows: flows.length, activeFlows: activeFlows.length, totalTasks: 0, // TODO: Implement task tracking flowNexus: this.flowNexus ? this.flowNexus.getSystemStatus() : undefined, hooksSystem: this.hooksSystem ? this.hooksSystem.getHookStatus() : undefined }; return status; } private generateTaskId(): string { return `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; } async shutdown(): Promise<void> { this.logger.info('Shutting down Nexus Engine...'); if (this.hooksSystem) { await this.hooksSystem.shutdown(); } if (this.flowNexus) { await this.flowNexus.shutdown(); } if (this.queenBee) { await this.queenBee.shutdown(); } await this.portal.shutdown(); await this.flowRegistry.shutdown(); this.initialized = false; this.emit('shutdown'); this.logger.info('Nexus Engine shutdown complete'); } }