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

293 lines โ€ข 11.3 kB
/** * Crash Prevention System * Comprehensive stability measures to prevent MCP server crashes */ import { EventEmitter } from 'events'; import * as os from 'os'; export class CrashPrevention extends EventEmitter { static instance; monitoringInterval = null; healthHistory = []; maxHistorySize = 60; // Keep 1 hour of 1-minute samples alertThresholds = { memoryUsage: 0.85, // 85% memory usage heapUsage: 0.90, // 90% heap usage cpuUsage: 0.80, // 80% CPU usage loadAverage: 5.0 // Load average > 5 }; criticalActions = { forceGC: true, killOldSessions: true, pauseNewConnections: true, emergencyCleanup: true }; static getInstance() { if (!CrashPrevention.instance) { CrashPrevention.instance = new CrashPrevention(); } return CrashPrevention.instance; } /** * Start continuous system monitoring */ startMonitoring() { if (this.monitoringInterval) { return; // Already monitoring } console.log('๐Ÿ›ก๏ธ Starting crash prevention monitoring...'); // Monitor every minute this.monitoringInterval = setInterval(() => { try { this.collectSystemHealth(); this.analyzeCrashRisk(); } catch (error) { console.error('โš ๏ธ Crash prevention monitoring error:', error); } }, 60 * 1000); // Initial health check this.collectSystemHealth(); } /** * Stop monitoring */ stopMonitoring() { if (this.monitoringInterval) { clearInterval(this.monitoringInterval); this.monitoringInterval = null; console.log('๐Ÿ›‘ Stopped crash prevention monitoring'); } } /** * Collect current system health metrics */ collectSystemHealth() { const memoryUsage = process.memoryUsage(); const cpuUsage = process.cpuUsage(); const loadAverage = os.loadavg(); const freeMemory = os.freemem(); const totalMemory = os.totalmem(); const health = { memoryUsage: { rss: memoryUsage.rss, heapTotal: memoryUsage.heapTotal, heapUsed: memoryUsage.heapUsed, external: memoryUsage.external, arrayBuffers: memoryUsage.arrayBuffers }, cpuUsage: { user: cpuUsage.user, system: cpuUsage.system }, uptime: process.uptime(), loadAverage, freeMemory, totalMemory, isUnderPressure: this.isSystemUnderPressure(memoryUsage, loadAverage, freeMemory, totalMemory) }; // Add to history this.healthHistory.push(health); if (this.healthHistory.length > this.maxHistorySize) { this.healthHistory.shift(); } return health; } /** * Determine if system is under pressure */ isSystemUnderPressure(memoryUsage, loadAverage, freeMemory, totalMemory) { // Focus on process memory, not system memory const processMemoryMB = memoryUsage.rss / (1024 * 1024); const heapUsagePercent = memoryUsage.heapUsed / memoryUsage.heapTotal; const cpuCount = os.cpus().length; const loadPerCpu = loadAverage[0] / cpuCount; return (processMemoryMB > 512 || // Process using over 512MB heapUsagePercent > this.alertThresholds.heapUsage || loadPerCpu > 2.0 // More than 200% load per CPU ); } /** * Analyze crash risk based on current and historical data */ analyzeCrashRisk() { const currentHealth = this.healthHistory[this.healthHistory.length - 1]; const factors = []; let riskLevel = 'low'; if (!currentHealth) { return { level: 'low', factors: [], recommendedActions: [], autoActionsEnabled: false }; } // Memory pressure analysis - Focus on PROCESS memory, not system memory const processMemoryMB = currentHealth.memoryUsage.rss / (1024 * 1024); const heapUsagePercent = currentHealth.memoryUsage.heapUsed / currentHealth.memoryUsage.heapTotal; // Only trigger on actual high process memory usage if (processMemoryMB > 1024) { // Over 1GB process memory factors.push(`Critical process memory usage (${processMemoryMB.toFixed(0)}MB)`); riskLevel = 'critical'; } else if (processMemoryMB > 512) { // Over 512MB process memory factors.push(`High process memory usage (${processMemoryMB.toFixed(0)}MB)`); riskLevel = riskLevel === 'low' ? 'medium' : riskLevel; } if (heapUsagePercent > 0.98) { // Node.js naturally uses high heap percentages factors.push('Critical heap usage (>98%)'); riskLevel = 'critical'; } else if (heapUsagePercent > this.alertThresholds.heapUsage) { factors.push(`High heap usage (${(heapUsagePercent * 100).toFixed(1)}%)`); riskLevel = riskLevel === 'low' ? 'medium' : riskLevel; } // CPU/Load analysis - Be more tolerant of system load const currentLoad = currentHealth.loadAverage[0]; const cpuCount = os.cpus().length; const loadPerCpu = currentLoad / cpuCount; // Only trigger on extreme load that affects the process if (loadPerCpu > 4.0) { // More than 400% load per CPU factors.push(`Critical system load (${currentLoad.toFixed(1)} on ${cpuCount} CPUs)`); riskLevel = 'critical'; } else if (loadPerCpu > 2.0) { // More than 200% load per CPU factors.push(`High system load (${currentLoad.toFixed(1)} on ${cpuCount} CPUs)`); riskLevel = riskLevel === 'low' ? 'medium' : riskLevel; } // Growth trend analysis if (this.healthHistory.length >= 10) { const memoryGrowth = this.analyzeMemoryGrowth(); if (memoryGrowth.isIncreasing && memoryGrowth.rate > 50) { // 50MB/minute factors.push(`Rapid memory growth (${memoryGrowth.rate.toFixed(1)}MB/min)`); riskLevel = riskLevel === 'low' ? 'high' : riskLevel; } } // Generate recommendations const recommendedActions = this.generateRecommendations(factors, riskLevel); // Execute automatic actions for critical situations const autoActionsEnabled = riskLevel === 'critical' && this.executeAutomaticActions(factors); const risk = { level: riskLevel, factors, recommendedActions, autoActionsEnabled }; // Emit risk assessment this.emit('riskAssessment', risk); // Log critical risks if (riskLevel === 'critical' || riskLevel === 'high') { console.warn(`๐Ÿšจ Crash risk: ${riskLevel.toUpperCase()}`); factors.forEach(factor => console.warn(` - ${factor}`)); } return risk; } /** * Analyze memory growth trend */ analyzeMemoryGrowth() { if (this.healthHistory.length < 10) { return { isIncreasing: false, rate: 0 }; } const recent = this.healthHistory.slice(-10); const first = recent[0]; const last = recent[recent.length - 1]; const memoryDiff = (last.memoryUsage.heapUsed - first.memoryUsage.heapUsed) / (1024 * 1024); // MB const timeDiff = (last.uptime - first.uptime) / 60; // minutes const rate = timeDiff > 0 ? memoryDiff / timeDiff : 0; return { isIncreasing: rate > 10, // More than 10MB/minute growth rate }; } /** * Generate recommended actions based on risk factors */ generateRecommendations(factors, riskLevel) { const actions = []; if (factors.some(f => f.includes('memory'))) { actions.push('Force garbage collection'); actions.push('Clean up inactive sessions'); actions.push('Reduce memory-intensive operations'); } if (factors.some(f => f.includes('heap'))) { actions.push('Clear internal buffers'); actions.push('Restart heavy components'); } if (factors.some(f => f.includes('load'))) { actions.push('Pause new connections'); actions.push('Kill old browser processes'); actions.push('Reduce concurrent operations'); } if (riskLevel === 'critical') { actions.push('Consider emergency server restart'); actions.push('Alert system administrators'); } return actions; } /** * Execute automatic actions for critical situations */ executeAutomaticActions(factors) { let actionsExecuted = false; try { // Force garbage collection if (this.criticalActions.forceGC && global.gc) { console.warn('๐Ÿ—‘๏ธ Executing emergency garbage collection...'); global.gc(); actionsExecuted = true; } // Clear event listener leaks if (factors.some(f => f.includes('memory'))) { console.warn('๐Ÿงน Clearing potential event listener leaks...'); process.removeAllListeners('warning'); process.setMaxListeners(50); // Increase limit temporarily actionsExecuted = true; } // Emit emergency cleanup signal if (this.criticalActions.emergencyCleanup) { console.warn('๐Ÿšจ Signaling emergency cleanup...'); this.emit('emergencyCleanup', { reason: 'critical_resource_pressure', factors }); actionsExecuted = true; } } catch (error) { console.error('โŒ Failed to execute automatic actions:', error); } return actionsExecuted; } /** * Get current system health */ getCurrentHealth() { return this.healthHistory.length > 0 ? this.healthHistory[this.healthHistory.length - 1] : null; } /** * Get health history */ getHealthHistory() { return [...this.healthHistory]; } /** * Force immediate health check and risk analysis */ performHealthCheck() { const health = this.collectSystemHealth(); const risk = this.analyzeCrashRisk(); return { health, risk }; } /** * Update alert thresholds */ updateThresholds(thresholds) { this.alertThresholds = { ...this.alertThresholds, ...thresholds }; console.log('๐Ÿ“Š Updated crash prevention thresholds:', this.alertThresholds); } /** * Enable/disable automatic actions */ updateCriticalActions(actions) { this.criticalActions = { ...this.criticalActions, ...actions }; console.log('โš™๏ธ Updated automatic actions:', this.criticalActions); } } //# sourceMappingURL=crash-prevention.js.map