Skip to main content

agentmux_srv_core/backend/
container_status.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! This machine's agent containers as the frontend sees them: a name, whose they are, a state and an image,
5//! pushed as `container-status` when one changes, with the container runtime's own state as
6//! `container-runtime`, and read as a whole with `GET /api/v1/containers`
7//! (`docs/specs/SPEC_CONTAINER_STATUS_IN_THE_FRONTEND_2026_11_14.md`).
8//!
9//! Names and states only. There is no field for a log, an environment, a mount or a statistic, so none can
10//! leak through it. Docker is the source of truth: [`run`] follows its event stream, rebuilds from a list now
11//! and then, and this module keeps what it was told ([`Registry`]) and says what changed ([`Hub`]).
12//!
13//! Which containers: those named `agentmux-<agent id>`, as `container_name_for_slug` names them. One whose id
14//! is no agent's is an orphan (`agent_id` null), because that is the one a person wants to see. Another
15//! container is never listed: a name must carry the label new containers get ([`AGENT_LABEL`]), or look like
16//! an agent id (a UUID), or be the id of a definition.
17//!
18//! A container that stopped, died or was removed ends its agent's gateway tokens (a model route's and the API key's), whoever stopped it: AgentMux's
19//! own stops do it where they happen (`container::key_route`), and this is the one for a stop it did not make (Docker
20//! Desktop, a daemon restart), so the token does not outlive the container and is not given again to one that takes its
21//! place at the same address ([`end_gateway_tokens`]).
22//!
23//! AgentMux's own helper containers (the gateway forwarder, `container::gateway_fwd`) are listed too, with `helper` naming
24//! what they are and no agent.
25
26pub(crate) mod docker_event;
27mod run;
28mod source;
29
30use std::collections::{BTreeMap, HashMap};
31use std::sync::{Arc, OnceLock};
32use std::time::Duration;
33
34use serde::Serialize;
35
36use super::container::gateway_fwd;
37use super::model_gateway::token;
38
39pub use docker_event::{Action, DockerEvent, Listed};
40pub use run::{run, Probe, Source};
41pub use source::DockerSource;
42
43/// The name every agent container starts with (`container_name_for_slug`).
44pub const NAME_PREFIX: &str = "agentmux-";
45/// The label a new agent container carries: its agent's id.
46pub const AGENT_LABEL: &str = "ai.agentmux.agent";
47/// How long a container srv is bringing up stays `starting` while Docker does not list it as running: long
48/// enough for a large image to download, short enough that a start that failed does not stay for good.
49const STARTING_GRACE_MS: u64 = 10 * 60_000;
50/// A gateway token made this recently is left alone by a stop event: Docker's events can run behind, and the token may be
51/// the one AgentMux made for the container that took the stopped one's place.
52const TOKEN_RECENT: Duration = Duration::from_secs(10);
53
54/// Where a container is.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
56#[ts(export, export_to = "../../../frontend/types/rpc/")]
57#[serde(rename_all = "snake_case")]
58pub enum ContainerState {
59    /// Being made or started: srv is bringing it up.
60    Starting,
61    Running,
62    /// Made and not running.
63    Stopped,
64    /// Removed. Only ever in an event, once.
65    Gone,
66}
67
68/// One agent container. `agent_id` and `agent_name` are null for an orphan.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
70#[ts(export, export_to = "../../../frontend/types/rpc/")]
71pub struct ContainerStatus {
72    pub name: String,
73    pub agent_id: Option<String>,
74    pub agent_name: Option<String>,
75    pub state: ContainerState,
76    /// The image reference as the container was made from it: name and tag, no credentials.
77    pub image: String,
78    /// When it entered `state`, in milliseconds since 1970.
79    #[ts(type = "number")]
80    pub since_ms: u64,
81    /// What an AgentMux helper container is (`AgentMux gateway forwarder`); null for an agent's container or an orphan.
82    #[serde(skip_serializing_if = "Option::is_none")]
83    #[ts(optional)]
84    pub helper: Option<String>,
85}
86
87/// The container runtime's own state, the fields of `containerruntimeavailable` with the time it was seen.
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
89#[ts(export, export_to = "../../../frontend/types/rpc/")]
90pub struct ContainerRuntimeStatus {
91    pub available: bool,
92    #[serde(skip_serializing_if = "Option::is_none")]
93    #[ts(optional)]
94    pub runtime: Option<String>,
95    #[serde(skip_serializing_if = "Option::is_none")]
96    #[ts(optional)]
97    pub detail: Option<String>,
98    #[ts(type = "number")]
99    pub at_ms: u64,
100}
101
102impl ContainerRuntimeStatus {
103    /// Before anything has been looked at: there is no runtime.
104    pub fn absent() -> Self {
105        Self { available: false, runtime: None, detail: None, at_ms: agentmux_common::time::now_ms_u64() }
106    }
107}
108
109/// The answer of `GET /api/v1/containers`: what is there now.
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
111#[ts(export, export_to = "../../../frontend/types/rpc/")]
112pub struct ContainersList {
113    pub runtime: ContainerRuntimeStatus,
114    pub containers: Vec<ContainerStatus>,
115}
116
117/// What [`Hub`] says to the outside.
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub enum Published {
120    Container(ContainerStatus),
121    Runtime(ContainerRuntimeStatus),
122}
123
124/// What is known of one container, before it is named for an agent.
125#[derive(Debug, Clone, PartialEq, Eq)]
126struct Raw {
127    state: ContainerState,
128    image: String,
129    since_ms: u64,
130    labelled: bool,
131}
132
133/// What Docker (and srv's own start-up) has said, and what was last published from it.
134#[derive(Debug, Default)]
135pub struct Registry {
136    raw: BTreeMap<String, Raw>,
137    sent: BTreeMap<String, ContainerStatus>,
138    runtime: Option<ContainerRuntimeStatus>,
139    ever_available: bool,
140}
141
142/// What a container is when it is one of AgentMux's own helpers, by its name.
143fn helper_of(name: &str) -> Option<&'static str> {
144    gateway_fwd::is_forwarder_name(name).then_some(gateway_fwd::HELPER_TEXT)
145}
146
147/// The agent id of a container name, when it is an agent container's.
148fn agent_id_of(name: &str) -> Option<&str> {
149    name.strip_prefix(NAME_PREFIX).filter(|id| !id.is_empty())
150}
151
152/// Ends the gateway tokens of the agent whose container `name` is, unless made just now ([`TOKEN_RECENT`]). A helper is no agent's.
153fn end_gateway_tokens(name: &str, recent: Duration) {
154    if let (Some(agent), None) = (agent_id_of(name), helper_of(name)) {
155        token::revoke_agent_everywhere_older_than(agent, recent);
156    }
157}
158
159/// Whether `id` is shaped like an agent's id (a UUID), as every definition's is.
160fn looks_like_agent_id(id: &str) -> bool {
161    let groups: Vec<&str> = id.split('-').collect();
162    groups.len() == 5
163        && groups.iter().zip([8, 4, 4, 4, 12]).all(|(g, n)| g.len() == n && g.bytes().all(|b| b.is_ascii_hexdigit()))
164}
165
166impl Registry {
167    /// One Docker event: the container moves to the state the action names. The same state again changes
168    /// nothing, so `since_ms` stays when it was entered.
169    pub fn apply(&mut self, event: DockerEvent, now_ms: u64) {
170        if agent_id_of(&event.name).is_none() {
171            return;
172        }
173        let state = match event.action {
174            Action::Create => ContainerState::Starting,
175            Action::Start => ContainerState::Running,
176            Action::Stop | Action::Die => ContainerState::Stopped,
177            Action::Destroy => {
178                self.raw.remove(&event.name);
179                return;
180            }
181        };
182        self.set(&event.name, state, &event.image, event.labelled, now_ms);
183    }
184
185    /// srv is bringing `name` up: shown as starting before Docker says anything. A container that is
186    /// already running stays running.
187    pub fn starting(&mut self, name: &str, image: &str, now_ms: u64) {
188        if agent_id_of(name).is_none() || self.raw.get(name).is_some_and(|r| r.state == ContainerState::Running) {
189            return;
190        }
191        self.set(name, ContainerState::Starting, image, true, now_ms);
192    }
193
194    /// The whole list from Docker: what it names replaces what was known, and a container it does not
195    /// name is gone, except one srv is still bringing up (its image may be downloading, so Docker does not
196    /// have it yet, or has made it and not started it), which stays `starting` for [`STARTING_GRACE_MS`].
197    pub fn replace(&mut self, listed: Vec<Listed>, now_ms: u64) {
198        let names: std::collections::HashSet<&str> = listed.iter().map(|l| l.name.as_str()).collect();
199        let coming_up = |r: &Raw| r.state == ContainerState::Starting && now_ms.saturating_sub(r.since_ms) < STARTING_GRACE_MS;
200        self.raw.retain(|name, r| names.contains(name.as_str()) || coming_up(r));
201        for l in &listed {
202            if agent_id_of(&l.name).is_none() {
203                continue;
204            }
205            if !l.running && self.raw.get(&l.name).is_some_and(coming_up) {
206                continue;
207            }
208            let state = if l.running { ContainerState::Running } else { ContainerState::Stopped };
209            self.set(&l.name, state, &l.image, l.labelled, now_ms);
210        }
211    }
212
213    /// The containers this registry had running that a full list shows to be not running or not there: a stop the event stream
214    /// missed. A container already known to be stopped is not one (a stopped container left over for an agent that now runs
215    /// locally has a token of its own), and nor is one srv is still bringing up.
216    fn stopped_unseen_by(&self, listed: &[Listed]) -> Vec<String> {
217        let running: std::collections::HashSet<&str> = listed.iter().filter(|l| l.running).map(|l| l.name.as_str()).collect();
218        self.raw.iter().filter(|(name, r)| r.state == ContainerState::Running && !running.contains(name.as_str())).map(|(name, _)| name.clone()).collect()
219    }
220
221    fn is_running(&self, name: &str) -> bool {
222        self.raw.get(name).is_some_and(|r| r.state == ContainerState::Running)
223    }
224
225    fn set(&mut self, name: &str, state: ContainerState, image: &str, labelled: bool, now_ms: u64) {
226        let known = self.raw.get(name);
227        // A start-up that has no image yet (a restart of a stopped container) keeps the one it had.
228        let image = if image.is_empty() { known.map(|r| r.image.clone()).unwrap_or_default() } else { image.to_string() };
229        let since_ms = known.filter(|r| r.state == state).map_or(now_ms, |r| r.since_ms);
230        let labelled = labelled || known.is_some_and(|r| r.labelled);
231        self.raw.insert(name.to_string(), Raw { state, image, since_ms, labelled });
232    }
233
234    /// The runtime as just looked at. `Some` when it differs from the last look in anything but the time.
235    pub fn set_runtime(&mut self, probe: Probe, now_ms: u64) -> Option<ContainerRuntimeStatus> {
236        self.ever_available |= probe.available;
237        let now = ContainerRuntimeStatus { available: probe.available, runtime: probe.runtime, detail: probe.detail, at_ms: now_ms };
238        let same = self.runtime.as_ref().is_some_and(|r| (r.available, &r.runtime, &r.detail) == (now.available, &now.runtime, &now.detail));
239        if same {
240            return None;
241        }
242        self.runtime = Some(now.clone());
243        Some(now)
244    }
245
246    /// What differs from what was last published, given the agents' names (by id): a changed container, and
247    /// a removed one once, as `gone`. Drops what is gone.
248    pub fn changes(&mut self, agents: &HashMap<String, String>, now_ms: u64) -> Vec<ContainerStatus> {
249        let mut now: BTreeMap<String, ContainerStatus> = BTreeMap::new();
250        for (name, raw) in &self.raw {
251            let Some(id) = agent_id_of(name) else { continue };
252            let helper = helper_of(name);
253            if !(raw.labelled || helper.is_some() || looks_like_agent_id(id) || agents.contains_key(id)) {
254                continue;
255            }
256            let agent_name = if helper.is_some() { None } else { agents.get(id) };
257            now.insert(
258                name.clone(),
259                ContainerStatus {
260                    name: name.clone(),
261                    agent_id: agent_name.map(|_| id.to_string()),
262                    agent_name: agent_name.cloned(),
263                    state: raw.state,
264                    image: raw.image.clone(),
265                    since_ms: raw.since_ms,
266                    helper: helper.map(str::to_string),
267                },
268            );
269        }
270        let mut changed: Vec<ContainerStatus> = now.values().filter(|s| self.sent.get(&s.name) != Some(s)).cloned().collect();
271        for (name, was) in &self.sent {
272            if !now.contains_key(name) {
273                changed.push(ContainerStatus { state: ContainerState::Gone, since_ms: now_ms, ..was.clone() });
274            }
275        }
276        self.sent = now;
277        changed
278    }
279
280    /// The containers as last published, by name.
281    pub fn containers(&self) -> Vec<ContainerStatus> {
282        self.sent.values().cloned().collect()
283    }
284
285    /// The runtime as last seen; "not available" before the first look.
286    pub fn runtime(&self, now_ms: u64) -> ContainerRuntimeStatus {
287        self.runtime.clone().unwrap_or(ContainerRuntimeStatus { available: false, runtime: None, detail: None, at_ms: now_ms })
288    }
289
290    /// Whether the runtime is absent, was never seen and has no container to report: nothing then needs
291    /// looking at until something wakes [`Hub::dormant_until_woken`].
292    pub fn is_dormant(&self) -> bool {
293        !self.ever_available && self.sent.is_empty() && self.raw.is_empty() && self.runtime.as_ref().is_some_and(|r| !r.available)
294    }
295}
296
297type AgentNames = Box<dyn Fn() -> HashMap<String, String> + Send + Sync>;
298type Sink = Box<dyn Fn(Published) + Send + Sync>;
299
300/// The registry with the way out: every change it makes is published, once.
301pub struct Hub {
302    registry: std::sync::Mutex<Registry>,
303    agents: AgentNames,
304    sink: Sink,
305    wake: tokio::sync::Notify,
306    /// How recent a key-route token must be to be left alone by a stop ([`TOKEN_RECENT`]; a test shortens it).
307    token_recent: Duration,
308}
309
310impl Hub {
311    /// `agents` is each agent's name by id, read when a change is worked out; `sink` gets what changed.
312    pub fn new(agents: impl Fn() -> HashMap<String, String> + Send + Sync + 'static, sink: impl Fn(Published) + Send + Sync + 'static) -> Self {
313        Self { registry: Default::default(), agents: Box::new(agents), sink: Box::new(sink), wake: tokio::sync::Notify::new(), token_recent: TOKEN_RECENT }
314    }
315
316    fn lock(&self) -> std::sync::MutexGuard<'_, Registry> {
317        self.registry.lock().unwrap_or_else(|e| e.into_inner())
318    }
319
320    /// Publishes what `change` made different.
321    fn publish_after(&self, change: impl FnOnce(&mut Registry, u64)) {
322        let agents = (self.agents)();
323        let now = agentmux_common::time::now_ms_u64();
324        let changed = {
325            let mut registry = self.lock();
326            change(&mut registry, now);
327            registry.changes(&agents, now)
328        };
329        for status in changed {
330            (self.sink)(Published::Container(status));
331        }
332    }
333
334    pub fn on_event(&self, event: DockerEvent) {
335        // Only a container that was running ends a token: a repeat (`die` then `stop`) or the end of one already stopped has nothing
336        // more to end, and a token made for the agent since is not that container's.
337        let ends = matches!(event.action, Action::Stop | Action::Die | Action::Destroy) && self.lock().is_running(&event.name);
338        if ends {
339            end_gateway_tokens(&event.name, self.token_recent);
340        }
341        self.publish_after(|r, now| r.apply(event, now));
342    }
343
344    pub fn on_listed(&self, listed: Vec<Listed>) {
345        // A stop the event stream missed is found here, once: after it the registry has the container stopped.
346        let ended = self.lock().stopped_unseen_by(&listed);
347        for name in ended {
348            end_gateway_tokens(&name, self.token_recent);
349        }
350        self.publish_after(|r, now| r.replace(listed, now));
351    }
352
353    /// srv is starting `name` from `image`; wakes the watcher if it was asleep.
354    pub fn on_starting(&self, name: &str, image: &str) {
355        self.publish_after(|r, now| r.starting(name, image, now));
356        self.wake.notify_one();
357    }
358
359    pub fn on_runtime(&self, probe: Probe) {
360        let changed = self.lock().set_runtime(probe, agentmux_common::time::now_ms_u64());
361        if let Some(status) = changed {
362            (self.sink)(Published::Runtime(status));
363        }
364    }
365
366    /// What is there now, for the route.
367    pub fn list(&self) -> ContainersList {
368        let registry = self.lock();
369        ContainersList { runtime: registry.runtime(agentmux_common::time::now_ms_u64()), containers: registry.containers() }
370    }
371
372    pub fn is_dormant(&self) -> bool {
373        self.lock().is_dormant()
374    }
375
376    /// Wakes the watcher: a person asked, or a container is being started.
377    pub fn wake(&self) {
378        self.wake.notify_one();
379    }
380
381    /// Waits to be woken. A wake that came first is not lost.
382    pub async fn dormant_until_woken(&self) {
383        self.wake.notified().await;
384    }
385}
386
387static HUB: OnceLock<Arc<Hub>> = OnceLock::new();
388
389/// Start publishing on `broker` for the rest of the process, and return the hub for [`run`]. The first call
390/// wins.
391pub fn install(broker: Arc<super::mps::Broker>, agents: impl Fn() -> HashMap<String, String> + Send + Sync + 'static) -> Arc<Hub> {
392    use super::mps_events::{ContainerRuntimeChanged, ContainerStatusChanged};
393    let hub = Arc::new(Hub::new(agents, move |published| match published {
394        Published::Container(status) => broker.publish_event::<ContainerStatusChanged>(&status, vec![], 0),
395        Published::Runtime(status) => broker.publish_event::<ContainerRuntimeChanged>(&status, vec![], 0),
396    }));
397    Arc::clone(HUB.get_or_init(|| hub))
398}
399
400/// The hub, once installed.
401pub fn hub() -> Option<&'static Arc<Hub>> {
402    HUB.get()
403}
404
405/// srv is about to bring `container_name` up from `image` (empty when it exists already).
406pub fn note_starting(container_name: &str, image: &str) {
407    if let Some(hub) = hub() {
408        hub.on_starting(container_name, image);
409    }
410}
411
412#[cfg(test)]
413mod tests;