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
326 lines • 12.1 kB
JavaScript
/**
* Context-Aware Agent Wrapper
* Ensures every agent is context-sharing aware and emphasizes the critical importance
*/
import { EventEmitter } from 'events';
/**
* Context-Aware Agent Wrapper
* Wraps any agent to make it context-sharing aware
*/
export class ContextAwareAgentWrapper extends EventEmitter {
contextManager;
config;
behavior;
syncInterval = null;
contextBuffer = [];
constructor(contextManager, config, behavior) {
super();
this.contextManager = contextManager;
this.config = config;
this.behavior = {
shareDiscoveries: true,
shareDecisions: true,
shareProgress: true,
shareErrors: true,
requestMissingContext: true,
acknowledgeContextReceived: true,
contextSyncInterval: 30000, // 30 seconds default
...behavior
};
this.initialize();
}
/**
* Initialize context-aware behavior
*/
async initialize() {
// Register with context manager
this.contextManager.registerAgent(this.config.agentId, this.config.agentType, {
contextDependencies: this.config.contextDependencies,
contextContributions: this.config.contextContributions,
sharingImportanceScore: this.config.sharingImportanceScore
});
// Emphasize context sharing importance
const importance = this.contextManager.emphasizeContextSharingImportance(this.config.agentId, 'agent_initialization');
// Emit importance awareness
this.emit('context_importance_emphasized', {
agentId: this.config.agentId,
importance: importance.importance,
reasoning: importance.reasoning,
recommendations: importance.recommendations
});
// Setup context synchronization
this.setupContextSynchronization();
// Setup event handlers
this.setupContextEventHandlers();
// Start periodic sync if configured
if (this.behavior.contextSyncInterval > 0) {
this.startPeriodicSync();
}
}
/**
* Share a discovery with relevant agents
*/
async shareDiscovery(discovery) {
if (!this.behavior.shareDiscoveries)
return '';
const contextId = await this.contextManager.shareContext({
source: this.getSourceType(),
sourceId: this.config.agentId,
type: 'discovery',
priority: discovery.priority || 'medium',
content: {
title: discovery.title,
description: discovery.description,
data: discovery.data,
impact: discovery.impact,
recommendations: discovery.recommendations
},
contextual: {
sessionId: discovery.sessionId,
framework: discovery.framework,
phase: 'discovery',
toolsInvolved: discovery.toolsInvolved
},
sharing: {
shareWithPrimary: this.config.agentType !== 'primary',
shareWithSubAgents: this.config.agentType === 'primary',
shareWithBackground: true,
criticalForDecisionMaking: discovery.priority === 'critical',
requiresAcknowledgment: discovery.priority === 'critical'
}
});
this.emit('discovery_shared', { discovery, contextId });
return contextId;
}
/**
* Share a decision with relevant agents
*/
async shareDecision(decision) {
if (!this.behavior.shareDecisions)
return '';
const contextId = await this.contextManager.shareContext({
source: this.getSourceType(),
sourceId: this.config.agentId,
type: 'decision',
priority: decision.priority || 'high', // Decisions are typically high priority
content: {
title: decision.title,
description: decision.description,
data: {
rationale: decision.rationale,
alternatives: decision.alternatives
},
impact: decision.impact
},
contextual: {
sessionId: decision.sessionId,
phase: 'decision',
toolsInvolved: decision.toolsInvolved
},
sharing: {
shareWithPrimary: this.config.agentType !== 'primary',
shareWithSubAgents: this.config.agentType === 'primary',
shareWithBackground: false, // Decisions typically don't need background sharing
criticalForDecisionMaking: true,
requiresAcknowledgment: decision.priority === 'critical'
}
});
this.emit('decision_shared', { decision, contextId });
return contextId;
}
/**
* Share progress update
*/
async shareProgress(progress) {
if (!this.behavior.shareProgress)
return '';
const contextId = await this.contextManager.shareContext({
source: this.getSourceType(),
sourceId: this.config.agentId,
type: 'progress',
priority: 'medium',
content: {
title: progress.title,
description: progress.description,
data: {
completionPercentage: progress.completionPercentage,
nextSteps: progress.nextSteps,
blockers: progress.blockers
}
},
contextual: {
sessionId: progress.sessionId,
phase: 'progress'
},
sharing: {
shareWithPrimary: this.config.agentType !== 'primary',
shareWithSubAgents: this.config.agentType === 'primary',
shareWithBackground: false,
criticalForDecisionMaking: !!(progress.blockers && progress.blockers.length > 0),
requiresAcknowledgment: false
}
});
this.emit('progress_shared', { progress, contextId });
return contextId;
}
/**
* Share error or problem
*/
async shareError(error) {
if (!this.behavior.shareErrors)
return '';
const contextId = await this.contextManager.shareContext({
source: this.getSourceType(),
sourceId: this.config.agentId,
type: 'error',
priority: error.severity,
content: {
title: error.title,
description: error.description,
data: {
errorDetails: error.errorDetails,
recoveryAttempts: error.recoveryAttempts
}
},
contextual: {
sessionId: error.sessionId,
phase: 'error_recovery',
toolsInvolved: error.toolsInvolved
},
sharing: {
shareWithPrimary: true, // Always share errors with primary
shareWithSubAgents: true, // Other agents might encounter similar issues
shareWithBackground: true, // Background agents should monitor errors
criticalForDecisionMaking: error.severity === 'critical',
requiresAcknowledgment: error.severity === 'critical'
}
});
this.emit('error_shared', { error, contextId });
return contextId;
}
/**
* Request specific context from other agents
*/
async requestContext(contextType, criteria) {
if (!this.behavior.requestMissingContext)
return [];
const contexts = await this.contextManager.requestContext(this.config.agentId, contextType, criteria);
this.emit('context_requested', { contextType, criteria, receivedCount: contexts.length });
return contexts;
}
/**
* Get agent's current context awareness status
*/
getContextAwarenessStatus() {
const importance = this.contextManager.emphasizeContextSharingImportance(this.config.agentId, 'status_check');
const awareness = this.contextManager.getAgentAwareness(this.config.agentId);
return {
agentId: this.config.agentId,
importance,
sharingMetrics: {
contextsShared: 0, // This would need to be tracked
contextsReceived: this.contextBuffer.length,
lastSyncTime: awareness?.lastContextSync || new Date()
},
buffer: [...this.contextBuffer]
};
}
/**
* Force context synchronization
*/
async forceContextSync() {
// Request all critical context types that this agent depends on
for (const contextType of this.config.contextDependencies) {
const contexts = await this.requestContext(contextType, {
maxAge: 300000, // 5 minutes
requiredFor: 'forced_sync'
});
// Add to buffer
this.contextBuffer.push(...contexts);
}
this.emit('context_sync_completed', {
agentId: this.config.agentId,
syncedContextCount: this.contextBuffer.length
});
}
/**
* Setup context synchronization
*/
setupContextSynchronization() {
// Listen for context shared by other agents
this.contextManager.on('agent_context_sync', ({ agentId, context, syncEvent }) => {
if (agentId !== this.config.agentId)
return;
// Add to buffer
this.contextBuffer.push(context);
// Acknowledge if required
if (context.sharing.requiresAcknowledgment && this.behavior.acknowledgeContextReceived) {
this.emit('context_acknowledgment', {
contextId: context.id,
acknowledgedBy: this.config.agentId
});
}
this.emit('context_received', { context, syncEvent });
});
}
/**
* Setup context event handlers
*/
setupContextEventHandlers() {
// Handle context importance emphasis
this.contextManager.on('agent_context_stale', ({ agentId, awareness, timeSinceSync }) => {
if (agentId === this.config.agentId) {
this.emit('context_sync_warning', {
message: `Context sharing is critical! Last sync was ${Math.round(timeSinceSync / 60000)} minutes ago`,
timeSinceSync,
awareness
});
// Automatically trigger sync if too stale
if (timeSinceSync > 600000) { // 10 minutes
this.forceContextSync();
}
}
});
}
/**
* Start periodic context synchronization
*/
startPeriodicSync() {
this.syncInterval = setInterval(async () => {
try {
await this.forceContextSync();
}
catch (error) {
this.emit('sync_error', { error, agentId: this.config.agentId });
}
}, this.behavior.contextSyncInterval);
}
/**
* Stop periodic synchronization
*/
stopPeriodicSync() {
if (this.syncInterval) {
clearInterval(this.syncInterval);
this.syncInterval = null;
}
}
/**
* Get source type for context sharing
*/
getSourceType() {
switch (this.config.agentType) {
case 'primary': return 'primary_agent';
case 'sub': return 'sub_agent';
case 'background': return 'background_agent';
default: return 'sub_agent';
}
}
/**
* Cleanup resources
*/
dispose() {
this.stopPeriodicSync();
this.removeAllListeners();
}
}
//# sourceMappingURL=context-aware-agent-wrapper.js.map