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: A run must always resolve to *some* model; this is the cheap, broadly
18/// available fallback used across trusty-code.
19/// What: The OpenRouter slug for GPT-4o-mini.
20/// Test: `routing::tests::resolve_model_falls_back_to_default`.
21pub const DEFAULT_MODEL: &str = "openai/gpt-4o-mini";
22
23/// Default per-turn completion token cap when `[llm].max_tokens` is unset.
24///
25/// Why: A turn cap must always resolve to *some* value, and it must be large
26/// enough for a real tool-calling turn (e.g. `write_file` emitting a whole
27/// source file) to complete without truncation — the bug this constant fixes
28/// was every turn silently capped at 1024 regardless of agent config,
29/// truncating real writes. 8192 is generous enough for typical file writes
30/// while still bounding a single turn's cost.
31/// What: The fallback completion-token cap used by [`resolve_max_tokens`].
32/// Test: `routing::tests::resolve_max_tokens_falls_back_to_default`.
33pub const DEFAULT_MAX_TOKENS: u32 = 8192;
34
35/// Environment variable overriding the `run-task` wall-clock deadline (#2207).
36///
37/// Why: Lets an operator (or the M3 bake-off runner) raise the deadline for a
38/// whole invocation without a CLI flag at every call site — mirrors
39/// `crate::mode::MODE_ENV_VAR`'s "escape hatch" precedent for a small, direct
40/// `std::env` read in production code.
41/// What: Read by [`resolve_deadline_secs`] as the middle precedence tier.
42/// Test: `routing::tests::resolve_deadline_secs_*`.
43pub const RUN_DEADLINE_ENV_VAR: &str = "TCODE_RUN_DEADLINE_SECONDS";
44
45/// Generous default wall-clock deadline for a `run-task` invocation, in
46/// seconds, when neither a CLI override nor [`RUN_DEADLINE_ENV_VAR`] is set.
47///
48/// Why: The AgentLoop's own built-in default (120s, `crate::agent_loop::AgentLoopConfig::default`)
49/// is tuned for a short interactive turn, not a full PM->engineer run-task
50/// invocation — #2207 found that cap cutting off a real, otherwise-successful
51/// task at turn 13 before it reached `finish_task`. 30 minutes is generous
52/// enough for the M3 bake-off's L1 pilot to complete cleanly while L2/L3 (1-3
53/// hour problems) can still raise it further via the flag/env override.
54/// What: The fallback tier of [`resolve_deadline_secs`].
55/// Test: `routing::tests::resolve_deadline_secs_falls_back_to_default`.
56pub const DEFAULT_RUN_DEADLINE_SECS: u64 = 1800;
57
58/// Resolve the wall-clock deadline (in seconds) for a `run-task` invocation.
59///
60/// Why: #2207 — the AgentLoop's built-in 120s timeout is too tight for a real
61/// PM->engineer run-task on anything but a trivial task, cutting off
62/// otherwise-successful runs before they reach `finish_task`. A single
63/// resolver mirrors [`resolve_model`]/[`resolve_max_tokens`]'s precedence-
64/// ladder pattern so every call site (the CLI's legacy in-process path, the
65/// daemon's `task.run`, and the in-process sub-agent runner) agrees.
66/// What: Returns, in priority order, the first of: (1) `cli_override` (the
67/// `run-task --timeout-seconds`/`task.run` `deadline_secs` request param,
68/// threaded in by the caller), (2) [`RUN_DEADLINE_ENV_VAR`] parsed as a `u64`
69/// (an unparseable value is treated as absent, falling through — logged at
70/// `warn` — rather than erroring the whole run), else (3)
71/// [`DEFAULT_RUN_DEADLINE_SECS`].
72/// Test: `routing::tests::resolve_deadline_secs_cli_override_wins`,
73/// `routing::tests::resolve_deadline_secs_env_wins_over_default`,
74/// `routing::tests::resolve_deadline_secs_invalid_env_falls_back_to_default`,
75/// `routing::tests::resolve_deadline_secs_falls_back_to_default`.
76pub fn resolve_deadline_secs(cli_override: Option<u64>) -> u64 {
77    if let Some(secs) = cli_override {
78        return secs;
79    }
80
81    if let Ok(raw) = std::env::var(RUN_DEADLINE_ENV_VAR) {
82        match raw.trim().parse::<u64>() {
83            Ok(secs) => return secs,
84            Err(e) => {
85                tracing::warn!(
86                    "{RUN_DEADLINE_ENV_VAR}={raw:?} is not a valid u64 ({e}); \
87                     falling back to DEFAULT_RUN_DEADLINE_SECS"
88                );
89            }
90        }
91    }
92
93    DEFAULT_RUN_DEADLINE_SECS
94}
95
96/// Short Claude model aliases (`opus`/`sonnet`/`haiku`) mapped to a concrete,
97/// provider-valid OpenRouter slug (#3438).
98///
99/// Why: these three bare words are the `claude` CLI's own `--model` shorthand
100/// (see `trusty_agents_common::agents::builder::tier_to_model`, which composes
101/// them from an agent's `resource_tier`, and every embedded roster agent's
102/// `.md` frontmatter — e.g. `assets/agents/python-engineer.md`'s
103/// `model: sonnet`) — valid input for the `claude` subprocess trusty-agents
104/// spawns, but NOT a real OpenRouter/Anthropic-API model id. trusty-code talks
105/// to providers directly (`llm::client::OpenAiCompatClient`), so a bare alias
106/// reaching the wire produces `API error 400: "opus is not a valid model ID"`
107/// verbatim — the exact failure #3438 traced. [`resolve_model`] is the single
108/// funnel every call site resolves its final slug through
109/// (`runner::in_process::InProcessAgentRunner::run_pipeline`,
110/// `task::executor`, `run_task::execute_run_task`), so normalising here fixes
111/// every path at once rather than patching each `.md` file or call site
112/// individually.
113/// What: Case-insensitive exact match on the trimmed slug; anything else
114/// (an already-concrete slug, a routed `bedrock/`/`fireworks/`/etc. prefix, an
115/// unrecognised alias) passes through unchanged — [`resolve_model`] never
116/// errors on an unmapped model, it just doesn't rewrite it.
117/// Test: `routing::tests::normalize_model_alias_maps_short_aliases`,
118/// `routing::tests::normalize_model_alias_passes_through_concrete_slugs`,
119/// `assets::tests::every_embedded_agent_model_normalizes_to_a_valid_slug`.
120fn normalize_model_alias(model: &str) -> &str {
121    match model.trim().to_ascii_lowercase().as_str() {
122        "opus" => "anthropic/claude-opus-4.5",
123        "sonnet" => "anthropic/claude-sonnet-4.5",
124        "haiku" => "anthropic/claude-haiku-4.5",
125        _ => model,
126    }
127}
128
129/// Resolve the model slug for an invocation.
130///
131/// Why: Centralises the precedence so per-call overrides, per-agent config, and
132/// the global default never disagree across call sites.
133/// What: Returns, in priority order, the first non-empty of:
134/// (1) `run_context.model` (per-call override),
135/// (2) `agent_config.agent.model`,
136/// (3) `agent_config.llm.model_override`,
137/// else (4) [`DEFAULT_MODEL`] — each candidate passed through
138/// [`normalize_model_alias`] (#3438) so a bare `opus`/`sonnet`/`haiku` alias
139/// never reaches a provider as-is.
140/// Test: `routing::tests::resolve_model_*` cover every tier;
141/// `routing::tests::resolve_model_normalizes_short_alias_from_agent_config`
142/// and `resolve_model_normalizes_short_alias_from_run_context` cover #3438.
143pub fn resolve_model(agent_config: &AgentConfig, run_context: Option<&RunContext>) -> String {
144    // 1. Per-call override wins.
145    if let Some(ctx) = run_context
146        && let Some(model) = non_empty(ctx.model.as_deref())
147    {
148        return normalize_model_alias(model).to_string();
149    }
150
151    // 2. Agent-level model.
152    if let Some(model) = non_empty(agent_config.agent.model.as_deref()) {
153        return normalize_model_alias(model).to_string();
154    }
155
156    // 3. `[llm].model_override` (lower precedence than `[agent].model`).
157    if let Some(model) = non_empty(agent_config.llm.model_override.as_deref()) {
158        return normalize_model_alias(model).to_string();
159    }
160
161    // 4. Built-in default.
162    DEFAULT_MODEL.to_string()
163}
164
165/// Fallback context-window size (in tokens) for a model slug this resolver
166/// does not recognise.
167///
168/// Why: [`resolve_context_window`] must always return a usable number even
169/// for an unlisted/unknown slug (a new provider, a typo'd override, etc.) —
170/// 128,000 is a conservative, widely-supported floor shared by several
171/// mainstream hosted models (e.g. `gpt-4o`), so an unknown model is treated
172/// no more generously than that.
173/// What: The fallback tier of [`resolve_context_window`].
174/// Test: `routing::tests::resolve_context_window_falls_back_to_default_for_unknown_model`.
175pub const DEFAULT_CONTEXT_WINDOW: usize = 128_000;
176
177/// Resolve the real context-window size (in tokens) for a model slug.
178///
179/// Why: #2308 — `CompactionConfig::default()`'s flat `token_threshold: 6_000`
180/// is model-blind: ~3% of Bedrock Claude Sonnet's real 200K-token window, so
181/// ordinary coding turns (post-#2261 tool-call-arg counting) blow through it
182/// constantly and trigger pathological re-compaction. Compaction must instead
183/// scale with the model actually in use, which means a resolver is needed
184/// alongside [`resolve_model`] to turn a slug into a window size before
185/// [`crate::agent_loop::CompactionConfig::for_context_window`] can compute a
186/// proportional threshold.
187/// What: A minimal substring/format table, checked in order: (1) any slug
188/// containing `claude-sonnet` or `claude-opus` (covers both the bare
189/// Anthropic slug and the Bedrock-routed
190/// `bedrock/us.anthropic.claude-sonnet-4-6` / `-opus-*` inference-profile
191/// format, see `crate::llm::bedrock::bedrock_model_id`) -> 200,000; (2) any
192/// slug beginning with the `atlascloud/` routing prefix -> 1,050,000 (#2536 —
193/// AtlasCloud's catalog default `openai/gpt-5.6-sol` has a 1.05M-token window,
194/// keyed off the routing prefix rather than the nested model id so the whole
195/// AtlasCloud family gets the large window); (3) any slug containing `gpt-4o` ->
196/// 128,000; else (4) [`DEFAULT_CONTEXT_WINDOW`]. Deliberately NOT a config file
197/// or per-agent override — the window size is a property of the model itself, not
198/// something an operator should need to tune per project.
199/// Test: `routing::tests::resolve_context_window_maps_bedrock_sonnet_to_200k`,
200/// `routing::tests::resolve_context_window_maps_atlascloud_to_1m`,
201/// `routing::tests::resolve_context_window_falls_back_to_default_for_unknown_model`.
202pub fn resolve_context_window(model: &str) -> usize {
203    if model.contains("claude-sonnet") || model.contains("claude-opus") {
204        200_000
205    } else if model.starts_with("atlascloud/") {
206        1_050_000
207    } else if model.contains("gpt-4o") {
208        128_000
209    } else {
210        DEFAULT_CONTEXT_WINDOW
211    }
212}
213
214/// Resolve the per-turn completion-token cap for an invocation.
215///
216/// Why: `[llm].max_tokens` is how an operator declares that an agent's turns
217/// need a larger completion budget than the default (e.g. an engineer that
218/// writes whole files needs far more than a chat-only PM). Before this fix,
219/// every call site building an `AgentLoopConfig` ignored the agent's
220/// `[llm].max_tokens` entirely and the loop hard-coded a 1024-token cap,
221/// truncating any turn that needed to emit more (#run_task-maxtokens-bug).
222/// What: Returns `agent_config.llm.max_tokens` when set, else
223/// [`DEFAULT_MAX_TOKENS`]. There is no per-call `RunContext` override yet —
224/// the config-file value or the built-in default are the only two tiers.
225/// Test: `routing::tests::resolve_max_tokens_*`.
226pub fn resolve_max_tokens(agent_config: &AgentConfig) -> u32 {
227    agent_config.llm.max_tokens.unwrap_or(DEFAULT_MAX_TOKENS)
228}
229
230/// Treat empty/whitespace-only strings as absent.
231///
232/// Why: An empty `model = ""` in TOML or an empty `RunContext.model` should fall
233/// through to the next tier rather than route to a blank slug.
234/// What: Returns `Some(trimmed-original)` only when the value has non-whitespace
235/// content; `None` otherwise.
236/// Test: `routing::tests::resolve_model_skips_empty_strings`.
237fn non_empty(value: Option<&str>) -> Option<&str> {
238    value.and_then(|v| {
239        let trimmed = v.trim();
240        if trimmed.is_empty() {
241            None
242        } else {
243            Some(trimmed)
244        }
245    })
246}
247
248/// Serializes every test in this module that sets/reads the process-wide
249/// [`RUN_DEADLINE_ENV_VAR`] — `cargo test` runs tests in parallel within one
250/// binary, and an unguarded `set_var`/`remove_var` pair would race across
251/// tests (mirrors `crate::mode::MODE_ENV_LOCK`'s identical rationale).
252#[cfg(test)]
253pub(crate) static RUN_DEADLINE_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
254
255// ── Tests ─────────────────────────────────────────────────────────────────────
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use crate::agents::config::{AgentInfo, LlmParams};
261
262    /// Build an `AgentConfig` with the given agent model and `model_override`.
263    fn cfg(agent_model: Option<&str>, override_model: Option<&str>) -> AgentConfig {
264        AgentConfig {
265            agent: AgentInfo {
266                name: "test-agent".into(),
267                model: agent_model.map(str::to_string),
268                ..Default::default()
269            },
270            llm: LlmParams {
271                model_override: override_model.map(str::to_string),
272                ..Default::default()
273            },
274            ..Default::default()
275        }
276    }
277
278    /// `RunContext.model` wins over agent config and default.
279    ///
280    /// Why: Per-call overrides must take precedence so a caller can pin a model
281    /// for a single invocation.
282    /// What: Provide all three sources; assert the RunContext slug is returned.
283    /// Test: this test.
284    #[test]
285    fn resolve_model_run_context_wins() {
286        let config = cfg(Some("anthropic/claude-sonnet-4-5"), Some("qwen/qwen-2.5"));
287        let ctx = RunContext {
288            model: Some("openai/gpt-4o".into()),
289            ..Default::default()
290        };
291        assert_eq!(resolve_model(&config, Some(&ctx)), "openai/gpt-4o");
292    }
293
294    /// `[agent].model` wins when no RunContext override is present.
295    ///
296    /// Why: The agent's declared model is the next authority below per-call.
297    /// What: No RunContext model; assert the agent slug is returned over the
298    /// `model_override` and the default.
299    /// Test: this test.
300    #[test]
301    fn resolve_model_agent_config_wins_over_default() {
302        let config = cfg(Some("anthropic/claude-haiku-4-5"), Some("qwen/qwen-2.5"));
303        assert_eq!(
304            resolve_model(&config, None),
305            "anthropic/claude-haiku-4-5",
306            "agent.model must win over model_override and default"
307        );
308    }
309
310    /// `[llm].model_override` is used when `[agent].model` is absent.
311    ///
312    /// Why: `model_override` is the documented lower-precedence config slot.
313    /// What: Agent model `None`, override set; assert override is returned.
314    /// Test: this test.
315    #[test]
316    fn resolve_model_uses_model_override_when_agent_absent() {
317        let config = cfg(None, Some("deepseek/deepseek-chat"));
318        assert_eq!(resolve_model(&config, None), "deepseek/deepseek-chat");
319    }
320
321    /// Falls back to `DEFAULT_MODEL` when nothing is specified.
322    ///
323    /// Why: A run must always resolve to a usable slug.
324    /// What: Empty config and no RunContext; assert the default.
325    /// Test: this test.
326    #[test]
327    fn resolve_model_falls_back_to_default() {
328        let config = cfg(None, None);
329        assert_eq!(resolve_model(&config, None), DEFAULT_MODEL);
330    }
331
332    // ── #3438: short-alias normalization ────────────────────────────────────
333
334    /// `normalize_model_alias` maps all three short Claude aliases to a
335    /// concrete OpenRouter slug, case-insensitively and trimmed.
336    ///
337    /// Why: `opus`/`sonnet`/`haiku` are the `claude` CLI's own shorthand
338    /// (`trusty_agents_common::agents::builder::tier_to_model`'s output and
339    /// every composed roster agent's `.md` `model:` field), not valid
340    /// OpenRouter/API model ids — this is the exact substitution that fixes
341    /// the `"opus is not a valid model ID"` 400 (#3438).
342    /// What: Each of the three aliases, plus an uppercase/padded variant,
343    /// resolves to its mapped concrete slug.
344    /// Test: this test.
345    #[test]
346    fn normalize_model_alias_maps_short_aliases() {
347        assert_eq!(normalize_model_alias("opus"), "anthropic/claude-opus-4.5");
348        assert_eq!(
349            normalize_model_alias("sonnet"),
350            "anthropic/claude-sonnet-4.5"
351        );
352        assert_eq!(normalize_model_alias("haiku"), "anthropic/claude-haiku-4.5");
353        assert_eq!(
354            normalize_model_alias("  Opus  "),
355            "anthropic/claude-opus-4.5",
356            "must be case-insensitive and trim surrounding whitespace"
357        );
358    }
359
360    /// An already-concrete slug (or any string that isn't one of the three
361    /// bare aliases) passes through [`normalize_model_alias`] unchanged.
362    ///
363    /// Why: The normalizer must not mangle a valid `vendor/model` slug, a
364    /// routed `bedrock/`/`fireworks/`/`together/`/`atlascloud/` prefix, or an
365    /// unrecognised model string — it only rewrites the three known aliases.
366    /// What: A realistic OpenRouter slug and an arbitrary unknown string both
367    /// round-trip unchanged.
368    /// Test: this test.
369    #[test]
370    fn normalize_model_alias_passes_through_concrete_slugs() {
371        assert_eq!(
372            normalize_model_alias("anthropic/claude-sonnet-4-5"),
373            "anthropic/claude-sonnet-4-5"
374        );
375        assert_eq!(
376            normalize_model_alias("bedrock/us.anthropic.claude-opus-4-6"),
377            "bedrock/us.anthropic.claude-opus-4-6"
378        );
379        assert_eq!(
380            normalize_model_alias("some-vendor/unheard-of-model"),
381            "some-vendor/unheard-of-model"
382        );
383    }
384
385    /// [`resolve_model`] normalizes a bare alias sourced from `[agent].model`
386    /// (the tier-composed or `.md`-frontmatter case #3438 actually hit).
387    ///
388    /// Why: Regression guard at the public `resolve_model` seam, not just the
389    /// private helper — this is what every real call site invokes.
390    /// What: `agent.model = "opus"` resolves to the concrete slug, not the
391    /// bare alias.
392    /// Test: this test.
393    #[test]
394    fn resolve_model_normalizes_short_alias_from_agent_config() {
395        let config = cfg(Some("opus"), None);
396        assert_eq!(resolve_model(&config, None), "anthropic/claude-opus-4.5");
397    }
398
399    /// [`resolve_model`] normalizes a bare alias sourced from a per-call
400    /// `RunContext.model` override too.
401    ///
402    /// Why: The highest-precedence tier must not bypass normalization — a
403    /// caller pinning `RunContext.model = "sonnet"` must still reach the
404    /// provider with a valid concrete id.
405    /// What: `RunContext.model = "sonnet"` resolves to the concrete slug.
406    /// Test: this test.
407    #[test]
408    fn resolve_model_normalizes_short_alias_from_run_context() {
409        let config = cfg(Some("anthropic/claude-haiku-4-5"), None);
410        let ctx = RunContext {
411            model: Some("sonnet".into()),
412            ..Default::default()
413        };
414        assert_eq!(
415            resolve_model(&config, Some(&ctx)),
416            "anthropic/claude-sonnet-4.5"
417        );
418    }
419
420    /// Empty / whitespace strings are treated as absent at each tier.
421    ///
422    /// Why: A blank `model = ""` should not route to an empty slug; it must fall
423    /// through to the next source.
424    /// What: Empty RunContext + empty agent model + valid override → override.
425    /// Test: this test.
426    #[test]
427    fn resolve_model_skips_empty_strings() {
428        let config = cfg(Some("   "), Some("google/gemma-2-27b-it"));
429        let ctx = RunContext {
430            model: Some("".into()),
431            ..Default::default()
432        };
433        assert_eq!(
434            resolve_model(&config, Some(&ctx)),
435            "google/gemma-2-27b-it",
436            "empty RunContext and empty agent model must fall through"
437        );
438    }
439
440    /// Whitespace-padded slugs are trimmed at every precedence tier.
441    ///
442    /// Why: A TOML or RunContext slug like `"  openai/gpt-4o  "` would otherwise
443    /// route to an invalid, whitespace-padded model id. `non_empty` must return
444    /// the trimmed value, not the original padded slice.
445    /// What: (a) padded `RunContext.model` resolves to the trimmed slug; (b) with
446    /// no RunContext, a padded `agent.model` resolves to its trimmed slug; (c) an
447    /// all-whitespace `agent.model` falls through to the next tier (`model_override`).
448    /// Test: this test.
449    #[test]
450    fn resolve_model_trims_padded_slugs() {
451        // (a) Padded per-call override is trimmed and wins.
452        let config = cfg(Some("anthropic/claude-sonnet-4-5"), None);
453        let ctx = RunContext {
454            model: Some("  openai/gpt-4o  ".into()),
455            ..Default::default()
456        };
457        assert_eq!(
458            resolve_model(&config, Some(&ctx)),
459            "openai/gpt-4o",
460            "padded RunContext.model must resolve to the trimmed slug"
461        );
462
463        // (b) Padded agent.model is trimmed when no RunContext override exists.
464        let config = cfg(Some("  anthropic/claude-haiku-4-5  "), None);
465        assert_eq!(
466            resolve_model(&config, None),
467            "anthropic/claude-haiku-4-5",
468            "padded agent.model must resolve to the trimmed slug"
469        );
470
471        // (c) All-whitespace agent.model falls through to model_override.
472        let config = cfg(Some("   "), Some("deepseek/deepseek-chat"));
473        assert_eq!(
474            resolve_model(&config, None),
475            "deepseek/deepseek-chat",
476            "all-whitespace agent.model must fall through to the next tier"
477        );
478    }
479
480    /// A configured `[llm].max_tokens` is honoured, not clamped to the default.
481    ///
482    /// Why: This is the regression guard for the bug this function fixes — a
483    /// configured cap higher than the old hard-coded 1024 must reach the
484    /// caller unchanged.
485    /// What: `[llm].max_tokens = 8192` resolves to `8192`.
486    /// Test: this test.
487    #[test]
488    fn resolve_max_tokens_honours_configured_value() {
489        let config = AgentConfig {
490            llm: LlmParams {
491                max_tokens: Some(8192),
492                ..Default::default()
493            },
494            ..Default::default()
495        };
496        assert_eq!(resolve_max_tokens(&config), 8192);
497    }
498
499    /// Falls back to `DEFAULT_MAX_TOKENS` when `[llm].max_tokens` is unset.
500    ///
501    /// Why: A run must always resolve to a usable, generous-enough cap even
502    /// when the agent TOML doesn't specify one.
503    /// What: Empty config resolves to `DEFAULT_MAX_TOKENS`.
504    /// Test: this test.
505    #[test]
506    fn resolve_max_tokens_falls_back_to_default() {
507        let config = AgentConfig::default();
508        assert_eq!(resolve_max_tokens(&config), DEFAULT_MAX_TOKENS);
509    }
510
511    // ── #2308: resolve_context_window ───────────────────────────────────────
512
513    /// The real Bedrock-routed Claude Sonnet slug maps to a 200K window.
514    ///
515    /// Why: This is the exact model whose flat 6,000-token compaction
516    /// threshold (#2308) was ~3% of its real context window; the resolver
517    /// must recognise the SAME slug format `resolve_model`/the Bedrock
518    /// dispatch layer actually produce
519    /// (`bedrock/us.anthropic.claude-sonnet-4-6`, see
520    /// `crate::llm::bedrock::bedrock_model_id`'s doctests), not just a bare
521    /// `claude-sonnet-*` slug.
522    /// What: Assert the real Bedrock dispatch slug resolves to 200,000.
523    /// Test: this test.
524    #[test]
525    fn resolve_context_window_maps_bedrock_sonnet_to_200k() {
526        assert_eq!(
527            resolve_context_window("bedrock/us.anthropic.claude-sonnet-4-6"),
528            200_000
529        );
530        assert_eq!(
531            resolve_context_window("bedrock/us.anthropic.claude-opus-4-6"),
532            200_000
533        );
534    }
535
536    /// An `atlascloud/*` slug maps to AtlasCloud's 1.05M-token window (#2536),
537    /// including the nested `atlascloud/openai/gpt-5.6-sol` form.
538    ///
539    /// Why: AtlasCloud's default `openai/gpt-5.6-sol` carries a 1,050,000-token
540    /// context window; keying off the `atlascloud/` routing prefix (not the
541    /// nested `gpt-4o`-adjacent model id) gives the whole family the large window
542    /// so compaction scales correctly.
543    /// What: Assert the nested and a bare AtlasCloud slug resolve to 1,050,000.
544    /// Test: this test.
545    #[test]
546    fn resolve_context_window_maps_atlascloud_to_1m() {
547        assert_eq!(
548            resolve_context_window("atlascloud/openai/gpt-5.6-sol"),
549            1_050_000
550        );
551        assert_eq!(resolve_context_window("atlascloud/deepseek-v3"), 1_050_000);
552    }
553
554    /// An unrecognised model slug falls back to [`DEFAULT_CONTEXT_WINDOW`].
555    ///
556    /// Why: A resolver that panics or silently returns 0 on an unknown slug
557    /// would break every downstream compaction-threshold calculation.
558    /// What: Assert an arbitrary/unknown slug resolves to the default.
559    /// Test: this test.
560    #[test]
561    fn resolve_context_window_falls_back_to_default_for_unknown_model() {
562        assert_eq!(
563            resolve_context_window("some-vendor/unheard-of-model-v1"),
564            DEFAULT_CONTEXT_WINDOW
565        );
566    }
567
568    // ── #2207: resolve_deadline_secs precedence ─────────────────────────────
569
570    /// Serializes access to [`RUN_DEADLINE_ENV_VAR`] for one test closure,
571    /// restoring the prior (absent) state afterward.
572    async fn with_env_deadline<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
573        let _guard = RUN_DEADLINE_ENV_LOCK.lock().await;
574        // SAFETY: test-only env mutation; serialized by `RUN_DEADLINE_ENV_LOCK`.
575        unsafe {
576            match value {
577                Some(v) => std::env::set_var(RUN_DEADLINE_ENV_VAR, v),
578                None => std::env::remove_var(RUN_DEADLINE_ENV_VAR),
579            }
580        }
581        let result = f();
582        unsafe {
583            std::env::remove_var(RUN_DEADLINE_ENV_VAR);
584        }
585        result
586    }
587
588    /// The explicit CLI override wins over both the env var and the default.
589    ///
590    /// Why: `run-task --timeout-seconds` (or `task.run`'s `deadline_secs`
591    /// param) must be the highest-precedence source — an operator setting it
592    /// explicitly for one run must never be silently overridden.
593    /// What: Set the env var to a different value; assert the override wins.
594    /// Test: this test.
595    #[tokio::test]
596    async fn resolve_deadline_secs_cli_override_wins() {
597        with_env_deadline(Some("60"), || {
598            assert_eq!(resolve_deadline_secs(Some(7200)), 7200);
599        })
600        .await;
601    }
602
603    /// The env var wins over the built-in default when no override is given.
604    ///
605    /// Why: `TCODE_RUN_DEADLINE_SECONDS` is the escape-hatch tier for a whole
606    /// invocation without threading a flag through every call site.
607    /// What: No CLI override; env var set; assert the env value is returned.
608    /// Test: this test.
609    #[tokio::test]
610    async fn resolve_deadline_secs_env_wins_over_default() {
611        with_env_deadline(Some("900"), || {
612            assert_eq!(resolve_deadline_secs(None), 900);
613        })
614        .await;
615    }
616
617    /// An unparseable env var falls through to the default rather than
618    /// erroring the whole run.
619    ///
620    /// Why: A misconfigured environment must degrade gracefully, not crash a
621    /// long-running task.
622    /// What: Env var set to a non-numeric string; assert the default wins.
623    /// Test: this test.
624    #[tokio::test]
625    async fn resolve_deadline_secs_invalid_env_falls_back_to_default() {
626        with_env_deadline(Some("not-a-number"), || {
627            assert_eq!(resolve_deadline_secs(None), DEFAULT_RUN_DEADLINE_SECS);
628        })
629        .await;
630    }
631
632    /// Falls back to [`DEFAULT_RUN_DEADLINE_SECS`] when nothing is set.
633    ///
634    /// Why: A run must always resolve to a usable, generous deadline even
635    /// when no override is configured anywhere.
636    /// What: No CLI override, no env var; assert the default.
637    /// Test: this test.
638    #[tokio::test]
639    async fn resolve_deadline_secs_falls_back_to_default() {
640        with_env_deadline(None, || {
641            assert_eq!(resolve_deadline_secs(None), DEFAULT_RUN_DEADLINE_SECS);
642        })
643        .await;
644    }
645}