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/// Resolve the model slug for an invocation.
97///
98/// Why: Centralises the precedence so per-call overrides, per-agent config, and
99/// the global default never disagree across call sites.
100/// What: Returns, in priority order, the first non-empty of:
101/// (1) `run_context.model` (per-call override),
102/// (2) `agent_config.agent.model`,
103/// (3) `agent_config.llm.model_override`,
104/// else (4) [`DEFAULT_MODEL`].
105/// Test: `routing::tests::resolve_model_*` cover every tier.
106pub fn resolve_model(agent_config: &AgentConfig, run_context: Option<&RunContext>) -> String {
107    // 1. Per-call override wins.
108    if let Some(ctx) = run_context
109        && let Some(model) = non_empty(ctx.model.as_deref())
110    {
111        return model.to_string();
112    }
113
114    // 2. Agent-level model.
115    if let Some(model) = non_empty(agent_config.agent.model.as_deref()) {
116        return model.to_string();
117    }
118
119    // 3. `[llm].model_override` (lower precedence than `[agent].model`).
120    if let Some(model) = non_empty(agent_config.llm.model_override.as_deref()) {
121        return model.to_string();
122    }
123
124    // 4. Built-in default.
125    DEFAULT_MODEL.to_string()
126}
127
128/// Resolve the per-turn completion-token cap for an invocation.
129///
130/// Why: `[llm].max_tokens` is how an operator declares that an agent's turns
131/// need a larger completion budget than the default (e.g. an engineer that
132/// writes whole files needs far more than a chat-only PM). Before this fix,
133/// every call site building an `AgentLoopConfig` ignored the agent's
134/// `[llm].max_tokens` entirely and the loop hard-coded a 1024-token cap,
135/// truncating any turn that needed to emit more (#run_task-maxtokens-bug).
136/// What: Returns `agent_config.llm.max_tokens` when set, else
137/// [`DEFAULT_MAX_TOKENS`]. There is no per-call `RunContext` override yet —
138/// the config-file value or the built-in default are the only two tiers.
139/// Test: `routing::tests::resolve_max_tokens_*`.
140pub fn resolve_max_tokens(agent_config: &AgentConfig) -> u32 {
141    agent_config.llm.max_tokens.unwrap_or(DEFAULT_MAX_TOKENS)
142}
143
144/// Treat empty/whitespace-only strings as absent.
145///
146/// Why: An empty `model = ""` in TOML or an empty `RunContext.model` should fall
147/// through to the next tier rather than route to a blank slug.
148/// What: Returns `Some(trimmed-original)` only when the value has non-whitespace
149/// content; `None` otherwise.
150/// Test: `routing::tests::resolve_model_skips_empty_strings`.
151fn non_empty(value: Option<&str>) -> Option<&str> {
152    value.and_then(|v| {
153        let trimmed = v.trim();
154        if trimmed.is_empty() {
155            None
156        } else {
157            Some(trimmed)
158        }
159    })
160}
161
162/// Serializes every test in this module that sets/reads the process-wide
163/// [`RUN_DEADLINE_ENV_VAR`] — `cargo test` runs tests in parallel within one
164/// binary, and an unguarded `set_var`/`remove_var` pair would race across
165/// tests (mirrors `crate::mode::MODE_ENV_LOCK`'s identical rationale).
166#[cfg(test)]
167pub(crate) static RUN_DEADLINE_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
168
169// ── Tests ─────────────────────────────────────────────────────────────────────
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use crate::agents::config::{AgentInfo, LlmParams};
175
176    /// Build an `AgentConfig` with the given agent model and `model_override`.
177    fn cfg(agent_model: Option<&str>, override_model: Option<&str>) -> AgentConfig {
178        AgentConfig {
179            agent: AgentInfo {
180                name: "test-agent".into(),
181                model: agent_model.map(str::to_string),
182                ..Default::default()
183            },
184            llm: LlmParams {
185                model_override: override_model.map(str::to_string),
186                ..Default::default()
187            },
188            ..Default::default()
189        }
190    }
191
192    /// `RunContext.model` wins over agent config and default.
193    ///
194    /// Why: Per-call overrides must take precedence so a caller can pin a model
195    /// for a single invocation.
196    /// What: Provide all three sources; assert the RunContext slug is returned.
197    /// Test: this test.
198    #[test]
199    fn resolve_model_run_context_wins() {
200        let config = cfg(Some("anthropic/claude-sonnet-4-5"), Some("qwen/qwen-2.5"));
201        let ctx = RunContext {
202            model: Some("openai/gpt-4o".into()),
203            ..Default::default()
204        };
205        assert_eq!(resolve_model(&config, Some(&ctx)), "openai/gpt-4o");
206    }
207
208    /// `[agent].model` wins when no RunContext override is present.
209    ///
210    /// Why: The agent's declared model is the next authority below per-call.
211    /// What: No RunContext model; assert the agent slug is returned over the
212    /// `model_override` and the default.
213    /// Test: this test.
214    #[test]
215    fn resolve_model_agent_config_wins_over_default() {
216        let config = cfg(Some("anthropic/claude-haiku-4-5"), Some("qwen/qwen-2.5"));
217        assert_eq!(
218            resolve_model(&config, None),
219            "anthropic/claude-haiku-4-5",
220            "agent.model must win over model_override and default"
221        );
222    }
223
224    /// `[llm].model_override` is used when `[agent].model` is absent.
225    ///
226    /// Why: `model_override` is the documented lower-precedence config slot.
227    /// What: Agent model `None`, override set; assert override is returned.
228    /// Test: this test.
229    #[test]
230    fn resolve_model_uses_model_override_when_agent_absent() {
231        let config = cfg(None, Some("deepseek/deepseek-chat"));
232        assert_eq!(resolve_model(&config, None), "deepseek/deepseek-chat");
233    }
234
235    /// Falls back to `DEFAULT_MODEL` when nothing is specified.
236    ///
237    /// Why: A run must always resolve to a usable slug.
238    /// What: Empty config and no RunContext; assert the default.
239    /// Test: this test.
240    #[test]
241    fn resolve_model_falls_back_to_default() {
242        let config = cfg(None, None);
243        assert_eq!(resolve_model(&config, None), DEFAULT_MODEL);
244    }
245
246    /// Empty / whitespace strings are treated as absent at each tier.
247    ///
248    /// Why: A blank `model = ""` should not route to an empty slug; it must fall
249    /// through to the next source.
250    /// What: Empty RunContext + empty agent model + valid override → override.
251    /// Test: this test.
252    #[test]
253    fn resolve_model_skips_empty_strings() {
254        let config = cfg(Some("   "), Some("google/gemma-2-27b-it"));
255        let ctx = RunContext {
256            model: Some("".into()),
257            ..Default::default()
258        };
259        assert_eq!(
260            resolve_model(&config, Some(&ctx)),
261            "google/gemma-2-27b-it",
262            "empty RunContext and empty agent model must fall through"
263        );
264    }
265
266    /// Whitespace-padded slugs are trimmed at every precedence tier.
267    ///
268    /// Why: A TOML or RunContext slug like `"  openai/gpt-4o  "` would otherwise
269    /// route to an invalid, whitespace-padded model id. `non_empty` must return
270    /// the trimmed value, not the original padded slice.
271    /// What: (a) padded `RunContext.model` resolves to the trimmed slug; (b) with
272    /// no RunContext, a padded `agent.model` resolves to its trimmed slug; (c) an
273    /// all-whitespace `agent.model` falls through to the next tier (`model_override`).
274    /// Test: this test.
275    #[test]
276    fn resolve_model_trims_padded_slugs() {
277        // (a) Padded per-call override is trimmed and wins.
278        let config = cfg(Some("anthropic/claude-sonnet-4-5"), None);
279        let ctx = RunContext {
280            model: Some("  openai/gpt-4o  ".into()),
281            ..Default::default()
282        };
283        assert_eq!(
284            resolve_model(&config, Some(&ctx)),
285            "openai/gpt-4o",
286            "padded RunContext.model must resolve to the trimmed slug"
287        );
288
289        // (b) Padded agent.model is trimmed when no RunContext override exists.
290        let config = cfg(Some("  anthropic/claude-haiku-4-5  "), None);
291        assert_eq!(
292            resolve_model(&config, None),
293            "anthropic/claude-haiku-4-5",
294            "padded agent.model must resolve to the trimmed slug"
295        );
296
297        // (c) All-whitespace agent.model falls through to model_override.
298        let config = cfg(Some("   "), Some("deepseek/deepseek-chat"));
299        assert_eq!(
300            resolve_model(&config, None),
301            "deepseek/deepseek-chat",
302            "all-whitespace agent.model must fall through to the next tier"
303        );
304    }
305
306    /// A configured `[llm].max_tokens` is honoured, not clamped to the default.
307    ///
308    /// Why: This is the regression guard for the bug this function fixes — a
309    /// configured cap higher than the old hard-coded 1024 must reach the
310    /// caller unchanged.
311    /// What: `[llm].max_tokens = 8192` resolves to `8192`.
312    /// Test: this test.
313    #[test]
314    fn resolve_max_tokens_honours_configured_value() {
315        let config = AgentConfig {
316            llm: LlmParams {
317                max_tokens: Some(8192),
318                ..Default::default()
319            },
320            ..Default::default()
321        };
322        assert_eq!(resolve_max_tokens(&config), 8192);
323    }
324
325    /// Falls back to `DEFAULT_MAX_TOKENS` when `[llm].max_tokens` is unset.
326    ///
327    /// Why: A run must always resolve to a usable, generous-enough cap even
328    /// when the agent TOML doesn't specify one.
329    /// What: Empty config resolves to `DEFAULT_MAX_TOKENS`.
330    /// Test: this test.
331    #[test]
332    fn resolve_max_tokens_falls_back_to_default() {
333        let config = AgentConfig::default();
334        assert_eq!(resolve_max_tokens(&config), DEFAULT_MAX_TOKENS);
335    }
336
337    // ── #2207: resolve_deadline_secs precedence ─────────────────────────────
338
339    /// Serializes access to [`RUN_DEADLINE_ENV_VAR`] for one test closure,
340    /// restoring the prior (absent) state afterward.
341    async fn with_env_deadline<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
342        let _guard = RUN_DEADLINE_ENV_LOCK.lock().await;
343        // SAFETY: test-only env mutation; serialized by `RUN_DEADLINE_ENV_LOCK`.
344        unsafe {
345            match value {
346                Some(v) => std::env::set_var(RUN_DEADLINE_ENV_VAR, v),
347                None => std::env::remove_var(RUN_DEADLINE_ENV_VAR),
348            }
349        }
350        let result = f();
351        unsafe {
352            std::env::remove_var(RUN_DEADLINE_ENV_VAR);
353        }
354        result
355    }
356
357    /// The explicit CLI override wins over both the env var and the default.
358    ///
359    /// Why: `run-task --timeout-seconds` (or `task.run`'s `deadline_secs`
360    /// param) must be the highest-precedence source — an operator setting it
361    /// explicitly for one run must never be silently overridden.
362    /// What: Set the env var to a different value; assert the override wins.
363    /// Test: this test.
364    #[tokio::test]
365    async fn resolve_deadline_secs_cli_override_wins() {
366        with_env_deadline(Some("60"), || {
367            assert_eq!(resolve_deadline_secs(Some(7200)), 7200);
368        })
369        .await;
370    }
371
372    /// The env var wins over the built-in default when no override is given.
373    ///
374    /// Why: `TCODE_RUN_DEADLINE_SECONDS` is the escape-hatch tier for a whole
375    /// invocation without threading a flag through every call site.
376    /// What: No CLI override; env var set; assert the env value is returned.
377    /// Test: this test.
378    #[tokio::test]
379    async fn resolve_deadline_secs_env_wins_over_default() {
380        with_env_deadline(Some("900"), || {
381            assert_eq!(resolve_deadline_secs(None), 900);
382        })
383        .await;
384    }
385
386    /// An unparseable env var falls through to the default rather than
387    /// erroring the whole run.
388    ///
389    /// Why: A misconfigured environment must degrade gracefully, not crash a
390    /// long-running task.
391    /// What: Env var set to a non-numeric string; assert the default wins.
392    /// Test: this test.
393    #[tokio::test]
394    async fn resolve_deadline_secs_invalid_env_falls_back_to_default() {
395        with_env_deadline(Some("not-a-number"), || {
396            assert_eq!(resolve_deadline_secs(None), DEFAULT_RUN_DEADLINE_SECS);
397        })
398        .await;
399    }
400
401    /// Falls back to [`DEFAULT_RUN_DEADLINE_SECS`] when nothing is set.
402    ///
403    /// Why: A run must always resolve to a usable, generous deadline even
404    /// when no override is configured anywhere.
405    /// What: No CLI override, no env var; assert the default.
406    /// Test: this test.
407    #[tokio::test]
408    async fn resolve_deadline_secs_falls_back_to_default() {
409        with_env_deadline(None, || {
410            assert_eq!(resolve_deadline_secs(None), DEFAULT_RUN_DEADLINE_SECS);
411        })
412        .await;
413    }
414}