Skip to main content

rinne_workers/adapters/
discover.rs

1//! Live model discovery from harness CLIs.
2//!
3//! Static `descriptor.models` ladders go stale when a harness renames or retires
4//! models (e.g. Grok dropped `grok-build` for `grok-4.5`). At registry build
5//! time we shell out to `<cli> models` and rebuild the cheap→strong ladder so
6//! routing never schedules a dead model id.
7
8use std::time::Duration;
9
10/// Models advertised by a harness CLI, after a successful `models` probe.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct DiscoveredModels {
13    /// Cheap → strong ladder for cascade / tier routing.
14    pub ladder: Vec<String>,
15    /// The CLI's default model id, when reported.
16    pub default: Option<String>,
17}
18
19impl DiscoveredModels {
20    /// Build a cheap→strong ladder: non-default models first (as listed), then
21    /// the default as the frontier rung when present.
22    pub fn from_listing(listed: Vec<String>, default: Option<String>) -> Self {
23        let mut ladder: Vec<String> = Vec::new();
24        // Non-default entries first (listing order ≈ preference/cheap first).
25        for m in &listed {
26            if default.as_deref() == Some(m.as_str()) {
27                continue;
28            }
29            if !ladder.iter().any(|x| x == m) {
30                ladder.push(m.clone());
31            }
32        }
33        // Default is the frontier rung for cascade / T3+ routing.
34        if let Some(d) = &default {
35            if !ladder.iter().any(|x| x == d) {
36                ladder.push(d.clone());
37            }
38        } else if ladder.is_empty() {
39            // No default and first loop skipped everything — use listing as-is.
40            for m in listed {
41                if !ladder.iter().any(|x| x == &m) {
42                    ladder.push(m);
43                }
44            }
45        }
46        Self { ladder, default }
47    }
48}
49
50/// Parse the free-form stdout of a `cli models` command.
51///
52/// Tolerates common shapes used by Grok Build and similar CLIs:
53/// ```text
54/// Default model: grok-4.5
55/// Available models:
56///   * grok-4.5 (default)
57///   - grok-composer-2.5-fast
58/// ```
59/// Also accepts bare one-id-per-line listings and JSON arrays of strings.
60pub fn parse_models_listing(stdout: &str) -> Option<DiscoveredModels> {
61    let trimmed = stdout.trim();
62    if trimmed.is_empty() {
63        return None;
64    }
65
66    // JSON array: ["a","b"] or {"models":[...],"default":"..."}
67    if let Some(d) = parse_json_models(trimmed) {
68        if !d.ladder.is_empty() {
69            return Some(d);
70        }
71    }
72
73    let mut default: Option<String> = None;
74    let mut listed: Vec<String> = Vec::new();
75
76    for line in stdout.lines() {
77        let line = line.trim();
78        if line.is_empty() {
79            continue;
80        }
81
82        // "Default model: foo" / "default: foo"
83        if let Some(rest) = line
84            .strip_prefix("Default model:")
85            .or_else(|| line.strip_prefix("default model:"))
86            .or_else(|| line.strip_prefix("Default:"))
87            .or_else(|| line.strip_prefix("default:"))
88        {
89            let id = clean_model_token(rest);
90            if !id.is_empty() {
91                default = Some(id);
92            }
93            continue;
94        }
95
96        // Bullet / star lines: "* id (default)" / "- id" / "• id"
97        let bullet = line
98            .strip_prefix("* ")
99            .or_else(|| line.strip_prefix("- "))
100            .or_else(|| line.strip_prefix("• "))
101            .or_else(|| line.strip_prefix("· "));
102        if let Some(rest) = bullet {
103            let is_default = rest.to_ascii_lowercase().contains("(default)");
104            let id = clean_model_token(rest);
105            if id.is_empty() || looks_like_header(&id) {
106                continue;
107            }
108            if is_default {
109                default = Some(id.clone());
110            }
111            if !listed.iter().any(|m| m == &id) {
112                listed.push(id);
113            }
114            continue;
115        }
116
117        // Bare model id line (no spaces, not a sentence).
118        if !line.contains(' ') && looks_like_model_id(line) {
119            let id = line.to_string();
120            if !listed.iter().any(|m| m == &id) {
121                listed.push(id);
122            }
123        }
124    }
125
126    if listed.is_empty() && default.is_none() {
127        return None;
128    }
129    Some(DiscoveredModels::from_listing(listed, default))
130}
131
132fn parse_json_models(s: &str) -> Option<DiscoveredModels> {
133    let v: serde_json::Value = serde_json::from_str(s).ok()?;
134    if let Some(arr) = v.as_array() {
135        let listed: Vec<String> = arr
136            .iter()
137            .filter_map(|x| x.as_str().map(str::to_string))
138            .collect();
139        if listed.is_empty() {
140            return None;
141        }
142        return Some(DiscoveredModels::from_listing(listed, None));
143    }
144    let listed: Vec<String> = v
145        .get("models")
146        .and_then(|m| m.as_array())
147        .map(|a| {
148            a.iter()
149                .filter_map(|x| {
150                    x.as_str()
151                        .map(str::to_string)
152                        .or_else(|| x.get("id").and_then(|i| i.as_str()).map(str::to_string))
153                })
154                .collect()
155        })
156        .unwrap_or_default();
157    let default = v
158        .get("default")
159        .or_else(|| v.get("default_model"))
160        .and_then(|d| d.as_str())
161        .map(str::to_string);
162    if listed.is_empty() && default.is_none() {
163        return None;
164    }
165    Some(DiscoveredModels::from_listing(listed, default))
166}
167
168fn clean_model_token(s: &str) -> String {
169    let s = s.trim();
170    // Strip trailing annotations: "(default)", "[fast]", etc.
171    let s = s.split_whitespace().next().unwrap_or(s);
172    s.trim_matches(|c: char| c == '`' || c == '"' || c == '\'' || c == ',')
173        .to_string()
174}
175
176fn looks_like_header(s: &str) -> bool {
177    let l = s.to_ascii_lowercase();
178    matches!(
179        l.as_str(),
180        "available" | "models" | "model" | "name" | "id" | "default"
181    ) || l.contains("available")
182}
183
184fn looks_like_model_id(s: &str) -> bool {
185    // Conservative: ids are kebab/snake/slash tokens, not prose.
186    !s.is_empty()
187        && s.len() < 80
188        && s.chars()
189            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':'))
190        && s.contains(|c: char| c.is_ascii_alphanumeric())
191}
192
193/// Run `<program> models` with a short timeout and parse the listing.
194///
195/// Returns `None` when the binary is missing, the subcommand fails with no
196/// usable stdout, or parsing finds no model ids — callers keep their static
197/// fallback ladder in that case.
198pub async fn discover_cli_models(program: &str) -> Option<DiscoveredModels> {
199    let mut cmd = tokio::process::Command::new(program);
200    cmd.arg("models")
201        .stdin(std::process::Stdio::null())
202        .stdout(std::process::Stdio::piped())
203        .stderr(std::process::Stdio::piped())
204        .kill_on_drop(true);
205
206    let fut = cmd.output();
207    let output = match tokio::time::timeout(Duration::from_secs(8), fut).await {
208        Ok(Ok(o)) => o,
209        _ => return None,
210    };
211
212    let stdout = String::from_utf8_lossy(&output.stdout);
213    let stderr = String::from_utf8_lossy(&output.stderr);
214    // Some CLIs print the listing on stderr when not fully logged in.
215    let text = if stdout.trim().is_empty() {
216        stderr.as_ref()
217    } else {
218        stdout.as_ref()
219    };
220    parse_models_listing(text)
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn parses_grok_models_listing() {
229        let out = r#"
230You are logged in with grok.com.
231
232Default model: grok-4.5
233
234Available models:
235  * grok-4.5 (default)
236  - grok-composer-2.5-fast
237"#;
238        let d = parse_models_listing(out).expect("parse");
239        assert_eq!(d.default.as_deref(), Some("grok-4.5"));
240        // Cheap first, default (frontier) last.
241        assert_eq!(
242            d.ladder,
243            vec!["grok-composer-2.5-fast".to_string(), "grok-4.5".to_string()]
244        );
245    }
246
247    #[test]
248    fn parses_json_array() {
249        let d = parse_models_listing(r#"["haiku","sonnet","opus"]"#).unwrap();
250        assert_eq!(d.ladder, vec!["haiku", "sonnet", "opus"]);
251    }
252
253    #[test]
254    fn from_listing_puts_default_last() {
255        let d = DiscoveredModels::from_listing(
256            vec!["a".into(), "b".into(), "c".into()],
257            Some("b".into()),
258        );
259        assert_eq!(d.ladder, vec!["a", "c", "b"]);
260    }
261
262    #[test]
263    fn empty_listing_is_none() {
264        assert!(parse_models_listing("Not logged in").is_none());
265        assert!(parse_models_listing("").is_none());
266    }
267}