Skip to main content

agentmux_srv_core/backend/
subagent_model.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which model a Claude agent's sub-agents run on
5//! (`docs/specs/SPEC_SUBAGENT_MODELS_2026_10_25.md`).
6//!
7//! Sub-agents were about a quarter of the fleet's spend and almost all of
8//! their calls ran on the biggest model, because a sub-agent inherits its
9//! parent's model. Measured on Claude Code 2.1.288:
10//!
11//! - `CLAUDE_CODE_SUBAGENT_MODEL` moves **general-purpose** sub-agents (and
12//!   custom ones with no model of their own). It is set at spawn from
13//!   [`SETTING_SUBAGENT`], or the pane's own [`META_SUBAGENT`]. Without
14//!   `..._FORCE`, an agent's own `model:` and the `model` its parent passes
15//!   per call still win, so a leader can send a hard question to Opus.
16//! - **Explore** and **Plan** ignore it and stay on the parent's model.
17//!   Explore is moved by a user-level agent definition named `Explore` in the
18//!   Claude config dir, which beats the built-in: AgentMux writes one
19//!   ([`seed_explore_agent`]) from [`SETTING_EXPLORE`] and removes it again
20//!   when the setting says `inherit`. One a person wrote is left alone.
21
22use std::collections::HashMap;
23use std::io;
24use std::path::Path;
25
26use crate::backend::obj::{meta_get_string, MetaMapType};
27
28/// `agent:subagentmodel`: the model for general-purpose sub-agents.
29pub const SETTING_SUBAGENT: &str = "agent:subagentmodel";
30pub const DEFAULT_SUBAGENT_MODEL: &str = "sonnet";
31/// `agent:exploremodel`: the model for Explore sub-agents.
32pub const SETTING_EXPLORE: &str = "agent:exploremodel";
33pub const DEFAULT_EXPLORE_MODEL: &str = "haiku";
34/// Block meta that overrides [`SETTING_SUBAGENT`] for one agent.
35pub const META_SUBAGENT: &str = "agent:subagentmodel";
36const ENV_KEY: &str = "CLAUDE_CODE_SUBAGENT_MODEL";
37/// First line of the body of the Explore definition AgentMux wrote.
38const MANAGED_MARK: &str = "<!-- agentmux-managed: replaced from the agent:exploremodel setting; set it to inherit to remove -->";
39
40/// The model a value names: an alias (`sonnet`, `haiku`, `opus`) or a model
41/// ID. `None` for an empty value, for `inherit` (and its synonyms, which mean
42/// "don't set one"), and for text that couldn't be a model name.
43fn named(value: &str) -> Option<Option<String>> {
44    let v = value.trim();
45    if v.is_empty() {
46        return None;
47    }
48    if matches!(v.to_ascii_lowercase().as_str(), "inherit" | "default" | "none" | "off") {
49        return Some(None);
50    }
51    let ok = v.len() <= 64
52        && v.chars().next().is_some_and(|c| c.is_ascii_alphanumeric())
53        && v.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '[' | ']'));
54    ok.then(|| Some(v.to_string()))
55}
56
57/// The model to set, the first level that says something: the pane's own,
58/// then the setting, then the default. `None` when it says `inherit`.
59pub fn resolve(per_agent: &str, setting: &str, default: &str) -> Option<String> {
60    named(per_agent).or_else(|| named(setting)).or_else(|| named(default)).flatten()
61}
62
63/// Add `CLAUDE_CODE_SUBAGENT_MODEL` to a Claude agent's spawn environment,
64/// unless its `cmd:env` already sets one. Not for other providers.
65pub fn carry(env_vars: &mut HashMap<String, String>, block_meta: &MetaMapType) {
66    let provider = meta_get_string(block_meta, "agentProvider", "claude");
67    let is_claude = provider.trim().is_empty() || crate::backend::providers::resolve_provider_alias(&provider) == "claude";
68    if !is_claude || env_vars.contains_key(ENV_KEY) {
69        return;
70    }
71    let setting = crate::backend::providers::live_setting_str(SETTING_SUBAGENT).unwrap_or_default();
72    if let Some(model) = resolve(&meta_get_string(block_meta, META_SUBAGENT, ""), &setting, DEFAULT_SUBAGENT_MODEL) {
73        env_vars.insert(ENV_KEY.to_string(), model);
74    }
75}
76
77/// [`SETTING_EXPLORE`] now, resolved: the model to write, or `None` for none.
78pub fn explore_model() -> Option<String> {
79    resolve("", &crate::backend::providers::live_setting_str(SETTING_EXPLORE).unwrap_or_default(), DEFAULT_EXPLORE_MODEL)
80}
81
82fn explore_definition(model: &str) -> String {
83    format!(
84        "---\nname: Explore\ndescription: Fast, read-only agent for searching and reading files and code. Use it to find where something is or how it works; it can't edit anything. Say how thorough to be: quick, medium or very thorough.\nmodel: {model}\ntools: Read, Glob, Grep, Bash\n---\n{MANAGED_MARK}\n\
85         You are a search specialist. You only read: never create, edit, move or delete files, and run only commands that read (ls, cat, git log, git diff, git show, grep). \
86         Find what you were asked for, start broad and narrow down, and look in more than one place when the first doesn't settle it. \
87         Report what you found with absolute file paths and line numbers, briefly, and say what you did not find.\n"
88    )
89}
90
91/// Write, or remove, the Explore definition in `config_dir`'s `agents/`
92/// folder for `model` (`None` removes AgentMux's own). Leaves one a person
93/// wrote. Returns whether the file changed.
94pub fn seed_explore_agent(config_dir: &str, model: Option<&str>) -> io::Result<bool> {
95    let path = Path::new(config_dir).join("agents").join("Explore.md");
96    let existing = std::fs::read_to_string(&path).ok();
97    if existing.as_deref().is_some_and(|t| !t.contains(MANAGED_MARK)) {
98        return Ok(false);
99    }
100    match model {
101        None => {
102            if existing.is_none() {
103                return Ok(false);
104            }
105            std::fs::remove_file(&path)?;
106            Ok(true)
107        }
108        Some(model) => {
109            let wanted = explore_definition(model);
110            if existing.as_deref() == Some(wanted.as_str()) {
111                return Ok(false);
112            }
113            std::fs::create_dir_all(path.parent().expect("a file path has a parent"))?;
114            let tmp = path.with_extension("md.tmp");
115            std::fs::write(&tmp, wanted)?;
116            std::fs::rename(&tmp, &path)?;
117            Ok(true)
118        }
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn the_first_level_that_says_something_wins() {
128        assert_eq!(resolve("", "", "sonnet").as_deref(), Some("sonnet"), "the default");
129        assert_eq!(resolve("", "opus", "sonnet").as_deref(), Some("opus"), "the setting over the default");
130        assert_eq!(resolve("haiku", "opus", "sonnet").as_deref(), Some("haiku"), "the pane over the setting");
131        assert_eq!(resolve("", "inherit", "sonnet"), None, "inherit sets nothing");
132        assert_eq!(resolve("Off", "opus", "sonnet"), None, "a pane can turn it off");
133        assert_eq!(resolve("", "claude-opus-5-5", "sonnet").as_deref(), Some("claude-opus-5-5"), "a model ID");
134        assert_eq!(resolve("", "opus; rm -rf", "sonnet").as_deref(), Some("sonnet"), "not a model name: skipped");
135    }
136
137    fn meta(provider: Option<&str>, model: Option<&str>) -> MetaMapType {
138        let mut m = MetaMapType::new();
139        if let Some(p) = provider {
140            m.insert("agentProvider".into(), serde_json::json!(p));
141        }
142        if let Some(v) = model {
143            m.insert(META_SUBAGENT.into(), serde_json::json!(v));
144        }
145        m
146    }
147
148    #[test]
149    fn a_claude_agent_gets_the_model_and_nothing_else_does() {
150        let mut env = HashMap::new();
151        carry(&mut env, &meta(Some("claude"), None));
152        assert_eq!(env.get(ENV_KEY).map(String::as_str), Some("sonnet"));
153        let mut env = HashMap::new();
154        carry(&mut env, &meta(None, Some("opus")));
155        assert_eq!(env.get(ENV_KEY).map(String::as_str), Some("opus"), "an unset provider is Claude; the pane's value wins");
156        let mut env = HashMap::new();
157        carry(&mut env, &meta(Some("codex"), None));
158        assert!(env.is_empty(), "other providers are left alone");
159        let mut env = HashMap::from([(ENV_KEY.to_string(), "haiku".to_string())]);
160        carry(&mut env, &meta(Some("claude"), Some("opus")));
161        assert_eq!(env.get(ENV_KEY).map(String::as_str), Some("haiku"), "an explicit cmd:env wins");
162        let mut env = HashMap::new();
163        carry(&mut env, &meta(Some("claude"), Some("inherit")));
164        assert!(env.is_empty(), "inherit sets none");
165    }
166
167    #[test]
168    fn the_explore_definition_follows_the_setting_and_never_replaces_a_persons() {
169        let dir = tempfile::tempdir().unwrap();
170        let cfg = dir.path().to_str().unwrap();
171        let file = dir.path().join("agents").join("Explore.md");
172
173        assert!(seed_explore_agent(cfg, Some("haiku")).unwrap());
174        let text = std::fs::read_to_string(&file).unwrap();
175        assert!(text.contains("name: Explore") && text.contains("model: haiku") && text.contains(MANAGED_MARK));
176        assert!(!seed_explore_agent(cfg, Some("haiku")).unwrap(), "unchanged: no write");
177        assert!(seed_explore_agent(cfg, Some("sonnet")).unwrap());
178        assert!(std::fs::read_to_string(&file).unwrap().contains("model: sonnet"), "follows the setting");
179        assert!(seed_explore_agent(cfg, None).unwrap(), "inherit removes AgentMux's own");
180        assert!(!file.exists());
181        assert!(!seed_explore_agent(cfg, None).unwrap(), "nothing to remove");
182
183        std::fs::create_dir_all(file.parent().unwrap()).unwrap();
184        std::fs::write(&file, "---\nname: Explore\nmodel: opus\n---\nmine\n").unwrap();
185        assert!(!seed_explore_agent(cfg, Some("haiku")).unwrap());
186        assert!(!seed_explore_agent(cfg, None).unwrap());
187        assert_eq!(std::fs::read_to_string(&file).unwrap(), "---\nname: Explore\nmodel: opus\n---\nmine\n", "a person's is untouched");
188    }
189}