ertangle-adapter 1.8.0

Agent adapters (Claude Code, Codex, ACP) for ertangle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Available model lists per agent: built-in for Claude, queried from each CLI for others. Shared by TUI and daemon (Web UI).

use ertangle_core::AgentKind;
use tr::tr;

/// Available models for Claude Code. The `claude` CLI has no subcommand to list models, so this is built-in:
/// the first entries are aliases (always pointing to the latest in each family), followed by pinned version ids.
/// Update here when new models launch; the Web UI fetches this same list via the daemon's `list_models`.
pub const CLAUDE_MODELS: &[(&str, &str)] = &[
    ("fable", ertangle_core::tr_noop!("最新 Fable")),
    ("opus", ertangle_core::tr_noop!("最新 Opus")),
    ("sonnet", ertangle_core::tr_noop!("最新 Sonnet")),
    ("haiku", ertangle_core::tr_noop!("最新 Haiku")),
    ("claude-fable-5-2", "Claude Fable 5.2"),
    ("claude-fable-5-1", "Claude Fable 5.1"),
    ("claude-fable-5", "Claude Fable 5"),
    ("claude-opus-5-5", "Claude Opus 5.5"),
    ("claude-opus-5", "Claude Opus 5"),
    ("claude-opus-4-8", "Claude Opus 4.8"),
    ("claude-opus-4-7", "Claude Opus 4.7"),
    ("claude-opus-4-6", "Claude Opus 4.6"),
    ("claude-sonnet-5-5", "Claude Sonnet 5.5"),
    ("claude-sonnet-5", "Claude Sonnet 5"),
    ("claude-sonnet-4-6", "Claude Sonnet 4.6"),
    ("claude-haiku-5-5", "Claude Haiku 5.5"),
    ("claude-haiku-4-5", "Claude Haiku 4.5"),
];

/// Default available models for Antigravity (agy).
pub const ANTIGRAVITY_MODELS: &[(&str, &str)] = &[
    ("gemini-4-neon", "Gemini 4 Neon"),
    ("gemini-4-carbon", "Gemini 4 Carbon"),
    ("gemini-4-argon", "Gemini 4 Argon"),
    ("gemini-4-hydrogen", "Gemini 4 Hydrogen"),
    ("gemini-3.8-flash", "Gemini 3.8 Flash"),
    ("gemini-pro-orchestrator-neon", "Orchestrator (Neon)"),
    ("gemini-pro-orchestrator", "Orchestrator (Carbon)"),
    ("gemini-pro-orchestrator-argon", "Orchestrator (Argon)"),
    ("claude-opus-5-5", "Claude Opus 5.5"),
    ("claude-sonnet-5-5", "Claude Sonnet 5.5"),
    ("gpt-oss-120b-medium", "GPT-OSS 120B (Medium)"),
];

/// Default available models for GitHub Copilot CLI (`copilot` has no `models` subcommand).
/// Keep in sync with `MODEL_CATALOG.copilot` in `crates/ertangle-daemon/src/web/index.html`.
pub const COPILOT_MODELS: &[(&str, &str)] = &[
    ("auto", ertangle_core::tr_noop!("Copilot 自動選取")),
    ("claude-sonnet-5.5", "Claude Sonnet 5.5"),
    ("claude-opus-5.5", "Claude Opus 5.5"),
    ("claude-haiku-5.5", "Claude Haiku 5.5"),
    ("claude-fable-5.2", "Claude Fable 5.2"),
    ("claude-sonnet-4.6", "Claude Sonnet 4.6"),
    ("claude-haiku-4.5", "Claude Haiku 4.5"),
    ("gpt-6.2-sol", "GPT-6.2 Sol"),
    ("gpt-6.2-astra", "GPT-6.2 Astra"),
    ("gpt-6.1-sol", "GPT-6.1 Sol"),
    ("gpt-6.1-terra", "GPT-6.1 Terra"),
    ("gpt-6-sol", "GPT-6 Sol"),
    ("gpt-5.6-sol", "GPT-5.6 Sol"),
    ("gpt-5.6-luna", "GPT-5.6 Luna"),
    ("gpt-5.4", "GPT-5.4"),
    ("gpt-5.4-nano", "GPT-5.4 nano"),
    ("gemini-4-neon", "Gemini 4 Neon"),
    ("gemini-4-carbon", "Gemini 4 Carbon"),
    ("gemini-4-argon", "Gemini 4 Argon"),
    ("gemini-4-hydrogen", "Gemini 4 Hydrogen"),
    ("gemini-3.8-flash", "Gemini 3.8 Flash"),
];

/// Timeout for querying the model list.
const QUERY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8);

/// Output captured after a child process exits.
#[derive(Debug, Default)]
struct Captured {
    stdout: String,
    stderr: String,
    /// Exit code; `None` if terminated by a signal.
    code: Option<i32>,
}

/// Reason a command execution failed.
#[derive(Debug)]
enum CaptureError {
    Spawn(std::io::Error),
    Timeout,
}

/// Drain an entire pipe in the background to prevent full pipe buffers from stalling the child process.
fn drain<R: std::io::Read + Send + 'static>(pipe: Option<R>) -> std::sync::mpsc::Receiver<String> {
    let (tx, rx) = std::sync::mpsc::channel();
    if let Some(mut pipe) = pipe {
        std::thread::spawn(move || {
            let mut bytes = Vec::new();
            // Read as much remaining data from the pipe as possible, ignoring read and send errors.
            let _ = pipe.read_to_end(&mut bytes);
            let _ = tx.send(String::from_utf8_lossy(&bytes).into_owned());
        });
    }
    rx
}

/// Run a command within `timeout` and capture stdout, stderr, and exit code.
/// Output must be drained concurrently while waiting: `codex debug models` can output hundreds of KB,
/// and waiting for exit before reading would fill the pipe, stall the process until timeout, and yield an empty list.
/// Environment variables listed in `remove` are excluded from the child process.
fn capture(
    bin: &str,
    args: &[&str],
    remove: &[&str],
    timeout: std::time::Duration,
) -> Result<Captured, CaptureError> {
    use std::process::Stdio;

    let mut command = std::process::Command::new(bin);
    for k in remove {
        command.env_remove(k);
    }
    let mut child = command
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(CaptureError::Spawn)?;
    let stdout = drain(child.stdout.take());
    let stderr = drain(child.stderr.take());
    let deadline = std::time::Instant::now() + timeout;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) if std::time::Instant::now() < deadline => {
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            _ => {
                // Force-kill and reap the child process on timeout, ignoring errors.
                let _ = child.kill();
                let _ = child.wait();
                return Err(CaptureError::Timeout);
            }
        }
    };
    let grace = std::time::Duration::from_secs(1);
    Ok(Captured {
        stdout: stdout.recv_timeout(grace).unwrap_or_default(),
        stderr: stderr.recv_timeout(grace).unwrap_or_default(),
        code: status.code(),
    })
}

/// Pick the most informative line from stderr: skip glog INFO lines (`I1123 ...`), spinners, and blank lines;
/// prefer lines containing error keywords, otherwise take the last line.
fn stderr_summary(stderr: &str) -> Option<String> {
    let lines: Vec<&str> = stderr
        .split(['\n', '\r'])
        .map(|l| l.trim_matches(|c: char| c.is_whitespace() || c == '\x1b'))
        .map(|l| l.strip_prefix("[K").unwrap_or(l).trim())
        .filter(|l| !l.is_empty())
        .filter(|l| !is_glog_info(l))
        .filter(|l| !l.contains("Fetching available models"))
        .collect();
    let pick = lines
        .iter()
        .rev()
        .find(|l| looks_like_error(l))
        .or_else(|| lines.last())?;
    let short: String = pick.chars().take(200).collect();
    Some(short)
}

/// glog INFO line, e.g. `I1123 14:35:36.832595 155 http_helpers.go:760] ...`.
fn is_glog_info(line: &str) -> bool {
    let mut chars = line.chars();
    chars.next() == Some('I') && chars.take(4).all(|c| c.is_ascii_digit())
}

/// Line that looks like an error or login/auth issue.
fn looks_like_error(line: &str) -> bool {
    let lower = line.to_ascii_lowercase();
    let glog_error = matches!(line.chars().next(), Some('E' | 'F'))
        && line.chars().skip(1).take(4).all(|c| c.is_ascii_digit());
    glog_error
        || [
            "error",
            "fail",
            "auth",
            "login",
            "log in",
            "sign in",
            "credential",
            "token",
            "permission denied",
            "401",
            "403",
        ]
        .iter()
        .any(|k| lower.contains(k))
}

/// 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.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ModelQuery {
    /// `(display_label, id)`.
    pub models: Vec<(String, String)>,
    /// User-facing problem description.
    pub problem: Option<String>,
}

/// Build a problem description from the query result; returns `None` if there is no problem.
fn diagnose(
    bin: &str,
    cmd: &str,
    result: &Result<Captured, CaptureError>,
    parsed: usize,
) -> Option<String> {
    let login_hint = tr!(
        "若尚未登入或登入已過期,請先在終端機執行 `{bin}` 重新登入",
        bin = bin
    );
    match result {
        Err(CaptureError::Spawn(e)) => Some(tr!("無法執行 `{cmd}`:{err}", cmd = cmd, err = e)),
        Err(CaptureError::Timeout) => Some(tr!(
            "`{cmd}` 超過 {secs} 秒沒有回應;{hint}",
            cmd = cmd,
            secs = QUERY_TIMEOUT.as_secs(),
            hint = login_hint
        )),
        Ok(c) => {
            let detail = stderr_summary(&c.stderr);
            let failed = c.code != Some(0);
            let suspicious = detail.as_deref().is_some_and(looks_like_error);
            if !failed && parsed > 0 && !suspicious {
                return None;
            }
            let head = if failed {
                match c.code {
                    Some(code) => tr!("`{cmd}` 失敗 (結束碼 {code})", cmd = cmd, code = code),
                    None => tr!("`{cmd}` 被中斷", cmd = cmd),
                }
            } else if parsed == 0 {
                tr!("`{cmd}` 沒有列出任何 model", cmd = cmd)
            } else {
                tr!("`{cmd}` 回報錯誤,清單可能不完整", cmd = cmd)
            };
            Some(match detail {
                Some(d) => tr!(
                    "{head}:{detail};{hint}",
                    head = head,
                    detail = d,
                    hint = login_hint
                ),
                None => tr!("{head};{hint}", head = head, hint = login_hint),
            })
        }
    }
}

/// Query the agent CLI for raw available models (`opencode models`, `agy models`, `codex debug models`), waiting up to 8 seconds.
/// Does not merge `antigravity` effort variants; attaches a description if the query fails or the CLI reports an error.
pub fn query_raw_models_detailed(kind: &AgentKind) -> ModelQuery {
    let (bin, args): (&str, &[&str]) = match kind {
        AgentKind::OpenCode => ("opencode", &["models"]),
        AgentKind::Antigravity => ("agy", &["models"]),
        AgentKind::Codex => ("codex", &["debug", "models"]),
        _ => return ModelQuery::default(),
    };
    let cmd = std::iter::once(bin)
        .chain(args.iter().copied())
        .collect::<Vec<_>>()
        .join(" ");
    let result = capture(bin, args, crate::env_removals(kind), QUERY_TIMEOUT);
    let models = match (&result, kind) {
        (Ok(c), AgentKind::Codex) => parse_codex_models(&c.stdout),
        (Ok(c), _) => parse_models(&c.stdout),
        (Err(_), _) => Vec::new(),
    };
    let problem = diagnose(bin, &cmd, &result, models.len());
    ModelQuery { models, problem }
}

/// Same as [`query_raw_models_detailed`], returning only the list.
pub fn query_raw_models(kind: &AgentKind) -> Vec<(String, String)> {
    query_raw_models_detailed(kind).models
}

/// Same as [`query_models`], but includes any query problem description.
pub fn query_models_detailed(kind: &AgentKind) -> ModelQuery {
    let q = query_raw_models_detailed(kind);
    match kind {
        AgentKind::Antigravity => ModelQuery {
            models: split_effort_variants(q.models),
            problem: q.problem,
        },
        _ => q,
    }
}

/// Query the agent CLI for available models (`opencode models`, `agy models`), waiting up to 8 seconds.
/// Each output line has the model id in the first column, followed by the display name (tab-separated).
/// agy's list embeds effort in the model id (`xxx-high`), whereas ACP separates model and effort, so variants are merged here.
pub fn query_models(kind: &AgentKind) -> Vec<(String, String)> {
    query_models_detailed(kind).models
}

/// Merge combined "model + effort" ids such as `base-low/-medium/-high/-xhigh/-max` into `base`
/// (with effort selected separately). Only merges when a base has two or more variants, avoiding
/// mis-splitting standalone ids like `gpt-oss-120b-medium`. Input is `(display_label, id)`, preserving original order.
pub fn split_effort_variants(models: Vec<(String, String)>) -> Vec<(String, String)> {
    let base_of = |id: &str| -> Option<String> {
        let (base, last) = id.rsplit_once('-')?;
        crate::EFFORT_LEVELS
            .contains(&last)
            .then(|| base.to_string())
    };
    let mut counts: std::collections::HashMap<String, usize> = Default::default();
    for (_, id) in &models {
        if let Some(b) = base_of(id) {
            *counts.entry(b).or_default() += 1;
        }
    }
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    for (label, id) in models {
        match base_of(&id).filter(|b| counts.get(b).copied().unwrap_or(0) >= 2) {
            Some(b) => {
                if seen.insert(b.clone()) {
                    // Display name "Gemini 4 Argon (Medium)" -> "Gemini 4 Argon"
                    let name = label
                        .split_once("  (")
                        .map(|(_, n)| n.trim_end_matches(')'))
                        .map(|n| match n.rsplit_once(" (") {
                            Some((head, _)) => head.to_string(),
                            None => n.to_string(),
                        });
                    let label = match name {
                        Some(n) => format!("{b}  ({n})"),
                        None => b.clone(),
                    };
                    out.push((label, b));
                }
            }
            None => out.push((label, id)),
        }
    }
    out
}

/// `codex debug models` outputs `{"models":[{slug,display_name,visibility}]}`; keep only `visibility == list`.
pub fn parse_codex_models(out: &str) -> Vec<(String, String)> {
    let Ok(v) = serde_json::from_str::<serde_json::Value>(out) else {
        return Vec::new();
    };
    v.get("models")
        .and_then(|m| m.as_array())
        .into_iter()
        .flatten()
        .filter(|m| m.get("visibility").and_then(|x| x.as_str()) == Some("list"))
        .filter_map(|m| {
            let slug = m.get("slug")?.as_str()?;
            let label = match m.get("display_name").and_then(|x| x.as_str()) {
                Some(n) if !n.is_empty() => format!("{slug}  ({n})"),
                _ => slug.to_string(),
            };
            Some((label, slug.to_string()))
        })
        .collect()
}

/// Parse output of the `models` subcommand: ignore blank lines and prompt lines that do not look like an id.
pub fn parse_models(out: &str) -> Vec<(String, String)> {
    out.lines()
        .filter_map(|line| {
            let (id, name) = if let Some((id, rest)) = line.split_once('\t') {
                (id.trim(), Some(rest.trim()))
            } else if let Some(idx) = line.find("  ") {
                let id = line[..idx].trim();
                let rest = line[idx..].trim();
                (id, if rest.is_empty() { None } else { Some(rest) })
            } else {
                (line.trim(), None)
            };
            if id.is_empty() || id.contains(char::is_whitespace) || id.ends_with("...") {
                return None;
            }
            let label = match name {
                Some(name) if !name.is_empty() => format!("{id}  ({name})"),
                _ => id.to_string(),
            };
            Some((label, id.to_string()))
        })
        .collect()
}

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

    /// `codex debug models` output is much larger than the pipe buffer; waiting for exit before reading
    /// would stall the process on write forever and return an empty list.
    #[cfg(unix)]
    #[test]
    fn capture_drains_large_output() {
        let out = capture(
            "sh",
            &["-c", "yes x | head -c 200000; yes y | head -c 200000 >&2"],
            &[],
            std::time::Duration::from_secs(8),
        )
        .expect("命令應成功執行");
        assert!(
            out.stdout.len() >= 200_000,
            "只讀到 {} bytes",
            out.stdout.len()
        );
        assert!(
            out.stderr.len() >= 200_000,
            "只讀到 {} bytes",
            out.stderr.len()
        );
        assert_eq!(out.code, Some(0));
    }

    #[cfg(unix)]
    #[test]
    fn capture_reports_timeout() {
        let r = capture("sleep", &["5"], &[], std::time::Duration::from_millis(200));
        assert!(matches!(r, Err(CaptureError::Timeout)));
    }

    #[test]
    fn capture_reports_missing_binary() {
        let r = capture(
            "ertangle-no-such-binary",
            &[],
            &[],
            std::time::Duration::from_secs(1),
        );
        assert!(matches!(r, Err(CaptureError::Spawn(_))));
    }

    #[test]
    fn capture_removes_listed_env_vars() {
        let out = capture(
            "sh",
            &["-c", "echo ${HOME-unset}"],
            &["HOME"],
            std::time::Duration::from_secs(8),
        )
        .expect("命令應成功執行");
        assert_eq!(out.stdout.trim(), "unset");
    }

    fn ok(stdout: &str, stderr: &str, code: i32) -> Result<Captured, CaptureError> {
        Ok(Captured {
            stdout: stdout.into(),
            stderr: stderr.into(),
            code: Some(code),
        })
    }

    #[test]
    fn stderr_summary_skips_info_and_spinner() {
        let err = "\r⠦ Fetching available models...\rI1123 14:35:36.832595 155 http_helpers.go:760] URL: x\n\r\x1b[K";
        assert_eq!(stderr_summary(err), None);
        let err = "I1123 a] ok\nE1123 14:35:36 auth.go:12] token expired\nI1123 b] bye\n";
        assert_eq!(
            stderr_summary(err).as_deref(),
            Some("E1123 14:35:36 auth.go:12] token expired")
        );
    }

    #[test]
    fn diagnose_accepts_clean_success() {
        let r = ok(
            "m1\tModel 1\n",
            "\r⠦ Fetching available models...\r\x1b[K",
            0,
        );
        assert_eq!(diagnose("agy", "agy models", &r, 1), None);
    }

    #[test]
    fn diagnose_flags_failure_and_empty_and_auth_errors() {
        let failed = diagnose("agy", "agy models", &ok("", "Error: not logged in\n", 1), 0)
            .expect("非零結束碼應回報");
        assert!(failed.contains("not logged in"), "{failed}");
        assert!(failed.contains("`agy`"), "{failed}");

        let empty = diagnose("agy", "agy models", &ok("", "", 0), 0).expect("空清單應回報");
        assert!(empty.contains("agy models"), "{empty}");

        let partial = diagnose(
            "agy",
            "agy models",
            &ok(
                "m1\tModel 1\n",
                "E1123 x] unauthenticated: please sign in\n",
                0,
            ),
            1,
        )
        .expect("有錯誤訊息時即使有清單也應回報");
        assert!(partial.contains("please sign in"), "{partial}");

        let timeout =
            diagnose("agy", "agy models", &Err(CaptureError::Timeout), 0).expect("逾時應回報");
        assert!(timeout.contains("agy models"), "{timeout}");
    }

    #[test]
    fn parse_models_handles_space_separated_columns() {
        let out = "gemini-4-neon-high    Gemini 4 Neon (High)\nplain-model\n\n";
        let parsed = parse_models(out);
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].1, "gemini-4-neon-high");
        assert_eq!(parsed[0].0, "gemini-4-neon-high  (Gemini 4 Neon (High))");
        assert_eq!(parsed[1].1, "plain-model");
        assert_eq!(parsed[1].0, "plain-model");
    }

    #[test]
    fn antigravity_builtin_models_available() {
        assert!(!ANTIGRAVITY_MODELS.is_empty());
        assert!(ANTIGRAVITY_MODELS
            .iter()
            .any(|(id, _)| *id == "gemini-4-neon"));
        assert!(ANTIGRAVITY_MODELS
            .iter()
            .any(|(id, _)| *id == "gemini-3.8-flash"));
    }

    #[test]
    fn copilot_model_query_returns_empty_without_error() {
        let q = query_raw_models_detailed(&AgentKind::Copilot);
        assert!(q.models.is_empty());
        assert!(q.problem.is_none());
    }
}