Skip to main content

ertangle_adapter/
models.rs

1//! Available model lists per agent: built-in for Claude, queried from each CLI for others. Shared by TUI and daemon (Web UI).
2
3use ertangle_core::AgentKind;
4use tr::tr;
5
6/// Available models for Claude Code. The `claude` CLI has no subcommand to list models, so this is built-in:
7/// the first entries are aliases (always pointing to the latest in each family), followed by pinned version ids.
8/// Update here when new models launch; the Web UI fetches this same list via the daemon's `list_models`.
9pub const CLAUDE_MODELS: &[(&str, &str)] = &[
10    ("fable", ertangle_core::tr_noop!("最新 Fable")),
11    ("opus", ertangle_core::tr_noop!("最新 Opus")),
12    ("sonnet", ertangle_core::tr_noop!("最新 Sonnet")),
13    ("haiku", ertangle_core::tr_noop!("最新 Haiku")),
14    ("claude-fable-5-2", "Claude Fable 5.2"),
15    ("claude-fable-5-1", "Claude Fable 5.1"),
16    ("claude-fable-5", "Claude Fable 5"),
17    ("claude-opus-5-5", "Claude Opus 5.5"),
18    ("claude-opus-5", "Claude Opus 5"),
19    ("claude-opus-4-8", "Claude Opus 4.8"),
20    ("claude-opus-4-7", "Claude Opus 4.7"),
21    ("claude-opus-4-6", "Claude Opus 4.6"),
22    ("claude-sonnet-5-5", "Claude Sonnet 5.5"),
23    ("claude-sonnet-5", "Claude Sonnet 5"),
24    ("claude-sonnet-4-6", "Claude Sonnet 4.6"),
25    ("claude-haiku-5-5", "Claude Haiku 5.5"),
26    ("claude-haiku-4-5", "Claude Haiku 4.5"),
27];
28
29/// Default available models for Antigravity (agy).
30pub const ANTIGRAVITY_MODELS: &[(&str, &str)] = &[
31    ("gemini-4-neon", "Gemini 4 Neon"),
32    ("gemini-4-carbon", "Gemini 4 Carbon"),
33    ("gemini-4-argon", "Gemini 4 Argon"),
34    ("gemini-4-hydrogen", "Gemini 4 Hydrogen"),
35    ("gemini-3.8-flash", "Gemini 3.8 Flash"),
36    ("gemini-pro-orchestrator-neon", "Orchestrator (Neon)"),
37    ("gemini-pro-orchestrator", "Orchestrator (Carbon)"),
38    ("gemini-pro-orchestrator-argon", "Orchestrator (Argon)"),
39    ("claude-opus-5-5", "Claude Opus 5.5"),
40    ("claude-sonnet-5-5", "Claude Sonnet 5.5"),
41    ("gpt-oss-120b-medium", "GPT-OSS 120B (Medium)"),
42];
43
44/// Default available models for GitHub Copilot CLI (`copilot` has no `models` subcommand).
45/// Keep in sync with `MODEL_CATALOG.copilot` in `crates/ertangle-daemon/src/web/index.html`.
46pub const COPILOT_MODELS: &[(&str, &str)] = &[
47    ("auto", ertangle_core::tr_noop!("Copilot 自動選取")),
48    ("claude-sonnet-5.5", "Claude Sonnet 5.5"),
49    ("claude-opus-5.5", "Claude Opus 5.5"),
50    ("claude-haiku-5.5", "Claude Haiku 5.5"),
51    ("claude-fable-5.2", "Claude Fable 5.2"),
52    ("claude-sonnet-4.6", "Claude Sonnet 4.6"),
53    ("claude-haiku-4.5", "Claude Haiku 4.5"),
54    ("gpt-6.2-sol", "GPT-6.2 Sol"),
55    ("gpt-6.2-astra", "GPT-6.2 Astra"),
56    ("gpt-6.1-sol", "GPT-6.1 Sol"),
57    ("gpt-6.1-terra", "GPT-6.1 Terra"),
58    ("gpt-6-sol", "GPT-6 Sol"),
59    ("gpt-5.6-sol", "GPT-5.6 Sol"),
60    ("gpt-5.6-luna", "GPT-5.6 Luna"),
61    ("gpt-5.4", "GPT-5.4"),
62    ("gpt-5.4-nano", "GPT-5.4 nano"),
63    ("gemini-4-neon", "Gemini 4 Neon"),
64    ("gemini-4-carbon", "Gemini 4 Carbon"),
65    ("gemini-4-argon", "Gemini 4 Argon"),
66    ("gemini-4-hydrogen", "Gemini 4 Hydrogen"),
67    ("gemini-3.8-flash", "Gemini 3.8 Flash"),
68];
69
70/// Timeout for querying the model list.
71const QUERY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8);
72
73/// Output captured after a child process exits.
74#[derive(Debug, Default)]
75struct Captured {
76    stdout: String,
77    stderr: String,
78    /// Exit code; `None` if terminated by a signal.
79    code: Option<i32>,
80}
81
82/// Reason a command execution failed.
83#[derive(Debug)]
84enum CaptureError {
85    Spawn(std::io::Error),
86    Timeout,
87}
88
89/// Drain an entire pipe in the background to prevent full pipe buffers from stalling the child process.
90fn drain<R: std::io::Read + Send + 'static>(pipe: Option<R>) -> std::sync::mpsc::Receiver<String> {
91    let (tx, rx) = std::sync::mpsc::channel();
92    if let Some(mut pipe) = pipe {
93        std::thread::spawn(move || {
94            let mut bytes = Vec::new();
95            // Read as much remaining data from the pipe as possible, ignoring read and send errors.
96            let _ = pipe.read_to_end(&mut bytes);
97            let _ = tx.send(String::from_utf8_lossy(&bytes).into_owned());
98        });
99    }
100    rx
101}
102
103/// Run a command within `timeout` and capture stdout, stderr, and exit code.
104/// Output must be drained concurrently while waiting: `codex debug models` can output hundreds of KB,
105/// and waiting for exit before reading would fill the pipe, stall the process until timeout, and yield an empty list.
106/// Environment variables listed in `remove` are excluded from the child process.
107fn capture(
108    bin: &str,
109    args: &[&str],
110    remove: &[&str],
111    timeout: std::time::Duration,
112) -> Result<Captured, CaptureError> {
113    use std::process::Stdio;
114
115    let mut command = std::process::Command::new(bin);
116    for k in remove {
117        command.env_remove(k);
118    }
119    let mut child = command
120        .args(args)
121        .stdin(Stdio::null())
122        .stdout(Stdio::piped())
123        .stderr(Stdio::piped())
124        .spawn()
125        .map_err(CaptureError::Spawn)?;
126    let stdout = drain(child.stdout.take());
127    let stderr = drain(child.stderr.take());
128    let deadline = std::time::Instant::now() + timeout;
129    let status = loop {
130        match child.try_wait() {
131            Ok(Some(status)) => break status,
132            Ok(None) if std::time::Instant::now() < deadline => {
133                std::thread::sleep(std::time::Duration::from_millis(50));
134            }
135            _ => {
136                // Force-kill and reap the child process on timeout, ignoring errors.
137                let _ = child.kill();
138                let _ = child.wait();
139                return Err(CaptureError::Timeout);
140            }
141        }
142    };
143    let grace = std::time::Duration::from_secs(1);
144    Ok(Captured {
145        stdout: stdout.recv_timeout(grace).unwrap_or_default(),
146        stderr: stderr.recv_timeout(grace).unwrap_or_default(),
147        code: status.code(),
148    })
149}
150
151/// Pick the most informative line from stderr: skip glog INFO lines (`I1123 ...`), spinners, and blank lines;
152/// prefer lines containing error keywords, otherwise take the last line.
153fn stderr_summary(stderr: &str) -> Option<String> {
154    let lines: Vec<&str> = stderr
155        .split(['\n', '\r'])
156        .map(|l| l.trim_matches(|c: char| c.is_whitespace() || c == '\x1b'))
157        .map(|l| l.strip_prefix("[K").unwrap_or(l).trim())
158        .filter(|l| !l.is_empty())
159        .filter(|l| !is_glog_info(l))
160        .filter(|l| !l.contains("Fetching available models"))
161        .collect();
162    let pick = lines
163        .iter()
164        .rev()
165        .find(|l| looks_like_error(l))
166        .or_else(|| lines.last())?;
167    let short: String = pick.chars().take(200).collect();
168    Some(short)
169}
170
171/// glog INFO line, e.g. `I1123 14:35:36.832595 155 http_helpers.go:760] ...`.
172fn is_glog_info(line: &str) -> bool {
173    let mut chars = line.chars();
174    chars.next() == Some('I') && chars.take(4).all(|c| c.is_ascii_digit())
175}
176
177/// Line that looks like an error or login/auth issue.
178fn looks_like_error(line: &str) -> bool {
179    let lower = line.to_ascii_lowercase();
180    let glog_error = matches!(line.chars().next(), Some('E' | 'F'))
181        && line.chars().skip(1).take(4).all(|c| c.is_ascii_digit());
182    glog_error
183        || [
184            "error",
185            "fail",
186            "auth",
187            "login",
188            "log in",
189            "sign in",
190            "credential",
191            "token",
192            "permission denied",
193            "401",
194            "403",
195        ]
196        .iter()
197        .any(|k| lower.contains(k))
198}
199
200/// Result of querying the model list: when `problem` is set, the list may be incomplete (e.g., not logged in or expired), and the user should be informed.
201#[derive(Debug, Default, Clone, PartialEq, Eq)]
202pub struct ModelQuery {
203    /// `(display_label, id)`.
204    pub models: Vec<(String, String)>,
205    /// User-facing problem description.
206    pub problem: Option<String>,
207}
208
209/// Build a problem description from the query result; returns `None` if there is no problem.
210fn diagnose(
211    bin: &str,
212    cmd: &str,
213    result: &Result<Captured, CaptureError>,
214    parsed: usize,
215) -> Option<String> {
216    let login_hint = tr!(
217        "若尚未登入或登入已過期,請先在終端機執行 `{bin}` 重新登入",
218        bin = bin
219    );
220    match result {
221        Err(CaptureError::Spawn(e)) => Some(tr!("無法執行 `{cmd}`:{err}", cmd = cmd, err = e)),
222        Err(CaptureError::Timeout) => Some(tr!(
223            "`{cmd}` 超過 {secs} 秒沒有回應;{hint}",
224            cmd = cmd,
225            secs = QUERY_TIMEOUT.as_secs(),
226            hint = login_hint
227        )),
228        Ok(c) => {
229            let detail = stderr_summary(&c.stderr);
230            let failed = c.code != Some(0);
231            let suspicious = detail.as_deref().is_some_and(looks_like_error);
232            if !failed && parsed > 0 && !suspicious {
233                return None;
234            }
235            let head = if failed {
236                match c.code {
237                    Some(code) => tr!("`{cmd}` 失敗 (結束碼 {code})", cmd = cmd, code = code),
238                    None => tr!("`{cmd}` 被中斷", cmd = cmd),
239                }
240            } else if parsed == 0 {
241                tr!("`{cmd}` 沒有列出任何 model", cmd = cmd)
242            } else {
243                tr!("`{cmd}` 回報錯誤,清單可能不完整", cmd = cmd)
244            };
245            Some(match detail {
246                Some(d) => tr!(
247                    "{head}:{detail};{hint}",
248                    head = head,
249                    detail = d,
250                    hint = login_hint
251                ),
252                None => tr!("{head};{hint}", head = head, hint = login_hint),
253            })
254        }
255    }
256}
257
258/// Query the agent CLI for raw available models (`opencode models`, `agy models`, `codex debug models`), waiting up to 8 seconds.
259/// Does not merge `antigravity` effort variants; attaches a description if the query fails or the CLI reports an error.
260pub fn query_raw_models_detailed(kind: &AgentKind) -> ModelQuery {
261    let (bin, args): (&str, &[&str]) = match kind {
262        AgentKind::OpenCode => ("opencode", &["models"]),
263        AgentKind::Antigravity => ("agy", &["models"]),
264        AgentKind::Codex => ("codex", &["debug", "models"]),
265        _ => return ModelQuery::default(),
266    };
267    let cmd = std::iter::once(bin)
268        .chain(args.iter().copied())
269        .collect::<Vec<_>>()
270        .join(" ");
271    let result = capture(bin, args, crate::env_removals(kind), QUERY_TIMEOUT);
272    let models = match (&result, kind) {
273        (Ok(c), AgentKind::Codex) => parse_codex_models(&c.stdout),
274        (Ok(c), _) => parse_models(&c.stdout),
275        (Err(_), _) => Vec::new(),
276    };
277    let problem = diagnose(bin, &cmd, &result, models.len());
278    ModelQuery { models, problem }
279}
280
281/// Same as [`query_raw_models_detailed`], returning only the list.
282pub fn query_raw_models(kind: &AgentKind) -> Vec<(String, String)> {
283    query_raw_models_detailed(kind).models
284}
285
286/// Same as [`query_models`], but includes any query problem description.
287pub fn query_models_detailed(kind: &AgentKind) -> ModelQuery {
288    let q = query_raw_models_detailed(kind);
289    match kind {
290        AgentKind::Antigravity => ModelQuery {
291            models: split_effort_variants(q.models),
292            problem: q.problem,
293        },
294        _ => q,
295    }
296}
297
298/// Query the agent CLI for available models (`opencode models`, `agy models`), waiting up to 8 seconds.
299/// Each output line has the model id in the first column, followed by the display name (tab-separated).
300/// agy's list embeds effort in the model id (`xxx-high`), whereas ACP separates model and effort, so variants are merged here.
301pub fn query_models(kind: &AgentKind) -> Vec<(String, String)> {
302    query_models_detailed(kind).models
303}
304
305/// Merge combined "model + effort" ids such as `base-low/-medium/-high/-xhigh/-max` into `base`
306/// (with effort selected separately). Only merges when a base has two or more variants, avoiding
307/// mis-splitting standalone ids like `gpt-oss-120b-medium`. Input is `(display_label, id)`, preserving original order.
308pub fn split_effort_variants(models: Vec<(String, String)>) -> Vec<(String, String)> {
309    let base_of = |id: &str| -> Option<String> {
310        let (base, last) = id.rsplit_once('-')?;
311        crate::EFFORT_LEVELS
312            .contains(&last)
313            .then(|| base.to_string())
314    };
315    let mut counts: std::collections::HashMap<String, usize> = Default::default();
316    for (_, id) in &models {
317        if let Some(b) = base_of(id) {
318            *counts.entry(b).or_default() += 1;
319        }
320    }
321    let mut seen = std::collections::HashSet::new();
322    let mut out = Vec::new();
323    for (label, id) in models {
324        match base_of(&id).filter(|b| counts.get(b).copied().unwrap_or(0) >= 2) {
325            Some(b) => {
326                if seen.insert(b.clone()) {
327                    // Display name "Gemini 4 Argon (Medium)" -> "Gemini 4 Argon"
328                    let name = label
329                        .split_once("  (")
330                        .map(|(_, n)| n.trim_end_matches(')'))
331                        .map(|n| match n.rsplit_once(" (") {
332                            Some((head, _)) => head.to_string(),
333                            None => n.to_string(),
334                        });
335                    let label = match name {
336                        Some(n) => format!("{b}  ({n})"),
337                        None => b.clone(),
338                    };
339                    out.push((label, b));
340                }
341            }
342            None => out.push((label, id)),
343        }
344    }
345    out
346}
347
348/// `codex debug models` outputs `{"models":[{slug,display_name,visibility}]}`; keep only `visibility == list`.
349pub fn parse_codex_models(out: &str) -> Vec<(String, String)> {
350    let Ok(v) = serde_json::from_str::<serde_json::Value>(out) else {
351        return Vec::new();
352    };
353    v.get("models")
354        .and_then(|m| m.as_array())
355        .into_iter()
356        .flatten()
357        .filter(|m| m.get("visibility").and_then(|x| x.as_str()) == Some("list"))
358        .filter_map(|m| {
359            let slug = m.get("slug")?.as_str()?;
360            let label = match m.get("display_name").and_then(|x| x.as_str()) {
361                Some(n) if !n.is_empty() => format!("{slug}  ({n})"),
362                _ => slug.to_string(),
363            };
364            Some((label, slug.to_string()))
365        })
366        .collect()
367}
368
369/// Parse output of the `models` subcommand: ignore blank lines and prompt lines that do not look like an id.
370pub fn parse_models(out: &str) -> Vec<(String, String)> {
371    out.lines()
372        .filter_map(|line| {
373            let (id, name) = if let Some((id, rest)) = line.split_once('\t') {
374                (id.trim(), Some(rest.trim()))
375            } else if let Some(idx) = line.find("  ") {
376                let id = line[..idx].trim();
377                let rest = line[idx..].trim();
378                (id, if rest.is_empty() { None } else { Some(rest) })
379            } else {
380                (line.trim(), None)
381            };
382            if id.is_empty() || id.contains(char::is_whitespace) || id.ends_with("...") {
383                return None;
384            }
385            let label = match name {
386                Some(name) if !name.is_empty() => format!("{id}  ({name})"),
387                _ => id.to_string(),
388            };
389            Some((label, id.to_string()))
390        })
391        .collect()
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    /// `codex debug models` output is much larger than the pipe buffer; waiting for exit before reading
399    /// would stall the process on write forever and return an empty list.
400    #[cfg(unix)]
401    #[test]
402    fn capture_drains_large_output() {
403        let out = capture(
404            "sh",
405            &["-c", "yes x | head -c 200000; yes y | head -c 200000 >&2"],
406            &[],
407            std::time::Duration::from_secs(8),
408        )
409        .expect("命令應成功執行");
410        assert!(
411            out.stdout.len() >= 200_000,
412            "只讀到 {} bytes",
413            out.stdout.len()
414        );
415        assert!(
416            out.stderr.len() >= 200_000,
417            "只讀到 {} bytes",
418            out.stderr.len()
419        );
420        assert_eq!(out.code, Some(0));
421    }
422
423    #[cfg(unix)]
424    #[test]
425    fn capture_reports_timeout() {
426        let r = capture("sleep", &["5"], &[], std::time::Duration::from_millis(200));
427        assert!(matches!(r, Err(CaptureError::Timeout)));
428    }
429
430    #[test]
431    fn capture_reports_missing_binary() {
432        let r = capture(
433            "ertangle-no-such-binary",
434            &[],
435            &[],
436            std::time::Duration::from_secs(1),
437        );
438        assert!(matches!(r, Err(CaptureError::Spawn(_))));
439    }
440
441    #[test]
442    fn capture_removes_listed_env_vars() {
443        let out = capture(
444            "sh",
445            &["-c", "echo ${HOME-unset}"],
446            &["HOME"],
447            std::time::Duration::from_secs(8),
448        )
449        .expect("命令應成功執行");
450        assert_eq!(out.stdout.trim(), "unset");
451    }
452
453    fn ok(stdout: &str, stderr: &str, code: i32) -> Result<Captured, CaptureError> {
454        Ok(Captured {
455            stdout: stdout.into(),
456            stderr: stderr.into(),
457            code: Some(code),
458        })
459    }
460
461    #[test]
462    fn stderr_summary_skips_info_and_spinner() {
463        let err = "\r⠦ Fetching available models...\rI1123 14:35:36.832595 155 http_helpers.go:760] URL: x\n\r\x1b[K";
464        assert_eq!(stderr_summary(err), None);
465        let err = "I1123 a] ok\nE1123 14:35:36 auth.go:12] token expired\nI1123 b] bye\n";
466        assert_eq!(
467            stderr_summary(err).as_deref(),
468            Some("E1123 14:35:36 auth.go:12] token expired")
469        );
470    }
471
472    #[test]
473    fn diagnose_accepts_clean_success() {
474        let r = ok(
475            "m1\tModel 1\n",
476            "\r⠦ Fetching available models...\r\x1b[K",
477            0,
478        );
479        assert_eq!(diagnose("agy", "agy models", &r, 1), None);
480    }
481
482    #[test]
483    fn diagnose_flags_failure_and_empty_and_auth_errors() {
484        let failed = diagnose("agy", "agy models", &ok("", "Error: not logged in\n", 1), 0)
485            .expect("非零結束碼應回報");
486        assert!(failed.contains("not logged in"), "{failed}");
487        assert!(failed.contains("`agy`"), "{failed}");
488
489        let empty = diagnose("agy", "agy models", &ok("", "", 0), 0).expect("空清單應回報");
490        assert!(empty.contains("agy models"), "{empty}");
491
492        let partial = diagnose(
493            "agy",
494            "agy models",
495            &ok(
496                "m1\tModel 1\n",
497                "E1123 x] unauthenticated: please sign in\n",
498                0,
499            ),
500            1,
501        )
502        .expect("有錯誤訊息時即使有清單也應回報");
503        assert!(partial.contains("please sign in"), "{partial}");
504
505        let timeout =
506            diagnose("agy", "agy models", &Err(CaptureError::Timeout), 0).expect("逾時應回報");
507        assert!(timeout.contains("agy models"), "{timeout}");
508    }
509
510    #[test]
511    fn parse_models_handles_space_separated_columns() {
512        let out = "gemini-4-neon-high    Gemini 4 Neon (High)\nplain-model\n\n";
513        let parsed = parse_models(out);
514        assert_eq!(parsed.len(), 2);
515        assert_eq!(parsed[0].1, "gemini-4-neon-high");
516        assert_eq!(parsed[0].0, "gemini-4-neon-high  (Gemini 4 Neon (High))");
517        assert_eq!(parsed[1].1, "plain-model");
518        assert_eq!(parsed[1].0, "plain-model");
519    }
520
521    #[test]
522    fn antigravity_builtin_models_available() {
523        assert!(!ANTIGRAVITY_MODELS.is_empty());
524        assert!(ANTIGRAVITY_MODELS
525            .iter()
526            .any(|(id, _)| *id == "gemini-4-neon"));
527        assert!(ANTIGRAVITY_MODELS
528            .iter()
529            .any(|(id, _)| *id == "gemini-3.8-flash"));
530    }
531
532    #[test]
533    fn copilot_model_query_returns_empty_without_error() {
534        let q = query_raw_models_detailed(&AgentKind::Copilot);
535        assert!(q.models.is_empty());
536        assert!(q.problem.is_none());
537    }
538}