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

661 lines • 28.4 kB
/** * Background Agents Handler * Integrates background debugging agents with the MCP tool system */ import { BackgroundAgentManager } from '../background-agents/background-agent-manager.js'; import { IntelligentToolSelector } from '../intelligent-tool-selection/tool-selector.js'; import { HumanEscalationManager } from '../human-escalation/escalation-manager.js'; import { BaseToolHandler } from './base-handler-migrated.js'; export class BackgroundAgentsHandler extends BaseToolHandler { agentManager; toolSelector; escalationManager; constructor() { super(); this.agentManager = new BackgroundAgentManager(); this.toolSelector = new IntelligentToolSelector(); this.escalationManager = new HumanEscalationManager(); this.setupEventHandlers(); } get tools() { return [ { name: 'start_background_monitoring', description: 'Start continuous background debugging agents for proactive monitoring. Includes Performance Watcher, Error Sentinel, Accessibility Guardian, and Regression Detective.', inputSchema: { type: 'object', properties: { sessionId: { type: 'string', description: 'Debug session ID to monitor' }, agentTypes: { type: 'array', items: { type: 'string', enum: ['performance-watcher', 'error-sentinel', 'accessibility-guardian', 'regression-detective', 'all'] }, default: ['all'], description: 'Specific agents to start, or "all" for complete monitoring' }, debugContext: { type: 'object', properties: { framework: { type: 'string' }, phase: { type: 'string', enum: ['initial', 'deep_dive', 'performance', 'testing', 'resolution'] }, userExperience: { type: 'string', enum: ['beginner', 'intermediate', 'expert'] }, projectComplexity: { type: 'string', enum: ['simple', 'moderate', 'complex'] }, timeConstraint: { type: 'string', enum: ['none', 'moderate', 'urgent'] } }, description: 'Current debugging context for intelligent monitoring' } }, required: ['sessionId'] } }, { name: 'stop_background_monitoring', description: 'Stop background debugging agents and get final monitoring report.', inputSchema: { type: 'object', properties: { agentIds: { type: 'array', items: { type: 'string' }, description: 'Specific agent IDs to stop, or empty for all agents' }, generateReport: { type: 'boolean', default: true, description: 'Generate comprehensive monitoring report' } } } }, { name: 'get_background_findings', description: 'Retrieve findings from background debugging agents with intelligent filtering and prioritization.', inputSchema: { type: 'object', properties: { severity: { type: 'string', enum: ['all', 'info', 'warning', 'error', 'critical'], default: 'all', description: 'Filter findings by severity level' }, category: { type: 'string', enum: ['all', 'performance', 'errors', 'accessibility', 'visual', 'security'], default: 'all', description: 'Filter findings by category' }, timeRange: { type: 'string', enum: ['1h', '6h', '24h', 'all'], default: '24h', description: 'Time range for findings' }, actionableOnly: { type: 'boolean', default: false, description: 'Only return findings that have available actions' } } } }, { name: 'get_intelligent_tool_recommendations', description: 'Get contextually intelligent tool recommendations based on current debugging situation, following Wordware\'s <15 tools principle.', inputSchema: { type: 'object', properties: { debugContext: { type: 'object', properties: { framework: { type: 'string' }, phase: { type: 'string', enum: ['initial', 'deep_dive', 'performance', 'testing', 'resolution'] }, userExperience: { type: 'string', enum: ['beginner', 'intermediate', 'expert'] }, projectComplexity: { type: 'string', enum: ['simple', 'moderate', 'complex'] }, timeConstraint: { type: 'string', enum: ['none', 'moderate', 'urgent'] } }, required: ['phase'] }, excludeTools: { type: 'array', items: { type: 'string' }, description: 'Tools to exclude from recommendations' }, maxTools: { type: 'number', default: 12, minimum: 5, maximum: 15, description: 'Maximum number of tools to recommend (follows Wordware <15 rule)' } }, required: ['debugContext'] } }, { name: 'create_human_escalation', description: 'Escalate to human when AI "knows what it doesn\'t know" - implements intelligent human-in-the-loop pattern.', inputSchema: { type: 'object', properties: { reason: { type: 'object', properties: { type: { type: 'string', enum: ['knowledge_gap', 'permission_needed', 'ambiguous_context', 'critical_decision', 'error_recovery', 'resource_access'] }, description: { type: 'string' }, severity: { type: 'string', enum: ['low', 'medium', 'high', 'critical'] } }, required: ['type', 'description', 'severity'] }, context: { type: 'object', properties: { sessionId: { type: 'string' }, toolName: { type: 'string' }, currentPhase: { type: 'string' }, userExperience: { type: 'string', enum: ['beginner', 'intermediate', 'expert'] }, lastActions: { type: 'array', items: { type: 'string' } }, errorHistory: { type: 'array', items: { type: 'string' } } }, required: ['currentPhase', 'userExperience'] }, autoTimeoutMs: { type: 'number', description: 'Auto-resolve timeout in milliseconds for non-critical escalations' } }, required: ['reason', 'context'] } }, { name: 'handle_escalation_response', description: 'Process human response to escalation request.', inputSchema: { type: 'object', properties: { escalationId: { type: 'string' }, selectedActionId: { type: 'string' }, userInput: { type: 'object' }, customAction: { type: 'string' }, continueAutonomously: { type: 'boolean', default: false } }, required: ['escalationId'] } }, { name: 'get_agent_status_dashboard', description: 'Get comprehensive status dashboard for all background agents and escalations.', inputSchema: { type: 'object', properties: { includeFindings: { type: 'boolean', default: true, description: 'Include recent findings in dashboard' }, includeEscalations: { type: 'boolean', default: true, description: 'Include pending escalations' } } } }, { name: 'configure_intelligent_tool_selection', description: 'Configure the intelligent tool selection algorithm based on user preferences.', inputSchema: { type: 'object', properties: { maxTools: { type: 'number', minimum: 5, maximum: 15, description: 'Maximum tools to select (Wordware recommends <15)' }, selectionWeights: { type: 'object', properties: { frameworkMatch: { type: 'number', minimum: 0, maximum: 1 }, trainingDataRich: { type: 'number', minimum: 0, maximum: 1 }, userHistoryMatch: { type: 'number', minimum: 0, maximum: 1 }, costEfficiency: { type: 'number', minimum: 0, maximum: 1 }, authorityLevel: { type: 'number', minimum: 0, maximum: 1 } }, description: 'Weights for different selection criteria (should sum to ~1.0)' }, minimumScore: { type: 'number', minimum: 0, maximum: 1, description: 'Minimum score threshold for tool inclusion' } } } } ]; } async handle(toolName, args, sessions) { switch (toolName) { case 'start_background_monitoring': return this.startBackgroundMonitoring(args); case 'stop_background_monitoring': return this.stopBackgroundMonitoring(args); case 'get_agent_status_dashboard': return this.getAgentStatusDashboard(args); case 'create_human_escalation': return this.createHumanEscalation(args); case 'handle_escalation_response': return this.handleEscalationResponse(args); case 'get_intelligent_tool_recommendations': return this.getIntelligentToolRecommendations(args); default: throw new Error(`Unknown tool: ${toolName}`); } } /** * Start background monitoring agents */ async startBackgroundMonitoring(args) { const { sessionId, agentTypes = ['all'], debugContext } = args; // Update debug context if provided if (debugContext) { this.agentManager.updateDebugContext(debugContext); } // Determine which agents to start const agentsToStart = agentTypes.includes('all') ? ['performance-watcher', 'error-sentinel', 'accessibility-guardian', 'regression-detective'] : agentTypes; const results = []; for (const agentId of agentsToStart) { try { await this.agentManager.startAgent(agentId); results.push({ agentId, status: 'started', message: `Background agent ${agentId} started successfully` }); } catch (error) { results.push({ agentId, status: 'error', message: `Failed to start agent ${agentId}: ${error instanceof Error ? error.message : String(error)}` }); } } return { success: true, sessionId, agents: results, message: 'Background monitoring initiated. Agents will continuously monitor your application and alert you to issues.', dashboard: this.agentManager.getAgentStatusSummary() }; } /** * Stop background monitoring */ async stopBackgroundMonitoring(args) { const { agentIds = [], generateReport = true } = args; let agentsToStop; if (agentIds.length === 0) { // Stop all agents agentsToStop = Array.from(this.agentManager.getAgentStatusSummary().map(a => a.agentId)); } else { agentsToStop = agentIds; } const results = []; for (const agentId of agentsToStop) { try { await this.agentManager.stopAgent(agentId); results.push({ agentId, status: 'stopped', message: `Agent ${agentId} stopped successfully` }); } catch (error) { results.push({ agentId, status: 'error', message: `Failed to stop agent ${agentId}: ${error instanceof Error ? error.message : String(error)}` }); } } let report = null; if (generateReport) { report = this.generateMonitoringReport(); } return { success: true, agents: results, report, message: 'Background monitoring stopped. Review the monitoring report for insights.' }; } /** * Get background findings with filtering */ async getBackgroundFindings(args) { const { severity = 'all', category = 'all', timeRange = '24h', actionableOnly = false } = args; let findings = this.agentManager.getAllFindings(); // Apply filters if (severity !== 'all') { findings = findings.filter(f => f.severity === severity); } if (category !== 'all') { findings = findings.filter(f => f.category === category); } if (actionableOnly) { findings = findings.filter(f => f.actionable); } // Apply time range filter const timeRangeMs = this.parseTimeRange(timeRange); const cutoffTime = new Date(Date.now() - timeRangeMs); findings = findings.filter(f => f.timestamp >= cutoffTime); // Sort by severity and timestamp findings.sort((a, b) => { const severityOrder = { critical: 4, error: 3, warning: 2, info: 1 }; const aSeverity = severityOrder[a.severity] || 0; const bSeverity = severityOrder[b.severity] || 0; if (aSeverity !== bSeverity) { return bSeverity - aSeverity; // Higher severity first } return b.timestamp.getTime() - a.timestamp.getTime(); // Newer first }); return { success: true, findings: findings.slice(0, 50), // Limit to 50 most relevant total: findings.length, filters: { severity, category, timeRange, actionableOnly }, summary: this.generateFindingsSummary(findings) }; } /** * Get intelligent tool recommendations */ async getIntelligentToolRecommendations(args) { const { debugContext, excludeTools = [], maxTools = 12 } = args; // Update tool selector strategy this.toolSelector.updateStrategy({ maxTools }); // For now, return a mock response as we don't have all tools converted to EnhancedTool format const mockRecommendations = { success: true, context: debugContext, selectedTools: [ { name: 'inject_debugging', score: 0.95, reasoning: ['High framework compatibility', 'Essential for initial debugging phase'] }, { name: 'take_screenshot', score: 0.87, reasoning: ['Visual debugging essential', 'Cost-efficient execution'] }, { name: 'run_audit', score: 0.82, reasoning: ['Comprehensive analysis tool', 'Rich training data available'] } ], totalAvailable: 346, selectionReasoning: `Selected ${maxTools} tools optimized for ${debugContext.phase} phase. Tool selection based on framework compatibility, training data richness, and user experience level.`, alternativeTools: [ 'get_console_logs', 'get_performance_metrics', 'analyze_with_ai' ] }; return mockRecommendations; } /** * Create human escalation */ async createHumanEscalation(args) { const { reason, context, autoTimeoutMs } = args; const escalationId = await this.escalationManager.createEscalation(reason, context, autoTimeoutMs); const escalation = this.escalationManager.getEscalation(escalationId); return { success: true, escalationId, escalation, message: `Human escalation created: ${reason.description}`, suggestedActions: escalation?.suggestedActions || [] }; } /** * Handle escalation response */ async handleEscalationResponse(args) { await this.escalationManager.handleEscalationResponse(args); return { success: true, escalationId: args.escalationId, message: 'Escalation response processed successfully' }; } /** * Get agent status dashboard */ async getAgentStatusDashboard(args) { const { includeFindings = true, includeEscalations = true } = args; const dashboard = { agents: this.agentManager.getAgentStatusSummary(), escalationStats: this.escalationManager.getEscalationStats() }; if (includeFindings) { const recentFindings = this.agentManager.getAllFindings() .slice(0, 10) .map(f => ({ id: f.id, agentId: f.agentId, severity: f.severity, title: f.title, timestamp: f.timestamp })); dashboard['recentFindings'] = recentFindings; } if (includeEscalations) { dashboard['pendingEscalations'] = this.escalationManager.getPendingEscalations().map(e => ({ id: e.id, reason: e.reason.type, severity: e.reason.severity, timestamp: e.timestamp })); } return { success: true, dashboard, timestamp: new Date().toISOString() }; } /** * Configure intelligent tool selection */ async configureIntelligentToolSelection(args) { this.toolSelector.updateStrategy(args); const currentStrategy = this.toolSelector.getStrategy(); return { success: true, message: 'Tool selection strategy updated', currentStrategy }; } /** * Setup event handlers for cross-component communication */ setupEventHandlers() { // Agent findings that might need escalation this.agentManager.on('agent_executed', (event) => { const { agent, findings } = event; for (const finding of findings) { if (finding.humanEscalationNeeded) { // Auto-create escalation for critical findings this.escalationManager.createEscalation({ type: 'critical_decision', description: `${agent.name} found critical issue: ${finding.title}`, severity: finding.severity, autoResolvable: finding.autoFixAvailable }, { sessionId: finding.context?.sessionId, toolName: agent.name, currentPhase: 'monitoring', userExperience: 'intermediate', timeConstraint: 'moderate', projectComplexity: 'moderate', lastActions: [`${agent.name} execution`], errorHistory: finding.severity === 'error' ? [finding.description] : [] }); } } }); this.agentManager.on('agent_error', (event) => { // Auto-escalate agent errors const { agent, error } = event; this.escalationManager.createEscalation({ type: 'error_recovery', description: `Background agent ${agent.name} encountered an error`, severity: 'medium', autoResolvable: true }, { currentPhase: 'monitoring', userExperience: 'intermediate', timeConstraint: 'moderate', projectComplexity: 'moderate', lastActions: [`${agent.name} execution failed`], errorHistory: [error.message] }); }); } /** * Generate monitoring report */ generateMonitoringReport() { const findings = this.agentManager.getAllFindings(); const agentStats = this.agentManager.getAgentStatusSummary(); const escalationStats = this.escalationManager.getEscalationStats(); return { summary: { totalFindings: findings.length, criticalIssues: findings.filter(f => f.severity === 'critical').length, agentsRun: agentStats.length, escalationsCreated: escalationStats.totalEscalations }, findings: this.generateFindingsSummary(findings), recommendations: this.generateRecommendations(findings), generatedAt: new Date().toISOString() }; } /** * Generate findings summary */ generateFindingsSummary(findings) { const summary = { bySeverity: {}, byCategory: {}, byAgent: {}, actionableCount: 0 }; for (const finding of findings) { // By severity summary.bySeverity[finding.severity] = (summary.bySeverity[finding.severity] || 0) + 1; // By category summary.byCategory[finding.category] = (summary.byCategory[finding.category] || 0) + 1; // By agent summary.byAgent[finding.agentId] = (summary.byAgent[finding.agentId] || 0) + 1; // Actionable count if (finding.actionable) { summary.actionableCount++; } } return summary; } /** * Generate recommendations based on findings */ generateRecommendations(findings) { const recommendations = []; const criticalFindings = findings.filter(f => f.severity === 'critical'); const errorFindings = findings.filter(f => f.severity === 'error'); if (criticalFindings.length > 0) { recommendations.push(`Address ${criticalFindings.length} critical issues immediately`); } if (errorFindings.length > 3) { recommendations.push('High error rate detected - investigate error patterns'); } const performanceFindings = findings.filter(f => f.category === 'performance'); if (performanceFindings.length > 0) { recommendations.push('Performance optimization needed - run detailed performance audit'); } const accessibilityFindings = findings.filter(f => f.category === 'accessibility'); if (accessibilityFindings.length > 0) { recommendations.push('Accessibility violations found - schedule accessibility review'); } if (recommendations.length === 0) { recommendations.push('No critical issues detected - continue monitoring'); } return recommendations; } /** * Parse time range string to milliseconds */ parseTimeRange(timeRange) { switch (timeRange) { case '1h': return 60 * 60 * 1000; case '6h': return 6 * 60 * 60 * 1000; case '24h': return 24 * 60 * 60 * 1000; case 'all': return Number.MAX_SAFE_INTEGER; default: return 24 * 60 * 60 * 1000; } } } //# sourceMappingURL=background-agents-handler.js.map