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