Skip to main content

trusty_code/provider/
routing.rs

1//! Per-agent model routing precedence.
2//!
3//! Why: A model can be specified in three places — the per-call [`RunContext`],
4//! the agent's TOML config (`[agent].model` or `[llm].model_override`), and a
5//! built-in default. The orchestrator needs one authoritative function that
6//! resolves these to a single slug so every call site agrees on precedence
7//! (#1021).
8//! What: [`resolve_model`] implements the precedence ladder and
9//! [`DEFAULT_MODEL`] names the fallback slug.
10//! Test: `routing::tests::*`.
11
12use crate::agents::AgentConfig;
13use crate::tools::RunContext;
14
15/// Default model slug when nothing else is specified.
16///
17/// Why (#7955): the former default, `openai/gpt-4o-mini`, is rejected with a
18/// `404 zdr-violation-by-guardrail` by any OpenRouter account with the
19/// zero-data-retention (ZDR) guardrail enabled — every unpinned `run-task`
20/// and the ignored `agent_loop_live` smoke failed identically at the first
21/// chat call. The default tracks whatever [`normalize_model_alias`]'s
22/// `"sonnet"` alias resolves to, so an unpinned run and a `--pm-model sonnet`
23/// run always reach the same provider slug.
24/// What: The OpenRouter slug for Claude Sonnet 5.
25/// Test: `routing::tests::resolve_model_falls_back_to_default`,
26/// `routing::tests::default_model_matches_the_sonnet_alias`.
27// #8128: retargeted from `anthropic/claude-sonnet-4.5` to the Claude 5 tier
28// Claude Code itself now runs; slug read from `GET
29// https://openrouter.ai/api/v1/models`.
30pub const DEFAULT_MODEL: &str = "anthropic/claude-sonnet-5";
31
32/// Default per-turn completion token cap when `[llm].max_tokens` is unset.
33///
34/// Why: A turn cap must always resolve to *some* value, and it must be large
35/// enough for a real tool-calling turn (e.g. `write_file` emitting a whole
36/// source file) to complete without truncation — the bug this constant fixes
37/// was every turn silently capped at 1024 regardless of agent config,
38/// truncating real writes. 8192 is generous enough for typical file writes
39/// while still bounding a single turn's cost.
40/// What: The fallback completion-token cap used by [`resolve_max_tokens`].
41/// Test: `routing::tests::resolve_max_tokens_falls_back_to_default`.
42pub const DEFAULT_MAX_TOKENS: u32 = 8192;
43
44/// Environment variable overriding the `run-task` wall-clock deadline (#2207).
45///
46/// Why: Lets an operator (or the M3 bake-off runner) raise the deadline for a
47/// whole invocation without a CLI flag at every call site — mirrors
48/// `crate::mode::MODE_ENV_VAR`'s "escape hatch" precedent for a small, direct
49/// `std::env` read in production code.
50/// What: Read by [`resolve_deadline_secs`] as the middle precedence tier.
51/// Test: `routing::tests::resolve_deadline_secs_*`.
52pub const RUN_DEADLINE_ENV_VAR: &str = "TCODE_RUN_DEADLINE_SECONDS";
53
54/// Generous default wall-clock deadline for a `run-task` invocation, in
55/// seconds, when neither a CLI override nor [`RUN_DEADLINE_ENV_VAR`] is set.
56///
57/// Why: The AgentLoop's own built-in default (120s, `crate::agent_loop::AgentLoopConfig::default`)
58/// is tuned for a short interactive turn, not a full PM->engineer run-task
59/// invocation — #2207 found that cap cutting off a real, otherwise-successful
60/// task at turn 13 before it reached `finish_task`. 30 minutes is generous
61/// enough for the M3 bake-off's L1 pilot to complete cleanly while L2/L3 (1-3
62/// hour problems) can still raise it further via the flag/env override.
63/// What: The fallback tier of [`resolve_deadline_secs`].
64/// Test: `routing::tests::resolve_deadline_secs_falls_back_to_default`.
65pub const DEFAULT_RUN_DEADLINE_SECS: u64 = 1800;
66
67/// Resolve the wall-clock deadline (in seconds) for a `run-task` invocation.
68///
69/// Why: #2207 — the AgentLoop's built-in 120s timeout is too tight for a real
70/// PM->engineer run-task on anything but a trivial task, cutting off
71/// otherwise-successful runs before they reach `finish_task`. A single
72/// resolver mirrors [`resolve_model`]/[`resolve_max_tokens`]'s precedence-
73/// ladder pattern so every call site (the CLI's legacy in-process path, the
74/// daemon's `task.run`, and the in-process sub-agent runner) agrees.
75/// What: Returns, in priority order, the first of: (1) `cli_override` (the
76/// `run-task --timeout-seconds`/`task.run` `deadline_secs` request param,
77/// threaded in by the caller), (2) [`RUN_DEADLINE_ENV_VAR`] parsed as a `u64`
78/// (an unparseable value is treated as absent, falling through — logged at
79/// `warn` — rather than erroring the whole run), else (3)
80/// [`DEFAULT_RUN_DEADLINE_SECS`].
81/// Test: `routing::tests::resolve_deadline_secs_cli_override_wins`,
82/// `routing::tests::resolve_deadline_secs_env_wins_over_default`,
83/// `routing::tests::resolve_deadline_secs_invalid_env_falls_back_to_default`,
84/// `routing::tests::resolve_deadline_secs_falls_back_to_default`.
85pub fn resolve_deadline_secs(cli_override: Option<u64>) -> u64 {
86    if let Some(secs) = cli_override {
87        return secs;
88    }
89
90    if let Ok(raw) = std::env::var(RUN_DEADLINE_ENV_VAR) {
91        match raw.trim().parse::<u64>() {
92            Ok(secs) => return secs,
93            Err(e) => {
94                tracing::warn!(
95                    "{RUN_DEADLINE_ENV_VAR}={raw:?} is not a valid u64 ({e}); \
96                     falling back to DEFAULT_RUN_DEADLINE_SECS"
97                );
98            }
99        }
100    }
101
102    DEFAULT_RUN_DEADLINE_SECS
103}
104
105/// Short Claude model aliases (`opus`/`sonnet`/`haiku`) mapped to a concrete,
106/// provider-valid OpenRouter slug (#3438).
107///
108/// Why: these three bare words are the `claude` CLI's own `--model` shorthand
109/// (see `trusty_agents_common::agents::builder::tier_to_model`, which composes
110/// them from an agent's `resource_tier`, and every embedded roster agent's
111/// `.md` frontmatter — e.g. `assets/agents/python-engineer.md`'s
112/// `model: sonnet`) — valid input for the `claude` subprocess trusty-agents
113/// spawns, but NOT a real OpenRouter/Anthropic-API model id. trusty-code talks
114/// to providers directly (`llm::client::OpenAiCompatClient`), so a bare alias
115/// reaching the wire produces `API error 400: "opus is not a valid model ID"`
116/// verbatim — the exact failure #3438 traced. [`resolve_model`] is the single
117/// funnel every call site resolves its final slug through
118/// (`runner::in_process::InProcessAgentRunner::run_pipeline`,
119/// `task::executor`, `run_task::execute_run_task`), so normalising here fixes
120/// every path at once rather than patching each `.md` file or call site
121/// individually.
122/// What: Case-insensitive exact match on the trimmed slug; anything else
123/// (an already-concrete slug, a routed `bedrock/`/`fireworks/`/etc. prefix, an
124/// unrecognised alias) passes through unchanged — [`resolve_model`] never
125/// errors on an unmapped model, it just doesn't rewrite it.
126/// Test: `routing::tests::normalize_model_alias_maps_short_aliases`,
127/// `routing::tests::normalize_model_alias_passes_through_concrete_slugs`,
128/// `assets::tests::every_embedded_agent_model_normalizes_to_a_valid_slug`.
129// #8128: the three targets track Claude Code's CURRENT tiers (opus 5 /
130// sonnet 5 / haiku 4.5, the newest Haiku OpenRouter serves), not the 4.5
131// generation they were pinned to. Each slug was read from `GET
132// https://openrouter.ai/api/v1/models`, never composed by hand.
133fn normalize_model_alias(model: &str) -> &str {
134    match model.trim().to_ascii_lowercase().as_str() {
135        "opus" => "anthropic/claude-opus-5",
136        "sonnet" => "anthropic/claude-sonnet-5",
137        "haiku" => "anthropic/claude-haiku-4.5",
138        _ => model,
139    }
140}
141
142/// Resolve the model slug for an invocation.
143///
144/// Why: Centralises the precedence so per-call overrides, per-agent config, and
145/// the global default never disagree across call sites.
146/// What: Returns, in priority order, the first non-empty of:
147/// (1) `run_context.model` (per-call override),
148/// (2) `agent_config.agent.model`,
149/// (3) `agent_config.llm.model_override`,
150/// else (4) [`DEFAULT_MODEL`] — each candidate passed through
151/// [`normalize_model_alias`] (#3438) so a bare `opus`/`sonnet`/`haiku` alias
152/// never reaches a provider as-is.
153/// Test: `routing::tests::resolve_model_*` cover every tier;
154/// `routing::tests::resolve_model_normalizes_short_alias_from_agent_config`
155/// and `resolve_model_normalizes_short_alias_from_run_context` cover #3438.
156pub fn resolve_model(agent_config: &AgentConfig, run_context: Option<&RunContext>) -> String {
157    // 1. Per-call override wins.
158    if let Some(ctx) = run_context
159        && let Some(model) = non_empty(ctx.model.as_deref())
160    {
161        return normalize_model_alias(model).to_string();
162    }
163
164    // 2. Agent-level model.
165    if let Some(model) = non_empty(agent_config.agent.model.as_deref()) {
166        return normalize_model_alias(model).to_string();
167    }
168
169    // 3. `[llm].model_override` (lower precedence than `[agent].model`).
170    if let Some(model) = non_empty(agent_config.llm.model_override.as_deref()) {
171        return normalize_model_alias(model).to_string();
172    }
173
174    // 4. Built-in default.
175    DEFAULT_MODEL.to_string()
176}
177
178/// Environment variable overriding the TOP-LEVEL (PM) agent's model (#8030).
179///
180/// Why: `--engineer-model`/`TCODE_ENGINEER_MODEL` only rewire the
181/// DELEGATED runner, so the top-level agent's own calls could be repointed
182/// only by hand-editing the deployed `.trusty-code/agents/<agent>.md` — the
183/// concrete failure #8030 records is `--engineer-model` set to a ZDR-safe
184/// slug while the PM's own calls still 404'd on the old default.
185/// What: The middle precedence tier of [`resolve_pm_model_override`], below
186/// the `--pm-model` flag and above the agent's front-matter `model:`.
187/// Test: `routing::tests::resolve_pm_model_override_env_wins_over_nothing`,
188/// `routing::tests::resolve_pm_model_override_flag_wins_over_env`.
189pub const PM_MODEL_ENV_VAR: &str = "TCODE_PM_MODEL";
190
191/// Environment variable overriding the PM loop's turn cap (#8128).
192///
193/// Why: a bake-off/parity run against Claude Code's tiers needs a turn cap
194/// bigger than [`crate::agent_loop::AgentLoopConfig`]'s built-in 8 for a
195/// multi-step delivery task, and an env var raises it for a whole invocation
196/// without a flag at every call site — the same escape-hatch precedent
197/// [`RUN_DEADLINE_ENV_VAR`] sets.
198/// What: The middle precedence tier of [`resolve_max_turns`].
199/// Test: `routing::tests::resolve_max_turns_env_wins_over_default`,
200/// `routing::tests::resolve_max_turns_rejects_zero_from_env`.
201pub const MAX_TURNS_ENV_VAR: &str = "TCODE_MAX_TURNS";
202
203/// Resolve the TOP-LEVEL (PM) agent's model override for one invocation.
204///
205/// Why (#8030): the top-level agent's model had no CLI/env override at all —
206/// `resolve_model(&pm_config, None)` went straight to the agent's front
207/// matter. This is the missing first tier, shaped exactly like the engineer's
208/// so one precedence story covers both halves of a run.
209/// What: Returns the first non-blank of (1) `cli_override` (the `--pm-model`
210/// flag or `task.run`'s `pm_model` field), (2) [`PM_MODEL_ENV_VAR`]. `None`
211/// means "no override" and leaves [`resolve_model`]'s own ladder (front
212/// matter, then [`DEFAULT_MODEL`]) untouched. The returned value is NOT
213/// normalised here — [`resolve_model_with_override`] runs it through
214/// [`normalize_model_alias`] at the point of use, so `--pm-model opus`
215/// behaves exactly like `--engineer-model opus`.
216/// Test: `routing::tests::resolve_pm_model_override_flag_wins_over_env`,
217/// `routing::tests::resolve_pm_model_override_env_wins_over_nothing`,
218/// `routing::tests::resolve_pm_model_override_blank_is_absent`.
219pub fn resolve_pm_model_override(cli_override: Option<String>) -> Option<String> {
220    if let Some(model) = cli_override.filter(|s| !s.trim().is_empty()) {
221        return Some(model);
222    }
223    std::env::var(PM_MODEL_ENV_VAR)
224        .ok()
225        .filter(|s| !s.trim().is_empty())
226}
227
228/// Resolve a model slug with an explicit per-run override ahead of the agent
229/// config (#8030).
230///
231/// Why: every top-level call site reads `resolve_model(&cfg, None)`, and
232/// threading a synthetic [`RunContext`] through each one purely to carry a
233/// CLI flag would restate a whole tool-call context to express one string.
234/// What: `override_model`, when non-blank, wins and is passed through
235/// [`normalize_model_alias`]; otherwise this is exactly
236/// `resolve_model(agent_config, None)`.
237/// Test: `routing::tests::resolve_model_with_override_wins_over_agent_config`,
238/// `routing::tests::resolve_model_with_override_normalizes_short_alias`,
239/// `routing::tests::resolve_model_with_override_absent_matches_resolve_model`.
240pub fn resolve_model_with_override(
241    agent_config: &AgentConfig,
242    override_model: Option<&str>,
243) -> String {
244    if let Some(model) = non_empty(override_model) {
245        return normalize_model_alias(model).to_string();
246    }
247    resolve_model(agent_config, None)
248}
249
250/// Resolve the PM loop's turn-cap override for one invocation (#8128).
251///
252/// Why: `run_task`/`task::executor` never overrode
253/// [`crate::agent_loop::AgentLoopConfig`]'s `max_turns: 8`, so a multi-step
254/// delivery task could not be given more turns without a rebuild.
255/// What: Returns the first of (1) `cli_override` (`--max-turns` /
256/// `task.run`'s `max_turns`), (2) [`MAX_TURNS_ENV_VAR`] parsed as a `u32`,
257/// else `Ok(None)` — "no override", which leaves the loop's own default in
258/// place so absent behaviour is unchanged. A zero from EITHER source is an
259/// `Err`: a zero-turn loop makes no LLM call at all and would report an
260/// empty run as a normal one. An unparseable env value is treated as absent
261/// (logged at `warn`), matching [`resolve_deadline_secs`].
262/// Test: `routing::tests::resolve_max_turns_flag_wins_over_env`,
263/// `routing::tests::resolve_max_turns_env_wins_over_default`,
264/// `routing::tests::resolve_max_turns_rejects_zero_from_flag`,
265/// `routing::tests::resolve_max_turns_rejects_zero_from_env`,
266/// `routing::tests::resolve_max_turns_invalid_env_falls_back_to_default`.
267pub fn resolve_max_turns(cli_override: Option<u32>) -> Result<Option<u32>, String> {
268    if let Some(turns) = cli_override {
269        if turns == 0 {
270            return Err("--max-turns must be at least 1 (0 would run no turns at all)".to_string());
271        }
272        return Ok(Some(turns));
273    }
274
275    if let Ok(raw) = std::env::var(MAX_TURNS_ENV_VAR) {
276        match raw.trim().parse::<u32>() {
277            Ok(0) => {
278                return Err(format!(
279                    "{MAX_TURNS_ENV_VAR}=0 is invalid: the turn cap must be at least 1 \
280                     (0 would run no turns at all)"
281                ));
282            }
283            Ok(turns) => return Ok(Some(turns)),
284            Err(e) => {
285                tracing::warn!(
286                    "{MAX_TURNS_ENV_VAR}={raw:?} is not a valid u32 ({e}); \
287                     falling back to the loop's built-in turn cap"
288                );
289            }
290        }
291    }
292
293    Ok(None)
294}
295
296/// Fallback context-window size (in tokens) for a model slug this resolver
297/// does not recognise.
298///
299/// Why: [`resolve_context_window`] must always return a usable number even
300/// for an unlisted/unknown slug (a new provider, a typo'd override, etc.) —
301/// 128,000 is a conservative, widely-supported floor shared by several
302/// mainstream hosted models (e.g. `gpt-4o`), so an unknown model is treated
303/// no more generously than that.
304/// What: The fallback tier of [`resolve_context_window`].
305/// Test: `routing::tests::resolve_context_window_falls_back_to_default_for_unknown_model`.
306pub const DEFAULT_CONTEXT_WINDOW: usize = 128_000;
307
308/// Resolve the real context-window size (in tokens) for a model slug.
309///
310/// Why: #2308 — `CompactionConfig::default()`'s flat `token_threshold: 6_000`
311/// is model-blind: ~3% of Bedrock Claude Sonnet's real 200K-token window, so
312/// ordinary coding turns (post-#2261 tool-call-arg counting) blow through it
313/// constantly and trigger pathological re-compaction. Compaction must instead
314/// scale with the model actually in use, which means a resolver is needed
315/// alongside [`resolve_model`] to turn a slug into a window size before
316/// [`crate::agent_loop::CompactionConfig::for_context_window`] can compute a
317/// proportional threshold.
318/// What: A minimal substring/format table, checked in order: (1) any slug
319/// containing `claude-sonnet` or `claude-opus` (covers both the bare
320/// Anthropic slug and the Bedrock-routed
321/// `bedrock/us.anthropic.claude-sonnet-4-6` / `-opus-*` inference-profile
322/// format, see `crate::llm::bedrock::bedrock_model_id`) -> 200,000; (2) any
323/// slug beginning with the `atlascloud/` routing prefix -> 1,050,000 (#2536 —
324/// AtlasCloud's catalog default `openai/gpt-5.6-sol` has a 1.05M-token window,
325/// keyed off the routing prefix rather than the nested model id so the whole
326/// AtlasCloud family gets the large window); (3) any slug containing `gpt-4o` ->
327/// 128,000; else (4) [`DEFAULT_CONTEXT_WINDOW`]. Deliberately NOT a config file
328/// or per-agent override — the window size is a property of the model itself, not
329/// something an operator should need to tune per project.
330/// Test: `routing::tests::resolve_context_window_maps_bedrock_sonnet_to_200k`,
331/// `routing::tests::resolve_context_window_maps_atlascloud_to_1m`,
332/// `routing::tests::resolve_context_window_falls_back_to_default_for_unknown_model`.
333pub fn resolve_context_window(model: &str) -> usize {
334    if model.contains("claude-sonnet") || model.contains("claude-opus") {
335        200_000
336    } else if model.starts_with("atlascloud/") {
337        1_050_000
338    } else if model.contains("gpt-4o") {
339        128_000
340    } else {
341        DEFAULT_CONTEXT_WINDOW
342    }
343}
344
345/// Resolve the per-turn completion-token cap for an invocation.
346///
347/// Why: `[llm].max_tokens` is how an operator declares that an agent's turns
348/// need a larger completion budget than the default (e.g. an engineer that
349/// writes whole files needs far more than a chat-only PM). Before this fix,
350/// every call site building an `AgentLoopConfig` ignored the agent's
351/// `[llm].max_tokens` entirely and the loop hard-coded a 1024-token cap,
352/// truncating any turn that needed to emit more (#run_task-maxtokens-bug).
353/// What: Returns `agent_config.llm.max_tokens` when set, else
354/// [`DEFAULT_MAX_TOKENS`]. There is no per-call `RunContext` override yet —
355/// the config-file value or the built-in default are the only two tiers.
356/// Test: `routing::tests::resolve_max_tokens_*`.
357pub fn resolve_max_tokens(agent_config: &AgentConfig) -> u32 {
358    agent_config.llm.max_tokens.unwrap_or(DEFAULT_MAX_TOKENS)
359}
360
361/// Treat empty/whitespace-only strings as absent.
362///
363/// Why: An empty `model = ""` in TOML or an empty `RunContext.model` should fall
364/// through to the next tier rather than route to a blank slug.
365/// What: Returns `Some(trimmed-original)` only when the value has non-whitespace
366/// content; `None` otherwise.
367/// Test: `routing::tests::resolve_model_skips_empty_strings`.
368fn non_empty(value: Option<&str>) -> Option<&str> {
369    value.and_then(|v| {
370        let trimmed = v.trim();
371        if trimmed.is_empty() {
372            None
373        } else {
374            Some(trimmed)
375        }
376    })
377}
378
379/// Serializes every test in this module that sets/reads the process-wide
380/// [`RUN_DEADLINE_ENV_VAR`] — `cargo test` runs tests in parallel within one
381/// binary, and an unguarded `set_var`/`remove_var` pair would race across
382/// tests (mirrors `crate::mode::MODE_ENV_LOCK`'s identical rationale).
383#[cfg(test)]
384pub(crate) static RUN_DEADLINE_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
385
386/// Same rationale as [`RUN_DEADLINE_ENV_LOCK`], for the two process-wide
387/// top-level-override variables ([`PM_MODEL_ENV_VAR`], [`MAX_TURNS_ENV_VAR`]).
388/// One lock covers both: no test needs them held independently, and a single
389/// lock cannot deadlock against itself the way a pair acquired in two orders
390/// could (#8030, #8128).
391#[cfg(test)]
392pub(crate) static TOP_LEVEL_OVERRIDE_ENV_LOCK: tokio::sync::Mutex<()> =
393    tokio::sync::Mutex::const_new(());
394
395// ── Tests ─────────────────────────────────────────────────────────────────────
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400    use crate::agents::config::{AgentInfo, LlmParams};
401
402    /// Build an `AgentConfig` with the given agent model and `model_override`.
403    fn cfg(agent_model: Option<&str>, override_model: Option<&str>) -> AgentConfig {
404        AgentConfig {
405            agent: AgentInfo {
406                name: "test-agent".into(),
407                model: agent_model.map(str::to_string),
408                ..Default::default()
409            },
410            llm: LlmParams {
411                model_override: override_model.map(str::to_string),
412                ..Default::default()
413            },
414            ..Default::default()
415        }
416    }
417
418    /// `RunContext.model` wins over agent config and default.
419    ///
420    /// Why: Per-call overrides must take precedence so a caller can pin a model
421    /// for a single invocation.
422    /// What: Provide all three sources; assert the RunContext slug is returned.
423    /// Test: this test.
424    #[test]
425    fn resolve_model_run_context_wins() {
426        let config = cfg(Some("anthropic/claude-sonnet-4-5"), Some("qwen/qwen-2.5"));
427        let ctx = RunContext {
428            model: Some("openai/gpt-4o".into()),
429            ..Default::default()
430        };
431        assert_eq!(resolve_model(&config, Some(&ctx)), "openai/gpt-4o");
432    }
433
434    /// `[agent].model` wins when no RunContext override is present.
435    ///
436    /// Why: The agent's declared model is the next authority below per-call.
437    /// What: No RunContext model; assert the agent slug is returned over the
438    /// `model_override` and the default.
439    /// Test: this test.
440    #[test]
441    fn resolve_model_agent_config_wins_over_default() {
442        let config = cfg(Some("anthropic/claude-haiku-4-5"), Some("qwen/qwen-2.5"));
443        assert_eq!(
444            resolve_model(&config, None),
445            "anthropic/claude-haiku-4-5",
446            "agent.model must win over model_override and default"
447        );
448    }
449
450    /// `[llm].model_override` is used when `[agent].model` is absent.
451    ///
452    /// Why: `model_override` is the documented lower-precedence config slot.
453    /// What: Agent model `None`, override set; assert override is returned.
454    /// Test: this test.
455    #[test]
456    fn resolve_model_uses_model_override_when_agent_absent() {
457        let config = cfg(None, Some("deepseek/deepseek-chat"));
458        assert_eq!(resolve_model(&config, None), "deepseek/deepseek-chat");
459    }
460
461    /// Falls back to `DEFAULT_MODEL` when nothing is specified.
462    ///
463    /// Why: A run must always resolve to a usable slug.
464    /// What: Empty config and no RunContext; assert the default.
465    /// Test: this test.
466    #[test]
467    fn resolve_model_falls_back_to_default() {
468        let config = cfg(None, None);
469        assert_eq!(resolve_model(&config, None), DEFAULT_MODEL);
470    }
471
472    // ── #3438: short-alias normalization ────────────────────────────────────
473
474    /// `normalize_model_alias` maps all three short Claude aliases to a
475    /// concrete OpenRouter slug, case-insensitively and trimmed.
476    ///
477    /// Why: `opus`/`sonnet`/`haiku` are the `claude` CLI's own shorthand
478    /// (`trusty_agents_common::agents::builder::tier_to_model`'s output and
479    /// every composed roster agent's `.md` `model:` field), not valid
480    /// OpenRouter/API model ids — this is the exact substitution that fixes
481    /// the `"opus is not a valid model ID"` 400 (#3438).
482    /// What: Each of the three aliases, plus an uppercase/padded variant,
483    /// resolves to its mapped concrete slug.
484    /// Test: this test.
485    #[test]
486    fn normalize_model_alias_maps_short_aliases() {
487        // #8128: the Claude 5 tiers, read from OpenRouter's own model list.
488        assert_eq!(normalize_model_alias("opus"), "anthropic/claude-opus-5");
489        assert_eq!(normalize_model_alias("sonnet"), "anthropic/claude-sonnet-5");
490        assert_eq!(normalize_model_alias("haiku"), "anthropic/claude-haiku-4.5");
491        assert_eq!(
492            normalize_model_alias("  Opus  "),
493            "anthropic/claude-opus-5",
494            "must be case-insensitive and trim surrounding whitespace"
495        );
496    }
497
498    /// [`DEFAULT_MODEL`] is the SAME slug the `"sonnet"` alias resolves to.
499    ///
500    /// Why (#8128): the default's own docs promise an unpinned run and a
501    /// `--pm-model sonnet` run reach one provider slug. Pinning that here is
502    /// what stops the two from drifting the next time a tier moves — the
503    /// exact drift #8128 found, where the alias table and the default were
504    /// both stale but only one was noticed.
505    /// What: asserts the equality directly.
506    /// Test: this test.
507    #[test]
508    fn default_model_matches_the_sonnet_alias() {
509        assert_eq!(DEFAULT_MODEL, normalize_model_alias("sonnet"));
510    }
511
512    /// An already-concrete slug (or any string that isn't one of the three
513    /// bare aliases) passes through [`normalize_model_alias`] unchanged.
514    ///
515    /// Why: The normalizer must not mangle a valid `vendor/model` slug, a
516    /// routed `bedrock/`/`fireworks/`/`together/`/`atlascloud/` prefix, or an
517    /// unrecognised model string — it only rewrites the three known aliases.
518    /// What: A realistic OpenRouter slug and an arbitrary unknown string both
519    /// round-trip unchanged.
520    /// Test: this test.
521    #[test]
522    fn normalize_model_alias_passes_through_concrete_slugs() {
523        assert_eq!(
524            normalize_model_alias("anthropic/claude-sonnet-4-5"),
525            "anthropic/claude-sonnet-4-5"
526        );
527        assert_eq!(
528            normalize_model_alias("bedrock/us.anthropic.claude-opus-4-6"),
529            "bedrock/us.anthropic.claude-opus-4-6"
530        );
531        assert_eq!(
532            normalize_model_alias("some-vendor/unheard-of-model"),
533            "some-vendor/unheard-of-model"
534        );
535    }
536
537    /// [`resolve_model`] normalizes a bare alias sourced from `[agent].model`
538    /// (the tier-composed or `.md`-frontmatter case #3438 actually hit).
539    ///
540    /// Why: Regression guard at the public `resolve_model` seam, not just the
541    /// private helper — this is what every real call site invokes.
542    /// What: `agent.model = "opus"` resolves to the concrete slug, not the
543    /// bare alias.
544    /// Test: this test.
545    #[test]
546    fn resolve_model_normalizes_short_alias_from_agent_config() {
547        let config = cfg(Some("opus"), None);
548        assert_eq!(resolve_model(&config, None), "anthropic/claude-opus-5");
549    }
550
551    /// [`resolve_model`] normalizes a bare alias sourced from a per-call
552    /// `RunContext.model` override too.
553    ///
554    /// Why: The highest-precedence tier must not bypass normalization — a
555    /// caller pinning `RunContext.model = "sonnet"` must still reach the
556    /// provider with a valid concrete id.
557    /// What: `RunContext.model = "sonnet"` resolves to the concrete slug.
558    /// Test: this test.
559    #[test]
560    fn resolve_model_normalizes_short_alias_from_run_context() {
561        let config = cfg(Some("anthropic/claude-haiku-4-5"), None);
562        let ctx = RunContext {
563            model: Some("sonnet".into()),
564            ..Default::default()
565        };
566        assert_eq!(
567            resolve_model(&config, Some(&ctx)),
568            "anthropic/claude-sonnet-5"
569        );
570    }
571
572    /// Empty / whitespace strings are treated as absent at each tier.
573    ///
574    /// Why: A blank `model = ""` should not route to an empty slug; it must fall
575    /// through to the next source.
576    /// What: Empty RunContext + empty agent model + valid override → override.
577    /// Test: this test.
578    #[test]
579    fn resolve_model_skips_empty_strings() {
580        let config = cfg(Some("   "), Some("google/gemma-2-27b-it"));
581        let ctx = RunContext {
582            model: Some("".into()),
583            ..Default::default()
584        };
585        assert_eq!(
586            resolve_model(&config, Some(&ctx)),
587            "google/gemma-2-27b-it",
588            "empty RunContext and empty agent model must fall through"
589        );
590    }
591
592    /// Whitespace-padded slugs are trimmed at every precedence tier.
593    ///
594    /// Why: A TOML or RunContext slug like `"  openai/gpt-4o  "` would otherwise
595    /// route to an invalid, whitespace-padded model id. `non_empty` must return
596    /// the trimmed value, not the original padded slice.
597    /// What: (a) padded `RunContext.model` resolves to the trimmed slug; (b) with
598    /// no RunContext, a padded `agent.model` resolves to its trimmed slug; (c) an
599    /// all-whitespace `agent.model` falls through to the next tier (`model_override`).
600    /// Test: this test.
601    #[test]
602    fn resolve_model_trims_padded_slugs() {
603        // (a) Padded per-call override is trimmed and wins.
604        let config = cfg(Some("anthropic/claude-sonnet-4-5"), None);
605        let ctx = RunContext {
606            model: Some("  openai/gpt-4o  ".into()),
607            ..Default::default()
608        };
609        assert_eq!(
610            resolve_model(&config, Some(&ctx)),
611            "openai/gpt-4o",
612            "padded RunContext.model must resolve to the trimmed slug"
613        );
614
615        // (b) Padded agent.model is trimmed when no RunContext override exists.
616        let config = cfg(Some("  anthropic/claude-haiku-4-5  "), None);
617        assert_eq!(
618            resolve_model(&config, None),
619            "anthropic/claude-haiku-4-5",
620            "padded agent.model must resolve to the trimmed slug"
621        );
622
623        // (c) All-whitespace agent.model falls through to model_override.
624        let config = cfg(Some("   "), Some("deepseek/deepseek-chat"));
625        assert_eq!(
626            resolve_model(&config, None),
627            "deepseek/deepseek-chat",
628            "all-whitespace agent.model must fall through to the next tier"
629        );
630    }
631
632    /// A configured `[llm].max_tokens` is honoured, not clamped to the default.
633    ///
634    /// Why: This is the regression guard for the bug this function fixes — a
635    /// configured cap higher than the old hard-coded 1024 must reach the
636    /// caller unchanged.
637    /// What: `[llm].max_tokens = 8192` resolves to `8192`.
638    /// Test: this test.
639    #[test]
640    fn resolve_max_tokens_honours_configured_value() {
641        let config = AgentConfig {
642            llm: LlmParams {
643                max_tokens: Some(8192),
644                ..Default::default()
645            },
646            ..Default::default()
647        };
648        assert_eq!(resolve_max_tokens(&config), 8192);
649    }
650
651    /// Falls back to `DEFAULT_MAX_TOKENS` when `[llm].max_tokens` is unset.
652    ///
653    /// Why: A run must always resolve to a usable, generous-enough cap even
654    /// when the agent TOML doesn't specify one.
655    /// What: Empty config resolves to `DEFAULT_MAX_TOKENS`.
656    /// Test: this test.
657    #[test]
658    fn resolve_max_tokens_falls_back_to_default() {
659        let config = AgentConfig::default();
660        assert_eq!(resolve_max_tokens(&config), DEFAULT_MAX_TOKENS);
661    }
662
663    // ── #2308: resolve_context_window ───────────────────────────────────────
664
665    /// The real Bedrock-routed Claude Sonnet slug maps to a 200K window.
666    ///
667    /// Why: This is the exact model whose flat 6,000-token compaction
668    /// threshold (#2308) was ~3% of its real context window; the resolver
669    /// must recognise the SAME slug format `resolve_model`/the Bedrock
670    /// dispatch layer actually produce
671    /// (`bedrock/us.anthropic.claude-sonnet-4-6`, see
672    /// `crate::llm::bedrock::bedrock_model_id`'s doctests), not just a bare
673    /// `claude-sonnet-*` slug.
674    /// What: Assert the real Bedrock dispatch slug resolves to 200,000.
675    /// Test: this test.
676    #[test]
677    fn resolve_context_window_maps_bedrock_sonnet_to_200k() {
678        assert_eq!(
679            resolve_context_window("bedrock/us.anthropic.claude-sonnet-4-6"),
680            200_000
681        );
682        assert_eq!(
683            resolve_context_window("bedrock/us.anthropic.claude-opus-4-6"),
684            200_000
685        );
686    }
687
688    /// An `atlascloud/*` slug maps to AtlasCloud's 1.05M-token window (#2536),
689    /// including the nested `atlascloud/openai/gpt-5.6-sol` form.
690    ///
691    /// Why: AtlasCloud's default `openai/gpt-5.6-sol` carries a 1,050,000-token
692    /// context window; keying off the `atlascloud/` routing prefix (not the
693    /// nested `gpt-4o`-adjacent model id) gives the whole family the large window
694    /// so compaction scales correctly.
695    /// What: Assert the nested and a bare AtlasCloud slug resolve to 1,050,000.
696    /// Test: this test.
697    #[test]
698    fn resolve_context_window_maps_atlascloud_to_1m() {
699        assert_eq!(
700            resolve_context_window("atlascloud/openai/gpt-5.6-sol"),
701            1_050_000
702        );
703        assert_eq!(resolve_context_window("atlascloud/deepseek-v3"), 1_050_000);
704    }
705
706    /// An unrecognised model slug falls back to [`DEFAULT_CONTEXT_WINDOW`].
707    ///
708    /// Why: A resolver that panics or silently returns 0 on an unknown slug
709    /// would break every downstream compaction-threshold calculation.
710    /// What: Assert an arbitrary/unknown slug resolves to the default.
711    /// Test: this test.
712    #[test]
713    fn resolve_context_window_falls_back_to_default_for_unknown_model() {
714        assert_eq!(
715            resolve_context_window("some-vendor/unheard-of-model-v1"),
716            DEFAULT_CONTEXT_WINDOW
717        );
718    }
719
720    // ── #2207: resolve_deadline_secs precedence ─────────────────────────────
721
722    /// Serializes access to [`RUN_DEADLINE_ENV_VAR`] for one test closure,
723    /// restoring the prior (absent) state afterward.
724    async fn with_env_deadline<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
725        let _guard = RUN_DEADLINE_ENV_LOCK.lock().await;
726        // SAFETY: test-only env mutation; serialized by `RUN_DEADLINE_ENV_LOCK`.
727        unsafe {
728            match value {
729                Some(v) => std::env::set_var(RUN_DEADLINE_ENV_VAR, v),
730                None => std::env::remove_var(RUN_DEADLINE_ENV_VAR),
731            }
732        }
733        let result = f();
734        unsafe {
735            std::env::remove_var(RUN_DEADLINE_ENV_VAR);
736        }
737        result
738    }
739
740    /// The explicit CLI override wins over both the env var and the default.
741    ///
742    /// Why: `run-task --timeout-seconds` (or `task.run`'s `deadline_secs`
743    /// param) must be the highest-precedence source — an operator setting it
744    /// explicitly for one run must never be silently overridden.
745    /// What: Set the env var to a different value; assert the override wins.
746    /// Test: this test.
747    #[tokio::test]
748    async fn resolve_deadline_secs_cli_override_wins() {
749        with_env_deadline(Some("60"), || {
750            assert_eq!(resolve_deadline_secs(Some(7200)), 7200);
751        })
752        .await;
753    }
754
755    /// The env var wins over the built-in default when no override is given.
756    ///
757    /// Why: `TCODE_RUN_DEADLINE_SECONDS` is the escape-hatch tier for a whole
758    /// invocation without threading a flag through every call site.
759    /// What: No CLI override; env var set; assert the env value is returned.
760    /// Test: this test.
761    #[tokio::test]
762    async fn resolve_deadline_secs_env_wins_over_default() {
763        with_env_deadline(Some("900"), || {
764            assert_eq!(resolve_deadline_secs(None), 900);
765        })
766        .await;
767    }
768
769    /// An unparseable env var falls through to the default rather than
770    /// erroring the whole run.
771    ///
772    /// Why: A misconfigured environment must degrade gracefully, not crash a
773    /// long-running task.
774    /// What: Env var set to a non-numeric string; assert the default wins.
775    /// Test: this test.
776    #[tokio::test]
777    async fn resolve_deadline_secs_invalid_env_falls_back_to_default() {
778        with_env_deadline(Some("not-a-number"), || {
779            assert_eq!(resolve_deadline_secs(None), DEFAULT_RUN_DEADLINE_SECS);
780        })
781        .await;
782    }
783
784    /// Falls back to [`DEFAULT_RUN_DEADLINE_SECS`] when nothing is set.
785    ///
786    /// Why: A run must always resolve to a usable, generous deadline even
787    /// when no override is configured anywhere.
788    /// What: No CLI override, no env var; assert the default.
789    /// Test: this test.
790    #[tokio::test]
791    async fn resolve_deadline_secs_falls_back_to_default() {
792        with_env_deadline(None, || {
793            assert_eq!(resolve_deadline_secs(None), DEFAULT_RUN_DEADLINE_SECS);
794        })
795        .await;
796    }
797
798    // ── #8030 / #8128: top-level PM overrides ───────────────────────────────
799
800    /// Serializes access to one of the two top-level-override env vars for a
801    /// single test closure, restoring the prior (absent) state afterward.
802    async fn with_env_var<T>(name: &str, value: Option<&str>, f: impl FnOnce() -> T) -> T {
803        let _guard = TOP_LEVEL_OVERRIDE_ENV_LOCK.lock().await;
804        // SAFETY: test-only env mutation; serialized by the lock above.
805        unsafe {
806            match value {
807                Some(v) => std::env::set_var(name, v),
808                None => std::env::remove_var(name),
809            }
810        }
811        let result = f();
812        unsafe {
813            std::env::remove_var(name);
814        }
815        result
816    }
817
818    /// The `--pm-model` flag wins over [`PM_MODEL_ENV_VAR`].
819    ///
820    /// Why (#8030): an operator pinning the top-level model for one run must
821    /// not be silently overridden by an exported default.
822    /// What: env set to one slug, flag to another; assert the flag.
823    /// Test: this test.
824    #[tokio::test]
825    async fn resolve_pm_model_override_flag_wins_over_env() {
826        with_env_var(PM_MODEL_ENV_VAR, Some("anthropic/claude-haiku-4.5"), || {
827            assert_eq!(
828                resolve_pm_model_override(Some("anthropic/claude-opus-5".to_string())),
829                Some("anthropic/claude-opus-5".to_string())
830            );
831        })
832        .await;
833    }
834
835    /// [`PM_MODEL_ENV_VAR`] supplies the override when no flag is given, and
836    /// its absence means "no override at all".
837    ///
838    /// Why (#8030): the env tier is what lets a bake-off runner repoint the
839    /// top-level agent for a whole invocation without a flag at every call.
840    /// What: with the var set, the value is returned; unset, `None`.
841    /// Test: this test.
842    #[tokio::test]
843    async fn resolve_pm_model_override_env_wins_over_nothing() {
844        with_env_var(PM_MODEL_ENV_VAR, Some("anthropic/claude-opus-5"), || {
845            assert_eq!(
846                resolve_pm_model_override(None),
847                Some("anthropic/claude-opus-5".to_string())
848            );
849        })
850        .await;
851        with_env_var(PM_MODEL_ENV_VAR, None, || {
852            assert_eq!(resolve_pm_model_override(None), None);
853        })
854        .await;
855    }
856
857    /// A blank flag or env value is treated as absent at both tiers.
858    ///
859    /// Why: `--pm-model ""` (or an exported empty var) must fall through to
860    /// the agent's own model, not pin an empty slug a provider would reject.
861    /// What: blank flag with a blank env → `None`; blank flag with a real env
862    /// value → the env value.
863    /// Test: this test.
864    #[tokio::test]
865    async fn resolve_pm_model_override_blank_is_absent() {
866        with_env_var(PM_MODEL_ENV_VAR, Some("  "), || {
867            assert_eq!(resolve_pm_model_override(Some("   ".to_string())), None);
868        })
869        .await;
870        with_env_var(PM_MODEL_ENV_VAR, Some("anthropic/claude-opus-5"), || {
871            assert_eq!(
872                resolve_pm_model_override(Some("".to_string())),
873                Some("anthropic/claude-opus-5".to_string())
874            );
875        })
876        .await;
877    }
878
879    /// [`resolve_model_with_override`] puts the per-run override ahead of the
880    /// agent config.
881    ///
882    /// Why (#8030): this is the whole point of the new tier — the top-level
883    /// agent's front-matter `model:` must lose to an explicit run override.
884    /// What: config pins one slug, override names another; assert the
885    /// override.
886    /// Test: this test.
887    #[test]
888    fn resolve_model_with_override_wins_over_agent_config() {
889        let config = cfg(Some("anthropic/claude-haiku-4.5"), None);
890        assert_eq!(
891            resolve_model_with_override(&config, Some("anthropic/claude-opus-5")),
892            "anthropic/claude-opus-5"
893        );
894    }
895
896    /// A short alias reaching [`resolve_model_with_override`] is normalised,
897    /// exactly as one reaching [`resolve_model`] is.
898    ///
899    /// Why (#3438/#8030): `--pm-model opus` must behave like
900    /// `--engineer-model opus`; a bare alias on the wire is the
901    /// `"opus is not a valid model ID"` 400.
902    /// What: `"opus"` resolves to the concrete Claude 5 slug.
903    /// Test: this test.
904    #[test]
905    fn resolve_model_with_override_normalizes_short_alias() {
906        let config = cfg(Some("anthropic/claude-haiku-4.5"), None);
907        assert_eq!(
908            resolve_model_with_override(&config, Some("opus")),
909            "anthropic/claude-opus-5"
910        );
911    }
912
913    /// With no override, [`resolve_model_with_override`] is exactly
914    /// [`resolve_model`] — including the blank-is-absent rule.
915    ///
916    /// Why: the new tier must be additive; every pre-#8030 call site keeps
917    /// its behaviour byte-for-byte.
918    /// What: `None` and a blank string both fall through to the config, and a
919    /// configless agent falls through to [`DEFAULT_MODEL`].
920    /// Test: this test.
921    #[test]
922    fn resolve_model_with_override_absent_matches_resolve_model() {
923        let config = cfg(Some("anthropic/claude-haiku-4.5"), None);
924        assert_eq!(
925            resolve_model_with_override(&config, None),
926            resolve_model(&config, None)
927        );
928        assert_eq!(
929            resolve_model_with_override(&config, Some("  ")),
930            "anthropic/claude-haiku-4.5"
931        );
932        assert_eq!(
933            resolve_model_with_override(&cfg(None, None), None),
934            DEFAULT_MODEL
935        );
936    }
937
938    /// The `--max-turns` flag wins over [`MAX_TURNS_ENV_VAR`].
939    ///
940    /// Why (#8128): same precedence contract every other per-run override in
941    /// this module follows.
942    /// What: env set to one cap, flag to another; assert the flag.
943    /// Test: this test.
944    #[tokio::test]
945    async fn resolve_max_turns_flag_wins_over_env() {
946        with_env_var(MAX_TURNS_ENV_VAR, Some("40"), || {
947            assert_eq!(resolve_max_turns(Some(12)), Ok(Some(12)));
948        })
949        .await;
950    }
951
952    /// [`MAX_TURNS_ENV_VAR`] supplies the cap when no flag is given, and its
953    /// absence leaves the loop's own default in place.
954    ///
955    /// Why (#8128): `None` must mean "do not override", so an absent flag
956    /// changes nothing about a run.
957    /// What: with the var set, that cap is returned; unset, `Ok(None)`.
958    /// Test: this test.
959    #[tokio::test]
960    async fn resolve_max_turns_env_wins_over_default() {
961        with_env_var(MAX_TURNS_ENV_VAR, Some("40"), || {
962            assert_eq!(resolve_max_turns(None), Ok(Some(40)));
963        })
964        .await;
965        with_env_var(MAX_TURNS_ENV_VAR, None, || {
966            assert_eq!(resolve_max_turns(None), Ok(None));
967        })
968        .await;
969    }
970
971    /// A zero flag is an error, not a run that does nothing.
972    ///
973    /// Why (#8128): a zero-turn loop makes no LLM call and would report an
974    /// empty run as a normal one — the operator must be told, not guessed at.
975    /// What: `Some(0)` returns `Err` naming the flag.
976    /// Test: this test.
977    #[tokio::test]
978    async fn resolve_max_turns_rejects_zero_from_flag() {
979        with_env_var(MAX_TURNS_ENV_VAR, None, || {
980            let err = resolve_max_turns(Some(0)).expect_err("0 must be rejected");
981            assert!(
982                err.contains("--max-turns"),
983                "the error must name the flag; got {err:?}"
984            );
985        })
986        .await;
987    }
988
989    /// A zero env value is rejected the same way as a zero flag.
990    ///
991    /// Why (#8128): the env tier must not be a back door around the flag's
992    /// own validation.
993    /// What: `TCODE_MAX_TURNS=0` returns `Err` naming the variable.
994    /// Test: this test.
995    #[tokio::test]
996    async fn resolve_max_turns_rejects_zero_from_env() {
997        with_env_var(MAX_TURNS_ENV_VAR, Some("0"), || {
998            let err = resolve_max_turns(None).expect_err("0 must be rejected");
999            assert!(
1000                err.contains(MAX_TURNS_ENV_VAR),
1001                "the error must name the env var; got {err:?}"
1002            );
1003        })
1004        .await;
1005    }
1006
1007    /// An unparseable env value falls through to "no override" rather than
1008    /// erroring the whole run.
1009    ///
1010    /// Why: matches [`resolve_deadline_secs`]'s established degrade-gracefully
1011    /// contract for a misconfigured environment.
1012    /// What: a non-numeric value yields `Ok(None)`.
1013    /// Test: this test.
1014    #[tokio::test]
1015    async fn resolve_max_turns_invalid_env_falls_back_to_default() {
1016        with_env_var(MAX_TURNS_ENV_VAR, Some("not-a-number"), || {
1017            assert_eq!(resolve_max_turns(None), Ok(None));
1018        })
1019        .await;
1020    }
1021}