/** * Unified Delegation API * * Single entry point for all delegation operations. * Provides easy integration for 3rd party AI coding tools. */ import { DelegationAPIConfig, DelegationRequest, DelegationResponse, IntegrationType, AgentType, RequestClassification, DelegationDecision, ProgressEvent, DelegationResult } from './core/types'; import { RequestClassifier, createRequestClassifier } from './core/request-classifier'; import { DelegationEngine, createDelegationEngine } from './core/delegation-engine'; import { AgentPoolManager, createAgentPoolManager } from './pool/agent-pool-manager'; import { ProgressStreamer, createProgressStreamer } from './streaming/progress-streamer'; import { QualityGate, createQualityGate } from './quality/quality-gate'; import { ContextHandoffManager, createContextHandoffManager } from './core/context-handoff'; import { OpenClawAdapter, ClaudeCodeAdapter, GenericAdapter, BaseIntegrationAdapter, createOpenClawAdapter, createClaudeCodeAdapter, createGenericAdapter } from './integrations/adapters'; // ============================================================================ // Default Configuration // ============================================================================ const DEFAULT_API_CONFIG: DelegationAPIConfig = { integrations: [], defaultStrategy: 'hybrid', maxConcurrentDelegations: 100, requestTimeout: 120000, enableCaching: true, cacheConfig: { maxSize: 1000, ttl: 300000 } }; // ============================================================================ // Delegation System Class // ============================================================================ export class DelegationSystem { private config: DelegationAPIConfig; private classifier: RequestClassifier; private poolManager: AgentPoolManager; private delegationEngine: DelegationEngine; private progressStreamer: ProgressStreamer; private qualityGate: QualityGate; private handoffManager: ContextHandoffManager; private adapters: Map = new Map(); private initialized: boolean = false; constructor(config: Partial = {}) { this.config = { ...DEFAULT_API_CONFIG, ...config }; // Initialize core components this.classifier = createRequestClassifier(); this.poolManager = createAgentPoolManager(); this.progressStreamer = createProgressStreamer(); this.qualityGate = createQualityGate(); this.delegationEngine = createDelegationEngine( this.classifier, this.poolManager ); this.handoffManager = createContextHandoffManager(); } // ============================================================================ // Initialization // ============================================================================ /** * Initialize the delegation system */ async initialize(): Promise { if (this.initialized) return; // Initialize configured integrations for (const integrationConfig of this.config.integrations) { await this.registerIntegration(integrationConfig.type, integrationConfig); } // If no integrations configured, register default ones if (this.adapters.size === 0) { await this.registerIntegration('openclaw'); await this.registerIntegration('claude-code'); await this.registerIntegration('generic'); } this.initialized = true; } /** * Register an integration */ async registerIntegration( type: IntegrationType, config?: any ): Promise { let adapter: BaseIntegrationAdapter; switch (type) { case 'openclaw': adapter = createOpenClawAdapter( this.classifier, this.delegationEngine, this.poolManager, this.progressStreamer, this.qualityGate ); break; case 'claude-code': adapter = createClaudeCodeAdapter( this.classifier, this.delegationEngine, this.poolManager, this.progressStreamer, this.qualityGate ); break; case 'cursor': case 'aider': case 'copilot': case 'generic': default: adapter = createGenericAdapter( this.classifier, this.delegationEngine, this.poolManager, this.progressStreamer, this.qualityGate ); break; } await adapter.initialize(config || {}); this.adapters.set(type, adapter); return adapter; } // ============================================================================ // Main API Methods // ============================================================================ /** * Process a delegation request */ async process(request: DelegationRequest): Promise { if (!this.initialized) { await this.initialize(); } const startTime = Date.now(); const requestId = request.id || `req-${Date.now()}`; // Determine which integration to use const integrationType = request.metadata?.integration || 'generic'; const adapter = this.adapters.get(integrationType as IntegrationType) || this.adapters.get('generic')!; try { // Classify request const classification = await adapter.classifyRequest({ content: request.content, type: request.type, files: request.files, metadata: request.metadata }); // Make delegation decision const decision = await this.delegationEngine.makeDecision({ content: request.content, type: request.type, files: request.files, metadata: request.metadata, timestamp: Date.now() }, classification); // Start progress tracking if requested if (request.streamProgress) { this.progressStreamer.startTracking(requestId); } // Execute delegation or process directly let result: DelegationResult; if (decision.shouldDelegate) { result = await adapter.delegateRequest({ content: request.content, files: request.files, metadata: request.metadata }, decision); } else { // Process with main agent (simulated) result = { success: true, output: `Main agent processed: ${request.content.slice(0, 100)}`, confidence: 0.95, tokensUsed: 200, duration: Date.now() - startTime, agentsUsed: ['main-agent'], needsReview: false }; } // Build response const response: DelegationResponse = { requestId, success: result.success, result: result.output, classification, delegation: decision, confidence: result.confidence, processingTime: Date.now() - startTime, agentsUsed: result.agentsUsed }; // Complete progress tracking if (request.streamProgress) { this.progressStreamer.complete(requestId); } return response; } catch (error) { // Error handling if (request.streamProgress) { this.progressStreamer.error(requestId, error instanceof Error ? error.message : 'Unknown error'); } return { requestId, success: false, result: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`, confidence: 0, processingTime: Date.now() - startTime, agentsUsed: [] }; } } /** * Quick classify a request (fast path) */ quickClassify(content: string): { complexity: string; agent: AgentType } { return this.classifier.quickClassify(content); } /** * Get an integration adapter */ getAdapter(type: IntegrationType): BaseIntegrationAdapter | undefined { return this.adapters.get(type); } /** * Get all registered adapters */ getAdapters(): Map { return new Map(this.adapters); } // ============================================================================ // Progress Streaming // ============================================================================ /** * Subscribe to progress updates */ onProgress( requestId: string, callback: (event: ProgressEvent) => void ): () => void { return this.progressStreamer.subscribe(requestId, callback); } /** * Subscribe to all progress events */ onAllProgress(callback: (event: ProgressEvent) => void): () => void { return this.progressStreamer.subscribeAll(callback); } // ============================================================================ // Status and Statistics // ============================================================================ /** * Get system status */ getStatus(): { initialized: boolean; adapters: number; poolStats: ReturnType; delegationStats: ReturnType; qualityStats: ReturnType; } { return { initialized: this.initialized, adapters: this.adapters.size, poolStats: this.poolManager.getPoolStats(), delegationStats: this.delegationEngine.getStats(), qualityStats: this.qualityGate.getStats() }; } /** * Get pool statistics */ getPoolStats(): ReturnType { return this.poolManager.getPoolStats(); } /** * Check if system is ready */ isReady(): boolean { return this.initialized && this.poolManager.getPoolStats().idleCount > 0; } // ============================================================================ // Lifecycle // ============================================================================ /** * Shutdown the system */ async shutdown(): Promise { // Shutdown all adapters for (const adapter of this.adapters.values()) { await adapter.shutdown(); } // Shutdown pool await this.poolManager.shutdown(); // Clear progress this.progressStreamer.clearAll(); this.initialized = false; } /** * Reset the system */ async reset(): Promise { await this.shutdown(); await this.initialize(); } } // ============================================================================ // Factory Function // ============================================================================ let defaultInstance: DelegationSystem | null = null; export function createDelegationSystem( config?: Partial ): DelegationSystem { return new DelegationSystem(config); } export function getDefaultDelegationSystem(): DelegationSystem { if (!defaultInstance) { defaultInstance = new DelegationSystem(); } return defaultInstance; } // ============================================================================ // Convenience Exports // ============================================================================ // Re-export all types export * from './core/types'; // Re-export all components export { RequestClassifier, createRequestClassifier } from './core/request-classifier'; export { DelegationEngine, createDelegationEngine } from './core/delegation-engine'; export { AgentPoolManager, createAgentPoolManager } from './pool/agent-pool-manager'; export { ProgressStreamer, createProgressStreamer } from './streaming/progress-streamer'; export { QualityGate, createQualityGate } from './quality/quality-gate'; export { ContextHandoffManager, createContextHandoffManager } from './core/context-handoff'; export { OpenClawAdapter, ClaudeCodeAdapter, GenericAdapter, createOpenClawAdapter, createClaudeCodeAdapter, createGenericAdapter } from './integrations/adapters'; // ============================================================================ // Export // ============================================================================ export default DelegationSystem;