Skip to main content

eclipse_core/
reasoning.rs

1//! How much a model thinks, and where the number goes.
2//!
3//! Two halves, and the split is the point. **What the user asks for** is one ladder, shared by every
4//! backend: `none < minimal < low < medium < high < xhigh < max`. **What a backend accepts** is not
5//! knowable from here — llama.cpp takes a graded `reasoning_effort` on some models and ignores it on
6//! others, a bool-valued chat-template kwarg is the only switch on a third, and an endpoint may
7//! reject a level with a 400 — so it is *declared*, per provider profile and per model, in an
8//! editable manifest (see the `[[provider_profile.reasoning]]` table). This module holds the math
9//! and the manifest shape; the manifests hold the knowledge.
10//!
11//! The clamping rule is borrowed from Hermes' `agent/reasoning_effort.clamp_effort`, and the
12//! per-model mapping shape from Pi's `thinkingLevelMap` — both are the same idea: a requested level
13//! resolves to a level *this* wire has, never upward, and a level that maps to nothing is omitted
14//! rather than guessed.
15
16use serde::{Deserialize, Serialize};
17use std::collections::BTreeMap;
18
19/// The ladder, weakest first. A request is clamped *down* it and never up: a level a backend does
20/// not have must not quietly cost more than the one that was asked for.
21pub const LADDER: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh", "max"];
22
23/// The level an install reasons at when nobody said otherwise: the `default` both shipped profiles
24/// declare, and the line `config init` writes live into `config.toml`.
25///
26/// One constant because the two answers are one fact (`#276`). A starter file that says `medium`
27/// while the resolver says nothing is the drift that makes a fresh install's read-out contradict
28/// its own config — the starter's key is not a second opinion, it is the same answer written down
29/// where the operator can see and edit it.
30pub const SHIPPED_DEFAULT: &str = "medium";
31
32/// What the read-out says when the next request carries no reasoning field at all.
33///
34/// Not `(unset)`: after `#276` an unset *file* means the level above, so the only thing left for
35/// this label to mean is "nothing goes on the wire" — which is a fact about the backend, not a gap
36/// in the configuration, and it should read like one.
37pub const NOT_SENT: &str = "not sent";
38
39/// The levels a `/reasoning` argument may name. `none` is here because it is also the off switch on
40/// every backend measured so far; a manifest that has no disable maps it to nothing instead.
41pub fn is_level(word: &str) -> bool {
42    LADDER.contains(&word.trim().to_lowercase().as_str())
43}
44
45/// The word that says "put no reasoning field on the wire at all".
46///
47/// Deliberately *not* a rung of [`LADDER`]: `none` is the off switch — it asks the model to stop
48/// thinking and puts a field on the wire — while `omit` sends nothing and leaves the endpoint's own
49/// default in charge (`#278`). It is a word in the same place, because the two settings that decide
50/// this are the file and the profile, and a second key for one knob would need a precedence rule
51/// every surface has to honour forever.
52pub const OMIT: &str = "omit";
53
54/// Whether this word is the "send no field" sentinel rather than a level.
55pub fn is_omit(word: &str) -> bool {
56    word.trim().to_lowercase() == OMIT
57}
58
59fn rank(level: &str) -> Option<usize> {
60    LADDER.iter().position(|l| *l == level)
61}
62
63/// What a backend's reasoning field takes.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
65#[serde(rename_all = "snake_case")]
66pub enum Kind {
67    /// Graded: the level itself goes on the wire (`reasoning_effort: "high"`).
68    #[default]
69    Level,
70    /// A bool-valued switch (`chat_template_kwargs: {enable_thinking: true}`): every graded level
71    /// means "on", the off level means "off", and there is nothing in between to send.
72    Bool,
73}
74
75/// How a backend turns thinking off, which is not the same anywhere.
76#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
77#[serde(untagged)]
78pub enum OffSwitch {
79    /// A level at the policy's field: `off = "none"`.
80    Text(String),
81    /// A bool at the policy's field: `off = false` for `enable_thinking`.
82    Flag(bool),
83    /// A whole body fragment, merged as it is: the switch is not at `field` at all.
84    Body(serde_json::Value),
85}
86
87impl From<&str> for OffSwitch {
88    fn from(text: &str) -> Self {
89        OffSwitch::Text(text.to_string())
90    }
91}
92
93impl OffSwitch {
94    /// The value to put at the policy's field, when that is the shape it is.
95    fn at_field(&self) -> Option<serde_json::Value> {
96        match self {
97            OffSwitch::Text(s) => Some(serde_json::Value::String(s.clone())),
98            OffSwitch::Flag(b) => Some(serde_json::Value::Bool(*b)),
99            OffSwitch::Body(_) => None,
100        }
101    }
102}
103
104/// One backend's reasoning policy, as a manifest declares it.
105///
106/// ```toml
107/// [provider_profile.reasoning]
108/// field  = "reasoning_effort"     # dotted path on the request body
109/// kind   = "level"                # "level" (default) or "bool"
110/// off    = "none"                 # level kind: what turns it off
111/// levels = ["low", "medium", "high"]
112/// map    = { minimal = "low", xhigh = "high" }
113/// default = "medium"              # when nothing was set; absent = send nothing
114/// ```
115#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Default)]
116#[serde(deny_unknown_fields)]
117pub struct Policy {
118    /// Dotted path into the request body: `reasoning_effort`, or
119    /// `chat_template_kwargs.enable_thinking`.
120    pub field: String,
121    #[serde(default)]
122    pub kind: Kind,
123    /// What disables reasoning on this backend: a level (`"none"`), a bool for a bool field, or a
124    /// body fragment when the switch lives somewhere else entirely
125    /// (`chat_template_kwargs = { enable_thinking = false }`). `None` = cannot be switched off.
126    #[serde(default)]
127    pub off: Option<OffSwitch>,
128    /// The off switch to use instead of `off` when the base URL is Ollama itself, because Ollama
129    /// ignores `reasoning_effort` on its native port and `think = false` 422s anywhere else.
130    #[serde(default)]
131    pub ollama_off: Option<OffSwitch>,
132    /// The graded levels this wire accepts, weakest first. Empty = it has no graded dial (on/off
133    /// only, or nothing at all).
134    #[serde(default)]
135    pub levels: Vec<String>,
136    /// Declared vendor mappings, consulted before the ladder: `minimal = "low"`, `xhigh = "high"`.
137    #[serde(default)]
138    pub map: BTreeMap<String, String>,
139    /// What to send when the user set nothing. Absent = send nothing and let the server default
140    /// apply — which is the honest default, because an endpoint's own default is not ours to guess.
141    #[serde(default)]
142    pub default: Option<String>,
143}
144
145/// What one request should carry, and what can be said about it.
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub enum Wire {
148    /// Put this value at the policy's field. `true`/`false` for a bool field, a string for a level.
149    Set(serde_json::Value),
150    /// Merge this fragment as it is: the switch is a whole table, not one field.
151    Body(serde_json::Value),
152    /// Send nothing: the backend has no dial for this ask (or no dial at all).
153    Omit(Omitted),
154}
155
156/// Why nothing is being sent — the sentence `/reasoning` prints instead of pretending.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum Omitted {
159    /// The policy has no field at all: this model does not reason, or nobody declared how it does.
160    NoPolicy,
161    /// A graded level was asked of a backend with no graded levels (it has an off switch only).
162    NoLevels,
163    /// The level resolves to nothing on this wire (its `map` says `null`, or it is not on the
164    /// ladder and not in `levels`).
165    NotOnThisWire,
166    /// Nothing was asked and the policy declares no default.
167    NothingAsked,
168    /// Somebody decided, deliberately, that this route carries no reasoning field — the `omit`
169    /// sentinel, in the file, in a profile's default, or from `/reasoning` for one session
170    /// (`#278`). A different sentence from [`Omitted::NothingAsked`]: that one is an absence
171    /// nobody chose.
172    AskedToOmit,
173}
174
175impl Wire {
176    /// The body patch this puts on the wire, as one dotted key.
177    pub fn body(&self, policy: &Policy) -> serde_json::Value {
178        match self {
179            Wire::Set(value) => put(&policy.field, value.clone()),
180            Wire::Body(fragment) => fragment.clone(),
181            Wire::Omit(_) => serde_json::json!({}),
182        }
183    }
184}
185
186/// `{"a.b": v}` as a nested object: `{"a": {"b": v}}`. Public because a profile names the path for
187/// anything it places (the reasoning field, `num_ctx`) and there should be one spelling of that.
188pub fn field_path(field: &str, value: serde_json::Value) -> serde_json::Value {
189    put(field, value)
190}
191
192/// `{"a.b": v}` as a nested object: `{"a": {"b": v}}`.
193fn put(field: &str, value: serde_json::Value) -> serde_json::Value {
194    let mut parts: Vec<&str> = field.split('.').filter(|p| !p.is_empty()).collect();
195    let Some(last) = parts.pop() else {
196        return serde_json::json!({});
197    };
198    let mut out = serde_json::json!({ last: value });
199    for part in parts.into_iter().rev() {
200        out = serde_json::json!({ part: out });
201    }
202    out
203}
204
205impl Policy {
206    /// The real OpenAI API's graded vocabulary. No off switch: `reasoning_effort: "none"` is not
207    /// something that endpoint accepts, and inventing it would be a 400.
208    ///
209    /// `default = medium` is what a fresh install reasons at (`#276`): a route nobody configured
210    /// still gets a level this wire is known to take, and a route that declares no policy at all
211    /// still gets no field. `SHIPPED_DEFAULT` is the same answer the starter file writes live, and
212    /// the test below is what keeps the two from drifting apart.
213    pub fn openai() -> Self {
214        Self {
215            field: "reasoning_effort".into(),
216            kind: Kind::Level,
217            off: None,
218            ollama_off: None,
219            levels: vec![
220                "minimal".into(),
221                "low".into(),
222                "medium".into(),
223                "high".into(),
224            ],
225            map: BTreeMap::new(),
226            default: Some(SHIPPED_DEFAULT.into()),
227        }
228    }
229
230    /// What a llama.cpp server was measured to take on this fleet: a graded dial on some models,
231    /// `none` as the off switch everywhere, `minimal` silently meaning "no thinking", and nothing
232    /// above `high`. A model that ignores the graded levels overrides this in a manifest.
233    ///
234    /// `default = medium` for the reason `openai` declares it; a per-model entry that declares no
235    /// default (the off-only gemma shape) sends nothing, which is what a graded level would be
236    /// there: a level the server ignores, reported as if it had worked.
237    pub fn llamacpp() -> Self {
238        let mut map = BTreeMap::new();
239        map.insert("minimal".to_string(), "low".to_string());
240        map.insert("xhigh".to_string(), "high".to_string());
241        map.insert("max".to_string(), "high".to_string());
242        Self {
243            field: "reasoning_effort".into(),
244            kind: Kind::Level,
245            off: Some("none".into()),
246            ollama_off: None,
247            levels: vec!["low".into(), "medium".into(), "high".into()],
248            map,
249            default: Some(SHIPPED_DEFAULT.into()),
250        }
251    }
252
253    /// Whether this backend has any reasoning control at all.
254    pub fn has_dial(&self) -> bool {
255        !self.field.is_empty()
256            && (self.off.is_some() || self.ollama_off.is_some() || !self.levels.is_empty())
257    }
258
259    /// The off switch as a word, when it is one — `asks_off` compares map targets against it.
260    fn off_text(&self) -> Option<&str> {
261        match &self.off {
262            Some(OffSwitch::Text(text)) => Some(text.as_str()),
263            _ => None,
264        }
265    }
266
267    /// Whether this route can turn thinking off at all (`#293`). The switch in the dashboard's
268    /// submenu is one of these: a route without an off draws it disabled, because the alternative
269    /// is a control that presses and changes nothing.
270    pub fn has_off(&self) -> bool {
271        !self.field.is_empty() && (self.off.is_some() || self.ollama_off.is_some())
272    }
273
274    /// Whether it has graded levels, as opposed to only off/on.
275    pub fn has_levels(&self) -> bool {
276        !self.levels.is_empty()
277    }
278
279    /// The words this wire takes, as a menu should offer them (`#275`): the graded levels it
280    /// declared, plus its off switch when it has one.
281    ///
282    /// The point of serving this instead of a union spelled in a front end is that a row offered
283    /// is a row that works. `openai` has no off switch — `reasoning_effort: "none"` is a 400
284    /// there — while `llamacpp` has `none` and only three rungs, and an off-only model can do
285    /// nothing but turn thinking off. Empty for a policy with no dial at all, which the menu says
286    /// in words instead of listing six dead ones.
287    pub fn vocabulary(&self) -> Vec<String> {
288        if !self.has_dial() {
289            return Vec::new();
290        }
291        let mut out = self.levels.clone();
292        // The off switch is asked for by the word `none` whatever shape it takes — a level, a
293        // bool, or a body fragment — because that is the word `asks_off` recognises, and a
294        // fragment is not something a person types.
295        if self.has_off() && !out.iter().any(|l| l == "none") {
296            out.push("none".to_string());
297        }
298        out
299    }
300
301    /// The effort in force when nothing was asked *and* nothing was configured.
302    pub fn default_effort(&self) -> Option<&str> {
303        self.default.as_deref()
304    }
305
306    /// Resolve a requested level into what this request carries.
307    pub fn resolve(&self, requested: Option<&str>) -> Wire {
308        self.resolve_at(requested, None)
309    }
310
311    /// The same, with the endpoint in hand: Ollama ignores `reasoning_effort` on its native port
312    /// and `think = false` 422s everywhere else, so which switch is the off switch is a property of
313    /// where the request is going.
314    pub fn resolve_at(&self, requested: Option<&str>, base_url: Option<&str>) -> Wire {
315        if !self.has_dial() {
316            return Wire::Omit(Omitted::NoPolicy);
317        }
318        let asked = requested
319            .map(|r| r.trim().to_lowercase())
320            .filter(|r| !r.is_empty());
321        let Some(asked) = asked.or_else(|| self.default_effort().map(str::to_string)) else {
322            return Wire::Omit(Omitted::NothingAsked);
323        };
324        // Before the ladder, and before the off switch: the sentinel is not a level any wire is
325        // asked to take, it is the absence of the field, so nothing may clamp it into something
326        // that is sent.
327        if is_omit(&asked) {
328            return Wire::Omit(Omitted::AskedToOmit);
329        }
330        if asks_off(&asked, self) {
331            return match self.off_wire(base_url) {
332                Some(Wire::Body(fragment)) => Wire::Body(fragment),
333                Some(Wire::Set(value)) => Wire::Set(value),
334                _ => Wire::Omit(Omitted::NotOnThisWire),
335            };
336        }
337        match self.kind {
338            Kind::Bool => match self.on_value() {
339                Some(value) => Wire::Set(value),
340                None => Wire::Omit(Omitted::NotOnThisWire),
341            },
342            Kind::Level => {
343                if !self.has_levels() {
344                    // An off switch and nothing else: an enabled ask has nowhere to go. Sending
345                    // the level anyway is how a "high" that changed nothing gets reported as if it
346                    // had worked.
347                    return Wire::Omit(Omitted::NoLevels);
348                }
349                match clamp(&asked, self) {
350                    Some(level) => Wire::Set(serde_json::Value::String(level)),
351                    None => Wire::Omit(Omitted::NotOnThisWire),
352                }
353            }
354        }
355    }
356
357    /// A sentence for a report: what this ask becomes on this backend.
358    pub fn describe(&self, requested: Option<&str>) -> String {
359        if !self.has_dial() {
360            return "no reasoning control on this backend".to_string();
361        }
362        let asked = requested
363            .map(|r| r.trim().to_lowercase())
364            .filter(|r| !r.is_empty())
365            .or_else(|| self.default_effort().map(str::to_string));
366        let Some(asked) = asked else {
367            return "not sent: nothing asked and this backend declares no default".to_string();
368        };
369        match self.resolve(Some(&asked)) {
370            Wire::Set(serde_json::Value::String(clamped)) if clamped == asked => {
371                format!("sends {clamped}")
372            }
373            // A clamp is said out loud: a report that echoed the request would claim a level this
374            // backend does not have.
375            Wire::Set(serde_json::Value::String(clamped)) => format!("{asked} → sends {clamped}"),
376            Wire::Set(serde_json::Value::Bool(true)) => "sends thinking on".to_string(),
377            Wire::Set(serde_json::Value::Bool(false)) => "sends thinking off".to_string(),
378            Wire::Set(_) => "sends it".to_string(),
379            // The switch is a table, not a level: name the keys rather than the JSON.
380            Wire::Body(fragment) => {
381                let keys: Vec<String> = fragment
382                    .as_object()
383                    .map(|o| o.keys().cloned().collect())
384                    .unwrap_or_default();
385                if keys.is_empty() {
386                    format!("{asked} → sends a body fragment")
387                } else {
388                    format!("{asked} → sends {}", keys.join(", "))
389                }
390            }
391            Wire::Omit(Omitted::NoLevels) => {
392                "not sent: this backend has no levels, only on or off".to_string()
393            }
394            Wire::Omit(Omitted::NotOnThisWire) => {
395                format!("not sent: {asked} is not a level this backend takes")
396            }
397            Wire::Omit(Omitted::NothingAsked) => "not sent: nothing asked".to_string(),
398            Wire::Omit(Omitted::AskedToOmit) => {
399                "not sent: asked for no field on this route".to_string()
400            }
401            Wire::Omit(Omitted::NoPolicy) => "no reasoning control on this backend".to_string(),
402        }
403    }
404
405    /// The switch this endpoint honours, as the wire shape to send.
406    fn off_wire(&self, base_url: Option<&str>) -> Option<Wire> {
407        let chosen = match (&self.ollama_off, base_url) {
408            (Some(switch), Some(url)) if looks_like_ollama(url) => switch,
409            _ => self.off.as_ref()?,
410        };
411        Some(match chosen {
412            OffSwitch::Body(fragment) => Wire::Body(fragment.clone()),
413            other => Wire::Set(other.at_field()?),
414        })
415    }
416
417    fn on_value(&self) -> Option<serde_json::Value> {
418        match self.kind {
419            Kind::Bool => Some(serde_json::Value::Bool(true)),
420            Kind::Level => self.levels.first().cloned().map(serde_json::Value::String),
421        }
422    }
423}
424
425/// Is this base URL Ollama *itself* rather than something that merely speaks its wire?
426///
427/// The native port, or a host name that names Ollama and is not a public domain: a container/service
428/// name (`ollama`, `my-ollama`), or one under a private label (`ollama.lan`, `ollama.internal`).
429/// `https://ollama.com` is the cloud — it speaks the OpenAI wire, ignores `think` and takes
430/// `reasoning_effort: "none"` — so a substring test on the whole URL would get this exactly backwards.
431pub fn looks_like_ollama(base_url: &str) -> bool {
432    let trimmed = base_url.trim();
433    let without_scheme = trimmed
434        .split_once("://")
435        .map(|(_, rest)| rest)
436        .unwrap_or(trimmed);
437    let authority = without_scheme
438        .split(['/', '?', '#'])
439        .next()
440        .unwrap_or(without_scheme);
441    let authority = authority
442        .rsplit_once('@')
443        .map_or(authority, |(_, rest)| rest);
444    if authority.is_empty() {
445        return false;
446    }
447    let (host, port) = match authority.rsplit_once(':') {
448        Some((host, port)) if !port.is_empty() && port.chars().all(|c| c.is_ascii_digit()) => {
449            (host, Some(port))
450        }
451        _ => (authority, None),
452    };
453    // The native port is Ollama whatever it is called.
454    if port == Some("11434") {
455        return true;
456    }
457    let host = host.trim_matches(['[', ']']).to_ascii_lowercase();
458    if host.is_empty() || !host.contains("ollama") {
459        return false;
460    }
461    let labels: Vec<&str> = host.split('.').collect();
462    // A single label is a container or service name: `ollama`, `my-ollama`.
463    if labels.len() == 1 {
464        return true;
465    }
466    // Anything under a private label is on somebody's own network.
467    const PRIVATE: [&str; 6] = [
468        "local",
469        "lan",
470        "internal",
471        "home",
472        "home.arpa",
473        "localdomain",
474    ];
475    labels
476        .iter()
477        .any(|label| PRIVATE.contains(label) || label.ends_with(".arpa"))
478}
479
480/// Whether this ask is the off switch — by name, or by a declared `map` that points at it.
481fn asks_off(asked: &str, policy: &Policy) -> bool {
482    if asked == "none" {
483        return true;
484    }
485    match (policy.map.get(asked), policy.off_text()) {
486        (Some(mapped), Some(off)) => mapped == off,
487        _ => false,
488    }
489}
490
491/// The nearest level this wire has, never stronger than the one asked for.
492///
493/// Verbatim when supported; a declared `map` wins over the ladder; otherwise the nearest *weaker*
494/// supported level, and only when nothing weaker exists the weakest supported one. `none` is never
495/// a degradation target: clamping an enabled ask down to it would silently switch thinking off.
496fn clamp(asked: &str, policy: &Policy) -> Option<String> {
497    // Verbatim against the *declared* list, whatever the levels are called: a custom endpoint's
498    // bespoke name (`turbo`) is a level, even though it is not a rung of our ladder.
499    if let Some(level) = policy
500        .levels
501        .iter()
502        .find(|level| level.to_lowercase() == asked)
503    {
504        return Some(level.clone());
505    }
506    if let Some(mapped) = policy.map.get(asked) {
507        let known = policy
508            .levels
509            .iter()
510            .find(|level| level.as_str() == mapped.as_str());
511        return Some(known.cloned().unwrap_or_else(|| mapped.clone()));
512    }
513    // Clamping needs the ladder: only a named rung has a "nearest weaker" one.
514    let supported: Vec<&String> = policy
515        .levels
516        .iter()
517        .filter(|level| rank(&level.to_lowercase()).is_some())
518        .collect();
519    if supported.is_empty() {
520        return None;
521    }
522    let asked_rank = rank(asked)?;
523    let mut weaker: Vec<&&String> = supported
524        .iter()
525        .filter(|level| level.to_lowercase() != "none")
526        .filter(|level| {
527            rank(&level.to_lowercase())
528                .map(|r| r < asked_rank)
529                .unwrap_or(false)
530        })
531        .collect();
532    weaker.sort_by_key(|level| rank(&level.to_lowercase()));
533    if let Some(best) = weaker.pop() {
534        return Some((**best).clone());
535    }
536    let mut any: Vec<&&String> = supported
537        .iter()
538        .filter(|level| level.to_lowercase() != "none")
539        .collect();
540    any.sort_by_key(|level| rank(&level.to_lowercase()));
541    any.first().map(|level| (**level).clone())
542}
543
544/// The effort a request carries, read **per request**.
545///
546/// The issue this exists for: `[provider] reasoning_effort` is copied into the client's options when
547/// the client is built, so the one moment you want a different level — right after a turn that
548/// thought too little — is the one the running session cannot do. So the configured level stays the
549/// *default*, and a session override sits in front of it, in an `Arc` shared by every route the
550/// session opened.
551#[derive(Debug, Default)]
552pub struct Dial {
553    /// `[provider] reasoning_effort`, as loaded.
554    configured: Option<String>,
555    /// `/reasoning <level>` for this process. `None` = follow the configuration; `Some(None)` =
556    /// follow it *and* ignore it, which is what `/reasoning default` means after a session override.
557    session: std::sync::Mutex<Option<Option<String>>>,
558}
559
560impl Dial {
561    pub fn new(configured: Option<String>) -> Self {
562        Self {
563            configured: clean(configured.as_deref()),
564            session: std::sync::Mutex::new(None),
565        }
566    }
567
568    /// What the next request should ask for: the session's override, else the configuration.
569    pub fn effort(&self) -> Option<String> {
570        let session = self.session.lock().unwrap_or_else(|e| e.into_inner());
571        match session.as_ref() {
572            Some(level) => level.clone(),
573            None => self.configured.clone(),
574        }
575    }
576
577    /// `/reasoning <level>`: from the next request on, in this process only.
578    pub fn set_session(&self, level: Option<String>) {
579        let mut session = self.session.lock().unwrap_or_else(|e| e.into_inner());
580        *session = Some(level.map(|l| l.trim().to_lowercase()));
581    }
582
583    /// Drop the override: the configuration is in force again.
584    pub fn clear_session(&self) {
585        let mut session = self.session.lock().unwrap_or_else(|e| e.into_inner());
586        *session = None;
587    }
588
589    /// What was configured, for a report that has to say "the same as the file".
590    pub fn configured(&self) -> Option<&str> {
591        self.configured.as_deref()
592    }
593
594    /// Whether a session override is in force.
595    pub fn overridden(&self) -> bool {
596        self.session
597            .lock()
598            .unwrap_or_else(|e| e.into_inner())
599            .is_some()
600    }
601
602    /// The level in force, with the one clause that makes an override visible: `high`,
603    /// `high (this session; config.toml says low)`, `medium (this backend's default; config.toml
604    /// sets nothing)`, or `not sent`.
605    ///
606    /// This is the read-out's wording and `/reasoning`'s, from one function, so the line under the
607    /// composer cannot claim a level the report does not. Three answers, because a dial has three:
608    /// the session asked (`/reasoning high`), the file asked, or neither did and the route's own
609    /// policy supplies the shipped default (`#276`). `not sent` is the fourth case and a fact, not
610    /// a shrug: the backend takes no level, or nobody declared one, so the field is not on the wire.
611    pub fn in_force(&self) -> String {
612        self.resolution(None).1
613    }
614
615    /// What is in force, and where it came from: `(level, wording)`.
616    ///
617    /// `default` is the route's declared default — [`crate::provider::Reasoning::declared_default`]
618    /// — and it is a parameter rather than a field because a route changes under a live dial
619    /// (`/model`), and a copy taken at construction is how a read-out starts describing a backend
620    /// the session left behind.
621    fn resolution(&self, default: Option<&str>) -> (Option<String>, String) {
622        let session = self.session.lock().unwrap_or_else(|e| e.into_inner());
623        let session_level = session.clone();
624        drop(session);
625        match session_level {
626            // `/reasoning <level>`: the session's own answer, and it says so. `omit` is a word a
627            // session may choose (`#278`), and the report calls the outcome what it is.
628            Some(Some(level)) => {
629                let label = (!is_omit(&level)).then(|| level.clone());
630                let word = shown(label.as_deref());
631                let said = match self.configured() {
632                    Some(configured) if is_omit(configured) => {
633                        format!("{word} (this session; config.toml asks for no field)")
634                    }
635                    Some(configured) => {
636                        format!("{word} (this session; config.toml says {configured})")
637                    }
638                    None => format!("{word} (this session; config.toml sets nothing)"),
639                };
640                (label, said)
641            }
642            // `/reasoning default` after an override, or an override that asked for nothing:
643            // the session decided, and what it decided is "no field".
644            Some(None) => {
645                let said = match self.configured() {
646                    Some(configured) if is_omit(configured) => {
647                        format!("{NOT_SENT} (this session; config.toml asks for no field)")
648                    }
649                    Some(configured) => {
650                        format!("{NOT_SENT} (this session; config.toml says {configured})")
651                    }
652                    None => format!("{NOT_SENT} (this session; config.toml sets nothing)"),
653                };
654                (None, said)
655            }
656            None => match self.configured() {
657                Some(configured) if is_omit(configured) => {
658                    (None, format!("{NOT_SENT} (config.toml asks for no field)"))
659                }
660                Some(configured) => (Some(configured.to_string()), configured.to_string()),
661                // Nobody set it: the route's declared default is the shipped answer, and the
662                // wording says so rather than pretending the file named it.
663                None => match clean(default) {
664                    Some(level) if is_omit(&level) => (
665                        None,
666                        format!("{NOT_SENT} (this backend's default; config.toml sets nothing)"),
667                    ),
668                    Some(level) => (
669                        Some(level.clone()),
670                        format!("{level} (this backend's default; config.toml sets nothing)"),
671                    ),
672                    None => (None, NOT_SENT.to_string()),
673                },
674            },
675        }
676    }
677}
678
679/// What a report calls a level: the level itself, or `not sent` when there is none — which is what
680/// the `omit` sentinel resolves to (`#278`).
681fn shown(level: Option<&str>) -> String {
682    level.unwrap_or(NOT_SENT).to_string()
683}
684
685/// A level as the dial holds them: trimmed, lowercased, empty means absent.
686fn clean(level: Option<&str>) -> Option<String> {
687    level
688        .map(|l| l.trim().to_lowercase())
689        .filter(|l| !l.is_empty())
690}
691
692/// The effort in force, in the forms each surface needs (`#264`).
693///
694/// One struct rather than four parallel strings, because the line under the composer, the
695/// full-screen read-out, `/status` and the dashboard all answer the same question and had all been
696/// answering it differently — three of them by silence.
697#[derive(Debug, Clone, PartialEq, Eq, Default)]
698pub struct InForce {
699    /// `high`, or `not sent` — the read-out's form, short enough for a line that is already full.
700    pub label: String,
701    /// `high (this session; config.toml says low)` — `/reasoning`'s and `/status`'s form.
702    pub in_force: String,
703    /// Whether `/reasoning` moved it for this process.
704    pub session: bool,
705    /// The level came from the backend's declared default, not from the file or the session: the
706    /// one origin a reader would otherwise have to guess at, because nothing in `config.toml` says
707    /// it.
708    pub by_default: bool,
709    /// What that level becomes on the route in force, in the provider's own words. Empty when
710    /// nobody could resolve it — a read-out that filled this in from a table would be the second
711    /// guess `/reasoning` exists to prevent.
712    pub resolved: String,
713}
714
715impl InForce {
716    /// The whole thing in one sentence: the level and its origin, then the field it is sent as.
717    ///
718    /// One formatter, because `/status`, the dashboard's `title` and the full-screen interface's
719    /// tooltip all describe one dial — and three copies of that sentence is how a read-out starts
720    /// disagreeing with a command about the same session (`#264`).
721    pub fn sentence(&self) -> String {
722        if self.resolved.is_empty() {
723            return self.in_force.clone();
724        }
725        // "not sent" is already the whole answer, and the backend's reason stands in for it:
726        // "not sent · on this backend: not sent: nothing asked" is one contradiction too many.
727        if self.label == NOT_SENT {
728            return self.resolved.clone();
729        }
730        format!("{} · on this backend: {}", self.in_force, self.resolved)
731    }
732}
733
734impl Dial {
735    /// The dial's own half of [`InForce`]: what it will ask for, why, and what that becomes.
736    ///
737    /// `default` is the route in force's declared default (`#276`): `Some("medium")` on both
738    /// shipped profiles, `None` for a backend that declares no policy or no default. With no
739    /// session override and no file value, that is the level the next request carries — and the
740    /// label says `not sent`, not a guessed level, when even that is absent.
741    pub fn in_force_report(&self, default: Option<&str>) -> InForce {
742        let (level, in_force) = self.resolution(default);
743        InForce {
744            label: level.clone().unwrap_or_else(|| NOT_SENT.to_string()),
745            by_default: level.is_some() && !self.overridden() && self.configured().is_none(),
746            in_force,
747            session: self.overridden(),
748            resolved: String::new(),
749        }
750    }
751}
752
753/// The whole report for a dial and the route behind it: the one construction every front uses.
754///
755/// `control` is what the next request's route resolves to ([`crate::provider::Reasoning`]), and it
756/// supplies both halves the dial cannot answer alone — the declared default (`#276`) and the
757/// backend's own sentence for what a level becomes. `Agent::reasoning_report()`, the full-screen
758/// read-out and `/reasoning` all call this, so a surface cannot describe the dial differently from
759/// the command that moved it.
760pub fn report_for(dial: &Dial, control: Option<&crate::provider::Reasoning>) -> InForce {
761    let mut report = dial.in_force_report(control.and_then(|c| c.declared_default()));
762    report.resolved = sentence(control, dial.effort().as_deref());
763    report
764}
765
766/// A dial every route of one session shares.
767pub type Shared = std::sync::Arc<Dial>;
768
769/// One sentence for a level, given the control a route resolved to. The single wording for
770/// `/reasoning`, the launch panel and the readout, so a clamp is described the same way wherever it
771/// is reported.
772///
773/// `None` means this agent could not resolve a profile at all — not "no reasoning control", which
774/// is [`crate::provider::Reasoning::Off`].
775pub fn sentence(control: Option<&crate::provider::Reasoning>, level: Option<&str>) -> String {
776    use crate::provider::Reasoning;
777    match control {
778        None => "unknown: this agent has no provider configuration to describe".to_string(),
779        Some(Reasoning::Policy(policy)) => policy.describe(level),
780        Some(Reasoning::Off) => "no reasoning control on this model".to_string(),
781        Some(Reasoning::Undeclared) => match level {
782            Some(_) => "sent as-is (this backend declares no reasoning control)".to_string(),
783            None => "not sent: nothing was asked and nothing is configured".to_string(),
784        },
785    }
786}
787
788#[cfg(test)]
789mod tests {
790    use super::*;
791
792    /// `#278`: the sentinel answers before the ladder, so no policy can clamp it into a level that
793    /// is sent — and the sentence says it was a decision, not an absence.
794    #[test]
795    fn the_omit_sentinel_is_answered_before_the_ladder_and_says_so() {
796        for policy in [Policy::openai(), Policy::llamacpp()] {
797            assert_eq!(
798                policy.resolve(Some(OMIT)),
799                Wire::Omit(Omitted::AskedToOmit),
800                "resolve({OMIT}) on a policy with a dial"
801            );
802        }
803        // A backend with no dial at all keeps its own answer: there is no field for the operator
804        // to omit, and saying "asked for no field" would hide that the model has no control.
805        assert_eq!(
806            Policy::default().resolve(Some(OMIT)),
807            Wire::Omit(Omitted::NoPolicy)
808        );
809        assert_eq!(
810            Policy::openai().describe(Some(OMIT)),
811            "not sent: asked for no field on this route"
812        );
813        // Not a level: nothing may reach it by clamping, and the menu must not offer it (the
814        // vocabulary test above holds that an offered word goes on the wire).
815        assert!(!is_level(OMIT));
816        assert!(is_omit("  OMIT "));
817        assert!(!is_omit("none"));
818        for policy in [Policy::openai(), Policy::llamacpp()] {
819            assert!(!policy.vocabulary().iter().any(|w| w == OMIT), "{policy:?}");
820        }
821    }
822
823    /// A profile may ship the sentinel as its default: the route then carries no field unless a
824    /// session asks for a level, which is how an operator keeps a config quiet without Rust.
825    #[test]
826    fn a_profile_default_of_omit_carries_no_field() {
827        let mut policy = Policy::openai();
828        policy.default = Some(OMIT.to_string());
829        assert_eq!(policy.resolve(None), Wire::Omit(Omitted::AskedToOmit));
830        assert_eq!(
831            policy.describe(None),
832            "not sent: asked for no field on this route"
833        );
834        // And a session still outranks it, which is the point of a default rather than a switch.
835        assert_eq!(
836            policy.resolve(Some("high")),
837            Wire::Set(serde_json::Value::String("high".into()))
838        );
839    }
840
841    /// The read-out's wording for a session that asked for no field: `not sent`, with the file's
842    /// own answer beside it — never the word `omit`, which is a spelling rather than a state.
843    #[test]
844    fn a_session_that_asked_for_no_field_reports_not_sent() {
845        let dial = Dial::new(Some(SHIPPED_DEFAULT.to_string()));
846        dial.set_session(Some(OMIT.to_string()));
847        let report = dial.in_force_report(Some(SHIPPED_DEFAULT));
848        assert_eq!(report.label, NOT_SENT);
849        assert_eq!(
850            report.in_force,
851            format!("{NOT_SENT} (this session; config.toml says {SHIPPED_DEFAULT})")
852        );
853        assert!(report.session);
854
855        // The same word written into the file, with no session override.
856        let configured = Dial::new(Some(OMIT.to_string()));
857        let report = configured.in_force_report(Some(SHIPPED_DEFAULT));
858        assert_eq!(report.label, NOT_SENT);
859        assert_eq!(
860            report.in_force,
861            format!("{NOT_SENT} (config.toml asks for no field)")
862        );
863    }
864
865    /// `#275`: the menu may only offer what the wire takes. `openai` has no off switch —
866    /// `reasoning_effort: "none"` is a 400 there — and `llamacpp` has one, whatever shape it takes.
867    #[test]
868    fn the_vocabulary_is_the_wires_own_and_not_a_union() {
869        assert_eq!(
870            Policy::openai().vocabulary(),
871            vec!["minimal", "low", "medium", "high"],
872            "four rungs, no off switch to offer"
873        );
874        assert_eq!(
875            Policy::llamacpp().vocabulary(),
876            vec!["low", "medium", "high", "none"],
877            "its three rungs, then the word its off switch is asked for by"
878        );
879        assert!(
880            Policy::default().vocabulary().is_empty(),
881            "a policy with no dial has nothing to offer, and saying so is the answer"
882        );
883        // Every word offered resolves to something that goes on the wire: a menu row that cannot
884        // be clicked is the bug this exists to prevent.
885        for policy in [Policy::openai(), Policy::llamacpp()] {
886            for level in policy.vocabulary() {
887                assert!(
888                    !matches!(policy.resolve(Some(&level)), Wire::Omit(_)),
889                    "{level} is offered but refused"
890                );
891            }
892        }
893    }
894
895    #[test]
896    fn the_session_override_wins_over_the_configured_level_until_it_is_cleared() {
897        let dial = Dial::new(Some("low".into()));
898        assert_eq!(dial.effort().as_deref(), Some("low"));
899        assert!(!dial.overridden());
900        dial.set_session(Some(" HIGH ".into()));
901        assert_eq!(
902            dial.effort().as_deref(),
903            Some("high"),
904            "trimmed, lowercased"
905        );
906        assert!(dial.overridden());
907        dial.clear_session();
908        assert_eq!(
909            dial.effort().as_deref(),
910            Some("low"),
911            "the configuration is back in force"
912        );
913        assert!(!dial.overridden());
914    }
915
916    /// `/reasoning default` after a session override asks for *nothing*, which is not the same as
917    /// asking for what the file says.
918    #[test]
919    fn an_explicit_absence_is_a_decision_not_a_fallthrough() {
920        let dial = Dial::new(Some("low".into()));
921        dial.set_session(None);
922        assert_eq!(dial.effort(), None);
923        assert!(dial.overridden(), "the override is still a decision");
924        dial.clear_session();
925        assert_eq!(dial.effort().as_deref(), Some("low"));
926    }
927
928    /// The read-out's wording, from the dial itself: what is in force, whether that is a session
929    /// override, and never a guessed level where nothing was asked (`#276`).
930    #[test]
931    fn in_force_names_the_level_and_says_when_the_session_moved_it() {
932        let dial = Dial::new(Some("low".into()));
933        assert_eq!(dial.in_force(), "low");
934        dial.set_session(Some("high".into()));
935        assert_eq!(dial.in_force(), "high (this session; config.toml says low)");
936        dial.set_session(None);
937        assert_eq!(
938            dial.in_force(),
939            "not sent (this session; config.toml says low)",
940            "asking for nothing is a decision, and no field is what it will send"
941        );
942        dial.clear_session();
943        assert_eq!(dial.in_force(), "low");
944
945        // Nothing configured and a route that declares nothing: `not sent`, not a guessed level.
946        let bare = Dial::new(None);
947        assert_eq!(bare.in_force(), NOT_SENT);
948        bare.set_session(Some("high".into()));
949        assert_eq!(
950            bare.in_force(),
951            "high (this session; config.toml sets nothing)"
952        );
953    }
954
955    /// `#276`: what a fresh install looks like. The file says nothing, the route declares a
956    /// default, and the read-out answers with the level the request will carry — saying where it
957    /// came from, because `config.toml` does not.
958    #[test]
959    fn a_policy_that_declares_a_default_resolves_it_and_says_the_file_did_not() {
960        let bare = Dial::new(None);
961        let report = bare.in_force_report(Some(SHIPPED_DEFAULT));
962        assert_eq!(report.label, SHIPPED_DEFAULT);
963        assert_eq!(
964            report.in_force,
965            "medium (this backend's default; config.toml sets nothing)"
966        );
967        assert!(report.by_default, "the origin is the backend, not the file");
968        assert!(!report.session);
969
970        // The file wins over the default, and the wording goes quiet about it.
971        let filed = Dial::new(Some("low".into())).in_force_report(Some(SHIPPED_DEFAULT));
972        assert_eq!(filed.label, "low");
973        assert_eq!(filed.in_force, "low");
974        assert!(!filed.by_default);
975
976        // A session override wins over both.
977        let dial = Dial::new(None);
978        dial.set_session(Some("high".into()));
979        let over = dial.in_force_report(Some(SHIPPED_DEFAULT));
980        assert_eq!(over.label, "high");
981        assert_eq!(
982            over.in_force,
983            "high (this session; config.toml sets nothing)"
984        );
985        assert!(!over.by_default);
986
987        // A route that declares no default still sends nothing, and the label says so rather
988        // than claiming the level that is not on its wire.
989        let undeclared = bare.in_force_report(None);
990        assert_eq!(undeclared.label, NOT_SENT);
991        assert_eq!(undeclared.in_force, NOT_SENT);
992        assert!(!undeclared.by_default);
993    }
994
995    /// The two shipped profiles are the reason `medium` is the answer, and the starter file is the
996    /// same answer written down. One test, because the alternative is the drift `#245` exists to
997    /// prevent: a file that says `medium` over a resolver that says nothing.
998    #[test]
999    fn the_shipped_profiles_and_the_starter_file_agree_on_the_default() {
1000        for policy in [Policy::openai(), Policy::llamacpp()] {
1001            assert_eq!(
1002                policy.default_effort(),
1003                Some(SHIPPED_DEFAULT),
1004                "a shipped profile declares the level the starter file names"
1005            );
1006            assert_eq!(
1007                policy.resolve(None),
1008                Wire::Set(serde_json::Value::String(SHIPPED_DEFAULT.into())),
1009                "and an unconfigured request carries it"
1010            );
1011        }
1012        let shipped = crate::config::starter_config().expect("the starter config generates");
1013        let starter = crate::config::Config::from_toml_str(&shipped).expect("it parses");
1014        assert_eq!(
1015            starter.provider.reasoning_effort.as_deref(),
1016            Some(SHIPPED_DEFAULT),
1017            "`config init` writes the same level on a live line"
1018        );
1019        assert!(
1020            shipped.contains(&format!("reasoning_effort = \"{SHIPPED_DEFAULT}\"")),
1021            "and it is on a line a person can read"
1022        );
1023    }
1024
1025    #[test]
1026    fn an_unset_configuration_means_no_effort_is_asked_for() {
1027        let dial = Dial::new(None);
1028        assert_eq!(dial.effort(), None);
1029        assert_eq!(dial.configured(), None);
1030        let blank = Dial::new(Some("   ".into()));
1031        assert_eq!(blank.effort(), None, "blank is absent, not a level");
1032    }
1033
1034    fn level_policy(levels: &[&str]) -> Policy {
1035        Policy {
1036            field: "reasoning_effort".into(),
1037            kind: Kind::Level,
1038            off: Some("none".into()),
1039            ollama_off: None,
1040            levels: levels.iter().map(|l| l.to_string()).collect(),
1041            map: BTreeMap::new(),
1042            default: None,
1043        }
1044    }
1045
1046    fn set(value: &str) -> Wire {
1047        Wire::Set(serde_json::Value::String(value.into()))
1048    }
1049
1050    #[test]
1051    fn a_level_the_wire_has_is_sent_verbatim() {
1052        let p = level_policy(&["low", "medium", "high"]);
1053        assert_eq!(p.resolve(Some("high")), set("high"));
1054        assert_eq!(p.resolve(Some("low")), set("low"));
1055    }
1056
1057    /// Clamping goes down, never up: asking for a level a backend does not have must not cost more
1058    /// than asking for one it does.
1059    #[test]
1060    fn a_level_it_does_not_have_clamps_to_the_nearest_weaker_one() {
1061        let three = level_policy(&["low", "medium", "high"]);
1062        assert_eq!(three.resolve(Some("xhigh")), set("high"));
1063        assert_eq!(three.resolve(Some("max")), set("high"));
1064        // Nothing weaker than `low`: the floor is the closest honest answer.
1065        let floor = level_policy(&["medium", "high"]);
1066        assert_eq!(floor.resolve(Some("low")), set("medium"));
1067        // And `minimal` on a wire that starts at `low`.
1068        assert_eq!(three.resolve(Some("minimal")), set("low"));
1069    }
1070
1071    /// `none` is the off switch, not a degradation target — and a wire that cannot be switched off
1072    /// says so rather than sending a level that would look like it had.
1073    #[test]
1074    fn off_is_its_own_answer_and_never_a_clamp_target() {
1075        let p = level_policy(&["low", "medium", "high"]);
1076        assert_eq!(p.resolve(Some("none")), set("none"));
1077        let mut no_off = level_policy(&["low", "high"]);
1078        no_off.off = None;
1079        assert_eq!(
1080            no_off.resolve(Some("none")),
1081            Wire::Omit(Omitted::NotOnThisWire)
1082        );
1083    }
1084
1085    /// A declared mapping wins over the ladder, which is how a vendor's bespoke naming is
1086    /// expressed without inventing a rung for it.
1087    #[test]
1088    fn a_declared_mapping_is_consulted_before_the_ladder() {
1089        let mut p = level_policy(&["low", "high", "max"]);
1090        p.map.insert("medium".into(), "high".into());
1091        p.map.insert("xhigh".into(), "max".into());
1092        assert_eq!(
1093            p.resolve(Some("medium")),
1094            set("high"),
1095            "K3-shaped: the middle rung is `high`"
1096        );
1097        assert_eq!(p.resolve(Some("xhigh")), set("max"));
1098        // A mapping that points at the off value is the off switch.
1099        let mut off_by_map = level_policy(&["low", "high", "max"]);
1100        off_by_map.map.insert("minimal".into(), "none".into());
1101        assert_eq!(off_by_map.resolve(Some("minimal")), set("none"));
1102    }
1103
1104    /// A bool-valued backend has an on and an off, and nothing else; a graded ask is omitted with a
1105    /// reason instead of being sent as `true` and reported as "high".
1106    #[test]
1107    fn a_bool_backend_sends_on_or_off_and_says_when_it_has_no_levels() {
1108        let p = Policy {
1109            field: "chat_template_kwargs.enable_thinking".into(),
1110            kind: Kind::Bool,
1111            // `off = false` in a manifest: the switch is a bool, and the manifest says so instead of
1112            // the code guessing from `kind`.
1113            off: Some(OffSwitch::Flag(false)),
1114            ollama_off: None,
1115            levels: vec!["low".into()],
1116            map: BTreeMap::new(),
1117            default: None,
1118        };
1119        assert_eq!(
1120            p.resolve(Some("high")),
1121            Wire::Set(serde_json::Value::Bool(true))
1122        );
1123        assert_eq!(
1124            p.resolve(Some("none")),
1125            Wire::Set(serde_json::Value::Bool(false))
1126        );
1127        assert_eq!(
1128            p.describe(Some("high")),
1129            "sends thinking on",
1130            "the report says on, not `high`"
1131        );
1132    }
1133
1134    /// A backend with an off switch and no graded dial is the measured shape of gemma on llama.cpp:
1135    /// every level it was sent produced the same number of reasoning tokens.
1136    #[test]
1137    fn an_off_only_backend_refuses_an_enabled_ask_by_name() {
1138        let p = level_policy(&[]);
1139        assert!(p.has_dial() && !p.has_levels());
1140        assert_eq!(p.resolve(Some("high")), Wire::Omit(Omitted::NoLevels));
1141        assert_eq!(p.resolve(Some("none")), set("none"));
1142        assert!(p.describe(Some("high")).contains("no levels"));
1143    }
1144
1145    #[test]
1146    fn a_model_with_no_policy_gets_no_field_at_all() {
1147        let p = Policy::default();
1148        assert!(!p.has_dial());
1149        assert_eq!(p.resolve(Some("high")), Wire::Omit(Omitted::NoPolicy));
1150        assert_eq!(
1151            p.describe(Some("high")),
1152            "no reasoning control on this backend"
1153        );
1154    }
1155
1156    /// Nothing asked and no declared default: send nothing. A default that is *declared* is sent,
1157    /// which is how "an unset effort leaves the endpoint's ceiling in charge" is fixed deliberately
1158    /// rather than by accident.
1159    #[test]
1160    fn an_unasked_level_is_omitted_unless_the_manifest_declares_a_default() {
1161        let mut p = level_policy(&["low", "medium", "high"]);
1162        assert_eq!(p.resolve(None), Wire::Omit(Omitted::NothingAsked));
1163        assert_eq!(p.describe(None).split(':').next(), Some("not sent"));
1164        p.default = Some("medium".into());
1165        assert_eq!(p.resolve(None), set("medium"));
1166        assert_eq!(p.describe(None), "sends medium");
1167    }
1168
1169    /// The field is a dotted path, so a backend that wants a nested object gets one.
1170    #[test]
1171    fn a_dotted_field_becomes_a_nested_body_key() {
1172        let p = Policy {
1173            field: "chat_template_kwargs.enable_thinking".into(),
1174            kind: Kind::Bool,
1175            // `off = false` in a manifest: the switch is a bool, and the manifest says so instead of
1176            // the code guessing from `kind`.
1177            off: Some(OffSwitch::Flag(false)),
1178            ollama_off: None,
1179            levels: Vec::new(),
1180            map: BTreeMap::new(),
1181            default: None,
1182        };
1183        assert_eq!(
1184            p.resolve(Some("none")).body(&p),
1185            serde_json::json!({"chat_template_kwargs": {"enable_thinking": false}})
1186        );
1187        let flat = level_policy(&["high"]);
1188        assert_eq!(
1189            flat.resolve(Some("high")).body(&flat),
1190            serde_json::json!({"reasoning_effort": "high"})
1191        );
1192    }
1193
1194    /// A bespoke level a custom endpoint invented is passed through rather than dropped: the ladder
1195    /// is Hermes'/Pi's vocabulary, not a closed set every server agrees on.
1196    #[test]
1197    fn a_bespoke_level_passes_through_when_the_wire_lists_it() {
1198        let p = level_policy(&["low", "turbo"]);
1199        assert_eq!(p.resolve(Some("turbo")), set("turbo"));
1200        // And one nobody lists is refused with the level named.
1201        assert_eq!(p.resolve(Some("warp")), Wire::Omit(Omitted::NotOnThisWire));
1202        assert!(p.describe(Some("warp")).contains("warp"));
1203    }
1204
1205    #[test]
1206    fn the_ladder_is_ordered_and_answers_what_it_accepts() {
1207        for level in LADDER {
1208            assert!(is_level(level), "{level}");
1209        }
1210        assert!(is_level(" HIGH "), "trimmed and lowercased");
1211        assert!(!is_level("turbo"));
1212        assert!(!is_level(""));
1213    }
1214}