Skip to main content

agent_core/core/
reasoning.rs

1//! Typed named reasoning level — single source of truth across providers.
2//!
3//! `ReasoningLevel` is a closed enum with exact parsing, display, and explicit
4//! conversion to legacy Anthropic token budgets. It lives in `synaps-core` so
5//! every crate (engine, TUI) can depend on the same type without circular deps.
6//!
7//! ## Invariants
8//! - `Max` must never alias `XHigh`.
9//! - `Ultra` must never map through a numeric bucket.
10//! - `Off` and `Adaptive` are distinct.
11//! - Unknown strings from external sources parse to `None` / are rejected at
12//!   the call-site, not silently coerced.
13
14use std::fmt;
15
16/// A named reasoning / thinking depth level.
17///
18/// Ordering is from least to most intensive; `Off` < `Adaptive` < `Low` < … < `Ultra`.
19#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub enum ReasoningLevel {
21    /// No reasoning / thinking output.
22    Off,
23    /// Model decides reasoning depth automatically (Anthropic adaptive path).
24    Adaptive,
25    /// Low reasoning budget.
26    Low,
27    /// Medium reasoning budget.
28    #[default]
29    Medium,
30    /// High reasoning budget.
31    High,
32    /// Extra-high reasoning budget (above high, below max).
33    XHigh,
34    /// Maximum named level (below ultra).
35    Max,
36    /// Ultra — highest intensity, only a subset of Codex models supports this.
37    Ultra,
38    /// Anthropic-only logical xhigh plus standing workflow mode.
39    UltraCode,
40}
41
42impl ReasoningLevel {
43    /// Parse a level from its canonical logical/config string.
44    ///
45    /// Returns `None` for unknown strings; callers must not silently fallback.
46    pub fn parse(s: &str) -> Option<Self> {
47        match s.trim().to_ascii_lowercase().as_str() {
48            "off" | "none" => Some(Self::Off),
49            "adaptive" => Some(Self::Adaptive),
50            "low" => Some(Self::Low),
51            "medium" | "med" => Some(Self::Medium),
52            "high" => Some(Self::High),
53            "xhigh" | "x-high" | "x_high" => Some(Self::XHigh),
54            "max" => Some(Self::Max),
55            "ultra" => Some(Self::Ultra),
56            "ultracode" => Some(Self::UltraCode),
57            _ => None,
58        }
59    }
60
61    /// The canonical logical/config representation.
62    ///
63    /// Provider request planners own wire conversion. In particular, Codex
64    /// logical Ultra uses the exact catalog's multi-agent wire effort (e.g.
65    /// Astra `xhigh`, Sol `max`) plus foreground proactive mode.
66    pub fn as_str(self) -> &'static str {
67        match self {
68            Self::Off => "off",
69            Self::Adaptive => "adaptive",
70            Self::Low => "low",
71            Self::Medium => "medium",
72            Self::High => "high",
73            Self::XHigh => "xhigh",
74            Self::Max => "max",
75            Self::Ultra => "ultra",
76            Self::UltraCode => "ultracode",
77        }
78    }
79
80    /// Convert to the legacy Anthropic token budget used by the enabled+budget_tokens
81    /// request shape. Returns `None` for levels that have no meaningful numeric
82    /// mapping (Max and Ultra are Codex execution modes, not numeric budgets).
83    pub fn to_legacy_budget(self) -> Option<u32> {
84        match self {
85            Self::Off | Self::Adaptive => Some(0),
86            Self::Low => Some(2048),
87            Self::Medium => Some(4096),
88            Self::High => Some(16384),
89            Self::XHigh => Some(32768),
90            Self::Max | Self::Ultra | Self::UltraCode => None,
91        }
92    }
93
94    /// Build from a legacy token budget value (Anthropic path).
95    ///
96    /// `0` → `Adaptive`, positive values → their tier. Does not produce `Max`
97    /// or `Ultra` — those are provider-named levels, never inferred from a budget.
98    pub fn from_legacy_budget(budget: u32) -> Self {
99        match budget {
100            0 => Self::Adaptive,
101            1..=2048 => Self::Low,
102            2049..=4096 => Self::Medium,
103            4097..=16384 => Self::High,
104            _ => Self::XHigh,
105        }
106    }
107
108    /// All levels that are strictly above XHigh (require Codex-specific support).
109    pub fn requires_codex_support(self) -> bool {
110        matches!(self, Self::Ultra)
111    }
112
113    /// Whether this level requires exact Anthropic mode capability evidence.
114    pub fn requires_anthropic_support(self) -> bool {
115        matches!(self, Self::Max | Self::UltraCode)
116    }
117}
118
119impl fmt::Display for ReasoningLevel {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.write_str(self.as_str())
122    }
123}
124
125/// Parse the `thinking` config key into either a named level or a raw numeric budget.
126///
127/// This is the single parse path for config files, `/thinking` commands, and
128/// session resumption. Named levels win over numeric-only parsing; numeric values
129/// that don't match a known level are treated as raw budget tokens.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum ThinkingSpec {
132    /// A recognized named level.
133    Named(ReasoningLevel),
134    /// A raw numeric budget (legacy Anthropic path, user-specified token count).
135    Budget(u32),
136}
137
138impl ThinkingSpec {
139    /// Parse from a string (config value or command argument).
140    ///
141    /// Returns `None` for strings that are neither a known name nor a non-negative integer.
142    pub fn parse(s: &str) -> Option<Self> {
143        // Named levels take priority.
144        if let Some(level) = ReasoningLevel::parse(s) {
145            return Some(Self::Named(level));
146        }
147        // Raw numeric budget (any non-negative integer).
148        if let Ok(n) = s.trim().parse::<u32>() {
149            return Some(Self::Budget(n));
150        }
151        None
152    }
153
154    /// The canonical level this spec resolves to, if deterministic.
155    /// `Budget` values are bucketized via `ReasoningLevel::from_legacy_budget`.
156    pub fn to_level(&self) -> ReasoningLevel {
157        match self {
158            Self::Named(l) => *l,
159            Self::Budget(n) => ReasoningLevel::from_legacy_budget(*n),
160        }
161    }
162
163    /// The numeric budget this spec resolves to for Anthropic requests.
164    /// Named Max/Ultra return `None` because they have no valid numeric budget.
165    pub fn to_budget(&self) -> Option<u32> {
166        match self {
167            Self::Named(l) => l.to_legacy_budget(),
168            Self::Budget(n) => Some(*n),
169        }
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn ultracode_is_a_distinct_canonical_non_numeric_level() {
179        let level = ReasoningLevel::parse("ultracode").expect("canonical ultracode");
180        assert_eq!(level, ReasoningLevel::UltraCode);
181        assert_eq!(level.to_string(), "ultracode");
182        assert_ne!(level, ReasoningLevel::Ultra);
183        assert_ne!(level, ReasoningLevel::Max);
184        assert_ne!(level, ReasoningLevel::XHigh);
185        assert_eq!(level.to_legacy_budget(), None);
186        assert!(!level.requires_codex_support());
187        assert!(level.requires_anthropic_support());
188    }
189
190    // ── Parse / round-trip ────────────────────────────────────────────────────
191
192    #[test]
193    fn all_canonical_strings_parse() {
194        for (s, expected) in [
195            ("off", ReasoningLevel::Off),
196            ("none", ReasoningLevel::Off),
197            ("adaptive", ReasoningLevel::Adaptive),
198            ("low", ReasoningLevel::Low),
199            ("medium", ReasoningLevel::Medium),
200            ("med", ReasoningLevel::Medium),
201            ("high", ReasoningLevel::High),
202            ("xhigh", ReasoningLevel::XHigh),
203            ("max", ReasoningLevel::Max),
204            ("ultra", ReasoningLevel::Ultra),
205            ("ultracode", ReasoningLevel::UltraCode),
206        ] {
207            assert_eq!(
208                ReasoningLevel::parse(s),
209                Some(expected),
210                "failed to parse {s:?}"
211            );
212        }
213    }
214
215    #[test]
216    fn case_insensitive_parse() {
217        assert_eq!(ReasoningLevel::parse("MAX"), Some(ReasoningLevel::Max));
218        assert_eq!(ReasoningLevel::parse("Ultra"), Some(ReasoningLevel::Ultra));
219        assert_eq!(ReasoningLevel::parse("XHIGH"), Some(ReasoningLevel::XHigh));
220        assert_eq!(ReasoningLevel::parse("  Low  "), Some(ReasoningLevel::Low));
221    }
222
223    #[test]
224    fn unknown_strings_return_none() {
225        assert_eq!(ReasoningLevel::parse(""), None);
226        assert_eq!(ReasoningLevel::parse("bogus"), None);
227        assert_eq!(ReasoningLevel::parse("maximum"), None);
228        assert_eq!(ReasoningLevel::parse("hyper"), None);
229        assert_eq!(ReasoningLevel::parse("xhigh+"), None);
230    }
231
232    #[test]
233    fn as_str_round_trips() {
234        for level in [
235            ReasoningLevel::Off,
236            ReasoningLevel::Adaptive,
237            ReasoningLevel::Low,
238            ReasoningLevel::Medium,
239            ReasoningLevel::High,
240            ReasoningLevel::XHigh,
241            ReasoningLevel::Max,
242            ReasoningLevel::Ultra,
243            ReasoningLevel::UltraCode,
244        ] {
245            let s = level.as_str();
246            assert_eq!(
247                ReasoningLevel::parse(s),
248                Some(level),
249                "as_str() → parse() failed for {:?}",
250                level
251            );
252        }
253    }
254
255    #[test]
256    fn display_matches_as_str() {
257        assert_eq!(ReasoningLevel::Max.to_string(), "max");
258        assert_eq!(ReasoningLevel::Ultra.to_string(), "ultra");
259        assert_eq!(ReasoningLevel::XHigh.to_string(), "xhigh");
260    }
261
262    // ── Max must never alias XHigh ─────────────────────────────────────────────
263
264    #[test]
265    fn max_is_distinct_from_xhigh() {
266        assert_ne!(ReasoningLevel::Max, ReasoningLevel::XHigh);
267        assert_ne!(ReasoningLevel::Max.as_str(), ReasoningLevel::XHigh.as_str());
268    }
269
270    // ── Ultra must not map through a numeric budget bucket ────────────────────
271
272    #[test]
273    fn ultra_has_no_legacy_budget() {
274        assert_eq!(ReasoningLevel::Ultra.to_legacy_budget(), None);
275    }
276
277    #[test]
278    fn max_has_no_legacy_budget() {
279        assert_eq!(ReasoningLevel::Max.to_legacy_budget(), None);
280    }
281
282    // ── Legacy budget conversion ──────────────────────────────────────────────
283
284    #[test]
285    fn known_legacy_budgets_convert_correctly() {
286        assert_eq!(ReasoningLevel::Off.to_legacy_budget(), Some(0));
287        assert_eq!(ReasoningLevel::Adaptive.to_legacy_budget(), Some(0));
288        assert_eq!(ReasoningLevel::Low.to_legacy_budget(), Some(2048));
289        assert_eq!(ReasoningLevel::Medium.to_legacy_budget(), Some(4096));
290        assert_eq!(ReasoningLevel::High.to_legacy_budget(), Some(16384));
291        assert_eq!(ReasoningLevel::XHigh.to_legacy_budget(), Some(32768));
292    }
293
294    #[test]
295    fn from_legacy_budget_never_returns_max_or_ultra() {
296        for budget in [0u32, 2048, 4096, 16384, 32768, 65536, u32::MAX] {
297            let level = ReasoningLevel::from_legacy_budget(budget);
298            assert!(
299                !matches!(level, ReasoningLevel::Max | ReasoningLevel::Ultra),
300                "from_legacy_budget({budget}) returned {level:?} which must not be Max/Ultra"
301            );
302        }
303    }
304
305    #[test]
306    fn from_legacy_budget_round_trips_for_known_values() {
307        for (budget, expected) in [
308            (0u32, ReasoningLevel::Adaptive),
309            (2048, ReasoningLevel::Low),
310            (4096, ReasoningLevel::Medium),
311            (16384, ReasoningLevel::High),
312            (32768, ReasoningLevel::XHigh),
313        ] {
314            assert_eq!(
315                ReasoningLevel::from_legacy_budget(budget),
316                expected,
317                "budget {budget}"
318            );
319        }
320    }
321
322    // ── Ordering ──────────────────────────────────────────────────────────────
323
324    #[test]
325    fn ordering_is_intensity() {
326        let levels = [
327            ReasoningLevel::Off,
328            ReasoningLevel::Adaptive,
329            ReasoningLevel::Low,
330            ReasoningLevel::Medium,
331            ReasoningLevel::High,
332            ReasoningLevel::XHigh,
333            ReasoningLevel::Max,
334            ReasoningLevel::Ultra,
335        ];
336        for w in levels.windows(2) {
337            assert!(w[0] < w[1], "{:?} should be less than {:?}", w[0], w[1]);
338        }
339    }
340
341    // ── requires_codex_support ────────────────────────────────────────────────
342
343    #[test]
344    fn only_ultra_requires_categorically_codex_support() {
345        assert!(!ReasoningLevel::Max.requires_codex_support());
346        assert!(ReasoningLevel::Ultra.requires_codex_support());
347        assert!(!ReasoningLevel::UltraCode.requires_codex_support());
348        assert!(!ReasoningLevel::XHigh.requires_codex_support());
349        assert!(!ReasoningLevel::High.requires_codex_support());
350        assert!(!ReasoningLevel::Adaptive.requires_codex_support());
351    }
352
353    // ── ThinkingSpec ──────────────────────────────────────────────────────────
354
355    #[test]
356    fn thinking_spec_named_levels_parse() {
357        assert_eq!(
358            ThinkingSpec::parse("max"),
359            Some(ThinkingSpec::Named(ReasoningLevel::Max))
360        );
361        assert_eq!(
362            ThinkingSpec::parse("ultra"),
363            Some(ThinkingSpec::Named(ReasoningLevel::Ultra))
364        );
365        assert_eq!(
366            ThinkingSpec::parse("xhigh"),
367            Some(ThinkingSpec::Named(ReasoningLevel::XHigh))
368        );
369    }
370
371    #[test]
372    fn thinking_spec_numeric_budget_parse() {
373        assert_eq!(
374            ThinkingSpec::parse("8192"),
375            Some(ThinkingSpec::Budget(8192))
376        );
377        assert_eq!(ThinkingSpec::parse("0"), Some(ThinkingSpec::Budget(0)));
378    }
379
380    #[test]
381    fn thinking_spec_parse_invalid() {
382        assert_eq!(ThinkingSpec::parse("bogus"), None);
383        assert_eq!(ThinkingSpec::parse(""), None);
384    }
385
386    #[test]
387    fn thinking_spec_max_has_no_budget() {
388        let spec = ThinkingSpec::Named(ReasoningLevel::Max);
389        assert_eq!(spec.to_budget(), None);
390        assert_eq!(spec.to_level(), ReasoningLevel::Max);
391    }
392
393    #[test]
394    fn thinking_spec_budget_round_trips() {
395        let spec = ThinkingSpec::Budget(8192);
396        assert_eq!(spec.to_budget(), Some(8192));
397        // 8192 is in the high tier (4097–16384)
398        assert_eq!(spec.to_level(), ReasoningLevel::High);
399    }
400}