import OpenAI from 'openai/index.mjs'; /** * Core types for smol-js */ type MessageRole = 'system' | 'user' | 'assistant' | 'tool'; interface TokenUsage { inputTokens: number; outputTokens: number; totalTokens: number; } interface Timing { startTime: number; endTime?: number; duration?: number; } interface ChatMessage { role: MessageRole; content: string | null; name?: string; toolCalls?: ToolCall[]; toolCallId?: string; tokenUsage?: TokenUsage; } interface ToolCall { id: string; type: 'function'; function: { name: string; arguments: string | Record; }; } type ToolInputType = 'string' | 'number' | 'boolean' | 'array' | 'object' | 'any'; interface ToolInput { type: ToolInputType; description: string; required?: boolean; default?: unknown; enum?: string[]; } interface ToolInputs { [key: string]: ToolInput; } interface OpenAIToolDefinition { type: 'function'; function: { name: string; description: string; parameters: { type: 'object'; properties: Record; required?: string[]; }; }; } interface CodeExecutionOutput { output: unknown; logs: string; isFinalAnswer: boolean; error?: Error; } interface ActionOutput { output: unknown; isFinalAnswer: boolean; } type MemoryStrategy = 'truncate' | 'compact'; interface AgentConfig$1 { model: Model$1; tools?: Tool$1[]; maxSteps?: number; codeExecutionDelay?: number; systemPrompt?: string; additionalAuthorizedImports?: string[]; streamOutputs?: boolean; verboseLevel?: LogLevel; persistent?: boolean; maxContextLength?: number; memoryStrategy?: MemoryStrategy; customInstructions?: string; maxTokens?: number; temperature?: number; } interface ModelConfig { modelId?: string; apiKey?: string; baseUrl?: string; maxTokens?: number; temperature?: number; timeout?: number; } declare enum LogLevel { OFF = -1, ERROR = 0, INFO = 1, DEBUG = 2 } type StepType = 'system' | 'task' | 'action' | 'planning' | 'final'; interface MemoryStep { type: StepType; timestamp: number; } interface SystemPromptStep extends MemoryStep { type: 'system'; content: string; } interface TaskStep extends MemoryStep { type: 'task'; task: string; } interface ActionStep extends MemoryStep { type: 'action'; stepNumber: number; timing: Timing; modelInputMessages: ChatMessage[]; modelOutputMessage?: ChatMessage; codeAction?: string; toolCalls?: ToolCall[]; toolResults?: ToolCallResult[]; observation?: string; actionOutput?: ActionOutput; tokenUsage?: TokenUsage; error?: Error; isFinalAnswer?: boolean; } interface ToolCallResult { toolCallId: string; toolName: string; result: unknown; error?: string; } interface FinalAnswerStep extends MemoryStep { type: 'final'; answer: unknown; } interface StreamEvent { type: 'delta' | 'toolCall' | 'observation' | 'step' | 'final' | 'error'; data: unknown; } interface RunResult { output: unknown; steps: MemoryStep[]; tokenUsage: TokenUsage; duration: number; } interface Tool$1 { name: string; description: string; inputs: ToolInputs; outputType: string; execute: (args: Record) => Promise; toCodePrompt: () => string; toOpenAITool: () => OpenAIToolDefinition; } interface Model$1 { modelId: string; generate: (messages: ChatMessage[], options?: GenerateOptions) => Promise; generateStream?: (messages: ChatMessage[], options?: GenerateOptions) => AsyncGenerator; } interface GenerateOptions { stopSequences?: string[]; maxTokens?: number; temperature?: number; tools?: Tool$1[]; toolDefinitions?: OpenAIToolDefinition[]; } interface YAMLAgentDefinition { name: string; type: 'ToolUseAgent' | 'CodeAgent' | 'TerminalAgent'; description?: string; model?: YAMLModelDefinition; tools?: string[]; agents?: string[]; maxSteps?: number; maxTokens?: number; temperature?: number; persistent?: boolean; maxContextLength?: number; memoryStrategy?: MemoryStrategy; customInstructions?: string; systemPrompt?: string; } interface YAMLModelDefinition { modelId?: string; baseUrl?: string; apiKey?: string; maxTokens?: number; temperature?: number; timeout?: number; } interface YAMLWorkflowDefinition { name: string; description?: string; model?: YAMLModelDefinition; tools?: Record; agents?: Record; entrypoint: string; globalMaxContextLength?: number; } interface YAMLToolDefinition { type: string; config?: Record; } interface OrchestratorEvent { type: 'agent_start' | 'agent_step' | 'agent_tool_call' | 'agent_observation' | 'agent_end' | 'agent_error'; agentName: string; depth: number; data: unknown; timestamp: number; } type JSONEventType = 'run_start' | 'workflow_loaded' | 'agent_start' | 'agent_step' | 'agent_thinking' | 'agent_tool_call' | 'agent_tool_result' | 'agent_observation' | 'agent_end' | 'run_end' | 'error' | 'log'; interface JSONEventBase { runId: string; timestamp: number; type: JSONEventType; } interface JSONRunStartEvent extends JSONEventBase { type: 'run_start'; data: { workflowPath: string; task: string; cwd?: string; }; } interface JSONWorkflowLoadedEvent extends JSONEventBase { type: 'workflow_loaded'; data: { name: string; description?: string; agents: string[]; tools: string[]; entrypoint: string; }; } interface JSONRunEndEvent extends JSONEventBase { type: 'run_end'; data: { success: boolean; output: unknown; totalDuration: number; totalTokens: number; totalSteps: number; }; } interface JSONAgentStartEvent extends JSONEventBase { type: 'agent_start'; agentName: string; depth: number; data: { task: string; agentType: 'CodeAgent' | 'ToolUseAgent'; maxSteps: number; }; } interface JSONAgentEndEvent extends JSONEventBase { type: 'agent_end'; agentName: string; depth: number; data: { output: unknown; totalSteps: number; tokenUsage: TokenUsage; duration: number; success: boolean; }; } interface JSONAgentStepEvent extends JSONEventBase { type: 'agent_step'; agentName: string; depth: number; data: { stepNumber: number; maxSteps: number; phase: 'start' | 'thinking' | 'acting' | 'complete'; }; } interface JSONAgentThinkingEvent extends JSONEventBase { type: 'agent_thinking'; agentName: string; depth: number; data: { stepNumber: number; content: string; isPartial?: boolean; }; } interface JSONAgentToolCallEvent extends JSONEventBase { type: 'agent_tool_call'; agentName: string; depth: number; data: { stepNumber: number; toolCallId: string; toolName: string; arguments: Record; }; } interface JSONAgentToolResultEvent extends JSONEventBase { type: 'agent_tool_result'; agentName: string; depth: number; data: { stepNumber: number; toolCallId: string; toolName: string; result: unknown; error?: string; duration: number; }; } interface JSONAgentObservationEvent extends JSONEventBase { type: 'agent_observation'; agentName: string; depth: number; data: { stepNumber: number; observation: string; codeAction?: string; logs?: string; }; } interface JSONErrorEvent extends JSONEventBase { type: 'error'; agentName?: string; depth?: number; data: { message: string; stack?: string; stepNumber?: number; }; } interface JSONLogEvent extends JSONEventBase { type: 'log'; data: { level: 'info' | 'warn' | 'error' | 'debug'; message: string; }; } type JSONEvent = JSONRunStartEvent | JSONWorkflowLoadedEvent | JSONRunEndEvent | JSONAgentStartEvent | JSONAgentEndEvent | JSONAgentStepEvent | JSONAgentThinkingEvent | JSONAgentToolCallEvent | JSONAgentToolResultEvent | JSONAgentObservationEvent | JSONErrorEvent | JSONLogEvent; type OutputFormat = 'text' | 'json'; /** * Tool base class for smol-js * * Tools are the primary way for agents to interact with the outside world. * Extend this class and implement the execute() method to create custom tools. */ declare abstract class Tool { /** * Unique identifier for the tool */ abstract readonly name: string; /** * Human-readable description of what the tool does */ abstract readonly description: string; /** * Input parameter schema */ abstract readonly inputs: ToolInputs; /** * Output type description */ abstract readonly outputType: string; /** * Whether the tool has been set up */ protected isSetup: boolean; /** * Optional setup method called before first use. * Override this for expensive initialization (loading models, etc.) */ setup(): Promise; /** * Execute the tool with the given arguments. * Must be implemented by subclasses. */ abstract execute(args: Record): Promise; /** * Call the tool, ensuring setup is complete and validating arguments. */ call(args: Record): Promise; /** * Validate that provided arguments match the input schema. */ protected validateArguments(args: Record): void; /** * Check if a value matches the expected type. */ protected checkType(value: unknown, expectedType: ToolInputType): boolean; /** * Generate a code-friendly prompt representation of this tool. * Used in the CodeAgent system prompt. */ toCodePrompt(): string; /** * Generate an OpenAI-compatible tool definition for function calling. */ toOpenAITool(): OpenAIToolDefinition; /** * Convert tool input type to JSON Schema type. */ protected typeToJsonSchemaType(type: ToolInputType): string; /** * Convert tool input type to JS/TS type string. */ protected typeToJsType(type: ToolInputType | string): string; /** * Serialize the tool to a JSON-compatible object. */ toJSON(): Record; } /** * Helper function to create a tool from a function. * This is an alternative to extending the Tool class. */ declare function createTool(config: { name: string; description: string; inputs: ToolInputs; outputType: string; execute: (args: Record) => Promise; }): Tool; /** * Model base class for smol-js * * Models are responsible for generating text responses from LLMs. * Extend this class to support different LLM providers. */ declare abstract class Model { /** * Model identifier (e.g., "gpt-4", "claude-3-sonnet") */ abstract readonly modelId: string; /** * Generate a response from the model. */ abstract generate(messages: ChatMessage[], options?: GenerateOptions): Promise; /** * Optional streaming generation. * Yields content chunks and returns the final message. */ generateStream?(messages: ChatMessage[], options?: GenerateOptions): AsyncGenerator; /** * Check if the model supports streaming. */ supportsStreaming(): boolean; /** * Extract token usage from a response message. */ protected extractTokenUsage(_response: unknown): TokenUsage | undefined; /** * Convert messages to the format expected by the model's API. */ protected formatMessages(messages: ChatMessage[]): unknown[]; } /** * AgentMemory - Tracks agent execution history with context management */ interface MemoryConfig { maxContextLength?: number; memoryStrategy?: MemoryStrategy; model?: Model$1; } declare class AgentMemory { /** System prompt step (always first) */ systemPrompt: SystemPromptStep; /** All execution steps */ steps: (TaskStep | ActionStep | FinalAnswerStep)[]; private maxContextLength; private memoryStrategy; private model?; constructor(systemPrompt: string, config?: MemoryConfig); /** Reset memory, keeping only the system prompt */ reset(): void; /** Add a task step */ addTask(task: string): TaskStep; /** Create a new action step */ createActionStep(stepNumber: number): ActionStep; /** Add a final answer step */ addFinalAnswer(answer: unknown): FinalAnswerStep; /** Get the last step */ getLastStep(): MemoryStep | undefined; /** Get all action steps */ getActionSteps(): ActionStep[]; /** * Convert memory to messages for LLM context. * Handles both CodeAgent (observation-based) and ToolUseAgent (tool_call-based) patterns. */ toMessages(): ChatMessage[]; /** * Manage context length - truncate or compact if exceeded. */ manageContext(): Promise; /** * Truncate older action steps to fit within context. */ private truncateOlderMessages; /** * Compact older messages into a summary. */ private compactMessages; /** Get total token usage across all steps */ getTotalTokenUsage(): TokenUsage; /** Get current estimated token count */ getEstimatedTokenCount(): number; /** Get a summary of the memory for logging */ getSummary(): string; /** Serialize memory to JSON */ toJSON(): Record; } /** * AgentLogger - Color-coded console logging for agent execution * * Provides formatted output with different colors for: * - Headers (cyan) * - Reasoning/Thoughts (yellow) * - Code blocks (green) * - Output/Results (blue) * - Errors (red) */ declare class AgentLogger { private level; private logFile?; private sessionId; constructor(level?: LogLevel); /** * Generate a unique session ID. */ private generateSessionId; /** * Initialize the log file. */ private initLogFile; /** * Write to the log file. */ private writeToFile; /** * Set the log level. */ setLevel(level: LogLevel): void; /** * Log a header (task start, step start, etc.) */ header(message: string, level?: LogLevel): void; /** * Log a subheader. */ subheader(message: string, level?: LogLevel): void; /** * Log reasoning/thought from the agent. */ reasoning(content: string, level?: LogLevel): void; /** * Log code block. */ code(content: string, language?: string, level?: LogLevel): void; /** * Log execution output. */ output(content: string, level?: LogLevel): void; /** * Log execution logs (print statements). */ logs(content: string, level?: LogLevel): void; /** * Log an error. */ error(message: string, error?: Error, level?: LogLevel): void; /** * Log a warning. */ warn(message: string, level?: LogLevel): void; /** * Log general info. */ info(message: string, level?: LogLevel): void; /** * Log debug info. */ debug(message: string): void; /** * Log final answer. */ finalAnswer(answer: unknown, level?: LogLevel): void; /** * Log step progress. */ stepProgress(current: number, max: number, level?: LogLevel): void; /** * Log waiting message for code execution delay. */ waiting(seconds: number, level?: LogLevel): void; /** * Stream content character by character. */ streamChar(char: string): void; /** * End streaming (add newline). */ streamEnd(): void; /** * Close the log file. */ close(): void; /** * Get the log file path. */ getLogPath(): string | undefined; } /** * Agent - Abstract base class for all agents * * Provides the foundation for multi-step agents that follow the ReAct framework. * Extend this class to create specific agent implementations. */ interface AgentConfig { /** The LLM model to use for generation */ model: Model; /** Tools available to the agent */ tools?: Tool[]; /** Maximum number of steps before stopping (default: 20) */ maxSteps?: number; /** Delay in ms before executing code (default: 5000) */ codeExecutionDelay?: number; /** Custom instructions appended to system prompt */ customInstructions?: string; /** Log level for output (default: INFO) */ verboseLevel?: LogLevel; /** Whether to stream model outputs (default: true) */ streamOutputs?: boolean; /** Whether the agent retains memory between run() calls (default: false) */ persistent?: boolean; /** Max context length in tokens (default: 100000) */ maxContextLength?: number; /** Memory management strategy when context is exceeded (default: 'truncate') */ memoryStrategy?: MemoryStrategy; /** Max tokens for generation (passed to model if set) */ maxTokens?: number; /** Temperature for generation (passed to model if set) */ temperature?: number; /** Agent name for logging */ name?: string; /** Callback for orchestration events */ onEvent?: (event: { type: string; data: unknown; }) => void; } declare abstract class Agent { /** The LLM model for generation */ protected model: Model; /** Available tools mapped by name */ protected tools: Map; /** Agent memory tracking all steps */ protected memory: AgentMemory; /** Logger for formatted output */ protected logger: AgentLogger; /** Configuration options */ protected config: { maxSteps: number; codeExecutionDelay: number; customInstructions: string; verboseLevel: LogLevel; streamOutputs: boolean; persistent: boolean; maxContextLength: number; memoryStrategy: MemoryStrategy; maxTokens?: number; temperature?: number; name: string; onEvent?: (event: { type: string; data: unknown; }) => void; }; /** Current step number */ protected currentStep: number; /** Whether the agent is currently running */ protected isRunning: boolean; /** Whether the agent has been initialized at least once */ private initialized; constructor(config: AgentConfig); /** * Initialize the system prompt for the agent. * Must be implemented by subclasses. */ protected abstract initializeSystemPrompt(): string; /** * Execute a single step in the agent loop. * Must be implemented by subclasses. */ protected abstract executeStep(memoryStep: ActionStep): Promise; /** * Run the agent on a task. */ run(task: string, reset?: boolean): Promise; /** * Generate a final answer when max steps is reached. */ protected provideFinalAnswer(task: string): Promise; /** Emit an orchestration event */ protected emitEvent(type: string, data: unknown): void; /** Stop the agent */ stop(): void; /** Get the current memory */ getMemory(): AgentMemory; /** Get registered tools */ getTools(): Map; /** Add a tool to the agent */ addTool(tool: Tool): void; /** Remove a tool from the agent */ removeTool(name: string): boolean; /** Get agent name */ getName(): string; /** Get agent type identifier */ getType(): string; /** Get max steps configuration */ getMaxSteps(): number; /** Set the event callback (useful for orchestration) */ setOnEvent(callback: (event: { type: string; data: unknown; }) => void): void; /** Sleep for a specified duration */ protected sleep(ms: number): Promise; } /** * LocalExecutor - JavaScript code execution engine using Node's vm module * * Executes JavaScript code chunks in an isolated context with: * - State persistence between steps (variables carry forward) * - Tool injection (tools available as async functions) * - Dynamic imports via CDN (esm.sh) * - Print capture and logging * - Safety timeouts */ interface ExecutorConfig { /** * Maximum execution time in milliseconds * @default 30000 */ timeout?: number; /** * Additional authorized imports (npm packages to allow) */ authorizedImports?: string[]; /** * Whether to allow fs module access * @default true */ allowFs?: boolean; /** * Working directory for fs operations */ workingDirectory?: string; } declare class LocalExecutor { private context; private state; private tools; private config; private capturedLogs; constructor(config?: ExecutorConfig); /** * Create the VM context with available globals. */ private createContext; /** * Add tools to the executor context. */ sendTools(tools: Record): void; /** * Send variables to the executor state. */ sendVariables(variables: Record): void; /** * Execute JavaScript code and return the result. */ execute(code: string): Promise; /** * Wrap code to handle async execution and final_answer calls. */ private wrapCode; /** * Instrument code to capture the last expression value and convert * let/const/var declarations to global assignments for state persistence. */ private instrumentCode; /** * Check if this is the last meaningful line of code. */ private isLastMeaningfulLine; /** * Update internal state from context after execution. */ private updateStateFromContext; /** * Stringify a value for logging. */ private stringify; /** * Reset the executor state. */ reset(): void; /** * Get the current state. */ getState(): Record; } /** * CodeAgent - Executes tasks by generating and running JavaScript code * * This is the main agent implementation for smol-js. It follows the ReAct pattern: * 1. Receives a task * 2. Generates reasoning and code * 3. Executes the code in a sandboxed environment * 4. Observes the result and continues or returns final answer */ interface CodeAgentConfig extends AgentConfig { /** * Additional npm packages that can be imported dynamically */ additionalAuthorizedImports?: string[]; /** * Executor configuration */ executorConfig?: ExecutorConfig; /** * Working directory for file operations */ workingDirectory?: string; } declare class CodeAgent extends Agent { /** * The JavaScript code executor */ private executor; /** * Authorized imports for dynamic npm package loading */ private authorizedImports; constructor(config: CodeAgentConfig); /** * Initialize the system prompt with tool definitions. */ protected initializeSystemPrompt(): string; /** * Execute a single step: get LLM response, extract code, execute it. */ protected executeStep(memoryStep: ActionStep): Promise; /** * Generate response from the LLM, optionally streaming. */ private generateResponse; /** * Format output for display. */ private formatOutput; /** * Format the observation to send back to the LLM. */ private formatObservation; /** * Reset the agent and executor state. */ reset(): void; /** * Get the executor instance. */ getExecutor(): LocalExecutor; /** * Override addTool to also register with executor. */ addTool(tool: Tool): void; } /** * ToolUseAgent - Executes tasks using standard OpenAI-style tool calls * * Unlike CodeAgent which generates and executes JavaScript code, * ToolUseAgent operates by making tool calls through the LLM's native * function calling capabilities, following the ReACT pattern: * Think -> Act (tool call) -> Observe (result) -> repeat */ interface ToolUseAgentConfig extends AgentConfig { /** Whether to run independent tool calls in parallel (default: true) */ parallelToolCalls?: boolean; } declare class ToolUseAgent extends Agent { private parallelToolCalls; constructor(config: ToolUseAgentConfig); /** * Initialize the system prompt with tool descriptions. */ protected initializeSystemPrompt(): string; /** * Execute a single step: send messages with tool definitions, process tool calls. */ protected executeStep(memoryStep: ActionStep): Promise; /** * Process tool calls from the model response. */ private processToolCalls; /** * Override provideFinalAnswer to use tool calling format. */ protected provideFinalAnswer(task: string): Promise; /** * Add a tool, which can also be an Agent instance (auto-wraps with AgentTool). */ addTool(tool: Tool): void; } /** * TerminalAgent - Accomplishes tasks by reasoning about and executing shell commands. * * Unlike CodeAgent (sandboxed JS VM) or ToolUseAgent (structured function calls), * TerminalAgent operates by having the LLM emit shell commands in fenced ```sh * blocks. Each block is executed on the user's real macOS terminal with full * stdout/stderr streaming. * * Key behaviours: * - Verbose logging is always on. The user sees reasoning, pending commands, * and live output. * - A 5-second delay fires before every command batch so the user can read * what is about to run and abort with Ctrl+C. * - User-assigned tools are stripped. The agent always has final_answer and * any AgentTools (sub-agent delegation) that were wired in via YAML. * - Commands run via child_process with stdio piped so output is captured * and streamed back to the agent as observations. */ interface TerminalAgentConfig extends AgentConfig { /** * Seconds to wait before executing each command batch. * Gives the user time to read pending commands and Ctrl+C. * Default: 5 */ commandDelay?: number; /** * Maximum characters of command output to feed back to the LLM per batch. * Very long outputs are truncated (head + tail preserved) to keep context * manageable. Default: 8000 */ maxOutputLength?: number; } declare class TerminalAgent extends Agent { private readonly commandDelay; private readonly maxOutputLength; constructor(config: TerminalAgentConfig); /** * Build the system prompt. Includes delegation info if sub-agents are present. */ protected initializeSystemPrompt(): string; /** * Execute one step of the ReAct loop: * 1. Send messages to LLM (with tool defs for final_answer / delegation) * 2. Extract reasoning and ```sh blocks from the response * 3. If tool calls present (final_answer or delegation), process them * 4. Otherwise execute shell commands with the pre-execution delay * 5. Feed stdout/stderr/exit-code back as observation */ protected executeStep(memoryStep: ActionStep): Promise; /** * Run a single shell command, capture stdout/stderr, return structured result. */ private runCommand; /** * Truncate long output, preserving head and tail so context stays useful. */ private truncateOutput; /** * Generate response, with streaming if available. */ private generateResponse; /** * Process tool calls (final_answer or AgentTool delegation). */ private processToolCalls; /** * Override: force final answer via tool call format when max steps hit. */ protected provideFinalAnswer(task: string): Promise; } /** * OpenAI-compatible Model implementation * * Supports any API that follows the OpenAI chat completions format, * including OpenRouter, Azure OpenAI, local servers, etc. */ interface OpenAIModelConfig { /** * Model identifier (e.g., "gpt-4", "anthropic/claude-sonnet-4.5") */ modelId?: string; /** * API key for authentication */ apiKey?: string; /** * Base URL for the API endpoint * @default "https://openrouter.ai/api/v1" */ baseUrl?: string; /** * Maximum tokens to generate (omitted from requests by default) */ maxTokens?: number; /** * Temperature for generation (omitted from requests by default) */ temperature?: number; /** * Request timeout in milliseconds */ timeout?: number; /** * Default headers to include in requests */ defaultHeaders?: Record; } declare class OpenAIModel extends Model { readonly modelId: string; private client; private config; constructor(config?: OpenAIModelConfig); /** * Generate a response from the model (supports tool calling). */ generate(messages: ChatMessage[], options?: GenerateOptions): Promise; /** * Generate a streaming response from the model. */ generateStream(messages: ChatMessage[], options?: GenerateOptions): AsyncGenerator; /** * Format messages for the OpenAI API, including tool call/response messages. */ protected formatMessages(messages: ChatMessage[]): OpenAI.Chat.ChatCompletionMessageParam[]; } /** * Default tools provided to all agents */ /** * FinalAnswerTool - Used by the agent to return the final answer. * This is always available to CodeAgent. */ declare class FinalAnswerTool extends Tool { readonly name = "final_answer"; readonly description = "Returns the final answer to the user query. Use this when you have completed the task and have the final result."; readonly inputs: ToolInputs; readonly outputType = "any"; execute(args: Record): Promise; } /** * UserInputTool - Allows the agent to ask the user for input. */ declare class UserInputTool extends Tool { readonly name = "user_input"; readonly description = "Asks the user for additional input or clarification."; readonly inputs: ToolInputs; readonly outputType = "string"; private inputHandler?; constructor(inputHandler?: (question: string) => Promise); execute(args: Record): Promise; } declare const finalAnswerTool: FinalAnswerTool; /** * AgentTool - Wraps a CodeAgent as a Tool for use by other agents * * This enables nested/hierarchical agent architectures where a "manager" agent * can delegate tasks to specialized "worker" agents. * * Based on the ManagedAgent pattern from Python smolagents. */ interface AgentToolConfig { /** * The agent to wrap as a tool */ agent: Agent; /** * Name for the tool (defaults to agent's name or "managed_agent") */ name?: string; /** * Description of what this agent does (used in parent agent's prompt) */ description?: string; /** * Additional context to provide to the agent with each task */ additionalContext?: string; /** * Whether to provide the full result object or just the output * @default false */ returnFullResult?: boolean; } declare class AgentTool extends Tool { readonly name: string; readonly description: string; readonly inputs: ToolInputs; readonly outputType = "string"; private agent; private additionalContext?; private returnFullResult; constructor(config: AgentToolConfig); /** * Generate a default description based on the agent's configuration */ private generateDescription; /** * Execute the agent with the given task */ execute(args: Record): Promise; /** * Override toCodePrompt to provide a cleaner signature for nested agents */ toCodePrompt(): string; } /** * Helper function to quickly wrap an agent as a tool */ declare function agentAsTool(agent: Agent, options?: Omit): AgentTool; /** * ReadFileTool - Read contents from a file */ declare class ReadFileTool extends Tool { readonly name = "read_file"; readonly description = "Read the contents of a file at the specified path. Returns the file content as a string."; readonly inputs: ToolInputs; readonly outputType = "string"; private workingDirectory; constructor(config?: { workingDirectory?: string; }); execute(args: Record): Promise; } /** * WriteFileTool - Write content to a file */ declare class WriteFileTool extends Tool { readonly name = "write_file"; readonly description = "Write content to a file at the specified path. Creates the file if it does not exist, and creates parent directories as needed. Overwrites existing content by default."; readonly inputs: ToolInputs; readonly outputType = "string"; private workingDirectory; constructor(config?: { workingDirectory?: string; }); execute(args: Record): Promise; } /** * CurlTool - HTTP requests (GET/POST) using fetch */ declare class CurlTool extends Tool { readonly name = "curl"; readonly description = "Make HTTP requests to any URL. Supports GET and POST methods with custom headers and body. Returns the response body as text."; readonly inputs: ToolInputs; readonly outputType = "string"; private timeout; constructor(config?: { timeout?: number; }); execute(args: Record): Promise; } /** * ExaSearchTool - Web search using the Exa.ai API * * Uses Exa's embeddings-based search for semantically intelligent results. */ interface ExaSearchConfig { apiKey?: string; } declare class ExaSearchTool extends Tool { readonly name = "exa_search"; readonly description = "Search the web using Exa.ai semantic search. Returns relevant web pages with titles, URLs, and optionally content snippets. Use this for finding information, research, and fact-checking."; readonly inputs: ToolInputs; readonly outputType = "string"; private apiKey; constructor(config?: ExaSearchConfig); setup(): Promise; execute(args: Record): Promise; } /** * ExaGetContentsTool - Get webpage contents using Exa.ai API * * Fetches and extracts clean text content from web pages. */ interface ExaGetContentsConfig { apiKey?: string; } declare class ExaGetContentsTool extends Tool { readonly name = "exa_get_contents"; readonly description = "Get the full text content of one or more web pages using Exa.ai. Returns cleaned, readable text extracted from the HTML. Use this to read articles, documentation, or any web page content."; readonly inputs: ToolInputs; readonly outputType = "string"; private apiKey; constructor(config?: ExaGetContentsConfig); setup(): Promise; execute(args: Record): Promise; } /** * ExaResearchTool - Agentic web research using Exa.ai Research API * * The Research API is an asynchronous, multi-step pipeline that transforms * open-ended questions into grounded reports with citations. The system performs * planning, searching, and reasoning to produce comprehensive research outputs. * * See: https://docs.exa.ai/reference/exa-research */ interface ExaResearchConfig { apiKey?: string; model?: 'exa-research-fast' | 'exa-research' | 'exa-research-pro'; pollInterval?: number; maxPollTime?: number; } declare class ExaResearchTool extends Tool { readonly name = "exa_research"; readonly description = "Perform comprehensive web research using Exa.ai's agentic research system. Provide natural-language instructions about what to research, and the AI research agent will plan searches, gather sources, extract facts, and synthesize findings into a detailed markdown report with citations. Ideal for deep research on any topic. Results typically complete in 20-90 seconds."; readonly inputs: ToolInputs; readonly outputType = "string"; private apiKey; private defaultModel; private pollInterval; private maxPollTime; constructor(config?: ExaResearchConfig); setup(): Promise; execute(args: Record): Promise; } /** * ProxyTool - Bridges the smol-js agent runtime to an external standalone tool * executed in an isolated Bun process via the toolHarness adapter. * * The tool file is never imported into the main Node.js process. When an agent * invokes this proxy, it spawns: * * bun run * * The harness is the ONLY place that speaks the stdout protocol. The tool * itself simply exports { TOOL_METADATA, execute } and knows nothing about * how it is being called. * * Protocol (stdout of harness/child): * - A line prefixed with `[TOOL_RESULT]` contains the JSON-serialized return value. * - A line prefixed with `[TOOL_ERROR]` means the tool threw; payload is the message. * - Any other stdout line (e.g. console.log inside execute()) is streaming output. * * Extensibility: The spawn+stdio transport is fully encapsulated here. A future * variant (HTTP, gRPC, IPC) only needs to replace execute() — the tool file and * YAML definition stay identical. */ interface ProxyToolConfig { /** Absolute path to the .ts or .js tool file */ toolPath: string; /** Tool name (must match the file's base name) */ name: string; /** Human-readable description exposed to agents */ description: string; /** Input schema that the LLM will see */ inputs: ToolInputs; /** Output type label */ outputType: string; /** Max execution time in ms (default 60 s) */ timeout?: number; } declare class ProxyTool extends Tool { readonly name: string; readonly description: string; readonly inputs: ToolInputs; readonly outputType: string; private readonly toolPath; private readonly timeout; private bunPath; private harnessPath; constructor(config: ProxyToolConfig); /** * Ensure Bun is available and locate the harness before first invocation. */ setup(): Promise; /** * Spawn the harness in a Bun child process. The harness imports the tool, * calls execute(args), and writes the protocol lines. Any console.log from * the tool flows through stdout as plain lines. */ execute(args: Record): Promise; private processLine; } /** * CustomToolScanner — discovers standalone tool files in a directory and * extracts their metadata so that ProxyTool instances can be registered * with the YAML loader. * * Convention over Configuration: * • Each file in the custom-tools folder must export a default metadata * object conforming to CustomToolMetadata (see standalone tool wrapper docs). * • The exported class name (or `name` field in metadata) MUST match the * file's basename (without extension). E.g. `WeatherLookup.ts` → name: "WeatherLookup". * • The tool is referenced in YAML by that same name. * * Metadata Extraction (zero-import approach): * We read the file as text and use a lightweight regex to pull the * `TOOL_METADATA` export block. This keeps the scanner decoupled from * Bun/ESM and lets it run purely in the Node.js main process. * The metadata block must be a single JSON object assigned to * `export const TOOL_METADATA = { ... };` */ interface CustomToolMetadata { /** Must match the file's basename (sans extension) */ name: string; /** Human-readable description shown to the LLM */ description: string; /** Input schema identical to Tool.inputs */ inputs: ToolInputs; /** Output type label */ outputType: string; /** Optional execution timeout in ms */ timeout?: number; } interface DiscoveredTool { /** Absolute path to the tool file */ filePath: string; /** Parsed metadata */ metadata: CustomToolMetadata; } /** * Scan a directory for custom tool files and extract their metadata. * * @param folderPath Absolute path to the custom-tools directory. * @returns Array of discovered tools with parsed metadata. * @throws If any file fails metadata extraction. */ declare function scanCustomTools(folderPath: string): DiscoveredTool[]; /** * Scan a folder and return a Map ready for registration * with YAMLLoader. */ declare function loadCustomTools(folderPath: string): Map; /** * System prompts for CodeAgent * * Adapted from smolagents Python prompts but optimized for JavaScript execution. */ interface PromptVariables { tools: string; authorizedImports: string; customInstructions?: string; } /** * Generate the system prompt for CodeAgent. */ declare function generateSystemPrompt(variables: PromptVariables): string; /** * Prompt for generating a final answer when max steps is reached. */ declare 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."; /** * Error recovery prompt. */ declare function getErrorRecoveryPrompt(error: string): string; /** * System prompts for ToolUseAgent */ interface ToolUsePromptVariables { tools: string; customInstructions?: string; /** Whether this agent has sub-agents (AgentTool instances) */ hasSubAgents?: boolean; /** Whether this agent has file tools (read_file, write_file) */ hasFileTools?: boolean; } /** * Generate the system prompt for ToolUseAgent. */ declare function generateToolUseSystemPrompt(variables: ToolUsePromptVariables): string; /** * Format tool descriptions for the system prompt. */ declare function formatToolDescriptions(tools: Array<{ name: string; description: string; inputs: Record; }>): string; /** * YAMLLoader - Loads and parses YAML workflow definitions into runnable agents */ interface LoadedWorkflow { name: string; description?: string; entrypointAgent: Agent; agents: Map; tools: Map; } declare class YAMLLoader { private customTools; private toolInstances; /** * Register a custom tool type (class) for use in YAML definitions. */ registerToolType(typeName: string, toolClass: new (config?: Record) => Tool): void; /** * Register a pre-built tool instance for use in YAML definitions. * Used by the custom tool system to register ProxyTool instances * that are created by the scanner rather than by class instantiation. */ registerToolInstance(typeName: string, tool: Tool): void; /** * Load a workflow from a YAML file path. */ loadFromFile(filePath: string): LoadedWorkflow; /** * Load a workflow from a YAML string. */ loadFromString(yamlContent: string): LoadedWorkflow; /** * Build a runnable workflow from a parsed definition. */ private buildWorkflow; /** * Build a tool instance from a type name and config. */ private buildTool; /** * Build an agent instance from a YAML definition. */ private buildAgent; } /** * JSONOutputHandler - Emits structured NDJSON events for machine-readable CLI output. */ interface JSONOutputConfig { runId: string; verbose?: boolean; } declare class JSONOutputHandler { private readonly runId; private readonly startTime; constructor(config: JSONOutputConfig); private emit; emitRunStart(workflowPath: string, task: string, cwd?: string): void; emitWorkflowLoaded(name: string, description: string | undefined, agents: string[], tools: string[], entrypoint: string): void; emitRunEnd(success: boolean, output: unknown, totalTokens: number, totalSteps: number): void; emitAgentStart(agentName: string, depth: number, task: string, agentType: string, maxSteps: number): void; emitAgentEnd(agentName: string, depth: number, output: unknown, totalSteps: number, tokenUsage: TokenUsage | undefined, duration: number, success: boolean): void; emitAgentStep(agentName: string, depth: number, stepNumber: number, maxSteps: number, phase: string): void; emitAgentThinking(agentName: string, depth: number, stepNumber: number, content: string, isPartial: boolean): void; emitToolCall(agentName: string, depth: number, stepNumber: number, toolCallId: string, toolName: string, args: Record): void; emitToolResult(agentName: string, depth: number, stepNumber: number, toolCallId: string, toolName: string, result: unknown, error: string | undefined, duration: number): void; emitObservation(agentName: string, depth: number, stepNumber: number, observation: string, codeAction: string | undefined, logs: string | undefined): void; emitError(message: string, stack?: string, agentName?: string, depth?: number, stepNumber?: number): void; } /** * Orchestrator - Loads, runs, and provides real-time visibility into agent execution */ interface OrchestratorConfig { /** Whether to display real-time output (default: true) */ verbose?: boolean; /** Callback for orchestrator events */ onEvent?: (event: OrchestratorEvent) => void; /** Output format: 'text' for chalk-formatted console, 'json' for NDJSON streaming */ outputFormat?: OutputFormat; /** Unique run identifier (required for JSON output) */ runId?: string; /** Working directory for agent file operations */ cwd?: string; } declare class Orchestrator { private loader; private config; private activeAgents; private eventLog; private jsonOutput; private isJsonMode; constructor(config?: OrchestratorConfig); /** * Load a workflow from a YAML file. */ loadWorkflow(filePath: string): LoadedWorkflow; /** * Load a workflow from YAML string. */ loadWorkflowFromString(yamlContent: string, sourcePath?: string): LoadedWorkflow; /** * Run a loaded workflow with a task. */ runWorkflow(workflow: LoadedWorkflow, task: string, workflowPath?: string): Promise; /** * Run a standalone agent with a task. */ runAgent(agent: Agent, task: string): Promise; /** * Instrument an agent with orchestrator event tracking. */ private instrumentAgent; /** * Emit an agent event as JSON. */ private emitAgentEventAsJSON; /** * Display workflow info at startup. */ private displayWorkflowInfo; /** * Display run start info. */ private displayRunStart; /** * Display run completion info. */ private displayRunEnd; /** * Display an error. */ private displayError; /** * Log an orchestration event. */ logEvent(event: OrchestratorEvent): void; /** * Get the event log. */ getEventLog(): OrchestratorEvent[]; /** * Get the YAML loader for registering custom tools. */ getLoader(): YAMLLoader; /** * Get the JSON output handler (if in JSON mode). */ getJSONOutputHandler(): JSONOutputHandler | null; /** * Check if in JSON output mode. */ isJSONOutputMode(): boolean; /** * Get the run ID. */ getRunId(): string | undefined; } export { type ActionOutput, type ActionStep, Agent, type AgentConfig, type AgentConfig$1 as AgentConfigType, AgentLogger, AgentMemory, AgentTool, type AgentToolConfig, type ChatMessage, CodeAgent, type CodeAgentConfig, type CodeExecutionOutput, CurlTool, type CustomToolMetadata, type DiscoveredTool, ExaGetContentsTool, ExaResearchTool, ExaSearchTool, type ExecutorConfig, FINAL_ANSWER_PROMPT, type FinalAnswerStep, FinalAnswerTool, type GenerateOptions, type JSONAgentEndEvent, type JSONAgentObservationEvent, type JSONAgentStartEvent, type JSONAgentStepEvent, type JSONAgentThinkingEvent, type JSONAgentToolCallEvent, type JSONAgentToolResultEvent, type JSONErrorEvent, type JSONEvent, type JSONEventBase, type JSONEventType, type JSONLogEvent, type JSONOutputConfig, JSONOutputHandler, type JSONRunEndEvent, type JSONRunStartEvent, type JSONWorkflowLoadedEvent, type LoadedWorkflow, LocalExecutor, LogLevel, type MemoryStep, type MemoryStrategy, type MessageRole, Model, type ModelConfig, OpenAIModel, type OpenAIModelConfig, type OpenAIToolDefinition, Orchestrator, type OrchestratorConfig, type OrchestratorEvent, type OutputFormat, type PromptVariables, ProxyTool, type ProxyToolConfig, ReadFileTool, type RunResult, type StreamEvent, type SystemPromptStep, type TaskStep, TerminalAgent, type TerminalAgentConfig, type Timing, type TokenUsage, Tool, type ToolCall, type ToolCallResult, type ToolInput, type ToolInputType, type ToolInputs, ToolUseAgent, type ToolUseAgentConfig, type ToolUsePromptVariables, UserInputTool, WriteFileTool, type YAMLAgentDefinition, YAMLLoader, type YAMLModelDefinition, type YAMLToolDefinition, type YAMLWorkflowDefinition, agentAsTool, createTool, finalAnswerTool, formatToolDescriptions, generateSystemPrompt, generateToolUseSystemPrompt, getErrorRecoveryPrompt, loadCustomTools, scanCustomTools };