agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! The copy of `agent-hub-cli` that agents are told to run.
//!
//! The build wrapper explicitly stages the CLI as a Tauri sidecar, but
//! the desktop bundle is not a stable location an agent can discover.
//! On Linux the `.deb`/`.rpm` land it in `/usr/bin`, which is already on PATH;
//! on macOS it sits inside the `.app`, and on Windows inside the install
//! directory. Neither is on PATH, and putting it there is not ours to do:
//! `/usr/local/bin` needs an admin prompt, `~/.local/bin` is not on the default
//! macOS PATH at all, and Windows reserves symlink creation for administrators.
//!
//! So the app maintains its own copy at a fixed, predictable path instead, and
//! the `agent-hub-cli` skill looks there first. A copy, not a symlink: an
//! AppImage is mounted at a temporary path, and a `.app` the user drags
//! elsewhere would leave a dangling link.
//!
//! ## Why the stamp file
//!
//! The copy can fail — on Windows the old binary may be running (an agent
//! mid-command) or held by a virus scanner, and then the rename cannot replace
//! it. A stale bridge is not merely out of date: before #363 the deploy path
//! deleted a user's unmanaged directory outright, so an old binary can be one
//! that destroys data a new one refuses to touch. The database's own
//! `user_version` gate does not catch this, because such a fix carries no
//! schema change.
//!
//! The stamp is therefore written last and removed first. Its presence means
//! "a copy of exactly this version completed and ran"; its absence means the
//! bridge must not be used, whether or not a binary is sitting there. It is a
//! small text file, so it can still be removed when the locked binary cannot.

use anyhow::{bail, Context, Result};
use fs2::FileExt;
use sha2::{Digest, Sha256};
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::Command;

use super::central_repo;

fn bridge_bin_name() -> &'static str {
    static NAME: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    NAME.get_or_init(|| {
        format!(
            "{}{}",
            crate::product::cli_name(),
            std::env::consts::EXE_SUFFIX
        )
    })
}

/// Where the bridge lives. Deliberately the home directory rather than
/// `central_repo::base_dir()`: the library can be relocated to anywhere the
/// user likes, and the skill has to be able to name this path without asking.
/// Development build hooks may explicitly override it with AGENT_HUB_BRIDGE_DIR.
pub fn bridge_dir() -> PathBuf {
    std::env::var_os("AGENT_HUB_BRIDGE_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|| central_repo::product_home_base_dir().join("bin"))
}

/// Whether `name` is one of the files the bridge keeps in [`bridge_dir`].
pub(crate) fn is_bridge_file(name: &str) -> bool {
    name == bridge_bin_name()
        || name == ".version"
        || name == ".build-info.json"
        || name == ".publish.lock"
        || name == format!(".{}.staged", bridge_bin_name())
}

pub fn bridge_path() -> PathBuf {
    bridge_dir().join(bridge_bin_name())
}

/// Refuse a copy invalidated by an interrupted publication, even if the binary remains.
pub(crate) fn validated_path() -> Result<PathBuf> {
    let path = bridge_path();
    if read_stamp().as_deref() != Some(crate::product::version())
        || !matching_build_stamp()
        || !super::tool_detection::executable(&path)
    {
        bail!("AgentHub CLI bridge is unavailable or unverified; update the application before launching a terminal");
    }
    Ok(path)
}

fn build_stamp() -> serde_json::Value {
    serde_json::to_value(crate::product::current()).expect("build metadata is serializable")
}

fn matching_build_stamp() -> bool {
    std::fs::read(bridge_dir().join(".build-info.json"))
        .ok()
        .and_then(|raw| serde_json::from_slice::<serde_json::Value>(&raw).ok())
        .is_some_and(|value| value == build_stamp())
}

fn stamp_path() -> PathBuf {
    bridge_dir().join(".version")
}

/// The CLI that shipped alongside the running app binary.
fn bundled_cli(development_cli: Option<&Path>) -> Result<PathBuf> {
    let exe = std::env::current_exe().context("cannot locate the running executable")?;
    bundled_cli_at(&exe, development_cli)
}

fn bundled_cli_at(exe: &Path, development_cli: Option<&Path>) -> Result<PathBuf> {
    if let Some(path) = development_cli {
        if !path.is_absolute() || !path.is_file() {
            bail!("Prepared development companion CLI is unavailable");
        }
        return Ok(path.to_path_buf());
    }
    let dir = exe
        .parent()
        .context("the running executable has no parent directory")?;
    let candidate = dir.join(bridge_bin_name());
    if !candidate.is_file() {
        bail!(
            "this build does not ship {} next to the app binary ({})",
            bridge_bin_name(),
            dir.display()
        );
    }
    Ok(candidate)
}

/// An empty stamp counts as no stamp — that is how `invalidate_bridge` disables
/// a file it cannot delete. The skill's own check uses `-s` for the same reason.
fn read_stamp() -> Option<String> {
    std::fs::read_to_string(stamp_path())
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// Make the current bridge untrusted before touching the binary.
///
/// A stamp that survives a failed republish is the one way the whole scheme
/// breaks: the old binary and its old stamp agree with each other, so nothing
/// downstream can tell they are stale. Three fallbacks, cheapest first, each
/// enough on its own to satisfy "an unstamped or absent binary is never run":
///
/// 1. unlink the stamp — the normal path;
/// 2. truncate it — a file that cannot be removed but can still be written
///    (the reader treats an empty stamp as no stamp);
/// 3. remove the binary itself — on Windows a locked or read-only `.version`
///    can defeat both of the above while the executable beside it is still
///    removable, and no binary is as good as no stamp.
///
/// If none of them works, the publish is abandoned rather than run with a
/// stamp that lies.
fn invalidate_bridge() -> Result<()> {
    let stamp = stamp_path();
    match std::fs::remove_file(&stamp) {
        Ok(()) => return Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => log::warn!("cli bridge: could not remove {}: {e}", stamp.display()),
    }
    if std::fs::write(&stamp, b"").is_ok() {
        return Ok(());
    }
    log::warn!("cli bridge: could not truncate {}", stamp.display());
    let binary = bridge_path();
    match std::fs::remove_file(&binary) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(anyhow::Error::new(e).context(format!(
            "cannot invalidate the published CLI: neither {} nor {} could be removed",
            stamp.display(),
            binary.display()
        ))),
    }
}

/// Build the command that runs the published CLI, without a console window.
///
/// The CLI is a console-subsystem binary and the app is not, so spawning it
/// plainly makes Windows open a console window for it — a black flash on the
/// first launch after every install (#413). Every other spawn in this crate
/// hides it the same way; a new one here has to as well.
fn cli_command(path: &Path) -> Command {
    #[allow(unused_mut)]
    let mut cmd = Command::new(path);
    #[cfg(target_os = "windows")]
    {
        use std::os::windows::process::CommandExt;
        cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
    }
    cmd
}

/// Linux may briefly retain a writer for a just-copied executable (for example,
/// across another thread's fork). ETXTBSY means exec did not start the program;
/// retry only that spawn failure, for at most 1.26 seconds.
fn cli_output(path: &Path, args: &[&str]) -> std::io::Result<std::process::Output> {
    let mut command = cli_command(path);
    command.args(args);
    #[cfg(not(target_os = "linux"))]
    {
        command.output()
    }
    #[cfg(target_os = "linux")]
    {
        let mut retries = 0;
        loop {
            match command.output() {
                Err(error) if error.raw_os_error() == Some(libc::ETXTBSY) && retries < 6 => {
                    std::thread::sleep(std::time::Duration::from_millis(20 << retries));
                    retries += 1;
                }
                result => return result,
            }
        }
    }
}

/// Run the freshly copied binary. A copy that cannot report its own version is
/// truncated, blocked, or built for another architecture — publishing it would
/// hand agents a binary that fails on first use.
fn verify(path: &Path, expected_version: &str) -> Result<()> {
    let output = cli_output(path, &["--version"])
        .with_context(|| format!("could not run {}", path.display()))?;
    if !output.status.success() {
        bail!("{} --version exited with {}", path.display(), output.status);
    }
    // Whole-token equality, not `contains`: 1.35.1 would otherwise accept a
    // binary reporting 1.35.10, and catching exactly that mismatch is the
    // reason this check exists.
    let reported = String::from_utf8_lossy(&output.stdout);
    let version = reported.split_whitespace().last().unwrap_or_default();
    if version != expected_version {
        bail!(
            "{} reports {:?}, expected version {expected_version}",
            path.display(),
            reported.trim()
        );
    }
    let output = cli_output(path, &["--json", "build-info"])?;
    if !output.status.success()
        || serde_json::from_slice::<serde_json::Value>(&output.stdout)
            .ok()
            .as_ref()
            != Some(&build_stamp())
    {
        bail!("Companion CLI product configuration does not match this application");
    }
    Ok(())
}

/// Publish the bundled CLI to the bridge path, replacing whatever is there.
///
/// Best-effort by contract: every failure leaves the stamp absent and is
/// logged, and the caller carries on. The app must start whether or not an
/// agent can drive it.
pub fn ensure_bridge(app_version: &str) {
    let development_cli = if cfg!(debug_assertions) {
        std::env::var_os("AGENT_HUB_DEV_CLI").map(PathBuf::from)
    } else {
        None
    };
    match publish_current_from(app_version, development_cli.as_deref()) {
        Ok(path) => log::info!("cli bridge: ready at {}", path.display()),
        Err(e) => log::warn!("cli bridge: not available: {e:#}"),
    }
}

/// Publish the running CLI, even when Cargo gave it the unbranded target name.
pub fn publish_current(app_version: &str) -> Result<PathBuf> {
    // A CLI build always publishes its own companion, even when its parent
    // terminal inherited a desktop development session's pinned sidecar.
    let executable = std::env::current_exe().context("could not locate the running CLI")?;
    publish_current_from(app_version, Some(&executable))
}

fn publish_current_from(app_version: &str, development_cli: Option<&Path>) -> Result<PathBuf> {
    let _lock = bridge_publish_lock()?;
    let source = match bundled_cli(development_cli) {
        Ok(source) => source,
        Err(error) => {
            if let Err(invalidate_error) = invalidate_bridge() {
                log::warn!("cli bridge: could not invalidate old copy: {invalidate_error:#}");
            }
            return Err(error);
        }
    };
    match ensure_bridge_from(&source, app_version) {
        Ok(path) => Ok(path),
        Err(error) => {
            // The stamp is the trust boundary. Keep invalidation under the
            // same cross-process lock so a concurrent publisher cannot remove
            // the next publisher's freshly written stamp.
            if let Err(invalidate_error) = invalidate_bridge() {
                log::warn!("cli bridge: could not invalidate old copy: {invalidate_error:#}");
            }
            Err(error)
        }
    }
}

fn bridge_publish_lock() -> Result<File> {
    let directory = bridge_dir();
    std::fs::create_dir_all(&directory)
        .with_context(|| format!("could not create {}", directory.display()))?;
    let lock = File::create(directory.join(".publish.lock"))
        .with_context(|| format!("could not open CLI bridge lock in {}", directory.display()))?;
    lock.lock_exclusive()
        .context("could not lock CLI bridge publication")?;
    Ok(lock)
}

fn file_digest(path: &Path) -> Result<[u8; 32]> {
    let mut file = std::fs::File::open(path)?;
    let mut digest = Sha256::new();
    let mut buffer = [0u8; 8192];
    loop {
        let count = file.read(&mut buffer)?;
        if count == 0 {
            break;
        }
        digest.update(&buffer[..count]);
    }
    Ok(digest.finalize().into())
}

fn ensure_bridge_from(source: &Path, app_version: &str) -> Result<PathBuf> {
    // Rebuilding with the same VERSION can change the CLI and its database
    // compatibility. A version-only fast path left an older binary stamped as
    // current, so compare the bundled and published bytes before trusting it.
    if read_stamp().as_deref() == Some(app_version)
        && matching_build_stamp()
        && bridge_path().is_file()
        && file_digest(source)? == file_digest(&bridge_path())?
    {
        return Ok(bridge_path());
    }
    publish_from(source, app_version)
}

fn publish_from(source: &Path, app_version: &str) -> Result<PathBuf> {
    let target = bridge_path();

    // From here the bridge is not to be trusted until the new copy lands.
    invalidate_bridge()?;

    let dir = bridge_dir();
    std::fs::create_dir_all(&dir).with_context(|| format!("could not create {}", dir.display()))?;

    // Copy beside the target so the rename stays on one filesystem.
    let staged = dir.join(format!(".{}.staged", bridge_bin_name()));
    let _ = std::fs::remove_file(&staged);
    std::fs::copy(source, &staged).with_context(|| {
        format!(
            "could not copy {} to {}",
            source.display(),
            staged.display()
        )
    })?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755))
            .context("could not make the staged CLI executable")?;
    }

    if let Err(e) = verify(&staged, app_version) {
        let _ = std::fs::remove_file(&staged);
        return Err(e);
    }

    // On Windows this fails while the old binary is running or held open by a
    // scanner. That is the case the stamp exists for: the stale binary stays,
    // unusable, rather than being silently presented as current.
    rename_retrying_sharing_violation(&staged, &target)
        .with_context(|| format!("could not replace {} (it may be in use)", target.display()))?;

    std::fs::write(
        dir.join(".build-info.json"),
        serde_json::to_vec(&build_stamp())?,
    )?;
    std::fs::write(stamp_path(), app_version)
        .with_context(|| format!("could not write {}", stamp_path().display()))?;

    log::info!(
        "cli bridge: published {app_version} to {}",
        target.display()
    );
    Ok(target)
}

/// #487: right after `verify` ran the staged exe, Windows can still hold it
/// for a moment (scanners inspect a freshly executed binary), so the rename
/// fails with a sharing violation. Wait that out, ~2 s at most; any other
/// error, or a lock that outlasts it, is reported as before.
fn rename_retrying_sharing_violation(from: &Path, to: &Path) -> std::io::Result<()> {
    const ERROR_SHARING_VIOLATION: i32 = 32;
    let mut attempts = 0;
    loop {
        match std::fs::rename(from, to) {
            Err(e)
                if cfg!(windows)
                    && e.raw_os_error() == Some(ERROR_SHARING_VIOLATION)
                    && attempts < 10 =>
            {
                attempts += 1;
                std::thread::sleep(std::time::Duration::from_millis(200));
            }
            result => return result,
        }
    }
}

#[cfg(test)]
mod tests;