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
906 lines (898 loc) • 47.7 kB
JavaScript
/**
* AI Tool Discovery System - Make tools completely discoverable by AI models
*
* This system ensures AI models can discover, understand, and use all debugging tools
* without requiring explicit user instructions about tool capabilities.
*/
import { loadHierarchicalConfig } from '../config/hierarchical-mode.js';
export class AIToolDiscovery {
toolMetadata = new Map();
categoryIndex = new Map();
signalIndex = new Map();
initialized = false;
hierarchicalMode = false;
constructor(hierarchicalMode) {
// If not explicitly set, check the global config
if (hierarchicalMode === undefined) {
const config = loadHierarchicalConfig();
this.hierarchicalMode = config.enabled && config.orchestratorOnly;
}
else {
this.hierarchicalMode = hierarchicalMode;
}
this.initializeToolMetadata();
}
initializeToolMetadata() {
if (this.hierarchicalMode) {
// Only register orchestrator tools in hierarchical mode
this.registerOrchestratorTools();
return;
}
// Core debugging tools with AI-friendly descriptions
this.registerTool({
name: 'inject_debugging',
category: 'session_management',
purpose: 'Start a debugging session for any web application',
aiDescription: 'This is THE starting point for all debugging activities. Call this first when user wants to debug, test, audit, or analyze any website or web application.',
useWhenUser: [
'wants to debug a website',
'asks to test a web app',
'needs to audit performance',
'wants to analyze a page',
'mentions any URL',
'asks about accessibility',
'wants to take screenshots',
'needs to interact with a page'
],
autoTriggerSignals: [
'debug',
'test',
'audit',
'analyze',
'check',
'inspect',
'screenshot',
'performance',
'accessibility',
'http://',
'https://',
'localhost',
'website',
'web app',
'page'
],
requiredParameters: [{
name: 'url',
type: 'string',
description: 'The URL of the web application to debug',
aiHint: 'Always provide the full URL including protocol (http:// or https://)',
examples: ['https://example.com', 'http://localhost:3000', 'https://app.mysite.com/dashboard']
}],
optionalParameters: [{
name: 'sessionId',
type: 'string',
description: 'Custom session identifier',
aiHint: 'Usually auto-generated, only specify if continuing an existing session',
defaultValue: null
}],
commonWorkflows: [{
scenario: 'User wants to debug a slow website',
steps: [
'1. Call inject_debugging with the URL',
'2. Wait for session to be established',
'3. Call run_audit for performance analysis',
'4. Call take_screenshot to document current state',
'5. Use simulate_user_action to test interactions'
],
expectedOutcome: 'Debugging session ready for comprehensive analysis'
}],
aiUsageExamples: [{
userRequest: 'Can you help me debug why my website is loading slowly?',
reasoning: 'User wants to debug performance issues with their website',
toolCall: {
tool: 'inject_debugging',
parameters: { url: 'https://user-website.com' }
},
expectedResult: 'Debugging session established, ready for performance analysis'
}],
troubleshooting: [{
issue: 'URL not accessible',
solution: 'Check if URL is correct and accessible from your network',
preventiveMeasures: ['Verify URL format', 'Test URL in browser first', 'Check network connectivity']
}],
integrationTips: {
worksBestWith: ['run_audit', 'take_screenshot', 'simulate_user_action'],
shouldNotUseWith: [],
sequenceRecommendations: ['Always call this FIRST before any other debugging tools']
}
});
this.registerTool({
name: 'take_screenshot',
category: 'visual_analysis',
purpose: 'Capture visual state of web pages for analysis and documentation',
aiDescription: 'Use this to capture the current visual state of a web page. Essential for documenting issues, comparing before/after states, and visual analysis.',
useWhenUser: [
'wants to see how a page looks',
'needs visual documentation',
'asks about page layout',
'mentions visual bugs',
'wants before/after comparison',
'needs to document current state'
],
autoTriggerSignals: [
'screenshot',
'capture',
'visual',
'see',
'looks like',
'appearance',
'layout',
'UI',
'interface',
'design'
],
requiredParameters: [{
name: 'sessionId',
type: 'string',
description: 'Active debugging session ID',
aiHint: 'Use the sessionId from inject_debugging response',
examples: ['session_abc123', 'debug_xyz789']
}],
optionalParameters: [{
name: 'selector',
type: 'string',
description: 'CSS selector to focus on specific element',
aiHint: 'Use to capture specific parts of the page',
defaultValue: null
}, {
name: 'fullPage',
type: 'boolean',
description: 'Capture entire page height',
aiHint: 'Set to true for full page screenshots',
defaultValue: false
}],
commonWorkflows: [{
scenario: 'Document current page state before making changes',
steps: [
'1. Ensure debugging session is active',
'2. Call take_screenshot with sessionId',
'3. Store result for comparison',
'4. Make changes or run other tools',
'5. Take another screenshot to compare'
],
expectedOutcome: 'Visual documentation of page state'
}],
aiUsageExamples: [{
userRequest: 'Can you show me how my homepage looks?',
reasoning: 'User wants visual representation of their page',
toolCall: {
tool: 'take_screenshot',
parameters: { sessionId: 'session_abc123', fullPage: true }
},
expectedResult: 'Screenshot of the complete homepage'
}],
troubleshooting: [{
issue: 'Screenshot appears blank',
solution: 'Page may still be loading or session may be invalid',
preventiveMeasures: ['Wait for page load', 'Verify session is active', 'Check if URL is accessible']
}],
integrationTips: {
worksBestWith: ['inject_debugging', 'simulate_user_action'],
shouldNotUseWith: [],
sequenceRecommendations: ['Take screenshots before and after making changes for comparison']
}
});
this.registerTool({
name: 'run_audit',
category: 'performance_analysis',
purpose: 'Comprehensive performance, accessibility, and quality analysis',
aiDescription: 'Performs comprehensive analysis including performance metrics, accessibility compliance, SEO, and best practices. Use whenever user wants to analyze page quality.',
useWhenUser: [
'wants performance analysis',
'asks about page speed',
'needs accessibility check',
'wants SEO analysis',
'asks about page quality',
'mentions optimization',
'wants comprehensive analysis'
],
autoTriggerSignals: [
'audit',
'performance',
'speed',
'accessibility',
'a11y',
'SEO',
'optimize',
'analyze',
'quality',
'lighthouse',
'metrics'
],
requiredParameters: [{
name: 'sessionId',
type: 'string',
description: 'Active debugging session ID',
aiHint: 'Use the sessionId from inject_debugging response',
examples: ['session_abc123']
}],
optionalParameters: [{
name: 'categories',
type: 'array',
description: 'Specific audit categories to run',
aiHint: 'Available: performance, accessibility, best-practices, seo',
defaultValue: ['performance', 'accessibility', 'best-practices', 'seo']
}],
commonWorkflows: [{
scenario: 'Comprehensive page quality analysis',
steps: [
'1. Start debugging session with inject_debugging',
'2. Call run_audit with sessionId',
'3. Analyze results for issues',
'4. Take screenshot for visual context',
'5. Provide recommendations based on audit results'
],
expectedOutcome: 'Detailed analysis with performance scores and recommendations'
}],
aiUsageExamples: [{
userRequest: 'My website feels slow, can you analyze its performance?',
reasoning: 'User wants performance analysis to identify bottlenecks',
toolCall: {
tool: 'run_audit',
parameters: { sessionId: 'session_abc123', categories: ['performance'] }
},
expectedResult: 'Performance metrics and optimization recommendations'
}],
troubleshooting: [{
issue: 'Audit takes too long',
solution: 'Large pages may take time to analyze completely',
preventiveMeasures: ['Use specific categories for faster results', 'Ensure stable network connection']
}],
integrationTips: {
worksBestWith: ['inject_debugging', 'take_screenshot'],
shouldNotUseWith: [],
sequenceRecommendations: ['Run after page has fully loaded for accurate metrics']
}
});
this.registerTool({
name: 'simulate_user_action',
category: 'interaction_testing',
purpose: 'Simulate user interactions like clicks, typing, and navigation',
aiDescription: 'Simulates real user interactions with web pages. Use to test functionality, fill forms, navigate through user flows, or reproduce user-reported issues.',
useWhenUser: [
'wants to test interactions',
'needs to click something',
'wants to fill a form',
'needs to test navigation',
'mentions user flow',
'wants to reproduce an issue'
],
autoTriggerSignals: [
'click',
'type',
'fill',
'submit',
'navigate',
'interact',
'test',
'button',
'form',
'input',
'link'
],
requiredParameters: [{
name: 'sessionId',
type: 'string',
description: 'Active debugging session ID',
aiHint: 'Use the sessionId from inject_debugging response',
examples: ['session_abc123']
}, {
name: 'action',
type: 'string',
description: 'Type of action to perform',
aiHint: 'Available: click, type, scroll, wait, navigate',
examples: ['click', 'type', 'scroll']
}],
optionalParameters: [{
name: 'selector',
type: 'string',
description: 'CSS selector for target element',
aiHint: 'Required for click and type actions',
defaultValue: null
}, {
name: 'text',
type: 'string',
description: 'Text to type',
aiHint: 'Required for type actions',
defaultValue: null
}],
commonWorkflows: [{
scenario: 'Test a login form',
steps: [
'1. Start debugging session',
'2. Take screenshot to see current state',
'3. Type username: simulate_user_action(action: "type", selector: "#username", text: "testuser")',
'4. Type password: simulate_user_action(action: "type", selector: "#password", text: "testpass")',
'5. Click submit: simulate_user_action(action: "click", selector: "#submit")',
'6. Take screenshot to see result'
],
expectedOutcome: 'Login form tested and result documented'
}],
aiUsageExamples: [{
userRequest: 'Can you test if my contact form works?',
reasoning: 'User wants to test form functionality',
toolCall: {
tool: 'simulate_user_action',
parameters: { sessionId: 'session_abc123', action: 'type', selector: '#email', text: 'test@example.com' }
},
expectedResult: 'Email field filled with test data'
}],
troubleshooting: [{
issue: 'Element not found',
solution: 'CSS selector may be incorrect or element may not be visible',
preventiveMeasures: ['Take screenshot first to identify correct selectors', 'Wait for page to load completely']
}],
integrationTips: {
worksBestWith: ['inject_debugging', 'take_screenshot'],
shouldNotUseWith: [],
sequenceRecommendations: ['Take screenshots before and after actions to document changes']
}
});
// Initialize indexes for quick lookup
this.buildIndexes();
this.initialized = true;
console.error('🤖 AI Tool Discovery System initialized with enhanced metadata');
}
registerOrchestratorTools() {
// Register only the 5 orchestrator tools
this.registerTool({
name: 'debug_orchestrator',
category: 'orchestration',
purpose: 'Coordinate comprehensive debugging workflows',
aiDescription: 'THE MAIN DEBUGGING TOOL. Always use this FIRST for any debugging task. It intelligently analyzes the problem and delegates to specialized sub-agents, saving you thousands of tokens. Handles: frontend issues, backend problems, performance bottlenecks, errors, crashes, unexpected behavior. Returns structured findings with root causes and fixes.',
useWhenUser: ['debug', 'inspect', 'analyze', 'check', 'examine', 'investigate', 'troubleshoot', 'figure out', 'find out', 'why', 'broken', 'not working', 'issue', 'problem', 'error', 'bug'],
autoTriggerSignals: ['debug', 'error', 'issue', 'problem', 'broken', 'not working', 'failing'],
requiredParameters: [{
name: 'task',
type: 'object',
description: 'The debugging task to orchestrate',
aiHint: 'Pass the user request as an object with task or description field',
examples: ['{ task: "debug slow page load" }', '{ description: "find memory leaks" }']
}],
optionalParameters: [],
commonWorkflows: [{
scenario: 'User reports issue',
steps: ['1. Analyze task', '2. Delegate to sub-agents', '3. Synthesize results'],
expectedOutcome: 'Comprehensive debugging report with findings and suggestions'
}],
aiUsageExamples: [{
userRequest: 'Debug this slow website',
reasoning: 'User wants to debug performance issues',
toolCall: { name: 'debug_orchestrator', args: { task: { description: 'debug slow website' } } },
expectedResult: 'Full performance analysis with bottlenecks and optimization suggestions'
}],
troubleshooting: [],
integrationTips: {
worksBestWith: ['performance_orchestrator', 'test_orchestrator'],
shouldNotUseWith: [],
sequenceRecommendations: ['Use as the first tool for any debugging task']
}
});
this.registerTool({
name: 'performance_orchestrator',
category: 'orchestration',
purpose: 'Analyze and optimize performance issues',
aiDescription: 'PERFORMANCE EXPERT. Use when users complain about speed, lag, or high resource usage. Automatically profiles the application, identifies bottlenecks, and provides specific optimization strategies. Returns metrics (LCP, FCP, bundle sizes) with actionable improvements. Saves hours of manual profiling.',
useWhenUser: ['slow', 'performance', 'optimize', 'speed', 'bundle', 'memory', 'lag', 'loading', 'sluggish', 'unresponsive', 'takes forever', 'freezing', 'hanging'],
autoTriggerSignals: ['slow', 'performance', 'optimize', 'speed', 'lag', 'memory leak'],
requiredParameters: [{
name: 'task',
type: 'object',
description: 'The performance task to analyze',
aiHint: 'Pass performance-related task details',
examples: ['{ task: "optimize page load time" }', '{ description: "reduce bundle size" }']
}],
optionalParameters: [{
name: 'targets',
type: 'object',
description: 'Performance targets to achieve',
aiHint: 'Specify target metrics',
defaultValue: null
}],
commonWorkflows: [{
scenario: 'Performance optimization',
steps: ['1. Collect metrics', '2. Profile runtime', '3. Generate optimizations'],
expectedOutcome: 'Performance report with actionable optimization suggestions'
}],
aiUsageExamples: [{
userRequest: 'The page is loading slowly',
reasoning: 'Performance issue detected',
toolCall: { name: 'performance_orchestrator', args: { task: { description: 'page loading slowly' } } },
expectedResult: 'Performance metrics, bottlenecks, and optimization plan'
}],
troubleshooting: [],
integrationTips: {
worksBestWith: ['debug_orchestrator', 'architecture_orchestrator'],
shouldNotUseWith: [],
sequenceRecommendations: ['Use after identifying performance as the main issue']
}
});
this.registerTool({
name: 'test_orchestrator',
category: 'orchestration',
purpose: 'Manage testing workflows and coverage',
aiDescription: 'TESTING AUTOMATION. Generates, executes, and analyzes tests automatically. Use for: writing new tests, improving coverage, finding regressions, validating fixes. Can generate entire test suites from debugging sessions. Returns coverage reports and identifies untested code paths.',
useWhenUser: ['test', 'coverage', 'regression', 'unit test', 'integration test', 'e2e', 'write tests', 'generate tests', 'test suite', 'testing', 'validate', 'verify'],
autoTriggerSignals: ['test', 'coverage', 'regression', 'failing tests', 'test suite'],
requiredParameters: [{
name: 'task',
type: 'object',
description: 'The testing task to coordinate',
aiHint: 'Pass testing requirements',
examples: ['{ task: "generate unit tests" }', '{ description: "improve test coverage" }']
}],
optionalParameters: [{
name: 'scope',
type: 'string',
description: 'Test scope: unit, integration, e2e, or all',
aiHint: 'Specify which type of tests',
defaultValue: 'all'
}],
commonWorkflows: [{
scenario: 'Test generation',
steps: ['1. Analyze code', '2. Generate tests', '3. Validate tests'],
expectedOutcome: 'New test files with high coverage'
}],
aiUsageExamples: [{
userRequest: 'Write tests for this module',
reasoning: 'User needs test generation',
toolCall: { name: 'test_orchestrator', args: { task: { task: 'generate tests for module' } } },
expectedResult: 'Generated test suite with coverage report'
}],
troubleshooting: [],
integrationTips: {
worksBestWith: ['fix_orchestrator', 'qa_orchestrator'],
shouldNotUseWith: [],
sequenceRecommendations: ['Use before deployment or after bug fixes']
}
});
this.registerTool({
name: 'architecture_orchestrator',
category: 'orchestration',
purpose: 'Analyze code architecture and quality',
aiDescription: 'CODE ARCHITECTURE ANALYST. Provides deep insights into codebase structure, dependencies, and patterns. Detects: circular dependencies, code smells, anti-patterns, technical debt. Returns visual dependency graphs and specific refactoring suggestions. Essential before major changes.',
useWhenUser: ['architecture', 'structure', 'dependencies', 'patterns', 'code quality', 'refactor', 'tech debt', 'code smell', 'messy code', 'organize', 'restructure', 'coupling'],
autoTriggerSignals: ['architecture', 'dependencies', 'circular', 'coupling', 'code smell'],
requiredParameters: [{
name: 'task',
type: 'object',
description: 'The architecture analysis task',
aiHint: 'Pass architecture concerns',
examples: ['{ task: "analyze dependencies" }', '{ focus: "patterns" }']
}],
optionalParameters: [{
name: 'focus',
type: 'string',
description: 'Focus area: structure, dependencies, patterns, quality, or all',
aiHint: 'Narrow down the analysis',
defaultValue: 'all'
}],
commonWorkflows: [{
scenario: 'Architecture review',
steps: ['1. Analyze structure', '2. Check dependencies', '3. Suggest improvements'],
expectedOutcome: 'Architecture report with refactoring suggestions'
}],
aiUsageExamples: [{
userRequest: 'Review the codebase architecture',
reasoning: 'Architecture analysis requested',
toolCall: { name: 'architecture_orchestrator', args: { task: { task: 'review architecture' } } },
expectedResult: 'Comprehensive architecture analysis with improvement suggestions'
}],
troubleshooting: [],
integrationTips: {
worksBestWith: ['fix_orchestrator', 'qa_orchestrator'],
shouldNotUseWith: [],
sequenceRecommendations: ['Use before major refactoring']
}
});
this.registerTool({
name: 'fix_orchestrator',
category: 'orchestration',
purpose: 'Coordinate automated fixes and code generation',
aiDescription: 'AUTOMATED FIX GENERATOR. Analyzes issues and generates working fixes with validation. Can fix: bugs, performance issues, security vulnerabilities, code quality problems. Each fix includes explanation and can be auto-applied with rollback support. Dramatically faster than manual fixing.',
useWhenUser: ['fix', 'repair', 'patch', 'resolve', 'correct', 'improve code', 'solve', 'remedy', 'fix the bug', 'fix the issue', 'make it work', 'repair this'],
autoTriggerSignals: ['fix', 'bug', 'error', 'broken', 'repair', 'patch'],
requiredParameters: [{
name: 'task',
type: 'object',
description: 'The fix task to execute',
aiHint: 'Pass issue details to fix',
examples: ['{ task: "fix the bug" }', '{ issues: ["null reference", "memory leak"] }']
}],
optionalParameters: [{
name: 'autoApply',
type: 'boolean',
description: 'Automatically apply fixes',
aiHint: 'Whether to apply fixes without review',
defaultValue: false
}],
commonWorkflows: [{
scenario: 'Bug fixing',
steps: ['1. Analyze issues', '2. Generate fixes', '3. Validate fixes'],
expectedOutcome: 'Fixed code with validation'
}],
aiUsageExamples: [{
userRequest: 'Fix the authentication bug',
reasoning: 'Bug fix requested',
toolCall: { name: 'fix_orchestrator', args: { task: { task: 'fix authentication bug' } } },
expectedResult: 'Generated and validated bug fix'
}],
troubleshooting: [],
integrationTips: {
worksBestWith: ['test_orchestrator', 'qa_orchestrator'],
shouldNotUseWith: [],
sequenceRecommendations: ['Use after identifying specific issues']
}
});
this.registerTool({
name: 'qa_orchestrator',
category: 'orchestration',
purpose: 'Comprehensive quality assurance workflows',
aiDescription: 'QUALITY ASSURANCE SUITE. Comprehensive code review covering: security vulnerabilities, compliance issues, best practices, documentation gaps. Returns prioritized findings with severity levels. Use before deployments or merges. Includes OWASP, accessibility, and framework-specific checks.',
useWhenUser: ['review', 'quality', 'security', 'compliance', 'audit', 'check code', 'code review', 'security scan', 'vulnerabilities', 'quality check', 'QA', 'pre-deployment'],
autoTriggerSignals: ['review', 'security', 'vulnerability', 'compliance', 'quality assurance'],
requiredParameters: [{
name: 'task',
type: 'object',
description: 'The QA task to perform',
aiHint: 'Pass QA requirements',
examples: ['{ task: "security review" }', '{ scope: "full" }']
}],
optionalParameters: [{
name: 'scope',
type: 'string',
description: 'QA scope: code-review, security, compliance, documentation, or full',
aiHint: 'Focus area for QA',
defaultValue: 'full'
}],
commonWorkflows: [{
scenario: 'Code review',
steps: ['1. Review code quality', '2. Check security', '3. Validate compliance'],
expectedOutcome: 'QA report with findings and recommendations'
}],
aiUsageExamples: [{
userRequest: 'Review this code for security issues',
reasoning: 'Security review requested',
toolCall: { name: 'qa_orchestrator', args: { task: { task: 'security review' }, scope: 'security' } },
expectedResult: 'Security vulnerabilities report with fixes'
}],
troubleshooting: [],
integrationTips: {
worksBestWith: ['fix_orchestrator', 'test_orchestrator'],
shouldNotUseWith: [],
sequenceRecommendations: ['Use before releases or after major changes']
}
});
// Add new verification-focused orchestrators
this.registerTool({
name: 'hybrid_orchestrator',
category: 'orchestration',
purpose: 'Direct control mode with verification capabilities',
aiDescription: 'STRATEGIC CONTROL MODE. Provides direct access to key verification tools while delegating complex workflows to sub-agents. Use this when you need to: verify sub-agent claims, get ground truth about system state, perform targeted debugging with specific tools, maintain control over the debugging process. Returns both direct tool results AND sub-agent summaries for comparison.',
useWhenUser: ['verify', 'check', 'confirm', 'validate', 'ensure', 'actually', 'really', 'truly', 'ground truth', 'direct access', 'manual check'],
autoTriggerSignals: ['verify', 'check', 'confirm', 'validate', 'ensure', 'actually', 'really'],
requiredParameters: [{
name: 'task',
type: 'object',
description: 'What to verify or investigate',
aiHint: 'Pass verification task with specific concerns',
examples: ['{ task: "verify the page actually loads" }', '{ task: "check if errors really exist" }']
}],
optionalParameters: [{
name: 'verificationTools',
type: 'array',
description: 'Specific tools to use for verification',
aiHint: 'List tools like ["take_screenshot", "get_console_logs"]',
defaultValue: []
}, {
name: 'compareWithSubAgent',
type: 'boolean',
description: 'Whether to also run sub-agent and compare results',
aiHint: 'Set to false to skip sub-agent comparison',
defaultValue: true
}],
commonWorkflows: [{
scenario: 'Verify sub-agent claims',
steps: ['1. Execute verification tools', '2. Run sub-agent', '3. Compare results', '4. Report discrepancies'],
expectedOutcome: 'Evidence-based verification with confidence score'
}],
aiUsageExamples: [{
userRequest: 'Verify the page is actually working',
reasoning: 'User wants direct verification, not just sub-agent claims',
toolCall: { name: 'hybrid_orchestrator', args: { task: { task: 'verify page is working' } } },
expectedResult: 'Direct evidence (screenshot, console logs) plus sub-agent analysis'
}],
troubleshooting: [],
integrationTips: {
worksBestWith: ['verification_first_orchestrator'],
shouldNotUseWith: [],
sequenceRecommendations: ['Use when sub-agent results seem unreliable']
}
});
this.registerTool({
name: 'conversational_orchestrator',
category: 'orchestration',
purpose: 'Enable dialog between agents for complex problems',
aiDescription: 'COLLABORATIVE DIALOG MODE. Enables back-and-forth conversation with sub-agents for complex problem solving. Use when: the problem is unclear and needs exploration, you need to brainstorm solutions, sub-agents need more context, you want to verify understanding before acting. Returns conversation transcript with collaborative insights.',
useWhenUser: ['discuss', 'explore', 'brainstorm', 'understand', 'clarify', 'dialog', 'conversation', 'talk through', 'figure out together', 'collaborate'],
autoTriggerSignals: [],
requiredParameters: [{
name: 'task',
type: 'object',
description: 'Problem to explore through dialog',
aiHint: 'Describe the problem to discuss',
examples: ['{ task: "understand why login fails intermittently" }', '{ task: "brainstorm performance optimizations" }']
}],
optionalParameters: [{
name: 'maxTurns',
type: 'number',
description: 'Maximum conversation turns',
aiHint: 'Limit conversation length',
defaultValue: 10
}, {
name: 'agents',
type: 'array',
description: 'Specific agents to involve',
aiHint: 'List agent names to include',
defaultValue: []
}],
commonWorkflows: [{
scenario: 'Complex problem solving',
steps: ['1. Initiate dialog', '2. Agents ask questions', '3. Provide clarifications', '4. Reach consensus'],
expectedOutcome: 'Collaborative solution with agent consensus'
}],
aiUsageExamples: [{
userRequest: 'Help me understand why this bug only happens sometimes',
reasoning: 'Complex intermittent issue needs exploration',
toolCall: { name: 'conversational_orchestrator', args: { task: { task: 'understand intermittent bug' } } },
expectedResult: 'Dialog transcript with insights from multiple agents'
}],
troubleshooting: [],
integrationTips: {
worksBestWith: ['debug_orchestrator'],
shouldNotUseWith: [],
sequenceRecommendations: ['Use for complex, unclear problems']
}
});
this.registerTool({
name: 'verification_first_orchestrator',
category: 'orchestration',
purpose: 'Always verify before trusting claims',
aiDescription: 'TRUST BUT VERIFY MODE. Always gathers evidence before accepting claims. Use when: you suspect false positives from sub-agents, you need high confidence in results, the stakes are high (production issues), previous debugging attempts failed. Returns evidence-based findings with confidence scores.',
useWhenUser: ['verify first', 'evidence', 'proof', 'high confidence', 'production issue', 'critical', 'must be sure', 'double check', 'triple check'],
autoTriggerSignals: [],
requiredParameters: [{
name: 'task',
type: 'object',
description: 'What to verify with evidence',
aiHint: 'Describe what needs verification',
examples: ['{ task: "verify the app is actually working" }', '{ task: "confirm there are no errors" }']
}],
optionalParameters: [{
name: 'url',
type: 'string',
description: 'URL to verify',
aiHint: 'Target URL for verification',
defaultValue: null
}, {
name: 'evidenceTypes',
type: 'array',
description: 'Types of evidence to gather',
aiHint: 'Choose from: visual, console, dom, network, performance, all',
defaultValue: ['all']
}],
commonWorkflows: [{
scenario: 'High-stakes debugging',
steps: ['1. Gather evidence', '2. Analyze actual state', '3. Delegate with context', '4. Verify claims'],
expectedOutcome: 'Evidence-based report with confidence scores'
}],
aiUsageExamples: [{
userRequest: 'Make absolutely sure there are no errors in production',
reasoning: 'High-stakes verification needed',
toolCall: { name: 'verification_first_orchestrator', args: { task: { task: 'verify no errors in production' }, url: 'https://prod.example.com' } },
expectedResult: 'Evidence-based verification with screenshots, logs, and confidence scores'
}],
troubleshooting: [],
integrationTips: {
worksBestWith: ['hybrid_orchestrator'],
shouldNotUseWith: [],
sequenceRecommendations: ['Use for critical issues or when confidence is low']
}
});
// Initialize indexes for quick lookup
this.buildIndexes();
this.initialized = true;
console.error('🎭 AI Tool Discovery System initialized in hierarchical mode with 9 orchestrators (including verification modes)');
}
registerTool(metadata) {
this.toolMetadata.set(metadata.name, metadata);
// Add to category index
if (!this.categoryIndex.has(metadata.category)) {
this.categoryIndex.set(metadata.category, []);
}
this.categoryIndex.get(metadata.category).push(metadata.name);
// Add to signal index
for (const signal of metadata.autoTriggerSignals) {
if (!this.signalIndex.has(signal.toLowerCase())) {
this.signalIndex.set(signal.toLowerCase(), []);
}
this.signalIndex.get(signal.toLowerCase()).push(metadata.name);
}
}
buildIndexes() {
// Build search indexes for fast AI discovery
console.error('🔍 Building AI discovery indexes...');
}
/**
* Get comprehensive tool information for AI models
*/
getToolMetadata(toolName) {
return this.toolMetadata.get(toolName) || null;
}
/**
* Get all tools with AI-friendly descriptions
*/
getAllToolsForAI() {
return Array.from(this.toolMetadata.entries()).map(([name, metadata]) => ({
name,
metadata
}));
}
/**
* Suggest tools based on user input or context
*/
suggestToolsForInput(userInput) {
const suggestions = [];
const inputLower = userInput.toLowerCase();
// Check for direct signal matches
for (const [signal, toolNames] of this.signalIndex) {
if (inputLower.includes(signal)) {
for (const toolName of toolNames) {
const metadata = this.toolMetadata.get(toolName);
// Calculate confidence based on signal strength and context
let confidence = 0.7; // Base confidence for signal match
// Boost confidence for multiple signal matches
const matchingSignals = metadata.autoTriggerSignals.filter(s => inputLower.includes(s.toLowerCase()));
confidence += matchingSignals.length * 0.1;
// Boost confidence for use case matches
const matchingUseCases = metadata.useWhenUser.filter(useCase => inputLower.includes(useCase.toLowerCase().split(' ').slice(0, 2).join(' ')));
confidence += matchingUseCases.length * 0.15;
confidence = Math.min(confidence, 1.0); // Cap at 100%
suggestions.push({
toolName,
confidence,
reasoning: `Detected signals: ${matchingSignals.join(', ')}`,
suggestedParameters: this.generateParameterSuggestions(metadata, userInput)
});
}
}
}
// Sort by confidence and return top suggestions
return suggestions
.sort((a, b) => b.confidence - a.confidence)
.slice(0, 5); // Top 5 suggestions
}
generateParameterSuggestions(metadata, userInput) {
const suggestions = {};
// Extract URLs from user input
const urlMatch = userInput.match(/https?:\/\/[^\s]+/);
if (urlMatch) {
suggestions.url = urlMatch[0];
}
// Extract selectors (basic CSS selector detection)
const selectorMatch = userInput.match(/[#.][a-zA-Z][a-zA-Z0-9-_]*/);
if (selectorMatch) {
suggestions.selector = selectorMatch[0];
}
return suggestions;
}
/**
* Generate AI-friendly tool documentation
*/
generateAIDocumentation() {
const docs = ['# AI-Debug Tools - Complete AI Reference\n'];
docs.push('This documentation is optimized for AI models to understand and use debugging tools effectively.\n');
// Group by category
const categories = Array.from(this.categoryIndex.keys());
for (const category of categories) {
docs.push(`## ${category.replace('_', ' ').toUpperCase()}\n`);
const toolsInCategory = this.categoryIndex.get(category);
for (const toolName of toolsInCategory) {
const metadata = this.toolMetadata.get(toolName);
docs.push(this.formatToolForAI(metadata));
}
}
return docs.join('\n');
}
formatToolForAI(metadata) {
return `
### ${metadata.name}
**Purpose**: ${metadata.purpose}
**AI Description**: ${metadata.aiDescription}
**Use When User**: ${metadata.useWhenUser.join(', ')}
**Auto-Trigger Signals**: ${metadata.autoTriggerSignals.join(', ')}
**Required Parameters**:
${metadata.requiredParameters.map(p => `- ${p.name} (${p.type}): ${p.description}\n AI Hint: ${p.aiHint}\n Examples: ${p.examples.join(', ')}`).join('\n')}
**Example Usage**:
${metadata.aiUsageExamples.map(ex => `User: "${ex.userRequest}"\nReasoning: ${ex.reasoning}\nTool Call: ${JSON.stringify(ex.toolCall, null, 2)}`).join('\n\n')}
**Integration Tips**: ${metadata.integrationTips.sequenceRecommendations.join(', ')}
---
`;
}
/**
* Determine if sub-agent delegation should be automatic
*/
shouldAutoDelegate(userInput) {
const inputLower = userInput.toLowerCase();
// Check for complex debugging requests that benefit from sub-agents
const complexityIndicators = [
'comprehensive', 'full analysis', 'complete audit', 'thorough',
'debug everything', 'analyze all', 'check everything'
];
const isComplex = complexityIndicators.some(indicator => inputLower.includes(indicator));
if (isComplex) {
return {
delegate: true,
agentType: 'debug-discovery-agent',
reasoning: 'Complex analysis request benefits from specialized sub-agent delegation'
};
}
// Check for performance-specific requests
if (inputLower.includes('performance') || inputLower.includes('slow') || inputLower.includes('optimize')) {
return {
delegate: true,
agentType: 'performance-analysis-agent',
reasoning: 'Performance analysis benefits from specialized performance agent'
};
}
// Check for accessibility requests
if (inputLower.includes('accessibility') || inputLower.includes('a11y') || inputLower.includes('wcag')) {
return {
delegate: true,
agentType: 'accessibility-audit-agent',
reasoning: 'Accessibility analysis requires specialized expertise'
};
}
return { delegate: false };
}
/**
* Get workflow suggestions for complex scenarios
*/
suggestWorkflow(scenario) {
const workflows = [];
// Check for auto-delegation opportunity
const delegationCheck = this.shouldAutoDelegate(scenario);
// Common debugging workflows
if (scenario.toLowerCase().includes('debug') || scenario.toLowerCase().includes('analyze')) {
workflows.push({
toolSequence: delegationCheck.delegate ? ['delegate_to_debug_agent'] : ['inject_debugging', 'take_screenshot', 'run_audit'],
reasoning: delegationCheck.delegate ? `Auto-delegating to ${delegationCheck.agentType}: ${delegationCheck.reasoning}` : 'Standard debugging workflow: establish session, document current state, analyze quality',
expectedOutcome: delegationCheck.delegate ? 'Specialized agent handles comprehensive analysis with context preservation' : 'Comprehensive understanding of page state and issues',
autoDelegate: delegationCheck.delegate ? {
shouldDelegate: true,
agentType: delegationCheck.agentType,
reasoning: delegationCheck.reasoning
} : undefined
});
}
if (scenario.toLowerCase().includes('test') || scenario.toLowerCase().includes('interaction')) {
workflows.push({
toolSequence: ['inject_debugging', 'take_screenshot', 'simulate_user_action', 'take_screenshot'],
reasoning: 'Interaction testing workflow: establish session, document before state, test interaction, document after state',
expectedOutcome: 'Visual proof of interaction testing results'
});
}
return workflows;
}
}
//# sourceMappingURL=ai-tool-discovery.js.map