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

429 lines • 16.5 kB
/** * Context Analyzer - Intelligent context detection for AI models * * Analyzes user input, conversation history, and environment to provide * intelligent context that helps AI models make better tool selection decisions. */ export class ContextAnalyzer { intentPatterns = new Map(); technologyPatterns = new Map(); actionPatterns = new Map(); conversationHistory = []; constructor() { this.initializePatterns(); } initializePatterns() { // Intent detection patterns this.intentPatterns.set('debugging', [ /\b(debug|debugs|debugging|fix|fixing|issue|problem|error|bug|broken)\b/i, /\b(not working|doesn't work|isn't working|failing|fails)\b/i, /\b(investigate|find out|figure out|understand why)\b/i ]); this.intentPatterns.set('testing', [ /\b(test|testing|check|verify|validate|confirm)\b/i, /\b(works|working|functions|functionality)\b/i, /\b(try|attempt|see if|make sure)\b/i ]); this.intentPatterns.set('analysis', [ /\b(analyze|analysis|examine|inspect|review|audit)\b/i, /\b(performance|speed|slow|fast|optimize|optimization)\b/i, /\b(accessibility|a11y|seo|quality|best practices)\b/i ]); this.intentPatterns.set('visual', [ /\b(see|look|view|show|display|appear|appearance)\b/i, /\b(screenshot|capture|image|visual|layout|design)\b/i, /\b(how does|what does|looks like)\b/i ]); this.intentPatterns.set('interaction', [ /\b(click|type|fill|submit|navigate|scroll|interact)\b/i, /\b(form|button|link|input|field|element)\b/i, /\b(user flow|user journey|workflow)\b/i ]); // Technology detection patterns this.technologyPatterns.set('react', [ /\breact\b/i, /\bjsx\b/i, /\bcomponent\b/i, /\bhooks?\b/i ]); this.technologyPatterns.set('vue', [ /\bvue\.?js?\b/i, /\bnuxt\b/i, /\bvuetify\b/i ]); this.technologyPatterns.set('angular', [ /\bangular\b/i, /\btypescript\b/i, /\brxjs\b/i ]); this.technologyPatterns.set('nextjs', [ /\bnext\.?js\b/i, /\bssr\b/i, /\bstatic\s+generation\b/i ]); this.technologyPatterns.set('flutter', [ /\bflutter\b/i, /\bdart\b/i, /\bwidget\b/i ]); // Action detection patterns this.actionPatterns.set('urgent', [ /\b(urgent|asap|immediately|now|quickly|fast)\b/i, /\b(production|live|critical|important)\b/i, /\b(down|broken|not working|failing)\b/i ]); this.actionPatterns.set('exploratory', [ /\b(explore|understand|learn|investigate|research)\b/i, /\b(how|why|what|when|where)\b/i, /\b(help me|show me|explain)\b/i ]); this.actionPatterns.set('systematic', [ /\b(comprehensive|thorough|complete|full|detailed)\b/i, /\b(step by step|methodical|systematic)\b/i, /\b(audit|analysis|review)\b/i ]); } /** * Analyze user input and context to provide intelligent insights */ analyzeContext(userInput, additionalContext) { const userIntent = this.analyzeUserIntent(userInput); const technicalContext = this.analyzeTechnicalContext(userInput); const actionContext = this.analyzeActionContext(userInput); const domainContext = this.analyzeDomainContext(userInput); const conversationContext = this.analyzeConversationContext(userInput, additionalContext); const environmentHints = this.generateEnvironmentHints(userInput, technicalContext); // Store in conversation history this.conversationHistory.push({ input: userInput, timestamp: Date.now(), tools: [] // Will be populated after tool execution }); // Keep only recent history (last 10 interactions) if (this.conversationHistory.length > 10) { this.conversationHistory = this.conversationHistory.slice(-10); } return { userIntent, technicalContext, actionContext, domainContext, conversationContext, environmentHints }; } analyzeUserIntent(userInput) { const intentScores = {}; // Score each intent based on pattern matches for (const [intent, patterns] of this.intentPatterns) { let score = 0; for (const pattern of patterns) { const matches = userInput.match(pattern); if (matches) { score += matches.length; } } if (score > 0) { intentScores[intent] = score; } } // Determine primary and secondary intents const sortedIntents = Object.entries(intentScores) .sort(([, a], [, b]) => b - a); const primary = sortedIntents[0]?.[0] || 'general'; const secondary = sortedIntents.slice(1, 3).map(([intent]) => intent); // Calculate confidence based on pattern strength const totalScore = Object.values(intentScores).reduce((sum, score) => sum + score, 0); const primaryScore = intentScores[primary] || 0; const confidence = totalScore > 0 ? Math.min(primaryScore / totalScore, 1.0) : 0.5; return { primary, secondary, confidence }; } analyzeTechnicalContext(userInput) { const urls = this.extractUrls(userInput); const technologies = this.detectTechnologies(userInput); const frameworks = this.detectFrameworks(userInput); const platforms = this.detectPlatforms(userInput); return { urls, technologies, frameworks, platforms }; } analyzeActionContext(userInput) { const requestedActions = this.extractExplicitActions(userInput); const impliedActions = this.inferImpliedActions(userInput); const urgencyLevel = this.assessUrgencyLevel(userInput); return { requestedActions, impliedActions, urgencyLevel }; } analyzeDomainContext(userInput) { const domain = this.identifyDomain(userInput); const expertise = this.assessExpertiseLevel(userInput); const commonPatterns = this.identifyCommonPatterns(userInput, domain); return { domain, expertise, commonPatterns }; } analyzeConversationContext(userInput, additionalContext) { const isFollowUp = this.isFollowUpRequest(userInput); const previousTools = this.getPreviousTools(); const sessionContinuity = this.hasSessionContinuity(additionalContext); return { isFollowUp, previousTools, sessionContinuity }; } generateEnvironmentHints(userInput, technicalContext) { let likelyPlatform = 'web'; let suggestedStartingPoint = 'inject_debugging'; const potentialChallenges = []; // Detect platform from context if (technicalContext.frameworks.includes('flutter')) { likelyPlatform = 'flutter_web'; potentialChallenges.push('Flutter Web specific rendering issues'); } else if (technicalContext.frameworks.includes('nextjs')) { likelyPlatform = 'nextjs'; potentialChallenges.push('SSR/hydration issues'); } else if (technicalContext.frameworks.includes('react')) { likelyPlatform = 'react_spa'; potentialChallenges.push('Client-side routing issues'); } // Suggest starting point based on intent if (userInput.includes('screenshot') || userInput.includes('look')) { suggestedStartingPoint = 'inject_debugging'; potentialChallenges.push('Page load timing for accurate screenshots'); } else if (userInput.includes('performance') || userInput.includes('slow')) { suggestedStartingPoint = 'inject_debugging'; potentialChallenges.push('Network conditions affecting measurements'); } // Add URL-specific challenges if (technicalContext.urls.some(url => url.includes('localhost'))) { potentialChallenges.push('Local development environment variables'); } return { likelyPlatform, suggestedStartingPoint, potentialChallenges }; } // Helper methods extractUrls(text) { const urlPattern = /https?:\/\/[^\s]+/g; return text.match(urlPattern) || []; } detectTechnologies(text) { const technologies = []; for (const [tech, patterns] of this.technologyPatterns) { for (const pattern of patterns) { if (pattern.test(text)) { technologies.push(tech); break; } } } return technologies; } detectFrameworks(text) { const frameworks = []; // Framework detection based on keywords if (/\b(react|jsx)\b/i.test(text)) frameworks.push('react'); if (/\bnext\.?js\b/i.test(text)) frameworks.push('nextjs'); if (/\bvue\.?js?\b/i.test(text)) frameworks.push('vue'); if (/\bangular\b/i.test(text)) frameworks.push('angular'); if (/\bflutter\b/i.test(text)) frameworks.push('flutter'); return frameworks; } detectPlatforms(text) { const platforms = []; if (/\b(mobile|phone|ios|android)\b/i.test(text)) platforms.push('mobile'); if (/\b(desktop|computer|pc|mac)\b/i.test(text)) platforms.push('desktop'); if (/\b(web|browser|chrome|firefox|safari)\b/i.test(text)) platforms.push('web'); return platforms; } extractExplicitActions(text) { const actions = []; if (/\bclick\b/i.test(text)) actions.push('click'); if (/\b(type|fill|enter)\b/i.test(text)) actions.push('type'); if (/\bscroll\b/i.test(text)) actions.push('scroll'); if (/\b(submit|send)\b/i.test(text)) actions.push('submit'); if (/\b(navigate|go to)\b/i.test(text)) actions.push('navigate'); if (/\b(screenshot|capture)\b/i.test(text)) actions.push('screenshot'); if (/\b(audit|analyze)\b/i.test(text)) actions.push('audit'); return actions; } inferImpliedActions(text) { const implied = []; // If they want to test something, they likely need screenshots if (/\btest\b/i.test(text)) { implied.push('screenshot', 'document_state'); } // If they mention forms, they likely want to interact if (/\bform\b/i.test(text)) { implied.push('fill_form', 'submit'); } // If they mention performance, they likely want audits if (/\b(slow|fast|performance)\b/i.test(text)) { implied.push('performance_audit'); } return implied; } assessUrgencyLevel(text) { const urgentPatterns = this.actionPatterns.get('urgent') || []; for (const pattern of urgentPatterns) { if (pattern.test(text)) { return 'high'; } } if (/\b(soon|today|need)\b/i.test(text)) { return 'medium'; } return 'low'; } identifyDomain(text) { if (/\b(e-commerce|shop|store|buy|sell|cart|checkout)\b/i.test(text)) { return 'ecommerce'; } if (/\b(blog|article|content|cms)\b/i.test(text)) { return 'content'; } if (/\b(dashboard|admin|management|analytics)\b/i.test(text)) { return 'admin'; } if (/\b(portfolio|personal|about|resume)\b/i.test(text)) { return 'portfolio'; } if (/\b(social|chat|message|community)\b/i.test(text)) { return 'social'; } return 'general'; } assessExpertiseLevel(text) { const expertTerms = /\b(optimization|performance|accessibility|seo|lighthouse|devtools|debugging|profiling)\b/i; const beginnerTerms = /\b(help|how|what|basic|simple|new|learn)\b/i; if (expertTerms.test(text)) { return 'expert'; } if (beginnerTerms.test(text)) { return 'beginner'; } return 'intermediate'; } identifyCommonPatterns(text, domain) { const patterns = []; if (domain === 'ecommerce') { patterns.push('product_pages', 'checkout_flow', 'cart_functionality'); } else if (domain === 'content') { patterns.push('reading_experience', 'navigation', 'search_functionality'); } else if (domain === 'admin') { patterns.push('data_tables', 'forms', 'authentication'); } return patterns; } isFollowUpRequest(text) { const followUpPatterns = [ /\b(also|additionally|furthermore|moreover|next|then)\b/i, /\b(now|after that|following|continue)\b/i, /\b(same|this|that|it)\b/i ]; return followUpPatterns.some(pattern => pattern.test(text)); } getPreviousTools() { return this.conversationHistory .slice(-3) // Last 3 interactions .flatMap(interaction => interaction.tools); } hasSessionContinuity(additionalContext) { return Boolean(additionalContext?.sessionId); } /** * Update conversation history with tool execution results */ updateToolHistory(tools) { if (this.conversationHistory.length > 0) { this.conversationHistory[this.conversationHistory.length - 1].tools = tools; } } /** * Get contextual recommendations for tool sequencing */ getSequenceRecommendations(analyzedContext) { const { userIntent, actionContext, technicalContext } = analyzedContext; // Base sequence on primary intent let recommended = ['inject_debugging']; let reasoning = 'Standard debugging workflow'; switch (userIntent.primary) { case 'visual': recommended = ['inject_debugging', 'take_screenshot']; reasoning = 'Visual analysis workflow for capturing current state'; break; case 'analysis': recommended = ['inject_debugging', 'run_audit', 'take_screenshot']; reasoning = 'Comprehensive analysis workflow with documentation'; break; case 'testing': recommended = ['inject_debugging', 'take_screenshot', 'simulate_user_action']; reasoning = 'Interactive testing workflow with before/after documentation'; break; case 'interaction': recommended = ['inject_debugging', 'take_screenshot', 'simulate_user_action', 'take_screenshot']; reasoning = 'Full interaction testing with visual proof'; break; } // Adjust for urgency if (actionContext.urgencyLevel === 'high') { recommended = recommended.slice(0, 2); // Shorter sequence for urgent requests reasoning += ' (abbreviated for urgency)'; } const alternatives = [ { sequence: ['inject_debugging', 'run_audit'], use_case: 'Quick performance check' }, { sequence: ['inject_debugging', 'take_screenshot'], use_case: 'Visual documentation only' }, { sequence: ['inject_debugging', 'simulate_user_action'], use_case: 'Direct interaction testing' } ]; return { recommended, reasoning, alternatives }; } } //# sourceMappingURL=context-analyzer.js.map