Skip to main content

agentmux_srv_core/backend/
container.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Container management for container-type agent panes (Phase 1).
5//!
6//! Manages persistent Docker containers — one per container agent. Each
7//! container runs the configured image (e.g. `ghcr.io/agentmuxai/agent-claude`)
8//! with `tini` as PID 1 and is kept alive between turns. Individual turns are
9//! executed via `docker exec -i` (no `-t` — avoids CR/LF corruption of NDJSON).
10//!
11//! Platform support (cross-platform, matches SPEC_CONTAINER_PANE_SUPPORT_2026_06_11.md):
12//!   - `DOCKER_HOST` when set (unix, tcp with or without TLS, https, npipe), else the sockets
13//!     Docker, Podman, Colima and OrbStack leave in their usual places; the first that answers a
14//!     ping is used (`container/runtime.rs`).
15//!   - Windows: named pipe `//./pipe/docker_engine`
16//!
17//! Independence boundary: this module has no dependency on any other project's container code.
18//! Docker best practices here were researched independently.
19
20pub mod drift;
21pub mod limits;
22pub mod oom;
23pub mod keychain_credentials;
24pub mod mount_source;
25pub mod mounts;
26pub mod oneshot;
27pub mod session_files;
28pub mod status_source;
29pub(crate) use self::mounts::container_memory_dir;
30pub mod pull;
31pub mod reap;
32pub mod argv;
33pub mod cli;
34pub mod cli_release;
35pub mod upload;
36pub mod credential;
37pub mod image;
38mod image_tools;
39mod agent_caps;
40pub mod gateway_fwd;
41pub mod key_route;
42pub mod runtime_socket;
43pub mod listener;
44pub mod routes;
45pub mod runtime;
46pub use self::pull::{StartEvent, StartObserver};
47
48use std::collections::HashMap;
49use std::pin::Pin;
50use std::sync::Arc;
51use tokio::io::AsyncWrite;
52use tokio::sync::Mutex;
53use futures_util::StreamExt as _;
54use bollard::Docker;
55
56use self::mount_source::fold_mount_source;
57use self::mounts::{agent_home_mounts, host_name_for_new_container};
58use bollard::container::{
59    Config, CreateContainerOptions, ListContainersOptions, StartContainerOptions, StopContainerOptions,
60};
61use bollard::exec::{CreateExecOptions, StartExecOptions, StartExecResults};
62use bollard::models::{ContainerInspectResponse, HostConfig, Mount, MountTypeEnum};
63use crate::backend::container::cli::{
64    check_says_present, install_failure_detail, reap_argv, reap_says_gone, CliInstall, InstallLimits,
65};
66use crate::backend::container::image::{CONTAINER_CLI_DIR,
67    cli_install_failure_message, docker_error_message, docker_unreachable_message,
68    looks_like_daemon_unreachable, pull_failure_message, PullFailure,
69};
70
71/// Where the agent CLI's config dir lives inside the image (`CLAUDE_CONFIG_DIR`).
72pub const CONTAINER_CLAUDE_DIR: &str = "/home/agent/.claude";
73/// Where the agent's working directory is bind-mounted inside the image.
74pub const CONTAINER_WORKSPACE_DIR: &str = "/workspace";
75/// Where the folder holding an agent's MCP config is bind-mounted when it lives outside the
76/// working directory, so a container launch never has to write it into a user's project (#3680).
77/// The folder, not the file: a single-file bind would keep the old inode across an atomic rewrite.
78/// Shared with `agentmux-mcp doctor`, which looks for the config here inside a container.
79pub use agentmux_common::mcp_config_path::CONTAINER_MCP_CONFIG_DIR;
80
81/// Shared user-defined Docker bridge network every agent container is
82/// attached to, ADDITIVE to whatever `network_mode`/`extra_hosts` already
83/// set up (container→host reachability, unaffected — see the doc comment
84/// on `network_mode` below). Unlike the default bridge network, a
85/// user-defined one gives per-container DNS resolution and lets the
86/// native dev-proxy (`backend::dev_proxy`) route to a container by its
87/// internal IP. See docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md §3.1.
88pub const AGENTMUX_DOCKER_NETWORK: &str = "agentmux-agents";
89
90/// Host directories a container agent needs mounted to be able to work.
91///
92/// Both were missing entirely before 2026-09-02, which is why container agents
93/// could never authenticate and always started with an empty `/workspace`. See
94/// `docs/reports/REPORT_CONTAINER_AGENT_CREDENTIALS_AND_WORKSPACE_2026_09_02.md`.
95#[derive(Debug, Clone, Default, PartialEq, Eq)]
96pub struct ContainerMountSpec {
97    /// The folder holding the container's own copy of the bound account's login: its `.credentials.json` is
98    /// bind-mounted into the container, so the CLI there signs in and refreshes from it (see [`agent_home_mounts`]
99    /// for why it is that one file and not the whole dir). It is never the account's own folder: a container that
100    /// holds the account's own file could empty it for every other container and every host CLI on the account.
101    /// Filled by the start of the container from [`Self::staged_login_config_dir`] (see [`keychain_credentials`]).
102    ///
103    /// `None` keeps the old behavior (an empty per-agent named volume), which is correct only for an agent with
104    /// no bound oauth account.
105    pub claude_config_host_dir: Option<String>,
106    /// The bound account's own resolved Claude config dir on the host: whatever `CLAUDE_CONFIG_DIR` the identity
107    /// resolver produced for this agent, never the operator's global `~/.claude`. The start of the container stages
108    /// the account's login (from its file, or on macOS from the Keychain) as a copy for this container alone, and
109    /// fills [`Self::claude_config_host_dir`] with the staging folder. `None` for an agent with no bound account
110    /// login, and for one on an API key.
111    pub staged_login_config_dir: Option<String>,
112    /// The agent's working directory on the host, bind-mounted at
113    /// [`CONTAINER_WORKSPACE_DIR`]. `None`/empty leaves `/workspace` empty, which
114    /// is what shipped before this existed.
115    pub workspace_host_dir: Option<String>,
116    /// The agent's Personal Memory folder on the host, bind-mounted where Claude reads memory in the container.
117    pub memory_host_dir: Option<String>,
118    /// The folder holding the agent's MCP config when it lives outside the working directory (#3680):
119    /// bind-mounted read-only at [`CONTAINER_MCP_CONFIG_DIR`] so no launch writes it into a user's
120    /// project, and a rewrite is visible without recreating the container.
121    pub mcp_config_host_dir: Option<String>,
122    /// AgentMux's git hooks (push scan, commit trailers) on the host, mounted read-only at
123    /// [`crate::identity::github_tokens::CONTAINER_HOOKS_DIR`] where container agents get git through AgentMux.
124    pub github_hooks_host_dir: Option<String>,
125    /// The AWS config folder (`identity::aws_broker::container`) and the tools folder (`::tools`), both read-only; in the drift check only when set, so not sharing never rebuilds.
126    pub aws_config_host_dir: Option<String>,
127    pub aws_tools_host_dir: Option<String>,
128    /// The agent's own CPU and memory limits (the app-wide setting and the default fill in what it leaves unset).
129    pub limits: limits::ContainerLimits,
130}
131
132/// Normalize a host path for Docker's mount API: backslashes are not accepted in
133/// a bind source, so `C:\Users\x` has to travel as `C:/Users/x`.
134fn normalize_host_path(path: &str) -> String {
135    path.replace('\\', "/")
136}
137
138/// The credentials file inside the account's config dir, and inside the image.
139pub const CLAUDE_CREDENTIALS_FILE: &str = ".credentials.json";
140
141/// The account config dir to hand to [`ContainerMountSpec::claude_config_host_dir`],
142/// or `None` when this account has no file-backed credential to mount.
143///
144/// The existence check is load-bearing, not defensive tidiness (codex P1 on PR
145/// #2933). **On macOS Claude Code keeps OAuth credentials in the encrypted
146/// Keychain and never writes this file at all** — see
147/// `identity/resolver/oauth_probe.rs` and
148/// `docs/retro/retro-macos-keychain-credential-isolation-gap-2026-08-17.md`.
149/// Binding a source that does not exist makes Docker reject `create_container`
150/// outright, so an unguarded bind would turn "container agents cannot
151/// authenticate on macOS" into "container agents cannot START on macOS" — a
152/// strictly worse failure than the one this fix exists to remove.
153///
154/// Returning `None` degrades to an empty per-agent volume and logs why. On macOS the
155/// container's start then stages the account's Keychain login instead (see
156/// [`ContainerMountSpec::staged_login_config_dir`] and `keychain_credentials`).
157pub fn credentials_dir_if_file_backed(claude_config_host_dir: &str) -> Option<String> {
158    if claude_config_host_dir.is_empty() {
159        return None;
160    }
161    let creds = std::path::Path::new(claude_config_host_dir).join(CLAUDE_CREDENTIALS_FILE);
162    if creds.is_file() {
163        return Some(claude_config_host_dir.to_string());
164    }
165    if cfg!(target_os = "macos") {
166        // Claude Code keeps this login in the Keychain; the container's start stages it (or stops with a message).
167        tracing::info!(
168            dir = %claude_config_host_dir,
169            "container agent: no {CLAUDE_CREDENTIALS_FILE} in the bound account's config dir — \
170             its Keychain login is staged for the container at start instead"
171        );
172    } else {
173        tracing::warn!(
174            dir = %claude_config_host_dir,
175            "container agent: no {CLAUDE_CREDENTIALS_FILE} in the bound account's config dir — \
176             not mounting credentials. The agent will start but will not be authenticated."
177        );
178    }
179    None
180}
181
182/// Rewrite a host-loopback `AGENTMUX_LOCAL_URL` (e.g. `http://127.0.0.1:PORT`)
183/// into something a container's network namespace can actually reach.
184///
185/// `docker exec` over the Docker socket never inherits the host process's
186/// env the way a host subprocess does, so a container agent gets no sidecar
187/// URL at all unless one is explicitly injected — and injecting the
188/// loopback value verbatim would be reachable from the srv process but not
189/// from inside the container. `host.docker.internal` is resolvable from
190/// Docker Desktop (macOS/Windows) automatically, and from native Linux via
191/// the `extra_hosts: host.docker.internal:host-gateway` entry
192/// `create_and_start` sets — see #2939 workstream 1.
193///
194/// Only rewrites `127.0.0.1`/`localhost`; any other host (already a real
195/// hostname/IP, or already `host.docker.internal`) passes through
196/// unchanged, so this is safe to call unconditionally.
197pub fn rewrite_local_url_for_container(local_url: &str) -> String {
198    local_url
199        .replace("127.0.0.1", "host.docker.internal")
200        .replace("localhost", "host.docker.internal")
201}
202
203/// Shared container manager. Clone-on-Arc; cheap to pass around.
204#[derive(Clone)]
205pub struct ContainerManager {
206    inner: Arc<ContainerManagerInner>,
207}
208
209struct ContainerManagerInner {
210    docker: Docker,
211    /// The runtime in use, for the pane: `Podman at unix:///…`. `None` for a connection made
212    /// without detection ([`ContainerManager::connect`]).
213    runtime: Option<String>,
214    /// Per-container serialization lock: prevents concurrent ensure_running calls
215    /// for the same container from both seeing "not found" in Docker and both
216    /// attempting create_container (which would fail with a 409 name-conflict
217    /// on the second caller).
218    ensure_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
219    /// Per-container `(uid, gid)` of the user execs run as, resolved once and
220    /// cached — see [`ContainerManager::exec_identity`].
221    exec_identities: Mutex<HashMap<String, (u64, u64)>>,
222    /// `(container, install marker)` pairs already confirmed installed, so a
223    /// running agent pays the check once, not on every turn. Dropped when the
224    /// container is created or removed.
225    cli_ready: Mutex<std::collections::HashSet<String>>,
226    /// Serializes `provision_cli` per container: two quick messages must not
227    /// run two `npm install`s into the same directory.
228    cli_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
229    /// Dev-proxy routing table, wired in post-construction by
230    /// [`ContainerManager::attach_dev_proxy_registry`] (called by
231    /// `ContainerRuntimeHandle`, which re-attaches after every reconnect
232    /// since each reconnect creates a fresh `ContainerManagerInner`).
233    /// `stop`/`remove` clear this agent's registrations when set — see
234    /// `cleanup_dev_proxy_routes`. Unset (`None` via `OnceLock`) in tests
235    /// and any path that never wires it up; cleanup is then simply
236    /// skipped, never an error. See
237    /// docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md.
238    dev_proxy: std::sync::OnceLock<crate::backend::dev_proxy::DevProxyRegistry>,
239}
240
241/// Exec session handle for a single turn.
242///
243/// `input` is the stdin pipe into the container process. It is ONLY usable for a
244/// process that completes on a newline: the write half can never be closed, so
245/// stdin never reaches EOF (see [`ContainerManager::exec`]). Turn input goes in
246/// a file instead — NOT argv, which would leak a pasted secret via `docker top`
247/// / host `ps` / `/proc/<pid>/cmdline`; see
248/// [`ContainerManager::upload_turn_prompt`]. `output` is a bollard `LogOutput`
249/// stream; with
250/// `tty: false` Docker multiplexes stdout as `LogOutput::StdOut` frames and
251/// stderr as `LogOutput::StdErr` frames.
252///
253/// Env vars are passed via `CreateExecOptions.env` (Docker socket) — they never
254/// appear in process argv, preventing CWE-214 credential exposure via ps/proc.
255pub struct ExecSession {
256    /// Docker exec id — pass to [`ContainerManager::inspect_exec`] after the
257    /// output stream ends to retrieve the process's real exit code. The stream
258    /// ending is NOT the exit status, so callers that care about success/failure
259    /// must inspect the exec (the in-container CLI can exit non-zero while still
260    /// closing stdout cleanly).
261    pub exec_id: String,
262    /// Stdin pipe to the container process. Unusable for EOF-terminated readers
263    /// — see the type-level doc and [`ContainerManager::exec`]'s `attach_stdin`.
264    pub input: Pin<Box<dyn AsyncWrite + Send>>,
265    /// Multiplexed stdout/stderr stream (LogOutput::StdOut / LogOutput::StdErr).
266    pub output: Pin<Box<dyn futures_util::Stream<Item = Result<bollard::container::LogOutput, bollard::errors::Error>> + Send>>,
267}
268
269/// Parse `id -u; id -g` output into `(uid, gid)`.
270///
271/// Split out so the parse is testable without a Docker daemon, and so a
272/// malformed or empty probe result is `None` — never a silent `(0, 0)`, which
273/// would produce a prompt file the exec user can neither read nor delete.
274fn parse_id_output(out: &str) -> Option<(u64, u64)> {
275    let mut fields = out.split_whitespace();
276    let uid: u64 = fields.next()?.parse().ok()?;
277    let gid: u64 = fields.next()?.parse().ok()?;
278    Some((uid, gid))
279}
280
281#[cfg(test)]
282mod exec_identity_tests {
283    use super::parse_id_output;
284
285    #[test]
286    fn parses_the_ordinary_two_line_form() {
287        assert_eq!(parse_id_output("1000\n1000\n"), Some((1000, 1000)));
288    }
289
290    #[test]
291    fn parses_root_and_a_split_uid_gid() {
292        assert_eq!(parse_id_output("0\n0\n"), Some((0, 0)));
293        assert_eq!(parse_id_output("1000\n2000\n"), Some((1000, 2000)));
294    }
295
296    /// Docker multiplexes frames, so the two numbers may arrive however they
297    /// arrive — whitespace splitting must not care.
298    #[test]
299    fn tolerates_arbitrary_whitespace_and_framing() {
300        assert_eq!(parse_id_output("  1000 \r\n  1000  \r\n"), Some((1000, 1000)));
301        assert_eq!(parse_id_output("1000 1000"), Some((1000, 1000)));
302    }
303
304    /// The whole point of returning Option: a failed or truncated probe must
305    /// NOT silently become root (reagent P1, PR #2883).
306    #[test]
307    fn a_missing_or_malformed_probe_is_none_not_root() {
308        assert_eq!(parse_id_output(""), None);
309        assert_eq!(parse_id_output("1000"), None, "gid missing");
310        assert_eq!(parse_id_output("id: command not found"), None);
311        assert_eq!(parse_id_output("uid=1000(agent)"), None, "not the -u form");
312        assert_eq!(parse_id_output("-1\n-1\n"), None, "negative is not a uid");
313    }
314}
315
316/// Errors from container operations.
317#[derive(Debug, thiserror::Error)]
318pub enum ContainerError {
319    #[error("Docker API error: {0}")]
320    Docker(#[from] bollard::errors::Error),
321    #[error("Container has no id after create: {name}")]
322    NoId { name: String },
323    #[error("Docker is not available on this host: {0}")]
324    NotAvailable(String),
325    /// No container runtime answered; the text says where it looked and why each place failed
326    /// ([`runtime::Missing::message`]).
327    #[error("{0}")]
328    NoRuntime(String),
329    /// The image could not be downloaded. `detail` is the daemon's own text,
330    /// kept for logs; the pane gets [`ContainerError::user_message`].
331    #[error("could not pull image {image}: {detail}")]
332    ImagePull {
333        image: String,
334        kind: PullFailure,
335        detail: String,
336    },
337    /// The provider CLI could not be installed in the container.
338    #[error("could not install {command} in the container: {detail}")]
339    CliInstall { command: String, detail: String },
340    /// A `container_volumes` entry whose source is a CLI session folder or a container runtime's socket or folder.
341    #[error("the volume source {path} is one a container may not mount")]
342    VolumeRefused { path: String },
343    /// The macOS Keychain login couldn't be given to the container (plain reason); raised before the image is pulled.
344    #[error("no login for the container: {0}")]
345    NoLogin(String),
346    /// The image lacks what an AgentMux agent needs to talk to AgentMux (`agentmux-bashwrap`, `agentmux-mcp`): a
347    /// container made from it starts and cannot reach its tools, its startup memory or anyone.
348    #[error("the image {image} has no {}", missing.join(" or "))]
349    ImageIncomplete { image: String, missing: Vec<String> },
350    /// The agent's API-key account can't be used from this container (plain reason, with what to do instead).
351    #[error("{0}")]
352    KeyRoute(String),
353}
354
355impl ContainerError {
356    /// What to tell the person using the agent: what happened and what to do
357    /// next, never the raw Docker error.
358    pub fn user_message(&self) -> String {
359        match self {
360            Self::ImagePull { image, kind, detail } => pull_failure_message(image, *kind, detail),
361            Self::Docker(e) => {
362                let text = e.to_string();
363                if looks_like_daemon_unreachable(&text) {
364                    docker_unreachable_message()
365                } else {
366                    docker_error_message(&text)
367                }
368            }
369            Self::NotAvailable(_) => docker_unreachable_message(),
370            Self::NoRuntime(message) => message.clone(),
371            Self::NoId { .. } => docker_error_message("the container was created without an id"),
372            Self::CliInstall { command, detail } => cli_install_failure_message(command, detail),
373            Self::NoLogin(reason) => keychain_credentials::no_login_message(reason),
374            Self::ImageIncomplete { image, missing } => format!(
375                "This agent's container image ({image}) has no {}, so the agent could not reach its tools or its startup \
376                 memory, or message anyone. Set its image to one AgentMux ships (`Agents update_container` with \
377                 container_image, or the agent's definition in the window), or build yours from ghcr.io/agentmuxai/agent-base.",
378                missing.join(" or ")
379            ),
380            Self::KeyRoute(reason) => reason.clone(),
381            Self::VolumeRefused { path } => format!(
382                "This agent's workspace or volumes list {path}, which a container may not mount (a container runtime's socket or pipe or a folder holding one, a folder the CLI keeps its sessions in, or the AgentMux folders or a folder that holds them, such as a home folder): remove it from the agent's volumes, or give the agent a folder of its own as its workspace. An agent that needs to run containers has to run on this machine, not in a container."
383            ),
384        }
385    }
386}
387
388impl ContainerManager {
389    /// Connect to the local Docker daemon using environment/platform defaults.
390    ///
391    /// Honors `DOCKER_HOST` env var (e.g. for rootless or remote daemons).
392    /// On Windows connects via named pipe; on macOS/Linux via Unix socket.
393    pub fn connect() -> Result<Self, ContainerError> {
394        let docker = Docker::connect_with_local_defaults()
395            .map_err(|e| ContainerError::NotAvailable(e.to_string()))?;
396        Ok(Self::with_docker(docker, None))
397    }
398
399    /// Connect to the runtime [`runtime`] finds: `DOCKER_HOST`, else the first socket
400    /// of rootless Docker, Podman, Docker Desktop, Colima, OrbStack or the system that answers a
401    /// ping. `Err` says where it looked and why each place failed.
402    pub async fn connect_detected() -> Result<Self, ContainerError> {
403        let env = runtime::Env::from_process();
404        match runtime::connect(&env).await {
405            Ok(found) => {
406                let label = found.label();
407                tracing::info!(runtime = %label, "container runtime found");
408                Ok(Self::with_docker(found.docker, Some(label)))
409            }
410            Err(missing) => Err(ContainerError::NoRuntime(missing.message())),
411        }
412    }
413
414    pub(crate) fn with_docker(docker: Docker, runtime: Option<String>) -> Self {
415        Self {
416            inner: Arc::new(ContainerManagerInner {
417                docker,
418                runtime,
419                ensure_locks: Mutex::new(HashMap::new()),
420                exec_identities: Mutex::new(HashMap::new()),
421                cli_ready: Mutex::new(std::collections::HashSet::new()),
422                cli_locks: Mutex::new(HashMap::new()),
423                dev_proxy: std::sync::OnceLock::new(),
424            }),
425        }
426    }
427
428    /// Which runtime this connection is to, e.g. `Podman at unix:///run/user/1000/podman/podman.sock`.
429    pub fn runtime_label(&self) -> Option<&str> {
430        self.inner.runtime.as_deref()
431    }
432
433    /// Wires a dev-proxy routing table into this manager so `stop`/`remove`
434    /// can clear an agent's registrations when its container goes away.
435    /// Set once per `ContainerManager` instance (a second call is a
436    /// harmless no-op — `OnceLock::set` fails silently, which is fine
437    /// here: the registry itself doesn't change after boot).
438    /// See docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md.
439    pub fn attach_dev_proxy_registry(&self, registry: crate::backend::dev_proxy::DevProxyRegistry) {
440        let _ = self.inner.dev_proxy.set(registry);
441    }
442
443    /// This container's IP address on [`AGENTMUX_DOCKER_NETWORK`] — what
444    /// the dev-proxy registry stores as the routable backend address.
445    /// `None` if the container isn't running, isn't on the network yet, or
446    /// Docker is unreachable. Always a fresh `inspect_container`, never
447    /// cached — the caller (`app_api::dev_server::handle_register_dev_server`)
448    /// needs the CURRENT address, not one from whenever the container was
449    /// first created.
450    pub async fn agent_network_ip(&self, container_name: &str) -> Option<String> {
451        let details = self.inner.docker.inspect_container(container_name, None).await.ok()?;
452        details
453            .network_settings?
454            .networks?
455            .get(AGENTMUX_DOCKER_NETWORK)?
456            .ip_address
457            .clone()
458            .filter(|s| !s.is_empty())
459    }
460
461    /// Ping the Docker daemon. Returns `Ok(())` if available.
462    pub async fn check_available(&self) -> Result<(), ContainerError> {
463        self.inner.docker.ping().await?;
464        Ok(())
465    }
466
467    /// Ensure the container for this agent is created and running.
468    ///
469    /// - If it exists and is running: no-op.
470    /// - If it exists but stopped: starts it.
471    /// - If it doesn't exist: creates and starts it.
472    ///
473    /// Always queries Docker (no in-memory cache) so externally killed containers
474    /// are detected. Concurrent calls for the **same** `container_name` are
475    /// serialized via a per-container mutex. Concurrent calls for **different**
476    /// containers proceed in parallel.
477    ///
478    /// `observe` is told about the steps that take long enough for a person to
479    /// wonder: downloading the image (with how far it has got) and creating the
480    /// container. Nothing is reported when it is already up. `true`: this call started it, so what ran in it is gone.
481    pub async fn ensure_running_observed(
482        &self,
483        container_name: &str,
484        image: &str,
485        volumes: &[String],
486        env_vars: &[(String, String)],
487        spec: &ContainerMountSpec,
488        observe: StartObserver<'_>,
489    ) -> Result<bool, ContainerError> {
490        // Acquire the per-container serialization lock before touching Docker.
491        // Concurrent callers for the same container_name queue here; once the
492        // first caller completes, the second finds the container already running
493        // via the Docker query below and returns immediately.
494        let container_lock = {
495            let mut locks = self.inner.ensure_locks.lock().await;
496            locks.entry(container_name.to_string())
497                .or_insert_with(|| Arc::new(Mutex::new(())))
498                .clone()
499        };
500        let guard = container_lock.lock().await;
501
502        let result = self.ensure_running_locked(container_name, image, volumes, env_vars, spec, observe).await;
503
504        // Release the per-container lock, then evict its map entry when no other
505        // caller is queued on it — otherwise `ensure_locks` grows unbounded (one
506        // entry per distinct container ever seen) over the process lifetime.
507        // A queued caller has already cloned the Arc (strong_count > 2), so we
508        // only drop the entry when it's truly idle (map's ref + our clone == 2),
509        // which can't reintroduce the create-race the lock guards: a new caller
510        // can't clone the old Arc while we hold the map lock, and after eviction
511        // it just creates a fresh one with no contention.
512        drop(guard);
513        {
514            let mut locks = self.inner.ensure_locks.lock().await;
515            if Arc::strong_count(&container_lock) <= 2 {
516                locks.remove(container_name);
517            }
518        }
519
520        result
521    }
522
523    /// Create/reuse logic for [`ensure_running`], run while holding the
524    /// per-container serialization lock. Split out so `ensure_running` can wrap
525    /// it with lock acquisition + map-entry eviction on every exit path.
526    async fn ensure_running_locked(
527        &self,
528        container_name: &str,
529        image: &str,
530        volumes: &[String],
531        env_vars: &[(String, String)],
532        spec: &ContainerMountSpec,
533        observe: StartObserver<'_>,
534    ) -> Result<bool, ContainerError> {
535        // Before the container is reused or made: an existing one is refused as well.
536        if let Some(path) = runtime_socket::refused_mount(volumes, spec.workspace_host_dir.as_deref()) {
537            return Err(ContainerError::VolumeRefused { path });
538        }
539        // Always query Docker — do not rely on an in-memory cache. The container
540        // can be stopped or removed externally (e.g. `docker rm -f`), and a
541        // stale cache entry would cause ensure_running to silently no-op while
542        // a subsequent exec call fails.
543        let existing = self.find_container(container_name).await?;
544
545        // A container created before this agent had credentials (or a workspace)
546        // keeps those mounts for its whole life — `docker` cannot add a mount to
547        // an existing container. Without this check the fix would silently never
548        // reach any agent whose container is already up, which is every agent
549        // that has ever run. Recreate on drift; the per-agent named volume
550        // carries session/project state across the swap.
551        let existing = match existing {
552            Some(status) => match self.container_drift(container_name, image, spec).await {
553                Some(reason) => {
554                    tracing::info!(container = container_name, reason, "container spec drift detected — recreating");
555                    let _ = self.stop(container_name, 10).await;
556                    self.remove(container_name, true).await?;
557                    self.restage_login(container_name, spec).await;
558                    None
559                }
560                None => Some(status),
561            },
562            None => None,
563        };
564
565        let started = existing.as_deref() != Some("running");
566        match existing {
567            Some(status) => {
568                if status != "running" {
569                    // Exists but stopped — start it.
570                    crate::backend::container_status::note_starting(container_name, "");
571                    self.inner.docker
572                        .start_container(container_name, None::<StartContainerOptions<String>>)
573                        .await?;
574                    tracing::info!(container = container_name, "restarted stopped container");
575                }
576                self.secure_credentials_once(container_name).await;
577                self.limits_apply(container_name, spec.limits).await;
578            }
579            None => {
580                // Pull the image via Docker socket before create so the Engine API
581                // has the image locally. Unlike `docker run`, the Engine's
582                // create_container does NOT auto-pull — it returns 404 if the image
583                // is absent. pull_image is a no-op when the image already exists.
584                crate::backend::container_status::note_starting(container_name, image);
585                let image = self.pull_with_fallback(image, observe).await?;
586                // Create and start.
587                observe(StartEvent::Starting);
588                self.create_and_start(container_name, &image, volumes, env_vars, spec).await?;
589                self.prepare_home(container_name, spec).await;
590                tracing::info!(container = container_name, image = image, "created and started container");
591            }
592        }
593
594        // Additive, best-effort: attach to the shared dev-proxy network
595        // regardless of which branch above ran, so an already-running
596        // container from before this feature shipped still gets picked up
597        // on its next turn. See `ensure_agent_network`'s own doc comment.
598        self.ensure_agent_network(container_name).await;
599
600        Ok(started)
601    }
602
603    /// Launch an exec session inside a running container.
604    ///
605    /// Uses `-i` (not `-t`) to avoid tty CR/LF corruption of NDJSON output.
606    /// The caller receives `ExecSession` whose `output` stream carries
607    /// multiplexed stdout/stderr for piping into the block.
608    ///
609    /// `attach_stdin` MUST be `false` unless the in-container process is a
610    /// reader that completes on a newline rather than on EOF. Attaching stdin
611    /// is a one-way door: bollard's hijacked exec stream cannot half-close the
612    /// write side (see the `exec (io)` integration test below), and on Windows
613    /// the Docker transport is a named pipe, which has no half-close at all —
614    /// so the process's stdin NEVER reaches EOF. Neither `drop(input)` nor an
615    /// explicit `input.shutdown().await` changes that; both were tried against
616    /// a live container on 2026-09-01 and the process hung indefinitely.
617    ///
618    /// Any command that reads stdin to EOF (`cat`, or `claude -p` taking its
619    /// prompt on stdin) will therefore hang forever, producing no output and
620    /// no exit. Give it a file to read instead — see
621    /// [`ContainerManager::upload_turn_prompt`], which also covers why argv and
622    /// env are both the wrong place for that input.
623    pub async fn exec(
624        &self,
625        container_name: &str,
626        cmd: &[String],
627        working_dir: Option<&str>,
628        env_vars: &[(String, String)],
629        attach_stdin: bool,
630    ) -> Result<ExecSession, ContainerError> {
631        let env: Vec<String> = env_vars.iter()
632            .map(|(k, v)| format!("{k}={v}"))
633            .collect();
634
635        let exec = self.inner.docker
636            .create_exec(container_name, CreateExecOptions {
637                attach_stdin: Some(attach_stdin),
638                attach_stdout: Some(true),
639                attach_stderr: Some(true),
640                tty: Some(false), // NO tty — preserves NDJSON newlines
641                cmd: Some(cmd.iter().map(String::as_str).collect()),
642                working_dir,
643                env: if env.is_empty() { None } else { Some(env.iter().map(String::as_str).collect()) },
644                ..Default::default()
645            })
646            .await?;
647
648        let results = self.inner.docker
649            .start_exec(&exec.id, Some(StartExecOptions {
650                detach: false,
651                ..Default::default()
652            }))
653            .await?;
654
655        match results {
656            StartExecResults::Attached { input, output } => {
657                Ok(ExecSession { exec_id: exec.id, input, output })
658            }
659            StartExecResults::Detached => {
660                Err(ContainerError::Docker(
661                    bollard::errors::Error::DockerResponseServerError {
662                        status_code: 0,
663                        message: "start_exec returned Detached unexpectedly (detach=false)".to_string(),
664                    }
665                ))
666            }
667        }
668    }
669
670    /// The `(uid, gid)` that `exec` runs as inside this container.
671    ///
672    /// Needed so an uploaded file can be OWNED by that user. A tar entry
673    /// defaults to uid 0, and `/tmp` is sticky (`1777`) in every standard
674    /// image — under which a non-root process cannot unlink a root-owned file
675    /// no matter what its mode is. That is not theoretical: it silently leaked
676    /// one prompt file per turn (`rm -f` fails quietly), including multi-
677    /// hundred-KB ones, until a live check caught the files piling up.
678    ///
679    /// Resolved by asking the container rather than assuming a uid, so this
680    /// holds for any image regardless of which user it runs as.
681    ///
682    /// **Only a successful probe is cached.** An earlier cut cached a `(0, 0)`
683    /// fallback on any failure, including a transient Docker hiccup — which
684    /// poisoned the cache for the container's whole life (reagent P1, PR
685    /// #2883). That is not a degraded mode but a permanent break: at mode
686    /// 0600 a root-owned prompt file is unreadable AND un-unlinkable by the
687    /// real exec user, so every later turn on that container would fail to
688    /// open its prompt and orphan another file. A failure now returns `None`
689    /// and is retried on the next turn.
690    async fn exec_identity(&self, container_name: &str) -> Option<(u64, u64)> {
691        if let Some(hit) = self.inner.exec_identities.lock().await.get(container_name) {
692            return Some(*hit);
693        }
694
695        let probe = async {
696            let session = self
697                .exec(
698                    container_name,
699                    &["sh".to_string(), "-c".to_string(), "id -u; id -g".to_string()],
700                    None,
701                    &[],
702                    false,
703                )
704                .await
705                .ok()?;
706            let mut out = String::new();
707            let mut stream = session.output;
708            while let Some(Ok(frame)) = stream.next().await {
709                out.push_str(&frame.to_string());
710            }
711            parse_id_output(&out)
712        }
713        .await;
714
715        match probe {
716            Some(resolved) => {
717                self.inner
718                    .exec_identities
719                    .lock()
720                    .await
721                    .insert(container_name.to_string(), resolved);
722                Some(resolved)
723            }
724            None => {
725                // NOT cached — the next turn probes again.
726                tracing::warn!(
727                    container = container_name,
728                    "could not resolve container exec uid/gid; will retry next turn",
729                );
730                None
731            }
732        }
733    }
734
735    /// Remove a prompt file uploaded by [`upload_turn_prompt`].
736    ///
737    /// The turn's own wrapper script removes the file after the CLI exits, so
738    /// this is only for the path where the wrapper never runs at all — the
739    /// upload succeeded but starting the exec failed, which would otherwise
740    /// orphan the file (reagent P2, PR #2883).
741    ///
742    /// Best-effort by design: it runs as the same user that owns the file, and
743    /// a failure here is not worth failing an already-failing turn over.
744    pub async fn remove_turn_prompt(&self, container_name: &str, prompt_path: &str) {
745        let removed = self
746            .exec(
747                container_name,
748                &[
749                    "sh".to_string(),
750                    "-c".to_string(),
751                    r#"rm -f "$1""#.to_string(),
752                    "agentmux-cleanup".to_string(),
753                    prompt_path.to_string(),
754                ],
755                None,
756                &[],
757                false,
758            )
759            .await;
760        match removed {
761            Ok(session) => {
762                // Drive the stream to completion so the exec actually runs —
763                // Docker starts it lazily on the attached connection.
764                let mut stream = session.output;
765                while let Some(Ok(_)) = stream.next().await {}
766            }
767            Err(e) => tracing::warn!(
768                container = container_name,
769                path = prompt_path,
770                "could not remove orphaned prompt file: {e}",
771            ),
772        }
773    }
774
775    /// Write a turn's prompt into the container as a file, returning its
776    /// absolute in-container path.
777    ///
778    /// This exists because a container turn has no other way to hand the CLI
779    /// its prompt:
780    ///
781    ///   * **exec stdin** can never reach EOF — bollard can't half-close the
782    ///     hijacked stream's write side, and on Windows the Docker transport is
783    ///     a named pipe, which has no half-close at all. A CLI that reads to
784    ///     EOF (`claude -p`) hangs forever with no output and no exit.
785    ///   * **argv** would expose any secret pasted into a chat message via
786    ///     `docker top` / host `ps` / `/proc/<pid>/cmdline`, breaking this
787    ///     module's own no-secrets-in-argv invariant (reagent P1, PR #2883).
788    ///   * **an env var** keeps it off those host surfaces, but shares argv's
789    ///     per-string `MAX_ARG_STRLEN` ceiling — measured in this very image at
790    ///     ~128 KiB (130,000 B passes, 200,000 B fails with "Argument list too
791    ///     long"). A long paste or a large `# Session Context` would break the
792    ///     turn (codex P2, PR #2883).
793    ///
794    /// A file has none of those limits: unbounded size, invisible to every
795    /// host-side process listing, and redirecting from it gives the CLI a real
796    /// stdin that reaches a real EOF.
797    ///
798    /// Ownership is the exec user's (see [`exec_identity`]) so the turn can
799    /// delete the file afterwards. Mode is 0600: only that user ever needs it,
800    /// and it is the same user the CLI already runs as.
801    pub async fn upload_turn_prompt(
802        &self,
803        container_name: &str,
804        turn_id: &str,
805        message: &str,
806    ) -> Result<String, ContainerError> {
807        let file_name = format!("agentmux-turn-{turn_id}");
808        self.upload_tmp_file(container_name, &file_name, message.as_bytes()).await
809    }
810
811    /// Retrieve the exit code of a finished exec via the Docker socket.
812    ///
813    /// Returns `Ok(Some(code))` once the exec has exited, `Ok(None)` while it is
814    /// still running (no code yet) or if Docker did not report one. Call this
815    /// after the exec's output stream has ended — unlike a child process's
816    /// `wait()`, the attached output stream closing does not carry the exit
817    /// status, so the turn's success/failure can only be known by inspecting.
818    pub async fn inspect_exec(&self, exec_id: &str) -> Result<Option<i64>, ContainerError> {
819        let info = self.inner.docker.inspect_exec(exec_id).await?;
820        // `running == Some(true)` means no meaningful code yet.
821        if info.running == Some(true) {
822            return Ok(None);
823        }
824        Ok(info.exit_code)
825    }
826
827    /// Run `argv` in the container and collect its output and exit code.
828    async fn exec_collect(
829        &self,
830        container_name: &str,
831        argv: &[String],
832        limit: std::time::Duration,
833    ) -> Result<ExecOutcome, ContainerError> {
834        const KEEP_BYTES: usize = 16 * 1024;
835        let session = self.exec(container_name, argv, None, &[], false).await?;
836        let exec_id = session.exec_id.clone();
837        let mut stream = session.output;
838        let mut output = String::new();
839        let drain = async {
840            while let Some(item) = stream.next().await {
841                let chunk = item?;
842                output.push_str(&String::from_utf8_lossy(&chunk.into_bytes()));
843                if output.len() > KEEP_BYTES {
844                    let mut cut = output.len() - KEEP_BYTES;
845                    while !output.is_char_boundary(cut) {
846                        cut += 1;
847                    }
848                    output.drain(..cut);
849                }
850            }
851            Ok::<(), bollard::errors::Error>(())
852        };
853        let timed_out = match tokio::time::timeout(limit, drain).await {
854            Ok(result) => {
855                result?;
856                false
857            }
858            Err(_) => true,
859        };
860        let exit = if timed_out { None } else { self.inspect_exec(&exec_id).await? };
861        Ok(ExecOutcome { exec_id, exit, output, timed_out })
862    }
863
864    /// Poll until the exec has stopped running, or `limit` passes. True when it
865    /// is confirmed finished.
866    async fn wait_exec_finished(&self, exec_id: &str, limit: std::time::Duration) -> bool {
867        let deadline = std::time::Instant::now() + limit;
868        loop {
869            match self.docker_exec_running(exec_id).await {
870                Some(false) => return true,
871                Some(true) => {}
872                None => return false,
873            }
874            if std::time::Instant::now() >= deadline {
875                return false;
876            }
877            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
878        }
879    }
880
881    /// Whether the exec is still running; `None` when Docker can't say.
882    async fn docker_exec_running(&self, exec_id: &str) -> Option<bool> {
883        self.inner.docker.inspect_exec(exec_id).await.ok().map(|i| i.running == Some(true))
884    }
885
886    /// Kill any `npm install` into the CLI directory and wait until none is left.
887    /// True only when that is confirmed.
888    async fn reap_cli_install(&self, container_name: &str) -> bool {
889        match self
890            .exec_collect(container_name, &reap_argv(), std::time::Duration::from_secs(30))
891            .await
892        {
893            Ok(out) => out.exit == Some(0) && reap_says_gone(&out.output),
894            Err(e) => {
895                tracing::warn!(container = container_name, error = %e, "could not check for a running CLI install");
896                false
897            }
898        }
899    }
900
901    /// Make sure the provider CLI is usable in this container, installing it on
902    /// first use. `on_install_start` runs just before an install begins (the
903    /// caller shows "Installing ..." then), never when nothing needs installing.
904    pub async fn provision_cli(
905        &self,
906        container_name: &str,
907        install: &CliInstall,
908        on_install_start: impl FnOnce(),
909    ) -> Result<CliProvision, ContainerError> {
910        self.provision_cli_with(container_name, install, install.limits(), on_install_start).await
911    }
912
913    /// [`provision_cli`](Self::provision_cli) with explicit time limits.
914    async fn provision_cli_with(
915        &self,
916        container_name: &str,
917        install: &CliInstall,
918        limits: InstallLimits,
919        on_install_start: impl FnOnce(),
920    ) -> Result<CliProvision, ContainerError> {
921        let key = install.cache_key(container_name);
922        if self.inner.cli_ready.lock().await.contains(&key) {
923            return Ok(CliProvision::Present);
924        }
925
926        let lock = {
927            let mut locks = self.inner.cli_locks.lock().await;
928            locks.entry(container_name.to_string()).or_insert_with(|| Arc::new(Mutex::new(()))).clone()
929        };
930        let guard = lock.lock().await;
931        let result = self.provision_cli_locked(container_name, install, &key, limits, on_install_start).await;
932        drop(guard);
933        {
934            let mut locks = self.inner.cli_locks.lock().await;
935            if Arc::strong_count(&lock) <= 2 {
936                locks.remove(container_name);
937            }
938        }
939        result
940    }
941
942    async fn provision_cli_locked(
943        &self,
944        container_name: &str,
945        install: &CliInstall,
946        key: &str,
947        limits: InstallLimits,
948        on_install_start: impl FnOnce(),
949    ) -> Result<CliProvision, ContainerError> {
950        if self.inner.cli_ready.lock().await.contains(key) {
951            return Ok(CliProvision::Present);
952        }
953        let check = self
954            .exec_collect(container_name, &install.check_argv(), std::time::Duration::from_secs(30))
955            .await?;
956        if check.exit == Some(0) && check_says_present(&check.output) {
957            self.inner.cli_ready.lock().await.insert(key.to_string());
958            return Ok(CliProvision::Present);
959        }
960
961        on_install_start();
962
963        // An earlier attempt may still be running (it timed out, or srv restarted
964        // under it). A second npm into the same volume could corrupt it, so
965        // nothing starts until the first is confirmed gone.
966        let fail = |detail: String| ContainerError::CliInstall { command: install.command.clone(), detail };
967        if !self.reap_cli_install(container_name).await {
968            return Err(fail("an earlier install is still running; wait a minute and try again".to_string()));
969        }
970
971        tracing::info!(container = container_name, command = %install.command, specs = ?install.specs, "installing the provider CLI in the container");
972        let started = std::time::Instant::now();
973        let reaper = reap::ReapOnDrop::new(self, container_name);
974        // The Python route reads its hash lock from files, which are too large for an argument.
975        for file in install.uploads() {
976            self.upload_tmp_file(container_name, &file.name, &file.bytes).await.map_err(|e| fail(e.to_string()))?;
977        }
978        let run = self
979            .exec_collect(container_name, &install.install_argv(limits), limits.run)
980            .await?;
981        reaper.disarm();
982        if run.exit == Some(0) {
983            self.inner.cli_ready.lock().await.insert(key.to_string());
984            return Ok(CliProvision::Installed { seconds: started.elapsed().as_secs_f64() });
985        }
986
987        // The host-side limit passed while the install was still running. Stop
988        // it and confirm it is gone BEFORE returning: the caller's lock is held
989        // until then, so a retry cannot start a second install on top of it.
990        let stopped = if run.timed_out {
991            let reaped = self.reap_cli_install(container_name).await;
992            let finished = self.wait_exec_finished(&run.exec_id, std::time::Duration::from_secs(30)).await;
993            Some(reaped && finished)
994        } else {
995            None
996        };
997        let detail = install_failure_detail(run.exit, run.timed_out, stopped, &run.output);
998        tracing::warn!(container = container_name, command = %install.command, detail = %detail, "provider CLI install failed");
999        Err(fail(detail))
1000    }
1001
1002    async fn forget_cli_ready(&self, container_name: &str) {
1003        let prefix = format!("{container_name}\u{0}");
1004        self.inner.cli_ready.lock().await.retain(|k| !k.starts_with(&prefix));
1005    }
1006
1007    /// Best-effort interruption of the turn's process(es) inside a container.
1008    ///
1009    /// Docker/bollard has no "kill exec" API, so we `pkill` the matching process
1010    /// via a short detached exec. The persistent-container model runs one turn at
1011    /// a time (guarded by `run_lock`), so a single CLI process matches `pattern`
1012    /// (the command name, e.g. `claude`). `-f` matches the full command line
1013    /// because the CLI runs under `node`, whose process name isn't the CLI's.
1014    ///
1015    /// Requires `pkill` (procps) in the image. Fire-and-forget (detached); a
1016    /// non-match (`pkill` exit 1, e.g. the turn already exited) is not an error.
1017    pub async fn signal_exec_process(
1018        &self,
1019        container_name: &str,
1020        pattern: &str,
1021        force: bool,
1022    ) -> Result<(), ContainerError> {
1023        let signal = if force { "-KILL" } else { "-TERM" };
1024        let cmd: Vec<&str> = vec!["pkill", signal, "-f", pattern];
1025        let exec = self.inner.docker
1026            .create_exec(container_name, CreateExecOptions {
1027                cmd: Some(cmd),
1028                attach_stdout: Some(false),
1029                attach_stderr: Some(false),
1030                ..Default::default()
1031            })
1032            .await?;
1033        self.inner.docker
1034            .start_exec(&exec.id, Some(StartExecOptions { detach: true, ..Default::default() }))
1035            .await?;
1036        Ok(())
1037    }
1038
1039    /// Gracefully stop a container. Uses SIGTERM → SIGKILL after `timeout_secs`.
1040    pub async fn stop(&self, container_name: &str, timeout_secs: i64) -> Result<(), ContainerError> {
1041        // First, whatever the daemon answers: a key account's token never outlives the container it was made for.
1042        key_route::revoke_container_tokens(container_name);
1043        self.inner.docker
1044            .stop_container(container_name, Some(StopContainerOptions { t: timeout_secs }))
1045            .await?;
1046        tracing::info!(container = container_name, "stopped container");
1047        self.cleanup_dev_proxy_routes(container_name).await;
1048        Ok(())
1049    }
1050
1051    /// Remove a container (must be stopped first or use `force = true`).
1052    pub async fn remove(&self, container_name: &str, force: bool) -> Result<(), ContainerError> {
1053        use bollard::container::RemoveContainerOptions;
1054        key_route::revoke_container_tokens(container_name);
1055        // A login the container refreshed goes back to the Keychain while the container is still there to ask.
1056        self.write_back_login(container_name).await;
1057        self.inner.docker
1058            .remove_container(container_name, Some(RemoveContainerOptions {
1059                force,
1060                ..Default::default()
1061            }))
1062            .await?;
1063        tracing::info!(container = container_name, "removed container");
1064        self.drop_staged_login(container_name).await;
1065        self.forget_cli_ready(container_name).await;
1066        self.cleanup_dev_proxy_routes(container_name).await;
1067        Ok(())
1068    }
1069
1070    /// Clears this container's dev-proxy routes (see
1071    /// docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md) if a
1072    /// registry was ever wired in via `attach_dev_proxy_registry` — a
1073    /// no-op everywhere else (tests, non-agent Docker use). Never fails
1074    /// `stop`/`remove`: the container operation itself already succeeded
1075    /// by the time this runs, and a routing-table cleanup miss is
1076    /// recoverable (the entry just goes stale until re-registered) in a
1077    /// way an interrupted `stop`/`remove` wouldn't be.
1078    async fn cleanup_dev_proxy_routes(&self, container_name: &str) {
1079        if let Some(registry) = self.inner.dev_proxy.get() {
1080            registry.unregister_container(container_name).await;
1081        }
1082    }
1083
1084    // ---- private helpers ----
1085
1086    fn owned_mount_targets() -> [String; 7] {
1087        mounts::owned_mount_targets()
1088    }
1089
1090    /// The `(target -> source)` this module wants mounted for `spec`. A target
1091    /// absent from the map is one that must NOT be mounted.
1092    fn desired_owned_mounts(
1093        container_name: &str,
1094        spec: &ContainerMountSpec,
1095    ) -> HashMap<String, String> {
1096        let mut desired: HashMap<String, String> = agent_home_mounts(container_name, spec)
1097            .into_iter()
1098            .filter_map(|m| Some((m.target?, m.source?)))
1099            .collect();
1100        if let Some(dir) = spec.workspace_host_dir.as_deref().filter(|d| !d.is_empty()) {
1101            desired.insert(CONTAINER_WORKSPACE_DIR.to_string(), normalize_host_path(dir));
1102        }
1103        desired
1104    }
1105
1106    /// Single Docker inspect covering both drift checks below — mounts and
1107    /// extra_hosts previously each did their own `inspect_container` round
1108    /// trip, doubling the Docker-socket call on every `ensure_running` for
1109    /// the common case of an already-compliant container (reagent P2 on PR
1110    /// #3393). Returns a human-readable reason if either has drifted, or
1111    /// `None` if the container matches (or the inspect itself failed —
1112    /// fails safe, same as the two checks below always did: a spurious
1113    /// recreate kills a live agent and loses its container-local state,
1114    /// which is worse than one more restart on stale state we couldn't
1115    /// even confirm).
1116    async fn container_drift(&self, container_name: &str, image: &str, spec: &ContainerMountSpec) -> Option<&'static str> {
1117        let Ok(details) = self.inner.docker.inspect_container(container_name, None).await else {
1118            return None;
1119        };
1120        if image_tools::made_from_retired_image(&details, image) {
1121            return Some("made from the retired agent image");
1122        }
1123        if !Self::mounts_match(&details, container_name, spec) {
1124            return Some("mounts differ from the desired spec (credentials/workspace)");
1125        }
1126        if !Self::extra_hosts_match(&details) {
1127            return Some("extra_hosts missing host.docker.internal:host-gateway");
1128        }
1129        if !agent_caps::drops_net_raw(&details) {
1130            return Some("NET_RAW not dropped");
1131        }
1132        None
1133    }
1134
1135    /// Does the existing container already carry exactly the mounts `spec` asks
1136    /// for? Used to decide whether an agent that is already up has to be
1137    /// recreated to pick up (or lose) credentials and a workspace.
1138    ///
1139    /// Compares the owned set in BOTH directions — a mount that should now be
1140    /// ABSENT is drift too, not just a missing or changed one. That case is the
1141    /// security-relevant one (reagent P1 on PR #2933): unbinding an agent's
1142    /// account is a normal transition that never reaches
1143    /// `SpawnGateError::MissingCredentials` (that gate fires when credentials
1144    /// are expected and missing, not when an agent legitimately has none). A
1145    /// presence-only check would leave the old account's `.credentials.json`
1146    /// bind-mounted and WRITABLE in the running container forever, so every
1147    /// later turn would keep authenticating — and refreshing tokens — as the
1148    /// account the operator just unbound.
1149    ///
1150    /// Only this module's own targets are considered; the caller's extra
1151    /// `container_volumes` are ignored, so a user adding an unrelated mount is
1152    /// never a reason to destroy and rebuild their container underneath them.
1153    ///
1154    /// Fails SAFE: missing mount data on the passed-in inspect result returns
1155    /// `true` ("matches"), leaving the container alone — the inspect-error case
1156    /// itself is now handled once, by `container_drift`'s caller.
1157    fn mounts_match(details: &ContainerInspectResponse, container_name: &str, spec: &ContainerMountSpec) -> bool {
1158        let Some(actual) = details.mounts.as_ref() else {
1159            return true;
1160        };
1161
1162        let source_at = |target: &str| -> Option<String> {
1163            actual
1164                .iter()
1165                .find(|m| m.destination.as_deref() == Some(target))
1166                .and_then(|m| m.name.clone().or_else(|| m.source.clone()))
1167                .map(|s| fold_mount_source(&s))
1168        };
1169
1170        let desired = Self::desired_owned_mounts(container_name, spec);
1171        Self::owned_mount_targets().iter().filter(|t| mounts::is_checked(spec, t)).all(|target| {
1172            let want = desired.get(target).map(|s| fold_mount_source(s));
1173            source_at(target) == want
1174        })
1175    }
1176
1177    /// Whether an existing container's `HostConfig.extra_hosts` already has
1178    /// the `host.docker.internal:host-gateway` entry `create_and_start` sets
1179    /// (reagent P1, PR #3393). Docker cannot add an extra_hosts entry to an
1180    /// already-existing container — only `container_drift`'s recreate path
1181    /// (via `ensure_running_locked`) can actually fix a container that
1182    /// predates this.
1183    fn extra_hosts_match(details: &ContainerInspectResponse) -> bool {
1184        let Some(extra_hosts) = details.host_config.as_ref().and_then(|hc| hc.extra_hosts.as_ref()) else {
1185            return false;
1186        };
1187        extra_hosts
1188            .iter()
1189            .any(|h| h == "host.docker.internal:host-gateway")
1190    }
1191
1192    /// Running Docker Compose containers whose project directory is `dir` or
1193    /// inside it (Compose's `com.docker.compose.project.working_dir` label):
1194    /// the ones an agent working there may have started. Names only.
1195    pub async fn running_compose_containers_under(&self, dir: &std::path::Path) -> Result<Vec<String>, ContainerError> {
1196        const WORKING_DIR: &str = "com.docker.compose.project.working_dir";
1197        let mut filters = HashMap::new();
1198        filters.insert("label", vec![WORKING_DIR]);
1199        filters.insert("status", vec!["running"]);
1200        let list = self.inner.docker
1201            .list_containers(Some(ListContainersOptions { all: false, filters, ..Default::default() }))
1202            .await?;
1203        Ok(list
1204            .into_iter()
1205            .filter(|c| {
1206                c.labels
1207                    .as_ref()
1208                    .and_then(|l| l.get(WORKING_DIR))
1209                    .is_some_and(|wd| std::path::Path::new(wd).starts_with(dir))
1210            })
1211            .filter_map(|c| c.names.and_then(|n| n.first().map(|n| n.trim_start_matches('/').to_string())))
1212            .collect())
1213    }
1214
1215    /// Returns the container status string ("running", "exited", …) or `None` if not found.
1216    async fn find_container(&self, name: &str) -> Result<Option<String>, ContainerError> {
1217        let mut filters = HashMap::new();
1218        filters.insert("name", vec![name]);
1219        let list = self.inner.docker
1220            .list_containers(Some(ListContainersOptions {
1221                all: true,
1222                filters,
1223                ..Default::default()
1224            }))
1225            .await?;
1226
1227        // `name` filter is a prefix match — verify exact name.
1228        let canonical = format!("/{name}");
1229        for c in &list {
1230            if let Some(names) = &c.names {
1231                if names.iter().any(|n| n == &canonical) {
1232                    return Ok(c.state.clone());
1233                }
1234            }
1235        }
1236        Ok(None)
1237    }
1238
1239    /// Whether the daemon already has `image`.
1240    pub async fn has_image_locally(&self, image: &str) -> bool {
1241        self.inner.docker.inspect_image(image).await.is_ok()
1242    }
1243
1244    async fn create_and_start(
1245        &self,
1246        container_name: &str,
1247        image: &str,
1248        volumes: &[String],
1249        env_vars: &[(String, String)],
1250        spec: &ContainerMountSpec,
1251    ) -> Result<(), ContainerError> {
1252        // A container name can be reused: `ensure_running` detects an
1253        // externally removed container and recreates it under the same name.
1254        // The replacement may exec as a DIFFERENT user -- a changed custom
1255        // image, or the same mutable tag repulled -- and a stale cached
1256        // identity would then chown every prompt file to the wrong uid, making
1257        // it unreadable (mode 0600) for the life of the process (codex P2,
1258        // PR #2883). The cache is keyed by name, so evict here, at the one
1259        // place a name starts pointing at a new container.
1260        self.inner.exec_identities.lock().await.remove(container_name);
1261        self.forget_cli_ready(container_name).await;
1262
1263        let env: Vec<String> = env_vars.iter()
1264            .map(|(k, v)| format!("{k}={v}"))
1265            .collect();
1266        let hostname = host_name_for_new_container();
1267
1268        let mounts: Vec<Mount> = volumes.iter().filter_map(|spec| {
1269            let (source, target, read_only) = parse_volume_spec(spec)?;
1270            if target.is_empty() {
1271                tracing::warn!(spec = %spec, "ignoring malformed volume spec (expected source:target)");
1272                return None;
1273            }
1274            let mount_type = if source.starts_with('/') || source.starts_with('~')
1275                || (source.len() >= 2 && source.as_bytes()[1] == b':')
1276            {
1277                MountTypeEnum::BIND
1278            } else {
1279                MountTypeEnum::VOLUME
1280            };
1281            Some(Mount {
1282                target: Some(target.to_string()),
1283                source: Some(source.to_string()),
1284                typ: Some(mount_type),
1285                read_only: Some(read_only),
1286                ..Default::default()
1287            })
1288        }).collect();
1289
1290        let mut all_mounts = agent_home_mounts(container_name, spec);
1291        if let Some(workspace) = spec.workspace_host_dir.as_deref().filter(|d| !d.is_empty()) {
1292            all_mounts.push(Mount {
1293                target: Some(CONTAINER_WORKSPACE_DIR.to_string()),
1294                source: Some(normalize_host_path(workspace)),
1295                typ: Some(MountTypeEnum::BIND),
1296                read_only: Some(false),
1297                ..Default::default()
1298            });
1299        }
1300        all_mounts.push(cli_dir_mount(container_name));
1301        all_mounts.extend(mounts);
1302        all_mounts.extend(self.cache_mounts_for_new(container_name, image, &all_mounts).await);
1303
1304        let wanted_limits = self.wanted_limits_for_new(image, spec.limits).await;
1305        let mut config: Config<String> = Config {
1306            image: Some(image.to_string()),
1307            hostname,
1308            env: if env.is_empty() { None } else { Some(env) },
1309            // Keep container alive between turns — idle PID 1 (`sleep infinity`
1310            // via tini) stays running until `docker stop`. Agent turns run via
1311            // `docker exec`, not as the PID-1 process.
1312            tty: Some(false),
1313            open_stdin: Some(true),
1314            labels: status_source::agent_labels(container_name),
1315            host_config: Some(agent_caps::agent_host_config(all_mounts)),
1316            ..Default::default()
1317        };
1318        wanted_limits.apply_to(config.host_config.get_or_insert_with(Default::default));
1319
1320        let container = self.inner.docker
1321            .create_container(
1322                Some(CreateContainerOptions {
1323                    name: container_name,
1324                    platform: None,
1325                }),
1326                config,
1327            )
1328            .await?;
1329
1330        let id = container.id;
1331        if id.is_empty() {
1332            return Err(ContainerError::NoId { name: container_name.to_string() });
1333        }
1334
1335        self.inner.docker
1336            .start_container(&id, None::<StartContainerOptions<String>>)
1337            .await?;
1338
1339        Ok(())
1340    }
1341
1342    /// Creates the shared [`AGENTMUX_DOCKER_NETWORK`] if it does not exist; whether it exists now.
1343    pub(super) async fn ensure_network_exists(&self) -> bool {
1344        use bollard::network::CreateNetworkOptions;
1345
1346        let create_opts = CreateNetworkOptions {
1347            name: AGENTMUX_DOCKER_NETWORK,
1348            driver: "bridge",
1349            ..Default::default()
1350        };
1351        if let Err(e) = self.inner.docker.create_network(create_opts).await {
1352            let already_exists = matches!(
1353                &e,
1354                bollard::errors::Error::DockerResponseServerError { message, .. }
1355                    if message.to_lowercase().contains("already exists")
1356            );
1357            if !already_exists {
1358                tracing::warn!(
1359                    network = AGENTMUX_DOCKER_NETWORK,
1360                    error = %e,
1361                    "dev-proxy: failed to create shared Docker network — dev-server routing unavailable this run"
1362                );
1363                return false;
1364            }
1365        }
1366        true
1367    }
1368
1369    /// Best-effort: create the shared [`AGENTMUX_DOCKER_NETWORK`] (if it
1370    /// doesn't already exist) and attach `container_name` to it, additive
1371    /// to whatever `network_mode`/`extra_hosts` `create_and_start` already
1372    /// set up (container→host reachability via `host.docker.internal`,
1373    /// entirely unaffected). Never fails `ensure_running` — this is purely
1374    /// in service of dev-proxy routing
1375    /// (docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md §3.1), not
1376    /// required for a container agent's core turn-execution path. Called
1377    /// on every `ensure_running`, not just at creation, so an
1378    /// already-running container from before this feature shipped is
1379    /// picked up too, and so a network deleted out-of-band (`docker
1380    /// network rm`) is recreated automatically.
1381    async fn ensure_agent_network(&self, container_name: &str) {
1382        use bollard::models::EndpointSettings;
1383        use bollard::network::ConnectNetworkOptions;
1384
1385        if !self.ensure_network_exists().await {
1386            return;
1387        }
1388        let connect_opts = ConnectNetworkOptions {
1389            container: container_name,
1390            endpoint_config: EndpointSettings {
1391                aliases: Some(vec![container_name.to_string()]),
1392                ..Default::default()
1393            },
1394        };
1395        if let Err(e) = self.inner.docker.connect_network(AGENTMUX_DOCKER_NETWORK, connect_opts).await {
1396            let already_attached = matches!(
1397                &e,
1398                bollard::errors::Error::DockerResponseServerError { message, .. }
1399                    if message.to_lowercase().contains("already exists")
1400            );
1401            if !already_attached {
1402                tracing::warn!(
1403                    container = container_name,
1404                    network = AGENTMUX_DOCKER_NETWORK,
1405                    error = %e,
1406                    "dev-proxy: failed to attach container to shared Docker network"
1407                );
1408            }
1409        }
1410        crate::backend::container::listener::ensure_bound(&self.inner.docker).await;
1411    }
1412}
1413
1414pub use crate::backend::container::runtime::ContainerRuntimeHandle;
1415
1416/// What a collected exec produced.
1417struct ExecOutcome {
1418    exec_id: String,
1419    exit: Option<i64>,
1420    output: String,
1421    timed_out: bool,
1422}
1423
1424/// Whether `provision_cli` found the CLI in place or had to install it.
1425#[derive(Debug, Clone, Copy, PartialEq)]
1426pub enum CliProvision {
1427    Present,
1428    Installed { seconds: f64 },
1429}
1430
1431/// The per-agent volume the provider CLI is installed into.
1432fn cli_dir_mount(container_name: &str) -> Mount {
1433    Mount {
1434        target: Some(CONTAINER_CLI_DIR.to_string()),
1435        source: Some(format!("agentmux-cli-{container_name}")),
1436        typ: Some(MountTypeEnum::VOLUME),
1437        read_only: Some(false),
1438        ..Default::default()
1439    }
1440}
1441
1442/// Derive the stable container name for an agent from its slug.
1443/// Format: `agentmux-<slug>`. Deterministic so restarts reuse the same container.
1444pub fn container_name_for_slug(slug: &str) -> String {
1445    format!("agentmux-{slug}")
1446}
1447
1448/// The container a container agent's pane (its block `meta`: `agentMode` = `container`) runs in, named
1449/// from its `agentId` as the launch path names it. `None` for any other pane.
1450pub fn container_of_meta(meta: &crate::backend::obj::MetaMapType) -> Option<String> {
1451    use crate::backend::obj::meta_get_string;
1452    if !crate::backend::runtime_adapter::RuntimeKind::of_block_meta(meta).is_container() {
1453        return None;
1454    }
1455    let agent_id = meta_get_string(meta, "agentId", "");
1456    (!agent_id.is_empty()).then(|| container_name_for_slug(&agent_id))
1457}
1458
1459/// Parse a Docker volume spec into `(source, target, read_only)`.
1460///
1461/// Format: `source:target` or `source:target:options`.
1462///
1463/// Handles Windows drive-letter bind paths (e.g. `C:\Users\me\repo:/workspace:ro`)
1464/// by treating the drive-letter colon (`X:`) as part of the source path, not as
1465/// the source/target separator. A plain `splitn(3, ':')` would split `C:\path`
1466/// into `C` and `\path`, losing the drive letter.
1467///
1468/// Returns `None` for malformed specs (no target separator found).
1469fn parse_volume_spec(spec: &str) -> Option<(&str, &str, bool)> {
1470    let bytes = spec.as_bytes();
1471
1472    // Detect Windows drive-letter prefix: single ASCII letter followed by ':\'  or ':/'
1473    let (source, rest) = if bytes.len() >= 3
1474        && bytes[0].is_ascii_alphabetic()
1475        && bytes[1] == b':'
1476        && (bytes[2] == b'\\' || bytes[2] == b'/')
1477    {
1478        // Windows path: skip the drive colon and split on the next ':'.
1479        let tail = &spec[2..]; // starts at '\' or '/'
1480        let pos = tail.find(':')?;
1481        (&spec[..2 + pos], &tail[pos + 1..])
1482    } else {
1483        let pos = spec.find(':')?;
1484        (&spec[..pos], &spec[pos + 1..])
1485    };
1486
1487    // Split target from optional options.
1488    let (target, options) = if let Some(pos) = rest.find(':') {
1489        (&rest[..pos], &rest[pos + 1..])
1490    } else {
1491        (rest, "")
1492    };
1493
1494    Some((source, target, options.contains("ro")))
1495}
1496
1497#[cfg(test)]
1498mod tests;