Skip to main content

agentmux_srv/server/live_facts/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What an agent is running on and doing now, read from AgentMux's own runtime state and never from the
5//! agent's say-so (docs/specs/SPEC_MUXAPI_AGENT_LIVE_FACTS_2026_11_20.md). One builder, [`facts_of`], for
6//! `Agents list`, `Agents status` and the Swarm's rows.
7//!
8//! The model and effort come first (`model`, the one group every row carries in short form); the rest are
9//! groups a caller asks for by name (`Select`), so a default row stays small and each group costs only
10//! when asked. Never in a fact: a credential, a vault entry, a prompt or a message (spec §3, "Not exposed").
11
12pub mod handler;
13pub mod model;
14pub mod query;
15
16use std::collections::HashMap;
17
18use serde::Serialize;
19use serde_json::Value;
20
21use crate::backend::account_usage::AccountUsage;
22use crate::backend::agent_runtime::{spawn_runtime_from_args, AgentRuntimeEvent};
23use crate::backend::agent_status::Pane;
24use crate::backend::obj::Block;
25use crate::backend::storage::identities::IdentityAccount;
26use crate::backend::storage::AgentDefinition;
27use crate::server::AppState;
28
29pub use model::ModelFacts;
30
31/// A context reading with no new call for this long, in a turn, is stale.
32const CONTEXT_STALE_MS: u64 = 5 * 60_000;
33
34/// Where an agent runs and how it is set up.
35#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
36#[ts(export, export_to = "../../../frontend/types/rpc/")]
37pub struct RuntimeFacts {
38    /// The provider's harness (`claude`, `codex`, ...).
39    pub harness: String,
40    /// `native` (a process on its host) or `container`.
41    pub kind: String,
42    #[serde(skip_serializing_if = "Option::is_none")]
43    #[ts(optional)]
44    pub image: Option<String>,
45    #[serde(skip_serializing_if = "Option::is_none")]
46    #[ts(optional)]
47    pub permission_mode: Option<String>,
48    /// Its pane is in a tab an open window shows.
49    pub pane_shown: bool,
50}
51
52/// Whether the agent is in a turn, and since when.
53#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
54#[ts(export, export_to = "../../../frontend/types/rpc/")]
55pub struct TurnFacts {
56    pub active: bool,
57    #[serde(skip_serializing_if = "Option::is_none")]
58    #[ts(optional, type = "number")]
59    pub since_ms: Option<u64>,
60    #[serde(skip_serializing_if = "Option::is_none")]
61    #[ts(optional, type = "number")]
62    pub duration_ms: Option<u64>,
63    #[serde(skip_serializing_if = "Option::is_none")]
64    #[ts(optional, type = "number")]
65    pub last_activity_ms: Option<u64>,
66    #[serde(skip_serializing_if = "Option::is_none")]
67    #[ts(optional, type = "number")]
68    pub idle_ms: Option<u64>,
69}
70
71/// How full the agent's context is. In memory: absent until the agent's next frame after srv starts.
72#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
73#[ts(export, export_to = "../../../frontend/types/rpc/")]
74pub struct ContextFacts {
75    #[serde(skip_serializing_if = "Option::is_none")]
76    #[ts(optional, type = "number")]
77    pub tokens: Option<u64>,
78    #[serde(skip_serializing_if = "Option::is_none")]
79    #[ts(optional, type = "number")]
80    pub window: Option<u64>,
81    #[serde(skip_serializing_if = "Option::is_none")]
82    #[ts(optional)]
83    pub percent: Option<f64>,
84    #[serde(skip_serializing_if = "Option::is_none")]
85    #[ts(optional, type = "number")]
86    pub auto_compact_at: Option<u64>,
87    pub compacting: bool,
88    #[ts(type = "number")]
89    pub compactions: u64,
90    #[serde(skip_serializing_if = "Option::is_none")]
91    #[ts(optional, type = "number")]
92    pub observed_ms: Option<u64>,
93    /// In a turn with no new reading for a while.
94    pub stale: bool,
95}
96
97/// The account the agent's run is on: a stable id and the label Identity accounts shows. Never a credential.
98#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
99#[ts(export, export_to = "../../../frontend/types/rpc/")]
100pub struct AccountFacts {
101    #[serde(skip_serializing_if = "Option::is_none")]
102    #[ts(optional)]
103    pub stable_id: Option<String>,
104    pub label: String,
105}
106
107/// The Kanban tasks the agent holds now.
108#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
109#[ts(export, export_to = "../../../frontend/types/rpc/")]
110pub struct TaskFacts {
111    /// The first of them.
112    #[ts(type = "number")]
113    pub number: i64,
114    #[ts(type = "Array<number>")]
115    pub all: Vec<i64>,
116}
117
118/// An agent that owes work and has done nothing for the quiet time
119/// (SPEC_LEADER_TOLD_WHEN_AN_AGENT_GOES_QUIET_2026_11_21.md §6): the Swarm's and the Kanban's "quiet 22 min". Read from
120/// the last sweep, so it can be up to half a minute behind; absent while the agent is not quiet.
121#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
122#[ts(export, export_to = "../../../frontend/types/rpc/")]
123pub struct QuietFacts {
124    /// When the quiet began: the agent's last activity.
125    #[ts(type = "number")]
126    pub since_ms: u64,
127    /// How long it has been quiet.
128    #[ts(type = "number")]
129    pub quiet_ms: u64,
130    /// The Kanban tasks it holds; empty for a spawned worker that owes its leader a report.
131    #[ts(type = "Array<number>")]
132    pub tasks: Vec<i64>,
133    /// The agents told about it (names).
134    pub watchers: Vec<String>,
135}
136
137/// When the agent's process started.
138#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
139#[ts(export, export_to = "../../../frontend/types/rpc/")]
140pub struct SessionFacts {
141    #[ts(type = "number")]
142    pub started_ms: u64,
143    #[ts(type = "number")]
144    pub uptime_ms: u64,
145}
146
147/// The AgentMux the agent runs in.
148#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
149#[ts(export, export_to = "../../../frontend/types/rpc/")]
150pub struct HostFacts {
151    pub name: String,
152    pub version: String,
153    pub build: String,
154    pub channel: String,
155}
156
157/// The groups asked for; each is absent when not asked for or when nothing says.
158#[derive(Debug, Clone, Default, PartialEq, Serialize, ts_rs::TS)]
159#[ts(export, export_to = "../../../frontend/types/rpc/")]
160pub struct LiveFacts {
161    #[serde(skip_serializing_if = "Option::is_none")]
162    #[ts(optional)]
163    pub model: Option<ModelFacts>,
164    #[serde(skip_serializing_if = "Option::is_none")]
165    #[ts(optional)]
166    pub runtime: Option<RuntimeFacts>,
167    #[serde(skip_serializing_if = "Option::is_none")]
168    #[ts(optional)]
169    pub turn: Option<TurnFacts>,
170    #[serde(skip_serializing_if = "Option::is_none")]
171    #[ts(optional)]
172    pub context: Option<ContextFacts>,
173    #[serde(skip_serializing_if = "Option::is_none")]
174    #[ts(optional)]
175    pub account: Option<AccountFacts>,
176    /// The account's usage windows, as `Identity accounts` reads them (backend::account_usage).
177    #[serde(skip_serializing_if = "Option::is_none")]
178    #[ts(optional)]
179    pub usage: Option<AccountUsage>,
180    /// What a route agent has spent today and its cap, as the list row's `spend` says.
181    #[serde(skip_serializing_if = "Option::is_none")]
182    #[ts(optional, type = "unknown")]
183    pub spend: Option<Value>,
184    #[serde(skip_serializing_if = "Option::is_none")]
185    #[ts(optional)]
186    pub task: Option<TaskFacts>,
187    #[serde(skip_serializing_if = "Option::is_none")]
188    #[ts(optional)]
189    pub quiet: Option<QuietFacts>,
190    #[serde(skip_serializing_if = "Option::is_none")]
191    #[ts(optional)]
192    pub session: Option<SessionFacts>,
193    #[serde(skip_serializing_if = "Option::is_none")]
194    #[ts(optional)]
195    pub host: Option<HostFacts>,
196}
197
198/// Which groups a caller asked for.
199#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
200pub struct Select {
201    pub model: bool,
202    pub runtime: bool,
203    pub turn: bool,
204    pub context: bool,
205    pub account: bool,
206    pub usage: bool,
207    pub spend: bool,
208    pub task: bool,
209    pub quiet: bool,
210    pub session: bool,
211    pub host: bool,
212}
213
214impl Select {
215    pub const GROUPS: [&'static str; 11] = ["model", "runtime", "turn", "context", "account", "usage", "spend", "task", "quiet", "session", "host"];
216
217    /// Every group (`host` only when `with_host`).
218    pub fn all(with_host: bool) -> Self {
219        Self { model: true, runtime: true, turn: true, context: true, account: true, usage: true, spend: true, task: true, quiet: true, session: true, host: with_host }
220    }
221
222    fn set(&mut self, group: &str) -> bool {
223        match group {
224            "model" => self.model = true,
225            "runtime" => self.runtime = true,
226            "turn" => self.turn = true,
227            "context" => self.context = true,
228            "account" => self.account = true,
229            "usage" => self.usage = true,
230            "spend" => self.spend = true,
231            "task" => self.task = true,
232            "quiet" => self.quiet = true,
233            "session" => self.session = true,
234            "host" => self.host = true,
235            _ => return false,
236        }
237        true
238    }
239
240    /// From `fields` (comma-separated group names, or `all`) and `detail` (`basic`, `facts`, `full`).
241    pub fn parse(fields: Option<&str>, detail: Option<&str>) -> Result<Self, String> {
242        let mut sel = match detail.map(str::trim).filter(|d| !d.is_empty()) {
243            None | Some("basic") => Self::default(),
244            Some("facts") => Self::all(false),
245            Some("full") => Self::all(true),
246            Some(other) => return Err(format!("unknown detail {other:?}: use basic, facts or full")),
247        };
248        for name in fields.unwrap_or_default().split(',').map(str::trim).filter(|n| !n.is_empty()) {
249            if name == "all" {
250                sel = Self::all(true);
251            } else if !sel.set(name) {
252                return Err(format!("unknown field group {name:?}: the groups are {}, or all", Self::GROUPS.join(", ")));
253            }
254        }
255        Ok(sel)
256    }
257
258    /// A `facts` object is wanted at all.
259    pub fn any(&self) -> bool {
260        *self != Self::default()
261    }
262}
263
264/// What every agent of a call shares, read once.
265pub struct Ctx<'a> {
266    state: &'a AppState,
267    now_ms: u64,
268    defs: Vec<AgentDefinition>,
269    /// Kanban task numbers held, by the holder's uid or `name:<lowercase name>`.
270    claimed: HashMap<String, Vec<i64>>,
271    accounts: Vec<IdentityAccount>,
272    settings: HashMap<String, Value>,
273    net: crate::connectivity::ConnectivityStatus,
274}
275
276impl<'a> Ctx<'a> {
277    /// Reads what `sel` and the filters will need: the claimed tasks only when tasks are asked for, the
278    /// accounts only when an account or its usage is.
279    pub fn new(state: &'a AppState, now_ms: u64, sel: &Select, needs_account: bool) -> Self {
280        let defs = state.mstore.agent_def_list().unwrap_or_default();
281        let accounts = if sel.account || sel.usage || needs_account { state.id_store.identity_list(None).unwrap_or_default() } else { Vec::new() };
282        Self {
283            state,
284            now_ms,
285            defs,
286            claimed: if sel.task { claimed_tasks(state) } else { HashMap::new() },
287            accounts,
288            settings: state.config_watcher.get_settings().extra.clone(),
289            net: crate::connectivity::status(),
290        }
291    }
292}
293
294/// The Kanban task numbers each agent holds.
295fn claimed_tasks(state: &AppState) -> HashMap<String, Vec<i64>> {
296    use crate::backend::storage::work_queue::work_state;
297    let now = agentmux_common::time::now_ms();
298    let items = state.work_store.work_board_list(now - crate::backend::kanban::FINISHED_WINDOW_MS, 500, now).unwrap_or_default();
299    let mut out: HashMap<String, Vec<i64>> = HashMap::new();
300    for t in items.iter().filter(|t| t.item.state == work_state::CLAIMED) {
301        let key = if t.item.claimed_by_uid.is_empty() { format!("name:{}", t.item.claimed_by.to_lowercase()) } else { t.item.claimed_by_uid.clone() };
302        out.entry(key).or_default().push(t.card.num);
303    }
304    out.values_mut().for_each(|v| v.sort_unstable());
305    out
306}
307
308/// One agent, as a caller of [`facts_of`] knows it.
309pub struct Agent<'a> {
310    pub uid: &'a str,
311    pub name: &'a str,
312    pub provider: &'a str,
313    pub block_id: Option<&'a str>,
314    /// Its runtime state (`idle`, `working`, `stopped`, ...), as `agent_runtime` names it.
315    pub state: &'a str,
316    pub container: bool,
317}
318
319/// The agent's own block, when it has one.
320fn block_of(ctx: &Ctx, a: &Agent) -> Option<Block> {
321    a.block_id.and_then(|b| ctx.state.mstore.get::<Block>(b).ok().flatten())
322}
323
324/// The model and effort: the one group every row carries (short, as `model_label` and `model_source`).
325pub fn model_of(ctx: &Ctx, a: &Agent, block: Option<&Block>) -> ModelFacts {
326    let def = ctx.defs.iter().find(|d| d.id == a.uid);
327    let event: Option<AgentRuntimeEvent> = a.block_id.and_then(crate::backend::agent_runtime_latest::get);
328    let reading = a.block_id.and_then(crate::backend::context_reading::get);
329    let choice = def.and_then(|d| crate::backend::model_gateway::launch::choice_of(&ctx.state.mstore, &d.id));
330    let route = choice.as_ref().and_then(|c| {
331        let r = crate::backend::model_gateway::catalog::route(&c.route)?;
332        let m = r.model(&c.model)?;
333        Some((r.id, r.label, m.id, m.label))
334    });
335    let meta = block.map(|b| &b.meta);
336    let meta_runtime = meta.and_then(|m| m.get("agent:runtime"));
337    let meta_model = meta_runtime.and_then(|r| r.get("model")).and_then(Value::as_str).or_else(|| meta.and_then(|m| m.get("agent:model")).and_then(Value::as_str));
338    let definition_model = def.and_then(|d| {
339        let argv: Vec<String> = d.provider_flags.split_whitespace().map(str::to_string).collect();
340        spawn_runtime_from_args(&argv).model
341    });
342    model::resolve(&model::Inputs {
343        event: event.as_ref(),
344        observed: reading.as_ref().and_then(|r| r.model.as_deref()),
345        route,
346        meta_model,
347        meta_effort: meta_runtime.and_then(|r| r.get("effort")).and_then(Value::as_str),
348        definition_model: definition_model.as_deref(),
349        running: a.state != "stopped" && a.state != "error",
350    })
351}
352
353fn runtime_of(ctx: &Ctx, a: &Agent, block: Option<&Block>) -> RuntimeFacts {
354    let def = ctx.defs.iter().find(|d| d.id == a.uid);
355    let event = a.block_id.and_then(crate::backend::agent_runtime_latest::get);
356    let meta_mode = block.and_then(|b| b.meta.get("agent:runtime")).and_then(|r| r.get("permission_mode")).and_then(Value::as_str);
357    let pane = super::availability_view::status_of(&ctx.state.mstore, a.block_id, block, &ctx.net, ctx.now_ms).pane;
358    RuntimeFacts {
359        harness: a.provider.to_string(),
360        kind: if a.container { "container" } else { "native" }.to_string(),
361        image: a.container.then(|| def.map(|d| crate::backend::container::image::resolve_container_image(&d.container_image))).flatten(),
362        permission_mode: event.and_then(|e| e.permission_mode).or_else(|| meta_mode.map(str::to_string)),
363        pane_shown: pane == Pane::Shown,
364    }
365}
366
367fn turn_of(ctx: &Ctx, a: &Agent) -> Option<TurnFacts> {
368    let ctrl = crate::backend::blockcontroller::get_controller(a.block_id?)?;
369    let tracker = ctrl.turn_tracker()?;
370    let ms = |v: Option<i64>| v.and_then(|v| u64::try_from(v).ok());
371    let since = ms(tracker.pass_started_ms());
372    let last = ms(ctrl.last_output_ms());
373    Some(TurnFacts {
374        active: since.is_some(),
375        since_ms: since,
376        duration_ms: since.map(|s| ctx.now_ms.saturating_sub(s)),
377        last_activity_ms: last,
378        idle_ms: last.map(|l| ctx.now_ms.saturating_sub(l)),
379    })
380}
381
382fn context_of(ctx: &Ctx, a: &Agent, turn_active: bool) -> Option<ContextFacts> {
383    let r = crate::backend::context_reading::get(a.block_id?)?;
384    r.tokens.or(r.window)?;
385    let percent = match (r.tokens, r.window) {
386        (Some(t), Some(w)) if w > 0 => Some((t as f64 / w as f64 * 1000.0).round() / 10.0),
387        _ => None,
388    };
389    Some(ContextFacts {
390        tokens: r.tokens,
391        window: r.window,
392        percent,
393        auto_compact_at: r.auto_compact_at,
394        compacting: r.compacting,
395        compactions: r.compactions,
396        observed_ms: r.observed_ms,
397        stale: turn_active && r.observed_ms.is_some_and(|o| ctx.now_ms.saturating_sub(o) > CONTEXT_STALE_MS),
398    })
399}
400
401/// The account the pane's run is on (`agent:run_account`), with its stable id, label and usage.
402fn account_of(ctx: &Ctx, block: Option<&Block>) -> Option<(AccountFacts, Option<AccountUsage>)> {
403    let id = block?.meta.get(crate::backend::agent_state::RUN_ACCOUNT_META_KEY)?.as_str()?;
404    let acct = ctx.accounts.iter().find(|a| a.id == id)?;
405    let facts = AccountFacts {
406        stable_id: crate::identity::stable_account::stable_account_id(acct),
407        label: safe_label(acct),
408    };
409    Some((facts, Some(AccountUsage::of(&acct.provider, id, ctx.now_ms))))
410}
411
412/// The account's name for a reader of the fleet: its display name or its name, never an email (a name can be one, and the
413/// account's own label falls back to the email) and never read from its context.
414fn safe_label(a: &IdentityAccount) -> String {
415    [a.display_name.as_str(), a.name.as_str()]
416        .into_iter()
417        .map(str::trim)
418        .find(|s| !s.is_empty() && !s.contains('@'))
419        .map_or_else(|| format!("{} account", a.provider), str::to_string)
420}
421
422fn task_of(ctx: &Ctx, a: &Agent) -> Option<TaskFacts> {
423    let all = ctx.claimed.get(a.uid).or_else(|| ctx.claimed.get(&format!("name:{}", a.name.to_lowercase())))?;
424    Some(TaskFacts { number: *all.first()?, all: all.clone() })
425}
426
427fn quiet_of(ctx: &Ctx, a: &Agent) -> Option<QuietFacts> {
428    let q = crate::backend::quiet_watch::quiet_view(a.uid)?;
429    Some(QuietFacts { since_ms: q.since_ms, quiet_ms: ctx.now_ms.saturating_sub(q.since_ms), tasks: q.tasks, watchers: q.watchers })
430}
431
432fn session_of(ctx: &Ctx, a: &Agent) -> Option<SessionFacts> {
433    let tracker = crate::backend::blockcontroller::get_controller(a.block_id?)?.turn_tracker()?;
434    let started = u64::try_from(tracker.spawned_at_ms()?).ok()?;
435    Some(SessionFacts { started_ms: started, uptime_ms: ctx.now_ms.saturating_sub(started) })
436}
437
438fn host_of(ctx: &Ctx) -> HostFacts {
439    HostFacts {
440        name: ctx.state.hostname.clone(),
441        version: ctx.state.version.clone(),
442        build: std::env::var("AGENTMUX_BUILD").ok().filter(|b| !b.is_empty()).unwrap_or_else(|| ctx.state.version.clone()),
443        channel: crate::backend::reactive::registry::local_channel_id(),
444    }
445}
446
447/// The groups of `sel` for `a`. `model` is the answer [`model_of`] already gave, so it is read once.
448pub fn facts_of(ctx: &Ctx, sel: &Select, a: &Agent, model: ModelFacts) -> LiveFacts {
449    let block = if sel.runtime || sel.account || sel.usage { block_of(ctx, a) } else { None };
450    let turn = (sel.turn || sel.context).then(|| turn_of(ctx, a)).flatten();
451    let (account, usage) = if sel.account || sel.usage { account_of(ctx, block.as_ref()).unzip() } else { (None, None) };
452    LiveFacts {
453        model: sel.model.then_some(model),
454        runtime: sel.runtime.then(|| runtime_of(ctx, a, block.as_ref())),
455        context: sel.context.then(|| context_of(ctx, a, turn.as_ref().is_some_and(|t| t.active))).flatten(),
456        turn: sel.turn.then_some(turn).flatten(),
457        account: if sel.account { account } else { None },
458        usage: if sel.usage { usage.flatten() } else { None },
459        spend: sel.spend.then(|| super::spend_watch::view(&ctx.state.mstore, &ctx.state.identity_store, &ctx.settings, &ctx.defs, a.uid)).flatten(),
460        task: sel.task.then(|| task_of(ctx, a)).flatten(),
461        quiet: sel.quiet.then(|| quiet_of(ctx, a)).flatten(),
462        session: sel.session.then(|| session_of(ctx, a)).flatten(),
463        host: sel.host.then(|| host_of(ctx)),
464    }
465}
466
467#[cfg(test)]
468#[path = "tests.rs"]
469mod tests;