Skip to main content

ag_agent/agent/
availability.rs

1//! Machine-scoped agent executable discovery.
2
3use std::env;
4use std::ffi::OsStr;
5use std::os::unix::fs::{MetadataExt, PermissionsExt};
6use std::path::{Path, PathBuf};
7use std::process::{Child, Command, Output, Stdio};
8use std::sync::{Mutex, OnceLock};
9use std::time::{Duration, Instant};
10
11pub use ag_session::{AgentAvailabilityProbe, StaticAgentAvailabilityProbe};
12use ag_session::{AgentKind, AgentModel};
13use semver::Version;
14
15use crate::model::agent::AgentCliInfo;
16
17/// Oldest Antigravity CLI release supported by Agentty's native stream
18/// protocol.
19const ANTIGRAVITY_MINIMUM_VERSION: Version = Version::new(1, 1, 18);
20/// Maximum time spent waiting for one provider CLI `--version` command.
21const AGENT_CLI_VERSION_TIMEOUT: Duration = Duration::from_secs(2);
22/// Maximum time spent waiting for one provider CLI `update` command.
23const AGENT_CLI_UPDATE_TIMEOUT: Duration = Duration::from_mins(5);
24/// Poll interval used while waiting for one bounded provider CLI subprocess.
25const AGENT_CLI_COMMAND_POLL_INTERVAL: Duration = Duration::from_millis(25);
26/// Canonical npm-global path segment for the Gemini CLI package.
27const GEMINI_NPM_PACKAGE_PATH: &str = "/lib/node_modules/@google/gemini-cli/";
28/// npm package spec used to refresh a globally installed Gemini CLI.
29const GEMINI_NPM_PACKAGE_SPEC: &str = "@google/gemini-cli@latest";
30
31/// Cached result of validating one exact Antigravity executable.
32#[derive(Clone)]
33struct AntigravityCompatibilitySnapshot {
34    fingerprint: Option<AntigravityExecutableFingerprint>,
35    result: Result<(), String>,
36}
37
38/// Metadata used to invalidate compatibility after `agy` changes on disk.
39#[derive(Clone, Debug, PartialEq, Eq)]
40struct AntigravityExecutableFingerprint {
41    device: u64,
42    inode: u64,
43    length: u64,
44    mode: u32,
45    modified_nanoseconds: i64,
46    modified_seconds: i64,
47    path: PathBuf,
48}
49
50/// Process-wide Antigravity compatibility snapshot populated by startup
51/// discovery and CLI refresh.
52static ANTIGRAVITY_COMPATIBILITY: OnceLock<Mutex<Option<AntigravityCompatibilitySnapshot>>> =
53    OnceLock::new();
54
55/// Executable plus arguments for one provider CLI startup update.
56struct AgentCliUpdateCommand {
57    args: &'static [&'static str],
58    executable_path: PathBuf,
59}
60
61impl AgentCliUpdateCommand {
62    /// Creates one provider update command.
63    fn new(executable_path: PathBuf, args: &'static [&'static str]) -> Self {
64        Self {
65            args,
66            executable_path,
67        }
68    }
69}
70
71/// Production availability probe backed by `PATH` executable discovery.
72pub struct RealAgentAvailabilityProbe;
73
74impl AgentAvailabilityProbe for RealAgentAvailabilityProbe {
75    fn available_agent_kinds(&self) -> Vec<AgentKind> {
76        available_agent_kinds_from_path(env::var_os("PATH").as_deref())
77    }
78
79    fn available_agent_clis(&self) -> Vec<AgentCliInfo> {
80        available_agent_clis_from_path(env::var_os("PATH").as_deref())
81    }
82
83    fn native_harness_default_model(&self) -> Option<AgentModel> {
84        super::native::default_model(&super::native::process_environment())
85    }
86}
87
88/// Returns the CLI executable name used by the provided agent kind, or `None`
89/// for the in-process harness.
90#[must_use]
91pub fn executable_name(agent_kind: AgentKind) -> Option<&'static str> {
92    agent_kind.executable_name()
93}
94
95/// Returns available agent CLI metadata from one `PATH` value.
96fn available_agent_clis_from_path(path_value: Option<&OsStr>) -> Vec<AgentCliInfo> {
97    let executable_agent_clis = AgentKind::ALL
98        .iter()
99        .copied()
100        .filter_map(|agent_kind| {
101            let executable_path =
102                executable_path_on_path(path_value, executable_name(agent_kind)?)?;
103
104            Some((agent_kind, executable_path))
105        })
106        .collect();
107
108    refresh_agent_cli_versions(executable_agent_clis, |agent_kind, executable_path| {
109        refresh_agent_cli_version(agent_kind, executable_path, path_value)
110    })
111}
112
113/// Returns agent kinds whose executables are present on one `PATH` value.
114fn available_agent_kinds_from_path(path_value: Option<&OsStr>) -> Vec<AgentKind> {
115    AgentKind::ALL
116        .iter()
117        .copied()
118        .filter(|agent_kind| {
119            if *agent_kind == AgentKind::Antigravity {
120                return ensure_antigravity_cli_supported_on_path(path_value).is_ok();
121            }
122
123            executable_name(*agent_kind)
124                .and_then(|name| executable_path_on_path(path_value, name))
125                .is_some()
126        })
127        .collect()
128}
129
130/// Validates one Antigravity executable resolved from the provided `PATH`.
131fn ensure_antigravity_cli_supported_on_path(path_value: Option<&OsStr>) -> Result<(), String> {
132    let Some(executable_path) = executable_name(AgentKind::Antigravity)
133        .and_then(|name| executable_path_on_path(path_value, name))
134    else {
135        let result = Err(format!(
136            "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but `agy` was \
137             not found on `PATH`. Install it or run `agy update`, then restart Agentty."
138        ));
139
140        cache_antigravity_cli_support(None, result.clone());
141
142        return result;
143    };
144    let detected_version = detect_agent_cli_version(&executable_path);
145    let result = validate_antigravity_cli_version(detected_version.as_deref());
146
147    cache_antigravity_cli_support(Some(&executable_path), result.clone());
148
149    result
150}
151
152/// Checks one `PATH` against the cached Antigravity compatibility snapshot.
153pub(super) fn ensure_cached_antigravity_cli_supported_on_path(
154    path_value: Option<&OsStr>,
155) -> Result<(), String> {
156    let executable_path = executable_name(AgentKind::Antigravity)
157        .and_then(|name| executable_path_on_path(path_value, name));
158    let current_fingerprint = executable_path
159        .as_deref()
160        .and_then(antigravity_executable_fingerprint);
161    let snapshot = ANTIGRAVITY_COMPATIBILITY
162        .get_or_init(|| Mutex::new(None))
163        .lock()
164        .ok()
165        .and_then(|snapshot| snapshot.clone());
166
167    validate_cached_antigravity_cli_support(snapshot.as_ref(), current_fingerprint.as_ref())
168}
169
170/// Returns a cached result only when it describes the current executable.
171fn validate_cached_antigravity_cli_support(
172    snapshot: Option<&AntigravityCompatibilitySnapshot>,
173    current_fingerprint: Option<&AntigravityExecutableFingerprint>,
174) -> Result<(), String> {
175    let Some(snapshot) = snapshot else {
176        return Err(
177            "Antigravity CLI has not been validated yet. Wait for CLI discovery to finish or \
178             restart Agentty, then retry."
179                .to_string(),
180        );
181    };
182    if snapshot.fingerprint.as_ref() != current_fingerprint {
183        return Err(
184            "Antigravity CLI installation changed after Agentty validated it. Wait for CLI \
185             discovery to finish or restart Agentty, then retry."
186                .to_string(),
187        );
188    }
189
190    snapshot.result.clone()
191}
192
193/// Stores one compatibility result alongside the exact executable it covers.
194fn cache_antigravity_cli_support(executable_path: Option<&Path>, result: Result<(), String>) {
195    let snapshot = AntigravityCompatibilitySnapshot {
196        fingerprint: executable_path.and_then(antigravity_executable_fingerprint),
197        result,
198    };
199    if let Ok(mut cached_snapshot) = ANTIGRAVITY_COMPATIBILITY
200        .get_or_init(|| Mutex::new(None))
201        .lock()
202    {
203        *cached_snapshot = Some(snapshot);
204    }
205}
206
207/// Captures stable metadata for one resolved Antigravity executable.
208fn antigravity_executable_fingerprint(
209    executable_path: &Path,
210) -> Option<AntigravityExecutableFingerprint> {
211    let metadata = executable_path.metadata().ok()?;
212
213    Some(AntigravityExecutableFingerprint {
214        device: metadata.dev(),
215        inode: metadata.ino(),
216        length: metadata.len(),
217        modified_nanoseconds: metadata.mtime_nsec(),
218        modified_seconds: metadata.mtime(),
219        mode: metadata.mode(),
220        path: executable_path.to_path_buf(),
221    })
222}
223
224/// Validates one parsed Antigravity version string against the supported
225/// minimum.
226fn validate_antigravity_cli_version(detected_version: Option<&str>) -> Result<(), String> {
227    let Some(detected_version) = detected_version else {
228        return Err(format!(
229            "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but `agy \
230             --version` did not report a version. Run `agy update`, then retry."
231        ));
232    };
233    let normalized_version = detected_version
234        .strip_prefix('v')
235        .unwrap_or(detected_version);
236    let parsed_version = Version::parse(normalized_version).map_err(|_| {
237        format!(
238            "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but `agy \
239             --version` reported `{detected_version}`. Run `agy update`, then retry."
240        )
241    })?;
242    if parsed_version < ANTIGRAVITY_MINIMUM_VERSION {
243        return Err(format!(
244            "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but \
245             `{detected_version}` is installed. Run `agy update`, then retry."
246        ));
247    }
248
249    Ok(())
250}
251
252/// Returns the first executable path matching one command name on `PATH`.
253fn executable_path_on_path(path_value: Option<&OsStr>, executable_name: &str) -> Option<PathBuf> {
254    path_value
255        .map(env::split_paths)
256        .into_iter()
257        .flatten()
258        .map(|path_entry| candidate_path_for_executable_name(&path_entry, executable_name))
259        .find(|candidate_path| is_executable_file(candidate_path))
260}
261
262/// Returns the candidate filesystem path for one executable name within a
263/// single `PATH` entry.
264fn candidate_path_for_executable_name(path_entry: &Path, executable_name: &str) -> PathBuf {
265    path_entry.join(executable_name)
266}
267
268/// Returns whether the candidate path is a regular file with at least one
269/// execute bit set.
270fn is_executable_file(candidate_path: &Path) -> bool {
271    let Ok(metadata) = candidate_path.metadata() else {
272        return false;
273    };
274
275    if !metadata.is_file() {
276        return false;
277    }
278
279    metadata.permissions().mode() & 0o111 != 0
280}
281
282/// Runs one available CLI's update command, then extracts the installed
283/// version token from a fresh version probe.
284fn refresh_agent_cli_version(
285    agent_kind: AgentKind,
286    executable_path: &Path,
287    path_value: Option<&OsStr>,
288) -> Option<String> {
289    run_agent_cli_update(agent_kind, executable_path, path_value);
290
291    let detected_version = detect_agent_cli_version(executable_path);
292    if agent_kind == AgentKind::Antigravity {
293        let result = validate_antigravity_cli_version(detected_version.as_deref());
294        cache_antigravity_cli_support(Some(executable_path), result);
295    }
296
297    detected_version
298}
299
300/// Refreshes all available CLI versions concurrently while preserving
301/// provider display order.
302fn refresh_agent_cli_versions(
303    executable_agent_clis: Vec<(AgentKind, PathBuf)>,
304    refresh_cli_version: impl Fn(AgentKind, &Path) -> Option<String> + Sync,
305) -> Vec<AgentCliInfo> {
306    std::thread::scope(|scope| {
307        let refresh_cli_version = &refresh_cli_version;
308        let refresh_handles = executable_agent_clis
309            .into_iter()
310            .map(|(agent_kind, executable_path)| {
311                (
312                    agent_kind,
313                    scope.spawn(move || refresh_cli_version(agent_kind, &executable_path)),
314                )
315            })
316            .collect::<Vec<_>>();
317
318        refresh_handles
319            .into_iter()
320            .map(|(agent_kind, refresh_handle)| {
321                AgentCliInfo::new(agent_kind, refresh_handle.join().unwrap_or(None))
322            })
323            .collect()
324    })
325}
326
327/// Runs one available CLI's best-effort provider or package-manager update.
328fn run_agent_cli_update(agent_kind: AgentKind, executable_path: &Path, path_value: Option<&OsStr>) {
329    let _ = run_agent_cli_update_with_timeout(
330        agent_kind,
331        executable_path,
332        path_value,
333        AGENT_CLI_UPDATE_TIMEOUT,
334    );
335}
336
337/// Runs one available CLI's best-effort update with a caller-provided timeout.
338fn run_agent_cli_update_with_timeout(
339    agent_kind: AgentKind,
340    executable_path: &Path,
341    path_value: Option<&OsStr>,
342    timeout: Duration,
343) -> bool {
344    let Some(update_command) = agent_cli_update_command(agent_kind, executable_path, path_value)
345    else {
346        return false;
347    };
348
349    command_status_with_timeout(&update_command, timeout).is_some()
350}
351
352/// Builds the supported startup update command for one provider CLI.
353fn agent_cli_update_command(
354    agent_kind: AgentKind,
355    executable_path: &Path,
356    path_value: Option<&OsStr>,
357) -> Option<AgentCliUpdateCommand> {
358    if agent_kind == AgentKind::Gemini {
359        return gemini_npm_update_command(executable_path, path_value);
360    }
361
362    Some(AgentCliUpdateCommand::new(
363        executable_path.to_path_buf(),
364        &["update"],
365    ))
366}
367
368/// Builds Gemini's supported npm-global update command when the discovered
369/// executable resolves into the global Gemini CLI package.
370///
371/// Canonicalization failure is treated as an unknown installation because
372/// Agentty cannot safely prove that npm owns the executable.
373fn gemini_npm_update_command(
374    executable_path: &Path,
375    path_value: Option<&OsStr>,
376) -> Option<AgentCliUpdateCommand> {
377    let canonical_executable_path = executable_path.canonicalize().ok()?;
378    let normalized_executable_path = canonical_executable_path.to_string_lossy();
379    if !normalized_executable_path.contains(GEMINI_NPM_PACKAGE_PATH) {
380        return None;
381    }
382
383    let npm_executable_path = executable_path_on_path(path_value, "npm")?;
384
385    Some(AgentCliUpdateCommand::new(
386        npm_executable_path,
387        &["install", "-g", GEMINI_NPM_PACKAGE_SPEC],
388    ))
389}
390
391/// Runs one available CLI's version command and extracts the installed
392/// version token from its output.
393fn detect_agent_cli_version(executable_path: &Path) -> Option<String> {
394    detect_agent_cli_version_with_timeout(executable_path, AGENT_CLI_VERSION_TIMEOUT)
395}
396
397/// Runs one available CLI's version command with a caller-provided timeout.
398fn detect_agent_cli_version_with_timeout(
399    executable_path: &Path,
400    timeout: Duration,
401) -> Option<String> {
402    let output = version_command_output(executable_path, timeout)?;
403    if !output.status.success() {
404        return None;
405    }
406
407    let stdout_text = String::from_utf8_lossy(&output.stdout);
408    let stderr_text = String::from_utf8_lossy(&output.stderr);
409    parse_agent_cli_version_output(&stdout_text)
410        .or_else(|| parse_agent_cli_version_output(&stderr_text))
411}
412
413/// Runs one provider CLI `--version` command and stops waiting once the
414/// timeout expires.
415fn version_command_output(executable_path: &Path, timeout: Duration) -> Option<Output> {
416    command_output_with_timeout(executable_path, &["--version"], timeout)
417}
418
419/// Runs one provider CLI command with output discarded and stops waiting once
420/// the timeout expires.
421fn command_status_with_timeout(
422    update_command: &AgentCliUpdateCommand,
423    timeout: Duration,
424) -> Option<()> {
425    let mut child = Command::new(&update_command.executable_path)
426        .args(update_command.args)
427        .stdin(Stdio::null())
428        .stdout(Stdio::null())
429        .stderr(Stdio::null())
430        .spawn()
431        .ok()?;
432    wait_for_child_exit(&mut child, timeout)?;
433    let _ = child.wait().ok()?;
434
435    Some(())
436}
437
438/// Runs one provider CLI command and stops waiting once the timeout expires.
439fn command_output_with_timeout(
440    executable_path: &Path,
441    args: &[&str],
442    timeout: Duration,
443) -> Option<Output> {
444    let mut child = Command::new(executable_path)
445        .args(args)
446        .stdin(Stdio::null())
447        .stdout(Stdio::piped())
448        .stderr(Stdio::piped())
449        .spawn()
450        .ok()?;
451    wait_for_child_exit(&mut child, timeout)?;
452
453    child.wait_with_output().ok()
454}
455
456/// Waits for one child process to exit, killing it when the timeout expires.
457fn wait_for_child_exit(child: &mut Child, timeout: Duration) -> Option<()> {
458    let started_at = Instant::now();
459
460    loop {
461        if child.try_wait().ok()?.is_some() {
462            return Some(());
463        }
464
465        if started_at.elapsed() >= timeout {
466            let _ = child.kill();
467            let _ = child.wait();
468
469            return None;
470        }
471
472        std::thread::sleep(
473            AGENT_CLI_COMMAND_POLL_INTERVAL.min(timeout.saturating_sub(started_at.elapsed())),
474        );
475    }
476}
477
478/// Parses a provider CLI version from the first useful `--version` output
479/// line.
480fn parse_agent_cli_version_output(output: &str) -> Option<String> {
481    let line = output
482        .lines()
483        .map(str::trim)
484        .find(|line| !line.is_empty())?;
485    let version_token = line
486        .split_whitespace()
487        .map(|token| {
488            token.trim_matches(|character: char| {
489                matches!(character, ',' | ';' | ':' | '(' | ')' | '[' | ']')
490            })
491        })
492        .find(|token| {
493            let normalized = token.strip_prefix('v').unwrap_or(token);
494
495            normalized
496                .chars()
497                .next()
498                .is_some_and(|character| character.is_ascii_digit())
499                && normalized.contains('.')
500        });
501
502    Some(version_token.unwrap_or(line).to_string())
503}
504
505#[cfg(test)]
506#[path = "availability_test.rs"]
507mod tests;