agentmux_srv/server/app_api/agent_spawn/
container.rs1use agentmux_common::api_types::ContainerAsk;
14
15use super::*;
16
17#[derive(Debug, Clone, Default, PartialEq, Eq)]
19pub(crate) enum Placement {
20 #[default]
22 AsSource,
23 Native,
25 Container(ContainerPlan),
26}
27
28#[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 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
56pub(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 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
113pub const SETTING_DEFAULT_RUNTIME: &str = "agents:defaultruntime";
116
117pub(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
125pub(crate) fn has_container_image(provider: &str) -> bool {
128 provider == "claude"
129}
130
131pub(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 && 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 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
163pub(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;