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

216 lines โ€ข 8.79 kB
/** * Stateless Debug Service - V2 Core Architecture * * Provides stateless debugging capabilities with comprehensive error handling * and automatic recovery mechanisms for AI-Debug V2 */ import { EventEmitter } from 'events'; export class StatelessDebugService extends EventEmitter { config; activeOperations = new Map(); operationHistory = []; isInitialized = false; constructor(config = {}) { super(); this.config = { maxConcurrentOperations: config.maxConcurrentOperations || 20, operationTimeoutMs: config.operationTimeoutMs || 30000, retryAttempts: config.retryAttempts || 3, enableCircuitBreaker: config.enableCircuitBreaker ?? true }; } async initialize() { if (this.isInitialized) { return; } try { console.error('๐Ÿ”ง Initializing V2 Stateless Debug Service...'); // Initialize any required resources await this.initializeResources(); // Start operation monitoring this.startOperationMonitoring(); this.isInitialized = true; console.error('โœ… V2 Stateless Debug Service initialized successfully'); } catch (error) { console.error('โŒ Failed to initialize V2 Stateless Debug Service:', error); throw error; } } async initializeResources() { // Initialize any required debugging resources // This is a placeholder for actual resource initialization await new Promise(resolve => setTimeout(resolve, 100)); } startOperationMonitoring() { // Monitor operations for timeouts and cleanup setInterval(() => { this.checkOperationTimeouts(); this.cleanupCompletedOperations(); }, 10000); // Check every 10 seconds } checkOperationTimeouts() { const now = Date.now(); for (const [id, operation] of this.activeOperations) { if (operation.status === 'running' && (now - operation.startTime) > this.config.operationTimeoutMs) { operation.status = 'timeout'; console.warn(`โฐ V2 Operation ${id} timed out after ${this.config.operationTimeoutMs}ms`); this.emit('operation_timeout', operation); this.activeOperations.delete(id); this.operationHistory.push(operation); } } } cleanupCompletedOperations() { // Keep operation history manageable if (this.operationHistory.length > 1000) { this.operationHistory = this.operationHistory.slice(-500); } } async executeDebugOperation(type, parameters = {}, sessionId) { if (!this.isInitialized) { throw new Error('Debug service not initialized'); } if (this.activeOperations.size >= this.config.maxConcurrentOperations) { throw new Error(`Maximum concurrent operations (${this.config.maxConcurrentOperations}) reached`); } const operation = { id: this.generateOperationId(), type, startTime: Date.now(), status: 'pending', sessionId, metadata: { parameters } }; this.activeOperations.set(operation.id, operation); try { operation.status = 'running'; // Execute the actual debug operation const result = await this.performDebugOperation(operation, parameters); operation.status = 'completed'; this.emit('operation_completed', operation); return result; } catch (error) { operation.status = 'failed'; operation.metadata.error = error.message; console.error(`โŒ V2 Debug operation ${operation.id} failed:`, error); this.emit('operation_failed', operation); throw error; } finally { this.activeOperations.delete(operation.id); this.operationHistory.push(operation); } } async performDebugOperation(operation, parameters) { // This is a placeholder for actual debug operation implementation // In the real implementation, this would dispatch to appropriate handlers switch (operation.type) { case 'screenshot': return await this.performScreenshot(parameters); case 'audit': return await this.performAudit(parameters); case 'user_action': return await this.performUserAction(parameters); default: return { success: true, operation: operation.type, result: `Placeholder result for ${operation.type}`, timestamp: new Date().toISOString(), executionTime: Math.random() * 1000 }; } } async performScreenshot(parameters) { // Simulate screenshot operation await new Promise(resolve => setTimeout(resolve, 200 + Math.random() * 800)); return { success: true, screenshot: { url: parameters.url || 'unknown', timestamp: new Date().toISOString(), dimensions: { width: 1920, height: 1080 }, format: 'png' } }; } async performAudit(parameters) { // Simulate audit operation await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 2000)); return { success: true, audit: { url: parameters.url || 'unknown', performance: Math.floor(Math.random() * 40) + 60, // 60-100 accessibility: Math.floor(Math.random() * 30) + 70, // 70-100 bestPractices: Math.floor(Math.random() * 25) + 75, // 75-100 seo: Math.floor(Math.random() * 20) + 80, // 80-100 timestamp: new Date().toISOString() } }; } async performUserAction(parameters) { // Simulate user action operation await new Promise(resolve => setTimeout(resolve, 300 + Math.random() * 700)); return { success: true, action: { type: parameters.action || 'click', target: parameters.selector || 'unknown', timestamp: new Date().toISOString(), result: 'Action executed successfully' } }; } generateOperationId() { return `v2_op_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; } getActiveOperations() { return Array.from(this.activeOperations.values()); } getOperationHistory() { return [...this.operationHistory]; } getServiceStats() { const active = this.activeOperations.size; const history = this.operationHistory; const completed = history.filter(op => op.status === 'completed').length; const failed = history.filter(op => op.status === 'failed').length; const timedOut = history.filter(op => op.status === 'timeout').length; return { initialized: this.isInitialized, activeOperations: active, totalOperations: history.length, successRate: history.length > 0 ? (completed / history.length) * 100 : 100, failureRate: history.length > 0 ? (failed / history.length) * 100 : 0, timeoutRate: history.length > 0 ? (timedOut / history.length) * 100 : 0, averageExecutionTime: this.calculateAverageExecutionTime() }; } calculateAverageExecutionTime() { const completedOps = this.operationHistory.filter(op => op.status === 'completed'); if (completedOps.length === 0) return 0; const totalTime = completedOps.reduce((sum, op) => { const endTime = op.metadata?.endTime || op.startTime + 1000; // Fallback return sum + (endTime - op.startTime); }, 0); return totalTime / completedOps.length; } async cleanup() { console.error('๐Ÿงน V2 Cleaning up Stateless Debug Service...'); // Cancel all active operations for (const [id, operation] of this.activeOperations) { operation.status = 'failed'; operation.metadata.error = 'Service shutdown'; console.error(`๐Ÿ›‘ Cancelling active operation: ${id}`); } this.activeOperations.clear(); this.isInitialized = false; console.error('โœ… V2 Stateless Debug Service cleanup completed'); } } //# sourceMappingURL=stateless-debug-service.js.map