/** * Agent Delegator * * Intelligent agent delegation system that uses complexity analysis to determine * optimal task distribution strategies and conflict resolution. * * Integrates with TaskSkillRouter for keyword-based preprocessing. * * @since 2026-01-07 */ import { ComplexityScore } from "./complexity-analyzer.js"; import { XrayStateManager } from "../state/state-manager.js"; import { xrayConfigLoader } from "../core/config-loader.js"; import { type AggregatedMetrics, type MetricsExport } from "./metrics-aggregator.js"; export interface AgentCapability { name: string; capabilities: string[]; expertise?: string[]; specialties?: string[]; status: "active" | "inactive"; [key: string]: string | string[] | boolean | number | undefined; } export interface DelegationContext { workingDirectory?: string; availableTools?: string[]; isDelegated?: boolean; files?: string[]; dependencies?: string[]; changeVolume?: number; riskLevel?: string; [key: string]: unknown; } export interface DelegationResponse { agent: string; operation: string; description: string; capabilities: string[]; mode: string; status: string; timestamp: string; message: string; } export interface DelegationRequest { operation: string; description: string; context?: DelegationContext; sessionId?: string; } export interface DelegationAnalysis { strategy: "single-agent" | "multi-agent" | "orchestrator-led"; agents: string[]; agentDetails: Array<{ name: string; confidence: number; role: string; }>; complexity: ComplexityScore; conflictResolution: "majority_vote" | "expert_priority" | "consensus"; estimatedDuration: number; metrics?: Record; } export interface DelegationResult { success: boolean; results: Array<{ agent: string; output: DelegationResponse; executionTime: number; }>; totalTime: number; errors?: string[] | undefined; agents?: string[]; } export interface PerformanceMetrics { totalDelegations: number; successfulDelegations: number; failedDelegations: number; averageExecutionTime: number; averageResponseTime: number; averageComplexity: number; averageDuration: number; strategyUsage: Record; agentUtilization: Record; } export interface DelegationMetrics extends PerformanceMetrics { recentDelegations: Array<{ timestamp: number; operation: string; strategy: string; success: boolean; totalTime: number; }>; } /** * AgentDelegator class for intelligent task delegation */ export declare class AgentDelegator { private complexityAnalyzer; private stateManager; private configLoader; private kernel; private agentMetrics; /** Minimum confidence for a learned mapping to override hardcoded routing. */ private static readonly MAPPING_CONFIDENCE_THRESHOLD; /** Parsed routing file. Identity is path, mtime, size, and a hash of the bytes. */ private routingMappingsCache; constructor(stateManager: XrayStateManager, configLoader: typeof xrayConfigLoader); /** * Load routing-mappings.json. First file among .xray/, xray/, then cwd. * Same path, mtime, and size still re-reads when the bytes change. */ private loadRoutingMappings; /** * Match a task description against learned keyword mappings. * Returns the best matching mapping if any keyword hits above threshold. */ private matchRoutingMappings; getAvailableAgents(): AgentCapability[]; /** * Pre-process a task description using TaskSkillRouter * This extracts operation type and context from natural language descriptions * before running complexity analysis */ preprocessTaskDescription(description: string, options?: { sessionId?: string; taskId?: string; complexity?: number; }): { operation: string; context: Record; suggestedAgent: string; suggestedSkill: string; confidence: number; }; analyzeDelegation(request: DelegationRequest): Promise; private determineAgents; private mapOperationToType; /** * Record analysis results for learning system */ private recordAnalysisForLearning; private determineConflictResolution; /** * Resolve the project directory for delegated agents * Ensures working directory is set correctly (src/ vs dist/ vs project root) */ private resolveProjectDirectory; /** * Allowlist of valid agent names for dynamic imports * Prevents path traversal and unauthorized agent loading */ private static readonly ALLOWED_AGENTS; /** * Validate agent name for security * @throws Error if agent name is invalid or not allowed */ private validateAgentName; /** * Create a properly configured agent with full tool access and working directory context */ private createProperlyConfiguredAgent; /** * Clear agent-stub creation and deprecated features * Remove this method if it exists in the future version */ private clearDeprecatedStubAgent; executeDelegation(analysis: DelegationAnalysis, request: DelegationRequest): Promise; getPerformanceMetrics(): PerformanceMetrics; getDelegationMetrics(): DelegationMetrics; aggregateAllMetrics(): { delegation: AggregatedMetrics; orchestration: AggregatedMetrics; }; getMetricsByAgent(type?: "delegation" | "orchestration"): Record; getMetricsByComplexity(type?: "delegation" | "orchestration"): Record; getMetricsByTimePeriod(type?: "delegation" | "orchestration"): Record; rotateMetricsEntries(maxEntries?: number): { delegation: number; orchestration: number; }; cleanupMetricsOlderThan(olderThanMs: number): { delegation: number; orchestration: number; }; exportMetricsData(format?: "json" | "csv" | "summary"): MetricsExport; updateAgentCapability(agentName: string, capabilities: Partial): void; } export declare function createAgentDelegator(stateManager: XrayStateManager, configLoader: typeof xrayConfigLoader): AgentDelegator;