/** * smol-js CLI - Run YAML-defined agent workflows from the command line * * Usage: * smol-js [--task "your task"] (auto-detects yaml files) * smol-js run [--task "your task"] * smol-js validate */ import * as fs from 'fs'; import * as path from 'path'; import * as readline from 'readline'; import chalk from 'chalk'; import dotenv from 'dotenv'; import { Orchestrator } from './orchestrator/Orchestrator.js'; import { loadCustomTools } from './tools/CustomToolScanner.js'; // Load environment variables dotenv.config(); async function main(): Promise { const args = process.argv.slice(2); if (args.length === 0 || args[0] === '--help' || args[0] === '-h') { printUsage(); process.exit(0); } const command = args[0]; if (command === 'run') { await runCommand(args.slice(1)); } else if (command === 'validate') { await validateCommand(args.slice(1)); } else if (command.endsWith('.yaml') || command.endsWith('.yml')) { // Auto-detect: if first arg is a YAML file, treat as "run" await runCommand(args); } else { console.error(chalk.red(`Unknown command: ${command}`)); printUsage(); process.exit(1); } } function printUsage(): void { console.log(chalk.cyan.bold('\nsmol-js CLI - YAML Agent Orchestrator\n')); console.log('Usage:'); console.log(' smol-js [options] Run a workflow (auto-detect)'); console.log(' smol-js run [options] Run a workflow (explicit)'); console.log(' smol-js validate Validate a workflow file'); console.log(''); console.log('Options:'); console.log(' --task, -t Task description (prompted if not provided)'); console.log(' --quiet, -q Reduce output verbosity'); console.log(' --output-format Output format: text (default) or json'); console.log(' --verbose Include full step details in output'); console.log(' --run-id Unique run identifier (auto-generated if not provided)'); console.log(' --cwd Working directory for agent file operations'); console.log(' --custom-tools-folder Path to folder containing standalone custom tool files'); console.log(' --help, -h Show this help message'); console.log(''); console.log('Examples:'); console.log(' npx @samrahimi/smol-js workflow.yaml --task "Research AI safety"'); console.log(' smol-js research-agent.yaml -t "Write a summary of quantum computing"'); console.log(' smol-js validate my-workflow.yaml'); console.log(' smol-js workflow.yaml --task "Task" --output-format json --run-id abc123'); } async function runCommand(args: string[]): Promise { if (args.length === 0) { console.error(chalk.red('Error: workflow file path required')); process.exit(1); } const filePath = args[0]; let task = ''; let quiet = false; let outputFormat: 'text' | 'json' = 'text'; let verbose = false; let runId = ''; let cwd = ''; let customToolsFolder = ''; // Parse remaining args for (let i = 1; i < args.length; i++) { if (args[i] === '--task' || args[i] === '-t') { task = args[i + 1] ?? ''; i++; } else if (args[i] === '--quiet' || args[i] === '-q') { quiet = true; } else if (args[i] === '--output-format') { const format = args[i + 1]; if (format === 'json' || format === 'text') { outputFormat = format; } else { console.error(chalk.red(`Invalid output format: ${format}. Use 'text' or 'json'.`)); process.exit(1); } i++; } else if (args[i] === '--verbose') { verbose = true; } else if (args[i] === '--run-id') { runId = args[i + 1] ?? ''; i++; } else if (args[i] === '--cwd') { cwd = args[i + 1] ?? ''; i++; } else if (args[i] === '--custom-tools-folder') { customToolsFolder = args[i + 1] ?? ''; i++; } } // Generate run ID if not provided and using JSON output if (outputFormat === 'json' && !runId) { runId = `run-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`; } // Resolve file path const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath); if (!fs.existsSync(resolvedPath)) { if (outputFormat === 'json') { console.log(JSON.stringify({ runId: runId || 'unknown', timestamp: Date.now(), type: 'error', data: { message: `File not found: ${resolvedPath}` }, })); } else { console.error(chalk.red(`Error: file not found: ${resolvedPath}`)); } process.exit(1); } // Get task from user if not provided (skip in JSON mode) if (!task) { if (outputFormat === 'json') { console.log(JSON.stringify({ runId: runId || 'unknown', timestamp: Date.now(), type: 'error', data: { message: 'Task is required in JSON output mode. Use --task flag.' }, })); process.exit(1); } task = await promptUser('Enter your task: '); if (!task.trim()) { console.error(chalk.red('Error: task cannot be empty')); process.exit(1); } } // Change working directory if specified if (cwd) { const resolvedCwd = path.isAbsolute(cwd) ? cwd : path.resolve(process.cwd(), cwd); if (!fs.existsSync(resolvedCwd)) { fs.mkdirSync(resolvedCwd, { recursive: true }); } process.chdir(resolvedCwd); } // Create orchestrator with appropriate config const orchestrator = new Orchestrator({ verbose: outputFormat === 'json' ? verbose : !quiet, outputFormat, runId: runId || undefined, cwd: cwd || undefined, }); // Register custom tools if folder specified if (customToolsFolder) { const resolvedToolsFolder = path.isAbsolute(customToolsFolder) ? customToolsFolder : path.resolve(process.cwd(), customToolsFolder); if (outputFormat !== 'json') { console.log(chalk.gray(`\nScanning custom tools in: ${resolvedToolsFolder}\n`)); } const customTools = loadCustomTools(resolvedToolsFolder); const loader = orchestrator.getLoader(); for (const [toolName, proxyTool] of customTools) { loader.registerToolInstance(toolName, proxyTool); if (outputFormat !== 'json') { console.log(chalk.green(` + Registered custom tool: ${toolName}`)); } } } try { if (outputFormat !== 'json') { console.log(chalk.gray(`\nLoading workflow from: ${resolvedPath}\n`)); } const workflow = orchestrator.loadWorkflow(resolvedPath); await orchestrator.runWorkflow(workflow, task, resolvedPath); // Exit with success process.exit(0); } catch (error) { if (outputFormat === 'json') { const jsonHandler = orchestrator.getJSONOutputHandler(); if (jsonHandler) { jsonHandler.emitError((error as Error).message, (error as Error).stack); jsonHandler.emitRunEnd(false, null, 0, 0); } else { console.log(JSON.stringify({ runId: runId || 'unknown', timestamp: Date.now(), type: 'error', data: { message: (error as Error).message, stack: (error as Error).stack }, })); } } else { console.error(chalk.red(`\nError: ${(error as Error).message}`)); if (process.env.DEBUG) { console.error((error as Error).stack); } } process.exit(1); } } async function validateCommand(args: string[]): Promise { if (args.length === 0) { console.error(chalk.red('Error: workflow file path required')); process.exit(1); } const filePath = args[0]; const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath); if (!fs.existsSync(resolvedPath)) { console.error(chalk.red(`Error: file not found: ${resolvedPath}`)); process.exit(1); } const orchestrator = new Orchestrator({ verbose: false }); try { const workflow = orchestrator.loadWorkflow(resolvedPath); console.log(chalk.green.bold('✅ Workflow is valid')); console.log(chalk.green(` Name: ${workflow.name}`)); console.log(chalk.green(` Agents: ${Array.from(workflow.agents.keys()).join(', ')}`)); console.log(chalk.green(` Tools: ${Array.from(workflow.tools.keys()).join(', ') || '(using defaults)'}`)); console.log(chalk.green(` Entrypoint: ${workflow.entrypointAgent.getName()}`)); process.exit(0); } catch (error) { console.error(chalk.red(`❌ Validation failed: ${(error as Error).message}`)); process.exit(1); } } function promptUser(question: string): Promise { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); return new Promise((resolve) => { rl.question(chalk.cyan(question), (answer) => { rl.close(); resolve(answer); }); }); } main().catch((error) => { console.error(chalk.red(`Fatal error: ${error.message}`)); process.exit(1); });