Skip to main content

agentmux_srv/server/app_api/
container_limits.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A container agent's CPU and memory limits: `Agents set_container_limits` (`POST /api/v1/agent/container/limits`),
5//! and the window's `agent.getContainerLimits` / `agent.setContainerLimits`, which share [`view`] and [`set`].
6//! `docs/specs/SPEC_CONTAINER_AGENT_RESOURCE_LIMITS_2026_10_29.md` §3, §4.
7//!
8//! A change is stored (`db_agent_container_limits`), put on the running container with `docker update` at once, and
9//! shown in the agent's pane with who made it. A container agent can read limits but not change them, its own
10//! included (the operator's decision of 2026-10-29): it asks a host agent or the operator.
11
12use axum::extract::State;
13use axum::http::StatusCode;
14use axum::response::{IntoResponse, Response};
15use axum::{Extension, Json};
16use serde::Deserialize;
17use serde_json::{json, Value};
18
19use crate::backend::container::limits::{normalize, ContainerLimits, Target};
20use crate::backend::rpc_types::AgentContainerLimitsResult;
21use crate::server::caller::Caller;
22use crate::server::state::AppState;
23
24/// A refusal: the status it travels with, and what to tell the caller.
25pub(crate) type Refusal = (StatusCode, String);
26
27fn refuse(status: StatusCode, message: impl Into<String>) -> Refusal {
28    (status, message.into())
29}
30
31/// The container agent `named` (an id or slug): its uid and definition.
32pub(crate) fn container_agent(state: &AppState, named: &str) -> Result<(String, crate::backend::storage::AgentDefinition), Refusal> {
33    let named = named.trim();
34    let uid = crate::backend::agent_resolve::resolve_agent_id(&state.mstore, named)
35        .map_err(|_| refuse(StatusCode::NOT_FOUND, format!("no agent '{named}' on this machine")))?;
36    let def = state
37        .mstore
38        .agent_def_get(&uid)
39        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("container limits: {e}")))?
40        .ok_or_else(|| refuse(StatusCode::NOT_FOUND, format!("no agent '{named}' on this machine")))?;
41    if !def.runtime().is_container() {
42        return Err(refuse(StatusCode::CONFLICT, format!("{} does not run in a container, so it has no container limits", def.name)));
43    }
44    Ok((uid, def))
45}
46
47fn mb_of(bytes: i64) -> u64 {
48    bytes as u64 / (1024 * 1024)
49}
50
51/// The limits stored for `uid`, what is in force, and what the daemon has.
52pub(crate) async fn view(state: &AppState, uid: &str, applied: Option<bool>) -> Result<AgentContainerLimitsResult, Refusal> {
53    let (memory_mb, cpus) = state
54        .mstore
55        .container_limits_get(uid)
56        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("container limits: {e}")))?
57        .unwrap_or_default();
58    let mut out = AgentContainerLimitsResult {
59        memory_mb: memory_mb.clone(),
60        cpus: cpus.clone(),
61        effective_memory_mb: None,
62        effective_cpus: None,
63        daemon_memory_mb: None,
64        daemon_cpus: None,
65        applied,
66    };
67    if let Some(cm) = state.container_manager.get().await {
68        let name = crate::backend::container::container_name_for_slug(uid);
69        let wanted = cm.wanted_limits_for_container(&name, ContainerLimits::from_strings(&memory_mb, &cpus)).await;
70        if let Target::Set(bytes) = wanted.memory {
71            out.effective_memory_mb = Some(mb_of(bytes));
72        }
73        if let Target::Set(nano) = wanted.cpus {
74            out.effective_cpus = Some(nano as f64 / 1e9);
75        }
76        if let Some(capacity) = cm.daemon_capacity().await {
77            out.daemon_memory_mb = Some(capacity.mem_total / (1024 * 1024));
78            out.daemon_cpus = Some(capacity.ncpu);
79        }
80    }
81    Ok(out)
82}
83
84/// Stores the limits given (`None` leaves one as it is), puts them on the container now and says so in the pane.
85/// `by` is who is shown as having made the change.
86pub(crate) async fn set(
87    state: &AppState,
88    uid: &str,
89    def: &crate::backend::storage::AgentDefinition,
90    memory: Option<&Value>,
91    cpus: Option<&Value>,
92    by: &str,
93) -> Result<AgentContainerLimitsResult, Refusal> {
94    let memory = memory.map(|v| normalize(v, "memory_mb")).transpose().map_err(|m| refuse(StatusCode::BAD_REQUEST, m))?;
95    let cpus = cpus.map(|v| normalize(v, "cpus")).transpose().map_err(|m| refuse(StatusCode::BAD_REQUEST, m))?;
96    let (old_memory, old_cpus) = state.mstore.container_limits_get(uid).ok().flatten().unwrap_or_default();
97    let (memory, cpus) = (memory.unwrap_or(old_memory), cpus.unwrap_or(old_cpus));
98    state
99        .mstore
100        .container_limits_set(uid, &memory, &cpus)
101        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("container limits: {e}")))?;
102
103    // Put on the running container now. A container that is not there takes them when it is made.
104    let mut applied = None;
105    if let Some(cm) = state.container_manager.get().await {
106        let name = crate::backend::container::container_name_for_slug(uid);
107        applied = cm.limits_apply(&name, ContainerLimits::from_strings(&memory, &cpus)).await;
108    }
109    let result = view(state, uid, applied).await?;
110    tracing::info!(agent = %def.slug, %by, memory_mb = %memory, cpus = %cpus, ?applied, "container limits set");
111    note_in_pane(state, uid, def, &result, by);
112    Ok(result)
113}
114
115/// One pane row saying the limits changed, so a change is visible whoever makes it.
116fn note_in_pane(state: &AppState, uid: &str, def: &crate::backend::storage::AgentDefinition, result: &AgentContainerLimitsResult, by: &str) {
117    let Some(registration) = crate::backend::reactive::handler::get_global_handler().get_agent(&def.slug) else { return };
118    let block_id = registration.block_id;
119    let provider = match state.mstore.get::<crate::backend::obj::Block>(&block_id) {
120        Ok(Some(block)) => crate::backend::obj::meta_get_string(&block.meta, "agentProvider", "claude"),
121        _ => return,
122    };
123    let (state_name, error) = match result.applied {
124        Some(false) => ("failed", Some("Docker did not take the new limits; the container keeps the ones it has")),
125        _ => ("changed", None),
126    };
127    let frame = crate::backend::cli_notice::container_limit_frame(
128        &provider,
129        &block_id,
130        (uid, &def.name),
131        state_name,
132        result.effective_memory_mb,
133        result.effective_cpus,
134        Some(by),
135        error,
136    );
137    crate::backend::cli_notice::append_to_pane(&state.broker, &state.filestore, &state.mstore, &block_id, &frame);
138}
139
140/// `POST /api/v1/agent/container/limits`: `Agents set_container_limits`. With neither `memory_mb` nor `cpus` it only
141/// reads.
142#[derive(Debug, Deserialize)]
143pub(crate) struct LimitsRequest {
144    agent: String,
145    /// MB, `"auto"`, or `0` for no limit.
146    #[serde(default)]
147    memory_mb: Option<Value>,
148    /// CPUs (fractions allowed), `"auto"`, or `0` for no limit.
149    #[serde(default)]
150    cpus: Option<Value>,
151}
152
153async fn run(state: &AppState, caller: Option<&Caller>, req: LimitsRequest) -> Result<Value, Refusal> {
154    let (uid, def) = container_agent(state, &req.agent)?;
155    let changing = req.memory_mb.is_some() || req.cpus.is_some();
156    let mut by = "you".to_string();
157    if let Some(caller_uid) = caller.and_then(Caller::uid) {
158        let caller_def = state
159            .mstore
160            .agent_def_get(caller_uid)
161            .ok()
162            .flatten()
163            .ok_or_else(|| refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"))?;
164        if changing && caller_def.runtime().is_container() {
165            return Err(refuse(
166                StatusCode::FORBIDDEN,
167                "CONTAINER_AGENT: a container agent cannot change a container's limits, its own included. Ask a host agent, \
168                 your steward or the operator to raise it, saying how much memory the work needs and why",
169            ));
170        }
171        by = caller_def.name;
172    }
173    let result = if changing {
174        set(state, &uid, &def, req.memory_mb.as_ref(), req.cpus.as_ref(), &by).await?
175    } else {
176        view(state, &uid, None).await?
177    };
178    Ok(json!({
179        "agent": def.name,
180        "limits": result,
181        "note": "memory_mb and cpus are what is set (empty: auto, \"0\": no limit); effective_* is what is in force now, \
182                 and daemon_* what Docker has in total. A change is put on the running container at once",
183    }))
184}
185
186pub(crate) async fn handle_container_limits(
187    State(state): State<AppState>,
188    caller: Option<Extension<Caller>>,
189    Json(req): Json<LimitsRequest>,
190) -> Response {
191    let caller = caller.map(|Extension(c)| c);
192    match run(&state, caller.as_ref(), req).await {
193        Ok(body) => Json(body).into_response(),
194        Err((status, message)) => (status, Json(json!({ "error": message }))).into_response(),
195    }
196}