Skip to main content

agent_hub_runtime/core/
cli_bridge.rs

1//! The copy of `agent-hub-cli` that agents are told to run.
2//!
3//! The build wrapper explicitly stages the CLI as a Tauri sidecar, but
4//! the desktop bundle is not a stable location an agent can discover.
5//! On Linux the `.deb`/`.rpm` land it in `/usr/bin`, which is already on PATH;
6//! on macOS it sits inside the `.app`, and on Windows inside the install
7//! directory. Neither is on PATH, and putting it there is not ours to do:
8//! `/usr/local/bin` needs an admin prompt, `~/.local/bin` is not on the default
9//! macOS PATH at all, and Windows reserves symlink creation for administrators.
10//!
11//! So the app maintains its own copy at a fixed, predictable path instead, and
12//! the `agent-hub-cli` skill looks there first. A copy, not a symlink: an
13//! AppImage is mounted at a temporary path, and a `.app` the user drags
14//! elsewhere would leave a dangling link.
15//!
16//! ## Why the stamp file
17//!
18//! The copy can fail — on Windows the old binary may be running (an agent
19//! mid-command) or held by a virus scanner, and then the rename cannot replace
20//! it. A stale bridge is not merely out of date: before #363 the deploy path
21//! deleted a user's unmanaged directory outright, so an old binary can be one
22//! that destroys data a new one refuses to touch. The database's own
23//! `user_version` gate does not catch this, because such a fix carries no
24//! schema change.
25//!
26//! The stamp is therefore written last and removed first. Its presence means
27//! "a copy of exactly this version completed and ran"; its absence means the
28//! bridge must not be used, whether or not a binary is sitting there. It is a
29//! small text file, so it can still be removed when the locked binary cannot.
30
31use 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
52/// Where the bridge lives. Deliberately the home directory rather than
53/// `central_repo::base_dir()`: the library can be relocated to anywhere the
54/// user likes, and the skill has to be able to name this path without asking.
55/// Development build hooks may explicitly override it with AGENT_HUB_BRIDGE_DIR.
56pub 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
62/// Whether `name` is one of the files the bridge keeps in [`bridge_dir`].
63pub(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
75/// Refuse a copy invalidated by an interrupted publication, even if the binary remains.
76pub(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
102/// The CLI that shipped alongside the running app binary.
103fn 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
129/// An empty stamp counts as no stamp — that is how `invalidate_bridge` disables
130/// a file it cannot delete. The skill's own check uses `-s` for the same reason.
131fn 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
138/// Make the current bridge untrusted before touching the binary.
139///
140/// A stamp that survives a failed republish is the one way the whole scheme
141/// breaks: the old binary and its old stamp agree with each other, so nothing
142/// downstream can tell they are stale. Three fallbacks, cheapest first, each
143/// enough on its own to satisfy "an unstamped or absent binary is never run":
144///
145/// 1. unlink the stamp — the normal path;
146/// 2. truncate it — a file that cannot be removed but can still be written
147///    (the reader treats an empty stamp as no stamp);
148/// 3. remove the binary itself — on Windows a locked or read-only `.version`
149///    can defeat both of the above while the executable beside it is still
150///    removable, and no binary is as good as no stamp.
151///
152/// If none of them works, the publish is abandoned rather than run with a
153/// stamp that lies.
154fn 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
177/// Build the command that runs the published CLI, without a console window.
178///
179/// The CLI is a console-subsystem binary and the app is not, so spawning it
180/// plainly makes Windows open a console window for it — a black flash on the
181/// first launch after every install (#413). Every other spawn in this crate
182/// hides it the same way; a new one here has to as well.
183fn 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); // CREATE_NO_WINDOW
190    }
191    cmd
192}
193
194/// Linux may briefly retain a writer for a just-copied executable (for example,
195/// across another thread's fork). ETXTBSY means exec did not start the program;
196/// retry only that spawn failure, for at most 1.26 seconds.
197fn 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
219/// Run the freshly copied binary. A copy that cannot report its own version is
220/// truncated, blocked, or built for another architecture — publishing it would
221/// hand agents a binary that fails on first use.
222fn 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    // Whole-token equality, not `contains`: 1.35.1 would otherwise accept a
229    // binary reporting 1.35.10, and catching exactly that mismatch is the
230    // reason this check exists.
231    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
252/// Publish the bundled CLI to the bridge path, replacing whatever is there.
253///
254/// Best-effort by contract: every failure leaves the stamp absent and is
255/// logged, and the caller carries on. The app must start whether or not an
256/// agent can drive it.
257pub 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
269/// Publish the running CLI, even when Cargo gave it the unbranded target name.
270pub fn publish_current(app_version: &str) -> Result<PathBuf> {
271    // A CLI build always publishes its own companion, even when its parent
272    // terminal inherited a desktop development session's pinned sidecar.
273    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            // The stamp is the trust boundary. Keep invalidation under the
292            // same cross-process lock so a concurrent publisher cannot remove
293            // the next publisher's freshly written stamp.
294            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    // Rebuilding with the same VERSION can change the CLI and its database
329    // compatibility. A version-only fast path left an older binary stamped as
330    // current, so compare the bundled and published bytes before trusting it.
331    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    // From here the bridge is not to be trusted until the new copy lands.
345    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    // Copy beside the target so the rename stays on one filesystem.
351    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    // On Windows this fails while the old binary is running or held open by a
374    // scanner. That is the case the stamp exists for: the stale binary stays,
375    // unusable, rather than being silently presented as current.
376    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
393/// #487: right after `verify` ran the staged exe, Windows can still hold it
394/// for a moment (scanners inspect a freshly executed binary), so the rename
395/// fails with a sharing violation. Wait that out, ~2 s at most; any other
396/// error, or a lock that outlasts it, is reported as before.
397fn 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;