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
252 lines • 9.75 kB
JavaScript
/**
* Performance Orchestrator - Performance analysis and optimization
*
* Coordinates performance profiling, metrics collection, and optimization suggestions
*/
export class PerformanceOrchestrator {
subAgents = {
metrics: 'metrics_collection_agent',
profiling: 'performance_profiling_agent',
bundle: 'bundle_analysis_agent',
optimization: 'optimization_suggestion_agent',
monitoring: 'performance_monitoring_agent'
};
async orchestrate(task) {
console.log('⚡ Performance Orchestrator: Analyzing performance task...');
const analysis = this.analyzeTask(task);
const plan = this.createExecutionPlan(analysis);
const results = await this.executePlan(plan);
return this.synthesizeResults(results);
}
analyzeTask(task) {
const keywords = (task.task || task.description || '').toLowerCase();
const analysis = {
primaryFocus: 'general',
metrics: [],
hasTargets: !!task.targets,
suggestedAgents: []
};
// Determine focus area
if (keywords.includes('slow') || keywords.includes('speed') || keywords.includes('latency')) {
analysis.primaryFocus = 'speed';
analysis.metrics.push('LCP', 'FCP', 'TTI', 'TBT');
analysis.suggestedAgents.push(this.subAgents.profiling);
}
if (keywords.includes('bundle') || keywords.includes('size') || keywords.includes('large')) {
analysis.primaryFocus = 'bundle';
analysis.metrics.push('bundleSize', 'chunkSizes');
analysis.suggestedAgents.push(this.subAgents.bundle);
}
if (keywords.includes('memory') || keywords.includes('leak')) {
analysis.primaryFocus = 'memory';
analysis.metrics.push('heapUsage', 'memoryLeaks');
analysis.suggestedAgents.push(this.subAgents.profiling);
}
// Always include metrics collection
if (!analysis.suggestedAgents.includes(this.subAgents.metrics)) {
analysis.suggestedAgents.unshift(this.subAgents.metrics);
}
// Always end with optimization suggestions
if (!analysis.suggestedAgents.includes(this.subAgents.optimization)) {
analysis.suggestedAgents.push(this.subAgents.optimization);
}
return analysis;
}
createExecutionPlan(analysis) {
const plan = {
steps: [],
parallel: true,
estimatedDuration: 0
};
// Step 1: Collect baseline metrics
plan.steps.push({
agent: this.subAgents.metrics,
action: 'collect_baseline',
params: {
metrics: analysis.metrics,
includeWebVitals: true
}
});
// Step 2: Deep analysis based on focus
switch (analysis.primaryFocus) {
case 'speed':
plan.steps.push({
agent: this.subAgents.profiling,
action: 'profile_runtime',
params: {
duration: 10000,
captureCallStacks: true
}
});
break;
case 'bundle':
plan.steps.push({
agent: this.subAgents.bundle,
action: 'analyze_bundles',
params: {
showDuplicates: true,
analyzeTreeShaking: true
}
});
break;
case 'memory':
plan.steps.push({
agent: this.subAgents.profiling,
action: 'profile_memory',
params: {
captureSnapshots: true,
detectLeaks: true
}
});
break;
}
// Step 3: Generate optimization suggestions
plan.steps.push({
agent: this.subAgents.optimization,
action: 'generate_suggestions',
params: {
targetMetrics: analysis.hasTargets,
prioritizeByImpact: true
}
});
plan.estimatedDuration = plan.steps.length * 8; // 8 seconds per step
return plan;
}
async executePlan(plan) {
const results = [];
for (const step of plan.steps) {
console.log(` → Delegating to ${step.agent} for ${step.action}...`);
// Mock implementation for now
const result = {
agent: step.agent,
action: step.action,
success: true,
summary: `Completed ${step.action}`,
data: this.getMockDataForAction(step.action),
duration: Math.random() * 5000 + 3000
};
results.push(result);
}
return results;
}
getMockDataForAction(action) {
switch (action) {
case 'collect_baseline':
return {
metrics: {
LCP: 2.5,
FCP: 1.8,
TTI: 3.5,
bundleSize: 2500,
memoryUsage: 45
},
score: 75
};
case 'profile_runtime':
return {
bottlenecks: [
{ function: 'renderLargeList', time: 1200, percentage: 35 },
{ function: 'calculateLayout', time: 800, percentage: 23 }
]
};
case 'analyze_bundles':
return {
totalSize: 2500,
chunks: [
{ name: 'main', size: 1200 },
{ name: 'vendor', size: 800 }
],
duplicates: ['lodash', 'moment']
};
case 'generate_suggestions':
return {
suggestions: [
{
title: 'Implement code splitting',
impact: 'high',
effort: 'medium',
description: 'Split main bundle into smaller chunks'
},
{
title: 'Optimize images',
impact: 'medium',
effort: 'low',
description: 'Use WebP format and lazy loading'
}
]
};
default:
return {};
}
}
synthesizeResults(results) {
// Extract key metrics
const metricsResult = results.find(r => r.action === 'collect_baseline');
const metrics = metricsResult?.data?.metrics || {};
// Extract issues
const issues = [];
results.forEach(result => {
if (result.data.bottlenecks) {
result.data.bottlenecks.forEach((b) => {
issues.push({
type: 'performance',
severity: b.percentage > 30 ? 'critical' : 'warning',
title: `Slow function: ${b.function}`,
description: `Taking ${b.time}ms (${b.percentage}% of runtime)`
});
});
}
if (result.data.duplicates) {
issues.push({
type: 'bundle',
severity: 'warning',
title: 'Duplicate dependencies detected',
description: `Found duplicates: ${result.data.duplicates.join(', ')}`
});
}
});
// Get suggestions
const suggestionsResult = results.find(r => r.action === 'generate_suggestions');
const suggestions = suggestionsResult?.data?.suggestions || [];
// Create summary
const summary = this.createSummary(metrics, issues);
return {
success: true,
summary,
findings: {
critical: issues.filter(i => i.severity === 'critical'),
warnings: issues.filter(i => i.severity === 'warning'),
info: issues.filter(i => i.severity === 'info')
},
suggestions: suggestions.slice(0, 3),
nextSteps: [
'Apply suggested optimizations',
'Re-run performance tests after changes',
'Set up continuous performance monitoring'
],
metadata: {
duration: results.reduce((sum, r) => sum + r.duration, 0),
agentsUsed: [...new Set(results.map(r => r.agent))],
confidence: 0.85,
metrics
}
};
}
createSummary(metrics, issues) {
const parts = [];
if (metrics.LCP) {
const lcpStatus = metrics.LCP <= 2.5 ? '✅' : metrics.LCP <= 4 ? '⚠️' : '❌';
parts.push(`LCP: ${metrics.LCP}s ${lcpStatus}`);
}
if (metrics.bundleSize) {
const sizeInMB = (metrics.bundleSize / 1024).toFixed(1);
parts.push(`Bundle: ${sizeInMB}MB`);
}
const criticalCount = issues.filter(i => i.severity === 'critical').length;
if (criticalCount > 0) {
parts.push(`${criticalCount} critical issues found`);
}
return parts.join(' | ') || 'Performance analysis complete';
}
}
//# sourceMappingURL=performance-orchestrator.js.map