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

502 lines • 21.7 kB
/** * Intelligent Agent Router * * Enhanced routing algorithms that learn from delegation patterns and optimize * agent selection through machine learning techniques, context analysis, and * adaptive decision making. */ export class IntelligentAgentRouter { agentProfiles; learningPatterns; contextAnalyzer; adaptiveWeights; routingHistory; performanceTracker; constructor() { this.agentProfiles = new Map(); this.learningPatterns = new Map(); this.contextAnalyzer = new ContextAnalyzer(); this.adaptiveWeights = new Map(); this.routingHistory = []; this.performanceTracker = new PerformanceTracker(); this.initializeAgentProfiles(); this.initializeAdaptiveWeights(); } /** * Initialize agent capability profiles with baseline data */ initializeAgentProfiles() { const profiles = [ { agentType: 'debug-discovery-agent', expertiseDomains: ['initial-assessment', 'framework-detection', 'browser-setup'], averageSuccessRate: 0.92, averageExecutionTime: 45, contextSpecializations: new Map([ ['react', 0.95], ['vue', 0.90], ['angular', 0.88], ['vanilla-js', 0.96] ]), learningMetrics: { improvementRate: 0.15, adaptabilityScore: 0.85, consistencyScore: 0.91 } }, { agentType: 'performance-analysis-agent', expertiseDomains: ['core-web-vitals', 'bundle-analysis', 'memory-profiling'], averageSuccessRate: 0.89, averageExecutionTime: 120, contextSpecializations: new Map([ ['react', 0.93], ['next.js', 0.96], ['vue', 0.87], ['angular', 0.84], ['spa', 0.91] ]), learningMetrics: { improvementRate: 0.22, adaptabilityScore: 0.78, consistencyScore: 0.86 } }, { agentType: 'accessibility-audit-agent', expertiseDomains: ['wcag-compliance', 'screen-reader', 'keyboard-navigation'], averageSuccessRate: 0.94, averageExecutionTime: 85, contextSpecializations: new Map([ ['react', 0.92], ['vue', 0.89], ['angular', 0.91], ['static-site', 0.96] ]), learningMetrics: { improvementRate: 0.12, adaptabilityScore: 0.88, consistencyScore: 0.94 } }, { agentType: 'error-investigation-agent', expertiseDomains: ['javascript-errors', 'network-issues', 'runtime-exceptions'], averageSuccessRate: 0.87, averageExecutionTime: 95, contextSpecializations: new Map([ ['react', 0.90], ['vue', 0.85], ['angular', 0.88], ['node.js', 0.92] ]), learningMetrics: { improvementRate: 0.18, adaptabilityScore: 0.82, consistencyScore: 0.79 } }, { agentType: 'test-review-agent', expertiseDomains: ['test-quality', 'coverage-analysis', 'framework-patterns'], averageSuccessRate: 0.91, averageExecutionTime: 70, contextSpecializations: new Map([ ['react', 0.94], ['vue', 0.88], ['angular', 0.86], ['jest', 0.96], ['cypress', 0.89] ]), learningMetrics: { improvementRate: 0.20, adaptabilityScore: 0.83, consistencyScore: 0.89 } } ]; for (const profile of profiles) { this.agentProfiles.set(profile.agentType, profile); } } /** * Initialize adaptive weights for different routing factors */ initializeAdaptiveWeights() { this.adaptiveWeights.set('success_rate', 0.35); this.adaptiveWeights.set('execution_time', 0.25); this.adaptiveWeights.set('context_match', 0.20); this.adaptiveWeights.set('learning_trend', 0.15); this.adaptiveWeights.set('consistency', 0.05); } /** * Intelligent agent selection with machine learning-based optimization */ async selectOptimalAgent(context) { const startTime = performance.now(); // Step 1: Analyze context and extract key features const contextFeatures = await this.contextAnalyzer.extractFeatures(context); // Step 2: Score all available agents based on multiple factors const agentScores = await this.scoreAgentsForContext(context, contextFeatures); // Step 3: Apply machine learning patterns and historical data const mlEnhancedScores = this.applyMachineLearningEnhancements(agentScores, context); // Step 4: Select best agent with confidence calculation const routingDecision = this.makeRoutingDecision(mlEnhancedScores, context); // Step 5: Learn from this decision for future improvements this.recordRoutingDecision(routingDecision, context); const executionTime = performance.now() - startTime; this.performanceTracker.recordRoutingTime(executionTime); return routingDecision; } /** * Score agents based on multiple factors and context analysis */ async scoreAgentsForContext(context, features) { const scores = new Map(); for (const [agentType, profile] of this.agentProfiles) { const score = await this.calculateAgentScore(profile, context, features); scores.set(agentType, score); } return scores; } /** * Calculate comprehensive score for an agent given the context */ async calculateAgentScore(profile, context, features) { const weights = this.adaptiveWeights; // Factor 1: Base success rate const successRateScore = profile.averageSuccessRate; // Factor 2: Execution time efficiency (inverted - lower time = higher score) const timeEfficiencyScore = Math.max(0, 1 - (profile.averageExecutionTime / context.performanceConstraints.maxTimeMs)); // Factor 3: Context specialization match const contextMatchScore = this.calculateContextMatchScore(profile, context); // Factor 4: Learning trend (improving agents get higher scores) const learningTrendScore = profile.learningMetrics.improvementRate; // Factor 5: Consistency score const consistencyScore = profile.learningMetrics.consistencyScore; // Factor 6: Domain expertise match const domainExpertiseScore = this.calculateDomainExpertiseScore(profile, features); // Weighted combination const compositeScore = successRateScore * weights.get('success_rate') + timeEfficiencyScore * weights.get('execution_time') + contextMatchScore * weights.get('context_match') + learningTrendScore * weights.get('learning_trend') + consistencyScore * weights.get('consistency'); return { agentType: profile.agentType, compositeScore, factors: { successRate: successRateScore, timeEfficiency: timeEfficiencyScore, contextMatch: contextMatchScore, learningTrend: learningTrendScore, consistency: consistencyScore, domainExpertise: domainExpertiseScore }, confidence: this.calculateConfidence(profile, context) }; } /** * Apply machine learning enhancements based on historical patterns */ applyMachineLearningEnhancements(baseScores, context) { const enhancedScores = new Map(); const contextSignature = this.contextAnalyzer.generateContextSignature(context); const learningPattern = this.learningPatterns.get(contextSignature); for (const [agentType, baseScore] of baseScores) { let enhancedScore = { ...baseScore }; // Enhancement 1: Historical success pattern boosting if (learningPattern) { const historicalSuccessRate = learningPattern.successfulAgents.get(agentType) || 0; const patternBoost = historicalSuccessRate * 0.15; // 15% boost for historical success enhancedScore.compositeScore += patternBoost; } // Enhancement 2: Recent performance trending const recentPerformance = this.performanceTracker.getRecentPerformance(agentType); const trendBoost = recentPerformance.trend * 0.10; // 10% boost for positive trends enhancedScore.compositeScore += trendBoost; // Enhancement 3: Failure pattern penalty if (learningPattern && this.hasFailurePattern(agentType, learningPattern)) { enhancedScore.compositeScore *= 0.85; // 15% penalty for failure patterns } // Enhancement 4: Adaptive weight learning const adaptiveBoost = this.getAdaptiveBoost(agentType, context); enhancedScore.compositeScore += adaptiveBoost; enhancedScores.set(agentType, enhancedScore); } return enhancedScores; } /** * Make final routing decision with confidence and alternatives */ makeRoutingDecision(scores, context) { // Sort agents by score const sortedAgents = Array.from(scores.entries()) .sort((a, b) => b[1].compositeScore - a[1].compositeScore); const [selectedAgent, topScore] = sortedAgents[0]; const alternatives = sortedAgents.slice(1, 3).map(([agent, score]) => ({ agent, score: score.compositeScore, reason: this.generateAlternativeReason(score) })); // Calculate confidence based on score gap and historical data const confidence = this.calculateSelectionConfidence(sortedAgents); // Generate reasoning const reasoning = this.generateReasoningExplanation(topScore, context); // Estimate performance const expectedPerformance = this.estimatePerformance(selectedAgent, context); return { selectedAgent, confidence, reasoning, alternativeAgents: alternatives, expectedPerformance }; } /** * Calculate context match score for agent specialization */ calculateContextMatchScore(profile, context) { if (!context.projectContext) return 0.5; // Default score for unknown context const { framework, language, complexity } = context.projectContext; let matchScore = 0; let totalWeight = 0; // Framework specialization if (profile.contextSpecializations.has(framework)) { const frameworkScore = profile.contextSpecializations.get(framework); matchScore += frameworkScore * 0.6; totalWeight += 0.6; } // Language specialization if (profile.contextSpecializations.has(language)) { const languageScore = profile.contextSpecializations.get(language); matchScore += languageScore * 0.3; totalWeight += 0.3; } // Complexity handling const complexityWeight = complexity === 'complex' ? 0.1 : 0.05; matchScore += profile.learningMetrics.adaptabilityScore * complexityWeight; totalWeight += complexityWeight; return totalWeight > 0 ? matchScore / totalWeight : 0.5; } /** * Calculate domain expertise match score */ calculateDomainExpertiseScore(profile, features) { const relevantDomains = features.identifiedDomains; const agentDomains = profile.expertiseDomains; const overlap = relevantDomains.filter(domain => agentDomains.some(agentDomain => domain.includes(agentDomain) || agentDomain.includes(domain))); return overlap.length / Math.max(relevantDomains.length, 1); } /** * Calculate confidence based on historical data and current context */ calculateConfidence(profile, context) { const baseConfidence = profile.averageSuccessRate; const consistencyBonus = profile.learningMetrics.consistencyScore * 0.1; const contextPenalty = context.performanceConstraints.maxTimeMs < profile.averageExecutionTime ? 0.15 : 0; return Math.max(0, Math.min(1, baseConfidence + consistencyBonus - contextPenalty)); } /** * Record routing decision for learning */ recordRoutingDecision(decision, context) { this.routingHistory.push(decision); // Update learning patterns const contextSignature = this.contextAnalyzer.generateContextSignature(context); this.updateLearningPattern(contextSignature, decision); // Limit history size if (this.routingHistory.length > 1000) { this.routingHistory = this.routingHistory.slice(-500); } } /** * Update learning patterns based on routing decisions */ updateLearningPattern(contextSignature, decision) { let pattern = this.learningPatterns.get(contextSignature); if (!pattern) { pattern = { contextSignature, successfulAgents: new Map(), failurePatterns: [], adaptiveWeights: new Map(), confidenceHistory: [] }; this.learningPatterns.set(contextSignature, pattern); } // Record confidence for trend analysis pattern.confidenceHistory.push(decision.confidence); if (pattern.confidenceHistory.length > 20) { pattern.confidenceHistory = pattern.confidenceHistory.slice(-10); } // Update adaptive weights based on decision quality this.updateAdaptiveWeights(decision); } /** * Update adaptive weights based on decision outcomes */ updateAdaptiveWeights(decision) { const learningRate = 0.05; // Increase weight for factors that led to high-confidence decisions if (decision.confidence > 0.8) { for (const [factor, weight] of this.adaptiveWeights) { // Slightly increase successful factor weights this.adaptiveWeights.set(factor, weight + (learningRate * decision.confidence * 0.1)); } } // Normalize weights to sum to 1 this.normalizeAdaptiveWeights(); } /** * Normalize adaptive weights to ensure they sum to 1 */ normalizeAdaptiveWeights() { const totalWeight = Array.from(this.adaptiveWeights.values()).reduce((sum, weight) => sum + weight, 0); for (const [factor, weight] of this.adaptiveWeights) { this.adaptiveWeights.set(factor, weight / totalWeight); } } /** * Get current performance metrics and learning status */ getIntelligenceMetrics() { const avgConfidence = this.routingHistory.length > 0 ? this.routingHistory.reduce((sum, d) => sum + d.confidence, 0) / this.routingHistory.length : 0; const agentPerformance = new Map(); for (const [agentType, profile] of this.agentProfiles) { agentPerformance.set(agentType, { successRate: profile.averageSuccessRate, avgTime: profile.averageExecutionTime }); } return { totalDecisions: this.routingHistory.length, averageConfidence: avgConfidence, learningPatterns: this.learningPatterns.size, adaptiveWeights: new Map(this.adaptiveWeights), agentPerformance }; } // Additional helper methods... hasFailurePattern(agentType, pattern) { return pattern.failurePatterns.some(p => p.includes(agentType)); } getAdaptiveBoost(agentType, context) { // Return small adaptive boost based on recent learning return Math.random() * 0.05; // Placeholder - would use real adaptive learning } calculateSelectionConfidence(sortedAgents) { if (sortedAgents.length < 2) return 0.9; const topScore = sortedAgents[0][1].compositeScore; const secondScore = sortedAgents[1][1].compositeScore; const gap = topScore - secondScore; // Higher confidence with larger gaps between top agents return Math.min(0.95, 0.5 + gap * 2); } generateReasoningExplanation(score, context) { const reasons = []; if (score.factors.successRate > 0.9) { reasons.push(`High success rate (${(score.factors.successRate * 100).toFixed(1)}%)`); } if (score.factors.contextMatch > 0.8) { reasons.push('Strong specialization match for project context'); } if (score.factors.timeEfficiency > 0.7) { reasons.push('Meets performance time constraints'); } if (score.factors.learningTrend > 0.15) { reasons.push('Showing positive improvement trend'); } return reasons; } generateAlternativeReason(score) { const topFactor = Object.entries(score.factors) .sort((a, b) => b[1] - a[1])[0]; return `Strong ${topFactor[0].replace(/([A-Z])/g, ' $1').toLowerCase()} (${(topFactor[1] * 100).toFixed(1)}%)`; } estimatePerformance(agentType, context) { const profile = this.agentProfiles.get(agentType); return { successProbability: profile.averageSuccessRate, estimatedTimeMs: profile.averageExecutionTime, qualityScore: profile.learningMetrics.consistencyScore }; } } class ContextAnalyzer { async extractFeatures(context) { // Extract relevant features from context for agent selection return { identifiedDomains: this.identifyDomains(context.taskType, context.userIntent), complexity: this.assessComplexity(context), urgency: this.assessUrgency(context), frameworkConfidence: this.assessFrameworkConfidence(context) }; } generateContextSignature(context) { // Generate unique signature for similar contexts const { taskType, projectContext } = context; return `${taskType}-${projectContext?.framework || 'unknown'}-${projectContext?.complexity || 'unknown'}`; } identifyDomains(taskType, userIntent) { const combinedText = `${taskType} ${userIntent}`.toLowerCase(); const domains = []; if (combinedText.includes('performance') || combinedText.includes('slow')) { domains.push('performance'); } if (combinedText.includes('accessibility') || combinedText.includes('a11y')) { domains.push('accessibility'); } if (combinedText.includes('error') || combinedText.includes('bug')) { domains.push('error-investigation'); } if (combinedText.includes('test') || combinedText.includes('coverage')) { domains.push('testing'); } return domains; } assessComplexity(context) { const factors = [ context.projectContext?.complexity === 'complex' ? 0.8 : 0.4, context.sessionHistory.length > 5 ? 0.6 : 0.3, context.performanceConstraints.tokenBudget > 5000 ? 0.7 : 0.4 ]; return factors.reduce((sum, factor) => sum + factor, 0) / factors.length; } assessUrgency(context) { return context.performanceConstraints.maxTimeMs < 100 ? 0.9 : 0.5; } assessFrameworkConfidence(context) { return context.projectContext?.framework ? 0.9 : 0.3; } } class PerformanceTracker { routingTimes = []; agentPerformance = new Map(); recordRoutingTime(timeMs) { this.routingTimes.push(timeMs); if (this.routingTimes.length > 100) { this.routingTimes = this.routingTimes.slice(-50); } } getRecentPerformance(agentType) { const data = this.agentPerformance.get(agentType); if (!data || data.times.length < 3) { return { trend: 0, avgTime: 75 }; // Default values } const recentTimes = data.times.slice(-10); const avgTime = recentTimes.reduce((sum, time) => sum + time, 0) / recentTimes.length; // Calculate trend (positive = improving performance) const firstHalf = recentTimes.slice(0, Math.floor(recentTimes.length / 2)); const secondHalf = recentTimes.slice(Math.floor(recentTimes.length / 2)); const firstAvg = firstHalf.reduce((sum, time) => sum + time, 0) / firstHalf.length; const secondAvg = secondHalf.reduce((sum, time) => sum + time, 0) / secondHalf.length; const trend = (firstAvg - secondAvg) / firstAvg; // Positive = getting faster return { trend, avgTime }; } } //# sourceMappingURL=intelligent-agent-router.js.map