/** * 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. */ import { spawn } from 'child_process'; import * as path from 'path'; import { Tool } from './Tool.js'; import type { ToolInputs } from '../types.js'; import { ensureBunAvailable } from '../utils/bunInstaller.js'; // --- Protocol delimiters (spoken only by toolHarness, parsed only here) --- export const TOOL_RESULT_PREFIX = '[TOOL_RESULT]'; export const TOOL_ERROR_PREFIX = '[TOOL_ERROR]'; /** How long (ms) to wait for the child process before forcefully killing it. */ const DEFAULT_TOOL_TIMEOUT_MS = 60_000; /** * Resolve the toolHarness.ts path shipped with this package. * At runtime the bundled code lives in dist/; the harness is at the package root. */ function resolveHarnessPath(): string { // __dirname in the CJS bundle points to dist/. The harness sits one level up. return path.resolve(__dirname, '..', 'toolHarness.ts'); } export 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; } export class ProxyTool extends Tool { readonly name: string; readonly description: string; readonly inputs: ToolInputs; readonly outputType: string; private readonly toolPath: string; private readonly timeout: number; private bunPath: string | null = null; private harnessPath: string | null = null; constructor(config: ProxyToolConfig) { super(); this.name = config.name; this.description = config.description; this.inputs = config.inputs; this.outputType = config.outputType; this.toolPath = config.toolPath; this.timeout = config.timeout ?? DEFAULT_TOOL_TIMEOUT_MS; } /** * Ensure Bun is available and locate the harness before first invocation. */ async setup(): Promise { this.bunPath = await ensureBunAvailable(); this.harnessPath = resolveHarnessPath(); this.isSetup = true; } /** * 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. */ async execute(args: Record): Promise { if (!this.bunPath || !this.harnessPath) { await this.setup(); } const serializedArgs = JSON.stringify(args); return new Promise((resolve, reject) => { // Harness signature: bun run toolHarness.ts const child = spawn(this.bunPath!, ['run', this.harnessPath!, this.toolPath, serializedArgs], { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env }, }); let result: unknown = undefined; let resultReceived = false; let errorMessage: string | null = null; const logBuffer: string[] = []; let stderr = ''; // --- stdout: stream lines, parse protocol --- let partialLine = ''; child.stdout.on('data', (chunk: Buffer) => { partialLine += chunk.toString('utf8'); const lines = partialLine.split('\n'); partialLine = lines.pop()!; for (const line of lines) { this.processLine(line, { onOutput: (msg) => logBuffer.push(msg), onResult: (value) => { result = value; resultReceived = true; }, onError: (msg) => { errorMessage = msg; }, }); } }); // --- stderr: accumulate for diagnostics --- child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8'); }); // --- timeout watchdog --- const timer = setTimeout(() => { child.kill('SIGTERM'); reject(new Error( `Custom tool "${this.name}" timed out after ${this.timeout}ms. ` + 'The process was terminated. Check the tool for infinite loops or slow operations.' )); }, this.timeout); timer.unref(); // --- process exit --- child.on('close', (code) => { clearTimeout(timer); // Flush any remaining partial line if (partialLine.trim()) { this.processLine(partialLine, { onOutput: (msg) => logBuffer.push(msg), onResult: (value) => { result = value; resultReceived = true; }, onError: (msg) => { errorMessage = msg; }, }); } if (errorMessage) { reject(new Error( `Custom tool "${this.name}" reported an error: ${errorMessage}` )); return; } if (resultReceived) { // Prepend captured log lines so agents have context about what the tool did if (logBuffer.length > 0) { const logPrefix = `[Tool output logs]\n${logBuffer.join('\n')}\n\n[Tool result]\n`; if (typeof result === 'string') { resolve(logPrefix + result); } else { resolve({ logs: logBuffer.join('\n'), result }); } } else { resolve(result); } return; } // No [TOOL_RESULT] received const combined = (logBuffer.join('\n') + '\n' + stderr).trim(); if (code !== 0) { reject(new Error( `Custom tool "${this.name}" exited with code ${code}. ` + `Output: ${combined || '(none)'}` )); } else { resolve(combined || `Tool "${this.name}" produced no output.`); } }); child.on('error', (err) => { clearTimeout(timer); reject(new Error( `Failed to spawn custom tool "${this.name}": ${err.message}` )); }); }); } // --- line parser: protocol is spoken by harness, interpreted here --- private processLine( line: string, handlers: { onOutput: (msg: string) => void; onResult: (value: unknown) => void; onError: (msg: string) => void; } ): void { const trimmed = line.trimEnd(); if (!trimmed) return; if (trimmed.startsWith(TOOL_RESULT_PREFIX)) { const json = trimmed.slice(TOOL_RESULT_PREFIX.length).trim(); try { handlers.onResult(JSON.parse(json)); } catch { handlers.onResult(json); } } else if (trimmed.startsWith(TOOL_ERROR_PREFIX)) { handlers.onError(trimmed.slice(TOOL_ERROR_PREFIX.length).trim()); } else { // Plain stdout from the tool (console.log inside execute) = streaming output handlers.onOutput(trimmed); } } }