1use 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 semver::Version;
12
13use crate::model::agent::{AgentCliInfo, AgentKind};
14
15const ANTIGRAVITY_MINIMUM_VERSION: Version = Version::new(1, 1, 18);
18const AGENT_CLI_VERSION_TIMEOUT: Duration = Duration::from_secs(2);
20const AGENT_CLI_UPDATE_TIMEOUT: Duration = Duration::from_mins(5);
22const AGENT_CLI_COMMAND_POLL_INTERVAL: Duration = Duration::from_millis(25);
24const GEMINI_NPM_PACKAGE_PATH: &str = "/lib/node_modules/@google/gemini-cli/";
26const GEMINI_NPM_PACKAGE_SPEC: &str = "@google/gemini-cli@latest";
28
29#[derive(Clone)]
31struct AntigravityCompatibilitySnapshot {
32 fingerprint: Option<AntigravityExecutableFingerprint>,
33 result: Result<(), String>,
34}
35
36#[derive(Clone, Debug, PartialEq, Eq)]
38struct AntigravityExecutableFingerprint {
39 device: u64,
40 inode: u64,
41 length: u64,
42 mode: u32,
43 modified_nanoseconds: i64,
44 modified_seconds: i64,
45 path: PathBuf,
46}
47
48static ANTIGRAVITY_COMPATIBILITY: OnceLock<Mutex<Option<AntigravityCompatibilitySnapshot>>> =
51 OnceLock::new();
52
53struct AgentCliUpdateCommand {
55 args: &'static [&'static str],
56 executable_path: PathBuf,
57}
58
59impl AgentCliUpdateCommand {
60 fn new(executable_path: PathBuf, args: &'static [&'static str]) -> Self {
62 Self {
63 args,
64 executable_path,
65 }
66 }
67}
68
69#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
71pub trait AgentAvailabilityProbe: Send + Sync {
72 fn available_agent_kinds(&self) -> Vec<AgentKind>;
74
75 fn available_agent_clis(&self) -> Vec<AgentCliInfo> {
77 AgentCliInfo::from_kinds(&self.available_agent_kinds())
78 }
79}
80
81pub struct RealAgentAvailabilityProbe;
83
84impl AgentAvailabilityProbe for RealAgentAvailabilityProbe {
85 fn available_agent_kinds(&self) -> Vec<AgentKind> {
86 available_agent_kinds_from_path(env::var_os("PATH").as_deref())
87 }
88
89 fn available_agent_clis(&self) -> Vec<AgentCliInfo> {
90 available_agent_clis_from_path(env::var_os("PATH").as_deref())
91 }
92}
93
94pub struct StaticAgentAvailabilityProbe {
96 pub available_agent_kinds: Vec<AgentKind>,
98}
99
100impl AgentAvailabilityProbe for StaticAgentAvailabilityProbe {
101 fn available_agent_kinds(&self) -> Vec<AgentKind> {
102 self.available_agent_kinds.clone()
103 }
104}
105
106#[must_use]
108pub fn executable_name(agent_kind: AgentKind) -> &'static str {
109 agent_kind.executable_name()
110}
111
112fn available_agent_clis_from_path(path_value: Option<&OsStr>) -> Vec<AgentCliInfo> {
114 let executable_agent_clis = AgentKind::ALL
115 .iter()
116 .copied()
117 .filter_map(|agent_kind| {
118 let executable_path = executable_path_on_path(path_value, executable_name(agent_kind))?;
119
120 Some((agent_kind, executable_path))
121 })
122 .collect();
123
124 refresh_agent_cli_versions(executable_agent_clis, |agent_kind, executable_path| {
125 refresh_agent_cli_version(agent_kind, executable_path, path_value)
126 })
127}
128
129fn available_agent_kinds_from_path(path_value: Option<&OsStr>) -> Vec<AgentKind> {
131 AgentKind::ALL
132 .iter()
133 .copied()
134 .filter(|agent_kind| {
135 if *agent_kind == AgentKind::Antigravity {
136 return ensure_antigravity_cli_supported_on_path(path_value).is_ok();
137 }
138
139 executable_path_on_path(path_value, executable_name(*agent_kind)).is_some()
140 })
141 .collect()
142}
143
144fn ensure_antigravity_cli_supported_on_path(path_value: Option<&OsStr>) -> Result<(), String> {
146 let Some(executable_path) =
147 executable_path_on_path(path_value, executable_name(AgentKind::Antigravity))
148 else {
149 let result = Err(format!(
150 "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but `agy` was \
151 not found on `PATH`. Install it or run `agy update`, then restart Agentty."
152 ));
153
154 cache_antigravity_cli_support(None, result.clone());
155
156 return result;
157 };
158 let detected_version = detect_agent_cli_version(&executable_path);
159 let result = validate_antigravity_cli_version(detected_version.as_deref());
160
161 cache_antigravity_cli_support(Some(&executable_path), result.clone());
162
163 result
164}
165
166pub(super) fn ensure_cached_antigravity_cli_supported_on_path(
168 path_value: Option<&OsStr>,
169) -> Result<(), String> {
170 let executable_path =
171 executable_path_on_path(path_value, executable_name(AgentKind::Antigravity));
172 let current_fingerprint = executable_path
173 .as_deref()
174 .and_then(antigravity_executable_fingerprint);
175 let snapshot = ANTIGRAVITY_COMPATIBILITY
176 .get_or_init(|| Mutex::new(None))
177 .lock()
178 .ok()
179 .and_then(|snapshot| snapshot.clone());
180
181 validate_cached_antigravity_cli_support(snapshot.as_ref(), current_fingerprint.as_ref())
182}
183
184fn validate_cached_antigravity_cli_support(
186 snapshot: Option<&AntigravityCompatibilitySnapshot>,
187 current_fingerprint: Option<&AntigravityExecutableFingerprint>,
188) -> Result<(), String> {
189 let Some(snapshot) = snapshot else {
190 return Err(
191 "Antigravity CLI has not been validated yet. Wait for CLI discovery to finish or \
192 restart Agentty, then retry."
193 .to_string(),
194 );
195 };
196 if snapshot.fingerprint.as_ref() != current_fingerprint {
197 return Err(
198 "Antigravity CLI installation changed after Agentty validated it. Wait for CLI \
199 discovery to finish or restart Agentty, then retry."
200 .to_string(),
201 );
202 }
203
204 snapshot.result.clone()
205}
206
207fn cache_antigravity_cli_support(executable_path: Option<&Path>, result: Result<(), String>) {
209 let snapshot = AntigravityCompatibilitySnapshot {
210 fingerprint: executable_path.and_then(antigravity_executable_fingerprint),
211 result,
212 };
213 if let Ok(mut cached_snapshot) = ANTIGRAVITY_COMPATIBILITY
214 .get_or_init(|| Mutex::new(None))
215 .lock()
216 {
217 *cached_snapshot = Some(snapshot);
218 }
219}
220
221fn antigravity_executable_fingerprint(
223 executable_path: &Path,
224) -> Option<AntigravityExecutableFingerprint> {
225 let metadata = executable_path.metadata().ok()?;
226
227 Some(AntigravityExecutableFingerprint {
228 device: metadata.dev(),
229 inode: metadata.ino(),
230 length: metadata.len(),
231 modified_nanoseconds: metadata.mtime_nsec(),
232 modified_seconds: metadata.mtime(),
233 mode: metadata.mode(),
234 path: executable_path.to_path_buf(),
235 })
236}
237
238fn validate_antigravity_cli_version(detected_version: Option<&str>) -> Result<(), String> {
241 let Some(detected_version) = detected_version else {
242 return Err(format!(
243 "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but `agy \
244 --version` did not report a version. Run `agy update`, then retry."
245 ));
246 };
247 let normalized_version = detected_version
248 .strip_prefix('v')
249 .unwrap_or(detected_version);
250 let parsed_version = Version::parse(normalized_version).map_err(|_| {
251 format!(
252 "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but `agy \
253 --version` reported `{detected_version}`. Run `agy update`, then retry."
254 )
255 })?;
256 if parsed_version < ANTIGRAVITY_MINIMUM_VERSION {
257 return Err(format!(
258 "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but \
259 `{detected_version}` is installed. Run `agy update`, then retry."
260 ));
261 }
262
263 Ok(())
264}
265
266fn executable_path_on_path(path_value: Option<&OsStr>, executable_name: &str) -> Option<PathBuf> {
268 path_value
269 .map(env::split_paths)
270 .into_iter()
271 .flatten()
272 .map(|path_entry| candidate_path_for_executable_name(&path_entry, executable_name))
273 .find(|candidate_path| is_executable_file(candidate_path))
274}
275
276fn candidate_path_for_executable_name(path_entry: &Path, executable_name: &str) -> PathBuf {
279 path_entry.join(executable_name)
280}
281
282fn is_executable_file(candidate_path: &Path) -> bool {
285 let Ok(metadata) = candidate_path.metadata() else {
286 return false;
287 };
288
289 if !metadata.is_file() {
290 return false;
291 }
292
293 metadata.permissions().mode() & 0o111 != 0
294}
295
296fn refresh_agent_cli_version(
299 agent_kind: AgentKind,
300 executable_path: &Path,
301 path_value: Option<&OsStr>,
302) -> Option<String> {
303 run_agent_cli_update(agent_kind, executable_path, path_value);
304
305 let detected_version = detect_agent_cli_version(executable_path);
306 if agent_kind == AgentKind::Antigravity {
307 let result = validate_antigravity_cli_version(detected_version.as_deref());
308 cache_antigravity_cli_support(Some(executable_path), result);
309 }
310
311 detected_version
312}
313
314fn refresh_agent_cli_versions(
317 executable_agent_clis: Vec<(AgentKind, PathBuf)>,
318 refresh_cli_version: impl Fn(AgentKind, &Path) -> Option<String> + Sync,
319) -> Vec<AgentCliInfo> {
320 std::thread::scope(|scope| {
321 let refresh_cli_version = &refresh_cli_version;
322 let refresh_handles = executable_agent_clis
323 .into_iter()
324 .map(|(agent_kind, executable_path)| {
325 (
326 agent_kind,
327 scope.spawn(move || refresh_cli_version(agent_kind, &executable_path)),
328 )
329 })
330 .collect::<Vec<_>>();
331
332 refresh_handles
333 .into_iter()
334 .map(|(agent_kind, refresh_handle)| {
335 AgentCliInfo::new(agent_kind, refresh_handle.join().unwrap_or(None))
336 })
337 .collect()
338 })
339}
340
341fn run_agent_cli_update(agent_kind: AgentKind, executable_path: &Path, path_value: Option<&OsStr>) {
343 let _ = run_agent_cli_update_with_timeout(
344 agent_kind,
345 executable_path,
346 path_value,
347 AGENT_CLI_UPDATE_TIMEOUT,
348 );
349}
350
351fn run_agent_cli_update_with_timeout(
353 agent_kind: AgentKind,
354 executable_path: &Path,
355 path_value: Option<&OsStr>,
356 timeout: Duration,
357) -> bool {
358 let Some(update_command) = agent_cli_update_command(agent_kind, executable_path, path_value)
359 else {
360 return false;
361 };
362
363 command_status_with_timeout(&update_command, timeout).is_some()
364}
365
366fn agent_cli_update_command(
368 agent_kind: AgentKind,
369 executable_path: &Path,
370 path_value: Option<&OsStr>,
371) -> Option<AgentCliUpdateCommand> {
372 if agent_kind == AgentKind::Gemini {
373 return gemini_npm_update_command(executable_path, path_value);
374 }
375
376 Some(AgentCliUpdateCommand::new(
377 executable_path.to_path_buf(),
378 &["update"],
379 ))
380}
381
382fn gemini_npm_update_command(
388 executable_path: &Path,
389 path_value: Option<&OsStr>,
390) -> Option<AgentCliUpdateCommand> {
391 let canonical_executable_path = executable_path.canonicalize().ok()?;
392 let normalized_executable_path = canonical_executable_path.to_string_lossy();
393 if !normalized_executable_path.contains(GEMINI_NPM_PACKAGE_PATH) {
394 return None;
395 }
396
397 let npm_executable_path = executable_path_on_path(path_value, "npm")?;
398
399 Some(AgentCliUpdateCommand::new(
400 npm_executable_path,
401 &["install", "-g", GEMINI_NPM_PACKAGE_SPEC],
402 ))
403}
404
405fn detect_agent_cli_version(executable_path: &Path) -> Option<String> {
408 detect_agent_cli_version_with_timeout(executable_path, AGENT_CLI_VERSION_TIMEOUT)
409}
410
411fn detect_agent_cli_version_with_timeout(
413 executable_path: &Path,
414 timeout: Duration,
415) -> Option<String> {
416 let output = version_command_output(executable_path, timeout)?;
417 if !output.status.success() {
418 return None;
419 }
420
421 let stdout_text = String::from_utf8_lossy(&output.stdout);
422 let stderr_text = String::from_utf8_lossy(&output.stderr);
423 parse_agent_cli_version_output(&stdout_text)
424 .or_else(|| parse_agent_cli_version_output(&stderr_text))
425}
426
427fn version_command_output(executable_path: &Path, timeout: Duration) -> Option<Output> {
430 command_output_with_timeout(executable_path, &["--version"], timeout)
431}
432
433fn command_status_with_timeout(
436 update_command: &AgentCliUpdateCommand,
437 timeout: Duration,
438) -> Option<()> {
439 let mut child = Command::new(&update_command.executable_path)
440 .args(update_command.args)
441 .stdin(Stdio::null())
442 .stdout(Stdio::null())
443 .stderr(Stdio::null())
444 .spawn()
445 .ok()?;
446 wait_for_child_exit(&mut child, timeout)?;
447 let _ = child.wait().ok()?;
448
449 Some(())
450}
451
452fn command_output_with_timeout(
454 executable_path: &Path,
455 args: &[&str],
456 timeout: Duration,
457) -> Option<Output> {
458 let mut child = Command::new(executable_path)
459 .args(args)
460 .stdin(Stdio::null())
461 .stdout(Stdio::piped())
462 .stderr(Stdio::piped())
463 .spawn()
464 .ok()?;
465 wait_for_child_exit(&mut child, timeout)?;
466
467 child.wait_with_output().ok()
468}
469
470fn wait_for_child_exit(child: &mut Child, timeout: Duration) -> Option<()> {
472 let started_at = Instant::now();
473
474 loop {
475 if child.try_wait().ok()?.is_some() {
476 return Some(());
477 }
478
479 if started_at.elapsed() >= timeout {
480 let _ = child.kill();
481 let _ = child.wait();
482
483 return None;
484 }
485
486 std::thread::sleep(
487 AGENT_CLI_COMMAND_POLL_INTERVAL.min(timeout.saturating_sub(started_at.elapsed())),
488 );
489 }
490}
491
492fn parse_agent_cli_version_output(output: &str) -> Option<String> {
495 let line = output
496 .lines()
497 .map(str::trim)
498 .find(|line| !line.is_empty())?;
499 let version_token = line
500 .split_whitespace()
501 .map(|token| {
502 token.trim_matches(|character: char| {
503 matches!(character, ',' | ';' | ':' | '(' | ')' | '[' | ']')
504 })
505 })
506 .find(|token| {
507 let normalized = token.strip_prefix('v').unwrap_or(token);
508
509 normalized
510 .chars()
511 .next()
512 .is_some_and(|character| character.is_ascii_digit())
513 && normalized.contains('.')
514 });
515
516 Some(version_token.unwrap_or(line).to_string())
517}
518
519#[cfg(test)]
520#[path = "availability_test.rs"]
521mod tests;