@samrahimi/smol-js 0.2.0 → 0.3.0
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/README.md +213 -99
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
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/models/Model.ts","../src/models/OpenAIModel.ts","../src/tools/AgentTool.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\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}\n\n// Tool inputs schema\nexport interface ToolInputs {\n [key: string]: ToolInput;\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// 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}\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 observation?: string;\n actionOutput?: ActionOutput;\n tokenUsage?: TokenUsage;\n error?: Error;\n isFinalAnswer?: boolean;\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}\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}\n","/**\n * AgentMemory - Tracks agent execution history\n *\n * Stores all steps taken by the agent and converts them to messages\n * that can be sent to the LLM for context.\n */\n\nimport type {\n MemoryStep,\n SystemPromptStep,\n TaskStep,\n ActionStep,\n FinalAnswerStep,\n ChatMessage,\n TokenUsage,\n} from '../types.js';\n\nexport class AgentMemory {\n /**\n * System prompt step (always first)\n */\n systemPrompt: SystemPromptStep;\n\n /**\n * All execution steps\n */\n steps: (TaskStep | ActionStep | FinalAnswerStep)[] = [];\n\n constructor(systemPrompt: string) {\n this.systemPrompt = {\n type: 'system',\n content: systemPrompt,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Reset memory, keeping only the system prompt.\n */\n reset(): void {\n this.steps = [];\n }\n\n /**\n * Add a task step.\n */\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 /**\n * Create a new action step.\n */\n createActionStep(stepNumber: number): ActionStep {\n const step: ActionStep = {\n type: 'action',\n stepNumber,\n timing: {\n startTime: Date.now(),\n },\n modelInputMessages: [],\n timestamp: Date.now(),\n };\n this.steps.push(step);\n return step;\n }\n\n /**\n * Add a final answer step.\n */\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 /**\n * Get the last step.\n */\n getLastStep(): MemoryStep | undefined {\n return this.steps[this.steps.length - 1];\n }\n\n /**\n * Get all action steps.\n */\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 */\n toMessages(): ChatMessage[] {\n const messages: ChatMessage[] = [];\n\n // Add 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 // Add assistant's response (reasoning + code)\n if (step.modelOutputMessage) {\n messages.push({\n role: 'assistant',\n content: step.modelOutputMessage.content,\n });\n }\n\n // Add observation as user message\n if (step.observation) {\n messages.push({\n role: 'user',\n content: step.observation,\n });\n }\n\n // Add error as user message\n if (step.error) {\n messages.push({\n role: 'user',\n content: `Error: ${step.error.message}`,\n });\n }\n break;\n\n case 'final':\n // Final answer doesn't need to be in messages\n break;\n }\n }\n\n return messages;\n }\n\n /**\n * Get total token usage across all steps.\n */\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 /**\n * Get a summary of the memory for logging.\n */\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 /**\n * Serialize memory to JSON.\n */\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');\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} 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\nexport interface AgentConfig {\n /**\n * The LLM model to use for generation\n */\n model: Model;\n\n /**\n * Tools available to the agent\n */\n tools?: Tool[];\n\n /**\n * Maximum number of steps before stopping\n * @default 20\n */\n maxSteps?: number;\n\n /**\n * Delay in milliseconds before executing code (for user interruption)\n * @default 5000\n */\n codeExecutionDelay?: number;\n\n /**\n * Custom system prompt (will be merged with generated prompt)\n */\n customInstructions?: string;\n\n /**\n * Log level for output\n * @default LogLevel.INFO\n */\n verboseLevel?: LogLevel;\n\n /**\n * Whether to stream model outputs\n * @default true\n */\n streamOutputs?: boolean;\n}\n\nexport abstract class Agent {\n /**\n * The LLM model for generation\n */\n protected model: Model;\n\n /**\n * Available tools mapped by name\n */\n protected tools: Map<string, Tool> = new Map();\n\n /**\n * Agent memory tracking all steps\n */\n protected memory!: AgentMemory;\n\n /**\n * Logger for formatted output\n */\n protected logger: AgentLogger;\n\n /**\n * Configuration options\n */\n protected config: Required<Omit<AgentConfig, 'model' | 'tools'>>;\n\n /**\n * Current step number\n */\n protected currentStep: number = 0;\n\n /**\n * Whether the agent is currently running\n */\n protected isRunning: boolean = false;\n\n constructor(config: AgentConfig) {\n this.model = config.model;\n this.logger = new AgentLogger(config.verboseLevel ?? LogLevelEnum.INFO);\n\n // Set default config values\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 };\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 * @param memoryStep - The memory step to populate with execution results\n * @returns The action output from this step\n */\n protected abstract executeStep(memoryStep: ActionStep): Promise<ActionOutput>;\n\n /**\n * Run the agent on a task.\n *\n * @param task - The task description\n * @param reset - Whether to reset memory before running\n * @returns The final result\n */\n async run(task: string, reset: boolean = true): Promise<RunResult> {\n const startTime = Date.now();\n\n // Reset if requested or this is a new run\n if (reset || !this.memory) {\n const systemPrompt = this.initializeSystemPrompt();\n this.memory = new AgentMemory(systemPrompt);\n this.currentStep = 0;\n }\n\n // Add task to memory\n this.memory.addTask(task);\n\n this.isRunning = true;\n this.logger.header(`🚀 Starting Agent: ${task.slice(0, 50)}${task.length > 50 ? '...' : ''}`);\n\n let finalOutput: unknown = null;\n let isFinalAnswer = false;\n\n try {\n // Main agent loop\n while (this.currentStep < this.config.maxSteps && this.isRunning) {\n this.currentStep++;\n this.logger.stepProgress(this.currentStep, this.config.maxSteps);\n\n // Create memory step\n const memoryStep = this.memory.createActionStep(this.currentStep);\n\n try {\n // Execute the step\n const actionOutput = await this.executeStep(memoryStep);\n\n // Update memory step\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 // Store error in memory step\n memoryStep.error = error as Error;\n memoryStep.timing.endTime = Date.now();\n memoryStep.timing.duration = memoryStep.timing.endTime - memoryStep.timing.startTime;\n\n this.logger.error('Step execution failed', error as Error);\n\n // Error will be passed to LLM in next iteration for recovery\n }\n }\n\n // If we hit max steps without a final answer\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 // Calculate total duration and token usage\n const duration = Date.now() - startTime;\n const tokenUsage = this.memory.getTotalTokenUsage();\n\n // Add final answer to memory\n this.memory.addFinalAnswer(finalOutput);\n\n this.logger.info(`\\n⏱️ Total time: ${(duration / 1000).toFixed(2)}s`);\n this.logger.info(`📊 Total tokens: ${tokenUsage.totalTokens}`);\n\n const logPath = this.logger.getLogPath();\n if (logPath) {\n this.logger.info(`📁 Log file: ${logPath}`);\n }\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\n // Add prompt for final answer\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}\"\n\nSummarize what you accomplished and provide a final answer. Call final_answer() with your response.`,\n });\n\n const response = await this.model.generate(messages);\n\n // Extract final answer from response\n // This is a simplified extraction - subclasses may override\n return response.content;\n }\n\n /**\n * Stop the agent.\n */\n stop(): void {\n this.isRunning = false;\n this.logger.info('Agent stopped by user');\n }\n\n /**\n * Get the current memory.\n */\n getMemory(): AgentMemory {\n return this.memory;\n }\n\n /**\n * Get registered tools.\n */\n getTools(): Map<string, Tool> {\n return this.tools;\n }\n\n /**\n * Add a tool to the agent.\n */\n addTool(tool: Tool): void {\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Remove a tool from the agent.\n */\n removeTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /**\n * Sleep for a specified duration.\n */\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 } 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 // Warn about unknown arguments\n if (providedKeys.size > 0) {\n console.warn(`Unknown arguments provided to ${this.name}: ${[...providedKeys].join(', ')}`);\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 * 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. Don't try to do everything at once.\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\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 });\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 });\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 * 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';\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\n */\n maxTokens?: number;\n\n /**\n * Temperature for generation (0-2)\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\n// Default configuration uses OpenRouter with Claude Sonnet\nconst DEFAULT_CONFIG: Required<Pick<OpenAIModelConfig, 'modelId' | 'baseUrl' | 'maxTokens' | 'temperature' | 'timeout'>> = {\n modelId: 'anthropic/claude-sonnet-4.5',\n baseUrl: 'https://openrouter.ai/api/v1',\n maxTokens: 4096,\n temperature: 0.7,\n timeout: 120000,\n};\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 = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n this.modelId = this.config.modelId ?? DEFAULT_CONFIG.modelId;\n\n // Get API key from config or environment\n const apiKey = this.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: this.config.baseUrl,\n timeout: this.config.timeout,\n defaultHeaders: this.config.defaultHeaders,\n });\n }\n\n /**\n * Generate a response from the model.\n */\n async generate(messages: ChatMessage[], options: GenerateOptions = {}): Promise<ChatMessage> {\n const formattedMessages = this.formatMessages(messages);\n\n const response = await this.client.chat.completions.create({\n model: this.modelId,\n messages: formattedMessages as OpenAI.Chat.ChatCompletionMessageParam[],\n max_tokens: options.maxTokens ?? this.config.maxTokens,\n temperature: options.temperature ?? this.config.temperature,\n ...(options.stopSequences && { stop: options.stopSequences }),\n });\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,\n totalTokens: response.usage.total_tokens,\n }\n : undefined;\n\n return {\n role: 'assistant' as MessageRole,\n content: message.content ?? '',\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 stream = await this.client.chat.completions.create({\n model: this.modelId,\n messages: formattedMessages as OpenAI.Chat.ChatCompletionMessageParam[],\n max_tokens: options.maxTokens ?? this.config.maxTokens,\n temperature: options.temperature ?? this.config.temperature,\n ...(options.stopSequences && { stop: options.stopSequences }),\n stream: true,\n });\n\n let fullContent = '';\n\n for await (const chunk of stream) {\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.\n */\n protected formatMessages(messages: ChatMessage[]): OpenAI.Chat.ChatCompletionMessageParam[] {\n return messages.map((msg) => {\n // Handle tool responses\n if (msg.role === 'tool') {\n return {\n role: 'user' as const,\n content: msg.content ?? '',\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"],"mappings":";AAoGO,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;;;ACnFL,IAAM,cAAN,MAAkB;AAAA;AAAA;AAAA;AAAA,EAIvB;AAAA;AAAA;AAAA;AAAA,EAKA,QAAqD,CAAC;AAAA,EAEtD,YAAY,cAAsB;AAChC,SAAK,eAAe;AAAA,MA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ogLevel","resolve","fs","path","os","resolve"]}
|
|
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/models/Model.ts","../src/models/OpenAIModel.ts","../src/tools/AgentTool.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\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}\n\n// Tool inputs schema\nexport interface ToolInputs {\n [key: string]: ToolInput;\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// 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}\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 observation?: string;\n actionOutput?: ActionOutput;\n tokenUsage?: TokenUsage;\n error?: Error;\n isFinalAnswer?: boolean;\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}\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}\n","/**\n * AgentMemory - Tracks agent execution history\n *\n * Stores all steps taken by the agent and converts them to messages\n * that can be sent to the LLM for context.\n */\n\nimport type {\n MemoryStep,\n SystemPromptStep,\n TaskStep,\n ActionStep,\n FinalAnswerStep,\n ChatMessage,\n TokenUsage,\n} from '../types.js';\n\nexport class AgentMemory {\n /**\n * System prompt step (always first)\n */\n systemPrompt: SystemPromptStep;\n\n /**\n * All execution steps\n */\n steps: (TaskStep | ActionStep | FinalAnswerStep)[] = [];\n\n constructor(systemPrompt: string) {\n this.systemPrompt = {\n type: 'system',\n content: systemPrompt,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Reset memory, keeping only the system prompt.\n */\n reset(): void {\n this.steps = [];\n }\n\n /**\n * Add a task step.\n */\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 /**\n * Create a new action step.\n */\n createActionStep(stepNumber: number): ActionStep {\n const step: ActionStep = {\n type: 'action',\n stepNumber,\n timing: {\n startTime: Date.now(),\n },\n modelInputMessages: [],\n timestamp: Date.now(),\n };\n this.steps.push(step);\n return step;\n }\n\n /**\n * Add a final answer step.\n */\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 /**\n * Get the last step.\n */\n getLastStep(): MemoryStep | undefined {\n return this.steps[this.steps.length - 1];\n }\n\n /**\n * Get all action steps.\n */\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 */\n toMessages(): ChatMessage[] {\n const messages: ChatMessage[] = [];\n\n // Add 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 // Add assistant's response (reasoning + code)\n if (step.modelOutputMessage) {\n messages.push({\n role: 'assistant',\n content: step.modelOutputMessage.content,\n });\n }\n\n // Add observation as user message\n if (step.observation) {\n messages.push({\n role: 'user',\n content: step.observation,\n });\n }\n\n // Add error as user message\n if (step.error) {\n messages.push({\n role: 'user',\n content: `Error: ${step.error.message}`,\n });\n }\n break;\n\n case 'final':\n // Final answer doesn't need to be in messages\n break;\n }\n }\n\n return messages;\n }\n\n /**\n * Get total token usage across all steps.\n */\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 /**\n * Get a summary of the memory for logging.\n */\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 /**\n * Serialize memory to JSON.\n */\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} 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\nexport interface AgentConfig {\n /**\n * The LLM model to use for generation\n */\n model: Model;\n\n /**\n * Tools available to the agent\n */\n tools?: Tool[];\n\n /**\n * Maximum number of steps before stopping\n * @default 20\n */\n maxSteps?: number;\n\n /**\n * Delay in milliseconds before executing code (for user interruption)\n * @default 5000\n */\n codeExecutionDelay?: number;\n\n /**\n * Custom system prompt (will be merged with generated prompt)\n */\n customInstructions?: string;\n\n /**\n * Log level for output\n * @default LogLevel.INFO\n */\n verboseLevel?: LogLevel;\n\n /**\n * Whether to stream model outputs\n * @default true\n */\n streamOutputs?: boolean;\n}\n\nexport abstract class Agent {\n /**\n * The LLM model for generation\n */\n protected model: Model;\n\n /**\n * Available tools mapped by name\n */\n protected tools: Map<string, Tool> = new Map();\n\n /**\n * Agent memory tracking all steps\n */\n protected memory!: AgentMemory;\n\n /**\n * Logger for formatted output\n */\n protected logger: AgentLogger;\n\n /**\n * Configuration options\n */\n protected config: Required<Omit<AgentConfig, 'model' | 'tools'>>;\n\n /**\n * Current step number\n */\n protected currentStep: number = 0;\n\n /**\n * Whether the agent is currently running\n */\n protected isRunning: boolean = false;\n\n constructor(config: AgentConfig) {\n this.model = config.model;\n this.logger = new AgentLogger(config.verboseLevel ?? LogLevelEnum.INFO);\n\n // Set default config values\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 };\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 * @param memoryStep - The memory step to populate with execution results\n * @returns The action output from this step\n */\n protected abstract executeStep(memoryStep: ActionStep): Promise<ActionOutput>;\n\n /**\n * Run the agent on a task.\n *\n * @param task - The task description\n * @param reset - Whether to reset memory before running\n * @returns The final result\n */\n async run(task: string, reset: boolean = true): Promise<RunResult> {\n const startTime = Date.now();\n\n // Reset if requested or this is a new run\n if (reset || !this.memory) {\n const systemPrompt = this.initializeSystemPrompt();\n this.memory = new AgentMemory(systemPrompt);\n this.currentStep = 0;\n }\n\n // Add task to memory\n this.memory.addTask(task);\n\n this.isRunning = true;\n this.logger.header(`🚀 Starting Agent: ${task.slice(0, 50)}${task.length > 50 ? '...' : ''}`);\n\n let finalOutput: unknown = null;\n let isFinalAnswer = false;\n\n try {\n // Main agent loop\n while (this.currentStep < this.config.maxSteps && this.isRunning) {\n this.currentStep++;\n this.logger.stepProgress(this.currentStep, this.config.maxSteps);\n\n // Create memory step\n const memoryStep = this.memory.createActionStep(this.currentStep);\n\n try {\n // Execute the step\n const actionOutput = await this.executeStep(memoryStep);\n\n // Update memory step\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 // Store error in memory step\n memoryStep.error = error as Error;\n memoryStep.timing.endTime = Date.now();\n memoryStep.timing.duration = memoryStep.timing.endTime - memoryStep.timing.startTime;\n\n this.logger.error('Step execution failed', error as Error);\n\n // Error will be passed to LLM in next iteration for recovery\n }\n }\n\n // If we hit max steps without a final answer\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 // Calculate total duration and token usage\n const duration = Date.now() - startTime;\n const tokenUsage = this.memory.getTotalTokenUsage();\n\n // Add final answer to memory\n this.memory.addFinalAnswer(finalOutput);\n\n this.logger.info(`\\n⏱️ Total time: ${(duration / 1000).toFixed(2)}s`);\n this.logger.info(`📊 Total tokens: ${tokenUsage.totalTokens}`);\n\n const logPath = this.logger.getLogPath();\n if (logPath) {\n this.logger.info(`📁 Log file: ${logPath}`);\n }\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\n // Add prompt for final answer\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}\"\n\nSummarize what you accomplished and provide a final answer. Call final_answer() with your response.`,\n });\n\n const response = await this.model.generate(messages);\n\n // Extract final answer from response\n // This is a simplified extraction - subclasses may override\n return response.content;\n }\n\n /**\n * Stop the agent.\n */\n stop(): void {\n this.isRunning = false;\n this.logger.info('Agent stopped by user');\n }\n\n /**\n * Get the current memory.\n */\n getMemory(): AgentMemory {\n return this.memory;\n }\n\n /**\n * Get registered tools.\n */\n getTools(): Map<string, Tool> {\n return this.tools;\n }\n\n /**\n * Add a tool to the agent.\n */\n addTool(tool: Tool): void {\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Remove a tool from the agent.\n */\n removeTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /**\n * Sleep for a specified duration.\n */\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 } 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 // Warn about unknown arguments\n if (providedKeys.size > 0) {\n console.warn(`Unknown arguments provided to ${this.name}: ${[...providedKeys].join(', ')}`);\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 * 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 });\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 });\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 * 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';\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\n */\n maxTokens?: number;\n\n /**\n * Temperature for generation (0-2)\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\n// Default configuration uses OpenRouter with Claude Sonnet\nconst DEFAULT_CONFIG: Required<Pick<OpenAIModelConfig, 'modelId' | 'baseUrl' | 'maxTokens' | 'temperature' | 'timeout'>> = {\n modelId: 'anthropic/claude-sonnet-4.5',\n baseUrl: 'https://openrouter.ai/api/v1',\n maxTokens: 65000,\n temperature: 1,\n timeout: 120000,\n};\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 = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n this.modelId = this.config.modelId ?? DEFAULT_CONFIG.modelId;\n\n // Get API key from config or environment\n const apiKey = this.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: this.config.baseUrl,\n timeout: this.config.timeout,\n defaultHeaders: this.config.defaultHeaders,\n });\n }\n\n /**\n * Generate a response from the model.\n */\n async generate(messages: ChatMessage[], options: GenerateOptions = {}): Promise<ChatMessage> {\n const formattedMessages = this.formatMessages(messages);\n\n const response = await this.client.chat.completions.create({\n model: this.modelId,\n messages: formattedMessages as OpenAI.Chat.ChatCompletionMessageParam[],\n max_tokens: options.maxTokens ?? this.config.maxTokens,\n temperature: options.temperature ?? this.config.temperature,\n ...(options.stopSequences && { stop: options.stopSequences }),\n });\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,\n totalTokens: response.usage.total_tokens,\n }\n : undefined;\n\n return {\n role: 'assistant' as MessageRole,\n content: message.content ?? '',\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 stream = await this.client.chat.completions.create({\n model: this.modelId,\n messages: formattedMessages as OpenAI.Chat.ChatCompletionMessageParam[],\n max_tokens: options.maxTokens ?? this.config.maxTokens,\n temperature: options.temperature ?? this.config.temperature,\n ...(options.stopSequences && { stop: options.stopSequences }),\n stream: true,\n });\n\n let fullContent = '';\n\n for await (const chunk of stream) {\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.\n */\n protected formatMessages(messages: ChatMessage[]): OpenAI.Chat.ChatCompletionMessageParam[] {\n return messages.map((msg) => {\n // Handle tool responses\n if (msg.role === 'tool') {\n return {\n role: 'user' as const,\n content: msg.content ?? '',\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"],"mappings":";AAoGO,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;;;ACnFL,IAAM,cAAN,MAAkB;AAAA;AAAA;AAAA;AAAA,EAIvB;AAAA;AAAA;AAAA;AAAA,EAKA,QAAqD,CAAC;AAAA,EAEtD,YAAY,cAAsB;AAChC,SAAK,eAAe;A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