1pub(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
43pub const NAME_PREFIX: &str = "agentmux-";
45pub const AGENT_LABEL: &str = "ai.agentmux.agent";
47const STARTING_GRACE_MS: u64 = 10 * 60_000;
50const TOKEN_RECENT: Duration = Duration::from_secs(10);
53
54#[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 Starting,
61 Running,
62 Stopped,
64 Gone,
66}
67
68#[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 pub image: String,
78 #[ts(type = "number")]
80 pub since_ms: u64,
81 #[serde(skip_serializing_if = "Option::is_none")]
83 #[ts(optional)]
84 pub helper: Option<String>,
85}
86
87#[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 pub fn absent() -> Self {
105 Self { available: false, runtime: None, detail: None, at_ms: agentmux_common::time::now_ms_u64() }
106 }
107}
108
109#[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#[derive(Debug, Clone, PartialEq, Eq)]
119pub enum Published {
120 Container(ContainerStatus),
121 Runtime(ContainerRuntimeStatus),
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
126struct Raw {
127 state: ContainerState,
128 image: String,
129 since_ms: u64,
130 labelled: bool,
131}
132
133#[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
142fn helper_of(name: &str) -> Option<&'static str> {
144 gateway_fwd::is_forwarder_name(name).then_some(gateway_fwd::HELPER_TEXT)
145}
146
147fn agent_id_of(name: &str) -> Option<&str> {
149 name.strip_prefix(NAME_PREFIX).filter(|id| !id.is_empty())
150}
151
152fn 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
159fn 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 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 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 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 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 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 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 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 pub fn containers(&self) -> Vec<ContainerStatus> {
282 self.sent.values().cloned().collect()
283 }
284
285 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 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
300pub struct Hub {
302 registry: std::sync::Mutex<Registry>,
303 agents: AgentNames,
304 sink: Sink,
305 wake: tokio::sync::Notify,
306 token_recent: Duration,
308}
309
310impl Hub {
311 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 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 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 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 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 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 pub fn wake(&self) {
378 self.wake.notify_one();
379 }
380
381 pub async fn dormant_until_woken(&self) {
383 self.wake.notified().await;
384 }
385}
386
387static HUB: OnceLock<Arc<Hub>> = OnceLock::new();
388
389pub 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
400pub fn hub() -> Option<&'static Arc<Hub>> {
402 HUB.get()
403}
404
405pub 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;