car-external-agents 0.34.0

Detection of installed agentic CLIs (Claude Code, Codex, Gemini) for the Common Agent Runtime.
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
//! Detection — locate installed adapter binaries on `$PATH`, probe
//! version and auth state, build [`ExternalAgentSpec`] entries.
//!
//! Detection is best-effort and idempotent. Failure of any sub-probe
//! (version timeout, missing cred file, malformed JSON) degrades the
//! affected field rather than dropping the entry — knowing "claude
//! is on disk but I can't tell you the version" is more useful than
//! a silent omission.

use crate::adapters::{self, Adapter};
use crate::types::ExternalAgentSpec;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

const VERSION_PROBE_TIMEOUT: Duration = Duration::from_secs(2);

/// Exclude world-writable scratch directories so a binary staged
/// under `/tmp` is never the one detection picks up. Matches
/// `car_registry::supervisor::validate_command`'s denylist for the
/// same reason — the 2026-05 audit walked an exploit chain that
/// staged under `/tmp` before lifecycle-spawning, and detection
/// should not be a backdoor around that.
const SCRATCH_PREFIXES: &[&str] = &["/tmp/", "/private/tmp/", "/var/tmp/", "/dev/shm/"];

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Candidate file names to try for a bare `bin_name` in each PATH dir.
///
/// On Unix this is just `[bin_name]`. On Windows an adapter's bare name
/// (`"claude"`) is installed by npm as several shims — `claude.exe`/`.cmd`/
/// `.ps1` plus an extensionless bash shim — and Windows resolves a bare command
/// against `%PATHEXT%`. So unless `bin_name` already carries an extension, try
/// `bin_name` + each `PATHEXT` entry (executable extensions first) and the bare
/// name last. Without this, an agent installed only as `claude.cmd` is missed
/// entirely (car#511). Mirrors the host's PATHEXT-aware lookup in
/// `apps/host-windows/src/paths.rs`.
fn candidate_names(bin_name: &str) -> Vec<String> {
    #[cfg(not(windows))]
    {
        vec![bin_name.to_string()]
    }
    #[cfg(windows)]
    {
        // Already has an extension → use it verbatim.
        if Path::new(bin_name).extension().is_some() {
            return vec![bin_name.to_string()];
        }
        let pathext =
            std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());
        let mut names: Vec<String> = pathext
            .split(';')
            .filter(|e| !e.is_empty())
            .map(|ext| format!("{bin_name}{}", ext.to_ascii_lowercase()))
            .collect();
        // The extensionless npm shim (a bash script) last: a real .exe/.cmd is
        // preferred because it can actually be spawned/probed on Windows.
        names.push(bin_name.to_string());
        names
    }
}

/// Resolve `bin_name` against the supplied `$PATH`-style search list
/// (`:`-separated on POSIX, `;` on Windows). Returns the first
/// executable match outside scratch directories. `None` when the
/// binary isn't found or every match is in a denied prefix.
///
/// `scratch_prefixes` is the list of path prefixes to refuse; in
/// production this is [`SCRATCH_PREFIXES`]. Tests pass `&[]` so
/// `tempfile`-created scratch dirs (which land under `/tmp/` on
/// Linux CI) work as PATH entries — the production denylist still
/// has unit coverage via [`tests::detect_rejects_scratch_dir_binaries`].
fn resolve_in_path(bin_name: &str, path_var: &str, scratch_prefixes: &[&str]) -> Option<PathBuf> {
    let separator = if cfg!(windows) { ';' } else { ':' };
    let names = candidate_names(bin_name);
    for dir in path_var.split(separator) {
        if dir.is_empty() {
            continue;
        }
        for name in &names {
            let candidate = Path::new(dir).join(name);
            // Reject scratch dirs before any FS work — the lossy
            // string conversion is fine for prefix matching.
            let candidate_str = candidate.to_string_lossy();
            if scratch_prefixes
                .iter()
                .any(|prefix| candidate_str.starts_with(prefix))
            {
                continue;
            }
            if !candidate.exists() {
                continue;
            }
            let Ok(meta) = std::fs::metadata(&candidate) else {
                continue;
            };
            if !meta.is_file() {
                continue;
            }
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if meta.permissions().mode() & 0o111 == 0 {
                    continue;
                }
            }
            return Some(candidate);
        }
    }
    None
}

/// Run `<bin> --version` with a 2s timeout, return the trimmed stdout
/// if the probe succeeded with a zero exit code. Stderr is dropped —
/// some tools emit deprecation warnings there that pollute the parse
/// shape.
async fn probe_version(bin: &Path) -> Option<String> {
    use tokio::process::Command;
    // On Windows a `.cmd`/`.bat` shim (how npm installs these CLIs) is a batch
    // script, not a PE image — `CreateProcess` can't run it directly, so route
    // it through `cmd /C`. A `.exe` (or Unix binary) is invoked directly.
    let is_batch_shim = cfg!(windows)
        && bin
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| {
                let e = e.to_ascii_lowercase();
                e == "cmd" || e == "bat"
            })
            .unwrap_or(false);
    let mut cmd = if is_batch_shim {
        let mut c = Command::new("cmd");
        c.arg("/C").arg(bin).arg("--version");
        c
    } else {
        let mut c = Command::new(bin);
        c.arg("--version");
        c
    };
    cmd.stdin(std::process::Stdio::null());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::null());
    cmd.kill_on_drop(true);
    let child = cmd.spawn().ok()?;
    let output = match tokio::time::timeout(VERSION_PROBE_TIMEOUT, child.wait_with_output()).await {
        Ok(Ok(out)) => out,
        _ => return None,
    };
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8(output.stdout).ok()?;
    let trimmed = stdout.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
}

/// Build a spec for one adapter, or `None` when the binary isn't
/// installed.
async fn detect_one(
    adapter: &Adapter,
    path_var: &str,
    home: &Path,
    scratch_prefixes: &[&str],
) -> Option<ExternalAgentSpec> {
    let binary_path = resolve_in_path(adapter.bin_name, path_var, scratch_prefixes)?;
    let version_raw = probe_version(&binary_path).await;
    let version = version_raw.and_then(|raw| (adapter.parse_version)(&raw));
    let auth_kind = (adapter.probe_auth)(home);
    Some(ExternalAgentSpec {
        id: adapter.id.as_str().to_string(),
        display_name: adapter.id.display_name().to_string(),
        binary_path,
        version,
        auth_kind,
        capabilities: adapter.capabilities.clone(),
        detected_at: now_secs(),
        health: None,
    })
}

/// Run detection for every known adapter against the current process
/// environment. Returns specs for installed adapters only — uninstalled
/// adapters are simply omitted from the list. Sorted by `id` for
/// deterministic UI ordering.
///
/// Best-effort: a failed sub-probe degrades the affected field rather
/// than dropping the entry. Only a missing binary causes omission.
pub async fn detect() -> Vec<ExternalAgentSpec> {
    let path_var = std::env::var("PATH").unwrap_or_default();
    let Some(home) = home_dir() else {
        // No HOME → can't probe auth state. Still detect binaries on
        // PATH; auth_kind defaults to Unknown.
        return detect_with_paths(&path_var, Path::new("/")).await;
    };
    detect_with_paths(&path_var, &home).await
}

/// Same as [`detect`] but with explicit `$PATH` and `$HOME` overrides.
/// Production scratch denylist applies. Used by tests; not part of the
/// public API.
pub(crate) async fn detect_with_paths(path_var: &str, home: &Path) -> Vec<ExternalAgentSpec> {
    detect_with_paths_filtered(path_var, home, SCRATCH_PREFIXES).await
}

/// Underlying implementation of [`detect_with_paths`] with an
/// overridable scratch-prefix list. Tests pass `&[]` so binaries
/// staged in `tempfile`-created dirs (which land under `/tmp/` on
/// Linux CI) survive the resolver. The production scratch denylist
/// keeps full unit coverage via [`tests::detect_rejects_scratch_dir_binaries`].
pub(crate) async fn detect_with_paths_filtered(
    path_var: &str,
    home: &Path,
    scratch_prefixes: &[&str],
) -> Vec<ExternalAgentSpec> {
    // Probe adapters concurrently — each is an independent binary lookup +
    // `--version` subprocess (bounded by VERSION_PROBE_TIMEOUT). Sequential, the
    // worst case is N × that timeout, which on a slow machine overshoots
    // callers' own deadlines (e.g. discovery's per-provider bound) and starves
    // detection entirely. Concurrent, the worst case is ~one probe timeout.
    let probes = adapters::all()
        .iter()
        .map(|adapter| detect_one(adapter, path_var, home, scratch_prefixes));
    let mut specs: Vec<ExternalAgentSpec> = futures::future::join_all(probes)
        .await
        .into_iter()
        .flatten()
        .collect();
    // Deterministic order regardless of which probe finished first.
    specs.sort_by(|a, b| a.id.cmp(&b.id));
    specs
}

/// Run detection and immediately populate each spec's `health` field
/// with the ground-truth result from each tool's auth-status command.
/// Slower than plain [`detect`] (subprocess spawn per tool) but gives
/// host UIs a one-stop call for "what's installed AND ready to use."
///
/// Pass `force = true` to bypass the 30s per-tool health-check TTL
/// cache.
pub async fn detect_with_health(force: bool) -> Vec<ExternalAgentSpec> {
    let mut specs = detect().await;
    let healths = crate::health::check_all(&specs, force).await;
    let by_id: std::collections::HashMap<&str, &crate::health::ExternalAgentHealth> =
        healths.iter().map(|h| (h.id.as_str(), h)).collect();
    for spec in specs.iter_mut() {
        if let Some(h) = by_id.get(spec.id.as_str()) {
            spec.health = Some((*h).clone());
        }
    }
    specs
}

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

    /// Build a fake executable for `name` that prints `version_output`.
    /// On Unix this is an extensionless `#!/bin/sh` script; on Windows it's a
    /// `name.cmd` npm-style batch shim (the real-world install shape), so
    /// detection exercises the PATHEXT resolution + `cmd /C` probe path.
    /// Returns the created path.
    fn make_fake_bin(dir: &Path, name: &str, version_output: &str) -> PathBuf {
        #[cfg(windows)]
        {
            let path = dir.join(format!("{name}.cmd"));
            std::fs::write(&path, format!("@echo off\r\necho {version_output}\r\n")).unwrap();
            path
        }
        #[cfg(not(windows))]
        {
            let path = dir.join(name);
            let script = format!("#!/bin/sh\necho '{version_output}'\n");
            std::fs::write(&path, script).unwrap();
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
            path
        }
    }

    #[cfg(windows)]
    #[test]
    fn candidate_names_expands_pathext_on_windows() {
        std::env::set_var("PATHEXT", ".COM;.EXE;.BAT;.CMD");
        let names = candidate_names("claude");
        // Executable extensions are tried, plus the bare npm shim last.
        assert!(names.contains(&"claude.exe".to_string()), "{names:?}");
        assert!(names.contains(&"claude.cmd".to_string()), "{names:?}");
        assert_eq!(names.last().unwrap(), "claude", "bare shim tried last");
        // A name that already has an extension is used verbatim.
        assert_eq!(
            candidate_names("claude.cmd"),
            vec!["claude.cmd".to_string()]
        );
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn detect_finds_cmd_shim_on_path() {
        // The npm `.cmd` shim must be found via PATHEXT and version-probed
        // through `cmd /C` (car#511).
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51 (Claude Code)");
        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths_filtered(&path_var, home_dir.path(), &[]).await;
        let claude = specs.iter().find(|s| s.id == "claude-code");
        assert!(
            claude.is_some(),
            "expected claude-code via .cmd shim in {specs:?}"
        );
        assert_eq!(claude.unwrap().version.as_deref(), Some("1.0.51"));
    }

    #[tokio::test]
    async fn detect_finds_fake_binary_on_path() {
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51 (Claude Code)");

        let path_var = bin_dir.path().to_string_lossy().to_string();
        // Empty scratch denylist — `tempfile` lands under /tmp/ on
        // Linux CI, which the production list rejects. The
        // production-denylist behavior is covered by
        // `detect_rejects_scratch_dir_binaries` below.
        let specs = detect_with_paths_filtered(&path_var, home_dir.path(), &[]).await;

        let claude = specs.iter().find(|s| s.id == "claude-code");
        assert!(claude.is_some(), "expected claude-code in {specs:?}");
        let claude = claude.unwrap();
        assert_eq!(claude.version.as_deref(), Some("1.0.51"));
        // No cred file → Unauthenticated, not Unknown.
        assert!(matches!(
            claude.auth_kind,
            crate::types::AuthKind::Unauthenticated
        ));
    }

    #[tokio::test]
    async fn detect_omits_uninstalled_binaries() {
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        // Empty PATH dir — no binaries installed.
        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths(&path_var, home_dir.path()).await;
        assert!(specs.is_empty(), "expected no detections, got {specs:?}");
    }

    #[tokio::test]
    async fn detect_picks_subscription_when_oauth_creds_present() {
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51");

        // Write a fake credential file with an oauth-shaped key.
        let claude_dir = home_dir.path().join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();
        std::fs::write(
            claude_dir.join(".credentials.json"),
            r#"{"oauthAccount": {"email": "[email protected]"}}"#,
        )
        .unwrap();

        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths_filtered(&path_var, home_dir.path(), &[]).await;
        let claude = specs.iter().find(|s| s.id == "claude-code").unwrap();
        assert!(matches!(
            claude.auth_kind,
            crate::types::AuthKind::Subscription
        ));
    }

    #[tokio::test]
    async fn detect_picks_apikey_when_only_apikey_present() {
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51");

        let claude_dir = home_dir.path().join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();
        std::fs::write(
            claude_dir.join(".credentials.json"),
            r#"{"apiKey": "sk-ant-..."}"#,
        )
        .unwrap();

        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths_filtered(&path_var, home_dir.path(), &[]).await;
        let claude = specs.iter().find(|s| s.id == "claude-code").unwrap();
        assert!(matches!(claude.auth_kind, crate::types::AuthKind::ApiKey));
    }

    #[tokio::test]
    async fn detect_rejects_scratch_dir_binaries() {
        // Skip on platforms where TMPDIR doesn't land under /tmp
        // (macOS resolves to /var/folders/... — outside the denylist
        // by design).
        let tmp = std::env::temp_dir();
        if !tmp.starts_with("/tmp") && !tmp.starts_with("/private/tmp") {
            return;
        }
        let bin_dir = tempfile::TempDir::new_in("/tmp").unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        make_fake_bin(bin_dir.path(), "claude", "1.0.51");

        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths(&path_var, home_dir.path()).await;
        assert!(
            specs.iter().all(|s| s.id != "claude-code"),
            "scratch-dir binary must be rejected, got {specs:?}"
        );
    }

    #[tokio::test]
    async fn detect_keeps_entry_when_version_probe_fails() {
        let bin_dir = tempfile::TempDir::new().unwrap();
        let home_dir = tempfile::TempDir::new().unwrap();
        // A binary that exits non-zero — version probe returns None.
        let path = bin_dir.path().join("claude");
        std::fs::write(&path, "#!/bin/sh\nexit 1\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
        }

        let path_var = bin_dir.path().to_string_lossy().to_string();
        let specs = detect_with_paths_filtered(&path_var, home_dir.path(), &[]).await;
        let claude = specs.iter().find(|s| s.id == "claude-code");
        assert!(claude.is_some(), "entry must survive failed version probe");
        assert!(claude.unwrap().version.is_none());
    }
}