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/// Fallback context-window size (in tokens) for a model slug this resolver
129/// does not recognise.
130///
131/// Why: [`resolve_context_window`] must always return a usable number even
132/// for an unlisted/unknown slug (a new provider, a typo'd override, etc.) —
133/// 128,000 is a conservative, widely-supported floor shared by several
134/// mainstream hosted models (e.g. `gpt-4o`), so an unknown model is treated
135/// no more generously than that.
136/// What: The fallback tier of [`resolve_context_window`].
137/// Test: `routing::tests::resolve_context_window_falls_back_to_default_for_unknown_model`.
138pub const DEFAULT_CONTEXT_WINDOW: usize = 128_000;
139
140/// Resolve the real context-window size (in tokens) for a model slug.
141///
142/// Why: #2308 — `CompactionConfig::default()`'s flat `token_threshold: 6_000`
143/// is model-blind: ~3% of Bedrock Claude Sonnet's real 200K-token window, so
144/// ordinary coding turns (post-#2261 tool-call-arg counting) blow through it
145/// constantly and trigger pathological re-compaction. Compaction must instead
146/// scale with the model actually in use, which means a resolver is needed
147/// alongside [`resolve_model`] to turn a slug into a window size before
148/// [`crate::agent_loop::CompactionConfig::for_context_window`] can compute a
149/// proportional threshold.
150/// What: A minimal substring/format table, checked in order: (1) any slug
151/// containing `claude-sonnet` or `claude-opus` (covers both the bare
152/// Anthropic slug and the Bedrock-routed
153/// `bedrock/us.anthropic.claude-sonnet-4-6` / `-opus-*` inference-profile
154/// format, see `crate::llm::bedrock::bedrock_model_id`) -> 200,000; (2) any
155/// slug beginning with the `atlascloud/` routing prefix -> 1,050,000 (#2536 —
156/// AtlasCloud's catalog default `openai/gpt-5.6-sol` has a 1.05M-token window,
157/// keyed off the routing prefix rather than the nested model id so the whole
158/// AtlasCloud family gets the large window); (3) any slug containing `gpt-4o` ->
159/// 128,000; else (4) [`DEFAULT_CONTEXT_WINDOW`]. Deliberately NOT a config file
160/// or per-agent override — the window size is a property of the model itself, not
161/// something an operator should need to tune per project.
162/// Test: `routing::tests::resolve_context_window_maps_bedrock_sonnet_to_200k`,
163/// `routing::tests::resolve_context_window_maps_atlascloud_to_1m`,
164/// `routing::tests::resolve_context_window_falls_back_to_default_for_unknown_model`.
165pub fn resolve_context_window(model: &str) -> usize {
166 if model.contains("claude-sonnet") || model.contains("claude-opus") {
167 200_000
168 } else if model.starts_with("atlascloud/") {
169 1_050_000
170 } else if model.contains("gpt-4o") {
171 128_000
172 } else {
173 DEFAULT_CONTEXT_WINDOW
174 }
175}
176
177/// Resolve the per-turn completion-token cap for an invocation.
178///
179/// Why: `[llm].max_tokens` is how an operator declares that an agent's turns
180/// need a larger completion budget than the default (e.g. an engineer that
181/// writes whole files needs far more than a chat-only PM). Before this fix,
182/// every call site building an `AgentLoopConfig` ignored the agent's
183/// `[llm].max_tokens` entirely and the loop hard-coded a 1024-token cap,
184/// truncating any turn that needed to emit more (#run_task-maxtokens-bug).
185/// What: Returns `agent_config.llm.max_tokens` when set, else
186/// [`DEFAULT_MAX_TOKENS`]. There is no per-call `RunContext` override yet —
187/// the config-file value or the built-in default are the only two tiers.
188/// Test: `routing::tests::resolve_max_tokens_*`.
189pub fn resolve_max_tokens(agent_config: &AgentConfig) -> u32 {
190 agent_config.llm.max_tokens.unwrap_or(DEFAULT_MAX_TOKENS)
191}
192
193/// Treat empty/whitespace-only strings as absent.
194///
195/// Why: An empty `model = ""` in TOML or an empty `RunContext.model` should fall
196/// through to the next tier rather than route to a blank slug.
197/// What: Returns `Some(trimmed-original)` only when the value has non-whitespace
198/// content; `None` otherwise.
199/// Test: `routing::tests::resolve_model_skips_empty_strings`.
200fn non_empty(value: Option<&str>) -> Option<&str> {
201 value.and_then(|v| {
202 let trimmed = v.trim();
203 if trimmed.is_empty() {
204 None
205 } else {
206 Some(trimmed)
207 }
208 })
209}
210
211/// Serializes every test in this module that sets/reads the process-wide
212/// [`RUN_DEADLINE_ENV_VAR`] — `cargo test` runs tests in parallel within one
213/// binary, and an unguarded `set_var`/`remove_var` pair would race across
214/// tests (mirrors `crate::mode::MODE_ENV_LOCK`'s identical rationale).
215#[cfg(test)]
216pub(crate) static RUN_DEADLINE_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
217
218// ── Tests ─────────────────────────────────────────────────────────────────────
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223 use crate::agents::config::{AgentInfo, LlmParams};
224
225 /// Build an `AgentConfig` with the given agent model and `model_override`.
226 fn cfg(agent_model: Option<&str>, override_model: Option<&str>) -> AgentConfig {
227 AgentConfig {
228 agent: AgentInfo {
229 name: "test-agent".into(),
230 model: agent_model.map(str::to_string),
231 ..Default::default()
232 },
233 llm: LlmParams {
234 model_override: override_model.map(str::to_string),
235 ..Default::default()
236 },
237 ..Default::default()
238 }
239 }
240
241 /// `RunContext.model` wins over agent config and default.
242 ///
243 /// Why: Per-call overrides must take precedence so a caller can pin a model
244 /// for a single invocation.
245 /// What: Provide all three sources; assert the RunContext slug is returned.
246 /// Test: this test.
247 #[test]
248 fn resolve_model_run_context_wins() {
249 let config = cfg(Some("anthropic/claude-sonnet-4-5"), Some("qwen/qwen-2.5"));
250 let ctx = RunContext {
251 model: Some("openai/gpt-4o".into()),
252 ..Default::default()
253 };
254 assert_eq!(resolve_model(&config, Some(&ctx)), "openai/gpt-4o");
255 }
256
257 /// `[agent].model` wins when no RunContext override is present.
258 ///
259 /// Why: The agent's declared model is the next authority below per-call.
260 /// What: No RunContext model; assert the agent slug is returned over the
261 /// `model_override` and the default.
262 /// Test: this test.
263 #[test]
264 fn resolve_model_agent_config_wins_over_default() {
265 let config = cfg(Some("anthropic/claude-haiku-4-5"), Some("qwen/qwen-2.5"));
266 assert_eq!(
267 resolve_model(&config, None),
268 "anthropic/claude-haiku-4-5",
269 "agent.model must win over model_override and default"
270 );
271 }
272
273 /// `[llm].model_override` is used when `[agent].model` is absent.
274 ///
275 /// Why: `model_override` is the documented lower-precedence config slot.
276 /// What: Agent model `None`, override set; assert override is returned.
277 /// Test: this test.
278 #[test]
279 fn resolve_model_uses_model_override_when_agent_absent() {
280 let config = cfg(None, Some("deepseek/deepseek-chat"));
281 assert_eq!(resolve_model(&config, None), "deepseek/deepseek-chat");
282 }
283
284 /// Falls back to `DEFAULT_MODEL` when nothing is specified.
285 ///
286 /// Why: A run must always resolve to a usable slug.
287 /// What: Empty config and no RunContext; assert the default.
288 /// Test: this test.
289 #[test]
290 fn resolve_model_falls_back_to_default() {
291 let config = cfg(None, None);
292 assert_eq!(resolve_model(&config, None), DEFAULT_MODEL);
293 }
294
295 /// Empty / whitespace strings are treated as absent at each tier.
296 ///
297 /// Why: A blank `model = ""` should not route to an empty slug; it must fall
298 /// through to the next source.
299 /// What: Empty RunContext + empty agent model + valid override → override.
300 /// Test: this test.
301 #[test]
302 fn resolve_model_skips_empty_strings() {
303 let config = cfg(Some(" "), Some("google/gemma-2-27b-it"));
304 let ctx = RunContext {
305 model: Some("".into()),
306 ..Default::default()
307 };
308 assert_eq!(
309 resolve_model(&config, Some(&ctx)),
310 "google/gemma-2-27b-it",
311 "empty RunContext and empty agent model must fall through"
312 );
313 }
314
315 /// Whitespace-padded slugs are trimmed at every precedence tier.
316 ///
317 /// Why: A TOML or RunContext slug like `" openai/gpt-4o "` would otherwise
318 /// route to an invalid, whitespace-padded model id. `non_empty` must return
319 /// the trimmed value, not the original padded slice.
320 /// What: (a) padded `RunContext.model` resolves to the trimmed slug; (b) with
321 /// no RunContext, a padded `agent.model` resolves to its trimmed slug; (c) an
322 /// all-whitespace `agent.model` falls through to the next tier (`model_override`).
323 /// Test: this test.
324 #[test]
325 fn resolve_model_trims_padded_slugs() {
326 // (a) Padded per-call override is trimmed and wins.
327 let config = cfg(Some("anthropic/claude-sonnet-4-5"), None);
328 let ctx = RunContext {
329 model: Some(" openai/gpt-4o ".into()),
330 ..Default::default()
331 };
332 assert_eq!(
333 resolve_model(&config, Some(&ctx)),
334 "openai/gpt-4o",
335 "padded RunContext.model must resolve to the trimmed slug"
336 );
337
338 // (b) Padded agent.model is trimmed when no RunContext override exists.
339 let config = cfg(Some(" anthropic/claude-haiku-4-5 "), None);
340 assert_eq!(
341 resolve_model(&config, None),
342 "anthropic/claude-haiku-4-5",
343 "padded agent.model must resolve to the trimmed slug"
344 );
345
346 // (c) All-whitespace agent.model falls through to model_override.
347 let config = cfg(Some(" "), Some("deepseek/deepseek-chat"));
348 assert_eq!(
349 resolve_model(&config, None),
350 "deepseek/deepseek-chat",
351 "all-whitespace agent.model must fall through to the next tier"
352 );
353 }
354
355 /// A configured `[llm].max_tokens` is honoured, not clamped to the default.
356 ///
357 /// Why: This is the regression guard for the bug this function fixes — a
358 /// configured cap higher than the old hard-coded 1024 must reach the
359 /// caller unchanged.
360 /// What: `[llm].max_tokens = 8192` resolves to `8192`.
361 /// Test: this test.
362 #[test]
363 fn resolve_max_tokens_honours_configured_value() {
364 let config = AgentConfig {
365 llm: LlmParams {
366 max_tokens: Some(8192),
367 ..Default::default()
368 },
369 ..Default::default()
370 };
371 assert_eq!(resolve_max_tokens(&config), 8192);
372 }
373
374 /// Falls back to `DEFAULT_MAX_TOKENS` when `[llm].max_tokens` is unset.
375 ///
376 /// Why: A run must always resolve to a usable, generous-enough cap even
377 /// when the agent TOML doesn't specify one.
378 /// What: Empty config resolves to `DEFAULT_MAX_TOKENS`.
379 /// Test: this test.
380 #[test]
381 fn resolve_max_tokens_falls_back_to_default() {
382 let config = AgentConfig::default();
383 assert_eq!(resolve_max_tokens(&config), DEFAULT_MAX_TOKENS);
384 }
385
386 // ── #2308: resolve_context_window ───────────────────────────────────────
387
388 /// The real Bedrock-routed Claude Sonnet slug maps to a 200K window.
389 ///
390 /// Why: This is the exact model whose flat 6,000-token compaction
391 /// threshold (#2308) was ~3% of its real context window; the resolver
392 /// must recognise the SAME slug format `resolve_model`/the Bedrock
393 /// dispatch layer actually produce
394 /// (`bedrock/us.anthropic.claude-sonnet-4-6`, see
395 /// `crate::llm::bedrock::bedrock_model_id`'s doctests), not just a bare
396 /// `claude-sonnet-*` slug.
397 /// What: Assert the real Bedrock dispatch slug resolves to 200,000.
398 /// Test: this test.
399 #[test]
400 fn resolve_context_window_maps_bedrock_sonnet_to_200k() {
401 assert_eq!(
402 resolve_context_window("bedrock/us.anthropic.claude-sonnet-4-6"),
403 200_000
404 );
405 assert_eq!(
406 resolve_context_window("bedrock/us.anthropic.claude-opus-4-6"),
407 200_000
408 );
409 }
410
411 /// An `atlascloud/*` slug maps to AtlasCloud's 1.05M-token window (#2536),
412 /// including the nested `atlascloud/openai/gpt-5.6-sol` form.
413 ///
414 /// Why: AtlasCloud's default `openai/gpt-5.6-sol` carries a 1,050,000-token
415 /// context window; keying off the `atlascloud/` routing prefix (not the
416 /// nested `gpt-4o`-adjacent model id) gives the whole family the large window
417 /// so compaction scales correctly.
418 /// What: Assert the nested and a bare AtlasCloud slug resolve to 1,050,000.
419 /// Test: this test.
420 #[test]
421 fn resolve_context_window_maps_atlascloud_to_1m() {
422 assert_eq!(
423 resolve_context_window("atlascloud/openai/gpt-5.6-sol"),
424 1_050_000
425 );
426 assert_eq!(resolve_context_window("atlascloud/deepseek-v3"), 1_050_000);
427 }
428
429 /// An unrecognised model slug falls back to [`DEFAULT_CONTEXT_WINDOW`].
430 ///
431 /// Why: A resolver that panics or silently returns 0 on an unknown slug
432 /// would break every downstream compaction-threshold calculation.
433 /// What: Assert an arbitrary/unknown slug resolves to the default.
434 /// Test: this test.
435 #[test]
436 fn resolve_context_window_falls_back_to_default_for_unknown_model() {
437 assert_eq!(
438 resolve_context_window("some-vendor/unheard-of-model-v1"),
439 DEFAULT_CONTEXT_WINDOW
440 );
441 }
442
443 // ── #2207: resolve_deadline_secs precedence ─────────────────────────────
444
445 /// Serializes access to [`RUN_DEADLINE_ENV_VAR`] for one test closure,
446 /// restoring the prior (absent) state afterward.
447 async fn with_env_deadline<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
448 let _guard = RUN_DEADLINE_ENV_LOCK.lock().await;
449 // SAFETY: test-only env mutation; serialized by `RUN_DEADLINE_ENV_LOCK`.
450 unsafe {
451 match value {
452 Some(v) => std::env::set_var(RUN_DEADLINE_ENV_VAR, v),
453 None => std::env::remove_var(RUN_DEADLINE_ENV_VAR),
454 }
455 }
456 let result = f();
457 unsafe {
458 std::env::remove_var(RUN_DEADLINE_ENV_VAR);
459 }
460 result
461 }
462
463 /// The explicit CLI override wins over both the env var and the default.
464 ///
465 /// Why: `run-task --timeout-seconds` (or `task.run`'s `deadline_secs`
466 /// param) must be the highest-precedence source — an operator setting it
467 /// explicitly for one run must never be silently overridden.
468 /// What: Set the env var to a different value; assert the override wins.
469 /// Test: this test.
470 #[tokio::test]
471 async fn resolve_deadline_secs_cli_override_wins() {
472 with_env_deadline(Some("60"), || {
473 assert_eq!(resolve_deadline_secs(Some(7200)), 7200);
474 })
475 .await;
476 }
477
478 /// The env var wins over the built-in default when no override is given.
479 ///
480 /// Why: `TCODE_RUN_DEADLINE_SECONDS` is the escape-hatch tier for a whole
481 /// invocation without threading a flag through every call site.
482 /// What: No CLI override; env var set; assert the env value is returned.
483 /// Test: this test.
484 #[tokio::test]
485 async fn resolve_deadline_secs_env_wins_over_default() {
486 with_env_deadline(Some("900"), || {
487 assert_eq!(resolve_deadline_secs(None), 900);
488 })
489 .await;
490 }
491
492 /// An unparseable env var falls through to the default rather than
493 /// erroring the whole run.
494 ///
495 /// Why: A misconfigured environment must degrade gracefully, not crash a
496 /// long-running task.
497 /// What: Env var set to a non-numeric string; assert the default wins.
498 /// Test: this test.
499 #[tokio::test]
500 async fn resolve_deadline_secs_invalid_env_falls_back_to_default() {
501 with_env_deadline(Some("not-a-number"), || {
502 assert_eq!(resolve_deadline_secs(None), DEFAULT_RUN_DEADLINE_SECS);
503 })
504 .await;
505 }
506
507 /// Falls back to [`DEFAULT_RUN_DEADLINE_SECS`] when nothing is set.
508 ///
509 /// Why: A run must always resolve to a usable, generous deadline even
510 /// when no override is configured anywhere.
511 /// What: No CLI override, no env var; assert the default.
512 /// Test: this test.
513 #[tokio::test]
514 async fn resolve_deadline_secs_falls_back_to_default() {
515 with_env_deadline(None, || {
516 assert_eq!(resolve_deadline_secs(None), DEFAULT_RUN_DEADLINE_SECS);
517 })
518 .await;
519 }
520}