Skip to main content

glass_dev/
harness.rs

1//! Discovery and safe handoff metadata for installed coding harnesses.
2//!
3//! Glass owns the workspace, trust boundary, and resident Pi agent. Other
4//! coding harnesses remain their own interactive programs, so the TUI only
5//! discovers fixed executable names and hands the terminal to a selected
6//! program. It never interpolates user-provided commands or emulates another
7//! harness's protocol.
8
9use std::ffi::OsStr;
10use std::path::{Path, PathBuf};
11use std::process::{Command, ExitStatus};
12
13/// Fixed metadata for a supported external coding harness.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct HarnessSpec {
16    /// Stable machine-readable identifier.
17    pub id: &'static str,
18    /// Human-readable display label.
19    pub label: &'static str,
20    /// Executable basename searched on `PATH`.
21    pub binary: &'static str,
22    /// Short description shown in discovery summaries.
23    pub description: &'static str,
24}
25
26/// PATH discovery result for one harness.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct HarnessStatus {
29    /// Harness metadata from [`SPECS`].
30    pub spec: HarnessSpec,
31    /// Resolved executable path, when found and executable.
32    pub path: Option<PathBuf>,
33}
34
35/// A validated harness launch target.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct ResolvedHarness {
38    /// Harness metadata.
39    pub spec: HarnessSpec,
40    /// Executable path selected from `PATH`.
41    pub path: PathBuf,
42}
43
44/// Fixed launch catalog. Discovery is PATH-only; no network or version probe
45/// runs during TUI refreshes.
46pub const SPECS: &[HarnessSpec] = &[
47    HarnessSpec {
48        id: "amp",
49        label: "Amp",
50        binary: "amp",
51        description: "threads, review mode, and supervised orb services",
52    },
53    HarnessSpec {
54        id: "aider",
55        label: "Aider",
56        binary: "aider",
57        description: "repo map, checkpoints, and lint/test loops",
58    },
59    HarnessSpec {
60        id: "claude",
61        label: "Claude Code",
62        binary: "claude",
63        description: "permission modes, hooks, and subagents",
64    },
65    HarnessSpec {
66        id: "codex",
67        label: "Codex CLI",
68        binary: "codex",
69        description: "sandboxed local work and resumable tasks",
70    },
71    HarnessSpec {
72        id: "gemini",
73        label: "Gemini CLI",
74        binary: "gemini",
75        description: "extensions, MCP, and interactive sessions",
76    },
77    HarnessSpec {
78        id: "goose",
79        label: "Goose",
80        binary: "goose",
81        description: "recipes, extensions, and session workflows",
82    },
83    HarnessSpec {
84        id: "kiro",
85        label: "Kiro CLI",
86        binary: "kiro-cli",
87        description: "spec-driven tasks, steering, and hooks",
88    },
89    HarnessSpec {
90        id: "opencode",
91        label: "OpenCode",
92        binary: "opencode",
93        description: "local TUI/server sessions and GitHub workflows",
94    },
95    HarnessSpec {
96        id: "pi",
97        label: "Pi",
98        binary: "pi",
99        description: "interactive sessions, extensions, and provider login",
100    },
101    HarnessSpec {
102        id: "qwen",
103        label: "Qwen Code",
104        binary: "qwen",
105        description: "MCP, extensions, and resumable coding sessions",
106    },
107    HarnessSpec {
108        id: "cursor",
109        label: "Cursor Agent",
110        binary: "cursor-agent",
111        description: "background agents, rules, and worktree workflows",
112    },
113    HarnessSpec {
114        id: "windsurf",
115        label: "Windsurf",
116        binary: "windsurf",
117        description: "interactive coding sessions and remote workflows",
118    },
119];
120
121/// Return the fixed supported-harness catalog.
122pub fn specs() -> &'static [HarnessSpec] {
123    SPECS
124}
125
126/// Discover supported harnesses using the process `PATH`.
127pub fn discover() -> Vec<HarnessStatus> {
128    discover_from_path(std::env::var_os("PATH").as_deref())
129}
130
131fn discover_from_path(path: Option<&OsStr>) -> Vec<HarnessStatus> {
132    SPECS
133        .iter()
134        .copied()
135        .map(|spec| HarnessStatus {
136            spec,
137            path: executable_on_path(spec.binary, path),
138        })
139        .collect()
140}
141
142/// Format a compact availability summary without probing versions or network.
143pub fn summary() -> String {
144    let statuses = discover();
145    summary_for(&statuses)
146}
147
148fn summary_for(statuses: &[HarnessStatus]) -> String {
149    statuses
150        .iter()
151        .map(|status| {
152            let marker = if status.path.is_some() { "●" } else { "○" };
153            format!(
154                "{marker} {:<9} {} · {}",
155                status.spec.id, status.spec.label, status.spec.description
156            )
157        })
158        .collect::<Vec<_>>()
159        .join("\n")
160}
161
162/// Resolve a case-insensitive id, label, or binary and require it on `PATH`.
163pub fn resolve(name: &str) -> Result<ResolvedHarness, String> {
164    let spec = SPECS
165        .iter()
166        .copied()
167        .find(|spec| {
168            spec.id.eq_ignore_ascii_case(name)
169                || spec.binary.eq_ignore_ascii_case(name)
170                || spec.label.eq_ignore_ascii_case(name)
171        })
172        .ok_or_else(|| {
173            format!(
174                "unknown harness `{name}`; choose one of {}",
175                SPECS
176                    .iter()
177                    .map(|spec| spec.id)
178                    .collect::<Vec<_>>()
179                    .join(", ")
180            )
181        })?;
182    let path = executable_on_path(spec.binary, std::env::var_os("PATH").as_deref())
183        .ok_or_else(|| format!("{} is not installed or not on PATH", spec.label))?;
184    Ok(ResolvedHarness { spec, path })
185}
186
187/// Launch a resolved harness in the requested project directory.
188pub fn launch_resolved(resolved: &ResolvedHarness, root: &Path) -> Result<ExitStatus, String> {
189    Command::new(&resolved.path)
190        .current_dir(root)
191        .status()
192        .map_err(|error| format!("{} failed to start: {error}", resolved.spec.label))
193}
194
195fn executable_on_path(binary: &str, path: Option<&OsStr>) -> Option<PathBuf> {
196    let path = path?;
197    for directory in std::env::split_paths(path) {
198        let candidate = directory.join(binary);
199        if is_executable(&candidate) {
200            return Some(candidate);
201        }
202        #[cfg(windows)]
203        for extension in [".exe", ".cmd", ".bat"] {
204            let candidate = directory.join(format!("{binary}{extension}"));
205            if is_executable(&candidate) {
206                return Some(candidate);
207            }
208        }
209    }
210    None
211}
212
213fn is_executable(path: &std::path::Path) -> bool {
214    let Ok(metadata) = std::fs::metadata(path) else {
215        return false;
216    };
217    if !metadata.is_file() {
218        return false;
219    }
220    #[cfg(unix)]
221    {
222        use std::os::unix::fs::PermissionsExt;
223        metadata.permissions().mode() & 0o111 != 0
224    }
225    #[cfg(not(unix))]
226    {
227        true
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234    use std::fs;
235    use std::time::{SystemTime, UNIX_EPOCH};
236
237    #[test]
238    fn catalog_covers_requested_harness_families() {
239        for name in [
240            "amp", "aider", "claude", "codex", "gemini", "goose", "kiro", "opencode", "pi", "qwen",
241            "cursor", "windsurf",
242        ] {
243            assert!(SPECS.iter().any(|spec| spec.id == name), "missing {name}");
244        }
245    }
246
247    #[test]
248    fn resolves_case_insensitive_ids_and_binary_aliases() {
249        assert_eq!(
250            SPECS
251                .iter()
252                .find(|spec| spec.id == "kiro")
253                .map(|spec| spec.binary),
254            Some("kiro-cli")
255        );
256        assert_eq!(
257            SPECS
258                .iter()
259                .copied()
260                .find(|spec| {
261                    spec.id.eq_ignore_ascii_case("OpenCode")
262                        || spec.binary.eq_ignore_ascii_case("OpenCode")
263                })
264                .map(|spec| spec.id),
265            Some("opencode")
266        );
267    }
268
269    #[test]
270    fn discovery_requires_an_executable_file_on_path() {
271        let suffix = SystemTime::now()
272            .duration_since(UNIX_EPOCH)
273            .expect("system clock")
274            .as_nanos();
275        let root = std::env::temp_dir().join(format!("glass-harness-{suffix}"));
276        fs::create_dir_all(&root).expect("create fixture");
277        let pi = root.join("pi");
278        fs::write(&pi, "#!/bin/sh\n").expect("write fixture");
279        #[cfg(unix)]
280        {
281            use std::os::unix::fs::PermissionsExt;
282            fs::set_permissions(&pi, fs::Permissions::from_mode(0o755))
283                .expect("make fixture executable");
284        }
285        let statuses = discover_from_path(Some(root.as_os_str()));
286        assert!(
287            statuses
288                .iter()
289                .find(|status| status.spec.id == "pi")
290                .and_then(|status| status.path.as_ref())
291                .is_some()
292        );
293        assert!(
294            statuses
295                .iter()
296                .find(|status| status.spec.id == "amp")
297                .is_some_and(|status| status.path.is_none())
298        );
299        let _ = fs::remove_dir_all(root);
300    }
301}