Skip to main content

agentmux_srv_core/backend/container/
image_tools.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The check that a container's image has what an AgentMux agent needs to talk to AgentMux (#47725).
5
6use super::{ContainerError, ContainerManager};
7
8/// What an agent's container needs from its image to be an AgentMux agent at all.
9const IMAGE_TOOLS: [&str; 2] = ["agentmux-bashwrap", "agentmux-mcp"];
10
11/// What the check prints: `missing:<tool>` per absent tool, then `checked` (so an exec that never ran the
12/// script is not read as "all present").
13const IMAGE_TOOLS_CHECK: &str = r#"for t in "$@"; do command -v "$t" >/dev/null 2>&1 || echo "missing:$t"; done; echo checked"#;
14
15/// The tools [`IMAGE_TOOLS_CHECK`] reported absent. `None` when the script's own `checked` line is missing: the
16/// probe did not run, which says nothing about the image.
17fn missing_image_tools(output: &str) -> Option<Vec<String>> {
18    if !output.lines().any(|l| l.trim() == "checked") {
19        return None;
20    }
21    Some(output.lines().filter_map(|l| l.trim().strip_prefix("missing:")).map(str::to_string).collect())
22}
23
24/// Whether the existing container was made from the retired image while `requested` (what this start asks for)
25/// is not it. Such a container is recreated, not reused: it has none of the AgentMux tools, and reusing it would
26/// refuse every start with an image the definition no longer names (#47725). A container on any other image,
27/// an older base image included, is left alone: moving it is `update_container`'s, so tools installed in it stay.
28pub(super) fn made_from_retired_image(details: &bollard::models::ContainerInspectResponse, requested: &str) -> bool {
29    let actual = details.config.as_ref().and_then(|c| c.image.as_deref()).unwrap_or("");
30    super::image::is_legacy_agent_image(actual) && !super::image::is_legacy_agent_image(requested)
31}
32
33impl ContainerManager {
34    /// Whether the running container `container_name`, made from `image`, has what an AgentMux agent needs
35    /// ([`IMAGE_TOOLS`]). An image that lacks them makes a container that starts and cannot talk (no tools, no
36    /// startup memory, no messages), so this is asked before the agent's first turn rather than answered by a
37    /// run of failed hooks. A probe that can't run says nothing about the image and lets the start go on.
38    /// Checked once per container: a removed container forgets it (`forget_cli_ready`).
39    pub async fn check_image_tools(&self, container_name: &str, image: &str) -> Result<(), ContainerError> {
40        let key = format!("{container_name}\u{0}tools\u{0}{image}");
41        if self.inner.cli_ready.lock().await.contains(&key) {
42            return Ok(());
43        }
44        let mut argv: Vec<String> = vec!["sh".into(), "-c".into(), IMAGE_TOOLS_CHECK.into(), "agentmux-image-check".into()];
45        argv.extend(IMAGE_TOOLS.iter().map(|t| t.to_string()));
46        let outcome = match self.exec_collect(container_name, &argv, std::time::Duration::from_secs(20)).await {
47            Ok(o) => o,
48            Err(e) => {
49                tracing::warn!(container = container_name, %image, error = %e, "could not check the image's AgentMux tools; starting anyway");
50                return Ok(());
51            }
52        };
53        match missing_image_tools(&outcome.output) {
54            Some(missing) if !missing.is_empty() => {
55                tracing::warn!(container = container_name, %image, ?missing, "the container image lacks the AgentMux tools; stopping it");
56                // Left running it would sit there idle and unusable; the next start asks again.
57                let _ = self.stop(container_name, 10).await;
58                Err(ContainerError::ImageIncomplete { image: image.to_string(), missing })
59            }
60            Some(_) => {
61                self.inner.cli_ready.lock().await.insert(key);
62                Ok(())
63            }
64            None => {
65                tracing::warn!(container = container_name, %image, "the image check printed nothing usable; starting anyway");
66                Ok(())
67            }
68        }
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn the_image_check_reads_what_the_script_printed_and_nothing_else() {
78        assert_eq!(missing_image_tools("checked\n"), Some(vec![]), "both present");
79        assert_eq!(
80            missing_image_tools("missing:agentmux-bashwrap\nmissing:agentmux-mcp\nchecked\n"),
81            Some(vec!["agentmux-bashwrap".to_string(), "agentmux-mcp".to_string()])
82        );
83        assert_eq!(missing_image_tools("missing:agentmux-mcp\r\nchecked\r\n"), Some(vec!["agentmux-mcp".to_string()]));
84        // The script never ran to its end (the exec failed, or `sh` is missing): that says nothing about the image.
85        assert_eq!(missing_image_tools(""), None);
86        assert_eq!(missing_image_tools("sh: not found\n"), None);
87        assert_eq!(missing_image_tools("missing:agentmux-mcp\n"), None);
88    }
89
90    #[test]
91    fn a_container_made_from_the_retired_image_is_recreated_and_no_other_is() {
92        let made_from = |image: &str| bollard::models::ContainerInspectResponse {
93            config: Some(bollard::models::ContainerConfig { image: Some(image.to_string()), ..Default::default() }),
94            ..Default::default()
95        };
96        let base = "ghcr.io/agentmuxai/agent-base:0.60.29";
97        assert!(made_from_retired_image(&made_from("ghcr.io/agentmuxai/agent-claude:latest"), base));
98        assert!(made_from_retired_image(&made_from("ghcr.io/agentmuxai/agent-claude@sha256:abc"), base));
99        assert!(!made_from_retired_image(&made_from("ghcr.io/agentmuxai/agent-base:0.60.1"), base), "an older base image is update_container's");
100        assert!(!made_from_retired_image(&made_from("my/own:1"), base));
101        assert!(!made_from_retired_image(&made_from("ghcr.io/agentmuxai/agent-claude:latest"), "ghcr.io/agentmuxai/agent-claude:latest"), "unless the retired image is what is asked for");
102        assert!(!made_from_retired_image(&bollard::models::ContainerInspectResponse::default(), base), "no inspect data: leave it");
103    }
104
105    #[test]
106    fn an_incomplete_image_says_which_image_and_what_to_do() {
107        let msg = ContainerError::ImageIncomplete {
108            image: "ghcr.io/agentmuxai/agent-claude:latest".into(),
109            missing: vec!["agentmux-bashwrap".into(), "agentmux-mcp".into()],
110        }
111        .user_message();
112        assert!(msg.contains("ghcr.io/agentmuxai/agent-claude:latest"), "{msg}");
113        assert!(msg.contains("agentmux-bashwrap or agentmux-mcp"), "{msg}");
114        assert!(msg.contains("update_container") && msg.contains("agent-base"), "{msg}");
115    }
116}