/** * Router Engine * * The main orchestration logic for AgentRouter. * Responsible for resolving roles to configurations and executing * agent invocations against the appropriate providers. * * Key responsibilities: * - Invoking agents by role with proper message construction * - Comparing responses from multiple agents in parallel * - Handling fallback providers when primary fails * - Logging request/response metadata for observability */ import { type Logger } from '../observability/logger.js'; import { type Config, type InvokeAgentInput, type AgentResponse, type SessionDelegationResponse, type AgentConfig } from '../types.js'; import { FailoverOrchestrator, type FailoverOrchestratorConfig } from '../failover/orchestrator.js'; import type { ProviderManager } from '../providers/manager.js'; /** * Options for configuring the RouterEngine. */ export interface RouterEngineOptions { /** Whether to enable fallback providers (default: true) */ enableFallback?: boolean; /** Maximum retries before attempting fallback (default: 0) */ maxRetries?: number; /** Failover orchestrator configuration */ failoverConfig?: FailoverOrchestratorConfig; } /** * Result of a comparison operation for a single role. */ export interface ComparisonResult { role: string; status: 'fulfilled' | 'rejected'; response?: AgentResponse; error?: Error; } /** * Main routing engine for AgentRouter. * * Handles: * - Role resolution to provider configurations * - Message building with system prompts and context * - Agent invocation with proper error handling * - Parallel comparison of multiple agents * - Fallback execution when primary providers fail * * @example * ```ts * const engine = new RouterEngine(config, providerManager, logger); * * // Invoke a single agent * const response = await engine.invokeAgent({ * role: 'coder', * task: 'Write a function to sort an array', * context: 'Using TypeScript', * }); * * // Compare multiple agents * const results = await engine.compareAgents( * ['coder', 'reviewer'], * 'Review this code for bugs' * ); * ``` */ export declare class RouterEngine { private roleResolver; private readonly providers; private readonly logger; private readonly options; private readonly config; private failoverOrchestrator?; /** * Create a new RouterEngine instance. * * @param config - Configuration object with role and provider definitions * @param providers - Provider manager for accessing LLM providers * @param logger - Logger instance for observability * @param options - Optional configuration for the engine */ constructor(config: Config, providers: ProviderManager, logger: Logger, options?: RouterEngineOptions); /** * Invoke an agent by role. * * Flow: * 1. Generate trace ID for request correlation * 2. Log request start with role and task preview * 3. Resolve role to agent configuration * 4. Build messages array (system prompt + context + task) * 5. Get provider from ProviderManager * 6. Call provider.complete() * 7. Log response with duration and token usage * 8. Return AgentResponse * 9. On error: try fallback if configured, otherwise throw * * @param input - Input parameters including role, task, and optional context * @returns Promise resolving to the agent's response or session delegation * @throws ProviderError if the provider fails and no fallback is available */ invokeAgent(input: InvokeAgentInput): Promise; /** * Compare responses from multiple agents for the same task. * * Executes all agents in parallel using Promise.allSettled to ensure * all results are collected even if some fail. * * @param roles - Array of role names to invoke * @param task - The task to send to all agents * @returns Map of role names to their responses (only includes successful results) */ compareAgents(roles: string[], task: string): Promise>; /** * Update the configuration. * This recreates the RoleResolver with the new configuration. * * @param config - New configuration object */ updateConfig(config: Config): void; /** * Get the list of available roles. * * @returns Array of role names */ listRoles(): string[]; /** * Check if a role is configured. * * @param role - Role name to check * @returns True if the role exists */ hasRole(role: string): boolean; /** * Resolve a role to its full agent configuration. * * @param role - Role name to resolve * @returns Resolved agent configuration with all defaults applied * @throws Error if the role does not exist */ resolveRole(role: string): AgentConfig; /** * Get the failover orchestrator (if enabled). * * @returns The failover orchestrator instance or undefined if not enabled */ getFailoverOrchestrator(): FailoverOrchestrator | undefined; /** * Initialize the router engine (starts health checks, fetches pricing). * Should be called after construction before handling requests. */ initialize(): Promise; /** * Shutdown the router engine. * Stops health checks and cleans up resources. */ shutdown(): void; /** * Build the messages array for a completion request. * * Message structure: * 1. System prompt (if configured) - wrapped in tags * 2. Context (if provided) - wrapped in tags * 3. Task - the actual user request * * @param agentConfig - Resolved agent configuration * @param input - Input parameters with task and optional context * @returns Array of messages for the completion request */ private buildMessages; /** * Invoke an agent using its fallback configuration. * * @param input - Original input parameters * @param originalConfig - Original agent configuration (contains fallback) * @param traceId - Trace ID for correlation * @param startTime - Original start time for duration calculation * @returns Promise resolving to the agent's response */ private invokeWithFallback; } /** * Create a RouterEngine instance with default options. * * @param config - Configuration object * @param providers - Provider manager * @param logger - Logger instance * @param options - Optional engine configuration * @returns Configured RouterEngine instance */ export declare function createRouterEngine(config: Config, providers: ProviderManager, logger: Logger, options?: RouterEngineOptions): RouterEngine; //# sourceMappingURL=engine.d.ts.map