repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

smith-cli/src/main.rs

Raw
File outline
#![forbid(unsafe_code)]
#![warn(missing_docs)]

//! Smith command-line entry point.
//!
//! Two modes today: `eval` runs one prompt through the agent and prints the
//! result; `rpc` speaks LF-delimited JSON-RPC on standard input and output.
//! Both use the same runtime assembly from `smith-harness`.

use clap::Parser;
use smith::error::Result;
use smith_harness::rpc::{RpcState, handle_line};
use smith_harness::runtime::{RuntimeConfig, RuntimeProvider, build_agent};
use std::io::{BufRead, Write};

/// Smith, a fast coding-agent runtime.
#[derive(Debug, Parser)]
#[command(name = "smith", version, about)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

/// Interface mode.
#[derive(Debug, Parser)]
enum Command {
    /// Run one prompt without the TUI.
    Eval {
        /// The prompt to run.
        prompt: String,
        /// Print the structured outcome as JSON.
        #[arg(long)]
        json: bool,
        /// Use the scripted mock provider instead of a real endpoint.
        #[arg(long)]
        r#mock: bool,
        /// OpenAI-compatible base URL.
        #[arg(long)]
        base_url: Option<String>,
        /// Model id; `mock-smith` when mocking.
        #[arg(long)]
        model: Option<String>,
    },
    /// Serve LF-delimited JSON-RPC on standard input and output.
    Rpc,
}

#[expect(clippy::print_stderr, reason = "the CLI reports failures on stderr")]
fn main() -> std::process::ExitCode {
    let cli = Cli::parse();
    let result = match cli.command {
        Command::Eval {
            prompt,
            json,
            r#mock,
            base_url,
            model,
        } => eval(&prompt, json, r#mock, base_url, model),
        Command::Rpc => rpc(),
    };
    match result {
        Ok(()) => std::process::ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("smith: {err}");
            std::process::ExitCode::FAILURE
        }
    }
}

fn provider(mock: bool, base_url: Option<String>, model: Option<String>) -> RuntimeProvider {
    if mock {
        return RuntimeProvider::Mock(vec![smith_harness::mock_text_reply(
            "mock provider: no model configured",
        )]);
    }
    let base = base_url.unwrap_or_else(|| "https://api.openai.com/v1".to_string());
    let model = model.unwrap_or_else(|| "gpt-5.1".to_string());
    RuntimeProvider::OpenAiCompatible {
        base_url: base,
        model,
    }
}

#[expect(clippy::print_stdout, reason = "eval output is the command's product")]
fn eval(
    prompt: &str,
    json: bool,
    mock: bool,
    base_url: Option<String>,
    model: Option<String>,
) -> Result<()> {
    let dir = session_dir()?;
    let config = RuntimeConfig {
        provider: provider(mock, base_url, model),
        workdir: dir.clone(),
        session_path: dir.join("eval.smh"),
    };
    let mut agent = build_agent(&config)?;
    let outcome = agent.run_turn(prompt)?;
    if json {
        println!(
            "{}",
            serde_json::json!({
                "text": outcome.text,
                "reason": format!("{:?}", outcome.reason),
                "cost": {
                    "input_tokens": outcome.cost.input_tokens,
                    "output_tokens": outcome.cost.output_tokens,
                },
            })
        );
    } else {
        println!("{}", outcome.text);
    }
    Ok(())
}

fn rpc() -> Result<()> {
    let dir = session_dir()?;
    let config = RuntimeConfig {
        provider: RuntimeProvider::Mock(vec![smith_harness::mock_text_reply(
            "rpc mock provider ready",
        )]),
        workdir: dir.clone(),
        session_path: dir.join("rpc.smh"),
    };
    let state = RpcState::new(build_agent(&config)?);
    let (input_tx, input_rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        for line in std::io::stdin().lock().lines() {
            if input_tx.send(Some(line)).is_err() {
                return;
            }
        }
        let _ = input_tx.send(None);
    });

    let mut stdout = std::io::stdout();
    let mut input_closed = false;
    loop {
        match input_rx.recv_timeout(std::time::Duration::from_millis(10)) {
            Ok(Some(Ok(line))) => {
                for response in handle_line(&state, &line) {
                    stdout
                        .write_all(response.as_bytes())
                        .map_err(rpc_stdout_error)?;
                }
            }
            Ok(Some(Err(error))) => {
                return Err(smith::error::SmithError::Session {
                    code: "RPC_STDIN".to_string(),
                    message: error.to_string(),
                });
            }
            Ok(None) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                input_closed = true;
            }
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
        }
        for response in state.drain_lines() {
            stdout
                .write_all(response.as_bytes())
                .map_err(rpc_stdout_error)?;
        }
        stdout.flush().map_err(rpc_stdout_error)?;
        if input_closed && state.is_settled() {
            for response in state.drain_lines() {
                stdout
                    .write_all(response.as_bytes())
                    .map_err(rpc_stdout_error)?;
            }
            return Ok(());
        }
    }
}

fn rpc_stdout_error(error: std::io::Error) -> smith::error::SmithError {
    let message = error.to_string();
    drop(error);
    smith::error::SmithError::Session {
        code: "RPC_STDOUT".to_string(),
        message,
    }
}

fn session_dir() -> Result<std::path::PathBuf> {
    let config = smith::config::Config::default_valid();
    let dir = std::path::PathBuf::from(config.session_dir).join("run");
    std::fs::create_dir_all(&dir).map_err(|e| smith::error::SmithError::Session {
        code: "RUNTIME_DIR".to_string(),
        message: e.to_string(),
    })?;
    Ok(dir)
}