Skip to main content

lean_ctx/proxy/
effort_routing.rs

1//! Per-turn effort routing (#1148, opt-in dynamic thinking budget).
2//!
3//! Unlike the static `effort.rs` which applies a constant reasoning level
4//! across all turns (for cache stability), this module classifies each turn
5//! and adjusts thinking effort dynamically.
6//!
7//! **Opt-in only** (`proxy.effort_routing = true`). When disabled, the static
8//! `effort.rs` path remains the sole controller. When enabled, this module
9//! overrides the static level with a per-turn classification.
10//!
11//! ## Cache stability tradeoff
12//!
13//! Provider prompt caches (Anthropic `cache_control`, OpenAI prefix caching)
14//! break when reasoning parameters change. This module accepts that tradeoff
15//! because:
16//! 1. Output tokens on Opus-class models cost **5x** input tokens — savings
17//!    from reduced thinking often exceed the cache-miss penalty.
18//! 2. Routine turns (file reads, passing tests) generate disproportionate
19//!    thinking waste for trivial tool-result acknowledgements.
20//! 3. The module uses a **two-level** strategy (not N levels) to minimize cache
21//!    key diversity: `routine` or `full` — only two cache prefixes to warm.
22//!
23//! ## Classification
24//!
25//! A turn is classified as **routine** when the last assistant message was a
26//! tool call and the tool result indicates success on a non-complex operation:
27//! - File read (tool_use with `ctx_read`, `read_file`, `Read`)
28//! - Successful shell command (exit_code == 0, no error indicators)
29//! - Search results (grep/glob/find)
30//! - Status checks (git status, test passing)
31//!
32//! A turn is classified as **full** (keep maximum thinking) when:
33//! - The user sent a new message (requires understanding intent)
34//! - The tool result contains errors/failures
35//! - Multiple tool results arrived (complex multi-step)
36//! - The content is architecturally complex (refactoring, debugging)
37
38use serde_json::Value;
39use std::sync::atomic::{AtomicU64, Ordering};
40
41use crate::core::config::Effort;
42
43/// Turn classification result.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum TurnClass {
46    /// Routine tool-result acknowledgement — minimize thinking.
47    Routine,
48    /// Full complexity — keep maximum thinking effort.
49    Full,
50}
51
52/// Statistics for monitoring effort routing effectiveness.
53#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
54pub struct RoutingStats {
55    pub routine_count: u64,
56    pub full_count: u64,
57}
58
59static ESTIMATED_OUTPUT_TOKENS_WITHOUT_ROUTING: AtomicU64 = AtomicU64::new(0);
60static ACTUAL_EFFORT_BUDGET_TOKENS: AtomicU64 = AtomicU64::new(0);
61
62#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
63pub struct EffortSavingsStats {
64    pub estimated_output_tokens_without_routing: u64,
65    pub actual_effort_budget_tokens: u64,
66}
67
68static ROUTINE_COUNT: AtomicU64 = AtomicU64::new(0);
69static FULL_COUNT: AtomicU64 = AtomicU64::new(0);
70
71/// Classify the current turn based on the message array.
72/// Returns `Routine` if the latest context is a simple tool-result
73/// acknowledgement, `Full` otherwise.
74pub fn classify_turn(messages: &Value) -> TurnClass {
75    let Some(arr) = messages.as_array() else {
76        return TurnClass::Full;
77    };
78
79    if arr.is_empty() {
80        return TurnClass::Full;
81    }
82
83    let last = &arr[arr.len() - 1];
84    let role = last.get("role").and_then(Value::as_str).unwrap_or("");
85
86    if role == "tool" {
87        classify_tool_result(last, arr)
88    } else {
89        TurnClass::Full
90    }
91}
92
93/// Classify based on OpenAI Responses API `input` array (different structure).
94pub fn classify_turn_responses(input: &Value) -> TurnClass {
95    let Some(arr) = input.as_array() else {
96        return TurnClass::Full;
97    };
98    if arr.is_empty() {
99        return TurnClass::Full;
100    }
101
102    // In Responses API, look for the last item's type.
103    let last = &arr[arr.len() - 1];
104    let item_type = last.get("type").and_then(Value::as_str).unwrap_or("");
105
106    if item_type == "function_call_output" {
107        let output = last.get("output").and_then(Value::as_str).unwrap_or("");
108        if is_routine_tool_output(output) {
109            return TurnClass::Routine;
110        }
111    }
112
113    TurnClass::Full
114}
115
116/// Classify based on Anthropic messages structure.
117pub fn classify_turn_anthropic(messages: &Value) -> TurnClass {
118    let Some(arr) = messages.as_array() else {
119        return TurnClass::Full;
120    };
121    if arr.is_empty() {
122        return TurnClass::Full;
123    }
124
125    let last = &arr[arr.len() - 1];
126    let role = last.get("role").and_then(Value::as_str).unwrap_or("");
127
128    if role != "user" {
129        return TurnClass::Full;
130    }
131
132    // Anthropic puts tool_results in user messages with content array.
133    let content = last.get("content");
134    if let Some(Value::Array(blocks)) = content {
135        let all_tool_results = !blocks.is_empty()
136            && blocks
137                .iter()
138                .all(|b| b.get("type").and_then(Value::as_str) == Some("tool_result"));
139
140        if all_tool_results {
141            // Check if any tool result has errors.
142            let has_errors = blocks.iter().any(|b| {
143                b.get("is_error") == Some(&Value::Bool(true))
144                    || b.get("content")
145                        .and_then(|c| c.as_str().or_else(|| extract_text_from_content(c)))
146                        .is_some_and(contains_error_indicators)
147            });
148
149            if has_errors {
150                return TurnClass::Full;
151            }
152
153            // Multiple tool results → likely complex multi-step.
154            if blocks.len() > 3 {
155                return TurnClass::Full;
156            }
157
158            // Check individual results.
159            let all_routine = blocks.iter().all(|b| {
160                let text = b
161                    .get("content")
162                    .and_then(|c| c.as_str().or_else(|| extract_text_from_content(c)))
163                    .unwrap_or("");
164                is_routine_tool_output(text)
165            });
166
167            if all_routine {
168                return TurnClass::Routine;
169            }
170        }
171    }
172
173    TurnClass::Full
174}
175
176/// Map a turn classification to the effort level to apply.
177/// `base` is the operator's configured static effort level.
178pub fn effort_for_turn(class: TurnClass, base: Effort) -> Effort {
179    match class {
180        TurnClass::Routine => {
181            ROUTINE_COUNT.fetch_add(1, Ordering::Relaxed);
182            // Routine turns get minimal thinking regardless of base.
183            Effort::Minimal
184        }
185        TurnClass::Full => {
186            FULL_COUNT.fetch_add(1, Ordering::Relaxed);
187            base
188        }
189    }
190}
191
192/// Adjust effort from a classifier intent while preserving the configured
193/// effort for intents that are not clearly simple reads or coding work.
194pub fn intent_aware_effort(intent: &str, base_effort: Effort) -> Effort {
195    let intent = intent.to_ascii_lowercase();
196    if [
197        "code",
198        "coding",
199        "fix",
200        "implement",
201        "refactor",
202        "debug",
203        "build",
204        "patch",
205        "test",
206    ]
207    .iter()
208    .any(|term| intent.contains(term))
209    {
210        Effort::High
211    } else if [
212        "read",
213        "list",
214        "show",
215        "explain",
216        "summarize",
217        "status",
218        "search",
219        "lookup",
220    ]
221    .iter()
222    .any(|term| intent.contains(term))
223    {
224        Effort::Minimal
225    } else {
226        base_effort
227    }
228}
229
230/// Snapshot routing statistics.
231pub fn stats() -> RoutingStats {
232    RoutingStats {
233        routine_count: ROUTINE_COUNT.load(Ordering::Relaxed),
234        full_count: FULL_COUNT.load(Ordering::Relaxed),
235    }
236}
237
238pub fn effort_savings_stats() -> EffortSavingsStats {
239    EffortSavingsStats {
240        estimated_output_tokens_without_routing: ESTIMATED_OUTPUT_TOKENS_WITHOUT_ROUTING
241            .load(Ordering::Relaxed),
242        actual_effort_budget_tokens: ACTUAL_EFFORT_BUDGET_TOKENS.load(Ordering::Relaxed),
243    }
244}
245
246/// Dynamic reasoning budget selected from the current request context.
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
248pub struct TaskComplexity {
249    pub score: u8,
250    pub effort: Effort,
251    pub budget_tokens: u32,
252}
253
254impl TaskComplexity {
255    pub const fn from_score(score: u8) -> Self {
256        match score {
257            1 => Self {
258                score: 1,
259                effort: Effort::Low,
260                budget_tokens: 1_024,
261            },
262            2 => Self {
263                score: 2,
264                effort: Effort::Low,
265                budget_tokens: 2_048,
266            },
267            3 => Self {
268                score: 3,
269                effort: Effort::Medium,
270                budget_tokens: 4_096,
271            },
272            4 => Self {
273                score: 4,
274                effort: Effort::High,
275                budget_tokens: 8_192,
276            },
277            _ => Self {
278                score: 5,
279                effort: Effort::High,
280                budget_tokens: 16_384,
281            },
282        }
283    }
284}
285
286/// Scores a conversation from its **first** user message only (#1912).
287///
288/// The injected thinking budget is a top-level request field, and Anthropic
289/// invalidates cached message blocks whenever thinking parameters change. The
290/// opening request of a session never changes turn to turn, so scoring it pins
291/// the budget for the whole conversation instead of letting a growing history
292/// (new errors, a longer last turn) move it between tiers.
293pub fn score_session_complexity(messages: &[Value]) -> u8 {
294    messages
295        .iter()
296        .find(|message| message.get("role").and_then(Value::as_str) == Some("user"))
297        .map_or(1, |first_user| {
298            score_complexity(std::slice::from_ref(first_user))
299        })
300}
301
302/// Scores request complexity on a stable 1–5 scale.
303pub fn score_complexity(messages: &[Value]) -> u8 {
304    let user_text = messages
305        .iter()
306        .rev()
307        .find(|message| message.get("role").and_then(Value::as_str) == Some("user"))
308        .and_then(|message| {
309            extract_text_from_content(message.get("content").unwrap_or(&Value::Null))
310        })
311        .unwrap_or_default();
312    let text = user_text.to_ascii_lowercase();
313    let file_mentions = count_file_mentions(&text);
314    let has_errors = messages.iter().any(message_has_error);
315    let critical = ["security", "vulnerability", "production", "incident", "cve"]
316        .iter()
317        .any(|marker| text.contains(marker));
318    let complex = ["debug", "architecture", "refactor", "design"]
319        .iter()
320        .any(|marker| text.contains(marker));
321
322    if critical {
323        5
324    } else if has_errors || complex {
325        4
326    } else if file_mentions >= 2 || user_text.len() > 1_200 || text.contains("test") {
327        3
328    } else if file_mentions == 1 || user_text.len() > 300 {
329        2
330    } else {
331        1
332    }
333}
334
335/// Scores and mutates a provider request in one step for proxy handlers.
336pub fn route_effort_budget(body: &mut Value) -> TaskComplexity {
337    let complexity = body
338        .get("messages")
339        .or_else(|| body.get("input"))
340        .and_then(Value::as_array)
341        .map_or(1, |messages| score_session_complexity(messages));
342    apply_effort_budget(body, complexity)
343}
344
345/// Anthropic's floor for `thinking.budget_tokens`.
346const MIN_THINKING_BUDGET: u32 = 1_024;
347
348/// The thinking budget the proxy may inject into an Anthropic request, or
349/// `None` when injecting would change the request's meaning or be rejected.
350///
351/// Anthropic counts thinking against `max_tokens` and requires
352/// `budget_tokens < max_tokens`; the budget is capped at half of `max_tokens`
353/// so the answer the client sized `max_tokens` for keeps its room. Extended
354/// thinking also rejects a non-default `temperature`, `top_k`, a `top_p`
355/// below 0.95 and a forced `tool_choice`, and needs every prior assistant turn
356/// to carry its thinking blocks — a history produced without thinking gets no
357/// injection rather than a 400.
358fn anthropic_thinking_budget(
359    object: &serde_json::Map<String, Value>,
360    task: TaskComplexity,
361) -> Option<u32> {
362    let max_tokens = object.get("max_tokens").and_then(Value::as_u64)?;
363    let half = u32::try_from(max_tokens / 2).unwrap_or(u32::MAX);
364    let budget = task.budget_tokens.min(half);
365    if budget < MIN_THINKING_BUDGET {
366        return None;
367    }
368    if object
369        .get("temperature")
370        .and_then(Value::as_f64)
371        .is_some_and(|temperature| (temperature - 1.0).abs() > f64::EPSILON)
372        || object.contains_key("top_k")
373        || object
374            .get("top_p")
375            .and_then(Value::as_f64)
376            .is_some_and(|top_p| top_p < 0.95)
377    {
378        return None;
379    }
380    let forced_tool = object
381        .get("tool_choice")
382        .and_then(|choice| choice.get("type"))
383        .and_then(Value::as_str)
384        .is_some_and(|kind| matches!(kind, "any" | "tool"));
385    if forced_tool {
386        return None;
387    }
388    let assistants = object
389        .get("messages")
390        .and_then(Value::as_array)
391        .map(|messages| {
392            messages
393                .iter()
394                .filter(|message| message.get("role").and_then(Value::as_str) == Some("assistant"))
395                .collect::<Vec<_>>()
396        })
397        .unwrap_or_default();
398    let history_has_thinking = assistants.iter().any(|message| {
399        message
400            .get("content")
401            .and_then(Value::as_array)
402            .is_some_and(|blocks| {
403                blocks.iter().any(|block| {
404                    matches!(
405                        block.get("type").and_then(Value::as_str),
406                        Some("thinking" | "redacted_thinking")
407                    )
408                })
409            })
410    });
411    if !assistants.is_empty() && !history_has_thinking {
412        return None;
413    }
414    Some(budget)
415}
416
417/// Whether an Anthropic model accepts the `thinking` parameter with a fixed
418/// `budget_tokens`, the form this module injects.
419///
420/// The list is deliberately narrow and fails **closed**: unknown models get no
421/// injection rather than risk a 400 from a model whose capabilities we guessed
422/// wrong. Ineligible families:
423/// - `claude-3-opus`/`claude-3-sonnet`/`claude-3-haiku`/`claude-3-5-haiku` have
424///   no extended thinking at all.
425/// - Opus/Sonnet 4.6+ and the 5-generation models reject `budget_tokens` (400);
426///   they take `thinking: {type: "adaptive"}` plus `output_config.effort`.
427fn anthropic_supports_thinking(model: &str) -> bool {
428    let bare = model.rsplit('/').next().unwrap_or(model);
429    let budget_token_families = [
430        "claude-3-5-sonnet",
431        "claude-3-7-sonnet",
432        "claude-3.5-sonnet",
433        "claude-3.7-sonnet",
434        "claude-sonnet-4-5",
435        "claude-opus-4-5",
436        "claude-haiku-4-5",
437        "claude-4-5",           // alias form (claude-4-5-sonnet / -haiku)
438        "claude-sonnet-4-2025", // dated snapshot (claude-sonnet-4-20250514)
439        "claude-opus-4-2025",   // dated snapshot (claude-opus-4-20250514)
440    ];
441    budget_token_families
442        .iter()
443        .any(|family| bare.starts_with(family))
444        // Bare launch-model ids that predate the 4.6+ adaptive-only era.
445        || bare == "claude-sonnet-4"
446        || bare == "claude-opus-4"
447}
448
449/// Calculates complexity for a request and applies its provider-native effort budget.
450pub fn apply_effort_budget(body: &mut Value, complexity: u8) -> TaskComplexity {
451    inject_effort_budget(body, complexity).0
452}
453
454/// Applies the provider-native effort budget and reports whether the body was
455/// changed, so callers can forward the client's original bytes when it was
456/// not (#1912).
457///
458/// A value the client already chose — `thinking`, `reasoning_effort` or
459/// `reasoning.effort` — is never overwritten.
460pub(crate) fn inject_effort_budget(body: &mut Value, complexity: u8) -> (TaskComplexity, bool) {
461    let task = TaskComplexity::from_score(complexity);
462    let Some(object) = body.as_object_mut() else {
463        return (task, false);
464    };
465
466    let model = object
467        .get("model")
468        .and_then(Value::as_str)
469        .unwrap_or_default()
470        .to_string();
471    let is_anthropic = object.contains_key("messages")
472        && (object.contains_key("max_tokens") || model.contains("claude"));
473    let mut injected_budget = None;
474    if is_anthropic && anthropic_supports_thinking(&model) {
475        if object.get("thinking").is_none() {
476            if let Some(budget) = anthropic_thinking_budget(object, task) {
477                object.insert(
478                    "thinking".into(),
479                    serde_json::json!({"type": "enabled", "budget_tokens": budget}),
480                );
481                injected_budget = Some(budget);
482            }
483        }
484    } else if crate::proxy::effort::openai_supports_effort(&model) {
485        let client_chose = object.contains_key("reasoning_effort")
486            || object
487                .get("reasoning")
488                .is_some_and(|reasoning| reasoning.get("effort").is_some());
489        if !client_chose {
490            let effort = Value::String(openai_effort_value(task.effort).into());
491            if object.contains_key("messages") {
492                // Chat Completions takes the flat `reasoning_effort` field.
493                object.insert("reasoning_effort".into(), effort);
494                injected_budget = Some(task.budget_tokens);
495            } else if object.contains_key("input") {
496                // The Responses API nests it under `reasoning`.
497                let reasoning = object
498                    .entry("reasoning")
499                    .or_insert_with(|| Value::Object(serde_json::Map::new()));
500                if let Some(reasoning) = reasoning.as_object_mut() {
501                    reasoning.insert("effort".into(), effort);
502                    injected_budget = Some(task.budget_tokens);
503                }
504            }
505        }
506    }
507    let Some(budget) = injected_budget else {
508        return (task, false);
509    };
510    ESTIMATED_OUTPUT_TOKENS_WITHOUT_ROUTING.fetch_add(16_384, Ordering::Relaxed);
511    ACTUAL_EFFORT_BUDGET_TOKENS.fetch_add(budget.into(), Ordering::Relaxed);
512    (task, true)
513}
514
515fn openai_effort_value(effort: Effort) -> &'static str {
516    match effort {
517        Effort::Minimal | Effort::Low => "low",
518        Effort::Medium => "medium",
519        Effort::High => "high",
520    }
521}
522
523#[cfg(test)]
524mod output_token_intelligence_tests {
525    use super::*;
526    use serde_json::json;
527
528    #[test]
529    fn trivial_task_gets_low_effort() {
530        let messages = vec![json!({"role": "user", "content": "Read src/lib.rs"})];
531        assert_eq!(score_complexity(&messages), 2);
532        assert_eq!(TaskComplexity::from_score(1).budget_tokens, 1_024);
533    }
534
535    #[test]
536    fn complex_task_gets_high_effort() {
537        let messages =
538            vec![json!({"role": "user", "content": "Design the architecture for this refactor"})];
539        let task = TaskComplexity::from_score(score_complexity(&messages));
540        assert_eq!(task.score, 4);
541        assert_eq!(task.effort, Effort::High);
542    }
543
544    #[test]
545    fn error_presence_increases_complexity() {
546        let messages = vec![
547            json!({"role": "tool", "content": "error[E0308]: mismatched types"}),
548            json!({"role": "user", "content": "fix this"}),
549        ];
550        assert_eq!(score_complexity(&messages), 4);
551    }
552
553    #[test]
554    fn applies_anthropic_thinking_budget() {
555        let mut body = json!({"model": "claude-sonnet-4", "max_tokens": 32_000, "messages": []});
556        let task = apply_effort_budget(&mut body, 4);
557        assert_eq!(task.budget_tokens, 8_192);
558        assert_eq!(body["thinking"]["budget_tokens"], 8_192);
559        assert_eq!(body["thinking"]["type"], "enabled");
560    }
561
562    #[test]
563    fn thinking_budget_stays_below_max_tokens() {
564        // #1912: Anthropic requires budget_tokens < max_tokens, and thinking
565        // eats into max_tokens — cap at half so the answer keeps its room.
566        let mut body = json!({"model": "claude-sonnet-4-5", "max_tokens": 4096, "messages": []});
567        let (_, changed) = inject_effort_budget(&mut body, 5);
568        assert!(changed);
569        let budget = body["thinking"]["budget_tokens"].as_u64().unwrap();
570        assert_eq!(budget, 2_048);
571        assert!(budget < 4096);
572    }
573
574    #[test]
575    fn small_max_tokens_gets_no_thinking() {
576        // Half of 1024 is below Anthropic's 1024 floor; injecting would 400.
577        for max_tokens in [1_024, 2_047] {
578            let mut body =
579                json!({"model": "claude-sonnet-4-5", "max_tokens": max_tokens, "messages": []});
580            let (_, changed) = inject_effort_budget(&mut body, 5);
581            assert!(!changed, "max_tokens {max_tokens} must not get thinking");
582            assert!(body.get("thinking").is_none());
583        }
584        let mut body = json!({"model": "claude-sonnet-4-5", "messages": []});
585        assert!(
586            !inject_effort_budget(&mut body, 5).1,
587            "no max_tokens → no injection"
588        );
589    }
590
591    #[test]
592    fn skips_thinking_when_sampling_or_tool_choice_conflicts() {
593        let base = json!({"model": "claude-sonnet-4-5", "max_tokens": 32_000, "messages": []});
594        for (key, value) in [
595            ("temperature", json!(0.2)),
596            ("top_k", json!(40)),
597            ("top_p", json!(0.5)),
598            ("tool_choice", json!({"type": "any"})),
599            ("tool_choice", json!({"type": "tool", "name": "x"})),
600        ] {
601            let mut body = base.clone();
602            body[key] = value.clone();
603            let (_, changed) = inject_effort_budget(&mut body, 4);
604            assert!(!changed, "{key}={value} must block thinking");
605            assert!(body.get("thinking").is_none());
606        }
607        let mut body = base.clone();
608        body["temperature"] = json!(1.0);
609        body["tool_choice"] = json!({"type": "auto"});
610        assert!(
611            inject_effort_budget(&mut body, 4).1,
612            "defaults must still inject"
613        );
614    }
615
616    #[test]
617    fn skips_thinking_when_history_has_no_thinking_blocks() {
618        // Enabling thinking mid-conversation on a history produced without
619        // it would be rejected; a history that carries thinking is fine.
620        let mut body = json!({
621            "model": "claude-sonnet-4-5",
622            "max_tokens": 32_000,
623            "messages": [
624                {"role": "user", "content": "hi"},
625                {"role": "assistant", "content": [{"type": "text", "text": "hello"}]},
626                {"role": "user", "content": "debug this"}
627            ]
628        });
629        assert!(!inject_effort_budget(&mut body, 4).1);
630        assert!(body.get("thinking").is_none());
631
632        body["messages"][1]["content"] = json!([
633            {"type": "thinking", "thinking": "…", "signature": "sig"},
634            {"type": "text", "text": "hello"}
635        ]);
636        assert!(inject_effort_budget(&mut body, 4).1);
637    }
638
639    #[test]
640    fn session_score_is_stable_across_turns() {
641        // #1912: the budget must not move as the conversation grows, or every
642        // turn invalidates Anthropic's message cache.
643        let first = json!({"role": "user", "content": "rename a variable"});
644        let turn_one = vec![first.clone()];
645        let turn_two = vec![
646            first,
647            json!({"role": "assistant", "content": "done"}),
648            json!({"role": "tool", "content": "error[E0308]: mismatched types"}),
649            json!({"role": "user", "content": "debug the production security incident"}),
650        ];
651        assert_eq!(
652            score_session_complexity(&turn_one),
653            score_session_complexity(&turn_two)
654        );
655        assert_ne!(score_complexity(&turn_one), score_complexity(&turn_two));
656        assert_eq!(score_session_complexity(&[]), 1);
657    }
658
659    #[test]
660    fn skips_thinking_for_unsupported_models() {
661        let mut body = json!({"model": "claude-sonnet-5", "max_tokens": 4096, "messages": []});
662        let task = apply_effort_budget(&mut body, 4);
663        assert_eq!(task.budget_tokens, 8_192);
664        assert!(
665            body.get("thinking").is_none(),
666            "sonnet-5 must not get thinking params"
667        );
668    }
669
670    #[test]
671    fn skips_thinking_for_openrouter_wrapped_unsupported() {
672        let mut body =
673            json!({"model": "anthropic/claude-sonnet-5", "max_tokens": 4096, "messages": []});
674        apply_effort_budget(&mut body, 4);
675        assert!(
676            body.get("thinking").is_none(),
677            "openrouter-wrapped sonnet-5 must not get thinking"
678        );
679    }
680
681    #[test]
682    fn preserves_client_thinking_params() {
683        let mut body = json!({
684            "model": "claude-sonnet-4",
685            "thinking": {"type": "adaptive"},
686            "messages": []
687        });
688        apply_effort_budget(&mut body, 4);
689        assert_eq!(
690            body["thinking"]["type"], "adaptive",
691            "must not overwrite client thinking"
692        );
693        assert!(
694            body["thinking"].get("budget_tokens").is_none(),
695            "must not inject budget_tokens"
696        );
697    }
698
699    #[test]
700    fn skips_thinking_for_adaptive_only_models() {
701        // Opus/Sonnet 4.6+ and the 5-generation reject `budget_tokens` with a
702        // 400 — never inject, even though these models do support thinking.
703        for model in [
704            "claude-opus-4-6",
705            "claude-opus-4-7",
706            "claude-opus-4-8",
707            "claude-sonnet-4-6",
708            "claude-sonnet-5",
709            "claude-opus-5",
710            "claude-fable-5",
711        ] {
712            let mut body = json!({"model": model, "max_tokens": 4096, "messages": []});
713            apply_effort_budget(&mut body, 4);
714            assert!(
715                body.get("thinking").is_none(),
716                "{model} must not get thinking params"
717            );
718        }
719    }
720
721    #[test]
722    fn skips_thinking_for_thinkingless_claude3() {
723        // The 2024 claude-3 series has no extended thinking at all.
724        for model in [
725            "claude-3-opus-20240229",
726            "claude-3-sonnet-20240229",
727            "claude-3-haiku-20240307",
728            "claude-3-5-haiku",
729        ] {
730            let mut body = json!({"model": model, "max_tokens": 4096, "messages": []});
731            apply_effort_budget(&mut body, 4);
732            assert!(
733                body.get("thinking").is_none(),
734                "{model} must not get thinking params"
735            );
736        }
737    }
738
739    #[test]
740    fn applies_thinking_to_budget_token_era() {
741        // claude-3-5/3-7 sonnet and the 4-5 era still accept budget_tokens.
742        for model in [
743            "claude-3-5-sonnet",
744            "claude-3-7-sonnet",
745            "anthropic/claude-3.5-sonnet",
746            "claude-sonnet-4-5",
747            "claude-opus-4-5",
748            "claude-haiku-4-5",
749            "claude-sonnet-4-20250514",
750            "claude-opus-4-20250514",
751        ] {
752            let mut body = json!({"model": model, "max_tokens": 32_000, "messages": []});
753            apply_effort_budget(&mut body, 4);
754            assert_eq!(
755                body["thinking"]["budget_tokens"], 8_192,
756                "{model} must get a thinking budget"
757            );
758        }
759    }
760
761    #[test]
762    fn applies_openai_reasoning_effort() {
763        // Chat Completions takes the flat field; `reasoning` is Responses-only.
764        let mut body = json!({"model": "gpt-5.4", "messages": []});
765        assert!(inject_effort_budget(&mut body, 3).1);
766        assert_eq!(body["reasoning_effort"], "medium");
767        assert!(body.get("reasoning").is_none());
768
769        let mut body = json!({"model": "gpt-5.4", "input": []});
770        assert!(inject_effort_budget(&mut body, 3).1);
771        assert_eq!(body["reasoning"]["effort"], "medium");
772        assert!(body.get("reasoning_effort").is_none());
773    }
774
775    #[test]
776    fn keeps_client_openai_effort() {
777        // #1912: a client-chosen effort is the client's decision.
778        let mut body = json!({"model": "gpt-5.4", "messages": [], "reasoning_effort": "high"});
779        let before = body.clone();
780        assert!(!inject_effort_budget(&mut body, 1).1);
781        assert_eq!(body, before);
782
783        let mut body = json!({"model": "gpt-5.4", "input": [], "reasoning": {"effort": "minimal"}});
784        let before = body.clone();
785        assert!(!inject_effort_budget(&mut body, 5).1);
786        assert_eq!(body, before);
787    }
788}
789
790fn count_file_mentions(text: &str) -> usize {
791    text.split_whitespace()
792        .filter(|word| {
793            let word = word.trim_matches(|character: char| {
794                !character.is_ascii_alphanumeric()
795                    && character != '.'
796                    && character != '_'
797                    && character != '/'
798            });
799            word.contains('/')
800                || [".rs", ".toml", ".json", ".md", ".py", ".ts", ".js"]
801                    .iter()
802                    .any(|suffix| word.ends_with(suffix))
803        })
804        .count()
805}
806
807fn message_has_error(message: &Value) -> bool {
808    message.get("is_error").and_then(Value::as_bool) == Some(true)
809        || extract_text_from_content(message.get("content").unwrap_or(&Value::Null))
810            .is_some_and(contains_error_indicators)
811}
812
813// ---------------------------------------------------------------------------
814// Internal classification helpers
815// ---------------------------------------------------------------------------
816
817fn classify_tool_result(msg: &Value, _all_messages: &[Value]) -> TurnClass {
818    let content = msg.get("content").and_then(Value::as_str).unwrap_or("");
819
820    if contains_error_indicators(content) {
821        return TurnClass::Full;
822    }
823
824    if is_routine_tool_output(content) {
825        return TurnClass::Routine;
826    }
827
828    TurnClass::Full
829}
830
831/// Heuristic: does this tool output look like a routine, successful result?
832fn is_routine_tool_output(content: &str) -> bool {
833    if content.is_empty() || content.len() < 10 {
834        return false;
835    }
836
837    // Error indicators → not routine.
838    if contains_error_indicators(content) {
839        return false;
840    }
841
842    // Very large outputs (>8000 chars) likely need careful processing.
843    if content.len() > 8000 {
844        return false;
845    }
846
847    // Positive signals for routine:
848    let routine_signals = [
849        // File read results (lean-ctx or native).
850        "deps ",      // lean-ctx read header
851        "[unchanged", // cached re-read
852        "[lean-ctx]", // lean-ctx footer
853        "lines:",     // line count indicators
854        // Shell success patterns.
855        "exit_code: 0",
856        "Command completed",
857        "0 errors",
858        "All tests passed",
859        "no changes",
860        "nothing to commit",
861        "Already up to date",
862        "Build succeeded",
863        // Search results.
864        "matches in",
865        "0 matches",
866    ];
867
868    routine_signals.iter().any(|sig| content.contains(sig))
869}
870
871/// Check if content contains error/failure indicators that need full thinking.
872fn contains_error_indicators(content: &str) -> bool {
873    let lower = content.to_ascii_lowercase();
874    let indicators = [
875        "error",
876        "failed",
877        "failure",
878        "fatal",
879        "panic",
880        "exception",
881        "traceback",
882        "stack trace",
883        "segfault",
884        "abort",
885        "denied",
886        "permission",
887        "not found",
888        "timed out",
889        "exit_code: 1",
890        "exit code 1",
891        "compilation error",
892        "syntax error",
893        "type error",
894    ];
895
896    indicators.iter().any(|ind| lower.contains(ind))
897}
898
899/// Extract text from Anthropic content blocks.
900fn extract_text_from_content(content: &Value) -> Option<&str> {
901    if let Some(s) = content.as_str() {
902        return Some(s);
903    }
904    if let Some(arr) = content.as_array() {
905        for block in arr {
906            if block.get("type").and_then(Value::as_str) == Some("text") {
907                return block.get("text").and_then(Value::as_str);
908            }
909        }
910    }
911    None
912}
913
914#[cfg(test)]
915mod tests {
916    use super::*;
917    use serde_json::json;
918
919    #[test]
920    fn user_message_is_always_full() {
921        let messages = json!([
922            {"role": "user", "content": "What does this function do?"}
923        ]);
924        assert_eq!(classify_turn(&messages), TurnClass::Full);
925    }
926
927    #[test]
928    fn successful_file_read_is_routine() {
929        let messages = json!([
930            {"role": "assistant", "content": "Let me read that file."},
931            {"role": "tool", "content": "main.rs 50L\n  deps serde\n[lean-ctx] full source: ..."}
932        ]);
933        assert_eq!(classify_turn(&messages), TurnClass::Routine);
934    }
935
936    #[test]
937    fn error_tool_result_is_full() {
938        let messages = json!([
939            {"role": "tool", "content": "error[E0308]: mismatched types\n  --> src/main.rs:5:12"}
940        ]);
941        assert_eq!(classify_turn(&messages), TurnClass::Full);
942    }
943
944    #[test]
945    fn successful_shell_is_routine() {
946        let messages = json!([
947            {"role": "tool", "content": "Command completed in 150ms\nexit_code: 0\nAll tests passed"}
948        ]);
949        assert_eq!(classify_turn(&messages), TurnClass::Routine);
950    }
951
952    #[test]
953    fn anthropic_tool_result_routine() {
954        let messages = json!([
955            {"role": "user", "content": [
956                {"type": "tool_result", "tool_use_id": "abc", "content": "[unchanged 5L]\n[lean-ctx] cached"}
957            ]}
958        ]);
959        assert_eq!(classify_turn_anthropic(&messages), TurnClass::Routine);
960    }
961
962    #[test]
963    fn anthropic_tool_result_with_error() {
964        let messages = json!([
965            {"role": "user", "content": [
966                {"type": "tool_result", "tool_use_id": "abc", "is_error": true, "content": "Tool failed"}
967            ]}
968        ]);
969        assert_eq!(classify_turn_anthropic(&messages), TurnClass::Full);
970    }
971
972    #[test]
973    fn effort_mapping() {
974        assert_eq!(
975            effort_for_turn(TurnClass::Routine, Effort::High),
976            Effort::Minimal
977        );
978        assert_eq!(effort_for_turn(TurnClass::Full, Effort::High), Effort::High);
979        assert_eq!(
980            effort_for_turn(TurnClass::Full, Effort::Medium),
981            Effort::Medium
982        );
983    }
984
985    #[test]
986    fn intent_adjusts_effort_by_task_complexity() {
987        assert_eq!(
988            intent_aware_effort("fix the parser", Effort::Low),
989            Effort::High
990        );
991        assert_eq!(
992            intent_aware_effort("read the config", Effort::High),
993            Effort::Minimal
994        );
995        assert_eq!(intent_aware_effort("chat", Effort::Medium), Effort::Medium);
996    }
997
998    #[test]
999    fn empty_messages_is_full() {
1000        assert_eq!(classify_turn(&json!([])), TurnClass::Full);
1001        assert_eq!(classify_turn(&json!(null)), TurnClass::Full);
1002    }
1003
1004    #[test]
1005    fn deterministic_classification() {
1006        let messages = json!([
1007            {"role": "tool", "content": "Build succeeded\nexit_code: 0\nCommand completed in 2s"}
1008        ]);
1009        let c1 = classify_turn(&messages);
1010        let c2 = classify_turn(&messages);
1011        assert_eq!(c1, c2, "classification must be deterministic");
1012    }
1013}