agent_hub_runtime/core/
cli_bridge.rs1use anyhow::{bail, Context, Result};
32use fs2::FileExt;
33use sha2::{Digest, Sha256};
34use std::fs::File;
35use std::io::Read;
36use std::path::{Path, PathBuf};
37use std::process::Command;
38
39use super::central_repo;
40
41fn bridge_bin_name() -> &'static str {
42 static NAME: std::sync::OnceLock<String> = std::sync::OnceLock::new();
43 NAME.get_or_init(|| {
44 format!(
45 "{}{}",
46 crate::product::cli_name(),
47 std::env::consts::EXE_SUFFIX
48 )
49 })
50}
51
52pub fn bridge_dir() -> PathBuf {
57 std::env::var_os("AGENT_HUB_BRIDGE_DIR")
58 .map(PathBuf::from)
59 .unwrap_or_else(|| central_repo::product_home_base_dir().join("bin"))
60}
61
62pub(crate) fn is_bridge_file(name: &str) -> bool {
64 name == bridge_bin_name()
65 || name == ".version"
66 || name == ".build-info.json"
67 || name == ".publish.lock"
68 || name == format!(".{}.staged", bridge_bin_name())
69}
70
71pub fn bridge_path() -> PathBuf {
72 bridge_dir().join(bridge_bin_name())
73}
74
75pub(crate) fn validated_path() -> Result<PathBuf> {
77 let path = bridge_path();
78 if read_stamp().as_deref() != Some(crate::product::version())
79 || !matching_build_stamp()
80 || !super::tool_detection::executable(&path)
81 {
82 bail!("AgentHub CLI bridge is unavailable or unverified; update the application before launching a terminal");
83 }
84 Ok(path)
85}
86
87fn build_stamp() -> serde_json::Value {
88 serde_json::to_value(crate::product::current()).expect("build metadata is serializable")
89}
90
91fn matching_build_stamp() -> bool {
92 std::fs::read(bridge_dir().join(".build-info.json"))
93 .ok()
94 .and_then(|raw| serde_json::from_slice::<serde_json::Value>(&raw).ok())
95 .is_some_and(|value| value == build_stamp())
96}
97
98fn stamp_path() -> PathBuf {
99 bridge_dir().join(".version")
100}
101
102fn bundled_cli(development_cli: Option<&Path>) -> Result<PathBuf> {
104 let exe = std::env::current_exe().context("cannot locate the running executable")?;
105 bundled_cli_at(&exe, development_cli)
106}
107
108fn bundled_cli_at(exe: &Path, development_cli: Option<&Path>) -> Result<PathBuf> {
109 if let Some(path) = development_cli {
110 if !path.is_absolute() || !path.is_file() {
111 bail!("Prepared development companion CLI is unavailable");
112 }
113 return Ok(path.to_path_buf());
114 }
115 let dir = exe
116 .parent()
117 .context("the running executable has no parent directory")?;
118 let candidate = dir.join(bridge_bin_name());
119 if !candidate.is_file() {
120 bail!(
121 "this build does not ship {} next to the app binary ({})",
122 bridge_bin_name(),
123 dir.display()
124 );
125 }
126 Ok(candidate)
127}
128
129fn read_stamp() -> Option<String> {
132 std::fs::read_to_string(stamp_path())
133 .ok()
134 .map(|s| s.trim().to_string())
135 .filter(|s| !s.is_empty())
136}
137
138fn invalidate_bridge() -> Result<()> {
155 let stamp = stamp_path();
156 match std::fs::remove_file(&stamp) {
157 Ok(()) => return Ok(()),
158 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
159 Err(e) => log::warn!("cli bridge: could not remove {}: {e}", stamp.display()),
160 }
161 if std::fs::write(&stamp, b"").is_ok() {
162 return Ok(());
163 }
164 log::warn!("cli bridge: could not truncate {}", stamp.display());
165 let binary = bridge_path();
166 match std::fs::remove_file(&binary) {
167 Ok(()) => Ok(()),
168 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
169 Err(e) => Err(anyhow::Error::new(e).context(format!(
170 "cannot invalidate the published CLI: neither {} nor {} could be removed",
171 stamp.display(),
172 binary.display()
173 ))),
174 }
175}
176
177fn cli_command(path: &Path) -> Command {
184 #[allow(unused_mut)]
185 let mut cmd = Command::new(path);
186 #[cfg(target_os = "windows")]
187 {
188 use std::os::windows::process::CommandExt;
189 cmd.creation_flags(0x08000000); }
191 cmd
192}
193
194fn cli_output(path: &Path, args: &[&str]) -> std::io::Result<std::process::Output> {
198 let mut command = cli_command(path);
199 command.args(args);
200 #[cfg(not(target_os = "linux"))]
201 {
202 command.output()
203 }
204 #[cfg(target_os = "linux")]
205 {
206 let mut retries = 0;
207 loop {
208 match command.output() {
209 Err(error) if error.raw_os_error() == Some(libc::ETXTBSY) && retries < 6 => {
210 std::thread::sleep(std::time::Duration::from_millis(20 << retries));
211 retries += 1;
212 }
213 result => return result,
214 }
215 }
216 }
217}
218
219fn verify(path: &Path, expected_version: &str) -> Result<()> {
223 let output = cli_output(path, &["--version"])
224 .with_context(|| format!("could not run {}", path.display()))?;
225 if !output.status.success() {
226 bail!("{} --version exited with {}", path.display(), output.status);
227 }
228 let reported = String::from_utf8_lossy(&output.stdout);
232 let version = reported.split_whitespace().last().unwrap_or_default();
233 if version != expected_version {
234 bail!(
235 "{} reports {:?}, expected version {expected_version}",
236 path.display(),
237 reported.trim()
238 );
239 }
240 let output = cli_output(path, &["--json", "build-info"])?;
241 if !output.status.success()
242 || serde_json::from_slice::<serde_json::Value>(&output.stdout)
243 .ok()
244 .as_ref()
245 != Some(&build_stamp())
246 {
247 bail!("Companion CLI product configuration does not match this application");
248 }
249 Ok(())
250}
251
252pub fn ensure_bridge(app_version: &str) {
258 let development_cli = if cfg!(debug_assertions) {
259 std::env::var_os("AGENT_HUB_DEV_CLI").map(PathBuf::from)
260 } else {
261 None
262 };
263 match publish_current_from(app_version, development_cli.as_deref()) {
264 Ok(path) => log::info!("cli bridge: ready at {}", path.display()),
265 Err(e) => log::warn!("cli bridge: not available: {e:#}"),
266 }
267}
268
269pub fn publish_current(app_version: &str) -> Result<PathBuf> {
271 let executable = std::env::current_exe().context("could not locate the running CLI")?;
274 publish_current_from(app_version, Some(&executable))
275}
276
277fn publish_current_from(app_version: &str, development_cli: Option<&Path>) -> Result<PathBuf> {
278 let _lock = bridge_publish_lock()?;
279 let source = match bundled_cli(development_cli) {
280 Ok(source) => source,
281 Err(error) => {
282 if let Err(invalidate_error) = invalidate_bridge() {
283 log::warn!("cli bridge: could not invalidate old copy: {invalidate_error:#}");
284 }
285 return Err(error);
286 }
287 };
288 match ensure_bridge_from(&source, app_version) {
289 Ok(path) => Ok(path),
290 Err(error) => {
291 if let Err(invalidate_error) = invalidate_bridge() {
295 log::warn!("cli bridge: could not invalidate old copy: {invalidate_error:#}");
296 }
297 Err(error)
298 }
299 }
300}
301
302fn bridge_publish_lock() -> Result<File> {
303 let directory = bridge_dir();
304 std::fs::create_dir_all(&directory)
305 .with_context(|| format!("could not create {}", directory.display()))?;
306 let lock = File::create(directory.join(".publish.lock"))
307 .with_context(|| format!("could not open CLI bridge lock in {}", directory.display()))?;
308 lock.lock_exclusive()
309 .context("could not lock CLI bridge publication")?;
310 Ok(lock)
311}
312
313fn file_digest(path: &Path) -> Result<[u8; 32]> {
314 let mut file = std::fs::File::open(path)?;
315 let mut digest = Sha256::new();
316 let mut buffer = [0u8; 8192];
317 loop {
318 let count = file.read(&mut buffer)?;
319 if count == 0 {
320 break;
321 }
322 digest.update(&buffer[..count]);
323 }
324 Ok(digest.finalize().into())
325}
326
327fn ensure_bridge_from(source: &Path, app_version: &str) -> Result<PathBuf> {
328 if read_stamp().as_deref() == Some(app_version)
332 && matching_build_stamp()
333 && bridge_path().is_file()
334 && file_digest(source)? == file_digest(&bridge_path())?
335 {
336 return Ok(bridge_path());
337 }
338 publish_from(source, app_version)
339}
340
341fn publish_from(source: &Path, app_version: &str) -> Result<PathBuf> {
342 let target = bridge_path();
343
344 invalidate_bridge()?;
346
347 let dir = bridge_dir();
348 std::fs::create_dir_all(&dir).with_context(|| format!("could not create {}", dir.display()))?;
349
350 let staged = dir.join(format!(".{}.staged", bridge_bin_name()));
352 let _ = std::fs::remove_file(&staged);
353 std::fs::copy(source, &staged).with_context(|| {
354 format!(
355 "could not copy {} to {}",
356 source.display(),
357 staged.display()
358 )
359 })?;
360
361 #[cfg(unix)]
362 {
363 use std::os::unix::fs::PermissionsExt;
364 std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755))
365 .context("could not make the staged CLI executable")?;
366 }
367
368 if let Err(e) = verify(&staged, app_version) {
369 let _ = std::fs::remove_file(&staged);
370 return Err(e);
371 }
372
373 rename_retrying_sharing_violation(&staged, &target)
377 .with_context(|| format!("could not replace {} (it may be in use)", target.display()))?;
378
379 std::fs::write(
380 dir.join(".build-info.json"),
381 serde_json::to_vec(&build_stamp())?,
382 )?;
383 std::fs::write(stamp_path(), app_version)
384 .with_context(|| format!("could not write {}", stamp_path().display()))?;
385
386 log::info!(
387 "cli bridge: published {app_version} to {}",
388 target.display()
389 );
390 Ok(target)
391}
392
393fn rename_retrying_sharing_violation(from: &Path, to: &Path) -> std::io::Result<()> {
398 const ERROR_SHARING_VIOLATION: i32 = 32;
399 let mut attempts = 0;
400 loop {
401 match std::fs::rename(from, to) {
402 Err(e)
403 if cfg!(windows)
404 && e.raw_os_error() == Some(ERROR_SHARING_VIOLATION)
405 && attempts < 10 =>
406 {
407 attempts += 1;
408 std::thread::sleep(std::time::Duration::from_millis(200));
409 }
410 result => return result,
411 }
412 }
413}
414
415#[cfg(test)]
416mod tests;