/** * Orchestrator - Loads, runs, and provides real-time visibility into agent execution */ import chalk from 'chalk'; import type { OrchestratorEvent, RunResult, OutputFormat, TokenUsage } from '../types.js'; import { Agent } from '../agents/Agent.js'; import { YAMLLoader, LoadedWorkflow } from './YAMLLoader.js'; import { JSONOutputHandler } from '../output/JSONOutputHandler.js'; export interface OrchestratorConfig { /** Whether to display real-time output (default: true) */ verbose?: boolean; /** Callback for orchestrator events */ onEvent?: (event: OrchestratorEvent) => void; /** Output format: 'text' for chalk-formatted console, 'json' for NDJSON streaming */ outputFormat?: OutputFormat; /** Unique run identifier (required for JSON output) */ runId?: string; /** Working directory for agent file operations */ cwd?: string; } export class Orchestrator { private loader: YAMLLoader; private config: OrchestratorConfig; private activeAgents: Map = new Map(); private eventLog: OrchestratorEvent[] = []; private jsonOutput: JSONOutputHandler | null = null; private isJsonMode: boolean = false; constructor(config: OrchestratorConfig = {}) { this.loader = new YAMLLoader(); this.isJsonMode = config.outputFormat === 'json'; this.config = { verbose: config.verbose ?? true, onEvent: config.onEvent, outputFormat: config.outputFormat ?? 'text', runId: config.runId, cwd: config.cwd, }; // Initialize JSON output handler if in JSON mode if (this.isJsonMode) { if (!config.runId) { throw new Error('runId is required for JSON output mode'); } this.jsonOutput = new JSONOutputHandler({ runId: config.runId, verbose: config.verbose ?? true, }); } } /** * Load a workflow from a YAML file. */ loadWorkflow(filePath: string): LoadedWorkflow { const workflow = this.loader.loadFromFile(filePath); this.displayWorkflowInfo(workflow, filePath); return workflow; } /** * Load a workflow from YAML string. */ loadWorkflowFromString(yamlContent: string, sourcePath?: string): LoadedWorkflow { const workflow = this.loader.loadFromString(yamlContent); this.displayWorkflowInfo(workflow, sourcePath); return workflow; } /** * Run a loaded workflow with a task. */ async runWorkflow(workflow: LoadedWorkflow, task: string, workflowPath?: string): Promise { this.displayRunStart(workflow.name, task, workflowPath); // Set up event tracking on the entrypoint agent this.instrumentAgent(workflow.entrypointAgent, workflow.entrypointAgent.getName(), 0); // Also instrument sub-agents for (const [name, agent] of workflow.agents) { if (agent !== workflow.entrypointAgent) { this.instrumentAgent(agent, name, 1); } } try { const result = await workflow.entrypointAgent.run(task); this.displayRunEnd(result, true); return result; } catch (error) { this.displayError(error as Error); // Emit run end with failure in JSON mode if (this.isJsonMode && this.jsonOutput) { this.jsonOutput.emitRunEnd(false, null, 0, 0); } throw error; } } /** * Run a standalone agent with a task. */ async runAgent(agent: Agent, task: string): Promise { this.instrumentAgent(agent, agent.getName(), 0); const result = await agent.run(task); return result; } /** * Instrument an agent with orchestrator event tracking. */ private instrumentAgent(agent: Agent, name: string, depth: number): void { this.activeAgents.set(name, { agent, depth }); // Set up event callback to capture and emit events agent.setOnEvent((event) => { // Log the event to our event log const orchestratorEvent: OrchestratorEvent = { type: event.type as OrchestratorEvent['type'], agentName: name, depth, data: event.data, timestamp: Date.now(), }; this.logEvent(orchestratorEvent); // In JSON mode, emit detailed events if (this.isJsonMode && this.jsonOutput) { this.emitAgentEventAsJSON(event, name, depth); } }); } /** * Emit an agent event as JSON. */ private emitAgentEventAsJSON( event: { type: string; data: unknown }, agentName: string, depth: number ): void { if (!this.jsonOutput) return; const data = event.data as Record; switch (event.type) { case 'agent_start': this.jsonOutput.emitAgentStart( agentName, depth, data.task as string, data.name ? 'ToolUseAgent' : 'CodeAgent', // Will be improved 20 // Default maxSteps, could be passed ); break; case 'agent_step': this.jsonOutput.emitAgentStep( agentName, depth, data.step as number, data.maxSteps as number, 'start' ); break; case 'agent_thinking': this.jsonOutput.emitAgentThinking( agentName, depth, data.step as number, data.content as string, false ); break; case 'agent_tool_call': this.jsonOutput.emitToolCall( agentName, depth, data.step as number, data.toolCallId as string, data.toolName as string, data.arguments as Record ); break; case 'agent_tool_result': this.jsonOutput.emitToolResult( agentName, depth, data.step as number, data.toolCallId as string, data.toolName as string, data.result, data.error as string | undefined, data.duration as number ); break; case 'agent_observation': this.jsonOutput.emitObservation( agentName, depth, data.step as number, data.observation as string, data.codeAction as string | undefined, data.logs as string | undefined ); break; case 'agent_error': this.jsonOutput.emitError( data.error as string, undefined, agentName, depth, data.step as number ); break; case 'agent_end': this.jsonOutput.emitAgentEnd( agentName, depth, data.output, 0, // totalSteps - would need to track data.tokenUsage as TokenUsage, data.duration as number, true ); break; } } /** * Display workflow info at startup. */ private displayWorkflowInfo(workflow: LoadedWorkflow, _sourcePath?: string): void { const agents = Array.from(workflow.agents.keys()); const tools = Array.from(workflow.tools.keys()); const entrypoint = workflow.entrypointAgent.getName(); if (this.isJsonMode && this.jsonOutput) { this.jsonOutput.emitWorkflowLoaded( workflow.name, workflow.description, agents, tools, entrypoint ); return; } if (!this.config.verbose) return; const line = '═'.repeat(70); console.log(chalk.cyan(line)); console.log(chalk.cyan.bold(` Workflow: ${workflow.name}`)); if (workflow.description) { console.log(chalk.cyan(` ${workflow.description}`)); } console.log(chalk.cyan(` Agents: ${agents.join(', ')}`)); console.log(chalk.cyan(` Tools: ${tools.join(', ') || '(none defined at workflow level)'}`)); console.log(chalk.cyan(` Entrypoint: ${entrypoint}`)); console.log(chalk.cyan(line)); console.log(); } /** * Display run start info. */ private displayRunStart(workflowName: string, task: string, workflowPath?: string): void { if (this.isJsonMode && this.jsonOutput) { this.jsonOutput.emitRunStart(workflowPath || workflowName, task, this.config.cwd); return; } if (!this.config.verbose) return; console.log(chalk.green.bold(`\n▶ Running workflow "${workflowName}"`)); console.log(chalk.green(` Task: ${task}`)); console.log(chalk.gray('─'.repeat(70))); } /** * Display run completion info. */ private displayRunEnd(result: RunResult, success: boolean = true): void { if (this.isJsonMode && this.jsonOutput) { this.jsonOutput.emitRunEnd( success, result.output, result.tokenUsage.totalTokens, result.steps.length ); return; } if (!this.config.verbose) return; console.log(chalk.gray('\n' + '─'.repeat(70))); console.log(chalk.green.bold(`\n✅ Workflow complete`)); console.log(chalk.green(` Duration: ${(result.duration / 1000).toFixed(2)}s`)); console.log(chalk.green(` Tokens: ${result.tokenUsage.totalTokens}`)); console.log(chalk.green(` Steps: ${result.steps.length}`)); const outputStr = typeof result.output === 'string' ? result.output : JSON.stringify(result.output, null, 2); console.log(chalk.magenta.bold('\n Final Output:')); // Indent output const indentedOutput = outputStr.split('\n').map(line => ` ${line}`).join('\n'); console.log(chalk.magenta(indentedOutput)); console.log(); } /** * Display an error. */ private displayError(error: Error): void { if (this.isJsonMode && this.jsonOutput) { this.jsonOutput.emitError(error.message, error.stack); return; } if (!this.config.verbose) return; console.error(chalk.red.bold(`\n❌ Workflow failed: ${error.message}`)); if (error.stack) { console.error(chalk.red.dim(error.stack)); } } /** * Log an orchestration event. */ logEvent(event: OrchestratorEvent): void { this.eventLog.push(event); if (this.config.onEvent) { this.config.onEvent(event); } } /** * Get the event log. */ getEventLog(): OrchestratorEvent[] { return [...this.eventLog]; } /** * Get the YAML loader for registering custom tools. */ getLoader(): YAMLLoader { return this.loader; } /** * Get the JSON output handler (if in JSON mode). */ getJSONOutputHandler(): JSONOutputHandler | null { return this.jsonOutput; } /** * Check if in JSON output mode. */ isJSONOutputMode(): boolean { return this.isJsonMode; } /** * Get the run ID. */ getRunId(): string | undefined { return this.config.runId; } }