Skip to main content

agentmux_srv/server/app_api/agent_spawn/
container.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where a new agent runs: the `runtime`, `container_image`, `memory_mb` and `cpus` of `Agents spawn` (a worker) and
5//! `Agents create` (a named agent from a template).
6//!
7//! Without them a worker runs as its leader does (`copy_definition` keeps the type and the image), and a created agent
8//! as its template says. With them, the new agent can run in a container when its caller runs on the host. The
9//! protections are the ones the rest of the container API has: a container caller starts only container agents
10//! (a container is not a way to a host process) and does not set limits (it asks a host agent, as for its own), and
11//! a container is refused when Docker is not there, with the reason.
12
13use agentmux_common::api_types::ContainerAsk;
14
15use super::*;
16
17/// Where the new agent runs.
18#[derive(Debug, Clone, Default, PartialEq, Eq)]
19pub(crate) enum Placement {
20    /// Nothing was asked: what its source (the leader or the template) gives.
21    #[default]
22    AsSource,
23    /// On the host.
24    Native,
25    Container(ContainerPlan),
26}
27
28/// A container agent as asked for: the image, and the limits to store (`None`: leave them automatic).
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub(crate) struct ContainerPlan {
31    pub image: String,
32    pub memory_mb: Option<String>,
33    pub cpus: Option<String>,
34}
35
36impl Placement {
37    /// How the new agent is described to the user in the approval prompt; empty for `AsSource`.
38    pub(crate) fn describe(&self) -> String {
39        match self {
40            Placement::AsSource => String::new(),
41            Placement::Native => " on this computer".to_string(),
42            Placement::Container(c) => {
43                let mut s = format!(" in a container ({})", c.image);
44                if let Some(m) = &c.memory_mb {
45                    s.push_str(&format!(", memory {}", if m == "0" { "unlimited".to_string() } else if m.is_empty() { "auto".to_string() } else { format!("{m} MB") }));
46                }
47                if let Some(c) = &c.cpus {
48                    s.push_str(&format!(", CPUs {}", if c == "0" { "unlimited".to_string() } else if c.is_empty() { "auto".to_string() } else { c.clone() }));
49                }
50                s
51            }
52        }
53    }
54}
55
56/// Check what `ask` wants, without making anything. `caller_in_container`: the asking agent runs in a container.
57/// `source_in_container` and `source_image`: how the source (the leader, or the template) runs, which `runtime` and
58/// `container_image` default to. `docker`: whether a container can be made here, or why not.
59pub(crate) fn decide(
60    ask: &ContainerAsk,
61    caller_in_container: bool,
62    source_in_container: bool,
63    source_image: &str,
64    docker: Result<(), String>,
65) -> Result<Placement, SpawnError> {
66    use crate::backend::container::limits::normalize;
67    // A container caller making an agent from a host template gets no say: a host agent is a way out of the container.
68    if ask.is_empty() && !(caller_in_container && !source_in_container) {
69        return Ok(Placement::AsSource);
70    }
71    let runtime = match ask.runtime.as_deref().map(str::trim).filter(|r| !r.is_empty()) {
72        None => None,
73        Some("native" | "host") => Some(false),
74        Some("container") => Some(true),
75        Some(other) => {
76            return Err(refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: runtime {other:?}: use native or container")));
77        }
78    };
79    let wants_limits = ask.memory_mb.is_some() || ask.cpus.is_some();
80    let in_container = runtime.unwrap_or(source_in_container);
81    if !in_container {
82        if ask.container_image.is_some() || wants_limits {
83            return Err(refuse(
84                StatusCode::BAD_REQUEST,
85                "INVALID_ARG: container_image, memory_mb and cpus are for a container agent: add runtime: container",
86            ));
87        }
88        if caller_in_container {
89            return Err(refuse(
90                StatusCode::FORBIDDEN,
91                "CONTAINER_AGENT: a container agent starts only container agents, never one on the host. Ask a host agent, \
92                 your steward or the operator",
93            ));
94        }
95        return Ok(Placement::Native);
96    }
97    if caller_in_container && wants_limits {
98        return Err(refuse(
99            StatusCode::FORBIDDEN,
100            "CONTAINER_AGENT: a container agent cannot set a container's limits. Leave memory_mb and cpus out, or ask a host \
101             agent, your steward or the operator, saying how much the work needs and why",
102        ));
103    }
104    let image = crate::server::agent_handlers::chosen_container_image(ask.container_image.as_deref(), "container", source_image)
105        .map_err(|e| refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: {e}")))?;
106    let image = if image.trim().is_empty() { crate::backend::container::image::DEFAULT_AGENT_IMAGE.to_string() } else { image };
107    let memory_mb = ask.memory_mb.as_ref().map(|v| normalize(v, "memory_mb")).transpose().map_err(|e| refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: {e}")))?;
108    let cpus = ask.cpus.as_ref().map(|v| normalize(v, "cpus")).transpose().map_err(|e| refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: {e}")))?;
109    docker.map_err(|why| refuse(StatusCode::SERVICE_UNAVAILABLE, format!("DOCKER_UNAVAILABLE: a container agent needs Docker, and {why}. Use runtime: native, or ask the user to start Docker")))?;
110    Ok(Placement::Container(ContainerPlan { image, memory_mb, cpus }))
111}
112
113/// The per-user setting for where a new agent runs when the call does not say: `container` (the default) or
114/// `native`. Spec: docs/specs/SPEC_AGENT_MODEL_ROUTES_ANY_MODEL_SPAWN_AND_SWITCH_2026_11_06.md section 10.
115pub const SETTING_DEFAULT_RUNTIME: &str = "agents:defaultruntime";
116
117/// Whether the setting leaves a new agent in a container: everything but `native` (or `host`) does.
118pub(crate) fn default_is_container(extra: &std::collections::HashMap<String, serde_json::Value>) -> bool {
119    match extra.get(SETTING_DEFAULT_RUNTIME).and_then(serde_json::Value::as_str).map(|s| s.trim().to_ascii_lowercase()) {
120        Some(s) => !matches!(s.as_str(), "native" | "host"),
121        None => true,
122    }
123}
124
125/// Whether the harness has a container image. The same list as `containerSupported` in the frontend's
126/// `defaults/cli-catalog.ts`: only Claude Code has an image built, so every other harness stays native.
127pub(crate) fn has_container_image(provider: &str) -> bool {
128    provider == "claude"
129}
130
131/// [`decide`] for a caller `caller` and a source defined by `source`, asking this machine whether Docker is there.
132/// `provider` is the harness the new agent runs. A call that says nothing about where gets the setting's default:
133/// a container, when the harness has an image and Docker answers, and otherwise as its source runs (never refused,
134/// since nobody asked for a container). A caller or a source that already runs in a container keeps what it did.
135pub(crate) async fn decide_here(
136    state: &AppState,
137    ask: &ContainerAsk,
138    caller: &AgentDefinition,
139    source: &AgentDefinition,
140    provider: &str,
141) -> Result<Placement, SpawnError> {
142    if ask.is_empty()
143        && !caller.runtime().is_container()
144        && !source.runtime().is_container()
145        && has_container_image(provider)
146        && default_is_container(&state.config_watcher.get_full_config().settings.extra)
147        // A live ping, not the cached connection: Docker that stopped since it was first reached is not there.
148        && state.container_manager.is_available().await
149    {
150        let by_default = ContainerAsk { runtime: Some("container".to_string()), ..ContainerAsk::default() };
151        return decide(&by_default, false, false, &source.container_image, Ok(()));
152    }
153    // Only a request for a container needs the answer; a plain one never starts a Docker lookup.
154    let wants_container = ask.runtime.as_deref().map(str::trim) == Some("container") || (ask.runtime.is_none() && source.runtime().is_container());
155    let docker = if wants_container && !ask.is_empty() {
156        state.container_manager.get_or_explain().await.map(|_| ())
157    } else {
158        Ok(())
159    };
160    decide(ask, caller.runtime().is_container(), source.runtime().is_container(), &source.container_image, docker)
161}
162
163/// Make `def` (just inserted) a container agent as `plan` says, and store its limits. A native placement on a
164/// definition that was a container one (a template's) is `agent_type` and `environment` back to the host's.
165pub(crate) fn apply(state: &AppState, def: &mut AgentDefinition, placement: &Placement) -> Result<(), String> {
166    match placement {
167        Placement::AsSource => return Ok(()),
168        Placement::Native => {
169            def.agent_type = "host".to_string();
170            def.environment = "local".to_string();
171            def.container_image = String::new();
172        }
173        Placement::Container(plan) => {
174            def.agent_type = "container".to_string();
175            def.environment = "docker".to_string();
176            def.container_image = plan.image.clone();
177            if plan.memory_mb.is_some() || plan.cpus.is_some() {
178                let (old_memory, old_cpus) = state.mstore.container_limits_get(&def.id).ok().flatten().unwrap_or_default();
179                state
180                    .mstore
181                    .container_limits_set(
182                        &def.id,
183                        plan.memory_mb.as_deref().unwrap_or(&old_memory),
184                        plan.cpus.as_deref().unwrap_or(&old_cpus),
185                    )
186                    .map_err(|e| format!("store its container limits: {e}"))?;
187            }
188        }
189    }
190    state.mstore.agent_def_update(def).map_err(|e| format!("set where it runs: {e}"))?;
191    Ok(())
192}
193
194#[cfg(test)]
195#[path = "../tests/agent_spawn_container_tests.rs"]
196mod tests;