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 stdin = std::io::stdin();
    let mut stdout = std::io::stdout();
    for line in stdin.lock().lines() {
        let line = line.map_err(|e| smith::error::SmithError::Session {
            code: "RPC_STDIN".to_string(),
            message: e.to_string(),
        })?;
        for response in handle_line(&state, &line) {
            stdout.write_all(response.as_bytes()).map_err(|e| {
                smith::error::SmithError::Session {
                    code: "RPC_STDOUT".to_string(),
                    message: e.to_string(),
                }
            })?;
        }
    }
    Ok(())
}

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)
}