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
263 lines âĸ 11.9 kB
JavaScript
/**
* Sub-Agent Auto-Delegation Decorator
*
* Provides decorators and utilities to automatically wrap handler methods
* with intelligent sub-agent delegation and elegant fallback.
*/
import { smartExecute, areSubAgentsAvailable } from './auto-delegation-wrapper.js';
import { UserFriendlyLogger } from './user-friendly-logger.js';
import { getErrorMessage } from './error-helper.js';
import { ContextDelegationTracker } from './token-savings-tracker.js';
const logger = new UserFriendlyLogger('SubAgentDelegate');
/**
* Determine which agent type should handle this task
*/
function determineAgentType(methodName, taskDescription, args) {
const task = taskDescription.toLowerCase();
const method = methodName.toLowerCase();
// Framework-specific routing
if (args.framework || task.includes('flutter') || task.includes('nextjs') || task.includes('phoenix')) {
return 'framework-specialist-agent';
}
// Performance-related tasks
if (method.includes('performance') || task.includes('performance') || task.includes('audit') || method.includes('audit')) {
return 'performance-analysis-agent';
}
// Accessibility tasks
if (method.includes('accessibility') || task.includes('accessibility') || task.includes('a11y') || task.includes('wcag')) {
return 'accessibility-audit-agent';
}
// Error and debugging tasks
if (method.includes('error') || task.includes('error') || method.includes('debug') || task.includes('console')) {
return 'error-investigation-agent';
}
// Testing and validation
if (method.includes('test') || task.includes('test') || method.includes('validation') || task.includes('quality')) {
return 'validation-testing-agent';
}
// Data extraction tasks
if (method.includes('data') || task.includes('data') || method.includes('console') || method.includes('network')) {
return 'data-extraction-agent';
}
// Testing infrastructure
if (method.includes('tdd') || task.includes('tdd') || method.includes('mock') || task.includes('infrastructure')) {
return 'testing-infrastructure-agent';
}
// Default to discovery agent for initial setup
return 'debug-discovery-agent';
}
/**
* Determine complexity level of the task
*/
function determineComplexityLevel(args, config) {
let complexityScore = 0;
// Priority indicates complexity
if (config.priority === 'high')
complexityScore += 2;
if (config.priority === 'medium')
complexityScore += 1;
// Multiple frameworks or tools indicate complexity
if (args.framework && args.framework !== 'auto')
complexityScore += 1;
if (args.includeSubsystems || args.deepAnalysis)
complexityScore += 1;
// Multi-step tasks are more complex
if (config.taskTemplate.includes('and') || config.taskTemplate.includes('then'))
complexityScore += 1;
// AI analysis adds complexity
if (args.aiAnalysis || config.contextHint?.includes('ai'))
complexityScore += 2;
// Revolutionary features
if (args.revolutionaryFeatures || config.taskTemplate.includes('revolutionary'))
complexityScore += 3;
if (complexityScore >= 5)
return 'revolutionary';
if (complexityScore >= 3)
return 'complex';
if (complexityScore >= 1)
return 'moderate';
return 'simple';
}
/**
* Method decorator for automatic sub-agent delegation
*/
export function withSubAgentDelegation(config) {
return function (target, propertyName, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args) {
const methodArgs = args[0] || {};
const sessions = args[1] || new Map();
// Create task description from template
const taskDescription = interpolateTemplate(config.taskTemplate, methodArgs);
// Check if sub-agents are available
const subAgentsAvailable = await areSubAgentsAvailable();
if (subAgentsAvailable) {
logger[config.logLevel](`đ¤ Attempting sub-agent delegation for ${propertyName}...`);
// Start context delegation tracking
const tracker = ContextDelegationTracker.getInstance();
const sessionId = methodArgs.sessionId || `session_${Date.now()}`;
const agentType = determineAgentType(propertyName, taskDescription, methodArgs);
const complexityLevel = determineComplexityLevel(methodArgs, config);
const trackingId = tracker.startDelegation(sessionId, agentType, taskDescription, complexityLevel, methodArgs.framework);
const delegationStartTime = Date.now();
try {
const delegationResult = await smartExecute(taskDescription, {
...methodArgs,
tool: propertyName,
priority: config.priority,
contextHint: config.contextHint,
originalArgs: args,
trackingId
});
if (delegationResult.success && delegationResult.usedSubAgent) {
logger.success(`â
Sub-agent ${delegationResult.agentType} handled ${propertyName} (saved ${delegationResult.contextSavedTokens} tokens)`);
return delegationResult.result;
}
else {
logger.info(`đ Sub-agent delegation failed: ${delegationResult.fallbackReason}, using direct execution`);
}
}
catch (error) {
logger.warn(`â ī¸ Sub-agent delegation error for ${propertyName}: ${getErrorMessage(error)}`);
if (config.fallbackStrategy === 'throw') {
throw error;
}
else if (config.fallbackStrategy === 'return_null') {
return null;
}
// fallbackStrategy === 'continue' falls through to original method
}
}
else {
logger.debug(`âšī¸ Sub-agents not available for ${propertyName}, using direct execution`);
}
// ELEGANT FALLBACK: Execute original method
logger.debug(`đ§ Executing ${propertyName} directly...`);
return originalMethod.apply(this, args);
};
return descriptor;
};
}
/**
* Interpolate template strings with method arguments
*/
function interpolateTemplate(template, args) {
return template.replace(/\{(\w+)\}/g, (match, key) => {
return args[key] !== undefined ? String(args[key]) : match;
});
}
/**
* Predefined delegation configurations for common debugging tasks
*/
export const DelegationConfigs = {
PERFORMANCE_ANALYSIS: {
taskTemplate: 'Analyze performance of {url} application. Profile Core Web Vitals, identify bottlenecks, and provide optimization recommendations.',
priority: 'high',
fallbackStrategy: 'continue',
logLevel: 'info',
contextHint: 'performance-optimization'
},
ACCESSIBILITY_AUDIT: {
taskTemplate: 'Perform comprehensive accessibility audit of {url}. Check WCAG compliance, keyboard navigation, screen reader compatibility, and color contrast.',
priority: 'medium',
fallbackStrategy: 'continue',
logLevel: 'info',
contextHint: 'accessibility-compliance'
},
ERROR_INVESTIGATION: {
taskTemplate: 'Investigate and analyze errors in {url} application. Collect console errors, analyze stack traces, and identify root causes.',
priority: 'high',
fallbackStrategy: 'continue',
logLevel: 'info',
contextHint: 'error-debugging'
},
USER_INTERACTION: {
taskTemplate: 'Simulate user interaction: {action} on {selector} in {url}. Monitor results and capture any errors or issues.',
priority: 'medium',
fallbackStrategy: 'continue',
logLevel: 'debug',
contextHint: 'user-testing'
},
VALIDATION_TESTING: {
taskTemplate: 'Validate functionality and perform regression testing for {url}. Verify user flows, check for visual regressions, and ensure quality gates.',
priority: 'high',
fallbackStrategy: 'continue',
logLevel: 'info',
contextHint: 'quality-assurance'
},
DEBUG_DISCOVERY: {
taskTemplate: 'Initialize debugging session for {url} with framework {framework}. Setup browser, inject debugging capabilities, and perform initial assessment.',
priority: 'high',
fallbackStrategy: 'continue',
logLevel: 'info',
contextHint: 'initial-setup'
}
};
/**
* Utility function to wrap any function with sub-agent delegation
*/
export function wrapWithSubAgentDelegation(fn, config, methodName = fn.name) {
return (async function (...args) {
const methodArgs = args[0] || {};
// Create task description from template
const taskDescription = interpolateTemplate(config.taskTemplate, methodArgs);
// Check if sub-agents are available
const subAgentsAvailable = await areSubAgentsAvailable();
if (subAgentsAvailable) {
logger[config.logLevel](`đ¤ Attempting sub-agent delegation for ${methodName}...`);
try {
const delegationResult = await smartExecute(taskDescription, {
...methodArgs,
tool: methodName,
priority: config.priority,
contextHint: config.contextHint,
originalArgs: args
});
if (delegationResult.success && delegationResult.usedSubAgent) {
logger.success(`â
Sub-agent ${delegationResult.agentType} handled ${methodName} (saved ${delegationResult.contextSavedTokens} tokens)`);
return delegationResult.result;
}
else {
logger.info(`đ Sub-agent delegation failed: ${delegationResult.fallbackReason}, using direct execution`);
}
}
catch (error) {
logger.warn(`â ī¸ Sub-agent delegation error for ${methodName}: ${getErrorMessage(error)}`);
if (config.fallbackStrategy === 'throw') {
throw error;
}
else if (config.fallbackStrategy === 'return_null') {
return null;
}
}
}
else {
logger.debug(`âšī¸ Sub-agents not available for ${methodName}, using direct execution`);
}
// ELEGANT FALLBACK: Execute original function
logger.debug(`đ§ Executing ${methodName} directly...`);
return fn(...args);
});
}
/**
* Convenience function to create a delegation-enabled handler method
*/
export function createDelegatedMethod(originalMethod, delegationConfig, methodName) {
return wrapWithSubAgentDelegation(originalMethod, delegationConfig, methodName);
}
/**
* Batch wrap multiple methods with sub-agent delegation
*/
export function batchWrapMethods(target, methodConfigs) {
Object.entries(methodConfigs).forEach(([methodName, config]) => {
const originalMethod = target[methodName];
if (typeof originalMethod === 'function') {
target[methodName] = wrapWithSubAgentDelegation(originalMethod.bind(target), config, methodName);
logger.info(`đ§ Wrapped ${methodName} with sub-agent delegation`);
}
else {
logger.warn(`â ī¸ Method ${methodName} not found on target object`);
}
});
}
//# sourceMappingURL=sub-agent-auto-delegate.js.map