Skip to main content

agentmux_srv/server/live_facts/
model.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which model an agent runs on, and where that answer came from (spec §3 and §7). Pure: the caller reads
5//! the runtime state and hands it in, so every order of preference is a test.
6//!
7//! In order: the model the agent's route sends to; the model its last reply came from (`observed`: the API's
8//! own `model` field, so what really answered); what the CLI itself reported using (`effective`: its settings,
9//! which a container's turns can run past); what its process was started with, then what its pane remembers
10//! asking for (`requested`); and otherwise `unknown`, with why.
11
12use serde::Serialize;
13
14use crate::backend::agent_runtime::AgentRuntimeEvent;
15use crate::backend::model_label::{label_of, same_model};
16
17/// Where a model answer came from.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
19#[ts(export, export_to = "../../../frontend/types/rpc/")]
20#[serde(rename_all = "snake_case")]
21pub enum ModelSource {
22    /// The CLI reported it (`get_settings`, read after every turn).
23    Effective,
24    /// The model the agent's last reply came from.
25    Observed,
26    /// The agent's model route: the gateway sends its requests to this model.
27    Route,
28    /// What the process was started with or the pane remembers asking for: not yet confirmed by the CLI.
29    Requested,
30    /// Nothing says.
31    Unknown,
32}
33
34/// The model route an agent is on.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
36#[ts(export, export_to = "../../../frontend/types/rpc/")]
37pub struct RouteFacts {
38    pub id: String,
39    pub label: String,
40}
41
42/// The model and effort an agent runs on.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
44#[ts(export, export_to = "../../../frontend/types/rpc/")]
45pub struct ModelFacts {
46    /// The model id, as its harness names it.
47    #[serde(skip_serializing_if = "Option::is_none")]
48    #[ts(optional)]
49    pub id: Option<String>,
50    /// A short name for it ("Sonnet 5.5"); the id itself when there is no shorter name.
51    #[serde(skip_serializing_if = "Option::is_none")]
52    #[ts(optional)]
53    pub label: Option<String>,
54    pub source: ModelSource,
55    /// Why there is no model, when `source` is `unknown`.
56    #[serde(skip_serializing_if = "Option::is_none")]
57    #[ts(optional)]
58    pub why: Option<String>,
59    #[serde(skip_serializing_if = "Option::is_none")]
60    #[ts(optional)]
61    pub effort: Option<String>,
62    /// A model or effort change is waiting for the end of the turn, so the model shown is not yet the new one.
63    pub pending_switch: bool,
64    /// The short name of the model the waiting change will run, when the change is to another model (not to another effort).
65    #[serde(skip_serializing_if = "Option::is_none")]
66    #[ts(optional)]
67    pub pending_label: Option<String>,
68    /// The short name of the model its definition asks for, when that is not the one it runs.
69    #[serde(skip_serializing_if = "Option::is_none")]
70    #[ts(optional)]
71    pub definition_label: Option<String>,
72    /// The route the agent is on, when it is on one.
73    #[serde(skip_serializing_if = "Option::is_none")]
74    #[ts(optional)]
75    pub route: Option<RouteFacts>,
76    /// The model it runs (the one its last reply came from) is not the one it was asked to run: its definition's
77    /// `--model`, else the one its pane picker asks for (a switch from the menu, a route, a resume).
78    pub differs_from_definition: bool,
79}
80
81/// What the caller knows about one agent.
82#[derive(Default)]
83pub struct Inputs<'a> {
84    /// The latest `agentruntime` event of its pane.
85    pub event: Option<&'a AgentRuntimeEvent>,
86    /// The model of the last call its pane made (`context_reading`).
87    pub observed: Option<&'a str>,
88    /// The route it is on: the route's id and label, the model's id and label.
89    pub route: Option<(&'a str, &'a str, &'a str, &'a str)>,
90    /// What the pane's `agent:runtime` or `agent:model` meta says it asked for.
91    pub meta_model: Option<&'a str>,
92    pub meta_effort: Option<&'a str>,
93    /// The `--model` of its definition's flags.
94    pub definition_model: Option<&'a str>,
95    /// A process is alive in it.
96    pub running: bool,
97}
98
99/// The model and effort of an agent, and where they came from.
100pub fn resolve(i: &Inputs) -> ModelFacts {
101    let live = i.event.filter(|e| e.running);
102    let (id, source) = if let Some((_, _, model, _)) = i.route {
103        (Some(model.to_string()), ModelSource::Route)
104    } else if let Some(m) = i.observed {
105        (Some(m.to_string()), ModelSource::Observed)
106    } else if let Some(m) = live.and_then(|e| e.effective_model.clone()) {
107        (Some(m), ModelSource::Effective)
108    } else if let Some(m) = live.and_then(|e| e.model.clone()).or_else(|| i.meta_model.map(str::to_string)) {
109        (Some(m), ModelSource::Requested)
110    } else {
111        (None, ModelSource::Unknown)
112    };
113    let label = match (i.route, &id) {
114        (Some((_, _, _, model_label)), _) => Some(model_label.to_string()),
115        (None, Some(m)) => Some(label_of(m)),
116        _ => None,
117    };
118    let why = (source == ModelSource::Unknown).then(|| {
119        if i.running { "its harness reports no model and none was asked for" } else { "no process is running and no model is on record" }.to_string()
120    });
121    let effort = live
122        .and_then(|e| e.effective_effort.clone().or_else(|| e.effort.clone()))
123        .or_else(|| i.meta_effort.map(str::to_string));
124    // What it was asked to run: its definition's `--model`, else the picker's choice (not while a switch to it waits
125    // for the end of the turn: the reply that stands is then the previous model's, and `pending_label` says so).
126    let waiting = i.event.is_some_and(|e| e.restart_pending);
127    let asked = i.definition_model.or(i.meta_model.filter(|_| !waiting)).filter(|m| !m.trim().is_empty());
128    let differs = source != ModelSource::Route && matches!((&id, asked), (Some(now), Some(asked)) if !same_model(now, asked));
129    // The model the change will run is what the pane now asks for (its meta); the event's `model` is what the
130    // running process was started with, which is the one being replaced.
131    let pending_label = i
132        .event
133        .filter(|e| e.restart_pending && source != ModelSource::Route)
134        .and(i.meta_model)
135        .filter(|asked| id.as_deref().is_none_or(|now| !same_model(now, asked)))
136        .map(label_of);
137    let definition_label = asked.filter(|_| differs).map(label_of);
138    ModelFacts {
139        id,
140        label,
141        source,
142        why,
143        effort,
144        pending_label,
145        definition_label,
146        pending_switch: i.event.is_some_and(|e| e.restart_pending),
147        route: i.route.map(|(id, label, _, _)| RouteFacts { id: id.to_string(), label: label.to_string() }),
148        differs_from_definition: differs,
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use crate::backend::agent_runtime::agent_runtime_event;
156
157    fn event(running: bool, model: Option<&str>, effective: Option<&str>, restart: bool) -> AgentRuntimeEvent {
158        let mut e = agent_runtime_event("b1", None, restart, None);
159        e.running = running;
160        e.model = model.map(str::to_string);
161        e.effective_model = effective.map(str::to_string);
162        e
163    }
164
165    #[test]
166    fn what_the_cli_reported_beats_what_was_asked_for_and_says_so() {
167        let e = event(true, Some("sonnet"), Some("claude-opus-5-5"), false);
168        let m = resolve(&Inputs { event: Some(&e), running: true, ..Default::default() });
169        assert_eq!((m.id.as_deref(), m.label.as_deref(), m.source), (Some("claude-opus-5-5"), Some("Opus 5.5"), ModelSource::Effective));
170    }
171
172    #[test]
173    fn the_model_a_reply_came_from_beats_what_the_cli_reports() {
174        // A container agent's CLI reports its settings (Sonnet) while its replies say they came from another model.
175        let e = event(true, Some("sonnet"), Some("claude-sonnet-5-5"), false);
176        let m = resolve(&Inputs { event: Some(&e), observed: Some("claude-fable-5-2"), running: true, ..Default::default() });
177        assert_eq!((m.id.as_deref(), m.label.as_deref(), m.source), (Some("claude-fable-5-2"), Some("Fable 5.2"), ModelSource::Observed));
178    }
179
180    #[test]
181    fn a_definition_that_pins_another_model_than_the_replies_shows_as_differing() {
182        let e = event(true, Some("sonnet"), Some("claude-sonnet-5-5"), false);
183        let m = resolve(&Inputs {
184            event: Some(&e),
185            observed: Some("claude-fable-5-2"),
186            definition_model: Some("sonnet"),
187            meta_model: Some("opus"),
188            running: true,
189            ..Default::default()
190        });
191        assert!(m.differs_from_definition, "the replies say fable, the definition pins sonnet");
192        assert_eq!(m.definition_label.as_deref(), Some("Sonnet"), "the model it was asked to run is the definition's, not the picker's");
193        let agrees = resolve(&Inputs { observed: Some("claude-sonnet-5-5"), definition_model: Some("sonnet"), running: true, ..Default::default() });
194        assert!(!agrees.differs_from_definition);
195    }
196
197    #[test]
198    fn with_no_pin_the_pickers_choice_is_what_it_was_asked_to_run() {
199        let m = resolve(&Inputs { observed: Some("claude-fable-5-2"), meta_model: Some("sonnet"), running: true, ..Default::default() });
200        assert!(m.differs_from_definition);
201        assert_eq!(m.definition_label.as_deref(), Some("Sonnet"));
202        let same = resolve(&Inputs { observed: Some("claude-sonnet-5-5"), meta_model: Some("sonnet"), running: true, ..Default::default() });
203        assert!(!same.differs_from_definition);
204        let blank = resolve(&Inputs { observed: Some("claude-sonnet-5-5"), meta_model: Some(" "), running: true, ..Default::default() });
205        assert!(!blank.differs_from_definition, "a picker that names no model asks for nothing");
206        // A switch waiting for the end of the turn: the reply that stands is the old model's, which is not a difference.
207        let e = event(true, Some("fable"), None, true);
208        let waiting = resolve(&Inputs { event: Some(&e), observed: Some("claude-fable-5-2"), meta_model: Some("sonnet"), running: true, ..Default::default() });
209        assert!(!waiting.differs_from_definition && waiting.pending_label.is_some());
210    }
211
212    #[test]
213    fn without_a_report_the_last_call_then_the_start_then_the_pane_s_memory_answer_in_that_order() {
214        let e = event(true, Some("sonnet"), None, false);
215        let observed = resolve(&Inputs { event: Some(&e), observed: Some("claude-sonnet-5-5"), running: true, ..Default::default() });
216        assert_eq!((observed.source, observed.id.as_deref()), (ModelSource::Observed, Some("claude-sonnet-5-5")));
217        let asked = resolve(&Inputs { event: Some(&e), running: true, ..Default::default() });
218        assert_eq!((asked.source, asked.label.as_deref()), (ModelSource::Requested, Some("Sonnet")));
219        let remembered = resolve(&Inputs { meta_model: Some("claude-opus-5-5"), ..Default::default() });
220        assert_eq!((remembered.source, remembered.label.as_deref()), (ModelSource::Requested, Some("Opus 5.5")));
221    }
222
223    #[test]
224    fn an_event_of_a_stopped_pane_reports_nothing_it_only_remembers() {
225        let stopped = event(false, Some("sonnet"), Some("claude-opus-5-5"), false);
226        let m = resolve(&Inputs { event: Some(&stopped), ..Default::default() });
227        assert_eq!((m.source, m.id.as_deref()), (ModelSource::Unknown, None));
228        assert!(m.why.unwrap().contains("no process"));
229        let alive = resolve(&Inputs { running: true, ..Default::default() });
230        assert!(alive.why.unwrap().contains("harness reports no model"));
231    }
232
233    #[test]
234    fn a_route_names_the_model_its_gateway_sends_to_and_is_never_a_difference() {
235        let e = event(true, Some("sonnet"), Some("claude-sonnet-5-5"), false);
236        let m = resolve(&Inputs {
237            event: Some(&e),
238            route: Some(("example", "Example route", "example-large", "Example Large")),
239            definition_model: Some("opus"),
240            running: true,
241            ..Default::default()
242        });
243        assert_eq!((m.source, m.id.as_deref(), m.label.as_deref()), (ModelSource::Route, Some("example-large"), Some("Example Large")));
244        assert_eq!(m.route, Some(RouteFacts { id: "example".into(), label: "Example route".into() }));
245        assert!(!m.differs_from_definition);
246    }
247
248    #[test]
249    fn a_model_that_is_not_the_definitions_is_marked_and_an_alias_of_it_is_not() {
250        let e = event(true, None, Some("claude-opus-5-5"), false);
251        let differs = resolve(&Inputs { event: Some(&e), definition_model: Some("sonnet"), running: true, ..Default::default() });
252        assert!(differs.differs_from_definition);
253        let same = resolve(&Inputs { event: Some(&e), definition_model: Some("opus"), running: true, ..Default::default() });
254        assert!(!same.differs_from_definition, "`opus` is the definition's name for claude-opus-5-5");
255        let none = resolve(&Inputs { event: Some(&e), running: true, ..Default::default() });
256        assert!(!none.differs_from_definition, "a definition that asks for nothing cannot differ");
257    }
258
259    #[test]
260    fn a_switch_waiting_for_the_end_of_the_turn_is_flagged_and_the_effort_follows_the_report() {
261        // The event's model is what the running process was started with (Sonnet); the model the change will run is
262        // what the pane now asks for (its meta), so that is the one named.
263        let mut e = event(true, Some("sonnet"), Some("claude-sonnet-5-5"), true);
264        e.effective_effort = Some("high".to_string());
265        e.effort = Some("low".to_string());
266        let m = resolve(&Inputs { event: Some(&e), meta_model: Some("opus"), running: true, ..Default::default() });
267        assert!(m.pending_switch);
268        assert_eq!(m.label.as_deref(), Some("Sonnet 5.5"), "what it runs now is unchanged until the switch applies");
269        assert_eq!(m.pending_label.as_deref(), Some("Opus"), "the model the change will run, by its short name");
270        let effort_only = resolve(&Inputs { event: Some(&e), meta_model: Some("sonnet"), running: true, ..Default::default() });
271        assert!(effort_only.pending_switch && effort_only.pending_label.is_none(), "an effort change names no model");
272        let nothing_asked = resolve(&Inputs { event: Some(&e), running: true, ..Default::default() });
273        assert!(nothing_asked.pending_switch && nothing_asked.pending_label.is_none());
274        let applied = event(true, Some("opus"), Some("claude-opus-5-5"), false);
275        let done = resolve(&Inputs { event: Some(&applied), meta_model: Some("opus"), running: true, ..Default::default() });
276        assert!(!done.pending_switch && done.pending_label.is_none(), "once the switch applies nothing is pending");
277        let routed = resolve(&Inputs {
278            event: Some(&e),
279            route: Some(("example", "Example route", "example-large", "Example Large")),
280            meta_model: Some("opus"),
281            running: true,
282            ..Default::default()
283        });
284        assert!(routed.pending_label.is_none(), "an agent on a route runs the route's model whatever its pane asks for");
285        let named = resolve(&Inputs { event: Some(&e), definition_model: Some("haiku"), running: true, ..Default::default() });
286        assert_eq!(named.definition_label.as_deref(), Some("Haiku"));
287        assert_eq!(m.definition_label, None);
288        assert_eq!(m.effort.as_deref(), Some("high"), "the effective effort wins over the requested one");
289        let remembered = resolve(&Inputs { meta_effort: Some("medium"), ..Default::default() });
290        assert_eq!(remembered.effort.as_deref(), Some("medium"));
291    }
292}