orch-cli 0.119.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! What orch knows about each agent name. A fact about a name is a row here, and a fact about
//! an output format is a method on its [`AgentRunner`]. A wrapper script around a CLI has no row:
//! the config names it as `runner:process`, such as `claude:kimi`

use super::AgentRunner;
use super::claude::ClaudeRunner;
use super::codex::CodexRunner;
use super::grok::GrokRunner;
use super::opencode::OpenCodeRunner;
use crate::config;
use crate::engine;
use std::path::{Path, PathBuf};

/// The runner type that builds an agent's command line and reads its output
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Cli {
    Claude,
    Codex,
    OpenCode,
    Grok,
}

/// One agent name and the facts that belong to the name
#[derive(Debug, Clone, Copy)]
pub struct AgentSpec {
    name: &'static str,
    cli: Cli,
    /// Its runner takes a binary name, so a wrapper script can stand in for the CLI
    wraps: bool,
    /// The CLI takes `--session-id` for a new session and `--resume` to continue it
    pub sessions: bool,
    /// It runs Claude Code's CLI, and so honours a tool allowlist
    pub claude_compatible: bool,
    /// Env vars that hold the login, so a set one counts as signed in
    pub login_env: &'static [&'static str],
    /// Arguments of a status command that exits without opening a session
    pub login_status: Option<&'static [&'static str]>,
    /// Credential files, each as path segments under the home directory
    credential_files: &'static [&'static [&'static str]],
    /// A folder under `$XDG_DATA_HOME` and `$XDG_CONFIG_HOME` that also holds an `auth.json`
    pub xdg_auth_dir: Option<&'static str>,
}

const NO_LOGIN: AgentSpec = AgentSpec {
    name: "",
    cli: Cli::Claude,
    wraps: false,
    sessions: false,
    claude_compatible: false,
    login_env: &[],
    login_status: None,
    credential_files: &[],
    xdg_auth_dir: None,
};

const AGENTS: &[AgentSpec] = &[
    AgentSpec {
        name: "claude",
        wraps: true,
        sessions: true,
        claude_compatible: true,
        login_env: &["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"],
        login_status: Some(&["auth", "status", "--text"]),
        credential_files: &[&[".claude", ".credentials.json"]],
        ..NO_LOGIN
    },
    AgentSpec {
        name: "codex",
        cli: Cli::Codex,
        login_env: &["OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_ACCESS_TOKEN"],
        login_status: Some(&["login", "status"]),
        credential_files: &[&[".codex", "auth.json"]],
        ..NO_LOGIN
    },
    AgentSpec {
        name: "opencode",
        cli: Cli::OpenCode,
        credential_files: &[
            &[".local", "share", "opencode", "auth.json"],
            &[".config", "opencode", "auth.json"],
        ],
        xdg_auth_dir: Some("opencode"),
        ..NO_LOGIN
    },
    AgentSpec {
        name: "grok",
        cli: Cli::Grok,
        sessions: true,
        login_env: &["XAI_API_KEY"],
        credential_files: &[&[".grok", "auth.json"]],
        ..NO_LOGIN
    },
];

impl AgentSpec {
    /// The credential files under `home`
    pub fn credential_paths(&self, home: &Path) -> Vec<PathBuf> {
        self.credential_files
            .iter()
            .map(|segments| {
                segments
                    .iter()
                    .fold(home.to_path_buf(), |path, s| path.join(s))
            })
            .collect()
    }

    fn runner(&self, binary: &str) -> Box<dyn AgentRunner> {
        match self.cli {
            Cli::Claude => Box::new(claude_runner(binary)),
            Cli::Codex => Box::new(CodexRunner),
            Cli::OpenCode => Box::new(OpenCodeRunner::new()),
            Cli::Grok => Box::new(GrokRunner),
        }
    }

    /// This row for a wrapper script, which holds its own login
    fn wrapped(&self) -> Self {
        Self {
            login_env: &[],
            login_status: None,
            credential_files: &[],
            xdg_auth_dir: None,
            ..*self
        }
    }
}

/// Split an `agents:` entry into its runner and its process. `claude:kimi` is the `kimi` binary
/// driven as Claude Code. Any other text is one name, with no runner
pub fn parse_entry(entry: &str) -> (Option<&'static str>, &str) {
    if let Some((runner, process)) = entry.split_once(':')
        && let Some(row) = AGENTS.iter().find(|row| row.name == runner && row.wraps)
        && !process.is_empty()
    {
        return (Some(row.name), process);
    }
    (None, entry)
}

/// The row of the runner that `entries` names for the process `name`
fn wrapper_in(name: &str, entries: &[String]) -> Option<AgentSpec> {
    let runner = entries.iter().find_map(|entry| match parse_entry(entry) {
        (Some(runner), process) if process == name => Some(runner),
        _ => None,
    })?;
    AGENTS
        .iter()
        .find(|row| row.name == runner)
        .map(AgentSpec::wrapped)
}

fn spec_in(name: &str, entries: impl FnOnce() -> Vec<String>) -> Option<AgentSpec> {
    if let Some(row) = AGENTS.iter().find(|row| row.name == name) {
        return Some(*row);
    }
    wrapper_in(name, &entries())
}

/// The facts for `name`: its own row, or its runner's row when the config lists it as a
/// wrapper. `None` for a name orch does not know
pub fn spec(name: &str) -> Option<AgentSpec> {
    spec_in(name, engine::configured_agent_entries)
}

/// The runner for `name`. An unknown name gets the Claude Code runner under its own name
pub fn runner(name: &str) -> Box<dyn AgentRunner> {
    if let Some(spec) = spec(name) {
        return spec.runner(name);
    }
    tracing::warn!(
        agent = name,
        "unknown agent, using claude-compatible runner"
    );
    Box::new(claude_runner(name))
}

/// The Claude Code runner for `binary`, lenient about a missing result line when the config
/// lists the agent under `workflow.done_without_result`
fn claude_runner(binary: &str) -> ClaudeRunner {
    let lenient = config::get_list("workflow.done_without_result")
        .is_ok_and(|agents| agents.iter().any(|agent| agent == binary));
    ClaudeRunner::new(binary).done_without_result(lenient)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_name_is_listed_once() {
        for spec in AGENTS {
            let count = AGENTS
                .iter()
                .filter(|other| other.name == spec.name)
                .count();
            assert_eq!(count, 1, "{} is listed {count} times", spec.name);
            assert!(!spec.name.is_empty(), "a row has no name");
        }
    }

    #[test]
    fn a_known_name_gets_its_own_runner() {
        for spec in AGENTS {
            assert_eq!(runner(spec.name).name(), spec.name);
        }
        assert_eq!(runner("unknown-agent").name(), "unknown-agent");
    }

    #[test]
    fn an_unknown_name_has_no_row() {
        assert!(spec("unknown-agent").is_none());
        assert!(spec("").is_none());
    }

    #[test]
    fn an_entry_splits_into_runner_and_process() {
        assert_eq!(parse_entry("claude"), (None, "claude"));
        assert_eq!(parse_entry("claude:kimi"), (Some("claude"), "kimi"));
        assert_eq!(parse_entry("kimi"), (None, "kimi"));
        // Only a runner that takes a binary name can be wrapped
        assert_eq!(parse_entry("codex:mine"), (None, "codex:mine"));
        assert_eq!(parse_entry("nothing:mine"), (None, "nothing:mine"));
        assert_eq!(parse_entry("claude:"), (None, "claude:"));
    }

    #[test]
    fn a_wrapper_gets_its_runner_facts_and_no_login() {
        let entries = || vec!["claude".to_string(), "claude:kimi".to_string()];
        let kimi = spec_in("kimi", entries).expect("the config lists kimi");
        assert!(kimi.sessions && kimi.claude_compatible);
        assert!(kimi.login_env.is_empty());
        assert!(kimi.login_status.is_none());
        assert!(kimi.credential_paths(Path::new("/home/ada")).is_empty());
        assert_eq!(kimi.runner("kimi").name(), "kimi");

        // A bare name is not a wrapper, and a known CLI keeps its own row
        assert!(spec_in("minimax", || vec!["minimax".to_string()]).is_none());
        let claude = spec_in("claude", || vec!["claude:claude".to_string()]).unwrap();
        assert!(!claude.login_env.is_empty());
    }
}