Skip to main content

hatchery_node/
provider_inventory.rs

1//! Provider inventory: which provider CLIs this node can run and which models each one
2//! exposes, read from the CLI itself (or its own config). Nothing is invented: a provider whose
3//! CLI does not list models reports only what its help text / config names.
4//!
5//! - codex: `codex debug models` (JSON catalog; entries with `visibility = "list"`).
6//! - grok: `grok models` (text list; `*` marks the default).
7//! - claude: the model aliases its `--help` names for `--model`, plus `model` from
8//!   `~/.claude/settings.json`.
9//! - kimi: `[models.<alias>]` and `default_model` from `~/.kimi/config.toml`
10//!   or `~/.kimi-code/config.toml`.
11
12use serde::Serialize;
13use std::io::Read;
14use std::path::{Path, PathBuf};
15use std::process::{Command, Stdio};
16use std::time::{Duration, Instant};
17
18#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
19pub struct ModelInfo {
20    pub id: String,
21    #[serde(skip_serializing_if = "Vec::is_empty")]
22    pub efforts: Vec<String>,
23    #[serde(skip_serializing_if = "std::ops::Not::not")]
24    pub default: bool,
25}
26
27#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
28pub struct ProviderInfo {
29    pub provider: String,
30    /// Where the list came from (`cli`, `help`, `config`).
31    pub source: String,
32    pub models: Vec<ModelInfo>,
33}
34
35pub const PROVIDERS: &[&str] = &["claude", "codex", "grok", "kimi"];
36
37fn which(bin: &str) -> Option<PathBuf> {
38    let path = std::env::var_os("PATH")?;
39    // Windows PATHEXT. Prefer a real launcher over an extensionless npm shim
40    // in the same directory: `Command` cannot execute that shim.
41    let exts: &[&str] = if cfg!(windows) { &[".exe", ".cmd", ".bat", ""] } else { &[""] };
42    std::env::split_paths(&path).find_map(|dir| {
43        exts.iter().map(|ext| dir.join(format!("{bin}{ext}"))).find(|p| p.is_file())
44    })
45}
46
47/// Run `bin args` with a deadline; stdout as text (stderr dropped, no stdin).
48fn run(bin: &Path, args: &[&str], deadline: Duration) -> Option<String> {
49    let mut child = Command::new(bin).args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?;
50    let mut out = child.stdout.take()?;
51    let reader = std::thread::spawn(move || {
52        let mut buf = Vec::new();
53        let _ = out.by_ref().take(4 << 20).read_to_end(&mut buf);
54        buf
55    });
56    let start = Instant::now();
57    loop {
58        match child.try_wait() {
59            Ok(Some(_)) => break,
60            Ok(None) if start.elapsed() < deadline => std::thread::sleep(Duration::from_millis(50)),
61            _ => {
62                let _ = child.kill();
63                let _ = child.wait();
64                return None;
65            }
66        }
67    }
68    String::from_utf8(reader.join().ok()?).ok()
69}
70
71/// Model ids may carry a vendor path or tag (`kimi-code/k3`, `name:tag`, `x@v`); entries that
72/// fail are dropped one by one, never the whole provider.
73fn ok_id(s: &str) -> bool {
74    !s.is_empty() && s.len() <= 128 && !s.starts_with(['/', ':']) && !s.contains("..") && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.[]/:@".contains(&b))
75}
76
77pub fn parse_codex(json: &str) -> Vec<ModelInfo> {
78    let Ok(v) = serde_json::from_str::<serde_json::Value>(json) else { return Vec::new() };
79    let list = v.get("models").and_then(|m| m.as_array()).cloned().unwrap_or_default();
80    list.iter()
81        .filter(|m| m.get("visibility").and_then(|x| x.as_str()).is_none_or(|x| x == "list"))
82        .filter_map(|m| {
83            let id = m.get("slug").or_else(|| m.get("id")).and_then(|x| x.as_str())?;
84            ok_id(id).then(|| ModelInfo {
85                id: id.to_owned(),
86                efforts: m
87                    .get("supported_reasoning_levels")
88                    .and_then(|l| l.as_array())
89                    .map(|l| l.iter().filter_map(|e| e.get("effort").and_then(|x| x.as_str())).filter(|e| ok_id(e)).map(str::to_owned).collect())
90                    .unwrap_or_default(),
91                default: false,
92            })
93        })
94        .collect()
95}
96
97pub fn parse_grok(text: &str) -> Vec<ModelInfo> {
98    text.lines()
99        .filter_map(|l| {
100            let t = l.trim_start();
101            let (default, rest) = if let Some(r) = t.strip_prefix("* ") { (true, r) } else { (false, t.strip_prefix("- ")?) };
102            let id = rest.split_whitespace().next()?;
103            ok_id(id).then(|| ModelInfo { id: id.to_owned(), efforts: Vec::new(), default })
104        })
105        .collect()
106}
107
108/// Quoted aliases in the `--model` paragraph of `claude --help`.
109pub fn parse_claude_help(help: &str) -> Vec<ModelInfo> {
110    let Some(start) = help.find("--model") else { return Vec::new() };
111    let para: String = help[start..].lines().take_while(|l| !l.trim().is_empty()).take(8).enumerate()
112        .filter(|(i, l)| *i == 0 || !l.trim_start().starts_with("--"))
113        .map(|(_, l)| l)
114        .collect::<Vec<_>>()
115        .join(" ");
116    let mut out: Vec<ModelInfo> = Vec::new();
117    for (i, part) in para.split('\'').enumerate() {
118        if i % 2 == 1 && ok_id(part) && !out.iter().any(|m| m.id == part) {
119            out.push(ModelInfo { id: part.to_owned(), efforts: Vec::new(), default: false });
120        }
121    }
122    out
123}
124
125pub fn parse_kimi_config(toml_text: &str) -> Vec<ModelInfo> {
126    let mut out = Vec::new();
127    let mut default = None;
128    for line in toml_text.lines() {
129        let l = line.trim();
130        if let Some(rest) = l.strip_prefix("[models.").and_then(|r| r.strip_suffix(']')) {
131            let id = rest.trim_matches('"');
132            if ok_id(id) {
133                out.push(ModelInfo { id: id.to_owned(), efforts: Vec::new(), default: false });
134            }
135        } else if let Some(v) = l.strip_prefix("default_model") {
136            default = v.trim_start().strip_prefix('=').map(|v| v.trim().trim_matches('"').to_owned());
137        }
138    }
139    for m in &mut out {
140        m.default = default.as_deref() == Some(m.id.as_str());
141    }
142    out
143}
144
145fn home() -> Option<PathBuf> {
146    std::env::var_os("HOME")
147        .or_else(|| std::env::var_os("USERPROFILE"))
148        .map(PathBuf::from)
149        .filter(|p| !p.as_os_str().is_empty())
150}
151
152fn provider_homes() -> Vec<PathBuf> {
153    let mut homes = Vec::new();
154    if let Some(h) = home() {
155        homes.push(h);
156    }
157    if let Some(extra) = std::env::var_os("HATCHERY_PROVIDER_HOMES") {
158        homes.extend(std::env::split_paths(&extra));
159    }
160    homes
161}
162
163fn kimi_config_text() -> Option<String> {
164    let home = home()?;
165    for rel in [".kimi/config.toml", ".kimi-code/config.toml"] {
166        if let Ok(text) = std::fs::read_to_string(home.join(rel)) {
167            if !text.is_empty() {
168                return Some(text);
169            }
170        }
171    }
172    None
173}
174
175/// Detect one provider; `None` when its CLI is not on PATH and not in a standard install directory.
176pub fn detect(provider: &str) -> Option<ProviderInfo> {
177    let homes = provider_homes();
178    let deadline = Duration::from_secs(20);
179    let (bin, source, models) = match provider {
180        "codex" => {
181            let bin = resolve_binary(provider, &homes)?;
182            let m = run(&bin, &["debug", "models"], deadline).map(|s| parse_codex(&s)).unwrap_or_default();
183            (bin, "cli", m)
184        }
185        "grok" => {
186            let bin = resolve_binary(provider, &homes)?;
187            let m = run(&bin, &["models"], deadline).map(|s| parse_grok(&s)).unwrap_or_default();
188            (bin, "cli", m)
189        }
190        "claude" => {
191            let bin = resolve_binary(provider, &homes)?;
192            let mut m = run(&bin, &["--help"], deadline).map(|s| parse_claude_help(&s)).unwrap_or_default();
193            if let Some(set) = home().and_then(|h| std::fs::read(h.join(".claude/settings.json")).ok()).and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok()) {
194                if let Some(id) = set.get("model").and_then(|x| x.as_str()).filter(|s| ok_id(s)) {
195                    match m.iter_mut().find(|x| x.id == id) {
196                        Some(x) => x.default = true,
197                        None => m.push(ModelInfo { id: id.to_owned(), efforts: Vec::new(), default: true }),
198                    }
199                }
200            }
201            (bin, "help", m)
202        }
203        "kimi" => {
204            let bin = resolve_binary(provider, &homes)?;
205            let m = kimi_config_text().map(|s| parse_kimi_config(&s)).unwrap_or_default();
206            (bin, "config", m)
207        }
208        _ => return None,
209    };
210    let _ = bin;
211    Some(ProviderInfo { provider: provider.to_owned(), source: source.to_owned(), models })
212}
213
214/// All providers whose CLI this node can run.
215pub fn detect_all() -> Vec<ProviderInfo> {
216    PROVIDERS.iter().filter_map(|p| detect(p)).collect()
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use std::path::{Path, PathBuf};
223
224    #[test]
225    fn parses_codex_catalog() {
226        let j = r#"{"models":[{"slug":"m-a","visibility":"list","supported_reasoning_levels":[{"effort":"low"},{"effort":"high"}]},{"slug":"m-hidden","visibility":"hide"},{"slug":"bad slug","visibility":"list"}]}"#;
227        let m = parse_codex(j);
228        assert_eq!(m.len(), 1);
229        assert_eq!(m[0].id, "m-a");
230        assert_eq!(m[0].efforts, ["low", "high"]);
231        assert!(parse_codex("nope").is_empty());
232    }
233
234    #[test]
235    fn parses_grok_list() {
236        let m = parse_grok("You are not authenticated.\n\nDefault model: g-1\n\nAvailable models:\n  * g-1 (default)\n  - g-0\n");
237        assert_eq!(m.iter().map(|x| (x.id.as_str(), x.default)).collect::<Vec<_>>(), [("g-1", true), ("g-0", false)]);
238    }
239
240    #[test]
241    fn parses_claude_help_aliases() {
242        let h = "  --mcp-config <c>    x\n  --model <model>     Model for the current session. Provide\n                      an alias for the latest model (e.g.\n                      'a1', 'b2', or 'c3') or a\n                      model's full name.\n  --name <n>          y 'zz'\n";
243        let m = parse_claude_help(h);
244        assert_eq!(m.iter().map(|x| x.id.as_str()).collect::<Vec<_>>(), ["a1", "b2", "c3"]);
245    }
246
247    #[test]
248    fn parses_kimi_config() {
249        let m = parse_kimi_config(
250            "default_model = \"k2\"\n[models.k1]\nprovider = \"x\"\n[models.\"k2\"]\n[models.\"kimi-code/k3\"]\n",
251        );
252        assert_eq!(
253            m.iter().map(|x| (x.id.as_str(), x.default)).collect::<Vec<_>>(),
254            [("k1", false), ("k2", true), ("kimi-code/k3", false)]
255        );
256    }
257
258    #[test]
259    fn typical_install_dirs_are_relative_to_any_home() {
260        let home = Path::new("/tmp/any-user");
261        let dirs: Vec<PathBuf> = TYPICAL_REL.iter().map(|rel| home.join(rel)).collect();
262        assert!(dirs.iter().any(|d| d.ends_with(Path::new(".local").join("bin"))));
263        assert!(dirs.iter().any(|d| d.ends_with(Path::new(".grok").join("bin"))));
264        assert!(dirs.iter().any(|d| d.ends_with(Path::new(".kimi-code").join("bin"))));
265        assert!(dirs.iter().any(|d| d.ends_with(Path::new(".claude").join("local"))));
266        assert!(dirs.iter().any(|d| d.ends_with(Path::new("AppData").join("Roaming").join("npm"))));
267    }
268
269    /// npm ships an extensionless shim next to `codex.cmd`. `Command` cannot run the shim.
270    #[cfg(windows)]
271    #[test]
272    fn cmd_wins_over_extensionless_shim_in_the_same_directory() {
273        let d = std::env::temp_dir().join(format!("hatchery-prov-{}", std::process::id()));
274        let _ = std::fs::remove_dir_all(&d);
275        std::fs::create_dir_all(&d).unwrap();
276        std::fs::write(d.join("codex"), b"shim").unwrap();
277        std::fs::write(d.join("codex.cmd"), b"@echo off\r\necho 1.2.3\r\n").unwrap();
278        let got = find_named("codex", &[d.clone()]).expect("codex.cmd");
279        let _ = std::fs::remove_dir_all(&d);
280        assert_eq!(got, d.join("codex.cmd"));
281    }
282}
283
284/// Binary names a provider may be installed under, in preference order. The canonical id
285/// (what g4a launches) comes first. Override per provider with `HATCHERY_PROVIDER_BIN_<ID>`
286/// (absolute path or a name on PATH).
287pub fn aliases(provider: &str) -> &'static [&'static str] {
288    match provider {
289        "kimi" => &["kimi", "kimi-cli", "kimi-code"],
290        "claude" => &["claude", "claude-code"],
291        "codex" => &["codex"],
292        "grok" => &["grok"],
293        _ => &[],
294    }
295}
296
297/// A candidate is usable only if `--version` answers and it is not a retired stub
298/// (kimi-cli 1.x prints "no longer maintained" and does nothing).
299fn usable(bin: &Path) -> bool {
300    let Some(out) = run(bin, &["--version"], Duration::from_secs(5)) else { return false };
301    let help = run(bin, &["--help"], Duration::from_secs(5)).unwrap_or_default();
302    !out.trim().is_empty() && !help.contains("no longer maintained") && !out.contains("no longer maintained")
303}
304
305/// Per-user directories a provider CLI is installed into. Relative to the home
306/// directory, the same list on every machine.
307const TYPICAL_REL: &[&str] = &[
308    ".local/bin",
309    ".claude/local",
310    ".grok/bin",
311    ".kimi-code/bin",
312    ".npm-global/bin",
313    ".volta/bin",
314    "AppData/Roaming/npm",
315    "scoop/shims",
316];
317
318fn push_unique(dirs: &mut Vec<PathBuf>, dir: PathBuf) {
319    if dir.as_os_str().is_empty() || dirs.iter().any(|d| d == &dir) {
320        return;
321    }
322    dirs.push(dir);
323}
324
325/// `PATH`, then the standard per-user install directories. No host-specific paths.
326pub(crate) fn search_dirs(extra_homes: &[PathBuf]) -> Vec<PathBuf> {
327    let mut dirs = Vec::new();
328    if let Some(path) = std::env::var_os("PATH") {
329        for dir in std::env::split_paths(&path) {
330            push_unique(&mut dirs, dir);
331        }
332    }
333    let mut homes = Vec::new();
334    if let Some(h) = home() {
335        homes.push(h);
336    }
337    for h in extra_homes {
338        if !homes.iter().any(|e| e == h) {
339            homes.push(h.clone());
340        }
341    }
342    for h in &homes {
343        for rel in TYPICAL_REL {
344            push_unique(&mut dirs, h.join(rel));
345        }
346    }
347    if let Some(appdata) = std::env::var_os("APPDATA") {
348        push_unique(&mut dirs, PathBuf::from(appdata).join("npm"));
349    }
350    if let Some(local) = std::env::var_os("LOCALAPPDATA") {
351        push_unique(&mut dirs, PathBuf::from(local).join("Microsoft").join("WinGet").join("Links"));
352    }
353    dirs
354}
355
356/// First usable `name` in `dirs`. On Windows, `.exe` then `.cmd` then `.bat`, and the
357/// extensionless npm shim only after those: `Command` cannot execute the shim.
358fn find_named(name: &str, dirs: &[PathBuf]) -> Option<PathBuf> {
359    let exts: &[&str] = if cfg!(windows) { &[".exe", ".cmd", ".bat", ""] } else { &[""] };
360    for dir in dirs {
361        for ext in exts {
362            let p = dir.join(format!("{name}{ext}"));
363            if p.is_file() && usable(&p) {
364                return Some(p);
365            }
366        }
367    }
368    None
369}
370
371/// Resolve the binary for `provider`: optional `HATCHERY_PROVIDER_BIN_<ID>`, then each
372/// alias on PATH and in the standard install directories.
373pub fn resolve_binary(provider: &str, extra_homes: &[PathBuf]) -> Option<PathBuf> {
374    let key = format!("HATCHERY_PROVIDER_BIN_{}", provider.to_ascii_uppercase());
375    if let Some(v) = std::env::var_os(&key).filter(|v| !v.is_empty()) {
376        let p = PathBuf::from(&v);
377        let p = if p.is_absolute() { Some(p) } else { which(&p.to_string_lossy()) };
378        return p.filter(|p| usable(p));
379    }
380    let dirs = search_dirs(extra_homes);
381    aliases(provider).iter().find_map(|name| find_named(name, &dirs))
382}
383
384/// Make every resolvable provider launchable under its canonical name: a node-private shim
385/// dir with `<id> -> <resolved binary>` symlinks, prepended to PATH (children inherit it).
386#[cfg(unix)]
387pub fn install_shims(shim_dir: &Path, extra_homes: &[PathBuf]) -> Vec<(String, PathBuf)> {
388    let mut done = Vec::new();
389    if std::fs::create_dir_all(shim_dir).is_err() {
390        return done;
391    }
392    for p in PROVIDERS {
393        let link = shim_dir.join(p);
394        let _ = std::fs::remove_file(&link);
395        // Already launchable under its own name and usable: nothing to do.
396        if which(p).filter(|b| usable(b)).is_some() {
397            continue;
398        }
399        if let Some(bin) = resolve_binary(p, extra_homes) {
400            if std::os::unix::fs::symlink(&bin, &link).is_ok() {
401                done.push((p.to_string(), bin));
402            }
403        }
404    }
405    let old = std::env::var_os("PATH").unwrap_or_default();
406    let mut parts = vec![shim_dir.to_path_buf()];
407    parts.extend(std::env::split_paths(&old).filter(|d| d != shim_dir));
408    if let Ok(joined) = std::env::join_paths(parts) {
409        std::env::set_var("PATH", joined);
410    }
411    done
412}
413
414#[cfg(all(test, unix))]
415mod alias_tests {
416    use super::*;
417    use std::os::unix::fs::PermissionsExt;
418
419    fn script(dir: &Path, name: &str, body: &str) -> PathBuf {
420        let p = dir.join(name);
421        std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
422        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
423        p
424    }
425
426    #[test]
427    fn retired_stub_is_skipped_and_vendor_install_is_found() {
428        let d = std::env::temp_dir().join(format!("alias-{}", std::process::id()));
429        let _ = std::fs::remove_dir_all(&d);
430        std::fs::create_dir_all(d.join("home/.kimi-code/bin")).unwrap();
431        let stub = script(&d, "kimi-cli", "echo 'kimi-cli is no longer maintained.'");
432        assert!(!usable(&stub));
433        let real = script(&d.join("home/.kimi-code/bin"), "kimi", "echo 2.1.1");
434        assert!(usable(&real));
435        // PATH may already carry a real kimi on dev boxes; either way the stub is never chosen.
436        let got = resolve_binary("kimi", &[d.join("home")]).expect("kimi resolved");
437        assert_ne!(got, stub);
438    }
439}