UNPKG

ai-debug-local-mcp

Version:

๐ŸŽฏ ENHANCED AI GUIDANCE v4.1.2: Dramatically improved tool descriptions help AI users choose the right tools instead of 'close enough' options. Ultra-fast keyboard automation (10x speed), universal recording, multi-ecosystem debugging support, and compreh

395 lines โ€ข 18 kB
/** * Performance-Optimized Sub-Agent Orchestrator * * Integrates delegation optimizer and intelligent routing for <100ms target * performance with machine learning-enhanced agent selection. */ import { SubAgentDelegationOptimizer } from './sub-agent-delegation-optimizer.js'; import { IntelligentAgentRouter } from './intelligent-agent-router.js'; import { UserFriendlyLogger } from './user-friendly-logger.js'; import { SubAgentTestGenerator } from './sub-agent-test-generation-integration.js'; export class PerformanceOptimizedOrchestrator { delegationOptimizer; intelligentRouter; logger; config; performanceHistory; constructor(config = {}) { this.config = { maxDelegationTimeMs: 100, cacheAgentAvailabilityMs: 60000, enableConnectionPooling: true, enablePrecomputation: true, enableParallelClassification: true, enableIntelligentRouting: true, enablePerformanceTracking: true, enableAdaptiveLearning: true, fallbackToDirectExecution: true, enableAutomaticTestGeneration: false, testGenerationConfig: { requireQualityThreshold: 0.8, enableTestReview: true, generateForAllAgents: true }, ...config }; this.delegationOptimizer = new SubAgentDelegationOptimizer(this.config); this.intelligentRouter = new IntelligentAgentRouter(); this.logger = new UserFriendlyLogger('PerformanceOrchestrator'); this.performanceHistory = []; } /** * Execute task with full optimization and intelligent routing */ async executeOptimizedTask(taskDescription, options = {}) { const startTime = performance.now(); const maxTime = options.performanceConstraints?.maxTimeMs || this.config.maxDelegationTimeMs; try { // Step 1: Intelligent agent routing (target: <15ms) const routingResult = await this.performIntelligentRouting(taskDescription, options); const routingTime = performance.now() - startTime; if (!routingResult.selectedAgent) { return this.createFailureResult(startTime, 'No suitable agent found', routingTime); } // Step 2: Check if we have time remaining for delegation const remainingTime = maxTime - routingTime; if (remainingTime < 30) { return this.createFailureResult(startTime, 'Insufficient time for delegation', routingTime); } // Step 3: Optimized delegation (target: remaining time) const delegationStartTime = performance.now(); const delegationResult = await this.delegationOptimizer.delegateTaskOptimized(taskDescription, { ...options, selectedAgent: routingResult.selectedAgent, maxTimeMs: remainingTime }); const delegationTime = performance.now() - delegationStartTime; // Step 4: Automatic Test Generation (if enabled) let testGenerationMetrics = undefined; if (this.config.enableAutomaticTestGeneration) { // CRITICAL FIX: Generate tests for BOTH successes AND failures // Failed delegations often provide the most valuable test scenarios testGenerationMetrics = await this.generateTestsAutomatically(routingResult.selectedAgent, delegationResult, options); } // Step 5: Compile results and metrics const totalTime = performance.now() - startTime; const result = this.createSuccessResult(startTime, routingResult, delegationResult, routingTime, delegationTime, testGenerationMetrics); // Step 5: Learn from this execution for future optimization this.recordPerformanceMetrics(result); // Step 6: Adaptive optimization if enabled if (this.config.enableAdaptiveLearning) { this.performAdaptiveOptimization(result); } return result; } catch (error) { const totalTime = performance.now() - startTime; this.logger.error(`Orchestration failed: ${error instanceof Error ? error.message : 'Unknown error'}`); return { success: false, performance: { totalTimeMs: totalTime, optimizationSavingsMs: 0, routingTimeMs: 0, delegationTimeMs: 0, cacheHitRate: 0 }, intelligence: { confidence: 0, reasoning: ['Orchestration error occurred'], alternatives: [] } }; } } /** * Perform intelligent agent routing with performance optimization */ async performIntelligentRouting(taskDescription, options) { if (!this.config.enableIntelligentRouting) { // Fallback to simple classification const classification = await this.delegationOptimizer.classifyTaskOptimized(taskDescription); return { selectedAgent: classification.recommendedAgent, confidence: classification.confidence, reasoning: ['Simple classification used'], alternatives: [] }; } // Build routing context const routingContext = { taskType: this.extractTaskType(taskDescription), userIntent: taskDescription, projectContext: options.projectContext, sessionHistory: options.sessionHistory || [], performanceConstraints: { maxTimeMs: options.performanceConstraints?.maxTimeMs || this.config.maxDelegationTimeMs, tokenBudget: options.performanceConstraints?.tokenBudget || 5000, qualityThreshold: options.performanceConstraints?.qualityThreshold || 0.8 } }; // Execute intelligent routing const routingDecision = await this.intelligentRouter.selectOptimalAgent(routingContext); return { selectedAgent: routingDecision.selectedAgent, confidence: routingDecision.confidence, reasoning: routingDecision.reasoning, alternatives: routingDecision.alternativeAgents }; } /** * Create success result with comprehensive metrics */ createSuccessResult(startTime, routingResult, delegationResult, routingTime, delegationTime, testGenerationMetrics) { const totalTime = performance.now() - startTime; const optimizerMetrics = this.delegationOptimizer.getPerformanceMetrics(); return { success: delegationResult.success, agentUsed: routingResult.selectedAgent, result: delegationResult.result, performance: { totalTimeMs: totalTime, optimizationSavingsMs: delegationResult.optimizationSavingsMs || 0, routingTimeMs: routingTime, delegationTimeMs: delegationTime, cacheHitRate: optimizerMetrics.cacheHitRate }, intelligence: { confidence: routingResult.confidence, reasoning: routingResult.reasoning, alternatives: routingResult.alternatives }, ...(testGenerationMetrics && { testGeneration: testGenerationMetrics }) }; } /** * Create failure result with metrics */ createFailureResult(startTime, reason, routingTime = 0) { const totalTime = performance.now() - startTime; return { success: false, performance: { totalTimeMs: totalTime, optimizationSavingsMs: 0, routingTimeMs: routingTime, delegationTimeMs: 0, cacheHitRate: 0 }, intelligence: { confidence: 0, reasoning: [reason], alternatives: [] } }; } /** * Record performance metrics for monitoring and optimization */ recordPerformanceMetrics(result) { if (!this.config.enablePerformanceTracking) return; this.performanceHistory.push({ timestamp: Date.now(), totalTime: result.performance.totalTimeMs, success: result.success }); // Keep only recent history (last 100 executions) if (this.performanceHistory.length > 100) { this.performanceHistory = this.performanceHistory.slice(-50); } // Log performance milestones if (result.performance.totalTimeMs < 50) { this.logger.success(`โšก Ultra-fast execution: ${result.performance.totalTimeMs.toFixed(1)}ms`); } else if (result.performance.totalTimeMs < 100) { this.logger.info(`๐ŸŽฏ Target achieved: ${result.performance.totalTimeMs.toFixed(1)}ms`); } else { this.logger.warn(`โฐ Performance target missed: ${result.performance.totalTimeMs.toFixed(1)}ms`); } } /** * Perform adaptive optimization based on performance history */ performAdaptiveOptimization(result) { const recentPerformance = this.getRecentPerformanceStats(); // Auto-tune delegation optimizer if (recentPerformance.averageTime > this.config.maxDelegationTimeMs) { this.delegationOptimizer.autoTuneConfiguration(); this.logger.info('๐Ÿ“ˆ Auto-tuned delegation optimizer for better performance'); } // Adjust caching strategy if (recentPerformance.cacheHitRate < 70) { this.config.cacheAgentAvailabilityMs = Math.min(120000, this.config.cacheAgentAvailabilityMs * 1.2); this.logger.info('๐Ÿ”„ Increased cache TTL to improve hit rate'); } // Enable/disable features based on performance if (recentPerformance.averageTime < 50 && !this.config.enableParallelClassification) { this.config.enableParallelClassification = true; this.logger.info('โšก Enabled parallel classification for ultra-fast performance'); } } /** * Get recent performance statistics */ getRecentPerformanceStats() { const recentSamples = this.performanceHistory.slice(-20); if (recentSamples.length === 0) { return { averageTime: 0, successRate: 0, cacheHitRate: 0, samplesCount: 0 }; } const averageTime = recentSamples.reduce((sum, sample) => sum + sample.totalTime, 0) / recentSamples.length; const successCount = recentSamples.filter(sample => sample.success).length; const successRate = successCount / recentSamples.length; const optimizerMetrics = this.delegationOptimizer.getPerformanceMetrics(); return { averageTime, successRate, cacheHitRate: optimizerMetrics.cacheHitRate, samplesCount: recentSamples.length }; } /** * Extract task type from description for routing */ extractTaskType(taskDescription) { const description = taskDescription.toLowerCase(); if (description.includes('performance') || description.includes('slow')) { return 'performance-analysis'; } if (description.includes('accessibility') || description.includes('a11y')) { return 'accessibility-audit'; } if (description.includes('error') || description.includes('bug')) { return 'error-investigation'; } if (description.includes('test') || description.includes('validate')) { return 'validation-testing'; } if (description.includes('debug') || description.includes('investigate')) { return 'debug-discovery'; } return 'general-debugging'; } /** * Get comprehensive orchestration metrics */ getOrchestrationMetrics() { const recentStats = this.getRecentPerformanceStats(); const optimizerMetrics = this.delegationOptimizer.getPerformanceMetrics(); const intelligenceMetrics = this.intelligentRouter.getIntelligenceMetrics(); const targetAchievements = this.performanceHistory.filter(sample => sample.totalTime <= this.config.maxDelegationTimeMs).length; return { performance: { averageExecutionTime: recentStats.averageTime, targetAchievementRate: this.performanceHistory.length > 0 ? (targetAchievements / this.performanceHistory.length) * 100 : 0, optimizationSavings: optimizerMetrics.totalOptimizationSavingsMs }, intelligence: { routingDecisions: intelligenceMetrics.totalDecisions, averageConfidence: intelligenceMetrics.averageConfidence, learningPatterns: intelligenceMetrics.learningPatterns }, optimization: { cacheHitRate: optimizerMetrics.cacheHitRate, delegationSuccessRate: recentStats.successRate * 100, adaptiveAdjustments: 0 // Would track actual adjustments made }, config: this.config }; } /** * Clear all caches and reset optimization state */ resetOptimization() { this.delegationOptimizer.clearCaches(); this.performanceHistory = []; this.logger.info('๐Ÿ”„ Reset optimization state and caches'); } /** * Update configuration and apply changes */ updateConfiguration(newConfig) { this.config = { ...this.config, ...newConfig }; // Recreate optimizer with new config this.delegationOptimizer = new SubAgentDelegationOptimizer(this.config); this.logger.info('โš™๏ธ Updated orchestration configuration'); } /** * Generate tests automatically from sub-agent debugging results */ async generateTestsAutomatically(agentType, delegationResult, options) { const startTime = performance.now(); try { // Enhanced context extraction for BOTH success and failure scenarios const isSuccess = delegationResult.success !== false; // For failures, treat the failure itself as an issue to prevent const failureIssues = !isSuccess ? [{ type: 'delegation_failure', description: delegationResult.error || 'Sub-agent delegation failed', severity: 'high', category: 'infrastructure', prevention: 'Generate tests to prevent this delegation failure pattern' }] : []; const testGenerationContext = { agentType, debuggingFindings: delegationResult.findings || [], frameworkDetected: options.projectContext?.framework || 'unknown', issuesFound: [...(delegationResult.issuesFound || []), ...failureIssues], optimizationsApplied: delegationResult.optimizations || [], sessionMetadata: { url: delegationResult.url || 'unknown', userFlow: delegationResult.userInteractions || [], complexity: options.projectContext?.complexity || 'moderate' } }; // Generate tests using sub-agent integration const sessionType = isSuccess ? 'successful' : 'failed'; this.logger.info(`๐Ÿงช Generating tests automatically from ${sessionType} ${agentType} session...`); if (!isSuccess) { this.logger.info(`๐Ÿ” Failure analysis: Creating prevention tests for delegation failure`); } const generatedTests = await SubAgentTestGenerator.generateTestsFromDebugging(testGenerationContext); const generationTime = performance.now() - startTime; // Calculate quality metrics const qualityScore = generatedTests.length > 0 ? generatedTests.reduce((sum, test) => sum + (test.confidence || 0.8), 0) / generatedTests.length : 0; const metrics = { enabled: true, testsGenerated: generatedTests.length, testQuality: qualityScore, generationTimeMs: generationTime }; // Log success this.logger.info(`โœ… Generated ${generatedTests.length} tests in ${generationTime.toFixed(1)}ms (quality: ${(qualityScore * 100).toFixed(1)}%)`); // Store tests for future reference (could write to file system here) if (generatedTests.length > 0) { this.logger.info(`๐ŸŽฏ Test generation breakdown:`); const testTypes = generatedTests.reduce((acc, test) => { acc[test.type] = (acc[test.type] || 0) + 1; return acc; }, {}); Object.entries(testTypes).forEach(([type, count]) => { this.logger.info(` ${type}: ${count} tests`); }); } return metrics; } catch (error) { const generationTime = performance.now() - startTime; this.logger.error(`โŒ Test generation failed: ${error instanceof Error ? error.message : 'Unknown error'}`); return { enabled: true, testsGenerated: 0, testQuality: 0, generationTimeMs: generationTime }; } } } //# sourceMappingURL=performance-optimized-orchestrator.js.map