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