@samrahimi/smol-js 0.7.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +31 -27
- package/dist/cli.js.map +1 -1
- package/dist/index.d.mts +20 -14
- package/dist/index.d.ts +20 -14
- package/dist/index.js +28 -24
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +28 -24
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -1
- package/toolHarness.ts +73 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/memory/AgentMemory.ts","../src/logging/AgentLogger.ts","../src/agents/Agent.ts","../src/executor/LocalExecutor.ts","../src/tools/Tool.ts","../src/tools/defaultTools.ts","../src/prompts/codeAgent.ts","../src/agents/CodeAgent.ts","../src/prompts/toolUseAgent.ts","../src/agents/ToolUseAgent.ts","../src/models/Model.ts","../src/models/OpenAIModel.ts","../src/tools/AgentTool.ts","../src/tools/ReadFileTool.ts","../src/tools/WriteFileTool.ts","../src/tools/CurlTool.ts","../src/tools/ExaSearchTool.ts","../src/tools/ExaGetContentsTool.ts","../src/tools/ExaResearchTool.ts","../src/tools/ProxyTool.ts","../src/utils/bunInstaller.ts","../src/tools/CustomToolScanner.ts","../src/orchestrator/YAMLLoader.ts","../src/orchestrator/Orchestrator.ts","../src/output/JSONOutputHandler.ts"],"sourcesContent":["/**\n * Core types for smol-js\n */\n\n// Message roles following OpenAI chat completions format\nexport type MessageRole = 'system' | 'user' | 'assistant' | 'tool';\n\n// Token usage tracking\nexport interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n}\n\n// Timing information for steps\nexport interface Timing {\n startTime: number;\n endTime?: number;\n duration?: number;\n}\n\n// Chat message structure\nexport interface ChatMessage {\n role: MessageRole;\n content: string | null;\n name?: string;\n toolCalls?: ToolCall[];\n toolCallId?: string;\n tokenUsage?: TokenUsage;\n}\n\n// Tool call structure (OpenAI format)\nexport interface ToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string | Record<string, unknown>;\n };\n}\n\n// Tool input schema type\nexport type ToolInputType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'array'\n | 'object'\n | 'any';\n\n// Tool input definition\nexport interface ToolInput {\n type: ToolInputType;\n description: string;\n required?: boolean;\n default?: unknown;\n enum?: string[];\n}\n\n// Tool inputs schema\nexport interface ToolInputs {\n [key: string]: ToolInput;\n}\n\n// OpenAI function tool definition\nexport interface OpenAIToolDefinition {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: {\n type: 'object';\n properties: Record<string, unknown>;\n required?: string[];\n };\n };\n}\n\n// Code execution output\nexport interface CodeExecutionOutput {\n output: unknown;\n logs: string;\n isFinalAnswer: boolean;\n error?: Error;\n}\n\n// Action output from a step\nexport interface ActionOutput {\n output: unknown;\n isFinalAnswer: boolean;\n}\n\n// Memory management strategy\nexport type MemoryStrategy = 'truncate' | 'compact';\n\n// Agent configuration\nexport interface AgentConfig {\n model: Model;\n tools?: Tool[];\n maxSteps?: number;\n codeExecutionDelay?: number;\n systemPrompt?: string;\n additionalAuthorizedImports?: string[];\n streamOutputs?: boolean;\n verboseLevel?: LogLevel;\n persistent?: boolean;\n maxContextLength?: number;\n memoryStrategy?: MemoryStrategy;\n customInstructions?: string;\n maxTokens?: number;\n temperature?: number;\n}\n\n// Model configuration\nexport interface ModelConfig {\n modelId?: string;\n apiKey?: string;\n baseUrl?: string;\n maxTokens?: number;\n temperature?: number;\n timeout?: number;\n}\n\n// Log levels\nexport enum LogLevel {\n OFF = -1,\n ERROR = 0,\n INFO = 1,\n DEBUG = 2,\n}\n\n// Step types for memory\nexport type StepType = 'system' | 'task' | 'action' | 'planning' | 'final';\n\n// Base memory step\nexport interface MemoryStep {\n type: StepType;\n timestamp: number;\n}\n\n// System prompt step\nexport interface SystemPromptStep extends MemoryStep {\n type: 'system';\n content: string;\n}\n\n// Task step\nexport interface TaskStep extends MemoryStep {\n type: 'task';\n task: string;\n}\n\n// Action step - main execution step\nexport interface ActionStep extends MemoryStep {\n type: 'action';\n stepNumber: number;\n timing: Timing;\n modelInputMessages: ChatMessage[];\n modelOutputMessage?: ChatMessage;\n codeAction?: string;\n toolCalls?: ToolCall[];\n toolResults?: ToolCallResult[];\n observation?: string;\n actionOutput?: ActionOutput;\n tokenUsage?: TokenUsage;\n error?: Error;\n isFinalAnswer?: boolean;\n}\n\n// Tool call result\nexport interface ToolCallResult {\n toolCallId: string;\n toolName: string;\n result: unknown;\n error?: string;\n}\n\n// Final answer step\nexport interface FinalAnswerStep extends MemoryStep {\n type: 'final';\n answer: unknown;\n}\n\n// Stream event types\nexport interface StreamEvent {\n type: 'delta' | 'toolCall' | 'observation' | 'step' | 'final' | 'error';\n data: unknown;\n}\n\n// Run result\nexport interface RunResult {\n output: unknown;\n steps: MemoryStep[];\n tokenUsage: TokenUsage;\n duration: number;\n}\n\n// Forward declarations for circular deps\nexport interface Tool {\n name: string;\n description: string;\n inputs: ToolInputs;\n outputType: string;\n execute: (args: Record<string, unknown>) => Promise<unknown>;\n toCodePrompt: () => string;\n toOpenAITool: () => OpenAIToolDefinition;\n}\n\nexport interface Model {\n modelId: string;\n generate: (\n messages: ChatMessage[],\n options?: GenerateOptions\n ) => Promise<ChatMessage>;\n generateStream?: (\n messages: ChatMessage[],\n options?: GenerateOptions\n ) => AsyncGenerator<string, ChatMessage, undefined>;\n}\n\n// Generation options\nexport interface GenerateOptions {\n stopSequences?: string[];\n maxTokens?: number;\n temperature?: number;\n tools?: Tool[];\n toolDefinitions?: OpenAIToolDefinition[];\n}\n\n// YAML agent definition\nexport interface YAMLAgentDefinition {\n name: string;\n type: 'ToolUseAgent' | 'CodeAgent';\n description?: string;\n model?: YAMLModelDefinition;\n tools?: string[];\n agents?: string[];\n maxSteps?: number;\n maxTokens?: number;\n temperature?: number;\n persistent?: boolean;\n maxContextLength?: number;\n memoryStrategy?: MemoryStrategy;\n customInstructions?: string;\n systemPrompt?: string;\n}\n\n// YAML model definition\nexport interface YAMLModelDefinition {\n modelId?: string;\n baseUrl?: string;\n apiKey?: string;\n maxTokens?: number;\n temperature?: number;\n timeout?: number;\n}\n\n// YAML workflow definition\nexport interface YAMLWorkflowDefinition {\n name: string;\n description?: string;\n model?: YAMLModelDefinition;\n tools?: Record<string, YAMLToolDefinition>;\n agents?: Record<string, YAMLAgentDefinition>;\n entrypoint: string;\n globalMaxContextLength?: number;\n}\n\n// YAML tool definition\nexport interface YAMLToolDefinition {\n type: string;\n config?: Record<string, unknown>;\n}\n\n// Orchestrator event\nexport interface OrchestratorEvent {\n type: 'agent_start' | 'agent_step' | 'agent_tool_call' | 'agent_observation' | 'agent_end' | 'agent_error';\n agentName: string;\n depth: number;\n data: unknown;\n timestamp: number;\n}\n\n// ============================================\n// JSON Output Types (for structured CLI output)\n// ============================================\n\nexport type JSONEventType =\n | 'run_start'\n | 'workflow_loaded'\n | 'agent_start'\n | 'agent_step'\n | 'agent_thinking'\n | 'agent_tool_call'\n | 'agent_tool_result'\n | 'agent_observation'\n | 'agent_end'\n | 'run_end'\n | 'error'\n | 'log';\n\n// Base JSON event structure\nexport interface JSONEventBase {\n runId: string;\n timestamp: number;\n type: JSONEventType;\n}\n\n// Run lifecycle events\nexport interface JSONRunStartEvent extends JSONEventBase {\n type: 'run_start';\n data: {\n workflowPath: string;\n task: string;\n cwd?: string;\n };\n}\n\nexport interface JSONWorkflowLoadedEvent extends JSONEventBase {\n type: 'workflow_loaded';\n data: {\n name: string;\n description?: string;\n agents: string[];\n tools: string[];\n entrypoint: string;\n };\n}\n\nexport interface JSONRunEndEvent extends JSONEventBase {\n type: 'run_end';\n data: {\n success: boolean;\n output: unknown;\n totalDuration: number;\n totalTokens: number;\n totalSteps: number;\n };\n}\n\n// Agent lifecycle events\nexport interface JSONAgentStartEvent extends JSONEventBase {\n type: 'agent_start';\n agentName: string;\n depth: number;\n data: {\n task: string;\n agentType: 'CodeAgent' | 'ToolUseAgent';\n maxSteps: number;\n };\n}\n\nexport interface JSONAgentEndEvent extends JSONEventBase {\n type: 'agent_end';\n agentName: string;\n depth: number;\n data: {\n output: unknown;\n totalSteps: number;\n tokenUsage: TokenUsage;\n duration: number;\n success: boolean;\n };\n}\n\n// Step events\nexport interface JSONAgentStepEvent extends JSONEventBase {\n type: 'agent_step';\n agentName: string;\n depth: number;\n data: {\n stepNumber: number;\n maxSteps: number;\n phase: 'start' | 'thinking' | 'acting' | 'complete';\n };\n}\n\nexport interface JSONAgentThinkingEvent extends JSONEventBase {\n type: 'agent_thinking';\n agentName: string;\n depth: number;\n data: {\n stepNumber: number;\n content: string;\n isPartial?: boolean;\n };\n}\n\n// Tool events\nexport interface JSONAgentToolCallEvent extends JSONEventBase {\n type: 'agent_tool_call';\n agentName: string;\n depth: number;\n data: {\n stepNumber: number;\n toolCallId: string;\n toolName: string;\n arguments: Record<string, unknown>;\n };\n}\n\nexport interface JSONAgentToolResultEvent extends JSONEventBase {\n type: 'agent_tool_result';\n agentName: string;\n depth: number;\n data: {\n stepNumber: number;\n toolCallId: string;\n toolName: string;\n result: unknown;\n error?: string;\n duration: number;\n };\n}\n\n// Observation event (for CodeAgent)\nexport interface JSONAgentObservationEvent extends JSONEventBase {\n type: 'agent_observation';\n agentName: string;\n depth: number;\n data: {\n stepNumber: number;\n observation: string;\n codeAction?: string;\n logs?: string;\n };\n}\n\n// Error event\nexport interface JSONErrorEvent extends JSONEventBase {\n type: 'error';\n agentName?: string;\n depth?: number;\n data: {\n message: string;\n stack?: string;\n stepNumber?: number;\n };\n}\n\n// Log event (for non-structured output)\nexport interface JSONLogEvent extends JSONEventBase {\n type: 'log';\n data: {\n level: 'info' | 'warn' | 'error' | 'debug';\n message: string;\n };\n}\n\n// Union type of all JSON events\nexport type JSONEvent =\n | JSONRunStartEvent\n | JSONWorkflowLoadedEvent\n | JSONRunEndEvent\n | JSONAgentStartEvent\n | JSONAgentEndEvent\n | JSONAgentStepEvent\n | JSONAgentThinkingEvent\n | JSONAgentToolCallEvent\n | JSONAgentToolResultEvent\n | JSONAgentObservationEvent\n | JSONErrorEvent\n | JSONLogEvent;\n\n// Output format configuration\nexport type OutputFormat = 'text' | 'json';\n","/**\n * AgentMemory - Tracks agent execution history with context management\n */\n\nimport type {\n MemoryStep,\n SystemPromptStep,\n TaskStep,\n ActionStep,\n FinalAnswerStep,\n ChatMessage,\n TokenUsage,\n MemoryStrategy,\n Model,\n} from '../types.js';\n\nexport interface MemoryConfig {\n maxContextLength?: number;\n memoryStrategy?: MemoryStrategy;\n model?: Model;\n}\n\n// Rough token estimation: ~4 chars per token on average\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nfunction estimateMessagesTokens(messages: ChatMessage[]): number {\n let total = 0;\n for (const msg of messages) {\n total += estimateTokens(msg.content ?? '');\n if (msg.toolCalls) {\n total += estimateTokens(JSON.stringify(msg.toolCalls));\n }\n total += 4; // overhead per message (role, etc.)\n }\n return total;\n}\n\nexport class AgentMemory {\n /** System prompt step (always first) */\n systemPrompt: SystemPromptStep;\n\n /** All execution steps */\n steps: (TaskStep | ActionStep | FinalAnswerStep)[] = [];\n\n private maxContextLength: number;\n private memoryStrategy: MemoryStrategy;\n private model?: Model;\n\n constructor(systemPrompt: string, config?: MemoryConfig) {\n this.systemPrompt = {\n type: 'system',\n content: systemPrompt,\n timestamp: Date.now(),\n };\n this.maxContextLength = config?.maxContextLength ?? 100000;\n this.memoryStrategy = config?.memoryStrategy ?? 'truncate';\n this.model = config?.model;\n }\n\n /** Reset memory, keeping only the system prompt */\n reset(): void {\n this.steps = [];\n }\n\n /** Add a task step */\n addTask(task: string): TaskStep {\n const step: TaskStep = {\n type: 'task',\n task,\n timestamp: Date.now(),\n };\n this.steps.push(step);\n return step;\n }\n\n /** Create a new action step */\n createActionStep(stepNumber: number): ActionStep {\n const step: ActionStep = {\n type: 'action',\n stepNumber,\n timing: { startTime: Date.now() },\n modelInputMessages: [],\n timestamp: Date.now(),\n };\n this.steps.push(step);\n return step;\n }\n\n /** Add a final answer step */\n addFinalAnswer(answer: unknown): FinalAnswerStep {\n const step: FinalAnswerStep = {\n type: 'final',\n answer,\n timestamp: Date.now(),\n };\n this.steps.push(step);\n return step;\n }\n\n /** Get the last step */\n getLastStep(): MemoryStep | undefined {\n return this.steps[this.steps.length - 1];\n }\n\n /** Get all action steps */\n getActionSteps(): ActionStep[] {\n return this.steps.filter((s): s is ActionStep => s.type === 'action');\n }\n\n /**\n * Convert memory to messages for LLM context.\n * Handles both CodeAgent (observation-based) and ToolUseAgent (tool_call-based) patterns.\n */\n toMessages(): ChatMessage[] {\n const messages: ChatMessage[] = [];\n\n // System prompt\n messages.push({\n role: 'system',\n content: this.systemPrompt.content,\n });\n\n for (const step of this.steps) {\n switch (step.type) {\n case 'task':\n messages.push({\n role: 'user',\n content: `Task: ${step.task}`,\n });\n break;\n\n case 'action':\n // Assistant response with tool calls (ToolUseAgent)\n if (step.toolCalls && step.toolCalls.length > 0) {\n messages.push({\n role: 'assistant',\n content: step.modelOutputMessage?.content ?? null,\n toolCalls: step.toolCalls,\n });\n\n // Add tool results\n if (step.toolResults) {\n for (const result of step.toolResults) {\n messages.push({\n role: 'tool',\n content: result.error\n ? `Error: ${result.error}`\n : typeof result.result === 'string'\n ? result.result\n : JSON.stringify(result.result, null, 2),\n toolCallId: result.toolCallId,\n });\n }\n }\n } else {\n // CodeAgent pattern: assistant message + observation\n if (step.modelOutputMessage) {\n messages.push({\n role: 'assistant',\n content: step.modelOutputMessage.content,\n });\n }\n\n if (step.observation) {\n messages.push({\n role: 'user',\n content: step.observation,\n });\n }\n\n if (step.error && !step.observation) {\n messages.push({\n role: 'user',\n content: `Error: ${step.error.message}`,\n });\n }\n }\n break;\n\n case 'final':\n break;\n }\n }\n\n return messages;\n }\n\n /**\n * Manage context length - truncate or compact if exceeded.\n */\n async manageContext(): Promise<void> {\n const messages = this.toMessages();\n const tokenCount = estimateMessagesTokens(messages);\n\n if (tokenCount <= this.maxContextLength) {\n return;\n }\n\n if (this.memoryStrategy === 'truncate') {\n this.truncateOlderMessages();\n } else if (this.memoryStrategy === 'compact') {\n await this.compactMessages();\n }\n }\n\n /**\n * Truncate older action steps to fit within context.\n */\n private truncateOlderMessages(): void {\n // Keep system prompt, task, and recent steps\n const actionSteps = this.getActionSteps();\n if (actionSteps.length <= 2) return;\n\n // Remove oldest action steps until we fit\n const targetTokens = this.maxContextLength * 0.75;\n let currentTokens = estimateMessagesTokens(this.toMessages());\n\n while (currentTokens > targetTokens && this.steps.length > 2) {\n // Find first action step and remove it\n const idx = this.steps.findIndex(s => s.type === 'action');\n if (idx === -1) break;\n this.steps.splice(idx, 1);\n currentTokens = estimateMessagesTokens(this.toMessages());\n }\n }\n\n /**\n * Compact older messages into a summary.\n */\n private async compactMessages(): Promise<void> {\n if (!this.model) {\n // Fall back to truncation if no model available\n this.truncateOlderMessages();\n return;\n }\n\n const actionSteps = this.getActionSteps();\n if (actionSteps.length <= 2) return;\n\n // Summarize older steps\n const stepsToSummarize = actionSteps.slice(0, -2);\n const summaryContent = stepsToSummarize.map(step => {\n const parts: string[] = [];\n if (step.modelOutputMessage?.content) {\n parts.push(`Action: ${step.modelOutputMessage.content.slice(0, 200)}`);\n }\n if (step.observation) {\n parts.push(`Observation: ${step.observation.slice(0, 200)}`);\n }\n if (step.toolResults) {\n for (const r of step.toolResults) {\n const resultStr = typeof r.result === 'string' ? r.result : JSON.stringify(r.result);\n parts.push(`Tool ${r.toolName}: ${resultStr.slice(0, 200)}`);\n }\n }\n return parts.join('\\n');\n }).join('\\n---\\n');\n\n try {\n const summaryResponse = await this.model.generate([\n {\n role: 'system',\n content: 'Summarize the following agent execution history concisely, preserving key findings and results. Be brief but complete.',\n },\n {\n role: 'user',\n content: summaryContent,\n },\n ]);\n\n // Remove the summarized steps and replace with a summary task step\n const recentSteps = this.steps.filter(s =>\n s.type === 'task' || s.type === 'final' ||\n (s.type === 'action' && actionSteps.indexOf(s) >= actionSteps.length - 2)\n );\n\n this.steps = [\n {\n type: 'task' as const,\n task: `[Context Summary from previous steps]\\n${summaryResponse.content}`,\n timestamp: Date.now(),\n },\n ...recentSteps,\n ];\n } catch {\n // Fall back to truncation\n this.truncateOlderMessages();\n }\n }\n\n /** Get total token usage across all steps */\n getTotalTokenUsage(): TokenUsage {\n let inputTokens = 0;\n let outputTokens = 0;\n\n for (const step of this.steps) {\n if (step.type === 'action' && step.tokenUsage) {\n inputTokens += step.tokenUsage.inputTokens;\n outputTokens += step.tokenUsage.outputTokens;\n }\n }\n\n return {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n };\n }\n\n /** Get current estimated token count */\n getEstimatedTokenCount(): number {\n return estimateMessagesTokens(this.toMessages());\n }\n\n /** Get a summary of the memory for logging */\n getSummary(): string {\n const actionSteps = this.getActionSteps();\n const lines = [\n `System Prompt: ${this.systemPrompt.content.slice(0, 100)}...`,\n `Total Steps: ${this.steps.length}`,\n `Action Steps: ${actionSteps.length}`,\n ];\n\n const tokenUsage = this.getTotalTokenUsage();\n if (tokenUsage.totalTokens > 0) {\n lines.push(`Total Tokens: ${tokenUsage.totalTokens}`);\n }\n\n return lines.join('\\n');\n }\n\n /** Serialize memory to JSON */\n toJSON(): Record<string, unknown> {\n return {\n systemPrompt: this.systemPrompt,\n steps: this.steps,\n };\n }\n}\n","/**\n * AgentLogger - Color-coded console logging for agent execution\n *\n * Provides formatted output with different colors for:\n * - Headers (cyan)\n * - Reasoning/Thoughts (yellow)\n * - Code blocks (green)\n * - Output/Results (blue)\n * - Errors (red)\n */\n\nimport chalk from 'chalk';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { LogLevel } from '../types.js';\n\n// Log file directory\nconst LOG_DIR = path.join(os.homedir(), '.smol-js/logs');\n\nexport class AgentLogger {\n private level: LogLevel;\n private logFile?: fs.WriteStream;\n private sessionId: string;\n\n constructor(level: LogLevel = LogLevel.INFO) {\n this.level = level;\n this.sessionId = this.generateSessionId();\n\n // Initialize log file if logging is enabled\n if (level > LogLevel.OFF) {\n this.initLogFile();\n }\n }\n\n /**\n * Generate a unique session ID.\n */\n private generateSessionId(): string {\n const now = new Date();\n const timestamp = now.toISOString().replace(/[:.]/g, '-');\n return `session-${timestamp}`;\n }\n\n /**\n * Initialize the log file.\n */\n private initLogFile(): void {\n try {\n // Create log directory if it doesn't exist\n if (!fs.existsSync(LOG_DIR)) {\n fs.mkdirSync(LOG_DIR, { recursive: true });\n }\n\n const logPath = path.join(LOG_DIR, `${this.sessionId}.log`);\n this.logFile = fs.createWriteStream(logPath, { flags: 'a' });\n\n this.writeToFile(`=== Session Started: ${new Date().toISOString()} ===\\n\\n`);\n } catch (error) {\n console.warn('Could not create log file:', (error as Error).message);\n }\n }\n\n /**\n * Write to the log file.\n */\n private writeToFile(content: string): void {\n if (this.logFile) {\n // Strip ANSI codes for file output\n // eslint-disable-next-line no-control-regex\n const cleanContent = content.replace(/\\x1b\\[[0-9;]*m/g, '');\n this.logFile.write(cleanContent);\n }\n }\n\n /**\n * Set the log level.\n */\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n\n /**\n * Log a header (task start, step start, etc.)\n */\n header(message: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const line = '═'.repeat(60);\n const output = `\\n${chalk.cyan(line)}\\n${chalk.cyan.bold(message)}\\n${chalk.cyan(line)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n${'═'.repeat(60)}\\n${message}\\n${'═'.repeat(60)}\\n`);\n }\n\n /**\n * Log a subheader.\n */\n subheader(message: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `\\n${chalk.cyan('─'.repeat(40))}\\n${chalk.cyan(message)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n${'─'.repeat(40)}\\n${message}\\n`);\n }\n\n /**\n * Log reasoning/thought from the agent.\n */\n reasoning(content: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.yellow.bold('💭 Reasoning:')}\\n${chalk.yellow(content)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n💭 Reasoning:\\n${content}\\n`);\n }\n\n /**\n * Log code block.\n */\n code(content: string, language: string = 'javascript', level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.green.bold('📝 Code:')}\\n${chalk.green('```' + language)}\\n${chalk.green(content)}\\n${chalk.green('```')}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n📝 Code:\\n\\`\\`\\`${language}\\n${content}\\n\\`\\`\\`\\n`);\n }\n\n /**\n * Log execution output.\n */\n output(content: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.blue.bold('📤 Output:')}\\n${chalk.blue(content)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n📤 Output:\\n${content}\\n`);\n }\n\n /**\n * Log execution logs (print statements).\n */\n logs(content: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level || !content.trim()) return;\n\n const output = `${chalk.gray.bold('📋 Logs:')}\\n${chalk.gray(content)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n📋 Logs:\\n${content}\\n`);\n }\n\n /**\n * Log an error.\n */\n error(message: string, error?: Error, level: LogLevel = LogLevel.ERROR): void {\n if (this.level < level) return;\n\n const errorMessage = error ? `${message}: ${error.message}` : message;\n const output = `${chalk.red.bold('❌ Error:')}\\n${chalk.red(errorMessage)}\\n`;\n\n console.error(output);\n this.writeToFile(`\\n❌ Error:\\n${errorMessage}\\n`);\n\n if (error?.stack && this.level >= LogLevel.DEBUG) {\n console.error(chalk.red.dim(error.stack));\n this.writeToFile(`Stack: ${error.stack}\\n`);\n }\n }\n\n /**\n * Log a warning.\n */\n warn(message: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.yellow.bold('⚠️ Warning:')} ${chalk.yellow(message)}\\n`;\n\n console.warn(output);\n this.writeToFile(`\\n⚠️ Warning: ${message}\\n`);\n }\n\n /**\n * Log general info.\n */\n info(message: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.white(message)}`;\n\n console.log(output);\n this.writeToFile(`${message}\\n`);\n }\n\n /**\n * Log debug info.\n */\n debug(message: string): void {\n if (this.level < LogLevel.DEBUG) return;\n\n const output = `${chalk.dim('[DEBUG]')} ${chalk.dim(message)}`;\n\n console.log(output);\n this.writeToFile(`[DEBUG] ${message}\\n`);\n }\n\n /**\n * Log final answer.\n */\n finalAnswer(answer: unknown, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const line = '═'.repeat(60);\n const answerStr = typeof answer === 'string' ? answer : JSON.stringify(answer, null, 2);\n const output = `\\n${chalk.magenta(line)}\\n${chalk.magenta.bold('✅ Final Answer:')}\\n${chalk.magenta(answerStr)}\\n${chalk.magenta(line)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n${'═'.repeat(60)}\\n✅ Final Answer:\\n${answerStr}\\n${'═'.repeat(60)}\\n`);\n }\n\n /**\n * Log step progress.\n */\n stepProgress(current: number, max: number, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.cyan.bold(`\\n🔄 Step ${current}/${max}`)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n🔄 Step ${current}/${max}\\n`);\n }\n\n /**\n * Log waiting message for code execution delay.\n */\n waiting(seconds: number, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.yellow(`⏳ Waiting ${seconds}s before code execution (Ctrl+C to abort)...`)}`;\n\n console.log(output);\n this.writeToFile(`⏳ Waiting ${seconds}s before code execution...\\n`);\n }\n\n /**\n * Stream content character by character.\n */\n streamChar(char: string): void {\n if (this.level < LogLevel.INFO) return;\n process.stdout.write(chalk.yellow(char));\n }\n\n /**\n * End streaming (add newline).\n */\n streamEnd(): void {\n if (this.level < LogLevel.INFO) return;\n console.log();\n }\n\n /**\n * Close the log file.\n */\n close(): void {\n if (this.logFile) {\n this.writeToFile(`\\n=== Session Ended: ${new Date().toISOString()} ===\\n`);\n this.logFile.end();\n }\n }\n\n /**\n * Get the log file path.\n */\n getLogPath(): string | undefined {\n return this.logFile ? path.join(LOG_DIR, `${this.sessionId}.log`) : undefined;\n }\n}\n","/**\n * Agent - Abstract base class for all agents\n *\n * Provides the foundation for multi-step agents that follow the ReAct framework.\n * Extend this class to create specific agent implementations.\n */\n\nimport type {\n ActionStep,\n RunResult,\n LogLevel,\n ActionOutput,\n MemoryStrategy,\n} from '../types.js';\nimport { Tool } from '../tools/Tool.js';\nimport { Model } from '../models/Model.js';\nimport { AgentMemory } from '../memory/AgentMemory.js';\nimport { AgentLogger } from '../logging/AgentLogger.js';\nimport { LogLevel as LogLevelEnum } from '../types.js';\n\n// Default global max context length (in tokens, estimated)\nconst DEFAULT_MAX_CONTEXT_LENGTH = 100000;\n\nexport interface AgentConfig {\n /** The LLM model to use for generation */\n model: Model;\n\n /** Tools available to the agent */\n tools?: Tool[];\n\n /** Maximum number of steps before stopping (default: 20) */\n maxSteps?: number;\n\n /** Delay in ms before executing code (default: 5000) */\n codeExecutionDelay?: number;\n\n /** Custom instructions appended to system prompt */\n customInstructions?: string;\n\n /** Log level for output (default: INFO) */\n verboseLevel?: LogLevel;\n\n /** Whether to stream model outputs (default: true) */\n streamOutputs?: boolean;\n\n /** Whether the agent retains memory between run() calls (default: false) */\n persistent?: boolean;\n\n /** Max context length in tokens (default: 100000) */\n maxContextLength?: number;\n\n /** Memory management strategy when context is exceeded (default: 'truncate') */\n memoryStrategy?: MemoryStrategy;\n\n /** Max tokens for generation (passed to model if set) */\n maxTokens?: number;\n\n /** Temperature for generation (passed to model if set) */\n temperature?: number;\n\n /** Agent name for logging */\n name?: string;\n\n /** Callback for orchestration events */\n onEvent?: (event: { type: string; data: unknown }) => void;\n}\n\nexport abstract class Agent {\n /** The LLM model for generation */\n protected model: Model;\n\n /** Available tools mapped by name */\n protected tools: Map<string, Tool> = new Map();\n\n /** Agent memory tracking all steps */\n protected memory!: AgentMemory;\n\n /** Logger for formatted output */\n protected logger: AgentLogger;\n\n /** Configuration options */\n protected config: {\n maxSteps: number;\n codeExecutionDelay: number;\n customInstructions: string;\n verboseLevel: LogLevel;\n streamOutputs: boolean;\n persistent: boolean;\n maxContextLength: number;\n memoryStrategy: MemoryStrategy;\n maxTokens?: number;\n temperature?: number;\n name: string;\n onEvent?: (event: { type: string; data: unknown }) => void;\n };\n\n /** Current step number */\n protected currentStep: number = 0;\n\n /** Whether the agent is currently running */\n protected isRunning: boolean = false;\n\n /** Whether the agent has been initialized at least once */\n private initialized: boolean = false;\n\n constructor(config: AgentConfig) {\n this.model = config.model;\n this.logger = new AgentLogger(config.verboseLevel ?? LogLevelEnum.INFO);\n\n this.config = {\n maxSteps: config.maxSteps ?? 20,\n codeExecutionDelay: config.codeExecutionDelay ?? 5000,\n customInstructions: config.customInstructions ?? '',\n verboseLevel: config.verboseLevel ?? LogLevelEnum.INFO,\n streamOutputs: config.streamOutputs ?? true,\n persistent: config.persistent ?? false,\n maxContextLength: config.maxContextLength ?? DEFAULT_MAX_CONTEXT_LENGTH,\n memoryStrategy: config.memoryStrategy ?? 'truncate',\n maxTokens: config.maxTokens,\n temperature: config.temperature,\n name: config.name ?? 'Agent',\n onEvent: config.onEvent,\n };\n\n // Register tools\n if (config.tools) {\n for (const tool of config.tools) {\n this.tools.set(tool.name, tool);\n }\n }\n }\n\n /**\n * Initialize the system prompt for the agent.\n * Must be implemented by subclasses.\n */\n protected abstract initializeSystemPrompt(): string;\n\n /**\n * Execute a single step in the agent loop.\n * Must be implemented by subclasses.\n */\n protected abstract executeStep(memoryStep: ActionStep): Promise<ActionOutput>;\n\n /**\n * Run the agent on a task.\n */\n async run(task: string, reset: boolean = true): Promise<RunResult> {\n const startTime = Date.now();\n\n // For persistent agents, only reset if explicitly requested or first run\n const shouldReset = !this.config.persistent ? (reset || !this.memory) : (!this.initialized);\n\n if (shouldReset) {\n const systemPrompt = this.initializeSystemPrompt();\n this.memory = new AgentMemory(systemPrompt, {\n maxContextLength: this.config.maxContextLength,\n memoryStrategy: this.config.memoryStrategy,\n model: this.model,\n });\n this.currentStep = 0;\n this.initialized = true;\n }\n\n // Add task to memory\n this.memory.addTask(task);\n\n this.isRunning = true;\n this.emitEvent('agent_start', { task, name: this.config.name });\n this.logger.header(`Starting ${this.config.name}: ${task.slice(0, 80)}${task.length > 80 ? '...' : ''}`);\n\n let finalOutput: unknown = null;\n let isFinalAnswer = false;\n\n try {\n while (this.currentStep < this.config.maxSteps && this.isRunning) {\n this.currentStep++;\n this.logger.stepProgress(this.currentStep, this.config.maxSteps);\n this.emitEvent('agent_step', { step: this.currentStep, maxSteps: this.config.maxSteps });\n\n const memoryStep = this.memory.createActionStep(this.currentStep);\n\n try {\n const actionOutput = await this.executeStep(memoryStep);\n\n memoryStep.timing.endTime = Date.now();\n memoryStep.timing.duration = memoryStep.timing.endTime - memoryStep.timing.startTime;\n memoryStep.actionOutput = actionOutput;\n memoryStep.isFinalAnswer = actionOutput.isFinalAnswer;\n\n if (actionOutput.isFinalAnswer) {\n finalOutput = actionOutput.output;\n isFinalAnswer = true;\n this.logger.finalAnswer(finalOutput);\n break;\n }\n } catch (error) {\n memoryStep.error = error as Error;\n memoryStep.timing.endTime = Date.now();\n memoryStep.timing.duration = memoryStep.timing.endTime - memoryStep.timing.startTime;\n this.logger.error('Step execution failed', error as Error);\n this.emitEvent('agent_error', { error: (error as Error).message, step: this.currentStep });\n }\n\n // Check and manage context length after each step\n await this.memory.manageContext();\n }\n\n if (!isFinalAnswer && this.currentStep >= this.config.maxSteps) {\n this.logger.warn(`Max steps (${this.config.maxSteps}) reached without final answer`);\n finalOutput = await this.provideFinalAnswer(task);\n }\n } finally {\n this.isRunning = false;\n }\n\n const duration = Date.now() - startTime;\n const tokenUsage = this.memory.getTotalTokenUsage();\n\n this.memory.addFinalAnswer(finalOutput);\n this.emitEvent('agent_end', { output: finalOutput, duration, tokenUsage });\n\n this.logger.info(`\\nTotal time: ${(duration / 1000).toFixed(2)}s`);\n this.logger.info(`Total tokens: ${tokenUsage.totalTokens}`);\n\n return {\n output: finalOutput,\n steps: this.memory.steps,\n tokenUsage,\n duration,\n };\n }\n\n /**\n * Generate a final answer when max steps is reached.\n */\n protected async provideFinalAnswer(task: string): Promise<unknown> {\n this.logger.subheader('Generating final answer from accumulated context');\n\n const messages = this.memory.toMessages();\n messages.push({\n role: 'user',\n content: `You have reached the maximum number of steps. Based on your work so far, provide the best answer you can for the original task: \"${task}\". Summarize what you accomplished and provide a final answer.`,\n });\n\n const response = await this.model.generate(messages, {\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n });\n\n return response.content;\n }\n\n /** Emit an orchestration event */\n protected emitEvent(type: string, data: unknown): void {\n if (this.config.onEvent) {\n this.config.onEvent({ type, data });\n }\n }\n\n /** Stop the agent */\n stop(): void {\n this.isRunning = false;\n this.logger.info('Agent stopped by user');\n }\n\n /** Get the current memory */\n getMemory(): AgentMemory {\n return this.memory;\n }\n\n /** Get registered tools */\n getTools(): Map<string, Tool> {\n return this.tools;\n }\n\n /** Add a tool to the agent */\n addTool(tool: Tool): void {\n this.tools.set(tool.name, tool);\n }\n\n /** Remove a tool from the agent */\n removeTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /** Get agent name */\n getName(): string {\n return this.config.name;\n }\n\n /** Get agent type identifier */\n getType(): string {\n return this.constructor.name;\n }\n\n /** Get max steps configuration */\n getMaxSteps(): number {\n return this.config.maxSteps;\n }\n\n /** Set the event callback (useful for orchestration) */\n setOnEvent(callback: (event: { type: string; data: unknown }) => void): void {\n this.config.onEvent = callback;\n }\n\n /** Sleep for a specified duration */\n protected sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * LocalExecutor - JavaScript code execution engine using Node's vm module\n *\n * Executes JavaScript code chunks in an isolated context with:\n * - State persistence between steps (variables carry forward)\n * - Tool injection (tools available as async functions)\n * - Dynamic imports via CDN (esm.sh)\n * - Print capture and logging\n * - Safety timeouts\n */\n\nimport * as vm from 'vm';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport type { CodeExecutionOutput } from '../types.js';\nimport { Tool as ToolClass } from '../tools/Tool.js';\n\n// Default timeout for code execution (30 seconds)\nconst DEFAULT_TIMEOUT_MS = 30000;\n\n// Maximum length of captured output\nconst MAX_OUTPUT_LENGTH = 50000;\n\n// Package cache directory\nconst PACKAGE_CACHE_DIR = path.join(os.homedir(), '.smol-js', 'packages');\n\nexport interface ExecutorConfig {\n /**\n * Maximum execution time in milliseconds\n * @default 30000\n */\n timeout?: number;\n\n /**\n * Additional authorized imports (npm packages to allow)\n */\n authorizedImports?: string[];\n\n /**\n * Whether to allow fs module access\n * @default true\n */\n allowFs?: boolean;\n\n /**\n * Working directory for fs operations\n */\n workingDirectory?: string;\n}\n\nexport class LocalExecutor {\n private context: vm.Context;\n private state: Record<string, unknown> = {};\n private tools: Map<string, ToolClass> = new Map();\n private config: ExecutorConfig;\n private capturedLogs: string[] = [];\n\n constructor(config: ExecutorConfig = {}) {\n this.config = {\n timeout: DEFAULT_TIMEOUT_MS,\n allowFs: true,\n workingDirectory: process.cwd(),\n ...config,\n };\n\n this.context = this.createContext();\n }\n\n /**\n * Create the VM context with available globals.\n */\n private createContext(): vm.Context {\n // Create a proxy for console to capture logs\n const consoleProxy = {\n log: (...args: unknown[]) => {\n const output = args.map((arg) => this.stringify(arg)).join(' ');\n this.capturedLogs.push(output);\n },\n error: (...args: unknown[]) => {\n const output = args.map((arg) => this.stringify(arg)).join(' ');\n this.capturedLogs.push(`[ERROR] ${output}`);\n },\n warn: (...args: unknown[]) => {\n const output = args.map((arg) => this.stringify(arg)).join(' ');\n this.capturedLogs.push(`[WARN] ${output}`);\n },\n info: (...args: unknown[]) => {\n const output = args.map((arg) => this.stringify(arg)).join(' ');\n this.capturedLogs.push(output);\n },\n debug: (...args: unknown[]) => {\n const output = args.map((arg) => this.stringify(arg)).join(' ');\n this.capturedLogs.push(`[DEBUG] ${output}`);\n },\n };\n\n // Create print function (alias for console.log)\n const print = (...args: unknown[]) => consoleProxy.log(...args);\n\n // Create dynamic import function for npm packages\n const dynamicImport = async (packageName: string): Promise<unknown> => {\n // Check if it's an authorized import\n const authorized = this.config.authorizedImports ?? [];\n const basePackage = packageName.split('/')[0];\n\n if (!authorized.includes(basePackage) && !authorized.includes(packageName)) {\n throw new Error(\n `Import not authorized: ${packageName}. Add it to authorizedImports to allow.`\n );\n }\n\n try {\n // Ensure cache directory exists\n if (!fs.existsSync(PACKAGE_CACHE_DIR)) {\n fs.mkdirSync(PACKAGE_CACHE_DIR, { recursive: true });\n }\n\n // Create a safe filename from package name\n const safeFileName = packageName.replace(/[/@]/g, '_') + '.mjs';\n const cachedPath = path.join(PACKAGE_CACHE_DIR, safeFileName);\n\n // Check if already cached and valid (not a redirect stub)\n let needsFetch = !fs.existsSync(cachedPath);\n if (!needsFetch) {\n const content = fs.readFileSync(cachedPath, 'utf-8');\n // Check if it's a redirect stub that needs resolution\n if (content.includes('export * from \"/') || content.includes(\"export * from '/\")) {\n needsFetch = true;\n fs.unlinkSync(cachedPath); // Remove invalid cache\n }\n }\n\n if (needsFetch) {\n this.capturedLogs.push(`[import] Fetching ${packageName}...`);\n\n // First, get the package info to find the actual bundle URL\n // Use jsdelivr which provides proper ESM bundles\n const jsdelivrUrl = `https://cdn.jsdelivr.net/npm/${packageName}/+esm`;\n\n const response = await fetch(jsdelivrUrl);\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n let code = await response.text();\n\n // jsdelivr ESM bundles may have imports from jsdelivr - rewrite them to be fetched too\n // For now, we'll inline simple packages. Complex packages with many deps may need more work.\n\n // Check if there are external imports we need to resolve\n const importMatches = code.matchAll(/from\\s+[\"'](https:\\/\\/cdn\\.jsdelivr\\.net\\/[^\"']+)[\"']/g);\n for (const match of importMatches) {\n const depUrl = match[1];\n const depName = depUrl.split('/npm/')[1]?.split('/')[0] || 'dep';\n const depFileName = depName.replace(/[/@]/g, '_') + '_dep.mjs';\n const depCachedPath = path.join(PACKAGE_CACHE_DIR, depFileName);\n\n if (!fs.existsSync(depCachedPath)) {\n this.capturedLogs.push(`[import] Fetching dependency from ${depUrl}...`);\n const depResponse = await fetch(depUrl);\n if (depResponse.ok) {\n const depCode = await depResponse.text();\n fs.writeFileSync(depCachedPath, depCode, 'utf-8');\n }\n }\n\n // Rewrite import to use local file\n code = code.replace(depUrl, `file://${depCachedPath}`);\n }\n\n // Write to cache\n fs.writeFileSync(cachedPath, code, 'utf-8');\n this.capturedLogs.push(`[import] Cached ${packageName} to ${cachedPath}`);\n } else {\n this.capturedLogs.push(`[import] Using cached ${packageName}`);\n }\n\n // Import from local cache using file:// URL\n const fileUrl = `file://${cachedPath}`;\n const module = await import(fileUrl);\n return module.default ?? module;\n } catch (error) {\n throw new Error(`Failed to import ${packageName}: ${(error as Error).message}`);\n }\n };\n\n // Build context object\n const contextObj: Record<string, unknown> = {\n // Console and print\n console: consoleProxy,\n print,\n\n // Built-in objects\n Object,\n Array,\n String,\n Number,\n Boolean,\n Date,\n Math,\n JSON,\n RegExp,\n Error,\n Map,\n Set,\n WeakMap,\n WeakSet,\n Promise,\n Symbol,\n Proxy,\n Reflect,\n\n // Type checking\n parseInt,\n parseFloat,\n isNaN,\n isFinite,\n typeof: (v: unknown) => typeof v,\n\n // Timers (promisified for async support)\n setTimeout: global.setTimeout,\n clearTimeout: global.clearTimeout,\n setInterval: global.setInterval,\n clearInterval: global.clearInterval,\n\n // Async utilities\n fetch: global.fetch,\n\n // Dynamic import for npm packages\n importPackage: dynamicImport,\n\n // URL handling\n URL,\n URLSearchParams,\n\n // Text encoding\n TextEncoder,\n TextDecoder,\n\n // Buffer (useful for many operations)\n Buffer,\n\n // State reference (variables persist here)\n __state__: this.state,\n\n // Final answer marker\n __final_answer__: null as unknown,\n __is_final_answer__: false,\n };\n\n // Add fs module if allowed\n if (this.config.allowFs) {\n contextObj.fs = {\n readFileSync: (filePath: string, encoding?: BufferEncoding) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), filePath);\n return fs.readFileSync(resolvedPath, encoding ?? 'utf-8');\n },\n writeFileSync: (filePath: string, data: string | Buffer) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), filePath);\n return fs.writeFileSync(resolvedPath, data);\n },\n existsSync: (filePath: string) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), filePath);\n return fs.existsSync(resolvedPath);\n },\n readdirSync: (dirPath: string) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), dirPath);\n return fs.readdirSync(resolvedPath);\n },\n mkdirSync: (dirPath: string, options?: fs.MakeDirectoryOptions) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), dirPath);\n return fs.mkdirSync(resolvedPath, options);\n },\n unlinkSync: (filePath: string) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), filePath);\n return fs.unlinkSync(resolvedPath);\n },\n statSync: (filePath: string) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), filePath);\n return fs.statSync(resolvedPath);\n },\n };\n\n contextObj.path = {\n join: path.join,\n resolve: (...paths: string[]) =>\n path.resolve(this.config.workingDirectory ?? process.cwd(), ...paths),\n dirname: path.dirname,\n basename: path.basename,\n extname: path.extname,\n };\n }\n\n return vm.createContext(contextObj);\n }\n\n /**\n * Add tools to the executor context.\n */\n sendTools(tools: Record<string, ToolClass>): void {\n for (const [name, tool] of Object.entries(tools)) {\n this.tools.set(name, tool);\n\n // Add tool as async function in context\n this.context[name] = async (...args: unknown[]) => {\n // Handle both positional and named arguments\n let callArgs: Record<string, unknown>;\n\n if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null) {\n // Called with named arguments object\n callArgs = args[0] as Record<string, unknown>;\n } else {\n // Called with positional arguments - map to input names\n const inputNames = Object.keys(tool.inputs);\n callArgs = {};\n args.forEach((arg, i) => {\n if (i < inputNames.length) {\n callArgs[inputNames[i]] = arg;\n }\n });\n }\n\n return tool.call(callArgs);\n };\n }\n }\n\n /**\n * Send variables to the executor state.\n */\n sendVariables(variables: Record<string, unknown>): void {\n Object.assign(this.state, variables);\n Object.assign(this.context, variables);\n }\n\n /**\n * Execute JavaScript code and return the result.\n */\n async execute(code: string): Promise<CodeExecutionOutput> {\n // Reset captured logs\n this.capturedLogs = [];\n\n // Reset final answer flag\n this.context.__is_final_answer__ = false;\n this.context.__final_answer__ = null;\n\n // Sync state to context\n Object.assign(this.context, this.state);\n\n // Wrap code to handle async and capture the last expression\n const wrappedCode = this.wrapCode(code);\n\n try {\n // Create and run the script\n const script = new vm.Script(wrappedCode, {\n filename: 'agent-code.js',\n });\n\n // Run with timeout\n const result = await script.runInContext(this.context, {\n timeout: this.config.timeout,\n displayErrors: true,\n });\n\n // Wait for the result if it's a promise\n const output = result instanceof Promise ? await result : result;\n\n // Update state with any new variables from context\n this.updateStateFromContext();\n\n // Check if final_answer was called\n const isFinalAnswer = this.context.__is_final_answer__ as boolean;\n const finalOutput = isFinalAnswer ? this.context.__final_answer__ : output;\n\n // Truncate logs if too long\n const logs = this.capturedLogs.join('\\n').slice(0, MAX_OUTPUT_LENGTH);\n\n return {\n output: finalOutput,\n logs,\n isFinalAnswer,\n };\n } catch (error) {\n // Truncate logs if too long\n const logs = this.capturedLogs.join('\\n').slice(0, MAX_OUTPUT_LENGTH);\n\n return {\n output: null,\n logs,\n isFinalAnswer: false,\n error: error as Error,\n };\n }\n }\n\n /**\n * Wrap code to handle async execution and final_answer calls.\n */\n private wrapCode(code: string): string {\n // Add final_answer function that sets the flag\n const finalAnswerFunc = `\n function final_answer(answer) {\n __is_final_answer__ = true;\n __final_answer__ = answer;\n return answer;\n }\n `;\n\n // Wrap in async IIFE to support await\n // Store result of last expression in __last_result__\n // We use a Function constructor approach to capture the last expression value\n return `\n ${finalAnswerFunc}\n (async () => {\n let __last_result__;\n ${this.instrumentCode(code)}\n return __last_result__;\n })()\n `;\n }\n\n /**\n * Instrument code to capture the last expression value and convert\n * let/const/var declarations to global assignments for state persistence.\n */\n private instrumentCode(code: string): string {\n // Split code into lines and find statements\n const lines = code.trim().split('\\n');\n\n if (lines.length === 0) {\n return code;\n }\n\n // Process the code to capture expression results\n const processedLines = lines.map((line, index) => {\n const trimmed = line.trim();\n\n // Skip empty lines and comments\n if (!trimmed ||\n trimmed.startsWith('//') ||\n trimmed.startsWith('/*') ||\n trimmed.startsWith('*') ||\n trimmed.endsWith('*/')) {\n return line;\n }\n\n // Transform variable declarations to global assignments for persistence\n // This allows variables to persist across script executions\n // Handle multiple declarations on the same line using global replacement\n let transformed = line;\n let hasDeclaration = false;\n\n // Replace all let/const/var declarations with global assignments\n transformed = transformed.replace(\n /\\b(let|const|var)\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=/g,\n (_match, _keyword, varName) => {\n hasDeclaration = true;\n return `${varName} =`;\n }\n );\n\n // Handle declarations without initialization\n transformed = transformed.replace(\n /\\b(let|const|var)\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*(?=[;,]|$)/g,\n (_match, _keyword, varName) => {\n hasDeclaration = true;\n return `${varName} = undefined`;\n }\n );\n\n if (hasDeclaration) {\n return transformed;\n }\n\n // Skip control flow statements for last-result capture\n if (trimmed.startsWith('if') ||\n trimmed.startsWith('else') ||\n trimmed.startsWith('for') ||\n trimmed.startsWith('while') ||\n trimmed.startsWith('do') ||\n trimmed.startsWith('switch') ||\n trimmed.startsWith('case') ||\n trimmed.startsWith('default') ||\n trimmed.startsWith('try') ||\n trimmed.startsWith('catch') ||\n trimmed.startsWith('finally') ||\n trimmed.startsWith('return') ||\n trimmed.startsWith('throw') ||\n trimmed.startsWith('break') ||\n trimmed.startsWith('continue') ||\n trimmed.startsWith('function') ||\n trimmed.startsWith('class') ||\n trimmed.startsWith('import') ||\n trimmed.startsWith('export') ||\n trimmed === '{' ||\n trimmed === '}' ||\n trimmed.endsWith('{') ||\n trimmed.endsWith('}')) {\n return line;\n }\n\n // For the last meaningful line, try to capture the expression value\n if (index === lines.length - 1 || this.isLastMeaningfulLine(lines, index)) {\n // If line doesn't end with semicolon, try to capture it\n if (!trimmed.endsWith(';')) {\n return `__last_result__ = ${line}`;\n } else {\n // Remove semicolon, capture, and add it back\n const withoutSemi = trimmed.slice(0, -1);\n // Check if it looks like an expression (not ending with closing brace)\n if (!withoutSemi.endsWith('}') && !withoutSemi.endsWith(')')) {\n return `__last_result__ = ${withoutSemi};`;\n }\n }\n }\n\n return line;\n });\n\n return processedLines.join('\\n');\n }\n\n /**\n * Check if this is the last meaningful line of code.\n */\n private isLastMeaningfulLine(lines: string[], currentIndex: number): boolean {\n for (let i = currentIndex + 1; i < lines.length; i++) {\n const trimmed = lines[i].trim();\n if (trimmed && !trimmed.startsWith('//') && !trimmed.startsWith('/*')) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Update internal state from context after execution.\n */\n private updateStateFromContext(): void {\n // List of keys to exclude from state (builtins and internals)\n const excludeKeys = new Set([\n 'console',\n 'print',\n 'Object',\n 'Array',\n 'String',\n 'Number',\n 'Boolean',\n 'Date',\n 'Math',\n 'JSON',\n 'RegExp',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'Promise',\n 'Symbol',\n 'Proxy',\n 'Reflect',\n 'parseInt',\n 'parseFloat',\n 'isNaN',\n 'isFinite',\n 'typeof',\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'fetch',\n 'importPackage',\n 'URL',\n 'URLSearchParams',\n 'TextEncoder',\n 'TextDecoder',\n 'Buffer',\n '__state__',\n '__final_answer__',\n '__is_final_answer__',\n 'fs',\n 'path',\n 'final_answer',\n // Exclude tools\n ...this.tools.keys(),\n ]);\n\n // Copy non-builtin keys to state\n for (const key of Object.keys(this.context)) {\n if (!excludeKeys.has(key)) {\n this.state[key] = this.context[key];\n }\n }\n }\n\n /**\n * Stringify a value for logging.\n */\n private stringify(value: unknown): string {\n if (value === undefined) return 'undefined';\n if (value === null) return 'null';\n if (typeof value === 'string') return value;\n if (typeof value === 'function') return `[Function: ${value.name || 'anonymous'}]`;\n\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n }\n\n /**\n * Reset the executor state.\n */\n reset(): void {\n this.state = {};\n this.capturedLogs = [];\n this.context = this.createContext();\n\n // Re-add tools\n const tools = Object.fromEntries(this.tools);\n this.sendTools(tools);\n }\n\n /**\n * Get the current state.\n */\n getState(): Record<string, unknown> {\n return { ...this.state };\n }\n}\n","/**\n * Tool base class for smol-js\n *\n * Tools are the primary way for agents to interact with the outside world.\n * Extend this class and implement the execute() method to create custom tools.\n */\n\nimport type { ToolInputs, ToolInputType, OpenAIToolDefinition } from '../types.js';\n\nexport abstract class Tool {\n /**\n * Unique identifier for the tool\n */\n abstract readonly name: string;\n\n /**\n * Human-readable description of what the tool does\n */\n abstract readonly description: string;\n\n /**\n * Input parameter schema\n */\n abstract readonly inputs: ToolInputs;\n\n /**\n * Output type description\n */\n abstract readonly outputType: string;\n\n /**\n * Whether the tool has been set up\n */\n protected isSetup: boolean = false;\n\n /**\n * Optional setup method called before first use.\n * Override this for expensive initialization (loading models, etc.)\n */\n async setup(): Promise<void> {\n this.isSetup = true;\n }\n\n /**\n * Execute the tool with the given arguments.\n * Must be implemented by subclasses.\n */\n abstract execute(args: Record<string, unknown>): Promise<unknown>;\n\n /**\n * Call the tool, ensuring setup is complete and validating arguments.\n */\n async call(args: Record<string, unknown>): Promise<unknown> {\n if (!this.isSetup) {\n await this.setup();\n }\n\n // Validate arguments\n this.validateArguments(args);\n\n // Execute and return result\n return this.execute(args);\n }\n\n /**\n * Validate that provided arguments match the input schema.\n */\n protected validateArguments(args: Record<string, unknown>): void {\n const providedKeys = new Set(Object.keys(args));\n\n for (const [key, input] of Object.entries(this.inputs)) {\n // Check required arguments\n if (input.required !== false && !providedKeys.has(key)) {\n throw new Error(`Missing required argument: ${key}`);\n }\n\n // Check type if argument is provided\n if (providedKeys.has(key) && args[key] !== undefined && args[key] !== null) {\n const value = args[key];\n if (!this.checkType(value, input.type)) {\n throw new Error(\n `Argument '${key}' has invalid type. Expected ${input.type}, got ${typeof value}`\n );\n }\n }\n\n providedKeys.delete(key);\n }\n }\n\n /**\n * Check if a value matches the expected type.\n */\n protected checkType(value: unknown, expectedType: ToolInputType): boolean {\n switch (expectedType) {\n case 'string':\n return typeof value === 'string';\n case 'number':\n return typeof value === 'number';\n case 'boolean':\n return typeof value === 'boolean';\n case 'array':\n return Array.isArray(value);\n case 'object':\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n case 'any':\n return true;\n default:\n return false;\n }\n }\n\n /**\n * Generate a code-friendly prompt representation of this tool.\n * Used in the CodeAgent system prompt.\n */\n toCodePrompt(): string {\n const argsSignature = Object.entries(this.inputs)\n .map(([name, input]) => {\n const optional = input.required === false ? '?' : '';\n return `${name}${optional}: ${this.typeToJsType(input.type)}`;\n })\n .join(', ');\n\n const argsDoc = Object.entries(this.inputs)\n .map(([name, input]) => ` * @param ${name} - ${input.description}`)\n .join('\\n');\n\n return `\n/**\n * ${this.description}\n *\n${argsDoc}\n * @returns ${this.outputType}\n */\nasync function ${this.name}(${argsSignature}): Promise<${this.typeToJsType(this.outputType as ToolInputType)}> { ... }\n`.trim();\n }\n\n /**\n * Generate an OpenAI-compatible tool definition for function calling.\n */\n toOpenAITool(): OpenAIToolDefinition {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [key, input] of Object.entries(this.inputs)) {\n const prop: Record<string, unknown> = {\n type: this.typeToJsonSchemaType(input.type),\n description: input.description,\n };\n\n if (input.enum) {\n prop.enum = input.enum;\n }\n\n if (input.default !== undefined) {\n prop.default = input.default;\n }\n\n properties[key] = prop;\n\n if (input.required !== false) {\n required.push(key);\n }\n }\n\n return {\n type: 'function',\n function: {\n name: this.name,\n description: this.description,\n parameters: {\n type: 'object',\n properties,\n ...(required.length > 0 && { required }),\n },\n },\n };\n }\n\n /**\n * Convert tool input type to JSON Schema type.\n */\n protected typeToJsonSchemaType(type: ToolInputType): string {\n switch (type) {\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'array':\n return 'array';\n case 'object':\n return 'object';\n case 'any':\n return 'string';\n default:\n return 'string';\n }\n }\n\n /**\n * Convert tool input type to JS/TS type string.\n */\n protected typeToJsType(type: ToolInputType | string): string {\n switch (type) {\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'array':\n return 'any[]';\n case 'object':\n return 'Record<string, any>';\n case 'any':\n return 'any';\n default:\n return type;\n }\n }\n\n /**\n * Serialize the tool to a JSON-compatible object.\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n description: this.description,\n inputs: this.inputs,\n outputType: this.outputType,\n };\n }\n}\n\n/**\n * Helper function to create a tool from a function.\n * This is an alternative to extending the Tool class.\n */\nexport function createTool(config: {\n name: string;\n description: string;\n inputs: ToolInputs;\n outputType: string;\n execute: (args: Record<string, unknown>) => Promise<unknown>;\n}): Tool {\n return new (class extends Tool {\n readonly name = config.name;\n readonly description = config.description;\n readonly inputs = config.inputs;\n readonly outputType = config.outputType;\n\n async execute(args: Record<string, unknown>): Promise<unknown> {\n return config.execute(args);\n }\n })();\n}\n","/**\n * Default tools provided to all agents\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\n\n/**\n * FinalAnswerTool - Used by the agent to return the final answer.\n * This is always available to CodeAgent.\n */\nexport class FinalAnswerTool extends Tool {\n readonly name = 'final_answer';\n readonly description = 'Returns the final answer to the user query. Use this when you have completed the task and have the final result.';\n readonly inputs: ToolInputs = {\n answer: {\n type: 'any',\n description: 'The final answer to return. Can be any type (string, number, object, etc.)',\n required: true,\n },\n };\n readonly outputType = 'any';\n\n async execute(args: Record<string, unknown>): Promise<unknown> {\n return args.answer;\n }\n}\n\n/**\n * UserInputTool - Allows the agent to ask the user for input.\n */\nexport class UserInputTool extends Tool {\n readonly name = 'user_input';\n readonly description = 'Asks the user for additional input or clarification.';\n readonly inputs: ToolInputs = {\n question: {\n type: 'string',\n description: 'The question to ask the user',\n required: true,\n },\n };\n readonly outputType = 'string';\n\n private inputHandler?: (question: string) => Promise<string>;\n\n constructor(inputHandler?: (question: string) => Promise<string>) {\n super();\n this.inputHandler = inputHandler;\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const question = args.question as string;\n\n if (this.inputHandler) {\n return this.inputHandler(question);\n }\n\n // Default: use readline for terminal input\n const readline = await import('readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(`\\n[Agent asks]: ${question}\\nYour response: `, (answer) => {\n rl.close();\n resolve(answer);\n });\n });\n }\n}\n\n// Export singleton instances\nexport const finalAnswerTool = new FinalAnswerTool();\n","/**\n * System prompts for CodeAgent\n *\n * Adapted from smolagents Python prompts but optimized for JavaScript execution.\n */\n\nexport interface PromptVariables {\n tools: string;\n authorizedImports: string;\n customInstructions?: string;\n}\n\n/**\n * Generate the system prompt for CodeAgent.\n */\nexport function generateSystemPrompt(variables: PromptVariables): string {\n const { tools, authorizedImports, customInstructions } = variables;\n\n return `You are an expert JavaScript developer and problem-solving agent. Your role is to solve tasks by writing and executing JavaScript code step by step.\n\n## How You Work\n\nYou follow a ReAct (Reasoning + Acting) framework:\n1. **Thought**: Analyze the current situation and decide what to do next\n2. **Code**: Write JavaScript code to perform the action\n3. **Observation**: See the result of your code execution\n4. Repeat until you have the final answer\n\n## Available Tools\n\nYou have access to the following tools as async functions:\n\n${tools}\n\n## Available Imports\n\nYou can dynamically import the following npm packages using \\`await importPackage('package-name')\\`:\n${authorizedImports || '(No additional packages authorized)'}\n\n## Built-in Capabilities\n\nThe following are available in your execution environment:\n- \\`console.log()\\` / \\`print()\\` - Output text (captured in logs)\n- \\`fs\\` - File system operations (readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync)\n- \\`path\\` - Path utilities (join, resolve, dirname, basename)\n- \\`fetch()\\` - HTTP requests\n- \\`Buffer\\` - Binary data handling\n- \\`JSON\\` - JSON parsing/stringifying\n- Standard JavaScript globals (Math, Date, Array methods, etc.)\n\n## Response Format\n\nAlways respond with your thought process followed by a code block:\n\nThought: [Your reasoning about what to do]\n\n\\`\\`\\`javascript\n// Your code here\n\\`\\`\\`\n\n## Rules\n\n1. **Always use final_answer()**: When you have the complete answer, call \\`final_answer(yourResult)\\` to return it.\n\n2. **One action per step**: Execute one logical action per code block and one code block per inference step. You will be given additional steps to complete your work if it cannot be done safely in one step. Don't try to do everything at once because you need to make sure that your tools returned valid, useful data before going on to make use of that data. In particular, if you are a Manager agent who is invoking Sub-Agents as tools, do not script the entire workflow in one step, make sure that you get to review the work of your subagents at critical points before going on to the next step.\n\n3. **Handle errors gracefully**: If something fails, explain what went wrong and try a different approach.\n\n4. **Use async/await**: All tool calls and imports are async. Always use await.\n\n5. **Variables persist**: Variables you define in one step are available in the next step.\n\n6. **Be concise**: Write clean, minimal code. Don't over-engineer.\n\n7. **Print for debugging**: Use console.log() to output intermediate results you want to see.\n\n8. **No require()**: Use \\`await importPackage('name')\\` for npm packages instead of require().\n\n9. **Internet Access**: You can use fetch() to get data from the web as needed. However, if you have access to specialized tools for browsing / searching / retrieving information, use those first and fall back to fetch if they don't work\n\n## Examples\n\n### Example 1: Simple calculation\nThought: I need to calculate the sum of squares from 1 to 10.\n\n\\`\\`\\`javascript\nlet sum = 0;\nfor (let i = 1; i <= 10; i++) {\n sum += i * i;\n}\nconsole.log(\"Sum of squares:\", sum);\nfinal_answer(sum);\n\\`\\`\\`\n\n### Example 2: Using a tool\nThought: I need to search the web for current information.\n\n\\`\\`\\`javascript\nconst results = await web_search({ query: \"latest JavaScript features 2024\" });\nconsole.log(\"Search results:\", results);\n\\`\\`\\`\n\n### Example 3: Reading a file\nThought: I need to read the contents of package.json.\n\n\\`\\`\\`javascript\nconst content = fs.readFileSync('package.json', 'utf-8');\nconst pkg = JSON.parse(content);\nconsole.log(\"Package name:\", pkg.name);\nfinal_answer(pkg);\n\\`\\`\\`\n\n### Example 4: Using dynamic imports\nThought: I need to use lodash for array manipulation.\n\n\\`\\`\\`javascript\nconst _ = await importPackage('lodash');\nconst numbers = [1, 2, 3, 4, 5];\nconst chunked = _.chunk(numbers, 2);\nfinal_answer(chunked);\n\\`\\`\\`\n\n### Example 5: Multi-step task\nThought: First, I'll fetch the data from the API.\n\n\\`\\`\\`javascript\nconst response = await fetch('https://api.example.com/data');\nconst data = await response.json();\nconsole.log(\"Fetched items:\", data.length);\n\\`\\`\\`\n\n(Observation: Fetched items: 42)\n\nThought: Now I'll process the data and return the result.\n\n\\`\\`\\`javascript\nconst processed = data.filter(item => item.active).map(item => item.name);\nfinal_answer(processed);\n\\`\\`\\`\n\n${customInstructions ? `\\n## Additional Instructions\\n\\n${customInstructions}` : ''}\n\nNow, let's solve the task step by step. Remember to always call final_answer() when you have the complete answer.`;\n}\n\n/**\n * Prompt for generating a final answer when max steps is reached.\n */\nexport const FINAL_ANSWER_PROMPT = `Based on the steps you've taken so far, provide the best answer you can to the original task.\nIf you couldn't fully complete the task, explain what you accomplished and what remains to be done.\nCall final_answer() with your response.`;\n\n/**\n * Error recovery prompt.\n */\nexport function getErrorRecoveryPrompt(error: string): string {\n return `Your previous code encountered an error:\n\n${error}\n\nPlease analyze the error and try a different approach. Fix the issue and continue working on the task.`;\n}\n","/**\n * CodeAgent - Executes tasks by generating and running JavaScript code\n *\n * This is the main agent implementation for smol-js. It follows the ReAct pattern:\n * 1. Receives a task\n * 2. Generates reasoning and code\n * 3. Executes the code in a sandboxed environment\n * 4. Observes the result and continues or returns final answer\n */\n\nimport { Agent, AgentConfig } from './Agent.js';\nimport { LocalExecutor, ExecutorConfig } from '../executor/LocalExecutor.js';\nimport { FinalAnswerTool } from '../tools/defaultTools.js';\nimport { Tool } from '../tools/Tool.js';\nimport { generateSystemPrompt, getErrorRecoveryPrompt } from '../prompts/codeAgent.js';\nimport type { ActionStep, ActionOutput, ChatMessage } from '../types.js';\n\nexport interface CodeAgentConfig extends AgentConfig {\n /**\n * Additional npm packages that can be imported dynamically\n */\n additionalAuthorizedImports?: string[];\n\n /**\n * Executor configuration\n */\n executorConfig?: ExecutorConfig;\n\n /**\n * Working directory for file operations\n */\n workingDirectory?: string;\n}\n\n// Regex patterns for extracting code from LLM output\nconst CODE_BLOCK_REGEX = /```(?:javascript|js)?\\n([\\s\\S]*?)```/;\nconst THOUGHT_REGEX = /(?:Thought|Reasoning):\\s*([\\s\\S]*?)(?=```|$)/i;\n\nexport class CodeAgent extends Agent {\n /**\n * The JavaScript code executor\n */\n private executor: LocalExecutor;\n\n /**\n * Authorized imports for dynamic npm package loading\n */\n private authorizedImports: string[];\n\n constructor(config: CodeAgentConfig) {\n super(config);\n\n // Set authorized imports\n this.authorizedImports = config.additionalAuthorizedImports ?? [];\n\n // Initialize executor\n this.executor = new LocalExecutor({\n ...config.executorConfig,\n authorizedImports: this.authorizedImports,\n workingDirectory: config.workingDirectory,\n });\n\n // Always add final_answer tool\n if (!this.tools.has('final_answer')) {\n this.tools.set('final_answer', new FinalAnswerTool());\n }\n\n // Send tools to executor\n this.executor.sendTools(Object.fromEntries(this.tools));\n }\n\n /**\n * Initialize the system prompt with tool definitions.\n */\n protected initializeSystemPrompt(): string {\n // Generate tool documentation\n const toolDocs = Array.from(this.tools.values())\n .filter((tool) => tool.name !== 'final_answer') // final_answer is documented separately\n .map((tool) => tool.toCodePrompt())\n .join('\\n\\n');\n\n // Add final_answer documentation\n const finalAnswerDoc = `\n/**\n * Returns the final answer to the user. Call this when you have completed the task.\n * @param answer - The final answer (can be any type)\n */\nfunction final_answer(answer: any): void { ... }\n`.trim();\n\n const allTools = toolDocs ? `${toolDocs}\\n\\n${finalAnswerDoc}` : finalAnswerDoc;\n\n // Format authorized imports\n const importsDoc = this.authorizedImports.length > 0\n ? this.authorizedImports.map((pkg) => `- ${pkg}`).join('\\n')\n : 'None (use built-in capabilities only)';\n\n return generateSystemPrompt({\n tools: allTools,\n authorizedImports: importsDoc,\n customInstructions: this.config.customInstructions,\n });\n }\n\n /**\n * Execute a single step: get LLM response, extract code, execute it.\n */\n protected async executeStep(memoryStep: ActionStep): Promise<ActionOutput> {\n // Get messages for LLM\n const messages = this.memory.toMessages();\n memoryStep.modelInputMessages = [...messages];\n\n // Check if last step had an error - add recovery prompt\n const lastStep = this.memory.getActionSteps().slice(-2)[0]; // Get step before current\n if (lastStep?.error) {\n messages.push({\n role: 'user',\n content: getErrorRecoveryPrompt(lastStep.error.message),\n });\n }\n\n // Generate response from LLM\n const response = await this.generateResponse(messages);\n memoryStep.modelOutputMessage = response;\n memoryStep.tokenUsage = response.tokenUsage;\n\n const content = response.content ?? '';\n\n // Extract thought/reasoning\n const thoughtMatch = content.match(THOUGHT_REGEX);\n if (thoughtMatch) {\n this.logger.reasoning(thoughtMatch[1].trim());\n }\n\n // Extract code block\n const codeMatch = content.match(CODE_BLOCK_REGEX);\n\n if (!codeMatch) {\n // No code block found - this might be just reasoning\n // Feed back to LLM to generate code\n this.logger.warn('No code block found in response');\n memoryStep.observation = 'No code block was found in your response. Please provide JavaScript code in a ```javascript code block.';\n\n return {\n output: null,\n isFinalAnswer: false,\n };\n }\n\n const code = codeMatch[1].trim();\n memoryStep.codeAction = code;\n\n this.logger.code(code);\n\n // Wait before execution (allows user to interrupt)\n if (this.config.codeExecutionDelay > 0) {\n this.logger.waiting(this.config.codeExecutionDelay / 1000);\n await this.sleep(this.config.codeExecutionDelay);\n }\n\n // Execute the code\n this.logger.subheader('Executing code...');\n const result = await this.executor.execute(code);\n\n // Log execution logs\n if (result.logs) {\n this.logger.logs(result.logs);\n }\n\n // Handle execution error\n if (result.error) {\n this.logger.error('Code execution error', result.error);\n\n memoryStep.error = result.error;\n memoryStep.observation = `Error during code execution:\\n${result.error.message}`;\n\n return {\n output: null,\n isFinalAnswer: false,\n };\n }\n\n // Format observation\n const outputStr = this.formatOutput(result.output);\n this.logger.output(outputStr);\n\n memoryStep.observation = this.formatObservation(result.logs, outputStr);\n\n return {\n output: result.output,\n isFinalAnswer: result.isFinalAnswer,\n };\n }\n\n /**\n * Generate response from the LLM, optionally streaming.\n */\n private async generateResponse(messages: ChatMessage[]): Promise<ChatMessage> {\n if (this.config.streamOutputs && this.model.supportsStreaming() && this.model.generateStream) {\n // Stream the response\n this.logger.subheader('Agent thinking...');\n\n let fullContent = '';\n const generator = this.model.generateStream(messages, {\n stopSequences: ['Observation:', 'Observation:\\n'],\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n });\n\n for await (const chunk of generator) {\n this.logger.streamChar(chunk);\n fullContent += chunk;\n }\n\n this.logger.streamEnd();\n\n return {\n role: 'assistant',\n content: fullContent,\n };\n } else {\n // Non-streaming response\n this.logger.subheader('Agent thinking...');\n\n return this.model.generate(messages, {\n stopSequences: ['Observation:', 'Observation:\\n'],\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n });\n }\n }\n\n /**\n * Format output for display.\n */\n private formatOutput(output: unknown): string {\n if (output === undefined || output === null) {\n return '(no output)';\n }\n\n if (typeof output === 'string') {\n return output;\n }\n\n try {\n return JSON.stringify(output, null, 2);\n } catch {\n return String(output);\n }\n }\n\n /**\n * Format the observation to send back to the LLM.\n */\n private formatObservation(logs: string, output: string): string {\n const parts: string[] = [];\n\n if (logs.trim()) {\n parts.push(`Execution logs:\\n${logs}`);\n }\n\n parts.push(`Last output:\\n${output}`);\n\n return `Observation:\\n${parts.join('\\n\\n')}`;\n }\n\n /**\n * Reset the agent and executor state.\n */\n reset(): void {\n this.executor.reset();\n this.currentStep = 0;\n }\n\n /**\n * Get the executor instance.\n */\n getExecutor(): LocalExecutor {\n return this.executor;\n }\n\n /**\n * Override addTool to also register with executor.\n */\n addTool(tool: Tool): void {\n super.addTool(tool);\n this.executor.sendTools({ [tool.name]: tool });\n }\n}\n","/**\n * System prompts for ToolUseAgent\n */\n\nexport interface ToolUsePromptVariables {\n tools: string;\n customInstructions?: string;\n /** Whether this agent has sub-agents (AgentTool instances) */\n hasSubAgents?: boolean;\n /** Whether this agent has file tools (read_file, write_file) */\n hasFileTools?: boolean;\n}\n\n/**\n * Generate the system prompt for ToolUseAgent.\n */\nexport function generateToolUseSystemPrompt(variables: ToolUsePromptVariables): string {\n const { tools, customInstructions, hasSubAgents, hasFileTools } = variables;\n\n // Build content delegation guidelines based on agent capabilities\n let contentGuidelines = '';\n\n if (hasFileTools) {\n contentGuidelines += `\n## Content Output Guidelines\n\nWhen you produce long-form content (reports, articles, analyses, or any output longer than a few paragraphs):\n1. **Save to file**: Use \\`write_file\\` to save the full content to a descriptively-named file (e.g., \\`research_report.md\\`, \\`analysis_results.md\\`).\n2. **Return summary + filename**: In your \\`final_answer\\`, provide a brief summary of what you produced AND the filename where the full content is saved. Example: \"Completed the research report covering X, Y, Z. Full report saved to: research_report.md\"\n\nThis ensures managing agents can access your full output via \\`read_file\\` without it being truncated in message passing.\n`;\n }\n\n if (hasSubAgents) {\n contentGuidelines += `\n## Working with Sub-Agents\n\nWhen you delegate tasks to sub-agents:\n- Sub-agents return a **summary and filename** rather than the full content of long-form outputs.\n- To access the full content a sub-agent produced, use \\`read_file\\` with the filename they provide.\n- **Do NOT re-invoke a sub-agent to retrieve content it already created.** Instead, read the file directly.\n- When composing your own final output from sub-agent results, read their files as needed and synthesize.\n`;\n }\n\n if (hasSubAgents && hasFileTools) {\n contentGuidelines += `\n## When You Are Both a Manager and a Sub-Agent\n\nIf you manage sub-agents AND are yourself delegated tasks by a parent agent:\n- Follow the sub-agent content guidelines: save your own long-form output to a file, return summary + filename.\n- Follow the manager guidelines: read sub-agent output files rather than re-calling them.\n`;\n }\n\n return `You are an expert assistant and problem-solving agent. You solve tasks by reasoning step by step and using the tools available to you.\n\n## How You Work\n\nYou follow a ReAct (Reasoning + Acting) framework:\n1. **Think**: Analyze the current situation and decide what to do next\n2. **Act**: Call one or more tools to perform actions\n3. **Observe**: Review the results of your tool calls\n4. Repeat until you have the final answer\n\n## Available Tools\n\n${tools}\n\n## Rules\n\n1. **Always use final_answer**: When you have the complete answer, call the \\`final_answer\\` tool to return it. This is mandatory - you must always end by calling final_answer.\n\n2. **Think before acting**: Provide your reasoning in the content of your response before making tool calls. This helps track your thought process.\n\n3. **One logical action per step**: Focus on one logical action per step. You may call multiple tools in a single step if they are independent, but avoid chaining dependent operations without reviewing intermediate results.\n\n4. **Handle errors gracefully**: If a tool call fails, analyze the error and try a different approach.\n\n5. **Be concise**: Keep your reasoning brief and focused. Don't over-explain.\n\n6. **Use the right tool**: Choose the most appropriate tool for each action. Don't try to accomplish something a tool can do through other means.\n${contentGuidelines}\n${customInstructions ? `## Additional Instructions\\n\\n${customInstructions}` : ''}\n\nNow, let's solve the task step by step. Think carefully about what tools to use and in what order.`;\n}\n\n/**\n * Format tool descriptions for the system prompt.\n */\nexport function formatToolDescriptions(tools: Array<{ name: string; description: string; inputs: Record<string, { type: string; description: string; required?: boolean }> }>): string {\n return tools.map(tool => {\n const params = Object.entries(tool.inputs)\n .map(([name, input]) => {\n const req = input.required !== false ? ' (required)' : ' (optional)';\n return ` - ${name}${req}: ${input.description}`;\n })\n .join('\\n');\n\n return `### ${tool.name}\\n${tool.description}\\nParameters:\\n${params}`;\n }).join('\\n\\n');\n}\n","/**\n * ToolUseAgent - Executes tasks using standard OpenAI-style tool calls\n *\n * Unlike CodeAgent which generates and executes JavaScript code,\n * ToolUseAgent operates by making tool calls through the LLM's native\n * function calling capabilities, following the ReACT pattern:\n * Think -> Act (tool call) -> Observe (result) -> repeat\n */\n\nimport { Agent, AgentConfig } from './Agent.js';\nimport { FinalAnswerTool } from '../tools/defaultTools.js';\nimport { Tool } from '../tools/Tool.js';\nimport { generateToolUseSystemPrompt, formatToolDescriptions } from '../prompts/toolUseAgent.js';\nimport type { ActionStep, ActionOutput, ToolCall, ToolCallResult } from '../types.js';\n\nexport interface ToolUseAgentConfig extends AgentConfig {\n /** Whether to run independent tool calls in parallel (default: true) */\n parallelToolCalls?: boolean;\n}\n\nexport class ToolUseAgent extends Agent {\n private parallelToolCalls: boolean;\n\n constructor(config: ToolUseAgentConfig) {\n super(config);\n this.parallelToolCalls = config.parallelToolCalls ?? true;\n\n // Always add final_answer tool\n if (!this.tools.has('final_answer')) {\n this.tools.set('final_answer', new FinalAnswerTool());\n }\n }\n\n /**\n * Initialize the system prompt with tool descriptions.\n */\n protected initializeSystemPrompt(): string {\n const toolList = Array.from(this.tools.values());\n const toolDescriptions = formatToolDescriptions(\n toolList.map(t => ({\n name: t.name,\n description: t.description,\n inputs: t.inputs,\n }))\n );\n\n // Detect capabilities for content delegation guidelines\n const toolNames = new Set(Array.from(this.tools.keys()));\n const hasSubAgents = toolList.some(t => t.constructor.name === 'AgentTool');\n const hasFileTools = toolNames.has('read_file') || toolNames.has('write_file') || toolNames.has('read') || toolNames.has('write');\n\n return generateToolUseSystemPrompt({\n tools: toolDescriptions,\n customInstructions: this.config.customInstructions,\n hasSubAgents,\n hasFileTools,\n });\n }\n\n /**\n * Execute a single step: send messages with tool definitions, process tool calls.\n */\n protected async executeStep(memoryStep: ActionStep): Promise<ActionOutput> {\n const messages = this.memory.toMessages();\n memoryStep.modelInputMessages = [...messages];\n\n // Handle error recovery from previous step\n const actionSteps = this.memory.getActionSteps();\n const prevStep = actionSteps.length >= 2 ? actionSteps[actionSteps.length - 2] : undefined;\n if (prevStep?.error) {\n messages.push({\n role: 'user',\n content: `Your previous action encountered an error: ${prevStep.error.message}\\nPlease try a different approach.`,\n });\n }\n\n // Get tool definitions for the API call\n const toolDefinitions = Array.from(this.tools.values()).map(t => t.toOpenAITool());\n\n // Generate response with tool calling\n this.logger.subheader('Agent thinking...');\n const response = await this.model.generate(messages, {\n toolDefinitions,\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n });\n\n memoryStep.modelOutputMessage = response;\n memoryStep.tokenUsage = response.tokenUsage;\n\n // Log reasoning (text content)\n if (response.content && response.content.trim()) {\n this.logger.reasoning(response.content.trim());\n this.emitEvent('agent_thinking', {\n step: this.currentStep,\n content: response.content.trim(),\n });\n }\n\n // Check if model made tool calls\n if (!response.toolCalls || response.toolCalls.length === 0) {\n // No tool calls - the model just responded with text\n this.logger.warn('No tool calls in response. Prompting model to use tools.');\n memoryStep.observation = 'You must use tools to complete the task. Please call the appropriate tool(s). When you have the final answer, call the final_answer tool.';\n return { output: null, isFinalAnswer: false };\n }\n\n // Process tool calls\n memoryStep.toolCalls = response.toolCalls;\n const toolResults = await this.processToolCalls(response.toolCalls);\n memoryStep.toolResults = toolResults;\n\n // Check if final_answer was called\n for (const result of toolResults) {\n if (result.toolName === 'final_answer') {\n return { output: result.result, isFinalAnswer: true };\n }\n }\n\n // Log tool results as observations\n for (const result of toolResults) {\n if (result.error) {\n this.logger.error(`Tool ${result.toolName} failed: ${result.error}`);\n this.emitEvent('agent_error', { tool: result.toolName, error: result.error });\n } else {\n const resultStr = typeof result.result === 'string'\n ? result.result\n : JSON.stringify(result.result, null, 2);\n this.logger.output(`[${result.toolName}]: ${resultStr.slice(0, 500)}${resultStr.length > 500 ? '...' : ''}`);\n this.emitEvent('agent_observation', { tool: result.toolName, result: resultStr.slice(0, 500) });\n }\n }\n\n return { output: null, isFinalAnswer: false };\n }\n\n /**\n * Process tool calls from the model response.\n */\n private async processToolCalls(toolCalls: ToolCall[]): Promise<ToolCallResult[]> {\n const results: ToolCallResult[] = [];\n\n // Execute tool calls\n const executeTool = async (tc: ToolCall): Promise<ToolCallResult> => {\n const startTime = Date.now();\n const toolName = tc.function.name;\n const tool = this.tools.get(toolName);\n\n if (!tool) {\n const error = `Unknown tool: ${toolName}. Available tools: ${Array.from(this.tools.keys()).join(', ')}`;\n this.emitEvent('agent_tool_result', {\n step: this.currentStep,\n toolCallId: tc.id,\n toolName,\n result: null,\n error,\n duration: Date.now() - startTime,\n });\n return {\n toolCallId: tc.id,\n toolName,\n result: null,\n error,\n };\n }\n\n // Parse arguments\n let args: Record<string, unknown>;\n try {\n args = typeof tc.function.arguments === 'string'\n ? JSON.parse(tc.function.arguments)\n : tc.function.arguments as Record<string, unknown>;\n } catch {\n const error = `Failed to parse tool arguments: ${tc.function.arguments}`;\n this.emitEvent('agent_tool_result', {\n step: this.currentStep,\n toolCallId: tc.id,\n toolName,\n result: null,\n error,\n duration: Date.now() - startTime,\n });\n return {\n toolCallId: tc.id,\n toolName,\n result: null,\n error,\n };\n }\n\n this.logger.info(` Calling tool: ${toolName}(${JSON.stringify(args).slice(0, 100)}...)`);\n this.emitEvent('agent_tool_call', {\n step: this.currentStep,\n toolCallId: tc.id,\n toolName,\n arguments: args,\n });\n\n try {\n const result = await tool.call(args);\n const duration = Date.now() - startTime;\n this.emitEvent('agent_tool_result', {\n step: this.currentStep,\n toolCallId: tc.id,\n toolName,\n result,\n duration,\n });\n return {\n toolCallId: tc.id,\n toolName,\n result,\n };\n } catch (error) {\n const errorMsg = `Tool execution error: ${(error as Error).message}`;\n const duration = Date.now() - startTime;\n this.emitEvent('agent_tool_result', {\n step: this.currentStep,\n toolCallId: tc.id,\n toolName,\n result: null,\n error: errorMsg,\n duration,\n });\n return {\n toolCallId: tc.id,\n toolName,\n result: null,\n error: errorMsg,\n };\n }\n };\n\n if (this.parallelToolCalls) {\n const promises = toolCalls.map(tc => executeTool(tc));\n const resolvedResults = await Promise.all(promises);\n results.push(...resolvedResults);\n } else {\n for (const tc of toolCalls) {\n results.push(await executeTool(tc));\n }\n }\n\n return results;\n }\n\n /**\n * Override provideFinalAnswer to use tool calling format.\n */\n protected async provideFinalAnswer(task: string): Promise<unknown> {\n this.logger.subheader('Generating final answer from accumulated context');\n\n const messages = this.memory.toMessages();\n messages.push({\n role: 'user',\n 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.`,\n });\n\n const toolDefinitions = [new FinalAnswerTool().toOpenAITool()];\n const response = await this.model.generate(messages, {\n toolDefinitions,\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n });\n\n // Try to extract from tool call\n if (response.toolCalls && response.toolCalls.length > 0) {\n const tc = response.toolCalls[0];\n try {\n const args = typeof tc.function.arguments === 'string'\n ? JSON.parse(tc.function.arguments)\n : tc.function.arguments;\n return (args as Record<string, unknown>).answer;\n } catch {\n return response.content;\n }\n }\n\n return response.content;\n }\n\n /**\n * Add a tool, which can also be an Agent instance (auto-wraps with AgentTool).\n */\n addTool(tool: Tool): void {\n super.addTool(tool);\n }\n}\n","/**\n * Model base class for smol-js\n *\n * Models are responsible for generating text responses from LLMs.\n * Extend this class to support different LLM providers.\n */\n\nimport type { ChatMessage, GenerateOptions, TokenUsage } from '../types.js';\n\nexport abstract class Model {\n /**\n * Model identifier (e.g., \"gpt-4\", \"claude-3-sonnet\")\n */\n abstract readonly modelId: string;\n\n /**\n * Generate a response from the model.\n */\n abstract generate(\n messages: ChatMessage[],\n options?: GenerateOptions\n ): Promise<ChatMessage>;\n\n /**\n * Optional streaming generation.\n * Yields content chunks and returns the final message.\n */\n generateStream?(\n messages: ChatMessage[],\n options?: GenerateOptions\n ): AsyncGenerator<string, ChatMessage, undefined>;\n\n /**\n * Check if the model supports streaming.\n */\n supportsStreaming(): boolean {\n return typeof this.generateStream === 'function';\n }\n\n /**\n * Extract token usage from a response message.\n */\n protected extractTokenUsage(_response: unknown): TokenUsage | undefined {\n // Override in subclasses to extract token usage from API responses\n return undefined;\n }\n\n /**\n * Convert messages to the format expected by the model's API.\n */\n protected formatMessages(messages: ChatMessage[]): unknown[] {\n // Default implementation - override for specific API formats\n return messages.map((msg) => ({\n role: msg.role,\n content: msg.content,\n ...(msg.name && { name: msg.name }),\n ...(msg.toolCallId && { tool_call_id: msg.toolCallId }),\n }));\n }\n}\n","/**\n * OpenAI-compatible Model implementation\n *\n * Supports any API that follows the OpenAI chat completions format,\n * including OpenRouter, Azure OpenAI, local servers, etc.\n */\n\nimport OpenAI from 'openai/index.mjs';\nimport { Model } from './Model.js';\nimport type { ChatMessage, GenerateOptions, TokenUsage, MessageRole } from '../types.js';\n\nexport interface OpenAIModelConfig {\n /**\n * Model identifier (e.g., \"gpt-4\", \"anthropic/claude-sonnet-4.5\")\n */\n modelId?: string;\n\n /**\n * API key for authentication\n */\n apiKey?: string;\n\n /**\n * Base URL for the API endpoint\n * @default \"https://openrouter.ai/api/v1\"\n */\n baseUrl?: string;\n\n /**\n * Maximum tokens to generate (omitted from requests by default)\n */\n maxTokens?: number;\n\n /**\n * Temperature for generation (omitted from requests by default)\n */\n temperature?: number;\n\n /**\n * Request timeout in milliseconds\n */\n timeout?: number;\n\n /**\n * Default headers to include in requests\n */\n defaultHeaders?: Record<string, string>;\n}\n\nconst DEFAULT_MODEL_ID = 'anthropic/claude-sonnet-4.5';\nconst DEFAULT_BASE_URL = 'https://openrouter.ai/api/v1';\nconst DEFAULT_TIMEOUT = 120000;\n\nexport class OpenAIModel extends Model {\n readonly modelId: string;\n private client: OpenAI;\n private config: OpenAIModelConfig;\n\n constructor(config: OpenAIModelConfig = {}) {\n super();\n\n this.config = config;\n this.modelId = config.modelId ?? DEFAULT_MODEL_ID;\n\n // Get API key from config or environment\n const apiKey = config.apiKey ?? process.env.OPENAI_API_KEY ?? process.env.OPENROUTER_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'API key is required. Set OPENAI_API_KEY or OPENROUTER_API_KEY environment variable, or pass apiKey in config.'\n );\n }\n\n this.client = new OpenAI({\n apiKey,\n baseURL: config.baseUrl ?? DEFAULT_BASE_URL,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n defaultHeaders: config.defaultHeaders,\n });\n }\n\n /**\n * Generate a response from the model (supports tool calling).\n */\n async generate(messages: ChatMessage[], options: GenerateOptions = {}): Promise<ChatMessage> {\n const formattedMessages = this.formatMessages(messages);\n\n const requestParams: Record<string, unknown> = {\n model: this.modelId,\n messages: formattedMessages,\n };\n\n // Only include maxTokens if specified at request or model config level\n const maxTokens = options.maxTokens ?? this.config.maxTokens;\n if (maxTokens !== undefined) {\n requestParams.max_tokens = maxTokens;\n }\n\n // Only include temperature if specified at request or model config level\n const temperature = options.temperature ?? this.config.temperature;\n if (temperature !== undefined) {\n requestParams.temperature = temperature;\n }\n\n if (options.stopSequences) {\n requestParams.stop = options.stopSequences;\n }\n\n // Add tool definitions for function calling\n if (options.toolDefinitions && options.toolDefinitions.length > 0) {\n requestParams.tools = options.toolDefinitions;\n } else if (options.tools && options.tools.length > 0) {\n requestParams.tools = options.tools.map(t => t.toOpenAITool());\n }\n\n const response = await this.client.chat.completions.create({\n ...requestParams,\n model: this.modelId,\n messages: formattedMessages as OpenAI.Chat.ChatCompletionMessageParam[],\n } as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming);\n\n const choice = response.choices[0];\n const message = choice?.message;\n\n if (!message) {\n throw new Error('No response from model');\n }\n\n const tokenUsage: TokenUsage | undefined = response.usage\n ? {\n inputTokens: response.usage.prompt_tokens,\n outputTokens: response.usage.completion_tokens ?? 0,\n totalTokens: response.usage.total_tokens,\n }\n : undefined;\n\n // Map tool_calls from OpenAI format\n const toolCalls = message.tool_calls?.map((tc: OpenAI.Chat.ChatCompletionMessageToolCall) => ({\n id: tc.id,\n type: 'function' as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n }));\n\n return {\n role: 'assistant' as MessageRole,\n content: message.content ?? '',\n toolCalls,\n tokenUsage,\n };\n }\n\n /**\n * Generate a streaming response from the model.\n */\n async *generateStream(\n messages: ChatMessage[],\n options: GenerateOptions = {}\n ): AsyncGenerator<string, ChatMessage, undefined> {\n const formattedMessages = this.formatMessages(messages);\n\n const requestParams: Record<string, unknown> = {\n model: this.modelId,\n messages: formattedMessages,\n stream: true,\n };\n\n const maxTokens = options.maxTokens ?? this.config.maxTokens;\n if (maxTokens !== undefined) {\n requestParams.max_tokens = maxTokens;\n }\n\n const temperature = options.temperature ?? this.config.temperature;\n if (temperature !== undefined) {\n requestParams.temperature = temperature;\n }\n\n if (options.stopSequences) {\n requestParams.stop = options.stopSequences;\n }\n\n const stream = await this.client.chat.completions.create({\n ...requestParams,\n model: this.modelId,\n messages: formattedMessages as OpenAI.Chat.ChatCompletionMessageParam[],\n stream: true,\n } as OpenAI.Chat.ChatCompletionCreateParamsStreaming);\n\n let fullContent = '';\n\n for await (const chunk of stream as AsyncIterable<OpenAI.Chat.ChatCompletionChunk>) {\n const delta = chunk.choices[0]?.delta;\n if (delta?.content) {\n fullContent += delta.content;\n yield delta.content;\n }\n }\n\n return {\n role: 'assistant' as MessageRole,\n content: fullContent,\n };\n }\n\n /**\n * Format messages for the OpenAI API, including tool call/response messages.\n */\n protected formatMessages(messages: ChatMessage[]): OpenAI.Chat.ChatCompletionMessageParam[] {\n return messages.map((msg) => {\n // Handle tool response messages\n if (msg.role === 'tool' && msg.toolCallId) {\n return {\n role: 'tool' as const,\n content: msg.content ?? '',\n tool_call_id: msg.toolCallId,\n };\n }\n\n // Handle tool responses without toolCallId (legacy format)\n if (msg.role === 'tool') {\n return {\n role: 'user' as const,\n content: msg.content ?? '',\n };\n }\n\n // Handle assistant messages with tool calls\n if (msg.role === 'assistant' && msg.toolCalls && msg.toolCalls.length > 0) {\n return {\n role: 'assistant' as const,\n content: msg.content || null,\n tool_calls: msg.toolCalls.map(tc => ({\n id: tc.id,\n type: 'function' as const,\n function: {\n name: tc.function.name,\n arguments: typeof tc.function.arguments === 'string'\n ? tc.function.arguments\n : JSON.stringify(tc.function.arguments),\n },\n })),\n };\n }\n\n return {\n role: msg.role as 'system' | 'user' | 'assistant',\n content: msg.content ?? '',\n };\n });\n }\n}\n","/**\n * AgentTool - Wraps a CodeAgent as a Tool for use by other agents\n *\n * This enables nested/hierarchical agent architectures where a \"manager\" agent\n * can delegate tasks to specialized \"worker\" agents.\n *\n * Based on the ManagedAgent pattern from Python smolagents.\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\nimport type { Agent } from '../agents/Agent.js';\n\nexport interface AgentToolConfig {\n /**\n * The agent to wrap as a tool\n */\n agent: Agent;\n\n /**\n * Name for the tool (defaults to agent's name or \"managed_agent\")\n */\n name?: string;\n\n /**\n * Description of what this agent does (used in parent agent's prompt)\n */\n description?: string;\n\n /**\n * Additional context to provide to the agent with each task\n */\n additionalContext?: string;\n\n /**\n * Whether to provide the full result object or just the output\n * @default false\n */\n returnFullResult?: boolean;\n}\n\nexport class AgentTool extends Tool {\n readonly name: string;\n readonly description: string;\n readonly inputs: ToolInputs = {\n task: {\n type: 'string',\n description: 'The task or question to delegate to this agent',\n required: true,\n },\n };\n readonly outputType = 'string';\n\n private agent: Agent;\n private additionalContext?: string;\n private returnFullResult: boolean;\n\n constructor(config: AgentToolConfig) {\n super();\n this.agent = config.agent;\n this.name = config.name ?? 'managed_agent';\n this.additionalContext = config.additionalContext;\n this.returnFullResult = config.returnFullResult ?? false;\n\n // Build description from config or generate default\n this.description = config.description ?? this.generateDescription();\n }\n\n /**\n * Generate a default description based on the agent's configuration\n */\n private generateDescription(): string {\n return `Delegates a task to a specialized agent.\nThis agent can help with complex sub-tasks that require multiple steps.\nPass a clear, specific task description and the agent will work autonomously to solve it.\nReturns the agent's final answer as a string.`;\n }\n\n /**\n * Execute the agent with the given task\n */\n async execute(args: Record<string, unknown>): Promise<unknown> {\n let task = args.task as string;\n\n // Add additional context if provided\n if (this.additionalContext) {\n task = `${this.additionalContext}\\n\\nTask: ${task}`;\n }\n\n // Run the agent\n const result = await this.agent.run(task, true);\n\n // Return full result or just output\n if (this.returnFullResult) {\n return {\n output: result.output,\n steps: result.steps.length,\n duration: result.duration,\n };\n }\n\n // Convert output to string if needed\n const output = result.output;\n if (typeof output === 'string') {\n return output;\n }\n return JSON.stringify(output, null, 2);\n }\n\n /**\n * Override toCodePrompt to provide a cleaner signature for nested agents\n */\n toCodePrompt(): string {\n return `\n/**\n * ${this.description}\n *\n * @param task - The task or question to delegate to this specialized agent\n * @returns The agent's answer as a string\n */\nasync function ${this.name}(task: string): Promise<string> { ... }\n`.trim();\n }\n}\n\n/**\n * Helper function to quickly wrap an agent as a tool\n */\nexport function agentAsTool(\n agent: Agent,\n options?: Omit<AgentToolConfig, 'agent'>\n): AgentTool {\n return new AgentTool({ agent, ...options });\n}\n","/**\n * ReadFileTool - Read contents from a file\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport class ReadFileTool extends Tool {\n readonly name = 'read_file';\n readonly description = 'Read the contents of a file at the specified path. Returns the file content as a string.';\n readonly inputs: ToolInputs = {\n path: {\n type: 'string',\n description: 'The file path to read (absolute or relative to working directory)',\n required: true,\n },\n encoding: {\n type: 'string',\n description: 'File encoding (default: utf-8)',\n required: false,\n default: 'utf-8',\n },\n };\n readonly outputType = 'string';\n\n private workingDirectory: string;\n\n constructor(config?: { workingDirectory?: string }) {\n super();\n this.workingDirectory = config?.workingDirectory ?? process.cwd();\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const filePath = args.path as string;\n const encoding = (args.encoding as BufferEncoding) ?? 'utf-8';\n\n const resolvedPath = path.isAbsolute(filePath)\n ? filePath\n : path.resolve(this.workingDirectory, filePath);\n\n if (!fs.existsSync(resolvedPath)) {\n throw new Error(`File not found: ${resolvedPath}`);\n }\n\n const stat = fs.statSync(resolvedPath);\n if (stat.isDirectory()) {\n throw new Error(`Path is a directory, not a file: ${resolvedPath}`);\n }\n\n const content = fs.readFileSync(resolvedPath, encoding);\n\n // Truncate very large files\n const maxLength = 100000;\n if (content.length > maxLength) {\n return content.slice(0, maxLength) + `\\n\\n[... truncated, file is ${content.length} characters total]`;\n }\n\n return content;\n }\n}\n","/**\n * WriteFileTool - Write content to a file\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport class WriteFileTool extends Tool {\n readonly name = 'write_file';\n readonly description = 'Write content to a file at the specified path. Creates the file if it does not exist, and creates parent directories as needed. Overwrites existing content by default.';\n readonly inputs: ToolInputs = {\n path: {\n type: 'string',\n description: 'The file path to write to (absolute or relative to working directory)',\n required: true,\n },\n content: {\n type: 'string',\n description: 'The content to write to the file',\n required: true,\n },\n append: {\n type: 'boolean',\n description: 'If true, append to the file instead of overwriting (default: false)',\n required: false,\n default: false,\n },\n };\n readonly outputType = 'string';\n\n private workingDirectory: string;\n\n constructor(config?: { workingDirectory?: string }) {\n super();\n this.workingDirectory = config?.workingDirectory ?? process.cwd();\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const filePath = args.path as string;\n const content = args.content as string;\n const append = (args.append as boolean) ?? false;\n\n const resolvedPath = path.isAbsolute(filePath)\n ? filePath\n : path.resolve(this.workingDirectory, filePath);\n\n // Create parent directories if needed\n const dir = path.dirname(resolvedPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n if (append) {\n fs.appendFileSync(resolvedPath, content, 'utf-8');\n return `Successfully appended ${content.length} characters to ${resolvedPath}`;\n } else {\n fs.writeFileSync(resolvedPath, content, 'utf-8');\n return `Successfully wrote ${content.length} characters to ${resolvedPath}`;\n }\n }\n}\n","/**\n * CurlTool - HTTP requests (GET/POST) using fetch\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\n\nexport class CurlTool extends Tool {\n readonly name = 'curl';\n readonly description = 'Make HTTP requests to any URL. Supports GET and POST methods with custom headers and body. Returns the response body as text.';\n readonly inputs: ToolInputs = {\n url: {\n type: 'string',\n description: 'The URL to request',\n required: true,\n },\n method: {\n type: 'string',\n description: 'HTTP method: GET or POST (default: GET)',\n required: false,\n default: 'GET',\n enum: ['GET', 'POST'],\n },\n headers: {\n type: 'object',\n description: 'Optional HTTP headers as key-value pairs (e.g., {\"Content-Type\": \"application/json\"})',\n required: false,\n },\n body: {\n type: 'string',\n description: 'Request body for POST requests (typically JSON string)',\n required: false,\n },\n };\n readonly outputType = 'string';\n\n private timeout: number;\n\n constructor(config?: { timeout?: number }) {\n super();\n this.timeout = config?.timeout ?? 30000;\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const url = args.url as string;\n const method = ((args.method as string) ?? 'GET').toUpperCase();\n const headers = (args.headers as Record<string, string>) ?? {};\n const body = args.body as string | undefined;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const fetchOptions: RequestInit = {\n method,\n headers,\n signal: controller.signal,\n };\n\n if (method === 'POST' && body) {\n fetchOptions.body = body;\n if (!headers['Content-Type'] && !headers['content-type']) {\n (fetchOptions.headers as Record<string, string>)['Content-Type'] = 'application/json';\n }\n }\n\n const response = await fetch(url, fetchOptions);\n const responseText = await response.text();\n\n const statusLine = `HTTP ${response.status} ${response.statusText}`;\n\n // Truncate very large responses\n const maxLength = 50000;\n const truncatedBody = responseText.length > maxLength\n ? responseText.slice(0, maxLength) + `\\n\\n[... truncated, response is ${responseText.length} characters total]`\n : responseText;\n\n return `${statusLine}\\n\\n${truncatedBody}`;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n throw new Error(`Request timed out after ${this.timeout}ms: ${url}`);\n }\n throw new Error(`HTTP request failed: ${(error as Error).message}`);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n","/**\n * ExaSearchTool - Web search using the Exa.ai API\n *\n * Uses Exa's embeddings-based search for semantically intelligent results.\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\n\nexport interface ExaSearchConfig {\n apiKey?: string;\n}\n\nexport class ExaSearchTool extends Tool {\n readonly name = 'exa_search';\n readonly description = 'Search the web using Exa.ai semantic search. Returns relevant web pages with titles, URLs, and optionally content snippets. Use this for finding information, research, and fact-checking.';\n readonly inputs: ToolInputs = {\n query: {\n type: 'string',\n description: 'The search query. Be specific and descriptive for best results.',\n required: true,\n },\n numResults: {\n type: 'number',\n description: 'Number of results to return (default: 10, max: 30)',\n required: false,\n default: 10,\n },\n type: {\n type: 'string',\n description: 'Search type: \"auto\" (default), \"neural\" (embeddings-based), or \"keyword\"',\n required: false,\n default: 'auto',\n enum: ['auto', 'neural', 'keyword'],\n },\n category: {\n type: 'string',\n description: 'Optional category filter: \"research paper\", \"news\", \"pdf\", \"github\", \"tweet\", \"company\", \"blog\"',\n required: false,\n },\n includeDomains: {\n type: 'array',\n description: 'Only include results from these domains (e.g., [\"arxiv.org\", \"github.com\"])',\n required: false,\n },\n excludeDomains: {\n type: 'array',\n description: 'Exclude results from these domains',\n required: false,\n },\n startPublishedDate: {\n type: 'string',\n description: 'Filter results published after this ISO 8601 date (e.g., \"2024-01-01\")',\n required: false,\n },\n };\n readonly outputType = 'string';\n\n private apiKey: string;\n\n constructor(config?: ExaSearchConfig) {\n super();\n this.apiKey = config?.apiKey ?? process.env.EXA_API_KEY ?? '';\n }\n\n async setup(): Promise<void> {\n if (!this.apiKey) {\n throw new Error('EXA_API_KEY is required. Set it as an environment variable or pass it in the config.');\n }\n this.isSetup = true;\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const query = args.query as string;\n const numResults = Math.min((args.numResults as number) ?? 10, 30);\n const type = (args.type as string) ?? 'auto';\n\n const requestBody: Record<string, unknown> = {\n query,\n numResults,\n type,\n text: { maxCharacters: 1000 },\n };\n\n if (args.category) requestBody.category = args.category;\n if (args.includeDomains) requestBody.includeDomains = args.includeDomains;\n if (args.excludeDomains) requestBody.excludeDomains = args.excludeDomains;\n if (args.startPublishedDate) requestBody.startPublishedDate = args.startPublishedDate;\n\n const response = await fetch('https://api.exa.ai/search', {\n method: 'POST',\n headers: {\n 'x-api-key': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Exa search failed (${response.status}): ${errorText}`);\n }\n\n const data = await response.json() as {\n results: Array<{\n title?: string;\n url: string;\n publishedDate?: string;\n author?: string;\n text?: string;\n score?: number;\n }>;\n };\n\n if (!data.results || data.results.length === 0) {\n return 'No results found for the query.';\n }\n\n // Format results for the agent\n const formattedResults = data.results.map((result, i) => {\n const parts = [`[${i + 1}] ${result.title ?? 'Untitled'}`];\n parts.push(` URL: ${result.url}`);\n if (result.publishedDate) parts.push(` Date: ${result.publishedDate}`);\n if (result.author) parts.push(` Author: ${result.author}`);\n if (result.text) {\n const snippet = result.text.slice(0, 300).trim();\n parts.push(` Snippet: ${snippet}${result.text.length > 300 ? '...' : ''}`);\n }\n return parts.join('\\n');\n }).join('\\n\\n');\n\n return `Search results for \"${query}\" (${data.results.length} results):\\n\\n${formattedResults}`;\n }\n}\n","/**\n * ExaGetContentsTool - Get webpage contents using Exa.ai API\n *\n * Fetches and extracts clean text content from web pages.\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\n\nexport interface ExaGetContentsConfig {\n apiKey?: string;\n}\n\nexport class ExaGetContentsTool extends Tool {\n readonly name = 'exa_get_contents';\n readonly description = 'Get the full text content of one or more web pages using Exa.ai. Returns cleaned, readable text extracted from the HTML. Use this to read articles, documentation, or any web page content.';\n readonly inputs: ToolInputs = {\n urls: {\n type: 'array',\n description: 'Array of URLs to fetch content from (max 10)',\n required: true,\n },\n maxCharacters: {\n type: 'number',\n description: 'Maximum characters of content to return per page (default: 10000)',\n required: false,\n default: 10000,\n },\n livecrawl: {\n type: 'string',\n description: 'Crawl strategy: \"fallback\" (use cache, fetch live if unavailable), \"always\" (always fetch live), \"never\" (cache only). Default: \"fallback\"',\n required: false,\n default: 'fallback',\n enum: ['fallback', 'always', 'never'],\n },\n };\n readonly outputType = 'string';\n\n private apiKey: string;\n\n constructor(config?: ExaGetContentsConfig) {\n super();\n this.apiKey = config?.apiKey ?? process.env.EXA_API_KEY ?? '';\n }\n\n async setup(): Promise<void> {\n if (!this.apiKey) {\n throw new Error('EXA_API_KEY is required. Set it as an environment variable or pass it in the config.');\n }\n this.isSetup = true;\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const urls = (args.urls as string[]).slice(0, 10);\n const maxCharacters = (args.maxCharacters as number) ?? 10000;\n const livecrawl = (args.livecrawl as string) ?? 'fallback';\n\n const requestBody = {\n urls,\n text: { maxCharacters },\n livecrawl,\n };\n\n const response = await fetch('https://api.exa.ai/contents', {\n method: 'POST',\n headers: {\n 'x-api-key': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Exa get contents failed (${response.status}): ${errorText}`);\n }\n\n const data = await response.json() as {\n results: Array<{\n url: string;\n title?: string;\n author?: string;\n publishedDate?: string;\n text?: string;\n }>;\n };\n\n if (!data.results || data.results.length === 0) {\n return 'No content could be retrieved from the provided URLs.';\n }\n\n const formattedResults = data.results.map((result) => {\n const parts = [`## ${result.title ?? result.url}`];\n parts.push(`URL: ${result.url}`);\n if (result.author) parts.push(`Author: ${result.author}`);\n if (result.publishedDate) parts.push(`Date: ${result.publishedDate}`);\n parts.push('');\n if (result.text) {\n parts.push(result.text);\n } else {\n parts.push('[No text content available]');\n }\n return parts.join('\\n');\n }).join('\\n\\n---\\n\\n');\n\n return formattedResults;\n }\n}\n","/**\n * ExaResearchTool - Agentic web research using Exa.ai Research API\n *\n * The Research API is an asynchronous, multi-step pipeline that transforms\n * open-ended questions into grounded reports with citations. The system performs\n * planning, searching, and reasoning to produce comprehensive research outputs.\n *\n * See: https://docs.exa.ai/reference/exa-research\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\n\nexport interface ExaResearchConfig {\n apiKey?: string;\n model?: 'exa-research-fast' | 'exa-research' | 'exa-research-pro';\n pollInterval?: number; // Milliseconds between status checks (default: 2000)\n maxPollTime?: number; // Max time to poll in milliseconds (default: 300000 = 5 minutes)\n}\n\ninterface ResearchResponse {\n researchId: string;\n createdAt: number;\n model: string;\n instructions: string;\n status: 'pending' | 'running' | 'completed' | 'failed' | 'canceled';\n output?: {\n content: string; // Markdown report with citations\n parsed?: unknown; // Structured data if outputSchema provided\n };\n costDollars?: {\n total: number;\n numSearches: number;\n numPages: number;\n reasoningTokens: number;\n };\n finishedAt?: number;\n error?: string;\n events?: Array<Record<string, unknown>>;\n}\n\nexport class ExaResearchTool extends Tool {\n readonly name = 'exa_research';\n readonly description = 'Perform comprehensive web research using Exa.ai\\'s agentic research system. Provide natural-language instructions about what to research, and the AI research agent will plan searches, gather sources, extract facts, and synthesize findings into a detailed markdown report with citations. Ideal for deep research on any topic. Results typically complete in 20-90 seconds.';\n readonly inputs: ToolInputs = {\n instructions: {\n type: 'string',\n description: 'Natural-language task description of what to research (max 4096 characters). Be clear about what information you want, how research should be conducted, and what the output should contain.',\n required: true,\n },\n model: {\n type: 'string',\n description: 'Research model: \"exa-research-fast\" (faster, cheaper), \"exa-research\" (balanced, default), or \"exa-research-pro\" (most thorough)',\n required: false,\n },\n outputSchema: {\n type: 'object',\n description: 'Optional JSON Schema to enforce structured output format (max 8 root fields, 5 levels deep). If omitted, returns markdown report.',\n required: false,\n },\n };\n readonly outputType = 'string';\n\n private apiKey: string;\n private defaultModel: string;\n private pollInterval: number;\n private maxPollTime: number;\n\n constructor(config?: ExaResearchConfig) {\n super();\n this.apiKey = config?.apiKey ?? process.env.EXA_API_KEY ?? '';\n this.defaultModel = config?.model ?? 'exa-research';\n this.pollInterval = config?.pollInterval ?? 2000; // 2 seconds\n this.maxPollTime = config?.maxPollTime ?? 300000; // 5 minutes\n }\n\n async setup(): Promise<void> {\n if (!this.apiKey) {\n throw new Error('EXA_API_KEY is required. Set it as an environment variable or pass it in the config.');\n }\n this.isSetup = true;\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const instructions = args.instructions as string;\n const model = (args.model as string) ?? this.defaultModel;\n const outputSchema = args.outputSchema as Record<string, unknown> | undefined;\n\n if (!instructions || instructions.length > 4096) {\n throw new Error('Instructions are required and must be <= 4096 characters');\n }\n\n // Step 1: Create research task\n const createBody: Record<string, unknown> = {\n instructions,\n model,\n };\n\n if (outputSchema) {\n createBody.outputSchema = outputSchema;\n }\n\n const createResponse = await fetch('https://api.exa.ai/research/v1', {\n method: 'POST',\n headers: {\n 'x-api-key': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(createBody),\n });\n\n if (!createResponse.ok) {\n const errorText = await createResponse.text();\n throw new Error(`Failed to create research task (${createResponse.status}): ${errorText}`);\n }\n\n const createData = await createResponse.json() as { researchId: string };\n const researchId = createData.researchId;\n\n console.log(`Research task created: ${researchId}. Polling for results...`);\n\n // Step 2: Poll for completion\n const startTime = Date.now();\n let attempts = 0;\n\n while (Date.now() - startTime < this.maxPollTime) {\n attempts++;\n\n // Wait before polling (except first attempt)\n if (attempts > 1) {\n await new Promise(resolve => setTimeout(resolve, this.pollInterval));\n }\n\n const statusResponse = await fetch(`https://api.exa.ai/research/v1/${researchId}`, {\n method: 'GET',\n headers: {\n 'x-api-key': this.apiKey,\n },\n });\n\n if (!statusResponse.ok) {\n const errorText = await statusResponse.text();\n throw new Error(`Failed to check research status (${statusResponse.status}): ${errorText}`);\n }\n\n const statusData = await statusResponse.json() as ResearchResponse;\n\n if (statusData.status === 'completed') {\n // Success! Return the research output\n const output = statusData.output;\n if (!output) {\n throw new Error('Research completed but no output was returned');\n }\n\n // Format the response with cost information\n const sections: string[] = [];\n\n // Add the main content (markdown report or structured data)\n if (outputSchema && output.parsed) {\n sections.push('# Research Results (Structured)\\n');\n sections.push(JSON.stringify(output.parsed, null, 2));\n } else {\n sections.push(output.content);\n }\n\n // Add cost breakdown\n if (statusData.costDollars) {\n const cost = statusData.costDollars;\n sections.push('\\n---\\n');\n sections.push('## Research Metrics\\n');\n sections.push(`- **Cost**: $${cost.total.toFixed(4)}`);\n sections.push(`- **Searches**: ${cost.numSearches}`);\n sections.push(`- **Pages analyzed**: ${cost.numPages}`);\n sections.push(`- **Reasoning tokens**: ${cost.reasoningTokens.toLocaleString()}`);\n }\n\n console.log(`Research completed in ${attempts} polls (${((Date.now() - startTime) / 1000).toFixed(1)}s)`);\n return sections.join('\\n');\n }\n\n if (statusData.status === 'failed') {\n throw new Error(`Research failed: ${statusData.error ?? 'Unknown error'}`);\n }\n\n if (statusData.status === 'canceled') {\n throw new Error('Research was canceled');\n }\n\n // Still pending or running, continue polling\n if (attempts % 10 === 0) {\n console.log(`Still researching... (${attempts} polls, ${((Date.now() - startTime) / 1000).toFixed(0)}s elapsed)`);\n }\n }\n\n throw new Error(`Research timed out after ${this.maxPollTime / 1000}s. Task ID: ${researchId}`);\n }\n}\n","/**\n * ProxyTool - Bridges the smol-js agent runtime to an external standalone tool\n * executed in an isolated Bun process.\n *\n * The tool file is never imported into the main Node.js process. Instead, when\n * an agent invokes this proxy, it spawns `bun run <toolPath>` and communicates\n * via a lightweight stdin/stdout JSON protocol.\n *\n * Protocol (stdout of child):\n * - Lines prefixed with `[TOOL_OUTPUT]` are streaming log lines from the tool.\n * - A line prefixed with `[TOOL_RESULT]` contains the JSON-serialized return value.\n * - A line prefixed with `[TOOL_ERROR]` means the tool threw; payload is the message.\n * - Any other stdout line is treated as a streaming log line.\n *\n * Extensibility note: The transport (child_process + stdio) is encapsulated here.\n * A future subclass or factory could swap this for HTTP, gRPC, or IPC with no change\n * to the ProxyTool interface visible to agents or YAML definitions.\n */\n\nimport { spawn } from 'child_process';\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\nimport { ensureBunAvailable } from '../utils/bunInstaller.js';\n\n// --- Protocol delimiters (must match the standalone tool wrapper) ---\nexport const TOOL_OUTPUT_PREFIX = '[TOOL_OUTPUT]';\nexport const TOOL_RESULT_PREFIX = '[TOOL_RESULT]';\nexport const TOOL_ERROR_PREFIX = '[TOOL_ERROR]';\n\n/** How long (ms) to wait for the child process before forcefully killing it. */\nconst DEFAULT_TOOL_TIMEOUT_MS = 60_000;\n\nexport interface ProxyToolConfig {\n /** Absolute path to the .ts or .js tool file */\n toolPath: string;\n /** Tool name (must match the class name inside the file) */\n name: string;\n /** Human-readable description exposed to agents */\n description: string;\n /** Input schema that the LLM will see */\n inputs: ToolInputs;\n /** Output type label */\n outputType: string;\n /** Max execution time in ms (default 60 s) */\n timeout?: number;\n}\n\nexport class ProxyTool extends Tool {\n readonly name: string;\n readonly description: string;\n readonly inputs: ToolInputs;\n readonly outputType: string;\n\n private readonly toolPath: string;\n private readonly timeout: number;\n private bunPath: string | null = null;\n\n constructor(config: ProxyToolConfig) {\n super();\n this.name = config.name;\n this.description = config.description;\n this.inputs = config.inputs;\n this.outputType = config.outputType;\n this.toolPath = config.toolPath;\n this.timeout = config.timeout ?? DEFAULT_TOOL_TIMEOUT_MS;\n }\n\n /**\n * Ensure Bun is available before first invocation.\n */\n async setup(): Promise<void> {\n this.bunPath = await ensureBunAvailable();\n this.isSetup = true;\n }\n\n /**\n * Spawn the tool in a Bun child process, pass serialized args via CLI,\n * stream stdout back as log lines, and parse the final result.\n */\n async execute(args: Record<string, unknown>): Promise<unknown> {\n if (!this.bunPath) {\n await this.setup();\n }\n\n const serializedArgs = JSON.stringify(args);\n\n return new Promise<unknown>((resolve, reject) => {\n const child = spawn(this.bunPath!, ['run', this.toolPath, serializedArgs], {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: { ...process.env },\n });\n\n let result: unknown = undefined;\n let resultReceived = false;\n let errorMessage: string | null = null;\n const logBuffer: string[] = [];\n let stderr = '';\n\n // --- stdout handler: stream lines ---\n let partialLine = '';\n child.stdout.on('data', (chunk: Buffer) => {\n partialLine += chunk.toString('utf8');\n const lines = partialLine.split('\\n');\n // Last element is either '' (complete line) or a partial (incomplete)\n partialLine = lines.pop()!;\n\n for (const line of lines) {\n this.processLine(line, {\n onOutput: (msg) => logBuffer.push(msg),\n onResult: (value) => {\n result = value;\n resultReceived = true;\n },\n onError: (msg) => {\n errorMessage = msg;\n },\n });\n }\n });\n\n // --- stderr handler ---\n child.stderr.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n\n // --- timeout watchdog ---\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n reject(new Error(\n `Custom tool \"${this.name}\" timed out after ${this.timeout}ms. ` +\n 'The process was terminated. Check the tool for infinite loops or slow operations.'\n ));\n }, this.timeout);\n timer.unref(); // Don't keep Node alive just for the timer\n\n // --- process exit ---\n child.on('close', (code) => {\n clearTimeout(timer);\n\n // Flush any remaining partial line\n if (partialLine.trim()) {\n this.processLine(partialLine, {\n onOutput: (msg) => logBuffer.push(msg),\n onResult: (value) => { result = value; resultReceived = true; },\n onError: (msg) => { errorMessage = msg; },\n });\n }\n\n if (errorMessage) {\n reject(new Error(\n `Custom tool \"${this.name}\" reported an error: ${errorMessage}`\n ));\n return;\n }\n\n if (resultReceived) {\n // Prepend any captured log lines so agents have context\n if (logBuffer.length > 0) {\n const logPrefix = `[Tool output logs]\\n${logBuffer.join('\\n')}\\n\\n[Tool result]\\n`;\n if (typeof result === 'string') {\n resolve(logPrefix + result);\n } else {\n resolve({ logs: logBuffer.join('\\n'), result });\n }\n } else {\n resolve(result);\n }\n return;\n }\n\n // No result line received — treat stderr + stdout as the error\n const combined = (logBuffer.join('\\n') + '\\n' + stderr).trim();\n if (code !== 0) {\n reject(new Error(\n `Custom tool \"${this.name}\" exited with code ${code}. ` +\n `Output: ${combined || '(none)'}`\n ));\n } else {\n // Exit 0 but no [TOOL_RESULT] — be lenient, return logs\n resolve(combined || `Tool \"${this.name}\" produced no output.`);\n }\n });\n\n child.on('error', (err) => {\n clearTimeout(timer);\n reject(new Error(\n `Failed to spawn custom tool \"${this.name}\": ${err.message}`\n ));\n });\n });\n }\n\n // --- internal line parser ---\n private processLine(\n line: string,\n handlers: {\n onOutput: (msg: string) => void;\n onResult: (value: unknown) => void;\n onError: (msg: string) => void;\n }\n ): void {\n const trimmed = line.trimEnd();\n if (!trimmed) return;\n\n if (trimmed.startsWith(TOOL_RESULT_PREFIX)) {\n const json = trimmed.slice(TOOL_RESULT_PREFIX.length).trim();\n try {\n handlers.onResult(JSON.parse(json));\n } catch {\n // Malformed JSON — treat the raw string as the result\n handlers.onResult(json);\n }\n } else if (trimmed.startsWith(TOOL_ERROR_PREFIX)) {\n handlers.onError(trimmed.slice(TOOL_ERROR_PREFIX.length).trim());\n } else if (trimmed.startsWith(TOOL_OUTPUT_PREFIX)) {\n handlers.onOutput(trimmed.slice(TOOL_OUTPUT_PREFIX.length).trim());\n } else {\n // Untagged stdout is treated as tool output\n handlers.onOutput(trimmed);\n }\n }\n}\n","/**\n * Utility to locate or auto-install Bun for running custom tool processes.\n *\n * Strategy:\n * 1. Check if `bun` is already on PATH (shell-out `which bun` / `where bun`).\n * 2. Check the well-known local install path (~/.bun/bin/bun).\n * 3. If neither found, run the official one-liner installer\n * (https://bun.sh) and return the path to the newly installed binary.\n *\n * The installer runs exactly once per session; subsequent calls return the\n * cached path immediately.\n */\n\nimport { execSync, execFileSync } from 'child_process';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as os from 'os';\n\nlet cachedBunPath: string | null = null;\n\n/**\n * Resolve or install Bun. Returns the absolute path to the bun binary.\n * Throws if installation fails.\n */\nexport async function ensureBunAvailable(): Promise<string> {\n if (cachedBunPath) return cachedBunPath;\n\n // 1. Try PATH\n const fromPath = whichBun();\n if (fromPath) {\n cachedBunPath = fromPath;\n return fromPath;\n }\n\n // 2. Try well-known local path\n const localPath = path.join(os.homedir(), '.bun', 'bin', 'bun');\n if (fs.existsSync(localPath)) {\n cachedBunPath = localPath;\n return localPath;\n }\n\n // 3. Auto-install via official installer\n console.log(\n '\\n[smol-js] Bun is required to run custom tools but was not found. ' +\n 'Installing Bun automatically...\\n'\n );\n\n try {\n // The official install script: https://bun.sh\n execSync('curl --proto =https --tlsv1.2 -sSf https://bun.sh | bash', {\n stdio: 'inherit',\n shell: '/bin/bash',\n env: { ...process.env, HOME: os.homedir() },\n });\n } catch (err) {\n throw new Error(\n '[smol-js] Failed to auto-install Bun. Please install it manually: https://bun.sh\\n' +\n `Details: ${(err as Error).message}`\n );\n }\n\n // Verify install succeeded\n const afterInstall = whichBun() || (fs.existsSync(localPath) ? localPath : null);\n if (!afterInstall) {\n throw new Error(\n '[smol-js] Bun installation appeared to succeed but the binary was not found. ' +\n 'Please install manually: https://bun.sh'\n );\n }\n\n console.log(`[smol-js] Bun installed successfully at: ${afterInstall}\\n`);\n cachedBunPath = afterInstall;\n return afterInstall;\n}\n\nfunction whichBun(): string | null {\n try {\n const cmd = process.platform === 'win32' ? 'where bun' : 'which bun';\n const result = execSync(cmd, { encoding: 'utf8', stdio: 'pipe' }).trim();\n // `which` may return multiple lines on some systems; take the first\n const first = result.split('\\n')[0]?.trim();\n if (first && fs.existsSync(first)) return first;\n return null;\n } catch {\n return null;\n }\n}\n","/**\n * CustomToolScanner — discovers standalone tool files in a directory and\n * extracts their metadata so that ProxyTool instances can be registered\n * with the YAML loader.\n *\n * Convention over Configuration:\n * • Each file in the custom-tools folder must export a default metadata\n * object conforming to CustomToolMetadata (see standalone tool wrapper docs).\n * • The exported class name (or `name` field in metadata) MUST match the\n * file's basename (without extension). E.g. `WeatherLookup.ts` → name: \"WeatherLookup\".\n * • The tool is referenced in YAML by that same name.\n *\n * Metadata Extraction (zero-import approach):\n * We read the file as text and use a lightweight regex to pull the\n * `TOOL_METADATA` export block. This keeps the scanner decoupled from\n * Bun/ESM and lets it run purely in the Node.js main process.\n * The metadata block must be a single JSON object assigned to\n * `export const TOOL_METADATA = { ... };`\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { ToolInputs } from '../types.js';\nimport { ProxyTool, ProxyToolConfig } from './ProxyTool.js';\n\nexport interface CustomToolMetadata {\n /** Must match the file's basename (sans extension) */\n name: string;\n /** Human-readable description shown to the LLM */\n description: string;\n /** Input schema identical to Tool.inputs */\n inputs: ToolInputs;\n /** Output type label */\n outputType: string;\n /** Optional execution timeout in ms */\n timeout?: number;\n}\n\nexport interface DiscoveredTool {\n /** Absolute path to the tool file */\n filePath: string;\n /** Parsed metadata */\n metadata: CustomToolMetadata;\n}\n\n// Regex: captures everything between the braces of `export const TOOL_METADATA = { ... };`\n// This is intentionally lenient — it matches the first `TOOL_METADATA = ` and grabs until the\n// matching closing brace followed by an optional semicolon.\nconst METADATA_REGEX =\n /export\\s+const\\s+TOOL_METADATA\\s*=\\s*(\\{[\\s\\S]*?\\});\\s*$/m;\n\n/**\n * Scan a directory for custom tool files and extract their metadata.\n *\n * @param folderPath Absolute path to the custom-tools directory.\n * @returns Array of discovered tools with parsed metadata.\n * @throws If any file fails metadata extraction.\n */\nexport function scanCustomTools(folderPath: string): DiscoveredTool[] {\n if (!fs.existsSync(folderPath)) {\n throw new Error(\n `Custom tools folder not found: ${folderPath}. ` +\n 'Create the directory or check your --custom-tools-folder path.'\n );\n }\n\n const entries = fs.readdirSync(folderPath, { withFileTypes: true });\n const discovered: DiscoveredTool[] = [];\n\n for (const entry of entries) {\n if (entry.isDirectory()) continue;\n\n const ext = path.extname(entry.name).toLowerCase();\n if (ext !== '.ts' && ext !== '.js') continue;\n\n const filePath = path.resolve(folderPath, entry.name);\n const baseName = path.basename(entry.name, ext);\n\n let metadata: CustomToolMetadata;\n try {\n metadata = extractMetadata(filePath);\n } catch (err) {\n throw new Error(\n `Failed to extract TOOL_METADATA from \"${entry.name}\": ${(err as Error).message}\\n` +\n 'Ensure the file exports `export const TOOL_METADATA = { name, description, inputs, outputType };`'\n );\n }\n\n // Enforce: metadata.name must match the file's base name\n if (metadata.name !== baseName) {\n throw new Error(\n `Tool metadata name mismatch in \"${entry.name}\": ` +\n `file is \"${baseName}\" but TOOL_METADATA.name is \"${metadata.name}\". ` +\n 'They must match (Convention over Configuration).'\n );\n }\n\n discovered.push({ filePath, metadata });\n }\n\n return discovered;\n}\n\n/**\n * Read a tool file and extract the TOOL_METADATA export via regex.\n */\nfunction extractMetadata(filePath: string): CustomToolMetadata {\n const source = fs.readFileSync(filePath, 'utf8');\n const match = source.match(METADATA_REGEX);\n\n if (!match) {\n throw new Error(\n 'No `export const TOOL_METADATA = { ... };` block found. ' +\n 'Add the metadata export at the bottom of your tool file.'\n );\n }\n\n let parsed: CustomToolMetadata;\n try {\n // Use Function constructor to safely evaluate the object literal.\n // This handles JS object syntax (unquoted keys, trailing commas) that\n // strict JSON.parse would reject.\n parsed = new Function(`\"use strict\"; return (${match[1]});`)() as CustomToolMetadata;\n } catch (err) {\n throw new Error(\n `Could not parse TOOL_METADATA object: ${(err as Error).message}. ` +\n 'Ensure it is a valid JavaScript object literal.'\n );\n }\n\n // Validate required fields\n if (!parsed.name || typeof parsed.name !== 'string') {\n throw new Error('TOOL_METADATA.name must be a non-empty string.');\n }\n if (!parsed.description || typeof parsed.description !== 'string') {\n throw new Error('TOOL_METADATA.description must be a non-empty string.');\n }\n if (!parsed.inputs || typeof parsed.inputs !== 'object') {\n throw new Error('TOOL_METADATA.inputs must be an object mapping parameter names to their schemas.');\n }\n if (!parsed.outputType || typeof parsed.outputType !== 'string') {\n throw new Error('TOOL_METADATA.outputType must be a non-empty string.');\n }\n\n return parsed;\n}\n\n/**\n * Scan a folder and return a Map<toolName, ProxyTool> ready for registration\n * with YAMLLoader.\n */\nexport function loadCustomTools(folderPath: string): Map<string, ProxyTool> {\n const discovered = scanCustomTools(folderPath);\n const tools = new Map<string, ProxyTool>();\n\n for (const { filePath, metadata } of discovered) {\n const config: ProxyToolConfig = {\n toolPath: filePath,\n name: metadata.name,\n description: metadata.description,\n inputs: metadata.inputs,\n outputType: metadata.outputType,\n timeout: metadata.timeout,\n };\n\n tools.set(metadata.name, new ProxyTool(config));\n }\n\n return tools;\n}\n","/**\n * YAMLLoader - Loads and parses YAML workflow definitions into runnable agents\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport YAML from 'yaml';\nimport type { YAMLWorkflowDefinition, YAMLAgentDefinition, YAMLModelDefinition } from '../types.js';\nimport { Agent } from '../agents/Agent.js';\nimport { CodeAgent } from '../agents/CodeAgent.js';\nimport { ToolUseAgent } from '../agents/ToolUseAgent.js';\nimport { Tool } from '../tools/Tool.js';\nimport { AgentTool } from '../tools/AgentTool.js';\nimport { OpenAIModel } from '../models/OpenAIModel.js';\nimport { ReadFileTool } from '../tools/ReadFileTool.js';\nimport { WriteFileTool } from '../tools/WriteFileTool.js';\nimport { CurlTool } from '../tools/CurlTool.js';\nimport { ExaSearchTool } from '../tools/ExaSearchTool.js';\nimport { ExaGetContentsTool } from '../tools/ExaGetContentsTool.js';\nimport { ExaResearchTool } from '../tools/ExaResearchTool.js';\nimport { FinalAnswerTool } from '../tools/defaultTools.js';\n\n// Registry of built-in tool types\nconst TOOL_REGISTRY: Record<string, new (config?: Record<string, unknown>) => Tool> = {\n read_file: ReadFileTool as unknown as new (config?: Record<string, unknown>) => Tool,\n write_file: WriteFileTool as unknown as new (config?: Record<string, unknown>) => Tool,\n curl: CurlTool as unknown as new (config?: Record<string, unknown>) => Tool,\n exa_search: ExaSearchTool as unknown as new (config?: Record<string, unknown>) => Tool,\n exa_get_contents: ExaGetContentsTool as unknown as new (config?: Record<string, unknown>) => Tool,\n exa_research: ExaResearchTool as unknown as new (config?: Record<string, unknown>) => Tool,\n final_answer: FinalAnswerTool as unknown as new (config?: Record<string, unknown>) => Tool,\n};\n\nexport interface LoadedWorkflow {\n name: string;\n description?: string;\n entrypointAgent: Agent;\n agents: Map<string, Agent>;\n tools: Map<string, Tool>;\n}\n\nexport class YAMLLoader {\n private customTools: Map<string, new (config?: Record<string, unknown>) => Tool> = new Map();\n private toolInstances: Map<string, Tool> = new Map();\n\n /**\n * Register a custom tool type (class) for use in YAML definitions.\n */\n registerToolType(typeName: string, toolClass: new (config?: Record<string, unknown>) => Tool): void {\n this.customTools.set(typeName, toolClass);\n }\n\n /**\n * Register a pre-built tool instance for use in YAML definitions.\n * Used by the custom tool system to register ProxyTool instances\n * that are created by the scanner rather than by class instantiation.\n */\n registerToolInstance(typeName: string, tool: Tool): void {\n this.toolInstances.set(typeName, tool);\n }\n\n /**\n * Load a workflow from a YAML file path.\n */\n loadFromFile(filePath: string): LoadedWorkflow {\n const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);\n\n if (!fs.existsSync(absolutePath)) {\n throw new Error(`Workflow file not found: ${absolutePath}`);\n }\n\n const content = fs.readFileSync(absolutePath, 'utf-8');\n return this.loadFromString(content);\n }\n\n /**\n * Load a workflow from a YAML string.\n */\n loadFromString(yamlContent: string): LoadedWorkflow {\n const definition = YAML.parse(yamlContent) as YAMLWorkflowDefinition;\n return this.buildWorkflow(definition);\n }\n\n /**\n * Build a runnable workflow from a parsed definition.\n */\n private buildWorkflow(definition: YAMLWorkflowDefinition): LoadedWorkflow {\n if (!definition.name) {\n throw new Error('Workflow must have a name');\n }\n if (!definition.entrypoint) {\n throw new Error('Workflow must have an entrypoint agent');\n }\n if (!definition.agents) {\n throw new Error('Workflow must define at least one agent');\n }\n\n // Build tools\n const tools = new Map<string, Tool>();\n if (definition.tools) {\n for (const [name, toolDef] of Object.entries(definition.tools)) {\n const tool = this.buildTool(name, toolDef.type, toolDef.config);\n tools.set(name, tool);\n }\n }\n\n // Build agents (handling dependencies between agents)\n const agents = new Map<string, Agent>();\n const agentDefs = definition.agents;\n\n // Topological sort: build agents that don't depend on other agents first\n const resolved = new Set<string>();\n const maxIterations = Object.keys(agentDefs).length * 2;\n let iterations = 0;\n\n while (resolved.size < Object.keys(agentDefs).length && iterations < maxIterations) {\n iterations++;\n for (const [agentName, agentDef] of Object.entries(agentDefs)) {\n if (resolved.has(agentName)) continue;\n\n // Check if all agent dependencies are resolved\n const agentDeps = agentDef.agents ?? [];\n const allDepsResolved = agentDeps.every(dep => resolved.has(dep));\n\n if (allDepsResolved) {\n const agent = this.buildAgent(\n agentName,\n agentDef,\n definition.model,\n tools,\n agents,\n definition.globalMaxContextLength\n );\n agents.set(agentName, agent);\n resolved.add(agentName);\n }\n }\n }\n\n if (resolved.size < Object.keys(agentDefs).length) {\n const unresolved = Object.keys(agentDefs).filter(n => !resolved.has(n));\n throw new Error(`Circular or unresolvable agent dependencies: ${unresolved.join(', ')}`);\n }\n\n const entrypointAgent = agents.get(definition.entrypoint);\n if (!entrypointAgent) {\n throw new Error(`Entrypoint agent \"${definition.entrypoint}\" not found in agents`);\n }\n\n return {\n name: definition.name,\n description: definition.description,\n entrypointAgent,\n agents,\n tools,\n };\n }\n\n /**\n * Build a tool instance from a type name and config.\n */\n private buildTool(name: string, type: string, config?: Record<string, unknown>): Tool {\n // Check for pre-registered tool instances first (e.g. ProxyTool from custom tools scanner)\n const existingInstance = this.toolInstances.get(type);\n if (existingInstance) {\n if (name !== type && name !== existingInstance.name) {\n Object.defineProperty(existingInstance, 'name', { value: name, writable: false });\n }\n return existingInstance;\n }\n\n const ToolClass = TOOL_REGISTRY[type] ?? this.customTools.get(type);\n\n if (!ToolClass) {\n throw new Error(`Unknown tool type: ${type}. Available types: ${[...Object.keys(TOOL_REGISTRY), ...this.customTools.keys(), ...this.toolInstances.keys()].join(', ')}`);\n }\n\n const tool = new ToolClass(config);\n // Override name if different from type\n if (name !== type && name !== tool.name) {\n Object.defineProperty(tool, 'name', { value: name, writable: false });\n }\n return tool;\n }\n\n /**\n * Build an agent instance from a YAML definition.\n */\n private buildAgent(\n name: string,\n definition: YAMLAgentDefinition,\n globalModel?: YAMLModelDefinition,\n availableTools?: Map<string, Tool>,\n resolvedAgents?: Map<string, Agent>,\n globalMaxContextLength?: number\n ): Agent {\n // Build model\n const modelConfig = definition.model ?? globalModel;\n const model = new OpenAIModel({\n modelId: modelConfig?.modelId,\n apiKey: modelConfig?.apiKey,\n baseUrl: modelConfig?.baseUrl,\n maxTokens: definition.maxTokens ?? modelConfig?.maxTokens,\n temperature: definition.temperature ?? modelConfig?.temperature,\n timeout: modelConfig?.timeout,\n });\n\n // Collect tools\n const agentTools: Tool[] = [];\n\n // Add referenced tools\n if (definition.tools && availableTools) {\n for (const toolName of definition.tools) {\n const tool = availableTools.get(toolName);\n if (tool) {\n agentTools.push(tool);\n } else {\n // Try pre-registered instance (e.g. custom ProxyTool)\n const instance = this.toolInstances.get(toolName);\n if (instance) {\n agentTools.push(instance);\n } else {\n // Try to create from registry directly\n const ToolClass = TOOL_REGISTRY[toolName] ?? this.customTools.get(toolName);\n if (ToolClass) {\n agentTools.push(new ToolClass());\n } else {\n throw new Error(`Tool \"${toolName}\" not found for agent \"${name}\"`);\n }\n }\n }\n }\n }\n\n // Add sub-agents as tools\n if (definition.agents && resolvedAgents) {\n for (const subAgentName of definition.agents) {\n const subAgent = resolvedAgents.get(subAgentName);\n if (!subAgent) {\n throw new Error(`Sub-agent \"${subAgentName}\" not found for agent \"${name}\"`);\n }\n agentTools.push(new AgentTool({\n agent: subAgent,\n name: subAgentName,\n description: definition.description\n ? `Sub-agent: ${subAgentName}`\n : `Delegate tasks to the ${subAgentName} agent`,\n }));\n }\n }\n\n const maxContextLength = definition.maxContextLength ?? globalMaxContextLength;\n\n // Build the agent based on type\n if (definition.type === 'CodeAgent') {\n return new CodeAgent({\n model,\n tools: agentTools,\n maxSteps: definition.maxSteps,\n customInstructions: definition.customInstructions,\n persistent: definition.persistent,\n maxContextLength,\n memoryStrategy: definition.memoryStrategy,\n maxTokens: definition.maxTokens,\n temperature: definition.temperature,\n name,\n });\n } else {\n // Default: ToolUseAgent\n return new ToolUseAgent({\n model,\n tools: agentTools,\n maxSteps: definition.maxSteps,\n customInstructions: definition.customInstructions,\n persistent: definition.persistent,\n maxContextLength,\n memoryStrategy: definition.memoryStrategy,\n maxTokens: definition.maxTokens,\n temperature: definition.temperature,\n name,\n });\n }\n }\n}\n","/**\n * Orchestrator - Loads, runs, and provides real-time visibility into agent execution\n */\n\nimport chalk from 'chalk';\nimport type { OrchestratorEvent, RunResult, OutputFormat, TokenUsage } from '../types.js';\nimport { Agent } from '../agents/Agent.js';\nimport { YAMLLoader, LoadedWorkflow } from './YAMLLoader.js';\nimport { JSONOutputHandler } from '../output/JSONOutputHandler.js';\n\nexport interface OrchestratorConfig {\n /** Whether to display real-time output (default: true) */\n verbose?: boolean;\n /** Callback for orchestrator events */\n onEvent?: (event: OrchestratorEvent) => void;\n /** Output format: 'text' for chalk-formatted console, 'json' for NDJSON streaming */\n outputFormat?: OutputFormat;\n /** Unique run identifier (required for JSON output) */\n runId?: string;\n /** Working directory for agent file operations */\n cwd?: string;\n}\n\nexport class Orchestrator {\n private loader: YAMLLoader;\n private config: OrchestratorConfig;\n private activeAgents: Map<string, { agent: Agent; depth: number }> = new Map();\n private eventLog: OrchestratorEvent[] = [];\n private jsonOutput: JSONOutputHandler | null = null;\n private isJsonMode: boolean = false;\n\n constructor(config: OrchestratorConfig = {}) {\n this.loader = new YAMLLoader();\n this.isJsonMode = config.outputFormat === 'json';\n this.config = {\n verbose: config.verbose ?? true,\n onEvent: config.onEvent,\n outputFormat: config.outputFormat ?? 'text',\n runId: config.runId,\n cwd: config.cwd,\n };\n\n // Initialize JSON output handler if in JSON mode\n if (this.isJsonMode) {\n if (!config.runId) {\n throw new Error('runId is required for JSON output mode');\n }\n this.jsonOutput = new JSONOutputHandler({\n runId: config.runId,\n verbose: config.verbose ?? true,\n });\n }\n }\n\n /**\n * Load a workflow from a YAML file.\n */\n loadWorkflow(filePath: string): LoadedWorkflow {\n const workflow = this.loader.loadFromFile(filePath);\n this.displayWorkflowInfo(workflow, filePath);\n return workflow;\n }\n\n /**\n * Load a workflow from YAML string.\n */\n loadWorkflowFromString(yamlContent: string, sourcePath?: string): LoadedWorkflow {\n const workflow = this.loader.loadFromString(yamlContent);\n this.displayWorkflowInfo(workflow, sourcePath);\n return workflow;\n }\n\n /**\n * Run a loaded workflow with a task.\n */\n async runWorkflow(workflow: LoadedWorkflow, task: string, workflowPath?: string): Promise<RunResult> {\n this.displayRunStart(workflow.name, task, workflowPath);\n\n // Set up event tracking on the entrypoint agent\n this.instrumentAgent(workflow.entrypointAgent, workflow.entrypointAgent.getName(), 0);\n\n // Also instrument sub-agents\n for (const [name, agent] of workflow.agents) {\n if (agent !== workflow.entrypointAgent) {\n this.instrumentAgent(agent, name, 1);\n }\n }\n\n try {\n const result = await workflow.entrypointAgent.run(task);\n this.displayRunEnd(result, true);\n return result;\n } catch (error) {\n this.displayError(error as Error);\n // Emit run end with failure in JSON mode\n if (this.isJsonMode && this.jsonOutput) {\n this.jsonOutput.emitRunEnd(false, null, 0, 0);\n }\n throw error;\n }\n }\n\n /**\n * Run a standalone agent with a task.\n */\n async runAgent(agent: Agent, task: string): Promise<RunResult> {\n this.instrumentAgent(agent, agent.getName(), 0);\n const result = await agent.run(task);\n return result;\n }\n\n /**\n * Instrument an agent with orchestrator event tracking.\n */\n private instrumentAgent(agent: Agent, name: string, depth: number): void {\n this.activeAgents.set(name, { agent, depth });\n\n // Set up event callback to capture and emit events\n agent.setOnEvent((event) => {\n // Log the event to our event log\n const orchestratorEvent: OrchestratorEvent = {\n type: event.type as OrchestratorEvent['type'],\n agentName: name,\n depth,\n data: event.data,\n timestamp: Date.now(),\n };\n this.logEvent(orchestratorEvent);\n\n // In JSON mode, emit detailed events\n if (this.isJsonMode && this.jsonOutput) {\n this.emitAgentEventAsJSON(event, name, depth);\n }\n });\n }\n\n /**\n * Emit an agent event as JSON.\n */\n private emitAgentEventAsJSON(\n event: { type: string; data: unknown },\n agentName: string,\n depth: number\n ): void {\n if (!this.jsonOutput) return;\n\n const data = event.data as Record<string, unknown>;\n\n switch (event.type) {\n case 'agent_start':\n this.jsonOutput.emitAgentStart(\n agentName,\n depth,\n data.task as string,\n data.name ? 'ToolUseAgent' : 'CodeAgent', // Will be improved\n 20 // Default maxSteps, could be passed\n );\n break;\n\n case 'agent_step':\n this.jsonOutput.emitAgentStep(\n agentName,\n depth,\n data.step as number,\n data.maxSteps as number,\n 'start'\n );\n break;\n\n case 'agent_thinking':\n this.jsonOutput.emitAgentThinking(\n agentName,\n depth,\n data.step as number,\n data.content as string,\n false\n );\n break;\n\n case 'agent_tool_call':\n this.jsonOutput.emitToolCall(\n agentName,\n depth,\n data.step as number,\n data.toolCallId as string,\n data.toolName as string,\n data.arguments as Record<string, unknown>\n );\n break;\n\n case 'agent_tool_result':\n this.jsonOutput.emitToolResult(\n agentName,\n depth,\n data.step as number,\n data.toolCallId as string,\n data.toolName as string,\n data.result,\n data.error as string | undefined,\n data.duration as number\n );\n break;\n\n case 'agent_observation':\n this.jsonOutput.emitObservation(\n agentName,\n depth,\n data.step as number,\n data.observation as string,\n data.codeAction as string | undefined,\n data.logs as string | undefined\n );\n break;\n\n case 'agent_error':\n this.jsonOutput.emitError(\n data.error as string,\n undefined,\n agentName,\n depth,\n data.step as number\n );\n break;\n\n case 'agent_end':\n this.jsonOutput.emitAgentEnd(\n agentName,\n depth,\n data.output,\n 0, // totalSteps - would need to track\n data.tokenUsage as TokenUsage,\n data.duration as number,\n true\n );\n break;\n }\n }\n\n /**\n * Display workflow info at startup.\n */\n private displayWorkflowInfo(workflow: LoadedWorkflow, _sourcePath?: string): void {\n const agents = Array.from(workflow.agents.keys());\n const tools = Array.from(workflow.tools.keys());\n const entrypoint = workflow.entrypointAgent.getName();\n\n if (this.isJsonMode && this.jsonOutput) {\n this.jsonOutput.emitWorkflowLoaded(\n workflow.name,\n workflow.description,\n agents,\n tools,\n entrypoint\n );\n return;\n }\n\n if (!this.config.verbose) return;\n\n const line = '═'.repeat(70);\n console.log(chalk.cyan(line));\n console.log(chalk.cyan.bold(` Workflow: ${workflow.name}`));\n if (workflow.description) {\n console.log(chalk.cyan(` ${workflow.description}`));\n }\n console.log(chalk.cyan(` Agents: ${agents.join(', ')}`));\n console.log(chalk.cyan(` Tools: ${tools.join(', ') || '(none defined at workflow level)'}`));\n console.log(chalk.cyan(` Entrypoint: ${entrypoint}`));\n console.log(chalk.cyan(line));\n console.log();\n }\n\n /**\n * Display run start info.\n */\n private displayRunStart(workflowName: string, task: string, workflowPath?: string): void {\n if (this.isJsonMode && this.jsonOutput) {\n this.jsonOutput.emitRunStart(workflowPath || workflowName, task, this.config.cwd);\n return;\n }\n\n if (!this.config.verbose) return;\n console.log(chalk.green.bold(`\\n▶ Running workflow \"${workflowName}\"`));\n console.log(chalk.green(` Task: ${task}`));\n console.log(chalk.gray('─'.repeat(70)));\n }\n\n /**\n * Display run completion info.\n */\n private displayRunEnd(result: RunResult, success: boolean = true): void {\n if (this.isJsonMode && this.jsonOutput) {\n this.jsonOutput.emitRunEnd(\n success,\n result.output,\n result.tokenUsage.totalTokens,\n result.steps.length\n );\n return;\n }\n\n if (!this.config.verbose) return;\n console.log(chalk.gray('\\n' + '─'.repeat(70)));\n console.log(chalk.green.bold(`\\n✅ Workflow complete`));\n console.log(chalk.green(` Duration: ${(result.duration / 1000).toFixed(2)}s`));\n console.log(chalk.green(` Tokens: ${result.tokenUsage.totalTokens}`));\n console.log(chalk.green(` Steps: ${result.steps.length}`));\n\n const outputStr = typeof result.output === 'string'\n ? result.output\n : JSON.stringify(result.output, null, 2);\n console.log(chalk.magenta.bold('\\n Final Output:'));\n // Indent output\n const indentedOutput = outputStr.split('\\n').map(line => ` ${line}`).join('\\n');\n console.log(chalk.magenta(indentedOutput));\n console.log();\n }\n\n /**\n * Display an error.\n */\n private displayError(error: Error): void {\n if (this.isJsonMode && this.jsonOutput) {\n this.jsonOutput.emitError(error.message, error.stack);\n return;\n }\n\n if (!this.config.verbose) return;\n console.error(chalk.red.bold(`\\n❌ Workflow failed: ${error.message}`));\n if (error.stack) {\n console.error(chalk.red.dim(error.stack));\n }\n }\n\n /**\n * Log an orchestration event.\n */\n logEvent(event: OrchestratorEvent): void {\n this.eventLog.push(event);\n if (this.config.onEvent) {\n this.config.onEvent(event);\n }\n }\n\n /**\n * Get the event log.\n */\n getEventLog(): OrchestratorEvent[] {\n return [...this.eventLog];\n }\n\n /**\n * Get the YAML loader for registering custom tools.\n */\n getLoader(): YAMLLoader {\n return this.loader;\n }\n\n /**\n * Get the JSON output handler (if in JSON mode).\n */\n getJSONOutputHandler(): JSONOutputHandler | null {\n return this.jsonOutput;\n }\n\n /**\n * Check if in JSON output mode.\n */\n isJSONOutputMode(): boolean {\n return this.isJsonMode;\n }\n\n /**\n * Get the run ID.\n */\n getRunId(): string | undefined {\n return this.config.runId;\n }\n}\n","/**\n * JSONOutputHandler - Emits structured NDJSON events for machine-readable CLI output.\n */\n\nimport type { TokenUsage } from '../types.js';\n\nexport interface JSONOutputConfig {\n runId: string;\n verbose?: boolean;\n}\n\nexport class JSONOutputHandler {\n private readonly runId: string;\n private readonly startTime: number;\n\n constructor(config: JSONOutputConfig) {\n this.runId = config.runId;\n this.startTime = Date.now();\n }\n\n private emit(type: string, data: unknown, extra: Record<string, unknown> = {}): void {\n console.log(JSON.stringify({\n runId: this.runId,\n timestamp: Date.now(),\n type,\n ...extra,\n data,\n }));\n }\n\n emitRunStart(workflowPath: string, task: string, cwd?: string): void {\n this.emit('run_start', { workflowPath, task, cwd });\n }\n\n emitWorkflowLoaded(name: string, description: string | undefined, agents: string[], tools: string[], entrypoint: string): void {\n this.emit('workflow_loaded', { name, description, agents, tools, entrypoint });\n }\n\n emitRunEnd(success: boolean, output: unknown, totalTokens: number, totalSteps: number): void {\n this.emit('run_end', {\n success,\n output,\n totalDuration: Date.now() - this.startTime,\n totalTokens,\n totalSteps,\n });\n }\n\n emitAgentStart(agentName: string, depth: number, task: string, agentType: string, maxSteps: number): void {\n this.emit('agent_start', { task, agentType, maxSteps }, { agentName, depth });\n }\n\n emitAgentEnd(agentName: string, depth: number, output: unknown, totalSteps: number, tokenUsage: TokenUsage | undefined, duration: number, success: boolean): void {\n this.emit('agent_end', { output, totalSteps, tokenUsage, duration, success }, { agentName, depth });\n }\n\n emitAgentStep(agentName: string, depth: number, stepNumber: number, maxSteps: number, phase: string): void {\n this.emit('agent_step', { stepNumber, maxSteps, phase }, { agentName, depth });\n }\n\n emitAgentThinking(agentName: string, depth: number, stepNumber: number, content: string, isPartial: boolean): void {\n this.emit('agent_thinking', { stepNumber, content, isPartial }, { agentName, depth });\n }\n\n emitToolCall(agentName: string, depth: number, stepNumber: number, toolCallId: string, toolName: string, args: Record<string, unknown>): void {\n this.emit('agent_tool_call', { stepNumber, toolCallId, toolName, arguments: args }, { agentName, depth });\n }\n\n emitToolResult(agentName: string, depth: number, stepNumber: number, toolCallId: string, toolName: string, result: unknown, error: string | undefined, duration: number): void {\n this.emit('agent_tool_result', { stepNumber, toolCallId, toolName, result, error, duration }, { agentName, depth });\n }\n\n emitObservation(agentName: string, depth: number, stepNumber: number, observation: string, codeAction: string | undefined, logs: string | undefined): void {\n this.emit('agent_observation', { stepNumber, observation, codeAction, logs }, { agentName, depth });\n }\n\n emitError(message: string, stack?: string, agentName?: string, depth?: number, stepNumber?: number): void {\n this.emit('error', { message, stack, stepNumber }, {\n ...(agentName ? { agentName } : {}),\n ...(depth !== undefined ? { depth } : {}),\n });\n }\n}\n"],"mappings":";AA4HO,IAAK,WAAL,kBAAKA,cAAL;AACL,EAAAA,oBAAA,SAAM,MAAN;AACA,EAAAA,oBAAA,WAAQ,KAAR;AACA,EAAAA,oBAAA,UAAO,KAAP;AACA,EAAAA,oBAAA,WAAQ,KAAR;AAJU,SAAAA;AAAA,GAAA;;;ACrGZ,SAAS,eAAe,MAAsB;AAC5C,SAAO,KAAK,KAAK,KAAK,SAAS,CAAC;AAClC;AAEA,SAAS,uBAAuB,UAAiC;AAC/D,MAAI,QAAQ;AACZ,aAAW,OAAO,UAAU;AAC1B,aAAS,eAAe,IAAI,WAAW,EAAE;AACzC,QAAI,IAAI,WAAW;AACjB,eAAS,eAAe,KAAK,UAAU,IAAI,SAAS,CAAC;AAAA,IACvD;AACA,aAAS;AAAA,EACX;AACA,SAAO;AACT;AAEO,IAAM,cAAN,MAAkB;AAAA;AAAA,EAEvB;AAAA;AAAA,EAGA,QAAqD,CAAC;AAAA,EAE9C;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,cAAsB,QAAuB;AACvD,SAAK,eAAe;AAAA,MAClB,MAAM;AAAA,MACN,SAAS;AAAA,MACT,WAAW,KAAK,IAAI;AAAA,IACtB;AACA,SAAK,mBAAmB,QAAQ,oBAAoB;AACpD,SAAK,iBAAiB,QAAQ,kBAAkB;AAChD,SAAK,QAAQ,QAAQ;AAAA,EACvB;AAAA;AAAA,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,EAKA,YAAwB;AACtB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,uBAAiD;AAC/C,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,mBAA4B;AAC1B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,WAA+B;AAC7B,WAAO,KAAK,OAAO;AAAA,EACrB;AACF;","names":["LogLevel","resolve","fs","path","os","resolve","fs","path","fs","path","resolve","path","fs","os","resolve","fs","path","fs","path","chalk","chalk"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/memory/AgentMemory.ts","../src/logging/AgentLogger.ts","../src/agents/Agent.ts","../src/executor/LocalExecutor.ts","../src/tools/Tool.ts","../src/tools/defaultTools.ts","../src/prompts/codeAgent.ts","../src/agents/CodeAgent.ts","../src/prompts/toolUseAgent.ts","../src/agents/ToolUseAgent.ts","../src/models/Model.ts","../src/models/OpenAIModel.ts","../src/tools/AgentTool.ts","../src/tools/ReadFileTool.ts","../src/tools/WriteFileTool.ts","../src/tools/CurlTool.ts","../src/tools/ExaSearchTool.ts","../src/tools/ExaGetContentsTool.ts","../src/tools/ExaResearchTool.ts","../src/tools/ProxyTool.ts","../src/utils/bunInstaller.ts","../src/tools/CustomToolScanner.ts","../src/orchestrator/YAMLLoader.ts","../src/orchestrator/Orchestrator.ts","../src/output/JSONOutputHandler.ts"],"sourcesContent":["/**\n * Core types for smol-js\n */\n\n// Message roles following OpenAI chat completions format\nexport type MessageRole = 'system' | 'user' | 'assistant' | 'tool';\n\n// Token usage tracking\nexport interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n}\n\n// Timing information for steps\nexport interface Timing {\n startTime: number;\n endTime?: number;\n duration?: number;\n}\n\n// Chat message structure\nexport interface ChatMessage {\n role: MessageRole;\n content: string | null;\n name?: string;\n toolCalls?: ToolCall[];\n toolCallId?: string;\n tokenUsage?: TokenUsage;\n}\n\n// Tool call structure (OpenAI format)\nexport interface ToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string | Record<string, unknown>;\n };\n}\n\n// Tool input schema type\nexport type ToolInputType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'array'\n | 'object'\n | 'any';\n\n// Tool input definition\nexport interface ToolInput {\n type: ToolInputType;\n description: string;\n required?: boolean;\n default?: unknown;\n enum?: string[];\n}\n\n// Tool inputs schema\nexport interface ToolInputs {\n [key: string]: ToolInput;\n}\n\n// OpenAI function tool definition\nexport interface OpenAIToolDefinition {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: {\n type: 'object';\n properties: Record<string, unknown>;\n required?: string[];\n };\n };\n}\n\n// Code execution output\nexport interface CodeExecutionOutput {\n output: unknown;\n logs: string;\n isFinalAnswer: boolean;\n error?: Error;\n}\n\n// Action output from a step\nexport interface ActionOutput {\n output: unknown;\n isFinalAnswer: boolean;\n}\n\n// Memory management strategy\nexport type MemoryStrategy = 'truncate' | 'compact';\n\n// Agent configuration\nexport interface AgentConfig {\n model: Model;\n tools?: Tool[];\n maxSteps?: number;\n codeExecutionDelay?: number;\n systemPrompt?: string;\n additionalAuthorizedImports?: string[];\n streamOutputs?: boolean;\n verboseLevel?: LogLevel;\n persistent?: boolean;\n maxContextLength?: number;\n memoryStrategy?: MemoryStrategy;\n customInstructions?: string;\n maxTokens?: number;\n temperature?: number;\n}\n\n// Model configuration\nexport interface ModelConfig {\n modelId?: string;\n apiKey?: string;\n baseUrl?: string;\n maxTokens?: number;\n temperature?: number;\n timeout?: number;\n}\n\n// Log levels\nexport enum LogLevel {\n OFF = -1,\n ERROR = 0,\n INFO = 1,\n DEBUG = 2,\n}\n\n// Step types for memory\nexport type StepType = 'system' | 'task' | 'action' | 'planning' | 'final';\n\n// Base memory step\nexport interface MemoryStep {\n type: StepType;\n timestamp: number;\n}\n\n// System prompt step\nexport interface SystemPromptStep extends MemoryStep {\n type: 'system';\n content: string;\n}\n\n// Task step\nexport interface TaskStep extends MemoryStep {\n type: 'task';\n task: string;\n}\n\n// Action step - main execution step\nexport interface ActionStep extends MemoryStep {\n type: 'action';\n stepNumber: number;\n timing: Timing;\n modelInputMessages: ChatMessage[];\n modelOutputMessage?: ChatMessage;\n codeAction?: string;\n toolCalls?: ToolCall[];\n toolResults?: ToolCallResult[];\n observation?: string;\n actionOutput?: ActionOutput;\n tokenUsage?: TokenUsage;\n error?: Error;\n isFinalAnswer?: boolean;\n}\n\n// Tool call result\nexport interface ToolCallResult {\n toolCallId: string;\n toolName: string;\n result: unknown;\n error?: string;\n}\n\n// Final answer step\nexport interface FinalAnswerStep extends MemoryStep {\n type: 'final';\n answer: unknown;\n}\n\n// Stream event types\nexport interface StreamEvent {\n type: 'delta' | 'toolCall' | 'observation' | 'step' | 'final' | 'error';\n data: unknown;\n}\n\n// Run result\nexport interface RunResult {\n output: unknown;\n steps: MemoryStep[];\n tokenUsage: TokenUsage;\n duration: number;\n}\n\n// Forward declarations for circular deps\nexport interface Tool {\n name: string;\n description: string;\n inputs: ToolInputs;\n outputType: string;\n execute: (args: Record<string, unknown>) => Promise<unknown>;\n toCodePrompt: () => string;\n toOpenAITool: () => OpenAIToolDefinition;\n}\n\nexport interface Model {\n modelId: string;\n generate: (\n messages: ChatMessage[],\n options?: GenerateOptions\n ) => Promise<ChatMessage>;\n generateStream?: (\n messages: ChatMessage[],\n options?: GenerateOptions\n ) => AsyncGenerator<string, ChatMessage, undefined>;\n}\n\n// Generation options\nexport interface GenerateOptions {\n stopSequences?: string[];\n maxTokens?: number;\n temperature?: number;\n tools?: Tool[];\n toolDefinitions?: OpenAIToolDefinition[];\n}\n\n// YAML agent definition\nexport interface YAMLAgentDefinition {\n name: string;\n type: 'ToolUseAgent' | 'CodeAgent';\n description?: string;\n model?: YAMLModelDefinition;\n tools?: string[];\n agents?: string[];\n maxSteps?: number;\n maxTokens?: number;\n temperature?: number;\n persistent?: boolean;\n maxContextLength?: number;\n memoryStrategy?: MemoryStrategy;\n customInstructions?: string;\n systemPrompt?: string;\n}\n\n// YAML model definition\nexport interface YAMLModelDefinition {\n modelId?: string;\n baseUrl?: string;\n apiKey?: string;\n maxTokens?: number;\n temperature?: number;\n timeout?: number;\n}\n\n// YAML workflow definition\nexport interface YAMLWorkflowDefinition {\n name: string;\n description?: string;\n model?: YAMLModelDefinition;\n tools?: Record<string, YAMLToolDefinition>;\n agents?: Record<string, YAMLAgentDefinition>;\n entrypoint: string;\n globalMaxContextLength?: number;\n}\n\n// YAML tool definition\nexport interface YAMLToolDefinition {\n type: string;\n config?: Record<string, unknown>;\n}\n\n// Orchestrator event\nexport interface OrchestratorEvent {\n type: 'agent_start' | 'agent_step' | 'agent_tool_call' | 'agent_observation' | 'agent_end' | 'agent_error';\n agentName: string;\n depth: number;\n data: unknown;\n timestamp: number;\n}\n\n// ============================================\n// JSON Output Types (for structured CLI output)\n// ============================================\n\nexport type JSONEventType =\n | 'run_start'\n | 'workflow_loaded'\n | 'agent_start'\n | 'agent_step'\n | 'agent_thinking'\n | 'agent_tool_call'\n | 'agent_tool_result'\n | 'agent_observation'\n | 'agent_end'\n | 'run_end'\n | 'error'\n | 'log';\n\n// Base JSON event structure\nexport interface JSONEventBase {\n runId: string;\n timestamp: number;\n type: JSONEventType;\n}\n\n// Run lifecycle events\nexport interface JSONRunStartEvent extends JSONEventBase {\n type: 'run_start';\n data: {\n workflowPath: string;\n task: string;\n cwd?: string;\n };\n}\n\nexport interface JSONWorkflowLoadedEvent extends JSONEventBase {\n type: 'workflow_loaded';\n data: {\n name: string;\n description?: string;\n agents: string[];\n tools: string[];\n entrypoint: string;\n };\n}\n\nexport interface JSONRunEndEvent extends JSONEventBase {\n type: 'run_end';\n data: {\n success: boolean;\n output: unknown;\n totalDuration: number;\n totalTokens: number;\n totalSteps: number;\n };\n}\n\n// Agent lifecycle events\nexport interface JSONAgentStartEvent extends JSONEventBase {\n type: 'agent_start';\n agentName: string;\n depth: number;\n data: {\n task: string;\n agentType: 'CodeAgent' | 'ToolUseAgent';\n maxSteps: number;\n };\n}\n\nexport interface JSONAgentEndEvent extends JSONEventBase {\n type: 'agent_end';\n agentName: string;\n depth: number;\n data: {\n output: unknown;\n totalSteps: number;\n tokenUsage: TokenUsage;\n duration: number;\n success: boolean;\n };\n}\n\n// Step events\nexport interface JSONAgentStepEvent extends JSONEventBase {\n type: 'agent_step';\n agentName: string;\n depth: number;\n data: {\n stepNumber: number;\n maxSteps: number;\n phase: 'start' | 'thinking' | 'acting' | 'complete';\n };\n}\n\nexport interface JSONAgentThinkingEvent extends JSONEventBase {\n type: 'agent_thinking';\n agentName: string;\n depth: number;\n data: {\n stepNumber: number;\n content: string;\n isPartial?: boolean;\n };\n}\n\n// Tool events\nexport interface JSONAgentToolCallEvent extends JSONEventBase {\n type: 'agent_tool_call';\n agentName: string;\n depth: number;\n data: {\n stepNumber: number;\n toolCallId: string;\n toolName: string;\n arguments: Record<string, unknown>;\n };\n}\n\nexport interface JSONAgentToolResultEvent extends JSONEventBase {\n type: 'agent_tool_result';\n agentName: string;\n depth: number;\n data: {\n stepNumber: number;\n toolCallId: string;\n toolName: string;\n result: unknown;\n error?: string;\n duration: number;\n };\n}\n\n// Observation event (for CodeAgent)\nexport interface JSONAgentObservationEvent extends JSONEventBase {\n type: 'agent_observation';\n agentName: string;\n depth: number;\n data: {\n stepNumber: number;\n observation: string;\n codeAction?: string;\n logs?: string;\n };\n}\n\n// Error event\nexport interface JSONErrorEvent extends JSONEventBase {\n type: 'error';\n agentName?: string;\n depth?: number;\n data: {\n message: string;\n stack?: string;\n stepNumber?: number;\n };\n}\n\n// Log event (for non-structured output)\nexport interface JSONLogEvent extends JSONEventBase {\n type: 'log';\n data: {\n level: 'info' | 'warn' | 'error' | 'debug';\n message: string;\n };\n}\n\n// Union type of all JSON events\nexport type JSONEvent =\n | JSONRunStartEvent\n | JSONWorkflowLoadedEvent\n | JSONRunEndEvent\n | JSONAgentStartEvent\n | JSONAgentEndEvent\n | JSONAgentStepEvent\n | JSONAgentThinkingEvent\n | JSONAgentToolCallEvent\n | JSONAgentToolResultEvent\n | JSONAgentObservationEvent\n | JSONErrorEvent\n | JSONLogEvent;\n\n// Output format configuration\nexport type OutputFormat = 'text' | 'json';\n","/**\n * AgentMemory - Tracks agent execution history with context management\n */\n\nimport type {\n MemoryStep,\n SystemPromptStep,\n TaskStep,\n ActionStep,\n FinalAnswerStep,\n ChatMessage,\n TokenUsage,\n MemoryStrategy,\n Model,\n} from '../types.js';\n\nexport interface MemoryConfig {\n maxContextLength?: number;\n memoryStrategy?: MemoryStrategy;\n model?: Model;\n}\n\n// Rough token estimation: ~4 chars per token on average\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nfunction estimateMessagesTokens(messages: ChatMessage[]): number {\n let total = 0;\n for (const msg of messages) {\n total += estimateTokens(msg.content ?? '');\n if (msg.toolCalls) {\n total += estimateTokens(JSON.stringify(msg.toolCalls));\n }\n total += 4; // overhead per message (role, etc.)\n }\n return total;\n}\n\nexport class AgentMemory {\n /** System prompt step (always first) */\n systemPrompt: SystemPromptStep;\n\n /** All execution steps */\n steps: (TaskStep | ActionStep | FinalAnswerStep)[] = [];\n\n private maxContextLength: number;\n private memoryStrategy: MemoryStrategy;\n private model?: Model;\n\n constructor(systemPrompt: string, config?: MemoryConfig) {\n this.systemPrompt = {\n type: 'system',\n content: systemPrompt,\n timestamp: Date.now(),\n };\n this.maxContextLength = config?.maxContextLength ?? 100000;\n this.memoryStrategy = config?.memoryStrategy ?? 'truncate';\n this.model = config?.model;\n }\n\n /** Reset memory, keeping only the system prompt */\n reset(): void {\n this.steps = [];\n }\n\n /** Add a task step */\n addTask(task: string): TaskStep {\n const step: TaskStep = {\n type: 'task',\n task,\n timestamp: Date.now(),\n };\n this.steps.push(step);\n return step;\n }\n\n /** Create a new action step */\n createActionStep(stepNumber: number): ActionStep {\n const step: ActionStep = {\n type: 'action',\n stepNumber,\n timing: { startTime: Date.now() },\n modelInputMessages: [],\n timestamp: Date.now(),\n };\n this.steps.push(step);\n return step;\n }\n\n /** Add a final answer step */\n addFinalAnswer(answer: unknown): FinalAnswerStep {\n const step: FinalAnswerStep = {\n type: 'final',\n answer,\n timestamp: Date.now(),\n };\n this.steps.push(step);\n return step;\n }\n\n /** Get the last step */\n getLastStep(): MemoryStep | undefined {\n return this.steps[this.steps.length - 1];\n }\n\n /** Get all action steps */\n getActionSteps(): ActionStep[] {\n return this.steps.filter((s): s is ActionStep => s.type === 'action');\n }\n\n /**\n * Convert memory to messages for LLM context.\n * Handles both CodeAgent (observation-based) and ToolUseAgent (tool_call-based) patterns.\n */\n toMessages(): ChatMessage[] {\n const messages: ChatMessage[] = [];\n\n // System prompt\n messages.push({\n role: 'system',\n content: this.systemPrompt.content,\n });\n\n for (const step of this.steps) {\n switch (step.type) {\n case 'task':\n messages.push({\n role: 'user',\n content: `Task: ${step.task}`,\n });\n break;\n\n case 'action':\n // Assistant response with tool calls (ToolUseAgent)\n if (step.toolCalls && step.toolCalls.length > 0) {\n messages.push({\n role: 'assistant',\n content: step.modelOutputMessage?.content ?? null,\n toolCalls: step.toolCalls,\n });\n\n // Add tool results\n if (step.toolResults) {\n for (const result of step.toolResults) {\n messages.push({\n role: 'tool',\n content: result.error\n ? `Error: ${result.error}`\n : typeof result.result === 'string'\n ? result.result\n : JSON.stringify(result.result, null, 2),\n toolCallId: result.toolCallId,\n });\n }\n }\n } else {\n // CodeAgent pattern: assistant message + observation\n if (step.modelOutputMessage) {\n messages.push({\n role: 'assistant',\n content: step.modelOutputMessage.content,\n });\n }\n\n if (step.observation) {\n messages.push({\n role: 'user',\n content: step.observation,\n });\n }\n\n if (step.error && !step.observation) {\n messages.push({\n role: 'user',\n content: `Error: ${step.error.message}`,\n });\n }\n }\n break;\n\n case 'final':\n break;\n }\n }\n\n return messages;\n }\n\n /**\n * Manage context length - truncate or compact if exceeded.\n */\n async manageContext(): Promise<void> {\n const messages = this.toMessages();\n const tokenCount = estimateMessagesTokens(messages);\n\n if (tokenCount <= this.maxContextLength) {\n return;\n }\n\n if (this.memoryStrategy === 'truncate') {\n this.truncateOlderMessages();\n } else if (this.memoryStrategy === 'compact') {\n await this.compactMessages();\n }\n }\n\n /**\n * Truncate older action steps to fit within context.\n */\n private truncateOlderMessages(): void {\n // Keep system prompt, task, and recent steps\n const actionSteps = this.getActionSteps();\n if (actionSteps.length <= 2) return;\n\n // Remove oldest action steps until we fit\n const targetTokens = this.maxContextLength * 0.75;\n let currentTokens = estimateMessagesTokens(this.toMessages());\n\n while (currentTokens > targetTokens && this.steps.length > 2) {\n // Find first action step and remove it\n const idx = this.steps.findIndex(s => s.type === 'action');\n if (idx === -1) break;\n this.steps.splice(idx, 1);\n currentTokens = estimateMessagesTokens(this.toMessages());\n }\n }\n\n /**\n * Compact older messages into a summary.\n */\n private async compactMessages(): Promise<void> {\n if (!this.model) {\n // Fall back to truncation if no model available\n this.truncateOlderMessages();\n return;\n }\n\n const actionSteps = this.getActionSteps();\n if (actionSteps.length <= 2) return;\n\n // Summarize older steps\n const stepsToSummarize = actionSteps.slice(0, -2);\n const summaryContent = stepsToSummarize.map(step => {\n const parts: string[] = [];\n if (step.modelOutputMessage?.content) {\n parts.push(`Action: ${step.modelOutputMessage.content.slice(0, 200)}`);\n }\n if (step.observation) {\n parts.push(`Observation: ${step.observation.slice(0, 200)}`);\n }\n if (step.toolResults) {\n for (const r of step.toolResults) {\n const resultStr = typeof r.result === 'string' ? r.result : JSON.stringify(r.result);\n parts.push(`Tool ${r.toolName}: ${resultStr.slice(0, 200)}`);\n }\n }\n return parts.join('\\n');\n }).join('\\n---\\n');\n\n try {\n const summaryResponse = await this.model.generate([\n {\n role: 'system',\n content: 'Summarize the following agent execution history concisely, preserving key findings and results. Be brief but complete.',\n },\n {\n role: 'user',\n content: summaryContent,\n },\n ]);\n\n // Remove the summarized steps and replace with a summary task step\n const recentSteps = this.steps.filter(s =>\n s.type === 'task' || s.type === 'final' ||\n (s.type === 'action' && actionSteps.indexOf(s) >= actionSteps.length - 2)\n );\n\n this.steps = [\n {\n type: 'task' as const,\n task: `[Context Summary from previous steps]\\n${summaryResponse.content}`,\n timestamp: Date.now(),\n },\n ...recentSteps,\n ];\n } catch {\n // Fall back to truncation\n this.truncateOlderMessages();\n }\n }\n\n /** Get total token usage across all steps */\n getTotalTokenUsage(): TokenUsage {\n let inputTokens = 0;\n let outputTokens = 0;\n\n for (const step of this.steps) {\n if (step.type === 'action' && step.tokenUsage) {\n inputTokens += step.tokenUsage.inputTokens;\n outputTokens += step.tokenUsage.outputTokens;\n }\n }\n\n return {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n };\n }\n\n /** Get current estimated token count */\n getEstimatedTokenCount(): number {\n return estimateMessagesTokens(this.toMessages());\n }\n\n /** Get a summary of the memory for logging */\n getSummary(): string {\n const actionSteps = this.getActionSteps();\n const lines = [\n `System Prompt: ${this.systemPrompt.content.slice(0, 100)}...`,\n `Total Steps: ${this.steps.length}`,\n `Action Steps: ${actionSteps.length}`,\n ];\n\n const tokenUsage = this.getTotalTokenUsage();\n if (tokenUsage.totalTokens > 0) {\n lines.push(`Total Tokens: ${tokenUsage.totalTokens}`);\n }\n\n return lines.join('\\n');\n }\n\n /** Serialize memory to JSON */\n toJSON(): Record<string, unknown> {\n return {\n systemPrompt: this.systemPrompt,\n steps: this.steps,\n };\n }\n}\n","/**\n * AgentLogger - Color-coded console logging for agent execution\n *\n * Provides formatted output with different colors for:\n * - Headers (cyan)\n * - Reasoning/Thoughts (yellow)\n * - Code blocks (green)\n * - Output/Results (blue)\n * - Errors (red)\n */\n\nimport chalk from 'chalk';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { LogLevel } from '../types.js';\n\n// Log file directory\nconst LOG_DIR = path.join(os.homedir(), '.smol-js/logs');\n\nexport class AgentLogger {\n private level: LogLevel;\n private logFile?: fs.WriteStream;\n private sessionId: string;\n\n constructor(level: LogLevel = LogLevel.INFO) {\n this.level = level;\n this.sessionId = this.generateSessionId();\n\n // Initialize log file if logging is enabled\n if (level > LogLevel.OFF) {\n this.initLogFile();\n }\n }\n\n /**\n * Generate a unique session ID.\n */\n private generateSessionId(): string {\n const now = new Date();\n const timestamp = now.toISOString().replace(/[:.]/g, '-');\n return `session-${timestamp}`;\n }\n\n /**\n * Initialize the log file.\n */\n private initLogFile(): void {\n try {\n // Create log directory if it doesn't exist\n if (!fs.existsSync(LOG_DIR)) {\n fs.mkdirSync(LOG_DIR, { recursive: true });\n }\n\n const logPath = path.join(LOG_DIR, `${this.sessionId}.log`);\n this.logFile = fs.createWriteStream(logPath, { flags: 'a' });\n\n this.writeToFile(`=== Session Started: ${new Date().toISOString()} ===\\n\\n`);\n } catch (error) {\n console.warn('Could not create log file:', (error as Error).message);\n }\n }\n\n /**\n * Write to the log file.\n */\n private writeToFile(content: string): void {\n if (this.logFile) {\n // Strip ANSI codes for file output\n // eslint-disable-next-line no-control-regex\n const cleanContent = content.replace(/\\x1b\\[[0-9;]*m/g, '');\n this.logFile.write(cleanContent);\n }\n }\n\n /**\n * Set the log level.\n */\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n\n /**\n * Log a header (task start, step start, etc.)\n */\n header(message: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const line = '═'.repeat(60);\n const output = `\\n${chalk.cyan(line)}\\n${chalk.cyan.bold(message)}\\n${chalk.cyan(line)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n${'═'.repeat(60)}\\n${message}\\n${'═'.repeat(60)}\\n`);\n }\n\n /**\n * Log a subheader.\n */\n subheader(message: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `\\n${chalk.cyan('─'.repeat(40))}\\n${chalk.cyan(message)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n${'─'.repeat(40)}\\n${message}\\n`);\n }\n\n /**\n * Log reasoning/thought from the agent.\n */\n reasoning(content: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.yellow.bold('💭 Reasoning:')}\\n${chalk.yellow(content)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n💭 Reasoning:\\n${content}\\n`);\n }\n\n /**\n * Log code block.\n */\n code(content: string, language: string = 'javascript', level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.green.bold('📝 Code:')}\\n${chalk.green('```' + language)}\\n${chalk.green(content)}\\n${chalk.green('```')}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n📝 Code:\\n\\`\\`\\`${language}\\n${content}\\n\\`\\`\\`\\n`);\n }\n\n /**\n * Log execution output.\n */\n output(content: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.blue.bold('📤 Output:')}\\n${chalk.blue(content)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n📤 Output:\\n${content}\\n`);\n }\n\n /**\n * Log execution logs (print statements).\n */\n logs(content: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level || !content.trim()) return;\n\n const output = `${chalk.gray.bold('📋 Logs:')}\\n${chalk.gray(content)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n📋 Logs:\\n${content}\\n`);\n }\n\n /**\n * Log an error.\n */\n error(message: string, error?: Error, level: LogLevel = LogLevel.ERROR): void {\n if (this.level < level) return;\n\n const errorMessage = error ? `${message}: ${error.message}` : message;\n const output = `${chalk.red.bold('❌ Error:')}\\n${chalk.red(errorMessage)}\\n`;\n\n console.error(output);\n this.writeToFile(`\\n❌ Error:\\n${errorMessage}\\n`);\n\n if (error?.stack && this.level >= LogLevel.DEBUG) {\n console.error(chalk.red.dim(error.stack));\n this.writeToFile(`Stack: ${error.stack}\\n`);\n }\n }\n\n /**\n * Log a warning.\n */\n warn(message: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.yellow.bold('⚠️ Warning:')} ${chalk.yellow(message)}\\n`;\n\n console.warn(output);\n this.writeToFile(`\\n⚠️ Warning: ${message}\\n`);\n }\n\n /**\n * Log general info.\n */\n info(message: string, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.white(message)}`;\n\n console.log(output);\n this.writeToFile(`${message}\\n`);\n }\n\n /**\n * Log debug info.\n */\n debug(message: string): void {\n if (this.level < LogLevel.DEBUG) return;\n\n const output = `${chalk.dim('[DEBUG]')} ${chalk.dim(message)}`;\n\n console.log(output);\n this.writeToFile(`[DEBUG] ${message}\\n`);\n }\n\n /**\n * Log final answer.\n */\n finalAnswer(answer: unknown, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const line = '═'.repeat(60);\n const answerStr = typeof answer === 'string' ? answer : JSON.stringify(answer, null, 2);\n const output = `\\n${chalk.magenta(line)}\\n${chalk.magenta.bold('✅ Final Answer:')}\\n${chalk.magenta(answerStr)}\\n${chalk.magenta(line)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n${'═'.repeat(60)}\\n✅ Final Answer:\\n${answerStr}\\n${'═'.repeat(60)}\\n`);\n }\n\n /**\n * Log step progress.\n */\n stepProgress(current: number, max: number, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.cyan.bold(`\\n🔄 Step ${current}/${max}`)}\\n`;\n\n console.log(output);\n this.writeToFile(`\\n🔄 Step ${current}/${max}\\n`);\n }\n\n /**\n * Log waiting message for code execution delay.\n */\n waiting(seconds: number, level: LogLevel = LogLevel.INFO): void {\n if (this.level < level) return;\n\n const output = `${chalk.yellow(`⏳ Waiting ${seconds}s before code execution (Ctrl+C to abort)...`)}`;\n\n console.log(output);\n this.writeToFile(`⏳ Waiting ${seconds}s before code execution...\\n`);\n }\n\n /**\n * Stream content character by character.\n */\n streamChar(char: string): void {\n if (this.level < LogLevel.INFO) return;\n process.stdout.write(chalk.yellow(char));\n }\n\n /**\n * End streaming (add newline).\n */\n streamEnd(): void {\n if (this.level < LogLevel.INFO) return;\n console.log();\n }\n\n /**\n * Close the log file.\n */\n close(): void {\n if (this.logFile) {\n this.writeToFile(`\\n=== Session Ended: ${new Date().toISOString()} ===\\n`);\n this.logFile.end();\n }\n }\n\n /**\n * Get the log file path.\n */\n getLogPath(): string | undefined {\n return this.logFile ? path.join(LOG_DIR, `${this.sessionId}.log`) : undefined;\n }\n}\n","/**\n * Agent - Abstract base class for all agents\n *\n * Provides the foundation for multi-step agents that follow the ReAct framework.\n * Extend this class to create specific agent implementations.\n */\n\nimport type {\n ActionStep,\n RunResult,\n LogLevel,\n ActionOutput,\n MemoryStrategy,\n} from '../types.js';\nimport { Tool } from '../tools/Tool.js';\nimport { Model } from '../models/Model.js';\nimport { AgentMemory } from '../memory/AgentMemory.js';\nimport { AgentLogger } from '../logging/AgentLogger.js';\nimport { LogLevel as LogLevelEnum } from '../types.js';\n\n// Default global max context length (in tokens, estimated)\nconst DEFAULT_MAX_CONTEXT_LENGTH = 100000;\n\nexport interface AgentConfig {\n /** The LLM model to use for generation */\n model: Model;\n\n /** Tools available to the agent */\n tools?: Tool[];\n\n /** Maximum number of steps before stopping (default: 20) */\n maxSteps?: number;\n\n /** Delay in ms before executing code (default: 5000) */\n codeExecutionDelay?: number;\n\n /** Custom instructions appended to system prompt */\n customInstructions?: string;\n\n /** Log level for output (default: INFO) */\n verboseLevel?: LogLevel;\n\n /** Whether to stream model outputs (default: true) */\n streamOutputs?: boolean;\n\n /** Whether the agent retains memory between run() calls (default: false) */\n persistent?: boolean;\n\n /** Max context length in tokens (default: 100000) */\n maxContextLength?: number;\n\n /** Memory management strategy when context is exceeded (default: 'truncate') */\n memoryStrategy?: MemoryStrategy;\n\n /** Max tokens for generation (passed to model if set) */\n maxTokens?: number;\n\n /** Temperature for generation (passed to model if set) */\n temperature?: number;\n\n /** Agent name for logging */\n name?: string;\n\n /** Callback for orchestration events */\n onEvent?: (event: { type: string; data: unknown }) => void;\n}\n\nexport abstract class Agent {\n /** The LLM model for generation */\n protected model: Model;\n\n /** Available tools mapped by name */\n protected tools: Map<string, Tool> = new Map();\n\n /** Agent memory tracking all steps */\n protected memory!: AgentMemory;\n\n /** Logger for formatted output */\n protected logger: AgentLogger;\n\n /** Configuration options */\n protected config: {\n maxSteps: number;\n codeExecutionDelay: number;\n customInstructions: string;\n verboseLevel: LogLevel;\n streamOutputs: boolean;\n persistent: boolean;\n maxContextLength: number;\n memoryStrategy: MemoryStrategy;\n maxTokens?: number;\n temperature?: number;\n name: string;\n onEvent?: (event: { type: string; data: unknown }) => void;\n };\n\n /** Current step number */\n protected currentStep: number = 0;\n\n /** Whether the agent is currently running */\n protected isRunning: boolean = false;\n\n /** Whether the agent has been initialized at least once */\n private initialized: boolean = false;\n\n constructor(config: AgentConfig) {\n this.model = config.model;\n this.logger = new AgentLogger(config.verboseLevel ?? LogLevelEnum.INFO);\n\n this.config = {\n maxSteps: config.maxSteps ?? 20,\n codeExecutionDelay: config.codeExecutionDelay ?? 5000,\n customInstructions: config.customInstructions ?? '',\n verboseLevel: config.verboseLevel ?? LogLevelEnum.INFO,\n streamOutputs: config.streamOutputs ?? true,\n persistent: config.persistent ?? false,\n maxContextLength: config.maxContextLength ?? DEFAULT_MAX_CONTEXT_LENGTH,\n memoryStrategy: config.memoryStrategy ?? 'truncate',\n maxTokens: config.maxTokens,\n temperature: config.temperature,\n name: config.name ?? 'Agent',\n onEvent: config.onEvent,\n };\n\n // Register tools\n if (config.tools) {\n for (const tool of config.tools) {\n this.tools.set(tool.name, tool);\n }\n }\n }\n\n /**\n * Initialize the system prompt for the agent.\n * Must be implemented by subclasses.\n */\n protected abstract initializeSystemPrompt(): string;\n\n /**\n * Execute a single step in the agent loop.\n * Must be implemented by subclasses.\n */\n protected abstract executeStep(memoryStep: ActionStep): Promise<ActionOutput>;\n\n /**\n * Run the agent on a task.\n */\n async run(task: string, reset: boolean = true): Promise<RunResult> {\n const startTime = Date.now();\n\n // For persistent agents, only reset if explicitly requested or first run\n const shouldReset = !this.config.persistent ? (reset || !this.memory) : (!this.initialized);\n\n if (shouldReset) {\n const systemPrompt = this.initializeSystemPrompt();\n this.memory = new AgentMemory(systemPrompt, {\n maxContextLength: this.config.maxContextLength,\n memoryStrategy: this.config.memoryStrategy,\n model: this.model,\n });\n this.currentStep = 0;\n this.initialized = true;\n }\n\n // Add task to memory\n this.memory.addTask(task);\n\n this.isRunning = true;\n this.emitEvent('agent_start', { task, name: this.config.name });\n this.logger.header(`Starting ${this.config.name}: ${task.slice(0, 80)}${task.length > 80 ? '...' : ''}`);\n\n let finalOutput: unknown = null;\n let isFinalAnswer = false;\n\n try {\n while (this.currentStep < this.config.maxSteps && this.isRunning) {\n this.currentStep++;\n this.logger.stepProgress(this.currentStep, this.config.maxSteps);\n this.emitEvent('agent_step', { step: this.currentStep, maxSteps: this.config.maxSteps });\n\n const memoryStep = this.memory.createActionStep(this.currentStep);\n\n try {\n const actionOutput = await this.executeStep(memoryStep);\n\n memoryStep.timing.endTime = Date.now();\n memoryStep.timing.duration = memoryStep.timing.endTime - memoryStep.timing.startTime;\n memoryStep.actionOutput = actionOutput;\n memoryStep.isFinalAnswer = actionOutput.isFinalAnswer;\n\n if (actionOutput.isFinalAnswer) {\n finalOutput = actionOutput.output;\n isFinalAnswer = true;\n this.logger.finalAnswer(finalOutput);\n break;\n }\n } catch (error) {\n memoryStep.error = error as Error;\n memoryStep.timing.endTime = Date.now();\n memoryStep.timing.duration = memoryStep.timing.endTime - memoryStep.timing.startTime;\n this.logger.error('Step execution failed', error as Error);\n this.emitEvent('agent_error', { error: (error as Error).message, step: this.currentStep });\n }\n\n // Check and manage context length after each step\n await this.memory.manageContext();\n }\n\n if (!isFinalAnswer && this.currentStep >= this.config.maxSteps) {\n this.logger.warn(`Max steps (${this.config.maxSteps}) reached without final answer`);\n finalOutput = await this.provideFinalAnswer(task);\n }\n } finally {\n this.isRunning = false;\n }\n\n const duration = Date.now() - startTime;\n const tokenUsage = this.memory.getTotalTokenUsage();\n\n this.memory.addFinalAnswer(finalOutput);\n this.emitEvent('agent_end', { output: finalOutput, duration, tokenUsage });\n\n this.logger.info(`\\nTotal time: ${(duration / 1000).toFixed(2)}s`);\n this.logger.info(`Total tokens: ${tokenUsage.totalTokens}`);\n\n return {\n output: finalOutput,\n steps: this.memory.steps,\n tokenUsage,\n duration,\n };\n }\n\n /**\n * Generate a final answer when max steps is reached.\n */\n protected async provideFinalAnswer(task: string): Promise<unknown> {\n this.logger.subheader('Generating final answer from accumulated context');\n\n const messages = this.memory.toMessages();\n messages.push({\n role: 'user',\n content: `You have reached the maximum number of steps. Based on your work so far, provide the best answer you can for the original task: \"${task}\". Summarize what you accomplished and provide a final answer.`,\n });\n\n const response = await this.model.generate(messages, {\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n });\n\n return response.content;\n }\n\n /** Emit an orchestration event */\n protected emitEvent(type: string, data: unknown): void {\n if (this.config.onEvent) {\n this.config.onEvent({ type, data });\n }\n }\n\n /** Stop the agent */\n stop(): void {\n this.isRunning = false;\n this.logger.info('Agent stopped by user');\n }\n\n /** Get the current memory */\n getMemory(): AgentMemory {\n return this.memory;\n }\n\n /** Get registered tools */\n getTools(): Map<string, Tool> {\n return this.tools;\n }\n\n /** Add a tool to the agent */\n addTool(tool: Tool): void {\n this.tools.set(tool.name, tool);\n }\n\n /** Remove a tool from the agent */\n removeTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /** Get agent name */\n getName(): string {\n return this.config.name;\n }\n\n /** Get agent type identifier */\n getType(): string {\n return this.constructor.name;\n }\n\n /** Get max steps configuration */\n getMaxSteps(): number {\n return this.config.maxSteps;\n }\n\n /** Set the event callback (useful for orchestration) */\n setOnEvent(callback: (event: { type: string; data: unknown }) => void): void {\n this.config.onEvent = callback;\n }\n\n /** Sleep for a specified duration */\n protected sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * LocalExecutor - JavaScript code execution engine using Node's vm module\n *\n * Executes JavaScript code chunks in an isolated context with:\n * - State persistence between steps (variables carry forward)\n * - Tool injection (tools available as async functions)\n * - Dynamic imports via CDN (esm.sh)\n * - Print capture and logging\n * - Safety timeouts\n */\n\nimport * as vm from 'vm';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport type { CodeExecutionOutput } from '../types.js';\nimport { Tool as ToolClass } from '../tools/Tool.js';\n\n// Default timeout for code execution (30 seconds)\nconst DEFAULT_TIMEOUT_MS = 30000;\n\n// Maximum length of captured output\nconst MAX_OUTPUT_LENGTH = 50000;\n\n// Package cache directory\nconst PACKAGE_CACHE_DIR = path.join(os.homedir(), '.smol-js', 'packages');\n\nexport interface ExecutorConfig {\n /**\n * Maximum execution time in milliseconds\n * @default 30000\n */\n timeout?: number;\n\n /**\n * Additional authorized imports (npm packages to allow)\n */\n authorizedImports?: string[];\n\n /**\n * Whether to allow fs module access\n * @default true\n */\n allowFs?: boolean;\n\n /**\n * Working directory for fs operations\n */\n workingDirectory?: string;\n}\n\nexport class LocalExecutor {\n private context: vm.Context;\n private state: Record<string, unknown> = {};\n private tools: Map<string, ToolClass> = new Map();\n private config: ExecutorConfig;\n private capturedLogs: string[] = [];\n\n constructor(config: ExecutorConfig = {}) {\n this.config = {\n timeout: DEFAULT_TIMEOUT_MS,\n allowFs: true,\n workingDirectory: process.cwd(),\n ...config,\n };\n\n this.context = this.createContext();\n }\n\n /**\n * Create the VM context with available globals.\n */\n private createContext(): vm.Context {\n // Create a proxy for console to capture logs\n const consoleProxy = {\n log: (...args: unknown[]) => {\n const output = args.map((arg) => this.stringify(arg)).join(' ');\n this.capturedLogs.push(output);\n },\n error: (...args: unknown[]) => {\n const output = args.map((arg) => this.stringify(arg)).join(' ');\n this.capturedLogs.push(`[ERROR] ${output}`);\n },\n warn: (...args: unknown[]) => {\n const output = args.map((arg) => this.stringify(arg)).join(' ');\n this.capturedLogs.push(`[WARN] ${output}`);\n },\n info: (...args: unknown[]) => {\n const output = args.map((arg) => this.stringify(arg)).join(' ');\n this.capturedLogs.push(output);\n },\n debug: (...args: unknown[]) => {\n const output = args.map((arg) => this.stringify(arg)).join(' ');\n this.capturedLogs.push(`[DEBUG] ${output}`);\n },\n };\n\n // Create print function (alias for console.log)\n const print = (...args: unknown[]) => consoleProxy.log(...args);\n\n // Create dynamic import function for npm packages\n const dynamicImport = async (packageName: string): Promise<unknown> => {\n // Check if it's an authorized import\n const authorized = this.config.authorizedImports ?? [];\n const basePackage = packageName.split('/')[0];\n\n if (!authorized.includes(basePackage) && !authorized.includes(packageName)) {\n throw new Error(\n `Import not authorized: ${packageName}. Add it to authorizedImports to allow.`\n );\n }\n\n try {\n // Ensure cache directory exists\n if (!fs.existsSync(PACKAGE_CACHE_DIR)) {\n fs.mkdirSync(PACKAGE_CACHE_DIR, { recursive: true });\n }\n\n // Create a safe filename from package name\n const safeFileName = packageName.replace(/[/@]/g, '_') + '.mjs';\n const cachedPath = path.join(PACKAGE_CACHE_DIR, safeFileName);\n\n // Check if already cached and valid (not a redirect stub)\n let needsFetch = !fs.existsSync(cachedPath);\n if (!needsFetch) {\n const content = fs.readFileSync(cachedPath, 'utf-8');\n // Check if it's a redirect stub that needs resolution\n if (content.includes('export * from \"/') || content.includes(\"export * from '/\")) {\n needsFetch = true;\n fs.unlinkSync(cachedPath); // Remove invalid cache\n }\n }\n\n if (needsFetch) {\n this.capturedLogs.push(`[import] Fetching ${packageName}...`);\n\n // First, get the package info to find the actual bundle URL\n // Use jsdelivr which provides proper ESM bundles\n const jsdelivrUrl = `https://cdn.jsdelivr.net/npm/${packageName}/+esm`;\n\n const response = await fetch(jsdelivrUrl);\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n let code = await response.text();\n\n // jsdelivr ESM bundles may have imports from jsdelivr - rewrite them to be fetched too\n // For now, we'll inline simple packages. Complex packages with many deps may need more work.\n\n // Check if there are external imports we need to resolve\n const importMatches = code.matchAll(/from\\s+[\"'](https:\\/\\/cdn\\.jsdelivr\\.net\\/[^\"']+)[\"']/g);\n for (const match of importMatches) {\n const depUrl = match[1];\n const depName = depUrl.split('/npm/')[1]?.split('/')[0] || 'dep';\n const depFileName = depName.replace(/[/@]/g, '_') + '_dep.mjs';\n const depCachedPath = path.join(PACKAGE_CACHE_DIR, depFileName);\n\n if (!fs.existsSync(depCachedPath)) {\n this.capturedLogs.push(`[import] Fetching dependency from ${depUrl}...`);\n const depResponse = await fetch(depUrl);\n if (depResponse.ok) {\n const depCode = await depResponse.text();\n fs.writeFileSync(depCachedPath, depCode, 'utf-8');\n }\n }\n\n // Rewrite import to use local file\n code = code.replace(depUrl, `file://${depCachedPath}`);\n }\n\n // Write to cache\n fs.writeFileSync(cachedPath, code, 'utf-8');\n this.capturedLogs.push(`[import] Cached ${packageName} to ${cachedPath}`);\n } else {\n this.capturedLogs.push(`[import] Using cached ${packageName}`);\n }\n\n // Import from local cache using file:// URL\n const fileUrl = `file://${cachedPath}`;\n const module = await import(fileUrl);\n return module.default ?? module;\n } catch (error) {\n throw new Error(`Failed to import ${packageName}: ${(error as Error).message}`);\n }\n };\n\n // Build context object\n const contextObj: Record<string, unknown> = {\n // Console and print\n console: consoleProxy,\n print,\n\n // Built-in objects\n Object,\n Array,\n String,\n Number,\n Boolean,\n Date,\n Math,\n JSON,\n RegExp,\n Error,\n Map,\n Set,\n WeakMap,\n WeakSet,\n Promise,\n Symbol,\n Proxy,\n Reflect,\n\n // Type checking\n parseInt,\n parseFloat,\n isNaN,\n isFinite,\n typeof: (v: unknown) => typeof v,\n\n // Timers (promisified for async support)\n setTimeout: global.setTimeout,\n clearTimeout: global.clearTimeout,\n setInterval: global.setInterval,\n clearInterval: global.clearInterval,\n\n // Async utilities\n fetch: global.fetch,\n\n // Dynamic import for npm packages\n importPackage: dynamicImport,\n\n // URL handling\n URL,\n URLSearchParams,\n\n // Text encoding\n TextEncoder,\n TextDecoder,\n\n // Buffer (useful for many operations)\n Buffer,\n\n // State reference (variables persist here)\n __state__: this.state,\n\n // Final answer marker\n __final_answer__: null as unknown,\n __is_final_answer__: false,\n };\n\n // Add fs module if allowed\n if (this.config.allowFs) {\n contextObj.fs = {\n readFileSync: (filePath: string, encoding?: BufferEncoding) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), filePath);\n return fs.readFileSync(resolvedPath, encoding ?? 'utf-8');\n },\n writeFileSync: (filePath: string, data: string | Buffer) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), filePath);\n return fs.writeFileSync(resolvedPath, data);\n },\n existsSync: (filePath: string) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), filePath);\n return fs.existsSync(resolvedPath);\n },\n readdirSync: (dirPath: string) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), dirPath);\n return fs.readdirSync(resolvedPath);\n },\n mkdirSync: (dirPath: string, options?: fs.MakeDirectoryOptions) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), dirPath);\n return fs.mkdirSync(resolvedPath, options);\n },\n unlinkSync: (filePath: string) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), filePath);\n return fs.unlinkSync(resolvedPath);\n },\n statSync: (filePath: string) => {\n const resolvedPath = path.resolve(this.config.workingDirectory ?? process.cwd(), filePath);\n return fs.statSync(resolvedPath);\n },\n };\n\n contextObj.path = {\n join: path.join,\n resolve: (...paths: string[]) =>\n path.resolve(this.config.workingDirectory ?? process.cwd(), ...paths),\n dirname: path.dirname,\n basename: path.basename,\n extname: path.extname,\n };\n }\n\n return vm.createContext(contextObj);\n }\n\n /**\n * Add tools to the executor context.\n */\n sendTools(tools: Record<string, ToolClass>): void {\n for (const [name, tool] of Object.entries(tools)) {\n this.tools.set(name, tool);\n\n // Add tool as async function in context\n this.context[name] = async (...args: unknown[]) => {\n // Handle both positional and named arguments\n let callArgs: Record<string, unknown>;\n\n if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null) {\n // Called with named arguments object\n callArgs = args[0] as Record<string, unknown>;\n } else {\n // Called with positional arguments - map to input names\n const inputNames = Object.keys(tool.inputs);\n callArgs = {};\n args.forEach((arg, i) => {\n if (i < inputNames.length) {\n callArgs[inputNames[i]] = arg;\n }\n });\n }\n\n return tool.call(callArgs);\n };\n }\n }\n\n /**\n * Send variables to the executor state.\n */\n sendVariables(variables: Record<string, unknown>): void {\n Object.assign(this.state, variables);\n Object.assign(this.context, variables);\n }\n\n /**\n * Execute JavaScript code and return the result.\n */\n async execute(code: string): Promise<CodeExecutionOutput> {\n // Reset captured logs\n this.capturedLogs = [];\n\n // Reset final answer flag\n this.context.__is_final_answer__ = false;\n this.context.__final_answer__ = null;\n\n // Sync state to context\n Object.assign(this.context, this.state);\n\n // Wrap code to handle async and capture the last expression\n const wrappedCode = this.wrapCode(code);\n\n try {\n // Create and run the script\n const script = new vm.Script(wrappedCode, {\n filename: 'agent-code.js',\n });\n\n // Run with timeout\n const result = await script.runInContext(this.context, {\n timeout: this.config.timeout,\n displayErrors: true,\n });\n\n // Wait for the result if it's a promise\n const output = result instanceof Promise ? await result : result;\n\n // Update state with any new variables from context\n this.updateStateFromContext();\n\n // Check if final_answer was called\n const isFinalAnswer = this.context.__is_final_answer__ as boolean;\n const finalOutput = isFinalAnswer ? this.context.__final_answer__ : output;\n\n // Truncate logs if too long\n const logs = this.capturedLogs.join('\\n').slice(0, MAX_OUTPUT_LENGTH);\n\n return {\n output: finalOutput,\n logs,\n isFinalAnswer,\n };\n } catch (error) {\n // Truncate logs if too long\n const logs = this.capturedLogs.join('\\n').slice(0, MAX_OUTPUT_LENGTH);\n\n return {\n output: null,\n logs,\n isFinalAnswer: false,\n error: error as Error,\n };\n }\n }\n\n /**\n * Wrap code to handle async execution and final_answer calls.\n */\n private wrapCode(code: string): string {\n // Add final_answer function that sets the flag\n const finalAnswerFunc = `\n function final_answer(answer) {\n __is_final_answer__ = true;\n __final_answer__ = answer;\n return answer;\n }\n `;\n\n // Wrap in async IIFE to support await\n // Store result of last expression in __last_result__\n // We use a Function constructor approach to capture the last expression value\n return `\n ${finalAnswerFunc}\n (async () => {\n let __last_result__;\n ${this.instrumentCode(code)}\n return __last_result__;\n })()\n `;\n }\n\n /**\n * Instrument code to capture the last expression value and convert\n * let/const/var declarations to global assignments for state persistence.\n */\n private instrumentCode(code: string): string {\n // Split code into lines and find statements\n const lines = code.trim().split('\\n');\n\n if (lines.length === 0) {\n return code;\n }\n\n // Process the code to capture expression results\n const processedLines = lines.map((line, index) => {\n const trimmed = line.trim();\n\n // Skip empty lines and comments\n if (!trimmed ||\n trimmed.startsWith('//') ||\n trimmed.startsWith('/*') ||\n trimmed.startsWith('*') ||\n trimmed.endsWith('*/')) {\n return line;\n }\n\n // Transform variable declarations to global assignments for persistence\n // This allows variables to persist across script executions\n // Handle multiple declarations on the same line using global replacement\n let transformed = line;\n let hasDeclaration = false;\n\n // Replace all let/const/var declarations with global assignments\n transformed = transformed.replace(\n /\\b(let|const|var)\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=/g,\n (_match, _keyword, varName) => {\n hasDeclaration = true;\n return `${varName} =`;\n }\n );\n\n // Handle declarations without initialization\n transformed = transformed.replace(\n /\\b(let|const|var)\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*(?=[;,]|$)/g,\n (_match, _keyword, varName) => {\n hasDeclaration = true;\n return `${varName} = undefined`;\n }\n );\n\n if (hasDeclaration) {\n return transformed;\n }\n\n // Skip control flow statements for last-result capture\n if (trimmed.startsWith('if') ||\n trimmed.startsWith('else') ||\n trimmed.startsWith('for') ||\n trimmed.startsWith('while') ||\n trimmed.startsWith('do') ||\n trimmed.startsWith('switch') ||\n trimmed.startsWith('case') ||\n trimmed.startsWith('default') ||\n trimmed.startsWith('try') ||\n trimmed.startsWith('catch') ||\n trimmed.startsWith('finally') ||\n trimmed.startsWith('return') ||\n trimmed.startsWith('throw') ||\n trimmed.startsWith('break') ||\n trimmed.startsWith('continue') ||\n trimmed.startsWith('function') ||\n trimmed.startsWith('class') ||\n trimmed.startsWith('import') ||\n trimmed.startsWith('export') ||\n trimmed === '{' ||\n trimmed === '}' ||\n trimmed.endsWith('{') ||\n trimmed.endsWith('}')) {\n return line;\n }\n\n // For the last meaningful line, try to capture the expression value\n if (index === lines.length - 1 || this.isLastMeaningfulLine(lines, index)) {\n // If line doesn't end with semicolon, try to capture it\n if (!trimmed.endsWith(';')) {\n return `__last_result__ = ${line}`;\n } else {\n // Remove semicolon, capture, and add it back\n const withoutSemi = trimmed.slice(0, -1);\n // Check if it looks like an expression (not ending with closing brace)\n if (!withoutSemi.endsWith('}') && !withoutSemi.endsWith(')')) {\n return `__last_result__ = ${withoutSemi};`;\n }\n }\n }\n\n return line;\n });\n\n return processedLines.join('\\n');\n }\n\n /**\n * Check if this is the last meaningful line of code.\n */\n private isLastMeaningfulLine(lines: string[], currentIndex: number): boolean {\n for (let i = currentIndex + 1; i < lines.length; i++) {\n const trimmed = lines[i].trim();\n if (trimmed && !trimmed.startsWith('//') && !trimmed.startsWith('/*')) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Update internal state from context after execution.\n */\n private updateStateFromContext(): void {\n // List of keys to exclude from state (builtins and internals)\n const excludeKeys = new Set([\n 'console',\n 'print',\n 'Object',\n 'Array',\n 'String',\n 'Number',\n 'Boolean',\n 'Date',\n 'Math',\n 'JSON',\n 'RegExp',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'Promise',\n 'Symbol',\n 'Proxy',\n 'Reflect',\n 'parseInt',\n 'parseFloat',\n 'isNaN',\n 'isFinite',\n 'typeof',\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'fetch',\n 'importPackage',\n 'URL',\n 'URLSearchParams',\n 'TextEncoder',\n 'TextDecoder',\n 'Buffer',\n '__state__',\n '__final_answer__',\n '__is_final_answer__',\n 'fs',\n 'path',\n 'final_answer',\n // Exclude tools\n ...this.tools.keys(),\n ]);\n\n // Copy non-builtin keys to state\n for (const key of Object.keys(this.context)) {\n if (!excludeKeys.has(key)) {\n this.state[key] = this.context[key];\n }\n }\n }\n\n /**\n * Stringify a value for logging.\n */\n private stringify(value: unknown): string {\n if (value === undefined) return 'undefined';\n if (value === null) return 'null';\n if (typeof value === 'string') return value;\n if (typeof value === 'function') return `[Function: ${value.name || 'anonymous'}]`;\n\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n }\n\n /**\n * Reset the executor state.\n */\n reset(): void {\n this.state = {};\n this.capturedLogs = [];\n this.context = this.createContext();\n\n // Re-add tools\n const tools = Object.fromEntries(this.tools);\n this.sendTools(tools);\n }\n\n /**\n * Get the current state.\n */\n getState(): Record<string, unknown> {\n return { ...this.state };\n }\n}\n","/**\n * Tool base class for smol-js\n *\n * Tools are the primary way for agents to interact with the outside world.\n * Extend this class and implement the execute() method to create custom tools.\n */\n\nimport type { ToolInputs, ToolInputType, OpenAIToolDefinition } from '../types.js';\n\nexport abstract class Tool {\n /**\n * Unique identifier for the tool\n */\n abstract readonly name: string;\n\n /**\n * Human-readable description of what the tool does\n */\n abstract readonly description: string;\n\n /**\n * Input parameter schema\n */\n abstract readonly inputs: ToolInputs;\n\n /**\n * Output type description\n */\n abstract readonly outputType: string;\n\n /**\n * Whether the tool has been set up\n */\n protected isSetup: boolean = false;\n\n /**\n * Optional setup method called before first use.\n * Override this for expensive initialization (loading models, etc.)\n */\n async setup(): Promise<void> {\n this.isSetup = true;\n }\n\n /**\n * Execute the tool with the given arguments.\n * Must be implemented by subclasses.\n */\n abstract execute(args: Record<string, unknown>): Promise<unknown>;\n\n /**\n * Call the tool, ensuring setup is complete and validating arguments.\n */\n async call(args: Record<string, unknown>): Promise<unknown> {\n if (!this.isSetup) {\n await this.setup();\n }\n\n // Validate arguments\n this.validateArguments(args);\n\n // Execute and return result\n return this.execute(args);\n }\n\n /**\n * Validate that provided arguments match the input schema.\n */\n protected validateArguments(args: Record<string, unknown>): void {\n const providedKeys = new Set(Object.keys(args));\n\n for (const [key, input] of Object.entries(this.inputs)) {\n // Check required arguments\n if (input.required !== false && !providedKeys.has(key)) {\n throw new Error(`Missing required argument: ${key}`);\n }\n\n // Check type if argument is provided\n if (providedKeys.has(key) && args[key] !== undefined && args[key] !== null) {\n const value = args[key];\n if (!this.checkType(value, input.type)) {\n throw new Error(\n `Argument '${key}' has invalid type. Expected ${input.type}, got ${typeof value}`\n );\n }\n }\n\n providedKeys.delete(key);\n }\n }\n\n /**\n * Check if a value matches the expected type.\n */\n protected checkType(value: unknown, expectedType: ToolInputType): boolean {\n switch (expectedType) {\n case 'string':\n return typeof value === 'string';\n case 'number':\n return typeof value === 'number';\n case 'boolean':\n return typeof value === 'boolean';\n case 'array':\n return Array.isArray(value);\n case 'object':\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n case 'any':\n return true;\n default:\n return false;\n }\n }\n\n /**\n * Generate a code-friendly prompt representation of this tool.\n * Used in the CodeAgent system prompt.\n */\n toCodePrompt(): string {\n const argsSignature = Object.entries(this.inputs)\n .map(([name, input]) => {\n const optional = input.required === false ? '?' : '';\n return `${name}${optional}: ${this.typeToJsType(input.type)}`;\n })\n .join(', ');\n\n const argsDoc = Object.entries(this.inputs)\n .map(([name, input]) => ` * @param ${name} - ${input.description}`)\n .join('\\n');\n\n return `\n/**\n * ${this.description}\n *\n${argsDoc}\n * @returns ${this.outputType}\n */\nasync function ${this.name}(${argsSignature}): Promise<${this.typeToJsType(this.outputType as ToolInputType)}> { ... }\n`.trim();\n }\n\n /**\n * Generate an OpenAI-compatible tool definition for function calling.\n */\n toOpenAITool(): OpenAIToolDefinition {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [key, input] of Object.entries(this.inputs)) {\n const prop: Record<string, unknown> = {\n type: this.typeToJsonSchemaType(input.type),\n description: input.description,\n };\n\n if (input.enum) {\n prop.enum = input.enum;\n }\n\n if (input.default !== undefined) {\n prop.default = input.default;\n }\n\n properties[key] = prop;\n\n if (input.required !== false) {\n required.push(key);\n }\n }\n\n return {\n type: 'function',\n function: {\n name: this.name,\n description: this.description,\n parameters: {\n type: 'object',\n properties,\n ...(required.length > 0 && { required }),\n },\n },\n };\n }\n\n /**\n * Convert tool input type to JSON Schema type.\n */\n protected typeToJsonSchemaType(type: ToolInputType): string {\n switch (type) {\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'array':\n return 'array';\n case 'object':\n return 'object';\n case 'any':\n return 'string';\n default:\n return 'string';\n }\n }\n\n /**\n * Convert tool input type to JS/TS type string.\n */\n protected typeToJsType(type: ToolInputType | string): string {\n switch (type) {\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'array':\n return 'any[]';\n case 'object':\n return 'Record<string, any>';\n case 'any':\n return 'any';\n default:\n return type;\n }\n }\n\n /**\n * Serialize the tool to a JSON-compatible object.\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n description: this.description,\n inputs: this.inputs,\n outputType: this.outputType,\n };\n }\n}\n\n/**\n * Helper function to create a tool from a function.\n * This is an alternative to extending the Tool class.\n */\nexport function createTool(config: {\n name: string;\n description: string;\n inputs: ToolInputs;\n outputType: string;\n execute: (args: Record<string, unknown>) => Promise<unknown>;\n}): Tool {\n return new (class extends Tool {\n readonly name = config.name;\n readonly description = config.description;\n readonly inputs = config.inputs;\n readonly outputType = config.outputType;\n\n async execute(args: Record<string, unknown>): Promise<unknown> {\n return config.execute(args);\n }\n })();\n}\n","/**\n * Default tools provided to all agents\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\n\n/**\n * FinalAnswerTool - Used by the agent to return the final answer.\n * This is always available to CodeAgent.\n */\nexport class FinalAnswerTool extends Tool {\n readonly name = 'final_answer';\n readonly description = 'Returns the final answer to the user query. Use this when you have completed the task and have the final result.';\n readonly inputs: ToolInputs = {\n answer: {\n type: 'any',\n description: 'The final answer to return. Can be any type (string, number, object, etc.)',\n required: true,\n },\n };\n readonly outputType = 'any';\n\n async execute(args: Record<string, unknown>): Promise<unknown> {\n return args.answer;\n }\n}\n\n/**\n * UserInputTool - Allows the agent to ask the user for input.\n */\nexport class UserInputTool extends Tool {\n readonly name = 'user_input';\n readonly description = 'Asks the user for additional input or clarification.';\n readonly inputs: ToolInputs = {\n question: {\n type: 'string',\n description: 'The question to ask the user',\n required: true,\n },\n };\n readonly outputType = 'string';\n\n private inputHandler?: (question: string) => Promise<string>;\n\n constructor(inputHandler?: (question: string) => Promise<string>) {\n super();\n this.inputHandler = inputHandler;\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const question = args.question as string;\n\n if (this.inputHandler) {\n return this.inputHandler(question);\n }\n\n // Default: use readline for terminal input\n const readline = await import('readline');\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(`\\n[Agent asks]: ${question}\\nYour response: `, (answer) => {\n rl.close();\n resolve(answer);\n });\n });\n }\n}\n\n// Export singleton instances\nexport const finalAnswerTool = new FinalAnswerTool();\n","/**\n * System prompts for CodeAgent\n *\n * Adapted from smolagents Python prompts but optimized for JavaScript execution.\n */\n\nexport interface PromptVariables {\n tools: string;\n authorizedImports: string;\n customInstructions?: string;\n}\n\n/**\n * Generate the system prompt for CodeAgent.\n */\nexport function generateSystemPrompt(variables: PromptVariables): string {\n const { tools, authorizedImports, customInstructions } = variables;\n\n return `You are an expert JavaScript developer and problem-solving agent. Your role is to solve tasks by writing and executing JavaScript code step by step.\n\n## How You Work\n\nYou follow a ReAct (Reasoning + Acting) framework:\n1. **Thought**: Analyze the current situation and decide what to do next\n2. **Code**: Write JavaScript code to perform the action\n3. **Observation**: See the result of your code execution\n4. Repeat until you have the final answer\n\n## Available Tools\n\nYou have access to the following tools as async functions:\n\n${tools}\n\n## Available Imports\n\nYou can dynamically import the following npm packages using \\`await importPackage('package-name')\\`:\n${authorizedImports || '(No additional packages authorized)'}\n\n## Built-in Capabilities\n\nThe following are available in your execution environment:\n- \\`console.log()\\` / \\`print()\\` - Output text (captured in logs)\n- \\`fs\\` - File system operations (readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync)\n- \\`path\\` - Path utilities (join, resolve, dirname, basename)\n- \\`fetch()\\` - HTTP requests\n- \\`Buffer\\` - Binary data handling\n- \\`JSON\\` - JSON parsing/stringifying\n- Standard JavaScript globals (Math, Date, Array methods, etc.)\n\n## Response Format\n\nAlways respond with your thought process followed by a code block:\n\nThought: [Your reasoning about what to do]\n\n\\`\\`\\`javascript\n// Your code here\n\\`\\`\\`\n\n## Rules\n\n1. **Always use final_answer()**: When you have the complete answer, call \\`final_answer(yourResult)\\` to return it.\n\n2. **One action per step**: Execute one logical action per code block and one code block per inference step. You will be given additional steps to complete your work if it cannot be done safely in one step. Don't try to do everything at once because you need to make sure that your tools returned valid, useful data before going on to make use of that data. In particular, if you are a Manager agent who is invoking Sub-Agents as tools, do not script the entire workflow in one step, make sure that you get to review the work of your subagents at critical points before going on to the next step.\n\n3. **Handle errors gracefully**: If something fails, explain what went wrong and try a different approach.\n\n4. **Use async/await**: All tool calls and imports are async. Always use await.\n\n5. **Variables persist**: Variables you define in one step are available in the next step.\n\n6. **Be concise**: Write clean, minimal code. Don't over-engineer.\n\n7. **Print for debugging**: Use console.log() to output intermediate results you want to see.\n\n8. **No require()**: Use \\`await importPackage('name')\\` for npm packages instead of require().\n\n9. **Internet Access**: You can use fetch() to get data from the web as needed. However, if you have access to specialized tools for browsing / searching / retrieving information, use those first and fall back to fetch if they don't work\n\n## Examples\n\n### Example 1: Simple calculation\nThought: I need to calculate the sum of squares from 1 to 10.\n\n\\`\\`\\`javascript\nlet sum = 0;\nfor (let i = 1; i <= 10; i++) {\n sum += i * i;\n}\nconsole.log(\"Sum of squares:\", sum);\nfinal_answer(sum);\n\\`\\`\\`\n\n### Example 2: Using a tool\nThought: I need to search the web for current information.\n\n\\`\\`\\`javascript\nconst results = await web_search({ query: \"latest JavaScript features 2024\" });\nconsole.log(\"Search results:\", results);\n\\`\\`\\`\n\n### Example 3: Reading a file\nThought: I need to read the contents of package.json.\n\n\\`\\`\\`javascript\nconst content = fs.readFileSync('package.json', 'utf-8');\nconst pkg = JSON.parse(content);\nconsole.log(\"Package name:\", pkg.name);\nfinal_answer(pkg);\n\\`\\`\\`\n\n### Example 4: Using dynamic imports\nThought: I need to use lodash for array manipulation.\n\n\\`\\`\\`javascript\nconst _ = await importPackage('lodash');\nconst numbers = [1, 2, 3, 4, 5];\nconst chunked = _.chunk(numbers, 2);\nfinal_answer(chunked);\n\\`\\`\\`\n\n### Example 5: Multi-step task\nThought: First, I'll fetch the data from the API.\n\n\\`\\`\\`javascript\nconst response = await fetch('https://api.example.com/data');\nconst data = await response.json();\nconsole.log(\"Fetched items:\", data.length);\n\\`\\`\\`\n\n(Observation: Fetched items: 42)\n\nThought: Now I'll process the data and return the result.\n\n\\`\\`\\`javascript\nconst processed = data.filter(item => item.active).map(item => item.name);\nfinal_answer(processed);\n\\`\\`\\`\n\n${customInstructions ? `\\n## Additional Instructions\\n\\n${customInstructions}` : ''}\n\nNow, let's solve the task step by step. Remember to always call final_answer() when you have the complete answer.`;\n}\n\n/**\n * Prompt for generating a final answer when max steps is reached.\n */\nexport const FINAL_ANSWER_PROMPT = `Based on the steps you've taken so far, provide the best answer you can to the original task.\nIf you couldn't fully complete the task, explain what you accomplished and what remains to be done.\nCall final_answer() with your response.`;\n\n/**\n * Error recovery prompt.\n */\nexport function getErrorRecoveryPrompt(error: string): string {\n return `Your previous code encountered an error:\n\n${error}\n\nPlease analyze the error and try a different approach. Fix the issue and continue working on the task.`;\n}\n","/**\n * CodeAgent - Executes tasks by generating and running JavaScript code\n *\n * This is the main agent implementation for smol-js. It follows the ReAct pattern:\n * 1. Receives a task\n * 2. Generates reasoning and code\n * 3. Executes the code in a sandboxed environment\n * 4. Observes the result and continues or returns final answer\n */\n\nimport { Agent, AgentConfig } from './Agent.js';\nimport { LocalExecutor, ExecutorConfig } from '../executor/LocalExecutor.js';\nimport { FinalAnswerTool } from '../tools/defaultTools.js';\nimport { Tool } from '../tools/Tool.js';\nimport { generateSystemPrompt, getErrorRecoveryPrompt } from '../prompts/codeAgent.js';\nimport type { ActionStep, ActionOutput, ChatMessage } from '../types.js';\n\nexport interface CodeAgentConfig extends AgentConfig {\n /**\n * Additional npm packages that can be imported dynamically\n */\n additionalAuthorizedImports?: string[];\n\n /**\n * Executor configuration\n */\n executorConfig?: ExecutorConfig;\n\n /**\n * Working directory for file operations\n */\n workingDirectory?: string;\n}\n\n// Regex patterns for extracting code from LLM output\nconst CODE_BLOCK_REGEX = /```(?:javascript|js)?\\n([\\s\\S]*?)```/;\nconst THOUGHT_REGEX = /(?:Thought|Reasoning):\\s*([\\s\\S]*?)(?=```|$)/i;\n\nexport class CodeAgent extends Agent {\n /**\n * The JavaScript code executor\n */\n private executor: LocalExecutor;\n\n /**\n * Authorized imports for dynamic npm package loading\n */\n private authorizedImports: string[];\n\n constructor(config: CodeAgentConfig) {\n super(config);\n\n // Set authorized imports\n this.authorizedImports = config.additionalAuthorizedImports ?? [];\n\n // Initialize executor\n this.executor = new LocalExecutor({\n ...config.executorConfig,\n authorizedImports: this.authorizedImports,\n workingDirectory: config.workingDirectory,\n });\n\n // Always add final_answer tool\n if (!this.tools.has('final_answer')) {\n this.tools.set('final_answer', new FinalAnswerTool());\n }\n\n // Send tools to executor\n this.executor.sendTools(Object.fromEntries(this.tools));\n }\n\n /**\n * Initialize the system prompt with tool definitions.\n */\n protected initializeSystemPrompt(): string {\n // Generate tool documentation\n const toolDocs = Array.from(this.tools.values())\n .filter((tool) => tool.name !== 'final_answer') // final_answer is documented separately\n .map((tool) => tool.toCodePrompt())\n .join('\\n\\n');\n\n // Add final_answer documentation\n const finalAnswerDoc = `\n/**\n * Returns the final answer to the user. Call this when you have completed the task.\n * @param answer - The final answer (can be any type)\n */\nfunction final_answer(answer: any): void { ... }\n`.trim();\n\n const allTools = toolDocs ? `${toolDocs}\\n\\n${finalAnswerDoc}` : finalAnswerDoc;\n\n // Format authorized imports\n const importsDoc = this.authorizedImports.length > 0\n ? this.authorizedImports.map((pkg) => `- ${pkg}`).join('\\n')\n : 'None (use built-in capabilities only)';\n\n return generateSystemPrompt({\n tools: allTools,\n authorizedImports: importsDoc,\n customInstructions: this.config.customInstructions,\n });\n }\n\n /**\n * Execute a single step: get LLM response, extract code, execute it.\n */\n protected async executeStep(memoryStep: ActionStep): Promise<ActionOutput> {\n // Get messages for LLM\n const messages = this.memory.toMessages();\n memoryStep.modelInputMessages = [...messages];\n\n // Check if last step had an error - add recovery prompt\n const lastStep = this.memory.getActionSteps().slice(-2)[0]; // Get step before current\n if (lastStep?.error) {\n messages.push({\n role: 'user',\n content: getErrorRecoveryPrompt(lastStep.error.message),\n });\n }\n\n // Generate response from LLM\n const response = await this.generateResponse(messages);\n memoryStep.modelOutputMessage = response;\n memoryStep.tokenUsage = response.tokenUsage;\n\n const content = response.content ?? '';\n\n // Extract thought/reasoning\n const thoughtMatch = content.match(THOUGHT_REGEX);\n if (thoughtMatch) {\n this.logger.reasoning(thoughtMatch[1].trim());\n }\n\n // Extract code block\n const codeMatch = content.match(CODE_BLOCK_REGEX);\n\n if (!codeMatch) {\n // No code block found - this might be just reasoning\n // Feed back to LLM to generate code\n this.logger.warn('No code block found in response');\n memoryStep.observation = 'No code block was found in your response. Please provide JavaScript code in a ```javascript code block.';\n\n return {\n output: null,\n isFinalAnswer: false,\n };\n }\n\n const code = codeMatch[1].trim();\n memoryStep.codeAction = code;\n\n this.logger.code(code);\n\n // Wait before execution (allows user to interrupt)\n if (this.config.codeExecutionDelay > 0) {\n this.logger.waiting(this.config.codeExecutionDelay / 1000);\n await this.sleep(this.config.codeExecutionDelay);\n }\n\n // Execute the code\n this.logger.subheader('Executing code...');\n const result = await this.executor.execute(code);\n\n // Log execution logs\n if (result.logs) {\n this.logger.logs(result.logs);\n }\n\n // Handle execution error\n if (result.error) {\n this.logger.error('Code execution error', result.error);\n\n memoryStep.error = result.error;\n memoryStep.observation = `Error during code execution:\\n${result.error.message}`;\n\n return {\n output: null,\n isFinalAnswer: false,\n };\n }\n\n // Format observation\n const outputStr = this.formatOutput(result.output);\n this.logger.output(outputStr);\n\n memoryStep.observation = this.formatObservation(result.logs, outputStr);\n\n return {\n output: result.output,\n isFinalAnswer: result.isFinalAnswer,\n };\n }\n\n /**\n * Generate response from the LLM, optionally streaming.\n */\n private async generateResponse(messages: ChatMessage[]): Promise<ChatMessage> {\n if (this.config.streamOutputs && this.model.supportsStreaming() && this.model.generateStream) {\n // Stream the response\n this.logger.subheader('Agent thinking...');\n\n let fullContent = '';\n const generator = this.model.generateStream(messages, {\n stopSequences: ['Observation:', 'Observation:\\n'],\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n });\n\n for await (const chunk of generator) {\n this.logger.streamChar(chunk);\n fullContent += chunk;\n }\n\n this.logger.streamEnd();\n\n return {\n role: 'assistant',\n content: fullContent,\n };\n } else {\n // Non-streaming response\n this.logger.subheader('Agent thinking...');\n\n return this.model.generate(messages, {\n stopSequences: ['Observation:', 'Observation:\\n'],\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n });\n }\n }\n\n /**\n * Format output for display.\n */\n private formatOutput(output: unknown): string {\n if (output === undefined || output === null) {\n return '(no output)';\n }\n\n if (typeof output === 'string') {\n return output;\n }\n\n try {\n return JSON.stringify(output, null, 2);\n } catch {\n return String(output);\n }\n }\n\n /**\n * Format the observation to send back to the LLM.\n */\n private formatObservation(logs: string, output: string): string {\n const parts: string[] = [];\n\n if (logs.trim()) {\n parts.push(`Execution logs:\\n${logs}`);\n }\n\n parts.push(`Last output:\\n${output}`);\n\n return `Observation:\\n${parts.join('\\n\\n')}`;\n }\n\n /**\n * Reset the agent and executor state.\n */\n reset(): void {\n this.executor.reset();\n this.currentStep = 0;\n }\n\n /**\n * Get the executor instance.\n */\n getExecutor(): LocalExecutor {\n return this.executor;\n }\n\n /**\n * Override addTool to also register with executor.\n */\n addTool(tool: Tool): void {\n super.addTool(tool);\n this.executor.sendTools({ [tool.name]: tool });\n }\n}\n","/**\n * System prompts for ToolUseAgent\n */\n\nexport interface ToolUsePromptVariables {\n tools: string;\n customInstructions?: string;\n /** Whether this agent has sub-agents (AgentTool instances) */\n hasSubAgents?: boolean;\n /** Whether this agent has file tools (read_file, write_file) */\n hasFileTools?: boolean;\n}\n\n/**\n * Generate the system prompt for ToolUseAgent.\n */\nexport function generateToolUseSystemPrompt(variables: ToolUsePromptVariables): string {\n const { tools, customInstructions, hasSubAgents, hasFileTools } = variables;\n\n // Build content delegation guidelines based on agent capabilities\n let contentGuidelines = '';\n\n if (hasFileTools) {\n contentGuidelines += `\n## Content Output Guidelines\n\nWhen you produce long-form content (reports, articles, analyses, or any output longer than a few paragraphs):\n1. **Save to file**: Use \\`write_file\\` to save the full content to a descriptively-named file (e.g., \\`research_report.md\\`, \\`analysis_results.md\\`).\n2. **Return summary + filename**: In your \\`final_answer\\`, provide a brief summary of what you produced AND the filename where the full content is saved. Example: \"Completed the research report covering X, Y, Z. Full report saved to: research_report.md\"\n\nThis ensures managing agents can access your full output via \\`read_file\\` without it being truncated in message passing.\n`;\n }\n\n if (hasSubAgents) {\n contentGuidelines += `\n## Working with Sub-Agents\n\nWhen you delegate tasks to sub-agents:\n- Sub-agents return a **summary and filename** rather than the full content of long-form outputs.\n- To access the full content a sub-agent produced, use \\`read_file\\` with the filename they provide.\n- **Do NOT re-invoke a sub-agent to retrieve content it already created.** Instead, read the file directly.\n- When composing your own final output from sub-agent results, read their files as needed and synthesize.\n`;\n }\n\n if (hasSubAgents && hasFileTools) {\n contentGuidelines += `\n## When You Are Both a Manager and a Sub-Agent\n\nIf you manage sub-agents AND are yourself delegated tasks by a parent agent:\n- Follow the sub-agent content guidelines: save your own long-form output to a file, return summary + filename.\n- Follow the manager guidelines: read sub-agent output files rather than re-calling them.\n`;\n }\n\n return `You are an expert assistant and problem-solving agent. You solve tasks by reasoning step by step and using the tools available to you.\n\n## How You Work\n\nYou follow a ReAct (Reasoning + Acting) framework:\n1. **Think**: Analyze the current situation and decide what to do next\n2. **Act**: Call one or more tools to perform actions\n3. **Observe**: Review the results of your tool calls\n4. Repeat until you have the final answer\n\n## Available Tools\n\n${tools}\n\n## Rules\n\n1. **Always use final_answer**: When you have the complete answer, call the \\`final_answer\\` tool to return it. This is mandatory - you must always end by calling final_answer.\n\n2. **Think before acting**: Provide your reasoning in the content of your response before making tool calls. This helps track your thought process.\n\n3. **One logical action per step**: Focus on one logical action per step. You may call multiple tools in a single step if they are independent, but avoid chaining dependent operations without reviewing intermediate results.\n\n4. **Handle errors gracefully**: If a tool call fails, analyze the error and try a different approach.\n\n5. **Be concise**: Keep your reasoning brief and focused. Don't over-explain.\n\n6. **Use the right tool**: Choose the most appropriate tool for each action. Don't try to accomplish something a tool can do through other means.\n${contentGuidelines}\n${customInstructions ? `## Additional Instructions\\n\\n${customInstructions}` : ''}\n\nNow, let's solve the task step by step. Think carefully about what tools to use and in what order.`;\n}\n\n/**\n * Format tool descriptions for the system prompt.\n */\nexport function formatToolDescriptions(tools: Array<{ name: string; description: string; inputs: Record<string, { type: string; description: string; required?: boolean }> }>): string {\n return tools.map(tool => {\n const params = Object.entries(tool.inputs)\n .map(([name, input]) => {\n const req = input.required !== false ? ' (required)' : ' (optional)';\n return ` - ${name}${req}: ${input.description}`;\n })\n .join('\\n');\n\n return `### ${tool.name}\\n${tool.description}\\nParameters:\\n${params}`;\n }).join('\\n\\n');\n}\n","/**\n * ToolUseAgent - Executes tasks using standard OpenAI-style tool calls\n *\n * Unlike CodeAgent which generates and executes JavaScript code,\n * ToolUseAgent operates by making tool calls through the LLM's native\n * function calling capabilities, following the ReACT pattern:\n * Think -> Act (tool call) -> Observe (result) -> repeat\n */\n\nimport { Agent, AgentConfig } from './Agent.js';\nimport { FinalAnswerTool } from '../tools/defaultTools.js';\nimport { Tool } from '../tools/Tool.js';\nimport { generateToolUseSystemPrompt, formatToolDescriptions } from '../prompts/toolUseAgent.js';\nimport type { ActionStep, ActionOutput, ToolCall, ToolCallResult } from '../types.js';\n\nexport interface ToolUseAgentConfig extends AgentConfig {\n /** Whether to run independent tool calls in parallel (default: true) */\n parallelToolCalls?: boolean;\n}\n\nexport class ToolUseAgent extends Agent {\n private parallelToolCalls: boolean;\n\n constructor(config: ToolUseAgentConfig) {\n super(config);\n this.parallelToolCalls = config.parallelToolCalls ?? true;\n\n // Always add final_answer tool\n if (!this.tools.has('final_answer')) {\n this.tools.set('final_answer', new FinalAnswerTool());\n }\n }\n\n /**\n * Initialize the system prompt with tool descriptions.\n */\n protected initializeSystemPrompt(): string {\n const toolList = Array.from(this.tools.values());\n const toolDescriptions = formatToolDescriptions(\n toolList.map(t => ({\n name: t.name,\n description: t.description,\n inputs: t.inputs,\n }))\n );\n\n // Detect capabilities for content delegation guidelines\n const toolNames = new Set(Array.from(this.tools.keys()));\n const hasSubAgents = toolList.some(t => t.constructor.name === 'AgentTool');\n const hasFileTools = toolNames.has('read_file') || toolNames.has('write_file') || toolNames.has('read') || toolNames.has('write');\n\n return generateToolUseSystemPrompt({\n tools: toolDescriptions,\n customInstructions: this.config.customInstructions,\n hasSubAgents,\n hasFileTools,\n });\n }\n\n /**\n * Execute a single step: send messages with tool definitions, process tool calls.\n */\n protected async executeStep(memoryStep: ActionStep): Promise<ActionOutput> {\n const messages = this.memory.toMessages();\n memoryStep.modelInputMessages = [...messages];\n\n // Handle error recovery from previous step\n const actionSteps = this.memory.getActionSteps();\n const prevStep = actionSteps.length >= 2 ? actionSteps[actionSteps.length - 2] : undefined;\n if (prevStep?.error) {\n messages.push({\n role: 'user',\n content: `Your previous action encountered an error: ${prevStep.error.message}\\nPlease try a different approach.`,\n });\n }\n\n // Get tool definitions for the API call\n const toolDefinitions = Array.from(this.tools.values()).map(t => t.toOpenAITool());\n\n // Generate response with tool calling\n this.logger.subheader('Agent thinking...');\n const response = await this.model.generate(messages, {\n toolDefinitions,\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n });\n\n memoryStep.modelOutputMessage = response;\n memoryStep.tokenUsage = response.tokenUsage;\n\n // Log reasoning (text content)\n if (response.content && response.content.trim()) {\n this.logger.reasoning(response.content.trim());\n this.emitEvent('agent_thinking', {\n step: this.currentStep,\n content: response.content.trim(),\n });\n }\n\n // Check if model made tool calls\n if (!response.toolCalls || response.toolCalls.length === 0) {\n // No tool calls - the model just responded with text\n this.logger.warn('No tool calls in response. Prompting model to use tools.');\n memoryStep.observation = 'You must use tools to complete the task. Please call the appropriate tool(s). When you have the final answer, call the final_answer tool.';\n return { output: null, isFinalAnswer: false };\n }\n\n // Process tool calls\n memoryStep.toolCalls = response.toolCalls;\n const toolResults = await this.processToolCalls(response.toolCalls);\n memoryStep.toolResults = toolResults;\n\n // Check if final_answer was called\n for (const result of toolResults) {\n if (result.toolName === 'final_answer') {\n return { output: result.result, isFinalAnswer: true };\n }\n }\n\n // Log tool results as observations\n for (const result of toolResults) {\n if (result.error) {\n this.logger.error(`Tool ${result.toolName} failed: ${result.error}`);\n this.emitEvent('agent_error', { tool: result.toolName, error: result.error });\n } else {\n const resultStr = typeof result.result === 'string'\n ? result.result\n : JSON.stringify(result.result, null, 2);\n this.logger.output(`[${result.toolName}]: ${resultStr.slice(0, 500)}${resultStr.length > 500 ? '...' : ''}`);\n this.emitEvent('agent_observation', { tool: result.toolName, result: resultStr.slice(0, 500) });\n }\n }\n\n return { output: null, isFinalAnswer: false };\n }\n\n /**\n * Process tool calls from the model response.\n */\n private async processToolCalls(toolCalls: ToolCall[]): Promise<ToolCallResult[]> {\n const results: ToolCallResult[] = [];\n\n // Execute tool calls\n const executeTool = async (tc: ToolCall): Promise<ToolCallResult> => {\n const startTime = Date.now();\n const toolName = tc.function.name;\n const tool = this.tools.get(toolName);\n\n if (!tool) {\n const error = `Unknown tool: ${toolName}. Available tools: ${Array.from(this.tools.keys()).join(', ')}`;\n this.emitEvent('agent_tool_result', {\n step: this.currentStep,\n toolCallId: tc.id,\n toolName,\n result: null,\n error,\n duration: Date.now() - startTime,\n });\n return {\n toolCallId: tc.id,\n toolName,\n result: null,\n error,\n };\n }\n\n // Parse arguments\n let args: Record<string, unknown>;\n try {\n args = typeof tc.function.arguments === 'string'\n ? JSON.parse(tc.function.arguments)\n : tc.function.arguments as Record<string, unknown>;\n } catch {\n const error = `Failed to parse tool arguments: ${tc.function.arguments}`;\n this.emitEvent('agent_tool_result', {\n step: this.currentStep,\n toolCallId: tc.id,\n toolName,\n result: null,\n error,\n duration: Date.now() - startTime,\n });\n return {\n toolCallId: tc.id,\n toolName,\n result: null,\n error,\n };\n }\n\n this.logger.info(` Calling tool: ${toolName}(${JSON.stringify(args).slice(0, 100)}...)`);\n this.emitEvent('agent_tool_call', {\n step: this.currentStep,\n toolCallId: tc.id,\n toolName,\n arguments: args,\n });\n\n try {\n const result = await tool.call(args);\n const duration = Date.now() - startTime;\n this.emitEvent('agent_tool_result', {\n step: this.currentStep,\n toolCallId: tc.id,\n toolName,\n result,\n duration,\n });\n return {\n toolCallId: tc.id,\n toolName,\n result,\n };\n } catch (error) {\n const errorMsg = `Tool execution error: ${(error as Error).message}`;\n const duration = Date.now() - startTime;\n this.emitEvent('agent_tool_result', {\n step: this.currentStep,\n toolCallId: tc.id,\n toolName,\n result: null,\n error: errorMsg,\n duration,\n });\n return {\n toolCallId: tc.id,\n toolName,\n result: null,\n error: errorMsg,\n };\n }\n };\n\n if (this.parallelToolCalls) {\n const promises = toolCalls.map(tc => executeTool(tc));\n const resolvedResults = await Promise.all(promises);\n results.push(...resolvedResults);\n } else {\n for (const tc of toolCalls) {\n results.push(await executeTool(tc));\n }\n }\n\n return results;\n }\n\n /**\n * Override provideFinalAnswer to use tool calling format.\n */\n protected async provideFinalAnswer(task: string): Promise<unknown> {\n this.logger.subheader('Generating final answer from accumulated context');\n\n const messages = this.memory.toMessages();\n messages.push({\n role: 'user',\n 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.`,\n });\n\n const toolDefinitions = [new FinalAnswerTool().toOpenAITool()];\n const response = await this.model.generate(messages, {\n toolDefinitions,\n maxTokens: this.config.maxTokens,\n temperature: this.config.temperature,\n });\n\n // Try to extract from tool call\n if (response.toolCalls && response.toolCalls.length > 0) {\n const tc = response.toolCalls[0];\n try {\n const args = typeof tc.function.arguments === 'string'\n ? JSON.parse(tc.function.arguments)\n : tc.function.arguments;\n return (args as Record<string, unknown>).answer;\n } catch {\n return response.content;\n }\n }\n\n return response.content;\n }\n\n /**\n * Add a tool, which can also be an Agent instance (auto-wraps with AgentTool).\n */\n addTool(tool: Tool): void {\n super.addTool(tool);\n }\n}\n","/**\n * Model base class for smol-js\n *\n * Models are responsible for generating text responses from LLMs.\n * Extend this class to support different LLM providers.\n */\n\nimport type { ChatMessage, GenerateOptions, TokenUsage } from '../types.js';\n\nexport abstract class Model {\n /**\n * Model identifier (e.g., \"gpt-4\", \"claude-3-sonnet\")\n */\n abstract readonly modelId: string;\n\n /**\n * Generate a response from the model.\n */\n abstract generate(\n messages: ChatMessage[],\n options?: GenerateOptions\n ): Promise<ChatMessage>;\n\n /**\n * Optional streaming generation.\n * Yields content chunks and returns the final message.\n */\n generateStream?(\n messages: ChatMessage[],\n options?: GenerateOptions\n ): AsyncGenerator<string, ChatMessage, undefined>;\n\n /**\n * Check if the model supports streaming.\n */\n supportsStreaming(): boolean {\n return typeof this.generateStream === 'function';\n }\n\n /**\n * Extract token usage from a response message.\n */\n protected extractTokenUsage(_response: unknown): TokenUsage | undefined {\n // Override in subclasses to extract token usage from API responses\n return undefined;\n }\n\n /**\n * Convert messages to the format expected by the model's API.\n */\n protected formatMessages(messages: ChatMessage[]): unknown[] {\n // Default implementation - override for specific API formats\n return messages.map((msg) => ({\n role: msg.role,\n content: msg.content,\n ...(msg.name && { name: msg.name }),\n ...(msg.toolCallId && { tool_call_id: msg.toolCallId }),\n }));\n }\n}\n","/**\n * OpenAI-compatible Model implementation\n *\n * Supports any API that follows the OpenAI chat completions format,\n * including OpenRouter, Azure OpenAI, local servers, etc.\n */\n\nimport OpenAI from 'openai/index.mjs';\nimport { Model } from './Model.js';\nimport type { ChatMessage, GenerateOptions, TokenUsage, MessageRole } from '../types.js';\n\nexport interface OpenAIModelConfig {\n /**\n * Model identifier (e.g., \"gpt-4\", \"anthropic/claude-sonnet-4.5\")\n */\n modelId?: string;\n\n /**\n * API key for authentication\n */\n apiKey?: string;\n\n /**\n * Base URL for the API endpoint\n * @default \"https://openrouter.ai/api/v1\"\n */\n baseUrl?: string;\n\n /**\n * Maximum tokens to generate (omitted from requests by default)\n */\n maxTokens?: number;\n\n /**\n * Temperature for generation (omitted from requests by default)\n */\n temperature?: number;\n\n /**\n * Request timeout in milliseconds\n */\n timeout?: number;\n\n /**\n * Default headers to include in requests\n */\n defaultHeaders?: Record<string, string>;\n}\n\nconst DEFAULT_MODEL_ID = 'anthropic/claude-sonnet-4.5';\nconst DEFAULT_BASE_URL = 'https://openrouter.ai/api/v1';\nconst DEFAULT_TIMEOUT = 120000;\n\nexport class OpenAIModel extends Model {\n readonly modelId: string;\n private client: OpenAI;\n private config: OpenAIModelConfig;\n\n constructor(config: OpenAIModelConfig = {}) {\n super();\n\n this.config = config;\n this.modelId = config.modelId ?? DEFAULT_MODEL_ID;\n\n // Get API key from config or environment\n const apiKey = config.apiKey ?? process.env.OPENAI_API_KEY ?? process.env.OPENROUTER_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'API key is required. Set OPENAI_API_KEY or OPENROUTER_API_KEY environment variable, or pass apiKey in config.'\n );\n }\n\n this.client = new OpenAI({\n apiKey,\n baseURL: config.baseUrl ?? DEFAULT_BASE_URL,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n defaultHeaders: config.defaultHeaders,\n });\n }\n\n /**\n * Generate a response from the model (supports tool calling).\n */\n async generate(messages: ChatMessage[], options: GenerateOptions = {}): Promise<ChatMessage> {\n const formattedMessages = this.formatMessages(messages);\n\n const requestParams: Record<string, unknown> = {\n model: this.modelId,\n messages: formattedMessages,\n };\n\n // Only include maxTokens if specified at request or model config level\n const maxTokens = options.maxTokens ?? this.config.maxTokens;\n if (maxTokens !== undefined) {\n requestParams.max_tokens = maxTokens;\n }\n\n // Only include temperature if specified at request or model config level\n const temperature = options.temperature ?? this.config.temperature;\n if (temperature !== undefined) {\n requestParams.temperature = temperature;\n }\n\n if (options.stopSequences) {\n requestParams.stop = options.stopSequences;\n }\n\n // Add tool definitions for function calling\n if (options.toolDefinitions && options.toolDefinitions.length > 0) {\n requestParams.tools = options.toolDefinitions;\n } else if (options.tools && options.tools.length > 0) {\n requestParams.tools = options.tools.map(t => t.toOpenAITool());\n }\n\n const response = await this.client.chat.completions.create({\n ...requestParams,\n model: this.modelId,\n messages: formattedMessages as OpenAI.Chat.ChatCompletionMessageParam[],\n } as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming);\n\n const choice = response.choices[0];\n const message = choice?.message;\n\n if (!message) {\n throw new Error('No response from model');\n }\n\n const tokenUsage: TokenUsage | undefined = response.usage\n ? {\n inputTokens: response.usage.prompt_tokens,\n outputTokens: response.usage.completion_tokens ?? 0,\n totalTokens: response.usage.total_tokens,\n }\n : undefined;\n\n // Map tool_calls from OpenAI format\n const toolCalls = message.tool_calls?.map((tc: OpenAI.Chat.ChatCompletionMessageToolCall) => ({\n id: tc.id,\n type: 'function' as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n }));\n\n return {\n role: 'assistant' as MessageRole,\n content: message.content ?? '',\n toolCalls,\n tokenUsage,\n };\n }\n\n /**\n * Generate a streaming response from the model.\n */\n async *generateStream(\n messages: ChatMessage[],\n options: GenerateOptions = {}\n ): AsyncGenerator<string, ChatMessage, undefined> {\n const formattedMessages = this.formatMessages(messages);\n\n const requestParams: Record<string, unknown> = {\n model: this.modelId,\n messages: formattedMessages,\n stream: true,\n };\n\n const maxTokens = options.maxTokens ?? this.config.maxTokens;\n if (maxTokens !== undefined) {\n requestParams.max_tokens = maxTokens;\n }\n\n const temperature = options.temperature ?? this.config.temperature;\n if (temperature !== undefined) {\n requestParams.temperature = temperature;\n }\n\n if (options.stopSequences) {\n requestParams.stop = options.stopSequences;\n }\n\n const stream = await this.client.chat.completions.create({\n ...requestParams,\n model: this.modelId,\n messages: formattedMessages as OpenAI.Chat.ChatCompletionMessageParam[],\n stream: true,\n } as OpenAI.Chat.ChatCompletionCreateParamsStreaming);\n\n let fullContent = '';\n\n for await (const chunk of stream as AsyncIterable<OpenAI.Chat.ChatCompletionChunk>) {\n const delta = chunk.choices[0]?.delta;\n if (delta?.content) {\n fullContent += delta.content;\n yield delta.content;\n }\n }\n\n return {\n role: 'assistant' as MessageRole,\n content: fullContent,\n };\n }\n\n /**\n * Format messages for the OpenAI API, including tool call/response messages.\n */\n protected formatMessages(messages: ChatMessage[]): OpenAI.Chat.ChatCompletionMessageParam[] {\n return messages.map((msg) => {\n // Handle tool response messages\n if (msg.role === 'tool' && msg.toolCallId) {\n return {\n role: 'tool' as const,\n content: msg.content ?? '',\n tool_call_id: msg.toolCallId,\n };\n }\n\n // Handle tool responses without toolCallId (legacy format)\n if (msg.role === 'tool') {\n return {\n role: 'user' as const,\n content: msg.content ?? '',\n };\n }\n\n // Handle assistant messages with tool calls\n if (msg.role === 'assistant' && msg.toolCalls && msg.toolCalls.length > 0) {\n return {\n role: 'assistant' as const,\n content: msg.content || null,\n tool_calls: msg.toolCalls.map(tc => ({\n id: tc.id,\n type: 'function' as const,\n function: {\n name: tc.function.name,\n arguments: typeof tc.function.arguments === 'string'\n ? tc.function.arguments\n : JSON.stringify(tc.function.arguments),\n },\n })),\n };\n }\n\n return {\n role: msg.role as 'system' | 'user' | 'assistant',\n content: msg.content ?? '',\n };\n });\n }\n}\n","/**\n * AgentTool - Wraps a CodeAgent as a Tool for use by other agents\n *\n * This enables nested/hierarchical agent architectures where a \"manager\" agent\n * can delegate tasks to specialized \"worker\" agents.\n *\n * Based on the ManagedAgent pattern from Python smolagents.\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\nimport type { Agent } from '../agents/Agent.js';\n\nexport interface AgentToolConfig {\n /**\n * The agent to wrap as a tool\n */\n agent: Agent;\n\n /**\n * Name for the tool (defaults to agent's name or \"managed_agent\")\n */\n name?: string;\n\n /**\n * Description of what this agent does (used in parent agent's prompt)\n */\n description?: string;\n\n /**\n * Additional context to provide to the agent with each task\n */\n additionalContext?: string;\n\n /**\n * Whether to provide the full result object or just the output\n * @default false\n */\n returnFullResult?: boolean;\n}\n\nexport class AgentTool extends Tool {\n readonly name: string;\n readonly description: string;\n readonly inputs: ToolInputs = {\n task: {\n type: 'string',\n description: 'The task or question to delegate to this agent',\n required: true,\n },\n };\n readonly outputType = 'string';\n\n private agent: Agent;\n private additionalContext?: string;\n private returnFullResult: boolean;\n\n constructor(config: AgentToolConfig) {\n super();\n this.agent = config.agent;\n this.name = config.name ?? 'managed_agent';\n this.additionalContext = config.additionalContext;\n this.returnFullResult = config.returnFullResult ?? false;\n\n // Build description from config or generate default\n this.description = config.description ?? this.generateDescription();\n }\n\n /**\n * Generate a default description based on the agent's configuration\n */\n private generateDescription(): string {\n return `Delegates a task to a specialized agent.\nThis agent can help with complex sub-tasks that require multiple steps.\nPass a clear, specific task description and the agent will work autonomously to solve it.\nReturns the agent's final answer as a string.`;\n }\n\n /**\n * Execute the agent with the given task\n */\n async execute(args: Record<string, unknown>): Promise<unknown> {\n let task = args.task as string;\n\n // Add additional context if provided\n if (this.additionalContext) {\n task = `${this.additionalContext}\\n\\nTask: ${task}`;\n }\n\n // Run the agent\n const result = await this.agent.run(task, true);\n\n // Return full result or just output\n if (this.returnFullResult) {\n return {\n output: result.output,\n steps: result.steps.length,\n duration: result.duration,\n };\n }\n\n // Convert output to string if needed\n const output = result.output;\n if (typeof output === 'string') {\n return output;\n }\n return JSON.stringify(output, null, 2);\n }\n\n /**\n * Override toCodePrompt to provide a cleaner signature for nested agents\n */\n toCodePrompt(): string {\n return `\n/**\n * ${this.description}\n *\n * @param task - The task or question to delegate to this specialized agent\n * @returns The agent's answer as a string\n */\nasync function ${this.name}(task: string): Promise<string> { ... }\n`.trim();\n }\n}\n\n/**\n * Helper function to quickly wrap an agent as a tool\n */\nexport function agentAsTool(\n agent: Agent,\n options?: Omit<AgentToolConfig, 'agent'>\n): AgentTool {\n return new AgentTool({ agent, ...options });\n}\n","/**\n * ReadFileTool - Read contents from a file\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport class ReadFileTool extends Tool {\n readonly name = 'read_file';\n readonly description = 'Read the contents of a file at the specified path. Returns the file content as a string.';\n readonly inputs: ToolInputs = {\n path: {\n type: 'string',\n description: 'The file path to read (absolute or relative to working directory)',\n required: true,\n },\n encoding: {\n type: 'string',\n description: 'File encoding (default: utf-8)',\n required: false,\n default: 'utf-8',\n },\n };\n readonly outputType = 'string';\n\n private workingDirectory: string;\n\n constructor(config?: { workingDirectory?: string }) {\n super();\n this.workingDirectory = config?.workingDirectory ?? process.cwd();\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const filePath = args.path as string;\n const encoding = (args.encoding as BufferEncoding) ?? 'utf-8';\n\n const resolvedPath = path.isAbsolute(filePath)\n ? filePath\n : path.resolve(this.workingDirectory, filePath);\n\n if (!fs.existsSync(resolvedPath)) {\n throw new Error(`File not found: ${resolvedPath}`);\n }\n\n const stat = fs.statSync(resolvedPath);\n if (stat.isDirectory()) {\n throw new Error(`Path is a directory, not a file: ${resolvedPath}`);\n }\n\n const content = fs.readFileSync(resolvedPath, encoding);\n\n // Truncate very large files\n const maxLength = 100000;\n if (content.length > maxLength) {\n return content.slice(0, maxLength) + `\\n\\n[... truncated, file is ${content.length} characters total]`;\n }\n\n return content;\n }\n}\n","/**\n * WriteFileTool - Write content to a file\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport class WriteFileTool extends Tool {\n readonly name = 'write_file';\n readonly description = 'Write content to a file at the specified path. Creates the file if it does not exist, and creates parent directories as needed. Overwrites existing content by default.';\n readonly inputs: ToolInputs = {\n path: {\n type: 'string',\n description: 'The file path to write to (absolute or relative to working directory)',\n required: true,\n },\n content: {\n type: 'string',\n description: 'The content to write to the file',\n required: true,\n },\n append: {\n type: 'boolean',\n description: 'If true, append to the file instead of overwriting (default: false)',\n required: false,\n default: false,\n },\n };\n readonly outputType = 'string';\n\n private workingDirectory: string;\n\n constructor(config?: { workingDirectory?: string }) {\n super();\n this.workingDirectory = config?.workingDirectory ?? process.cwd();\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const filePath = args.path as string;\n const content = args.content as string;\n const append = (args.append as boolean) ?? false;\n\n const resolvedPath = path.isAbsolute(filePath)\n ? filePath\n : path.resolve(this.workingDirectory, filePath);\n\n // Create parent directories if needed\n const dir = path.dirname(resolvedPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n if (append) {\n fs.appendFileSync(resolvedPath, content, 'utf-8');\n return `Successfully appended ${content.length} characters to ${resolvedPath}`;\n } else {\n fs.writeFileSync(resolvedPath, content, 'utf-8');\n return `Successfully wrote ${content.length} characters to ${resolvedPath}`;\n }\n }\n}\n","/**\n * CurlTool - HTTP requests (GET/POST) using fetch\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\n\nexport class CurlTool extends Tool {\n readonly name = 'curl';\n readonly description = 'Make HTTP requests to any URL. Supports GET and POST methods with custom headers and body. Returns the response body as text.';\n readonly inputs: ToolInputs = {\n url: {\n type: 'string',\n description: 'The URL to request',\n required: true,\n },\n method: {\n type: 'string',\n description: 'HTTP method: GET or POST (default: GET)',\n required: false,\n default: 'GET',\n enum: ['GET', 'POST'],\n },\n headers: {\n type: 'object',\n description: 'Optional HTTP headers as key-value pairs (e.g., {\"Content-Type\": \"application/json\"})',\n required: false,\n },\n body: {\n type: 'string',\n description: 'Request body for POST requests (typically JSON string)',\n required: false,\n },\n };\n readonly outputType = 'string';\n\n private timeout: number;\n\n constructor(config?: { timeout?: number }) {\n super();\n this.timeout = config?.timeout ?? 30000;\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const url = args.url as string;\n const method = ((args.method as string) ?? 'GET').toUpperCase();\n const headers = (args.headers as Record<string, string>) ?? {};\n const body = args.body as string | undefined;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const fetchOptions: RequestInit = {\n method,\n headers,\n signal: controller.signal,\n };\n\n if (method === 'POST' && body) {\n fetchOptions.body = body;\n if (!headers['Content-Type'] && !headers['content-type']) {\n (fetchOptions.headers as Record<string, string>)['Content-Type'] = 'application/json';\n }\n }\n\n const response = await fetch(url, fetchOptions);\n const responseText = await response.text();\n\n const statusLine = `HTTP ${response.status} ${response.statusText}`;\n\n // Truncate very large responses\n const maxLength = 50000;\n const truncatedBody = responseText.length > maxLength\n ? responseText.slice(0, maxLength) + `\\n\\n[... truncated, response is ${responseText.length} characters total]`\n : responseText;\n\n return `${statusLine}\\n\\n${truncatedBody}`;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n throw new Error(`Request timed out after ${this.timeout}ms: ${url}`);\n }\n throw new Error(`HTTP request failed: ${(error as Error).message}`);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n","/**\n * ExaSearchTool - Web search using the Exa.ai API\n *\n * Uses Exa's embeddings-based search for semantically intelligent results.\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\n\nexport interface ExaSearchConfig {\n apiKey?: string;\n}\n\nexport class ExaSearchTool extends Tool {\n readonly name = 'exa_search';\n readonly description = 'Search the web using Exa.ai semantic search. Returns relevant web pages with titles, URLs, and optionally content snippets. Use this for finding information, research, and fact-checking.';\n readonly inputs: ToolInputs = {\n query: {\n type: 'string',\n description: 'The search query. Be specific and descriptive for best results.',\n required: true,\n },\n numResults: {\n type: 'number',\n description: 'Number of results to return (default: 10, max: 30)',\n required: false,\n default: 10,\n },\n type: {\n type: 'string',\n description: 'Search type: \"auto\" (default), \"neural\" (embeddings-based), or \"keyword\"',\n required: false,\n default: 'auto',\n enum: ['auto', 'neural', 'keyword'],\n },\n category: {\n type: 'string',\n description: 'Optional category filter: \"research paper\", \"news\", \"pdf\", \"github\", \"tweet\", \"company\", \"blog\"',\n required: false,\n },\n includeDomains: {\n type: 'array',\n description: 'Only include results from these domains (e.g., [\"arxiv.org\", \"github.com\"])',\n required: false,\n },\n excludeDomains: {\n type: 'array',\n description: 'Exclude results from these domains',\n required: false,\n },\n startPublishedDate: {\n type: 'string',\n description: 'Filter results published after this ISO 8601 date (e.g., \"2024-01-01\")',\n required: false,\n },\n };\n readonly outputType = 'string';\n\n private apiKey: string;\n\n constructor(config?: ExaSearchConfig) {\n super();\n this.apiKey = config?.apiKey ?? process.env.EXA_API_KEY ?? '';\n }\n\n async setup(): Promise<void> {\n if (!this.apiKey) {\n throw new Error('EXA_API_KEY is required. Set it as an environment variable or pass it in the config.');\n }\n this.isSetup = true;\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const query = args.query as string;\n const numResults = Math.min((args.numResults as number) ?? 10, 30);\n const type = (args.type as string) ?? 'auto';\n\n const requestBody: Record<string, unknown> = {\n query,\n numResults,\n type,\n text: { maxCharacters: 1000 },\n };\n\n if (args.category) requestBody.category = args.category;\n if (args.includeDomains) requestBody.includeDomains = args.includeDomains;\n if (args.excludeDomains) requestBody.excludeDomains = args.excludeDomains;\n if (args.startPublishedDate) requestBody.startPublishedDate = args.startPublishedDate;\n\n const response = await fetch('https://api.exa.ai/search', {\n method: 'POST',\n headers: {\n 'x-api-key': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Exa search failed (${response.status}): ${errorText}`);\n }\n\n const data = await response.json() as {\n results: Array<{\n title?: string;\n url: string;\n publishedDate?: string;\n author?: string;\n text?: string;\n score?: number;\n }>;\n };\n\n if (!data.results || data.results.length === 0) {\n return 'No results found for the query.';\n }\n\n // Format results for the agent\n const formattedResults = data.results.map((result, i) => {\n const parts = [`[${i + 1}] ${result.title ?? 'Untitled'}`];\n parts.push(` URL: ${result.url}`);\n if (result.publishedDate) parts.push(` Date: ${result.publishedDate}`);\n if (result.author) parts.push(` Author: ${result.author}`);\n if (result.text) {\n const snippet = result.text.slice(0, 300).trim();\n parts.push(` Snippet: ${snippet}${result.text.length > 300 ? '...' : ''}`);\n }\n return parts.join('\\n');\n }).join('\\n\\n');\n\n return `Search results for \"${query}\" (${data.results.length} results):\\n\\n${formattedResults}`;\n }\n}\n","/**\n * ExaGetContentsTool - Get webpage contents using Exa.ai API\n *\n * Fetches and extracts clean text content from web pages.\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\n\nexport interface ExaGetContentsConfig {\n apiKey?: string;\n}\n\nexport class ExaGetContentsTool extends Tool {\n readonly name = 'exa_get_contents';\n readonly description = 'Get the full text content of one or more web pages using Exa.ai. Returns cleaned, readable text extracted from the HTML. Use this to read articles, documentation, or any web page content.';\n readonly inputs: ToolInputs = {\n urls: {\n type: 'array',\n description: 'Array of URLs to fetch content from (max 10)',\n required: true,\n },\n maxCharacters: {\n type: 'number',\n description: 'Maximum characters of content to return per page (default: 10000)',\n required: false,\n default: 10000,\n },\n livecrawl: {\n type: 'string',\n description: 'Crawl strategy: \"fallback\" (use cache, fetch live if unavailable), \"always\" (always fetch live), \"never\" (cache only). Default: \"fallback\"',\n required: false,\n default: 'fallback',\n enum: ['fallback', 'always', 'never'],\n },\n };\n readonly outputType = 'string';\n\n private apiKey: string;\n\n constructor(config?: ExaGetContentsConfig) {\n super();\n this.apiKey = config?.apiKey ?? process.env.EXA_API_KEY ?? '';\n }\n\n async setup(): Promise<void> {\n if (!this.apiKey) {\n throw new Error('EXA_API_KEY is required. Set it as an environment variable or pass it in the config.');\n }\n this.isSetup = true;\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const urls = (args.urls as string[]).slice(0, 10);\n const maxCharacters = (args.maxCharacters as number) ?? 10000;\n const livecrawl = (args.livecrawl as string) ?? 'fallback';\n\n const requestBody = {\n urls,\n text: { maxCharacters },\n livecrawl,\n };\n\n const response = await fetch('https://api.exa.ai/contents', {\n method: 'POST',\n headers: {\n 'x-api-key': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Exa get contents failed (${response.status}): ${errorText}`);\n }\n\n const data = await response.json() as {\n results: Array<{\n url: string;\n title?: string;\n author?: string;\n publishedDate?: string;\n text?: string;\n }>;\n };\n\n if (!data.results || data.results.length === 0) {\n return 'No content could be retrieved from the provided URLs.';\n }\n\n const formattedResults = data.results.map((result) => {\n const parts = [`## ${result.title ?? result.url}`];\n parts.push(`URL: ${result.url}`);\n if (result.author) parts.push(`Author: ${result.author}`);\n if (result.publishedDate) parts.push(`Date: ${result.publishedDate}`);\n parts.push('');\n if (result.text) {\n parts.push(result.text);\n } else {\n parts.push('[No text content available]');\n }\n return parts.join('\\n');\n }).join('\\n\\n---\\n\\n');\n\n return formattedResults;\n }\n}\n","/**\n * ExaResearchTool - Agentic web research using Exa.ai Research API\n *\n * The Research API is an asynchronous, multi-step pipeline that transforms\n * open-ended questions into grounded reports with citations. The system performs\n * planning, searching, and reasoning to produce comprehensive research outputs.\n *\n * See: https://docs.exa.ai/reference/exa-research\n */\n\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\n\nexport interface ExaResearchConfig {\n apiKey?: string;\n model?: 'exa-research-fast' | 'exa-research' | 'exa-research-pro';\n pollInterval?: number; // Milliseconds between status checks (default: 2000)\n maxPollTime?: number; // Max time to poll in milliseconds (default: 300000 = 5 minutes)\n}\n\ninterface ResearchResponse {\n researchId: string;\n createdAt: number;\n model: string;\n instructions: string;\n status: 'pending' | 'running' | 'completed' | 'failed' | 'canceled';\n output?: {\n content: string; // Markdown report with citations\n parsed?: unknown; // Structured data if outputSchema provided\n };\n costDollars?: {\n total: number;\n numSearches: number;\n numPages: number;\n reasoningTokens: number;\n };\n finishedAt?: number;\n error?: string;\n events?: Array<Record<string, unknown>>;\n}\n\nexport class ExaResearchTool extends Tool {\n readonly name = 'exa_research';\n readonly description = 'Perform comprehensive web research using Exa.ai\\'s agentic research system. Provide natural-language instructions about what to research, and the AI research agent will plan searches, gather sources, extract facts, and synthesize findings into a detailed markdown report with citations. Ideal for deep research on any topic. Results typically complete in 20-90 seconds.';\n readonly inputs: ToolInputs = {\n instructions: {\n type: 'string',\n description: 'Natural-language task description of what to research (max 4096 characters). Be clear about what information you want, how research should be conducted, and what the output should contain.',\n required: true,\n },\n model: {\n type: 'string',\n description: 'Research model: \"exa-research-fast\" (faster, cheaper), \"exa-research\" (balanced, default), or \"exa-research-pro\" (most thorough)',\n required: false,\n },\n outputSchema: {\n type: 'object',\n description: 'Optional JSON Schema to enforce structured output format (max 8 root fields, 5 levels deep). If omitted, returns markdown report.',\n required: false,\n },\n };\n readonly outputType = 'string';\n\n private apiKey: string;\n private defaultModel: string;\n private pollInterval: number;\n private maxPollTime: number;\n\n constructor(config?: ExaResearchConfig) {\n super();\n this.apiKey = config?.apiKey ?? process.env.EXA_API_KEY ?? '';\n this.defaultModel = config?.model ?? 'exa-research';\n this.pollInterval = config?.pollInterval ?? 2000; // 2 seconds\n this.maxPollTime = config?.maxPollTime ?? 300000; // 5 minutes\n }\n\n async setup(): Promise<void> {\n if (!this.apiKey) {\n throw new Error('EXA_API_KEY is required. Set it as an environment variable or pass it in the config.');\n }\n this.isSetup = true;\n }\n\n async execute(args: Record<string, unknown>): Promise<string> {\n const instructions = args.instructions as string;\n const model = (args.model as string) ?? this.defaultModel;\n const outputSchema = args.outputSchema as Record<string, unknown> | undefined;\n\n if (!instructions || instructions.length > 4096) {\n throw new Error('Instructions are required and must be <= 4096 characters');\n }\n\n // Step 1: Create research task\n const createBody: Record<string, unknown> = {\n instructions,\n model,\n };\n\n if (outputSchema) {\n createBody.outputSchema = outputSchema;\n }\n\n const createResponse = await fetch('https://api.exa.ai/research/v1', {\n method: 'POST',\n headers: {\n 'x-api-key': this.apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(createBody),\n });\n\n if (!createResponse.ok) {\n const errorText = await createResponse.text();\n throw new Error(`Failed to create research task (${createResponse.status}): ${errorText}`);\n }\n\n const createData = await createResponse.json() as { researchId: string };\n const researchId = createData.researchId;\n\n console.log(`Research task created: ${researchId}. Polling for results...`);\n\n // Step 2: Poll for completion\n const startTime = Date.now();\n let attempts = 0;\n\n while (Date.now() - startTime < this.maxPollTime) {\n attempts++;\n\n // Wait before polling (except first attempt)\n if (attempts > 1) {\n await new Promise(resolve => setTimeout(resolve, this.pollInterval));\n }\n\n const statusResponse = await fetch(`https://api.exa.ai/research/v1/${researchId}`, {\n method: 'GET',\n headers: {\n 'x-api-key': this.apiKey,\n },\n });\n\n if (!statusResponse.ok) {\n const errorText = await statusResponse.text();\n throw new Error(`Failed to check research status (${statusResponse.status}): ${errorText}`);\n }\n\n const statusData = await statusResponse.json() as ResearchResponse;\n\n if (statusData.status === 'completed') {\n // Success! Return the research output\n const output = statusData.output;\n if (!output) {\n throw new Error('Research completed but no output was returned');\n }\n\n // Format the response with cost information\n const sections: string[] = [];\n\n // Add the main content (markdown report or structured data)\n if (outputSchema && output.parsed) {\n sections.push('# Research Results (Structured)\\n');\n sections.push(JSON.stringify(output.parsed, null, 2));\n } else {\n sections.push(output.content);\n }\n\n // Add cost breakdown\n if (statusData.costDollars) {\n const cost = statusData.costDollars;\n sections.push('\\n---\\n');\n sections.push('## Research Metrics\\n');\n sections.push(`- **Cost**: $${cost.total.toFixed(4)}`);\n sections.push(`- **Searches**: ${cost.numSearches}`);\n sections.push(`- **Pages analyzed**: ${cost.numPages}`);\n sections.push(`- **Reasoning tokens**: ${cost.reasoningTokens.toLocaleString()}`);\n }\n\n console.log(`Research completed in ${attempts} polls (${((Date.now() - startTime) / 1000).toFixed(1)}s)`);\n return sections.join('\\n');\n }\n\n if (statusData.status === 'failed') {\n throw new Error(`Research failed: ${statusData.error ?? 'Unknown error'}`);\n }\n\n if (statusData.status === 'canceled') {\n throw new Error('Research was canceled');\n }\n\n // Still pending or running, continue polling\n if (attempts % 10 === 0) {\n console.log(`Still researching... (${attempts} polls, ${((Date.now() - startTime) / 1000).toFixed(0)}s elapsed)`);\n }\n }\n\n throw new Error(`Research timed out after ${this.maxPollTime / 1000}s. Task ID: ${researchId}`);\n }\n}\n","/**\n * ProxyTool - Bridges the smol-js agent runtime to an external standalone tool\n * executed in an isolated Bun process via the toolHarness adapter.\n *\n * The tool file is never imported into the main Node.js process. When an agent\n * invokes this proxy, it spawns:\n *\n * bun run <toolHarness.ts> <toolPath> <argsJson>\n *\n * The harness is the ONLY place that speaks the stdout protocol. The tool\n * itself simply exports { TOOL_METADATA, execute } and knows nothing about\n * how it is being called.\n *\n * Protocol (stdout of harness/child):\n * - A line prefixed with `[TOOL_RESULT]` contains the JSON-serialized return value.\n * - A line prefixed with `[TOOL_ERROR]` means the tool threw; payload is the message.\n * - Any other stdout line (e.g. console.log inside execute()) is streaming output.\n *\n * Extensibility: The spawn+stdio transport is fully encapsulated here. A future\n * variant (HTTP, gRPC, IPC) only needs to replace execute() — the tool file and\n * YAML definition stay identical.\n */\n\nimport { spawn } from 'child_process';\nimport * as path from 'path';\nimport { Tool } from './Tool.js';\nimport type { ToolInputs } from '../types.js';\nimport { ensureBunAvailable } from '../utils/bunInstaller.js';\n\n// --- Protocol delimiters (spoken only by toolHarness, parsed only here) ---\nexport const TOOL_RESULT_PREFIX = '[TOOL_RESULT]';\nexport const TOOL_ERROR_PREFIX = '[TOOL_ERROR]';\n\n/** How long (ms) to wait for the child process before forcefully killing it. */\nconst DEFAULT_TOOL_TIMEOUT_MS = 60_000;\n\n/**\n * Resolve the toolHarness.ts path shipped with this package.\n * At runtime the bundled code lives in dist/; the harness is at the package root.\n */\nfunction resolveHarnessPath(): string {\n // __dirname in the CJS bundle points to dist/. The harness sits one level up.\n return path.resolve(__dirname, '..', 'toolHarness.ts');\n}\n\nexport interface ProxyToolConfig {\n /** Absolute path to the .ts or .js tool file */\n toolPath: string;\n /** Tool name (must match the file's base name) */\n name: string;\n /** Human-readable description exposed to agents */\n description: string;\n /** Input schema that the LLM will see */\n inputs: ToolInputs;\n /** Output type label */\n outputType: string;\n /** Max execution time in ms (default 60 s) */\n timeout?: number;\n}\n\nexport class ProxyTool extends Tool {\n readonly name: string;\n readonly description: string;\n readonly inputs: ToolInputs;\n readonly outputType: string;\n\n private readonly toolPath: string;\n private readonly timeout: number;\n private bunPath: string | null = null;\n private harnessPath: string | null = null;\n\n constructor(config: ProxyToolConfig) {\n super();\n this.name = config.name;\n this.description = config.description;\n this.inputs = config.inputs;\n this.outputType = config.outputType;\n this.toolPath = config.toolPath;\n this.timeout = config.timeout ?? DEFAULT_TOOL_TIMEOUT_MS;\n }\n\n /**\n * Ensure Bun is available and locate the harness before first invocation.\n */\n async setup(): Promise<void> {\n this.bunPath = await ensureBunAvailable();\n this.harnessPath = resolveHarnessPath();\n this.isSetup = true;\n }\n\n /**\n * Spawn the harness in a Bun child process. The harness imports the tool,\n * calls execute(args), and writes the protocol lines. Any console.log from\n * the tool flows through stdout as plain lines.\n */\n async execute(args: Record<string, unknown>): Promise<unknown> {\n if (!this.bunPath || !this.harnessPath) {\n await this.setup();\n }\n\n const serializedArgs = JSON.stringify(args);\n\n return new Promise<unknown>((resolve, reject) => {\n // Harness signature: bun run toolHarness.ts <toolPath> <argsJson>\n const child = spawn(this.bunPath!, ['run', this.harnessPath!, this.toolPath, serializedArgs], {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: { ...process.env },\n });\n\n let result: unknown = undefined;\n let resultReceived = false;\n let errorMessage: string | null = null;\n const logBuffer: string[] = [];\n let stderr = '';\n\n // --- stdout: stream lines, parse protocol ---\n let partialLine = '';\n child.stdout.on('data', (chunk: Buffer) => {\n partialLine += chunk.toString('utf8');\n const lines = partialLine.split('\\n');\n partialLine = lines.pop()!;\n\n for (const line of lines) {\n this.processLine(line, {\n onOutput: (msg) => logBuffer.push(msg),\n onResult: (value) => {\n result = value;\n resultReceived = true;\n },\n onError: (msg) => {\n errorMessage = msg;\n },\n });\n }\n });\n\n // --- stderr: accumulate for diagnostics ---\n child.stderr.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n\n // --- timeout watchdog ---\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n reject(new Error(\n `Custom tool \"${this.name}\" timed out after ${this.timeout}ms. ` +\n 'The process was terminated. Check the tool for infinite loops or slow operations.'\n ));\n }, this.timeout);\n timer.unref();\n\n // --- process exit ---\n child.on('close', (code) => {\n clearTimeout(timer);\n\n // Flush any remaining partial line\n if (partialLine.trim()) {\n this.processLine(partialLine, {\n onOutput: (msg) => logBuffer.push(msg),\n onResult: (value) => { result = value; resultReceived = true; },\n onError: (msg) => { errorMessage = msg; },\n });\n }\n\n if (errorMessage) {\n reject(new Error(\n `Custom tool \"${this.name}\" reported an error: ${errorMessage}`\n ));\n return;\n }\n\n if (resultReceived) {\n // Prepend captured log lines so agents have context about what the tool did\n if (logBuffer.length > 0) {\n const logPrefix = `[Tool output logs]\\n${logBuffer.join('\\n')}\\n\\n[Tool result]\\n`;\n if (typeof result === 'string') {\n resolve(logPrefix + result);\n } else {\n resolve({ logs: logBuffer.join('\\n'), result });\n }\n } else {\n resolve(result);\n }\n return;\n }\n\n // No [TOOL_RESULT] received\n const combined = (logBuffer.join('\\n') + '\\n' + stderr).trim();\n if (code !== 0) {\n reject(new Error(\n `Custom tool \"${this.name}\" exited with code ${code}. ` +\n `Output: ${combined || '(none)'}`\n ));\n } else {\n resolve(combined || `Tool \"${this.name}\" produced no output.`);\n }\n });\n\n child.on('error', (err) => {\n clearTimeout(timer);\n reject(new Error(\n `Failed to spawn custom tool \"${this.name}\": ${err.message}`\n ));\n });\n });\n }\n\n // --- line parser: protocol is spoken by harness, interpreted here ---\n private processLine(\n line: string,\n handlers: {\n onOutput: (msg: string) => void;\n onResult: (value: unknown) => void;\n onError: (msg: string) => void;\n }\n ): void {\n const trimmed = line.trimEnd();\n if (!trimmed) return;\n\n if (trimmed.startsWith(TOOL_RESULT_PREFIX)) {\n const json = trimmed.slice(TOOL_RESULT_PREFIX.length).trim();\n try {\n handlers.onResult(JSON.parse(json));\n } catch {\n handlers.onResult(json);\n }\n } else if (trimmed.startsWith(TOOL_ERROR_PREFIX)) {\n handlers.onError(trimmed.slice(TOOL_ERROR_PREFIX.length).trim());\n } else {\n // Plain stdout from the tool (console.log inside execute) = streaming output\n handlers.onOutput(trimmed);\n }\n }\n}\n","/**\n * Utility to locate or auto-install Bun for running custom tool processes.\n *\n * Strategy:\n * 1. Check if `bun` is already on PATH (shell-out `which bun` / `where bun`).\n * 2. Check the well-known local install path (~/.bun/bin/bun).\n * 3. If neither found, run the official one-liner installer\n * (https://bun.sh) and return the path to the newly installed binary.\n *\n * The installer runs exactly once per session; subsequent calls return the\n * cached path immediately.\n */\n\nimport { execSync, execFileSync } from 'child_process';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as os from 'os';\n\nlet cachedBunPath: string | null = null;\n\n/**\n * Resolve or install Bun. Returns the absolute path to the bun binary.\n * Throws if installation fails.\n */\nexport async function ensureBunAvailable(): Promise<string> {\n if (cachedBunPath) return cachedBunPath;\n\n // 1. Try PATH\n const fromPath = whichBun();\n if (fromPath) {\n cachedBunPath = fromPath;\n return fromPath;\n }\n\n // 2. Try well-known local path\n const localPath = path.join(os.homedir(), '.bun', 'bin', 'bun');\n if (fs.existsSync(localPath)) {\n cachedBunPath = localPath;\n return localPath;\n }\n\n // 3. Auto-install via official installer\n console.log(\n '\\n[smol-js] Bun is required to run custom tools but was not found. ' +\n 'Installing Bun automatically...\\n'\n );\n\n try {\n // The official install script: https://bun.sh\n execSync('curl --proto =https --tlsv1.2 -sSf https://bun.sh | bash', {\n stdio: 'inherit',\n shell: '/bin/bash',\n env: { ...process.env, HOME: os.homedir() },\n });\n } catch (err) {\n throw new Error(\n '[smol-js] Failed to auto-install Bun. Please install it manually: https://bun.sh\\n' +\n `Details: ${(err as Error).message}`\n );\n }\n\n // Verify install succeeded\n const afterInstall = whichBun() || (fs.existsSync(localPath) ? localPath : null);\n if (!afterInstall) {\n throw new Error(\n '[smol-js] Bun installation appeared to succeed but the binary was not found. ' +\n 'Please install manually: https://bun.sh'\n );\n }\n\n console.log(`[smol-js] Bun installed successfully at: ${afterInstall}\\n`);\n cachedBunPath = afterInstall;\n return afterInstall;\n}\n\nfunction whichBun(): string | null {\n try {\n const cmd = process.platform === 'win32' ? 'where bun' : 'which bun';\n const result = execSync(cmd, { encoding: 'utf8', stdio: 'pipe' }).trim();\n // `which` may return multiple lines on some systems; take the first\n const first = result.split('\\n')[0]?.trim();\n if (first && fs.existsSync(first)) return first;\n return null;\n } catch {\n return null;\n }\n}\n","/**\n * CustomToolScanner — discovers standalone tool files in a directory and\n * extracts their metadata so that ProxyTool instances can be registered\n * with the YAML loader.\n *\n * Convention over Configuration:\n * • Each file in the custom-tools folder must export a default metadata\n * object conforming to CustomToolMetadata (see standalone tool wrapper docs).\n * • The exported class name (or `name` field in metadata) MUST match the\n * file's basename (without extension). E.g. `WeatherLookup.ts` → name: \"WeatherLookup\".\n * • The tool is referenced in YAML by that same name.\n *\n * Metadata Extraction (zero-import approach):\n * We read the file as text and use a lightweight regex to pull the\n * `TOOL_METADATA` export block. This keeps the scanner decoupled from\n * Bun/ESM and lets it run purely in the Node.js main process.\n * The metadata block must be a single JSON object assigned to\n * `export const TOOL_METADATA = { ... };`\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { ToolInputs } from '../types.js';\nimport { ProxyTool, ProxyToolConfig } from './ProxyTool.js';\n\nexport interface CustomToolMetadata {\n /** Must match the file's basename (sans extension) */\n name: string;\n /** Human-readable description shown to the LLM */\n description: string;\n /** Input schema identical to Tool.inputs */\n inputs: ToolInputs;\n /** Output type label */\n outputType: string;\n /** Optional execution timeout in ms */\n timeout?: number;\n}\n\nexport interface DiscoveredTool {\n /** Absolute path to the tool file */\n filePath: string;\n /** Parsed metadata */\n metadata: CustomToolMetadata;\n}\n\n// Regex: captures everything between the braces of `export const TOOL_METADATA = { ... };`\n// This is intentionally lenient — it matches the first `TOOL_METADATA = ` and grabs until the\n// matching closing brace followed by an optional semicolon.\nconst METADATA_REGEX =\n /export\\s+const\\s+TOOL_METADATA\\s*=\\s*(\\{[\\s\\S]*?\\});\\s*$/m;\n\n/**\n * Scan a directory for custom tool files and extract their metadata.\n *\n * @param folderPath Absolute path to the custom-tools directory.\n * @returns Array of discovered tools with parsed metadata.\n * @throws If any file fails metadata extraction.\n */\nexport function scanCustomTools(folderPath: string): DiscoveredTool[] {\n if (!fs.existsSync(folderPath)) {\n throw new Error(\n `Custom tools folder not found: ${folderPath}. ` +\n 'Create the directory or check your --custom-tools-folder path.'\n );\n }\n\n const entries = fs.readdirSync(folderPath, { withFileTypes: true });\n const discovered: DiscoveredTool[] = [];\n\n for (const entry of entries) {\n if (entry.isDirectory()) continue;\n\n const ext = path.extname(entry.name).toLowerCase();\n if (ext !== '.ts' && ext !== '.js') continue;\n\n const filePath = path.resolve(folderPath, entry.name);\n const baseName = path.basename(entry.name, ext);\n\n let metadata: CustomToolMetadata;\n try {\n metadata = extractMetadata(filePath);\n } catch (err) {\n throw new Error(\n `Failed to extract TOOL_METADATA from \"${entry.name}\": ${(err as Error).message}\\n` +\n 'Ensure the file exports `export const TOOL_METADATA = { name, description, inputs, outputType };`'\n );\n }\n\n // Enforce: metadata.name must match the file's base name\n if (metadata.name !== baseName) {\n throw new Error(\n `Tool metadata name mismatch in \"${entry.name}\": ` +\n `file is \"${baseName}\" but TOOL_METADATA.name is \"${metadata.name}\". ` +\n 'They must match (Convention over Configuration).'\n );\n }\n\n discovered.push({ filePath, metadata });\n }\n\n return discovered;\n}\n\n/**\n * Read a tool file and extract the TOOL_METADATA export via regex.\n */\nfunction extractMetadata(filePath: string): CustomToolMetadata {\n const source = fs.readFileSync(filePath, 'utf8');\n const match = source.match(METADATA_REGEX);\n\n if (!match) {\n throw new Error(\n 'No `export const TOOL_METADATA = { ... };` block found. ' +\n 'Add the metadata export at the bottom of your tool file.'\n );\n }\n\n let parsed: CustomToolMetadata;\n try {\n // Use Function constructor to safely evaluate the object literal.\n // This handles JS object syntax (unquoted keys, trailing commas) that\n // strict JSON.parse would reject.\n parsed = new Function(`\"use strict\"; return (${match[1]});`)() as CustomToolMetadata;\n } catch (err) {\n throw new Error(\n `Could not parse TOOL_METADATA object: ${(err as Error).message}. ` +\n 'Ensure it is a valid JavaScript object literal.'\n );\n }\n\n // Validate required fields\n if (!parsed.name || typeof parsed.name !== 'string') {\n throw new Error('TOOL_METADATA.name must be a non-empty string.');\n }\n if (!parsed.description || typeof parsed.description !== 'string') {\n throw new Error('TOOL_METADATA.description must be a non-empty string.');\n }\n if (!parsed.inputs || typeof parsed.inputs !== 'object') {\n throw new Error('TOOL_METADATA.inputs must be an object mapping parameter names to their schemas.');\n }\n if (!parsed.outputType || typeof parsed.outputType !== 'string') {\n throw new Error('TOOL_METADATA.outputType must be a non-empty string.');\n }\n\n return parsed;\n}\n\n/**\n * Scan a folder and return a Map<toolName, ProxyTool> ready for registration\n * with YAMLLoader.\n */\nexport function loadCustomTools(folderPath: string): Map<string, ProxyTool> {\n const discovered = scanCustomTools(folderPath);\n const tools = new Map<string, ProxyTool>();\n\n for (const { filePath, metadata } of discovered) {\n const config: ProxyToolConfig = {\n toolPath: filePath,\n name: metadata.name,\n description: metadata.description,\n inputs: metadata.inputs,\n outputType: metadata.outputType,\n timeout: metadata.timeout,\n };\n\n tools.set(metadata.name, new ProxyTool(config));\n }\n\n return tools;\n}\n","/**\n * YAMLLoader - Loads and parses YAML workflow definitions into runnable agents\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport YAML from 'yaml';\nimport type { YAMLWorkflowDefinition, YAMLAgentDefinition, YAMLModelDefinition } from '../types.js';\nimport { Agent } from '../agents/Agent.js';\nimport { CodeAgent } from '../agents/CodeAgent.js';\nimport { ToolUseAgent } from '../agents/ToolUseAgent.js';\nimport { Tool } from '../tools/Tool.js';\nimport { AgentTool } from '../tools/AgentTool.js';\nimport { OpenAIModel } from '../models/OpenAIModel.js';\nimport { ReadFileTool } from '../tools/ReadFileTool.js';\nimport { WriteFileTool } from '../tools/WriteFileTool.js';\nimport { CurlTool } from '../tools/CurlTool.js';\nimport { ExaSearchTool } from '../tools/ExaSearchTool.js';\nimport { ExaGetContentsTool } from '../tools/ExaGetContentsTool.js';\nimport { ExaResearchTool } from '../tools/ExaResearchTool.js';\nimport { FinalAnswerTool } from '../tools/defaultTools.js';\n\n// Registry of built-in tool types\nconst TOOL_REGISTRY: Record<string, new (config?: Record<string, unknown>) => Tool> = {\n read_file: ReadFileTool as unknown as new (config?: Record<string, unknown>) => Tool,\n write_file: WriteFileTool as unknown as new (config?: Record<string, unknown>) => Tool,\n curl: CurlTool as unknown as new (config?: Record<string, unknown>) => Tool,\n exa_search: ExaSearchTool as unknown as new (config?: Record<string, unknown>) => Tool,\n exa_get_contents: ExaGetContentsTool as unknown as new (config?: Record<string, unknown>) => Tool,\n exa_research: ExaResearchTool as unknown as new (config?: Record<string, unknown>) => Tool,\n final_answer: FinalAnswerTool as unknown as new (config?: Record<string, unknown>) => Tool,\n};\n\nexport interface LoadedWorkflow {\n name: string;\n description?: string;\n entrypointAgent: Agent;\n agents: Map<string, Agent>;\n tools: Map<string, Tool>;\n}\n\nexport class YAMLLoader {\n private customTools: Map<string, new (config?: Record<string, unknown>) => Tool> = new Map();\n private toolInstances: Map<string, Tool> = new Map();\n\n /**\n * Register a custom tool type (class) for use in YAML definitions.\n */\n registerToolType(typeName: string, toolClass: new (config?: Record<string, unknown>) => Tool): void {\n this.customTools.set(typeName, toolClass);\n }\n\n /**\n * Register a pre-built tool instance for use in YAML definitions.\n * Used by the custom tool system to register ProxyTool instances\n * that are created by the scanner rather than by class instantiation.\n */\n registerToolInstance(typeName: string, tool: Tool): void {\n this.toolInstances.set(typeName, tool);\n }\n\n /**\n * Load a workflow from a YAML file path.\n */\n loadFromFile(filePath: string): LoadedWorkflow {\n const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);\n\n if (!fs.existsSync(absolutePath)) {\n throw new Error(`Workflow file not found: ${absolutePath}`);\n }\n\n const content = fs.readFileSync(absolutePath, 'utf-8');\n return this.loadFromString(content);\n }\n\n /**\n * Load a workflow from a YAML string.\n */\n loadFromString(yamlContent: string): LoadedWorkflow {\n const definition = YAML.parse(yamlContent) as YAMLWorkflowDefinition;\n return this.buildWorkflow(definition);\n }\n\n /**\n * Build a runnable workflow from a parsed definition.\n */\n private buildWorkflow(definition: YAMLWorkflowDefinition): LoadedWorkflow {\n if (!definition.name) {\n throw new Error('Workflow must have a name');\n }\n if (!definition.entrypoint) {\n throw new Error('Workflow must have an entrypoint agent');\n }\n if (!definition.agents) {\n throw new Error('Workflow must define at least one agent');\n }\n\n // Build tools\n const tools = new Map<string, Tool>();\n if (definition.tools) {\n for (const [name, toolDef] of Object.entries(definition.tools)) {\n const tool = this.buildTool(name, toolDef.type, toolDef.config);\n tools.set(name, tool);\n }\n }\n\n // Build agents (handling dependencies between agents)\n const agents = new Map<string, Agent>();\n const agentDefs = definition.agents;\n\n // Topological sort: build agents that don't depend on other agents first\n const resolved = new Set<string>();\n const maxIterations = Object.keys(agentDefs).length * 2;\n let iterations = 0;\n\n while (resolved.size < Object.keys(agentDefs).length && iterations < maxIterations) {\n iterations++;\n for (const [agentName, agentDef] of Object.entries(agentDefs)) {\n if (resolved.has(agentName)) continue;\n\n // Check if all agent dependencies are resolved\n const agentDeps = agentDef.agents ?? [];\n const allDepsResolved = agentDeps.every(dep => resolved.has(dep));\n\n if (allDepsResolved) {\n const agent = this.buildAgent(\n agentName,\n agentDef,\n definition.model,\n tools,\n agents,\n definition.globalMaxContextLength\n );\n agents.set(agentName, agent);\n resolved.add(agentName);\n }\n }\n }\n\n if (resolved.size < Object.keys(agentDefs).length) {\n const unresolved = Object.keys(agentDefs).filter(n => !resolved.has(n));\n throw new Error(`Circular or unresolvable agent dependencies: ${unresolved.join(', ')}`);\n }\n\n const entrypointAgent = agents.get(definition.entrypoint);\n if (!entrypointAgent) {\n throw new Error(`Entrypoint agent \"${definition.entrypoint}\" not found in agents`);\n }\n\n return {\n name: definition.name,\n description: definition.description,\n entrypointAgent,\n agents,\n tools,\n };\n }\n\n /**\n * Build a tool instance from a type name and config.\n */\n private buildTool(name: string, type: string, config?: Record<string, unknown>): Tool {\n // Check for pre-registered tool instances first (e.g. ProxyTool from custom tools scanner)\n const existingInstance = this.toolInstances.get(type);\n if (existingInstance) {\n if (name !== type && name !== existingInstance.name) {\n Object.defineProperty(existingInstance, 'name', { value: name, writable: false });\n }\n return existingInstance;\n }\n\n const ToolClass = TOOL_REGISTRY[type] ?? this.customTools.get(type);\n\n if (!ToolClass) {\n throw new Error(`Unknown tool type: ${type}. Available types: ${[...Object.keys(TOOL_REGISTRY), ...this.customTools.keys(), ...this.toolInstances.keys()].join(', ')}`);\n }\n\n const tool = new ToolClass(config);\n // Override name if different from type\n if (name !== type && name !== tool.name) {\n Object.defineProperty(tool, 'name', { value: name, writable: false });\n }\n return tool;\n }\n\n /**\n * Build an agent instance from a YAML definition.\n */\n private buildAgent(\n name: string,\n definition: YAMLAgentDefinition,\n globalModel?: YAMLModelDefinition,\n availableTools?: Map<string, Tool>,\n resolvedAgents?: Map<string, Agent>,\n globalMaxContextLength?: number\n ): Agent {\n // Build model\n const modelConfig = definition.model ?? globalModel;\n const model = new OpenAIModel({\n modelId: modelConfig?.modelId,\n apiKey: modelConfig?.apiKey,\n baseUrl: modelConfig?.baseUrl,\n maxTokens: definition.maxTokens ?? modelConfig?.maxTokens,\n temperature: definition.temperature ?? modelConfig?.temperature,\n timeout: modelConfig?.timeout,\n });\n\n // Collect tools\n const agentTools: Tool[] = [];\n\n // Add referenced tools\n if (definition.tools && availableTools) {\n for (const toolName of definition.tools) {\n const tool = availableTools.get(toolName);\n if (tool) {\n agentTools.push(tool);\n } else {\n // Try pre-registered instance (e.g. custom ProxyTool)\n const instance = this.toolInstances.get(toolName);\n if (instance) {\n agentTools.push(instance);\n } else {\n // Try to create from registry directly\n const ToolClass = TOOL_REGISTRY[toolName] ?? this.customTools.get(toolName);\n if (ToolClass) {\n agentTools.push(new ToolClass());\n } else {\n throw new Error(`Tool \"${toolName}\" not found for agent \"${name}\"`);\n }\n }\n }\n }\n }\n\n // Add sub-agents as tools\n if (definition.agents && resolvedAgents) {\n for (const subAgentName of definition.agents) {\n const subAgent = resolvedAgents.get(subAgentName);\n if (!subAgent) {\n throw new Error(`Sub-agent \"${subAgentName}\" not found for agent \"${name}\"`);\n }\n agentTools.push(new AgentTool({\n agent: subAgent,\n name: subAgentName,\n description: definition.description\n ? `Sub-agent: ${subAgentName}`\n : `Delegate tasks to the ${subAgentName} agent`,\n }));\n }\n }\n\n const maxContextLength = definition.maxContextLength ?? globalMaxContextLength;\n\n // Build the agent based on type\n if (definition.type === 'CodeAgent') {\n return new CodeAgent({\n model,\n tools: agentTools,\n maxSteps: definition.maxSteps,\n customInstructions: definition.customInstructions,\n persistent: definition.persistent,\n maxContextLength,\n memoryStrategy: definition.memoryStrategy,\n maxTokens: definition.maxTokens,\n temperature: definition.temperature,\n name,\n });\n } else {\n // Default: ToolUseAgent\n return new ToolUseAgent({\n model,\n tools: agentTools,\n maxSteps: definition.maxSteps,\n customInstructions: definition.customInstructions,\n persistent: definition.persistent,\n maxContextLength,\n memoryStrategy: definition.memoryStrategy,\n maxTokens: definition.maxTokens,\n temperature: definition.temperature,\n name,\n });\n }\n }\n}\n","/**\n * Orchestrator - Loads, runs, and provides real-time visibility into agent execution\n */\n\nimport chalk from 'chalk';\nimport type { OrchestratorEvent, RunResult, OutputFormat, TokenUsage } from '../types.js';\nimport { Agent } from '../agents/Agent.js';\nimport { YAMLLoader, LoadedWorkflow } from './YAMLLoader.js';\nimport { JSONOutputHandler } from '../output/JSONOutputHandler.js';\n\nexport interface OrchestratorConfig {\n /** Whether to display real-time output (default: true) */\n verbose?: boolean;\n /** Callback for orchestrator events */\n onEvent?: (event: OrchestratorEvent) => void;\n /** Output format: 'text' for chalk-formatted console, 'json' for NDJSON streaming */\n outputFormat?: OutputFormat;\n /** Unique run identifier (required for JSON output) */\n runId?: string;\n /** Working directory for agent file operations */\n cwd?: string;\n}\n\nexport class Orchestrator {\n private loader: YAMLLoader;\n private config: OrchestratorConfig;\n private activeAgents: Map<string, { agent: Agent; depth: number }> = new Map();\n private eventLog: OrchestratorEvent[] = [];\n private jsonOutput: JSONOutputHandler | null = null;\n private isJsonMode: boolean = false;\n\n constructor(config: OrchestratorConfig = {}) {\n this.loader = new YAMLLoader();\n this.isJsonMode = config.outputFormat === 'json';\n this.config = {\n verbose: config.verbose ?? true,\n onEvent: config.onEvent,\n outputFormat: config.outputFormat ?? 'text',\n runId: config.runId,\n cwd: config.cwd,\n };\n\n // Initialize JSON output handler if in JSON mode\n if (this.isJsonMode) {\n if (!config.runId) {\n throw new Error('runId is required for JSON output mode');\n }\n this.jsonOutput = new JSONOutputHandler({\n runId: config.runId,\n verbose: config.verbose ?? true,\n });\n }\n }\n\n /**\n * Load a workflow from a YAML file.\n */\n loadWorkflow(filePath: string): LoadedWorkflow {\n const workflow = this.loader.loadFromFile(filePath);\n this.displayWorkflowInfo(workflow, filePath);\n return workflow;\n }\n\n /**\n * Load a workflow from YAML string.\n */\n loadWorkflowFromString(yamlContent: string, sourcePath?: string): LoadedWorkflow {\n const workflow = this.loader.loadFromString(yamlContent);\n this.displayWorkflowInfo(workflow, sourcePath);\n return workflow;\n }\n\n /**\n * Run a loaded workflow with a task.\n */\n async runWorkflow(workflow: LoadedWorkflow, task: string, workflowPath?: string): Promise<RunResult> {\n this.displayRunStart(workflow.name, task, workflowPath);\n\n // Set up event tracking on the entrypoint agent\n this.instrumentAgent(workflow.entrypointAgent, workflow.entrypointAgent.getName(), 0);\n\n // Also instrument sub-agents\n for (const [name, agent] of workflow.agents) {\n if (agent !== workflow.entrypointAgent) {\n this.instrumentAgent(agent, name, 1);\n }\n }\n\n try {\n const result = await workflow.entrypointAgent.run(task);\n this.displayRunEnd(result, true);\n return result;\n } catch (error) {\n this.displayError(error as Error);\n // Emit run end with failure in JSON mode\n if (this.isJsonMode && this.jsonOutput) {\n this.jsonOutput.emitRunEnd(false, null, 0, 0);\n }\n throw error;\n }\n }\n\n /**\n * Run a standalone agent with a task.\n */\n async runAgent(agent: Agent, task: string): Promise<RunResult> {\n this.instrumentAgent(agent, agent.getName(), 0);\n const result = await agent.run(task);\n return result;\n }\n\n /**\n * Instrument an agent with orchestrator event tracking.\n */\n private instrumentAgent(agent: Agent, name: string, depth: number): void {\n this.activeAgents.set(name, { agent, depth });\n\n // Set up event callback to capture and emit events\n agent.setOnEvent((event) => {\n // Log the event to our event log\n const orchestratorEvent: OrchestratorEvent = {\n type: event.type as OrchestratorEvent['type'],\n agentName: name,\n depth,\n data: event.data,\n timestamp: Date.now(),\n };\n this.logEvent(orchestratorEvent);\n\n // In JSON mode, emit detailed events\n if (this.isJsonMode && this.jsonOutput) {\n this.emitAgentEventAsJSON(event, name, depth);\n }\n });\n }\n\n /**\n * Emit an agent event as JSON.\n */\n private emitAgentEventAsJSON(\n event: { type: string; data: unknown },\n agentName: string,\n depth: number\n ): void {\n if (!this.jsonOutput) return;\n\n const data = event.data as Record<string, unknown>;\n\n switch (event.type) {\n case 'agent_start':\n this.jsonOutput.emitAgentStart(\n agentName,\n depth,\n data.task as string,\n data.name ? 'ToolUseAgent' : 'CodeAgent', // Will be improved\n 20 // Default maxSteps, could be passed\n );\n break;\n\n case 'agent_step':\n this.jsonOutput.emitAgentStep(\n agentName,\n depth,\n data.step as number,\n data.maxSteps as number,\n 'start'\n );\n break;\n\n case 'agent_thinking':\n this.jsonOutput.emitAgentThinking(\n agentName,\n depth,\n data.step as number,\n data.content as string,\n false\n );\n break;\n\n case 'agent_tool_call':\n this.jsonOutput.emitToolCall(\n agentName,\n depth,\n data.step as number,\n data.toolCallId as string,\n data.toolName as string,\n data.arguments as Record<string, unknown>\n );\n break;\n\n case 'agent_tool_result':\n this.jsonOutput.emitToolResult(\n agentName,\n depth,\n data.step as number,\n data.toolCallId as string,\n data.toolName as string,\n data.result,\n data.error as string | undefined,\n data.duration as number\n );\n break;\n\n case 'agent_observation':\n this.jsonOutput.emitObservation(\n agentName,\n depth,\n data.step as number,\n data.observation as string,\n data.codeAction as string | undefined,\n data.logs as string | undefined\n );\n break;\n\n case 'agent_error':\n this.jsonOutput.emitError(\n data.error as string,\n undefined,\n agentName,\n depth,\n data.step as number\n );\n break;\n\n case 'agent_end':\n this.jsonOutput.emitAgentEnd(\n agentName,\n depth,\n data.output,\n 0, // totalSteps - would need to track\n data.tokenUsage as TokenUsage,\n data.duration as number,\n true\n );\n break;\n }\n }\n\n /**\n * Display workflow info at startup.\n */\n private displayWorkflowInfo(workflow: LoadedWorkflow, _sourcePath?: string): void {\n const agents = Array.from(workflow.agents.keys());\n const tools = Array.from(workflow.tools.keys());\n const entrypoint = workflow.entrypointAgent.getName();\n\n if (this.isJsonMode && this.jsonOutput) {\n this.jsonOutput.emitWorkflowLoaded(\n workflow.name,\n workflow.description,\n agents,\n tools,\n entrypoint\n );\n return;\n }\n\n if (!this.config.verbose) return;\n\n const line = '═'.repeat(70);\n console.log(chalk.cyan(line));\n console.log(chalk.cyan.bold(` Workflow: ${workflow.name}`));\n if (workflow.description) {\n console.log(chalk.cyan(` ${workflow.description}`));\n }\n console.log(chalk.cyan(` Agents: ${agents.join(', ')}`));\n console.log(chalk.cyan(` Tools: ${tools.join(', ') || '(none defined at workflow level)'}`));\n console.log(chalk.cyan(` Entrypoint: ${entrypoint}`));\n console.log(chalk.cyan(line));\n console.log();\n }\n\n /**\n * Display run start info.\n */\n private displayRunStart(workflowName: string, task: string, workflowPath?: string): void {\n if (this.isJsonMode && this.jsonOutput) {\n this.jsonOutput.emitRunStart(workflowPath || workflowName, task, this.config.cwd);\n return;\n }\n\n if (!this.config.verbose) return;\n console.log(chalk.green.bold(`\\n▶ Running workflow \"${workflowName}\"`));\n console.log(chalk.green(` Task: ${task}`));\n console.log(chalk.gray('─'.repeat(70)));\n }\n\n /**\n * Display run completion info.\n */\n private displayRunEnd(result: RunResult, success: boolean = true): void {\n if (this.isJsonMode && this.jsonOutput) {\n this.jsonOutput.emitRunEnd(\n success,\n result.output,\n result.tokenUsage.totalTokens,\n result.steps.length\n );\n return;\n }\n\n if (!this.config.verbose) return;\n console.log(chalk.gray('\\n' + '─'.repeat(70)));\n console.log(chalk.green.bold(`\\n✅ Workflow complete`));\n console.log(chalk.green(` Duration: ${(result.duration / 1000).toFixed(2)}s`));\n console.log(chalk.green(` Tokens: ${result.tokenUsage.totalTokens}`));\n console.log(chalk.green(` Steps: ${result.steps.length}`));\n\n const outputStr = typeof result.output === 'string'\n ? result.output\n : JSON.stringify(result.output, null, 2);\n console.log(chalk.magenta.bold('\\n Final Output:'));\n // Indent output\n const indentedOutput = outputStr.split('\\n').map(line => ` ${line}`).join('\\n');\n console.log(chalk.magenta(indentedOutput));\n console.log();\n }\n\n /**\n * Display an error.\n */\n private displayError(error: Error): void {\n if (this.isJsonMode && this.jsonOutput) {\n this.jsonOutput.emitError(error.message, error.stack);\n return;\n }\n\n if (!this.config.verbose) return;\n console.error(chalk.red.bold(`\\n❌ Workflow failed: ${error.message}`));\n if (error.stack) {\n console.error(chalk.red.dim(error.stack));\n }\n }\n\n /**\n * Log an orchestration event.\n */\n logEvent(event: OrchestratorEvent): void {\n this.eventLog.push(event);\n if (this.config.onEvent) {\n this.config.onEvent(event);\n }\n }\n\n /**\n * Get the event log.\n */\n getEventLog(): OrchestratorEvent[] {\n return [...this.eventLog];\n }\n\n /**\n * Get the YAML loader for registering custom tools.\n */\n getLoader(): YAMLLoader {\n return this.loader;\n }\n\n /**\n * Get the JSON output handler (if in JSON mode).\n */\n getJSONOutputHandler(): JSONOutputHandler | null {\n return this.jsonOutput;\n }\n\n /**\n * Check if in JSON output mode.\n */\n isJSONOutputMode(): boolean {\n return this.isJsonMode;\n }\n\n /**\n * Get the run ID.\n */\n getRunId(): string | undefined {\n return this.config.runId;\n }\n}\n","/**\n * JSONOutputHandler - Emits structured NDJSON events for machine-readable CLI output.\n */\n\nimport type { TokenUsage } from '../types.js';\n\nexport interface JSONOutputConfig {\n runId: string;\n verbose?: boolean;\n}\n\nexport class JSONOutputHandler {\n private readonly runId: string;\n private readonly startTime: number;\n\n constructor(config: JSONOutputConfig) {\n this.runId = config.runId;\n this.startTime = Date.now();\n }\n\n private emit(type: string, data: unknown, extra: Record<string, unknown> = {}): void {\n console.log(JSON.stringify({\n runId: this.runId,\n timestamp: Date.now(),\n type,\n ...extra,\n data,\n }));\n }\n\n emitRunStart(workflowPath: string, task: string, cwd?: string): void {\n this.emit('run_start', { workflowPath, task, cwd });\n }\n\n emitWorkflowLoaded(name: string, description: string | undefined, agents: string[], tools: string[], entrypoint: string): void {\n this.emit('workflow_loaded', { name, description, agents, tools, entrypoint });\n }\n\n emitRunEnd(success: boolean, output: unknown, totalTokens: number, totalSteps: number): void {\n this.emit('run_end', {\n success,\n output,\n totalDuration: Date.now() - this.startTime,\n totalTokens,\n totalSteps,\n });\n }\n\n emitAgentStart(agentName: string, depth: number, task: string, agentType: string, maxSteps: number): void {\n this.emit('agent_start', { task, agentType, maxSteps }, { agentName, depth });\n }\n\n emitAgentEnd(agentName: string, depth: number, output: unknown, totalSteps: number, tokenUsage: TokenUsage | undefined, duration: number, success: boolean): void {\n this.emit('agent_end', { output, totalSteps, tokenUsage, duration, success }, { agentName, depth });\n }\n\n emitAgentStep(agentName: string, depth: number, stepNumber: number, maxSteps: number, phase: string): void {\n this.emit('agent_step', { stepNumber, maxSteps, phase }, { agentName, depth });\n }\n\n emitAgentThinking(agentName: string, depth: number, stepNumber: number, content: string, isPartial: boolean): void {\n this.emit('agent_thinking', { stepNumber, content, isPartial }, { agentName, depth });\n }\n\n emitToolCall(agentName: string, depth: number, stepNumber: number, toolCallId: string, toolName: string, args: Record<string, unknown>): void {\n this.emit('agent_tool_call', { stepNumber, toolCallId, toolName, arguments: args }, { agentName, depth });\n }\n\n emitToolResult(agentName: string, depth: number, stepNumber: number, toolCallId: string, toolName: string, result: unknown, error: string | undefined, duration: number): void {\n this.emit('agent_tool_result', { stepNumber, toolCallId, toolName, result, error, duration }, { agentName, depth });\n }\n\n emitObservation(agentName: string, depth: number, stepNumber: number, observation: string, codeAction: string | undefined, logs: string | undefined): void {\n this.emit('agent_observation', { stepNumber, observation, codeAction, logs }, { agentName, depth });\n }\n\n emitError(message: string, stack?: string, agentName?: string, depth?: number, stepNumber?: number): void {\n this.emit('error', { message, stack, stepNumber }, {\n ...(agentName ? { agentName } : {}),\n ...(depth !== undefined ? { depth } : {}),\n });\n }\n}\n"],"mappings":";AA4HO,IAAK,WAAL,kBAAKA,cAAL;AACL,EAAAA,oBAAA,SAAM,MAAN;AACA,EAAAA,oBAAA,WAAQ,KAAR;AACA,EAAAA,oBAAA,UAAO,KAAP;AACA,EAAAA,oBAAA,WAAQ,KAAR;AAJU,SAAAA;AAAA,GAAA;;;ACrGZ,SAAS,eAAe,MAAsB;AAC5C,SAAO,KAAK,KAAK,KAAK,SAAS,CAAC;AAClC;AAEA,SAAS,uBAAuB,UAAiC;AAC/D,MAAI,QAAQ;AACZ,aAAW,OAAO,UAAU;AAC1B,aAAS,eAAe,IAAI,WAAW,EAAE;AACzC,QAAI,IAAI,WAAW;AACjB,eAAS,eAAe,KAAK,UAAU,IAAI,SAAS,CAAC;AAAA,IACvD;AACA,aAAS;AAAA,EACX;AACA,SAAO;AACT;AAEO,IAAM,cAAN,MAAkB;AAAA;AAAA,EAEvB;AAAA;AAAA,EAGA,QAAqD,CAAC;AAAA,EAE9C;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,cAAsB,QAAuB;AACvD,SAAK,eAAe;AAAA,MAClB,MAAM;AAAA,MACN,SAAS;AAAA,MACT,WAAW,K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AAO,SAAS;AACvB,WAAK,OAAO,QAAQ,KAAK;AAAA,IAC3B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,cAAmC;AACjC,WAAO,CAAC,GAAG,KAAK,QAAQ;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA,EAKA,YAAwB;AACtB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,uBAAiD;AAC/C,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,mBAA4B;AAC1B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,WAA+B;AAC7B,WAAO,KAAK,OAAO;AAAA,EACrB;AACF;","names":["LogLevel","resolve","fs","path","os","resolve","fs","path","fs","path","resolve","path","path","fs","os","resolve","fs","path","fs","path","chalk","chalk"]}
|