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_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
19const ANTIGRAVITY_MINIMUM_VERSION: Version = Version::new(1, 5, 8);
22const AGENT_CLI_VERSION_TIMEOUT: Duration = Duration::from_secs(2);
24const AGENT_CLI_UPDATE_TIMEOUT: Duration = Duration::from_mins(5);
26const AGENT_CLI_COMMAND_POLL_INTERVAL: Duration = Duration::from_millis(25);
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
53pub struct RealAgentAvailabilityProbe;
55
56#[async_trait]
57impl AgentAvailabilityProbe for RealAgentAvailabilityProbe {
58 fn available_agent_kinds(&self) -> Vec<AgentKind> {
59 available_agent_kinds_from_path(env::var_os("PATH").as_deref())
60 }
61
62 fn available_agent_clis(&self) -> Vec<AgentCliInfo> {
63 available_agent_clis_from_path(env::var_os("PATH").as_deref())
64 }
65
66 async fn native_harness_models(&self) -> Vec<HarnessModelOption> {
67 super::native::harness_models(&super::native::process_environment(), chatgpt_is_signed_in)
68 .await
69 }
70
71 async fn sign_in_chatgpt(
72 &self,
73 on_url: ChatGptSignInUrlHandler,
74 ) -> Result<ChatGptSignInOutcome, String> {
75 super::native::sign_in_chatgpt(&super::native::process_environment(), on_url).await
76 }
77}
78
79#[must_use]
82pub fn executable_name(agent_kind: AgentKind) -> Option<&'static str> {
83 agent_kind.executable_name()
84}
85
86fn available_agent_clis_from_path(path_value: Option<&OsStr>) -> Vec<AgentCliInfo> {
88 let executable_agent_clis = AgentKind::ALL
89 .iter()
90 .copied()
91 .filter_map(|agent_kind| {
92 let executable_path =
93 executable_path_on_path(path_value, executable_name(agent_kind)?)?;
94
95 Some((agent_kind, executable_path))
96 })
97 .collect();
98
99 refresh_agent_cli_versions(executable_agent_clis, refresh_agent_cli_version)
100}
101
102fn available_agent_kinds_from_path(path_value: Option<&OsStr>) -> Vec<AgentKind> {
104 AgentKind::ALL
105 .iter()
106 .copied()
107 .filter(|agent_kind| {
108 if *agent_kind == AgentKind::Antigravity {
109 return ensure_antigravity_cli_supported_on_path(path_value).is_ok();
110 }
111
112 executable_name(*agent_kind)
113 .and_then(|name| executable_path_on_path(path_value, name))
114 .is_some()
115 })
116 .collect()
117}
118
119fn ensure_antigravity_cli_supported_on_path(path_value: Option<&OsStr>) -> Result<(), String> {
121 let Some(executable_path) = executable_name(AgentKind::Antigravity)
122 .and_then(|name| executable_path_on_path(path_value, name))
123 else {
124 let result = Err(format!(
125 "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but `agy` was \
126 not found on `PATH`. Install it or run `agy update`, then restart Agentty."
127 ));
128
129 cache_antigravity_cli_support(None, result.clone());
130
131 return result;
132 };
133 let detected_version = detect_agent_cli_version(&executable_path);
134 let result = validate_antigravity_cli_version(detected_version.as_deref());
135
136 cache_antigravity_cli_support(Some(&executable_path), result.clone());
137
138 result
139}
140
141pub(super) fn ensure_cached_antigravity_cli_supported_on_path(
143 path_value: Option<&OsStr>,
144) -> Result<(), String> {
145 let executable_path = executable_name(AgentKind::Antigravity)
146 .and_then(|name| executable_path_on_path(path_value, name));
147 let current_fingerprint = executable_path
148 .as_deref()
149 .and_then(antigravity_executable_fingerprint);
150 let snapshot = ANTIGRAVITY_COMPATIBILITY
151 .get_or_init(|| Mutex::new(None))
152 .lock()
153 .ok()
154 .and_then(|snapshot| snapshot.clone());
155
156 validate_cached_antigravity_cli_support(snapshot.as_ref(), current_fingerprint.as_ref())
157}
158
159fn validate_cached_antigravity_cli_support(
161 snapshot: Option<&AntigravityCompatibilitySnapshot>,
162 current_fingerprint: Option<&AntigravityExecutableFingerprint>,
163) -> Result<(), String> {
164 let Some(snapshot) = snapshot else {
165 return Err(
166 "Antigravity CLI has not been validated yet. Wait for CLI discovery to finish or \
167 restart Agentty, then retry."
168 .to_string(),
169 );
170 };
171 if snapshot.fingerprint.as_ref() != current_fingerprint {
172 return Err(
173 "Antigravity CLI installation changed after Agentty validated it. Wait for CLI \
174 discovery to finish or restart Agentty, then retry."
175 .to_string(),
176 );
177 }
178
179 snapshot.result.clone()
180}
181
182fn cache_antigravity_cli_support(executable_path: Option<&Path>, result: Result<(), String>) {
184 let snapshot = AntigravityCompatibilitySnapshot {
185 fingerprint: executable_path.and_then(antigravity_executable_fingerprint),
186 result,
187 };
188 if let Ok(mut cached_snapshot) = ANTIGRAVITY_COMPATIBILITY
189 .get_or_init(|| Mutex::new(None))
190 .lock()
191 {
192 *cached_snapshot = Some(snapshot);
193 }
194}
195
196fn antigravity_executable_fingerprint(
198 executable_path: &Path,
199) -> Option<AntigravityExecutableFingerprint> {
200 let metadata = executable_path.metadata().ok()?;
201
202 Some(AntigravityExecutableFingerprint {
203 device: metadata.dev(),
204 inode: metadata.ino(),
205 length: metadata.len(),
206 modified_nanoseconds: metadata.mtime_nsec(),
207 modified_seconds: metadata.mtime(),
208 mode: metadata.mode(),
209 path: executable_path.to_path_buf(),
210 })
211}
212
213fn validate_antigravity_cli_version(detected_version: Option<&str>) -> Result<(), String> {
216 let Some(detected_version) = detected_version else {
217 return Err(format!(
218 "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but `agy \
219 --version` did not report a version. Run `agy update`, then retry."
220 ));
221 };
222 let normalized_version = detected_version
223 .strip_prefix('v')
224 .unwrap_or(detected_version);
225 let parsed_version = Version::parse(normalized_version).map_err(|_| {
226 format!(
227 "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but `agy \
228 --version` reported `{detected_version}`. Run `agy update`, then retry."
229 )
230 })?;
231 if parsed_version < ANTIGRAVITY_MINIMUM_VERSION {
232 return Err(format!(
233 "Antigravity CLI {ANTIGRAVITY_MINIMUM_VERSION} or newer is required, but \
234 `{detected_version}` is installed. Run `agy update`, then retry."
235 ));
236 }
237
238 Ok(())
239}
240
241fn executable_path_on_path(path_value: Option<&OsStr>, executable_name: &str) -> Option<PathBuf> {
243 path_value
244 .map(env::split_paths)
245 .into_iter()
246 .flatten()
247 .map(|path_entry| candidate_path_for_executable_name(&path_entry, executable_name))
248 .find(|candidate_path| is_executable_file(candidate_path))
249}
250
251fn candidate_path_for_executable_name(path_entry: &Path, executable_name: &str) -> PathBuf {
254 path_entry.join(executable_name)
255}
256
257fn is_executable_file(candidate_path: &Path) -> bool {
260 let Ok(metadata) = candidate_path.metadata() else {
261 return false;
262 };
263
264 if !metadata.is_file() {
265 return false;
266 }
267
268 metadata.permissions().mode() & 0o111 != 0
269}
270
271fn refresh_agent_cli_version(agent_kind: AgentKind, executable_path: &Path) -> Option<String> {
274 let _ = run_agent_cli_update_with_timeout(executable_path, AGENT_CLI_UPDATE_TIMEOUT);
275
276 let detected_version = detect_agent_cli_version(executable_path);
277 if agent_kind == AgentKind::Antigravity {
278 let result = validate_antigravity_cli_version(detected_version.as_deref());
279 cache_antigravity_cli_support(Some(executable_path), result);
280 }
281
282 detected_version
283}
284
285fn refresh_agent_cli_versions(
288 executable_agent_clis: Vec<(AgentKind, PathBuf)>,
289 refresh_cli_version: impl Fn(AgentKind, &Path) -> Option<String> + Sync,
290) -> Vec<AgentCliInfo> {
291 std::thread::scope(|scope| {
292 let refresh_cli_version = &refresh_cli_version;
293 let refresh_handles = executable_agent_clis
294 .into_iter()
295 .map(|(agent_kind, executable_path)| {
296 (
297 agent_kind,
298 scope.spawn(move || refresh_cli_version(agent_kind, &executable_path)),
299 )
300 })
301 .collect::<Vec<_>>();
302
303 refresh_handles
304 .into_iter()
305 .map(|(agent_kind, refresh_handle)| {
306 AgentCliInfo::new(agent_kind, refresh_handle.join().unwrap_or(None))
307 })
308 .collect()
309 })
310}
311
312fn run_agent_cli_update_with_timeout(executable_path: &Path, timeout: Duration) -> bool {
315 command_status_with_timeout(executable_path, &["update"], timeout).is_some()
316}
317
318fn detect_agent_cli_version(executable_path: &Path) -> Option<String> {
321 detect_agent_cli_version_with_timeout(executable_path, AGENT_CLI_VERSION_TIMEOUT)
322}
323
324fn detect_agent_cli_version_with_timeout(
326 executable_path: &Path,
327 timeout: Duration,
328) -> Option<String> {
329 let output = version_command_output(executable_path, timeout)?;
330 if !output.status.success() {
331 return None;
332 }
333
334 let stdout_text = String::from_utf8_lossy(&output.stdout);
335 let stderr_text = String::from_utf8_lossy(&output.stderr);
336 parse_agent_cli_version_output(&stdout_text)
337 .or_else(|| parse_agent_cli_version_output(&stderr_text))
338}
339
340fn version_command_output(executable_path: &Path, timeout: Duration) -> Option<Output> {
343 command_output_with_timeout(executable_path, &["--version"], timeout)
344}
345
346fn command_status_with_timeout(
349 executable_path: &Path,
350 args: &[&str],
351 timeout: Duration,
352) -> Option<()> {
353 let mut child = Command::new(executable_path)
354 .args(args)
355 .stdin(Stdio::null())
356 .stdout(Stdio::null())
357 .stderr(Stdio::null())
358 .spawn()
359 .ok()?;
360 wait_for_child_exit(&mut child, timeout)?;
361 let _ = child.wait().ok()?;
362
363 Some(())
364}
365
366fn command_output_with_timeout(
368 executable_path: &Path,
369 args: &[&str],
370 timeout: Duration,
371) -> Option<Output> {
372 let mut child = Command::new(executable_path)
373 .args(args)
374 .stdin(Stdio::null())
375 .stdout(Stdio::piped())
376 .stderr(Stdio::piped())
377 .spawn()
378 .ok()?;
379 wait_for_child_exit(&mut child, timeout)?;
380
381 child.wait_with_output().ok()
382}
383
384fn wait_for_child_exit(child: &mut Child, timeout: Duration) -> Option<()> {
386 let started_at = Instant::now();
387
388 loop {
389 if child.try_wait().ok()?.is_some() {
390 return Some(());
391 }
392
393 if started_at.elapsed() >= timeout {
394 let _ = child.kill();
395 let _ = child.wait();
396
397 return None;
398 }
399
400 std::thread::sleep(
401 AGENT_CLI_COMMAND_POLL_INTERVAL.min(timeout.saturating_sub(started_at.elapsed())),
402 );
403 }
404}
405
406fn parse_agent_cli_version_output(output: &str) -> Option<String> {
409 let line = output
410 .lines()
411 .map(str::trim)
412 .find(|line| !line.is_empty())?;
413 let version_token = line
414 .split_whitespace()
415 .map(|token| {
416 token.trim_matches(|character: char| {
417 matches!(character, ',' | ';' | ':' | '(' | ')' | '[' | ']')
418 })
419 })
420 .find(|token| {
421 let normalized = token.strip_prefix('v').unwrap_or(token);
422
423 normalized
424 .chars()
425 .next()
426 .is_some_and(|character| character.is_ascii_digit())
427 && normalized.contains('.')
428 });
429
430 Some(version_token.unwrap_or(line).to_string())
431}
432
433#[cfg(test)]
434#[path = "availability_test.rs"]
435mod tests;