Skip to main content

agentmux_srv_core/backend/
agent_tools.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The helper programs an agent's hooks and MCP config run (`agentmux-mcp`, `agentmux-bashwrap`), written down once
5//! in `config/tools.lock.json` and used by both ways an agent gets them (task #13666, step 4). A native agent finds
6//! them in AgentMux's tool folders ([`find_in_tool_dirs`]); a container agent finds them where the image copies them,
7//! and `docker/Dockerfile.agent-agentmux` is checked against the lock by `the_dockerfile_installs_what_the_lock_lists`,
8//! so a tool added to one side without the other fails a test, not an agent's first turn.
9
10use std::path::PathBuf;
11
12use serde::Deserialize;
13
14const LOCK_JSON: &str = include_str!("../config/tools.lock.json");
15
16#[derive(Debug, Deserialize)]
17pub struct ToolLock {
18    pub tools: Vec<LockedTool>,
19}
20
21#[derive(Debug, Deserialize)]
22pub struct LockedTool {
23    pub id: String,
24    /// The cargo package that builds it.
25    pub package: String,
26    /// Where the container image installs it.
27    pub container_path: String,
28    pub used_by: Vec<String>,
29}
30
31pub fn lock() -> ToolLock {
32    serde_json::from_str(LOCK_JSON).expect("tools.lock.json parses")
33}
34
35/// A folder AgentMux keeps its own tools in.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum ToolDir {
38    /// `<srv-dir>/tools/bin`, where a packaged build ships them.
39    Bundled,
40    /// `~/.agentmux/tools/bin`, where `task dev` puts them.
41    User,
42    /// The folder srv itself runs from.
43    BesideSrv,
44}
45
46impl ToolDir {
47    fn path(self) -> Option<PathBuf> {
48        match self {
49            ToolDir::Bundled => crate::backend::tool_store::bundled_tools_dir(),
50            ToolDir::User => crate::backend::tool_store::user_tools_dir(),
51            ToolDir::BesideSrv => std::env::current_exe().ok().and_then(|exe| exe.parent().map(|d| d.to_path_buf())),
52        }
53    }
54}
55
56/// `name` as a file in the first of `dirs` that has it, with the platform's executable suffix tried first.
57pub fn find_in_tool_dirs(name: &str, dirs: &[ToolDir]) -> Option<PathBuf> {
58    let names = [format!("{name}{}", std::env::consts::EXE_SUFFIX), name.to_string()];
59    dirs.iter()
60        .filter_map(|dir| dir.path())
61        .find_map(|dir| names.iter().map(|n| dir.join(n)).find(|p| p.is_file()))
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67    use std::collections::BTreeSet;
68
69    const DOCKERFILE: &str = include_str!("../../../../docker/Dockerfile.agent-agentmux");
70
71    #[test]
72    fn the_lock_names_each_tool_once_and_says_who_uses_it() {
73        let lock = lock();
74        let ids: BTreeSet<_> = lock.tools.iter().map(|t| t.id.as_str()).collect();
75        assert_eq!(ids.len(), lock.tools.len(), "a tool is listed twice");
76        for t in &lock.tools {
77            assert!(!t.used_by.is_empty(), "{} says nothing about who uses it", t.id);
78            assert_eq!(t.container_path, format!("/usr/local/bin/{}", t.id), "{}: the image installs tools on PATH under their id", t.id);
79        }
80    }
81
82    /// `gh` on PATH is `agentmux-bashwrap` (crates/bashwrap/src/gh_shim.rs): `timeout gh` and scripts skip the shell function.
83    #[test]
84    fn the_image_puts_agentmux_bashwrap_on_path_as_gh() {
85        assert!(DOCKERFILE.lines().any(|l| l.trim() == "RUN ln -s agentmux-bashwrap /usr/local/bin/gh"));
86    }
87
88    #[test]
89    fn the_dockerfile_installs_what_the_lock_lists() {
90        let lock = lock();
91        let wanted: BTreeSet<(String, String)> = lock
92            .tools
93            .iter()
94            .map(|t| (format!("/build/target/release/{}", t.package), t.container_path.clone()))
95            .collect();
96        let copied: BTreeSet<(String, String)> = DOCKERFILE
97            .lines()
98            .filter(|l| l.starts_with("COPY --from=mcp-builder"))
99            .map(|l| {
100                let mut paths = l.split_whitespace().filter(|w| w.starts_with('/'));
101                (paths.next().unwrap_or_default().to_string(), paths.next().unwrap_or_default().to_string())
102            })
103            .collect();
104        assert_eq!(copied, wanted, "docker/Dockerfile.agent-agentmux COPY lines must equal tools.lock.json");
105        let built: BTreeSet<String> = DOCKERFILE
106            .lines()
107            .find(|l| l.starts_with("RUN cargo build --release"))
108            .map(|l| l.split_whitespace().skip_while(|w| *w != "-p").filter(|w| *w != "-p").map(str::to_string).collect())
109            .unwrap_or_default();
110        let packages: BTreeSet<String> = lock.tools.iter().map(|t| t.package.clone()).collect();
111        assert_eq!(built, packages, "the mcp-builder stage must build exactly the locked packages");
112    }
113
114    /// The first word of every command a launch's hooks run, and the command of its `agentmux` MCP server.
115    fn commands_a_launch_runs() -> BTreeSet<String> {
116        let files = crate::backend::agent_config::build_config_files(
117            &Default::default(),
118            &[],
119            "Lock",
120            "lock-id",
121            "lock",
122            "work",
123            "claude",
124        );
125        let json = |name: &str| -> serde_json::Value {
126            let f = files.iter().find(|f| f.filename == name).unwrap_or_else(|| panic!("no {name}"));
127            serde_json::from_str(&f.content).unwrap()
128        };
129        let mut out = BTreeSet::new();
130        let settings = json(".claude/settings.json");
131        let mut stack = vec![&settings["hooks"]];
132        while let Some(v) = stack.pop() {
133            match v {
134                serde_json::Value::Object(map) => {
135                    if let Some(cmd) = map.get("command").and_then(|c| c.as_str()) {
136                        out.insert(cmd.split_whitespace().next().unwrap_or_default().to_string());
137                    }
138                    stack.extend(map.values());
139                }
140                serde_json::Value::Array(items) => stack.extend(items),
141                _ => {}
142            }
143        }
144        let mcp = json(".mcp.json");
145        out.insert(mcp["mcpServers"]["agentmux"]["command"].as_str().unwrap().to_string());
146        out
147    }
148
149    #[test]
150    fn every_tool_a_launch_runs_is_in_the_lock() {
151        let ids: BTreeSet<String> = lock().tools.into_iter().map(|t| t.id).collect();
152        let used = commands_a_launch_runs();
153        assert!(!used.is_empty(), "the launch ran no tools: the check would pass on nothing");
154        let unlocked: Vec<_> = used.difference(&ids).collect();
155        assert!(unlocked.is_empty(), "add these to tools.lock.json, and to the image: {unlocked:?}");
156    }
157
158    #[test]
159    fn a_tool_is_found_in_the_first_folder_that_has_it() {
160        assert_eq!(find_in_tool_dirs("agentmux-no-such-tool", &[ToolDir::Bundled, ToolDir::User, ToolDir::BesideSrv]), None);
161    }
162}