Skip to main content

agentmux_srv_core/backend/
packaged_tools.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Store (MSIX) install keeps the app's tools (`agentmux-mcp`, `agentmux-bashwrap`
5//! and the rest) inside the package folder under `WindowsApps`. A process that
6//! doesn't have the package's identity can't run files from there (`EPERM` /
7//! "Permission denied"), and an agent's shell and its MCP server are exactly
8//! such processes: the agent lost its AgentMux tools and `Bash`.
9//!
10//! So a packaged install runs its tools from a copy: `~/.agentmux/tools/packaged/<package folder>/`,
11//! made on first use and keyed by the package folder (which carries the version), so an
12//! update stages a new one and never overwrites a copy a running agent uses. Any other
13//! install (portable, setup.exe, `task dev`) is unchanged.
14
15use std::io;
16use std::path::{Component, Path, PathBuf};
17use std::sync::OnceLock;
18
19/// Whether `path` is inside a Windows package install (`...\WindowsApps\<package>\...`).
20pub(crate) fn is_package_path(path: &Path) -> bool {
21    path.components().any(|c| matches!(c, Component::Normal(n) if n.eq_ignore_ascii_case("WindowsApps")))
22}
23
24/// Where the copy of `source`'s tools goes: under the home's `.agentmux/tools/packaged/`, named for the
25/// package folder that follows `WindowsApps` (so the version is in it).
26pub(crate) fn staged_dir(source: &Path, home: &Path) -> Option<PathBuf> {
27    let mut parts = source.components();
28    parts.find(|c| matches!(c, Component::Normal(n) if n.eq_ignore_ascii_case("WindowsApps")))?;
29    let package = match parts.next()? {
30        Component::Normal(n) => n.to_string_lossy().into_owned(),
31        _ => return None,
32    };
33    let name: String = package.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { c } else { '_' }).collect();
34    Some(home.join(".agentmux").join("tools").join("packaged").join(name).join("bin"))
35}
36
37/// Copies `source`'s files into `dest`, skipping a file that is already there with the same size. A file
38/// is copied under a temporary name and renamed, so a second srv starting at the same time never runs a
39/// half-written program.
40pub(crate) fn stage(source: &Path, dest: &Path) -> io::Result<()> {
41    std::fs::create_dir_all(dest)?;
42    for entry in std::fs::read_dir(source)? {
43        let entry = entry?;
44        let from = entry.path();
45        let to = dest.join(entry.file_name());
46        if entry.file_type()?.is_dir() {
47            stage(&from, &to)?;
48            continue;
49        }
50        let len = entry.metadata()?.len();
51        if std::fs::metadata(&to).map(|m| m.len() == len).unwrap_or(false) {
52            continue;
53        }
54        let tmp = to.with_extension(format!("{}.tmp", std::process::id()));
55        std::fs::copy(&from, &tmp)?;
56        if let Err(e) = std::fs::rename(&tmp, &to) {
57            let _ = std::fs::remove_file(&tmp);
58            // Another srv put the same file there first, and it may be running.
59            if !std::fs::metadata(&to).map(|m| m.len() == len).unwrap_or(false) {
60                return Err(e);
61            }
62        }
63    }
64    Ok(())
65}
66
67/// The folder to run the bundled tools from: `source` itself, except in a package install, where it is the
68/// staged copy (made once per run; `source` again if the copy can't be made, which is logged).
69pub(crate) fn runnable(source: PathBuf) -> PathBuf {
70    static STAGED: OnceLock<PathBuf> = OnceLock::new();
71    if !is_package_path(&source) || !source.is_dir() {
72        return source;
73    }
74    STAGED
75        .get_or_init(|| {
76            let staged = dirs::home_dir().and_then(|home| staged_dir(&source, &home));
77            match staged {
78                Some(dest) => match stage(&source, &dest) {
79                    Ok(()) => {
80                        tracing::info!(from = %source.display(), to = %dest.display(), "packaged install: running the app's tools from a copy outside the package");
81                        dest
82                    }
83                    Err(e) => {
84                        tracing::warn!(from = %source.display(), to = %dest.display(), error = %e, "packaged install: couldn't copy the app's tools out of the package; agents may be unable to start them");
85                        source.clone()
86                    }
87                },
88                None => source.clone(),
89            }
90        })
91        .clone()
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn only_a_path_inside_windowsapps_is_a_package() {
100        // Forward slashes: `Path` splits on them on every platform (on backslashes only on Windows).
101        assert!(is_package_path(Path::new("C:/Program Files/WindowsApps/AgentMux.AgentMux_0.60.2.0_x64__abc/runtime/tools/bin")));
102        assert!(is_package_path(Path::new("c:/program files/windowsapps/AgentMux.AgentMux_1_x64__abc/tools/bin")));
103        assert!(!is_package_path(Path::new("C:/Users/a/AppData/Local/Programs/AgentMux/runtime/tools/bin")));
104        assert!(!is_package_path(Path::new("C:/Users/a/Desktop/agentmux-portable/runtime/tools/bin")));
105        assert!(!is_package_path(Path::new("C:/Users/a/WindowsAppsBackup/tools")));
106    }
107
108    #[cfg(windows)]
109    #[test]
110    fn a_windows_path_with_backslashes_is_a_package_too() {
111        assert!(is_package_path(Path::new(r"C:\Program Files\WindowsApps\AgentMux.AgentMux_0.60.2.0_x64__abc\runtime\tools\bin")));
112        assert!(!is_package_path(Path::new(r"C:\Users\a\WindowsAppsBackup\tools")));
113    }
114
115    #[test]
116    fn the_copy_is_named_for_the_package_so_an_update_gets_its_own() {
117        let home = Path::new("/home/a");
118        let v1 = staged_dir(Path::new("C:/Program Files/WindowsApps/AgentMux.AgentMux_0.60.2.0_x64__abc/runtime/tools/bin"), home).unwrap();
119        let v2 = staged_dir(Path::new("C:/Program Files/WindowsApps/AgentMux.AgentMux_0.60.3.0_x64__abc/runtime/tools/bin"), home).unwrap();
120        assert_eq!(v1, home.join(".agentmux/tools/packaged/AgentMux.AgentMux_0.60.2.0_x64__abc/bin"));
121        assert_ne!(v1, v2);
122        assert_eq!(staged_dir(Path::new("C:/Users/a/AgentMux/tools/bin"), home), None);
123    }
124
125    #[test]
126    fn staging_copies_files_and_folders_and_a_second_run_changes_nothing() {
127        let tmp = tempfile::tempdir().unwrap();
128        let (src, dst) = (tmp.path().join("src"), tmp.path().join("dst"));
129        std::fs::create_dir_all(src.join("sub")).unwrap();
130        std::fs::write(src.join("agentmux-mcp.exe"), b"mcp").unwrap();
131        std::fs::write(src.join("sub").join("lib.dll"), b"lib").unwrap();
132
133        stage(&src, &dst).unwrap();
134        assert_eq!(std::fs::read(dst.join("agentmux-mcp.exe")).unwrap(), b"mcp");
135        assert_eq!(std::fs::read(dst.join("sub").join("lib.dll")).unwrap(), b"lib");
136
137        // A copy that is already there (and may be running) is left alone.
138        std::fs::write(dst.join("agentmux-mcp.exe"), b"xyz").unwrap();
139        stage(&src, &dst).unwrap();
140        assert_eq!(std::fs::read(dst.join("agentmux-mcp.exe")).unwrap(), b"xyz");
141
142        // A file of another size is replaced; no temporary file is left behind.
143        std::fs::write(src.join("agentmux-mcp.exe"), b"longer").unwrap();
144        stage(&src, &dst).unwrap();
145        assert_eq!(std::fs::read(dst.join("agentmux-mcp.exe")).unwrap(), b"longer");
146        assert!(std::fs::read_dir(&dst).unwrap().all(|e| !e.unwrap().file_name().to_string_lossy().ends_with(".tmp")));
147    }
148
149    #[test]
150    fn a_folder_that_isnt_in_a_package_is_used_as_it_is() {
151        let tmp = tempfile::tempdir().unwrap();
152        assert_eq!(runnable(tmp.path().to_path_buf()), tmp.path());
153    }
154}