/** * TerminalAgent - Accomplishes tasks by reasoning about and executing shell commands. * * Unlike CodeAgent (sandboxed JS VM) or ToolUseAgent (structured function calls), * TerminalAgent operates by having the LLM emit shell commands in fenced ```sh * blocks. Each block is executed on the user's real macOS terminal with full * stdout/stderr streaming. * * Key behaviours: * - Verbose logging is always on. The user sees reasoning, pending commands, * and live output. * - A 5-second delay fires before every command batch so the user can read * what is about to run and abort with Ctrl+C. * - User-assigned tools are stripped. The agent always has final_answer and * any AgentTools (sub-agent delegation) that were wired in via YAML. * - Commands run via child_process with stdio piped so output is captured * and streamed back to the agent as observations. */ import { execSync } from 'child_process'; import { Agent, AgentConfig } from './Agent.js'; import { FinalAnswerTool } from '../tools/defaultTools.js'; import { generateTerminalAgentSystemPrompt } from '../prompts/terminalAgent.js'; import { LogLevel } from '../types.js'; import type { ActionStep, ActionOutput, ChatMessage } from '../types.js'; export interface TerminalAgentConfig extends AgentConfig { /** * Seconds to wait before executing each command batch. * Gives the user time to read pending commands and Ctrl+C. * Default: 5 */ commandDelay?: number; /** * Maximum characters of command output to feed back to the LLM per batch. * Very long outputs are truncated (head + tail preserved) to keep context * manageable. Default: 8000 */ maxOutputLength?: number; } // Regex: captures everything inside ```sh ... ``` blocks (one or more per response) const SH_BLOCK_REGEX = /```(?:sh|bash|shell|zsh)\n([\s\S]*?)```/g; const THOUGHT_REGEX = /(?:Thought|Reasoning|Think):\s*([\s\S]*?)(?=```|FINAL_ANSWER:|$)/i; // Text marker for signalling completion — avoids sending final_answer as a tool // definition, which would pull the LLM out of "emit shell commands" mode. const FINAL_ANSWER_MARKER = /^FINAL_ANSWER:\s*([\s\S]*)$/m; /** Separator used to split multi-command blocks for sequential execution */ const NEWLINE = '\n'; export class TerminalAgent extends Agent { private readonly commandDelay: number; private readonly maxOutputLength: number; constructor(config: TerminalAgentConfig) { // Force verbose logging — this agent's whole value is visibility. super({ ...config, verboseLevel: LogLevel.DEBUG }); this.commandDelay = config.commandDelay ?? 5; this.maxOutputLength = config.maxOutputLength ?? 8000; // Strip any user-assigned tools. TerminalAgent only keeps: // - final_answer (always) // - AgentTool instances (delegation) const keepTools = new Map(); for (const [name, tool] of this.tools) { if (tool.constructor.name === 'AgentTool') { keepTools.set(name, tool); } } this.tools = keepTools; // Always ensure final_answer is present if (!this.tools.has('final_answer')) { this.tools.set('final_answer', new FinalAnswerTool()); } } /** * Build the system prompt. Includes delegation info if sub-agents are present. */ protected initializeSystemPrompt(): string { const agentTools = Array.from(this.tools.values()).filter( t => t.constructor.name === 'AgentTool' ); const hasSubAgents = agentTools.length > 0; const subAgentDescriptions = agentTools .map(t => `- **${t.name}**: ${t.description}`) .join('\n'); return generateTerminalAgentSystemPrompt({ customInstructions: this.config.customInstructions, hasSubAgents, subAgentDescriptions, }); } /** * Execute one step of the ReAct loop: * 1. Send messages to LLM (with tool defs for final_answer / delegation) * 2. Extract reasoning and ```sh blocks from the response * 3. If tool calls present (final_answer or delegation), process them * 4. Otherwise execute shell commands with the pre-execution delay * 5. Feed stdout/stderr/exit-code back as observation */ protected async executeStep(memoryStep: ActionStep): Promise { const messages = this.memory.toMessages(); memoryStep.modelInputMessages = [...messages]; // Error recovery from previous step const actionSteps = this.memory.getActionSteps(); const prevStep = actionSteps.length >= 2 ? actionSteps[actionSteps.length - 2] : undefined; if (prevStep?.error) { messages.push({ role: 'user', content: `Your previous action encountered an error: ${prevStep.error.message}\nPlease try a different approach.`, }); } // Only send AgentTool definitions for sub-agent delegation. // final_answer is NOT sent as a tool — that would flip the LLM into // function-calling mode and it would stop emitting ```sh blocks. // Instead, completion is signalled via the FINAL_ANSWER: text marker. const delegationTools = Array.from(this.tools.values()) .filter(t => t.constructor.name === 'AgentTool'); const toolDefinitions = delegationTools.map(t => t.toOpenAITool()); // Generate LLM response this.logger.subheader('Agent thinking...'); const response = await this.generateResponse(messages, toolDefinitions); memoryStep.modelOutputMessage = response; memoryStep.tokenUsage = response.tokenUsage; const content = response.content ?? ''; // Log reasoning const thoughtMatch = content.match(THOUGHT_REGEX); if (thoughtMatch) { this.logger.reasoning(thoughtMatch[1].trim()); this.emitEvent('agent_thinking', { step: this.currentStep, content: thoughtMatch[1].trim() }); } // --- Path A: FINAL_ANSWER text marker (primary completion signal) --- const finalMatch = content.match(FINAL_ANSWER_MARKER); if (finalMatch) { const answer = finalMatch[1].trim(); this.logger.finalAnswer(answer); return { output: answer, isFinalAnswer: true }; } // --- Path B: delegation tool calls (AgentTools only) --- if (response.toolCalls && response.toolCalls.length > 0) { memoryStep.toolCalls = response.toolCalls; const results = await this.processToolCalls(response.toolCalls); memoryStep.toolResults = results; for (const result of results) { if (result.error) { this.logger.error(`Tool ${result.toolName} failed: ${result.error}`); } else { const str = typeof result.result === 'string' ? result.result : JSON.stringify(result.result, null, 2); this.logger.output(`[${result.toolName}]: ${str.slice(0, 500)}${str.length > 500 ? '...' : ''}`); } } const obs = results .map(r => r.error ? `[${r.toolName}] Error: ${r.error}` : `[${r.toolName}] Result: ${typeof r.result === 'string' ? r.result : JSON.stringify(r.result)}`) .join('\n'); memoryStep.observation = `Observation:\n${obs}`; return { output: null, isFinalAnswer: false }; } // --- Path B: Extract and execute shell command blocks --- const blocks: string[] = []; let match: RegExpExecArray | null; const regex = new RegExp(SH_BLOCK_REGEX.source, 'g'); while ((match = regex.exec(content)) !== null) { blocks.push(match[1].trim()); } if (blocks.length === 0) { // No commands and no tool calls — nudge the model this.logger.warn('No shell commands or tool calls in response.'); memoryStep.observation = 'No shell command block was found in your response. ' + 'Emit commands inside a ```sh code block, or call final_answer if the task is complete.'; return { output: null, isFinalAnswer: false }; } // Display pending commands so the user can review before execution const allCommands = blocks.join('\n---\n'); this.logger.code(allCommands, 'sh'); this.emitEvent('agent_observation', { step: this.currentStep, observation: `Pending commands:\n${allCommands}`, }); // --- Pre-execution delay (Ctrl+C window) --- this.logger.waiting(this.commandDelay); await this.sleep(this.commandDelay * 1000); // --- Execute each block sequentially --- const observations: string[] = []; let hitError = false; for (let i = 0; i < blocks.length; i++) { const block = blocks[i]; const commands = block.split(NEWLINE).filter(l => l.trim() && !l.trim().startsWith('#')); this.logger.subheader(`Executing command block ${blocks.length > 1 ? `${i + 1}/${blocks.length}` : ''}...`); for (const cmd of commands) { this.logger.info(` $ ${cmd}`); const result = this.runCommand(cmd); if (result.stdout) { this.logger.logs(result.stdout); } if (result.stderr) { this.logger.error(`stderr: ${result.stderr}`); } observations.push( `$ ${cmd}\n` + (result.stdout ? `stdout:\n${result.stdout}` : '') + (result.stderr ? `stderr:\n${result.stderr}` : '') + `exit code: ${result.exitCode}` ); if (result.exitCode !== 0) { hitError = true; break; // Stop this block on error } } if (hitError) break; } const observation = observations.join('\n\n'); memoryStep.observation = `Observation:\n${observation}`; if (hitError) { memoryStep.error = new Error('Command exited with non-zero status. See observation for details.'); } return { output: observation, isFinalAnswer: false }; } /** * Run a single shell command, capture stdout/stderr, return structured result. */ private runCommand(cmd: string): { stdout: string; stderr: string; exitCode: number } { try { const stdout = execSync(cmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], shell: '/bin/zsh', timeout: 120_000, // 2-minute per-command timeout maxBuffer: 50 * 1024 * 1024, // 50 MB }); return { stdout: this.truncateOutput(stdout), stderr: '', exitCode: 0 }; } catch (err) { const e = err as NodeJS.ErrnoException & { stdout?: string; stderr?: string; status?: number }; return { stdout: this.truncateOutput(e.stdout ?? ''), stderr: this.truncateOutput(e.stderr ?? e.message), exitCode: e.status ?? 1, }; } } /** * Truncate long output, preserving head and tail so context stays useful. */ private truncateOutput(output: string): string { if (output.length <= this.maxOutputLength) return output; const half = Math.floor(this.maxOutputLength / 2); const head = output.slice(0, half); const tail = output.slice(output.length - half); const omitted = output.length - this.maxOutputLength; return `${head}\n\n... [${omitted} characters omitted] ...\n\n${tail}`; } /** * Generate response, with streaming if available. */ private async generateResponse(messages: ChatMessage[], toolDefinitions: unknown[]): Promise { if (this.config.streamOutputs && this.model.supportsStreaming() && this.model.generateStream) { let fullContent = ''; const generator = this.model.generateStream(messages, { toolDefinitions: toolDefinitions as Parameters[1] extends infer O ? O extends { toolDefinitions?: infer T } ? T : never : never, maxTokens: this.config.maxTokens, temperature: this.config.temperature, }); for await (const chunk of generator) { this.logger.streamChar(chunk); fullContent += chunk; } this.logger.streamEnd(); return { role: 'assistant', content: fullContent }; } return this.model.generate(messages, { toolDefinitions: toolDefinitions as Parameters[1] extends infer O ? O extends { toolDefinitions?: infer T } ? T : never : never, maxTokens: this.config.maxTokens, temperature: this.config.temperature, }); } /** * Process tool calls (final_answer or AgentTool delegation). */ private async processToolCalls( toolCalls: import('../types.js').ToolCall[] ): Promise { const results: import('../types.js').ToolCallResult[] = []; for (const tc of toolCalls) { const toolName = tc.function.name; const tool = this.tools.get(toolName); if (!tool) { results.push({ toolCallId: tc.id, toolName, result: null, error: `Unknown tool: ${toolName}` }); continue; } let args: Record; try { args = typeof tc.function.arguments === 'string' ? JSON.parse(tc.function.arguments) : tc.function.arguments as Record; } catch { results.push({ toolCallId: tc.id, toolName, result: null, error: 'Failed to parse tool arguments' }); continue; } this.logger.info(` Calling tool: ${toolName}(${JSON.stringify(args).slice(0, 100)}...)`); this.emitEvent('agent_tool_call', { step: this.currentStep, toolCallId: tc.id, toolName, arguments: args }); try { const result = await tool.call(args); this.emitEvent('agent_tool_result', { step: this.currentStep, toolCallId: tc.id, toolName, result, duration: 0 }); results.push({ toolCallId: tc.id, toolName, result }); } catch (error) { const msg = `Tool execution error: ${(error as Error).message}`; this.emitEvent('agent_tool_result', { step: this.currentStep, toolCallId: tc.id, toolName, result: null, error: msg, duration: 0 }); results.push({ toolCallId: tc.id, toolName, result: null, error: msg }); } } return results; } /** * Override: force final answer via tool call format when max steps hit. */ protected async provideFinalAnswer(task: string): Promise { this.logger.subheader('Generating final answer from accumulated context'); const messages = this.memory.toMessages(); messages.push({ role: 'user', content: `You have reached the maximum number of steps. Based on your work so far, provide the best answer for the task: "${task}". Call the final_answer tool with your response.`, }); const toolDefinitions = [new FinalAnswerTool().toOpenAITool()]; const response = await this.model.generate(messages, { toolDefinitions, maxTokens: this.config.maxTokens, temperature: this.config.temperature }); if (response.toolCalls && response.toolCalls.length > 0) { try { const args = typeof response.toolCalls[0].function.arguments === 'string' ? JSON.parse(response.toolCalls[0].function.arguments) : response.toolCalls[0].function.arguments; return (args as Record).answer; } catch { return response.content; } } return response.content; } }