Skip to main content

agentmux_srv/server/app_api/
agent_runtime_pick.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `model` and `effort` of `Agents update` for a Claude agent that is not on a model route: the same runtime choice the pane's
5//! picker makes (the Runtime menu, `/model`, `/effort`; `frontend/app/view/agent/runtime-apply.ts`), by an agent, on
6//! this machine or on another (`host`).
7//!
8//! It writes what the picker writes: `agent:runtime` on each of the agent's panes, `cmd:args` without its own `--model` and
9//! `--effort` (the next launch builds them from the runtime: `agent_runtime::with_runtime_flags`), and the agent's
10//! remembered runtime, so a closed agent opens on it. Then the agent's persistent panes restart at the end of their turn,
11//! with their conversation; a one-shot pane (a container agent's) takes it at its next turn.
12//!
13//! What it does not do: change a model the definition's own provider flags fix (the operator's, in My Agents), or an agent
14//! pointed at a model server of its own (its model is `ANTHROPIC_MODEL` in its environment, `Agents env_set`).
15
16use axum::http::StatusCode;
17use serde_json::{json, Value};
18
19use super::agent_lifecycle::{refuse, Refusal};
20use crate::backend::agent_runtime;
21use crate::backend::obj::MetaMapType;
22use crate::backend::storage::AgentDefinition;
23use crate::server::state::AppState;
24
25fn bad(message: impl Into<String>) -> Refusal {
26    refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: {}", message.into()))
27}
28
29/// What a pick did, for the answer.
30pub(super) struct Picked {
31    pub(super) model: Option<String>,
32    pub(super) effort: Option<String>,
33    pub(super) panes: usize,
34    pub(super) restarted: u32,
35    pub(super) next_turn: u32,
36    pub(super) failed: Vec<String>,
37}
38
39impl Picked {
40    /// The answer's `applied` object.
41    pub(super) fn to_json(&self) -> Value {
42        let when = if self.panes == 0 {
43            "the agent has no pane open: it opens on this choice"
44        } else if self.restarted > 0 {
45            "its pane restarts at the end of the turn it is in, with its conversation; no fresh session is needed"
46        } else {
47            "it applies at the agent's next turn; no restart is needed"
48        };
49        json!({
50            "model": self.model,
51            "effort": self.effort,
52            "panes": self.panes,
53            "restarting": self.restarted,
54            "applies_at_next_turn": self.next_turn,
55            "not_restarted": self.failed,
56            "when": when,
57        })
58    }
59}
60
61/// Why this agent cannot be given the pick: only a Claude agent takes it (Codex's model is its pane's picker's, and
62/// its remembered runtime is not read at launch).
63fn check_harness(state: &AppState, agent: &AgentDefinition) -> Result<(), Refusal> {
64    let harness = state.id_store.resolve_effective_provider_id(agent);
65    match crate::backend::providers::resolve_provider_alias(&harness) {
66        "claude" => Ok(()),
67        other => Err(bad(format!(
68            "Agents update model and effort are for Claude agents, and this agent runs {}: its model is chosen in its own pane's picker",
69            if other.is_empty() { harness.as_str() } else { other }
70        ))),
71    }
72}
73
74/// Whether `model` can be given to a Claude agent, by name.
75fn check_model(model: &str) -> Result<(), Refusal> {
76    if agent_runtime::is_claude_model_name(model) {
77        return Ok(());
78    }
79    Err(bad(format!("{model} is not a Claude model: use sonnet, opus, haiku or a model id such as claude-fable-5-2 (a model on a model route needs the agent on that route, which the person approves)")))
80}
81
82const OWN_SERVER: &str =
83    "the agent is pointed at a model server of its own, which it asks for the model ANTHROPIC_MODEL names: change that with Agents env_set";
84
85/// Whether the definition itself points the agent at a server of its own, with a pane open or not: its saved
86/// environment and its structured model vendor URL are what the next launch builds from.
87fn definition_points_at_own_server(state: &AppState, agent: &AgentDefinition) -> Result<bool, Refusal> {
88    let text = state
89        .mstore
90        .agent_content_get(&agent.id, crate::backend::agent_env::CONTENT_TYPE)
91        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents update: {e}")))?
92        .map(|c| c.content)
93        .unwrap_or_default();
94    Ok(crate::backend::agent_env::points_at_own_server_with(&text, &agent.model_vendor_base_url))
95}
96
97const PINNED: &str = "the agent's definition carries its own --model or --effort in its provider flags: the operator changes it in My Agents";
98
99/// Why this pane cannot take the pick, or none.
100fn pane_refusal(meta: &MetaMapType, model: Option<&str>, effort: Option<&str>) -> Option<String> {
101    let (pins_model, pins_effort) = agent_runtime::provider_flags_pin(meta);
102    if model.is_some() && pins_model {
103        return Some(PINNED.to_string());
104    }
105    if effort.is_some() && pins_effort {
106        return Some(PINNED.to_string());
107    }
108    if model.is_some() && agent_runtime::endpoint_model(meta).is_some() {
109        return Some(OWN_SERVER.to_string());
110    }
111    None
112}
113
114/// The agent's remembered runtime with `model` and `effort` laid over it.
115fn remembered_with(state: &AppState, agent: &AgentDefinition, model: Option<&str>, effort: Option<&str>) -> Result<String, Refusal> {
116    let internal = |e: String| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents update: {e}"));
117    let current = state.mstore.agent_last_runtime_get(&agent.id).map_err(|e| internal(e.to_string()))?;
118    let mut remembered = serde_json::from_str::<Value>(&current).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default();
119    for (key, value) in [("model", model), ("effort", effort)] {
120        if let Some(value) = value {
121            remembered.insert(key.to_string(), json!(value));
122        }
123    }
124    crate::backend::storage::agents::normalize_last_runtime(&Value::Object(remembered).to_string()).map_err(internal)
125}
126
127/// Make the pick. Everything is checked before anything is written.
128pub(super) fn pick(state: &AppState, agent: &AgentDefinition, model: Option<&str>, effort: Option<&str>) -> Result<Picked, Refusal> {
129    check_harness(state, agent)?;
130    if let Some(model) = model {
131        check_model(model)?;
132    }
133    if let Some(effort) = effort.filter(|e| !agent_runtime::is_claude_effort(e)) {
134        return Err(bad(format!("{effort} is not an effort: low, medium, high, xhigh or max")));
135    }
136    // The definition's own flags count with no pane open too: the launch would put the remembered choice over them.
137    let (pins_model, pins_effort) = agent_runtime::flags_pin(&agent.provider_flags);
138    if (model.is_some() && pins_model) || (effort.is_some() && pins_effort) {
139        return Err(bad(PINNED));
140    }
141    if model.is_some() && definition_points_at_own_server(state, agent)? {
142        return Err(bad(OWN_SERVER));
143    }
144    let panes = crate::server::account_episodes::panes_of(state, &agent.id);
145    if let Some(why) = panes.iter().find_map(|b| pane_refusal(&b.meta, model, effort)) {
146        return Err(bad(why));
147    }
148    let remembered = remembered_with(state, agent, model, effort)?;
149    for pane in &panes {
150        let (_, pins_effort) = agent_runtime::provider_flags_pin(&pane.meta);
151        let choice = agent_runtime::runtime_choice(&pane.meta, model, effort, pins_effort);
152        let mut updates = vec![("agent:runtime", choice.runtime)];
153        if let Some(args) = choice.cli_args {
154            updates.push(("cmd:args", json!(args)));
155        }
156        crate::server::prep::set_block_meta(state, &[pane.oid.as_str()], &updates);
157    }
158    state
159        .mstore
160        .agent_last_runtime_set(&agent.id, &remembered)
161        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents update: {e}")))?;
162    let (restarted, next_turn, failed) = crate::server::account_episodes::restart_panes_of(state, &agent.id);
163    for why in &failed {
164        tracing::warn!(agent = %agent.slug, why, "Agents update: a pane was not restarted on the new runtime");
165    }
166    Ok(Picked { model: model.map(str::to_string), effort: effort.map(str::to_string), panes: panes.len(), restarted, next_turn, failed })
167}