/** * Pattern Executor * * Orchestrates multi-agent workflows using various execution patterns. * Provides high-level patterns for agent collaboration including: * - Sequential pipelines (A → B → C) * - Parallel comparison (same task to multiple agents) * - Generator-Critic loops (generate → critique → improve) * - Consensus building (propose → vote → synthesize) * * Each pattern leverages the RouterEngine for individual agent invocations * while managing the overall workflow state and data flow between agents. */ import { type Logger } from '../observability/logger.js'; import type { AgentResponse } from '../types.js'; import type { RouterEngine } from './engine.js'; /** * Step definition for sequential pipeline execution. */ export interface SequentialStep { /** The role of the agent to invoke for this step */ role: string; /** Task template for this step. Use {{input}} or {{previousOutput}} placeholders */ taskTemplate: string; /** Optional transform function to modify input before sending to agent */ transform?: (input: string) => string; } /** * Result of a sequential pipeline execution. */ export interface SequentialResult { /** Pattern identifier */ pattern: 'sequential'; /** All step responses in order */ steps: AgentResponse[]; /** Final output text from the last step */ finalOutput: string; /** Total duration in milliseconds */ totalDurationMs: number; /** Trace ID for correlation */ traceId: string; } /** * Result of a parallel comparison execution. */ export interface ParallelResult { /** Pattern identifier */ pattern: 'parallel'; /** Map of role names to their responses */ responses: Map; /** Errors for roles that failed */ errors: Map; /** Total duration in milliseconds */ totalDurationMs: number; /** Trace ID for correlation */ traceId: string; } /** * Result of a generator-critic loop execution. */ export interface CriticLoopResult { /** Pattern identifier */ pattern: 'critic-loop'; /** Number of iterations completed */ iterations: number; /** Final response from the generator */ finalResponse: AgentResponse; /** Complete history of all generation and critique responses */ history: CriticLoopIteration[]; /** Whether the critic approved the final result */ approved: boolean; /** Final output text */ finalOutput: string; /** Total duration in milliseconds */ totalDurationMs: number; /** Trace ID for correlation */ traceId: string; } /** * Single iteration of a critic loop. */ export interface CriticLoopIteration { /** Iteration number (1-indexed) */ iteration: number; /** Generator's response */ generation: AgentResponse; /** Critic's response */ critique: AgentResponse; /** Whether the critic approved this iteration */ approved: boolean; } /** * Result of a consensus building execution. */ export interface ConsensusResult { /** Pattern identifier */ pattern: 'consensus'; /** Initial proposals from all participating roles */ proposals: Map; /** Votes/assessments from each role on all proposals */ votes: Map; /** Final synthesized recommendation */ synthesis: AgentResponse; /** Final output text */ finalOutput: string; /** Total duration in milliseconds */ totalDurationMs: number; /** Trace ID for correlation */ traceId: string; } /** * Options for critic loop execution. */ export interface CriticLoopOptions { /** Maximum number of iterations (default: 3) */ maxIterations?: number; /** Custom approval detection function */ isApproved?: (critique: string) => boolean; /** Custom task template for critique requests */ critiqueTaskTemplate?: string; /** Custom task template for improvement requests */ improvementTaskTemplate?: string; } /** * Options for consensus building execution. */ export interface ConsensusOptions { /** Role to use for final synthesis (default: first role in list) */ synthesizeRole?: string; /** Custom task template for voting phase */ voteTaskTemplate?: string; /** Custom task template for synthesis phase */ synthesisTaskTemplate?: string; } /** * Union type of all orchestration results. */ export type OrchestrationResult = SequentialResult | ParallelResult | CriticLoopResult | ConsensusResult; /** * Orchestrates multi-agent workflows using various execution patterns. * * @example * ```typescript * const executor = new PatternExecutor(routerEngine, logger); * * // Sequential pipeline * const result = await executor.executeSequential([ * { role: 'coder', taskTemplate: 'Implement: {{input}}' }, * { role: 'reviewer', taskTemplate: 'Review this code: {{previousOutput}}' }, * ], 'Create a sorting function'); * * // Parallel comparison * const comparison = await executor.executeParallel( * ['coder', 'researcher'], * 'What are the best practices for error handling?' * ); * * // Critic loop * const improved = await executor.executeCriticLoop( * 'coder', * 'critic', * 'Write a REST API endpoint', * { maxIterations: 3 } * ); * ``` */ export declare class PatternExecutor { private readonly router; private readonly logger; constructor(router: RouterEngine, logger: Logger); /** * Execute a sequential pipeline of agents. * * Each agent's output becomes input to the next. Task templates can use * placeholders: * - `{{input}}` - The original input or previous step's output * - `{{previousOutput}}` - Alias for input from previous step * * @param steps - Array of step definitions with roles and task templates * @param initialInput - Initial input to the first step * @returns Promise resolving to SequentialResult with all step outputs * * @example * ```typescript * const result = await executor.executeSequential([ * { role: 'coder', taskTemplate: '{{input}}' }, * { role: 'reviewer', taskTemplate: 'Review: {{previousOutput}}' }, * { role: 'coder', taskTemplate: 'Fix issues: {{previousOutput}}' }, * ], 'Write a function to validate email addresses'); * ``` */ executeSequential(steps: SequentialStep[], initialInput: string): Promise; /** * Execute the same task through multiple agents in parallel. * * All agents receive the same task and run concurrently. Results are * collected for comparison. Errors for individual agents don't fail * the entire operation. * * @param roles - Array of role names to invoke * @param task - The task to send to all agents * @returns Promise resolving to ParallelResult with all agent responses * * @example * ```typescript * const result = await executor.executeParallel( * ['coder', 'researcher', 'critic'], * 'What is the best approach to implement caching?' * ); * * for (const [role, response] of result.responses) { * console.log(`${role}: ${extractText(response)}`); * } * ``` */ executeParallel(roles: string[], task: string): Promise; /** * Execute a generator-critic improvement loop. * * The generator creates an initial response, then the critic reviews it. * If the critic identifies issues, the generator improves based on feedback. * This continues until the critic approves or max iterations is reached. * * @param generatorRole - Role for generating content * @param criticRole - Role for critiquing content * @param task - Initial task for the generator * @param options - Optional configuration for the loop * @returns Promise resolving to CriticLoopResult with iteration history * * @example * ```typescript * const result = await executor.executeCriticLoop( * 'coder', * 'critic', * 'Write a function to parse JSON with error handling', * { maxIterations: 3 } * ); * * if (result.approved) { * console.log('Critic approved the final version'); * } * console.log(`Completed in ${result.iterations} iterations`); * ``` */ executeCriticLoop(generatorRole: string, criticRole: string, task: string, options?: CriticLoopOptions): Promise; /** * Execute a consensus building workflow. * * Three phases: * 1. Proposals: All roles respond to the initial question * 2. Voting: Each role evaluates all proposals * 3. Synthesis: A designated role synthesizes a final recommendation * * @param roles - Array of role names to participate * @param question - The question or decision to reach consensus on * @param options - Optional configuration for the workflow * @returns Promise resolving to ConsensusResult with all phases * * @example * ```typescript * const result = await executor.executeConsensus( * ['coder', 'critic', 'designer'], * 'What is the best architecture for a real-time chat application?', * { synthesizeRole: 'coder' } * ); * * console.log('Final recommendation:', result.finalOutput); * ``` */ executeConsensus(roles: string[], question: string, options?: ConsensusOptions): Promise; /** * Extract text content from an agent response. * * @param response - Agent response to extract text from * @returns Concatenated text content from all text blocks */ extractText(response: AgentResponse): string; /** * Interpolate a template string with variable values. * * @param template - Template string with {{variable}} placeholders * @param variables - Object mapping variable names to values * @returns Interpolated string */ private interpolateTemplate; /** * Format proposals for display in templates. * * @param proposals - Map of role names to responses * @returns Formatted string with numbered proposals */ private formatProposals; /** * Format votes/assessments for display in templates. * * @param votes - Map of role names to vote responses * @returns Formatted string with role assessments */ private formatVotes; /** * Truncate a string to a maximum length. * * @param str - String to truncate * @param maxLength - Maximum length before truncation * @returns Truncated string with ellipsis if needed */ private truncate; } /** * Create a PatternExecutor instance. * * @param router - RouterEngine for agent invocations * @param logger - Logger for observability * @returns Configured PatternExecutor instance */ export declare function createPatternExecutor(router: RouterEngine, logger: Logger): PatternExecutor; //# sourceMappingURL=pattern-executor.d.ts.map