Skip to main content

ContainerManager

Struct ContainerManager 

Source
pub struct ContainerManager { /* private fields */ }
Expand description

Shared container manager. Clone-on-Arc; cheap to pass around.

Implementations§

Source§

impl ContainerManager

Source

pub async fn base_image_version(&self, container_name: &str) -> Option<String>

The AgentMux version of the base image container_name was created from, or None when it isn’t the base image (a custom image is the user’s), or can’t be read.

Source

pub async fn update_container( &self, container_name: &str, ) -> Result<(), ContainerError>

Removes the container so the next turn creates it again from the current image. The per-agent volumes (CLI, Claude home) and the bind-mounted workspace and memory stay; whatever else was installed inside the container is gone.

Source§

impl ContainerManager

Source

pub async fn daemon_capacity(&self) -> Option<DaemonCapacity>

What the daemon has, from docker info; kept for a few minutes. None when it can’t be read (logged).

Source

pub async fn wanted_limits( &self, agent: ContainerLimits, recommended_min_mb: Option<u64>, ) -> Wanted

The limits agent should carry on this daemon, under the app-wide settings.

Source

pub async fn wanted_limits_for_container( &self, container_name: &str, agent: ContainerLimits, ) -> Wanted

The limits container_name has or would be given: as Self::limits_apply sets them, with its image’s recommended minimum. Without such a container, no label is known.

Source

pub async fn limits_apply( &self, container_name: &str, agent: ContainerLimits, ) -> Option<bool>

Puts the limits on an existing container (one made before they existed, or whose setting changed), without recreating it. A failure is logged and the container is left as it is. None: there is no such container (it takes the limits when it is made); Some(true): it has them now; Some(false): Docker refused the update.

Source§

impl ContainerManager

Source

pub async fn oom_kill_count(&self, container_name: &str) -> Option<u64>

How many processes the kernel has killed in this container for memory since it started; None when it can’t be read. Bounded: a turn waits on it before it starts, where a stop can’t reach it.

Source

pub async fn oom_since( &self, container_name: &str, before: Option<u64>, ) -> Option<OomEvent>

Whether a process was killed for memory since the count was before.

Source§

impl ContainerManager

Source

pub async fn stage_login( &self, container_name: &str, config_dir: &str, spec: &ContainerMountSpec, ) -> Result<String, String>

Stages the login of the account whose config dir is config_dir for the container about to be created, and returns the folder to mount as the account’s credentials; Err with the reason in plain words when there is no login to give. The container never gets the account’s own file: it holds a copy of its own.

Source§

impl ContainerManager

Source

pub async fn cache_volumes( &self, container_name: &str, ) -> Result<Vec<ContainerCacheVolume>, String>

The cache volumes of container_name and what each holds, largest first (Docker’s own disk-usage report, which does not scan the volumes; a volume whose driver can’t say is counted as 0).

Source

pub async fn clear_caches( &self, container_name: &str, ) -> Result<Vec<ContainerCacheVolume>, String>

Removes the container and its cache volumes (the CLI and Claude home volumes stay): the next message starts a new container, which fills them again. Returns what was removed. The caller makes sure no turn is using the container.

Source

pub async fn remove_agent_storage(&self, container_name: &str)

Removes the container and every volume made for an agent, once the agent is deleted: its cache volumes (by label), and the CLI and Claude home volumes older versions made without one. Best effort: what is not there, or is still in use, is skipped and logged.

Source§

impl ContainerManager

Source

pub async fn run_oneshot( &self, spec: &OneShot, ) -> Result<OneShotOutcome, String>

Run spec once and give what it said. The container is removed whatever happens, including when this future is dropped. A command that exits non-zero is an outcome, not an error.

Source§

impl ContainerManager

Source

pub async fn session_files_stage_out( &self, container_name: &str, project: &str, sid: &str, dest: &Path, ) -> Result<(), String>

Copy one session’s files out of the container into dest (a project folder on the host): <sid>.jsonl and <sid>/, as they are. A path the container does not have is not copied; a session with neither leaves dest empty. Works on a stopped container.

Source

pub async fn session_files_remove( &self, container_name: &str, project: &str, sid: &str, ) -> Result<(), String>

Remove one session’s files from the container, by session id: through an exec when it runs, through a helper container on its volume when it does not. A session that is not there is removed.

Source§

impl ContainerManager

Source

pub async fn check_image_tools( &self, container_name: &str, image: &str, ) -> Result<(), ContainerError>

Whether the running container container_name, made from image, has what an AgentMux agent needs ([IMAGE_TOOLS]). An image that lacks them makes a container that starts and cannot talk (no tools, no startup memory, no messages), so this is asked before the agent’s first turn rather than answered by a run of failed hooks. A probe that can’t run says nothing about the image and lets the start go on. Checked once per container: a removed container forgets it (forget_cli_ready).

Source§

impl ContainerManager

Source

pub fn connect() -> Result<Self, ContainerError>

Connect to the local Docker daemon using environment/platform defaults.

Honors DOCKER_HOST env var (e.g. for rootless or remote daemons). On Windows connects via named pipe; on macOS/Linux via Unix socket.

Source

pub async fn connect_detected() -> Result<Self, ContainerError>

Connect to the runtime runtime finds: DOCKER_HOST, else the first socket of rootless Docker, Podman, Docker Desktop, Colima, OrbStack or the system that answers a ping. Err says where it looked and why each place failed.

Source

pub fn runtime_label(&self) -> Option<&str>

Which runtime this connection is to, e.g. Podman at unix:///run/user/1000/podman/podman.sock.

Source

pub fn attach_dev_proxy_registry(&self, registry: DevProxyRegistry)

Wires a dev-proxy routing table into this manager so stop/remove can clear an agent’s registrations when its container goes away. Set once per ContainerManager instance (a second call is a harmless no-op — OnceLock::set fails silently, which is fine here: the registry itself doesn’t change after boot). See docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md.

Source

pub async fn agent_network_ip(&self, container_name: &str) -> Option<String>

This container’s IP address on AGENTMUX_DOCKER_NETWORK — what the dev-proxy registry stores as the routable backend address. None if the container isn’t running, isn’t on the network yet, or Docker is unreachable. Always a fresh inspect_container, never cached — the caller (app_api::dev_server::handle_register_dev_server) needs the CURRENT address, not one from whenever the container was first created.

Source

pub async fn check_available(&self) -> Result<(), ContainerError>

Ping the Docker daemon. Returns Ok(()) if available.

Source

pub async fn ensure_running_observed( &self, container_name: &str, image: &str, volumes: &[String], env_vars: &[(String, String)], spec: &ContainerMountSpec, observe: StartObserver<'_>, ) -> Result<bool, ContainerError>

Ensure the container for this agent is created and running.

  • If it exists and is running: no-op.
  • If it exists but stopped: starts it.
  • If it doesn’t exist: creates and starts it.

Always queries Docker (no in-memory cache) so externally killed containers are detected. Concurrent calls for the same container_name are serialized via a per-container mutex. Concurrent calls for different containers proceed in parallel.

observe is told about the steps that take long enough for a person to wonder: downloading the image (with how far it has got) and creating the container. Nothing is reported when it is already up. true: this call started it, so what ran in it is gone.

Source

pub async fn exec( &self, container_name: &str, cmd: &[String], working_dir: Option<&str>, env_vars: &[(String, String)], attach_stdin: bool, ) -> Result<ExecSession, ContainerError>

Launch an exec session inside a running container.

Uses -i (not -t) to avoid tty CR/LF corruption of NDJSON output. The caller receives ExecSession whose output stream carries multiplexed stdout/stderr for piping into the block.

attach_stdin MUST be false unless the in-container process is a reader that completes on a newline rather than on EOF. Attaching stdin is a one-way door: bollard’s hijacked exec stream cannot half-close the write side (see the exec (io) integration test below), and on Windows the Docker transport is a named pipe, which has no half-close at all — so the process’s stdin NEVER reaches EOF. Neither drop(input) nor an explicit input.shutdown().await changes that; both were tried against a live container on 2026-09-01 and the process hung indefinitely.

Any command that reads stdin to EOF (cat, or claude -p taking its prompt on stdin) will therefore hang forever, producing no output and no exit. Give it a file to read instead — see ContainerManager::upload_turn_prompt, which also covers why argv and env are both the wrong place for that input.

Source

pub async fn remove_turn_prompt(&self, container_name: &str, prompt_path: &str)

Remove a prompt file uploaded by [upload_turn_prompt].

The turn’s own wrapper script removes the file after the CLI exits, so this is only for the path where the wrapper never runs at all — the upload succeeded but starting the exec failed, which would otherwise orphan the file (reagent P2, PR #2883).

Best-effort by design: it runs as the same user that owns the file, and a failure here is not worth failing an already-failing turn over.

Source

pub async fn upload_turn_prompt( &self, container_name: &str, turn_id: &str, message: &str, ) -> Result<String, ContainerError>

Write a turn’s prompt into the container as a file, returning its absolute in-container path.

This exists because a container turn has no other way to hand the CLI its prompt:

  • exec stdin can never reach EOF — bollard can’t half-close the hijacked stream’s write side, and on Windows the Docker transport is a named pipe, which has no half-close at all. A CLI that reads to EOF (claude -p) hangs forever with no output and no exit.
  • argv would expose any secret pasted into a chat message via docker top / host ps / /proc/<pid>/cmdline, breaking this module’s own no-secrets-in-argv invariant (reagent P1, PR #2883).
  • an env var keeps it off those host surfaces, but shares argv’s per-string MAX_ARG_STRLEN ceiling — measured in this very image at ~128 KiB (130,000 B passes, 200,000 B fails with “Argument list too long”). A long paste or a large # Session Context would break the turn (codex P2, PR #2883).

A file has none of those limits: unbounded size, invisible to every host-side process listing, and redirecting from it gives the CLI a real stdin that reaches a real EOF.

Ownership is the exec user’s (see [exec_identity]) so the turn can delete the file afterwards. Mode is 0600: only that user ever needs it, and it is the same user the CLI already runs as.

Source

pub async fn inspect_exec( &self, exec_id: &str, ) -> Result<Option<i64>, ContainerError>

Retrieve the exit code of a finished exec via the Docker socket.

Returns Ok(Some(code)) once the exec has exited, Ok(None) while it is still running (no code yet) or if Docker did not report one. Call this after the exec’s output stream has ended — unlike a child process’s wait(), the attached output stream closing does not carry the exit status, so the turn’s success/failure can only be known by inspecting.

Source

pub async fn provision_cli( &self, container_name: &str, install: &CliInstall, on_install_start: impl FnOnce(), ) -> Result<CliProvision, ContainerError>

Make sure the provider CLI is usable in this container, installing it on first use. on_install_start runs just before an install begins (the caller shows “Installing …” then), never when nothing needs installing.

Source

pub async fn signal_exec_process( &self, container_name: &str, pattern: &str, force: bool, ) -> Result<(), ContainerError>

Best-effort interruption of the turn’s process(es) inside a container.

Docker/bollard has no “kill exec” API, so we pkill the matching process via a short detached exec. The persistent-container model runs one turn at a time (guarded by run_lock), so a single CLI process matches pattern (the command name, e.g. claude). -f matches the full command line because the CLI runs under node, whose process name isn’t the CLI’s.

Requires pkill (procps) in the image. Fire-and-forget (detached); a non-match (pkill exit 1, e.g. the turn already exited) is not an error.

Source

pub async fn stop( &self, container_name: &str, timeout_secs: i64, ) -> Result<(), ContainerError>

Gracefully stop a container. Uses SIGTERM → SIGKILL after timeout_secs.

Source

pub async fn remove( &self, container_name: &str, force: bool, ) -> Result<(), ContainerError>

Remove a container (must be stopped first or use force = true).

Source

pub async fn running_compose_containers_under( &self, dir: &Path, ) -> Result<Vec<String>, ContainerError>

Running Docker Compose containers whose project directory is dir or inside it (Compose’s com.docker.compose.project.working_dir label): the ones an agent working there may have started. Names only.

Source

pub async fn has_image_locally(&self, image: &str) -> bool

Whether the daemon already has image.

Trait Implementations§

Source§

impl Clone for ContainerManager

Source§

fn clone(&self) -> ContainerManager

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync> ⓘ

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FromRef<T> for T
where T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more