Skip to main content

agentmux_srv_core/backend/remote/
helper_install.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Installing AgentMux's helper (`agentmux-remote`) on an SSH host, for
5//! durable sessions (spec §6.2 of
6//! SPEC_REMOTE_TERMINALS_AND_DURABLE_SESSIONS_2026_10_02.md).
7//!
8//! 1. Probe the host over the pane's own ssh: `uname -sm`, and whether this
9//!    version's helper is already at `~/.agentmux-remote/bin/<version>/`.
10//! 2. Get the matching static build from this package, which carries all four
11//!    (`tools/remote/<target>/`, spec §9.1; on macOS the Linux builds sit in
12//!    `Contents/Resources/remote/<target>/`). A developer can point
13//!    `AGENTMUX_REMOTE_HELPER_DIR` at their own builds
14//!    (`scripts/build-remote-helpers.sh` writes the same layout).
15//! 3. Upload it over that ssh (`cat >` a temp file in an owner-only folder;
16//!    no scp or sftp needed on the host), check its hash there, then
17//!    `chmod 700` and move it into place.
18//!
19//! Every remote script runs under `sh -c '...'`, so it works whatever the
20//! user's login shell is.
21
22use std::path::{Path, PathBuf};
23
24use crate::backend::memory::record::sha256_hex;
25
26/// The helper's build target for `uname -sm` output (`Linux x86_64`,
27/// `Darwin arm64`, ...). `None` for a platform without a build.
28pub fn target_for(uname: &str) -> Option<&'static str> {
29    let mut words = uname.split_whitespace();
30    let os = words.next()?;
31    let arch = words.next()?;
32    Some(match (os, arch) {
33        ("Linux", "x86_64" | "amd64") => "x86_64-unknown-linux-musl",
34        ("Linux", "aarch64" | "arm64") => "aarch64-unknown-linux-musl",
35        ("Darwin", "x86_64") => "x86_64-apple-darwin",
36        ("Darwin", "arm64" | "aarch64") => "aarch64-apple-darwin",
37        _ => return None,
38    })
39}
40
41/// The flat name a build had as a release asset, `agentmux-remote-<version>-<target>`.
42/// Still accepted in `AGENTMUX_REMOTE_HELPER_DIR` beside the packaged layout.
43pub fn asset_name(version: &str, target: &str) -> String {
44    format!("agentmux-remote-{version}-{target}")
45}
46
47const HELPER_FILE: &str = "agentmux-remote";
48
49/// Where a package keeps the build for `target`, relative to srv's own folder
50/// (`exe_dir`): `tools/remote/<target>/` beside the other bundled tools, or, in
51/// a macOS app, `../Resources/remote/<target>/`, because the bundle seal only
52/// allows Mach-O code under `Contents/MacOS` and the Linux builds are data there.
53pub fn packaged_paths(exe_dir: &Path, target: &str) -> [PathBuf; 2] {
54    [
55        exe_dir.join("tools").join("remote").join(target).join(HELPER_FILE),
56        exe_dir.join("..").join("Resources").join("remote").join(target).join(HELPER_FILE),
57    ]
58}
59
60/// The paths to try for `target`, in order: `dev_dir`
61/// (`AGENTMUX_REMOTE_HELPER_DIR`) alone when it is set, else this package's.
62fn candidate_paths(dev_dir: Option<&Path>, exe_dir: Option<&Path>, version: &str, target: &str) -> Vec<PathBuf> {
63    match (dev_dir, exe_dir) {
64        (Some(dir), _) => vec![
65            dir.join(target).join(HELPER_FILE),
66            dir.join(asset_name(version, target)),
67        ],
68        (None, Some(exe_dir)) => packaged_paths(exe_dir, target).to_vec(),
69        (None, None) => Vec::new(),
70    }
71}
72
73/// The helper's folder on the host, relative to the remote home.
74fn remote_dir(version: &str) -> String {
75    format!("$HOME/.agentmux-remote/bin/{version}")
76}
77
78/// One remote command: `sh -c '<script>'`, single-quoted for whatever shell
79/// the user logs in with.
80fn sh(script: &str) -> String {
81    format!("sh -c {}", super::ssh::quote(script))
82}
83
84/// Prints `uname -sm`, then this version's helper's `version` line if it is
85/// installed and runs.
86pub fn probe_command(version: &str) -> String {
87    let dir = remote_dir(version);
88    sh(&format!(
89        "uname -sm; p=\"{dir}/agentmux-remote\"; if [ -x \"$p\" ]; then \"$p\" version 2>/dev/null; fi; true"
90    ))
91}
92
93/// Reads the binary from stdin into a temp file in an owner-only folder.
94/// A temp file of this install's own (`tag`: the pane's session id, letters,
95/// digits, `-` and `_`), so two panes installing on one host at once never
96/// write, check or remove each other's upload.
97fn temp_name(tag: &str) -> String {
98    let tag: String = tag
99        .chars()
100        .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
101        .collect();
102    format!("agentmux-remote.{tag}.tmp")
103}
104
105pub fn upload_command(version: &str, tag: &str) -> String {
106    let dir = remote_dir(version);
107    let tmp = temp_name(tag);
108    sh(&format!(
109        "umask 077; mkdir -p \"{dir}\" && cat > \"{dir}/{tmp}\""
110    ))
111}
112
113/// Checks the uploaded file's hash; on a match makes it the helper, else
114/// removes it. Prints `ok` or `mismatch <hash>`.
115pub fn install_command(version: &str, tag: &str, sha256: &str) -> String {
116    let dir = remote_dir(version);
117    let tmp = temp_name(tag);
118    sh(&format!(
119        "f=\"{dir}/{tmp}\"; \
120         h=$( (sha256sum \"$f\" 2>/dev/null || shasum -a 256 \"$f\") | cut -d' ' -f1); \
121         if [ \"$h\" = \"{sha256}\" ]; then chmod 700 \"$f\" && mv -f \"$f\" \"{dir}/agentmux-remote\" && echo ok; \
122         else rm -f \"$f\"; echo \"mismatch $h\"; fi"
123    ))
124}
125
126/// Removes the helper from the host (SPEC_REMOTES_PANE_2026_10_05.md §4.9):
127/// ends every session each installed version's daemon holds and stops the
128/// daemon, then deletes `~/.agentmux-remote`. A helper older than `stop`
129/// ignores it, and its daemon, with no sessions left, exits within a minute.
130/// Prints `ok`.
131pub fn remove_command() -> String {
132    sh("for p in \"$HOME\"/.agentmux-remote/bin/*/agentmux-remote; do \
133          [ -x \"$p\" ] || continue; \
134          \"$p\" list 2>/dev/null | while read -r id rest; do \
135            \"$p\" end --session \"$id\" >/dev/null 2>&1; \
136          done; \
137          \"$p\" stop >/dev/null 2>&1; \
138        done; \
139        rm -rf \"$HOME/.agentmux-remote\" && echo ok")
140}
141
142/// What a probe found.
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct Probe {
145    pub uname: String,
146    /// This version's helper is installed and answered `version`.
147    pub installed: bool,
148}
149
150/// Read a probe's output.
151pub fn parse_probe(out: &str, version: &str) -> Probe {
152    let mut lines = out.lines().map(str::trim).filter(|l| !l.is_empty());
153    let uname = lines.next().unwrap_or_default().to_string();
154    let want = format!(
155        "agentmux-remote {version} protocol {}",
156        agentmux_remote::frame::PROTOCOL
157    );
158    let installed = lines.any(|l| l == want);
159    Probe { uname, installed }
160}
161
162/// Where this version's build for `target` is on this computer (the same
163/// places [`local_build`] reads): what WSL runs in place.
164#[cfg(windows)]
165pub fn local_path(version: &str, target: &str) -> Result<PathBuf, String> {
166    let dev_dir = std::env::var_os("AGENTMUX_REMOTE_HELPER_DIR").map(PathBuf::from);
167    let exe_dir = std::env::current_exe()
168        .ok()
169        .and_then(|exe| exe.parent().map(Path::to_path_buf));
170    let paths = candidate_paths(dev_dir.as_deref(), exe_dir.as_deref(), version, target);
171    paths.iter().find(|p| p.is_file()).cloned().ok_or_else(|| {
172        format!(
173            "this AgentMux build doesn't include the helper for {target} (looked in {})",
174            paths.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(", ")
175        )
176    })
177}
178
179/// This version's build for `target`, and its hash: from
180/// `AGENTMUX_REMOTE_HELPER_DIR` when set (a developer's own builds), else from
181/// this package (spec §9.1). Nothing is downloaded.
182pub fn local_build(version: &str, target: &str) -> Result<(Vec<u8>, String), String> {
183    let dev_dir = std::env::var_os("AGENTMUX_REMOTE_HELPER_DIR").map(PathBuf::from);
184    let exe_dir = std::env::current_exe()
185        .ok()
186        .and_then(|exe| exe.parent().map(Path::to_path_buf));
187    read_first(&candidate_paths(dev_dir.as_deref(), exe_dir.as_deref(), version, target), target)
188}
189
190fn read_first(paths: &[PathBuf], target: &str) -> Result<(Vec<u8>, String), String> {
191    for path in paths {
192        if let Ok(bytes) = std::fs::read(path) {
193            let hash = sha256_hex(&bytes);
194            return Ok((bytes, hash));
195        }
196    }
197    Err(format!(
198        "this AgentMux build doesn't include the helper for {target} (looked in {})",
199        paths
200            .iter()
201            .map(|p| p.display().to_string())
202            .collect::<Vec<_>>()
203            .join(", ")
204    ))
205}
206
207/// Put this version's helper on `host` if it is not there (spec §6.2): probe
208/// the platform (recorded under `connection` for Connectors → Remotes), get the
209/// matching build (checked against the release's hashes), upload it over
210/// ssh, check its hash there, move it in. `tag` names
211/// this install's own temp file (letters, digits, `-`, `_`), so two installs
212/// on one host never touch each other's upload. `announce` hears the size
213/// just before the upload, for whoever is waiting to say what is happening.
214pub async fn ensure<F, Fut>(
215    host: &super::host::HostSsh,
216    connection: &str,
217    tag: &str,
218    announce: F,
219) -> Result<(), String>
220where
221    F: FnOnce(usize) -> Fut,
222    Fut: std::future::Future<Output = ()>,
223{
224    let run = |cmd: String, input: Option<Vec<u8>>| async move {
225        host.run(&cmd, input, std::time::Duration::from_secs(120))
226            .await?
227            .ok()
228    };
229    let version = env!("CARGO_PKG_VERSION");
230    let probe = parse_probe(&run(probe_command(version), None).await?, version);
231    // Connectors → Remotes shows the host's platform (SPEC_REMOTES_PANE_2026_10_05.md §4.6).
232    super::helper_hosts::record_uname(connection, &probe.uname);
233    if probe.installed {
234        return Ok(());
235    }
236    let target = target_for(&probe.uname).ok_or_else(|| {
237        format!(
238            "AgentMux has no helper build for this host ({})",
239            probe.uname.trim()
240        )
241    })?;
242    let (bytes, hash) = local_build(version, target)?;
243    announce(bytes.len()).await;
244    run(upload_command(version, tag), Some(bytes)).await?;
245    let out = run(install_command(version, tag, &hash), None).await?;
246    if out.trim() != "ok" {
247        return Err(format!(
248            "the uploaded helper did not check out on the host ({})",
249            out.trim()
250        ));
251    }
252    Ok(())
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    #[test]
260    fn each_supported_platform_has_its_build() {
261        assert_eq!(
262            target_for("Linux x86_64"),
263            Some("x86_64-unknown-linux-musl")
264        );
265        assert_eq!(
266            target_for("Linux aarch64\n"),
267            Some("aarch64-unknown-linux-musl")
268        );
269        assert_eq!(target_for("Darwin arm64"), Some("aarch64-apple-darwin"));
270        assert_eq!(target_for("Darwin x86_64"), Some("x86_64-apple-darwin"));
271        assert_eq!(target_for("FreeBSD amd64"), None);
272        assert_eq!(target_for("Linux armv7l"), None);
273        assert_eq!(target_for(""), None);
274    }
275
276    fn put(path: &Path, bytes: &[u8]) {
277        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
278        std::fs::write(path, bytes).unwrap();
279    }
280
281    #[test]
282    fn a_package_carries_the_helper_beside_its_other_tools() {
283        let dir = tempfile::tempdir().unwrap();
284        let exe_dir = dir.path().join("runtime");
285        let t = "x86_64-unknown-linux-musl";
286        put(&exe_dir.join("tools").join("remote").join(t).join("agentmux-remote"), b"linux build");
287        let (bytes, hash) = read_first(&candidate_paths(None, Some(&exe_dir), "0.59.9", t), t).unwrap();
288        assert_eq!(bytes, b"linux build");
289        assert_eq!(hash, sha256_hex(b"linux build"));
290    }
291
292    #[test]
293    fn a_macos_app_keeps_the_linux_builds_in_its_resources() {
294        let dir = tempfile::tempdir().unwrap();
295        let contents = dir.path().join("AgentMux.app").join("Contents");
296        let exe_dir = contents.join("MacOS");
297        std::fs::create_dir_all(&exe_dir).unwrap();
298        let t = "aarch64-unknown-linux-musl";
299        put(&contents.join("Resources").join("remote").join(t).join("agentmux-remote"), b"arm build");
300        let (bytes, _) = read_first(&candidate_paths(None, Some(&exe_dir), "0.59.9", t), t).unwrap();
301        assert_eq!(bytes, b"arm build");
302    }
303
304    #[test]
305    fn a_developers_folder_wins_in_either_layout() {
306        let dir = tempfile::tempdir().unwrap();
307        let exe_dir = dir.path().join("runtime");
308        let dev = dir.path().join("dev");
309        let t = "x86_64-apple-darwin";
310        put(&exe_dir.join("tools").join("remote").join(t).join("agentmux-remote"), b"packaged");
311        put(&dev.join(t).join("agentmux-remote"), b"dev, script layout");
312        let (bytes, _) = read_first(&candidate_paths(Some(&dev), Some(&exe_dir), "0.59.9", t), t).unwrap();
313        assert_eq!(bytes, b"dev, script layout");
314
315        let flat = dir.path().join("flat");
316        put(&flat.join(asset_name("0.59.9", t)), b"dev, flat name");
317        let (bytes, _) = read_first(&candidate_paths(Some(&flat), Some(&exe_dir), "0.59.9", t), t).unwrap();
318        assert_eq!(bytes, b"dev, flat name");
319    }
320
321    #[test]
322    fn a_build_without_the_helper_says_so_and_downloads_nothing() {
323        let dir = tempfile::tempdir().unwrap();
324        let t = "aarch64-apple-darwin";
325        let err = read_first(&candidate_paths(None, Some(dir.path()), "0.59.9", t), t).unwrap_err();
326        assert!(err.contains("doesn't include the helper for aarch64-apple-darwin"), "{err}");
327        assert!(!err.contains("http"), "{err}");
328    }
329
330    #[test]
331    fn a_probe_reads_the_platform_and_whether_this_version_is_there() {
332        let v = "0.59.8";
333        let ok = format!(
334            "Linux x86_64\nagentmux-remote {v} protocol {}\n",
335            agentmux_remote::frame::PROTOCOL
336        );
337        assert_eq!(
338            parse_probe(&ok, v),
339            Probe {
340                uname: "Linux x86_64".into(),
341                installed: true
342            }
343        );
344        assert!(!parse_probe("Linux x86_64\n", v).installed);
345        assert!(
346            !parse_probe("Linux x86_64\nagentmux-remote 0.59.7 protocol 1\n", v).installed,
347            "another version"
348        );
349    }
350
351    #[test]
352    fn the_remote_scripts_run_under_sh_whatever_the_login_shell() {
353        for cmd in [
354            probe_command("0.59.8"),
355            upload_command("0.59.8", "amx-1"),
356            install_command("0.59.8", "amx-1", &"a".repeat(64)),
357        ] {
358            assert!(cmd.starts_with("sh -c '"), "{cmd}");
359            assert!(cmd.ends_with('\''), "{cmd}");
360            assert!(cmd.contains("$HOME/.agentmux-remote/bin/0.59.8"), "{cmd}");
361        }
362        assert!(install_command("0.59.8", "amx-1", "abc").contains("= \"abc\" ]"));
363        // Each install its own temp file; nothing but the id's own characters.
364        assert!(upload_command("0.59.8", "amx-1").contains("agentmux-remote.amx-1.tmp"));
365        assert!(upload_command("0.59.8", "a;b $x").contains("agentmux-remote.abx.tmp"));
366    }
367
368    /// The scripts do what they say in a real `sh` (where there is one).
369    #[cfg(unix)]
370    #[test]
371    fn upload_then_install_puts_a_checked_binary_in_place() {
372        let home = tempfile::tempdir().unwrap();
373        let run = |cmd: &str, input: &[u8]| {
374            use std::io::Write;
375            let mut child = std::process::Command::new("sh")
376                .arg("-c")
377                .arg(cmd)
378                .env("HOME", home.path())
379                .stdin(std::process::Stdio::piped())
380                .stdout(std::process::Stdio::piped())
381                .spawn()
382                .unwrap();
383            child.stdin.take().unwrap().write_all(input).unwrap();
384            String::from_utf8(child.wait_with_output().unwrap().stdout).unwrap()
385        };
386        let body = b"#!/bin/sh\necho agentmux-remote 0.59.8 protocol 1\n";
387        run(&upload_command("0.59.8", "s1"), body);
388        assert!(run(&install_command("0.59.8", "s1", &"0".repeat(64)), b"").starts_with("mismatch"));
389        // Another pane's upload in flight is untouched by this one's install.
390        run(&upload_command("0.59.8", "s2"), b"other");
391        run(&upload_command("0.59.8", "s1"), body);
392        assert_eq!(
393            run(&install_command("0.59.8", "s1", &sha256_hex(body)), b"").trim(),
394            "ok"
395        );
396        assert!(home
397            .path()
398            .join(".agentmux-remote/bin/0.59.8/agentmux-remote.s2.tmp")
399            .exists());
400        let probe = parse_probe(&run(&probe_command("0.59.8"), b""), "0.59.8");
401        assert!(probe.installed, "{probe:?}");
402    }
403
404    /// Removing ends each session through the helper, stops its daemon at
405    /// once rather than leaving it to exit idle a minute later (#4513), then
406    /// deletes its folder.
407    #[cfg(unix)]
408    #[test]
409    fn remove_ends_the_sessions_stops_the_daemon_and_deletes_the_folder() {
410        let home = tempfile::tempdir().unwrap();
411        let dir = home.path().join(".agentmux-remote/bin/0.59.8");
412        std::fs::create_dir_all(&dir).unwrap();
413        let ended = home.path().join("ended");
414        let fake = format!(
415            "#!/bin/sh\ncase \"$1\" in list) echo 'amx-1 10 -'; echo 'amx-2 5 0';; end) echo \"$3\" >> '{0}';; stop) echo stop >> '{0}';; esac\n",
416            ended.display()
417        );
418        let bin = dir.join("agentmux-remote");
419        std::fs::write(&bin, fake).unwrap();
420        use std::os::unix::fs::PermissionsExt;
421        std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o700)).unwrap();
422        let out = std::process::Command::new("sh")
423            .arg("-c")
424            .arg(remove_command())
425            .env("HOME", home.path())
426            .output()
427            .unwrap();
428        assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "ok");
429        assert_eq!(std::fs::read_to_string(&ended).unwrap(), "amx-1\namx-2\nstop\n");
430        assert!(!home.path().join(".agentmux-remote").exists());
431    }
432}