Skip to main content

agentmux_srv_core/backend/container/
cli.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Installing the provider CLI inside a container agent's container.
5//!
6//! The public base image carries no provider CLI, so the first start installs
7//! it from npm into a per-agent volume. This module is the pure part: what to
8//! install, the marker that says it is done, and the two `sh` scripts. The
9//! `docker exec` plumbing is in `ContainerManager::provision_cli`.
10//!
11//! Spec: docs/specs/SPEC_CONTAINER_AGENTS_WORK_FOR_EVERYONE_2026_10_07.md section 3.2.
12
13use crate::backend::container::cli_release::{self, Source, Upload};
14use crate::backend::container::image::CONTAINER_CLI_DIR;
15use crate::backend::providers;
16
17/// What to install for one container agent.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct CliInstall {
20    pub provider_id: String,
21    /// The command turns run, e.g. `claude`.
22    pub command: String,
23    /// `name@version` for the CLI and its companions.
24    pub specs: Vec<String>,
25    /// The pinned version, for the pane's "Installing Claude Code 2.1.321" row.
26    pub version: String,
27    /// How it gets into the container: npm, or the pinned file or Python tool of the non-npm route
28    /// (`container::cli_release`).
29    pub source: Source,
30}
31
32impl CliInstall {
33    /// The install for `provider_id`, if the container runs that provider's own
34    /// CLI by its usual name and AgentMux can install it: from npm, or by the
35    /// pinned file or `uv` route of the six that are not on npm. `None` for a
36    /// custom command or a provider with neither.
37    pub fn for_provider(provider_id: &str, container_command: &str) -> Option<Self> {
38        let provider = providers::get_provider(provider_id)?;
39        if provider.cli_command != container_command {
40            return None;
41        }
42        if !provider.npm_package.is_empty() {
43            if provider.pinned_version.is_empty() {
44                return None;
45            }
46            return Some(Self {
47                provider_id: provider.id.to_string(),
48                command: provider.cli_command.to_string(),
49                specs: provider.npm_install_specs(provider.pinned_version),
50                version: provider.pinned_version.to_string(),
51                source: Source::Npm,
52            });
53        }
54        let (source, version) = cli_release::source_for(provider.id)?;
55        Some(Self {
56            provider_id: provider.id.to_string(),
57            command: provider.cli_command.to_string(),
58            // The marker is built from this: a new pin is a new marker, so the next start installs it.
59            specs: vec![format!("{}@{version}", provider.id)],
60            version: version.to_string(),
61            source,
62        })
63    }
64
65    /// The time limits for this install.
66    pub fn limits(&self) -> InstallLimits {
67        self.source.limits()
68    }
69
70    /// Files the install script reads from `/tmp`, written before it runs.
71    pub fn uploads(&self) -> Vec<Upload> {
72        match self.source {
73            Source::Npm | Source::Download => Vec::new(),
74        }
75    }
76
77    /// File name inside [`CONTAINER_CLI_DIR`] that says this exact set of
78    /// packages is installed. A new pin changes it, which is what makes the
79    /// next start reinstall.
80    pub fn marker(&self) -> String {
81        let joined = self.specs.join("+");
82        let safe: String = joined
83            .chars()
84            .map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' || c == '+' { c } else { '-' })
85            .collect();
86        format!(".installed-{}", safe.trim_start_matches('-'))
87    }
88
89    /// Key for the "already checked" cache.
90    pub fn cache_key(&self, container_name: &str) -> String {
91        format!("{container_name}\u{0}{}", self.marker())
92    }
93
94    /// argv for the fast check; prints `present` or `missing`. The command on
95    /// the image's own `PATH` counts as present: that is a legacy image with
96    /// the CLI baked in, which must be left alone.
97    pub fn check_argv(&self) -> Vec<String> {
98        vec![
99            "sh".into(),
100            "-c".into(),
101            CHECK_SCRIPT.into(),
102            "agentmux-cli-check".into(),
103            self.command.clone(),
104            CONTAINER_CLI_DIR.into(),
105            self.marker(),
106        ]
107    }
108
109    /// argv for the install. Everything variable is a positional parameter,
110    /// never spliced into the script text.
111    pub fn install_argv(&self, limits: InstallLimits) -> Vec<String> {
112        let marker = self.marker();
113        let routed = match self.source {
114            Source::Npm => None,
115            Source::Download => cli_release::download_argv(CONTAINER_CLI_DIR, &marker, &self.command, &self.provider_id, limits),
116        };
117        if let Some(argv) = routed {
118            return argv;
119        }
120        let mut argv = vec![
121            "sh".into(),
122            "-c".into(),
123            INSTALL_SCRIPT.into(),
124            "agentmux-cli-install".into(),
125            CONTAINER_CLI_DIR.into(),
126            self.marker(),
127            self.command.clone(),
128            limits.script.as_secs().max(1).to_string(),
129        ];
130        argv.extend(self.specs.iter().cloned());
131        argv
132    }
133}
134
135/// How long an install may run. The script limits npm itself (`script`), which
136/// kills the whole process group; the host side (`run`) is the backstop for a
137/// script that does not return, and is followed by [`reap_argv`].
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub struct InstallLimits {
140    pub run: std::time::Duration,
141    pub script: std::time::Duration,
142}
143
144impl Default for InstallLimits {
145    fn default() -> Self {
146        Self {
147            run: std::time::Duration::from_secs(600),
148            script: std::time::Duration::from_secs(540),
149        }
150    }
151}
152
153/// Regex (in `pkill -f` / `pgrep -f` form) matching what an install runs: the install script itself, its `npm`, its
154/// `curl` and the staged `uv`. The brackets keep the reap script's own command line, which contains this text, from
155/// matching itself.
156const NPM_INSTALL_PATTERN: &str =
157    "[n]pm install --prefix /home/agent/.agentmux/cli|[a]gentmux-cli-install|[c]url -fsSL --proto|[.]staging/uv (venv|pip)";
158
159/// argv that kills any `npm install` into [`CONTAINER_CLI_DIR`] and waits for
160/// it to be gone. Prints `gone` and exits 0 only once none is left.
161pub fn reap_argv() -> Vec<String> {
162    vec![
163        "sh".into(),
164        "-c".into(),
165        REAP_SCRIPT.into(),
166        "agentmux-cli-reap".into(),
167        NPM_INSTALL_PATTERN.into(),
168    ]
169}
170
171/// `$1` the process pattern.
172const REAP_SCRIPT: &str = r#"pkill -KILL -f "$1" || true
173i=0
174while pgrep -f "$1" >/dev/null 2>&1; do
175    i=$((i+1))
176    if [ "$i" -gt 20 ]; then echo alive; exit 1; fi
177    sleep 0.5
178done
179echo gone"#;
180
181/// Whether the reap script's output says nothing is left running.
182pub fn reap_says_gone(output: &str) -> bool {
183    output.lines().any(|l| l.trim() == "gone")
184}
185
186/// Why an install did not finish, in words for the pane.
187///
188/// `stopped` is whether the host-side backstop confirmed the install is no
189/// longer running; `None` when the backstop did not apply.
190pub fn install_failure_detail(exit: Option<i64>, timed_out: bool, stopped: Option<bool>, output: &str) -> String {
191    if timed_out {
192        return match stopped {
193            Some(true) => "the install took too long and was stopped".to_string(),
194            _ => "the install took too long and could not be stopped; wait a minute before trying again".to_string(),
195        };
196    }
197    // `timeout` exits 124 when it had to kill npm.
198    if exit == Some(124) || exit == Some(137) {
199        return "the install took too long and was stopped".to_string();
200    }
201    let tail = output_tail(output, 600);
202    if !tail.is_empty() {
203        return tail;
204    }
205    format!("the install exited with status {}", exit.map_or("unknown".to_string(), |c| c.to_string()))
206}
207
208/// `$1` command, `$2` install dir, `$3` marker.
209const CHECK_SCRIPT: &str = r#"if command -v "$1" >/dev/null 2>&1 || [ -f "$2/$3" ]; then echo present; else echo missing; fi"#;
210
211/// `$1` install dir, `$2` marker, `$3` command, `$4` seconds npm may run, the
212/// rest `name@version`.
213///
214/// npm installs into a staging directory inside the volume, so an attempt that
215/// dies half-way never leaves a half-written `node_modules` where the CLI is
216/// looked up. Only a verified install replaces the live tree, and the marker is
217/// written last, so "marker present" always means "complete". The marker of an
218/// older pin goes before the swap for the same reason.
219const INSTALL_SCRIPT: &str = r#"set -eu
220DIR="$1"; MARKER="$2"; BIN="$3"; LIMIT="$4"; shift 4
221STAGE="$DIR/.staging"
222mkdir -p "$DIR"
223rm -rf "$STAGE"
224mkdir -p "$STAGE"
225export npm_config_cache=/tmp/agentmux-npm-cache npm_config_update_notifier=false
226trap 'rm -rf /tmp/agentmux-npm-cache "$STAGE"' EXIT
227timeout -k 15 "$LIMIT" npm install --prefix "$STAGE" --no-audit --no-fund --no-progress --legacy-peer-deps=false --loglevel=error "$@"
228"$STAGE/node_modules/.bin/$BIN" --version >/dev/null
229rm -f "$DIR"/.installed-*
230rm -rf "$DIR/node_modules"
231mv "$STAGE/node_modules" "$DIR/node_modules"
232"$DIR/node_modules/.bin/$BIN" --version >/dev/null
233: > "$DIR/$MARKER""#;
234
235/// The directory an npm install puts its shims in.
236pub fn cli_bin_dir() -> String {
237    format!("{CONTAINER_CLI_DIR}/node_modules/.bin")
238}
239
240/// What the turn wrapper appends to `PATH`: the npm shims, the downloaded files and the Python tools' venv.
241pub fn cli_path_dirs() -> String {
242    format!("{}:{CONTAINER_CLI_DIR}/bin:{CONTAINER_CLI_DIR}/venv/bin", cli_bin_dir())
243}
244
245/// Whether the check script's output means the CLI is already there.
246pub fn check_says_present(output: &str) -> bool {
247    output.lines().any(|l| l.trim() == "present")
248}
249
250/// The last `max` characters of `output`, whole lines where possible, trimmed.
251pub fn output_tail(output: &str, max: usize) -> String {
252    let trimmed = output.trim();
253    let count = trimmed.chars().count();
254    if count <= max {
255        return trimmed.to_string();
256    }
257    let tail: String = trimmed.chars().skip(count - max).collect();
258    match tail.find('\n') {
259        Some(i) if i + 1 < tail.len() => tail[i + 1..].trim().to_string(),
260        _ => tail.trim().to_string(),
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    fn claude() -> CliInstall {
269        CliInstall::for_provider("claude", "claude").expect("claude installs from npm")
270    }
271
272    #[test]
273    fn claude_installs_the_version_the_provider_table_pins() {
274        let install = claude();
275        let provider = providers::get_provider("claude").unwrap();
276        assert_eq!(install.version, provider.pinned_version);
277        assert_eq!(install.specs, vec![format!("@anthropic-ai/claude-code@{}", provider.pinned_version)]);
278        assert_eq!(install.command, "claude");
279    }
280
281    #[test]
282    fn a_custom_command_or_a_non_npm_provider_is_not_installed() {
283        assert_eq!(CliInstall::for_provider("claude", "my-claude-wrapper"), None);
284        assert_eq!(CliInstall::for_provider("no-such-provider", "x"), None);
285    }
286
287    #[test]
288    fn the_marker_changes_with_the_pin_and_is_a_plain_file_name() {
289        let a = claude();
290        let mut b = a.clone();
291        b.specs = vec!["@anthropic-ai/claude-code@9.9.9".into()];
292        assert_ne!(a.marker(), b.marker());
293        let marker = a.marker();
294        assert!(marker.starts_with(".installed-"));
295        assert!(!marker.contains('/') && !marker.contains('@') && !marker.contains(' '), "{marker}");
296    }
297
298    #[test]
299    fn the_cache_key_separates_containers_and_pins() {
300        let a = claude();
301        assert_ne!(a.cache_key("agentmux-one"), a.cache_key("agentmux-two"));
302    }
303
304    #[test]
305    fn the_scripts_get_their_inputs_as_positional_parameters() {
306        let install = claude();
307        let argv = install.install_argv(InstallLimits::default());
308        assert_eq!(&argv[..2], ["sh", "-c"]);
309        assert_eq!(argv[2], INSTALL_SCRIPT);
310        assert_eq!(argv[4], CONTAINER_CLI_DIR);
311        assert_eq!(argv[5], install.marker());
312        assert_eq!(argv[6], "claude");
313        assert_eq!(argv[7], "540", "npm's own limit is the script limit");
314        assert_eq!(&argv[8..], install.specs.as_slice());
315        // Nothing variable is part of the script text.
316        assert!(!INSTALL_SCRIPT.contains("claude-code"));
317        assert!(!INSTALL_SCRIPT.contains(&install.version));
318
319        let check = install.check_argv();
320        assert_eq!(check[2], CHECK_SCRIPT);
321        assert_eq!(&check[4..], ["claude", CONTAINER_CLI_DIR, install.marker().as_str()]);
322    }
323
324    #[test]
325    fn the_install_verifies_the_binary_before_writing_the_marker() {
326        let verify = INSTALL_SCRIPT.rfind("--version").expect("verifies");
327        let marker = INSTALL_SCRIPT.find(": > ").expect("writes the marker");
328        assert!(verify < marker, "the marker is the last step, after the final check");
329        assert!(INSTALL_SCRIPT.starts_with("set -eu"), "any failed step ends the script");
330        assert!(INSTALL_SCRIPT.contains("rm -f \"$DIR\"/.installed-*"), "an older pin's marker goes");
331    }
332
333    #[test]
334    fn the_install_builds_in_a_staging_dir_and_swaps_only_after_it_verified() {
335        let npm = INSTALL_SCRIPT.find("npm install --prefix \"$STAGE\"").expect("npm installs into staging");
336        let verify = INSTALL_SCRIPT.find("\"$STAGE/node_modules/.bin/$BIN\" --version").expect("verifies the staged binary");
337        let drop_marker = INSTALL_SCRIPT.find("rm -f \"$DIR\"/.installed-*").expect("drops the old marker");
338        let drop_live = INSTALL_SCRIPT.find("rm -rf \"$DIR/node_modules\"").expect("drops the live tree");
339        let swap = INSTALL_SCRIPT.find("mv \"$STAGE/node_modules\"").expect("swaps");
340        let write_marker = INSTALL_SCRIPT.find(": > ").expect("writes the marker");
341        assert!(npm < verify && verify < drop_marker && drop_marker < drop_live && drop_live < swap && swap < write_marker);
342        assert!(INSTALL_SCRIPT.contains("rm -rf \"$STAGE\"\n"), "a half-written earlier attempt is cleared first");
343        assert!(INSTALL_SCRIPT.contains("timeout -k 15 \"$LIMIT\" npm install"), "npm limits itself");
344    }
345
346    #[test]
347    fn the_reap_script_kills_the_install_and_waits_until_it_is_gone() {
348        let argv = reap_argv();
349        assert_eq!(argv[2], REAP_SCRIPT);
350        assert!(REAP_SCRIPT.contains("pkill -KILL -f \"$1\""));
351        assert!(REAP_SCRIPT.contains("pgrep -f \"$1\""), "it checks, not just signals");
352        assert!(REAP_SCRIPT.contains("echo alive; exit 1"), "and fails when something survives");
353        // The bracket keeps the script's own command line from matching itself.
354        assert!(argv[4].starts_with("[n]pm install --prefix /home/agent/.agentmux/cli"));
355        assert!(!argv[4].replace('[', "").replace(']', "").is_empty());
356    }
357
358    #[test]
359    fn reap_output_is_read_by_line() {
360        assert!(reap_says_gone("gone\n"));
361        assert!(!reap_says_gone("alive\n"));
362        assert!(!reap_says_gone(""));
363    }
364
365    #[test]
366    fn a_timeout_reads_as_stopped_only_when_the_backstop_confirmed_it() {
367        let stopped = install_failure_detail(None, true, Some(true), "");
368        assert!(stopped.contains("was stopped"), "{stopped}");
369        for unconfirmed in [Some(false), None] {
370            let msg = install_failure_detail(None, true, unconfirmed, "");
371            assert!(msg.contains("could not be stopped"), "{msg}");
372            assert!(msg.contains("wait"), "tells the person not to retry at once: {msg}");
373        }
374    }
375
376    #[test]
377    fn the_scripts_own_timeout_and_a_kill_read_as_too_slow() {
378        for code in [124, 137] {
379            let msg = install_failure_detail(Some(code), false, None, "npm warn something");
380            assert!(msg.contains("took too long"), "{msg}");
381        }
382    }
383
384    #[test]
385    fn an_ordinary_failure_shows_npms_own_last_words_or_the_status() {
386        assert_eq!(install_failure_detail(Some(1), false, None, "npm error code ENOTFOUND\n"), "npm error code ENOTFOUND");
387        assert_eq!(install_failure_detail(Some(1), false, None, ""), "the install exited with status 1");
388        assert_eq!(install_failure_detail(None, false, None, ""), "the install exited with status unknown");
389    }
390
391    #[test]
392    fn the_install_keeps_the_npm_cache_out_of_the_container_layer() {
393        assert!(INSTALL_SCRIPT.contains("npm_config_cache=/tmp/"));
394        assert!(INSTALL_SCRIPT.contains("rm -rf /tmp/agentmux-npm-cache"));
395    }
396
397    #[test]
398    fn the_bin_dir_is_where_npm_puts_the_binary() {
399        assert_eq!(cli_bin_dir(), "/home/agent/.agentmux/cli/node_modules/.bin");
400    }
401
402    #[test]
403    fn the_check_output_is_read_by_line() {
404        assert!(check_says_present("present\n"));
405        assert!(check_says_present("noise\npresent\r\n"));
406        assert!(!check_says_present("missing\n"));
407        assert!(!check_says_present(""));
408    }
409
410    #[test]
411    fn the_output_tail_keeps_the_end_on_a_line_boundary() {
412        assert_eq!(output_tail("  short  ", 100), "short");
413        let long = format!("{}\nlast line one\nlast line two", "x".repeat(500));
414        let tail = output_tail(&long, 40);
415        assert!(tail.ends_with("last line two"), "{tail}");
416        assert!(!tail.contains('x'), "{tail}");
417    }
418
419    /// Runs the real scripts in a shell, with `npm` and the CLI faked.
420    #[cfg(unix)]
421    #[test]
422    fn the_scripts_behave_in_a_real_shell() {
423        use std::os::unix::fs::PermissionsExt;
424        use std::process::Command;
425        // The install script runs in the Linux agent container, which has
426        // coreutils `timeout`; a host without it (macOS) can't run it.
427        if !Command::new("sh").args(["-c", "command -v timeout"]).output().is_ok_and(|o| o.status.success()) {
428            eprintln!("skipped: no `timeout` on this host; the script targets the Linux agent container");
429            return;
430        }
431        let dir = std::env::temp_dir().join(format!("agentmux-cli-script-test-{}", std::process::id()));
432        let _ = std::fs::remove_dir_all(&dir);
433        std::fs::create_dir_all(&dir).unwrap();
434        let bin = dir.join("fakebin");
435        std::fs::create_dir_all(&bin).unwrap();
436        // A fake npm that "installs" a fake binary under --prefix.
437        let npm = bin.join("npm");
438        std::fs::write(
439            &npm,
440            "#!/bin/sh\nwhile [ \"$1\" != \"--prefix\" ]; do shift; done\nP=\"$2\"\nif [ -e \"$P/../.hang\" ]; then sleep 30; fi\nmkdir -p \"$P/node_modules/.bin\"\nprintf '#!/bin/sh\\necho 1.2.3\\n' > \"$P/node_modules/.bin/fakecli\"\nchmod +x \"$P/node_modules/.bin/fakecli\"\n",
441        )
442        .unwrap();
443        std::fs::set_permissions(&npm, std::fs::Permissions::from_mode(0o755)).unwrap();
444        let cli_dir = dir.join("cli");
445        let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default());
446        let run = |script: &str, args: &[&str]| {
447            let out = Command::new("sh")
448                .arg("-c")
449                .arg(script)
450                .arg("t")
451                .args(args)
452                .env("PATH", &path)
453                .output()
454                .unwrap();
455            (out.status.success(), String::from_utf8_lossy(&out.stdout).to_string())
456        };
457        let dir_s = cli_dir.to_string_lossy().to_string();
458
459        let (_, before) = run(CHECK_SCRIPT, &["fakecli", &dir_s, ".installed-x"]);
460        assert!(!check_says_present(&before), "{before}");
461
462        let (ok, _) = run(INSTALL_SCRIPT, &[&dir_s, ".installed-x", "fakecli", "60", "fake@1.2.3"]);
463        assert!(ok, "install should succeed");
464        assert!(cli_dir.join(".installed-x").is_file());
465
466        let (_, after) = run(CHECK_SCRIPT, &["fakecli", &dir_s, ".installed-x"]);
467        assert!(check_says_present(&after), "{after}");
468
469        // A new pin leaves the old marker behind no longer.
470        let (ok, _) = run(INSTALL_SCRIPT, &[&dir_s, ".installed-y", "fakecli", "60", "fake@2.0.0"]);
471        assert!(ok);
472        assert!(!cli_dir.join(".installed-x").exists());
473        assert!(cli_dir.join(".installed-y").is_file());
474
475        // A binary that is not produced fails the script and writes no marker.
476        let (ok, _) = run(INSTALL_SCRIPT, &[&dir_s, ".installed-z", "missingcli", "60", "fake@3.0.0"]);
477        assert!(!ok, "a missing binary must fail the install");
478        assert!(!cli_dir.join(".installed-z").exists());
479        assert!(!cli_dir.join(".staging").exists(), "staging is cleaned up on failure");
480
481        // A half-written earlier attempt (stale staging, junk in the staging tree)
482        // does not leak into a retry.
483        std::fs::create_dir_all(cli_dir.join(".staging/node_modules/junk")).unwrap();
484        let (ok, _) = run(INSTALL_SCRIPT, &[&dir_s, ".installed-w", "fakecli", "60", "fake@4.0.0"]);
485        assert!(ok);
486        assert!(cli_dir.join(".installed-w").is_file());
487        assert!(!cli_dir.join("node_modules/junk").exists(), "stale staging content is not installed");
488
489        // A hanging npm (the fake sleeps while `.hang` exists) is killed by the
490        // script's own limit: the script fails, no marker is written, and the
491        // previous good install is left as it was.
492        std::fs::write(cli_dir.join(".hang"), "").unwrap();
493        let started = std::time::Instant::now();
494        let (ok, _) = run(INSTALL_SCRIPT, &[&dir_s, ".installed-v", "fakecli", "1", "fake@5.0.0"]);
495        assert!(!ok, "the script gives up on a hanging npm");
496        assert!(started.elapsed() < std::time::Duration::from_secs(20), "it did not wait for the sleep");
497        assert!(!cli_dir.join(".installed-v").exists());
498        assert!(cli_dir.join(".installed-w").is_file(), "the previous install and its marker are intact");
499        assert!(cli_dir.join("node_modules/.bin/fakecli").exists());
500        assert!(!cli_dir.join(".staging").exists());
501        std::fs::remove_file(cli_dir.join(".hang")).unwrap();
502
503        let _ = std::fs::remove_dir_all(&dir);
504    }
505}