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