Skip to main content

orch/engine/agents/
registry.rs

1//! What orch knows about each agent name. A fact about a name is a row here, and a fact about
2//! an output format is a method on its [`AgentRunner`]. A wrapper script around a CLI has no row:
3//! the config names it as `runner:process`, such as `claude:kimi`
4
5use super::AgentRunner;
6use super::claude::ClaudeRunner;
7use super::codex::CodexRunner;
8use super::grok::GrokRunner;
9use super::opencode::OpenCodeRunner;
10use crate::config;
11use crate::engine;
12use std::path::{Path, PathBuf};
13
14/// The runner type that builds an agent's command line and reads its output
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16enum Cli {
17    Claude,
18    Codex,
19    OpenCode,
20    Grok,
21}
22
23/// One agent name and the facts that belong to the name
24#[derive(Debug, Clone, Copy)]
25pub struct AgentSpec {
26    name: &'static str,
27    cli: Cli,
28    /// Its runner takes a binary name, so a wrapper script can stand in for the CLI
29    wraps: bool,
30    /// The CLI takes `--session-id` for a new session and `--resume` to continue it
31    pub sessions: bool,
32    /// It runs Claude Code's CLI, and so honours a tool allowlist
33    pub claude_compatible: bool,
34    /// Env vars that hold the login, so a set one counts as signed in
35    pub login_env: &'static [&'static str],
36    /// Arguments of a status command that exits without opening a session
37    pub login_status: Option<&'static [&'static str]>,
38    /// Credential files, each as path segments under the home directory
39    credential_files: &'static [&'static [&'static str]],
40    /// A folder under `$XDG_DATA_HOME` and `$XDG_CONFIG_HOME` that also holds an `auth.json`
41    pub xdg_auth_dir: Option<&'static str>,
42}
43
44const NO_LOGIN: AgentSpec = AgentSpec {
45    name: "",
46    cli: Cli::Claude,
47    wraps: false,
48    sessions: false,
49    claude_compatible: false,
50    login_env: &[],
51    login_status: None,
52    credential_files: &[],
53    xdg_auth_dir: None,
54};
55
56const AGENTS: &[AgentSpec] = &[
57    AgentSpec {
58        name: "claude",
59        wraps: true,
60        sessions: true,
61        claude_compatible: true,
62        login_env: &["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"],
63        login_status: Some(&["auth", "status", "--text"]),
64        credential_files: &[&[".claude", ".credentials.json"]],
65        ..NO_LOGIN
66    },
67    AgentSpec {
68        name: "codex",
69        cli: Cli::Codex,
70        login_env: &["OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_ACCESS_TOKEN"],
71        login_status: Some(&["login", "status"]),
72        credential_files: &[&[".codex", "auth.json"]],
73        ..NO_LOGIN
74    },
75    AgentSpec {
76        name: "opencode",
77        cli: Cli::OpenCode,
78        credential_files: &[
79            &[".local", "share", "opencode", "auth.json"],
80            &[".config", "opencode", "auth.json"],
81        ],
82        xdg_auth_dir: Some("opencode"),
83        ..NO_LOGIN
84    },
85    AgentSpec {
86        name: "grok",
87        cli: Cli::Grok,
88        sessions: true,
89        login_env: &["XAI_API_KEY"],
90        credential_files: &[&[".grok", "auth.json"]],
91        ..NO_LOGIN
92    },
93];
94
95impl AgentSpec {
96    /// The credential files under `home`
97    pub fn credential_paths(&self, home: &Path) -> Vec<PathBuf> {
98        self.credential_files
99            .iter()
100            .map(|segments| {
101                segments
102                    .iter()
103                    .fold(home.to_path_buf(), |path, s| path.join(s))
104            })
105            .collect()
106    }
107
108    fn runner(&self, binary: &str) -> Box<dyn AgentRunner> {
109        match self.cli {
110            Cli::Claude => Box::new(claude_runner(binary)),
111            Cli::Codex => Box::new(CodexRunner),
112            Cli::OpenCode => Box::new(OpenCodeRunner::new()),
113            Cli::Grok => Box::new(GrokRunner),
114        }
115    }
116
117    /// This row for a wrapper script, which holds its own login
118    fn wrapped(&self) -> Self {
119        Self {
120            login_env: &[],
121            login_status: None,
122            credential_files: &[],
123            xdg_auth_dir: None,
124            ..*self
125        }
126    }
127}
128
129/// Split an `agents:` entry into its runner and its process. `claude:kimi` is the `kimi` binary
130/// driven as Claude Code. Any other text is one name, with no runner
131pub fn parse_entry(entry: &str) -> (Option<&'static str>, &str) {
132    if let Some((runner, process)) = entry.split_once(':')
133        && let Some(row) = AGENTS.iter().find(|row| row.name == runner && row.wraps)
134        && !process.is_empty()
135    {
136        return (Some(row.name), process);
137    }
138    (None, entry)
139}
140
141/// The row of the runner that `entries` names for the process `name`
142fn wrapper_in(name: &str, entries: &[String]) -> Option<AgentSpec> {
143    let runner = entries.iter().find_map(|entry| match parse_entry(entry) {
144        (Some(runner), process) if process == name => Some(runner),
145        _ => None,
146    })?;
147    AGENTS
148        .iter()
149        .find(|row| row.name == runner)
150        .map(AgentSpec::wrapped)
151}
152
153fn spec_in(name: &str, entries: impl FnOnce() -> Vec<String>) -> Option<AgentSpec> {
154    if let Some(row) = AGENTS.iter().find(|row| row.name == name) {
155        return Some(*row);
156    }
157    wrapper_in(name, &entries())
158}
159
160/// The facts for `name`: its own row, or its runner's row when the config lists it as a
161/// wrapper. `None` for a name orch does not know
162pub fn spec(name: &str) -> Option<AgentSpec> {
163    spec_in(name, engine::configured_agent_entries)
164}
165
166/// The runner for `name`. An unknown name gets the Claude Code runner under its own name
167pub fn runner(name: &str) -> Box<dyn AgentRunner> {
168    if let Some(spec) = spec(name) {
169        return spec.runner(name);
170    }
171    tracing::warn!(
172        agent = name,
173        "unknown agent, using claude-compatible runner"
174    );
175    Box::new(claude_runner(name))
176}
177
178/// The Claude Code runner for `binary`, lenient about a missing result line when the config
179/// lists the agent under `workflow.done_without_result`
180fn claude_runner(binary: &str) -> ClaudeRunner {
181    let lenient = config::get_list("workflow.done_without_result")
182        .is_ok_and(|agents| agents.iter().any(|agent| agent == binary));
183    ClaudeRunner::new(binary).done_without_result(lenient)
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn every_name_is_listed_once() {
192        for spec in AGENTS {
193            let count = AGENTS
194                .iter()
195                .filter(|other| other.name == spec.name)
196                .count();
197            assert_eq!(count, 1, "{} is listed {count} times", spec.name);
198            assert!(!spec.name.is_empty(), "a row has no name");
199        }
200    }
201
202    #[test]
203    fn a_known_name_gets_its_own_runner() {
204        for spec in AGENTS {
205            assert_eq!(runner(spec.name).name(), spec.name);
206        }
207        assert_eq!(runner("unknown-agent").name(), "unknown-agent");
208    }
209
210    #[test]
211    fn an_unknown_name_has_no_row() {
212        assert!(spec("unknown-agent").is_none());
213        assert!(spec("").is_none());
214    }
215
216    #[test]
217    fn an_entry_splits_into_runner_and_process() {
218        assert_eq!(parse_entry("claude"), (None, "claude"));
219        assert_eq!(parse_entry("claude:kimi"), (Some("claude"), "kimi"));
220        assert_eq!(parse_entry("kimi"), (None, "kimi"));
221        // Only a runner that takes a binary name can be wrapped
222        assert_eq!(parse_entry("codex:mine"), (None, "codex:mine"));
223        assert_eq!(parse_entry("nothing:mine"), (None, "nothing:mine"));
224        assert_eq!(parse_entry("claude:"), (None, "claude:"));
225    }
226
227    #[test]
228    fn a_wrapper_gets_its_runner_facts_and_no_login() {
229        let entries = || vec!["claude".to_string(), "claude:kimi".to_string()];
230        let kimi = spec_in("kimi", entries).expect("the config lists kimi");
231        assert!(kimi.sessions && kimi.claude_compatible);
232        assert!(kimi.login_env.is_empty());
233        assert!(kimi.login_status.is_none());
234        assert!(kimi.credential_paths(Path::new("/home/ada")).is_empty());
235        assert_eq!(kimi.runner("kimi").name(), "kimi");
236
237        // A bare name is not a wrapper, and a known CLI keeps its own row
238        assert!(spec_in("minimax", || vec!["minimax".to_string()]).is_none());
239        let claude = spec_in("claude", || vec!["claude:claude".to_string()]).unwrap();
240        assert!(!claude.login_env.is_empty());
241    }
242}